/// <summary>
        /// Creates a new deployment.
        ///
        /// </summary>
        /// <param name="request">The request object containing the details to send. Required.</param>
        /// <param name="retryConfiguration">The retry configuration that will be used by to send this request. Optional.</param>
        /// <param name="cancellationToken">The cancellation token to cancel this operation. Optional.</param>
        /// <returns>A response object containing details about the completed operation</returns>
        public async Task <CreateDeploymentResponse> CreateDeployment(CreateDeploymentRequest request, RetryConfiguration retryConfiguration = null, CancellationToken cancellationToken = default)
        {
            logger.Trace("Called createDeployment");
            Uri                uri            = new Uri(this.restClient.GetEndpoint(), System.IO.Path.Combine(basePathWithoutHost, "/deployments".Trim('/')));
            HttpMethod         method         = new HttpMethod("Post");
            HttpRequestMessage requestMessage = Converter.ToHttpRequestMessage(uri, method, request);

            requestMessage.Headers.Add("Accept", "application/json");
            GenericRetrier      retryingClient = Retrier.GetPreferredRetrier(retryConfiguration, this.retryConfiguration);
            HttpResponseMessage responseMessage;

            try
            {
                if (retryingClient != null)
                {
                    responseMessage = await retryingClient.MakeRetryingCall(this.restClient.HttpSend, requestMessage, cancellationToken);
                }
                else
                {
                    responseMessage = await this.restClient.HttpSend(requestMessage);
                }

                return(Converter.FromHttpResponseMessage <CreateDeploymentResponse>(responseMessage));
            }
            catch (Exception e)
            {
                logger.Error($"CreateDeployment failed with error: {e.Message}");
                throw;
            }
        }
        /// <summary>
        /// A simple function that takes a string and does a ToUpper
        /// </summary>
        /// <param name="input"></param>
        /// <param name="context"></param>
        /// <returns></returns>

        public async Task <string> FunctionHandler(CodeDeployInvokeRequest input, ILambdaContext context)
        {
            String envId   = input.EnvironmentId;
            String appName = input.ApplicationName;

            AmazonCodeDeployClient client = new AmazonCodeDeployClient();

            var request = new CreateDeploymentRequest();

            request.ApplicationName     = appName;
            request.DeploymentGroupName = input.DeploymentGroup;
            request.Description         = "Testing Deployment created by Lambda";
            request.Revision            = new RevisionLocation()
            {
                RevisionType = Amazon.CodeDeploy.RevisionLocationType.S3,
                S3Location   = new S3Location()
                {
                    Bucket     = input.S3BucketName,
                    BucketType = Amazon.CodeDeploy.BundleType.Zip,
                    Key        = input.S3KeyName
                }
            };

            var response = await client.CreateDeploymentAsync(request);

            return(response.ToString());
        }
Exemple #3
0
        public async Task Can_Create_Concurrent_Deployments()
        {
            var request = new CreateDeploymentRequest
            {
                Version   = "3.5.3",
                AutoStart = true
            };

            var createTasks = new List <Task <DeploymentResponse> >();

            for (var i = 0; i < 4; i++)
            {
                createTasks.Add(ServiceClient.PostAsync(request));
            }

            await Task.WhenAll(createTasks);

            var deployments = createTasks.Select(t => t.Result.Deployment).ToList();

            foreach (var deployment in deployments)
            {
                Assert.AreEqual("Started", deployment.Status);
            }

            var distinctEndpoints = deployments.Select(d => d.Endpoints.HttpEndpoint).Distinct();

            Assert.AreEqual(4, distinctEndpoints.Count());

            foreach (var deployment in deployments)
            {
                await DeleteDeployment(deployment.Id);
            }
        }
        // Create
        public async Task <DeploymentResponse> Post(CreateDeploymentRequest request)
        {
            var version = appSettings.Neo4jVersions()
                          .Single(v => v.VersionNumber == request.Version);

            var defaultLeasePeriod = appSettings.Get <TimeSpan>(AppSettingsKeys.DefaultLeasePeriod);

            var neo4jDeploymentRequest = new Neo4jDeploymentRequest
            {
                LeasePeriod = request.LeasePeriod ?? defaultLeasePeriod,
                Version     = new Neo4jVersion
                {
                    Architecture = (Neo4jArchitecture)Enum.Parse(typeof(Neo4jArchitecture), version.Architecture),
                    DownloadUrl  = version.DownloadUrl,
                    Version      = version.VersionNumber,
                    ZipFileName  = version.ZipFileName
                }
            };

            var id = pool.Create(neo4jDeploymentRequest);

            if (!pool.ContainsKey(id))
            {
                throw HttpError.NotFound($"Deployment {id} not found");
            }

            var instance = pool[id];

            request.PluginUrls?.ForEach(p =>
            {
                if (!p.IsEmpty())
                {
                    instance.InstallPlugin(p);
                }
            });

            request.Settings?.ForEach(s =>
            {
                instance.Configure(s.ConfigFile, s.Key, s.Value);
            });

            if (!string.IsNullOrEmpty(request.RestoreDumpFileUrl))
            {
                // Force start to create initial databases/graph.db folder
                await instance.Start(CancellationToken.None);

                await instance.Restore(CancellationToken.None, request.RestoreDumpFileUrl);
            }

            // No need to start if restoring a backup as the restore process needs to auto start due to file system requirements
            if (request.AutoStart && string.IsNullOrEmpty(request.RestoreDumpFileUrl))
            {
                await instance.Start(CancellationToken.None);
            }

            var keyedInstance = pool.SingleOrDefault(p => p.Key == id);

            return(keyedInstance.ConvertTo <DeploymentResponse>());
        }
