Exemple #1
0
        protected internal virtual DeploymentEntity initDeployment()
        {
            DeploymentEntity deployment = deploymentBuilder.Deployment;

            deployment.DeploymentTime = ClockUtil.CurrentTime;
            return(deployment);
        }
Exemple #2
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Before public void setup()
        public virtual void setup()
        {
            modelInstance = Cmmn.createEmptyModel();
            definitions   = modelInstance.newInstance(typeof(Definitions));
            definitions.TargetNamespace = "http://camunda.org/examples";
            modelInstance.Definitions   = definitions;

            caseDefinition = createElement(definitions, "aCaseDefinition", typeof(Case));
            casePlanModel  = createElement(caseDefinition, "aCasePlanModel", typeof(CasePlanModel));

            context = new CmmnHandlerContext();

            CaseDefinitionEntity caseDefinition = new CaseDefinitionEntity();

            caseDefinition.TaskDefinitions = new Dictionary <string, TaskDefinition>();
            context.CaseDefinition         = caseDefinition;

            ExpressionManager expressionManager = new ExpressionManager();

            context.ExpressionManager = expressionManager;

            DeploymentEntity deployment = new DeploymentEntity();

            deployment.Id      = "foo";
            context.Deployment = deployment;
        }
        //TODO cache未实现
        public virtual T ResolveDefinition(T definition)
        {
            string definitionId = ((IResourceDefinition)definition).Id;

            string deploymentId     = definition.DeploymentId;
            T      cachedDefinition = cache.Get(definitionId);

            if (cachedDefinition == null)  //双层If+Lock
            {
                lock (this)
                {
                    cachedDefinition = cache.Get(definitionId);
                    // cachedDefinition = Context.CommandContext.DeploymentManager.Get(definitionId) as T;
                    if (cachedDefinition == null)
                    {
                        DeploymentEntity deployment = Context.CommandContext.DeploymentManager.FindDeploymentById(deploymentId);
                        deployment.IsNew = false;
                        CacheDeployer.DeployOnlyGivenResourcesOfDeployment(deployment, definition.ResourceName, definition.DiagramResourceName);
                        cachedDefinition = cache.Get(definitionId);
                    }
                }
                CheckInvalidDefinitionWasCached(deploymentId, definitionId, cachedDefinition);
            }
            return(cachedDefinition);
        }
Exemple #4
0
        protected internal virtual IProcessApplicationRegistration RegisterProcessApplication(
            CommandContext commandContext, DeploymentEntity deployment, ISet <string> processKeysToRegisterFor)
        {
            var appDeploymentBuilder = (ProcessApplicationDeploymentBuilderImpl)deploymentBuilder;
            var appReference         = appDeploymentBuilder.ProcessApplicationReference;

            // build set of deployment ids this process app should be registered for:
            List <string> deploymentsToRegister = new List <string>()
            {
                deployment.Id
            };

            if (appDeploymentBuilder.IsResumePreviousVersions())
            {
                if (ResumePreviousBy.ResumeByProcessDefinitionKey == appDeploymentBuilder.ResumePreviousVersionsByRenamed)
                {
                    deploymentsToRegister.AddRange(ResumePreviousByProcessDefinitionKey(commandContext, deployment, processKeysToRegisterFor));
                }
                else if (ResumePreviousBy.ResumeByDeploymentName == appDeploymentBuilder.ResumePreviousVersionsByRenamed)
                {
                    deploymentsToRegister.AddRange(ResumePreviousByDeploymentName(commandContext, deployment));
                }
            }

            // register process application for deployments
            return((new RegisterProcessApplicationCmd(deploymentsToRegister, appReference)).Execute(commandContext));
        }
