Exemplo n.º 1
0
        public static IJob GetJob(ICloudStampyLogger logger, CloudStampyParameters args, StampyJobType requestedJobType)
        {
            IJob job = null;

            switch (requestedJobType)
            {
            case StampyJobType.None:
                break;

            case StampyJobType.CreateService:
                job = new ServiceCreationJob(logger, args);
                break;

            case StampyJobType.Build:
                job = new BuildJob(logger, args);
                break;

            case StampyJobType.Deploy:
                job = new DeploymentJob(logger, args);
                break;

            case StampyJobType.Test:
                job = new TestJob(logger, args);
                break;

            case StampyJobType.RemoveResources:
                job = new ScavengerJob(logger, args);
                break;

            default:
                break;
            }

            return(job);
        }
Exemplo n.º 2
0
 public DeploymentJobLightModel(DeploymentJob job)
 {
     Id      = job.Id;
     Project = job.Project;
     Service = job.Service;
     Status  = job.Status.ToString();
     EndTime = job.EndTime.ToPresentationFormat();
 }
        private static void DeployScheduledPublications(AspNetDeployEntities entities)
        {
            List <Publication> publications = entities.Publication
                                              .Include("Package.BundleVersion")
                                              .Include("Environment")
                                              .Where(p =>
                                                     p.State == PublicationState.Queued &&
                                                     !p.Package.Publications.Any(p2 =>
                                                                                 p2.CreatedDate > p.CreatedDate &&
                                                                                 p2.EnvironmentId == p.EnvironmentId))
                                              .ToList();

            List <IGrouping <BundleVersion, Publication> > groupedPublications = publications
                                                                                 .GroupBy(p => p.Package.BundleVersion)
                                                                                 .Where(bv => !bv.Key.IsDeleted)
                                                                                 .ToList();

            groupedPublications.ForEach(group =>
            {
                TaskRunnerContext.SetBundleVersionState(group.Key.Id, BundleState.Deploying);

                try
                {
                    foreach (Publication publication in group)
                    {
                        try
                        {
                            DeploymentJob job = new DeploymentJob();
                            job.Start(
                                publication.Id,
                                machineId => TaskRunnerContext.SetMachineState(machineId, MachineState.Deploying),
                                (machineId, isSuccess) => TaskRunnerContext.SetMachineState(machineId, isSuccess ? MachineState.Idle : MachineState.Error));
                        }
                        catch (Exception e)
                        {
                            throw new AspNetDeployException("Publication failed: " + publication.Id, e);
                        }
                    }
                }
                catch (Exception e)
                {
                    TaskRunnerContext.SetBundleVersionState(group.Key.Id, BundleState.Error);

                    Factory.GetInstance <ILoggingService>().Log(e, null);

                    if (e.IsCritical())
                    {
                        throw;
                    }

                    return;
                }

                TaskRunnerContext.SetBundleVersionState(group.Key.Id, BundleState.Idle);
            });
        }
Exemplo n.º 4
0
 public DeploymentJobModel(DeploymentJob job)
 {
     Id            = job.Id;
     Project       = job.Project;
     Service       = job.Service;
     Status        = job.Status.ToString();
     CurrentAction = job.CurrentAction;
     ErrorMessage  = job.ErrorMessage;
     CreatedTime   = job.CreatedTime.ToPresentationFormat();
     EndTime       = job.EndTime.ToPresentationFormat();
 }
        public bool TryRunJobIfNotInProgress(
            string project,
            string service,
            List <DeploymentScript> scripts,
            out DeploymentJob job)
        {
            if (!_jobsDataAccess.TryCreateIfVacant(project, service, out job))
            {
                return(false);
            }

            Task.Run(() => RunJob(job.Id, scripts));

            return(true);
        }