Exemple #5
0
        private async Task <dynamic> PostCreate(dynamic parameters, CancellationToken token)
        {
            var model   = this.Bind <DeploymentEditModel>();
            var request = new CreateDeploymentRequest(model);
            await _mediator.Send(request, token).ConfigureAwait(false);

            return(RedirectToList());
        }
Exemple #6
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="request">
 /// The request object containing all of the parameters for the API call.
 /// </param>
 /// <param name="callSettings">
 /// If not null, applies overrides to this RPC call.
 /// </param>
 /// <returns>
 /// The RPC response.
 /// </returns>
 public override lro::Operation <Deployment, CreateDeploymentMetadata> CreateDeployment(
     CreateDeploymentRequest request,
     gaxgrpc::CallSettings callSettings = null)
 {
     Modify_CreateDeploymentRequest(ref request, ref callSettings);
     return(new lro::Operation <Deployment, CreateDeploymentMetadata>(
                _callCreateDeployment.Sync(request, callSettings), CreateDeploymentOperationsClient));
 }
Exemple #7
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="request">
 /// The request object containing all of the parameters for the API call.
 /// </param>
 /// <param name="callSettings">
 /// If not null, applies overrides to this RPC call.
 /// </param>
 /// <returns>
 /// A Task containing the RPC response.
 /// </returns>
 public override async stt::Task <lro::Operation <Deployment, CreateDeploymentMetadata> > CreateDeploymentAsync(
     CreateDeploymentRequest request,
     gaxgrpc::CallSettings callSettings = null)
 {
     Modify_CreateDeploymentRequest(ref request, ref callSettings);
     return(new lro::Operation <Deployment, CreateDeploymentMetadata>(
                await _callCreateDeployment.Async(request, callSettings).ConfigureAwait(false), CreateDeploymentOperationsClient));
 }
        public static Google.LongRunning.Operation <Deployment, CreateDeploymentMetadata> CreateDeployment(DeploymentTemplate template)
        {
            var request = new CreateDeploymentRequest
            {
                Deployment = template.ToDeployment()
            };

            return(ExceptionHandler.HandleGrpcCall(() => deploymentServiceClient.CreateDeployment(request)));
        }
Exemple #9
0
        public async Task <BasicResponse> CreateDeployment(CreateDeploymentRequest metadata)
        {
            await using var dataContext = await _dataContextFactory.Construct();

            var dataBridge = dataContext.GetDeploymentDataBridge();
            var result     = await dataBridge.CreateDeployment(metadata);

            return(new BasicResponse(result.ToString()));
        }
Exemple #10
0
        public async Task <IActionResult> CreateDeployment([FromBody] CreateDeploymentRequest metadata)
        {
            var result = await _deployLogic.CreateDeployment(metadata);

            return(new JsonResult(result)
            {
                StatusCode = 201
            });
        }
        public async Task <IActionResult> Create([FromBody] CreateDeploymentDto deployment)
        {
            var request  = new CreateDeploymentRequest(deployment);
            var response = await _mediator.Send(request);

            var envelope = new Envelope <string>(response);

            return(CreatedAtAction(nameof(Retrieve), new { id = envelope.Data }, envelope));
        }
Exemple #12
0
        public async Task <int> CreateDeployment(CreateDeploymentRequest metadata)
        {
            var insertCommand = "INSERT INTO deployments(package_name, version, status) VALUES (@PackageName, @Version, @Status);";
            await _connection.ExecuteAsync(insertCommand, new { metadata.PackageName, metadata.Version, Status = (byte)DeploymentStatus.Created }).ConfigureAwait(false);

            var getIdCommand = "SELECT id FROM deployments WHERE package_name = @PackageName AND version = @Version ORDER BY timestamp_utc DESC";

            var result = await _connection.QueryFirstAsync <int>(getIdCommand, new { metadata.PackageName, metadata.Version }).ConfigureAwait(false);

            return(result);
        }