Exemple #5
0
        public async Task CreateAsync_OK()
        {
            // Arrange
            DeploymentModel deploymentModel = new DeploymentModel
            {
                TagName = "1",
            };

            deploymentModel.Environment = new EnvironmentModel
            {
                Name     = "at23",
                Hostname = "hostname"
            };

            _releaseRepository.Setup(r => r.GetSucceededReleaseFromDb(
                                         It.IsAny <string>(),
                                         It.IsAny <string>(),
                                         It.IsAny <string>())).ReturnsAsync(GetReleases("updatedRelease.json").First());

            _applicationInformationService.Setup(ais => ais.UpdateApplicationInformationAsync(
                                                     It.IsAny <string>(),
                                                     It.IsAny <string>(),
                                                     It.IsAny <string>(),
                                                     It.IsAny <EnvironmentModel>())).Returns(Task.CompletedTask);

            Mock <IAzureDevOpsBuildClient> azureDevOpsBuildClient = new Mock <IAzureDevOpsBuildClient>();

            azureDevOpsBuildClient.Setup(b => b.QueueAsync(
                                             It.IsAny <QueueBuildParameters>(),
                                             It.IsAny <int>())).ReturnsAsync(GetBuild());

            _deploymentRepository.Setup(r => r.Create(
                                            It.IsAny <DeploymentEntity>())).ReturnsAsync(GetDeployments("createdDeployment.json").First());

            DeploymentService deploymentService = new DeploymentService(
                new TestOptionsMonitor <AzureDevOpsSettings>(GetAzureDevOpsSettings()),
                azureDevOpsBuildClient.Object,
                _httpContextAccessor.Object,
                _deploymentRepository.Object,
                _releaseRepository.Object,
                _applicationInformationService.Object);

            // Act
            DeploymentEntity deploymentEntity = await deploymentService.CreateAsync(deploymentModel);

            // Assert
            Assert.NotNull(deploymentEntity);
            _releaseRepository.Verify(
                r => r.GetSucceededReleaseFromDb(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()), Times.Once);
            _applicationInformationService.Verify(
                ais => ais.UpdateApplicationInformationAsync(
                    It.IsAny <string>(),
                    It.IsAny <string>(),
                    It.IsAny <string>(),
                    It.IsAny <EnvironmentModel>()),
                Times.Once);
            azureDevOpsBuildClient.Verify(
                b => b.QueueAsync(It.IsAny <QueueBuildParameters>(), It.IsAny <int>()), Times.Once);
            _deploymentRepository.Verify(r => r.Create(It.IsAny <DeploymentEntity>()), Times.Once);
        }
Exemple #6
0
        /// <inheritdoc/>
        public async Task <DeploymentEntity> Create(DeploymentEntity deploymentEntity)
        {
            try
            {
                using NpgsqlConnection conn = new NpgsqlConnection(_connectionString);
                await conn.OpenAsync();

                NpgsqlCommand pgcom = new NpgsqlCommand(insertDeploymentSql, conn);
                pgcom.Parameters.AddWithValue("buildid", deploymentEntity.Build.Id);
                pgcom.Parameters.AddWithValue("tagName", deploymentEntity.TagName);
                pgcom.Parameters.AddWithValue("org", deploymentEntity.Org);
                pgcom.Parameters.AddWithValue("app", deploymentEntity.App);
                pgcom.Parameters.AddWithValue("buildresult", deploymentEntity.Build.Result.ToEnumMemberAttributeValue());
                pgcom.Parameters.AddWithValue("created", deploymentEntity.Created);
                pgcom.Parameters.AddWithValue("entity", JsonString(deploymentEntity));

                await pgcom.ExecuteNonQueryAsync();

                return(deploymentEntity);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "DeploymentRepository // Create // Exception");
                throw;
            }
        }
