public void Install(RunningDeployment deployment)
        {
            var features = deployment.Variables.GetStrings(SpecialVariables.Package.EnabledFeatures).Where(s => !string.IsNullOrWhiteSpace(s)).ToList();

            if (!features.Contains(SpecialVariables.Features.CustomScripts))
                return;

            foreach (var scriptName in scriptEngine.GetSupportedExtensions()
                .Select(extension => GetScriptName(deploymentStage, extension)))
            {
                var scriptBody = deployment.Variables.Get(scriptName);

                if (string.IsNullOrWhiteSpace(scriptBody))
                    continue;

                var scriptFile = Path.Combine(deployment.CurrentDirectory, scriptName);

                fileSystem.OverwriteFile(scriptFile, scriptBody);

                // Execute the script
                Log.VerboseFormat("Executing '{0}'", scriptFile);
                var result = scriptEngine.Execute(scriptFile, deployment.Variables, commandLineRunner);

                if (result.ExitCode != 0)
                {
                    throw new CommandException(string.Format("Script '{0}' returned non-zero exit code: {1}", scriptFile,
                        result.ExitCode));
                }

                // And then delete it (this means if the script failed, it will persist, which may assist debugging)
                fileSystem.DeleteFile(scriptFile, DeletionOptions.TryThreeTimesIgnoreFailure);
            }
        }
        public void Install(RunningDeployment deployment)
        {
            var customInstallationDirectory = deployment.Variables.Get(SpecialVariables.Package.CustomInstallationDirectory);
            var sourceDirectory = deployment.Variables.Get(SpecialVariables.OriginalPackageDirectoryPath);

            if (string.IsNullOrWhiteSpace(customInstallationDirectory))
            {
                Log.Verbose("The package has been installed to: " + sourceDirectory);
                Log.VerboseFormat("If you would like the package to be installed to an alternative location, please specify the variable '{0}'", SpecialVariables.Package.CustomInstallationDirectory);
                // If the variable was not set then we set it, as it makes it simpler for anything to depend on it from this point on
                deployment.Variables.Set(SpecialVariables.Package.CustomInstallationDirectory,
                   sourceDirectory);

                return;
            }

            // Purge if requested
            if (deployment.Variables.GetFlag(
                SpecialVariables.Package.CustomInstallationDirectoryShouldBePurgedBeforeDeployment))
            {
                Log.Info("Purging the directory '{0}'", customInstallationDirectory);
                fileSystem.PurgeDirectory(deployment.CustomDirectory, FailureOptions.ThrowOnFailure);
            }

            // Copy files from staging area to custom directory
            Log.Info("Copying package contents to '{0}'", customInstallationDirectory);
            int count = fileSystem.CopyDirectory(deployment.StagingDirectory, deployment.CustomDirectory);
            Log.Info("Copied {0} files", count);

            // From this point on, the current directory will be the custom-directory
            deployment.CurrentDirectoryProvider = DeploymentWorkingDirectory.CustomDirectory;

            Log.SetOutputVariable(SpecialVariables.Package.Output.InstallationDirectoryPath, deployment.CustomDirectory, deployment.Variables);
        }
        public void Install(RunningDeployment deployment)
        {
            var transformDefinitions = GetTransformDefinitions(deployment.Variables.Get(SpecialVariables.Package.AdditionalXmlConfigurationTransforms));

            var sourceExtensions = new HashSet<string>(
                  transformDefinitions
                    .Where(transform => transform.Advanced)
                    .Select(transform => "*" + Path.GetExtension(transform.SourcePattern))
                    .Distinct()
                );

            if (deployment.Variables.GetFlag(SpecialVariables.Package.AutomaticallyRunConfigurationTransformationFiles))
            {
                sourceExtensions.Add("*.config");
                transformDefinitions.Add(new XmlConfigTransformDefinition("Release"));

                var environment = deployment.Variables.Get(SpecialVariables.Environment.Name);
                if (!string.IsNullOrWhiteSpace(environment))
                {
                    transformDefinitions.Add(new XmlConfigTransformDefinition(environment));
                }
            }

            var transformsRun = new HashSet<string>();
            foreach (var configFile in fileSystem.EnumerateFilesRecursively(deployment.CurrentDirectory,
                sourceExtensions.ToArray()))
            {
                ApplyTransformations(configFile, transformDefinitions, transformsRun);

            }

            deployment.Variables.SetStrings(SpecialVariables.AppliedXmlConfigTransforms, transformsRun, "|");
        }
        public void Install(RunningDeployment deployment)
        {
            if (deployment.Variables.GetFlag(SpecialVariables.Package.AutomaticallyUpdateAppSettingsAndConnectionStrings) == false)
            {
                return;
            }

            var appliedAsTransforms = deployment.Variables.GetStrings(SpecialVariables.AppliedXmlConfigTransforms, '|');

            Log.Verbose("Looking for appSettings and connectionStrings in any .config files");

            if (deployment.Variables.GetFlag(SpecialVariables.Package.IgnoreVariableReplacementErrors))
                Log.Info("Variable replacement errors are supressed because the variable Octopus.Action.Package.IgnoreVariableReplacementErrors has been set.");

            var configurationFiles = fileSystem.EnumerateFilesRecursively(deployment.CurrentDirectory, "*.config");
            foreach (var configurationFile in configurationFiles)
            {
                if (appliedAsTransforms.Contains(configurationFile))
                {
                    Log.VerboseFormat("File '{0}' was interpreted as an XML configuration transform; variable substitution won't be attempted.", configurationFile);
                    continue;
                }

                replacer.ModifyConfigurationFile(configurationFile, deployment.Variables);
            }
        }
        public void Install(RunningDeployment deployment)
        {
            if (!deployment.Variables.GetFlag(SpecialVariables.Package.SkipIfAlreadyInstalled))
            {
                return;
            }

            var id = deployment.Variables.Get(SpecialVariables.Package.NuGetPackageId);
            var version = deployment.Variables.Get(SpecialVariables.Package.NuGetPackageVersion);
            var policySet = deployment.Variables.Get(SpecialVariables.RetentionPolicySet);

            var previous = journal.GetLatestInstallation(policySet, id, version);
            if (previous == null) 
                return;

            if (!previous.WasSuccessful)
            {
                Log.Info("The previous attempt to deploy this package was not successful; re-deploying.");
            }
            else
            {
                Log.Info("The package has already been installed on this machine, so installation will be skipped.");
                Log.SetOutputVariable(SpecialVariables.Package.Output.InstallationDirectoryPath, previous.ExtractedTo);
                deployment.Variables.Set(SpecialVariables.Action.SkipRemainingConventions, "true");
                deployment.Variables.Set(SpecialVariables.Action.SkipJournal, "true");
            }
        }
        public void Install(RunningDeployment deployment)
        {
            var policySet = deployment.Variables.Get(SpecialVariables.RetentionPolicySet);
            var previous = journal.GetLatestInstallation(policySet);
            string previousExtractedFrom;
            string previousExtractedTo;
            string previousVersion;
            string previousCustom;
            if (previous == null)
            {
                previousExtractedTo = previousExtractedFrom = previousVersion = previousCustom = "";
            }
            else
            {
                previousExtractedFrom = previous.ExtractedFrom;
                previousExtractedTo = previous.ExtractedTo;
                previousVersion = previous.PackageVersion;
                previousCustom = previous.CustomInstallationDirectory;
            }

            deployment.Variables.Set(SpecialVariables.Tentacle.PreviousInstallation.OriginalInstalledPath, previousExtractedTo);
            deployment.Variables.Set(SpecialVariables.Tentacle.PreviousInstallation.CustomInstallationDirectory, previousCustom);
            deployment.Variables.Set(SpecialVariables.Tentacle.PreviousInstallation.PackageFilePath, previousExtractedFrom);
            deployment.Variables.Set(SpecialVariables.Tentacle.PreviousInstallation.PackageVersion, previousVersion);
        }
        public void Install(RunningDeployment deployment)
        {
            if (deployment.Variables.GetFlag(SpecialVariables.Action.Azure.CloudServicePackageExtractionDisabled, false))
                return;

            Log.Verbose("Re-packaging cspkg.");
            var workingDirectory = deployment.CurrentDirectory;
            var originalPackagePath = deployment.Variables.Get(SpecialVariables.Action.Azure.CloudServicePackagePath);
            var newPackagePath = Path.Combine(Path.GetDirectoryName(originalPackagePath), Path.GetFileNameWithoutExtension(originalPackagePath) + "_repacked.cspkg");
            using (var originalPackage = Package.Open(originalPackagePath, FileMode.Open))
            using (var newPackage = Package.Open(newPackagePath, FileMode.CreateNew))
            {
                var originalManifest = AzureCloudServiceConventions.ReadPackageManifest(originalPackage);

                var newManifest = new PackageDefinition
                {
                    MetaData = {AzureVersion = originalManifest.MetaData.AzureVersion}
                };

                AddParts(newPackage, newManifest, Path.Combine(workingDirectory, AzureCloudServiceConventions.PackageFolders.ServiceDefinition),
                    AzureCloudServiceConventions.PackageFolders.ServiceDefinition);
                AddParts(newPackage, newManifest, Path.Combine(workingDirectory, AzureCloudServiceConventions.PackageFolders.NamedStreams),
                    AzureCloudServiceConventions.PackageFolders.NamedStreams);
                AddLocalContent(newPackage, newManifest, workingDirectory);

                AddPackageManifest(newPackage, newManifest);

                newPackage.Flush();
            }

            fileSystem.OverwriteAndDelete(originalPackagePath, newPackagePath);
        }
        public void Install(RunningDeployment deployment)
        {
            Log.Info("Config file: " + deployment.Variables.Get(ConfigureAzureCloudServiceConvention.ConfigurationFileVariable));

            Log.SetOutputVariable("OctopusAzureServiceName", deployment.Variables.Get(SpecialVariables.Action.Azure.CloudServiceName), deployment.Variables);
            Log.SetOutputVariable("OctopusAzureStorageAccountName", deployment.Variables.Get(SpecialVariables.Action.Azure.StorageAccountName), deployment.Variables);
            Log.SetOutputVariable("OctopusAzureSlot", deployment.Variables.Get(SpecialVariables.Action.Azure.Slot), deployment.Variables);
            Log.SetOutputVariable("OctopusAzurePackageUri", deployment.Variables.Get(SpecialVariables.Action.Azure.UploadedPackageUri), deployment.Variables);
            Log.SetOutputVariable("OctopusAzureDeploymentLabel", deployment.Variables.Get(SpecialVariables.Action.Name) + " v" + deployment.Variables.Get(SpecialVariables.Release.Number), deployment.Variables);
            Log.SetOutputVariable("OctopusAzureSwapIfPossible", deployment.Variables.Get(SpecialVariables.Action.Azure.SwapIfPossible, defaultValue: false.ToString()), deployment.Variables);
            Log.SetOutputVariable("OctopusAzureUseCurrentInstanceCount", deployment.Variables.Get(SpecialVariables.Action.Azure.UseCurrentInstanceCount), deployment.Variables);

            // The script name 'DeployToAzure.ps1' is used for backwards-compatibility
            var scriptFile = Path.Combine(deployment.CurrentDirectory, "DeployToAzure.ps1");

            // The user may supply the script, to override behaviour
            if (!fileSystem.FileExists(scriptFile))
            {
               fileSystem.OverwriteFile(scriptFile, embeddedResources.GetEmbeddedResourceText("Calamari.Scripts.DeployAzureCloudService.ps1"));
            }

            var result = scriptEngine.Execute(scriptFile, deployment.Variables, commandLineRunner);

            fileSystem.DeleteFile(scriptFile, DeletionOptions.TryThreeTimesIgnoreFailure);

            if (result.ExitCode != 0)
            {
                throw new CommandException(string.Format("Script '{0}' returned non-zero exit code: {1}", scriptFile,
                    result.ExitCode));
            }
        }
        public void Install(RunningDeployment deployment)
        {
            if (!deployment.Variables.GetFlag(SpecialVariables.Package.UpdateIisWebsite))
                return;

            var iisSiteName = deployment.Variables.Get(SpecialVariables.Package.UpdateIisWebsiteName);
            if (string.IsNullOrWhiteSpace(iisSiteName))
            {
                iisSiteName = deployment.Variables.Get(SpecialVariables.Package.NuGetPackageId);
            }

            var webRoot = GetRootMostDirectoryContainingWebConfig(deployment);
            if (webRoot == null)
                throw new CommandException("A web.config file was not found, so no IIS configuration will be performed. To turn off this feature, use the 'Configure features' link in the deployment step configuration to disable IIS updates.");

            // In situations where the IIS version cannot be correctly determined automatically,
            // this variable can be set to force IIS6 compatibility.
            var legacySupport = deployment.Variables.GetFlag(SpecialVariables.UseLegacyIisSupport);

            var updated = iis.OverwriteHomeDirectory(iisSiteName, webRoot, legacySupport);

            if (!updated)
                throw new CommandException(
                    string.Format(
                        "Could not find an IIS website or virtual directory named '{0}' on the local machine. You need to create the site and/or virtual directory manually. To turn off this feature, use the 'Configure features' link in the deployment step configuration to disable IIS updates.", 
                        iisSiteName));

            Log.Info("The IIS website named '{0}' has had its path updated to: '{1}'", iisSiteName, webRoot);
        }
 public void Install(RunningDeployment deployment)
 {
     RunScripts(deployment);
     if (deployment.Variables.GetFlag(SpecialVariables.DeleteScriptsOnCleanup, true))
     {
         DeleteScripts(deployment);
     }
 }
        public void Install(RunningDeployment deployment)
        {
            // Allow scripts and other conventions to access environment variables. 
            // For example, #{env:SystemRoot} is equivalent to %SystemRoot%
            // This technique is also used for Tentacle (the host process that invokes Calamari) to pass variables in

            deployment.Variables.EnrichWithEnvironmentVariables();
        }
        string ChooseWhichConfigurationFileToUse(RunningDeployment deployment)
        {
            var configurationFilePath = GetFirstExistingFile(deployment,
                deployment.Variables.Get(SpecialVariables.Action.Azure.CloudServiceConfigurationFileRelativePath),
                BuildEnvironmentSpecificFallbackFileName(deployment),
                FallbackFileName);

            return configurationFilePath;
        }
        void DeleteScripts(RunningDeployment deployment)
        {
            var scripts = FindScripts(deployment);

            foreach (var script in scripts)
            {
                fileSystem.DeleteFile(script, FailureOptions.IgnoreFailure);
            }
        }
        protected override string GetTargetPath(RunningDeployment deployment, PackageMetadata metadata)
        {
            var packageExtractionPathVariable = deployment.Variables[SpecialVariables.Action.Azure.PackageExtractionPath];

            // The PackageExtractionPath variable will always be provided by the OD server, but just in case Calamari is run
            // stand-alone, we will fall-back to a temporary path
            return !string.IsNullOrWhiteSpace(packageExtractionPathVariable)
                ? packageExtractionPathVariable
                : fileSystem.CreateTemporaryDirectory();
        }
        public void Install(RunningDeployment deployment)
        {
            var configurationFile = ChooseWhichConfigurationFileToUse(deployment);
            Log.SetOutputVariable(ConfigurationFileVariable, configurationFile, deployment.Variables);

            var configuration = XDocument.Parse(fileSystem.ReadFile(configurationFile));
            UpdateConfigurationWithCurrentInstanceCount(configuration, configurationFile, deployment.Variables);
            UpdateConfigurationSettings(configuration, deployment.Variables);
            SaveConfigurationFile(configuration, configurationFile);
        }
 IEnumerable<string> FindScripts(RunningDeployment deployment)
 {
     var supportedScriptExtensions = scriptEngine.GetSupportedExtensions();
     var searchPatterns = supportedScriptExtensions.Select(e => "*." + e).ToArray();
     return
         from file in fileSystem.EnumerateFiles(deployment.CurrentDirectory, searchPatterns)
         let nameWithoutExtension = Path.GetFileNameWithoutExtension(file)
         where nameWithoutExtension.Equals(scriptFilePrefix, StringComparison.OrdinalIgnoreCase)
         select file;
 }
        public void Install(RunningDeployment deployment)
        {
            // Validate we actually have a real path to the real config file since this value is potentially passed via variable or a previous convention
            var configurationFilePath = deployment.Variables.Get(SpecialVariables.Action.Azure.Output.ConfigurationFile);
            if (!fileSystem.FileExists(configurationFilePath))
                throw new CommandException("Could not find the Azure Cloud Service Configuration file: " + configurationFilePath);

            var configuration = XDocument.Parse(fileSystem.ReadFile(configurationFilePath));
            UpdateConfigurationWithCurrentInstanceCount(configuration, configurationFilePath, deployment.Variables);
            UpdateConfigurationSettings(configuration, deployment.Variables);
            SaveConfigurationFile(configuration, configurationFilePath);
        }
        string GetRootMostDirectoryContainingWebConfig(RunningDeployment deployment)
        {
            // Optimize for most common case.
            if (fileSystem.FileExists(Path.Combine(deployment.CurrentDirectory, "Web.config")))
            {
                return deployment.CurrentDirectory;
            }

            // Find all folders under package root and sort them by depth
            var dirs = fileSystem.EnumerateDirectoriesRecursively(deployment.CurrentDirectory).ToList();
            return dirs.OrderBy(x => x.Count(c => c == '\\')).FirstOrDefault(dir => fileSystem.FileExists(Path.Combine(dir, "Web.config")));
        }
        public void Install(RunningDeployment deployment)
        {
            if (deployment.Variables.GetFlag(SpecialVariables.Package.GenerateAppSettingsJson) == false)
            {
                return;
            }

            var path = deployment.Variables.Get(SpecialVariables.Package.AppSettingsJsonPath);
            if (string.IsNullOrWhiteSpace(path))
                return;

            appSettings.Generate(path, deployment.Variables);
        }
        protected void RunScripts(RunningDeployment deployment)
        {
            var scripts = FindScripts(deployment);

            foreach (var script in scripts)
            {
                var result = scriptEngine.Execute(script, deployment.Variables, commandLineRunner);
                if (result.ExitCode != 0)
                {
                    throw new CommandException(string.Format("Script '{0}' returned non-zero exit code: {1}. Deployment terminated.", script, result.ExitCode));
                }
            }
        }
