2 * Copyright © 2019 Bell Canada
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
16 package org.onap.ccsdk.cds.sdclistener.service;
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;
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;
57 @ConfigurationProperties("listenerservice")
58 public class ListenerServiceImpl implements ListenerService {
61 private BluePrintProcesssorHandler bluePrintProcesssorHandler;
64 private SdcListenerAuthClientInterceptor sdcListenerAuthClientInterceptor;
67 private SdcListenerStatus listenerStatus;
70 private SdcListenerDto sdcListenerDto;
72 @Value("${listenerservice.config.grpcAddress}")
73 private String grpcAddress;
75 @Value("${listenerservice.config.grpcPort}")
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);
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)) {
95 final String cbaArchiveName = Paths.get(fileName).getFileName().toString();
96 LOGGER.info("Storing the CBA archive {}", cbaArchiveName);
97 storeBluePrint(zipFile, cbaArchiveName, cbaStorageDir, entry);
101 if (validPathCount == 0) {
103 .info("CBA archive doesn't exist in the CSAR Package or it doesn't exist as per the given path {}",
105 listenerStatus.sendResponseBackToSdc(distributionId, COMPONENT_DONE_OK, null,
106 artifactUrl, SDC_LISTENER_COMPONENT);
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);
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());
123 targetZipFile.createNewFile();
124 } catch (IOException e) {
125 LOGGER.error("Could not able to create file {}", targetZipFile, e);
128 try (InputStream inputStream = zipFile.getInputStream(entry); OutputStream out = new FileOutputStream(
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);
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());
144 LOGGER.error("Could not able to read CBA archives from this location {}", cbaArchivePath);
149 public void extractCsarAndStore(IDistributionClientDownloadResult result, Path csarArchivePath) {
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);
157 LOGGER.info("The target location for the CSAR file is {}", targetLocation);
159 File targetCsarFile = new File(targetLocation.toString());
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);
166 } catch (Exception e) {
167 LOGGER.error("Fail to write the data into FileOutputStream {}, {}", targetLocation, e);
171 private Path getStorageDirectory(String path) {
172 Path fileStorageLocation = Paths.get(path).toAbsolutePath().normalize();
174 if (!fileStorageLocation.toFile().exists()) {
176 return Files.createDirectories(fileStorageLocation);
177 } catch (IOException e) {
178 LOGGER.error("Fail to create directory {}, {}", e, fileStorageLocation);
181 return fileStorageLocation;
184 private void prepareRequestForCdsBackend(List<File> files, ManagedChannel managedChannel, String path) {
185 final String distributionId = getDistributionId();
186 final String artifactUrl = getArtifactUrl();
188 files.forEach(zipFile -> {
190 final BluePrintUploadInput request = generateBluePrintUploadInputBuilder(zipFile);
192 // Send request to CDS Backend.
193 final Status responseStatus = bluePrintProcesssorHandler.sendRequest(request, managedChannel);
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);
202 LOGGER.info(responseStatus.getMessage());
203 listenerStatus.sendResponseBackToSdc(distributionId, COMPONENT_DONE_OK, null, artifactUrl,
204 SDC_LISTENER_COMPONENT);
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);
213 FileUtil.deleteFile(zipFile, path);
218 private BluePrintUploadInput generateBluePrintUploadInputBuilder(File file) throws IOException {
219 byte[] bytes = FileUtils.readFileToByteArray(file);
220 FileChunk fileChunk = FileChunk.newBuilder().setChunk(ByteString.copyFrom(bytes)).build();
222 return BluePrintUploadInput.newBuilder()
223 .setFileChunk(fileChunk)
227 private String getDistributionId() {
228 return sdcListenerDto.getDistributionId();
231 private String getArtifactUrl() {
232 return sdcListenerDto.getArtifactUrl();