Change the model to fix TCA
[clamp.git] / src / main / java / org / onap / clamp / clds / client / req / SdcReq.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights
6  *                             reserved.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  * http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END============================================
20  * ===================================================================
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  */
23
24 package org.onap.clamp.clds.client.req;
25
26 import com.att.eelf.configuration.EELFLogger;
27 import com.att.eelf.configuration.EELFManager;
28 import com.fasterxml.jackson.core.JsonParseException;
29 import com.fasterxml.jackson.databind.JsonMappingException;
30 import com.fasterxml.jackson.databind.JsonNode;
31 import com.fasterxml.jackson.databind.ObjectMapper;
32 import com.fasterxml.jackson.databind.node.ArrayNode;
33 import com.fasterxml.jackson.databind.node.ObjectNode;
34 import com.fasterxml.jackson.dataformat.yaml.snakeyaml.Yaml;
35
36 import java.io.IOException;
37 import java.nio.charset.StandardCharsets;
38 import java.util.ArrayList;
39 import java.util.Base64;
40 import java.util.Iterator;
41 import java.util.List;
42 import java.util.Map;
43 import java.util.Map.Entry;
44
45 import org.apache.commons.codec.digest.DigestUtils;
46 import org.camunda.bpm.engine.delegate.DelegateExecution;
47 import org.onap.clamp.clds.client.SdcCatalogServices;
48 import org.onap.clamp.clds.model.CldsSdcResource;
49 import org.onap.clamp.clds.model.CldsSdcServiceDetail;
50 import org.onap.clamp.clds.model.prop.Global;
51 import org.onap.clamp.clds.model.prop.ModelProperties;
52 import org.onap.clamp.clds.model.prop.Tca;
53 import org.onap.clamp.clds.model.refprop.RefProp;
54
55 /**
56  * Construct a Sdc request given CLDS objects.
57  */
58 public class SdcReq {
59     protected static final EELFLogger logger        = EELFManager.getInstance().getLogger(SdcReq.class);
60     protected static final EELFLogger metricsLogger = EELFManager.getInstance().getMetricsLogger();
61
62     /**
63      * Format the Blueprint from a Yaml
64      *
65      * @param refProp
66      *            The RefProp instance containing the Clds config
67      * @param prop
68      *            The ModelProperties describing the clds model
69      * @param docText
70      *            The Yaml file that must be converted
71      *
72      * @return A String containing the BluePrint
73      * @throws JsonParseException
74      *             In case of issues
75      * @throws JsonMappingException
76      *             In case of issues
77      * @throws IOException
78      *             In case of issues
79      */
80     public static String formatBlueprint(RefProp refProp, ModelProperties prop, String docText)
81             throws JsonParseException, JsonMappingException, IOException {
82
83         Global globalProp = prop.getGlobal();
84         String service = globalProp.getService();
85
86         String yamlvalue = getYamlvalue(docText);
87
88         String updatedBlueprint = "";
89         Tca tca = prop.getType(Tca.class);
90         if (tca.isFound()) {
91                 updatedBlueprint = TcaRequestFormatter.updatedBlueprintWithConfiguration(refProp, prop, yamlvalue);
92         } 
93         logger.info("value of blueprint:" + updatedBlueprint);
94         return updatedBlueprint;
95     }
96
97     private static String getUpdatedBlueprintWithConfiguration(RefProp refProp, ModelProperties prop, String yamlValue,
98             ObjectNode serviceConf) throws IOException {
99         String blueprint = "";
100         Yaml yaml = new Yaml();
101         // Serialiaze Yaml file
102         Map<String, Map> loadedYaml = (Map<String, Map>) yaml.load(yamlValue);
103         // Get node templates information from Yaml
104         Map<String, Map> nodeTemplates = loadedYaml.get("node_templates");
105         logger.info("value of NodeTemplates:" + nodeTemplates);
106         // Get Tca Object information from node templates of Yaml
107         Map<String, Map> tcaObject = nodeTemplates.get("MTCA");
108         logger.info("value of Tca:" + tcaObject);
109         // Get Properties Object information from tca of Yaml
110         Map<String, String> propsObject = tcaObject.get("properties");
111         logger.info("value of PropsObject:" + propsObject);
112         String deploymentJsonObject = propsObject.get("deployment_JSON");
113         logger.info("value of deploymentJson:" + deploymentJsonObject);
114
115         ObjectMapper mapper = new ObjectMapper();
116
117         ObjectNode deployJsonNode = (ObjectNode) mapper.readTree(deploymentJsonObject);
118
119         // "policyName":"example_model06.ClosedLoop_FRWL_SIG_0538e6f2_8c1b_4656_9999_3501b3c59ad7_Tca_",
120         String policyNamePrefix = refProp.getStringValue("policy.ms.policyNamePrefix");
121         String policyName = prop.getCurrentPolicyScopeAndFullPolicyName(policyNamePrefix);
122         serviceConf.put("policyName", policyName);
123
124         deployJsonNode.set("configuration", serviceConf);
125         propsObject.put("deployment_JSON", deployJsonNode.toString());
126         blueprint = yaml.dump(loadedYaml);
127         logger.info("value of updated Yaml File:" + blueprint);
128
129         return blueprint;
130     }
131
132     public static String formatSdcLocationsReq(ModelProperties prop, String artifactName) {
133         ObjectMapper objectMapper = new ObjectMapper();
134         Global global = prop.getGlobal();
135         List<String> locationsList = global.getLocation();
136         ArrayNode locationsArrayNode = objectMapper.createArrayNode();
137         ObjectNode locationObject = objectMapper.createObjectNode();
138         for (String currLocation : locationsList) {
139             locationsArrayNode.add(currLocation);
140         }
141         locationObject.put("artifactName", artifactName);
142         locationObject.putPOJO("locations", locationsArrayNode);
143         String locationJsonFormat = locationObject.toString();
144         logger.info("Value of locaation Json Artifact:" + locationsArrayNode);
145         return locationJsonFormat;
146     }
147
148     public static String formatSdcReq(String payloadData, String artifactName, String artifactLabel,
149             String artifactType) throws IOException {
150         logger.info("artifact=" + payloadData);
151         String base64Artifact = base64Encode(payloadData);
152         return "{ \n" + "\"payloadData\" : \"" + base64Artifact + "\",\n" + "\"artifactLabel\" : \"" + artifactLabel
153                 + "\",\n" + "\"artifactName\" :\"" + artifactName + "\",\n" + "\"artifactType\" : \"" + artifactType
154                 + "\",\n" + "\"artifactGroupType\" : \"DEPLOYMENT\",\n" + "\"description\" : \"from CLAMP Cockpit\"\n"
155                 + "} \n";
156     }
157
158     public static String getSdcReqUrl(ModelProperties prop, String url) {
159         Global globalProps = prop.getGlobal();
160         String serviceUUID = "";
161         String resourceInstanceName = "";
162         if (globalProps != null) {
163             List<String> resourceVf = globalProps.getResourceVf();
164             if (resourceVf != null && !resourceVf.isEmpty()) {
165                 resourceInstanceName = resourceVf.get(0);
166             }
167             if (globalProps.getService() != null) {
168                 serviceUUID = globalProps.getService();
169             }
170         }
171         String normalizedResourceInstanceName = normalizeResourceInstanceName(resourceInstanceName);
172         return url + "/" + serviceUUID + "/resourceInstances/" + normalizedResourceInstanceName + "/artifacts";
173     }
174
175     /**
176      * To get List of urls for all vfresources
177      *
178      * @param prop
179      * @param baseUrl
180      * @param sdcCatalogServices
181      * @return
182      */
183     public static List<String> getSdcReqUrlsList(ModelProperties prop, String baseUrl,
184             SdcCatalogServices sdcCatalogServices, DelegateExecution execution) {
185         // TODO : refact and regroup with very similar code
186         List<String> urlList = new ArrayList<>();
187
188         Global globalProps = prop.getGlobal();
189         if (globalProps != null) {
190             if (globalProps.getService() != null) {
191                 String serviceInvariantUUID = globalProps.getService();
192                 execution.setVariable("serviceInvariantUUID", serviceInvariantUUID);
193                 List<String> resourceVfList = globalProps.getResourceVf();
194                 String serviceUUID = sdcCatalogServices.getServiceUuidFromServiceInvariantId(serviceInvariantUUID);
195                 String sdcServicesInformation = sdcCatalogServices.getSdcServicesInformation(serviceUUID);
196                 CldsSdcServiceDetail cldsSdcServiceDetail = sdcCatalogServices
197                         .getCldsSdcServiceDetailFromJson(sdcServicesInformation);
198                 if (cldsSdcServiceDetail != null && resourceVfList != null) {
199                     List<CldsSdcResource> cldsSdcResourcesList = cldsSdcServiceDetail.getResources();
200                     if (cldsSdcResourcesList != null && !cldsSdcResourcesList.isEmpty()) {
201                         for (CldsSdcResource CldsSdcResource : cldsSdcResourcesList) {
202                             if (CldsSdcResource != null && CldsSdcResource.getResoucreType() != null
203                                     && CldsSdcResource.getResoucreType().equalsIgnoreCase("VF")
204                                     && resourceVfList.contains(CldsSdcResource.getResourceInvariantUUID())) {
205                                 String normalizedResourceInstanceName = normalizeResourceInstanceName(
206                                         CldsSdcResource.getResourceInstanceName());
207                                 String svcUrl = baseUrl + "/" + serviceUUID + "/resourceInstances/"
208                                         + normalizedResourceInstanceName + "/artifacts";
209                                 urlList.add(svcUrl);
210
211                             }
212                         }
213                     }
214                 }
215             }
216         }
217
218         return urlList;
219     }
220
221     /**
222      * "Normalize" the resource instance name: - Remove spaces, underscores,
223      * dashes, and periods. - make lower case This is required by SDC when using
224      * the resource instance name to upload an artifact.
225      *
226      * @param inText
227      * @return
228      */
229     public static String normalizeResourceInstanceName(String inText) {
230         return inText.replace(" ", "").replace("-", "").replace(".", "").toLowerCase();
231     }
232
233     /**
234      * from michael
235      *
236      * @param data
237      * @return
238      */
239     public static String calculateMD5ByString(String data) {
240         String calculatedMd5 = DigestUtils.md5Hex(data);
241         // encode base-64 result
242         return base64Encode(calculatedMd5.getBytes());
243     }
244
245     /**
246      * Base 64 encode a String.
247      *
248      * @param inText
249      * @return
250      */
251     public static String base64Encode(String inText) {
252         return base64Encode(stringToByteArray(inText));
253     }
254
255     /**
256      * Convert String to byte array.
257      *
258      * @param inText
259      * @return
260      */
261     public static byte[] stringToByteArray(String inText) {
262         return inText.getBytes(StandardCharsets.UTF_8);
263     }
264
265     /**
266      * Base 64 encode a byte array.
267      *
268      * @param bytes
269      * @return
270      */
271     public static String base64Encode(byte[] bytes) {
272         Base64.Encoder encoder = Base64.getEncoder();
273         return encoder.encodeToString(bytes);
274     }
275
276     /**
277      * Return SDC id and pw as a HTTP Basic Auth string (for example: Basic
278      * dGVzdDoxMjM0NTY=).
279      *
280      * @return
281      */
282     public static String getSdcBasicAuth(RefProp refProp) {
283         String sdcId = refProp.getStringValue("sdc.serviceUsername");
284         String sdcPw = refProp.getStringValue("sdc.servicePassword");
285         String idPw = base64Encode(sdcId + ":" + sdcPw);
286         return "Basic " + idPw;
287     }
288
289     /**
290      * Method to get yaml/template properties value from json
291      *
292      * @param docText
293      * @return
294      * @throws IOException
295      */
296     public static String getYamlvalue(String docText) throws IOException {
297         ObjectMapper objectMapper = new ObjectMapper();
298         String yamlFileValue = "";
299         ObjectNode root = objectMapper.readValue(docText, ObjectNode.class);
300         Iterator<Entry<String, JsonNode>> entryItr = root.fields();
301         while (entryItr.hasNext()) {
302             Entry<String, JsonNode> entry = entryItr.next();
303             String key = entry.getKey();
304             if (key != null && key.equalsIgnoreCase("global")) {
305                 ArrayNode arrayNode = (ArrayNode) entry.getValue();
306                 for (JsonNode anArrayNode : arrayNode) {
307                     ObjectNode node = (ObjectNode) anArrayNode;
308                     ArrayNode arrayValueNode = (ArrayNode) node.get("value");
309                     JsonNode jsonNode = arrayValueNode.get(0);
310                     yamlFileValue = jsonNode.asText();
311                     logger.info("value:" + yamlFileValue);
312                 }
313                 break;
314             }
315         }
316         return yamlFileValue;
317     }
318 }