Exemple #7
0
        /// <inheritdoc/>
        public async Task <IEnumerable <DeploymentEntity> > Get(DocumentQueryModel query)
        {
            List <DeploymentEntity> searchResult = new List <DeploymentEntity>();

            try
            {
                using NpgsqlConnection conn = new NpgsqlConnection(_connectionString);
                await conn.OpenAsync();

                NpgsqlCommand pgcom = new NpgsqlCommand(getDeploymentsSql, conn);
                pgcom.Parameters.AddWithValue("_org", NpgsqlDbType.Varchar, query.Org);
                pgcom.Parameters.AddWithValue("_app", NpgsqlDbType.Varchar, query.App);
                pgcom.Parameters.AddWithValue("_limit", NpgsqlDbType.Integer, query.Top ?? int.MaxValue);
                pgcom.Parameters.AddWithValue("_order_asc_desc", NpgsqlDbType.Varchar, query.SortDirection == SortDirection.Ascending ? "asc" : "desc");

                using (NpgsqlDataReader reader = pgcom.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        DeploymentEntity deploymentEntity = Deserialize(reader[0].ToString());
                        searchResult.Add(deploymentEntity);
                    }
                }

                return(searchResult);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "DeploymentRepository // Get(DocumentQueryModel) // Exception");
                throw;
            }
        }
Exemple #8
0
        /// <inheritdoc/>
        public async Task <DeploymentEntity> Get(string org, string buildId)
        {
            try
            {
                DeploymentEntity deploymentEntity = null;
                using NpgsqlConnection conn = new NpgsqlConnection(_connectionString);
                await conn.OpenAsync();

                NpgsqlCommand pgcom = new NpgsqlCommand(getDeploymentSql, conn);
                pgcom.Parameters.AddWithValue("_org", NpgsqlDbType.Varchar, org);
                pgcom.Parameters.AddWithValue("_buildid", NpgsqlDbType.Varchar, buildId);

                using (NpgsqlDataReader reader = pgcom.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        deploymentEntity = Deserialize(reader[0].ToString());
                    }
                }

                return(deploymentEntity);
            }
            catch (Exception e)
            {
                _logger.LogError(e, "DeploymentRepository // Get(string org, string buildId) // Exception");
                throw;
            }
        }
Exemple #9
0
        //JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
        //ORIGINAL LINE: @SuppressWarnings("unchecked") public java.util.Map<String, ResourceEntity> findLatestResourcesByDeploymentName(String deploymentName, java.util.ISet<string> resourcesToFind, String source, String tenantId)
        public virtual IDictionary <string, ResourceEntity> FindLatestResourcesByDeploymentName(string deploymentName, ISet <string> resourcesToFind, string source, string tenantId)
        {
            //IDictionary<string, object> @params = new Dictionary<string, object>();
            //@params["deploymentName"] = deploymentName;//"BpmProcessEngineCmdTest"
            //@params["resourcesToFind"] = resourcesToFind;//"BpmnParseTest.testInvalidSubProcessWithCompensationStartEvent.bpmn"
            //@params["source"] = source;//"process application"
            //@params["tenantId"] = tenantId;
            //IList<ResourceEntity> resources = ListExt.ConvertToListT<ResourceEntity>(DbEntityManager.SelectList("selectLatestResourcesByDeploymentName", @params));
            //throw new System.NotImplementedException("复杂查询");
            //重写查询 source数据库为null 暂时忽略source @params["source"] = source;//"process application" 解析不到
            IList <ResourceEntity> resources = new List <ResourceEntity>();

            DeploymentEntity lastDeploy = context.Impl.Context.CommandContext.DeploymentManager.FindLatestDeploymentByName(deploymentName);

            if (lastDeploy != null)
            {
                resources = Find(m => m.DeploymentId == lastDeploy.Id && resourcesToFind.Contains(m.Name) && m.TenantId == tenantId).ToList();
            }

            IDictionary <string, ResourceEntity> existingResourcesByName = new Dictionary <string, ResourceEntity>();

            foreach (ResourceEntity existingResource in resources)
            {
                existingResourcesByName[existingResource.Name] = existingResource;
            }

            return(existingResourcesByName);
        }
