2 * ============LICENSE_START=======================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
23 package org.onap.appc.sdc.listener;
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;
35 import java.util.HashMap;
37 import java.util.Properties;
38 import java.util.concurrent.CountDownLatch;
39 import java.util.concurrent.TimeUnit;
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.
46 public class SdcListener {
47 private final EELFLogger logger = EELFManager.getInstance().getLogger(SdcListener.class);
52 private IDistributionClient client;
53 private SdcCallback callback;
54 private SdcConfig config;
55 private CountDownLatch latch;
57 private Thread startThread = null;
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));
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()));
75 client = DistributionClientFactory.createDistributionClient();
76 logger.debug(String.format("[%d] created SDC client", timeStamp));
78 callback = new SdcCallback(config.getStoreOpURI(), client);
79 logger.debug(String.format("[%d] created SDC callback", timeStamp));
81 latch = new CountDownLatch(1);
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));
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));
95 stopStartThread(timeStamp);
98 logger.debug(String.format("[%d] waiting SDC latch count to 0 for 10 seconds", timeStamp));
99 latch.await(10, TimeUnit.SECONDS);
103 if (callback != null) {
104 logger.debug(String.format("[%d] stopping SDC callback", timeStamp));
108 if (client != null) {
109 logger.debug(String.format("[%d] stopping SDC client", timeStamp));
114 logger.info(String.format("[%d] SDC Listener stopped successfully", timeStamp));
117 void stopStartThread(long timeStamp) throws InterruptedException {
118 if (startThread == null) {
122 if (startThread.getState() == Thread.State.TERMINATED) {
123 logger.debug(String.format("[%d] SDC thread(%s) is already terminated.",
124 timeStamp, startThread.getName()));
126 logger.debug(String.format("[%d] SDC thread(%s) is to be interrupted with state(%s)",
127 timeStamp, startThread.getName(), startThread.getState().toString()));
129 startThread.interrupt();
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()));
139 * Runnable implementation for actual initialization during SDC listener start
141 class StartRunnable implements Runnable {
142 private final long timeStamp;
144 StartRunnable(long theTimeStamp) {
145 timeStamp = theTimeStamp;
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.
155 if (!initialRegistration()) {
156 logger.warn(String.format("[%d] SDC thread initial registration failed.", timeStamp));
159 if (isThreadInterrupted("after initial registration")) {
163 IDistributionClientResult result = client.init(config, callback);
165 if (isThreadInterrupted("after client init")) {
169 if (result.getDistributionActionResult() == DistributionActionResultEnum.SUCCESS) {
172 logger.error(String.format("[%d] Could not register SDC client. %s - %s",
173 timeStamp, result.getDistributionActionResult(), result.getDistributionMessageResult()));
179 private boolean initialRegistration() {
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(":")) {
188 String[] saltedPass = saltedPassStr.split(":");
189 String json = String.format(jsonTemplate, config.getUser(), saltedPass[0], saltedPass[1]);
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");
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));
200 logger.info(String.format("Attempting to register user %s on %s with salted pass of %s",
201 config.getUser(), url, saltedPass[1]));
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) {
210 "Error performing initial registration with SDC server. User may not be able to connect",
216 private boolean isThreadInterrupted(String details) {
217 if (Thread.currentThread().isInterrupted()) {
218 logger.info(String.format("[%d] SDC thread interrupted %s.", timeStamp, details));