Beispiel #1
0
        public void GetLatestTagMatchingPolicy_PositiveTest()
        {
            // setup
            var x = new DeploymentWorkflowService(
                GetLogger <DeploymentWorkflowService>(),
                MockOf <IContainerImageMetadataService>(),
                MockOf <IApplicationService>(),
                Mock.Of <IApplicationImageInstanceService>(),
                MockOf <IDeploymentService>(),
                MockOf <IDeploymentQueueService>(),
                Mock.Of <IGitHubClient>()
                );

            var imagePolicy = new GlobImageUpdatePolicy("develop-*");

            var expectedResult = new ContainerImage("testapp", "develop-256", DateTimeOffset.Now);
            var images         = new[]
            {
                new ContainerImage("testapp", "master-123", DateTimeOffset.Now),
                new ContainerImage("testapp", "develop-123", DateTimeOffset.Now.AddDays(-1)),
                expectedResult,
            };

            // test
            var actualResult = x.GetLatestTagMatchingPolicy(images, imagePolicy);

            // verify
            actualResult.Should().BeEquivalentTo(expectedResult);
        }
        internal DotnetStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            var vpc = new Vpc(this, "MyVpc", new VpcProps
            {
                MaxAzs = 3 // Max zones
            });

            var cluster = new Cluster(this, "MyCluster", new ClusterProps
            {
                Vpc = vpc
            });

            var serviceProps = new ApplicationLoadBalancedFargateServiceProps()
            {
                Cluster          = cluster, // Required
                DesiredCount     = 5,       // Default is 1
                TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions
                {
                    Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample") // PHP Sample :-( my bad => https://hub.docker.com/r/amazon/amazon-ecs-sample
                },
                MemoryLimitMiB     = 2048,                                          // Default is 256
                PublicLoadBalancer = true,                                          // Default is false
            };

            // Create Loadbalancer fargate and make it public

            new ApplicationLoadBalancedFargateService(this, "MyFargateService",
                                                      serviceProps);
        }
Beispiel #3
0
        private void ConfigureTaskDefinition(IRecipeProps <Configuration> props)
        {
            var settings = props.Settings;

            AppTaskDefinition = new FargateTaskDefinition(this, nameof(AppTaskDefinition), InvokeCustomizeCDKPropsEvent(nameof(AppTaskDefinition), this, new FargateTaskDefinitionProps
            {
                TaskRole       = AppIAMTaskRole,
                Cpu            = settings.TaskCpu,
                MemoryLimitMiB = settings.TaskMemory
            }));

            AppLogging = new AwsLogDriver(InvokeCustomizeCDKPropsEvent(nameof(AppLogging), this, new AwsLogDriverProps
            {
                StreamPrefix = props.StackName
            }));

            if (string.IsNullOrEmpty(props.ECRRepositoryName))
            {
                throw new InvalidOrMissingConfigurationException("The provided ECR Repository Name is null or empty.");
            }

            var ecrRepository = Repository.FromRepositoryName(this, "ECRRepository", props.ECRRepositoryName);

            AppContainerDefinition = new ContainerDefinitionOptions
            {
                Image   = ContainerImage.FromEcrRepository(ecrRepository, props.ECRImageTag),
                Logging = AppLogging
            };

            AppTaskDefinition.AddContainer(nameof(AppContainerDefinition), InvokeCustomizeCDKPropsEvent(nameof(AppContainerDefinition), this, AppContainerDefinition));
        }
        public async Task <bool> DeleteImage(ContainerImage image, CancellationToken cancellationToken)
        {
            //Check if valid
            var imageExists = await _dbContext.Images.AnyAsync(c => c.Id == image.Id, cancellationToken);

            if (!imageExists)
            {
                _logger.LogError("Unable to delete image: No such image exists {@Id}", image.Id);
                return(false);
            }

            //delete
            var result = _dbContext.Images.Remove(image);
            await _dbContext.SaveChangesAsync(cancellationToken);


            //return result
            if (result != null)
            {
                _logger.LogInformation("Deleted image with id {@Id}", image.Id);
                return(true);
            }

            _logger.LogInformation("Unable to delete image with id {@Id}", image.Id);
            return(true);
        }