Exemple #10
0
 protected internal virtual void updateDefinitionByPersistedDefinition(DeploymentEntity deployment, DefinitionEntity definition, DefinitionEntity persistedDefinition)
 {
     definition.Version      = persistedDefinition.Version;
     definition.Id           = persistedDefinition.Id;
     definition.DeploymentId = deployment.Id;
     definition.TenantId     = persistedDefinition.TenantId;
 }
Exemple #11
0
 protected internal virtual void updateDefinitionByLatestDefinition(DeploymentEntity deployment, DefinitionEntity definition, DefinitionEntity latestDefinition)
 {
     definition.Version      = getNextVersion(deployment, definition, latestDefinition);
     definition.Id           = generateDefinitionId(deployment, definition, latestDefinition);
     definition.DeploymentId = deployment.Id;
     definition.TenantId     = deployment.TenantId;
 }
        /// <inheritdoc />
        public async Task <string> CreateDeploymentAsync(DeploymentEntity deployment)
        {
            // Handle the potential case of a null value being passed as deployment
            if (deployment == null)
            {
                throw new ArgumentNullException(nameof(deployment), "Parameter deployment must not be null.");
            }

            // Expand potential port ranges in the deployment entity
            var expandedPorts = DeploymentUtils.ExpandPortRanges(deployment.Ports);

            deployment.Ports = expandedPorts;

            // Create a unique identifier for the deployment
            var id                   = Guid.NewGuid().ToString();
            var deploymentPath       = Path.Combine(_storage, $"{id}.yaml");
            var serializedDeployment = _yamlSerializer.Serialize(deployment);

            // Check if the deployment is already existent; should not happen!
            if (File.Exists(deploymentPath))
            {
                return(null);
            }

            // Write out the serialized deployment to a YAML file
            await using (var streamWriter = File.CreateText(deploymentPath))
            {
                await streamWriter.WriteLineAsync(serializedDeployment);
            }

            _logger.LogInformation("Successfully created deployment with id '{Id}'.", id);
            return(id);
        }
        /// <inheritdoc/>
        public async Task <DeploymentEntity> CreateAsync(DeploymentModel deployment)
        {
            DeploymentEntity deploymentEntity = new DeploymentEntity();

            deploymentEntity.PopulateBaseProperties(_org, _app, _httpContext);
            deploymentEntity.TagName         = deployment.TagName;
            deploymentEntity.EnvironmentName = deployment.Environment.Name;

            ReleaseEntity release = await _releaseRepository.GetSucceededReleaseFromDb(
                deploymentEntity.Org,
                deploymentEntity.App,
                deploymentEntity.TagName);

            await _applicationInformationService
            .UpdateApplicationInformationAsync(_org, _app, release.TargetCommitish, deployment.Environment);

            Build queuedBuild = await QueueDeploymentBuild(release, deploymentEntity, deployment.Environment.Hostname);

            deploymentEntity.Build = new BuildEntity
            {
                Id      = queuedBuild.Id.ToString(),
                Status  = queuedBuild.Status,
                Started = queuedBuild.StartTime
            };

            return(await _deploymentRepository.CreateAsync(deploymentEntity));
        }
Exemple #14
0
 protected internal override void updateDefinitionByPersistedDefinition(DeploymentEntity deployment, DecisionRequirementsDefinitionEntity definition, DecisionRequirementsDefinitionEntity persistedDefinition)
 {
     // cannot update the definition if it is not persistent
     if (persistedDefinition != null)
     {
         base.updateDefinitionByPersistedDefinition(deployment, definition, persistedDefinition);
     }
 }
Exemple #15
0
        protected internal virtual DeploymentEntity InitDeployment()
        {
            DeploymentEntity deployment = deploymentBuilder.Deployment;

            //TODO 线程开始的时间,Reset重置为当前时间
            deployment.DeploymentTime = ClockUtil.CurrentTime;
            return(deployment);
        }
