Beispiel #1
0
        public async Task Initialize(string workingDirectory, Version cdkVersion)
        {
            var packageJsonFileContent = _packageJsonGenerator.Generate(cdkVersion);
            var packageJsonFilePath    = Path.Combine(workingDirectory, _packageJsonFileName);

            try
            {
                if (!_directoryManager.Exists(workingDirectory))
                {
                    _directoryManager.CreateDirectory(workingDirectory);
                }

                await _fileManager.WriteAllTextAsync(packageJsonFilePath, packageJsonFileContent);
            }
            catch (Exception exception)
            {
                throw new PackageJsonFileException($"Failed to write {_packageJsonFileName} at {packageJsonFilePath}", exception);
            }

            try
            {
                // Install node packages specified in package.json file
                await _commandLineWrapper.Run("npm install", workingDirectory, false);
            }
            catch (Exception exception)
            {
                throw new NPMCommandFailedException($"Failed to install npm packages at {workingDirectory}", exception);
            }
        }
        public async Task DeployCdkProject(OrchestratorSession session, string cdkProjectPath, Recommendation recommendation)
        {
            var recipeInfo           = $"{recommendation.Recipe.Id}_{recommendation.Recipe.Version}";
            var environmentVariables = new Dictionary <string, string>
            {
                { EnvironmentVariableKeys.AWS_EXECUTION_ENV, recipeInfo }
            };

            _interactiveService.LogMessageLine("Starting deployment of CDK Project");

            // Ensure region is bootstrapped
            await _commandLineWrapper.Run($"npx cdk bootstrap aws://{session.AWSAccountId}/{session.AWSRegion}",
                                          needAwsCredentials : true);

            var appSettingsFilePath = Path.Combine(cdkProjectPath, "appsettings.json");

            // Handover to CDK command line tool
            // Use a CDK Context parameter to specify the settings file that has been serialized.
            var cdkDeploy = await _commandLineWrapper.TryRunWithResult($"npx cdk deploy --require-approval never -c {Constants.CloudFormationIdentifier.SETTINGS_PATH_CDK_CONTEXT_PARAMETER}=\"{appSettingsFilePath}\"",
                                                                       workingDirectory : cdkProjectPath,
                                                                       environmentVariables : environmentVariables,
                                                                       needAwsCredentials : true,
                                                                       streamOutputToInteractiveService : true);

            if (cdkDeploy.ExitCode != 0)
            {
                throw new FailedToDeployCDKAppException("We had an issue deploying your application to AWS. Check the deployment output for more details.");
            }
        }
Beispiel #3
0
        public async Task CreateCdkDeployment(OrchestratorSession session, CloudApplication cloudApplication, Recommendation recommendation)
        {
            // Create a new temporary CDK project for a new deployment
            _interactiveService.LogMessageLine($"Generating a {recommendation.Recipe.Name} CDK Project");
            var cdkProjectPath = await CreateCdkProjectForDeployment(recommendation, session);

            // Write required configuration in appsettings.json
            var appSettingsBody     = _appSettingsBuilder.Build(cloudApplication, recommendation);
            var appSettingsFilePath = Path.Combine(cdkProjectPath, "appsettings.json");

            using (var appSettingsFile = new StreamWriter(appSettingsFilePath))
            {
                await appSettingsFile.WriteAsync(appSettingsBody);
            }

            _interactiveService.LogMessageLine("Starting deployment of CDK Project");

            // Ensure region is bootstrapped
            await _commandLineWrapper.Run($"npx cdk bootstrap aws://{session.AWSAccountId}/{session.AWSRegion}");

            // Handover to CDK command line tool
            // Use a CDK Context parameter to specify the settings file that has been serialized.
            await _commandLineWrapper.Run($"npx cdk deploy --require-approval never -c {CloudFormationIdentifierConstants.SETTINGS_PATH_CDK_CONTEXT_PARAMETER}=\"{appSettingsFilePath}\"", cdkProjectPath);
        }
Beispiel #4
0
        /// <summary>
        /// Convenience extension to <see cref="ICommandLineWrapper.Run"/>
        /// that returns a <see cref="TryRunWithResult"/> with the full contents
        /// of <see cref="Process.StandardError"/> and <see cref="Process.StandardOutput"/>
        /// </summary>
        /// <param name="commandLineWrapper">
        /// See <see cref="ICommandLineWrapper"/>
        /// </param>
        /// <param name="command">
        /// Shell script to execute
        /// </param>
        /// <param name="workingDirectory">
        /// Default directory for the shell.  This needs to have the correct pathing for
        /// the current OS
        /// </param>
        /// <param name="streamOutputToInteractiveService">
        /// By default standard out/error will be piped to a <see cref="IOrchestratorInteractiveService"/>.
        /// Set this to false to disable sending output.
        /// </param>
        /// <param name="redirectIO">
        /// By default, <see cref="Process.StandardInput"/>, <see cref="Process.StandardOutput"/> and <see cref="Process.StandardError"/> will be redirected.
        /// Set this to false to avoid redirection.
        /// </param>
        /// <param name="cancelToken">
        /// <see cref="CancellationToken"/>
        /// </param>
        public static async Task <TryRunResult> TryRunWithResult(
            this ICommandLineWrapper commandLineWrapper,
            string command,
            string workingDirectory = "",
            bool streamOutputToInteractiveService = false,
            bool redirectIO = true,
            CancellationToken cancelToken = default)
        {
            var result = new TryRunResult();

            await commandLineWrapper.Run(
                command,
                workingDirectory,
                streamOutputToInteractiveService,
                onComplete : runResult => result = runResult,
                redirectIO : redirectIO,
                cancelToken);

            return(result);
        }