Beispiel #5
0
        public FargateStack(Construct parent, string id, IStackProps props) : base(parent, id, props)
        {
            var vpc = new VpcNetwork(this, "MyVpc", new VpcNetworkProps()
            {
                MaxAZs = 2
            });
            var cluster = new Cluster(this, "Cluster", new ClusterProps()
            {
                Vpc = VpcNetwork.Import(this, "vpc2", vpc.Export())
            });
            var env = new Dictionary <string, string>();

            // Instantiate Fargate Service with just cluster and image
            var fargateService = new LoadBalancedFargateService(this, "FargateService",
                                                                new LoadBalancedFargateServiceProps()
            {
                Cluster = cluster,
                //Image = ContainerImage.FromRegistry("amazon/amazon-ecs-sample", null),
                Image              = ContainerImage.FromRegistry("karthequian/helloworld", null),
                Environment        = env,
                PublicLoadBalancer = true,
                CreateLogs         = true
            });

            // Output the DNS where you can access your service
            new CfnOutput(this, "LoadBalancerDNS", new CfnOutputProps()
            {
                Value = fargateService.LoadBalancer.DnsName
            });
        }
        public async Task <ContainerImage> EditImage(ContainerImage image, CancellationToken cancellationToken)
        {
            //Check if id exists
            var imageExists = await _dbContext.Images.AnyAsync(c => c.Id == image.Id, cancellationToken);

            //check is valid
            var userExists = await _dbContext.Users.AnyAsync(c => c.Id == image.Owner.Id, cancellationToken);

            if (!imageExists || !userExists)
            {
                _logger.LogError("Unable to Edit Image; user {user}; image {image}", userExists, imageExists);
                return(null);
            }


            //update
            var newImage = _dbContext.Images.Update(image);
            await _dbContext.SaveChangesAsync(cancellationToken);


            //return new ContainerImage
            if (newImage?.Entity != null)
            {
                _logger.LogInformation("Edited image with id {Id}", image.Id);
                return(newImage.Entity);
            }

            _logger.LogError("Unable to edit image {@Image}", image);
            return(null);
        }
        public static FargateTaskDefinition CreateTaskDefinition1(Construct scope)
        {
            var repo = CreateDockerContainerImage(scope);

            var taskDefinition = new FargateTaskDefinition(scope, "DownloadAccuzipFileTaskDefinition", new FargateTaskDefinitionProps()
            {
                MemoryLimitMiB = 2048,
            });

            taskDefinition.AddContainer(Config.ECR_REPO_NAME, new ContainerDefinitionProps()
            {
                MemoryLimitMiB = 2048,
                Image          = ContainerImage.FromEcrRepository(repo),
                Logging        = new AwsLogDriver(new AwsLogDriverProps()
                {
                    StreamPrefix = "dmappresort"
                })
            });



            var policyStatement = new Amazon.CDK.AWS.IAM.PolicyStatement();

            policyStatement.AddAllResources();
            policyStatement.AddActions(new string[] { "s3:*" });
            taskDefinition.AddToTaskRolePolicy(policyStatement);


            return(taskDefinition);
        }
Beispiel #8
0
        internal CdkStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            var vpc = new Vpc(this, "MyVpc", new VpcProps
            {
                MaxAzs = 2 // Default is all AZs in region
            });

            var cluster = new Cluster(this, "MyCluster", new ClusterProps
            {
                Vpc = vpc
            });

            // Create a load-balanced Fargate service and make it public
            new ApplicationLoadBalancedFargateService(this, "MyFargateService",
                                                      new ApplicationLoadBalancedFargateServiceProps
            {
                Cluster          = cluster,     // Required
                DesiredCount     = 2,           // Default is 1
                TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions
                {
                    Image = ContainerImage.FromAsset(".")
                },
                MemoryLimitMiB     = 1024,      // Default is 256
                PublicLoadBalancer = true       // Default is false
            }
                                                      );
        }
        public async Task <bool> CreateImage(ContainerImage image, CancellationToken cancellationToken)
        {
            //check is valid TODO:Add fluent validation
            var userExists = await _dbContext.Users.AnyAsync(c => c.Id == image.Owner.Id, cancellationToken);

            if (!userExists)
            {
                _logger.LogError("Unable to create Image: No owner exists with the id {@Id}", image.Id);
                return(false);
            }

            //Try create
            var result = await _dbContext.Images.AddAsync(image, cancellationToken);

            await _dbContext.SaveChangesAsync(cancellationToken);

            //report

            if (result != null)
            {
                _logger.LogInformation("Created Image with Id {@Id}", image.Id);
                return(true);
            }

            _logger.LogError("Unable to create image {@Image}", image);
            return(false);
        }
