Sdc Listener Platform hardening changes
[appc.git] / appc-sdc-listener / appc-sdc-listener-bundle / src / main / java / org / onap / appc / sdc / listener / SdcListener.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  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  *
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  *
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.appc.sdc.listener;
24
25 import com.att.eelf.configuration.EELFLogger;
26 import com.att.eelf.configuration.EELFManager;
27 import org.onap.appc.configuration.Configuration;
28 import org.onap.appc.configuration.ConfigurationFactory;
29 import org.onap.sdc.api.IDistributionClient;
30 import org.onap.sdc.api.results.IDistributionClientResult;
31 import org.onap.sdc.impl.DistributionClientFactory;
32 import org.onap.sdc.utils.DistributionActionResultEnum;
33
34 import java.net.URL;
35 import java.util.HashMap;
36 import java.util.Map;
37 import java.util.Properties;
38 import java.util.concurrent.CountDownLatch;
39 import java.util.concurrent.TimeUnit;
40
41 /**
42  * SDC listener handles bundle start and stop through start and stop method. <p>
43  * Register connection with SDC server based on properties file configuration when start,
44  * and disconnect with SDC server when stop.
45  */
46 public class SdcListener {
47     private final EELFLogger logger = EELFManager.getInstance().getLogger(SdcListener.class);
48
49     /**
50      * The bundle context
51      */
52     private IDistributionClient client;
53     private SdcCallback callback;
54     private SdcConfig config;
55     private CountDownLatch latch;
56
57     private Thread startThread = null;
58     private String ukey;
59     private String uval;
60
61     @SuppressWarnings("unused")
62     public void start() throws Exception {
63         // Add timestamp to the log to differentiate the jmeter run testing calls.
64         final long timeStamp = System.currentTimeMillis();
65         logger.info(String.format("[%d] Starting SDC Listener", timeStamp));
66
67         Configuration configuration = ConfigurationFactory.getConfiguration();
68         Properties props = configuration.getProperties();
69         config = new SdcConfig(props);
70         ukey = props.getProperty("appc.sdc.provider.user");
71         uval = props.getProperty("appc.sdc.provider.pass");
72         logger.debug(String.format("[%d] created SDC config provider URL [%s]", timeStamp, config.getStoreOpURI().toString()));
73
74
75         client = DistributionClientFactory.createDistributionClient();
76         logger.debug(String.format("[%d] created SDC client", timeStamp));
77
78         callback = new SdcCallback(config.getStoreOpURI(), client);
79         logger.debug(String.format("[%d] created SDC callback", timeStamp));
80
81         latch = new CountDownLatch(1);
82
83         startThread = new Thread(new StartRunnable(timeStamp));
84         startThread.setName(String.format("[%d] sdcListener start", timeStamp));
85         logger.debug(String.format("[%d] created SDC initialization thread", timeStamp));
86         startThread.start();
87     }
88
89     @SuppressWarnings("unused")
90     public void stop() throws InterruptedException {
91         // Add timestamp to the log to differentiate the jmeter run testing calls.
92         final long timeStamp = System.currentTimeMillis();
93         logger.info(String.format("[%d] Stopping SDC Listener", timeStamp));
94
95         stopStartThread(timeStamp);
96
97         if (latch != null) {
98             logger.debug(String.format("[%d] waiting SDC latch count to 0 for 10 seconds", timeStamp));
99             latch.await(10, TimeUnit.SECONDS);
100             latch = null;
101         }
102
103         if (callback != null) {
104             logger.debug(String.format("[%d] stopping SDC callback", timeStamp));
105             callback.stop();
106             callback = null;
107         }
108         if (client != null) {
109             logger.debug(String.format("[%d] stopping SDC client", timeStamp));
110             client.stop();
111             client = null;
112
113         }
114         logger.info(String.format("[%d] SDC Listener stopped successfully", timeStamp));
115     }
116
117     void stopStartThread(long timeStamp) throws InterruptedException {
118         if (startThread == null) {
119             return;
120         }
121
122         if (startThread.getState() == Thread.State.TERMINATED) {
123             logger.debug(String.format("[%d] SDC thread(%s) is already terminated.",
124                     timeStamp, startThread.getName()));
125         } else {
126             logger.debug(String.format("[%d] SDC thread(%s) is to be interrupted with state(%s)",
127                     timeStamp, startThread.getName(), startThread.getState().toString()));
128
129             startThread.interrupt();
130
131             logger.debug(String.format("[%d] SDC thread(%s) has been interrupted(%s) with state(%s)",
132                     timeStamp, startThread.getName(), startThread.isInterrupted(),
133                     startThread.getState().toString()));
134         }
135         startThread = null;
136     }
137
138     /**
139      * Runnable implementation for actual initialization during SDC listener start
140      */
141     class StartRunnable implements Runnable {
142         private final long timeStamp;
143
144         StartRunnable(long theTimeStamp) {
145             timeStamp = theTimeStamp;
146         }
147
148         /**
149          * This run method calls SDC client for init and start which are synchronized calls along with stop.
150          * To interrupt this thread at stop time, we added thread interrupted checking in each step
151          * for earlier interruption.
152          */
153         @Override
154         public void run() {
155             if (!initialRegistration()) {
156                 logger.warn(String.format("[%d] SDC thread initial registration failed.", timeStamp));
157             }
158
159             if (isThreadInterrupted("after initial registration")) {
160                 return;
161             }
162
163             IDistributionClientResult result = client.init(config, callback);
164
165             if (isThreadInterrupted("after client init")) {
166                 return;
167             }
168
169             if (result.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS) {
170                 client.start();
171             } else {
172                 logger.error(String.format("[%d] Could not register SDC client. %s - %s",
173                         timeStamp, result.getDistributionActionResult(), result.getDistributionMessageResult()));
174             }
175
176             latch.countDown();
177         }
178
179         private boolean initialRegistration() {
180             try {
181                 final String jsonTemplate =
182                         "{\"consumerName\": \"%s\",\"consumerSalt\": \"%s\",\"consumerPassword\":\"%s\"}";
183                 String saltedPassStr = org.onap.tlv.sdc.security.Passwords.hashPassword(config.getPassword());
184                 if (saltedPassStr == null || !saltedPassStr.contains(":")) {
185                     return false;
186                 }
187
188                 String[] saltedPass = saltedPassStr.split(":");
189                 String json = String.format(jsonTemplate, config.getUser(), saltedPass[0], saltedPass[1]);
190
191                 Map<String, String> headers = new HashMap<>();
192                 // TODO - Replace the header below to sdc's requirements. What should the new value be
193                 headers.put("USER_ID", "test");
194
195                 // TODO - How to format the url. Always same endpoint or ports?
196                 String host = config.getAsdcAddress();
197                 URL url = new URL(String.format("http%s://%s/sdc2/rest/v1/consumers",
198                         host.contains("443") ? "s" : "", host));
199
200                 logger.info(String.format("Attempting to register user %s on %s with salted pass of %s",
201                         config.getUser(), url, saltedPass[1]));
202
203                 ProviderOperations providerOperations = new ProviderOperations();
204                 ProviderOperations.setDefaultUrl(config.getStoreOpURI().toURL());
205                 ProviderOperations.setAuthentication(ukey, uval);
206                 ProviderResponse result = providerOperations.post(url, json, headers);
207                 return result.getStatus() == 200;
208             } catch (Exception e) {
209                 logger.error(
210                         "Error performing initial registration with SDC server. User may not be able to connect",
211                         e);
212                 return false;
213             }
214         }
215
216         private boolean isThreadInterrupted(String details) {
217             if (Thread.currentThread().isInterrupted()) {
218                 logger.info(String.format("[%d] SDC thread interrupted %s.", timeStamp, details));
219                 return true;
220             }
221             return false;
222         }
223     }
224 }