Exemple #21
0
 public JournalEntry(RunningDeployment deployment, bool wasSuccessful)
     : this(Guid.NewGuid().ToString(),
         deployment.Variables.Get(SpecialVariables.Environment.Id),
         deployment.Variables.Get(SpecialVariables.Project.Id),
         deployment.Variables.Get(SpecialVariables.Package.NuGetPackageId),
         deployment.Variables.Get(SpecialVariables.Package.NuGetPackageVersion),
         deployment.Variables.Get(SpecialVariables.RetentionPolicySet),
         DateTime.UtcNow,
         deployment.PackageFilePath,
         deployment.Variables.Get(SpecialVariables.OriginalPackageDirectoryPath),
         deployment.Variables.Get(SpecialVariables.Package.CustomInstallationDirectory),
         wasSuccessful
     )
 { }
        public void Install(RunningDeployment deployment)
        {
            var features = deployment.Variables.GetStrings(SpecialVariables.Package.EnabledFeatures).Where(s => !string.IsNullOrWhiteSpace(s)).ToList();

            if (!features.Any())
                return;

            var embeddedResourceNames = new HashSet<string>(embeddedResources.GetEmbeddedResourceNames());

            foreach (var featureScript in features.SelectMany(GetScriptNames))
            {
                // Determine the embedded-resource name
                var scriptEmbeddedResource = GetEmbeddedResourceName(featureScript);

                // If there is a matching embedded resource
                if (!embeddedResourceNames.Contains(scriptEmbeddedResource))
                    continue;

                var scriptFile = Path.Combine(deployment.CurrentDirectory, featureScript);

                // To execute the script, we need a physical file on disk. 
                // If one already exists, we don't recreate it, as this provides a handy
                // way to override behaviour.
                if (!fileSystem.FileExists(scriptFile))
                {
                    Log.VerboseFormat("Creating '{0}' from embedded resource", scriptFile);
                    fileSystem.OverwriteFile(scriptFile, embeddedResources.GetEmbeddedResourceText(scriptEmbeddedResource));
                }
                else
                {
                    Log.WarnFormat("Did not overwrite '{0}', it was already on disk", scriptFile);
                }

                // Execute the script
                Log.VerboseFormat("Executing '{0}'", scriptFile);
                var result = scriptEngine.Execute(scriptFile, deployment.Variables, commandLineRunner);

                // And then delete it
                Log.VerboseFormat("Deleting '{0}'", scriptFile);
                fileSystem.DeleteFile(scriptFile, FailureOptions.IgnoreFailure);

                if (result.ExitCode != 0)
                {
                    throw new CommandException(string.Format("Script '{0}' returned non-zero exit code: {1}", scriptFile,
                        result.ExitCode));
                }
            }
        }
        string GetFirstExistingFile(RunningDeployment deployment, params string[] fileNames)
        {
            foreach (var name in fileNames)
            {
                if (string.IsNullOrWhiteSpace(name))
                    continue;

                var path = Path.Combine(deployment.CurrentDirectory, name);
                if (fileSystem.FileExists(path))
                {
                    Log.Verbose("Found Azure Cloud Service Configuration file: " + path);
                    return path;
                }

                Log.Verbose("Azure Cloud Service Configuration file (*.cscfg) not found: " + path);
            }

            throw new CommandException(
                "Could not find an Azure Cloud Service Configuration file (*.cscfg) in the package.");
        }
        public void Install(RunningDeployment deployment)
        {
            if (deployment.Variables.GetFlag(SpecialVariables.Action.Azure.CloudServicePackageExtractionDisabled, false))
                return;

            var packagePath = deployment.Variables.Get(SpecialVariables.Action.Azure.CloudServicePackagePath);
            Log.VerboseFormat("Extracting Cloud Service package: '{0}'", packagePath);
            using (var package = Package.Open(packagePath, FileMode.Open))
            {
                var manifest = AzureCloudServiceConventions.ReadPackageManifest(package);
                var workingDirectory = deployment.CurrentDirectory;

                ExtractContents(package, manifest, AzureCloudServiceConventions.PackageFolders.ServiceDefinition, workingDirectory);
                ExtractContents(package, manifest, AzureCloudServiceConventions.PackageFolders.NamedStreams, workingDirectory);
                ExtractLayouts(package, manifest, workingDirectory);
            }

            if (deployment.Variables.GetFlag(SpecialVariables.Action.Azure.LogExtractedCspkg))
                LogExtractedPackage(deployment.CurrentDirectory);
        }
        public void Install(RunningDeployment deployment)
        {
            var package = deployment.Variables.Get(SpecialVariables.Action.Azure.CloudServicePackagePath);
            Log.Info("Uploading package to Azure blob storage: '{0}'", package);
            var packageHash = Hash(package);
            var nugetPackageVersion = deployment.Variables.Get(SpecialVariables.Package.NuGetPackageVersion);
            var uploadedFileName = Path.ChangeExtension(Path.GetFileName(package), "." + nugetPackageVersion + "_" + packageHash + ".cspkg");

            var credentials = credentialsFactory.GetCredentials(
                deployment.Variables.Get(SpecialVariables.Action.Azure.SubscriptionId),
                deployment.Variables.Get(SpecialVariables.Action.Azure.CertificateThumbprint),
                deployment.Variables.Get(SpecialVariables.Action.Azure.CertificateBytes)
                );

            var storageAccountName = deployment.Variables.Get(SpecialVariables.Action.Azure.StorageAccountName);

            var uploadedUri = azurePackageUploader.Upload(credentials, storageAccountName, package, uploadedFileName);

            Log.SetOutputVariable(SpecialVariables.Action.Azure.UploadedPackageUri, uploadedUri.ToString(), deployment.Variables);
            Log.Info("Package uploaded to " + uploadedUri.ToString());
        }
        public void Install(RunningDeployment deployment)
        {
            if (deployment.Variables.GetFlag(SpecialVariables.Action.Azure.CloudServicePackageExtractionDisabled, false))
                return;

            Log.VerboseFormat("Ensuring cloud-service-package is {0} format.", PackageFormats.V20120315.ToString());
            var packagePath = deployment.Variables.Get(SpecialVariables.Action.Azure.CloudServicePackagePath);
            var packageFormat = PackageConverter.GetFormat(packagePath);

            switch (packageFormat)
            {
                case PackageFormats.Legacy:
                    Log.VerboseFormat("Package is Legacy format. Converting to {0} format.", PackageFormats.V20120315.ToString());
                    ConvertPackage(packagePath);
                    return;
                case PackageFormats.V20120315:
                    Log.VerboseFormat("Package is {0} format.", PackageFormats.V20120315.ToString());
                    return;
                default:
                    throw new InvalidOperationException("Unexpected PackageFormat: " + packageFormat);
            }
        }
        public void Install(RunningDeployment deployment)
        {
            if (!deployment.Variables.GetFlag(SpecialVariables.Package.SubstituteInFilesEnabled))
                return;

            foreach (var target in deployment.Variables.GetPaths(SpecialVariables.Package.SubstituteInFilesTargets))
            {
                var matchingFiles = fileSystem.EnumerateFiles(deployment.CurrentDirectory, target)
                    .Select(Path.GetFullPath).ToList();

                if (!matchingFiles.Any())
                {
                    Log.WarnFormat("No files were found that match the substitution target pattern '{0}'", target);
                    continue;
                }

                foreach (var file in matchingFiles)
                {
                    Log.Info("Performing variable substitution on '{0}'", file);
                    substituter.PerformSubstitution(file, deployment.Variables);
                }

            }
        }
 static string BuildEnvironmentSpecificFallbackFileName(RunningDeployment deployment)
 {
     return string.Format(EnvironmentFallbackFileName,
         deployment.Variables.Get(SpecialVariables.Environment.Name));
 }
 private void CreateVariables(RunningDeployment context, string targetDiscoveryContextJson)
 {
     context.Variables.Add("Octopus.TargetDiscovery.Context", targetDiscoveryContextJson);
 }