Beispiel #10
0
        public void ComparerTest_Glob_MoreRecentImageVsCurrentImage()
        {
            // setup
            var x = new DeploymentWorkflowService(
                GetLogger <DeploymentWorkflowService>(),
                MockOf <IContainerImageMetadataService>(),
                MockOf <IApplicationService>(),
                Mock.Of <IApplicationImageInstanceService>(),
                MockOf <IDeploymentService>(),
                MockOf <IDeploymentQueueService>(),
                Mock.Of <IGitHubClient>()

                );

            var currentImage   = new ContainerImage("testapp", "develop-123", DateTimeOffset.Now.AddDays(-1));
            var expectedResult = new ContainerImage("testapp", "develop-256", DateTimeOffset.Now);

            var imagePolicy = new GlobImageUpdatePolicy("develop-*");

            var comparer = x.GetContainerImageComparer(imagePolicy);

            // test
            var compare = comparer.Compare(currentImage, expectedResult);

            // verify
            compare.Should().BeLessThan(0);
        }
 private Task ProcessImageScanRequest(ImageScanRequestMessage msg)
 {
     return(this.scanner.Scan(new ScanRequest
     {
         Image = ContainerImage.FromFullName(msg.Payload.ImageFullName),
         ScanId = msg.Payload.ImageScanId,
     }));
 }
        public Task AddContainerImage(ContainerImage containerImage)
        {
            var bag = Store.GetOrAdd(containerImage.Repository, registry => new ConcurrentBag <ContainerImage>());

            bag.Add(containerImage);

            return(Task.CompletedTask);
        }
Beispiel #13
0
 public PingPongServices(Construct scope, string id, PingPongServicesProps props) : base(scope, id)
 {
     var pingImage  = ContainerImage.FromAsset($"ping-service");
     var pongImage  = ContainerImage.FromAsset($"pong-service");
     var envoyImage = ContainerImage.FromRegistry($"840364872350.dkr.ecr.{props.Env.Region}.amazonaws.com/aws-appmesh-envoy:v1.12.3.0-prod");
     // TODO: Maybe just create this role here as part of the stack. I think it gets created with the ECS cluster automatically.
     var taskExecRole = Role.FromRoleArn(this, "task-execution-role", $"arn:aws:iam::{props.Env.Account}:role/ecsTaskExecutionRole");
     var pingService  = new PingPongServiceConstruct(this, $"{id}_ping-master", new PingPongServiceConstructProps()
     {
         ServiceContainerImage = pingImage,
         EnvoyImage            = envoyImage,
         TaskExecutionRole     = taskExecRole,
         ServiceName           = "ping",
         Branch            = "master",
         Mesh              = props.Mesh,
         CloudmapNamespace = props.CloudmapNamespace,
         VirturalNodeName  = $"ping-service-master-node",
         Cluster           = props.Cluster,
         Vpc           = props.Vpc,
         Backends      = new VirtualService[] { props.PongVirtualService },
         VirtualRouter = props.PingVirtualRouter,
         RoutePriority = 0
     });
     var pongMasterService = new PingPongServiceConstruct(this, $"{id}_pong-master", new PingPongServiceConstructProps()
     {
         ServiceContainerImage = pongImage,
         EnvoyImage            = envoyImage,
         TaskExecutionRole     = taskExecRole,
         ServiceName           = "pong",
         Branch            = "master",
         Mesh              = props.Mesh,
         CloudmapNamespace = props.CloudmapNamespace,
         VirturalNodeName  = $"pong-service-master-node",
         Cluster           = props.Cluster,
         Vpc           = props.Vpc,
         Backends      = new VirtualService[] { },
         VirtualRouter = props.PongVirtualRouter,
         RoutePriority = 2
     });
     var pongBranchService = new PingPongServiceConstruct(this, $"{id}_pong-testbranch", new PingPongServiceConstructProps()
     {
         ServiceContainerImage = pongImage,
         EnvoyImage            = envoyImage,
         TaskExecutionRole     = taskExecRole,
         ServiceName           = "pong",
         Branch            = "testbranch",
         Mesh              = props.Mesh,
         CloudmapNamespace = props.CloudmapNamespace,
         VirturalNodeName  = $"pong-service-testbranch-node",
         Cluster           = props.Cluster,
         Vpc           = props.Vpc,
         Backends      = new VirtualService[] { },
         VirtualRouter = props.PongVirtualRouter,
         RoutePriority = 1
     });
 }