Exemple #16
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;
     }
 }
 protected void LoadScriptSource()
 {
     if (GetScriptSource() == null)
     {
         DeploymentEntity deployment = Context.CoreExecutionContext.Deployment;//.GetCoreExecutionContext().getDeployment();
         String           source     = ResourceUtil.LoadResourceContent(scriptResource, deployment);
         SetScriptSource(source);
     }
 }
Exemple #18
0
        public virtual void deploy(DeploymentEntity deployment)
        {
            LOG.debugProcessingDeployment(deployment.Name);
            Properties properties = new Properties();
            IList <DefinitionEntity> definitions = parseDefinitionResources(deployment, properties);

            ensureNoDuplicateDefinitionKeys(definitions);
            postProcessDefinitions(deployment, definitions, properties);
        }
Exemple #19
0
        public virtual void Deploy(DeploymentEntity deployment)
        {
            LOG.DebugProcessingDeployment(deployment.Name);
            var properties = new Dictionary <string, object>();
            IList <TDefinitionEntity> definitions = ParseDefinitionResources(deployment, new Core.Model.Properties(properties));

            EnsureNoDuplicateDefinitionKeys(definitions);
            //Post 把流程定义实例写入持久层(薪)/更新流程定义(旧) 及放到上下文中 供其它领域模型使用
            PostProcessDefinitions(deployment, definitions, new Core.Model.Properties(properties));
        }
Exemple #20
0
        /// <summary>
        /// per default we increment the latest definition version by one - but you
        /// might want to hook in some own logic here, e.g. to align definition
        /// versions with deployment / build versions.
        /// </summary>
        protected internal virtual int getNextVersion(DeploymentEntity deployment, DefinitionEntity newDefinition, DefinitionEntity latestDefinition)
        {
            int result = 1;

            if (latestDefinition != null)
            {
                int latestVersion = latestDefinition.Version;
                result = latestVersion + 1;
            }
            return(result);
        }
Exemple #21
0
 public virtual void checkReadDeployment(string deploymentId)
 {
     if (TenantManager.TenantCheckEnabled)
     {
         DeploymentEntity deployment = findDeploymentById(deploymentId);
         if (deployment != null && !TenantManager.isAuthenticatedTenant(deployment.TenantId))
         {
             throw LOG.exceptionCommandWithUnauthorizedTenant("get the deployment '" + deploymentId + "'");
         }
     }
 }
Exemple #22
0
        /// <inheritdoc/>
        public async Task UpdateAsync(DeploymentEntity deployment, string appOwner)
        {
            DeploymentEntity deploymentEntity = await _deploymentRepository.Get(appOwner, deployment.Build.Id);

            deploymentEntity.Build.Status   = deployment.Build.Status;
            deploymentEntity.Build.Result   = deployment.Build.Result;
            deploymentEntity.Build.Started  = deployment.Build.Started;
            deploymentEntity.Build.Finished = deployment.Build.Finished;

            await _deploymentRepository.Update(deploymentEntity);
        }
Exemple #23
0
        protected internal virtual void loadDefinitions(DeploymentEntity deployment, IList <DefinitionEntity> definitions, Properties properties)
        {
            foreach (DefinitionEntity definition in definitions)
            {
                string deploymentId  = deployment.Id;
                string definitionKey = definition.Key;

                DefinitionEntity persistedDefinition = findDefinitionByDeploymentAndKey(deploymentId, definitionKey);
                handlePersistedDefinition(definition, persistedDefinition, deployment, properties);
            }
        }
 public virtual void CheckDeleteDeployment(string deploymentId)
 {
     if (TenantManager.TenantCheckEnabled)
     {
         DeploymentEntity deployment = FindDeploymentById(deploymentId);
         if (deployment != null && !TenantManager.IsAuthenticatedTenant(deployment.TenantId))
         {
             throw Log.ExceptionCommandWithUnauthorizedTenant("delete the deployment '" + deploymentId + "'");
         }
     }
 }
