c7850537717fda94329c1262262076a4ec9e594a
[ccsdk/cds.git] /
1 /*
2  * Copyright © 2019 Bell Canada
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 package org.onap.ccsdk.cds.sdclistener.service;
17
18 import static java.lang.String.format;
19 import static org.onap.ccsdk.cds.sdclistener.status.SdcListenerStatus.NotificationType.SDC_LISTENER_COMPONENT;
20 import static org.onap.sdc.utils.DistributionStatusEnum.COMPONENT_DONE_ERROR;
21 import static org.onap.sdc.utils.DistributionStatusEnum.COMPONENT_DONE_OK;
22 import com.google.protobuf.ByteString;
23 import io.grpc.ManagedChannel;
24 import java.io.File;
25 import java.io.FileOutputStream;
26 import java.io.IOException;
27 import java.io.InputStream;
28 import java.io.OutputStream;
29 import java.nio.file.Files;
30 import java.nio.file.Path;
31 import java.nio.file.Paths;
32 import java.util.Enumeration;
33 import java.util.List;
34 import java.util.Optional;
35 import java.util.regex.Pattern;
36 import java.util.zip.ZipEntry;
37 import java.util.zip.ZipFile;
38 import org.apache.commons.io.FileUtils;
39 import org.apache.tomcat.util.http.fileupload.IOUtils;
40 import org.onap.ccsdk.cds.controllerblueprints.common.api.Status;
41 import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintUploadInput;
42 import org.onap.ccsdk.cds.controllerblueprints.management.api.FileChunk;
43 import org.onap.ccsdk.cds.sdclistener.client.SdcListenerAuthClientInterceptor;
44 import org.onap.ccsdk.cds.sdclistener.dto.SdcListenerDto;
45 import org.onap.ccsdk.cds.sdclistener.handler.BluePrintProcesssorHandler;
46 import org.onap.ccsdk.cds.sdclistener.status.SdcListenerStatus;
47 import org.onap.ccsdk.cds.sdclistener.util.FileUtil;
48 import org.onap.sdc.api.results.IDistributionClientDownloadResult;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51 import org.springframework.beans.factory.annotation.Autowired;
52 import org.springframework.beans.factory.annotation.Value;
53 import org.springframework.boot.context.properties.ConfigurationProperties;
54 import org.springframework.stereotype.Component;
55
56 @Component
57 @ConfigurationProperties("listenerservice")
58 public class ListenerServiceImpl implements ListenerService {
59
60     @Autowired
61     private BluePrintProcesssorHandler bluePrintProcesssorHandler;
62
63     @Autowired
64     private SdcListenerAuthClientInterceptor sdcListenerAuthClientInterceptor;
65
66     @Autowired
67     private SdcListenerStatus listenerStatus;
68
69     @Autowired
70     private SdcListenerDto sdcListenerDto;
71
72     @Value("${listenerservice.config.grpcAddress}")
73     private String grpcAddress;
74
75     @Value("${listenerservice.config.grpcPort}")
76     private int grpcPort;
77
78     private static final String CBA_ZIP_PATH = "Artifacts/[a-zA-Z0-9-_.]+/Deployment/CONTROLLER_BLUEPRINT_ARCHIVE/[a-zA-Z0-9-_.()]+[.]zip";
79     private static final int SUCCESS_CODE = 200;
80     private static final Logger LOGGER = LoggerFactory.getLogger(ListenerServiceImpl.class);
81
82     @Override
83     public void extractBluePrint(String csarArchivePath, String cbaArchivePath) {
84         int validPathCount = 0;
85         final String distributionId = getDistributionId();
86         final String artifactUrl = getArtifactUrl();
87         Path cbaStorageDir = getStorageDirectory(cbaArchivePath);
88         try (ZipFile zipFile = new ZipFile(csarArchivePath)) {
89             Enumeration<? extends ZipEntry> entries = zipFile.entries();
90             while (entries.hasMoreElements()) {
91                 ZipEntry entry = entries.nextElement();
92                 String fileName = entry.getName();
93                 if (Pattern.matches(CBA_ZIP_PATH, fileName)) {
94                     validPathCount++;
95                     final String cbaArchiveName = Paths.get(fileName).getFileName().toString();
96                     LOGGER.info("Storing the CBA archive {}", cbaArchiveName);
97                     storeBluePrint(zipFile, cbaArchiveName, cbaStorageDir, entry);
98                 }
99             }
100
101             if (validPathCount == 0) {
102                 LOGGER
103                     .info("CBA archive doesn't exist in the CSAR Package or it doesn't exist as per the given path {}",
104                         CBA_ZIP_PATH);
105                 listenerStatus.sendResponseBackToSdc(distributionId, COMPONENT_DONE_OK, null,
106                     artifactUrl, SDC_LISTENER_COMPONENT);
107             }
108
109         } catch (Exception e) {
110             final String errorMessage = format("Failed to extract blueprint %s", e.getMessage());
111             listenerStatus.sendResponseBackToSdc(distributionId, COMPONENT_DONE_ERROR, errorMessage,
112                 artifactUrl, SDC_LISTENER_COMPONENT);
113             LOGGER.error(errorMessage);
114         }
115     }
116
117     private void storeBluePrint(ZipFile zipFile, String fileName, Path cbaArchivePath, ZipEntry entry) {
118         Path targetLocation = cbaArchivePath.resolve(fileName);
119         LOGGER.info("The target location for zip file is {}", targetLocation);
120         File targetZipFile = new File(targetLocation.toString());
121
122         try {
123             targetZipFile.createNewFile();
124         } catch (IOException e) {
125             LOGGER.error("Could not able to create file {}", targetZipFile, e);
126         }
127
128         try (InputStream inputStream = zipFile.getInputStream(entry); OutputStream out = new FileOutputStream(
129             targetZipFile)) {
130             IOUtils.copy(inputStream, out);
131             LOGGER.info("Successfully store the CBA archive {} at this location", targetZipFile);
132         } catch (Exception e) {
133             LOGGER.error("Failed to put zip file into target location {}, {}", targetLocation, e);
134         }
135     }
136
137     @Override
138     public void saveBluePrintToCdsDatabase(Path cbaArchivePath, ManagedChannel channel) {
139         List<File> zipFiles = FileUtil.getFilesFromDisk(cbaArchivePath);
140         if (!zipFiles.isEmpty()) {
141             zipFiles.forEach(file -> FileUtil.deleteFile(file, cbaArchivePath.toString()));
142             prepareRequestForCdsBackend(zipFiles, channel, cbaArchivePath.toString());
143         } else {
144             LOGGER.error("Could not able to read CBA archives from this location {}", cbaArchivePath);
145         }
146     }
147
148     @Override
149     public void extractCsarAndStore(IDistributionClientDownloadResult result, Path csarArchivePath) {
150
151         // Create CSAR storage directory
152         Path csarStorageDir = getStorageDirectory(csarArchivePath.toString());
153         byte[] payload = result.getArtifactPayload();
154         String csarFileName = result.getArtifactFilename();
155         Path targetLocation = csarStorageDir.resolve(csarFileName);
156
157         LOGGER.info("The target location for the CSAR file is {}", targetLocation);
158
159         File targetCsarFile = new File(targetLocation.toString());
160
161         try (FileOutputStream outFile = new FileOutputStream(targetCsarFile)) {
162             outFile.write(payload, 0, payload.length);
163             if (!csarArchivePath.toFile().exists()) {
164                 LOGGER.error("Could not able to store the CSAR at this location {}", csarArchivePath);
165             }
166         } catch (Exception e) {
167             LOGGER.error("Fail to write the data into FileOutputStream {}, {}", targetLocation, e);
168         }
169     }
170
171     private Path getStorageDirectory(String path) {
172         Path fileStorageLocation = Paths.get(path).toAbsolutePath().normalize();
173
174         if (!fileStorageLocation.toFile().exists()) {
175             try {
176                 return Files.createDirectories(fileStorageLocation);
177             } catch (IOException e) {
178                 LOGGER.error("Fail to create directory {}, {}", e, fileStorageLocation);
179             }
180         }
181         return fileStorageLocation;
182     }
183
184     private void prepareRequestForCdsBackend(List<File> files, ManagedChannel managedChannel, String path) {
185         final String distributionId = getDistributionId();
186         final String artifactUrl = getArtifactUrl();
187
188         files.forEach(zipFile -> {
189             try {
190                 final BluePrintUploadInput request = generateBluePrintUploadInputBuilder(zipFile);
191
192                 // Send request to CDS Backend.
193                 final Status responseStatus = bluePrintProcesssorHandler.sendRequest(request, managedChannel);
194
195                 if (responseStatus.getCode() != SUCCESS_CODE) {
196                     final String errorMessage = format("Failed to store the CBA archive into CDS DB due to %s",
197                         responseStatus.getErrorMessage());
198                     listenerStatus.sendResponseBackToSdc(distributionId, COMPONENT_DONE_ERROR, errorMessage, artifactUrl,
199                         SDC_LISTENER_COMPONENT);
200                     LOGGER.error(errorMessage);
201                 } else {
202                     LOGGER.info(responseStatus.getMessage());
203                     listenerStatus.sendResponseBackToSdc(distributionId, COMPONENT_DONE_OK, null, artifactUrl,
204                         SDC_LISTENER_COMPONENT);
205                 }
206
207             } catch (Exception e) {
208                 final String errorMessage = format("Failure due to %s", e.getMessage());
209                 listenerStatus.sendResponseBackToSdc(distributionId, COMPONENT_DONE_ERROR, errorMessage, artifactUrl,
210                    SDC_LISTENER_COMPONENT);
211                 LOGGER.error(errorMessage);
212             } finally {
213                 FileUtil.deleteFile(zipFile, path);
214             }
215         });
216     }
217
218     private BluePrintUploadInput generateBluePrintUploadInputBuilder(File file) throws IOException {
219         byte[] bytes = FileUtils.readFileToByteArray(file);
220         FileChunk fileChunk = FileChunk.newBuilder().setChunk(ByteString.copyFrom(bytes)).build();
221
222         return BluePrintUploadInput.newBuilder()
223                 .setFileChunk(fileChunk)
224                 .build();
225     }
226
227     private String getDistributionId() {
228         return sdcListenerDto.getDistributionId();
229     }
230
231     private String getArtifactUrl() {
232         return sdcListenerDto.getArtifactUrl();
233     }
234 }