Beispiel #14
0
        public FargateStack(Construct scope, string id, FargateStackProps props = null) : base(scope, id, props)
        {
            var cluster = new Cluster(this, "WhatDayOfWeekCluster", new ClusterProps
            {
                Vpc = props.Vpc
            });

            var logging = new AwsLogDriver(new AwsLogDriverProps()
            {
                StreamPrefix = "WhatDayOfWeek",
                LogRetention = Amazon.CDK.AWS.Logs.RetentionDays.ONE_DAY
            });

            //container

            /*
             * var repo = Repository.FromRepositoryName(this, "myrepo","MyRepositoryName");
             *
             * var containerOptions = new ContainerDefinitionOptions
             * {
             *   Image =  ContainerImage.FromEcrRepository(repo)
             * };
             */
            // to build the container image from the app in the local folder, replace lines 29-35 with


            //var rootDirectory = Directory.GetCurrentDirectory();
            //var path = Path.GetFullPath(Path.Combine(rootDirectory, @"App/WhatDayOfWeek"));

            var containerOptions = new ContainerDefinitionOptions
            {
                Image   = ContainerImage.FromAsset(@"App/WhatDayOfWeek"),
                Logging = logging
            };

            var portMapping = new PortMapping()
            {
                ContainerPort = 80,
                HostPort      = 80
            };

            var taskDef = new FargateTaskDefinition(this, "WhatDayOfWeekTaskDefinition");

            taskDef.AddContainer("WhatDayOfWeekContainer", containerOptions).AddPortMappings(portMapping);

            var serviceProps = new ApplicationLoadBalancedFargateServiceProps()
            {
                ServiceName    = "WhatDayOfWeekService",
                MemoryLimitMiB = 512,
                Cpu            = 256,
                TaskDefinition = taskDef,
                Cluster        = cluster
            };

            ApplicationLoadBalancedFargateService service = new ApplicationLoadBalancedFargateService(this, "WhatDayOfWeekService", serviceProps);
        }
        internal CdkFargateStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            var vpc = new Vpc(this, "SatellytesVpc", new VpcProps
            {
                Cidr   = "10.0.0.0/16",
                MaxAzs = 1,
                SubnetConfiguration = new[] {
                    new SubnetConfiguration()
                    {
                        Name       = "Satellytes/public",
                        SubnetType = SubnetType.PUBLIC,
                    }
                },
            });

            var cluster = new Cluster(this, "SatellytesCluster", new ClusterProps
            {
                Vpc = vpc,
            });

            var taskDefinition = new TaskDefinition(this, "SatellytesWebTask", new TaskDefinitionProps {
                TaskRole = Role.FromRoleArn(this, "taskRole", "arn:aws:iam::576853867587:role/ecsTaskExecutionRole", new FromRoleArnOptions()
                {
                    Mutable = false
                }),
                ExecutionRole = Role.FromRoleArn(this, "taskExecutionRole", "arn:aws:iam::576853867587:role/ecsTaskExecutionRole", new FromRoleArnOptions()
                {
                    Mutable = false
                }),
                Compatibility = Compatibility.FARGATE,
                Cpu           = "256",
                MemoryMiB     = "512",
            });

            var inboundSecurityGrp = new SecurityGroup(this, "satellytesSecurityGrpInboundInet", new SecurityGroupProps {
                Vpc = vpc
            });

            inboundSecurityGrp.AddIngressRule(Peer.AnyIpv4(), Port.Tcp(8080), "inbound http");



            taskDefinition.AddContainer("satellytesWebImage", new ContainerDefinitionProps {
                Image = ContainerImage.FromEcrRepository(Repository.FromRepositoryName(this, "repo", "satellytes-website/backend"), "1cfb651f73fcd20895fc44c06f7bb180ca0e8322"),
            });

            new FargateService(this, "SatellytesWebService", new FargateServiceProps {
                Cluster        = cluster,
                TaskDefinition = taskDefinition,
                VpcSubnets     = new SubnetSelection {
                    SubnetType = SubnetType.PUBLIC
                },
                AssignPublicIp = true,
            });
        }
        private void CreateContainerDefinition(EcsTaskDefinitionOptions definitionOptions, TaskDefinition taskDefinition)
        {
            foreach (var containerDef in definitionOptions.Containers)
            {
                var ecr = StackResources.EcrRepositories.FirstOrDefault(ecr => ecr.Key == containerDef.RepositoryId);

                if (ecr.Key == null || ecr.Value == null)
                {
                    throw new ArgumentException("Please add a ECR definition option properly set up on your json configuration. No task definition could not be added.");
                }

                var portMapping = new List <PortMapping>();
                if (containerDef.TCPPortMapping?.Any() == true)
                {
                    foreach (var ports in containerDef.TCPPortMapping)
                    {
                        portMapping.Add(new PortMapping
                        {
                            ContainerPort = ports.ContainerPort,
                            HostPort      = ports.HostPort,
                            Protocol      = Amazon.CDK.AWS.ECS.Protocol.TCP
                        });
                    }
                }

                var containerDefinitionProps = new ContainerDefinitionProps
                {
                    TaskDefinition = taskDefinition,
                    Image          = ContainerImage.FromEcrRepository(ecr.Value, containerDef.ImageTag),
                    MemoryLimitMiB = containerDef.MemoryLimitMiB,
                    Cpu            = containerDef.CpuUnits,
                    StartTimeout   = Duration.Minutes(containerDef.StartTimeOutMinutes),
                    PortMappings   = portMapping.ToArray(),
                    Environment    = containerDef.EnvironmentVariables,
                    DnsServers     = containerDef.DnsServers?.ToArray()
                };

                var container = AwsCdkHandler.CreateContainerDefinitionByProps(containerDef.Id, containerDefinitionProps);

                if (definitionOptions.MountPoints?.Any() == true)
                {
                    var mountPoints = new List <MountPoint>();
                    foreach (var mountPointOption in definitionOptions.MountPoints)
                    {
                        mountPoints.Add(new MountPoint
                        {
                            SourceVolume  = mountPointOption.SourceVolume,
                            ContainerPath = mountPointOption.ContainerPath
                        });
                    }
                    container.AddMountPoints(mountPoints.ToArray());
                }
            }
        }