Exemple #25
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Before public void setUp()
        public virtual void setUp()
        {
            context = new CmmnHandlerContext();

            DeploymentEntity deployment = new DeploymentEntity();

            deployment.Id = "aDeploymentId";

            context.Deployment = deployment;
            context.Model      = modelInstance;
        }
Exemple #26
0
 protected internal virtual void PostProcessDefinitions(DeploymentEntity deployment,
                                                        IList <TDefinitionEntity> definitions, Core.Model.Properties properties)
 {
     if (deployment.IsNew)//新的,写入持久层及上下文中
     {
         PersistDefinitions(deployment, definitions, properties);
     }
     else//已有,从持久层加载到上下文中
     {
         LoadDefinitions(deployment, definitions, properties);
     }
 }
Exemple #27
0
        // logger ////////////////////////////////////////////////////////////////////////////

        protected internal virtual void logRegistration(ISet <string> deploymentIds, ProcessApplicationReference reference)
        {
            if (!LOG.InfoEnabled)
            {
                // building the log message is expensive (db queries) so we avoid it if we can
                return;
            }

            try
            {
                StringBuilder builder = new StringBuilder();
                builder.Append("ProcessApplication '");
                builder.Append(reference.Name);
                builder.Append("' registered for DB deployments ");
                builder.Append(deploymentIds);
                builder.Append(". ");

                IList <ProcessDefinition> processDefinitions = new List <ProcessDefinition>();
                IList <CaseDefinition>    caseDefinitions    = new List <CaseDefinition>();

                CommandContext commandContext = Context.CommandContext;
                ProcessEngineConfigurationImpl processEngineConfiguration = Context.ProcessEngineConfiguration;
                bool cmmnEnabled = processEngineConfiguration.CmmnEnabled;

                foreach (string deploymentId in deploymentIds)
                {
                    DeploymentEntity deployment = commandContext.DbEntityManager.selectById(typeof(DeploymentEntity), deploymentId);

                    if (deployment != null)
                    {
                        ((IList <ProcessDefinition>)processDefinitions).AddRange(getDeployedProcessDefinitionArtifacts(deployment));

                        if (cmmnEnabled)
                        {
                            ((IList <CaseDefinition>)caseDefinitions).AddRange(getDeployedCaseDefinitionArtifacts(deployment));
                        }
                    }
                }

                logProcessDefinitionRegistrations(builder, processDefinitions);

                if (cmmnEnabled)
                {
                    logCaseDefinitionRegistrations(builder, caseDefinitions);
                }

                LOG.registrationSummary(builder.ToString());
            }
            catch (Exception e)
            {
                LOG.exceptionWhileLoggingRegistrationSummary(e);
            }
        }
Exemple #28
0
        protected internal virtual void registerDefinition(DeploymentEntity deployment, DefinitionEntity definition, Properties properties)
        {
            DeploymentCache deploymentCache = DeploymentCache;

            // Add to cache
            addDefinitionToDeploymentCache(deploymentCache, definition);

            definitionAddedToDeploymentCache(deployment, definition, properties);

            // Add to deployment for further usage
            deployment.addDeployedArtifact(definition);
        }
Exemple #29
0
 public virtual void Deploy(DeploymentEntity deployment)
 {
     Context.CommandContext.RunWithoutAuthorization <object>(() =>
     {
         //包含了BPmn,dmn的DecisionRequirementsDefinition和DecisionDefinition 3种部署,按名Name后缀区分
         foreach (var deployer in deployers)
         {
             deployer.Deploy(deployment);
         }
         return(null);
     });
 }
Exemple #30
0
        protected internal virtual void LoadDefinitions(DeploymentEntity deployment, IList <TDefinitionEntity> definitions,
                                                        Core.Model.Properties properties)
        {
            foreach (var definition in definitions)
            {
                var deploymentId  = deployment.Id;
                var definitionKey = definition.Key;

                var persistedDefinition = FindDefinitionByDeploymentAndKey(deploymentId, definitionKey);
                HandlePersistedDefinition(definition, persistedDefinition, deployment, properties);
            }
        }