Fix the sdc-controller
[clamp.git] / src / main / java / org / onap / clamp / clds / sdc / controller / installer / CsarHandler.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP CLAMP
4  * ================================================================================
5  * Copyright (C) 2018 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.sdc.controller.installer;
25
26 import com.att.aft.dme2.internal.apache.commons.io.IOUtils;
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29
30 import java.io.IOException;
31 import java.io.InputStream;
32 import java.io.OutputStream;
33 import java.nio.file.Files;
34 import java.nio.file.Path;
35 import java.nio.file.Paths;
36 import java.util.Enumeration;
37 import java.util.HashMap;
38 import java.util.List;
39 import java.util.Map;
40 import java.util.zip.ZipEntry;
41 import java.util.zip.ZipFile;
42
43 import org.onap.clamp.clds.exception.sdc.controller.CsarHandlerException;
44 import org.onap.clamp.clds.exception.sdc.controller.SdcArtifactInstallerException;
45 import org.onap.sdc.api.notification.IArtifactInfo;
46 import org.onap.sdc.api.notification.INotificationData;
47 import org.onap.sdc.api.notification.IResourceInstance;
48 import org.onap.sdc.api.results.IDistributionClientDownloadResult;
49 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
50 import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException;
51 import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory;
52
53 /**
54  * CsarDescriptor that will be used to deploy file in CLAMP file system. Some
55  * methods can also be used to get some data from it.
56  */
57 public class CsarHandler {
58
59     private static final EELFLogger logger = EELFManager.getInstance().getLogger(CsarHandler.class);
60     private IArtifactInfo artifactElement;
61     private String csarFilePath;
62     private String controllerName;
63     private SdcToscaParserFactory factory = SdcToscaParserFactory.getInstance();
64     private ISdcCsarHelper sdcCsarHelper;
65     private Map<String, BlueprintArtifact> mapOfBlueprints = new HashMap<>();
66     public static final String CSAR_TYPE = "TOSCA_CSAR";
67     public static final String BLUEPRINT_TYPE = "DCAE_INVENTORY_BLUEPRINT";
68     private INotificationData sdcNotification;
69     public static final String RESOURCE_INSTANCE_NAME_PREFIX = "/Artifacts/Resources/";
70     public static final String RESOURCE_INSTANCE_NAME_SUFFIX = "/Deployment/";
71
72     public CsarHandler(INotificationData iNotif, String controller, String clampCsarPath) throws CsarHandlerException {
73         this.sdcNotification = iNotif;
74         this.controllerName = controller;
75         this.artifactElement = searchForUniqueCsar(iNotif);
76         this.csarFilePath = buildFilePathForCsar(artifactElement, clampCsarPath);
77     }
78
79     private String buildFilePathForCsar(IArtifactInfo artifactElement, String clampCsarPath) {
80         return clampCsarPath + "/" + controllerName + "/" + artifactElement.getArtifactName();
81     }
82
83     private IArtifactInfo searchForUniqueCsar(INotificationData iNotif) throws CsarHandlerException {
84         List<IArtifactInfo> serviceArtifacts = iNotif.getServiceArtifacts();
85         for (IArtifactInfo artifact : serviceArtifacts) {
86             if (artifact.getArtifactType().equals(CSAR_TYPE)) {
87                 return artifact;
88             }
89         }
90         throw new CsarHandlerException("Unable to find a CSAR in the Sdc Notification");
91     }
92
93     public synchronized void save(IDistributionClientDownloadResult resultArtifact)
94             throws SdcArtifactInstallerException, SdcToscaParserException {
95         try {
96             logger.info("Writing CSAR file : " + artifactElement.getArtifactURL() + " UUID "
97                     + artifactElement.getArtifactUUID() + ")");
98             Path path = Paths.get(csarFilePath);
99             Files.createDirectories(path.getParent());
100             // Create or replace the file
101             try (OutputStream out = Files.newOutputStream(path)) {
102                 out.write(resultArtifact.getArtifactPayload(), 0, resultArtifact.getArtifactPayload().length);
103             }
104             sdcCsarHelper = factory.getSdcCsarHelper(csarFilePath);
105             this.loadDcaeBlueprint();
106         } catch (IOException e) {
107             throw new SdcArtifactInstallerException(
108                     "Exception caught when trying to write the CSAR on the file system to " + csarFilePath, e);
109         }
110     }
111
112     private IResourceInstance searchForResourceByInstanceName(String blueprintResourceInstanceName)
113             throws SdcArtifactInstallerException {
114         for (IResourceInstance resource : this.sdcNotification.getResources()) {
115             String filteredString = resource.getResourceInstanceName().replaceAll("-", "");
116             filteredString = filteredString.replaceAll(" ", "");
117             if (filteredString.equals(blueprintResourceInstanceName)) {
118                 return resource;
119             }
120         }
121         throw new SdcArtifactInstallerException("Error when searching for " + blueprintResourceInstanceName
122                 + " as ResourceInstanceName in Sdc notification and did not find it");
123     }
124
125     private void loadDcaeBlueprint() throws IOException, SdcArtifactInstallerException {
126         try (ZipFile zipFile = new ZipFile(csarFilePath)) {
127             Enumeration<? extends ZipEntry> entries = zipFile.entries();
128             while (entries.hasMoreElements()) {
129                 ZipEntry entry = entries.nextElement();
130                 if (entry.getName().contains(BLUEPRINT_TYPE)) {
131                     BlueprintArtifact blueprintArtifact = new BlueprintArtifact();
132                     blueprintArtifact.setBlueprintArtifactName(
133                             entry.getName().substring(entry.getName().lastIndexOf('/') + 1, entry.getName().length()));
134                     blueprintArtifact
135                             .setBlueprintInvariantServiceUuid(this.getSdcNotification().getServiceInvariantUUID());
136                     try (InputStream stream = zipFile.getInputStream(entry)) {
137                         blueprintArtifact.setDcaeBlueprint(IOUtils.toString(stream));
138                     }
139                     IResourceInstance resource = searchForResourceByInstanceName(entry.getName().substring(
140                             entry.getName().indexOf(RESOURCE_INSTANCE_NAME_PREFIX)
141                                     + RESOURCE_INSTANCE_NAME_PREFIX.length(),
142                             entry.getName().indexOf(RESOURCE_INSTANCE_NAME_SUFFIX)));
143                     blueprintArtifact.setBlueprintInvariantResourceUuid(resource.getResourceInvariantUUID());
144                     blueprintArtifact.setBlueprintResourceInstanceName(resource.getResourceInstanceName());
145                     this.mapOfBlueprints.put(blueprintArtifact.getBlueprintResourceInstanceName(), blueprintArtifact);
146                 }
147             }
148         }
149     }
150
151     public IArtifactInfo getArtifactElement() {
152         return artifactElement;
153     }
154
155     public String getFilePath() {
156         return csarFilePath;
157     }
158
159     public synchronized ISdcCsarHelper getSdcCsarHelper() {
160         return sdcCsarHelper;
161     }
162
163     public INotificationData getSdcNotification() {
164         return sdcNotification;
165     }
166
167     public Map<String, BlueprintArtifact> getMapOfBlueprints() {
168         return mapOfBlueprints;
169     }
170 }