Beispiel #17
0
        internal Stack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            //setup the image
            var asset = new DockerImageAsset(this, $"{Config.AppName}Image", new DockerImageAssetProps {
                Directory = Path.Combine(System.Environment.CurrentDirectory, "api"),
            });

            //Create the Fargate service
            var vpc = Vpc.FromLookup(
                this, "sandbox", new VpcLookupOptions
            {
                VpcName = "sandbox_vpc"
            }
                );

            var cluster = new Cluster(this, $"{Config.AppName}Cluster", new ClusterProps
            {
                Vpc = vpc
            });

            var applicationDomain = $"{Config.ApplicationSubdomain}.{Config.DomainName}";
            var hostedZone        = HostedZone.FromLookup(
                this, "HostedZone", new HostedZoneProviderProps
            {
                DomainName  = $"{Config.DomainName}.",
                PrivateZone = false
            }
                );

            // Create a load-balanced Fargate service and make it public
            var fargateService = new ApplicationLoadBalancedFargateService(this, $"{Config.AppName}Service",
                                                                           new ApplicationLoadBalancedFargateServiceProps
            {
                Cluster          = cluster,     // Required
                DesiredCount     = 1,           // Default is 1
                TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions
                {
                    Image = ContainerImage.FromDockerImageAsset(asset)
                },
                MemoryLimitMiB     = 1024,      // Default is 256
                PublicLoadBalancer = true,      // Default is false
                DomainName         = applicationDomain,
                DomainZone         = hostedZone,
            }
                                                                           );

            new CfnOutput(
                this, "Route53Url", new CfnOutputProps
            {
                Value       = applicationDomain,
                Description = "Nice Route53 Url"
            }
                );
        }