Beispiel #5
0
        private async Task <DockerInfo> HasDockerInstalledAndRunning()
        {
            var processExitCode = -1;
            var containerType   = "";
            var command         = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "docker info -f \"{{.OSType}}\"" : "docker info";

            await _commandLineWrapper.Run(
                command,
                streamOutputToInteractiveService : false,
                onComplete : proc =>
            {
                processExitCode = proc.ExitCode;
                containerType   = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ?
                                  proc.StandardOut?.TrimEnd('\n') ??
                                  throw new DockerInfoException("Failed to check if Docker is running in Windows or Linux container mode.") :
                                  "linux";
            });

            var dockerInfo = new DockerInfo(processExitCode == 0, containerType);

            return(dockerInfo);
        }
Beispiel #6
0
        private async Task <DockerInfo> HasDockerInstalledAndRunning()
        {
            var processExitCode = -1;
            var containerType   = "";
            var command         = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "docker info -f \"{{.OSType}}\"" : "docker info";

            await _commandLineWrapper.Run(
                command,
                streamOutputToInteractiveService : false,
                onComplete : proc =>
            {
                processExitCode = proc.ExitCode;
                containerType   = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? proc.StandardOut.TrimEnd('\n') : "linux";
            });

            var dockerInfo = new DockerInfo
            {
                DockerInstalled     = processExitCode == 0,
                DockerContainerType = containerType
            };

            return(dockerInfo);
        }
Beispiel #7
0
        /// <summary>
        /// Convenience extension to <see cref="ICommandLineWrapper.Run"/>
        /// that returns a <see cref="TryRunWithResult"/> with the full contents
        /// of <see cref="Process.StandardError"/> and <see cref="Process.StandardOutput"/>
        /// </summary>
        /// <param name="commandLineWrapper">
        /// See <see cref="ICommandLineWrapper"/>
        /// </param>
        /// <param name="command">
        /// Shell script to execute
        /// </param>
        /// <param name="workingDirectory">
        /// Default directory for the shell.  This needs to have the correct pathing for
        /// the current OS
        /// </param>
        /// <param name="streamOutputToInteractiveService">
        /// By default standard out/error will be piped to a <see cref="IOrchestratorInteractiveService"/>.
        /// Set this to false to disable sending output.
        /// </param>
        /// <param name="redirectIO">
        /// By default, <see cref="Process.StandardInput"/>, <see cref="Process.StandardOutput"/> and <see cref="Process.StandardError"/> will be redirected.
        /// Set this to false to avoid redirection.
        /// </param>
        /// <param name="environmentVariables">
        /// <see cref="command"/> is executed as a child process of running process which inherits the parent process's environment variables.
        /// <see cref="environmentVariables"/> allows to add (replace if exists) extra environment variables to the child process.
        /// <remarks>
        /// AWS Execution Environment string to append in AWS_EXECUTION_ENV env var.
        /// AWS SDK calls made while executing <see cref="command"/> will have User-Agent string containing
        /// </remarks>
        /// </param>
        /// <param name="cancelToken">
        /// <see cref="CancellationToken"/>
        /// </param>
        public static async Task <TryRunResult> TryRunWithResult(
            this ICommandLineWrapper commandLineWrapper,
            string command,
            string workingDirectory = "",
            bool streamOutputToInteractiveService = false,
            bool redirectIO = true,
            IDictionary <string, string>?environmentVariables = null,
            CancellationToken cancelToken = default,
            bool needAwsCredentials       = false)
        {
            var result = new TryRunResult();

            await commandLineWrapper.Run(
                command,
                workingDirectory,
                streamOutputToInteractiveService,
                onComplete : runResult => result = runResult,
                redirectIO : redirectIO,
                environmentVariables : environmentVariables,
                cancelToken : cancelToken,
                needAwsCredentials : needAwsCredentials);

            return(result);
        }
Beispiel #8
0
 public async Task Install(string workingDirectory, Version version)
 {
     await _commandLineWrapper.Run($"npm install aws-cdk@{version}", workingDirectory, false);
 }