Add history ttl to all bpmn's programatically
[so.git] / bpmn / mso-infrastructure-bpmn / src / main / java / org / onap / so / bpmn / infrastructure / MSOInfrastructureApplication.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.bpmn.infrastructure;
24
25 import java.util.List;
26 import java.util.concurrent.Executor;
27 import javax.annotation.PostConstruct;
28 import org.camunda.bpm.application.PreUndeploy;
29 import org.camunda.bpm.application.ProcessApplicationInfo;
30 import org.camunda.bpm.engine.ProcessEngine;
31 import org.camunda.bpm.engine.RepositoryService;
32 import org.camunda.bpm.engine.repository.Deployment;
33 import org.camunda.bpm.engine.repository.DeploymentBuilder;
34 import org.camunda.bpm.engine.repository.ProcessDefinition;
35 import org.onap.logging.filter.spring.MDCTaskDecorator;
36 import org.onap.so.bpmn.common.DefaultToShortClassNameBeanNameGenerator;
37 import org.onap.so.db.catalog.beans.Workflow;
38 import org.onap.so.db.catalog.client.CatalogDbClient;
39 import org.onap.so.logger.LoggingAnchor;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42 import org.springframework.beans.factory.annotation.Autowired;
43 import org.springframework.beans.factory.annotation.Value;
44 import org.springframework.boot.SpringApplication;
45 import org.springframework.boot.autoconfigure.SpringBootApplication;
46 import org.springframework.context.annotation.Bean;
47 import org.springframework.context.annotation.ComponentScan;
48 import org.springframework.context.annotation.ComponentScan.Filter;
49 import org.springframework.context.annotation.FilterType;
50 import org.springframework.context.annotation.Primary;
51 import org.springframework.scheduling.annotation.EnableAsync;
52 import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
53
54 /**
55  * @since Version 1.0
56  *
57  */
58
59 @SpringBootApplication
60 @EnableAsync
61 @ComponentScan(basePackages = {"org.onap"}, nameGenerator = DefaultToShortClassNameBeanNameGenerator.class,
62         excludeFilters = {@Filter(type = FilterType.ANNOTATION, classes = SpringBootApplication.class)})
63
64 public class MSOInfrastructureApplication {
65
66     private static final Logger logger = LoggerFactory.getLogger(MSOInfrastructureApplication.class);
67     @Autowired
68     private ProcessEngine processEngine;
69
70     @Autowired
71     private CatalogDbClient catalogDbClient;
72
73     @Value("${mso.async.core-pool-size}")
74     private int corePoolSize;
75
76     @Value("${mso.async.max-pool-size}")
77     private int maxPoolSize;
78
79     @Value("${mso.async.queue-capacity}")
80     private int queueCapacity;
81
82     @Value("${mso.bpmn-history-ttl:14}")
83     private Integer bpmnHistoryTtl;
84
85     private static final String LOGS_DIR = "logs_dir";
86     private static final String BPMN_SUFFIX = ".bpmn";
87     private static final String SDC_SOURCE = "sdc";
88     private static final int CANNOT_INVOKE_COMMAND = 126;
89
90
91     private static void setLogsDir() {
92         if (System.getProperty(LOGS_DIR) == null) {
93             System.getProperties().setProperty(LOGS_DIR, "./logs/bpmn/");
94         }
95     }
96
97     public static void main(String... args) {
98         try {
99             SpringApplication.run(MSOInfrastructureApplication.class, args);
100             System.getProperties().setProperty("mso.config.path", ".");
101             setLogsDir();
102         } catch (Exception e) {
103             logger.error("Exception has occurred during application startup. App will exit. ", e);
104             System.exit(CANNOT_INVOKE_COMMAND);
105         }
106     }
107
108     @PostConstruct
109     public void postConstruct() {
110         try {
111             RepositoryService repositoryService = processEngine.getRepositoryService();
112             DeploymentBuilder deploymentBuilder = repositoryService.createDeployment();
113             deployCustomWorkflows(deploymentBuilder);
114             setBpmnTTL(repositoryService, bpmnHistoryTtl);
115         } catch (Exception e) {
116             logger.warn("Unable to invoke deploymentBuilder ", e);
117         }
118     }
119
120     @PreUndeploy
121     public void cleanup(ProcessEngine processEngine, ProcessApplicationInfo processApplicationInfo,
122             List<ProcessEngine> processEngines) {}
123
124     @Bean
125     @Primary
126     public Executor asyncExecutor() {
127         ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
128         executor.setTaskDecorator(new MDCTaskDecorator());
129         executor.setCorePoolSize(corePoolSize);
130         executor.setMaxPoolSize(maxPoolSize);
131         executor.setQueueCapacity(queueCapacity);
132         executor.setThreadNamePrefix("Camunda-");
133         executor.initialize();
134         return executor;
135     }
136
137     public void deployCustomWorkflows(DeploymentBuilder deploymentBuilder) {
138         logger.debug("Attempting to deploy custom workflows");
139         try {
140             List<Workflow> workflows = catalogDbClient.findWorkflowBySource(SDC_SOURCE);
141             if (workflows != null && !workflows.isEmpty()) {
142                 for (Workflow workflow : workflows) {
143                     String workflowName = workflow.getName();
144                     String workflowBody = workflow.getBody();
145                     if (!workflowName.endsWith(BPMN_SUFFIX)) {
146                         workflowName += BPMN_SUFFIX;
147                     }
148                     if (workflowBody != null) {
149                         logger.info(LoggingAnchor.TWO, "Deploying custom workflow", workflowName);
150                         deploymentBuilder.addString(workflowName, workflowBody);
151                     }
152                     deploymentBuilder.enableDuplicateFiltering(true);
153                 }
154                 deploymentBuilder.deploy();
155             }
156         } catch (Exception e) {
157             logger.warn("Unable to deploy custom workflows ", e);
158         }
159     }
160
161     private void setBpmnTTL(RepositoryService repositoryService, Integer ttl) {
162         List<Deployment> deployments = repositoryService.createDeploymentQuery().list();
163         for (Deployment deployment : deployments) {
164             List<ProcessDefinition> processDefinitions =
165                     repositoryService.createProcessDefinitionQuery().deploymentId(deployment.getId()).list();
166             for (ProcessDefinition processDefinition : processDefinitions) {
167                 if (!ttl.equals(processDefinition.getHistoryTimeToLive())) {
168                     logger.info("Setting ttl {} for processdefinition {}", ttl, processDefinition.getName());
169                     repositoryService.updateProcessDefinitionHistoryTimeToLive(processDefinition.getId(), ttl);
170                 }
171             }
172         }
173     }
174 }