public static DeploymentTaskRoot Create(PackageCreationComponentGraph action, DeploymentType deploymentType)
        {
            if (action.SourceContentPath.EndsWith(@".csproj")
                || action.SourceContentPath.EndsWith(@".vbproj")
                || action.SourceContentPath.EndsWith(@".wdproj"))
            {
                if (deploymentType == DeploymentType.local)
                {
                    return new LocalProjectPackgeCreationTask(action);
                }

                if (deploymentType == DeploymentType.msDeploy)
                {
                    return new MsDeployProjectPackgeCreationTask(action);
                }

                throw new ArgumentOutOfRangeException("unknown deployment type for project package creation");
            }

            if (deploymentType == DeploymentType.local)
            {
                return new LocalFolderPackgeCreationTask(action);
            }

            if (deploymentType == DeploymentType.msDeploy)
            {
                return new MsDeployFolderPackgeCreationTask(action);
            }

            throw new ArgumentOutOfRangeException("unknown deployment type for folder package creation");
        }
 public InProgressOperation(ResourceGroup resourceGroup, DeploymentType deploymentType)
 {
     this.ResourceGroup = resourceGroup;
     this.DeploymentType = deploymentType;
     this._tokenSource = new CancellationTokenSource();
     this.Task = Task.Delay(Timeout.Infinite, this._tokenSource.Token);
 }
        public NuwaWebDeploymentScopeAttribute(DeploymentType type, string path = null)
        {
            if (type == DeploymentType.Directory)
            {
                if (string.IsNullOrEmpty(path))
                {
                    throw new ArgumentNullException("path");
                }
            }

            this.DeploymentType = type;
            ScopePath = path;

        }
Exemple #4
0
        /// <summary>
        /// Add a script installer deployment type to an application, using registry key in HKLM
        /// </summary>
        public static void AddScriptInstaller(string applicationName, string installName, string hklmKey, bool is64bit, string valueName, string valueNameValue, string dataType, string expressionOperator, string installCommand, string uninstallCommand, int postInstallBehaviour, int userInteractMode, int maxExecTime, int estimateExecTime, int execContext, string server)
        {
            Application app = CMApplication.GetApplicationByName(applicationName, server);
            ScriptInstaller installer = ReturnStandardScriptInstaller(installCommand, uninstallCommand, postInstallBehaviour, userInteractMode, maxExecTime, estimateExecTime, execContext);

            installer.DetectionMethod = DetectionMethod.Enhanced;
            EnhancedDetectionMethod enhancedDetectionMethod = new EnhancedDetectionMethod();

            ConstantValue expectedValue = null;
            RegistrySetting registrySetting = new RegistrySetting(null);
            registrySetting.RootKey = RegistryRootKey.LocalMachine;
            registrySetting.Key = hklmKey;
            registrySetting.Is64Bit = is64bit;
            registrySetting.ValueName = valueName;
            registrySetting.CreateMissingPath = false;

            switch (dataType)
            {
                case "Version":
                    registrySetting.SettingDataType = DataType.Version;
                    expectedValue = new ConstantValue(valueNameValue, DataType.Version);
                    break;
                default:
                    break;
            }

            enhancedDetectionMethod.Settings.Add(registrySetting);

            SettingReference settingReference = new SettingReference(app.Scope, app.Name, app.Version.GetValueOrDefault(), registrySetting.LogicalName, registrySetting.SettingDataType, registrySetting.SourceType, false);
            settingReference.MethodType = ConfigurationItemSettingMethodType.Value;

            CustomCollection<ExpressionBase> operands = new CustomCollection<ExpressionBase>();
            operands.Add(settingReference);
            operands.Add(expectedValue);

            Expression expression = null;

            switch (expressionOperator)
            {
                case "IsEquals":
                    expression = new Expression(ExpressionOperator.IsEquals, operands);
                    break;
                case "LessEquals":
                    expression = new Expression(ExpressionOperator.LessEquals, operands);
                    break;
                default:
                    break;
            }

            Rule rule = new Rule(Guid.NewGuid().ToString("N"), NoncomplianceSeverity.None, null, expression);
            enhancedDetectionMethod.Rule = rule;

            installer.EnhancedDetectionMethod = enhancedDetectionMethod;

            DeploymentType deploymentType = new DeploymentType(installer, ScriptInstaller.TechnologyId, NativeHostingTechnology.TechnologyId);
            deploymentType.Title = installName;
            app.DeploymentTypes.Add(deploymentType);

            CMApplication.Save(app, server);
        }
