Updated SDC listener and dependent bundles
[appc.git] / appc-sdc-listener / appc-sdc-listener-bundle / src / main / java / org / onap / 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.onap.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.onap.appc.adapter.message.EventSender;
34 import org.onap.appc.exceptions.APPCException;
35 import org.onap.appc.sdc.artifacts.helper.DependencyModelGenerator;
36 import org.onap.appc.sdc.artifacts.object.Resource;
37 import org.onap.appc.sdc.artifacts.object.SDCArtifact;
38 import org.onap.appc.sdc.artifacts.object.SDCReference;
39 import org.openecomp.sdc.api.IDistributionClient;
40 import org.openecomp.sdc.api.notification.IArtifactInfo;
41 import org.openecomp.sdc.api.notification.INotificationData;
42 import org.openecomp.sdc.api.notification.IResourceInstance;
43 import org.openecomp.sdc.api.results.IDistributionClientDownloadResult;
44
45 import java.io.BufferedReader;
46 import java.io.ByteArrayInputStream;
47 import java.io.IOException;
48 import java.io.InputStreamReader;
49 import java.net.URI;
50 import java.util.HashMap;
51 import java.util.Iterator;
52 import java.util.LinkedList;
53 import java.util.List;
54 import java.util.Map;
55 import java.net.URI;
56 import java.util.*;
57 import java.util.zip.ZipEntry;
58 import java.util.zip.ZipInputStream;
59
60 public class ToscaCsarArtifactProcessor extends AbstractArtifactProcessor{
61
62     private final EELFLogger logger = EELFManager.getInstance().getLogger(ToscaCsarArtifactProcessor.class);
63
64     private DependencyModelGenerator dependencyModelGenerator;
65
66     public ToscaCsarArtifactProcessor(IDistributionClient client,
67                                       EventSender eventSender,
68                                       INotificationData notification,
69                                       IResourceInstance resource,
70                                       IArtifactInfo artifact,
71                                       URI storeUri){
72         super(client,eventSender,notification,resource,artifact,storeUri);
73         dependencyModelGenerator = new DependencyModelGenerator();
74     }
75
76     @Override
77     public void processArtifact(IDistributionClientDownloadResult download) throws APPCException {
78         logger.debug("processing artifact " + super.artifact.getArtifactType());
79         byte[] byteArray = download.getArtifactPayload();
80         String serviceFileName = "";
81         String serviceTemplateContent = "";
82         List<Resource> resources = null;
83         Map<String,String> csarFiles = new HashMap<>();
84         try (ZipInputStream inputStream = new ZipInputStream(new ByteArrayInputStream(byteArray))) {
85             ZipEntry entry = inputStream.getNextEntry();
86             logger.debug("First Entry = " +entry);
87             while(entry!= null){
88                 String filename = entry.getName();
89                 logger.debug("Next Entry = "+ filename);
90
91                 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
92                 String str = null;
93                 StringBuilder sb = new StringBuilder();
94                 while((str = bufferedReader.readLine()) != null){
95                     sb.append(new String(str)).append(System.getProperty("line.separator"));
96                 }
97                 csarFiles.put(filename,sb.toString());
98                 entry = inputStream.getNextEntry();
99             }
100
101         } catch (IOException e) {
102             logger.error("Error Reading TOSCA.meta from CSAR",e);
103             throw new APPCException(e);
104         }
105         serviceFileName = readServiceFileName(csarFiles.get("TOSCA-Metadata/TOSCA.meta"));
106         logger.debug("Service File Name = " + serviceFileName);
107         serviceTemplateContent = csarFiles.get(serviceFileName);
108
109         try {
110             resources = readResources (serviceTemplateContent);
111         } catch (Exception e) {
112             logger.error("Error reading resources from " + ", serviceFileName = " + serviceFileName
113                     + ", TOSCA Metadata = " + csarFiles.get("TOSCA-Metadata/TOSCA.meta"),e);
114             throw new APPCException(e);
115         }
116
117         for(Resource resource:resources){
118             String resourceTemplate = csarFiles.get("Definitions/resource-" + resource.getFileNameTag() + "-template.yml");
119             SDCArtifact artifact = this.getArtifactObject(resource,resourceTemplate);
120             processArtifact(artifact);
121         }
122     }
123
124     private String readServiceFileName(String toscaMetadata) {
125         toscaMetadata = toscaMetadata.substring(toscaMetadata.indexOf("Entry-Definitions"), toscaMetadata.indexOf(System.getProperty("line.separator"),toscaMetadata.indexOf("Entry-Definitions")));
126         toscaMetadata =toscaMetadata.split(":")[1].trim();
127         return toscaMetadata;
128     }
129
130     protected SDCArtifact getArtifactObject(Resource resource, String data){
131
132         SDCArtifact sdcArtifact = new SDCArtifact();
133
134         sdcArtifact.setArtifactUUID(this.artifact.getArtifactUUID());
135         sdcArtifact.setArtifactName(this.artifact.getArtifactName());
136         sdcArtifact.setArtifactType(this.artifact.getArtifactType());
137         sdcArtifact.setArtifactVersion(this.artifact.getArtifactVersion());
138         sdcArtifact.setArtifactDescription(this.artifact.getArtifactDescription());
139         sdcArtifact.setArtifactContent(data);
140         sdcArtifact.setCreationDate(super.getCurrentDateTime());
141
142         sdcArtifact.setDistributionId(this.notification.getDistributionID());
143         sdcArtifact.setServiceUUID(this.notification.getServiceUUID());
144         sdcArtifact.setServiceName(this.notification.getServiceName());
145         sdcArtifact.setServiceDescription(this.notification.getServiceDescription());
146
147         sdcArtifact.setResourceName(resource.getName());
148         sdcArtifact.setResourceType(resource.getType());
149         sdcArtifact.setResourceVersion(resource.getVersion());
150         sdcArtifact.setResourceUUID(resource.getUuid());
151         sdcArtifact.setResourceInstanceName(resource.getInstanceName());
152
153         return sdcArtifact;
154     }
155
156     private List<Resource> readResources(String serviceTemplateContent) throws IOException {
157         List<Resource> resources = new LinkedList<>();
158         ObjectMapper mapper = new ObjectMapper(new YAMLFactory());
159         JsonNode root = mapper.readTree(serviceTemplateContent);
160         JsonNode topologyTemplate =  root.get("topology_template");
161         JsonNode nodeTemplates =  topologyTemplate.get("node_templates");
162         Iterator<Map.Entry<String, JsonNode>> itr = nodeTemplates.fields();
163         while(itr.hasNext()){
164             Map.Entry<String, JsonNode> entry = itr.next();
165             String instanceName = entry.getKey();
166             JsonNode nodeTemplate = entry.getValue();
167
168             String fileNameTag =  nodeTemplate.get("type").asText();
169             logger.debug("Resource type in Service Template = " + fileNameTag);
170             fileNameTag = fileNameTag.substring(fileNameTag.lastIndexOf(".")+1,fileNameTag.length());
171             String version = nodeTemplate.get("metadata").get("version").asText();
172             String uuid = nodeTemplate.get("metadata").get("UUID").asText();
173             String name = nodeTemplate.get("metadata").get("name").asText();
174             String type = nodeTemplate.get("metadata").get("type").asText();
175
176             if(!"VF".equalsIgnoreCase(type)){
177                 continue;
178             }
179
180             Resource resource = new Resource();
181             resource.setFileNameTag(fileNameTag);
182             resource.setVersion(version);
183             resource.setUuid(uuid);
184             resource.setInstanceName(instanceName);
185             resource.setName(name);
186             resource.setType(type);
187
188             resources.add(resource);
189         }
190         return resources;
191     }
192
193
194     @Override
195     protected void processArtifact(SDCArtifact artifact) throws APPCException {
196         String vnfType = artifact.getResourceName();
197         String version = artifact.getResourceVersion();
198         String packageArtifactID = artifact.getArtifactUUID();
199
200         if (StringUtils.isEmpty(vnfType) ||
201                 StringUtils.isEmpty(version) ||
202                 StringUtils.isEmpty(packageArtifactID)) {
203             String errStr = String.format("Missing information in SDC request. Details: resource_type='%s', resource_version='%s', artifactID='%s'", vnfType, version, packageArtifactID);
204             logger.error(errStr);
205             throw new APPCException(errStr);
206         }
207         try {
208             SDCReference reference = new SDCReference();
209             reference.setVnfType(vnfType);
210             reference.setFileCategory("tosca_model");
211             reference.setArtifactName(artifact.getArtifactName());
212             logger.debug("Storing TOSCA to SDC Artifact");
213             artifactStorageService.storeSDCArtifactWithReference(artifact,reference);
214
215             SDCArtifact dependencyArtifact = getDependencyArtifact(artifact);
216             SDCReference dependencyReference = new SDCReference();
217             dependencyReference.setVnfType(vnfType);
218             dependencyReference.setFileCategory("tosca_dependency_model");
219             dependencyReference.setArtifactName(dependencyArtifact.getArtifactName());
220             logger.debug("Storing Dependency to SDC Artifact");
221             artifactStorageService.storeSDCArtifactWithReference(dependencyArtifact,dependencyReference);
222         } catch (Exception e) {
223             logger.error("Error processing artifact : " + artifact.toString() );
224             throw new APPCException(e.getMessage(),e);
225         }
226     }
227
228     private SDCArtifact getDependencyArtifact(SDCArtifact toscaArtifact) throws APPCException {
229         SDCArtifact artifact = new SDCArtifact();
230         artifact.setArtifactName("dependency_"+toscaArtifact.getArtifactName());
231         String dependencyModel = dependencyModelGenerator.getDependencyModel(toscaArtifact.getArtifactContent(),toscaArtifact.getResourceName());
232         artifact.setArtifactContent(dependencyModel);
233         artifact.setArtifactType("DEPENDENCY_MODEL");
234
235         artifact.setArtifactUUID(toscaArtifact.getArtifactUUID());
236         artifact.setArtifactVersion(toscaArtifact.getArtifactVersion());
237         artifact.setArtifactDescription(toscaArtifact.getArtifactDescription());
238         artifact.setCreationDate(super.getCurrentDateTime());
239         artifact.setDistributionId(toscaArtifact.getDistributionId());
240         artifact.setServiceUUID(toscaArtifact.getServiceUUID());
241         artifact.setServiceName(toscaArtifact.getServiceName());
242         artifact.setServiceDescription(toscaArtifact.getServiceDescription());
243         artifact.setResourceName(toscaArtifact.getResourceName());
244         artifact.setResourceType(toscaArtifact.getResourceType());
245         artifact.setResourceVersion(toscaArtifact.getResourceVersion());
246         artifact.setResourceUUID(toscaArtifact.getResourceUUID());
247         artifact.setResourceInstanceName(toscaArtifact.getResourceInstanceName());
248         return artifact;
249     }
250
251
252 }