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.regex.Pattern;
35 import java.util.zip.ZipEntry;
36 import java.util.zip.ZipFile;
37 import org.apache.commons.io.FileUtils;
38 import org.apache.tomcat.util.http.fileupload.IOUtils;
39 import org.onap.ccsdk.cds.controllerblueprints.common.api.Status;
40 import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintUploadInput;
41 import org.onap.ccsdk.cds.controllerblueprints.management.api.FileChunk;
42 import org.onap.ccsdk.cds.sdclistener.client.SdcListenerAuthClientInterceptor;
43 import org.onap.ccsdk.cds.sdclistener.dto.SdcListenerDto;
44 import org.onap.ccsdk.cds.sdclistener.handler.BluePrintProcesssorHandler;
45 import org.onap.ccsdk.cds.sdclistener.status.SdcListenerStatus;
46 import org.onap.ccsdk.cds.sdclistener.util.FileUtil;
47 import org.onap.sdc.api.results.IDistributionClientDownloadResult;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.springframework.beans.factory.annotation.Autowired;
51 import org.springframework.beans.factory.annotation.Value;
52 import org.springframework.boot.context.properties.ConfigurationProperties;
53 import org.springframework.stereotype.Component;
56 @ConfigurationProperties("listenerservice")
57 public class ListenerServiceImpl implements ListenerService {
60 private BluePrintProcesssorHandler bluePrintProcesssorHandler;
63 private SdcListenerAuthClientInterceptor sdcListenerAuthClientInterceptor;
66 private SdcListenerStatus listenerStatus;
69 private SdcListenerDto sdcListenerDto;
71 @Value("${listenerservice.config.grpcAddress}")
72 private String grpcAddress;
74 @Value("${listenerservice.config.grpcPort}")
77 private static final String CBA_ZIP_PATH = "Artifacts/[a-zA-Z0-9-_.]+/Deployment/CONTROLLER_BLUEPRINT_ARCHIVE/[a-zA-Z0-9-_.()]+[.]zip";
78 private static final int SUCCESS_CODE = 200;
79 private static final Logger LOGGER = LoggerFactory.getLogger(ListenerServiceImpl.class);
82 public void extractBluePrint(String csarArchivePath, String cbaArchivePath) {
83 int validPathCount = 0;
84 final String distributionId = getDistributionId();
85 final String artifactUrl = getArtifactUrl();
86 Path cbaStorageDir = getStorageDirectory(cbaArchivePath);
87 try (ZipFile zipFile = new ZipFile(csarArchivePath)) {
88 Enumeration<? extends ZipEntry> entries = zipFile.entries();
89 while (entries.hasMoreElements()) {
90 ZipEntry entry = entries.nextElement();
91 String fileName = entry.getName();
92 if (Pattern.matches(CBA_ZIP_PATH, fileName)) {
94 final String cbaArchiveName = Paths.get(fileName).getFileName().toString();
95 LOGGER.info("Storing the CBA archive {}", cbaArchiveName);
96 storeBluePrint(zipFile, cbaArchiveName, cbaStorageDir, entry);
100 if (validPathCount == 0) {
102 .info("CBA archive doesn't exist in the CSAR Package or it doesn't exist as per the given path {}",
104 listenerStatus.sendResponseBackToSdc(distributionId, COMPONENT_DONE_OK, null,
105 artifactUrl, SDC_LISTENER_COMPONENT);
108 } catch (Exception e) {
109 final String errorMessage = format("Failed to extract blueprint %s", e.getMessage());
110 listenerStatus.sendResponseBackToSdc(distributionId, COMPONENT_DONE_ERROR, errorMessage,
111 artifactUrl, SDC_LISTENER_COMPONENT);
112 LOGGER.error(errorMessage);
116 private void storeBluePrint(ZipFile zipFile, String fileName, Path cbaArchivePath, ZipEntry entry) {
117 Path targetLocation = cbaArchivePath.resolve(fileName);
118 LOGGER.info("The target location for zip file is {}", targetLocation);
119 File targetZipFile = new File(targetLocation.toString());
122 targetZipFile.createNewFile();
123 } catch (IOException e) {
124 LOGGER.error("Could not able to create file {}", targetZipFile, e);
127 try (InputStream inputStream = zipFile.getInputStream(entry); OutputStream out = new FileOutputStream(
129 IOUtils.copy(inputStream, out);
130 LOGGER.info("Successfully store the CBA archive {} at this location", targetZipFile);
131 } catch (Exception e) {
132 LOGGER.error("Failed to put zip file into target location {}, {}", targetLocation, e);
137 public void saveBluePrintToCdsDatabase(Path cbaArchivePath, ManagedChannel channel) {
138 List<File> zipFiles = FileUtil.getFilesFromDisk(cbaArchivePath);
139 if (!zipFiles.isEmpty()) {
140 prepareRequestForCdsBackend(zipFiles, channel, cbaArchivePath.toString());
145 public void extractCsarAndStore(IDistributionClientDownloadResult result, Path csarArchivePath) {
147 // Create CSAR storage directory
148 Path csarStorageDir = getStorageDirectory(csarArchivePath.toString());
149 byte[] payload = result.getArtifactPayload();
150 String csarFileName = result.getArtifactFilename();
151 Path targetLocation = csarStorageDir.resolve(csarFileName);
153 LOGGER.info("The target location for the CSAR file is {}", targetLocation);
155 File targetCsarFile = new File(targetLocation.toString());
157 try (FileOutputStream outFile = new FileOutputStream(targetCsarFile)) {
158 outFile.write(payload, 0, payload.length);
159 if (!csarArchivePath.toFile().exists()) {
160 LOGGER.error("Could not able to store the CSAR at this location {}", csarArchivePath);
162 } catch (Exception e) {
163 LOGGER.error("Fail to write the data into FileOutputStream {}, {}", targetLocation, e);
167 private Path getStorageDirectory(String path) {
168 Path fileStorageLocation = Paths.get(path).toAbsolutePath().normalize();
170 if (!fileStorageLocation.toFile().exists()) {
172 return Files.createDirectories(fileStorageLocation);
173 } catch (IOException e) {
174 LOGGER.error("Fail to create directory {}, {}", e, fileStorageLocation);
177 return fileStorageLocation;
180 private void prepareRequestForCdsBackend(List<File> files, ManagedChannel managedChannel, String path) {
181 final String distributionId = getDistributionId();
182 final String artifactUrl = getArtifactUrl();
184 files.forEach(zipFile -> {
186 final BluePrintUploadInput request = generateBluePrintUploadInputBuilder(zipFile, path);
188 // Send request to CDS Backend.
189 final Status responseStatus = bluePrintProcesssorHandler.sendRequest(request, managedChannel);
191 if (responseStatus.getCode() != SUCCESS_CODE) {
192 final String errorMessage = format("Failed to store the CBA archive into CDS DB due to %s",
193 responseStatus.getErrorMessage());
194 listenerStatus.sendResponseBackToSdc(distributionId, COMPONENT_DONE_ERROR, errorMessage, artifactUrl,
195 SDC_LISTENER_COMPONENT);
196 LOGGER.error(errorMessage);
198 LOGGER.info(responseStatus.getMessage());
199 listenerStatus.sendResponseBackToSdc(distributionId, COMPONENT_DONE_OK, null, artifactUrl,
200 SDC_LISTENER_COMPONENT);
203 } catch (Exception e) {
204 final String errorMessage = format("Failure due to %s", e.getMessage());
205 listenerStatus.sendResponseBackToSdc(distributionId, COMPONENT_DONE_ERROR, errorMessage, artifactUrl,
206 SDC_LISTENER_COMPONENT);
207 LOGGER.error(errorMessage);
212 private BluePrintUploadInput generateBluePrintUploadInputBuilder(File file, String path) throws IOException {
213 byte[] bytes = FileUtils.readFileToByteArray(file);
214 FileChunk fileChunk = FileChunk.newBuilder().setChunk(ByteString.copyFrom(bytes)).build();
215 FileUtil.deleteFile(file, path);
216 return BluePrintUploadInput.newBuilder()
217 .setFileChunk(fileChunk)
221 private String getDistributionId() {
222 return sdcListenerDto.getDistributionId();
225 private String getArtifactUrl() {
226 return sdcListenerDto.getArtifactUrl();