-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathDeploymentController.cs
More file actions
803 lines (684 loc) · 39.7 KB
/
DeploymentController.cs
File metadata and controls
803 lines (684 loc) · 39.7 KB
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
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using System.Threading.Tasks;
using Amazon;
using Amazon.ElasticLoadBalancingV2;
using AWS.Deploy.CLI.Utilities;
using AWS.Deploy.Recipes;
using AWS.Deploy.Orchestration.CDK;
using AWS.Deploy.Orchestration.Data;
using AWS.Deploy.Common;
using AWS.Deploy.CLI.ServerMode.Tasks;
using AWS.Deploy.CLI.ServerMode.Models;
using AWS.Deploy.CLI.ServerMode.Services;
using AWS.Deploy.Orchestration;
using Swashbuckle.AspNetCore.Annotations;
using AWS.Deploy.CLI.ServerMode.Hubs;
using Microsoft.AspNetCore.SignalR;
using AWS.Deploy.CLI.Extensions;
using AWS.Deploy.Orchestration.Utilities;
using Microsoft.AspNetCore.Authorization;
using Amazon.Runtime;
using AWS.Deploy.Common.Recipes;
using AWS.Deploy.Orchestration.DisplayedResources;
using AWS.Deploy.Common.IO;
using AWS.Deploy.Orchestration.LocalUserSettings;
using AWS.Deploy.CLI.Commands;
using AWS.Deploy.CLI.Commands.TypeHints;
using AWS.Deploy.Common.TypeHintData;
using AWS.Deploy.Orchestration.ServiceHandlers;
using AWS.Deploy.Common.Data;
using AWS.Deploy.Common.Recipes.Validation;
using AWS.Deploy.Orchestration.Docker;
namespace AWS.Deploy.CLI.ServerMode.Controllers
{
[Produces("application/json")]
[ApiController]
[Route("api/v1/[controller]")]
public class DeploymentController : ControllerBase
{
private readonly IDeploymentSessionStateServer _stateServer;
private readonly IProjectParserUtility _projectParserUtility;
private readonly ICloudApplicationNameGenerator _cloudApplicationNameGenerator;
private readonly IHubContext<DeploymentCommunicationHub, IDeploymentCommunicationHub> _hubContext;
public DeploymentController(
IDeploymentSessionStateServer stateServer,
IProjectParserUtility projectParserUtility,
ICloudApplicationNameGenerator cloudApplicationNameGenerator,
IHubContext<DeploymentCommunicationHub, IDeploymentCommunicationHub> hubContext
)
{
_stateServer = stateServer;
_projectParserUtility = projectParserUtility;
_cloudApplicationNameGenerator = cloudApplicationNameGenerator;
_hubContext = hubContext;
}
/// <summary>
/// Start a deployment session. A session id will be generated. This session id needs to be passed in future API calls to configure and execute deployment.
/// </summary>
[HttpPost("session")]
[SwaggerOperation(OperationId = "StartDeploymentSession")]
[SwaggerResponse(200, type: typeof(StartDeploymentSessionOutput))]
[Authorize]
public async Task<IActionResult> StartDeploymentSession(StartDeploymentSessionInput input)
{
var output = new StartDeploymentSessionOutput(
Guid.NewGuid().ToString()
);
var state = new SessionState(
output.SessionId,
input.ProjectPath,
input.AWSRegion,
await _projectParserUtility.Parse(input.ProjectPath)
);
var serviceProvider = CreateSessionServiceProvider(state);
var awsResourceQueryer = serviceProvider.GetRequiredService<IAWSResourceQueryer>();
state.AWSAccountId = (await awsResourceQueryer.GetCallerIdentity(input.AWSRegion)).Account;
_stateServer.Save(output.SessionId, state);
var deployedApplicationQueryer = serviceProvider.GetRequiredService<IDeployedApplicationQueryer>();
var session = CreateOrchestratorSession(state);
var orchestrator = CreateOrchestrator(state);
// Determine what recommendations are possible for the project.
var recommendations = await orchestrator.GenerateDeploymentRecommendations();
state.NewRecommendations = recommendations;
// Get all existing CloudApplications based on the deploymentTypes filter
var allDeployedApplications = await deployedApplicationQueryer.GetExistingDeployedApplications(recommendations.Select(x => x.Recipe.DeploymentType).ToList());
var existingApplications = await deployedApplicationQueryer.GetCompatibleApplications(recommendations, allDeployedApplications, session);
state.ExistingDeployments = existingApplications;
output.DefaultDeploymentName = _cloudApplicationNameGenerator.GenerateValidName(state.ProjectDefinition, existingApplications);
return Ok(output);
}
/// <summary>
/// Closes the deployment session. This removes any session state for the session id.
/// </summary>
[HttpDelete("session/<sessionId>")]
[SwaggerOperation(OperationId = "CloseDeploymentSession")]
[Authorize]
public IActionResult CloseDeploymentSession(string sessionId)
{
_stateServer.Delete(sessionId);
return Ok();
}
/// <summary>
/// Gets the list of compatible deployments for the session's project. The list is ordered with the first recommendation in the list being the most compatible recommendation.
/// </summary>
[HttpGet("session/<sessionId>/recommendations")]
[SwaggerOperation(OperationId = "GetRecommendations")]
[SwaggerResponse(200, type: typeof(GetRecommendationsOutput))]
[ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound)]
[Authorize]
public async Task<IActionResult> GetRecommendations(string sessionId)
{
var state = _stateServer.Get(sessionId);
if (state == null)
{
return NotFound($"Session ID {sessionId} not found.");
}
var orchestrator = CreateOrchestrator(state);
var output = new GetRecommendationsOutput();
//NewRecommendations is set during StartDeploymentSession API. It is only updated here if NewRecommendations was null.
state.NewRecommendations ??= await orchestrator.GenerateDeploymentRecommendations();
foreach (var recommendation in state.NewRecommendations)
{
if (recommendation.Recipe.DisableNewDeployments)
continue;
output.Recommendations.Add(new RecommendationSummary(
baseRecipeId: recommendation.Recipe.BaseRecipeId,
recipeId: recommendation.Recipe.Id,
name: recommendation.Name,
settingsCategories: CategorySummary.FromCategories(recommendation.GetConfigurableOptionSettingCategories()),
isPersistedDeploymentProject: recommendation.Recipe.PersistedDeploymentProject,
shortDescription: recommendation.ShortDescription,
description: recommendation.Description,
targetService: recommendation.Recipe.TargetService,
deploymentType: recommendation.Recipe.DeploymentType
));
}
return Ok(output);
}
/// <summary>
/// Gets the list of updatable option setting items for the selected recommendation.
/// </summary>
[HttpGet("session/<sessionId>/settings")]
[SwaggerOperation(OperationId = "GetConfigSettings")]
[SwaggerResponse(200, type: typeof(GetOptionSettingsOutput))]
[ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound)]
[Authorize]
public IActionResult GetConfigSettings(string sessionId)
{
var state = _stateServer.Get(sessionId);
if (state == null)
{
return NotFound($"Session ID {sessionId} not found.");
}
if (state.SelectedRecommendation == null)
{
return NotFound($"A deployment target is not set for Session ID {sessionId}.");
}
var orchestrator = CreateOrchestrator(state);
var serviceProvider = CreateSessionServiceProvider(state);
var optionSettingHandler = serviceProvider.GetRequiredService<IOptionSettingHandler>();
var configurableOptionSettings = state.SelectedRecommendation.GetConfigurableOptionSettingItems();
var output = new GetOptionSettingsOutput();
output.OptionSettings = ListOptionSettingSummary(optionSettingHandler, state.SelectedRecommendation, configurableOptionSettings);
return Ok(output);
}
private List<OptionSettingItemSummary> ListOptionSettingSummary(IOptionSettingHandler optionSettingHandler, Recommendation recommendation, IEnumerable<OptionSettingItem> configurableOptionSettings)
{
var optionSettingItems = new List<OptionSettingItemSummary>();
foreach (var setting in configurableOptionSettings)
{
var settingSummary = new OptionSettingItemSummary(
setting.Id,
setting.FullyQualifiedId,
setting.Name,
setting.Description,
setting.Type.ToString())
{
Category = setting.Category,
TypeHint = setting.TypeHint?.ToString(),
TypeHintData = setting.TypeHintData,
Value = optionSettingHandler.GetOptionSettingValue(recommendation, setting),
Advanced = setting.AdvancedSetting,
ReadOnly = recommendation.IsExistingCloudApplication && !setting.Updatable,
Visible =
optionSettingHandler.IsOptionSettingDisplayable(recommendation, setting) &&
// Updating visibility of settings in server-mode to be determined by 'VisibleOnRedeployment'
// when performing a redeployment and 'Updatable' is set to false.
!(recommendation.IsExistingCloudApplication && !setting.Updatable && !setting.VisibleOnRedeployment),
SummaryDisplayable = optionSettingHandler.IsSummaryDisplayable(recommendation, setting),
AllowedValues = setting.AllowedValues,
ValueMapping = setting.ValueMapping,
Validation = setting.Validation,
ChildOptionSettings = ListOptionSettingSummary(optionSettingHandler, recommendation, setting.ChildOptionSettings)
};
optionSettingItems.Add(settingSummary);
}
return optionSettingItems;
}
/// <summary>
/// Applies a value for a list of option setting items on the selected recommendation.
/// Option setting updates are provided as Key Value pairs with the Key being the JSON path to the leaf node.
/// Only primitive data types are supported for Value updates. The Value is a string value which will be parsed as its corresponding data type.
/// </summary>
[HttpPut("session/<sessionId>/settings")]
[SwaggerOperation(OperationId = "ApplyConfigSettings")]
[SwaggerResponse(200, type: typeof(ApplyConfigSettingsOutput))]
[ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound)]
[ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest)]
[Authorize]
public async Task<IActionResult> ApplyConfigSettings(string sessionId, [FromBody] ApplyConfigSettingsInput input)
{
var state = _stateServer.Get(sessionId);
if (state == null)
{
return NotFound($"Session ID {sessionId} not found.");
}
if (state.SelectedRecommendation == null)
{
return NotFound($"A deployment target is not set for Session ID {sessionId}.");
}
var serviceProvider = CreateSessionServiceProvider(state);
var optionSettingHandler = serviceProvider.GetRequiredService<IOptionSettingHandler>();
var output = new ApplyConfigSettingsOutput();
var optionSettingItems = input.UpdatedSettings
.Select(x => optionSettingHandler.GetOptionSetting(state.SelectedRecommendation, x.Key));
var readonlySettings = optionSettingItems
.Where(x => state.SelectedRecommendation.IsExistingCloudApplication && !x.Updatable);
if (readonlySettings.Any())
return BadRequest($"The following settings are read only and cannot be updated: {string.Join(", ", readonlySettings)}");
foreach (var updatedSetting in optionSettingItems)
{
try
{
await optionSettingHandler.SetOptionSettingValue(state.SelectedRecommendation, updatedSetting, input.UpdatedSettings[updatedSetting.FullyQualifiedId]);
}
catch (Exception ex)
{
output.FailedConfigUpdates.Add(updatedSetting.FullyQualifiedId, ex.Message);
}
}
return Ok(output);
}
[HttpGet("session/<sessionId>/settings/<configSettingId>/resources")]
[SwaggerOperation(OperationId = "GetConfigSettingResources")]
[SwaggerResponse(200, type: typeof(GetConfigSettingResourcesOutput))]
[ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound)]
[Authorize]
public async Task<IActionResult> GetConfigSettingResources(string sessionId, string configSettingId)
{
var state = _stateServer.Get(sessionId);
if (state == null)
{
return NotFound($"Session ID {sessionId} not found.");
}
if (state.SelectedRecommendation == null)
{
return NotFound($"A deployment target is not set for Session ID {sessionId}.");
}
var serviceProvider = CreateSessionServiceProvider(state);
var typeHintCommandFactory = serviceProvider.GetRequiredService<ITypeHintCommandFactory>();
var optionSettingHandler = serviceProvider.GetRequiredService<IOptionSettingHandler>();
var configSetting = optionSettingHandler.GetOptionSetting(state.SelectedRecommendation, configSettingId);
if (configSetting.TypeHint.HasValue && typeHintCommandFactory.GetCommand(configSetting.TypeHint.Value) is var typeHintCommand && typeHintCommand != null)
{
var output = new GetConfigSettingResourcesOutput();
var resourceTable = await typeHintCommand.GetResources(state.SelectedRecommendation, configSetting);
if (resourceTable == null)
{
return NotFound("The Config Setting type hint is not recognized.");
}
output.Columns = resourceTable.Columns?.Select(column => new Models.TypeHintResourceColumn(column.DisplayName)).ToList();
output.Resources = resourceTable.Rows?.Select(resource => new TypeHintResourceSummary(resource.SystemName, resource.DisplayName, resource.ColumnValues)).ToList();
return Ok(output);
}
return NotFound("The Config Setting type hint is not recognized.");
}
/// <summary>
/// Gets the list of existing deployments that are compatible with the session's project.
/// </summary>
[HttpGet("session/<sessionId>/deployments")]
[SwaggerOperation(OperationId = "GetExistingDeployments")]
[SwaggerResponse(200, type: typeof(GetExistingDeploymentsOutput))]
[ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound)]
[Authorize]
public async Task<IActionResult> GetExistingDeployments(string sessionId)
{
var state = _stateServer.Get(sessionId);
if (state == null)
{
return NotFound($"Session ID {sessionId} not found.");
}
var serviceProvider = CreateSessionServiceProvider(state);
if(state.NewRecommendations == null)
{
await GetRecommendations(sessionId);
}
var output = new GetExistingDeploymentsOutput();
if(state.NewRecommendations == null)
{
return Ok(output);
}
var deployedApplicationQueryer = serviceProvider.GetRequiredService<IDeployedApplicationQueryer>();
var session = CreateOrchestratorSession(state);
//ExistingDeployments is set during StartDeploymentSession API. It is only updated here if ExistingDeployments was null.
state.ExistingDeployments ??= await deployedApplicationQueryer.GetCompatibleApplications(state.NewRecommendations.ToList(), session: session);
foreach(var deployment in state.ExistingDeployments)
{
var recommendation = state.NewRecommendations.First(x => string.Equals(x.Recipe.Id, deployment.RecipeId));
output.ExistingDeployments.Add(new ExistingDeploymentSummary(
name: deployment.Name,
baseRecipeId: recommendation.Recipe.BaseRecipeId,
recipeId: deployment.RecipeId,
recipeName: recommendation.Name,
settingsCategories: CategorySummary.FromCategories(recommendation.GetConfigurableOptionSettingCategories()),
isPersistedDeploymentProject: recommendation.Recipe.PersistedDeploymentProject,
shortDescription: recommendation.ShortDescription,
description: recommendation.Description,
targetService: recommendation.Recipe.TargetService,
lastUpdatedTime: deployment.LastUpdatedTime,
updatedByCurrentUser: deployment.UpdatedByCurrentUser,
resourceType: deployment.ResourceType,
uniqueIdentifier: deployment.UniqueIdentifier));
}
return Ok(output);
}
/// <summary>
/// Set the target recipe and name for the deployment.
/// </summary>
[HttpPost("session/<sessionId>")]
[SwaggerOperation(OperationId = "SetDeploymentTarget")]
[ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound)]
[ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status400BadRequest)]
[Authorize]
public async Task<IActionResult> SetDeploymentTarget(string sessionId, [FromBody] SetDeploymentTargetInput input)
{
var state = _stateServer.Get(sessionId);
if(state == null)
{
return NotFound($"Session ID {sessionId} not found.");
}
var serviceProvider = CreateSessionServiceProvider(state);
var orchestrator = CreateOrchestrator(state, serviceProvider);
var cloudApplicationNameGenerator = serviceProvider.GetRequiredService<ICloudApplicationNameGenerator>();
if (!string.IsNullOrEmpty(input.NewDeploymentRecipeId))
{
var newDeploymentName = input.NewDeploymentName ?? string.Empty;
state.SelectedRecommendation = state.NewRecommendations?.FirstOrDefault(x => string.Equals(input.NewDeploymentRecipeId, x.Recipe.Id));
if (state.SelectedRecommendation == null)
{
return NotFound($"Recommendation {input.NewDeploymentRecipeId} not found.");
}
// We only validate the name when the recipe deployment type is not ElasticContainerRegistryImage.
// This is because pushing images to ECR does not need a cloud application name.
if (state.SelectedRecommendation.Recipe.DeploymentType != Common.Recipes.DeploymentTypes.ElasticContainerRegistryImage)
{
var validationResult = cloudApplicationNameGenerator.IsValidName(newDeploymentName, state.ExistingDeployments ?? new List<CloudApplication>(), state.SelectedRecommendation.Recipe.DeploymentType);
if (!validationResult.IsValid)
return ValidationProblem(validationResult.ErrorMessage);
}
state.ApplicationDetails.Name = newDeploymentName;
state.ApplicationDetails.UniqueIdentifier = string.Empty;
state.ApplicationDetails.ResourceType = orchestrator.GetCloudApplicationResourceType(state.SelectedRecommendation.Recipe.DeploymentType);
state.ApplicationDetails.RecipeId = input.NewDeploymentRecipeId;
await orchestrator.ApplyAllReplacementTokens(state.SelectedRecommendation, newDeploymentName);
}
else if(!string.IsNullOrEmpty(input.ExistingDeploymentId))
{
var templateMetadataReader = serviceProvider.GetRequiredService<ICloudFormationTemplateReader>();
var deployedApplicationQueryer = serviceProvider.GetRequiredService<IDeployedApplicationQueryer>();
var optionSettingHandler = serviceProvider.GetRequiredService<IOptionSettingHandler>();
var existingDeployment = state.ExistingDeployments?.FirstOrDefault(x => string.Equals(input.ExistingDeploymentId, x.UniqueIdentifier));
if (existingDeployment == null)
{
return NotFound($"Existing deployment {input.ExistingDeploymentId} not found.");
}
state.SelectedRecommendation = state.NewRecommendations?.FirstOrDefault(x => string.Equals(existingDeployment.RecipeId, x.Recipe.Id));
if (state.SelectedRecommendation == null)
{
return NotFound($"Recommendation {input.NewDeploymentRecipeId} used in existing deployment {existingDeployment.RecipeId} not found.");
}
IDictionary<string, object> previousSettings;
if (existingDeployment.ResourceType == CloudApplicationResourceType.CloudFormationStack)
{
var metadata = await templateMetadataReader.LoadCloudApplicationMetadata(existingDeployment.Name);
previousSettings = metadata.Settings.Union(metadata.DeploymentBundleSettings).ToDictionary(x => x.Key, x => x.Value);
}
else
{
previousSettings = await deployedApplicationQueryer.GetPreviousSettings(existingDeployment, state.SelectedRecommendation);
}
state.SelectedRecommendation = await orchestrator.ApplyRecommendationPreviousSettings(state.SelectedRecommendation, previousSettings);
state.ApplicationDetails.Name = existingDeployment.Name;
state.ApplicationDetails.UniqueIdentifier = existingDeployment.UniqueIdentifier;
state.ApplicationDetails.RecipeId = existingDeployment.RecipeId;
state.ApplicationDetails.ResourceType = existingDeployment.ResourceType;
await orchestrator.ApplyAllReplacementTokens(state.SelectedRecommendation, existingDeployment.Name);
}
return Ok();
}
/// <summary>
/// Checks the missing System Capabilities for a given session.
/// </summary>
[HttpPost("session/<sessionId>/compatiblity")]
[SwaggerOperation(OperationId = "GetCompatibility")]
[SwaggerResponse(200, type: typeof(GetCompatibilityOutput))]
[ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound)]
[Authorize]
public async Task<IActionResult> GetCompatibility(string sessionId)
{
var state = _stateServer.Get(sessionId);
if (state == null)
{
return NotFound($"Session ID {sessionId} not found.");
}
if (state.SelectedRecommendation == null)
{
return NotFound($"A deployment target is not set for Session ID {sessionId}.");
}
var output = new GetCompatibilityOutput();
var serviceProvider = CreateSessionServiceProvider(state);
var systemCapabilityEvaluator = serviceProvider.GetRequiredService<ISystemCapabilityEvaluator>();
var capabilities = await systemCapabilityEvaluator.EvaluateSystemCapabilities(state.SelectedRecommendation);
output.Capabilities = capabilities.Select(x => new SystemCapabilitySummary(x.Name, x.Message, x.InstallationUrl));
return Ok(output);
}
/// <summary>
/// Creates the CloudFormation template that will be used by CDK for the deployment.
/// This operation returns the CloudFormation template that is created for this deployment.
/// </summary>
[HttpGet("session/<sessionId>/cftemplate")]
[SwaggerOperation(OperationId = "GenerateCloudFormationTemplate")]
[SwaggerResponse(200, type: typeof(GenerateCloudFormationTemplateOutput))]
[ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound)]
[Authorize]
public async Task<IActionResult> GenerateCloudFormationTemplate(string sessionId)
{
var state = _stateServer.Get(sessionId);
if (state == null)
{
return NotFound($"Session ID {sessionId} not found.");
}
var serviceProvider = CreateSessionServiceProvider(state);
var orchestratorSession = CreateOrchestratorSession(state);
var orchestrator = CreateOrchestrator(state, serviceProvider);
var cdkProjectHandler = CreateCdkProjectHandler(state, serviceProvider);
if (state.SelectedRecommendation == null)
throw new SelectedRecommendationIsNullException("The selected recommendation is null or invalid.");
if (!state.SelectedRecommendation.Recipe.DeploymentType.Equals(Common.Recipes.DeploymentTypes.CdkProject))
throw new SelectedRecommendationIsIncompatibleException($"We cannot generate a CloudFormation template for the selected recommendation as it is not of type '{nameof(Models.DeploymentTypes.CloudFormationStack)}'.");
var task = new DeployRecommendationTask(orchestratorSession, orchestrator, state.ApplicationDetails, state.SelectedRecommendation);
var cloudFormationTemplate = await task.GenerateCloudFormationTemplate(cdkProjectHandler);
var output = new GenerateCloudFormationTemplateOutput(cloudFormationTemplate);
return Ok(output);
}
/// <summary>
/// Begin execution of the deployment.
/// </summary>
[HttpPost("session/<sessionId>/execute")]
[SwaggerOperation(OperationId = "StartDeployment")]
[ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound)]
[ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status424FailedDependency)]
[Authorize]
public async Task<IActionResult> StartDeployment(string sessionId)
{
var state = _stateServer.Get(sessionId);
if (state == null)
{
return NotFound($"Session ID {sessionId} not found.");
}
var serviceProvider = CreateSessionServiceProvider(state);
var orchestratorSession = CreateOrchestratorSession(state);
var orchestrator = CreateOrchestrator(state, serviceProvider);
if (state.SelectedRecommendation == null)
throw new SelectedRecommendationIsNullException("The selected recommendation is null or invalid.");
var optionSettingHandler = serviceProvider.GetRequiredService<IOptionSettingHandler>();
var recipeHandler = serviceProvider.GetRequiredService<IRecipeHandler>();
var settingValidatorFailedResults = optionSettingHandler.RunOptionSettingValidators(state.SelectedRecommendation);
var recipeValidatorFailedResults = recipeHandler.RunRecipeValidators(state.SelectedRecommendation, orchestratorSession);
if (settingValidatorFailedResults.Any() || recipeValidatorFailedResults.Any())
{
var settingValidationErrorMessage = $"The deployment configuration needs to be adjusted before it can be deployed:{Environment.NewLine}";
foreach (var result in settingValidatorFailedResults)
settingValidationErrorMessage += $" - {result.ValidationFailedMessage}{Environment.NewLine}{Environment.NewLine}";
foreach (var result in recipeValidatorFailedResults)
settingValidationErrorMessage += $" - {result.ValidationFailedMessage}{Environment.NewLine}{Environment.NewLine}";
settingValidationErrorMessage += $"{Environment.NewLine}Please adjust your settings";
return Problem(settingValidationErrorMessage);
}
var systemCapabilityEvaluator = serviceProvider.GetRequiredService<ISystemCapabilityEvaluator>();
var capabilities = await systemCapabilityEvaluator.EvaluateSystemCapabilities(state.SelectedRecommendation);
var missingCapabilitiesMessage = "";
foreach (var capability in capabilities)
{
missingCapabilitiesMessage = $"{missingCapabilitiesMessage}{capability.GetMessage()}{Environment.NewLine}";
}
if (capabilities.Any())
return Problem($"Unable to start deployment due to missing system capabilities.{Environment.NewLine}{missingCapabilitiesMessage}", statusCode: Microsoft.AspNetCore.Http.StatusCodes.Status424FailedDependency);
// Because we're starting a deployment, clear the cached system capabilities checks
// in case the deployment fails and the user reruns it after modifying Docker or Node
systemCapabilityEvaluator.ClearCachedCapabilityChecks();
var task = new DeployRecommendationTask(orchestratorSession, orchestrator, state.ApplicationDetails, state.SelectedRecommendation);
state.DeploymentTask = task.Execute();
return Ok();
}
/// <summary>
/// Gets the status of the deployment.
/// </summary>
[HttpGet("session/<sessionId>/execute")]
[SwaggerOperation(OperationId = "GetDeploymentStatus")]
[SwaggerResponse(200, type: typeof(GetDeploymentStatusOutput))]
[ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound)]
[Authorize]
public IActionResult GetDeploymentStatus(string sessionId)
{
var state = _stateServer.Get(sessionId);
if (state == null)
{
return NotFound($"Session ID {sessionId} not found.");
}
var output = new GetDeploymentStatusOutput();
if (state.DeploymentTask == null)
output.Status = DeploymentStatus.NotStarted;
else if (state.DeploymentTask.IsCompleted && state.DeploymentTask.Status == TaskStatus.RanToCompletion)
output.Status = DeploymentStatus.Success;
else if (state.DeploymentTask.IsCompleted && state.DeploymentTask.Status == TaskStatus.Faulted)
{
output.Status = DeploymentStatus.Error;
if (state.DeploymentTask.Exception != null)
{
var innerException = state.DeploymentTask.Exception.InnerException;
var message = innerException.GetTruncatedErrorMessage();
if (innerException is DeployToolException deployToolException)
{
output.Exception = new DeployToolExceptionSummary(deployToolException.ErrorCode.ToString(), message, deployToolException.ProcessExitCode);
}
else
{
output.Exception = new DeployToolExceptionSummary(DeployToolErrorCode.UnexpectedError.ToString(), message);
}
}
}
else
output.Status = DeploymentStatus.Executing;
return Ok(output);
}
/// <summary>
/// Gets information about the displayed resources defined in the recipe definition.
/// </summary>
[HttpGet("session/<sessionId>/details")]
[SwaggerOperation(OperationId = "GetDeploymentDetails")]
[SwaggerResponse(200, type: typeof(GetDeploymentDetailsOutput))]
[ProducesResponseType(Microsoft.AspNetCore.Http.StatusCodes.Status404NotFound)]
[Authorize]
public async Task<IActionResult> GetDeploymentDetails(string sessionId)
{
var state = _stateServer.Get(sessionId);
if (state == null)
{
return NotFound($"Session ID {sessionId} not found.");
}
var serviceProvider = CreateSessionServiceProvider(state);
var displayedResourcesHandler = serviceProvider.GetRequiredService<IDisplayedResourcesHandler>();
if (state.SelectedRecommendation == null)
{
return NotFound($"A deployment target is not set for Session ID {sessionId}.");
}
var displayedResources = await displayedResourcesHandler.GetDeploymentOutputs(state.ApplicationDetails, state.SelectedRecommendation);
var output = new GetDeploymentDetailsOutput(
state.ApplicationDetails.Name,
displayedResources
.Select(x => new DisplayedResourceSummary(x.Id, x.Description, x.Type, x.Data))
.ToList());
return Ok(output);
}
private IServiceProvider CreateSessionServiceProvider(SessionState state)
{
var awsCredentials = HttpContext.User.ToAWSCredentials();
if(awsCredentials == null)
{
throw new FailedToRetrieveAWSCredentialsException("AWS credentials are missing for the current session.");
}
var interactiveServices = new SessionOrchestratorInteractiveService(state.SessionId, _hubContext);
var services = new ServiceCollection();
services.AddSingleton<IOrchestratorInteractiveService>(interactiveServices);
services.AddSingleton<ICommandLineWrapper>(services =>
{
var wrapper = new CommandLineWrapper(interactiveServices, true);
wrapper.RegisterAWSContext(awsCredentials, state.AWSRegion);
return wrapper;
});
if (state.AWSResourceQueryService == null)
{
services.AddSingleton<IAWSResourceQueryer, SessionAWSResourceQuery>();
}
else
{
services.AddSingleton<IAWSResourceQueryer>(state.AWSResourceQueryService);
}
if (state.SystemCapabilityEvaluator == null)
{
services.AddSingleton<ISystemCapabilityEvaluator, SystemCapabilityEvaluator>();
}
else
{
services.AddSingleton<ISystemCapabilityEvaluator>(state.SystemCapabilityEvaluator);
}
services.AddCustomServices();
var serviceProvider = services.BuildServiceProvider();
var awsClientFactory = serviceProvider.GetRequiredService<IAWSClientFactory>();
awsClientFactory.ConfigureAWSOptions(awsOptions =>
{
awsOptions.Credentials = awsCredentials;
awsOptions.Region = RegionEndpoint.GetBySystemName(state.AWSRegion);
});
// Cache the SessionAWSResourceQuery and SystemCapabilityEvaluator with the session state
// so they can be reused in future ServerMode API calls with the same session id. This avoids reloading
// existing resources from AWS and running the Docker/Node checks when they're not expected to change.
state.AWSResourceQueryService = serviceProvider.GetRequiredService<IAWSResourceQueryer>() as SessionAWSResourceQuery;
state.SystemCapabilityEvaluator = serviceProvider.GetRequiredService<ISystemCapabilityEvaluator>() as SystemCapabilityEvaluator;
return serviceProvider;
}
private OrchestratorSession CreateOrchestratorSession(SessionState state, AWSCredentials? awsCredentials = null)
{
return new OrchestratorSession(
state.ProjectDefinition,
awsCredentials ?? HttpContext.User.ToAWSCredentials() ??
throw new FailedToRetrieveAWSCredentialsException("The tool was not able to retrieve the AWS Credentials."),
state.AWSRegion,
state.AWSAccountId);
}
private CdkProjectHandler CreateCdkProjectHandler(SessionState state, IServiceProvider? serviceProvider = null)
{
if (serviceProvider == null)
{
serviceProvider = CreateSessionServiceProvider(state);
}
return new CdkProjectHandler(
serviceProvider.GetRequiredService<IOrchestratorInteractiveService>(),
serviceProvider.GetRequiredService<ICommandLineWrapper>(),
serviceProvider.GetRequiredService<IAWSResourceQueryer>(),
serviceProvider.GetRequiredService<ICdkAppSettingsSerializer>(),
serviceProvider.GetRequiredService<IFileManager>(),
serviceProvider.GetRequiredService<IDirectoryManager>(),
serviceProvider.GetRequiredService<IOptionSettingHandler>(),
serviceProvider.GetRequiredService<IDeployToolWorkspaceMetadata>(),
serviceProvider.GetRequiredService<ICloudFormationTemplateReader>()
);
}
private Orchestrator CreateOrchestrator(SessionState state, IServiceProvider? serviceProvider = null, AWSCredentials? awsCredentials = null)
{
if(serviceProvider == null)
{
serviceProvider = CreateSessionServiceProvider(state);
}
var session = CreateOrchestratorSession(state, awsCredentials);
return new Orchestrator(
session,
serviceProvider.GetRequiredService<IOrchestratorInteractiveService>(),
serviceProvider.GetRequiredService<ICdkProjectHandler>(),
serviceProvider.GetRequiredService<ICDKManager>(),
serviceProvider.GetRequiredService<ICDKVersionDetector>(),
serviceProvider.GetRequiredService<IAWSResourceQueryer>(),
serviceProvider.GetRequiredService<IDeploymentBundleHandler>(),
serviceProvider.GetRequiredService<ILocalUserSettingsEngine>(),
new DockerEngine(
session.ProjectDefinition,
serviceProvider.GetRequiredService<IFileManager>(),
serviceProvider.GetRequiredService<IDirectoryManager>()),
serviceProvider.GetRequiredService<IRecipeHandler>(),
serviceProvider.GetRequiredService<IFileManager>(),
serviceProvider.GetRequiredService<IDirectoryManager>(),
serviceProvider.GetRequiredService<IAWSServiceHandler>(),
serviceProvider.GetRequiredService<IOptionSettingHandler>(),
serviceProvider.GetRequiredService<IDeployToolWorkspaceMetadata>(),
serviceProvider.GetRequiredService<ISystemCapabilityEvaluator>()
);
}
}
}