Exemplo n.º 1
0
        /// <summary>
        /// Deploys the content to one site.
        /// </summary>
        /// <param name="contentPath">The content path.</param>
        /// <param name="publishSettingsFile">The publish settings file.</param>
        /// <param name="password">The password.</param>
        /// <returns>DeploymentChangeSummary.</returns>
        public DeploymentChangeSummary DeployContentToOneSite(string contentPath, string publishSettingsFile, string password = null)
        {
            contentPath = Path.GetFullPath(contentPath);

            var sourceBaseOptions = new DeploymentBaseOptions();
            DeploymentBaseOptions destBaseOptions;
            string siteName = ParsePublishSettings(publishSettingsFile, out destBaseOptions);

            // use the password from the command line args if provided
            if (!string.IsNullOrEmpty(password))
            {
                destBaseOptions.Password = password;
            }

            // If the content path is a zip file, use the Package provider
            DeploymentWellKnownProvider provider;

            if (Path.GetExtension(contentPath).Equals(".zip", StringComparison.OrdinalIgnoreCase))
            {
                provider = DeploymentWellKnownProvider.Package;
            }
            else
            {
                provider = DeploymentWellKnownProvider.ContentPath;
            }

            // Publish the content to the remote site
            using (var deploymentObject = DeploymentManager.CreateObject(provider, contentPath, sourceBaseOptions))
            {
                // Note: would be nice to have an async flavor of this API...
                return(deploymentObject.SyncTo(DeploymentWellKnownProvider.ContentPath, siteName, destBaseOptions, new DeploymentSyncOptions()));
            }
        }
Exemplo n.º 2
0
        public async Task <HttpResponseMessage> WarPushDeploy(
            [FromUri] bool isAsync       = false,
            [FromUri] string author      = null,
            [FromUri] string authorEmail = null,
            [FromUri] string deployer    = DefaultDeployer,
            [FromUri] string message     = DefaultMessage)
        {
            using (_tracer.Step("WarPushDeploy"))
            {
                var deploymentInfo = new ZipDeploymentInfo(_environment, _traceFactory)
                {
                    AllowDeploymentWhileScmDisabled = true,
                    Deployer                = deployer,
                    TargetPath              = Path.Combine("webapps", "ROOT"),
                    WatchedFilePath         = Path.Combine("WEB-INF", "web.xml"),
                    IsContinuous            = false,
                    AllowDeferredDeployment = false,
                    IsReusable              = false,
                    TargetChangeset         = DeploymentManager.CreateTemporaryChangeSet(message: "Deploying from pushed war file"),
                    CommitId                = null,
                    RepositoryType          = RepositoryType.None,
                    Fetch = LocalZipFetch,
                    DoFullBuildByDefault = false,
                    Author      = author,
                    AuthorEmail = authorEmail,
                    Message     = message
                };

                return(await PushDeployAsync(deploymentInfo, isAsync));
            }
        }
        public async Task <IActionResult> ZipPushDeployViaUrl(
            [FromBody] JObject requestJson,
            [FromQuery] bool isAsync       = false,
            [FromQuery] bool syncTriggers  = false,
            [FromQuery] string author      = null,
            [FromQuery] string authorEmail = null,
            [FromQuery] string deployer    = DefaultDeployer,
            [FromQuery] string message     = DefaultMessage)
        {
            using (_tracer.Step("ZipPushDeployViaUrl"))
            {
                string zipUrl = GetZipURLFromJSON(requestJson);

                var deploymentInfo = new ZipDeploymentInfo(_environment, _traceFactory)
                {
                    AllowDeploymentWhileScmDisabled = true,
                    Deployer                = deployer,
                    IsContinuous            = false,
                    AllowDeferredDeployment = false,
                    IsReusable              = false,
                    TargetChangeset         =
                        DeploymentManager.CreateTemporaryChangeSet(message: "Deploying from pushed zip file"),
                    CommitId             = null,
                    RepositoryType       = RepositoryType.None,
                    Fetch                = LocalZipHandler,
                    DoFullBuildByDefault = false,
                    Author               = author,
                    AuthorEmail          = authorEmail,
                    Message              = message,
                    ZipURL               = zipUrl,
                    DoSyncTriggers       = syncTriggers
                };
                return(await PushDeployAsync(deploymentInfo, isAsync, HttpContext));
            }
        }
        ///<inheritdoc />
        public virtual IProcessInstance Execute(ICommandContext commandContext)
        {
            if (messageName is null)
            {
                throw new ActivitiIllegalArgumentException("Cannot start process instance by message: message name is null");
            }

            IMessageEventSubscriptionEntity messageEventSubscription = commandContext.EventSubscriptionEntityManager.FindMessageStartEventSubscriptionByName(messageName, tenantId);

            if (messageEventSubscription == null)
            {
                throw new ActivitiObjectNotFoundException("Cannot start process instance by message: no subscription to message with name '" + messageName + "' found.", typeof(IMessageEventSubscriptionEntity));
            }

            string processDefinitionId = messageEventSubscription.Configuration;

            if (string.IsNullOrWhiteSpace(processDefinitionId))
            {
                throw new ActivitiException("Cannot start process instance by message: subscription to message with name '" + messageName + "' is not a message start event.");
            }

            DeploymentManager deploymentCache = commandContext.ProcessEngineConfiguration.DeploymentManager;

            IProcessDefinition processDefinition = deploymentCache.FindDeployedProcessDefinitionById(processDefinitionId);

            if (processDefinition == null)
            {
                throw new ActivitiObjectNotFoundException("No process definition found for id '" + processDefinitionId + "'", typeof(IProcessDefinition));
            }

            ProcessInstanceHelper processInstanceHelper = commandContext.ProcessEngineConfiguration.ProcessInstanceHelper;
            IProcessInstance      processInstance       = processInstanceHelper.CreateAndStartProcessInstanceByMessage(processDefinition, messageName, processVariables, transientVariables);

            return(processInstance);
        }