Exemple #13
0
        /// <summary>
        /// Deploys an application revision through the specified deployment group.
        /// </summary>
        /// <param name="applicationName">The name of an AWS CodeDeploy application associated with the applicable IAM user or AWS account.</param>
        /// <param name="deploymentGroup">The name of the deployment group.</param>
        /// <param name="settings">The <see cref="DeploySettings"/> used during the request to AWS.</param>
        /// <param name="cancellationToken">A cancellation token that can be used by other objects or threads to receive notice of cancellation.</param>
        public async Task <bool> CreateDeployment(string applicationName, string deploymentGroup, DeploySettings settings, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (String.IsNullOrEmpty(applicationName))
            {
                throw new ArgumentNullException("applicationName");
            }
            if (String.IsNullOrEmpty(deploymentGroup))
            {
                throw new ArgumentNullException("deploymentGroup");
            }



            // Create Request
            AmazonCodeDeployClient  client  = this.CreateClient(settings);
            CreateDeploymentRequest request = new CreateDeploymentRequest();

            request.ApplicationName     = applicationName;
            request.DeploymentGroupName = deploymentGroup;

            request.Revision = new RevisionLocation()
            {
                RevisionType = RevisionLocationType.S3,

                S3Location = new S3Location()
                {
                    BundleType = BundleType.Zip,

                    Bucket  = settings.S3Bucket,
                    Key     = settings.S3Key,
                    Version = settings.S3Version
                }
            };



            // Check Response
            CreateDeploymentResponse response = await client.CreateDeploymentAsync(request, cancellationToken);

            if (response.HttpStatusCode == HttpStatusCode.OK)
            {
                _Log.Verbose("Successfully deployed application '{0}'", applicationName);
                return(true);
            }
            else
            {
                _Log.Error("Failed to deploy application '{0}'", applicationName);
                return(false);
            }
        }
 /// <summary>Snippet for CreateDeployment</summary>
 public void CreateDeploymentRequestObject()
 {
     // Snippet: CreateDeployment(CreateDeploymentRequest, CallSettings)
     // Create client
     GSuiteAddOnsClient gSuiteAddOnsClient = GSuiteAddOnsClient.Create();
     // Initialize request argument(s)
     CreateDeploymentRequest request = new CreateDeploymentRequest
     {
         ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
         DeploymentId        = "",
         Deployment          = new Deployment(),
     };
     // Make the request
     Deployment response = gSuiteAddOnsClient.CreateDeployment(request);
     // End snippet
 }
        public async Task <IActionResult> Add(CreateDeploymentRequest createDeploymentRequest)
        {
            try
            {
                // need to move BundleType and RevisionType to UI
                createDeploymentRequest.Revision.S3Location.BundleType = Amazon.CodeDeploy.BundleType.Zip;
                createDeploymentRequest.Revision.RevisionType          = Amazon.CodeDeploy.RevisionLocationType.S3;
                var createDeploymentResponse = await AmazonCodeDeployClient.CreateDeploymentAsync(createDeploymentRequest);
            }
            catch (System.Exception ex)
            {
                throw;
            }

            return(RedirectToAction("Index", "Project"));
        }
Exemple #16
0
        internal static string Deploy(string applicationName, string deploymentGroupName, string bucket, string key, string eTag, string version, string region = "")
        {
            try
            {
                S3Location location = new S3Location()
                {
                    Bucket     = bucket,
                    BundleType = BundleType.Zip,
                    ETag       = eTag,
                    Key        = key,
                    Version    = version
                };

                CreateDeploymentRequest request = new CreateDeploymentRequest()
                {
                    ApplicationName     = applicationName,
                    DeploymentGroupName = deploymentGroupName,
                    Revision            = new RevisionLocation()
                    {
                        S3Location   = location,
                        RevisionType = RevisionLocationType.S3
                    },
                };

                AmazonCodeDeployClient client = string.IsNullOrEmpty(region) ?
                                                new AmazonCodeDeployClient() :
                                                new AmazonCodeDeployClient(RegionEndpoint.GetBySystemName(region));

                Task <CreateDeploymentResponse> response = client.CreateDeploymentAsync(request);
                Task.WaitAll(new Task[] { response });


                string message = "Deployment Created: {0} \ndotnet codedeploy status --deployment-id {0}";
                if (!string.IsNullOrEmpty(region))
                {
                    message += " --region {1}";
                }

                Log.Information(message, response.Result.DeploymentId, region);
                return(response.Result.DeploymentId);
            }
            catch (System.Exception e)
            {
                Log.Error($"{e.GetBaseException().GetType().Name}: {e.Message}");
                return(null);
            }
        }
        /// <summary>Snippet for CreateDeploymentAsync</summary>
        public async Task CreateDeploymentRequestObjectAsync()
        {
            // Snippet: CreateDeploymentAsync(CreateDeploymentRequest, CallSettings)
            // Additional: CreateDeploymentAsync(CreateDeploymentRequest, CancellationToken)
            // Create client
            GSuiteAddOnsClient gSuiteAddOnsClient = await GSuiteAddOnsClient.CreateAsync();

            // Initialize request argument(s)
            CreateDeploymentRequest request = new CreateDeploymentRequest
            {
                ParentAsProjectName = ProjectName.FromProject("[PROJECT]"),
                DeploymentId        = "",
                Deployment          = new Deployment(),
            };
            // Make the request
            Deployment response = await gSuiteAddOnsClient.CreateDeploymentAsync(request);

            // End snippet
        }