Exemple #5
0
        /// <summary>
        /// Add a script installer deployment type to an application, using a PowerShell script for the detection logic
        /// </summary>
        public static void AddScriptInstaller(string applicationName, string installName, string powershellDetectionScript, string installCommand, string uninstallCommand, int postInstallBehaviour, int userInteractMode, int maxExecTime, int estimateExecTime, int execContext, string server)
        {
            Application app = CMApplication.GetApplicationByName(applicationName, server);
            ScriptInstaller installer = ReturnStandardScriptInstaller(installCommand, uninstallCommand, postInstallBehaviour, userInteractMode, maxExecTime, estimateExecTime, execContext);

            installer.DetectionMethod = DetectionMethod.Script;
            installer.DetectionScript = new Script { Text = powershellDetectionScript, Language = "PowerShell" };

            DeploymentType deploymentType = new DeploymentType(installer, ScriptInstaller.TechnologyId, NativeHostingTechnology.TechnologyId);
            deploymentType.Title = installName;
            app.DeploymentTypes.Add(deploymentType);

            CMApplication.Save(app, server);
        }
        // ARM
        private async Task<ResourceGroup> ActivateResourceGroup(TryWebsitesIdentity userIdentity, AppService appService, DeploymentType deploymentType, Func<ResourceGroup, InProgressOperation, Task<ResourceGroup>> func)
        {
            ResourceGroup resourceGroup = null;
            if (userIdentity == null)
            {
                throw new InvalidUserIdentityException();
            }

            var userId = userIdentity.Name;
            try
            {
                if (_backgroundQueueManager.ResourceGroupsInUse.TryGetValue(userId, out resourceGroup))
                {
                    throw new MoreThanOneResourceGroupException();
                }

                if (_backgroundQueueManager.FreeResourceGroups.TryDequeue(out resourceGroup))
                {
                    //mark site in use as soon as it's checked out so that if there is a reload it will be sorted out to the used queue.
                    await resourceGroup.MarkInUse(userId, ResourceGroupExpiryTime, appService);
                    var rbacTask = Task.FromResult(false); //RbacHelper.AddRbacUser(userIdentity.Puid, userIdentity.Email, resourceGroup);
                    var process = new InProgressOperation(resourceGroup, deploymentType);
                    _backgroundQueueManager.ResourceGroupsInProgress.AddOrUpdate(userId, s => process, (s, task) => process);
                    SimpleTrace.Diagnostics.Information("resourceGroup {resourceGroupId} is now in use", resourceGroup.CsmId);

                    resourceGroup = await func(resourceGroup, process);

                    var addedResourceGroup = _backgroundQueueManager.ResourceGroupsInUse.GetOrAdd(userId, resourceGroup);
                    if (addedResourceGroup.ResourceGroupName == resourceGroup.ResourceGroupName)
                    {
                        //this means we just added the resourceGroup for the user.
                        await addedResourceGroup.MarkInUse(userId, ResourceGroupExpiryTime, appService);
                        return addedResourceGroup;
                    }
                    else
                    {
                        //this means the user is trying to add more than 1 site.
                        //delete the new site that's not yet added to the used list
                        await resourceGroup.DeleteAndCreateReplacement();
                        throw new MoreThanOneResourceGroupException();
                    }
                }
                else
                {
                    throw new NoFreeResourceGroupsException();
                }
                // End site specific stuff
            }
            catch (MoreThanOneResourceGroupException)
            {
                throw;
            }
            catch (NoFreeResourceGroupsException)
            {
                throw;
            }
            catch (InvalidGithubRepoException)
            {
                throw;
            }
            catch (Exception e)
            {
                //unknown exception, log it
                SimpleTrace.Diagnostics.Fatal(e, "Unknown error during UserCreate, Count {Count}", Interlocked.Increment(ref _unknownErrorInCreateErrorCount));
            }
            finally
            {
                InProgressOperation temp;
                _backgroundQueueManager.ResourceGroupsInProgress.TryRemove(userId, out temp);
                temp.Complete();
                LogQueueStatistics();
            }
            //if we are here that means a bad exception happened above, but we might leak a site if we don't remove the site and replace it correctly.
            if (resourceGroup != null)
            {
                //no need to await this call
                //this call is to fix our internal state, return an error right away to the caller
                ThreadPool.QueueUserWorkItem(async o => await DeleteResourceGroup(resourceGroup).IgnoreFailure());
            }
            throw new Exception(Resources.Server.Error_GeneralErrorMessage);
        }
        private string validateSettings(StringDictionary keyValues, DeploymentType deploymentType)
        {
            string sMessage = null;

            string sSettingsFilePath = keyValues[f_csSETTINGS_FILE_PARAM];
            if (string.IsNullOrEmpty(sSettingsFilePath))
            {
                sMessage = "Error - no settings file was specifed! You must specify the path to an XML settings file " +
                           "in the 'settingsFile' parameter. This file should be generated by saving import or export " +
                           "settings in the Content Deployment Wizard";
            }

            if (!File.Exists(sSettingsFilePath))
            {
                sMessage = string.Format("Error - unable to find settings file at path '{0}'!", sSettingsFilePath);
            }

            using (XmlTextReader xReader = new XmlTextReader(sSettingsFilePath))
            {
                WizardOperationSettings settings = WizardDeployment.CollectSettings(xReader);
                if (settings is WizardExportSettings && deploymentType == DeploymentType.Import)
                {
                    sMessage = string.Format("Error - settings file '{0}' contains export settings but you selected the RunWizardImport " +
                        "command!", sSettingsFilePath);
                }

                if (settings is WizardImportSettings && deploymentType == DeploymentType.Export)
                {
                    sMessage = string.Format("Error - settings file '{0}' contains import settings but you selected the RunWizardExport " +
                        "command!", sSettingsFilePath);
                } 
            }
            
            return sMessage;
        }
        public IServiceResult Install(string packageId, DeploymentType deploymentType, bool forceInstallation, string[] packageConfigurationProfiles, string[] buildConfigurationProfiles)
        {
            if (string.IsNullOrWhiteSpace(packageId))
            {
                throw new ArgumentException("packageId");
            }

            if (packageConfigurationProfiles == null)
            {
                throw new ArgumentNullException("packageConfigurationProfiles");
            }

            if (buildConfigurationProfiles == null)
            {
                throw new ArgumentNullException("buildConfigurationProfiles");
            }

            if (deploymentType == DeploymentType.NotRecognized)
            {
                throw new ArgumentException("deploymentType");
            }

            // check package source configuration
            if (this.packageRepositoryBrowser.RepositoryConfigurations == null || !this.packageRepositoryBrowser.RepositoryConfigurations.Any())
            {
                return new FailureResult(Resources.PackageInstaller.NoPackageRepositoryConfigurationsAvailable);
            }

            // fetch package from repository
            IPackage package = this.packageRepositoryBrowser.FindPackage(packageId);
            if (package == null)
            {
                return new FailureResult(
                    Resources.PackageInstaller.PackageNotFoundMessageTemplate,
                    packageId,
                    string.Join(", ", this.packageRepositoryBrowser.RepositoryConfigurations.Select(r => r.Url)));
            }

            // check if install/update is required
            IServiceResult installRequired = this.installationLogicProvider.IsInstallRequired(packageId, package.Version, forceInstallation);
            if (installRequired.Status == ServiceResultType.Failure)
            {
                return new FailureResult(Resources.PackageInstaller.InstallationIsNotRequiredMessageTemplate, packageId)
                    {
                        InnerResult = installRequired
                    };
            }

            // uninstall previous version (if required)
            IServiceResult uninstallRequired = this.installationLogicProvider.IsUninstallRequired(packageId, package.Version, deploymentType, forceInstallation);
            if (uninstallRequired.Status == ServiceResultType.Success)
            {
                IServiceResult uninstallResult = this.packageUninstaller.Uninstall(package.Id, null);
                if (uninstallResult.Status == ServiceResultType.Failure && !forceInstallation)
                {
                    // abort installation
                    return new FailureResult(Resources.PackageInstaller.PackageRemovalFailedMessageTemplate, package.Id) { InnerResult = uninstallResult };
                }
            }

            // extract the package
            NuDeployPackageInfo extractedPackage = this.nugetPackageExtractor.Extract(package, this.applicationInformation.StartupFolder);
            if (extractedPackage == null)
            {
                return new FailureResult(
                    Resources.PackageInstaller.PackageExtractionFailedMessageTemplate, packageId, this.applicationInformation.StartupFolder);
            }

            // apply system setting transformations
            IServiceResult systemSettingTransformationResult = this.packageConfigurationTransformationService.TransformSystemSettings(
                extractedPackage.Folder, packageConfigurationProfiles);

            if (systemSettingTransformationResult.Status == ServiceResultType.Failure)
            {
                return new FailureResult(Resources.PackageInstaller.SystemSettingTransformationFailedMessageTemplate, packageId)
                    {
                        InnerResult = systemSettingTransformationResult
                    };
            }

            // apply configuraton file transformations
            IServiceResult configFileTransformationResult = this.configurationFileTransformationService.TransformConfigurationFiles(
                extractedPackage.Folder, buildConfigurationProfiles);

            if (configFileTransformationResult.Status == ServiceResultType.Failure)
            {
                return new FailureResult(Resources.PackageInstaller.ConfigurationFileTransformationFailedMessageTemplate, packageId)
                    {
                        InnerResult = configFileTransformationResult
                    };
            }

            // locate installation script
            string scriptParameter = string.Format("-{0} {1}", InstallPowerShellScriptDeploymentTypeParameterName, deploymentType);
            string installScriptPath = Path.Combine(extractedPackage.Folder, InstallPowerShellScriptName);

            if (!this.filesystemAccessor.FileExists(installScriptPath))
            {
                return new FailureResult(
                    Resources.PackageInstaller.InstallScriptNotFoundMessageTemplate,
                    installScriptPath,
                    extractedPackage.Id,
                    extractedPackage.Version,
                    extractedPackage.Folder);
            }

            // execute installation script
            IServiceResult powerShellResult = this.powerShellExecutor.ExecuteScript(installScriptPath, scriptParameter);
            if (powerShellResult.Status == ServiceResultType.Failure)
            {
                return new FailureResult(Resources.PackageInstaller.InstallationScriptExecutionFailedMessageTemplate, installScriptPath)
                    {
                        InnerResult = powerShellResult
                    };
            }

            // update package configuration
            IServiceResult packageConfigurationUpdateResult =
                this.packageConfigurationAccessor.AddOrUpdate(new PackageInfo { Id = package.Id, Version = package.Version.ToString() });

            if (packageConfigurationUpdateResult.Status == ServiceResultType.Failure)
            {
                return new FailureResult(Resources.PackageInstaller.PackageCouldNotBeAddedToConfigurationMessageTemplate, packageId, package.Version)
                    {
                        InnerResult = packageConfigurationUpdateResult
                    };
            }

            return new SuccessResult(Resources.PackageInstaller.PackageHasBeenSuccessfullyInstalledMessageTemplate, packageId, package.Version);
        }