Exemple #30
0
 public void Install(RunningDeployment deployment)
 {
     deployment.Variables.LogVariables();
 }
        private string BuildHelmCommand(RunningDeployment deployment)
        {
            var releaseName = GetReleaseName(deployment.Variables);
            var packagePath = GetChartLocation(deployment);

            var sb = new StringBuilder();

            var helmExecutable = deployment.Variables.Get(SpecialVariables.Helm.CustomHelmExecutable);

            if (!string.IsNullOrWhiteSpace(helmExecutable))
            {
                if (deployment.Variables.GetIndexes(Deployment.SpecialVariables.Packages.PackageCollection)
                    .Contains(SpecialVariables.Helm.Packages.CustomHelmExePackageKey) && !Path.IsPathRooted(helmExecutable))
                {
                    helmExecutable = Path.Combine(SpecialVariables.Helm.Packages.CustomHelmExePackageKey, helmExecutable);
                    Log.Info($"Using custom helm executable at {helmExecutable} from inside package. Full path at {Path.GetFullPath(helmExecutable)}");
                }
                else
                {
                    Log.Info($"Using custom helm executable at {helmExecutable}");
                }

                var scriptType = scriptEngine.GetSupportedTypes();
                if (scriptType.Contains(ScriptSyntax.PowerShell))
                {
                    sb.Append(". "); //With powershell we need to invoke custom executables
                }
                else
                {
                    sb.Append($"chmod +x \"{helmExecutable}\"\n");
                }

                sb.Append($"\"{helmExecutable}\"");
            }
            else
            {
                sb.Append("helm");
            }

            sb.Append($" upgrade");

            if (deployment.Variables.GetFlag(SpecialVariables.Helm.ResetValues, true))
            {
                sb.Append(" --reset-values");
            }

            /*if (deployment.Variables.GetFlag(SpecialVariables.Helm.Install, true))
             * {*/
            sb.Append(" --install");
            /*}*/

            foreach (var additionalValuesFile in AdditionalValuesFiles(deployment))
            {
                sb.Append($" --values \"{additionalValuesFile}\"");
            }

            if (TryAddRawValuesYaml(deployment, out var rawValuesFile))
            {
                sb.Append($" --values \"{rawValuesFile}\"");
            }

            if (TryGenerateVariablesFile(deployment, out var valuesFile))
            {
                sb.Append($" --values \"{valuesFile}\"");
            }

            sb.Append($" \"{releaseName}\" \"{packagePath}\"");

            Log.Verbose(sb.ToString());
            return(sb.ToString());
        }
 public abstract void Install(RunningDeployment deployment);
 public Task Execute(RunningDeployment context)
 {
     substituteInFiles.SubstituteBasedSettingsInSuppliedVariables(context);
     return(this.CompletedTask());
 }
 protected override string GetTargetPath(RunningDeployment deployment, PackageMetadata metadata)
 {
     return(ApplicationDirectory.GetApplicationDirectory(metadata, deployment.Variables, fileSystem));
 }