Beispiel #18
0
        public async Task AddOrUpdate(ContainerImage containerImage)
        {
            if (containerImage == null)
            {
                throw new ArgumentNullException(nameof(containerImage));
            }

            await AddOrUpdateWorker(containerImage);

            await _unitOfWork.Commit();
        }
        internal MyDotNetCoreServerlessWebAppEcsFargateCdkAppStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            var         imageTagParameter = this.Node.TryGetContext("ImageTag");
            string      imageTag          = imageTagParameter.ToString() ?? "latest";
            IRepository ecrRepository     = Repository.FromRepositoryArn(this, "MyDotNetCorServerlessWebAppServiceContainerRepository", "arn:aws:ecr:eu-west-1:098208531922:repository/mydotnetcorewebapp");

            var loadBalancedFargateService = new ApplicationLoadBalancedFargateService(this, "MyDotNetCorServerlessWebAppService", new ApplicationLoadBalancedFargateServiceProps()
            {
                AssignPublicIp   = true,
                TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions()
                {
                    Image = ContainerImage.FromEcrRepository(ecrRepository, imageTag),
                }
            });;
        }
        public async Task <ActionResult> Post([FromBody] NewDeploymentDto newDeploymentDto)
        {
            var containerImage = new ContainerImage(
                newDeploymentDto.Repository,
                newDeploymentDto.Tag
                );

            var createdDeployments = (await _deploymentWorkflowService.StartImageDeployment(containerImage, false)).ToList();

            if (createdDeployments.Any())
            {
                return(StatusCode(StatusCodes.Status201Created, createdDeployments.Select(ConvertFromModel).ToList()));
            }

            return(Ok());
        }
Beispiel #21
0
        /// <summary>
        ///     Handles the logic required to deploy a new container image to one or more applications.
        ///     <remarks>
        ///         A new container image can be either detected by the repository polling jobs, OR through manual
        ///         submission from the Administrative REST API.
        ///     </remarks>
        /// </summary>
        /// <param name="latestImage"></param>
        /// <param name="isContainerRepositoryUpdate"></param>
        /// <returns>List of deployments that were created.</returns>
        public Task <IEnumerable <Deployment> > StartImageDeployment(
            ContainerImage latestImage,
            bool isContainerRepositoryUpdate = false
            )
        {
            var allApplicationsTrackingThisRepository = GetAllApplicationsTrackingThisRepository(latestImage.Repository);

            return(InternalStartImageDeployment(
                       allApplicationsTrackingThisRepository,
                       latestImage.Repository,
                       new List <ContainerImage> {
                latestImage
            },
                       isContainerRepositoryUpdate
                       ));
        }
        private ApplicationLoadBalancedFargateService CreateEcsService(
            Cluster ecsCluster,
            Secret dbPasswordSecret,
            DatabaseConstructFactory dbConstructFactory,
            DatabaseConstructOutput dbConstructOutput
            )
        {
            var imageRepository = Repository.FromRepositoryName(this, "ExistingEcrRepository", settings.DockerImageRepository);

            var ecsService = new ApplicationLoadBalancedFargateService(this, $"{settings.ScopeName}FargateService",
                                                                       new ApplicationLoadBalancedFargateServiceProps
            {
                Cluster            = ecsCluster,
                DesiredCount       = settings.DesiredComputeReplicaCount,
                Cpu                = settings.CpuMillicores,
                MemoryLimitMiB     = settings.MemoryMiB,
                PublicLoadBalancer = settings.PublicLoadBalancer,
                LoadBalancer       = new ApplicationLoadBalancer(this, $"{settings.ScopeName}-ALB", new ApplicationLoadBalancerProps {
                    LoadBalancerName = "unicorn-store",
                    Vpc                = ecsCluster.Vpc,
                    InternetFacing     = true,
                    DeletionProtection = false,
                }),
                TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions
                {
                    Image       = ContainerImage.FromEcrRepository(imageRepository, settings.ImageTag),
                    Environment = new Dictionary <string, string>()
                    {
                        { "ASPNETCORE_ENVIRONMENT", settings.DotNetEnvironment ?? "Production" },
                        { "DefaultAdminUsername", settings.DefaultSiteAdminUsername },
                        { $"UnicornDbConnectionStringBuilder__{dbConstructFactory.DbConnStrBuilderServerPropName}",
                          dbConstructOutput.EndpointAddress },
                        { $"UnicornDbConnectionStringBuilder__Port", dbConstructOutput.Port },
                        { $"UnicornDbConnectionStringBuilder__{dbConstructFactory.DBConnStrBuilderUserPropName}",
                          settings.DbUsername },
                    },
                    Secrets = new Dictionary <string, Secret>
                    {
                        { "DefaultAdminPassword", Helpers.CreateAutoGenPasswordSecretDef($"{settings.ScopeName}DefaultSiteAdminPassword").CreateSecret(this) },
                        { $"UnicornDbConnectionStringBuilder__{dbConstructFactory.DBConnStrBuilderPasswordPropName}", dbPasswordSecret }
                    }
                },
            }
                                                                       );

            return(ecsService);
        }