Exemple #9
0
 /// <summary>
 /// Upgrades the given deployment with the package contents.
 /// </summary>
 public async Task UpgradeAsync(
     Uri packageUrl,
     DeploymentType deploymentType,
     string roleToUpgrade = null)
 {
     Contract.Requires(Parent != null);
     Contract.Requires(packageUrl != null);
     Contract.Requires(!string.IsNullOrWhiteSpace(Label));
     Contract.Requires(Configuration != null);
     
     var ns = XmlNamespaces.WindowsAzure;
     var content = new XElement(ns + "UpgradeDeployment",
         new XElement(ns + "Mode", "Auto"),
         new XElement(ns + "PackageUrl", packageUrl.ToString()),
         new XElement(ns + "Configuration", Configuration.ToXml().ToString().ToBase64String()),
         new XElement(ns + "Label", Label.ToBase64String()),
         new XElement(ns + "RoleToUpgrade", roleToUpgrade),
         new XElement(ns + "Force", deploymentType == DeploymentType.Forced));
     // With the deployments endpoint, you need a forward slash separating the URI from the query string!
     HttpResponseMessage response = await GetRestClient(Parent, "/?comp=upgrade").PostAsync(content);
     await Parent.Subscription.WaitForOperationCompletionAsync(response);
 }
