Change code to use dmaap microservice
[appc.git] / appc-sdc-listener / appc-sdc-listener-bundle / src / main / java / org / onap / appc / sdc / listener / SdcCallback.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP : APPC
4  * ================================================================================
5  * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Copyright (C) 2017 Amdocs
8  * =============================================================================
9  * Modifications Copyright (C) 2019 IBM
10  * =============================================================================
11  * Licensed under the Apache License, Version 2.0 (the "License");
12  * you may not use this file except in compliance with the License.
13  * You may obtain a copy of the License at
14  * 
15  *      http://www.apache.org/licenses/LICENSE-2.0
16  * 
17  * Unless required by applicable law or agreed to in writing, software
18  * distributed under the License is distributed on an "AS IS" BASIS,
19  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20  * See the License for the specific language governing permissions and
21  * limitations under the License.
22  * ============LICENSE_END=========================================================
23  */
24
25 package org.onap.appc.sdc.listener;
26
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
29 import org.onap.appc.srvcomm.messaging.event.EventSender;
30 import org.onap.appc.sdc.artifacts.ArtifactProcessor;
31 import org.onap.appc.sdc.artifacts.impl.ArtifactProcessorFactory;
32 import org.onap.sdc.api.IDistributionClient;
33 import org.onap.sdc.api.consumer.INotificationCallback;
34 import org.onap.sdc.api.notification.IArtifactInfo;
35 import org.onap.sdc.api.notification.INotificationData;
36 import org.onap.sdc.api.notification.IResourceInstance;
37 import org.apache.commons.lang3.concurrent.BasicThreadFactory;
38 import org.onap.sdc.utils.DistributionStatusEnum;
39 import org.osgi.framework.BundleContext;
40 import org.osgi.framework.FrameworkUtil;
41 import org.osgi.framework.ServiceReference;
42
43 import java.net.URI;
44 import java.util.concurrent.ArrayBlockingQueue;
45 import java.util.concurrent.ThreadPoolExecutor;
46 import java.util.concurrent.TimeUnit;
47 import java.util.concurrent.atomic.AtomicBoolean;
48
49 public class SdcCallback implements INotificationCallback {
50
51     private final EELFLogger logger = EELFManager.getInstance().getLogger(SdcCallback.class);
52     private ArtifactProcessorFactory artifactProcessorFactory = new ArtifactProcessorFactory();
53
54     private URI storeUri;
55     private IDistributionClient client;
56
57     private EventSender eventSender = null;
58
59     private ThreadPoolExecutor executor;
60     private int threadCount = 10;
61
62     private AtomicBoolean isRunning = new AtomicBoolean(false);
63
64
65     public SdcCallback(URI storeUri, IDistributionClient client) {
66         this.storeUri = storeUri;
67         this.client = client;
68
69         // Create the thread pool
70         executor = new ThreadPoolExecutor(threadCount, threadCount, 1, TimeUnit.SECONDS,
71             new ArrayBlockingQueue<Runnable>(threadCount * 2));
72
73         // Custom Named thread factory
74         BasicThreadFactory threadFactory = new BasicThreadFactory.Builder().namingPattern("Appc-Listener-%d").build();
75         executor.setThreadFactory(threadFactory);
76
77         isRunning.set(true);
78     }
79
80     @Override
81     public void activateCallback(INotificationData data) {
82         if (null == eventSender) {
83             try {
84                 BundleContext bctx = FrameworkUtil.getBundle(EventSender.class).getBundleContext();
85                 ServiceReference sref = bctx.getServiceReference(EventSender.class);
86                 eventSender = (EventSender) bctx.getService(sref);
87             } catch (Exception e) {
88                 logger.error("SdcCallback failed on initializing EventSender", e);
89             }
90         }
91
92         if (isRunning.get()) {
93
94             for(IArtifactInfo artifact:data.getServiceArtifacts()){
95                 ArtifactProcessor artifactProcessor = artifactProcessorFactory.getArtifactProcessor(
96                     client, eventSender, data, null, artifact, storeUri);
97                 if(artifactProcessor!=null){
98                     executor.submit(artifactProcessor);
99                 }
100             }
101
102             for (IResourceInstance resource : data.getResources()) {
103                 for (IArtifactInfo artifact : resource.getArtifacts()) {
104                     logger.info(Util.toSdcStoreDocumentInput(data, resource, artifact, "abc"));
105                     if (executor.getQueue().size() >= threadCount) {
106                         logger.warn(String.format("excuter queue size (%d) is exceeding thread count (%s).",
107                             executor.getQueue().size(), threadCount));
108                     }
109                     ArtifactProcessor artifactProcessor = artifactProcessorFactory.getArtifactProcessor(
110                         client, eventSender, data, resource, artifact, storeUri);
111                     if(artifactProcessor != null){
112                         executor.submit(artifactProcessor);
113                     }
114                     else{
115                         /* Before refactoring of the DownloadAndStoreOp class, the approach was to download all the
116                             artifacts, send the download status, and then perform the processing of artifact if it is
117                             required. Now that we are downloading the artifacts only when its processing is required,
118                             we are sending the download status as positive just to have the same behaviour as before
119                             refactoring.
120                          */
121                         client.sendDownloadStatus(Util.buildDistributionStatusMessage(
122                             client, data, artifact, DistributionStatusEnum.DOWNLOAD_OK));
123                         logger.error("Artifact type not supported : " + artifact.getArtifactType());
124                     }
125                 }
126             }
127         } else {
128             // TODO - return a failed result so sdc knows we are shut down
129         }
130     }
131
132     public void stop() {
133         stop(10);
134     }
135
136     public void stop(int waitSec) {
137         isRunning.set(false);
138         logger.info(String.format("Stopping the SDC listener and waiting up to %ds for %d pending jobs", waitSec,
139             executor.getQueue().size()));
140         boolean cleanShutdown = false;
141         executor.shutdown();
142         try {
143             cleanShutdown = executor.awaitTermination(waitSec, TimeUnit.SECONDS);
144             executor.shutdownNow(); // In case of timeout
145         } catch (InterruptedException e) {
146             logger.error("Error in SdcCallback for stop(int waitSec) method due to InterruptedException: reason= " + e.getMessage(), e);
147             Thread.currentThread().interrupt();
148         }
149         logger.info(String.format("Attempting to shutdown cleanly: %s", cleanShutdown ? "SUCCESS" : "FAILURE"));
150         logger.info("Shutdown complete.");
151     }
152
153 }