Exemplo n.º 6
0
        public ActionResult Update(DeployDataFromView model)
        {
            var deploy = new DeploymentJob();
            deploy.Id = Guid.NewGuid().ToString();
            deploy.Date = DateTime.Now;

            var Companies = new MongoRepository<Company>();
            deploy.Company = Companies.Single(c => c.CompanyKey == model.deployData["Company"]);
            var Environments = new MongoRepository<Entities.Environment>();
            deploy.Server = Environments.Single(e=>e.Id==model.deployData["Environment"]);
            var Revisions = new MongoRepository<Revision>();
            deploy.Revision = Revisions.Single(r=>r.Id== model.deployData["Revision"]);
            if (model.deployData["DeploySide"] == "Server")
            {
                if (model.deployData.ContainsKey("Database") && model.deployData["Database"]=="True")
                {
                    deploy.Database = true;
                }
                if (model.deployData.ContainsKey("Create") && model.deployData["Create"] == "True")
                {
                    deploy.Create = true;
                }
            }
            else
            {
                deploy.ServerSide = false;
                deploy.ClientSide = true;
                if (model.deployData.ContainsKey("Android") && model.deployData["Android"] == "True")
                {
                    deploy.Android = true;
                }
                if (model.deployData.ContainsKey("Callbox") && model.deployData["Callbox"] == "True")
                {
                    deploy.CallBox = true;
                }
                if (model.deployData.ContainsKey("IosAdhoc") && model.deployData["IosAdhoc"] == "True")
                {
                    deploy.IosAdhoc = true;
                }
                if (model.deployData.ContainsKey("IosAppStore") && model.deployData["IosAppStore"] == "True")
                {
                    deploy.IosAppStore = true;
                }
            }

            Repository.Add(deploy);
            return View();
        }
        private void CheckAndRunJobWithBuild()
        {
            try
            {
                var job = new DeploymentJobServiceClient().GetNext();
                if (job == null)
                {
                    return;
                }

                _job = job;

                Log("Starting", JobStatus.Inprogress);

                var sourceDirectory = Path.Combine(Path.GetPathRoot(System.Environment.GetFolderPath(System.Environment.SpecialFolder.System)), "mktaxi");

                Log("Source Folder = " + sourceDirectory);

                var taxiRepo = new TaxiRepository(sourceDirectory, bool.Parse(ConfigurationManager.AppSettings["IsGitHubSourceControl"]));
                if (_job.Server.Role == EnvironmentRole.BuildServer)
                {
                    taxiRepo.FetchSource(_job.Revision.Commit, str => Log(str));
                    Build(sourceDirectory);
                }

                //build server and deploy
                if (_job.ServerSide || _job.Database)
                {
                    var packagesDirectory = Path.Combine(sourceDirectory, "Deployment\\Server\\Package\\");
                    if (_job.Server.Role != EnvironmentRole.BuildServer)
                    {
                        packagesDirectory = ConfigurationManager.AppSettings["DeployFolder"];
                    }
                    var packagesLocation = CleanAndUnZip(packagesDirectory);
                    DeployTaxiHail(packagesLocation);
                }

                Log("Job Complete", JobStatus.Success);
            }
            catch (Exception e)
            {
                _logger.Error(e.Message, e);
                Log(e.Message, JobStatus.Error);
            }
        }
