aboutsummaryrefslogtreecommitdiffstats
path: root/ms/sdclistener/application/src/main/java/org/onap/ccsdk/cds/sdclistener/service/ListenerServiceImpl.java
blob: 1aebd74b8a7be91ff65caf3381f0092ca0ccb8b7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
/*
 * Copyright © 2019 Bell Canada
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.onap.ccsdk.cds.sdclistener.service;

import com.google.protobuf.ByteString;
import io.grpc.ManagedChannel;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers;
import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader;
import org.onap.ccsdk.cds.controllerblueprints.common.api.Status;
import org.onap.ccsdk.cds.controllerblueprints.management.api.BlueprintUploadInput;
import org.onap.ccsdk.cds.controllerblueprints.management.api.FileChunk;
import org.onap.ccsdk.cds.controllerblueprints.management.api.UploadAction;
import org.onap.ccsdk.cds.sdclistener.client.SdcListenerAuthClientInterceptor;
import org.onap.ccsdk.cds.sdclistener.dto.SdcListenerDto;
import org.onap.ccsdk.cds.sdclistener.handler.BlueprintProcesssorHandler;
import org.onap.ccsdk.cds.sdclistener.status.SdcListenerStatus;
import org.onap.ccsdk.cds.sdclistener.util.FileUtil;
import org.onap.sdc.api.results.IDistributionClientDownloadResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

import static java.lang.String.format;
import static org.onap.ccsdk.cds.sdclistener.status.SdcListenerStatus.NotificationType.SDC_LISTENER_COMPONENT;
import static org.onap.sdc.utils.DistributionStatusEnum.COMPONENT_DONE_ERROR;
import static org.onap.sdc.utils.DistributionStatusEnum.COMPONENT_DONE_OK;

@Component
@ConfigurationProperties("listenerservice")
public class ListenerServiceImpl implements ListenerService {

    @Autowired
    private BlueprintProcesssorHandler bluePrintProcesssorHandler;

    @Autowired
    private SdcListenerAuthClientInterceptor sdcListenerAuthClientInterceptor;

    @Autowired
    private SdcListenerStatus listenerStatus;

    @Autowired
    private SdcListenerDto sdcListenerDto;

    @Value("${listenerservice.config.grpcAddress}")
    private String grpcAddress;

    @Value("${listenerservice.config.grpcPort}")
    private int grpcPort;

    private static final String CBA_ZIP_PATH =
            "Artifacts/[a-zA-Z0-9-_.]+/Deployment/CONTROLLER_BLUEPRINT_ARCHIVE/[a-zA-Z0-9-_.()]+[.]zip";
    private static final int SUCCESS_CODE = 200;
    private static final Logger LOGGER = LoggerFactory.getLogger(ListenerServiceImpl.class);

    @Override
    public void extractBlueprint(String csarArchivePath, String cbaArchivePath) {
        int validPathCount = 0;
        final String distributionId = getDistributionId();
        final String artifactUrl = getArtifactUrl();
        Path cbaStorageDir = getStorageDirectory(cbaArchivePath);
        try (ZipFile zipFile = new ZipFile(csarArchivePath)) {
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while (entries.hasMoreElements()) {
                ZipEntry entry = entries.nextElement();
                String fileName = entry.getName();
                if (Pattern.matches(CBA_ZIP_PATH, fileName)) {
                    validPathCount++;
                    final String cbaArchiveName = Paths.get(fileName).getFileName().toString();
                    LOGGER.info("Storing the CBA archive {}", cbaArchiveName);
                    storeBlueprint(zipFile, cbaArchiveName, cbaStorageDir, entry);
                }
            }

            if (validPathCount == 0) {
                LOGGER.info(
                        "CBA archive doesn't exist in the CSAR Package or it doesn't exist as per the given path {}",
                        CBA_ZIP_PATH);
                listenerStatus.sendResponseBackToSdc(distributionId, COMPONENT_DONE_OK, null, artifactUrl,
                        SDC_LISTENER_COMPONENT);
            }

        } catch (Exception e) {
            final String errorMessage = format("Failed to extract blueprint %s", e.getMessage());
            listenerStatus.sendResponseBackToSdc(distributionId, COMPONENT_DONE_ERROR, errorMessage, artifactUrl,
                    SDC_LISTENER_COMPONENT);
            LOGGER.error(errorMessage);
        }
    }

    private void storeBlueprint(ZipFile zipFile, String fileName, Path cbaArchivePath, ZipEntry entry) {
        Path targetLocation = cbaArchivePath.resolve(fileName);
        LOGGER.info("The target location for zip file is {}", targetLocation);
        File targetZipFile = new File(targetLocation.toString());

        try {
            if (!targetZipFile.createNewFile()) {
                LOGGER.warn("Overwriting zip file {}", targetLocation);
            }
        } catch (IOException e) {
            LOGGER.error("Could not able to create file {}", targetZipFile, e);
        }

        try (InputStream inputStream = zipFile.getInputStream(entry);
                OutputStream out = new FileOutputStream(targetZipFile)) {
            IOUtils.copy(inputStream, out);
            LOGGER.info("Successfully store the CBA archive {} at this location", targetZipFile);
        } catch (Exception e) {
            LOGGER.error("Failed to put zip file into target location {}, {}", targetLocation, e);
        }
    }

    @Override
    public void saveBlueprintToCdsDatabase(Path cbaArchivePath, ManagedChannel channel) {
        List<File> zipFiles = FileUtil.getFilesFromDisk(cbaArchivePath);
        if (!zipFiles.isEmpty()) {
            prepareRequestForCdsBackend(zipFiles, channel, cbaArchivePath.toString());
        }
    }

    @Override
    public void extractCsarAndStore(IDistributionClientDownloadResult result, Path csarArchivePath) {

        // Create CSAR storage directory
        Path csarStorageDir = getStorageDirectory(csarArchivePath.toString());
        byte[] payload = result.getArtifactPayload();
        String csarFileName = result.getArtifactFilename();
        Path targetLocation = csarStorageDir.resolve(csarFileName);

        LOGGER.info("The target location for the CSAR file is {}", targetLocation);

        File targetCsarFile = new File(targetLocation.toString());

        try (FileOutputStream outFile = new FileOutputStream(targetCsarFile)) {
            outFile.write(payload, 0, payload.length);
            if (!csarArchivePath.toFile().exists()) {
                LOGGER.error("Could not able to store the CSAR at this location {}", csarArchivePath);
            }
        } catch (Exception e) {
            LOGGER.error("Fail to write the data into FileOutputStream {}, {}", targetLocation, e);
        }
    }

    private Path getStorageDirectory(String path) {
        Path fileStorageLocation = Paths.get(path).toAbsolutePath().normalize();

        if (!fileStorageLocation.toFile().exists()) {
            try {
                return Files.createDirectories(fileStorageLocation);
            } catch (IOException e) {
                LOGGER.error("Fail to create directory {}, {}", e, fileStorageLocation);
            }
        }
        return fileStorageLocation;
    }

    private void prepareRequestForCdsBackend(List<File> files, ManagedChannel managedChannel, String path) {
        final String distributionId = getDistributionId();
        final String artifactUrl = getArtifactUrl();

        files.forEach(zipFile -> {
            try {
                final BlueprintUploadInput request = generateBlueprintUploadInputBuilder(zipFile, path);

                // Send request to CDS Backend.
                final Status responseStatus = bluePrintProcesssorHandler.sendRequest(request, managedChannel);

                if (responseStatus.getCode() != SUCCESS_CODE) {
                    final String errorMessage = format("Failed to store the CBA archive into CDS DB due to %s",
                            responseStatus.getErrorMessage());
                    listenerStatus.sendResponseBackToSdc(distributionId, COMPONENT_DONE_ERROR, errorMessage,
                            artifactUrl, SDC_LISTENER_COMPONENT);
                    LOGGER.error(errorMessage);
                } else {
                    LOGGER.info(responseStatus.getMessage());
                    listenerStatus.sendResponseBackToSdc(distributionId, COMPONENT_DONE_OK, null, artifactUrl,
                            SDC_LISTENER_COMPONENT);
                }

            } catch (Exception e) {
                final String errorMessage = format("Failure due to %s", e.getMessage());
                listenerStatus.sendResponseBackToSdc(distributionId, COMPONENT_DONE_ERROR, errorMessage, artifactUrl,
                        SDC_LISTENER_COMPONENT);
                LOGGER.error(errorMessage);
            }
        });
    }

    private BlueprintUploadInput generateBlueprintUploadInputBuilder(File file, String path) throws IOException {
        byte[] bytes = FileUtils.readFileToByteArray(file);
        FileChunk fileChunk = FileChunk.newBuilder().setChunk(ByteString.copyFrom(bytes)).build();
        FileUtil.deleteFile(file, path);
        return BlueprintUploadInput.newBuilder()
                .setCommonHeader(CommonHeader.newBuilder().setRequestId(UUID.randomUUID().toString())
                        .setSubRequestId(UUID.randomUUID().toString()).setOriginatorId("SDC-LISTENER").build())
                .setActionIdentifiers(
                        ActionIdentifiers.newBuilder().setActionName(UploadAction.PUBLISH.toString()).build())
                .setFileChunk(fileChunk).build();
    }

    private String getDistributionId() {
        return sdcListenerDto.getDistributionId();
    }

    private String getArtifactUrl() {
        return sdcListenerDto.getArtifactUrl();
    }

}