Exemplo n.º 5
0
        private void FormLaunchWeb_Load(object sender, EventArgs e)
        {
            var iisexpress = new IISExpressManager();

            if (!iisexpress.IsInstalled)
            {
                panelError.Location = new Point(12, 76);
                panelError.Visible  = true;
                WireControlMove(panelError);
                return;
            }

            var deployment  = new DeploymentManager(Program.Path);
            var productList = deployment.Products;

            productList.Reverse();

            foreach (var prod in productList.Where(prod => prod != "argos-saleslogix"))
            {
                AddProduct(prod);
            }

            if (productList.Contains("argos-saleslogix"))
            {
                AddProduct("argos-saleslogix");
            }

            labelPath.Text = string.Format("Path:  {0}", Program.Path);
            toolTip1.SetToolTip(labelPath, "Mobile Environment Path:\r\n" + Program.Path);
        }
Exemplo n.º 6
0
        public void GetExecutionPlan_WhereTaskHasDuplicateExplicitHostsProvided_ReturnsOnePlan()
        {
            // Arrange
            var taskblock = typeof(DuplicateExplicitHosts);
            var host = new Host
            {
                Hostname = SomeHostname
            };
            var config = new DeploymentConfig
            {
                Hosts = new[]
                {
                    host
                }
            };

            var expected = new List<ExecutionPlan>
            {
                new ExecutionPlan(host, taskblock.GetObjMethods("Task1"))
            };

            // Act
            var manager = new DeploymentManager<DuplicateExplicitHosts>(config);
            var actual = manager.GetExecutionPlans();

            // Assert
            CollectionAssert.AreEqual(
                expected.OrderBy(p => p.Host.Hostname).ToList(),
                actual.OrderBy(p => p.Host.Hostname).ToList());
        }