Exemplo n.º 8
0
        private string ReplacePlaceholders(string scriptBody, string scriptName,
                                           IEnumerable <ScriptParameter> parameters, IEnumerable <Variable> variables,
                                           DeploymentJob job, string environmentName,
                                           string targetComputerName = null, string credentialUsername = null, string credentialPassword = null)
        {
            foreach (var parameter in parameters)
            {
                var variable = variables
                               .FirstOrDefault(v => v.Name == parameter.Name && !v.Value.IsNullOrWhiteSpace());

                string value = null;

                if (variable != null)
                {
                    value = variable.Value;
                }

                if (value.IsNullOrWhiteSpace())
                {
                    value = this.GetValueFromPredefinedVariable(
                        parameter.Name, job.DeploymentJobID, job.ProductVersion, environmentName,
                        targetComputerName, credentialUsername, credentialPassword);
                }

                if (value.IsNullOrWhiteSpace())
                {
                    value = parameter.DefaultValue;
                }

                if (value.IsNullOrWhiteSpace() && parameter.IsMandatory)
                {
                    throw new Exception(
                              "Variables did not provide value for mandatory parameter [{0}] in script [{1}]."
                              .FormatString(parameter.Name, scriptName));
                }

                var placeholder = VariableHelper.FormatPlaceholder(parameter.Name);
                if (scriptBody.Contains(placeholder))
                {
                    scriptBody = scriptBody.Replace(placeholder, value);
                }
            }

            return(scriptBody);
        }
 private static string GetZipFileName(DeploymentJob job)
 {
     return(string.Format("TaxiHail_[GitHub]{0}.zip", MakeValidFileName(job.Revision.Tag)));
 }
        private void AddDeploymentJob(AddDeploymentJobModel model, string email = null)
        {
            Action <Company> addACompanyAction = company =>
            {
                var user = _session.Users.SingleOrDefault(x => x.UserName == User.Identity.Name);

                var userDisplayName = user != null ? user.CatchAll["Name"].AsString : "Unknown";

                var deploy = new DeploymentJob
                {
                    Id        = Guid.NewGuid().ToString(),
                    Date      = DateTime.Now,
                    Company   = company,
                    UserEmail = User.Identity.Name,
                    UserName  = userDisplayName
                };
                var environments = new MongoRepository <Environment>();

                deploy.Server = environments.Single(e => e.Id == model.ServerId);
                var revisions = new MongoRepository <Revision>();
                deploy.Revision = revisions.Single(r => r.Id == model.RevisionId);

                var createType = (DeploymentJobType)model.CreateType;

                deploy.ServerSide = createType == DeploymentJobType.ServerPackage ||
                                    createType == DeploymentJobType.DeployServer;
                deploy.ClientSide = !deploy.ServerSide;
                deploy.Type       = createType;

                if (deploy.ServerSide && (createType == DeploymentJobType.ServerPackage))
                {
                    deploy.ServerSide = false;
                    deploy.Database   = false;
                }
                else if (deploy.ServerSide)
                {
                    deploy.Database = model.Database;
                }
                else
                {
                    deploy.ServerUrl = GetUrlFromModel(model, company);
                    if (string.IsNullOrWhiteSpace(deploy.ServerUrl))
                    {
                        throw new InvalidOperationException("Server url must be set");
                    }
                    deploy.Android     = model.Android;
                    deploy.CallBox     = model.CallBox;
                    deploy.IosAdhoc    = model.IosAdhoc;
                    deploy.IosAppStore = model.IosAppStore;
                    deploy.BlackBerry  = model.BlackBerry;
                }


                company.LastKnownProductionVersion = null;
                company.LastKnownStagingVersion    = null;

                new MongoRepository <Company>().Update(company);

                Repository.Add(deploy);
            };


            var companies = new MongoRepository <Company>();

            if (model.CompanyId == _allCompaniesKey)
            {
                foreach (var company in companies.Where(c => (c.Status == AppStatus.Production) || (c.Status == AppStatus.TestingNewVersion)))
                {
                    addACompanyAction(company);
                }
            }
            else if (model.CreateType == (int)DeploymentJobType.ServerPackage)
            {
                var company = companies.Single(c => c.CompanyKey == "TaxiHailDemo");
                addACompanyAction(company);
            }
            else if (model.SelectedCompaniesId.Any())
            {
                foreach (var companyId in model.SelectedCompaniesId)
                {
                    var company = companies.Single(c => c.CompanyKey == companyId);
                    addACompanyAction(company);
                }
            }
            else
            {
                var company = companies.Single(c => c.CompanyKey == model.CompanyId);
                addACompanyAction(company);
            }
        }
 // PUT api/deploymentjob/5
 public void Put(int id, [FromBody] DeploymentJob value)
 {
 }
