Merging in bug fixes
[appc.git] / appc-asdc-listener / appc-asdc-listener-bundle / src / main / java / org / openecomp / appc / sdc / artifacts / impl / ToscaCsarArtifactProcessor.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * 
21  * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.openecomp.appc.sdc.artifacts.impl;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import com.fasterxml.jackson.databind.JsonNode;
30 import com.fasterxml.jackson.databind.ObjectMapper;
31 import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
32 import org.apache.commons.lang.StringUtils;
33 import org.openecomp.appc.adapter.message.EventSender;
34 import org.openecomp.appc.exceptions.APPCException;
35 import org.openecomp.appc.licmgr.Constants;
36 import org.openecomp.appc.sdc.artifacts.object.Resource;
37 import org.openecomp.appc.sdc.artifacts.object.SDCArtifact;
38 import org.openecomp.sdc.api.IDistributionClient;
39 import org.openecomp.sdc.api.notification.IArtifactInfo;
40 import org.openecomp.sdc.api.notification.INotificationData;
41 import org.openecomp.sdc.api.notification.IResourceInstance;
42 import org.openecomp.sdc.api.results.IDistributionClientDownloadResult;
43
44 import javax.json.Json;
45 import java.io.*;
46 import java.net.URI;
47 import java.util.*;
48 import java.util.zip.ZipEntry;
49 import java.util.zip.ZipInputStream;
50
51 public class ToscaCsarArtifactProcessor extends AbstractArtifactProcessor{
52
53     private final EELFLogger logger = EELFManager.getInstance().getLogger(ToscaCsarArtifactProcessor.class);
54
55     public ToscaCsarArtifactProcessor(IDistributionClient client, EventSender eventSender, INotificationData notification, IResourceInstance resource,
56                                IArtifactInfo artifact, URI storeUri){
57         super(client,eventSender,notification,resource,artifact,storeUri);
58     }
59
60     @Override
61     public void processArtifact(IDistributionClientDownloadResult download) throws APPCException {
62         logger.debug("processing artifact " + super.artifact.getArtifactType());
63         byte[] byteArray = download.getArtifactPayload();
64         String serviceFileName = "";
65         String serviceTemplateContent = "";
66         List<Resource> resources = null;
67         Map<String,String> csarFiles = new HashMap<>();
68         try (ZipInputStream inputStream = new ZipInputStream(new ByteArrayInputStream(byteArray))) {
69             ZipEntry entry = inputStream.getNextEntry();
70             logger.debug("First Entry = " +entry);
71             while(entry!= null){
72                 String filename = entry.getName();
73                 logger.debug("Next Entry = "+ filename);
74
75                 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
76                 String str = null;
77                 StringBuilder sb = new StringBuilder();
78                 while((str = bufferedReader.readLine()) != null){
79                     sb.append(new String(str)).append(System.getProperty("line.separator"));
80                 }
81                 csarFiles.put(filename,sb.toString());
82                 entry = inputStream.getNextEntry();
83             }
84
85         } catch (IOException e) {
86             logger.error("Error Reading TOSCA.meta from CSAR",e);
87             throw new APPCException(e);
88         }
89         serviceFileName = readServiceFileName(csarFiles.get("TOSCA-Metadata/TOSCA.meta"));
90         logger.debug("Service File Name = " + serviceFileName);
91         serviceTemplateContent = csarFiles.get(serviceFileName);
92
93         try {
94             resources = readResources (serviceTemplateContent);
95         } catch (Exception e) {
96             logger.error("Error reading resources from " + ", serviceFileName = " + serviceFileName
97                                                     + ", TOSCA Metadata = " + csarFiles.get("TOSCA-Metadata/TOSCA.meta"),e);
98             throw new APPCException(e);
99         }
100
101         for(Resource resource:resources){
102             String resourceTemplate = csarFiles.get("Definitions/resource-" + resource.getFileNameTag() + "-template.yml");
103             SDCArtifact artifact = this.getArtifactObject(resource,resourceTemplate);
104             processArtifact(artifact);
105         }
106     }
107
108     private String readServiceFileName(String toscaMetadata) {
109         toscaMetadata = toscaMetadata.substring(toscaMetadata.indexOf("Entry-Definitions"), toscaMetadata.indexOf(System.getProperty("line.separator"),toscaMetadata.indexOf("Entry-Definitions")));
110         toscaMetadata =toscaMetadata.split(":")[1].trim();
111         return toscaMetadata;
112     }
113
114     protected SDCArtifact getArtifactObject(Resource resource, String data){
115
116         SDCArtifact sdcArtifact = new SDCArtifact();
117
118         sdcArtifact.setArtifactUUID(this.artifact.getArtifactUUID());
119         sdcArtifact.setArtifactName(this.artifact.getArtifactName());
120         sdcArtifact.setArtifactType(this.artifact.getArtifactType());
121         sdcArtifact.setArtifactVersion(this.artifact.getArtifactVersion());
122         sdcArtifact.setArtifactDescription(this.artifact.getArtifactDescription());
123         sdcArtifact.setArtifactContent(data);
124         sdcArtifact.setCreationDate(super.getCurrentDateTime());
125
126         sdcArtifact.setDistributionId(this.notification.getDistributionID());
127         sdcArtifact.setServiceUUID(this.notification.getServiceUUID());
128         sdcArtifact.setServiceName(this.notification.getServiceName());
129         sdcArtifact.setServiceDescription(this.notification.getServiceDescription());
130
131         sdcArtifact.setResourceName(resource.getName());
132         sdcArtifact.setResourceType(resource.getType());
133         sdcArtifact.setResourceVersion(resource.getVersion());
134         sdcArtifact.setResourceUUID(resource.getUuid());
135         sdcArtifact.setResourceInstanceName(resource.getInstanceName());
136
137         return sdcArtifact;
138     }
139
140     private List<Resource> readResources(String serviceTemplateContent) throws IOException {
141         List<Resource> resources = new LinkedList<>();
142         ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
143         JsonNode root = mapper.readTree(serviceTemplateContent);
144         JsonNode topologyTemplate =  root.get("topology_template");
145         JsonNode nodeTemplates =  topologyTemplate.get("node_templates");
146         Iterator<Map.Entry<String, JsonNode>> itr = nodeTemplates.fields();
147         while(itr.hasNext()){
148             Map.Entry<String, JsonNode> entry = itr.next();
149             String instanceName = entry.getKey();
150             JsonNode nodeTemplate = entry.getValue();
151
152             String fileNameTag =  nodeTemplate.get("type").asText();
153             logger.debug("Resource type in Service Template = " + fileNameTag);
154             fileNameTag = fileNameTag.substring(fileNameTag.lastIndexOf(".")+1,fileNameTag.length());
155             String version = nodeTemplate.get("metadata").get("version").asText();
156             String uuid = nodeTemplate.get("metadata").get("UUID").asText();
157             String name = nodeTemplate.get("metadata").get("name").asText();
158             String type = nodeTemplate.get("metadata").get("type").asText();
159
160             if(!"VF".equalsIgnoreCase(type)){
161                 continue;
162             }
163
164             Resource resource = new Resource();
165             resource.setFileNameTag(fileNameTag);
166             resource.setVersion(version);
167             resource.setUuid(uuid);
168             resource.setInstanceName(instanceName);
169             resource.setName(name);
170             resource.setType(type);
171
172             resources.add(resource);
173         }
174         return resources;
175     }
176
177
178     @Override
179     protected void processArtifact(SDCArtifact artifact) throws APPCException {
180         String vnfType = artifact.getResourceName();
181         String version = artifact.getResourceVersion();
182         String packageArtifactID = artifact.getArtifactUUID();
183
184         if (StringUtils.isEmpty(vnfType) ||
185                 StringUtils.isEmpty(version) ||
186                 StringUtils.isEmpty(packageArtifactID)) {
187             String errStr = String.format("Missing information in SDC request. Details: resource_type='%s', resource_version='%s', artifactID='%s'", vnfType, version, packageArtifactID);
188             logger.error(errStr);
189             throw new APPCException(errStr);
190         }
191
192         try {
193             SDCArtifact existingArtifact = artifactStorageService.retrieveSDCArtifact(vnfType, version,artifact.getArtifactType());
194
195             if (existingArtifact ==null) { // new resource
196                 logger.debug("Artifact not found for vnfType = " + vnfType + " , version = " +  version + " , artifactType = " + artifact.getArtifactType());
197                 artifactStorageService.storeASDCArtifact(artifact);
198             } else { // duplicate
199                 logger.debug("Artifact retrieved from database = " + existingArtifact);
200                 logger.warn(String.format("Artifact of type '%s' already deployed for resource_type='%s' and resource_version='%s'", Constants.VF_LICENSE, vnfType, version));
201             }
202
203         } catch (Exception e) {
204             logger.error("Error processing artifact : " + artifact.toString() );
205             throw new APPCException(e.getMessage(),e);
206         }
207     }
208
209
210 }