Passing Instance params for SO Macro request
[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
15 package org.onap.nbi.apis.servicecatalog;
16
17 import java.nio.file.Path;
18 import java.util.ArrayList;
19 import java.util.Arrays;
20 import java.util.HashMap;
21 import java.util.HashSet;
22 import java.util.LinkedHashMap;
23 import java.util.List;
24 import java.util.Map;
25 import java.util.Map.Entry;
26 import java.util.Set;
27
28 import org.onap.nbi.apis.serviceorder.model.consumer.VFModelInfo;
29 import org.onap.sdc.tosca.parser.api.IEntityDetails;
30 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
31 import org.onap.sdc.tosca.parser.elements.queries.EntityQuery;
32 import org.onap.sdc.tosca.parser.elements.queries.TopologyTemplateQuery;
33 import org.onap.sdc.tosca.parser.enums.SdcTypes;
34 import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException;
35 import org.onap.sdc.tosca.parser.impl.SdcPropertyNames;
36 import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory;
37 import org.onap.sdc.toscaparser.api.NodeTemplate;
38 import org.onap.sdc.toscaparser.api.elements.Metadata;
39 import org.onap.sdc.toscaparser.api.functions.GetInput;
40 import org.onap.sdc.toscaparser.api.parameters.Input;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43 import org.springframework.beans.factory.annotation.Autowired;
44 import org.springframework.stereotype.Service;
45 import com.fasterxml.jackson.databind.ObjectMapper;
46 import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
47 import io.swagger.models.Model;
48 import io.swagger.models.ModelImpl;
49 import io.swagger.models.properties.Property;
50 import io.swagger.models.properties.PropertyBuilder;
51 import io.swagger.util.Json;
52
53 @Service
54 public class ToscaInfosProcessor {
55
56     @Autowired
57     SdcClient sdcClient;
58
59     @Autowired
60     private ServiceSpecificationDBManager serviceSpecificationDBManager;
61
62     private Set<String> vnfInstanceParams = new HashSet<String>(Arrays.asList("onap_private_net_id",
63         "onap_private_subnet_id", "pub_key", "sec_group", "install_script_version", "demo_artifacts_version",
64         "cloud_env", "public_net_id", "aic-cloud-region", "image_name", "flavor_name"));
65
66     final ObjectMapper mapper = new ObjectMapper(new YAMLFactory()); // jackson databind
67
68     private static final Logger LOGGER = LoggerFactory.getLogger(ToscaInfosProcessor.class);
69
70     public void buildResponseWithSdcToscaParser(Path path, Map serviceCatalogResponse) throws SdcToscaParserException {
71
72         SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance();
73         ISdcCsarHelper sdcCsarHelper = factory.getSdcCsarHelper(path.toFile().getAbsolutePath(), false);
74         List<Input> inputs = sdcCsarHelper.getServiceInputs();
75         if (inputs != null && inputs.size() > 0) {
76             ArrayList serviceSpecCharacteristic = new ArrayList();
77             for (Input input : inputs) {
78                 LinkedHashMap mapParameter = new LinkedHashMap();
79                 mapParameter.put("name", input.getName());
80                 mapParameter.put("description", input.getDescription());
81                 mapParameter.put("valueType", input.getType());
82                 mapParameter.put("@type", "ONAPserviceCharacteristic");
83                 mapParameter.put("required", input.isRequired());
84                 mapParameter.put("status", null);
85                 mapParameter.put("serviceSpecCharacteristicValue", null);
86                 // If this Input has a default value, then put it in serviceSpecCharacteristicValue
87                 if (input.getDefault() != null) {
88                     List<LinkedHashMap> serviceSpecCharacteristicValues =
89                             buildServiceSpecCharacteristicsValuesFromSdc(input);
90                     mapParameter.put("serviceSpecCharacteristicValue", serviceSpecCharacteristicValues);
91                 }
92                 serviceSpecCharacteristic.add(mapParameter);
93             }
94             serviceCatalogResponse.put("serviceSpecCharacteristic", serviceSpecCharacteristic);
95         }
96         List<NodeTemplate> nodeTemplates = sdcCsarHelper.getServiceNodeTemplates();
97
98         List<LinkedHashMap> resourceSpecifications =
99                 (List<LinkedHashMap>) serviceCatalogResponse.get("resourceSpecification");
100         for (LinkedHashMap resourceSpecification : resourceSpecifications) {
101             if (resourceSpecification.get("id") != null) {
102                 String id = (String) resourceSpecification.get("id");
103                 LOGGER.debug("get tosca infos for service id: {}", id);
104                 NodeTemplate nodeTemplate = null;
105                 for (NodeTemplate node : nodeTemplates) {
106                     if (node.getMetaData().getValue("UUID").equals(id)) {
107                         nodeTemplate = node;
108                         break;
109                     }
110                 }
111                 if (nodeTemplate == null)
112                     continue;
113                 resourceSpecification.put("modelCustomizationId",
114                         sdcCsarHelper.getNodeTemplateCustomizationUuid(nodeTemplate));
115             }
116         }
117     }
118
119     private List<LinkedHashMap> buildServiceSpecCharacteristicsValuesFromSdc(Input input) {
120
121         List<LinkedHashMap> serviceSpecCharacteristicValues = new ArrayList<>();
122         LinkedHashMap serviceSpecCharacteristicValue = new LinkedHashMap();
123
124         serviceSpecCharacteristicValue.put("isDefault", true);
125         serviceSpecCharacteristicValue.put("value", input.getDefault());
126         serviceSpecCharacteristicValue.put("valueType", input.getType());
127         serviceSpecCharacteristicValues.add(serviceSpecCharacteristicValue);
128
129         return serviceSpecCharacteristicValues;
130     }
131
132     public void buildAndSaveResponseWithSdcToscaParser(Path path, Map serviceCatalogResponse)
133                         throws SdcToscaParserException {
134
135                 SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance();
136                 ISdcCsarHelper sdcCsarHelper = factory.getSdcCsarHelper(path.toFile().getAbsolutePath(), false);
137                 List<Input> inputs = sdcCsarHelper.getServiceInputs();
138
139                 List<IEntityDetails> vfEntityList = sdcCsarHelper.getEntity(EntityQuery.newBuilder(SdcTypes.VF).build(),
140                                 TopologyTemplateQuery.newBuilder(SdcTypes.SERVICE).build(), false);
141
142                 Map<String, org.onap.sdc.toscaparser.api.Property> groupProperties = null;
143                 Map<String, String> listOfInstanceParameters = new HashMap<>();
144                 if (!vfEntityList.isEmpty()) {
145
146                         IEntityDetails iEntityDetails = vfEntityList.get(0);
147                         groupProperties = iEntityDetails.getProperties();
148
149                         for (String key : groupProperties.keySet()) {
150                                 org.onap.sdc.toscaparser.api.Property property = groupProperties.get(key);
151                                 String paramName = property.getName();
152                                 if (paramName != null) {
153                                         if (vnfInstanceParams.stream()
154                                                         .filter(vnfInstanceParam -> vnfInstanceParam.equalsIgnoreCase(paramName)).findFirst()
155                                                         .isPresent()) {
156                                                 listOfInstanceParameters.put(paramName, property.getValue().toString());
157                                         }
158                                 }
159                         }
160
161                 }
162
163                 // it will build Entity as VfModules
164                 List<IEntityDetails> vfModuleEntityList = sdcCsarHelper.getEntity(
165                                 EntityQuery.newBuilder("org.openecomp.groups.VfModule").build(),
166                                 TopologyTemplateQuery.newBuilder(SdcTypes.SERVICE)
167                                                 .customizationUUID(SdcPropertyNames.PROPERTY_NAME_CUSTOMIZATIONUUID).build(),
168                                 false);
169                 List<VFModelInfo> listOfVfModelInfo = new ArrayList<>();
170
171                 if (!vfModuleEntityList.isEmpty()) {
172                         // Fetching vfModule metadata in a loop
173                         for (IEntityDetails vfModuleEntity : vfModuleEntityList) {
174                                 VFModelInfo vfModel = new VFModelInfo();
175                                 Metadata vfMetadata = vfModuleEntity.getMetadata();
176                                 // Preparing VFModel
177                                 vfModel.setModelInvariantUuid(
178                                                 testNull(vfMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELINVARIANTUUID)));
179                                 vfModel.setModelName(testNull(vfMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELNAME)));
180                                 vfModel.setModelUuid(testNull(vfMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELUUID)));
181                                 vfModel.setModelVersion(
182                                                 testNull(vfMetadata.getValue(SdcPropertyNames.PROPERTY_NAME_VFMODULEMODELVERSION)));
183                                 vfModel.setModelCustomizationUuid(testNull(vfMetadata.getValue("vfModuleModelCustomizationUUID")));
184
185                                 // Adding it to the list
186                                 listOfVfModelInfo.add(vfModel);
187                         }
188                 }
189
190                 Map<String, Model> definitions = new HashMap<String, Model>();
191                 Model model = new ModelImpl();
192
193                 if (!inputs.isEmpty() && inputs.size() > 0) {
194                         for (Input input : inputs) {
195                                 Property property = null;
196                                 if (input.getType().equals("list") || input.getType().equals("map"))
197                                         property = PropertyBuilder.build("array", null, null);
198                                 else
199                                         property = PropertyBuilder.build(input.getType(), null, null);
200
201                                 property.setDescription(input.getDescription());
202                                 property.setRequired(input.isRequired());
203
204                                 if (input.getDefault() != null) {
205                                         property.setDefault(input.getDefault().toString());
206                                 }
207                                 ((ModelImpl) model).addProperty(input.getName(), property);
208                         }
209                         definitions.put("ServiceCharacteristics", model);
210
211                 }
212
213                 String svcCharacteristicsJson = Json.pretty(definitions);
214                 serviceSpecificationDBManager.saveSpecificationInputSchema(svcCharacteristicsJson, serviceCatalogResponse);
215
216                 Metadata serviceMetadata = sdcCsarHelper.getServiceMetadata();
217                 String instantationType = serviceMetadata.getValue("instantiationType");
218                 serviceCatalogResponse.put("instantiationType", instantationType);
219
220                 LinkedHashMap inputSchemaRef = new LinkedHashMap();
221                 // use object to match examples in Specifications
222                 inputSchemaRef.put("valueType", "object");
223                 inputSchemaRef.put("@schemaLocation",
224                                 "/serviceSpecification/" + serviceCatalogResponse.get("id") + "/specificationInputSchema");
225                 inputSchemaRef.put("@type", serviceCatalogResponse.get("name") + "_ServiceCharacteristic");
226
227                 LinkedHashMap serviceSpecCharacteristic = new LinkedHashMap();
228                 serviceSpecCharacteristic.put("name", serviceCatalogResponse.get("name") + "_ServiceCharacteristics");
229                 serviceSpecCharacteristic.put("description",
230                                 "This object describes all the inputs needed from the client to interact with the "
231                                                 + serviceCatalogResponse.get("name") + " Service Topology");
232                 serviceSpecCharacteristic.put("valueType", "object");
233                 serviceSpecCharacteristic.put("@type", "ONAPServiceCharacteristic");
234                 serviceSpecCharacteristic.put("@schemaLocation", "null");
235                 serviceSpecCharacteristic.put("serviceSpecCharacteristicValue", inputSchemaRef);
236
237                 serviceCatalogResponse.put("serviceSpecCharacteristic", serviceSpecCharacteristic);
238
239                 List<NodeTemplate> nodeTemplates = sdcCsarHelper.getServiceNodeTemplates();
240                 List<LinkedHashMap> resourceSpecifications = (List<LinkedHashMap>) serviceCatalogResponse
241                                 .get("resourceSpecification");
242                 for (LinkedHashMap resourceSpecification : resourceSpecifications) {
243                         if (resourceSpecification.get("id") != null) {
244                                 String id = (String) resourceSpecification.get("id");
245                                 LOGGER.debug("get tosca infos for service id: {}", id);
246                                 NodeTemplate nodeTemplate = null;
247                                 for (NodeTemplate node : nodeTemplates) {
248                                         if (node.getMetaData().getValue("UUID").equals(id)) {
249                                                 nodeTemplate = node;
250                                                 break;
251                                         }
252                                 }
253                                 if (nodeTemplate == null)
254                                         continue;
255                                 resourceSpecification.put("modelCustomizationId",
256                                                 sdcCsarHelper.getNodeTemplateCustomizationUuid(nodeTemplate));
257                                 if (!vfModuleEntityList.isEmpty()) {
258                                         resourceSpecification.put("childResourceSpecification", listOfVfModelInfo);
259                                 }
260                                 HashMap<String, Object> serviceInstanceParams = getServiceLevelInstanceParams(inputs);
261                                 resourceSpecification.put("serviceInstanceParams", serviceInstanceParams);
262                                 HashMap<String, Object> vnfInstanceParams = getUserDefinedVFLevelInstanceParams(groupProperties, listOfInstanceParameters);
263                                 resourceSpecification.put("InstanceSpecification", vnfInstanceParams);
264                         }
265                 }
266         }
267     
268  // Get List of Service Level InputParams as Key Value
269         private HashMap<String, Object> getServiceLevelInstanceParams(List<Input> listOfServiceLevelInputs) {
270
271                 HashMap<String, Object> serviceLevelInstanceParams = new HashMap<>();
272
273                 for (Input input : listOfServiceLevelInputs) {
274                         serviceLevelInstanceParams.put(input.getName(), input.getDefault());
275                 }
276
277                 return serviceLevelInstanceParams;
278         }
279         
280         private HashMap<String, Object> getUserDefinedVFLevelInstanceParams(
281                         Map<String, org.onap.sdc.toscaparser.api.Property> groupProperties, Map listOfVFLevelInputs) {
282
283                 HashMap<String, Object> vnfLevelInstanceParams = new HashMap<>();
284                 
285                 for (Entry<String, org.onap.sdc.toscaparser.api.Property> entry : groupProperties.entrySet()) {
286
287                         org.onap.sdc.toscaparser.api.Property property = entry.getValue();
288                         
289                         if ((property.getValue().getClass() == GetInput.class)) {
290                                 GetInput getInput = (GetInput) property.getValue();
291                                 listOfVFLevelInputs.put(getInput.getInputName(), getInput.result());
292                                 listOfVFLevelInputs.remove(property.getName());
293                         }
294                 }
295
296                 return (HashMap<String, Object>) listOfVFLevelInputs;           
297         }
298
299
300     private static String testNull(Object object) {
301         if (object == null) {
302           return "NULL";
303         } else if (object instanceof Integer) {
304           return object.toString();
305         } else if (object instanceof String) {
306           return (String) object;
307         } else {
308           return "Type not recognized";
309         }
310     }
311
312 }