Exemple #35
0
        public void Install(RunningDeployment deployment)
        {
            string errorString;
            var    customInstallationDirectory = deployment.Variables.Get(SpecialVariables.Package.CustomInstallationDirectory, out errorString);
            var    sourceDirectory             = deployment.Variables.Get(SpecialVariables.OriginalPackageDirectoryPath);

            if (string.IsNullOrWhiteSpace(customInstallationDirectory))
            {
                Log.Verbose("The package has been installed to: " + sourceDirectory);
                Log.VerboseFormat(
                    "If you would like the package to be installed to an alternative location, please specify the variable '{0}'",
                    SpecialVariables.Package.CustomInstallationDirectory);
                // If the variable was not set then we set it, as it makes it simpler for anything to depend on it from this point on
                deployment.Variables.Set(SpecialVariables.Package.CustomInstallationDirectory,
                                         sourceDirectory);

                return;
            }

            if (!string.IsNullOrEmpty(errorString))
            {
                throw new CommandException(
                          $"An error occurred when evaluating the value for the custom install directory. {errorString}");
            }

            if (string.IsNullOrEmpty(Path.GetPathRoot(customInstallationDirectory)))
            {
                throw new CommandException(
                          $"The custom install directory '{customInstallationDirectory}' is a relative path, please specify the path as an absolute path or a UNC path.");
            }

            if (customInstallationDirectory.IsChildDirectoryOf(sourceDirectory))
            {
                throw new CommandException(
                          $"The custom install directory '{customInstallationDirectory}' is a child directory of the base installation directory '{sourceDirectory}', please specify a different destination.");
            }

            try
            {
                // Purge if requested
                if (deployment.Variables.GetFlag(
                        SpecialVariables.Package.CustomInstallationDirectoryShouldBePurgedBeforeDeployment))
                {
                    Log.Info("Purging the directory '{0}'", customInstallationDirectory);
                    fileSystem.PurgeDirectory(deployment.CustomDirectory, FailureOptions.ThrowOnFailure);
                }

                // Copy files from staging area to custom directory
                Log.Info("Copying package contents to '{0}'", customInstallationDirectory);
                int count = fileSystem.CopyDirectory(deployment.StagingDirectory, deployment.CustomDirectory);
                Log.Info("Copied {0} files", count);

                // From this point on, the current directory will be the custom-directory
                deployment.CurrentDirectoryProvider = DeploymentWorkingDirectory.CustomDirectory;

                Log.SetOutputVariable(SpecialVariables.Package.Output.InstallationDirectoryPath, deployment.CustomDirectory, deployment.Variables);
                Log.SetOutputVariable(SpecialVariables.Package.Output.DeprecatedInstallationDirectoryPath, deployment.CustomDirectory, deployment.Variables);
                Log.SetOutputVariable(SpecialVariables.Package.Output.CopiedFileCount, count.ToString(), deployment.Variables);
            }
            catch (UnauthorizedAccessException uae) when(uae.Message.StartsWith("Access to the path"))
            {
                throw new CommandException(
                          $"{uae.Message} Ensure that the application that uses this directory is not running. " +
                          "If this is an IIS website, stop the application pool or use an app_offline.htm file " +
                          "(see https://g.octopushq.com/TakingWebsiteOffline)."
                          );
            }
        }
