|
| 1 | +namespace UET.Commands.Internal.RegisterGitLabRunner |
| 2 | +{ |
| 3 | + using Microsoft.Extensions.Logging; |
| 4 | + using System; |
| 5 | + using System.Collections.Generic; |
| 6 | + using System.CommandLine; |
| 7 | + using System.CommandLine.Invocation; |
| 8 | + using System.Globalization; |
| 9 | + using System.Linq; |
| 10 | + using System.Net.Http.Json; |
| 11 | + using System.Text; |
| 12 | + using System.Text.Json; |
| 13 | + using System.Threading.Tasks; |
| 14 | + |
| 15 | + internal sealed class RegisterGitLabRunnerCommand |
| 16 | + { |
| 17 | + internal sealed class Options |
| 18 | + { |
| 19 | + } |
| 20 | + |
| 21 | + public static Command CreateRegisterGitLabRunnerCommand() |
| 22 | + { |
| 23 | + var options = new Options(); |
| 24 | + var command = new Command( |
| 25 | + "register-gitlab-runner", |
| 26 | + "Register a GitLab runner with the GitLab API using the new authentication flow."); |
| 27 | + command.AddAllOptions(options); |
| 28 | + command.AddCommonHandler<RegisterGitLabRunnerCommandInstance>(options); |
| 29 | + return command; |
| 30 | + } |
| 31 | + |
| 32 | + private sealed class RegisterGitLabRunnerCommandInstance : ICommandInstance |
| 33 | + { |
| 34 | + private readonly ILogger<RegisterGitLabRunnerCommandInstance> _logger; |
| 35 | + |
| 36 | + public RegisterGitLabRunnerCommandInstance( |
| 37 | + ILogger<RegisterGitLabRunnerCommandInstance> logger) |
| 38 | + { |
| 39 | + _logger = logger; |
| 40 | + } |
| 41 | + |
| 42 | + public async Task<int> ExecuteAsync(InvocationContext context) |
| 43 | + { |
| 44 | + var baseUrl = Environment.GetEnvironmentVariable("UET_GITLAB_BASE_URL"); |
| 45 | + var personalAccessToken = Environment.GetEnvironmentVariable("UET_GITLAB_PERSONAL_ACCESS_TOKEN"); |
| 46 | + var registrationSpecRaw = Environment.GetEnvironmentVariable("UET_GITLAB_REGISTER_SPEC"); |
| 47 | + GitLabRunnerRegistrationSpec[] registrationSpec; |
| 48 | + try |
| 49 | + { |
| 50 | + registrationSpec = JsonSerializer.Deserialize(registrationSpecRaw!, RegisterGitLabRunnerJsonSerializerContext.Default.GitLabRunnerRegistrationSpecArray)!; |
| 51 | + ArgumentNullException.ThrowIfNull(registrationSpec); |
| 52 | + } |
| 53 | + catch (Exception ex) |
| 54 | + { |
| 55 | + _logger.LogError(ex, "Environment variable 'UET_GITLAB_REGISTER_SPEC' was invalid."); |
| 56 | + return 1; |
| 57 | + } |
| 58 | + if (string.IsNullOrWhiteSpace(baseUrl)) |
| 59 | + { |
| 60 | + _logger.LogError("Environment variable 'UET_GITLAB_BASE_URL' was invalid."); |
| 61 | + return 1; |
| 62 | + } |
| 63 | + if (string.IsNullOrWhiteSpace(baseUrl)) |
| 64 | + { |
| 65 | + _logger.LogError("Environment variable 'UET_GITLAB_PERSONAL_ACCESS_TOKEN' was invalid."); |
| 66 | + return 1; |
| 67 | + } |
| 68 | + |
| 69 | + using (var client = new HttpClient()) |
| 70 | + { |
| 71 | + client.DefaultRequestHeaders.Add( |
| 72 | + "PRIVATE-TOKEN", |
| 73 | + personalAccessToken); |
| 74 | + |
| 75 | + // Iterate through registration specs, registering where necessary. |
| 76 | + foreach (var spec in registrationSpec) |
| 77 | + { |
| 78 | + if (File.Exists(spec.IdPath)) |
| 79 | + { |
| 80 | + _logger.LogInformation($"Checking if existing runner with ID at path {spec.IdPath} is already registered..."); |
| 81 | + try |
| 82 | + { |
| 83 | + var id = (await File.ReadAllTextAsync(spec.IdPath, context.GetCancellationToken()).ConfigureAwait(false)).Trim(); |
| 84 | + var json = await client.GetFromJsonAsync( |
| 85 | + $"{baseUrl}/api/v4/runners/{id}", |
| 86 | + RegisterGitLabRunnerJsonSerializerContext.Default.GitLabGetRunnerResponse); |
| 87 | + _logger.LogInformation($"Runner with ID at path {spec.IdPath} is already registered."); |
| 88 | + continue; |
| 89 | + } |
| 90 | + catch (Exception ex) |
| 91 | + { |
| 92 | + _logger.LogWarning(ex, "Runner is not registered or failed to read from GitLab."); |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + var form = new Dictionary<string, string> |
| 97 | + { |
| 98 | + { "runner_type", spec.RunnerType }, |
| 99 | + }; |
| 100 | + if (spec.GroupId.HasValue) |
| 101 | + { |
| 102 | + form.Add("group_id", spec.GroupId.Value.ToString(CultureInfo.InvariantCulture)); |
| 103 | + } |
| 104 | + if (spec.ProjectId.HasValue) |
| 105 | + { |
| 106 | + form.Add("project_id", spec.ProjectId.Value.ToString(CultureInfo.InvariantCulture)); |
| 107 | + } |
| 108 | + if (!string.IsNullOrWhiteSpace(spec.Description)) |
| 109 | + { |
| 110 | + form.Add("description", spec.Description |
| 111 | + .Replace( |
| 112 | + "__HOSTNAME__", |
| 113 | + Environment.MachineName.ToLowerInvariant(), |
| 114 | + StringComparison.Ordinal)); |
| 115 | + } |
| 116 | + form.Add("paused", spec.Paused ? "true" : "false"); |
| 117 | + form.Add("locked", spec.Locked ? "true" : "false"); |
| 118 | + form.Add("run_untagged", spec.RunUntagged ? "true" : "false"); |
| 119 | + if (!string.IsNullOrWhiteSpace(spec.TagList)) |
| 120 | + { |
| 121 | + form.Add("tag_list", spec.TagList |
| 122 | + .Replace( |
| 123 | + "__HOSTNAME__", |
| 124 | + Environment.MachineName.ToLowerInvariant(), |
| 125 | + StringComparison.Ordinal)); |
| 126 | + } |
| 127 | + if (!string.IsNullOrWhiteSpace(spec.AccessLevel)) |
| 128 | + { |
| 129 | + form.Add("access_level", spec.AccessLevel); |
| 130 | + } |
| 131 | + if (spec.MaximumTimeout.HasValue) |
| 132 | + { |
| 133 | + form.Add("maximum_timeout", spec.MaximumTimeout.Value.ToString(CultureInfo.InvariantCulture)); |
| 134 | + } |
| 135 | + if (!string.IsNullOrWhiteSpace(spec.MaintainenceNote)) |
| 136 | + { |
| 137 | + form.Add("maintenance_note", spec.MaintainenceNote); |
| 138 | + } |
| 139 | + |
| 140 | + _logger.LogInformation($"Registering new GitLab runner..."); |
| 141 | + var response = await client.PostAsync( |
| 142 | + new Uri($"{baseUrl}/api/v4/user/runners"), |
| 143 | + new FormUrlEncodedContent(form), |
| 144 | + context.GetCancellationToken()); |
| 145 | + if (!response.IsSuccessStatusCode) |
| 146 | + { |
| 147 | + _logger.LogError($"Got unexpected response from GitLab: {await response.Content.ReadAsStringAsync(context.GetCancellationToken())}"); |
| 148 | + response.EnsureSuccessStatusCode(); |
| 149 | + } |
| 150 | + |
| 151 | + var register = await response.Content.ReadFromJsonAsync( |
| 152 | + RegisterGitLabRunnerJsonSerializerContext.Default.GitLabRegisterRunnerResponse, |
| 153 | + context.GetCancellationToken()); |
| 154 | + if (register == null) |
| 155 | + { |
| 156 | + throw new InvalidOperationException("Expected non-null response from runner registration."); |
| 157 | + } |
| 158 | + |
| 159 | + var idPathDirectory = Path.GetDirectoryName(spec.IdPath); |
| 160 | + var tokenPathDirectory = Path.GetDirectoryName(spec.TokenPath); |
| 161 | + if (!string.IsNullOrWhiteSpace(idPathDirectory)) |
| 162 | + { |
| 163 | + Directory.CreateDirectory(idPathDirectory); |
| 164 | + } |
| 165 | + if (!string.IsNullOrWhiteSpace(tokenPathDirectory)) |
| 166 | + { |
| 167 | + Directory.CreateDirectory(tokenPathDirectory); |
| 168 | + } |
| 169 | + await File.WriteAllTextAsync( |
| 170 | + spec.IdPath, |
| 171 | + register.Id.ToString(CultureInfo.InvariantCulture), |
| 172 | + context.GetCancellationToken()); |
| 173 | + await File.WriteAllTextAsync( |
| 174 | + spec.TokenPath, |
| 175 | + register.Token, |
| 176 | + context.GetCancellationToken()); |
| 177 | + |
| 178 | + _logger.LogInformation($"Runner with ID at path {spec.IdPath} now successfully registered."); |
| 179 | + } |
| 180 | + } |
| 181 | + |
| 182 | + return 0; |
| 183 | + } |
| 184 | + } |
| 185 | + } |
| 186 | +} |
0 commit comments