Use distribution json for workflow install
[so.git] / asdc-controller / src / main / java / org / onap / so / asdc / installer / bpmn / BpmnInstaller.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.asdc.installer.bpmn;
24
25 import java.io.BufferedOutputStream;
26 import java.io.FileInputStream;
27 import java.io.FileOutputStream;
28 import java.io.IOException;
29 import java.net.URI;
30 import java.nio.file.Path;
31 import java.nio.file.Paths;
32 import java.util.Enumeration;
33 import java.util.zip.ZipEntry;
34 import java.util.zip.ZipFile;
35 import java.util.zip.ZipInputStream;
36 import org.apache.commons.io.IOUtils;
37 import org.apache.http.HttpEntity;
38 import org.apache.http.HttpResponse;
39 import org.apache.http.client.HttpClient;
40 import org.apache.http.client.config.RequestConfig;
41 import org.apache.http.client.methods.HttpPost;
42 import org.apache.http.entity.ContentType;
43 import org.apache.http.entity.mime.FormBodyPartBuilder;
44 import org.apache.http.entity.mime.MultipartEntityBuilder;
45 import org.apache.http.entity.mime.content.ByteArrayBody;
46 import org.apache.http.entity.mime.content.StringBody;
47 import org.apache.http.impl.client.HttpClientBuilder;
48 import org.onap.so.logger.ErrorCode;
49 import org.onap.so.logger.MessageEnum;
50 import org.slf4j.Logger;
51 import org.slf4j.LoggerFactory;
52 import org.springframework.beans.factory.annotation.Autowired;
53 import org.springframework.core.env.Environment;
54 import org.springframework.stereotype.Component;
55
56 @Component
57 public class BpmnInstaller {
58     protected static final Logger logger = LoggerFactory.getLogger(BpmnInstaller.class);
59     private static final String BPMN_SUFFIX = ".bpmn";
60     private static final String CAMUNDA_URL = "mso.camundaURL";
61     private static final String CREATE_DEPLOYMENT_PATH = "sobpmnengine/deployment/create";
62
63     @Autowired
64     private Environment env;
65
66     public void installBpmn(String csarFilePath) {
67         logger.info("Deploying BPMN files from {}", csarFilePath);
68         try {
69             ZipInputStream csarFile =
70                     new ZipInputStream(new FileInputStream(Paths.get(csarFilePath).normalize().toString()));
71             ZipEntry entry = csarFile.getNextEntry();
72
73             while (entry != null) {
74                 String name = entry.getName();
75                 if (name.endsWith(BPMN_SUFFIX)) {
76                     logger.debug("Attempting to deploy BPMN file: {}", name);
77                     try {
78                         Path p = Paths.get(name);
79                         String fileName = p.getFileName().toString();
80                         extractBpmnFileFromCsar(csarFile, fileName);
81                         HttpResponse response = sendDeploymentRequest(fileName, "");
82                         logger.debug("Response status line: {}", response.getStatusLine());
83                         logger.debug("Response entity: {}", response.getEntity().toString());
84                         if (response.getStatusLine().getStatusCode() != 200) {
85                             logger.debug("Failed deploying BPMN {}", name);
86                             logger.error("{} {} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL.toString(),
87                                     name, fileName, Integer.toString(response.getStatusLine().getStatusCode()),
88                                     ErrorCode.DataError.getValue(), "ASDC BPMN deploy failed");
89                         } else {
90                             logger.debug("Successfully deployed to Camunda: {}", name);
91                         }
92                     } catch (Exception e) {
93                         logger.debug("Exception :", e);
94                         logger.error("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL.toString(), name,
95                                 e.getMessage(), ErrorCode.DataError.getValue(), "ASDC BPMN deploy failed");
96                     }
97                 }
98                 entry = csarFile.getNextEntry();
99             }
100             csarFile.close();
101         } catch (IOException ex) {
102             logger.debug("Exception :", ex);
103             logger.error("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_NOT_DEPLOYED_DETAIL.toString(), csarFilePath,
104                     ex.getMessage(), ErrorCode.DataError.getValue(), "ASDC reading CSAR with workflows failed");
105         }
106         return;
107     }
108
109     public boolean containsWorkflows(String csarFilePath) {
110         boolean workflowsInCsar = false;
111         try (ZipFile zipFile = new ZipFile(csarFilePath)) {
112             Enumeration<? extends ZipEntry> zipEntries = zipFile.entries();
113             while (zipEntries.hasMoreElements()) {
114                 String fileName = zipEntries.nextElement().getName();
115                 if (fileName.endsWith(BPMN_SUFFIX)) {
116                     workflowsInCsar = true;
117                     break;
118                 }
119             }
120         } catch (Exception e) {
121             logger.debug("Exception :", e);
122             logger.error("{} {} {} {} {}", MessageEnum.ASDC_ARTIFACT_CHECK_EXC.toString(), csarFilePath, e.getMessage(),
123                     ErrorCode.DataError.getValue(), "ASDC Unable to check CSAR entries");
124         }
125         return workflowsInCsar;
126     }
127
128     protected HttpResponse sendDeploymentRequest(String bpmnFileName, String version) throws Exception {
129         HttpClient client = HttpClientBuilder.create().build();
130         URI deploymentUri = new URI(this.env.getProperty(CAMUNDA_URL) + CREATE_DEPLOYMENT_PATH);
131         HttpPost post = new HttpPost(deploymentUri);
132         RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(1000000).setConnectTimeout(1000)
133                 .setConnectionRequestTimeout(1000).build();
134         post.setConfig(requestConfig);
135         HttpEntity requestEntity = buildMimeMultipart(bpmnFileName, version);
136         post.setEntity(requestEntity);
137         return client.execute(post);
138     }
139
140     protected HttpEntity buildMimeMultipart(String bpmnFileName, String version) throws Exception {
141         FileInputStream bpmnFileStream = new FileInputStream(
142                 Paths.get(System.getProperty("mso.config.path"), "ASDC", version, bpmnFileName).normalize().toString());
143
144         byte[] bytesToSend = IOUtils.toByteArray(bpmnFileStream);
145         HttpEntity requestEntity =
146                 MultipartEntityBuilder.create()
147                         .addPart(FormBodyPartBuilder.create().setName("deployment-name")
148                                 .setBody(new StringBody("MSO Sample 1", ContentType.TEXT_PLAIN))
149                                 .setField("Content-Disposition",
150                                         String.format("form-data; name=\"%s\"", "deployment-name"))
151                                 .build())
152                         .addPart(FormBodyPartBuilder.create().setName("enable-duplicate-filtering")
153                                 .setBody(new StringBody("false", ContentType.TEXT_PLAIN))
154                                 .setField("Content-Disposition",
155                                         String.format("form-data; name=\"%s\"", "enable-duplicate-filtering"))
156                                 .build())
157                         .addPart(FormBodyPartBuilder.create().setName("deplpy-changed-only")
158                                 .setBody(new StringBody("false", ContentType.TEXT_PLAIN))
159                                 .setField("Content-Disposition",
160                                         String.format("form-data; name=\"%s\"", "deploy-changed-only"))
161                                 .build())
162                         .addPart(FormBodyPartBuilder.create().setName("deployment-source")
163                                 .setBody(new StringBody("local", ContentType.TEXT_PLAIN))
164                                 .setField("Content-Disposition",
165                                         String.format("form-data; name=\"%s\"", "deployment-source"))
166                                 .build())
167                         .addPart(
168                                 FormBodyPartBuilder.create().setName(bpmnFileName)
169                                         .setBody(new ByteArrayBody(bytesToSend, ContentType.create("octet"),
170                                                 bpmnFileName))
171                                         .setField("Content-Disposition",
172                                                 String.format("form-data; name=\"%s\"; filename=\"%s\"; size=%d",
173                                                         bpmnFileName, bpmnFileName, bytesToSend.length))
174                                         .build())
175                         .build();
176
177         IOUtils.closeQuietly(bpmnFileStream);
178         return requestEntity;
179     }
180
181     /* protected void extractBpmnFileFromCsar(ZipInputStream zipIn, String fileName) throws IOException */
182     protected void extractBpmnFileFromCsar(ZipInputStream zipIn, String fileName) {
183         String filePath = Paths.get(System.getProperty("mso.config.path"), "ASDC", fileName).normalize().toString();
184         /* BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath)); */
185         try (BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(filePath))) {
186             byte[] bytesIn = new byte[4096];
187             int read = 0;
188             while ((read = zipIn.read(bytesIn)) != -1) {
189                 outputStream.write(bytesIn, 0, read);
190             }
191             /* outputStream.close(); */
192         } catch (IOException e) {
193             logger.error("Unable to open file.", e);
194         }
195     }
196 }