Exemple #36
0
 public void Cleanup(RunningDeployment deployment)
 {
 }
Exemple #37
0
 public void Rollback(RunningDeployment deployment)
 {
     Run(deployment);
 }
Exemple #38
0
 public void Install(RunningDeployment deployment)
 {
     Run(deployment);
 }
        public override int Execute(string[] commandLineArguments)
        {
            Options.Parse(commandLineArguments);

            Guard.NotNullOrWhiteSpace(pathToPackage, "No package file was specified. Please pass --package YourPackage.nupkg");

            if (!File.Exists(pathToPackage))
            {
                throw new CommandException("Could not find package file: " + pathToPackage);
            }

            Log.Info("Deploying package:    " + pathToPackage);

            var featureClasses = new List <IFeature>();

            var replacer = new ConfigurationVariablesReplacer(variables, log);
            var allFileFormatReplacers           = FileFormatVariableReplacers.BuildAllReplacers(fileSystem, log);
            var structuredConfigVariablesService = new StructuredConfigVariablesService(allFileFormatReplacers, fileSystem, log);
            var configurationTransformer         = ConfigurationTransformer.FromVariables(variables, log);
            var transformFileLocator             = new TransformFileLocator(fileSystem, log);
            var embeddedResources = new AssemblyEmbeddedResources();

#if IIS_SUPPORT
            var iis = new InternetInformationServer();
            featureClasses.AddRange(new IFeature[] { new IisWebSiteBeforeDeployFeature(), new IisWebSiteAfterPostDeployFeature() });
#endif
            if (!CalamariEnvironment.IsRunningOnWindows)
            {
                featureClasses.Add(new NginxFeature(NginxServer.AutoDetect(), fileSystem));
            }

            var semaphore = SemaphoreFactory.Get();
            var journal   = new DeploymentJournal(fileSystem, semaphore, variables);

            var conventions = new List <IConvention>
            {
                new AlreadyInstalledConvention(log, journal),
                new DelegateInstallConvention(d => extractPackage.ExtractToApplicationDirectory(pathToPackage)),
                new FeatureConvention(DeploymentStages.BeforePreDeploy, featureClasses, fileSystem, scriptEngine, commandLineRunner, embeddedResources),
                new ConfiguredScriptConvention(new PreDeployConfiguredScriptBehaviour(log, fileSystem, scriptEngine, commandLineRunner)),
                new PackagedScriptConvention(new PreDeployPackagedScriptBehaviour(log, fileSystem, scriptEngine, commandLineRunner)),
                new FeatureConvention(DeploymentStages.AfterPreDeploy, featureClasses, fileSystem, scriptEngine, commandLineRunner, embeddedResources),
                new SubstituteInFilesConvention(new SubstituteInFilesBehaviour(substituteInFiles)),
                new ConfigurationTransformsConvention(new ConfigurationTransformsBehaviour(fileSystem, configurationTransformer, transformFileLocator, log)),
                new ConfigurationVariablesConvention(new ConfigurationVariablesBehaviour(fileSystem, replacer, log)),
                new StructuredConfigurationVariablesConvention(new StructuredConfigurationVariablesBehaviour(structuredConfigVariablesService)),
                new CopyPackageToCustomInstallationDirectoryConvention(fileSystem),
                new FeatureConvention(DeploymentStages.BeforeDeploy, featureClasses, fileSystem, scriptEngine, commandLineRunner, embeddedResources),
                new PackagedScriptConvention(new DeployPackagedScriptBehaviour(log, fileSystem, scriptEngine, commandLineRunner)),
                new ConfiguredScriptConvention(new DeployConfiguredScriptBehaviour(log, fileSystem, scriptEngine, commandLineRunner)),
                new FeatureConvention(DeploymentStages.AfterDeploy, featureClasses, fileSystem, scriptEngine, commandLineRunner, embeddedResources),
#if IIS_SUPPORT
                new LegacyIisWebSiteConvention(fileSystem, iis),
#endif
                new FeatureConvention(DeploymentStages.BeforePostDeploy, featureClasses, fileSystem, scriptEngine, commandLineRunner, embeddedResources),
                new PackagedScriptConvention(new PostDeployPackagedScriptBehaviour(log, fileSystem, scriptEngine, commandLineRunner)),
                new ConfiguredScriptConvention(new PostDeployConfiguredScriptBehaviour(log, fileSystem, scriptEngine, commandLineRunner)),
                new FeatureConvention(DeploymentStages.AfterPostDeploy, featureClasses, fileSystem, scriptEngine, commandLineRunner, embeddedResources),
                new RollbackScriptConvention(log, DeploymentStages.DeployFailed, fileSystem, scriptEngine, commandLineRunner),
                new FeatureRollbackConvention(DeploymentStages.DeployFailed, fileSystem, scriptEngine, commandLineRunner, embeddedResources)
            };

            var deployment       = new RunningDeployment(pathToPackage, variables);
            var conventionRunner = new ConventionProcessor(deployment, conventions, log);

            try
            {
                conventionRunner.RunConventions();
                if (!deployment.SkipJournal)
                {
                    journal.AddJournalEntry(new JournalEntry(deployment, true));
                }
            }
            catch (Exception)
            {
                if (!deployment.SkipJournal)
                {
                    journal.AddJournalEntry(new JournalEntry(deployment, false));
                }
                throw;
            }

            return(0);
        }
