| | 1 | | using System.Collections.Immutable; |
| | 2 | | using System.Diagnostics.CodeAnalysis; |
| | 3 | | using System.Net; |
| | 4 | | using System.Net.Http.Json; |
| | 5 | | using System.Net.Sockets; |
| | 6 | | using System.Text.Json; |
| | 7 | | using Dotnet.Installer.Core.Types; |
| | 8 | |
|
| | 9 | | namespace Dotnet.Installer.Core.Services.Implementations; |
| | 10 | |
|
| | 11 | | public partial class SnapService |
| | 12 | | { |
| | 13 | | private SnapdRestClient? _snapdRestClient; |
| | 14 | |
|
| | 15 | | private SnapdRestClient GetSnapdRestClient() |
| 0 | 16 | | { |
| 0 | 17 | | if (_snapdRestClient is null) |
| 0 | 18 | | { |
| 0 | 19 | | _snapdRestClient = new SnapdRestClient(); |
| 0 | 20 | | } |
| | 21 | |
|
| 0 | 22 | | return _snapdRestClient; |
| 0 | 23 | | } |
| | 24 | |
|
| | 25 | | /// <summary> |
| | 26 | | /// HTTP client that interacts with the local snapd REST API via a Unix socket. |
| | 27 | | /// </summary> |
| | 28 | | /// <see href="https://snapcraft.io/docs/snapd-api"/> |
| | 29 | | private class SnapdRestClient : IDisposable |
| | 30 | | { |
| | 31 | | private const string SnapdUnixSocketPath = "/run/snapd.socket"; |
| | 32 | |
|
| | 33 | | private readonly HttpClient _httpClient; |
| | 34 | | private readonly JsonSerializerOptions _jsonSerializerOptions; |
| | 35 | |
|
| 0 | 36 | | public SnapdRestClient() |
| 0 | 37 | | { |
| 0 | 38 | | if (!File.Exists(SnapdUnixSocketPath)) |
| 0 | 39 | | { |
| 0 | 40 | | throw new ApplicationException($"Could not find the snapd unix-socket {SnapdUnixSocketPath}"); |
| | 41 | | } |
| | 42 | |
|
| 0 | 43 | | var httpMessageHandler = new SocketsHttpHandler |
| 0 | 44 | | { |
| 0 | 45 | | ConnectCallback = async (_, cancellationToken) => |
| 0 | 46 | | { |
| 0 | 47 | | var socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP); |
| 0 | 48 | | var endpoint = new UnixDomainSocketEndPoint(SnapdUnixSocketPath); |
| 0 | 49 | | await socket.ConnectAsync(endpoint, cancellationToken).ConfigureAwait(false); |
| 0 | 50 | | return new NetworkStream(socket, ownsSocket: false); |
| 0 | 51 | | } |
| 0 | 52 | | }; |
| | 53 | |
|
| 0 | 54 | | _httpClient = new HttpClient(httpMessageHandler); |
| 0 | 55 | | _httpClient.BaseAddress = new Uri("http://localhost"); |
| | 56 | |
|
| 0 | 57 | | _jsonSerializerOptions = new JsonSerializerOptions(JsonSerializerDefaults.Web) |
| 0 | 58 | | { |
| 0 | 59 | | PropertyNamingPolicy = JsonNamingPolicy.KebabCaseLower, |
| 0 | 60 | | }; |
| 0 | 61 | | } |
| | 62 | |
|
| | 63 | | public async Task<IImmutableList<SnapInfo>> GetInstalledSnapsAsync(CancellationToken cancellationToken) |
| 0 | 64 | | { |
| | 65 | | try |
| 0 | 66 | | { |
| 0 | 67 | | var snapdResponse = await RequestAsync(requestUri: "/v2/snaps", cancellationToken); |
| | 68 | |
|
| 0 | 69 | | if (snapdResponse is { StatusCode: HttpStatusCode.OK }) |
| 0 | 70 | | { |
| 0 | 71 | | return snapdResponse.Deserialize<IImmutableList<SnapInfo>>(_jsonSerializerOptions); |
| | 72 | | } |
| | 73 | |
|
| 0 | 74 | | var error = snapdResponse.Deserialize<SnapdError>(_jsonSerializerOptions); |
| | 75 | |
|
| 0 | 76 | | throw new ApplicationException(message: $"Snapd REST API responded with status code " + |
| 0 | 77 | | $"{(int)snapdResponse.StatusCode} ({snapdResponse.Status}): " + |
| 0 | 78 | | error.Message); |
| | 79 | | } |
| 0 | 80 | | catch (Exception exception) when (exception is not OperationCanceledException) |
| 0 | 81 | | { |
| 0 | 82 | | throw new ApplicationException( |
| 0 | 83 | | message: "An unexpected failure occured while requesting information about the local snaps", |
| 0 | 84 | | innerException: exception); |
| | 85 | | } |
| 0 | 86 | | } |
| | 87 | |
|
| | 88 | | public async Task<SnapInfo?> GetInstalledSnapAsync(string snapName, CancellationToken cancellationToken = defaul |
| 0 | 89 | | { |
| | 90 | | try |
| 0 | 91 | | { |
| 0 | 92 | | var snapdResponse = await RequestAsync( |
| 0 | 93 | | requestUri: $"/v2/snaps/{Uri.EscapeDataString(snapName)}", |
| 0 | 94 | | cancellationToken); |
| | 95 | |
|
| 0 | 96 | | if (snapdResponse is { StatusCode: HttpStatusCode.OK }) |
| 0 | 97 | | { |
| 0 | 98 | | return snapdResponse.Deserialize<SnapInfo>(_jsonSerializerOptions); |
| | 99 | | } |
| | 100 | |
|
| 0 | 101 | | var error = snapdResponse.Deserialize<SnapdError>(_jsonSerializerOptions); |
| | 102 | |
|
| 0 | 103 | | if (error is { Kind: "snap-not-found" }) |
| 0 | 104 | | { |
| 0 | 105 | | return null; |
| | 106 | | } |
| | 107 | |
|
| 0 | 108 | | throw new ApplicationException(message: $"Snapd REST API responded with status code " + |
| 0 | 109 | | $"{(int)snapdResponse.StatusCode} ({snapdResponse.Status}): " + |
| 0 | 110 | | error.Message); |
| | 111 | | } |
| 0 | 112 | | catch (Exception exception) when (exception is not OperationCanceledException) |
| 0 | 113 | | { |
| 0 | 114 | | throw new ApplicationException( |
| 0 | 115 | | message: $"An unexpected failure occured while requesting information about the local snap \"{snapNa |
| 0 | 116 | | innerException: exception); |
| | 117 | | } |
| 0 | 118 | | } |
| | 119 | |
|
| | 120 | | /// <summary> |
| | 121 | | /// Search for snaps whose name matches the given string. |
| | 122 | | /// </summary> |
| | 123 | | /// <param name="snapName"> |
| | 124 | | /// The name of the snap to search for. The match is exact |
| | 125 | | /// (i.e. <see cref="FindSnapAsync"/> would return 0 or 1 results) unless the string ends in <c>*</c> |
| | 126 | | /// </param> |
| | 127 | | /// <param name="cancellationToken">The cancellation token to cancel the operation.</param> |
| | 128 | | /// <returns>A list of snaps that matches the specified <paramref name="snapName"/></returns> |
| | 129 | | /// <exception cref="ObjectDisposedException"></exception> |
| | 130 | | /// <exception cref="ApplicationException"></exception> |
| | 131 | | /// <exception cref="OperationCanceledException"></exception> |
| | 132 | | /// <seealso href="https://snapcraft.io/docs/snapd-api#heading--find"/> |
| | 133 | | public async Task<SnapInfo?> FindSnapAsync(string snapName, CancellationToken cancellationToken = default) |
| 0 | 134 | | { |
| | 135 | | try |
| 0 | 136 | | { |
| 0 | 137 | | var snapdResponse = await RequestAsync( |
| 0 | 138 | | requestUri: $"/v2/find?name={Uri.EscapeDataString(snapName)}", |
| 0 | 139 | | cancellationToken); |
| | 140 | |
|
| 0 | 141 | | if (snapdResponse is { StatusCode: HttpStatusCode.OK }) |
| 0 | 142 | | { |
| 0 | 143 | | return snapdResponse.Deserialize<SnapInfo[]>(_jsonSerializerOptions).Single(); |
| | 144 | | } |
| | 145 | |
|
| 0 | 146 | | var error = snapdResponse.Deserialize<SnapdError>(_jsonSerializerOptions); |
| | 147 | |
|
| 0 | 148 | | if (error is { Kind: "snap-not-found" }) |
| 0 | 149 | | { |
| 0 | 150 | | return null; |
| | 151 | | } |
| | 152 | |
|
| 0 | 153 | | throw new ApplicationException(message: $"Snapd REST API responded with status code " + |
| 0 | 154 | | $"{(int)snapdResponse.StatusCode} ({snapdResponse.Status}): " + |
| 0 | 155 | | error.Message); |
| | 156 | | } |
| 0 | 157 | | catch (Exception exception) when (exception is not OperationCanceledException) |
| 0 | 158 | | { |
| 0 | 159 | | throw new ApplicationException( |
| 0 | 160 | | message: $"An unexpected failure occured while requesting information about the snap \"{snapName}\"" |
| 0 | 161 | | innerException: exception); |
| | 162 | | } |
| 0 | 163 | | } |
| | 164 | |
|
| | 165 | | private async Task<SnapdResponse> RequestAsync(string requestUri, CancellationToken cancellationToken) |
| 0 | 166 | | { |
| 0 | 167 | | cancellationToken.ThrowIfCancellationRequested(); |
| | 168 | |
|
| 0 | 169 | | var snapdResponse = await _httpClient |
| 0 | 170 | | .GetFromJsonAsync<SnapdResponse>(requestUri, _jsonSerializerOptions, cancellationToken) |
| 0 | 171 | | .ConfigureAwait(false); |
| | 172 | |
|
| 0 | 173 | | return snapdResponse ?? throw new ApplicationException("Snapd REST API response is null"); |
| 0 | 174 | | } |
| | 175 | |
|
| | 176 | | public void Dispose() |
| 0 | 177 | | { |
| 0 | 178 | | _httpClient.Dispose(); |
| 0 | 179 | | } |
| | 180 | |
|
| 0 | 181 | | private record SnapdResponse( |
| 0 | 182 | | string Type, |
| 0 | 183 | | HttpStatusCode StatusCode, |
| 0 | 184 | | string Status, |
| 0 | 185 | | JsonElement Result) |
| | 186 | | { |
| | 187 | | public TResult Deserialize<TResult>(JsonSerializerOptions jsonDeserializerOptions) |
| 0 | 188 | | { |
| 0 | 189 | | return Result.Deserialize<TResult>(jsonDeserializerOptions) |
| 0 | 190 | | ?? throw new ApplicationException("Snapd REST API result is null"); |
| 0 | 191 | | } |
| | 192 | |
|
| | 193 | | public bool TryGetResultAs<TResult>( |
| | 194 | | JsonSerializerOptions jsonDeserializerOptions, |
| | 195 | | [NotNullWhen(returnValue: true)] |
| | 196 | | out TResult? result) |
| 0 | 197 | | { |
| | 198 | | try |
| 0 | 199 | | { |
| 0 | 200 | | result = Result.Deserialize<TResult>(jsonDeserializerOptions); |
| 0 | 201 | | } |
| 0 | 202 | | catch |
| 0 | 203 | | { |
| 0 | 204 | | result = default; |
| 0 | 205 | | } |
| | 206 | |
|
| 0 | 207 | | return result is not null; |
| 0 | 208 | | } |
| | 209 | | } |
| | 210 | |
|
| 0 | 211 | | private record SnapdError(string Message, string? Kind); |
| | 212 | | } |
| | 213 | | } |