aboutsummaryrefslogtreecommitdiffstats
path: root/plugins/reception-plugins/src/main/java/org/onap/policy/distribution/reception/handling/sdc/SdcReceptionHandler.java
blob: de44dc85bd6e744302bbad8f1ba61d959d54a694 (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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
/*-
 * ============LICENSE_START=======================================================
 *  Copyright (C) 2018 Ericsson. All rights reserved.
 *  Copyright (C) 2019, 2022-2023 Nordix Foundation.
 *  Modifications Copyright (C) 2020-2021 AT&T Intellectual Property. All rights reserved.
 *  Modifications Copyright (C) 2021 Bell Canada. All rights reserved.
 * ================================================================================
 * 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.
 *
 * SPDX-License-Identifier: Apache-2.0
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.distribution.reception.handling.sdc;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Optional;
import java.util.concurrent.atomic.AtomicInteger;
import org.onap.policy.common.parameters.ParameterService;
import org.onap.policy.distribution.model.Csar;
import org.onap.policy.distribution.reception.decoding.PolicyDecodingException;
import org.onap.policy.distribution.reception.handling.AbstractReceptionHandler;
import org.onap.policy.distribution.reception.handling.sdc.SdcClientHandler.SdcClientOperationType;
import org.onap.policy.distribution.reception.handling.sdc.exceptions.ArtifactDownloadException;
import org.onap.policy.distribution.reception.statistics.DistributionStatisticsManager;
import org.onap.sdc.api.IDistributionClient;
import org.onap.sdc.api.consumer.IComponentDoneStatusMessage;
import org.onap.sdc.api.consumer.IDistributionStatusMessage;
import org.onap.sdc.api.consumer.INotificationCallback;
import org.onap.sdc.api.notification.IArtifactInfo;
import org.onap.sdc.api.notification.INotificationData;
import org.onap.sdc.api.results.IDistributionClientDownloadResult;
import org.onap.sdc.api.results.IDistributionClientResult;
import org.onap.sdc.impl.DistributionClientFactory;
import org.onap.sdc.impl.DistributionClientImpl;
import org.onap.sdc.utils.DistributionActionResultEnum;
import org.onap.sdc.utils.DistributionStatusEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Handles reception of inputs from ONAP Service Design and Creation (SDC) from which policies may be decoded.
 */
public class SdcReceptionHandler extends AbstractReceptionHandler implements INotificationCallback {

    private static final Logger LOGGER = LoggerFactory.getLogger(SdcReceptionHandler.class);
    private static final String SECONDS = "Seconds";

    private SdcReceptionHandlerStatus sdcReceptionHandlerStatus = SdcReceptionHandlerStatus.STOPPED;
    private IDistributionClient distributionClient;
    private SdcConfiguration sdcConfig;
    private final AtomicInteger nbOfNotificationsOngoing = new AtomicInteger();
    private int retryDelay;
    private SdcClientHandler sdcClientHandler;

    private enum DistributionStatusType {
        DOWNLOAD, DEPLOY
    }

    @Override
    protected void initializeReception(final String parameterGroupName) {
        final SdcReceptionHandlerConfigurationParameterGroup handlerParameters =
            ParameterService.get(parameterGroupName);
        retryDelay = handlerParameters.getRetryDelay() < 30 ? 30 : handlerParameters.getRetryDelay();
        sdcConfig = new SdcConfiguration(handlerParameters);
        distributionClient = createSdcDistributionClient();
        sdcClientHandler = new SdcClientHandler(this, SdcClientOperationType.START, retryDelay);
    }

    @Override
    public void destroy() {
        if (distributionClient != null) {
            sdcClientHandler = new SdcClientHandler(this, SdcClientOperationType.STOP, retryDelay);
        }
    }

    @Override
    public void activateCallback(final INotificationData notificationData) {
        LOGGER.debug("Receieved the notification from SDC with ID: {}", notificationData.getDistributionID());
        changeSdcReceptionHandlerStatus(SdcReceptionHandlerStatus.BUSY);
        processCsarServiceArtifacts(notificationData);
        changeSdcReceptionHandlerStatus(SdcReceptionHandlerStatus.IDLE);
        LOGGER.debug("Processed the notification from SDC with ID: {}", notificationData.getDistributionID());
    }

    /**
     * Method to change the status of this reception handler instance.
     *
     * @param newStatus the new status
     */
    private synchronized void changeSdcReceptionHandlerStatus(final SdcReceptionHandlerStatus newStatus) {
        switch (newStatus) {
            case INIT, STOPPED:
                sdcReceptionHandlerStatus = newStatus;
                break;
            case IDLE:
                handleIdleStatusChange(newStatus);
                break;
            case BUSY:
                nbOfNotificationsOngoing.incrementAndGet();
                sdcReceptionHandlerStatus = newStatus;
                break;
            default:
                break;
        }
    }

    /**
     * Creates an instance of {@link IDistributionClient} from {@link DistributionClientFactory}.
     *
     * @return the {@link IDistributionClient} instance
     */
    protected IDistributionClient createSdcDistributionClient() {
        return new DistributionClientImpl();
    }

    /**
     * Method to initialize the SDC client.
     */
    protected void initializeSdcClient() {

        LOGGER.debug("Initializing the SDC Client...");
        if (sdcReceptionHandlerStatus != SdcReceptionHandlerStatus.STOPPED) {
            LOGGER.error("The SDC Client is already initialized");
            return;
        }
        final IDistributionClientResult clientResult = distributionClient.init(sdcConfig, this);
        if (!clientResult.getDistributionActionResult().equals(DistributionActionResultEnum.SUCCESS)) {
            LOGGER.error("SDC client initialization failed with reason: {}. Initialization will be retried after {} {}",
                clientResult.getDistributionMessageResult(), retryDelay, SECONDS);
            return;
        }
        LOGGER.debug("SDC Client is initialized successfully");
        changeSdcReceptionHandlerStatus(SdcReceptionHandlerStatus.INIT);
    }

    /**
     * Method to start the SDC client.
     */
    protected void startSdcClient() {

        LOGGER.debug("Going to start the SDC Client...");
        if (sdcReceptionHandlerStatus != SdcReceptionHandlerStatus.INIT) {
            LOGGER.error("The SDC Client is not initialized");
            return;
        }
        final IDistributionClientResult clientResult = distributionClient.start();
        if (!clientResult.getDistributionActionResult().equals(DistributionActionResultEnum.SUCCESS)) {
            LOGGER.error("SDC client start failed with reason: {}. Start will be retried after {} {}",
                clientResult.getDistributionMessageResult(), retryDelay, SECONDS);
            return;
        }
        LOGGER.debug("SDC Client is started successfully");
        changeSdcReceptionHandlerStatus(SdcReceptionHandlerStatus.IDLE);
        sdcClientHandler.cancel();
    }

    /**
     * Method to stop the SDC client.
     */
    protected void stopSdcClient() {
        LOGGER.debug("Going to stop the SDC Client...");
        final IDistributionClientResult clientResult = distributionClient.stop();
        if (!clientResult.getDistributionActionResult().equals(DistributionActionResultEnum.SUCCESS)) {
            LOGGER.error("SDC client stop failed with reason: {}. Stop will be retried after {} {}",
                clientResult.getDistributionMessageResult(), retryDelay, SECONDS);
            return;
        }
        LOGGER.debug("SDC Client is stopped successfully");
        changeSdcReceptionHandlerStatus(SdcReceptionHandlerStatus.STOPPED);
        sdcClientHandler.cancel();
    }

    /**
     * Method to process csar service artifacts from incoming SDC notification.
     *
     * @param notificationData the notification from SDC
     */
    public void processCsarServiceArtifacts(final INotificationData notificationData) {
        var artifactsProcessedSuccessfully = true;
        DistributionStatisticsManager.updateTotalDistributionCount();
        for (final IArtifactInfo artifact : notificationData.getServiceArtifacts()) {
            try {
                final IDistributionClientDownloadResult resultArtifact =
                    downloadTheArtifact(artifact, notificationData);
                final var filePath = writeArtifactToFile(artifact, resultArtifact);
                final var csarObject = new Csar(filePath.toString());
                inputReceived(csarObject);
                sendDistributionStatus(DistributionStatusType.DEPLOY, artifact.getArtifactURL(),
                    notificationData.getDistributionID(), DistributionStatusEnum.DEPLOY_OK, null);
                deleteArtifactFile(filePath);
            } catch (final ArtifactDownloadException | PolicyDecodingException exp) {
                LOGGER.error("Failed to process csar service artifacts ", exp);
                artifactsProcessedSuccessfully = false;
                sendDistributionStatus(DistributionStatusType.DEPLOY, artifact.getArtifactURL(),
                    notificationData.getDistributionID(), DistributionStatusEnum.DEPLOY_ERROR,
                    "Failed to deploy the artifact due to: " + exp.getMessage());
            }
        }

        // NoSonar here for complaining about var not changing, when, in fact,
        // can change to false when Exceptions are triggered.
        if (artifactsProcessedSuccessfully) { // NOSONAR
            DistributionStatisticsManager.updateDistributionSuccessCount();
            sendComponentDoneStatus(notificationData.getDistributionID(), DistributionStatusEnum.COMPONENT_DONE_OK,
                null);
        } else {
            DistributionStatisticsManager.updateDistributionFailureCount();
            sendComponentDoneStatus(notificationData.getDistributionID(), DistributionStatusEnum.COMPONENT_DONE_ERROR,
                "Failed to process the artifact");
        }
    }

    /**
     * Method to download the distribution artifact.
     *
     * @param artifact the artifact
     * @return the download result
     * @throws ArtifactDownloadException if download fails
     */
    private IDistributionClientDownloadResult downloadTheArtifact(final IArtifactInfo artifact,
                                                                  final INotificationData notificationData)
        throws ArtifactDownloadException {

        DistributionStatisticsManager.updateTotalDownloadCount();
        final IDistributionClientDownloadResult downloadResult = distributionClient.download(artifact);
        if (!downloadResult.getDistributionActionResult().equals(DistributionActionResultEnum.SUCCESS)) {
            DistributionStatisticsManager.updateDownloadFailureCount();
            final String message = "Failed to download artifact with name: " + artifact.getArtifactName() + " due to: "
                + downloadResult.getDistributionMessageResult();
            LOGGER.error(message);
            sendDistributionStatus(DistributionStatusType.DOWNLOAD, artifact.getArtifactURL(),
                notificationData.getDistributionID(), DistributionStatusEnum.DOWNLOAD_ERROR, message);
            throw new ArtifactDownloadException(message);
        }
        DistributionStatisticsManager.updateDownloadSuccessCount();
        sendDistributionStatus(DistributionStatusType.DOWNLOAD, artifact.getArtifactURL(),
            notificationData.getDistributionID(), DistributionStatusEnum.DOWNLOAD_OK, null);
        return downloadResult;
    }

    /**
     * Method to write the downloaded distribution artifact to local file system.
     *
     * @param artifact       the notification artifact
     * @param resultArtifact the download result artifact
     * @return the local path of written file
     * @throws ArtifactDownloadException if error occurs while writing the artifact
     */
    private Path writeArtifactToFile(final IArtifactInfo artifact,
                                     final IDistributionClientDownloadResult resultArtifact)
        throws ArtifactDownloadException {
        try {
            final byte[] payloadBytes = resultArtifact.getArtifactPayload();

            final var tempArtifactFile = Optional.ofNullable(safelyCreateFile(artifact.getArtifactName()))
                .orElseThrow(() -> new ArtifactDownloadException("Failed to create temporary file."));
            try (var fileOutputStream = new FileOutputStream(tempArtifactFile)) {
                fileOutputStream.write(payloadBytes, 0, payloadBytes.length);
                return tempArtifactFile.toPath();
            }
        } catch (final Exception exp) {
            throw new ArtifactDownloadException("Failed to write artifact to local repository", exp);
        }
    }

    /**
     * Method to delete the downloaded notification artifact from local file system.
     *
     * @param filePath the path of file
     */
    private void deleteArtifactFile(final Path filePath) {
        try {
            Files.deleteIfExists(filePath);
        } catch (final IOException exp) {
            LOGGER.error("Failed to delete the downloaded artifact file", exp);
        }
    }

    /**
     * Sends the distribution status to SDC using the input values.
     *
     * @param statusType     the status type
     * @param artifactUrl    the artifact url
     * @param distributionId the distribution id
     * @param status         the status
     * @param errorReason    the error reason
     */
    private void sendDistributionStatus(final DistributionStatusType statusType, final String artifactUrl,
                                        final String distributionId, final DistributionStatusEnum status,
                                        final String errorReason) {

        IDistributionClientResult clientResult;
        final IDistributionStatusMessage message = DistributionStatusMessage.builder().artifactUrl(artifactUrl)
            .consumerId(sdcConfig.getConsumerID()).distributionId(distributionId).distributionStatus(status)
            .timestamp(System.currentTimeMillis()).build();
        if (DistributionStatusType.DOWNLOAD.equals(statusType)) {
            if (errorReason != null) {
                clientResult = distributionClient.sendDownloadStatus(message, errorReason);
            } else {
                clientResult = distributionClient.sendDownloadStatus(message);
            }
        } else {
            if (errorReason != null) {
                clientResult = distributionClient.sendDeploymentStatus(message, errorReason);
            } else {
                clientResult = distributionClient.sendDeploymentStatus(message);
            }
        }
        final var loggerMessage = new StringBuilder();
        loggerMessage.append("distribution status to SDC with values - ").append("DistributionId")
            .append(distributionId).append(" Artifact: ").append(artifactUrl).append(" StatusType: ")
            .append(statusType.name()).append(" Status: ").append(status.name());
        if (errorReason != null) {
            loggerMessage.append(" ErrorReason: ").append(errorReason);
        }
        if (!clientResult.getDistributionActionResult().equals(DistributionActionResultEnum.SUCCESS)) {
            loggerMessage.insert(0, "Failed sending ");
            LOGGER.debug("Failed sending {}", loggerMessage);
        } else {
            loggerMessage.insert(0, "Successfully Sent ");
            LOGGER.debug("Successfully Sent {}", loggerMessage);
        }
    }

    /**
     * Sends the component done status to SDC using the input values.
     *
     * @param distributionId the distribution Id
     * @param status         the distribution status
     * @param errorReason    the error reason
     */
    private void sendComponentDoneStatus(final String distributionId, final DistributionStatusEnum status,
                                         final String errorReason) {
        IDistributionClientResult clientResult;
        final IComponentDoneStatusMessage message = ComponentDoneStatusMessage.builder()
            .consumerId(sdcConfig.getConsumerID()).distributionId(distributionId).distributionStatus(status)
            .timestamp(System.currentTimeMillis()).build();
        if (errorReason == null) {
            clientResult = distributionClient.sendComponentDoneStatus(message);
        } else {
            clientResult = distributionClient.sendComponentDoneStatus(message, errorReason);
        }

        final var loggerMessage = new StringBuilder();
        loggerMessage.append("component done status to SDC with values - ").append("DistributionId")
            .append(distributionId).append(" Status: ").append(status.name());
        if (errorReason != null) {
            loggerMessage.append(" ErrorReason: ").append(errorReason);
        }
        if (!clientResult.getDistributionActionResult().equals(DistributionActionResultEnum.SUCCESS)) {
            LOGGER.debug("Failed sending {}", loggerMessage);
        } else {
            LOGGER.debug("Successfully Sent {}", loggerMessage);
        }
    }

    /**
     * Handle the status change of {@link SdcReceptionHandler} to Idle.
     *
     * @param newStatus the new status
     */
    private void handleIdleStatusChange(final SdcReceptionHandlerStatus newStatus) {
        if (nbOfNotificationsOngoing.getAndUpdate(curval -> Math.max(0, curval - 1)) == 0) {
            sdcReceptionHandlerStatus = newStatus;
        }
    }

    private File safelyCreateFile(String prefix) throws IOException {
        File file = Files.createTempFile(prefix, ".csar").toFile(); // NOSONAR
        if (file.setReadable(true, false)
            && file.setWritable(true, true)) {
            return file;
        }
        return null;
    }
}