Exemple #40
0
 public WarPackageProvider(ILog log, IVariables variables, RunningDeployment deployment)
 {
     Log        = log;
     Variables  = variables;
     Deployment = deployment;
 }
 public bool IsEnabled(RunningDeployment context)
 {
     return(context.Variables.IsFeatureEnabled(KnownVariables.Features.SubstituteInFiles));
 }
Exemple #42
0
        /// <summary>
        /// Uploads the given package file with the provided package options
        /// </summary>
        /// <param name="clientFactory"></param>
        /// <param name="deployment"></param>
        /// <param name="options"></param>
        public Task <S3UploadResult> UploadUsingPackage(Func <AmazonS3Client> clientFactory, RunningDeployment deployment, S3PackageOptions options)
        {
            Guard.NotNull(deployment, "Deployment may not be null");
            Guard.NotNull(options, "Package options may not be null");
            Guard.NotNull(clientFactory, "Client factory must not be null");

            var filename = GetNormalizedPackageFilename(deployment);

            return(CreateRequest(deployment.PackageFilePath,
                                 GetBucketKey(filename, options), options)
                   .Tee(x => LogPutObjectRequest("entire package", x))
                   .Map(x => HandleUploadRequest(clientFactory(), x, ThrowInvalidFileUpload)));
        }
Exemple #43
0
        public override int Execute(string[] commandLineArguments)
        {
            Options.Parse(commandLineArguments);

            Guard.NotNullOrWhiteSpace(packageFile, "No package file was specified. Please pass --package YourPackage.nupkg");

            if (!File.Exists(packageFile))
            {
                throw new CommandException("Could not find package file: " + packageFile);
            }

            if (variablesFile != null && !File.Exists(variablesFile))
            {
                throw new CommandException("Could not find variables file: " + variablesFile);
            }

            Log.Info("Deploying package:    " + packageFile);
            var variables = new CalamariVariableDictionary(variablesFile, sensitiveVariableFiles, sensitiveVariablesPassword);

            var account = (AzureAccount)AccountFactory.Create(variables);

            var fileSystem                         = new WindowsPhysicalFileSystem();
            var embeddedResources                  = new AssemblyEmbeddedResources();
            var commandLineRunner                  = new CommandLineRunner(new SplitCommandOutput(new ConsoleCommandOutput(), new ServiceMessageCommandOutput(variables)));
            var azurePackageUploader               = new AzurePackageUploader();
            var certificateStore                   = new CalamariCertificateStore();
            var cloudCredentialsFactory            = new SubscriptionCloudCredentialsFactory(certificateStore);
            var cloudServiceConfigurationRetriever = new AzureCloudServiceConfigurationRetriever();
            var substituter                        = new FileSubstituter(fileSystem);
            var configurationTransformer           = ConfigurationTransformer.FromVariables(variables);
            var transformFileLocator               = new TransformFileLocator(fileSystem);
            var replacer = new ConfigurationVariablesReplacer(variables.GetFlag(SpecialVariables.Package.IgnoreVariableReplacementErrors));
            var jsonVariablesReplacer = new JsonConfigurationVariableReplacer();

            var conventions = new List <IConvention>
            {
                new ContributeEnvironmentVariablesConvention(),
                new LogVariablesConvention(),
                new SwapAzureDeploymentConvention(fileSystem, embeddedResources, scriptEngine, commandLineRunner),
                new ExtractPackageToStagingDirectoryConvention(new GenericPackageExtractorFactory().createStandardGenericPackageExtractor(), fileSystem),
                new FindCloudServicePackageConvention(fileSystem),
                new EnsureCloudServicePackageIsCtpFormatConvention(fileSystem),
                new ExtractAzureCloudServicePackageConvention(fileSystem),
                new ChooseCloudServiceConfigurationFileConvention(fileSystem),
                new ConfiguredScriptConvention(DeploymentStages.PreDeploy, fileSystem, scriptEngine, commandLineRunner),
                new PackagedScriptConvention(DeploymentStages.PreDeploy, fileSystem, scriptEngine, commandLineRunner),
                new ConfigureAzureCloudServiceConvention(account, fileSystem, cloudCredentialsFactory, cloudServiceConfigurationRetriever, certificateStore),
                new SubstituteInFilesConvention(fileSystem, substituter),
                new ConfigurationTransformsConvention(fileSystem, configurationTransformer, transformFileLocator),
                new ConfigurationVariablesConvention(fileSystem, replacer),
                new JsonConfigurationVariablesConvention(jsonVariablesReplacer, fileSystem),
                new PackagedScriptConvention(DeploymentStages.Deploy, fileSystem, scriptEngine, commandLineRunner),
                new ConfiguredScriptConvention(DeploymentStages.Deploy, fileSystem, scriptEngine, commandLineRunner),
                new RePackageCloudServiceConvention(fileSystem),
                new UploadAzureCloudServicePackageConvention(fileSystem, azurePackageUploader, cloudCredentialsFactory),
                new DeployAzureCloudServicePackageConvention(fileSystem, embeddedResources, scriptEngine, commandLineRunner),
                new PackagedScriptConvention(DeploymentStages.PostDeploy, fileSystem, scriptEngine, commandLineRunner),
                new ConfiguredScriptConvention(DeploymentStages.PostDeploy, fileSystem, scriptEngine, commandLineRunner)
            };

            var deployment       = new RunningDeployment(packageFile, variables);
            var conventionRunner = new ConventionProcessor(deployment, conventions);

            conventionRunner.RunConventions();

            return(0);
        }
 string SyntaxSpecificFileName(RunningDeployment deployment, ScriptSyntax syntax)
 {
     return(Path.Combine(deployment.CurrentDirectory, syntax == ScriptSyntax.PowerShell ? "Calamari.HelmUpgrade.ps1" : "Calamari.HelmUpgrade.sh"));
 }
Exemple #45
0
 public override void Install(RunningDeployment deployment)
 {
     InstallAsync(deployment).GetAwaiter().GetResult();
 }
 protected override string GetTargetPath(RunningDeployment deployment, PackageMetadata metadata)
 {
     var root = GetInitialExtractionDirectory(deployment.Variables);
     return EnsureTargetPathIsEmpty(Path.Combine(root, metadata.Id, metadata.Version));
 }
Exemple #47
0
        /// <summary>
        /// Uploads a single file with the given properties
        /// </summary>
        /// <param name="clientFactory"></param>
        /// <param name="deployment"></param>
        /// <param name="selection"></param>
        public Task <S3UploadResult> UploadSingleFileSelection(Func <AmazonS3Client> clientFactory, RunningDeployment deployment, S3SingleFileSelectionProperties selection)
        {
            Guard.NotNull(deployment, "Deployment may not be null");
            Guard.NotNull(selection, "Single file selection properties may not be null");
            Guard.NotNull(clientFactory, "Client factory must not be null");

            var filePath = Path.Combine(deployment.StagingDirectory, selection.Path);

            if (!fileSystem.FileExists(filePath))
            {
                throw new FileNotFoundException($"The file {selection.Path} could not be found in the package.");
            }

            if (selection.PerformVariableSubstitution)
            {
                substituteInFiles.Substitute(deployment, new List <string> {
                    filePath
                });
            }

            return(CreateRequest(filePath, GetBucketKey(filePath.AsRelativePathFrom(deployment.StagingDirectory), selection), selection)
                   .Tee(x => LogPutObjectRequest(filePath, x))
                   .Map(x => HandleUploadRequest(clientFactory(), x, ThrowInvalidFileUpload)));
        }
