-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathDeployer.cs
2378 lines (2049 loc) · 130 KB
/
Deployer.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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Net.WebSockets;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.Network;
using Azure.ResourceManager.Network.Models;
using Azure.Security.KeyVault.Secrets;
using Azure.Storage;
using Azure.Storage.Blobs;
using CommonUtilities;
using IdentityModel.Client;
using k8s;
using Microsoft.Azure.Management.Batch;
using Microsoft.Azure.Management.Batch.Models;
using Microsoft.Azure.Management.Compute.Fluent;
using Microsoft.Azure.Management.ContainerRegistry.Fluent;
using Microsoft.Azure.Management.ContainerService;
using Microsoft.Azure.Management.ContainerService.Fluent;
using Microsoft.Azure.Management.ContainerService.Models;
using Microsoft.Azure.Management.Fluent;
using Microsoft.Azure.Management.Graph.RBAC.Fluent;
using Microsoft.Azure.Management.KeyVault;
using Microsoft.Azure.Management.KeyVault.Fluent;
using Microsoft.Azure.Management.KeyVault.Models;
using Microsoft.Azure.Management.Msi.Fluent;
using Microsoft.Azure.Management.Network;
using Microsoft.Azure.Management.Network.Fluent;
using Microsoft.Azure.Management.Network.Fluent.Models;
using Microsoft.Azure.Management.PostgreSQL;
using Microsoft.Azure.Management.PrivateDns.Fluent;
using Microsoft.Azure.Management.ResourceGraph;
using Microsoft.Azure.Management.ResourceManager.Fluent;
using Microsoft.Azure.Management.ResourceManager.Fluent.Authentication;
using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
using Microsoft.Azure.Management.Storage.Fluent;
using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Rest;
using Newtonsoft.Json;
using Polly;
using Polly.Retry;
using Tes.Models;
using static Microsoft.Azure.Management.PostgreSQL.FlexibleServers.DatabasesOperationsExtensions;
using static Microsoft.Azure.Management.PostgreSQL.FlexibleServers.ServersOperationsExtensions;
using static Microsoft.Azure.Management.PostgreSQL.ServersOperationsExtensions;
using static Microsoft.Azure.Management.ResourceManager.Fluent.Core.RestClient;
using Extensions = Microsoft.Azure.Management.ResourceManager.Fluent.Core.Extensions;
using FlexibleServer = Microsoft.Azure.Management.PostgreSQL.FlexibleServers;
using FlexibleServerModel = Microsoft.Azure.Management.PostgreSQL.FlexibleServers.Models;
using IResource = Microsoft.Azure.Management.ResourceManager.Fluent.Core.IResource;
using KeyVaultManagementClient = Microsoft.Azure.Management.KeyVault.KeyVaultManagementClient;
using SingleServer = Microsoft.Azure.Management.PostgreSQL;
using SingleServerModel = Microsoft.Azure.Management.PostgreSQL.Models;
namespace TesDeployer
{
public class Deployer
{
private static readonly AsyncRetryPolicy roleAssignmentHashConflictRetryPolicy = Policy
.Handle<Microsoft.Rest.Azure.CloudException>(cloudException => cloudException.Body.Code.Equals("HashConflictOnDifferentRoleAssignmentIds"))
.RetryAsync();
private static readonly AsyncRetryPolicy generalRetryPolicy = Policy
.Handle<Exception>()
.WaitAndRetryAsync(3, retryAttempt => System.TimeSpan.FromSeconds(1));
private static readonly AsyncRetryPolicy longRetryPolicy = Policy
.Handle<Exception>()
.WaitAndRetryAsync(60, retryAttempt => System.TimeSpan.FromSeconds(15));
public const string ConfigurationContainerName = "configuration";
public const string ContainersToMountFileName = "containers-to-mount";
public const string AllowedVmSizesFileName = "allowed-vm-sizes";
public const string TesCredentialsFileName = "TesCredentials.json";
public const string InputsContainerName = "inputs";
public const string StorageAccountKeySecretName = "CoAStorageKey";
public const string PostgresqlSslMode = "VerifyFull";
private record TesCredentials(string TesHostname, string TesUsername, string TesPassword);
private readonly CancellationTokenSource cts = new();
private readonly List<string> requiredResourceProviders = new()
{
"Microsoft.Authorization",
"Microsoft.Batch",
"Microsoft.Compute",
"Microsoft.ContainerService",
"Microsoft.DocumentDB",
"Microsoft.OperationalInsights",
"Microsoft.OperationsManagement",
"Microsoft.insights",
"Microsoft.Network",
"Microsoft.Storage",
"Microsoft.DBforPostgreSQL"
};
private Configuration configuration { get; set; }
private ITokenProvider tokenProvider;
private TokenCredentials tokenCredentials;
private IAzure azureSubscriptionClient { get; set; }
private Microsoft.Azure.Management.Fluent.Azure.IAuthenticated azureClient { get; set; }
private IResourceManager resourceManagerClient { get; set; }
private ArmClient armClient { get; set; }
private Microsoft.Azure.Management.Network.INetworkManagementClient networkManagementClient { get; set; }
private AzureCredentials azureCredentials { get; set; }
private FlexibleServer.IPostgreSQLManagementClient postgreSqlFlexManagementClient { get; set; }
private SingleServer.IPostgreSQLManagementClient postgreSqlSingleManagementClient { get; set; }
private IEnumerable<string> subscriptionIds { get; set; }
private bool isResourceGroupCreated { get; set; }
private KubernetesManager kubernetesManager { get; set; }
public Deployer(Configuration configuration)
=> this.configuration = configuration;
public async Task<int> DeployAsync()
{
var mainTimer = Stopwatch.StartNew();
try
{
ValidateInitialCommandLineArgs();
ConsoleEx.WriteLine("Running...");
await ValidateTokenProviderAsync();
await Execute("Connecting to Azure Services...", async () =>
{
tokenProvider = new RefreshableAzureServiceTokenProvider("https://management.azure.com/");
tokenCredentials = new(tokenProvider);
azureCredentials = new(tokenCredentials, null, null, AzureEnvironment.AzureGlobalCloud);
azureClient = GetAzureClient(azureCredentials);
armClient = new ArmClient(new AzureCliCredential());
azureSubscriptionClient = azureClient.WithSubscription(configuration.SubscriptionId);
subscriptionIds = (await azureClient.Subscriptions.ListAsync()).Select(s => s.SubscriptionId);
resourceManagerClient = GetResourceManagerClient(azureCredentials);
networkManagementClient = new Microsoft.Azure.Management.Network.NetworkManagementClient(azureCredentials) { SubscriptionId = configuration.SubscriptionId };
postgreSqlFlexManagementClient = new FlexibleServer.PostgreSQLManagementClient(azureCredentials) { SubscriptionId = configuration.SubscriptionId, LongRunningOperationRetryTimeout = 1200 };
postgreSqlSingleManagementClient = new SingleServer.PostgreSQLManagementClient(azureCredentials) { SubscriptionId = configuration.SubscriptionId, LongRunningOperationRetryTimeout = 1200 };
});
await ValidateSubscriptionAndResourceGroupAsync(configuration);
kubernetesManager = new(configuration, azureCredentials, cts);
IResourceGroup resourceGroup = null;
ManagedCluster aksCluster = null;
BatchAccount batchAccount = null;
IGenericResource logAnalyticsWorkspace = null;
IGenericResource appInsights = null;
FlexibleServerModel.Server postgreSqlFlexServer = null;
SingleServerModel.Server postgreSqlSingleServer = null;
IStorageAccount storageAccount = null;
var keyVaultUri = string.Empty;
IIdentity managedIdentity = null;
IPrivateDnsZone postgreSqlDnsZone = null;
try
{
if (configuration.Update)
{
resourceGroup = await azureSubscriptionClient.ResourceGroups.GetByNameAsync(configuration.ResourceGroupName);
configuration.RegionName = resourceGroup.RegionName;
var targetVersion = Utility.DelimitedTextToDictionary(Utility.GetFileContent("scripts", "env-00-tes-version.txt")).GetValueOrDefault("TesOnAzureVersion");
ConsoleEx.WriteLine($"Upgrading TES on Azure instance in resource group '{resourceGroup.Name}' to version {targetVersion}...");
if (!string.IsNullOrEmpty(configuration.StorageAccountName))
{
storageAccount = await GetExistingStorageAccountAsync(configuration.StorageAccountName)
?? throw new ValidationException($"Storage account {configuration.StorageAccountName} does not exist in region {configuration.RegionName} or is not accessible to the current user.", displayExample: false);
}
else
{
var storageAccounts = (await azureSubscriptionClient.StorageAccounts.ListByResourceGroupAsync(configuration.ResourceGroupName)).ToList();
storageAccount = storageAccounts.Count switch
{
0 => throw new ValidationException($"Update was requested but resource group {configuration.ResourceGroupName} does not contain any storage accounts.", displayExample: false),
1 => storageAccounts.Single(),
_ => throw new ValidationException($"Resource group {configuration.ResourceGroupName} contains multiple storage accounts. {nameof(configuration.StorageAccountName)} must be provided.", displayExample: false),
};
}
ManagedCluster existingAksCluster = default;
if (!string.IsNullOrWhiteSpace(configuration.AksClusterName))
{
existingAksCluster = (await GetExistingAKSClusterAsync(configuration.AksClusterName))
?? throw new ValidationException($"AKS cluster {configuration.AksClusterName} does not exist in region {configuration.RegionName} or is not accessible to the current user.", displayExample: false);
}
else
{
using var client = new ContainerServiceClient(azureCredentials) { SubscriptionId = configuration.SubscriptionId };
var aksClusters = (await client.ManagedClusters.ListByResourceGroupAsync(configuration.ResourceGroupName)).ToList();
existingAksCluster = aksClusters.Count switch
{
0 => throw new ValidationException($"Update was requested but resource group {configuration.ResourceGroupName} does not contain any AKS clusters.", displayExample: false),
1 => aksClusters.Single(),
_ => throw new ValidationException($"Resource group {configuration.ResourceGroupName} contains multiple AKS clusters. {nameof(configuration.AksClusterName)} must be provided.", displayExample: false),
};
configuration.AksClusterName = existingAksCluster.Name;
}
var aksValues = await kubernetesManager.GetAKSSettingsAsync(storageAccount);
if (!aksValues.Any())
{
throw new ValidationException($"Could not retrieve account names from stored configuration in {storageAccount.Name}.", displayExample: false);
}
if (aksValues.TryGetValue("EnableIngress", out var enableIngress) && aksValues.TryGetValue("TesHostname", out var tesHostname))
{
kubernetesManager.TesHostname = tesHostname;
configuration.EnableIngress = bool.TryParse(enableIngress, out var parsed) ? parsed : null;
var tesCredentials = new FileInfo(Path.Combine(Directory.GetCurrentDirectory(), TesCredentialsFileName));
if (configuration.EnableIngress.GetValueOrDefault() && tesCredentials.Exists)
{
try
{
using var stream = tesCredentials.OpenRead();
var (hostname, tesUsername, tesPassword) = System.Text.Json.JsonSerializer.Deserialize<TesCredentials>(stream,
new System.Text.Json.JsonSerializerOptions() { IncludeFields = true, PropertyNameCaseInsensitive = true });
if (kubernetesManager.TesHostname.Equals(hostname, StringComparison.InvariantCultureIgnoreCase) && string.IsNullOrEmpty(configuration.TesPassword))
{
configuration.TesPassword = tesPassword;
configuration.TesUsername = tesUsername;
}
}
catch (NotSupportedException)
{ }
catch (ArgumentException)
{ }
catch (IOException)
{ }
catch (UnauthorizedAccessException)
{ }
catch (System.Text.Json.JsonException)
{ }
}
}
if (!configuration.SkipTestWorkflow && configuration.EnableIngress.GetValueOrDefault() && string.IsNullOrEmpty(configuration.TesPassword))
{
throw new ValidationException($"{nameof(configuration.TesPassword)} is required for update.", false);
}
if (!aksValues.TryGetValue("BatchAccountName", out var batchAccountName))
{
throw new ValidationException($"Could not retrieve the Batch account name from stored configuration in {storageAccount.Name}.", displayExample: false);
}
batchAccount = await GetExistingBatchAccountAsync(batchAccountName)
?? throw new ValidationException($"Batch account {batchAccountName}, referenced by the stored configuration, does not exist in region {configuration.RegionName} or is not accessible to the current user.", displayExample: false);
configuration.BatchAccountName = batchAccountName;
// Note: Current behavior is to block switching from Docker MySQL to Azure PostgreSql on Update.
// However we do ancitipate including this change, this code is here to facilitate this future behavior.
configuration.PostgreSqlServerName = aksValues.GetValueOrDefault("PostgreSqlServerName");
if (aksValues.TryGetValue("CrossSubscriptionAKSDeployment", out var crossSubscriptionAKSDeployment))
{
configuration.CrossSubscriptionAKSDeployment = bool.TryParse(crossSubscriptionAKSDeployment, out var parsed) ? parsed : null;
}
if (aksValues.TryGetValue("KeyVaultName", out var keyVaultName))
{
var keyVault = await GetKeyVaultAsync(keyVaultName);
keyVaultUri = keyVault.Properties.VaultUri;
}
if (!aksValues.TryGetValue("ManagedIdentityClientId", out var managedIdentityClientId))
{
throw new ValidationException($"Could not retrieve ManagedIdentityClientId.", displayExample: false);
}
managedIdentity = azureSubscriptionClient.Identities.ListByResourceGroup(configuration.ResourceGroupName).Where(id => id.ClientId == managedIdentityClientId).FirstOrDefault()
?? throw new ValidationException($"Managed Identity {managedIdentityClientId} does not exist in region {configuration.RegionName} or is not accessible to the current user.", displayExample: false);
// Override any configuration that is used by the update.
var versionString = aksValues["TesOnAzureVersion"];
var installedVersion = !string.IsNullOrEmpty(versionString) && Version.TryParse(versionString, out var version) ? version : null;
if (installedVersion is null || installedVersion < new Version(4, 1)) // Assume 4.0.0. The work needed to upgrade from this version shouldn't apply to other releases of TES.
{
var tesImageString = aksValues["TesImageName"];
if (!string.IsNullOrEmpty(tesImageString) && tesImageString.EndsWith("/tes:4"))
{
aksValues["TesImageName"] = tesImageString + ".0";
installedVersion = new("4.0");
}
}
var settings = ConfigureSettings(managedIdentity.ClientId, aksValues, installedVersion);
//if (installedVersion is null || installedVersion < new Version(4, 2))
//{
//}
if (installedVersion is null || installedVersion < new Version(4, 4))
{
// Ensure all storage containers are created.
await CreateDefaultStorageContainersAsync(storageAccount);
if (string.IsNullOrWhiteSpace(settings["BatchNodesSubnetId"]))
{
settings["BatchNodesSubnetId"] = await UpdateVnetWithBatchSubnet();
}
}
await kubernetesManager.UpgradeValuesYamlAsync(storageAccount, settings);
await PerformHelmDeploymentAsync(resourceGroup);
}
if (!configuration.Update)
{
configuration.ProvisionPostgreSqlOnAzure ??= true;
if (string.IsNullOrWhiteSpace(configuration.BatchPrefix))
{
var blob = new byte[5];
RandomNumberGenerator.Fill(blob);
configuration.BatchPrefix = CommonUtilities.Base32.ConvertToBase32(blob).TrimEnd('=');
}
ValidateRegionName(configuration.RegionName);
ValidateMainIdentifierPrefix(configuration.MainIdentifierPrefix);
storageAccount = await ValidateAndGetExistingStorageAccountAsync();
batchAccount = await ValidateAndGetExistingBatchAccountAsync();
aksCluster = await ValidateAndGetExistingAKSClusterAsync();
postgreSqlFlexServer = await ValidateAndGetExistingPostgresqlServerAsync();
var keyVault = await ValidateAndGetExistingKeyVaultAsync();
// Configuration preferences not currently settable by user.
if (string.IsNullOrWhiteSpace(configuration.PostgreSqlServerName) && configuration.ProvisionPostgreSqlOnAzure.GetValueOrDefault())
{
configuration.PostgreSqlServerName = SdkContext.RandomResourceName($"{configuration.MainIdentifierPrefix}-", 15);
}
configuration.PostgreSqlAdministratorPassword = PasswordGenerator.GeneratePassword();
configuration.PostgreSqlTesUserPassword = PasswordGenerator.GeneratePassword();
if (string.IsNullOrWhiteSpace(configuration.BatchAccountName))
{
configuration.BatchAccountName = SdkContext.RandomResourceName($"{configuration.MainIdentifierPrefix}", 15);
}
if (string.IsNullOrWhiteSpace(configuration.StorageAccountName))
{
configuration.StorageAccountName = SdkContext.RandomResourceName($"{configuration.MainIdentifierPrefix}", 24);
}
//if (string.IsNullOrWhiteSpace(configuration.NetworkSecurityGroupName))
//{
// configuration.NetworkSecurityGroupName = SdkContext.RandomResourceName($"{configuration.MainIdentifierPrefix}", 15);
//}
if (string.IsNullOrWhiteSpace(configuration.ApplicationInsightsAccountName))
{
configuration.ApplicationInsightsAccountName = SdkContext.RandomResourceName($"{configuration.MainIdentifierPrefix}-", 15);
}
if (string.IsNullOrWhiteSpace(configuration.TesPassword))
{
configuration.TesPassword = PasswordGenerator.GeneratePassword();
}
if (string.IsNullOrWhiteSpace(configuration.AksClusterName))
{
configuration.AksClusterName = SdkContext.RandomResourceName($"{configuration.MainIdentifierPrefix}-", 25);
}
if (string.IsNullOrWhiteSpace(configuration.KeyVaultName))
{
configuration.KeyVaultName = SdkContext.RandomResourceName($"{configuration.MainIdentifierPrefix}-", 15);
}
await RegisterResourceProvidersAsync();
await ValidateVmAsync();
if (batchAccount is null)
{
await ValidateBatchAccountQuotaAsync();
}
var vnetAndSubnet = await ValidateAndGetExistingVirtualNetworkAsync();
if (string.IsNullOrWhiteSpace(configuration.ResourceGroupName))
{
configuration.ResourceGroupName = SdkContext.RandomResourceName($"{configuration.MainIdentifierPrefix}-", 15);
resourceGroup = await CreateResourceGroupAsync();
isResourceGroupCreated = true;
}
else
{
resourceGroup = await azureSubscriptionClient.ResourceGroups.GetByNameAsync(configuration.ResourceGroupName);
}
// Derive TES ingress URL from resource group name
kubernetesManager.SetTesIngressNetworkingConfiguration(configuration.ResourceGroupName);
managedIdentity = await CreateUserManagedIdentityAsync(resourceGroup);
if (vnetAndSubnet is not null)
{
ConsoleEx.WriteLine($"Creating VM in existing virtual network {vnetAndSubnet.Value.virtualNetwork.Name} and subnet {vnetAndSubnet.Value.vmSubnet.Name}");
}
if (storageAccount is not null)
{
ConsoleEx.WriteLine($"Using existing Storage Account {storageAccount.Name}");
}
if (batchAccount is not null)
{
ConsoleEx.WriteLine($"Using existing Batch Account {batchAccount.Name}");
}
if (vnetAndSubnet is null)
{
configuration.VnetName = SdkContext.RandomResourceName($"{configuration.MainIdentifierPrefix}-", 15);
configuration.PostgreSqlSubnetName = string.IsNullOrEmpty(configuration.PostgreSqlSubnetName) ? configuration.DefaultPostgreSqlSubnetName : configuration.PostgreSqlSubnetName;
configuration.BatchSubnetName = string.IsNullOrEmpty(configuration.BatchSubnetName) ? configuration.DefaultBatchSubnetName : configuration.BatchSubnetName;
configuration.VmSubnetName = string.IsNullOrEmpty(configuration.VmSubnetName) ? configuration.DefaultVmSubnetName : configuration.VmSubnetName;
vnetAndSubnet = await CreateVnetAndSubnetsAsync(resourceGroup);
if (string.IsNullOrEmpty(this.configuration.BatchNodesSubnetId))
{
this.configuration.BatchNodesSubnetId = vnetAndSubnet.Value.batchSubnet.Inner.Id;
}
}
if (string.IsNullOrWhiteSpace(configuration.LogAnalyticsArmId))
{
var workspaceName = SdkContext.RandomResourceName(configuration.MainIdentifierPrefix, 15);
logAnalyticsWorkspace = await CreateLogAnalyticsWorkspaceResourceAsync(workspaceName);
configuration.LogAnalyticsArmId = logAnalyticsWorkspace.Id;
}
await Task.Run(async () =>
{
storageAccount ??= await CreateStorageAccountAsync();
await CreateDefaultStorageContainersAsync(storageAccount);
await WritePersonalizedFilesToStorageAccountAsync(storageAccount, managedIdentity.Name);
await AssignVmAsContributorToStorageAccountAsync(managedIdentity, storageAccount);
await AssignVmAsDataReaderToStorageAccountAsync(managedIdentity, storageAccount);
await AssignManagedIdOperatorToResourceAsync(managedIdentity, resourceGroup);
await AssignMIAsNetworkContributorToResourceAsync(managedIdentity, resourceGroup);
});
if (configuration.CrossSubscriptionAKSDeployment.GetValueOrDefault())
{
await Task.Run(async () =>
{
keyVault ??= await CreateKeyVaultAsync(configuration.KeyVaultName, managedIdentity, vnetAndSubnet.Value.vmSubnet);
keyVaultUri = keyVault.Properties.VaultUri;
var keys = await storageAccount.GetKeysAsync();
await SetStorageKeySecret(keyVaultUri, StorageAccountKeySecretName, keys[0].Value);
});
}
if (configuration.ProvisionPostgreSqlOnAzure.GetValueOrDefault() && postgreSqlFlexServer is null)
{
postgreSqlDnsZone = await CreatePrivateDnsZoneAsync(vnetAndSubnet.Value.virtualNetwork, $"privatelink.postgres.database.azure.com", "PostgreSQL Server");
}
await Task.WhenAll(new[]
{
Task.Run(async () =>
{
if (aksCluster is null && !configuration.ManualHelmDeployment)
{
await ProvisionManagedClusterAsync(resourceGroup, managedIdentity, logAnalyticsWorkspace, vnetAndSubnet?.virtualNetwork, vnetAndSubnet?.vmSubnet.Name, configuration.PrivateNetworking.GetValueOrDefault());
}
}),
Task.Run(async () =>
{
batchAccount ??= await CreateBatchAccountAsync(storageAccount.Id);
await AssignVmAsContributorToBatchAccountAsync(managedIdentity, batchAccount);
}),
Task.Run(async () =>
{
appInsights = await CreateAppInsightsResourceAsync(configuration.LogAnalyticsArmId);
await AssignVmAsContributorToAppInsightsAsync(managedIdentity, appInsights);
}),
Task.Run(async () => {
if (configuration.UsePostgreSqlSingleServer)
{
postgreSqlSingleServer ??= await CreateSinglePostgreSqlServerAndDatabaseAsync(postgreSqlSingleManagementClient, vnetAndSubnet.Value.vmSubnet, postgreSqlDnsZone);
}
else
{
postgreSqlFlexServer ??= await CreatePostgreSqlServerAndDatabaseAsync(postgreSqlFlexManagementClient, vnetAndSubnet.Value.postgreSqlSubnet, postgreSqlDnsZone);
}
})
});
var clientId = managedIdentity.ClientId;
var settings = ConfigureSettings(clientId);
await kubernetesManager.UpdateHelmValuesAsync(storageAccount, keyVaultUri, resourceGroup.Name, settings, managedIdentity);
await PerformHelmDeploymentAsync(resourceGroup,
new[]
{
"Run the following postgresql command to setup the database.",
"\tPostgreSQL command: " + GetPostgreSQLCreateUserCommand(configuration.UsePostgreSqlSingleServer, configuration.PostgreSqlTesDatabaseName, GetCreateTesUserString()),
},
async kubernetesClient =>
{
await kubernetesManager.DeployCoADependenciesAsync();
// Deploy an ubuntu pod to run PSQL commands, then delete it
const string deploymentNamespace = "default";
var (deploymentName, ubuntuDeployment) = KubernetesManager.GetUbuntuDeploymentTemplate();
await kubernetesClient.AppsV1.CreateNamespacedDeploymentAsync(ubuntuDeployment, deploymentNamespace);
await ExecuteQueriesOnAzurePostgreSQLDbFromK8(kubernetesClient, deploymentName, deploymentNamespace);
await kubernetesClient.AppsV1.DeleteNamespacedDeploymentAsync(deploymentName, deploymentNamespace);
if (configuration.EnableIngress.GetValueOrDefault())
{
_ = await kubernetesManager.EnableIngress(configuration.TesUsername, configuration.TesPassword, kubernetesClient);
}
});
}
}
finally
{
if (!configuration.ManualHelmDeployment)
{
kubernetesManager.DeleteTempFiles();
}
}
var maxPerFamilyQuota = batchAccount.DedicatedCoreQuotaPerVMFamilyEnforced ? batchAccount.DedicatedCoreQuotaPerVMFamily.Select(q => q.CoreQuota).Where(q => 0 != q) : Enumerable.Repeat(batchAccount.DedicatedCoreQuota ?? 0, 1);
var isBatchQuotaAvailable = batchAccount.LowPriorityCoreQuota > 0 || (batchAccount.DedicatedCoreQuota > 0 && maxPerFamilyQuota.Append(0).Max() > 0);
int exitCode;
if (configuration.EnableIngress.GetValueOrDefault())
{
ConsoleEx.WriteLine($"TES ingress is enabled");
ConsoleEx.WriteLine($"TES is secured with basic auth at {kubernetesManager.TesHostname}");
if (configuration.OutputTesCredentialsJson.GetValueOrDefault())
{
// Write credentials to JSON file in working directory
var credentialsJson = System.Text.Json.JsonSerializer.Serialize<TesCredentials>(
new(kubernetesManager.TesHostname, configuration.TesUsername, configuration.TesPassword));
var credentialsPath = Path.Combine(Directory.GetCurrentDirectory(), TesCredentialsFileName);
await File.WriteAllTextAsync(credentialsPath, credentialsJson);
ConsoleEx.WriteLine($"TES credentials file written to: {credentialsPath}");
}
if (isBatchQuotaAvailable)
{
if (configuration.SkipTestWorkflow)
{
exitCode = 0;
}
else
{
var isTestWorkflowSuccessful = await RunTestTask(kubernetesManager.TesHostname, batchAccount.LowPriorityCoreQuota > 0, configuration.TesUsername, configuration.TesPassword);
if (!isTestWorkflowSuccessful)
{
await DeleteResourceGroupIfUserConsentsAsync();
}
exitCode = isTestWorkflowSuccessful ? 0 : 1;
}
}
else
{
if (!configuration.SkipTestWorkflow)
{
ConsoleEx.WriteLine($"Could not run the test task.", ConsoleColor.Yellow);
}
ConsoleEx.WriteLine($"Deployment was successful, but Batch account {configuration.BatchAccountName} does not have sufficient core quota to run workflows.", ConsoleColor.Yellow);
ConsoleEx.WriteLine($"Request Batch core quota: https://docs.microsoft.com/en-us/azure/batch/batch-quota-limit", ConsoleColor.Yellow);
ConsoleEx.WriteLine($"After receiving the quota, read the docs to run a test workflow and confirm successful deployment.", ConsoleColor.Yellow);
exitCode = 2;
}
}
else
{
ConsoleEx.WriteLine($"TES ingress is not enabled, skipping test tasks.");
exitCode = 2;
}
ConsoleEx.WriteLine($"Completed in {mainTimer.Elapsed.TotalMinutes:n1} minutes.");
return exitCode;
}
catch (ValidationException validationException)
{
DisplayValidationExceptionAndExit(validationException);
return 1;
}
catch (Exception exc)
{
if (!(exc is OperationCanceledException && cts.Token.IsCancellationRequested))
{
ConsoleEx.WriteLine();
ConsoleEx.WriteLine($"{exc.GetType().Name}: {exc.Message}", ConsoleColor.Red);
if (configuration.DebugLogging)
{
ConsoleEx.WriteLine(exc.StackTrace, ConsoleColor.Red);
if (exc is KubernetesException kExc)
{
ConsoleEx.WriteLine($"Kubenetes Status: {kExc.Status}");
}
if (exc is WebSocketException wExc)
{
ConsoleEx.WriteLine($"WebSocket ErrorCode: {wExc.WebSocketErrorCode}");
}
if (exc is HttpOperationException hExc)
{
ConsoleEx.WriteLine($"HTTP Response: {hExc.Response.Content}");
}
if (exc is HttpRequestException rExc)
{
ConsoleEx.WriteLine($"HTTP Request StatusCode: {rExc.StatusCode.ToString()}");
if (rExc.InnerException is not null)
{
ConsoleEx.WriteLine($"InnerException: {rExc.InnerException.GetType().FullName}: {rExc.InnerException.Message}");
}
}
if (exc is JsonReaderException jExc)
{
if (!string.IsNullOrEmpty(jExc.Path))
{
ConsoleEx.WriteLine($"JSON Path: {jExc.Path}");
}
if (jExc.Data.Contains("Body"))
{
ConsoleEx.WriteLine($"HTTP Response: {jExc.Data["Body"]}");
}
}
}
}
ConsoleEx.WriteLine();
Debugger.Break();
WriteGeneralRetryMessageToConsole();
await DeleteResourceGroupIfUserConsentsAsync();
return 1;
}
}
private async Task PerformHelmDeploymentAsync(IResourceGroup resourceGroup, IEnumerable<string> manualPrecommands = default, Func<IKubernetes, Task> asyncTask = default)
{
if (configuration.ManualHelmDeployment)
{
ConsoleEx.WriteLine($"Helm chart written to disk at: {kubernetesManager.helmScriptsRootDirectory}");
ConsoleEx.WriteLine($"Please update values file if needed here: {kubernetesManager.TempHelmValuesYamlPath}");
foreach (var line in manualPrecommands ?? Enumerable.Empty<string>())
{
ConsoleEx.WriteLine(line);
}
ConsoleEx.WriteLine($"Then, deploy the helm chart, and press Enter to continue.");
ConsoleEx.ReadLine();
}
else
{
var kubernetesClient = await kubernetesManager.GetKubernetesClientAsync(resourceGroup);
await (asyncTask?.Invoke(kubernetesClient) ?? Task.CompletedTask);
await kubernetesManager.DeployHelmChartToClusterAsync(kubernetesClient);
}
}
private static async Task<int> TestTaskAsync(string tesEndpoint, bool preemptible, string tesUsername, string tesPassword)
{
using var client = new HttpClient();
client.SetBasicAuthentication(tesUsername, tesPassword);
var task = new TesTask()
{
Inputs = new List<TesInput>(),
Outputs = new List<TesOutput>(),
Executors = new List<TesExecutor>
{
new TesExecutor()
{
Image = "ubuntu:22.04",
Command = new List<string>{"echo 'hello world'" },
}
},
Resources = new TesResources()
{
Preemptible = preemptible
}
};
var content = new StringContent(JsonConvert.SerializeObject(task), Encoding.UTF8, "application/json");
var requestUri = $"https://{tesEndpoint}/v1/tasks";
Dictionary<string, string> response = null;
await longRetryPolicy.ExecuteAsync(
async () =>
{
var responseBody = await client.PostAsync(requestUri, content);
var body = await responseBody.Content.ReadAsStringAsync();
try
{
response = JsonConvert.DeserializeObject<Dictionary<string, string>>(body);
}
catch (JsonReaderException exception)
{
exception.Data.Add("Body", body);
throw;
}
});
return await IsTaskSuccessfulAfterLongPollingAsync(client, $"{requestUri}/{response["id"]}?view=full") ? 0 : 1;
}
private static async Task<bool> RunTestTask(string tesEndpoint, bool preemptible, string tesUsername, string tesPassword)
{
var startTime = DateTime.UtcNow;
var line = ConsoleEx.WriteLine("Running a test task...");
var isTestWorkflowSuccessful = (await TestTaskAsync(tesEndpoint, preemptible, tesUsername, tesPassword)) < 1;
WriteExecutionTime(line, startTime);
if (isTestWorkflowSuccessful)
{
ConsoleEx.WriteLine();
ConsoleEx.WriteLine($"Test task succeeded.", ConsoleColor.Green);
ConsoleEx.WriteLine();
ConsoleEx.WriteLine("Learn more about how to use Tes on Azure: https://github.com/microsoft/ga4gh-tes");
ConsoleEx.WriteLine();
}
else
{
ConsoleEx.WriteLine();
ConsoleEx.WriteLine($"Test task failed.", ConsoleColor.Red);
ConsoleEx.WriteLine();
WriteGeneralRetryMessageToConsole();
ConsoleEx.WriteLine();
}
return isTestWorkflowSuccessful;
}
private static async Task<bool> IsTaskSuccessfulAfterLongPollingAsync(HttpClient client, string taskEndpoint)
{
while (true)
{
try
{
var responseBody = await client.GetAsync(taskEndpoint);
var content = await responseBody.Content.ReadAsStringAsync();
var response = JsonConvert.DeserializeObject<TesTask>(content);
if (response.State == TesState.COMPLETEEnum)
{
if (string.IsNullOrWhiteSpace(response.FailureReason))
{
ConsoleEx.WriteLine($"TES Task State: {response.State}");
return true;
}
ConsoleEx.WriteLine($"Failure reason: {response.FailureReason}");
return false;
}
else if (response.State == TesState.EXECUTORERROREnum || response.State == TesState.SYSTEMERROREnum || response.State == TesState.CANCELEDEnum)
{
ConsoleEx.WriteLine($"TES Task State: {response.State}");
ConsoleEx.WriteLine(content);
if (!string.IsNullOrWhiteSpace(response.FailureReason))
{
ConsoleEx.WriteLine($"Failure reason: {response.FailureReason}");
}
return false;
}
}
catch (Exception exc)
{
// "Server is busy" occasionally can be ignored
ConsoleEx.WriteLine($"Transient error: '{exc.Message}' Will retry again in 10s.");
}
await Task.Delay(System.TimeSpan.FromSeconds(10));
}
}
private async Task<Vault> ValidateAndGetExistingKeyVaultAsync()
{
if (string.IsNullOrWhiteSpace(configuration.KeyVaultName))
{
return null;
}
return (await GetKeyVaultAsync(configuration.KeyVaultName))
?? throw new ValidationException($"If key vault name is provided, it must already exist in region {configuration.RegionName}, and be accessible to the current user.", displayExample: false);
}
private async Task<FlexibleServerModel.Server> ValidateAndGetExistingPostgresqlServerAsync()
{
if (string.IsNullOrWhiteSpace(configuration.PostgreSqlServerName))
{
return null;
}
return (await GetExistingPostgresqlServiceAsync(configuration.PostgreSqlServerName))
?? throw new ValidationException($"If Postgresql server name is provided, the server must already exist in region {configuration.RegionName}, and be accessible to the current user.", displayExample: false);
}
private async Task<ManagedCluster> ValidateAndGetExistingAKSClusterAsync()
{
if (string.IsNullOrWhiteSpace(configuration.AksClusterName))
{
return null;
}
return (await GetExistingAKSClusterAsync(configuration.AksClusterName))
?? throw new ValidationException($"If AKS cluster name is provided, the cluster must already exist in region {configuration.RegionName}, and be accessible to the current user.", displayExample: false);
}
private async Task<FlexibleServerModel.Server> GetExistingPostgresqlServiceAsync(string serverName)
{
var regex = new Regex(@"\s+");
return (await Task.WhenAll(subscriptionIds.Select(async s =>
{
try
{
var client = new FlexibleServer.PostgreSQLManagementClient(tokenCredentials) { SubscriptionId = s };
return await client.Servers.ListAsync();
}
catch (Exception e)
{
ConsoleEx.WriteLine(e.Message);
return null;
}
})))
.Where(a => a is not null)
.SelectMany(a => a)
.SingleOrDefault(a => a.Name.Equals(serverName, StringComparison.OrdinalIgnoreCase) && regex.Replace(a.Location, "").Equals(configuration.RegionName, StringComparison.OrdinalIgnoreCase));
}
private async Task<ManagedCluster> GetExistingAKSClusterAsync(string aksClusterName)
{
return (await Task.WhenAll(subscriptionIds.Select(async s =>
{
try
{
var client = new ContainerServiceClient(tokenCredentials) { SubscriptionId = s };
return await client.ManagedClusters.ListAsync();
}
catch (Exception e)
{
ConsoleEx.WriteLine(e.Message);
return null;
}
})))
.Where(a => a is not null)
.SelectMany(a => a)
.SingleOrDefault(a => a.Name.Equals(aksClusterName, StringComparison.OrdinalIgnoreCase) && a.Location.Equals(configuration.RegionName, StringComparison.OrdinalIgnoreCase));
}
private async Task<ManagedCluster> ProvisionManagedClusterAsync(IResource resourceGroupObject, IIdentity managedIdentity, IGenericResource logAnalyticsWorkspace, INetwork virtualNetwork, string subnetName, bool privateNetworking)
{
var resourceGroup = resourceGroupObject.Name;
var nodePoolName = "nodepool1";
var containerServiceClient = new ContainerServiceClient(azureCredentials) { SubscriptionId = configuration.SubscriptionId };
var cluster = new ManagedCluster
{
AddonProfiles = new Dictionary<string, ManagedClusterAddonProfile>
{
{ "omsagent", new(true, new Dictionary<string, string>() { { "logAnalyticsWorkspaceResourceID", logAnalyticsWorkspace.Id } }) }
},
Location = configuration.RegionName,
DnsPrefix = configuration.AksClusterName,
NetworkProfile = new()
{
NetworkPlugin = NetworkPlugin.Azure,
ServiceCidr = configuration.KubernetesServiceCidr,
DnsServiceIP = configuration.KubernetesDnsServiceIP,
DockerBridgeCidr = configuration.KubernetesDockerBridgeCidr,
NetworkPolicy = NetworkPolicy.Azure
},
Identity = new(managedIdentity.PrincipalId, managedIdentity.TenantId, Microsoft.Azure.Management.ContainerService.Models.ResourceIdentityType.UserAssigned)
{
UserAssignedIdentities = new Dictionary<string, ManagedClusterIdentityUserAssignedIdentitiesValue>()
}
};
if (!string.IsNullOrWhiteSpace(configuration.AadGroupIds))
{
cluster.EnableRBAC = true;
cluster.AadProfile = new ManagedClusterAADProfile()
{
AdminGroupObjectIDs = configuration.AadGroupIds.Split(",", StringSplitOptions.RemoveEmptyEntries),
EnableAzureRBAC = false,
Managed = true
};
}
cluster.Identity.UserAssignedIdentities.Add(managedIdentity.Id, new(managedIdentity.PrincipalId, managedIdentity.ClientId));
cluster.IdentityProfile = new Dictionary<string, ManagedClusterPropertiesIdentityProfileValue>
{
{ "kubeletidentity", new(managedIdentity.Id, managedIdentity.ClientId, managedIdentity.PrincipalId) }
};
cluster.AgentPoolProfiles = new List<ManagedClusterAgentPoolProfile>
{
new()
{
Name = nodePoolName,
Count = configuration.AksPoolSize,
VmSize = configuration.VmSize,
OsDiskSizeGB = 128,
OsDiskType = OSDiskType.Managed,
Type = "VirtualMachineScaleSets",
EnableAutoScaling = false,
EnableNodePublicIP = false,
OsType = "Linux",
Mode = "System",
VnetSubnetID = virtualNetwork.Subnets[subnetName].Inner.Id,
}
};
if (privateNetworking)
{
cluster.ApiServerAccessProfile = new()
{
EnablePrivateCluster = true,
EnablePrivateClusterPublicFQDN = true
};
}
return await Execute(
$"Creating AKS Cluster: {configuration.AksClusterName}...",
() => containerServiceClient.ManagedClusters.CreateOrUpdateAsync(resourceGroup, configuration.AksClusterName, cluster));
}
private static Dictionary<string, string> GetDefaultValues(string[] files)
{
var settings = new Dictionary<string, string>();
foreach (var file in files)
{
settings = settings.Union(Utility.DelimitedTextToDictionary(Utility.GetFileContent("scripts", file))).ToDictionary(kv => kv.Key, kv => kv.Value);
}
return settings;
}
private Dictionary<string, string> ConfigureSettings(string managedIdentityClientId, Dictionary<string, string> settings = null, Version installedVersion = null)
{
settings ??= new();
var defaults = GetDefaultValues(new[] { "env-00-tes-version.txt", "env-01-account-names.txt", "env-02-internal-images.txt", "env-04-settings.txt" });
// We always overwrite the CoA version
UpdateSetting(settings, defaults, "TesOnAzureVersion", default(string), ignoreDefaults: false);
UpdateSetting(settings, defaults, "ResourceGroupName", configuration.ResourceGroupName, ignoreDefaults: false);
UpdateSetting(settings, defaults, "RegionName", configuration.RegionName, ignoreDefaults: false);
// Process images
UpdateSetting(settings, defaults, "TesImageName", configuration.TesImageName,
ignoreDefaults: ImageNameIgnoreDefaults(settings, defaults, "TesImageName", configuration.TesImageName is null, installedVersion));
// Additional non-personalized settings
UpdateSetting(settings, defaults, "BatchNodesSubnetId", configuration.BatchNodesSubnetId);
UpdateSetting(settings, defaults, "DockerInDockerImageName", configuration.DockerInDockerImageName);
UpdateSetting(settings, defaults, "DisableBatchNodesPublicIpAddress", configuration.DisableBatchNodesPublicIpAddress, b => b.GetValueOrDefault().ToString(), configuration.DisableBatchNodesPublicIpAddress.GetValueOrDefault().ToString());
if (installedVersion is null)
{