Exemplo n.º 12
0
        public string ResolveVariables(
            Script script, DeploymentPlanStep planStep, DeploymentJob job, string environmentName,
            short?targetGroupID       = null, int?targetGroupEnvironmentID = null, int?projectTargetID       = null,
            string targetComputerName = null, string credentialUsername    = null, string credentialPassword = null)
        {
            if (script.Body.IsNullOrWhiteSpace())
            {
                throw new ArgumentException("Script body is empty.");
            }

            List <Variable> variables;

            using (var uow = _unitOfWorkFactory.Create())
            {
                variables = uow.Repository <Variable>()
                            .Get(v =>
                                 v.ScopeKey == VariableScope.Global.ToString() ||
                                 (v.ScopeKey == VariableScope.Project.ToString() &&
                                  v.ScopeID == job.ProjectID) ||
                                 (v.ScopeKey == VariableScope.TargetGroup.ToString() &&
                                  v.ScopeID == targetGroupID) ||
                                 (v.ScopeKey == VariableScope.Environment.ToString() &&
                                  v.ScopeID == job.ProjectEnvironmentID) ||
                                 (v.ScopeKey == VariableScope.TargetGroupEnvironment.ToString() &&
                                  v.ScopeID == targetGroupEnvironmentID) ||
                                 (v.ScopeKey == VariableScope.ProjectTarget.ToString() &&
                                  v.ScopeID == projectTargetID) ||
                                 (v.ScopeKey == VariableScope.DeploymentPlan.ToString() &&
                                  v.ScopeID == planStep.DeploymentPlanID) ||
                                 (v.ScopeKey == VariableScope.DeploymentStep.ToString() &&
                                  v.ScopeID == planStep.DeploymentPlanStepID) ||
                                 (v.ScopeKey == VariableScope.DeploymentJob.ToString() &&
                                  v.ScopeID == job.DeploymentJobID))
                            .OrderByDescending(v => v.Scope) // First enum value (Global) has lowest precedence.
                            .ToList();
            }

            var parameters = script.Parameters
                             .OrderBy(v => v.Name)
                             .ToList();

            parameters.Add(new ScriptParameter {
                Name = VariableHelper.DeploymentJobNumberVariable
            });
            parameters.Add(new ScriptParameter {
                Name = VariableHelper.ProductVersionVariable
            });
            parameters.Add(new ScriptParameter {
                Name = VariableHelper.EnvironmentNameVariable
            });
            parameters.Add(new ScriptParameter {
                Name = VariableHelper.TargetComputerNameVariable
            });
            parameters.Add(new ScriptParameter {
                Name = VariableHelper.CredentialUsernameVariable
            });
            parameters.Add(new ScriptParameter {
                Name = VariableHelper.CredentialPasswordVariable
            });

            // Replace variable placeholders with values in multiple passes
            // to enable using variables inside other variables.
            var cyclesLeft   = 10;
            var originalBody = script.Body;

            while (true)
            {
                var processedBody = this.ReplacePlaceholders(originalBody, script.Name, parameters, variables,
                                                             job, environmentName, targetComputerName, credentialUsername, credentialPassword);

                if (processedBody == originalBody)  // Nothing left to replace
                {
                    return(processedBody);
                }

                originalBody = processedBody;

                if (--cyclesLeft == 0)
                {
                    throw new Exception("Possible cyclic reference in variables.");
                }
            }
        }