Beispiel #23
0
        private async Task AddOrUpdateWorker(ContainerImage containerImage)
        {
            var normalizedContainerRepository = NormalizeContainerRepository(containerImage.Repository);
            var repository = await GetRepositoryDao(normalizedContainerRepository);

            var metadata = await _containerImageMetadata
                           .Query()
                           .FirstOrDefaultAsync(
                x =>
                x.RepositoryId == repository.Id &&
                x.Hash == containerImage.Hash
                )
                           ??
                           await _containerImageMetadata.Add(new ContainerImageMetadata()
            {
                Hash            = containerImage.Hash,
                Id              = Guid.NewGuid(),
                Repository      = repository,
                CreatedDateTime = containerImage.CreationDateTime.UtcDateTime
            });

            var tag = await _containerImageTagRepository.Query()
                      .FirstOrDefaultAsync(x => x.RepositoryId == repository.Id && x.Tag == containerImage.Tag);

            if (tag == null)
            {
                // create a new tag entry
                tag = await _containerImageTagRepository.Add(new ContainerImageTag()
                {
                    Id         = Guid.NewGuid(),
                    Metadata   = metadata,
                    Repository = repository,
                    Tag        = containerImage.Tag
                });
            }
            else
            {
                // check if we are updating the tag
                if (tag.MetadataId != metadata.Id)
                {
                    // tag had it's hash changed
                    tag.Metadata = metadata;
                }
            }

            await _unitOfWork.Commit();
        }
Beispiel #24
0
        public ContainersStack(Construct parent, string id, IStackProps props) : base(parent, id, props)
        {
            var vpc = Vpc.FromLookup(this, id = "DefaultVpc", new VpcLookupOptions
            {
                IsDefault = true
            });

            if (vpc == null)
            {
                throw new System.NullReferenceException($"Unable to determine default VPC in region {this.Region}");
            }

            var cluster = new Cluster(this, "Cluster", new ClusterProps
            {
                Vpc = vpc
            });

            var taskDef = new FargateTaskDefinition(this, "FargateTaskDefinition");

            var currentDir = Directory.GetCurrentDirectory();
            var path       = Path.GetFullPath(Path.Combine(currentDir, @"dotnetapp/"));

            var containerOptions = new ContainerDefinitionOptions
            {
                Image = ContainerImage.FromAsset("dotnetapp")
            };

            var portMapping = new PortMapping()
            {
                ContainerPort = 80,
                HostPort      = 80
            };

            taskDef.AddContainer("Container", containerOptions).AddPortMappings(portMapping);

            var serviceProps = new ApplicationLoadBalancedFargateServiceProps()
            {
                MemoryLimitMiB = 512,
                Cpu            = 256,
                TaskDefinition = taskDef
            };

            ApplicationLoadBalancedFargateService service
                = new ApplicationLoadBalancedFargateService(this, "DotnetFargateApp", serviceProps);
        }
Beispiel #25
0
        public Task <IEnumerable <Deployment> > StartImageDeployment(
            string applicationName,
            ContainerImage containerImage,
            bool isContainerRepositoryUpdate = false)
        {
            var application  = _applicationService.GetApplication(applicationName);
            var targetImages = application.Images
                               .Where(image => image.Repository.Equals(containerImage.Repository))
                               .Select(image => (image, application))
                               .ToList();

            return(InternalStartImageDeployment(
                       targetImages,
                       containerImage.Repository,
                       new List <ContainerImage> {
                containerImage
            },
                       isContainerRepositoryUpdate
                       ));
        }
