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 org.onap.sdc.utils.DistributionStatusEnum.COMPONENT_DONE_ERROR;
19 import static org.onap.sdc.utils.DistributionStatusEnum.COMPONENT_DONE_OK;
20 import com.google.protobuf.ByteString;
21 import io.grpc.ManagedChannel;
23 import java.io.FileOutputStream;
24 import java.io.IOException;
25 import java.io.InputStream;
26 import java.io.OutputStream;
27 import java.nio.file.Files;
28 import java.nio.file.Path;
29 import java.nio.file.Paths;
30 import java.util.Enumeration;
31 import java.util.List;
32 import java.util.Optional;
33 import java.util.regex.Pattern;
34 import java.util.zip.ZipEntry;
35 import java.util.zip.ZipFile;
36 import org.apache.commons.io.FileUtils;
37 import org.apache.tomcat.util.http.fileupload.IOUtils;
38 import org.onap.ccsdk.cds.sdclistener.client.SdcListenerAuthClientInterceptor;
39 import org.onap.ccsdk.cds.sdclistener.dto.SdcListenerDto;
40 import org.onap.ccsdk.cds.sdclistener.handler.BluePrintProcesssorHandler;
41 import org.onap.ccsdk.cds.sdclistener.status.SdcListenerStatus;
42 import org.onap.ccsdk.cds.sdclistener.util.FileUtil;
43 import org.onap.ccsdk.cds.controllerblueprints.common.api.Status;
44 import org.onap.ccsdk.cds.controllerblueprints.management.api.BluePrintUploadInput;
45 import org.onap.ccsdk.cds.controllerblueprints.management.api.FileChunk;
46 import org.onap.sdc.api.results.IDistributionClientDownloadResult;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.springframework.beans.factory.annotation.Autowired;
50 import org.springframework.beans.factory.annotation.Value;
51 import org.springframework.boot.context.properties.ConfigurationProperties;
52 import org.springframework.stereotype.Component;
55 @ConfigurationProperties("listenerservice")
56 public class ListenerServiceImpl implements ListenerService {
59 private BluePrintProcesssorHandler bluePrintProcesssorHandler;
62 private SdcListenerAuthClientInterceptor sdcListenerAuthClientInterceptor;
65 private SdcListenerStatus listenerStatus;
68 private SdcListenerDto sdcListenerDto;
70 @Value("${listenerservice.config.grpcAddress}")
71 private String grpcAddress;
73 @Value("${listenerservice.config.grpcPort}")
76 private static final String CBA_ZIP_PATH = "Artifacts/Resources/[a-zA-Z0-9-_]+/Deployment/CONTROLLER_BLUEPRINT_ARCHIVE/[a-zA-Z0-9-_]+[.]zip";
77 private static final int SUCCESS_CODE = 200;
78 private static final Logger LOGGER = LoggerFactory.getLogger(ListenerServiceImpl.class);
81 public void extractBluePrint(String csarArchivePath, String cbaArchivePath) {
82 Path cbaStorageDir = getStorageDirectory(cbaArchivePath);
83 try (ZipFile zipFile = new ZipFile(csarArchivePath)) {
84 Enumeration<? extends ZipEntry> entries = zipFile.entries();
85 while (entries.hasMoreElements()) {
86 ZipEntry entry = entries.nextElement();
87 String fileName = entry.getName();
88 if (Pattern.matches(CBA_ZIP_PATH, fileName)) {
89 final String cbaArchiveName = Paths.get(fileName).getFileName().toString();
90 LOGGER.info("Storing the CBA archive {}", cbaArchiveName);
91 storeBluePrint(zipFile, cbaArchiveName, cbaStorageDir, entry);
95 } catch (Exception e) {
96 LOGGER.error("Failed to extract blueprint {}", e);
100 private void storeBluePrint(ZipFile zipFile, String fileName, Path cbaArchivePath, ZipEntry entry) {
101 Path targetLocation = cbaArchivePath.resolve(fileName);
102 LOGGER.info("The target location for zip file is {}", targetLocation);
103 File targetZipFile = new File(targetLocation.toString());
106 targetZipFile.createNewFile();
107 } catch (IOException e) {
108 LOGGER.error("Could not able to create file {}", targetZipFile, e);
111 try (InputStream inputStream = zipFile.getInputStream(entry); OutputStream out = new FileOutputStream(
113 IOUtils.copy(inputStream, out);
114 LOGGER.info("Successfully store the CBA archive {} at this location", targetZipFile);
115 } catch (Exception e) {
116 LOGGER.error("Failed to put zip file into target location {}, {}", targetLocation, e);
121 public void saveBluePrintToCdsDatabase(Path cbaArchivePath, ManagedChannel channel) {
122 Optional<List<File>> zipFiles = FileUtil.getFilesFromDisk(cbaArchivePath);
123 zipFiles.ifPresent(files -> prepareRequestForCdsBackend(files, channel, cbaArchivePath.toString()));
127 public void extractCsarAndStore(IDistributionClientDownloadResult result, String csarArchivePath) {
129 // Create CSAR storage directory
130 Path csarStorageDir = getStorageDirectory(csarArchivePath);
131 byte[] payload = result.getArtifactPayload();
132 String csarFileName = result.getArtifactFilename();
133 Path targetLocation = csarStorageDir.resolve(csarFileName);
135 LOGGER.info("The target location for the CSAR file is {}", targetLocation);
137 File targetCsarFile = new File(targetLocation.toString());
139 try (FileOutputStream outFile = new FileOutputStream(targetCsarFile)) {
140 outFile.write(payload, 0, payload.length);
141 } catch (Exception e) {
142 LOGGER.error("Failed to put CSAR file into target location {}, {}", targetLocation, e);
146 private Path getStorageDirectory(String path) {
147 Path fileStorageLocation = Paths.get(path).toAbsolutePath().normalize();
149 if (!fileStorageLocation.toFile().exists()) {
151 return Files.createDirectories(fileStorageLocation);
152 } catch (IOException e) {
153 LOGGER.error("Fail to create directory {}, {}", e, fileStorageLocation);
156 return fileStorageLocation;
159 private void prepareRequestForCdsBackend(List<File> files, ManagedChannel managedChannel, String path) {
160 final String distributionId = sdcListenerDto.getDistributionId();
162 files.forEach(zipFile -> {
164 final BluePrintUploadInput request = generateBluePrintUploadInputBuilder(zipFile);
166 // Send request to CDS Backend.
167 final Status responseStatus = bluePrintProcesssorHandler.sendRequest(request, managedChannel);
169 if (responseStatus.getCode() != SUCCESS_CODE) {
170 final String errorMessage = String.format("Failed to store the CBA archive into CDS DB due to %s",
171 responseStatus.getErrorMessage());
172 listenerStatus.sendResponseStatusBackToSDC(distributionId,
173 COMPONENT_DONE_ERROR, errorMessage);
174 LOGGER.error(errorMessage);
177 LOGGER.info(responseStatus.getMessage());
178 listenerStatus.sendResponseStatusBackToSDC(distributionId,
179 COMPONENT_DONE_OK, null);
182 } catch (Exception e) {
183 final String errorMessage = String.format("Failure due to %s", e.getMessage());
184 listenerStatus.sendResponseStatusBackToSDC(distributionId, COMPONENT_DONE_ERROR, errorMessage);
185 LOGGER.error("Failure due to {}", e);
187 FileUtil.deleteFile(zipFile, path);
192 private BluePrintUploadInput generateBluePrintUploadInputBuilder(File file) throws IOException {
193 byte[] bytes = FileUtils.readFileToByteArray(file);
194 FileChunk fileChunk = FileChunk.newBuilder().setChunk(ByteString.copyFrom(bytes)).build();
196 return BluePrintUploadInput.newBuilder()
197 .setFileChunk(fileChunk)