daab4de7196e5a1ea312aac172136cfd55bd8d30
[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 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;
22 import java.io.File;
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;
53
54 @Component
55 @ConfigurationProperties("listenerservice")
56 public class ListenerServiceImpl implements ListenerService {
57
58     @Autowired
59     private BluePrintProcesssorHandler bluePrintProcesssorHandler;
60
61     @Autowired
62     private SdcListenerAuthClientInterceptor sdcListenerAuthClientInterceptor;
63
64     @Autowired
65     private SdcListenerStatus listenerStatus;
66
67     @Autowired
68     private SdcListenerDto sdcListenerDto;
69
70     @Value("${listenerservice.config.grpcAddress}")
71     private String grpcAddress;
72
73     @Value("${listenerservice.config.grpcPort}")
74     private int grpcPort;
75
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);
79
80     @Override
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);
92                 }
93             }
94
95         } catch (Exception e) {
96             LOGGER.error("Failed to extract blueprint {}", e);
97         }
98     }
99
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());
104
105         try {
106             targetZipFile.createNewFile();
107         } catch (IOException e) {
108             LOGGER.error("Could not able to create file {}", targetZipFile, e);
109         }
110
111         try (InputStream inputStream = zipFile.getInputStream(entry); OutputStream out = new FileOutputStream(
112             targetZipFile)) {
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);
117         }
118     }
119
120     @Override
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()));
124     }
125
126     @Override
127     public void extractCsarAndStore(IDistributionClientDownloadResult result, String csarArchivePath) {
128
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);
134
135         LOGGER.info("The target location for the CSAR file is {}", targetLocation);
136
137         File targetCsarFile = new File(targetLocation.toString());
138
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);
143         }
144     }
145
146     private Path getStorageDirectory(String path) {
147         Path fileStorageLocation = Paths.get(path).toAbsolutePath().normalize();
148
149         if (!fileStorageLocation.toFile().exists()) {
150             try {
151                 return Files.createDirectories(fileStorageLocation);
152             } catch (IOException e) {
153                 LOGGER.error("Fail to create directory {}, {}", e, fileStorageLocation);
154             }
155         }
156         return fileStorageLocation;
157     }
158
159     private void prepareRequestForCdsBackend(List<File> files, ManagedChannel managedChannel, String path) {
160         final String distributionId = sdcListenerDto.getDistributionId();
161
162         files.forEach(zipFile -> {
163             try {
164                 final BluePrintUploadInput request = generateBluePrintUploadInputBuilder(zipFile);
165
166                 // Send request to CDS Backend.
167                 final Status responseStatus = bluePrintProcesssorHandler.sendRequest(request, managedChannel);
168
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);
175
176                 } else {
177                     LOGGER.info(responseStatus.getMessage());
178                     listenerStatus.sendResponseStatusBackToSDC(distributionId,
179                         COMPONENT_DONE_OK, null);
180                 }
181
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);
186             } finally {
187                 FileUtil.deleteFile(zipFile, path);
188             }
189         });
190     }
191
192     private BluePrintUploadInput generateBluePrintUploadInputBuilder(File file) throws IOException {
193         byte[] bytes = FileUtils.readFileToByteArray(file);
194         FileChunk fileChunk = FileChunk.newBuilder().setChunk(ByteString.copyFrom(bytes)).build();
195
196         return BluePrintUploadInput.newBuilder()
197                 .setFileChunk(fileChunk)
198                 .build();
199     }
200 }