Exemplo n.º 7
0
        public virtual IProcessInstance Execute(ICommandContext commandContext)
        {
            if (this.startCmd != null)
            {
                return(this.StartFromCommand(commandContext));
            }
            else
            {
                DeploymentManager deploymentCache = commandContext.ProcessEngineConfiguration.DeploymentManager;

                // Find the process definition
                IProcessDefinition processDefinition;
                if (!string.IsNullOrWhiteSpace(processDefinitionId))
                {
                    processDefinition = deploymentCache.FindDeployedProcessDefinitionById(processDefinitionId);
                    if (processDefinition == null)
                    {
                        throw new ActivitiObjectNotFoundException("No process definition found for id = '" + processDefinitionId + "'", typeof(IProcessDefinition));
                    }
                }
                else if (processDefinitionKey is object && (tenantId is null || ProcessEngineConfiguration.NO_TENANT_ID.Equals(tenantId)))
                {
                    processDefinition = deploymentCache.FindDeployedLatestProcessDefinitionByKey(processDefinitionKey);
                    if (processDefinition == null)
                    {
                        throw new ActivitiObjectNotFoundException("No process definition found for key '" + processDefinitionKey + "'", typeof(IProcessDefinition));
                    }
                }
Exemplo n.º 8
0
        public virtual IProcessInstance Execute(ICommandContext commandContext)
        {
            DeploymentManager deploymentCache = commandContext.ProcessEngineConfiguration.DeploymentManager;

            IProcessDefinition processDefinition = deploymentCache.FindDeployedProcessDefinitionById(processDefinitionId);

            if (processDefinition == null)
            {
                throw new ActivitiObjectNotFoundException("No process definition found for id '" + processDefinitionId + "'", typeof(IProcessDefinition));
            }

            ProcessInstanceHelper processInstanceHelper = commandContext.ProcessEngineConfiguration.ProcessInstanceHelper;

            // Get model from cache
            Process process = ProcessDefinitionUtil.GetProcess(processDefinition.Id);

            if (process == null)
            {
                throw new ActivitiException("Cannot start process instance. Process model " + processDefinition.Name + " (id = " + processDefinition.Id + ") could not be found");
            }

            FlowElement initialFlowElement = process.FlowElements.FirstOrDefault(x => x.Id == activityId);

            IProcessInstance processInstance = processInstanceHelper.CreateAndStartProcessInstanceWithInitialFlowElement(processDefinition, businessKey, processInstanceName, initialFlowElement, process, processVariables, transientVariables, startProcessInstance);

            return(processInstance);
        }
Exemplo n.º 9
0
        public void Start(int publicationId, Action <int> machineDeploymentStarted, Action <int, bool> machineDeploymentComplete)
        {
            AspNetDeployEntities entities = new AspNetDeployEntities();

            Publication publication = entities.Publication
                                      .Include("Package.BundleVersion.Properties")
                                      .Include("Environment")
                                      .First(p => p.Id == publicationId);

            DeploymentManager deploymentManager = Factory.GetInstance <DeploymentManager>();

            DateTime deploymentStart = DateTime.UtcNow;

            deploymentManager.Deploy(
                publication.Id,
                machineId =>
            {
                machineDeploymentStarted(machineId);
            },
                (machineId, isSuccess) =>
            {
                machineDeploymentComplete(machineId, isSuccess);
            });

            publication.Package.BundleVersion.SetStringProperty("LastPublicationAttemptPackage", publication.PackageId.ToString());
            publication.Package.BundleVersion.SetStringProperty("LastDeploymentDuration-e" + publication.EnvironmentId, (DateTime.UtcNow - deploymentStart).TotalSeconds.ToString(CultureInfo.InvariantCulture));

            entities.SaveChanges();
        }
Exemplo n.º 10
0
        public void PublishFolder()
        {
            var oldColor = Console.ForegroundColor;

            Console.ForegroundColor = ConsoleColor.DarkGray;

            // Create temp files for the manifests
            System.Net.ServicePointManager.ServerCertificateValidationCallback = AllowCertificateCallback;
            DeploymentBaseOptions RemoteBaseOption = new DeploymentBaseOptions();
            DeploymentSyncOptions SyncOption       = new DeploymentSyncOptions();

            UpdateBaseOptions(RemoteBaseOption, _serviceUrl, _remoteSite, _user, _password);

            SyncOption.DoNotDelete = true;
            SyncOption.WhatIf      = false;


            DeploymentBaseOptions localBaseOptions = new DeploymentBaseOptions();

            using (DeploymentObject deploymentObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath, _localSourceFolder, localBaseOptions))
            {
                deploymentObject.SyncTo(DeploymentWellKnownProvider.ContentPath, _remoteSite, RemoteBaseOption, SyncOption);
            }

            Console.ForegroundColor = oldColor;
        }
Exemplo n.º 11
0
        public static void SyncWebApps(Profile src, Profile dest)
        {
            DeploymentSyncOptions syncOptions = new DeploymentSyncOptions();

            DeploymentBaseOptions sourceBaseOptions = new DeploymentBaseOptions();

            sourceBaseOptions.ComputerName       = "https://" + src.publishUrl + "/msdeploy.axd";
            sourceBaseOptions.UserName           = src.userName;
            sourceBaseOptions.Password           = src.userPwd;
            sourceBaseOptions.AuthenticationType = "basic";

            sourceBaseOptions.Trace += TraceEventHandler;

            sourceBaseOptions.TraceLevel = TraceLevel.Verbose;

            DeploymentBaseOptions destBaseOptions = new DeploymentBaseOptions();

            destBaseOptions.ComputerName       = "https://" + dest.publishUrl + "/msdeploy.axd";
            destBaseOptions.UserName           = dest.userName;
            destBaseOptions.Password           = dest.userPwd;
            destBaseOptions.AuthenticationType = "basic";


            destBaseOptions.Trace += TraceEventHandler;

            destBaseOptions.TraceLevel = TraceLevel.Verbose;

            DeploymentProviderOptions destProviderOptions = new DeploymentProviderOptions(DeploymentWellKnownProvider.ContentPath);

            destProviderOptions.Path = dest.sitename;
            DeploymentObject sourceObj = DeploymentManager.CreateObject(DeploymentWellKnownProvider.ContentPath, src.sitename, sourceBaseOptions);

            sourceObj.SyncTo(destProviderOptions, destBaseOptions, syncOptions);
        }
Exemplo n.º 12
0
        protected virtual GitDeploymentInfo GetDeploymentInfo(HttpRequestBase request, JObject payload, string targetBranch)
        {
            var sessionToken = payload.Value <JObject>("sessionToken");

            var info = new GitDeploymentInfo {
                RepositoryType = RepositoryType.Git
            };

            info.Deployer = GetDeployer();

            // even it is empty password we need to explicitly say so (with colon).
            // without colon, LibGit2Sharp is not working
            Uri remoteUrl = new Uri(_settings.GetValue("repoUrl"));

            info.RepositoryUrl = string.Format(CultureInfo.InvariantCulture, "{0}://{1}:@{2}{3}",
                                               remoteUrl.Scheme,
                                               sessionToken.Value <string>("token"),
                                               remoteUrl.Authority,
                                               remoteUrl.PathAndQuery);

            info.TargetChangeset = DeploymentManager.CreateTemporaryChangeSet(
                authorName: info.Deployer,
                authorEmail: info.Deployer,
                message: String.Format(CultureInfo.CurrentUICulture, Resources.Vso_Synchronizing)
                );

            return(info);
        }
Exemplo n.º 13
0
        public static void SyncDatabases(Profile src, Profile dest, string dbtype)
        {
            DeploymentSyncOptions syncOptions       = new DeploymentSyncOptions();
            DeploymentBaseOptions destBaseOptions   = new DeploymentBaseOptions();
            DeploymentBaseOptions sourceBaseOptions = new DeploymentBaseOptions();

            destBaseOptions.Trace       += TraceEventHandler;
            sourceBaseOptions.Trace     += TraceEventHandler;
            destBaseOptions.TraceLevel   = TraceLevel.Verbose;
            sourceBaseOptions.TraceLevel = TraceLevel.Verbose;

            DeploymentProviderOptions destProviderOptions = null;

            DeploymentObject sourceObj = null;

            if (dbtype.Equals("mysql", StringComparison.InvariantCultureIgnoreCase))
            {
                destProviderOptions      = new DeploymentProviderOptions(DeploymentWellKnownProvider.DBMySql);
                destProviderOptions.Path = dest.mysqlConnectionstring;
                sourceObj = DeploymentManager.CreateObject(DeploymentWellKnownProvider.DBMySql, src.mysqlConnectionstring, sourceBaseOptions);
            }
            else if (dbtype.Equals("sql", StringComparison.InvariantCultureIgnoreCase))
            {
                destProviderOptions      = new DeploymentProviderOptions(DeploymentWellKnownProvider.DBFullSql);
                destProviderOptions.Path = dest.sqlazureconnectionstring;
                sourceObj = DeploymentManager.CreateObject(DeploymentWellKnownProvider.DBFullSql, src.sqlazureconnectionstring, sourceBaseOptions);
            }
            if (sourceObj != null)
            {
                sourceObj.SyncTo(destProviderOptions, destBaseOptions, syncOptions);
            }
        }
Exemplo n.º 14
0
        public void GetExecutionPlan_WhereTaskHasDependencyNotSpecifiedForHost_AddsDependencyToPlan()
        {
            // Arrange
            var taskblock = typeof(InheritDependencies);
            var host = new Host
            {
                Hostname = SomeHostname
            };
            var config = new DeploymentConfig
            {
                Hosts = new[]
                {
                    host
                }
            };

            var expected = new List<ExecutionPlan>
            {
                new ExecutionPlan(host, taskblock.GetObjMethods("Task1", "Task2"))
            };

            // Act
            var manager = new DeploymentManager<InheritDependencies>(config);
            var actual = manager.GetExecutionPlans();

            // Assert
            CollectionAssert.AreEqual(
                expected.OrderBy(p => p.Host.Hostname).ToList(),
                actual.OrderBy(p => p.Host.Hostname).ToList());
        }
        private void getStatusScenarioButton_Click(object sender, RoutedEventArgs e)
        {
            scenario.Text            = "Scenario: DeploymentManager.GetStatus()";
            resultStatus.Text        = "Result Status:";
            resultExtendedError.Text = "Result ExtendedError:";
            resultImplication.Text   = "";

            // GetStatus() is a fast check to see if all of the packages the WindowsAppRuntime
            // requires and expects are present in in an Ok state.
            DeploymentResult result = DeploymentManager.GetStatus();

            // The two properties for a result include the resulting status and the extended
            // error code. The Status is usually the property of interest, as the ExtendedError is
            // typically used for diagnostic purposes or troubleshooting.
            resultStatus.Text        = "Result Status: " + result.Status.ToString();
            resultExtendedError.Text = "Result ExtendedError: " + result.ExtendedError.ToString();

            // Check the resulting Status.
            if (result.Status == DeploymentStatus.Ok)
            {
                resultImplication.Text = "The WindowsAppRuntime is ready for use!";
            }
            else
            {
                // A not-Ok status means it is not ready for us. The Status will indicate the
                // reason it is not Ok, such as some packages need to be installed.
                resultImplication.Text = "The WindowsAppRuntime is not ready for use.";
            }
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            string apiKey = Request.QueryString["apiKey"];

            if (!string.Equals(apiKey, GetApiKey()))
            {
                Response.Write("Invalid API Key");
                Sitecore.Diagnostics.Log.Warn("DeployMarketingDefinitions utility: Invalid API key", this);
                Response.End();
            }

            try
            {
                IServiceProvider         provider = ServiceLocator.ServiceProvider.GetService <IServiceProvider>();
                DefinitionManagerFactory factory  = provider.GetDefinitionManagerFactory();
                DeploymentManager        manager  = new DeploymentManager(factory);

                CultureInfo culture = CultureInfo.CurrentCulture;
                manager.DeployAllAsync <IMarketingAssetDefinition>(culture);

                Sitecore.Diagnostics.Log.Info("Deploying Marketing Definitions", this);
            }
            catch (Exception ex)
            {
                Sitecore.Diagnostics.Log.Error(string.Format("Deploying Marketing Definitions failed: {0}", ex.Message), this);
            }
        }
Exemplo n.º 17
0
        private void CreateOrDeleteAppOffline(bool create = true)
        {
            var sourceOptions      = WebDeployOptionsFactory.GetSourceOptions();
            var destinationOptions = WebDeployOptionsFactory.GetDestinationOptions(_settings);

            destinationOptions.Trace += WebDeployLogger.DestinationOptions_Trace;
            var syncOptions = WebDeployOptionsFactory.GetSyncOptions(_settings);

            if (!create)
            {
                syncOptions.DoNotDelete = false;
            }

            var sourceProvider      = DeploymentWellKnownProvider.ContentPath;
            var destinationProvider = DeploymentWellKnownProvider.ContentPath;

            using (var deploymentObject = DeploymentManager.CreateObject(sourceProvider, _tempAppOfflinePath, sourceOptions))
            {
                if (!create)
                {
                    syncOptions.DeleteDestination = true;
                }

                deploymentObject.SyncTo(destinationProvider, _settings.SiteName + "/app_offline.htm", destinationOptions, syncOptions);
            }
        }
Exemplo n.º 18
0
        /// <summary>
        /// Packages sites that are in IIS but not in local temp storage.
        /// There are new sites that have been deployed to this instance using Web Deploy.
        /// </summary>
        public void PackageSitesToLocal()
        {
            _logger.DebugFormat("[IIS => Local Storage] - Site deploy times: {0}", string.Join(",", _siteDeployTimes.Select(t => t.Key + " - " + t.Value).ToArray()));

            using (var serverManager = new ServerManager())
            {
                foreach (var site in serverManager.Sites.Where(s => !_sitesToExclude.Contains(s.Name)))
                {
                    var siteName = site.Name.Replace("-", ".").ToLowerInvariant();

                    if (!site.Name.Equals(AzureRoleEnvironment.RoleWebsiteName(), StringComparison.OrdinalIgnoreCase))
                    {
                        var sitePath             = Path.Combine(_localSitesPath, siteName);
                        var siteLastModifiedTime = GetFolderLastModifiedTimeUtc(sitePath);

                        if (!_siteDeployTimes.ContainsKey(siteName))
                        {
                            _siteDeployTimes.Add(siteName, siteLastModifiedTime);
                        }

                        _logger.DebugFormat("[IIS => Local Storage] - Site last modified time: '{0}'", siteLastModifiedTime);

                        // If the site has been modified since the last deploy, but not within the last {SyncWait}s (otherwise it might be mid-sync)
                        if (_siteDeployTimes[siteName] < siteLastModifiedTime && siteLastModifiedTime < DateTime.UtcNow.AddSeconds(-SyncWait))
                        {
                            // Update status to deployed
                            UpdateSyncStatus(siteName, SyncInstanceStatus.Deployed);

                            // Ensure the temp path exists
                            var tempSitePath = Path.Combine(_localTempPath, siteName);
                            if (!Directory.Exists(tempSitePath))
                            {
                                Directory.CreateDirectory(tempSitePath);
                            }

                            // Create a package of the site and move it to local temp sites
                            var packageFile = Path.Combine(tempSitePath, siteName + ".zip");
                            _logger.InfoFormat("[IIS => Local Storage] - Creating a package of the site '{0}' and moving it to local temp sites '{1}'", siteName, packageFile);
                            try
                            {
                                using (var deploymentObject = DeploymentManager.CreateObject(DeploymentWellKnownProvider.DirPath, sitePath))
                                {
                                    deploymentObject.SyncTo(DeploymentWellKnownProvider.Package, packageFile, new DeploymentBaseOptions(), new DeploymentSyncOptions());
                                }

                                _logger.DebugFormat(string.Format("Calling OnSiteUpdated event for {0}...", siteName));
                                OnSiteUpdated(siteName);
                                _siteDeployTimes[siteName] = DateTime.UtcNow;
                            }
                            catch (Exception ex)
                            {
                                UpdateSyncStatus(siteName, SyncInstanceStatus.Error, ex);
                                throw;
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 19
0
        public static async Task Main(string[] args)
        {
            await Bootstrap.StartNode(args, KillRecpientType.Service, IpcApplicationType.Client,
                                      ab =>
            {
                ab.OnMemberUp((context, system, cluster) =>
                {
                    string ApplyMongoUrl(string baseUrl, string repoKey, SharpRepositoryConfiguration configuration)
                    {
                        var builder = new MongoUrlBuilder(baseUrl)
                        {
                            DatabaseName = repoKey, ApplicationName = context.HostingEnvironment.ApplicationName
                        };
                        var mongoUrl = builder.ToString();

                        configuration.AddRepository(new MongoDbRepositoryConfiguration(repoKey, mongoUrl)
                        {
                            Factory = typeof(MongoDbConfigRepositoryFactory)
                        });

                        return(mongoUrl);
                    }

                    ServiceRegistry.Get(system)
                    .RegisterService(new RegisterService(
                                         context.HostingEnvironment.ApplicationName,
                                         cluster.SelfUniqueAddress,
                                         ServiceTypes.Infrastructure));

                    var connectionstring = system.Settings.Config.GetString("akka.persistence.snapshot-store.mongodb.connection-string");
                    if (string.IsNullOrWhiteSpace(connectionstring))
                    {
                        LogManager.GetCurrentClassLogger().Error("No Mongo DB Connection provided: Shutdown");
                        system.Terminate();
                        return;
                    }

                    var config            = new SharpRepositoryConfiguration();
                    var fileSystemBuilder = new VirtualFileFactory();

                    ApplyMongoUrl(connectionstring, CleanUpManager.RepositoryKey, config);

                    var url = ApplyMongoUrl(connectionstring, RepositoryManager.RepositoryKey, config);
                    RepositoryManager.InitRepositoryManager(system,
                                                            new RepositoryManagerConfiguration(config, fileSystemBuilder.CreateMongoDb(url),
                                                                                               DataTransferManager.New(system, "Repository-DataTransfer")));

                    url = ApplyMongoUrl(connectionstring, DeploymentManager.RepositoryKey, config);
                    DeploymentManager.InitDeploymentManager(system,
                                                            new DeploymentConfiguration(config,
                                                                                        fileSystemBuilder.CreateMongoDb(url),
                                                                                        DataTransferManager.New(system, "Deployment-DataTransfer"),
                                                                                        RepositoryApi.CreateProxy(system)));

                    ApplyMongoUrl(connectionstring, ServiceManagerDeamon.RepositoryKey, config);
                    ServiceManagerDeamon.Init(system, config);
                })
                .OnMemberRemoved((_, system, _) => system.Terminate());
            }, true)
Exemplo n.º 20
0
        // key goal is to create background tracer that is independent of request.
        public static void PerformBackgroundDeployment(DeploymentInfo deployInfo, IEnvironment environment, IDeploymentSettingsManager settings, TraceLevel traceLevel, Uri uri)
        {
            var tracer       = traceLevel <= TraceLevel.Off ? NullTracer.Instance : new XmlTracer(environment.TracePath, traceLevel);
            var traceFactory = new TracerFactory(() => tracer);

            var backgroundTrace = tracer.Step(XmlTracer.BackgroundTrace, new Dictionary <string, string>
            {
                { "url", uri.AbsolutePath },
                { "method", "POST" }
            });

            Task.Run(() =>
            {
                try
                {
                    // lock related
                    string lockPath           = Path.Combine(environment.SiteRootPath, Constants.LockPath);
                    string deploymentLockPath = Path.Combine(lockPath, Constants.DeploymentLockFile);
                    string statusLockPath     = Path.Combine(lockPath, Constants.StatusLockFile);
                    string hooksLockPath      = Path.Combine(lockPath, Constants.HooksLockFile);
                    var statusLock            = new LockFile(statusLockPath, traceFactory);
                    var hooksLock             = new LockFile(hooksLockPath, traceFactory);
                    var deploymentLock        = new DeploymentLockFile(deploymentLockPath, traceFactory);

                    var analytics = new Analytics(settings, new ServerConfiguration(), traceFactory);
                    var deploymentStatusManager = new DeploymentStatusManager(environment, analytics, statusLock);
                    var repositoryFactory       = new RepositoryFactory(environment, settings, traceFactory);
                    var siteBuilderFactory      = new SiteBuilderFactory(new BuildPropertyProvider(), environment);
                    var webHooksManager         = new WebHooksManager(tracer, environment, hooksLock);
                    var deploymentManager       = new DeploymentManager(siteBuilderFactory, environment, traceFactory, analytics, settings, deploymentStatusManager, deploymentLock, NullLogger.Instance, webHooksManager);
                    var fetchHandler            = new FetchHandler(tracer, deploymentManager, settings, deploymentStatusManager, deploymentLock, environment, null, repositoryFactory, null);

                    // Perform deployment
                    var acquired = deploymentLock.TryLockOperation(() =>
                    {
                        fetchHandler.PerformDeployment(deployInfo).Wait();
                    }, TimeSpan.Zero);

                    if (!acquired)
                    {
                        using (tracer.Step("Update pending deployment marker file"))
                        {
                            // REVIEW: This makes the assumption that the repository url is the same.
                            // If it isn't the result would be buggy either way.
                            FileSystemHelpers.SetLastWriteTimeUtc(fetchHandler._markerFilePath, DateTime.UtcNow);
                        }
                    }
                }
                catch (Exception ex)
                {
                    tracer.TraceError(ex);
                }
                finally
                {
                    backgroundTrace.Dispose();
                }
            });
        }
        public async Task <IHttpActionResult> PostValidate(AscDeployment deployment)
        {
            var template = await repository.GetTemplate(deployment.TemplateName);

            deployment.Template = template.TemplateData;
            var result = await DeploymentManager.ValidateDeployment(deployment);

            return(this.Ok(result));
        }
Exemplo n.º 22
0
 protected internal virtual void setDeploymentName(string deploymentId, DeploymentBuilderImpl deploymentBuilder, CommandContext commandContext)
 {
     if (!string.ReferenceEquals(deploymentId, null) && deploymentId.Length > 0)
     {
         DeploymentManager deploymentManager = commandContext.DeploymentManager;
         DeploymentEntity  deployment        = deploymentManager.findDeploymentById(deploymentId);
         deploymentBuilder.Deployment.Name = deployment.Name;
     }
 }
Exemplo n.º 23
0
        public static BpmnModel GetBpmnModel(string processDefinitionId)
        {
            DeploymentManager deploymentManager = Context.ProcessEngineConfiguration.DeploymentManager;

            // This will check the cache in the findDeployedProcessDefinitionById and resolveProcessDefinition method
            IProcessDefinition processDefinitionEntity = deploymentManager.FindDeployedProcessDefinitionById(processDefinitionId);

            return(deploymentManager.ResolveProcessDefinition(processDefinitionEntity).BpmnModel);
        }
Exemplo n.º 24
0
 public void DeployBpmnTest()
 {
     using (BpmDbContext db = new BpmDbContext())
     {
         DeploymentManager manager  = new DeploymentManager(db);
         string            bpmnFile = Directory.GetParent(Directory.GetCurrentDirectory()).Parent.Parent.FullName + "\\LosFlow.bpmn";
         manager.DeployBpmn(bpmnFile);
     }
 }
Exemplo n.º 25
0
        public RuntimeManager(Context context)
        {
            this.context           = context;
            this.deploymentManager = context.DeploymentManager;
            this.session           = context.DbSession;

            var options = context.Engine.Options;

            this.compositeProcessEventListener = new CompositeProcessEventListener(options.ProcessEventListeners);
        }
Exemplo n.º 26
0
 public void Reload(ProjectControlSourceItem item, ProjectControlSource source)
 {
     this.source          = source;
     this.item            = item;
     projectLabel.Content = item.Project;
     Timestamp            = item.Timestamp;
     bumper = new DeploymentManager(source, item);
     JSONinit();
     UpdateVersion();
 }
Exemplo n.º 27
0
        public override void ProcessRequestBase(HttpContextBase context)
        {
            using (Tracer.Step("RpcService.ReceivePack"))
            {
                // Ensure that the target directory does not have a non-Git repository.
                IRepository repository = _repositoryFactory.GetRepository();
                if (repository != null && repository.RepositoryType != RepositoryType.Git)
                {
                    context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    if (context.ApplicationInstance != null)
                    {
                        context.ApplicationInstance.CompleteRequest();
                    }
                    return;
                }

                bool acquired = DeploymentLock.TryLockOperation(() =>
                {
                    context.Response.ContentType = "application/x-git-receive-pack-result";

                    if (_autoSwapHandler.IsAutoSwapOngoing())
                    {
                        context.Response.StatusCode = (int)HttpStatusCode.Conflict;
                        context.Response.Write(Resources.Error_AutoSwapDeploymentOngoing);
                        context.ApplicationInstance.CompleteRequest();
                        return;
                    }

                    string username = null;
                    if (AuthUtility.TryExtractBasicAuthUser(context.Request, out username))
                    {
                        GitServer.SetDeployer(username);
                    }

                    UpdateNoCacheForResponse(context.Response);

                    // This temporary deployment is for ui purposes only, it will always be deleted via finally.
                    ChangeSet tempChangeSet;
                    using (DeploymentManager.CreateTemporaryDeployment(Resources.ReceivingChanges, out tempChangeSet))
                    {
                        GitServer.Receive(context.Request.GetInputStream(), context.Response.OutputStream);
                    }

                    // TODO: Currently we do not support auto-swap for git push due to an issue where we already sent the headers at the
                    // beginning of the deployment and cannot flag at this point to make the auto swap (by sending the proper headers).
                    //_autoSwapHandler.HandleAutoSwap(verifyActiveDeploymentIdChanged: true);
                }, TimeSpan.Zero);

                if (!acquired)
                {
                    context.Response.StatusCode = 409;
                    context.ApplicationInstance.CompleteRequest();
                }
            }
        }
Exemplo n.º 28
0
        public override void ProcessRequestBase(HttpContextBase context)
        {
            using (Tracer.Step("RpcService.ReceivePack"))
            {
                // Ensure that the target directory does not have a non-Git repository.
                IRepository repository = _repositoryFactory.GetRepository();
                if (repository != null && repository.RepositoryType != RepositoryType.Git)
                {
                    context.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    if (context.ApplicationInstance != null)
                    {
                        context.ApplicationInstance.CompleteRequest();
                    }
                    return;
                }

                try
                {
                    DeploymentLock.LockOperation(() =>
                    {
                        context.Response.ContentType = "application/x-git-receive-pack-result";

                        if (_autoSwapHandler.IsAutoSwapOngoing())
                        {
                            context.Response.StatusCode = (int)HttpStatusCode.Conflict;
                            context.Response.Write(Resources.Error_AutoSwapDeploymentOngoing);
                            context.ApplicationInstance.CompleteRequest();
                            return;
                        }

                        string username = null;
                        if (AuthUtility.TryExtractBasicAuthUser(context.Request, out username))
                        {
                            GitServer.SetDeployer(username);
                        }

                        UpdateNoCacheForResponse(context.Response);

                        // This temporary deployment is for ui purposes only, it will always be deleted via finally.
                        ChangeSet tempChangeSet;
                        using (DeploymentManager.CreateTemporaryDeployment(Resources.ReceivingChanges, out tempChangeSet))
                        {
                            GitServer.Receive(context.Request.GetInputStream(), context.Response.OutputStream);
                        }
                    }, "Handling git receive pack", TimeSpan.Zero);
                }
                catch (LockOperationException ex)
                {
                    context.Response.StatusCode = 409;
                    context.Response.Write(ex.Message);
                    context.ApplicationInstance.CompleteRequest();
                }
            }
        }
            private void InitClient(string connection)
            {
                _repository?.Stop();
                _repository = null;

                _deploymentServer?.Stop();
                _deploymentServer = null;

                _repository       = RepositoryManager.InitRepositoryManager(Context.System, connection, _dataTransfer);
                _deploymentServer = DeploymentManager.InitDeploymentManager(Context.System, connection, _dataTransfer, _repositoryApi);
            }
        public async Task <IHttpActionResult> Get(string resourceGroupName, string deploymentName, string subscriptionId)
        {
            var result = await DeploymentManager.GetDeployment(resourceGroupName, deploymentName, subscriptionId);

            var response = new
            {
                subscriptionId    = subscriptionId,
                provisioningState = result.Deployment.Properties.ProvisioningState,
                correlationId     = result.Deployment.Properties.CorrelationId
            };

            return(this.Ok(response));
        }
Exemplo n.º 31
0
        static void Main(string[] args)
        {
            var serializer = new XmlSerializer(typeof(Config));
            var config = (Config)serializer.Deserialize(XmlReader.Create(args[0]));

            var deploymentConfig = new DeploymentConfig<Config>
            {
                Hosts = config.Hosts
            };

            var manager = new DeploymentManager<Tasks, Config>(deploymentConfig);
            manager.BeginDeployments();
        }
Exemplo n.º 32
0
        protected void NewCluster(string clusterConfigurationFilePath, string fabricPackageSourcePath, bool noCleanupOnFailure, bool force, int maxPercentFailedNodes, uint timeoutInSeconds)
        {
            this.ChangeCurrentDirectoryToSession();
            clusterConfigurationFilePath = this.GetAbsolutePath(clusterConfigurationFilePath);
            fabricPackageSourcePath      = this.GetAbsolutePath(fabricPackageSourcePath);

            ClusterCreationOptions creationOptions = ClusterCreationOptions.None;

            if (noCleanupOnFailure)
            {
                creationOptions |= ClusterCreationOptions.OptOutCleanupOnFailure;
            }

            if (force)
            {
                creationOptions |= ClusterCreationOptions.Force;
            }

            TimeSpan?timeout = null;

            if (timeoutInSeconds > 0)
            {
                timeout = TimeSpan.FromSeconds(timeoutInSeconds);
            }

            try
            {
                this.WriteObject(StringResources.Info_CreatingServiceFabricCluster);
                this.WriteObject(StringResources.Info_CreatingServiceFabricClusterDebugDetails);
                DeploymentManager.CreateClusterAsync(
                    clusterConfigurationFilePath,
                    fabricPackageSourcePath,
                    creationOptions,
                    maxPercentFailedNodes,
                    timeout).Wait();

                var standAloneModel = StandAloneInstallerJsonModelBase.GetJsonConfigFromFile(clusterConfigurationFilePath);
                var node            = standAloneModel.Nodes[0];
                var nodeType        = standAloneModel.GetUserConfig().NodeTypes.Find(type => type.Name == node.NodeTypeRef);
                this.WriteObject(string.Format(StringResources.Info_CreateServiceFabricClusterSucceeded, node.IPAddress, nodeType.ClientConnectionEndpointPort));
            }
            catch (Exception exception)
            {
                this.WriteObject(StringResources.Error_CreateServiceFabricClusterFailed);
                this.WriteObject(exception.InnerException != null ? exception.InnerException.Message : exception.Message);
                this.ThrowTerminatingError(
                    exception,
                    Constants.NewNodeConfigurationErrorId,
                    null);
            }
        }
Exemplo n.º 33
0
        private static void ExecuteDeploy(
            string sourcePath,
            string destinationPath,
            DeploymentWellKnownProvider srcProvider,
            DeploymentBaseOptions srcBaseOptions,
            DeploymentWellKnownProvider destProvider,
            DeploymentBaseOptions destBaseOptions,
            DeploymentSyncOptions destSyncOptions,
            Func <string, string> syncParamResolver = null,
            IEnumerable <string> removedParameters  = null)
        {
            ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, e) => true;

            try
            {
                using (DeploymentObject deployObj = DeploymentManager.CreateObject(srcProvider, sourcePath, srcBaseOptions))
                {
                    // resolve parameters if any
                    if (syncParamResolver != null)
                    {
                        foreach (var syncParam in deployObj.SyncParameters)
                        {
                            var resolvedValue = syncParamResolver(syncParam.Name);
                            if (resolvedValue != null)
                            {
                                syncParam.Value = resolvedValue;
                            }
                        }
                    }

                    // remove parameters if any
                    if (removedParameters != null)
                    {
                        foreach (var parameter in removedParameters)
                        {
                            deployObj.SyncParameters.Remove(parameter);
                        }
                    }

                    TestEasyLog.Instance.Info(string.Format("Deploying: {0}", sourcePath));

                    // do action
                    TestEasyLog.Instance.LogObject(deployObj.SyncTo(destProvider, destinationPath, destBaseOptions, destSyncOptions));
                }
            }
            catch (Exception e)
            {
                TestEasyLog.Instance.Info(string.Format("Exception during deployment of '{0}': '{1}'", sourcePath, e.Message));
                throw;
            }
        }
Exemplo n.º 34
0
        public void GetExecutionPlan_WhereTaskHasOverlappingHostAndRole_ReturnsOnePlan()
        {
            // Arrange
            var taskblock = typeof(OverlappingHostAndRole);
            var host = new Host
            {
                Hostname = SomeHostname,
                Roles = new[] { SomeRole }
            };
            var config = new DeploymentConfig
            {
                Hosts = new[]
                {
                    host
                }
            };

            var expected = new List<ExecutionPlan>
            {
                new ExecutionPlan(host, taskblock.GetObjMethods("Task1"))
            };

            // Act
            var manager = new DeploymentManager<OverlappingHostAndRole>(config);
            var actual = manager.GetExecutionPlans();

            // Assert
            CollectionAssert.AreEqual(
                expected.OrderBy(p => p.Host.Hostname).ToList(),
                actual.OrderBy(p => p.Host.Hostname).ToList());
        }
 internal DeploymentConfigurationFileActivity(DeploymentManager manager)
 {
     Manager = manager;
 }
Exemplo n.º 36
0
 /// <summary>
 /// Sets the deployment manager and assumes that there will be a rebuild 
 /// </summary>
 public BuildActivity(DeploymentManager manager)
 {
     UseExistingBuild = false;
     _manager = manager;
 }
 /// <summary>
 /// Constructs a DeploymenTransaction class instance
 /// </summary>
 /// <param name="manager">The DeploymentManager class which has the transaction state and context necessary</param>
 public DeploymentTransaction(DeploymentManager manager)
 {
     _manager = manager;
     _blobClient = new BlobClient(_manager.SubscriptionId, Constants.DefaultBlobContainerName, _manager.StorageAccountName, _manager.StorageAccountKey);
 }
Exemplo n.º 38
0
 internal RoleReference(DeploymentManager manager)
 {
     _manager = manager;
 }
Exemplo n.º 39
0
        public void GetExecutionPlan_WhereTaskNotIncludedAsDependency_IsNotPresentInPlan()
        {
            // Arrange
            var taskblock = typeof(UnusedTask);
            var host = new Host
            {
                Hostname = SomeHostname
            };
            var config = new DeploymentConfig
            {
                Hosts = new[]
                {
                    host
                }
            };

            var expected = new List<ExecutionPlan>
            {
                new ExecutionPlan(host, taskblock.GetObjMethods("Task2", "Task3"))
            };

            // Act
            var manager = new DeploymentManager<UnusedTask>(config);
            var actual = manager.GetExecutionPlans();

            // Assert
            CollectionAssert.AreEqual(
                expected.OrderBy(p => p.Host.Hostname).ToList(),
                actual.OrderBy(p => p.Host.Hostname).ToList());
        }
Exemplo n.º 40
0
        public void GetExecutionPlan_WhereTaskHasOneRoleAttributeAndMultipleHostsProvided_ReturnsMultiplePlans()
        {
            // Arrange
            var taskblock = typeof(RoleMultipleHosts);
            var host = new Host
            {
                Hostname = SomeHostname,
                Roles = new[] { SomeRole }
            };
            var host2 = new Host
            {
                Hostname = SomeHostname2,
                Roles = new[] { SomeRole }
            };
            var config = new DeploymentConfig
            {
                Hosts = new[]
                {
                    host,
                    host2
                }
            };

            var expected = new List<ExecutionPlan>
            {
                new ExecutionPlan(host, taskblock.GetObjMethods("Task1")),
                new ExecutionPlan(host2, taskblock.GetObjMethods("Task1"))
            };

            // Act
            var manager = new DeploymentManager<RoleMultipleHosts>(config);
            var actual = manager.GetExecutionPlans();

            // Assert
            CollectionAssert.AreEqual(
                expected.OrderBy(p => p.Host.Hostname).ToList(),
                actual.OrderBy(p => p.Host.Hostname).ToList());
        }
Exemplo n.º 41
0
        public void GetExecutionPlan_WhereTaskHasOneHostAttributeAndAliasProvided_ReturnsOnePlan()
        {
            // Arrange
            var taskblock = typeof(HostAttrs);
            var host = new Host
            {
                Alias = SomeHostname,
                Hostname = "something else"
            };
            var config = new DeploymentConfig
            {
                Hosts = new[]
                {
                    host
                }
            };

            var expected = new List<ExecutionPlan>
            {
                new ExecutionPlan(host, taskblock.GetObjMethods("Task1"))
            };

            // Act
            var manager = new DeploymentManager<HostAttrs>(config);
            var actual = manager.GetExecutionPlans();

            // Assert
            CollectionAssert.AreEqual(
                expected.OrderBy(p => p.Host.Hostname).ToList(),
                actual.OrderBy(p => p.Host.Hostname).ToList());
        }
 /// <summary>
 /// Constructs a DeploymenTransaction class instance
 /// </summary>
 /// <param name="manager">The DeploymentManager class which has the transaction state and context necessary</param>
 public DeploymentTransaction(DeploymentManager manager)
 {
     _manager = manager;
 }
 /// <summary>
 /// Used to construct the HostedServiceActivity
 /// </summary>
 /// <param name="manager">The DeploymentManager class</param>
 public HostedServiceActivity(DeploymentManager manager)
 {
     _manager = manager;
 }
Exemplo n.º 44
0
        public void GetExecutionPlan_WhereTaskHasInitializationAndCleanup_ReturnsInitializationFirstAndCleanupLast()
        {
            // Arrange
            var taskblock = typeof(InitializationAndCleanup);
            var host = new Host
            {
                Hostname = SomeHostname
            };
            var config = new DeploymentConfig
            {
                Hosts = new[]
                {
                    host
                }
            };

            var expected = new List<ExecutionPlan>
            {
                new ExecutionPlan(host, taskblock.GetObjMethods("Init", "Task1", "Cleanup"))
            };

            // Act
            var manager = new DeploymentManager<InitializationAndCleanup>(config);
            var actual = manager.GetExecutionPlans();

            // Assert
            CollectionAssert.AreEqual(expected.ToList(), actual.ToList());
        }
 /// <summary>
 /// Used to construct the HostedServiceActivity
 /// </summary>
 /// <param name="manager">The DeploymentManager class</param>
 public HostedServiceActivity(DeploymentManager manager)
 {
     _manager = manager;
     _client = new ServiceClient(_manager.SubscriptionId, _manager.ManagementCertificate, _manager.HostedServiceName);
 }