Exemple #18
0
        public static void ExecuteVerb(DeploymentCreateOptions opts)
        {
            Console.WriteLine("Create deployment");

            var request = new CreateDeploymentRequest
            {
                Deployment = new Deployment
                {
                    Id           = opts.DeploymentName,
                    ProjectName  = opts.ProjectName,
                    Name         = opts.DeploymentName,
                    LaunchConfig = new LaunchConfig
                    {
                        ConfigJson = File.ReadAllText(opts.LaunchConfigFilePath)
                    },
                    Tag = { opts.Tags },
                    StartingSnapshotId = opts.SnapshotId,
                    AssemblyId         = opts.AssemblyId
                }
            };

            try
            {
                var response = GetDeploymentServiceClient(opts.Host, opts.Port)
                               .CreateDeployment(request)
                               .PollUntilCompleted()
                               .GetResultOrNull();

                if (response != null && response.Status == Deployment.Types.Status.Running)
                {
                    Console.WriteLine("Successfully made a new deployment.");
                }
                else
                {
                    Console.Error.WriteLine("Failed to create new deployment!");
                }
            }
            catch (Grpc.Core.RpcException rpce)
            {
                Console.Error.WriteLine(rpce);
            }
        }
        public void CreateDeployment()
        {
            var base64ConfigFile = @"<?xml version=""1.0"" encoding=""utf-8""?>
            <ServiceConfiguration serviceName=""EmptyWorker"" xmlns=""http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceConfiguration"" osFamily=""2"" osVersion=""*"">
              <Role name=""EmptyWorkerRole"">
            <Instances count=""1"" />
            <ConfigurationSettings>
              <Setting name=""Microsoft.WindowsAzure.Plugins.RemoteAccess.Enabled"" value=""true"" />
              <Setting name=""Microsoft.WindowsAzure.Plugins.RemoteAccess.AccountUsername"" value=""admin"" />
              <Setting name=""Microsoft.WindowsAzure.Plugins.RemoteAccess.AccountEncryptedPassword"" value=""MIIBnQYJKoZIhvcNAQcDoIIBjjCCAYoCAQAxggFOMIIBSgIBADAyMB4xHDAaBgNVBAMME1dpbmRvd3MgQXp1cmUgVG9vbHMCEHqfmBYoV4uxS2eIuf6f1uIwDQYJKoZIhvcNAQEBBQAEggEAN4HgeWCTgX8J+7PdzaYEDcN4a5occpX3ph7WsuxHAm0TosAb2Dx7rYy+KfkxBJbKAtjT39xB5Ik5PCndZWMw5WDIAGmjIU5y7w7oVulrH/jAgjlUxkuvNJWVVt3kq92PGvr8Buches8ca5lhksIhlo7UnneQ6N/LxjEDJuqoE+lxxWrDnEFiHABPgmeHMty2dsrXmi4N6cNMDRZZX+383YbLzLuWOFDasvwH/kz5IxgYQJEQsA5udmLPRSDrWKGqR/lwAGy0XyB4vsV76RoGiAD7w039pIIOoGW0PibDovBc567kUsXHYMvE5mRdEG2zp0XMpcQwUjsM2H0f7hrG0jAzBgkqhkiG9w0BBwEwFAYIKoZIhvcNAwcECGiZM1bE0hxTgBC6GGkWZe5xDg2dvBnPnGD3"" />
              <Setting name=""Microsoft.WindowsAzure.Plugins.RemoteAccess.AccountExpiration"" value=""2013-04-09T23:59:59.0000000+10:00"" />
              <Setting name=""Microsoft.WindowsAzure.Plugins.RemoteForwarder.Enabled"" value=""true"" />
              <Setting name=""Microsoft.WindowsAzure.Plugins.Diagnostics.ConnectionString"" value=""DefaultEndpointsProtocol=https;AccountName=ameerdeen;AccountKey=VB8WTbNDcVNDfCuaeECdIwne4LtWfnCk8X9SRf50yHV1XWwc5vfpl2EF884Tj/YkaCq6tmOrti/GQ4eigAEu9g=="" />
            </ConfigurationSettings>
            <Certificates>
              <Certificate name=""Microsoft.WindowsAzure.Plugins.RemoteAccess.PasswordEncryption"" thumbprint=""B53E2ADE5F1626B33A79CC10D57AC5159B2F6374"" thumbprintAlgorithm=""sha1"" />
            </Certificates>
              </Role>
            </ServiceConfiguration>
            ".ToBase64();

            var name = "Ameer1111";
            var xmlRequest = new CreateDeploymentRequest {
                DeploymentName  = name,
                PackageUrlInBlobStorage = "https://ameerdeen.blob.core.windows.net/public/EmptyWorker.cspkg",
                Label = name,
                Configuration   = base64ConfigFile,
                StartDeployment = true,
                TreatWarningsAsError = false
            }.ToString();

            var serviceName = "ameeristesting2";
            var deploymentSlotName = "production";
            var resourceName = "services/hostedservices/" + serviceName + "/deploymentslots/" + deploymentSlotName;

            var response = _managementClient.ExecutePost(resourceName, xmlRequest);
            Console.WriteLine(xmlRequest);
            Console.WriteLine(response);
        }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            CreateDeploymentRequest request;

            try
            {
                request = new CreateDeploymentRequest
                {
                    CreateDeploymentDetails = CreateDeploymentDetails,
                    OpcRetryToken           = OpcRetryToken,
                    OpcRequestId            = OpcRequestId
                };

                response = client.CreateDeployment(request).GetAwaiter().GetResult();
                WriteOutput(response, response.Deployment);
                FinishProcessing(response);
            }
            catch (Exception ex)
            {
                TerminatingErrorDuringExecution(ex);
            }
        }
        static void Main(string[] args)
        {
            var config  = CreateConfiguration();
            var rootDir = Directory.GetCurrentDirectory();

            var awsRegion     = RegionEndpoint.GetBySystemName(config.AWS.DefaultRegion);
            var awsCredential = new BasicAWSCredentials(config.AWS.Credentials.AccessKeyId, config.AWS.Credentials.SecretAccessKey);

            //checking package file
            System.Console.WriteLine("checking package file...");

            if (File.Exists(config.PackagePath) == false)
            {
                System.Console.WriteLine("package file does not exists.");
                System.Environment.Exit(1);
                return;
            }

            var appPackage  = new AppPackage(config.PackagePath);
            var functionARN = "";

            //creating lambda function
            using (var lambdaClient = new AmazonLambdaClient(awsCredential, awsRegion))
            {
                //checking lambda function
                System.Console.WriteLine("checking if lambda function exists...");

                var getFunctionResponse = lambdaClient
                                          .ExecuteWithNoExceptionsAsync(c => { return(c.GetFunctionConfigurationAsync(config.AWS.Lambda.FunctionName)); })
                                          .Result;

                if (getFunctionResponse.HttpStatusCode != HttpStatusCode.OK && getFunctionResponse.HttpStatusCode != HttpStatusCode.NotFound)
                {
                    ExitDueUnexpectedResponse(getFunctionResponse);
                    return;
                }

                //function does not exists, create a new
                if (getFunctionResponse.HttpStatusCode == HttpStatusCode.NotFound)
                {
                    System.Console.WriteLine("lambda function does not exists, creating function....");

                    var createFunctionResponse = lambdaClient
                                                 .ExecuteWithNoExceptionsAsync(c => { return(c.CreateFunctionAsync(appPackage, config.AWS.Lambda, Runtime.Dotnetcore20)); })
                                                 .Result;

                    //checking create function response
                    if (createFunctionResponse.HttpStatusCode != HttpStatusCode.Created)
                    {
                        ExitDueUnexpectedResponse(createFunctionResponse);
                        return;
                    }

                    System.Console.WriteLine("lambda function created with success.");
                    functionARN = createFunctionResponse.FunctionArn;
                }
                else
                {
                    functionARN = getFunctionResponse.FunctionArn;
                }

                //checking if is new package
                var hashFilePath  = $"{rootDir}/package.hash";
                var isSamePackage = false;

                if (File.Exists(hashFilePath))
                {
                    var currentHash = File.ReadAllText(hashFilePath);
                    isSamePackage = appPackage.PackageSha256.Equals(currentHash);
                }

                if (getFunctionResponse.HttpStatusCode == HttpStatusCode.OK)
                {
                    functionARN = getFunctionResponse.FunctionArn;

                    if (isSamePackage == false)
                    {
                        System.Console.WriteLine("lambda function exists, updating lambda function code...");

                        var updateCodeResponse = lambdaClient
                                                 .ExecuteWithNoExceptionsAsync(c => { return(c.UpdateFunctionCodeAsync(appPackage, config.AWS.Lambda)); })
                                                 .Result;

                        if (updateCodeResponse.HttpStatusCode != HttpStatusCode.OK)
                        {
                            ExitDueUnexpectedResponse(updateCodeResponse);
                            return;
                        }

                        System.Console.WriteLine("lambda function code updated with success.");
                    }
                    else
                    {
                        System.Console.WriteLine("lambda function exists and its code is updated.");
                    }
                }

                if (isSamePackage == false)
                {
                    File.WriteAllText(hashFilePath, appPackage.PackageSha256);
                }
            }

            using (var gatewayClient = new AmazonAPIGatewayClient(awsCredential, awsRegion))
            {
                //checking if api exists
                System.Console.WriteLine("checking existence of api gateway...");

                var listApiResponse = gatewayClient
                                      .ExecuteWithNoExceptionsAsync(c => { return(c.GetRestApisAsync(config.AWS.ApiGateway.GatewayName)); })
                                      .Result;

                if (listApiResponse.HttpStatusCode != HttpStatusCode.OK)
                {
                    ExitDueUnexpectedResponse(listApiResponse);
                    return;
                }

                //creating api
                var restApi = listApiResponse.Items.SingleOrDefault();

                if (restApi == null)
                {
                    System.Console.WriteLine("api gateway does not exists, creating api gateway...");

                    var createApiResponse = gatewayClient
                                            .ExecuteWithNoExceptionsAsync(c => { return(c.CreateRestApiAsync(config.AWS.ApiGateway.GatewayName)); })
                                            .Result;

                    if (createApiResponse.HttpStatusCode != HttpStatusCode.Created)
                    {
                        ExitDueUnexpectedResponse(createApiResponse);
                        return;
                    }

                    restApi = new RestApi
                    {
                        Id   = createApiResponse.Id,
                        Name = config.AWS.ApiGateway.GatewayName
                    };
                }
                else
                {
                    System.Console.WriteLine("api gateway - OK");
                }

                //checkig if resource exists
                System.Console.WriteLine("checking existence of api resource...");
                var listResourceRequest = new GetResourcesRequest()
                {
                    RestApiId = restApi.Id,
                };

                var listResourceResponse = gatewayClient
                                           .ExecuteWithNoExceptionsAsync(c => { return(c.GetResourcesAsync(listResourceRequest)); })
                                           .Result;

                if (listResourceResponse.HttpStatusCode != HttpStatusCode.OK)
                {
                    ExitDueUnexpectedResponse(listResourceResponse);
                    return;
                }

                var rootResource  = listResourceResponse.Items.GetRootResource() ?? throw new System.Exception($"root resource can't be found on api:{restApi.Id}");
                var proxyResource = listResourceResponse.Items.GetProxyResource();

                if (proxyResource == null)
                {
                    //creating resource
                    System.Console.WriteLine("api resource not found, creating api resource...");

                    var createResourceResponse = gatewayClient
                                                 .ExecuteWithNoExceptionsAsync(c => { return(c.CreateProxyResourceAsync(restApi.Id, rootResource.Id)); })
                                                 .Result;

                    if (createResourceResponse.HttpStatusCode != HttpStatusCode.Created)
                    {
                        ExitDueUnexpectedResponse(createResourceResponse);
                        return;
                    }

                    proxyResource = createResourceResponse.MapToResource();
                    System.Console.WriteLine("api resource created.");
                }
                else
                {
                    System.Console.WriteLine("api resource - OK");
                }

                //checking if methods were created
                System.Console.WriteLine("checking if resource methods exists...");

                var getMethodRequest = new GetMethodRequest()
                {
                    HttpMethod = AmazonModelExtensions.ANY_METHOD,
                    ResourceId = proxyResource.Id,
                    RestApiId  = restApi.Id
                };

                var getMethodResponse = gatewayClient
                                        .ExecuteWithNoExceptionsAsync(c => { return(c.GetMethodAsync(getMethodRequest)); })
                                        .Result;

                if (getMethodResponse.HttpStatusCode != HttpStatusCode.OK && getMethodResponse.HttpStatusCode != HttpStatusCode.NotFound)
                {
                    ExitDueUnexpectedResponse(getMethodResponse);
                    return;
                }

                if (getMethodResponse.HttpStatusCode == HttpStatusCode.NotFound)
                {
                    System.Console.WriteLine("resource methods does not exists, creating resource methods....");

                    var putMethodResponse = gatewayClient.ExecuteWithNoExceptionsAsync
                                            (
                        c =>
                    {
                        return(c.PutProxyMethodAsync(proxyResource.Id, restApi.Id, AmazonModelExtensions.ANY_METHOD, "proxy"));
                    }
                                            )
                                            .Result;

                    if (putMethodResponse.HttpStatusCode != HttpStatusCode.Created)
                    {
                        ExitDueUnexpectedResponse(putMethodResponse);
                        return;
                    }

                    System.Console.WriteLine("resource method created with success");
                }
                else
                {
                    System.Console.WriteLine("resource methods - OK");
                }

                //checking integration with lambda function
                System.Console.WriteLine("checking if integration with lambda exists...");

                var getIntegrationRequest = new GetIntegrationRequest()
                {
                    HttpMethod = AmazonModelExtensions.ANY_METHOD,
                    ResourceId = proxyResource.Id,
                    RestApiId  = restApi.Id
                };

                var getIntegrationResponse = gatewayClient
                                             .ExecuteWithNoExceptionsAsync(c => { return(c.GetIntegrationAsync(getIntegrationRequest)); })
                                             .Result;

                if (getIntegrationResponse.HttpStatusCode != HttpStatusCode.OK && getIntegrationResponse.HttpStatusCode != HttpStatusCode.NotFound)
                {
                    ExitDueUnexpectedResponse(getIntegrationResponse);
                    return;
                }

                if (getIntegrationResponse.HttpStatusCode == HttpStatusCode.NotFound)
                {
                    System.Console.WriteLine("integration with lambda does not exists, creating integration...");

                    var putIntegrationResponse = gatewayClient.ExecuteWithNoExceptionsAsync
                                                 (
                        c =>
                    {
                        return(c.PutLambdaProxyIntegrationAsync
                               (
                                   proxyResource.Id,
                                   restApi.Id,

                                   AmazonModelExtensions.ANY_METHOD,
                                   config.AWS.Lambda.FunctionTimeoutSeconds.Value * 1000,

                                   functionARN,
                                   config.AWS.DefaultRegion
                               ));
                    }
                                                 )
                                                 .Result;

                    if (putIntegrationResponse.HttpStatusCode != HttpStatusCode.Created)
                    {
                        ExitDueUnexpectedResponse(putIntegrationResponse);
                        return;
                    }

                    System.Console.WriteLine("integration with lambda created with success");
                }
                else
                {
                    System.Console.WriteLine("integration with lambda - OK");
                }

                //checking deployment
                System.Console.WriteLine("checking api gateway deployment...");
                var getDeployRequest = new GetDeploymentsRequest()
                {
                    RestApiId = restApi.Id
                };

                var getDeployResponse = gatewayClient
                                        .ExecuteWithNoExceptionsAsync(c => { return(c.GetDeploymentsAsync(getDeployRequest)); })
                                        .Result;

                if (getDeployResponse.HttpStatusCode != HttpStatusCode.OK)
                {
                    ExitDueUnexpectedResponse(getDeployResponse);
                    return;
                }

                var deployment = (Deployment)null;

                if (getDeployResponse.Items.Count == 0)
                {
                    System.Console.WriteLine("api gateway deployment not found, deploying api gateway...");

                    var createDeployRequest = new CreateDeploymentRequest()
                    {
                        RestApiId        = restApi.Id,
                        StageName        = config.ASPNETCORE_ENVIRONMENT,
                        StageDescription = config.ASPNETCORE_ENVIRONMENT,
                    };

                    var createDeployResponse = gatewayClient
                                               .ExecuteWithNoExceptionsAsync(c => { return(c.CreateDeploymentAsync(createDeployRequest)); })
                                               .Result;

                    if (createDeployResponse.HttpStatusCode != HttpStatusCode.Created)
                    {
                        ExitDueUnexpectedResponse(createDeployResponse);
                        return;
                    }

                    System.Console.WriteLine("api gateway deployed with success.");
                }
                else
                {
                    deployment = getDeployResponse.Items[0];
                    System.Console.WriteLine("api gateway deployment - OK");
                }

                using (var lambdaClient = new AmazonLambdaClient(awsCredential, awsRegion))
                {
                    System.Console.WriteLine("grating permission to api gateway trigger lambda...");

                    var permissionResponse = lambdaClient.ExecuteWithNoExceptionsAsync
                                             (
                        c =>
                    {
                        return(c.AddExecuteApiPermissionAsync
                               (
                                   config.AWS.Lambda, restApi.Id, config.AWS.DefaultRegion, config.AWS.AccountId
                               ));
                    }
                                             )
                                             .Result;

                    if (permissionResponse.HttpStatusCode != HttpStatusCode.Created && permissionResponse.HttpStatusCode != HttpStatusCode.Conflict)
                    {
                        ExitDueUnexpectedResponse(permissionResponse);
                        return;
                    }

                    if (permissionResponse.HttpStatusCode == HttpStatusCode.Conflict)
                    {
                        System.Console.WriteLine("permission already granted.");
                    }
                    else
                    {
                        System.Console.WriteLine("permission granted with success.");
                    }
                }
            }
        }
        public async Task ExecuteAsync()
        {
            var publishDirectory = this.Utilities.GetOutputFolder();
            var applicationBundleFile = string.Format("{0}-{1}.zip", 
                this.AppEnv.ApplicationName, DateTime.Now.Ticks);
            var applicationBundlePath = Path.Combine(publishDirectory, "..", applicationBundleFile);
            Console.WriteLine("Publishing {0} to {1}", this.AppEnv.ApplicationName, publishDirectory);

            // Package up application for publishing
            if(!this.Utilities.ExecutePublish(true))
            {
                Console.Error.WriteLine("Error packaging up project");
                return;
            }


            UtilityService.CopyFile(
                Path.Combine(this.AppEnv.ApplicationBasePath, "CodeDeployScripts/appspec.yml"),
                Path.Combine(publishDirectory, "appspec.yml"));

            if (File.Exists(applicationBundlePath))
                File.Delete(applicationBundlePath);

            Console.WriteLine("Creating application bundle: " + applicationBundlePath);
            ZipFile.CreateFromDirectory(publishDirectory, applicationBundlePath);


            string eTag = null;
            var bucketName = this.Configuration["Deployment:S3Bucket"];

            var putRequest = new PutObjectRequest
            {
                BucketName = bucketName,
                FilePath = applicationBundlePath
            };

            int percentToUpdateOn = 25;
            putRequest.StreamTransferProgress = ((s, e) =>
            {
                if (e.PercentDone == percentToUpdateOn || e.PercentDone > percentToUpdateOn)
                {
                    int increment = e.PercentDone % 25;
                    if (increment == 0)
                        increment = 25;
                    percentToUpdateOn = e.PercentDone + increment;
                    Console.WriteLine("Uploading to S3 {0}%", e.PercentDone);
                }
            });

            Console.WriteLine("Uploading application bunble to S3: {0}/{1}", 
                bucketName, applicationBundleFile);
            eTag = (await this.S3Client.PutObjectAsync(putRequest)).ETag;

            var request = new CreateDeploymentRequest
            {
                ApplicationName = "Pollster-" + this.AppEnv.ApplicationName,
                DeploymentGroupName = "Pollster-" + this.AppEnv.ApplicationName + "-Fleet",
                Revision = new RevisionLocation
                {
                    RevisionType = RevisionLocationType.S3,
                    S3Location = new S3Location
                    {
                        Bucket = bucketName,
                        Key = applicationBundleFile,
                        BundleType = BundleType.Zip,
                        ETag = eTag
                    }
                }
            };
            var response = await this.CodeDeployClient.CreateDeploymentAsync(request);
            Console.WriteLine("Deployment initiated with deployment id {0}", response.DeploymentId);

            return;
        }
 public async Task<Deployment> CreateAsync(CreateDeploymentRequest request)
 {
     return (await client.PostAsync(request)).Deployment;
 }
 public Deployment Create(CreateDeploymentRequest request)
 {
     return client.Post(request).Deployment;
 }