Exemplo n.º 13
0
        private void CheckAndRunJobWithBuild()
        {
            try
            {
                var job = new DeploymentJobServiceClient().GetNext();

                if (job == null)
                {
                    return;
                }

                _job = job;

                try
                {
                    _logger.Debug("Begin work on " + job.Company.CompanyName);

                    UpdateJob("Starting at " + DateTime.Now, JobStatus.Inprogress);

                    var sourceDirectoryConfig = ConfigurationManager.AppSettings["CheckoutDir"];

                    var sourceDirectory = string.IsNullOrEmpty(sourceDirectoryConfig)
                                                ? Path.Combine(Path.GetTempPath(), "TaxiHailSourceNewService")
                                                : sourceDirectoryConfig;

                    if (!Directory.Exists(sourceDirectory))
                    {
                        Directory.CreateDirectory(sourceDirectory);
                        UpdateJob("Directory " + sourceDirectory + " did not exist, creating...");
                        _isNewFolder = true;
                    }

                    var releaseiOSAdHocDir = Path.Combine(sourceDirectory, "Src", "Mobile", "iOS", "bin", "iPhone", "AdHoc");
                    if (Directory.Exists(releaseiOSAdHocDir))
                    {
                        Directory.Delete(releaseiOSAdHocDir, true);
                    }
                    var releaseiOSAdHocObjDir = Path.Combine(sourceDirectory, "Src", "Mobile", "iOS", "obj", "iPhone", "AdHoc");
                    if (Directory.Exists(releaseiOSAdHocObjDir))
                    {
                        Directory.Delete(releaseiOSAdHocObjDir, true);
                    }

                    var releaseiOSAppStoreDir = Path.Combine(sourceDirectory, "Src", "Mobile", "iOS", "bin", "iPhone", "AppStore");
                    if (Directory.Exists(releaseiOSAppStoreDir))
                    {
                        Directory.Delete(releaseiOSAppStoreDir, true);
                    }
                    var releaseiOSAppStoreObjDir = Path.Combine(sourceDirectory, "Src", "Mobile", "iOS", "obj", "iPhone", "AppStore");
                    if (Directory.Exists(releaseiOSAppStoreObjDir))
                    {
                        Directory.Delete(releaseiOSAppStoreObjDir, true);
                    }

                    var releaseAndroidDir = Path.Combine(sourceDirectory, "Src", "Mobile", "Android", "bin", "Release");
                    if (Directory.Exists(releaseAndroidDir))
                    {
                        Directory.Delete(releaseAndroidDir, true);
                    }

                    var releaseBlackBerryApkDir = Path.Combine(sourceDirectory, "Src", "Mobile", "TaxiHail.BlackBerry", "bin", "Release");
                    if (Directory.Exists(releaseBlackBerryApkDir))
                    {
                        Directory.Delete(releaseBlackBerryApkDir, true);
                    }

                    var releaseBlackBerryBarDir = Path.Combine(sourceDirectory, "Src", "BBTools", "Outputs");
                    if (Directory.Exists(releaseBlackBerryBarDir))
                    {
                        Directory.Delete(releaseBlackBerryBarDir, true);
                    }

                    var releaseCallboxAndroidDir = Path.Combine(sourceDirectory, "Src", "Mobile", "MK.Callbox.Mobile.Client.Android", "bin", "Release");
                    if (Directory.Exists(releaseCallboxAndroidDir))
                    {
                        Directory.Delete(releaseCallboxAndroidDir, true);
                    }

                    DownloadAndInstallProfileIfNecessary();

                    var isGitHub = bool.Parse(ConfigurationManager.AppSettings["IsGitHubSourceControl"]);
                    var taxiRepo = new TaxiRepository(sourceDirectory, isGitHub);

                    UpdateJob("FetchSource");
                    taxiRepo.FetchSource(_job.Revision.Commit, str => UpdateJob(str));

                    UpdateJob("Customize");
                    Customize(sourceDirectory, _job);

                    UpdateJob("Build");
                    BuildMobile(sourceDirectory, releaseiOSAdHocDir, releaseiOSAppStoreDir);

                    UpdateJob("Deploy");
                    var deploymentInfo = Deploy(_job.Company, releaseiOSAdHocDir, releaseiOSAppStoreDir, releaseAndroidDir, releaseCallboxAndroidDir, releaseBlackBerryApkDir, releaseBlackBerryBarDir);

                    CreateNewVersionInCustomerPortal(deploymentInfo);
                    UpdateJob(string.Format("Done (ended at {0})", DateTime.Now), JobStatus.Success);

                    _logger.Debug("Deployment finished without error");
                }
                catch (Exception e)
                {
                    _logger.Error(e.Message);
                    UpdateJob(string.Format("{0} (ended at {1})", e.Message, DateTime.Now), JobStatus.Error);
                }
            }
            catch (Exception e)
            {
                _logger.Error(e.Message);
            }
        }
