-
Notifications
You must be signed in to change notification settings - Fork 0
/
CloudController.cs
235 lines (195 loc) · 8.27 KB
/
CloudController.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
using System.Collections.Concurrent;
using System.Text;
using System.Text.Json;
using GithubActionsOrchestrator.Database;
using GithubActionsOrchestrator.GitHub;
using GithubActionsOrchestrator.Models;
using HetznerCloudApi;
using HetznerCloudApi.Object.Image;
using HetznerCloudApi.Object.Server;
using HetznerCloudApi.Object.ServerType;
using HetznerCloudApi.Object.SshKey;
using HetznerCloudApi.Object.Universal;
using Microsoft.EntityFrameworkCore;
using RandomFriendlyNameGenerator;
namespace GithubActionsOrchestrator;
public class CloudController
{
private readonly HetznerCloudClient _client;
private readonly ILogger _logger;
private readonly List<MachineSize> _configSizes;
private readonly string _provisionBaseUrl;
private readonly string _metricUser;
private readonly string _metricPassword;
public CloudController(ILogger<CloudController> logger,
string hetznerCloudToken,
List<MachineSize> configSizes,
string provisionScriptBaseUrl,
string metricUser,
string metricPassword)
{
_configSizes = configSizes;
_client = new(hetznerCloudToken);
_logger = logger;
_provisionBaseUrl = provisionScriptBaseUrl;
_metricUser = metricUser;
_metricPassword = metricPassword;
_logger.LogInformation("Controller init done.");
}
private async Task<string> GenerateName()
{
var db = new ActionsRunnerContext();
string name = string.Empty;
bool nameCollision = false;
do
{
if (nameCollision)
{
_logger.LogWarning($"Name collision detected: {name}");
}
// Name duplicate detection. Generate names as long as there is no duplicate found
name = $"{Program.Config.RunnerPrefix}-{NameGenerator.Identifiers.Get(IdentifierTemplate.AnyThreeComponents, NameOrderingStyle.BobTheBuilderStyle, separator: "-")}".ToLower().Replace(' ', '-');
nameCollision = true;
} while (await db.Runners.AnyAsync(x => x.Hostname == name));
return name;
}
public async Task<Machine> CreateNewRunner(string arch, string size, string runnerToken, string targetName, bool isCustom = false, string profileName = "default", bool usePrivateNetworks = false)
{
// Select VM size for job - All AMD
string vmSize = _configSizes.FirstOrDefault(x => x.Arch == arch && x.Name == size)?.VmType;
if (string.IsNullOrEmpty(vmSize))
{
throw new Exception($"Unknown arch and size combination [{arch}/{size}]");
}
// Build image name
// Load profile info
RunnerProfile profile = isCustom ?
Program.Config.Profiles.FirstOrDefault(x => x.Name == profileName) :
Program.Config.Profiles.FirstOrDefault(x => x.Name == "default");
if (profile == null)
{
throw new Exception($"Unable to load profile: {profileName}");
}
string imageName = profile.IsCustomImage ? $"ghri-{profile.OsImageName}-{arch}" : profile.OsImageName;
// The naming generator might produce names with whitespace.
string name = await GenerateName();
_logger.LogInformation($"Creating VM {name} from image {imageName} of size {size} for {targetName}");
string htzArch = "x86";
if (arch == "arm64")
{
htzArch = "arm";
}
// Grab image
List<Image> images = await _client.Image.Get();
long? imageId = images.FirstOrDefault(x => x.Description == imageName && x.Architecture == htzArch)?.Id;
if (!imageId.HasValue)
{
throw new ImageNotFoundException($"Unable to find image: {imageName}");
}
// Grab server type
List<ServerType> srvTypes = await _client.ServerType.Get();
long? srvType = srvTypes.FirstOrDefault(x => x.Name == vmSize)?.Id;
// Grab SSH keys
List<SshKey> sshKeys = await _client.SshKey.Get();
List<long> srvKeys = sshKeys.Select(x => x.Id).ToList();
// Grab private network
var networks = await _client.Network.Get();
// Create new server
string runnerVersion = Program.Config.GithubAgentVersion;
string provisionVersion = $"v{profile.ScriptVersion}";
string customEnv = isCustom ? "1" : "0";
string cloudInitcontent = new StringBuilder()
.AppendLine("#cloud-config")
.AppendLine("write_files:")
.AppendLine(" - path: /data/config.env")
.AppendLine(" content: |")
.AppendLine($" export GH_VERSION='{runnerVersion}'")
.AppendLine($" export ORG_NAME='{targetName}'")
.AppendLine($" export GH_TOKEN='{runnerToken}'")
.AppendLine($" export RUNNER_SIZE='{size}'")
.AppendLine($" export METRIC_USER='{_metricUser}'")
.AppendLine($" export METRIC_PASS='{_metricPassword}'")
.AppendLine($" export GH_PROFILE_NAME='{profile.Name}'")
.AppendLine($" export GH_IS_CUSTOM='{customEnv}'")
.AppendLine($" export RUNNER_PREFIX='{Program.Config.RunnerPrefix}'")
.AppendLine($" export CONTROLLER_URL='{Program.Config.ControllerUrl}'")
.AppendLine("runcmd:")
.AppendLine($" - [ sh, -xc, 'curl -fsSL {_provisionBaseUrl}/provision.{profile.ScriptName}.{arch}.{provisionVersion}.sh -o /data/provision.sh']")
.AppendLine(" - [ sh, -xc, 'bash /data/provision.sh']")
.ToString();
Server newSrv = null;
bool success = false;
List<eDataCenter> dataCenters =
[
eDataCenter.fsn1,
eDataCenter.hel1,
eDataCenter.nbg1
];
int ct = 0;
while (!success)
{
if (ct == dataCenters.Count)
{
throw new Exception($"Unable to find any htz DC able to host {name} of size {size}");
}
try
{
var privateNetworks = usePrivateNetworks ? networks.Select(x => x.Id).ToList() : new List<long>();
newSrv = await _client.Server.Create(dataCenters[ct], imageId.Value, name, srvType.Value, userData: cloudInitcontent, sshKeysIds: srvKeys, privateNetoworksIds: privateNetworks);
success = true;
}
catch (Exception ex)
{
// Htz not able to schedule in nbg, try different one
if (ex.Message.Contains("resource_unavailable"))
{
_logger.LogWarning($"Unable to create VM {name} from image {imageName} of size {size} in {dataCenters[ct]}. Trying different location.");
ct++;
}
else
{
throw;
}
}
}
if (newSrv == null)
{
throw new Exception("Unable to spin up VM for " + name);
}
return new Machine
{
Id = newSrv.Id,
Name = newSrv.Name,
Ipv4 = newSrv.PublicNet.Ipv4.Ip,
CreatedAt = DateTime.UtcNow,
TargetName = targetName,
Size = size,
Arch = arch,
Profile = profileName,
IsCustom = isCustom
};
}
public async Task DeleteRunner(long serverId)
{
var db = new ActionsRunnerContext();
var runner = await db.Runners.FirstOrDefaultAsync(x => x.CloudServerId == serverId);
if (runner == null)
{
_logger.LogWarning($"VM with ID {serverId} not in active runners list. Only removing from htz.");
}
else
{
_logger.LogInformation($"Deleting VM {runner.Hostname} with IP {runner.IPv4}");
}
await _client.Server.Delete(serverId);
}
public async Task<List<Server>> GetAllServersFromCsp()
{
List<Server> srvs = await _client.Server.Get();
return srvs.Where(x =>x.Name.StartsWith(Program.Config.RunnerPrefix)).ToList();
}
public async Task<int> GetServerCountFromCsp()
{
return (await GetAllServersFromCsp()).Count;
}
}