Beispiel #26
0
        public async Task <ObjectResult> ScanImages([FromRoute] string imageTag)
        {
            try
            {
                var unescapedTag = HttpUtility.UrlDecode(imageTag);
                var image        = ContainerImage.FromFullName(unescapedTag);
                var result       = await this.scanner.Scan(new ScanRequest
                {
                    Image  = image,
                    ScanId = Guid.NewGuid().ToString(),
                });

                return(this.StatusCode(201, result));
            }
            catch (Exception ex)
            {
                Logger.Warning(ex, "Failed to scan the image {Image}", imageTag);
                return(this.StatusCode(500, $"Failed to scan an image because of exception: {ex.Message}"));
            }
        }
Beispiel #27
0
        internal FargateStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
        {
            // Create VPC
            var vpc = new Vpc(this, "SampleVpc", new VpcProps
            {
                MaxAzs = 2
            });

            // Create ECS cluster
            var cluster = new Cluster(this, "SampleCluster", new ClusterProps
            {
                Vpc = vpc
            });

            var taskDef = new FargateTaskDefinition(this, "FargateTaskDefinition");

            // Build container image from local assets
            var containerOptions = new ContainerDefinitionOptions
            {
                Image = ContainerImage.FromAsset("webapp")
            };

            var portMapping = new PortMapping()
            {
                ContainerPort = 80,
                HostPort      = 80
            };

            taskDef
            .AddContainer("Container", containerOptions)
            .AddPortMappings(portMapping);

            // Create Fargate Service behind Application Load Balancer
            new ApplicationLoadBalancedFargateService(this, "DotnetFargateSampleApp", new ApplicationLoadBalancedFargateServiceProps()
            {
                Cluster        = cluster,
                MemoryLimitMiB = 512,
                Cpu            = 256,
                TaskDefinition = taskDef
            });
        }
Beispiel #28
0
        public override int GetHashCode()
        {
            int hash = 1;

            if (Name.Length != 0)
            {
                hash ^= Name.GetHashCode();
            }
            if (ContainerImage.Length != 0)
            {
                hash ^= ContainerImage.GetHashCode();
            }
            if (Shell.Length != 0)
            {
                hash ^= Shell.GetHashCode();
            }
            if (WorkingDirectory.Length != 0)
            {
                hash ^= WorkingDirectory.GetHashCode();
            }
            hash ^= commands_.GetHashCode();
            if (When.Length != 0)
            {
                hash ^= When.GetHashCode();
            }
            hash ^= EnvVars.GetHashCode();
            if (AutoInjected != false)
            {
                hash ^= AutoInjected.GetHashCode();
            }
            if (Retries != 0L)
            {
                hash ^= Retries.GetHashCode();
            }
            hash ^= CustomProperties.GetHashCode();
            if (_unknownFields != null)
            {
                hash ^= _unknownFields.GetHashCode();
            }
            return(hash);
        }
Beispiel #29
0
        public async Task <ActionResult> AddContainerImageIntoLocalStore(ContainerImageDto dto)
        {
            var containerImage = new ContainerImage(dto.Repository, dto.Tag, dto.Hash, dto.CreationDateTime);

            await _containerImageMetadataService.AddOrUpdate(containerImage);

            var containerImages = await _containerImageMetadataService
                                  .GetTagsForRepository(containerImage.Repository);

            return(Ok(
                       containerImages
                       .Select(x => new ContainerImageDto()
            {
                Hash = x.Hash,
                Repository = x.Repository,
                Tag = x.Tag,
                CreationDateTime = x.CreationDateTime
            })
                       .ToList()
                       ));
        }
Beispiel #30
0
        private ApplicationLoadBalancedEc2Service CreateService(Cluster cluster)
        {
            var repository = Repository.FromRepositoryAttributes(this, "dev-api-repo", new RepositoryAttributes
            {
                RepositoryName = "app-repo",
                RepositoryArn  = "arn:aws:ecr:us-east-1:714871639201:repository/app-repo",
            });

            return(new ApplicationLoadBalancedEc2Service(this, "dev-ecs-service",
                                                         new ApplicationLoadBalancedEc2ServiceProps()
            {
                ServiceName = "dev-crud-api-service",
                Cluster = cluster,
                DesiredCount = 1,
                TaskImageOptions = new ApplicationLoadBalancedTaskImageOptions
                {
                    Image = ContainerImage.FromEcrRepository(repository, "latest"),
                },
                MemoryLimitMiB = 256,
                PublicLoadBalancer = true,
            }));
        }