Exemple #48
0
 public void Install(RunningDeployment deployment)
 {
     deployment.Variables.Set(SpecialVariables.Action.Azure.CloudServicePackagePath, FindPackage(deployment.CurrentDirectory));
 }
        string GetTargetPath(RunningDeployment deployment, PackageMetadata metadata)
        {
            var root = GetInitialExtractionDirectory(deployment.Variables);

            return(Path.Combine(root, metadata.Id, metadata.Version));
        }
 private bool ChangesetsEnabled(RunningDeployment deployment)
 {
     return(deployment.Variables.Get(SpecialVariables.Package.EnabledFeatures)
            ?.Contains(AwsSpecialVariables.CloudFormation.Changesets.Feature) ?? false);
 }
 public bool IsEnabled(RunningDeployment context)
 {
     return
         (!string.IsNullOrWhiteSpace(context.Variables.Get(SpecialVariables.Action.Azure.AppSettings)) ||
          !string.IsNullOrWhiteSpace(context.Variables.Get(SpecialVariables.Action.Azure.ConnectionStrings)));
 }
 private bool ChangesetsDisabled(RunningDeployment deployment)
 {
     return(!ChangesetsEnabled(deployment));
 }
 public void Install(RunningDeployment deployment)
 {
     var configurationFile = ChooseWhichConfigurationFileToUse(deployment);
     Log.SetOutputVariable(SpecialVariables.Action.Azure.Output.ConfigurationFile,
         configurationFile, deployment.Variables);
 }
        public override int Execute(string[] commandLineArguments)
        {
            Options.Parse(commandLineArguments);
            if (variablesFile != null && !File.Exists(variablesFile))
            {
                throw new CommandException("Could not find variables file: " + variablesFile);
            }

            var variables = new CalamariVariableDictionary(variablesFile, sensitiveVariablesFile,
                                                           sensitiveVariablesPassword);

            var fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem();

            var filesInPackage   = !string.IsNullOrWhiteSpace(packageFile);
            var environment      = AwsEnvironmentGeneration.Create(variables).GetAwaiter().GetResult();
            var templateResolver = new TemplateResolver(fileSystem);

            IAmazonCloudFormation ClientFactory() => ClientHelpers.CreateCloudFormationClient(environment);
            StackArn StackProvider(RunningDeployment x) => new StackArn(stackName);
            ChangeSetArn ChangesetProvider(RunningDeployment x) => new ChangeSetArn(x.Variables[AwsSpecialVariables.CloudFormation.Changesets.Arn]);
            string RoleArnProvider(RunningDeployment x) => x.Variables[AwsSpecialVariables.CloudFormation.RoleArn];

            CloudFormationTemplate TemplateFactory()
            {
                var resolvedTemplate   = templateResolver.Resolve(templateFile, filesInPackage, variables);
                var resolvedParameters = templateResolver.MaybeResolve(templateParameterFile, filesInPackage, variables);

                if (templateParameterFile != null && !resolvedParameters.Some())
                {
                    throw new CommandException("Could not find template parameters file: " + templateParameterFile);
                }

                var parameters = CloudFormationParametersFile.Create(resolvedParameters, fileSystem, variables);

                return(CloudFormationTemplate.Create(resolvedTemplate, parameters, fileSystem, variables));
            }

            var stackEventLogger = new StackEventLogger(new LogWrapper());

            var conventions = new List <IConvention>
            {
                new LogAwsUserInfoConvention(environment),
                new ContributeEnvironmentVariablesConvention(),
                new LogVariablesConvention(),
                new ExtractPackageToStagingDirectoryConvention(new GenericPackageExtractorFactory().createStandardGenericPackageExtractor(), fileSystem),

                //Create or Update the stack using changesets
                new AggregateInstallationConvention(
                    new GenerateCloudFormationChangesetNameConvention(),
                    new CreateCloudFormationChangeSetConvention(ClientFactory, stackEventLogger, StackProvider, RoleArnProvider, TemplateFactory, iamCapabilities),
                    new DescribeCloudFormationChangeSetConvention(ClientFactory, stackEventLogger, StackProvider, ChangesetProvider),
                    new ExecuteCloudFormationChangeSetConvention(ClientFactory, stackEventLogger, StackProvider, ChangesetProvider, waitForComplete)
                    .When(ImmediateChangesetExecution),
                    new CloudFormationOutputsAsVariablesConvention(ClientFactory, stackEventLogger, StackProvider, () => TemplateFactory().HasOutputs)
                    .When(ImmediateChangesetExecution)
                    ).When(ChangesetsEnabled),

                //Create or update stack using a template (no changesets)
                new AggregateInstallationConvention(
                    new  DeployAwsCloudFormationConvention(
                        ClientFactory,
                        TemplateFactory,
                        stackEventLogger,
                        StackProvider,
                        RoleArnProvider,
                        waitForComplete,
                        stackName,
                        iamCapabilities,
                        disableRollback,
                        environment),
                    new CloudFormationOutputsAsVariablesConvention(ClientFactory, stackEventLogger, StackProvider, () => TemplateFactory().HasOutputs)
                    )
                .When(ChangesetsDisabled)
            };

            var deployment       = new RunningDeployment(packageFile, variables);
            var conventionRunner = new ConventionProcessor(deployment, conventions);

            conventionRunner.RunConventions();
            return(0);
        }
Exemple #55
0
        public override int Execute(string[] commandLineArguments)
        {
            Options.Parse(commandLineArguments);

            var filesInPackage   = !string.IsNullOrWhiteSpace(pathToPackage);
            var environment      = AwsEnvironmentGeneration.Create(log, variables).GetAwaiter().GetResult();
            var templateResolver = new TemplateResolver(fileSystem);

            IAmazonCloudFormation ClientFactory() => ClientHelpers.CreateCloudFormationClient(environment);
            StackArn StackProvider(RunningDeployment x) => new StackArn(stackName);
            ChangeSetArn ChangesetProvider(RunningDeployment x) => new ChangeSetArn(x.Variables[AwsSpecialVariables.CloudFormation.Changesets.Arn]);
            string RoleArnProvider(RunningDeployment x) => x.Variables[AwsSpecialVariables.CloudFormation.RoleArn];

            var iamCapabilities = JsonConvert.DeserializeObject <List <string> >(variables.Get(AwsSpecialVariables.IamCapabilities, "[]"));
            var tags            = JsonConvert.DeserializeObject <List <KeyValuePair <string, string> > >(variables.Get(AwsSpecialVariables.CloudFormation.Tags, "[]"));
            var deployment      = new RunningDeployment(pathToPackage, variables);

            ICloudFormationRequestBuilder TemplateFactory() => string.IsNullOrWhiteSpace(templateS3Url)
                ? CloudFormationTemplate.Create(templateResolver,
                                                templateFile,
                                                templateParameterFile,
                                                filesInPackage,
                                                fileSystem,
                                                variables,
                                                stackName,
                                                iamCapabilities,
                                                disableRollback,
                                                RoleArnProvider(deployment),
                                                tags,
                                                StackProvider(deployment),
                                                ClientFactory)
                : CloudFormationS3Template.Create(templateS3Url,
                                                  templateParameterS3Url,
                                                  fileSystem,
                                                  variables,
                                                  log,
                                                  stackName,
                                                  iamCapabilities,
                                                  disableRollback,
                                                  RoleArnProvider(deployment),
                                                  tags,
                                                  StackProvider(deployment),
                                                  ClientFactory);

            var stackEventLogger = new StackEventLogger(log);

            var conventions = new List <IConvention>
            {
                new LogAwsUserInfoConvention(environment),
                new DelegateInstallConvention(d => extractPackage.ExtractToStagingDirectory(pathToPackage)),
                new StructuredConfigurationVariablesConvention(new StructuredConfigurationVariablesBehaviour(structuredConfigVariablesService)),

                //Create or Update the stack using changesets
                new AggregateInstallationConvention(
                    new GenerateCloudFormationChangesetNameConvention(log),
                    new CreateCloudFormationChangeSetConvention(ClientFactory,
                                                                stackEventLogger,
                                                                StackProvider,
                                                                TemplateFactory),
                    new DescribeCloudFormationChangeSetConvention(ClientFactory, stackEventLogger, StackProvider, ChangesetProvider),
                    new ExecuteCloudFormationChangeSetConvention(ClientFactory,
                                                                 stackEventLogger,
                                                                 StackProvider,
                                                                 ChangesetProvider,
                                                                 waitForComplete)
                    .When(ImmediateChangesetExecution),
                    new CloudFormationOutputsAsVariablesConvention(ClientFactory, stackEventLogger, StackProvider)
                    .When(ImmediateChangesetExecution)
                    ).When(ChangesetsEnabled),

                //Create or update stack using a template (no changesets)
                new AggregateInstallationConvention(
                    new DeployAwsCloudFormationConvention(
                        ClientFactory,
                        TemplateFactory,
                        stackEventLogger,
                        StackProvider,
                        RoleArnProvider,
                        waitForComplete,
                        stackName,
                        environment),
                    new CloudFormationOutputsAsVariablesConvention(ClientFactory, stackEventLogger, StackProvider)
                    )
                .When(ChangesetsDisabled)
            };

            var conventionRunner = new ConventionProcessor(deployment, conventions, log);

            conventionRunner.RunConventions();
            return(0);
        }
