aboutsummaryrefslogtreecommitdiffstats
path: root/feature-server-pool/src/main/java/org/onap/policy/drools/serverpool/Discovery.java
blob: 2d643a342864252a07db9dde66dfea3d0db637b7 (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
/*
 * ============LICENSE_START=======================================================
 * feature-server-pool
 * ================================================================================
 * Copyright (C) 2020 AT&T Intellectual Property. 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.
 * ============LICENSE_END=========================================================
 */

package org.onap.policy.drools.serverpool;

import static org.onap.policy.drools.serverpool.ServerPoolProperties.DEFAULT_DISCOVERY_FETCH_LIMIT;
import static org.onap.policy.drools.serverpool.ServerPoolProperties.DEFAULT_DISCOVERY_FETCH_TIMEOUT;
import static org.onap.policy.drools.serverpool.ServerPoolProperties.DEFAULT_DISCOVER_PUBLISHER_LOOP_CYCLE_TIME;
import static org.onap.policy.drools.serverpool.ServerPoolProperties.DISCOVERY_ALLOW_SELF_SIGNED_CERTIFICATES;
import static org.onap.policy.drools.serverpool.ServerPoolProperties.DISCOVERY_API_KEY;
import static org.onap.policy.drools.serverpool.ServerPoolProperties.DISCOVERY_API_SECRET;
import static org.onap.policy.drools.serverpool.ServerPoolProperties.DISCOVERY_FETCH_LIMIT;
import static org.onap.policy.drools.serverpool.ServerPoolProperties.DISCOVERY_FETCH_TIMEOUT;
import static org.onap.policy.drools.serverpool.ServerPoolProperties.DISCOVERY_HTTPS;
import static org.onap.policy.drools.serverpool.ServerPoolProperties.DISCOVERY_PASSWORD;
import static org.onap.policy.drools.serverpool.ServerPoolProperties.DISCOVERY_SERVERS;
import static org.onap.policy.drools.serverpool.ServerPoolProperties.DISCOVERY_TOPIC;
import static org.onap.policy.drools.serverpool.ServerPoolProperties.DISCOVERY_USERNAME;
import static org.onap.policy.drools.serverpool.ServerPoolProperties.DISCOVER_PUBLISHER_LOOP_CYCLE_TIME;
import static org.onap.policy.drools.serverpool.ServerPoolProperties.getProperty;

import com.google.gson.Gson;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import org.onap.policy.common.endpoints.event.comm.Topic.CommInfrastructure;
import org.onap.policy.common.endpoints.event.comm.TopicEndpointManager;
import org.onap.policy.common.endpoints.event.comm.TopicListener;
import org.onap.policy.common.endpoints.event.comm.TopicSink;
import org.onap.policy.common.endpoints.event.comm.TopicSource;
import org.onap.policy.common.endpoints.properties.PolicyEndPointProperties;
import org.onap.policy.common.utils.coder.CoderException;
import org.onap.policy.common.utils.coder.StandardCoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * This class makes use of UEB/DMAAP to discover other servers in the pool.
 * The discovery processes ordinarily run only on the lead server, but they
 * run on other servers up until the point that they determine who the
 * leader is.
 */
public class Discovery implements TopicListener {
    private static Logger logger = LoggerFactory.getLogger(Discovery.class);

    // used for JSON <-> String conversion
    private static StandardCoder coder = new StandardCoder();

    private static Discovery discovery = null;

    private volatile Publisher publisherThread = null;

    private List<TopicSource> consumers = null;
    private List<TopicSink> publishers = null;

    private Discovery() {
        // we want to modify the properties we send to 'TopicManager'
        PropBuilder builder = new PropBuilder(ServerPoolProperties.getProperties());
        builder.convert(DISCOVERY_SERVERS, null,
                        PolicyEndPointProperties.PROPERTY_TOPIC_SERVERS_SUFFIX);
        builder.convert(DISCOVERY_USERNAME, null,
                        PolicyEndPointProperties.PROPERTY_TOPIC_AAF_MECHID_SUFFIX);
        builder.convert(DISCOVERY_PASSWORD, null,
                        PolicyEndPointProperties.PROPERTY_TOPIC_AAF_PASSWORD_SUFFIX);
        builder.convert(DISCOVERY_HTTPS, null,
                        PolicyEndPointProperties.PROPERTY_HTTP_HTTPS_SUFFIX);
        builder.convert(DISCOVERY_API_KEY, null,
                        PolicyEndPointProperties.PROPERTY_TOPIC_API_KEY_SUFFIX);
        builder.convert(DISCOVERY_API_SECRET, null,
                        PolicyEndPointProperties.PROPERTY_TOPIC_API_SECRET_SUFFIX);
        builder.convert(DISCOVERY_FETCH_TIMEOUT,
                        String.valueOf(DEFAULT_DISCOVERY_FETCH_TIMEOUT),
                        PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_FETCH_TIMEOUT_SUFFIX);
        builder.convert(DISCOVERY_FETCH_LIMIT,
                        String.valueOf(DEFAULT_DISCOVERY_FETCH_LIMIT),
                        PolicyEndPointProperties.PROPERTY_TOPIC_SOURCE_FETCH_LIMIT_SUFFIX);
        builder.convert(DISCOVERY_ALLOW_SELF_SIGNED_CERTIFICATES, null,
                        PolicyEndPointProperties.PROPERTY_ALLOW_SELF_SIGNED_CERTIFICATES_SUFFIX);
        Properties prop = builder.finish();
        logger.debug("Discovery converted properties: {}", prop);

        consumers = TopicEndpointManager.getManager().addTopicSources(prop);
        publishers = TopicEndpointManager.getManager().addTopicSinks(prop);

        if (consumers.isEmpty()) {
            logger.error("No consumer topics");
        }
        if (publishers.isEmpty()) {
            logger.error("No publisher topics");
        }
        logger.debug("Discovery: {} consumers, {} publishers",
                     consumers.size(), publishers.size());
    }

    /**
     * Start all consumers and publishers, and start the publisher thread.
     */
    static synchronized void startDiscovery() {
        if (discovery == null) {
            discovery = new Discovery();
        }
        discovery.start();
    }

    /**
     * Stop all consumers and publishers, and stop the publisher thread.
     */
    static synchronized void stopDiscovery() {
        if (discovery != null) {
            discovery.stop();
        }
    }

    /**
     * Start all consumers and publishers, and start the publisher thread.
     */
    private void start() {
        for (TopicSource consumer : consumers) {
            consumer.register(this);
            consumer.start();
        }
        for (TopicSink publisher : publishers) {
            publisher.start();
        }
        if (publisherThread == null) {
            // send thread wasn't running -- start it
            publisherThread = new Publisher();
            publisherThread.start();
        }
    }

    /**
     * Stop all consumers and publishers, and stop the publisher thread.
     */
    private void stop() {
        publisherThread = null;
        for (TopicSink publisher : publishers) {
            publisher.stop();
        }
        for (TopicSource consumer : consumers) {
            consumer.unregister(this);
            consumer.stop();
        }
    }

    /*===========================*/
    /* 'TopicListener' interface */
    /*===========================*/

    /**
     * {@inheritDoc}
     */
    @Override
    public void onTopicEvent(CommInfrastructure infra, String topic, String event) {
        /*
         * a JSON message has been received -- it should contain
         * a single string parameter 'pingData', which contains the
         * same format base64-encoded message that 'Server'
         * instances periodically exchange
         */
        LinkedHashMap<String, String> map = new LinkedHashMap<>();
        try {
            map = coder.decode(event, LinkedHashMap.class);
            String message = map.get("pingData");
            Server.adminRequest(message.getBytes(StandardCharsets.UTF_8));
            logger.info("Received a message, server count={}", Server.getServerCount());
        } catch (CoderException e) {
            logger.error("Can't decode message: {}", e);
        }
    }

    /* ============================================================ */

    /**
     * This class is used to convert internal 'discovery.*' properties to
     * properties that 'TopicEndpointManager' can use.
     */
    private static class PropBuilder {
        // properties being incrementally modified
        Properties prop;

        // value from 'discovery.topic' parameter
        String topic;

        // 'true' only if both 'discovery.topic' and 'discovery.servers'
        // has been defined
        boolean doConversion = false;

        // contains "ueb.source.topics" or "dmaap.source.topics"
        String sourceTopicsName = null;

        // contains "<TYPE>.source.topics.<TOPIC>" (<TYPE> = ueb|dmaap)
        String sourcePrefix = null;

        // contains "ueb.sink.topics" or "dmaap.sink.topics"
        String sinkTopicsName = null;

        // contains "<TYPE>.sink.topics.<TOPIC>" (<TYPE> = ueb|dmaap)
        String sinkPrefix = null;

        /**
         * Constructor - decide whether we are going to do conversion or not,
         * and initialize accordingly.
         *
         * @param prop the initial list of properties
         */
        PropBuilder(Properties prop) {
            this.prop = new Properties(prop);
            this.topic = prop.getProperty(DISCOVERY_TOPIC);
            String servers = prop.getProperty(DISCOVERY_SERVERS);
            if (topic != null && servers != null) {
                // we do have property conversion to do
                doConversion = true;
                String type = topic.contains(".") ? "dmaap" : "ueb";
                sourceTopicsName = type + ".source.topics";
                sourcePrefix = sourceTopicsName + "." + topic;
                sinkTopicsName = type + ".sink.topics";
                sinkPrefix = sinkTopicsName + "." + topic;
            }
        }

        /**
         * If we are doing conversion, convert an internal property
         * to something that 'TopicEndpointManager' can use.
         *
         * @param intName server pool property name (e.g. "discovery.servers")
         * @param defaultValue value to use if property 'intName' is not specified
         * @param extSuffix TopicEndpointManager suffix, including leading "."
         */
        void convert(String intName, String defaultValue, String extSuffix) {
            if (doConversion) {
                String value = prop.getProperty(intName, defaultValue);
                if (value != null) {
                    prop.setProperty(sourcePrefix + extSuffix, value);
                    prop.setProperty(sinkPrefix + extSuffix, value);
                }
            }
        }

        /**
         * Generate/update the '*.source.topics' and '*.sink.topics' parameters.
         *
         * @return the updated properties list
         */
        Properties finish() {
            if (doConversion) {
                String currentValue = prop.getProperty(sourceTopicsName);
                if (currentValue == null) {
                    // '*.source.topics' is not defined -- set it
                    prop.setProperty(sourceTopicsName, topic);
                } else {
                    // '*.source.topics' is defined -- append to it
                    prop.setProperty(sourceTopicsName, currentValue + "," + topic);
                }
                currentValue = prop.getProperty(sinkTopicsName);
                if (currentValue == null) {
                    // '*.sink.topics' is not defined -- set it
                    prop.setProperty(sinkTopicsName, topic);
                } else {
                    // '*.sink.topics' is defined -- append to it
                    prop.setProperty(sinkTopicsName, currentValue + "," + topic);
                }
            }
            return prop;
        }
    }

    /* ============================================================ */

    /**
     * This is the sender thread, which periodically sends out 'ping' messages.
     */
    private class Publisher extends Thread {
        /**
         * Constructor -- read in the properties, and initialze 'publisher'.
         */
        Publisher() {
            super("Discovery Publisher Thread");
        }

        /**
         * {@inheritDoc}
         */
        @Override
        public void run() {
            // this loop will terminate once 'publisher' is set to 'null',
            // or some other 'Publisher' instance replaces it
            long cycleTime = getProperty(DISCOVER_PUBLISHER_LOOP_CYCLE_TIME,
                                         DEFAULT_DISCOVER_PUBLISHER_LOOP_CYCLE_TIME);
            while (this == publisherThread) {
                try {
                    // wait 5 seconds (default)
                    Thread.sleep(cycleTime);

                    // generate a 'ping' message
                    ByteArrayOutputStream bos = new ByteArrayOutputStream();
                    DataOutputStream dos = new DataOutputStream(bos);

                    // write the 'ping' data for this server
                    Server thisServer = Server.getThisServer();
                    thisServer.writeServerData(dos);
                    String encodedData =
                        new String(Base64.getEncoder().encode(bos.toByteArray()));

                    // base64-encoded value is passed as JSON parameter 'pingData'
                    LinkedHashMap<String, String> map = new LinkedHashMap<>();
                    map.put("pingData", encodedData);
                    String jsonString = new Gson().toJson(map, Map.class);
                    for (TopicSink publisher : publishers) {
                        publisher.send(jsonString);
                    }
                } catch (InterruptedException e) {
                    logger.error("Exception in Discovery.Publisher.run():", e);
                    return;
                } catch (Exception e) {
                    logger.error("Exception in Discovery.Publisher.run():", e);
                    // grace period -- we don't want to get UEB upset at us
                    try {
                        Thread.sleep(15000);
                    } catch (InterruptedException e2) {
                        logger.error("Discovery.Publisher sleep interrupted");
                    }
                    return;
                }
            }
        }
    }
}