Exemple #10
0
        /// <summary>
        /// Initialises this class with settings for an import or export operation.
        /// </summary>
        /// <param name="DeploymentXml">XML containing settings - this should be initially generated by using the 'Save settings' functionality in the UI.</param>
        /// <param name="DeploymentType">The type of operation to perform.</param>
        public WizardDeployment(XmlTextReader DeploymentXml, DeploymentType DeploymentType)
        {
            trace = new TraceHelper(this);
            Type = DeploymentType;

            if (DeploymentType == DeploymentType.Export)
            {
                WizardExportSettings weSettings = CollectExportSettings(DeploymentXml);
                ExportSettings = (SPExportSettings) weSettings.Settings;
            }
            if (DeploymentType == DeploymentType.Import)
            {
                WizardImportSettings wiSettings = CollectImportSettings(DeploymentXml);
                ImportSettings = (SPImportSettings) wiSettings.Settings;
            }
        }
Exemple #11
0
        public async Task <Deployment> AddDeployment(
            Application application,
            ApplicationImage image,
            string newTag,
            DeploymentType type = DeploymentType.ImageUpdate,
            string instanceId   = "",
            IReadOnlyDictionary <string, string>?parameters = null)
        {
            var currentTagInStore = await _applicationImageInstanceService.GetCurrentTag(application, image, instanceId);

            var currentTag = currentTagInStore.available ? currentTagInStore.tag : "";

            var deployments = _deploymentsDbContextConfigurator.Set <Dao.Deployment>();

            var deploymentExists = await IsDeploymentPresent(
                application,
                image,
                newTag,
                type,
                instanceId
                );

            if (deploymentExists)
            {
                _log.LogInformation(
                    "Image tag update operation already in queue for '{Repository}' with {Tag} for application {Application} with new tag {NewTag}",
                    image.Repository,
                    currentTag,
                    application.Name,
                    newTag
                    );

                throw new Exception($"Deployment for {image} with {newTag} on application '{application.Name}' already exists.");
            }

            var entity = await CreateAndStoreDeploymentDao(
                deployments,
                application,
                image,
                type == DeploymentType.ImageUpdate?DaoDeploymentType.ImageUpdate : DaoDeploymentType.PreviewRelease,
                newTag,
                currentTag,
                string.Empty,
                instanceId,
                parameters
                );

            _log.LogInformation(
                "Adding image tag update operation for '{Repository}' with {Tag} for application {Application} with new tag {NewTag}",
                image.Repository,
                currentTag,
                application.Name,
                newTag
                );

            await _deploymentsDbContextConfigurator.SaveChangesAsync();

            var deployment = entity.Entity.ConvertToDeploymentModel();

            await _deploymentNotificationService.CreateNotification(deployment);

            return(deployment);
        }