Exemple #56
0
 public bool IsEnabled(RunningDeployment context)
 {
     return(false);
 }
 private bool ChangesetsDeferred(RunningDeployment deployment)
 {
     return(string.Compare(deployment.Variables[AwsSpecialVariables.CloudFormation.Changesets.Defer], bool.TrueString,
                           StringComparison.OrdinalIgnoreCase) == 0);
 }
 private bool ImmediateChangesetExecution(RunningDeployment deployment)
 {
     return(!ChangesetsDeferred(deployment));
 }
        public override int Execute(string[] commandLineArguments)
        {
            Options.Parse(commandLineArguments);

            Guard.NotNullOrWhiteSpace(packageFile, "No package file was specified. Please pass --package YourPackage.nupkg");

            if (!File.Exists(packageFile))
            {
                throw new CommandException("Could not find package file: " + packageFile);
            }

            Log.Info("Deploying package:    " + packageFile);

            var fileSystem = CalamariPhysicalFileSystem.GetPhysicalFileSystem();

            var variables = new CalamariVariableDictionary(variablesFile, sensitiveVariablesFile, sensitiveVariablesPassword);

            fileSystem.FreeDiskSpaceOverrideInMegaBytes = variables.GetInt32(SpecialVariables.FreeDiskSpaceOverrideInMegaBytes);
            fileSystem.SkipFreeDiskSpaceCheck           = variables.GetFlag(SpecialVariables.SkipFreeDiskSpaceCheck);

            var scriptCapability         = new CombinedScriptEngine();
            var replacer                 = new ConfigurationVariablesReplacer(variables.GetFlag(SpecialVariables.Package.IgnoreVariableReplacementErrors));
            var generator                = new JsonConfigurationVariableReplacer();
            var substituter              = new FileSubstituter(fileSystem);
            var configurationTransformer = new ConfigurationTransformer(variables.GetFlag(SpecialVariables.Package.IgnoreConfigTransformationErrors), variables.GetFlag(SpecialVariables.Package.SuppressConfigTransformationLogging));
            var embeddedResources        = new CallingAssemblyEmbeddedResources();
            var iis = new InternetInformationServer();
            var commandLineRunner = new CommandLineRunner(new SplitCommandOutput(new ConsoleCommandOutput(), new ServiceMessageCommandOutput(variables)));
            var semaphore         = new SystemSemaphore();
            var journal           = new DeploymentJournal(fileSystem, semaphore, variables);

            var conventions = new List <IConvention>
            {
                new ContributeEnvironmentVariablesConvention(),
                new ContributePreviousInstallationConvention(journal),
                new LogVariablesConvention(),
                new AlreadyInstalledConvention(journal),
                new ExtractPackageToApplicationDirectoryConvention(new GenericPackageExtractor(), fileSystem, semaphore),
                new FeatureScriptConvention(DeploymentStages.BeforePreDeploy, fileSystem, embeddedResources, scriptCapability, commandLineRunner),
                new ConfiguredScriptConvention(DeploymentStages.PreDeploy, scriptCapability, fileSystem, commandLineRunner),
                new PackagedScriptConvention(DeploymentStages.PreDeploy, fileSystem, scriptCapability, commandLineRunner),
                new FeatureScriptConvention(DeploymentStages.AfterPreDeploy, fileSystem, embeddedResources, scriptCapability, commandLineRunner),
                new SubstituteInFilesConvention(fileSystem, substituter),
                new ConfigurationTransformsConvention(fileSystem, configurationTransformer),
                new ConfigurationVariablesConvention(fileSystem, replacer),
                new JsonConfigurationVariablesConvention(generator, fileSystem),
                new CopyPackageToCustomInstallationDirectoryConvention(fileSystem),
                new FeatureScriptConvention(DeploymentStages.BeforeDeploy, fileSystem, embeddedResources, scriptCapability, commandLineRunner),
                new PackagedScriptConvention(DeploymentStages.Deploy, fileSystem, scriptCapability, commandLineRunner),
                new ConfiguredScriptConvention(DeploymentStages.Deploy, scriptCapability, fileSystem, commandLineRunner),
                new FeatureScriptConvention(DeploymentStages.AfterDeploy, fileSystem, embeddedResources, scriptCapability, commandLineRunner),
                new LegacyIisWebSiteConvention(fileSystem, iis),
                new FeatureScriptConvention(DeploymentStages.BeforePostDeploy, fileSystem, embeddedResources, scriptCapability, commandLineRunner),
                new PackagedScriptConvention(DeploymentStages.PostDeploy, fileSystem, scriptCapability, commandLineRunner),
                new ConfiguredScriptConvention(DeploymentStages.PostDeploy, scriptCapability, fileSystem, commandLineRunner),
                new FeatureScriptConvention(DeploymentStages.AfterPostDeploy, fileSystem, embeddedResources, scriptCapability, commandLineRunner),
                new RollbackScriptConvention(DeploymentStages.DeployFailed, fileSystem, scriptCapability, commandLineRunner)
            };

            var deployment       = new RunningDeployment(packageFile, variables);
            var conventionRunner = new ConventionProcessor(deployment, conventions);

            try
            {
                conventionRunner.RunConventions();
                if (!deployment.SkipJournal)
                {
                    journal.AddJournalEntry(new JournalEntry(deployment, true));
                }
            }
            catch (Exception)
            {
                if (!deployment.SkipJournal)
                {
                    journal.AddJournalEntry(new JournalEntry(deployment, false));
                }
                throw;
            }

            return(0);
        }
Exemple #60
0
 public Task Execute(RunningDeployment context)
 {
     throw new NotImplementedException();
 }