Exemple #25
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="request">
 /// The request object containing all of the parameters for the API call.
 /// </param>
 /// <param name="callSettings">
 /// If not null, applies overrides to this RPC call.
 /// </param>
 /// <returns>
 /// The RPC response.
 /// </returns>
 public virtual lro::Operation <Deployment, CreateDeploymentMetadata> CreateDeployment(
     CreateDeploymentRequest request,
     gaxgrpc::CallSettings callSettings = null)
 {
     throw new sys::NotImplementedException();
 }
Exemple #26
0
 partial void Modify_CreateDeploymentRequest(ref CreateDeploymentRequest request, ref gaxgrpc::CallSettings settings);
Exemple #27
0
        private void StartDeployment(string newDeploymentName)
        {
            Log.Logger.Information("Starting new deployment named {dplName}", newDeploymentName);
            string snapshotId;

            try
            {
                snapshotId = CreateSnapshotId(newDeploymentName);
            }
            catch (RpcException e)
            {
                if (e.StatusCode == StatusCode.ResourceExhausted)
                {
                    Log.Logger.Warning("Resource exhausted creating snapshot: {err}", e.Message);
                    return;
                }

                throw e;
            }
            var launchConfig = GetLaunchConfig();

            var deployment = new Deployment
            {
                Name               = newDeploymentName,
                ProjectName        = spatialProject,
                Description        = "Launched by Deployment Pool",
                AssemblyId         = assemblyName,
                LaunchConfig       = launchConfig,
                StartingSnapshotId = snapshotId,
            };

            deployment.Tag.Add(DeploymentPool.StartingTag);
            deployment.Tag.Add(matchType);

            var createDeploymentRequest = new CreateDeploymentRequest
            {
                Deployment = deployment
            };

            try
            {
                var startTime = DateTime.Now;
                Reporter.ReportDeploymentCreationRequest(matchType);
                var createOp = deploymentServiceClient.CreateDeployment(createDeploymentRequest);
                Task.Run(() =>
                {
                    var completed = createOp.PollUntilCompleted();
                    Reporter.ReportDeploymentCreationDuration(matchType, (DateTime.Now - startTime).TotalSeconds);
                    if (completed.IsCompleted)
                    {
                        Log.Logger.Information("Deployment {dplName} started succesfully", completed.Result.Name);
                    }
                    else if (completed.IsFaulted)
                    {
                        Log.Logger.Error("Failed to start deployment {DplName}. Operation {opName}. Error {err}", createDeploymentRequest.Deployment.Name, completed.Name, completed.Exception.Message);
                    }
                    else
                    {
                        Log.Logger.Error("Internal error starting deployment {dplName}. Operation {opName}. Error {err}", completed.Result.Name, completed.Name, completed.Exception.Message);
                    }
                });
            }
            catch (RpcException e)
            {
                Reporter.ReportDeploymentCreationFailure(matchType);
                Log.Logger.Error("Failed to start deployment creation. Error: {err}", e.Message);
            }
        }