Exemplo n.º 14
0
        private void Customize(string sourceDirectory, DeploymentJob job)
        {
            var company = job.Company;

            UpdateJob("Service Url : " + job.ServerUrl);
            UpdateJob("Customize - Build Config Tool Customization");

            var sln         = string.Format("{0}/ConfigTool.iOS.sln", Path.Combine(sourceDirectory, "Src", "ConfigTool"));
            var projectName = "NinePatchMaker.Lib";

            if (_builder.ProjectIsInSolution(sln, projectName))
            {
                var ninePatchProjectConfi = String.Format("\"--project:{0}\" \"--configuration:{1}\"", projectName, "Release");
                _builder.BuildProjectUsingMdTool(string.Format("build " + ninePatchProjectConfi + "  \"{0}\"", sln));
            }
            else
            {
                UpdateJob("Skipping NinePatch.Lib because it does not exist on this version");
            }

            projectName = "NinePatchMaker";
            if (_builder.ProjectIsInSolution(sln, projectName))
            {
                var ninePatchProjectConfi = String.Format("\"--project:{0}\" \"--configuration:{1}\"", projectName, "Release");
                _builder.BuildProjectUsingMdTool(string.Format("build " + ninePatchProjectConfi + "  \"{0}\"", sln));
            }
            else
            {
                UpdateJob("Skipping NinePatch because it does not exist on this version");
            }

            var mainConfig = String.Format("\"--project:{0}\" \"--configuration:{1}\"", "apcurium.MK.Booking.ConfigTool", "Release");

            _builder.BuildProjectUsingMdTool(string.Format("build " + mainConfig + "  \"{0}/ConfigTool.iOS.sln\"", Path.Combine(sourceDirectory, "Src", "ConfigTool")));

            UpdateJob("Run Config Tool Customization");

            var workingDirectory = Path.Combine(sourceDirectory, "Src", "ConfigTool", "apcurium.MK.Booking.ConfigTool.Console", "bin", "Release");
            var configToolRun    = ProcessEx.GetProcess("/usr/local/bin/mono", string.Format("apcurium.MK.Booking.ConfigTool.exe {0} {1}", company.CompanyKey, job.ServerUrl), workingDirectory);

            using (var exeProcess = Process.Start(configToolRun))
            {
                var output = ProcessEx.GetOutput(exeProcess);
                if (exeProcess != null && exeProcess.ExitCode > 0)
                {
                    throw new Exception("Error during customization, " + output);
                }
                UpdateJob("Customize Successful");
            }

            SleepFor(5);

            UpdateJob("Customization Finished");
            UpdateJob("Run Localization tool for Android");

            var localizationToolRun = new ProcessStartInfo {
                FileName               = "/usr/local/bin/mono",
                UseShellExecute        = false,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                WorkingDirectory       = Path.Combine(sourceDirectory, "Src", "LocalizationTool"),
                Arguments              = "output/LocalizationTool.exe -t=android -m=\"../Mobile/Common/Localization/Master.resx\" -d=\"../Mobile/Android/Resources/Values/String.xml\" -s=\"../Mobile/Common/Settings/Settings.json\""
            };

            using (var exeProcess = Process.Start(localizationToolRun))
            {
                var outputAndroid = ProcessEx.GetOutput(exeProcess);
                if (exeProcess != null && exeProcess.ExitCode > 0)
                {
                    throw new Exception("Error during localization tool for android");
                }
                UpdateJob(outputAndroid);
            }

            SleepFor(5);

            UpdateJob("Run Localization tool for Android Finished");
            UpdateJob("Run Localization tool for iOS");

            localizationToolRun = new ProcessStartInfo
            {
                FileName = "/usr/local/bin/mono",
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                UseShellExecute        = false,
                WorkingDirectory       = Path.Combine(sourceDirectory, "Src", "LocalizationTool"),
                Arguments = "output/LocalizationTool.exe -t=ios -m=\"../Mobile/Common/Localization/Master.resx\" -d=\"../Mobile/iOS/en.lproj/Localizable.strings\" -s=\"../Mobile/Common/Settings/Settings.json\""
            };

            using (var exeProcess = Process.Start(localizationToolRun))
            {
                var outputiOS = ProcessEx.GetOutput(exeProcess);
                if (exeProcess != null && exeProcess.ExitCode > 0)
                {
                    throw new Exception("Error during localization tool for iOS");
                }
                UpdateJob(outputiOS);
            }

            SleepFor(5);
            UpdateJob("Run Localization tool for iOS Finished");

            if (!job.CallBox)
            {
                return;
            }

            UpdateJob("Run Localization tool for Callbox");

            localizationToolRun = new ProcessStartInfo
            {
                FileName               = "/usr/local/bin/mono",
                UseShellExecute        = false,
                RedirectStandardOutput = true,
                RedirectStandardError  = true,
                WorkingDirectory       = Path.Combine(sourceDirectory, "Src", "LocalizationTool"),
                Arguments              = "output/LocalizationTool.exe -t=callbox -m=\"../Mobile/Common/Localization/Master.resx\" -d=\"../Mobile/MK.Callbox.Mobile.Client.Android/Resources/Values/Strings.xml\" -s=\"../Mobile/Common/Settings/Settings.json\""
            };

            using (var exeProcess = Process.Start(localizationToolRun))
            {
                var outputCallbox = ProcessEx.GetOutput(exeProcess);
                if (exeProcess != null && exeProcess.ExitCode > 0)
                {
                    throw new Exception("Error during localization tool for callbox");
                }
                UpdateJob(outputCallbox);
            }

            SleepFor(5);
            UpdateJob("Run Localization tool for Callbox Finished");
        }
        private void ExecuteDeploymentStepOnTargets(
            Script script, DeploymentPlanStep planStep, DeploymentJob job, string environmentName,
            int deploymentJobStepID, params short[] targetGroupIDs)
        {
            foreach (var targetGroupID in targetGroupIDs)
            {
                var targetGroupEnvironmentID = _targetGroupEnvironmentService
                                               .GetCombinationID(targetGroupID, job.ProjectEnvironmentID);

                var projectTargets = _projectTargetService
                                     .GetAllForTargetGroupAndEnvironment(targetGroupID, job.ProjectEnvironmentID)
                                     .OrderBy(t => t.Target.Name)
                                     .ToList();

                foreach (var projectTarget in projectTargets)
                {
                    var targetID = projectTarget.TargetID;

                    var jobStepTarget = new DeploymentJobStepTarget
                    {
                        DeploymentJobStepID = deploymentJobStepID,
                        TargetID            = targetID,
                        Status             = DeploymentStatus.Running,
                        StartTime          = DateTime.UtcNow,
                        ExecutionReference = Guid.NewGuid()
                    };
                    _deploymentJobStepTargetService.Insert(jobStepTarget);

                    var target = _targetService.GetWithCredential(targetID);

                    try
                    {
                        var username     = target.UsernameWithDomain;
                        var password     = _credentialService.DecryptPassword(target.Credential.Password);
                        var tempPassword = Guid.NewGuid().ToString();

                        var scriptBody = _variableService.ResolveVariables(script, planStep, job, environmentName,
                                                                           targetGroupID, targetGroupEnvironmentID, projectTarget.ProjectTargetID,
                                                                           target.ComputerName, username, tempPassword);

                        // Don't log real password.
                        jobStepTarget.ExecutedScript  = scriptBody.Replace(tempPassword, "**********");
                        jobStepTarget.ExecutionOutput = "Waiting for output...";
                        _deploymentJobStepTargetService.Update(jobStepTarget);

                        scriptBody = scriptBody.Replace(tempPassword, password);

                        var descriptor = new ScriptJobDescriptor
                        {
                            ScriptType      = script.ScriptType,
                            ScriptBody      = scriptBody,
                            SuccessKeywords = script.SuccessKeywords,
                            FailureKeywords = script.FailureKeywords,
                            RemoteExecution = planStep.RemoteExecution,
                            TargetID        = target.TargetID
                        };
                        var result = _scriptExecutionService.ExecuteScript(descriptor);

                        jobStepTarget.ExecutionOutput = result.Output;
                        if (!result.IsSuccessful)
                        {
                            throw new Exception("Script execution on target [{0}] was not successful."
                                                .FormatString(target.Name));
                        }

                        jobStepTarget.Status = DeploymentStatus.Finished;
                    }
                    catch (Exception ex)
                    {
                        jobStepTarget.Status = DeploymentStatus.Failed;
                        throw new Exception("Deployment step [{0}] failed for target [{1}]."
                                            .FormatString(planStep.Name, target.Name), ex);
                    }
                    finally
                    {
                        jobStepTarget.EndTime = DateTime.UtcNow;
                        _deploymentJobStepTargetService.Update(jobStepTarget);
                    }
                }
            }
        }
        private void ExecuteDeploymentSteps(DeploymentJob job)
        {
            var planSteps = _deploymentPlanStepService.GetEnabledForDeploymentPlan(job.DeploymentPlanID)
                            .OrderBy(s => s.ExecutionOrder)
                            .ToList();

            if (planSteps.IsNullOrEmpty())
            {
                return;
            }

            var targetGroupIDs = _targetGroupService.GetAllForProject(job.ProjectID)
                                 .OrderBy(g => g.Name)
                                 .Select(g => g.TargetGroupID)
                                 .ToArray();

            var environmentName = _projectEnvironmentService.GetByKey(job.ProjectEnvironmentID)
                                  .Name;

            foreach (var planStep in planSteps)
            {
                var jobStep = new DeploymentJobStep
                {
                    DeploymentJobID      = job.DeploymentJobID,
                    DeploymentPlanStepID = planStep.DeploymentPlanStepID,
                    Status             = DeploymentStatus.Running,
                    StartTime          = DateTime.UtcNow,
                    ExecutionReference = Guid.NewGuid()
                };
                _deploymentJobStepService.Insert(jobStep);

                try
                {
                    var script = _scriptService.GetWithParameters(planStep.ScriptID);

                    if (planStep.AllTargetGroups)
                    {
                        this.ExecuteDeploymentStepOnTargets(script, planStep, job, environmentName,
                                                            jobStep.DeploymentJobStepID, targetGroupIDs);
                    }
                    else if (planStep.TargetGroupID.HasValue)
                    {
                        this.ExecuteDeploymentStepOnTargets(script, planStep, job, environmentName,
                                                            jobStep.DeploymentJobStepID, planStep.TargetGroupID.Value);
                    }
                    else  // Execute on deployment server
                    {
                        jobStep.ExecutedScript = _variableService.ResolveVariables(
                            script, planStep, job, environmentName);
                        jobStep.ExecutionOutput = "Waiting for output...";
                        _deploymentJobStepService.Update(jobStep);

                        var descriptor = new ScriptJobDescriptor
                        {
                            ScriptType      = script.ScriptType,
                            ScriptBody      = jobStep.ExecutedScript,
                            SuccessKeywords = script.SuccessKeywords,
                            FailureKeywords = script.FailureKeywords
                        };
                        var result = _scriptExecutionService.ExecuteScript(descriptor);

                        jobStep.ExecutionOutput = result.Output;
                        if (!result.IsSuccessful)
                        {
                            throw new Exception("Script execution on deployment server was not successful.");
                        }
                    }

                    jobStep.Status = DeploymentStatus.Finished;
                }
                catch (Exception ex)
                {
                    jobStep.Status = DeploymentStatus.Failed;
                    throw new Exception("Deployment step [{0}] failed.".FormatString(planStep.Name), ex);
                }
                finally
                {
                    jobStep.EndTime = DateTime.UtcNow;
                    _deploymentJobStepService.Update(jobStep);
                }
            }
        }
        public IActionResult Delete(string id)
        {
            DeploymentJob deletedJob = _jobsDataAccess.DeleteJob(id);

            return(Ok(new DeploymentJobModel(deletedJob)));
        }
Exemplo n.º 18
0
 public DeploymentJobModel()
 {
     Jobs         = new DeploymentJob[0];
     ModelForView = new DeploymentModel();
     DomainModel  = new DeploymentJob();
 }