34aed185a934befc93a9e8bda920c0b7339bd42c
[externalapi/nbi.git] / src / main / java / org / onap / nbi / apis / servicecatalog / ToscaInfosProcessor.java
1 /**
2  * Copyright (c) 2018 Orange
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
5  * in compliance with the License. You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software distributed under the License
10  * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
11  * or implied. See the License for the specific language governing permissions and limitations under
12  * the License.
13  */
14 package org.onap.nbi.apis.servicecatalog;
15
16 import java.io.File;
17 import java.io.FileInputStream;
18 import java.io.FileOutputStream;
19 import java.io.IOException;
20 import java.sql.Timestamp;
21 import java.util.ArrayList;
22 import java.util.LinkedHashMap;
23 import java.util.List;
24 import java.util.zip.ZipEntry;
25 import java.util.zip.ZipInputStream;
26 import org.apache.commons.collections.CollectionUtils;
27 import org.apache.commons.io.FileUtils;
28 import org.onap.nbi.exceptions.TechnicalException;
29 import org.slf4j.Logger;
30 import org.slf4j.LoggerFactory;
31 import org.springframework.beans.factory.annotation.Autowired;
32 import org.springframework.stereotype.Service;
33 import com.fasterxml.jackson.databind.ObjectMapper;
34 import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
35
36 @Service
37 public class ToscaInfosProcessor {
38
39     @Autowired
40     SdcClient sdcClient;
41
42     final ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); // jackson databind
43
44     private static final Logger LOGGER = LoggerFactory.getLogger(ToscaInfosProcessor.class);
45
46     public void buildResponseWithToscaInfos(LinkedHashMap toscaInfosTopologyTemplate,
47             LinkedHashMap serviceCatalogResponse) {
48         if (toscaInfosTopologyTemplate.get("inputs") != null) {
49             ArrayList serviceSpecCharacteristic = new ArrayList();
50             LinkedHashMap toscaInfos = (LinkedHashMap) toscaInfosTopologyTemplate.get("inputs");
51             for (Object key : toscaInfos.entrySet()) {
52                 String keyString = (String) key;
53                 LinkedHashMap inputParameter = (LinkedHashMap) toscaInfos.get(key);
54                 LinkedHashMap mapParameter = new LinkedHashMap();
55                 String parameterType = (String) inputParameter.get("type");
56                 mapParameter.put("name", keyString);
57                 mapParameter.put("description", inputParameter.get("description"));
58                 mapParameter.put("valueType", parameterType);
59                 mapParameter.put("@type", "ONAPserviceCharacteristic");
60                 mapParameter.put("required", inputParameter.get("required"));
61                 mapParameter.put("status", inputParameter.get("status"));
62                 List<LinkedHashMap> serviceSpecCharacteristicValues =
63                         buildServiceSpecCharacteristicsValues(inputParameter, parameterType);
64                 mapParameter.put("serviceSpecCharacteristicValue", serviceSpecCharacteristicValues);
65                 serviceSpecCharacteristic.add(mapParameter);
66             }
67
68             serviceCatalogResponse.put("serviceSpecCharacteristic", serviceSpecCharacteristic);
69         }
70         LinkedHashMap nodeTemplate = (LinkedHashMap) toscaInfosTopologyTemplate.get("node_templates");
71
72         List<LinkedHashMap> resourceSpecifications =
73                 (List<LinkedHashMap>) serviceCatalogResponse.get("resourceSpecification");
74         for (LinkedHashMap resourceSpecification : resourceSpecifications) {
75             String id = (String) resourceSpecification.get("id");
76             LOGGER.debug("get tosca infos for service id: {0}", id);
77             LinkedHashMap toscaInfosFromResourceId = getToscaInfosFromResourceUUID(nodeTemplate, id);
78             if (toscaInfosFromResourceId != null) {
79                 resourceSpecification.put("modelCustomizationId", toscaInfosFromResourceId.get("customizationUUID"));
80             }
81
82         }
83     }
84
85     private List<LinkedHashMap> buildServiceSpecCharacteristicsValues(LinkedHashMap parameter, String parameterType) {
86         List<LinkedHashMap> serviceSpecCharacteristicValues = new ArrayList<>();
87         if (!"map".equalsIgnoreCase(parameterType) && !"list".equalsIgnoreCase(parameterType)) {
88             LOGGER.debug("get tosca infos for serviceSpecCharacteristicValues of type map or string : {0}", parameter);
89             Object aDefault = parameter.get("default");
90             if (parameter.get("entry_schema") != null) {
91                 ArrayList entrySchema = (ArrayList) parameter.get("entry_schema");
92                 if (CollectionUtils.isNotEmpty(entrySchema)) {
93                     buildCharacteristicValuesFormShema(parameterType, serviceSpecCharacteristicValues, aDefault,
94                             entrySchema);
95                 }
96             }
97         }
98         return serviceSpecCharacteristicValues;
99     }
100
101     private void buildCharacteristicValuesFormShema(String parameterType,
102             List<LinkedHashMap> serviceSpecCharacteristicValues, Object aDefault, ArrayList entry_schema) {
103         LinkedHashMap constraints = (LinkedHashMap) entry_schema.get(0);
104         if (constraints != null) {
105             ArrayList constraintsList = (ArrayList) constraints.get("constraints");
106             if (CollectionUtils.isNotEmpty(constraintsList)) {
107                 LinkedHashMap valuesMap = (LinkedHashMap) constraintsList.get(0);
108                 if (valuesMap != null) {
109                     List<Object> values = (List<Object>) valuesMap.get("valid_values");
110                     for (Object value : values) {
111                         String stringValue = value.toString();
112                         LinkedHashMap serviceSpecCharacteristicValue = new LinkedHashMap();
113                         serviceSpecCharacteristicValue.put("isDefault",
114                                 aDefault != null && aDefault.toString().equals(stringValue));
115                         serviceSpecCharacteristicValue.put("value", stringValue);
116                         serviceSpecCharacteristicValue.put("valueType", parameterType);
117                         serviceSpecCharacteristicValues.add(serviceSpecCharacteristicValue);
118                     }
119                 }
120             }
121         }
122     }
123
124
125     private LinkedHashMap getToscaInfosFromResourceUUID(LinkedHashMap node_templates, String name) {
126         if(node_templates!=null) {
127             for (Object nodeTemplateObject : node_templates.values()) {
128                 LinkedHashMap nodeTemplate = (LinkedHashMap) nodeTemplateObject;
129                 LinkedHashMap metadata = (LinkedHashMap) nodeTemplate.get("metadata");
130                 String metadataUUID = (String) metadata.get("UUID");
131                 String metadataType = (String) metadata.get("type");
132                 if ("VF".equalsIgnoreCase(metadataType) && name.equalsIgnoreCase(metadataUUID)) {
133                     return metadata;
134                 }
135             }
136         }
137         return null;
138     }
139
140
141     public LinkedHashMap getToscaInfos(LinkedHashMap sdcResponse) {
142
143         LinkedHashMap topologyTemplate = null;
144
145         String toscaModelUrl = (String) sdcResponse.get("toscaModelURL");
146         String serviceId = (String) sdcResponse.get("uuid");
147         File toscaFile = sdcClient.callGetWithAttachment(toscaModelUrl);
148         Timestamp timestamp = new Timestamp(System.currentTimeMillis());
149         String tempFolderName = serviceId + timestamp;
150         File folderTemp = null;
151
152         try {
153             unZipArchive(toscaFile.getName(), tempFolderName);
154             folderTemp = new File(tempFolderName);
155             LOGGER.debug("temp folder for tosca files : " + folderTemp.getName());
156
157             LinkedHashMap toscaMetaFileHashMap = parseToscaFile(tempFolderName + "/TOSCA-Metadata/TOSCA.meta");
158             topologyTemplate = getToscaTopologyTemplateNode(tempFolderName, toscaMetaFileHashMap);
159             return topologyTemplate;
160         } catch (TechnicalException e) {
161             LOGGER.error("unable to parse tosca file for id : " + serviceId, e);
162             return  topologyTemplate;
163         }
164         finally {
165             deleteTempFiles(serviceId, toscaFile, folderTemp);
166         }
167
168     }
169
170     private LinkedHashMap getToscaTopologyTemplateNode(String tempFolderName,LinkedHashMap toscaMetaFileHashMap) {
171         LinkedHashMap topologyTemplate = null;
172         if (toscaMetaFileHashMap.get("Entry-Definitions") != null) {
173             String toscaFilePath = (String) toscaMetaFileHashMap.get("Entry-Definitions");
174             LinkedHashMap toscaFileHashMap = parseToscaFile(tempFolderName + "/" + toscaFilePath);
175             if (toscaFileHashMap.get("topology_template") != null) {
176                 topologyTemplate = (LinkedHashMap) toscaFileHashMap.get("topology_template");
177             } else {
178                 LOGGER.error("no Entry-Definitions node in TOSCA.meta");
179             }
180         } else {
181             LOGGER.error("no topology_template node in tosca file");
182         }
183         return topologyTemplate;
184     }
185
186
187     private void deleteTempFiles(String serviceId, File toscaFile, File folderTemp) {
188         try {
189             if(folderTemp!=null){
190                 LOGGER.debug("deleting temp folder for tosca files : " + folderTemp.getName());
191                 FileUtils.deleteDirectory(folderTemp);
192             }
193             LOGGER.debug("deleting tosca archive : " + toscaFile.getName());
194             FileUtils.forceDelete(toscaFile);
195         } catch (IOException e) {
196             LOGGER.error("unable to delete temp directory tosca file for id : " + serviceId, e);
197         }
198     }
199
200     private LinkedHashMap parseToscaFile(String fileName) {
201
202         File toscaFile = new File(fileName);
203         if (!toscaFile.exists()) {
204             throw new TechnicalException("unable to find  file : " + fileName);
205         }
206         try {
207             return (LinkedHashMap) mapper.readValue(toscaFile, Object.class);
208         } catch (IOException e) {
209             LOGGER.warn("unable to parse tosca file : " + fileName, e);
210             throw new TechnicalException("Unable to parse tosca file : " + fileName);
211
212         } catch (NullPointerException e) {
213             LOGGER.warn("unable to find tosca file : " + fileName, e);
214             throw new TechnicalException("unable to find tosca file : " + fileName);
215         }
216     }
217
218
219     /**
220      * Unzip it
221      *
222      * @param zipFile input zip file
223      * @param outputFolder zip file output folder
224      */
225     private void unZipArchive(String zipFile, String outputFolder) {
226
227         byte[] buffer = new byte[1024];
228
229         try {
230
231             // create output directory is not exists
232             File folder = new File(outputFolder);
233             if (!folder.exists()) {
234                 folder.mkdir();
235             }
236
237             // get the zip file content
238             try (ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile))) {
239                 // get the zipped file list entry
240                 ZipEntry ze = zis.getNextEntry();
241
242                 while (ze != null) {
243
244                     String fileName = ze.getName();
245                     File newFile = new File(outputFolder + File.separator + fileName);
246
247                     LOGGER.debug("File to unzip : " + newFile.getAbsoluteFile());
248
249                     // create all non exists folders
250                     // else you will hit FileNotFoundException for compressed folder
251                     new File(newFile.getParent()).mkdirs();
252
253                     try (FileOutputStream fos = new FileOutputStream(newFile)) {
254
255                         int len;
256                         while ((len = zis.read(buffer)) > 0) {
257                             fos.write(buffer, 0, len);
258                         }
259
260                         fos.close();
261                     }
262                     ze = zis.getNextEntry();
263                 }
264
265                 zis.closeEntry();
266                 zis.close();
267             }
268
269             LOGGER.debug("Done");
270
271         } catch (IOException ex) {
272             LOGGER.error("Error while unzipping ToscaModel archive from ONAP", ex);
273             throw new TechnicalException("Error while unzipping ToscaModel archive from ONAP");
274         }
275     }
276
277
278 }