48dd67f02d90523d9c31945d5214dafce6bbf7c1
[appc.git] / appc-inbound / appc-artifact-handler / provider / src / main / java / org / onap / appc / artifact / handler / node / ArtifactHandlerNode.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * ================================================================================
9  * Modifications Copyright (C) 2019 Ericsson
10  * =============================================================================
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  *
15  *      http://www.apache.org/licenses/LICENSE-2.0
16  *
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  *
23  * ============LICENSE_END=========================================================
24  */
25
26 package org.onap.appc.artifact.handler.node;
27
28 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ACTION;
29 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ACTION_LEVEL;
30 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ACTION_LEVEL_VF_MODULE;
31 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ACTION_LEVEL_VM;
32 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ACTION_LEVEL_VNF;
33 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ACTION_LEVEL_VNFC;
34 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ARTIFACT_CONTENTS;
35 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ARTIFACT_DESRIPTION;
36 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ARTIFACT_NAME;
37 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ARTIFACT_NAME_CAPABILITY;
38 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ARTIFACT_NAME_REFERENCE;
39 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ARTIFACT_TYPE;
40 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ARTIFACT_UUID;
41 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ARTIFACT_VERSION;
42 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.CAPABILITY;
43 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.DB_CONFIG_ACTION_DG;
44 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.DB_DEVICE_AUTHENTICATION;
45 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.DB_DEVICE_INTERFACE_PROTOCOL;
46 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.DB_DOWNLOAD_DG_REFERENCE;
47 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.DB_SDC_REFERENCE;
48 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.DEVICE_PROTOCOL;
49 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.DISTRIBUTION_ID;
50 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.DOCUMENT_PARAMETERS;
51 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.DOWNLOAD_DG_REFERENCE;
52 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.FILE_CATEGORY;
53 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.GROUP_NOTATION_TYPE;
54 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.GROUP_NOTATION_VALUE;
55 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.IPADDRESS_V4_OAM_VIP;
56 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.PARAMETER_YANG;
57 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.PD;
58 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.PORT_NUMBER;
59 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.REFERENCE;
60 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.REQUEST_ID;
61 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.REQUEST_INFORMATION;
62 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.RESOURCE_INSTANCE_NAME;
63 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.RESOURCE_NAME;
64 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.RESOURCE_TYPE;
65 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.RESOURCE_UUID;
66 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.RESOURCE_VERSION;
67 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.SERVICE_DESCRIPTION;
68 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.SERVICE_NAME;
69 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.SERVICE_UUID;
70 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.TEMPLATE;
71 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.TEMPLATE_ID;
72 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.TOSCA_MODEL;
73 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.USER_NAME;
74 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.VM;
75 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.VM_INSTANCE;
76 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.VNFC;
77 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.VNFC_FUNCTION_CODE;
78 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.VNFC_FUNCTION_CODE_LIST;
79 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.VNFC_INSTANCE;
80 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.VNFC_TYPE;
81 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.VNFC_TYPE_LIST;
82 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.VNF_TYPE;
83 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.URL;
84 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.OPENSTACK;
85 import static org.onap.appc.artifact.handler.utils.SdcArtifactHandlerConstants.ANSIBLE;
86 import com.att.eelf.configuration.EELFLogger;
87 import com.att.eelf.configuration.EELFManager;
88 import java.io.ByteArrayOutputStream;
89 import java.io.OutputStream;
90 import java.sql.SQLException;
91 import java.util.Map;
92 import java.util.function.Function;
93 import org.apache.commons.configuration.ConfigurationException;
94 import org.apache.commons.lang.StringUtils;
95 import org.json.JSONArray;
96 import org.json.JSONException;
97 import org.json.JSONObject;
98 import org.onap.appc.artifact.handler.dbservices.DBException;
99 import org.onap.appc.artifact.handler.dbservices.DBService;
100 import org.onap.appc.artifact.handler.utils.ArtifactHandlerProviderUtil;
101 import org.onap.appc.yang.YANGGenerator;
102 import org.onap.appc.yang.impl.YANGGeneratorFactory;
103 import org.onap.ccsdk.sli.core.sli.SvcLogicContext;
104 import org.onap.ccsdk.sli.core.sli.SvcLogicException;
105 import org.onap.ccsdk.sli.core.sli.SvcLogicJavaPlugin;
106 import org.onap.sdnc.config.params.transformer.tosca.ArtifactProcessorImpl;
107 import org.onap.sdnc.config.params.transformer.tosca.exceptions.ArtifactProcessorException;
108 import java.util.ArrayList;
109 import java.util.HashMap;
110 import java.util.List;
111
112 public class ArtifactHandlerNode implements SvcLogicJavaPlugin {
113
114     private static final EELFLogger log = EELFManager.getInstance().getLogger(ArtifactHandlerNode.class);
115     private static final String TOSCA_PARAM = "Tosca";
116     private static final String YANG_PARAM = "Yang";
117     private static final String ARTIFACT_LIST_PARAM = "artifact-list";
118     private static final String CONFIGURE_PARAM = "Configure";
119     private static final String CONFIG_SCALE_OUT_PARAM = "ConfigScaleOut";
120     private static final String CONFIG_MODIFY_PARAM = "ConfigModify";
121     private static final String GET_CONFIG = "GetConfig";
122     private static final String POST_EVACUATE = "PostEvacuate";
123     private static final String PRE_EVACUATE = "PreEvacuate";
124     private static final String POST_MIGRATE = "PostMigrate";
125     private static final String PRE_MIGRATE = "PreMigrate";
126     private static final String PRE_REBUILD = "PreRebuild";
127     private static final String POST_REBUILD = "PostRebuild";
128     private static final String STOP_TRAFFIC = "StopTraffic";
129
130     public void processArtifact(Map<String, String> inParams, SvcLogicContext ctx) throws ArtifactProcessorException {
131
132         if (inParams == null || inParams.isEmpty()) {
133             return;
134         }
135         String postData = inParams.get("postData");
136         if (StringUtils.isBlank(postData)) {
137             return;
138         }
139         try {
140             log.info("Received request for process Artifact with params: " + inParams.toString());
141             JSONObject input = new JSONObject(postData).getJSONObject("input");
142             storeUpdateSdcArtifacts(input);
143         } catch (Exception e) {
144             log.error("Error when processing artifact", e);
145             throw new ArtifactProcessorException("Error occurred while processing artifact, " + e.getMessage(), e);
146         }
147     }
148
149     private boolean storeUpdateSdcArtifacts(JSONObject postDataJson) throws ArtifactHandlerInternalException {
150         log.info("Starting processing of SDC Artifacts into Handler with Data: " + postDataJson.toString());
151         try {
152             JSONObject requestInfo = (JSONObject) postDataJson.get(REQUEST_INFORMATION);
153             JSONObject documentInfo = (JSONObject) postDataJson.get(DOCUMENT_PARAMETERS);
154             String artifactName = documentInfo.getString(ARTIFACT_NAME);
155
156             if (StringUtils.isBlank(artifactName)) {
157                 throw new ArtifactHandlerInternalException("Missing Artifact Name");
158             }
159
160             if (artifactName.toLowerCase().startsWith(ANSIBLE)) {
161                 validateAnsibleAdminArtifact(documentInfo);
162                 log.info("validateAnsibleAdminArtifact sucessfully done");
163             }
164
165             updateStoreArtifacts(requestInfo, documentInfo);
166
167             if (artifactName.toLowerCase().startsWith(REFERENCE)) {
168                 return storeReferenceData(requestInfo, documentInfo);
169             } else if (artifactName.toLowerCase().startsWith(PD)) {
170                 return createDataForPD(requestInfo, documentInfo);
171             }
172
173         } catch (Exception e) {
174             log.error("Error while processing request with id: "
175                     + ((JSONObject) postDataJson.get(REQUEST_INFORMATION)).getString(REQUEST_ID), e);
176             throw new ArtifactHandlerInternalException("Error while processing request with id: "
177                     + ((JSONObject) postDataJson.get(REQUEST_INFORMATION)).getString(REQUEST_ID)
178                     + ", Exception Message: " + e.getMessage(), e);
179         }
180         return false;
181     }
182
183     public void validateAnsibleAdminArtifact(JSONObject documentInfo) throws ArtifactHandlerInternalException {
184
185         String fn = "ArtifactHandlerNode.validateAnsibleAdminArtifact";
186         String artifactName = documentInfo.getString(ARTIFACT_NAME);
187         log.info(fn + ": Received Admin File Name: " + artifactName
188                 + ", ArtifactContent: " + documentInfo.getString(ARTIFACT_CONTENTS));
189         try {
190             ArtifactHandlerProviderUtil ahpUtil = new ArtifactHandlerProviderUtil();
191             String contentString = ahpUtil.escapeSql(documentInfo.getString(ARTIFACT_CONTENTS));
192             JSONObject artifact = new JSONObject(contentString);
193             JSONArray fqdnList = artifact.getJSONArray("fqdn-list");
194             Map<String, List<String>> artifactMap = new HashMap<>();
195
196             for (int i = 0; i < fqdnList.length(); i++) {
197                 JSONObject fqdn = fqdnList.getJSONObject(i);
198                 List<String> valuesforFQDN = populateValueForFQDN(fqdn);
199                 artifactMap.put(fqdn.getString("vnf-management-server-fqdn"), valuesforFQDN);
200             }
201
202             validateKeyValue(artifactMap);
203
204         } catch (JSONException je) {
205             log.error(fn + " ansible admin artifact content may not be a valid JSON, error message: "
206                     + je.getMessage());
207             throw new ArtifactHandlerInternalException(
208                     "JSON Exception:ansible admin artifact content may not be a valid JSON, error message: "
209                     + je.getMessage(),
210                     je);
211         } catch (ArtifactHandlerInternalException ae) {
212             throw ae;
213         } catch (Exception e) {
214             log.error(fn + "Error while creating Admin data records", e);
215             throw new ArtifactHandlerInternalException(
216                     "Error while processing ansible admin artifact: " + e.getMessage(), e);
217         }
218
219     }
220
221     private void validateKeyValue(Map<String, List<String>> artifactMap) throws ArtifactHandlerInternalException {
222         for (String fqdn1 : artifactMap.keySet()) {
223
224             for (String value : artifactMap.get(fqdn1)) {
225
226                 for (String fqdn2 : artifactMap.keySet()) {
227
228                     if (!fqdn1.equals(fqdn2) && artifactMap.get(fqdn2).contains(value)) {
229                         String msg = "Validation Failure: Ansible Admin artifact has CloudOwner-RegionId-Tenant: "
230                                 + value + " mapped to multiple FQDN: " + fqdn1 + " & " + fqdn2;
231                         log.info(msg);
232                         throw new ArtifactHandlerInternalException(msg);
233                     }
234
235                 }
236             }
237
238         }
239
240     }
241
242     private List<String> populateValueForFQDN(JSONObject fqdn) {
243         log.info("Inside populateValueForFQDN: " + fqdn.getString("vnf-management-server-fqdn"));
244         List<String> valuesforFQDN = new ArrayList<>();
245         JSONArray cloudJsonList = fqdn.getJSONArray("cloud-owner-list");
246         for (int j = 0; j < cloudJsonList.length(); j++) {
247             String cloudOwner = cloudJsonList.getJSONObject(j).getString("cloud-owner");
248             JSONArray regionList = cloudJsonList.getJSONObject(j).getJSONArray("region-id-list");
249
250             for (int i = 0; i < regionList.length(); i++) {
251
252                 String region = regionList.getJSONObject(i).getString("region-id");
253
254                 JSONArray tenantList = regionList.getJSONObject(i).getJSONArray("tenant-id-list");
255
256                 for (int k = 0; k < tenantList.length(); k++) {
257                     String tenant = tenantList.getString(k);
258                     String valueforFQDN = cloudOwner + "-" + region + "-" + tenant;
259                     log.info("valueforFQDN for i " + i + " & j " + j + ": " + valueforFQDN);
260                     valuesforFQDN.add(valueforFQDN);
261                 }
262             }
263         }
264
265         return valuesforFQDN;
266     }
267
268     private boolean createDataForPD(JSONObject requestInfo, JSONObject documentInfo)
269             throws ArtifactHandlerInternalException {
270
271         String fn = "ArtifactHandlerNode.createReferenceDataForPD";
272         String artifactName = documentInfo.getString(ARTIFACT_NAME);
273         log.info(fn + " Received PD File Name: " + artifactName + " and suffix length " + PD.length());
274         try {
275
276             String suffix = artifactName.substring(PD.length());
277             createArtifactRecords(requestInfo, documentInfo, suffix);
278         } catch (Exception e) {
279             log.error("Error while creating PD data records", e);
280             throw new ArtifactHandlerInternalException("Error while creating PD data records", e);
281         }
282         return true;
283     }
284
285     private void createArtifactRecords(JSONObject requestInfo, JSONObject documentInfo, String suffix)
286             throws ArtifactHandlerInternalException {
287
288         try {
289             log.info("Creating Tosca Records and storing into SDC Artifacts");
290             String[] docs = { TOSCA_PARAM, YANG_PARAM };
291             ArtifactHandlerProviderUtil ahpUtil = new ArtifactHandlerProviderUtil();
292             String pdFileContents = documentInfo.getString(ARTIFACT_CONTENTS);
293
294             // Tosca generation
295             OutputStream toscaStream = new ByteArrayOutputStream();
296             String toscaContents;
297             ArtifactProcessorImpl toscaGenerator = getArtifactProcessorImpl();
298             toscaGenerator.generateArtifact(pdFileContents, toscaStream);
299             toscaContents = toscaStream.toString();
300             log.info("Generated Tosca File: " + toscaContents);
301
302             String yangContents = "YANG generation is in Progress";
303             String yangName = null;
304
305             for (String doc : docs) {
306                 documentInfo.put(ARTIFACT_TYPE, doc.concat("Type"));
307                 documentInfo.put(ARTIFACT_DESRIPTION, doc.concat("Model"));
308                 if (doc.equals(TOSCA_PARAM)) {
309                     documentInfo.put(ARTIFACT_CONTENTS, ahpUtil.escapeSql(toscaContents));
310                 } else if (doc.equals(YANG_PARAM)) {
311                     documentInfo.put(ARTIFACT_CONTENTS, ahpUtil.escapeSql(yangContents));
312                 }
313                 documentInfo.put(ARTIFACT_NAME, doc.concat(suffix));
314                 yangName = doc.concat(suffix);
315                 updateStoreArtifacts(requestInfo, documentInfo);
316             }
317
318             String artifactId = getArtifactID(yangName);
319             OutputStream yangStream = new ByteArrayOutputStream();
320             YANGGenerator yangGenerator = YANGGeneratorFactory.getYANGGenerator();
321             yangGenerator.generateYANG(artifactId, toscaContents, yangStream);
322             yangContents = yangStream.toString();
323
324             if (yangContents != null) {
325                 updateYangContents(artifactId, ahpUtil.escapeSql(yangContents));
326             }
327         } catch (Exception e) {
328             log.error("Error while creating artifact records", e);
329             throw new ArtifactHandlerInternalException("Error while creating artifact records", e);
330         }
331
332     }
333
334     private void updateYangContents(String artifactId, String yangContents) throws SvcLogicException {
335         SvcLogicContext context = new SvcLogicContext();
336         DBService dbservice = DBService.initialise();
337         dbservice.updateYangContents(context, artifactId, yangContents);
338     }
339
340     private String getArtifactID(String yangName) throws SvcLogicException {
341         SvcLogicContext context = new SvcLogicContext();
342         DBService dbservice = DBService.initialise();
343         return dbservice.getArtifactID(context, yangName);
344     }
345
346     protected boolean updateStoreArtifacts(JSONObject requestInfo, JSONObject documentInfo)
347             throws SvcLogicException, SQLException {
348         log.info("updateStoreArtifacts started storing of SDC Artifacts");
349
350         SvcLogicContext context = new SvcLogicContext();
351         DBService dbservice = DBService.initialise();
352         ArtifactHandlerProviderUtil ahpUtil = new ArtifactHandlerProviderUtil();
353         int intversion = 0;
354         context.setAttribute("artifact_name", documentInfo.getString(ARTIFACT_NAME));
355         String internalVersion =
356                 dbservice.getInternalVersionNumber(context, documentInfo.getString(ARTIFACT_NAME), null);
357         log.info("Internal Version number received from Database: " + internalVersion);
358         if (internalVersion != null) {
359             intversion = Integer.parseInt(internalVersion);
360             intversion++;
361         }
362         setAttribute(context, documentInfo::getString, SERVICE_UUID);
363         setAttribute(context, documentInfo::getString, DISTRIBUTION_ID);
364         setAttribute(context, documentInfo::getString, SERVICE_NAME);
365         setAttribute(context, documentInfo::getString, SERVICE_DESCRIPTION);
366         setAttribute(context, documentInfo::getString, RESOURCE_UUID);
367         setAttribute(context, documentInfo::getString, RESOURCE_INSTANCE_NAME);
368         setAttribute(context, documentInfo::getString, RESOURCE_VERSION);
369         setAttribute(context, documentInfo::getString, RESOURCE_NAME);
370         setAttribute(context, documentInfo::getString, RESOURCE_TYPE);
371         setAttribute(context, documentInfo::getString, ARTIFACT_UUID);
372         setAttribute(context, documentInfo::getString, ARTIFACT_TYPE);
373         setAttribute(context, documentInfo::getString, ARTIFACT_VERSION);
374         setAttribute(context, documentInfo::getString, ARTIFACT_DESRIPTION);
375         setAttribute(context, documentInfo::getString, ARTIFACT_NAME);
376         setAttribute(context, s -> ahpUtil.escapeSql(documentInfo.getString(s)), ARTIFACT_CONTENTS);
377
378         dbservice.saveArtifacts(context, intversion);
379         return true;
380     }
381
382     public boolean storeReferenceData(JSONObject requestInfo, JSONObject documentInfo)
383             throws ArtifactHandlerInternalException {
384         log.info("Started storing of SDC Artifacts into Handler");
385         try {
386             DBService dbservice = DBService.initialise();
387             ArtifactHandlerProviderUtil ahpUtil = new ArtifactHandlerProviderUtil();
388             String contentString = ahpUtil.escapeSql(documentInfo.getString(ARTIFACT_CONTENTS));
389             String artifactName = ahpUtil.escapeSql(documentInfo.getString(ARTIFACT_NAME));
390             String capabilityArtifactName =
391                     StringUtils.replace(artifactName, ARTIFACT_NAME_REFERENCE, ARTIFACT_NAME_CAPABILITY);
392             JSONObject capabilities = new JSONObject();
393             JSONArray vnfActionList = new JSONArray();
394             JSONArray vfModuleActionList = new JSONArray();
395             JSONArray vnfcActionList = new JSONArray();
396             JSONArray vmActionVnfcFunctionCodesList = new JSONArray();
397             String vnfType = null;
398             JSONObject contentObject = new JSONObject(contentString);
399             JSONArray contentArray = contentObject.getJSONArray("reference_data");
400             boolean storeCapabilityArtifact = true;
401
402             for (int a = 0; a < contentArray.length(); a++) {
403                 JSONObject content = contentArray.getJSONObject(a);
404                 log.info("contentString = " + content.toString());
405                 JSONObject scope = content.getJSONObject("scope");
406                 log.info("scope: " + scope);
407                 SvcLogicContext context = new SvcLogicContext();
408                 vnfType = scope.getString(VNF_TYPE);
409                 setAttribute(context, scope::getString, VNF_TYPE);
410                 setAttribute(context, content::getString, ACTION);
411                 String actionLevel = content.getString(ACTION_LEVEL);
412                 setAttribute(context, content::getString, ACTION_LEVEL);
413                 setAttribute(context, documentInfo::getString, ARTIFACT_TYPE);
414                 processActionLists(content, actionLevel, vnfcActionList, vfModuleActionList, vnfActionList,
415                         vmActionVnfcFunctionCodesList);
416                 JSONArray vnfcTypeList = setVnfcTypeInformation(scope, context);
417                 storeCapabilityArtifact = isCapabilityArtifactNeeded(context);
418
419                 if (content.has(DEVICE_PROTOCOL)) {
420                     setAttribute(context, content::getString, DEVICE_PROTOCOL);
421                 }
422                 if (content.has(USER_NAME)) {
423                     setAttribute(context, content::getString, USER_NAME);
424                 }
425                 if (content.has(PORT_NUMBER)) {
426                     setAttribute(context, content::getString, PORT_NUMBER);
427                 }
428                 if (content.has(URL)) {
429                     setAttribute(context, content::getString, URL);
430                 }
431                 processArtifactList(content, dbservice, context, vnfcTypeList);
432                 processConfigTypeActions(content, dbservice, context);
433                 dbservice.processDeviceAuthentication(context,
434                         dbservice.isArtifactUpdateRequired(context, DB_DEVICE_AUTHENTICATION));
435
436                 String actionProtocol = tryGetProtocol(content);
437                 if (!StringUtils.equalsIgnoreCase(actionProtocol, OPENSTACK)) {
438                     populateProtocolReference(dbservice, content);
439                 }
440                 context.setAttribute(VNFC_TYPE, null);
441                 if (content.has(VM) && content.get(VM) instanceof JSONArray) {
442                     processVmList(content, context, dbservice);
443                 }
444             }
445             if (storeCapabilityArtifact) {
446                 capabilities.put("vnf", vnfActionList);
447                 capabilities.put("vf-module", vfModuleActionList);
448                 capabilities.put("vnfc", vnfcActionList);
449                 capabilities.put("vm", vmActionVnfcFunctionCodesList);
450                 processAndStoreCapabilitiesArtifact(dbservice, documentInfo, capabilities, capabilityArtifactName,
451                         vnfType);
452             }
453
454         } catch (Exception e) {
455
456             log.error("Error while storing reference data", e);
457             throw new ArtifactHandlerInternalException("Error while storing reference data", e);
458         }
459
460         return true;
461     }
462
463     public boolean isCapabilityArtifactNeeded(SvcLogicContext context) {
464         String vnfcType = context.getAttribute(VNFC_TYPE);
465         if (StringUtils.isNotBlank(vnfcType)) {
466             log.info("No capability Artifact for this reference data as it is at VNFC level!!");
467             return false;
468         } else {
469             return true;
470         }
471     }
472
473     public JSONArray setVnfcTypeInformation(JSONObject scope, SvcLogicContext context) {
474         JSONArray vnfcTypeList = null;
475         if (scope.has(VNFC_TYPE) && !scope.isNull(VNFC_TYPE)) {
476             String vnfcTypeScope = scope.getString(VNFC_TYPE);
477             if (StringUtils.isNotBlank(vnfcTypeScope)) {
478                 setAttribute(context, scope::getString, VNFC_TYPE);
479                 log.info("VNFC type has been set for this reference artifact!! " + vnfcTypeScope);
480             } else {
481                 context.setAttribute(VNFC_TYPE, null);
482             }
483         } else {
484             context.setAttribute(VNFC_TYPE, null);
485         }
486         if (scope.has(VNFC_TYPE_LIST) && !scope.isNull(VNFC_TYPE_LIST)
487                 && scope.get(VNFC_TYPE_LIST) instanceof JSONArray) {
488             vnfcTypeList = scope.getJSONArray(VNFC_TYPE_LIST);
489             log.info("VNFC TYPE LIST found for this artifact!! " + vnfcTypeList.toString());
490         }
491         return vnfcTypeList;
492     }
493
494     public void processActionLists(JSONObject content, String actionLevel, JSONArray vnfcActionList,
495             JSONArray vfModuleActionList, JSONArray vnfActionList, JSONArray vmActionVnfcFunctionCodesList) {
496         if (validateActionLevel(actionLevel, ACTION_LEVEL_VNFC)) {
497             vnfcActionList.put(content.getString(ACTION));
498         }
499         if (validateActionLevel(actionLevel, ACTION_LEVEL_VF_MODULE)) {
500             vfModuleActionList.put(content.getString(ACTION));
501         }
502         if (validateActionLevel(actionLevel, ACTION_LEVEL_VNF)) {
503             vnfActionList.put(content.getString(ACTION));
504         }
505         if (validateActionLevel(actionLevel, ACTION_LEVEL_VM)) {
506             if (content.has(VNFC_FUNCTION_CODE_LIST)
507                     && !content.isNull(VNFC_FUNCTION_CODE_LIST)
508                     && content.get(VNFC_FUNCTION_CODE_LIST) instanceof JSONArray) {
509                 log.info("Found vnfc-function-code-list!!");
510                 JSONArray vnfcList = content.getJSONArray(VNFC_FUNCTION_CODE_LIST);
511                 JSONObject obj = new JSONObject();
512                 obj.put(content.getString(ACTION), vnfcList);
513                 vmActionVnfcFunctionCodesList.put(obj);
514             } else {
515                 log.info("Not getting JSONArray for VNFC FUNCTION CODES");
516             }
517         }
518
519     }
520
521     private boolean validateActionLevel(String actionLevel, String actionLevelVnfc) {
522         return null != actionLevel && actionLevel.equalsIgnoreCase(actionLevelVnfc);
523     }
524
525     public void processArtifactList(JSONObject content, DBService dbservice, SvcLogicContext context,
526             JSONArray vnfcTypeList)
527             throws ArtifactHandlerInternalException {
528
529         try {
530             if (content.has(ARTIFACT_LIST_PARAM) && content.get(ARTIFACT_LIST_PARAM) instanceof JSONArray) {
531                 JSONArray artifactLists = (JSONArray) content.get(ARTIFACT_LIST_PARAM);
532                 JSONArray templateIdList = null;
533                 if (content.has("template-id-list") && null != content.get("template-id-list")
534                         && content.get("template-id-list") instanceof JSONArray) {
535                     templateIdList = content.getJSONArray("template-id-list");
536                 }
537                 doProcessArtifactList(dbservice, context, artifactLists, templateIdList, vnfcTypeList);
538             }
539         } catch (Exception e) {
540             log.error("An error occurred when processing artifact list", e);
541             throw new ArtifactHandlerInternalException(e);
542         }
543     }
544
545     private void doProcessArtifactList(DBService dbservice, SvcLogicContext context, JSONArray artifactLists,
546             JSONArray templateIdList, JSONArray vnfcTypeList)
547             throws SvcLogicException, SQLException, ConfigurationException, DBException {
548         boolean pdFile = false;
549         int modelInd = 0;
550         int vnfcRefInd = 0;
551
552         for (int i = 0; i < artifactLists.length(); i++) {
553             String suffix = null;
554             String model = null;
555             JSONObject artifact = (JSONObject) artifactLists.get(i);
556             log.info("artifact is " + artifact);
557
558             // Get Model details
559             if (null != templateIdList && i > 0 && i % 2 == 0) { // Should this be changed to 3
560                 modelInd++; // to account for 3 artifacts
561             }
562             if (null != vnfcTypeList && i > 0 && i % 3 == 0) {
563                 // TDP 517180 - CD tool has made changes to send 3 artifacts instead of 2
564                 vnfcRefInd++;
565             }
566             setAttribute(context, artifact::getString, ARTIFACT_NAME);
567             context.setAttribute(FILE_CATEGORY, artifact.getString(ARTIFACT_TYPE));
568
569             if (artifact.getString(ARTIFACT_NAME) != null
570                     && artifact.getString(ARTIFACT_NAME).toLowerCase().startsWith(PD)) {
571
572                 suffix = artifact.getString(ARTIFACT_NAME).substring(PD.length());
573                 pdFile = true;
574             }
575             log.info("Artifact-type = " + context.getAttribute(FILE_CATEGORY));
576             log.info("Artifact-name = " + context.getAttribute(ARTIFACT_NAME));
577
578             if (null != templateIdList && modelInd < templateIdList.length()) {
579                 model = templateIdList.getString(modelInd);
580                 log.info("Model is ::: " + model + ", modelInd = " + modelInd);
581             }
582             if (null != vnfcTypeList && vnfcRefInd < vnfcTypeList.length()) {
583                 String vnfcType = vnfcTypeList.getString(vnfcRefInd);
584                 if (StringUtils.isNotBlank(vnfcType)) {
585                     context.setAttribute(VNFC_TYPE, vnfcType);
586                 }
587                 log.info("Setting vnfc type from vnfc-type-list :: " + vnfcType);
588             }
589             if (StringUtils.isNotBlank(model)) {
590                 dbservice.processSdcReferences(context,
591                         dbservice.isArtifactUpdateRequired(context, DB_SDC_REFERENCE, model),
592                         model);
593             } else {
594                 dbservice.processSdcReferences(context, dbservice.isArtifactUpdateRequired(context, DB_SDC_REFERENCE));
595             }
596
597             cleanArtifactInstanceData(context);
598             // Moving this into the for loop to account for mulitple artifact sets with pds
599             if (pdFile) {
600                 log.info("Sending information related to pdfile Artifact");
601                 tryUpdateContext(dbservice, context, pdFile, suffix, model);
602                 pdFile = false; // set to false after processing yang and Tosca
603             }
604         }
605     }
606
607     private void tryUpdateContext(DBService dbservice, SvcLogicContext context, boolean pdFile, String suffix,
608             String model)
609             throws SvcLogicException, SQLException, ConfigurationException, DBException {
610         if (pdFile) {
611             context.setAttribute(ARTIFACT_NAME, "Tosca".concat(suffix));
612             context.setAttribute(FILE_CATEGORY, TOSCA_MODEL);
613             dbservice.processSdcReferences(context,
614                     dbservice.isArtifactUpdateRequired(context, DB_SDC_REFERENCE, model), model);
615             context.setAttribute(ARTIFACT_NAME, "Yang".concat(suffix));
616             context.setAttribute(FILE_CATEGORY, PARAMETER_YANG);
617             dbservice.processSdcReferences(context,
618                     dbservice.isArtifactUpdateRequired(context, DB_SDC_REFERENCE, model), model);
619         }
620     }
621
622     public void processConfigTypeActions(JSONObject content, DBService dbservice, SvcLogicContext context)
623             throws ArtifactHandlerInternalException {
624
625         try {
626             if (contentsActionEquals(content, CONFIGURE_PARAM)
627                     || contentsActionEquals(content, CONFIG_MODIFY_PARAM)
628                     || contentsActionEquals(content, CONFIG_SCALE_OUT_PARAM)
629                     || contentsActionEquals(content, GET_CONFIG)
630                     || contentsActionEquals(content, POST_EVACUATE)
631                     || contentsActionEquals(content, PRE_EVACUATE)
632                     || contentsActionEquals(content, POST_MIGRATE)
633                     || contentsActionEquals(content, PRE_MIGRATE)
634                     || contentsActionEquals(content, POST_REBUILD)
635                     || contentsActionEquals(content, PRE_REBUILD)
636                     || contentsActionEquals(content, STOP_TRAFFIC)
637                     ) {
638
639                 if (content.has(DOWNLOAD_DG_REFERENCE) && content.getString(DOWNLOAD_DG_REFERENCE).length() > 0) {
640
641                     setAttribute(context, content::getString, DOWNLOAD_DG_REFERENCE);
642                     dbservice.processDownloadDgReference(context,
643                             dbservice.isArtifactUpdateRequired(context, DB_DOWNLOAD_DG_REFERENCE));
644                 }
645                 if (StringUtils.isBlank(context.getAttribute(DOWNLOAD_DG_REFERENCE))) {
646                     context.setAttribute(DOWNLOAD_DG_REFERENCE, dbservice.getDownLoadDGReference(context));
647                 }
648                 dbservice.processConfigActionDg(context,
649                         dbservice.isArtifactUpdateRequired(context, DB_CONFIG_ACTION_DG));
650
651                 tryProcessInterfaceProtocol(content, dbservice, context);
652             }
653         } catch (Exception e) {
654             log.error("An error occurred when processing config type actions", e);
655             throw new ArtifactHandlerInternalException(e);
656         }
657     }
658
659     private void tryProcessInterfaceProtocol(JSONObject content, DBService dbservice, SvcLogicContext context)
660             throws SvcLogicException, SQLException, ConfigurationException, DBException {
661
662         if (contentsActionEquals(content, CONFIGURE_PARAM) || contentsActionEquals(content, CONFIG_SCALE_OUT_PARAM)) {
663             boolean isUpdateRequired = dbservice.isArtifactUpdateRequired(context, DB_DEVICE_INTERFACE_PROTOCOL);
664             if (contentsActionEquals(content, CONFIGURE_PARAM)
665                     || (contentsActionEquals(content, CONFIG_SCALE_OUT_PARAM)
666                         && !isUpdateRequired)) {
667
668                 dbservice.processDeviceInterfaceProtocol(context, isUpdateRequired);
669             }
670         }
671     }
672
673     private boolean contentsActionEquals(JSONObject content, String action) {
674         return content.getString(ACTION).equals(action);
675     }
676
677     public void processVmList(JSONObject content, SvcLogicContext context, DBService dbservice)
678             throws SvcLogicException {
679         JSONArray vmList = (JSONArray) content.get(VM);
680         dbservice.cleanUpVnfcReferencesForVnf(context);
681         for (int i = 0; i < vmList.length(); i++) {
682             JSONObject vmInstance = (JSONObject) vmList.get(i);
683             setAttribute(context, s -> String.valueOf(vmInstance.getInt(s)), VM_INSTANCE);
684             log.info("VALUE = " + context.getAttribute(VM_INSTANCE));
685             String templateId = vmInstance.optString(TEMPLATE_ID);
686             trySetContext(context, vmInstance, templateId);
687             if (vmInstance.get(VNFC) instanceof JSONArray) {
688                 JSONArray vnfcInstanceList = (JSONArray) vmInstance.get(VNFC);
689                 for (int k = 0; k < vnfcInstanceList.length(); k++) {
690                     JSONObject vnfcInstance = (JSONObject) vnfcInstanceList.get(k);
691
692                     setAttribute(context, s -> String.valueOf(vnfcInstance.getInt(s)), VNFC_INSTANCE);
693                     setAttribute(context, vnfcInstance::getString, VNFC_TYPE);
694                     setAttribute(context, vnfcInstance::getString, VNFC_FUNCTION_CODE);
695                     resolveContext(context, vnfcInstance);
696                     tryProcessVnfcReference(content, context, dbservice);
697                     cleanVnfcInstance(context);
698                 }
699                 context.setAttribute(VM_INSTANCE, null);
700                 context.setAttribute(TEMPLATE_ID, null);
701             }
702         }
703     }
704
705     private void trySetContext(SvcLogicContext context, JSONObject vmInstance, String templateId) {
706         if (StringUtils.isNotBlank(templateId)) {
707             setAttribute(context, vmInstance::optString, TEMPLATE_ID);
708         }
709     }
710
711     private void tryProcessVnfcReference(JSONObject content, SvcLogicContext context, DBService dbservice)
712             throws SvcLogicException {
713         if (content.getString(ACTION).equals(CONFIGURE_PARAM)
714                 || content.getString(ACTION).equals(CONFIG_SCALE_OUT_PARAM)) {
715
716             dbservice.processVnfcReference(context, false);
717         }
718     }
719
720     private void resolveContext(SvcLogicContext context, JSONObject vnfcInstance) {
721         if (vnfcInstance.has(IPADDRESS_V4_OAM_VIP)) {
722             setAttribute(context, vnfcInstance::getString, IPADDRESS_V4_OAM_VIP);
723         }
724         if (vnfcInstance.has(GROUP_NOTATION_TYPE)) {
725             setAttribute(context, vnfcInstance::getString, GROUP_NOTATION_TYPE);
726         }
727         if (vnfcInstance.has(GROUP_NOTATION_VALUE)) {
728             setAttribute(context, vnfcInstance::getString, GROUP_NOTATION_VALUE);
729         }
730     }
731
732     private void cleanArtifactInstanceData(SvcLogicContext context) {
733         context.setAttribute(ARTIFACT_NAME, null);
734         context.setAttribute(FILE_CATEGORY, null);
735     }
736
737     private void cleanVnfcInstance(SvcLogicContext context) {
738
739         context.setAttribute(VNFC_INSTANCE, null);
740         context.setAttribute(VNFC_TYPE, null);
741         context.setAttribute(VNFC_FUNCTION_CODE, null);
742         context.setAttribute(IPADDRESS_V4_OAM_VIP, null);
743         context.setAttribute(GROUP_NOTATION_TYPE, null);
744         context.setAttribute(GROUP_NOTATION_VALUE, null);
745
746     }
747
748     private void processAndStoreCapabilitiesArtifact(DBService dbService, JSONObject documentInfo,
749             JSONObject capabilities, String capabilityArtifactName, String vnfType)
750             throws ArtifactHandlerInternalException {
751
752         log.info("Begin-->processAndStoreCapabilitiesArtifact");
753
754         try {
755             JSONObject newCapabilitiesObject = new JSONObject();
756             newCapabilitiesObject.put("capabilities", capabilities);
757             SvcLogicContext context = new SvcLogicContext();
758             context.setAttribute(ARTIFACT_NAME, capabilityArtifactName);
759             context.setAttribute(FILE_CATEGORY, CAPABILITY);
760             context.setAttribute(ACTION, null);
761             context.setAttribute(VNFC_TYPE, null);
762             context.setAttribute(ARTIFACT_TYPE, null);
763             context.setAttribute(VNF_TYPE, vnfType);
764             context.setAttribute(ARTIFACT_CONTENTS, newCapabilitiesObject.toString());
765             dbService.processSdcReferences(context, dbService.isArtifactUpdateRequired(context, DB_SDC_REFERENCE));
766             int intVersion = 0;
767             String internalVersion =
768                     dbService.getInternalVersionNumber(context, context.getAttribute(ARTIFACT_NAME), null);
769             log.info("Internal Version number received from Database: " + internalVersion);
770             if (internalVersion != null) {
771                 intVersion = Integer.parseInt(internalVersion) + 1;
772             }
773             setAttribute(context, documentInfo::getString, SERVICE_UUID);
774             setAttribute(context, documentInfo::getString, DISTRIBUTION_ID);
775             setAttribute(context, documentInfo::getString, SERVICE_NAME);
776             setAttribute(context, documentInfo::getString, SERVICE_DESCRIPTION);
777             setAttribute(context, documentInfo::getString, RESOURCE_UUID);
778             setAttribute(context, documentInfo::getString, RESOURCE_INSTANCE_NAME);
779             setAttribute(context, documentInfo::getString, RESOURCE_VERSION);
780             setAttribute(context, documentInfo::getString, RESOURCE_TYPE);
781             setAttribute(context, documentInfo::getString, ARTIFACT_UUID);
782             setAttribute(context, documentInfo::getString, ARTIFACT_VERSION);
783             setAttribute(context, documentInfo::getString, ARTIFACT_DESRIPTION);
784             dbService.saveArtifacts(context, intVersion);
785         } catch (Exception e) {
786             log.error("Error saving capabilities artifact to DB", e);
787             throw new ArtifactHandlerInternalException("Error saving capabilities artifact to DB", e);
788         } finally {
789             log.info("End-->processAndStoreCapabilitiesArtifact");
790         }
791     }
792
793     private void setAttribute(SvcLogicContext context, Function<String, String> value, String key) {
794         context.setAttribute(key, value.apply(key));
795     }
796
797     private void populateProtocolReference(DBService dbservice, JSONObject content)
798             throws ArtifactHandlerInternalException {
799         log.info("Begin-->populateProtocolReference");
800         try {
801             SvcLogicContext context = new SvcLogicContext();
802             JSONObject scope = content.getJSONObject("scope");
803             String vnfType = tryGetVnfType(scope);
804             String protocol = tryGetProtocol(content);
805             String action = tryGetAction(content);
806             String actionLevel = tryGetActionLevel(content);
807             String template = tryGetTemplate(content);
808
809             boolean isUpdateNeeded = dbservice.isProtocolReferenceUpdateRequired(context, vnfType, protocol, action,
810                     actionLevel, template);
811             if (isUpdateNeeded) {
812                 dbservice.updateProtocolReference(context, vnfType, protocol, action, actionLevel, template);
813             } else {
814                 dbservice.insertProtocolReference(context, vnfType, protocol, action, actionLevel, template);
815             }
816         } catch (Exception e) {
817             log.error("Error inserting record into protocolReference", e);
818             throw new ArtifactHandlerInternalException("Error inserting record into protocolReference", e);
819         } finally {
820             log.info("End-->populateProtocolReference");
821         }
822     }
823
824     private String tryGetVnfType(JSONObject scope) {
825         if (scope.has(VNF_TYPE) && !scope.isNull(VNF_TYPE)) {
826             return scope.getString(VNF_TYPE);
827         }
828         return null;
829     }
830
831     private String tryGetProtocol(JSONObject content) {
832         if (content.has(DEVICE_PROTOCOL)) {
833             return content.getString(DEVICE_PROTOCOL);
834         }
835         return null;
836     }
837
838     private String tryGetAction(JSONObject content) {
839         if (content.has(ACTION)) {
840             return content.getString(ACTION);
841         }
842         return null;
843     }
844
845     private String tryGetActionLevel(JSONObject content) {
846         if (content.has(ACTION_LEVEL)) {
847             return content.getString(ACTION_LEVEL);
848         }
849         return null;
850     }
851
852     private String tryGetTemplate(JSONObject content) {
853         if (content.has(TEMPLATE) && !content.isNull(TEMPLATE)) {
854             return content.getString(TEMPLATE);
855         }
856         return null;
857     }
858
859     protected ArtifactProcessorImpl getArtifactProcessorImpl() {
860         return new ArtifactProcessorImpl();
861     }
862 }