Update for OOM integration
[dmaap/datarouter.git] / datarouter-prov / src / main / java / org / onap / dmaap / datarouter / provisioning / Poker.java
1 /*******************************************************************************
2  * ============LICENSE_START==================================================
3  * * org.onap.dmaap
4  * * ===========================================================================
5  * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
6  * * ===========================================================================
7  * * Licensed under the Apache License, Version 2.0 (the "License");
8  * * you may not use this file except in compliance with the License.
9  * * You may obtain a copy of the License at
10  * *
11  *  *      http://www.apache.org/licenses/LICENSE-2.0
12  * *
13  *  * Unless required by applicable law or agreed to in writing, software
14  * * distributed under the License is distributed on an "AS IS" BASIS,
15  * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * * See the License for the specific language governing permissions and
17  * * limitations under the License.
18  * * ============LICENSE_END====================================================
19  * *
20  * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
21  * *
22  ******************************************************************************/
23
24 package org.onap.dmaap.datarouter.provisioning;
25
26 import java.io.IOException;
27 import java.net.HttpURLConnection;
28 import java.net.InetAddress;
29 import java.net.MalformedURLException;
30 import java.net.URL;
31 import java.net.UnknownHostException;
32 import java.util.Arrays;
33 import java.util.HashSet;
34 import java.util.Map;
35 import java.util.Set;
36 import java.util.Timer;
37 import java.util.TimerTask;
38 import java.util.TreeSet;
39
40 import org.apache.log4j.Logger;
41 import org.json.JSONException;
42 import org.json.JSONObject;
43 import org.json.JSONTokener;
44 import org.onap.dmaap.datarouter.provisioning.beans.EgressRoute;
45 import org.onap.dmaap.datarouter.provisioning.beans.Feed;
46 import org.onap.dmaap.datarouter.provisioning.beans.Group;
47 import org.onap.dmaap.datarouter.provisioning.beans.IngressRoute;
48 import org.onap.dmaap.datarouter.provisioning.beans.NetworkRoute;
49 import org.onap.dmaap.datarouter.provisioning.beans.Parameters;
50 import org.onap.dmaap.datarouter.provisioning.beans.Subscription;
51 import org.onap.dmaap.datarouter.provisioning.utils.*;
52
53 /**
54  * This class handles the two timers (described in R1 Design Notes), and takes care of issuing the GET to each node of
55  * the URL to "poke".
56  *
57  * @author Robert Eby
58  * @version $Id: Poker.java,v 1.11 2014/01/08 16:13:47 eby Exp $
59  */
60 public class Poker extends TimerTask {
61
62     /**
63      * Template used to generate the URL to issue the GET against
64      */
65     private static final String POKE_URL_TEMPLATE = "http://%s/internal/fetchProv";
66
67     /**
68      * This is a singleton -- there is only one Poker object in the server
69      */
70     private static Poker poker;
71
72     /**
73      * Get the singleton Poker object.
74      *
75      * @return the Poker
76      */
77     public static synchronized Poker getPoker() {
78         if (poker == null) {
79             poker = new Poker();
80         }
81         return poker;
82     }
83
84     private long timer1;
85     private long timer2;
86     private String thisPod;        // DNS name of this machine
87     private Logger logger;
88     private String provString;
89
90     private Poker() {
91         timer1 = timer2 = 0;
92         Timer rolex = new Timer();
93         logger = Logger.getLogger("org.onap.dmaap.datarouter.provisioning.internal");
94         try {
95             thisPod = InetAddress.getLocalHost().getHostName();
96         } catch (UnknownHostException e) {
97             thisPod = "*UNKNOWN*";    // not a major problem
98         }
99         provString = buildProvisioningString();
100
101         rolex.scheduleAtFixedRate(this, 0L, 1000L);    // Run once a second to check the timers
102     }
103
104     /**
105      * This method sets the two timers described in the design notes.
106      *
107      * @param t1 the first timer controls how long to wait after a provisioning request before poking each node This
108      * timer can be reset if it has not "gone off".
109      * @param t2 the second timer set the outer bound on how long to wait.  It cannot be reset.
110      */
111     public void setTimers(long t1, long t2) {
112         synchronized (thisPod) {
113             if (timer1 == 0 || t1 > timer1) {
114                 timer1 = t1;
115             }
116             if (timer2 == 0) {
117                 timer2 = t2;
118             }
119         }
120         if (logger.isDebugEnabled()) {
121             logger.debug("Poker timers set to " + timer1 + " and " + timer2);
122         }
123
124
125     }
126
127     /**
128      * Return the last provisioning string built.
129      *
130      * @return the last provisioning string built.
131      */
132     public String getProvisioningString() {
133         return provString;
134     }
135
136     /**
137      * The method to run at the predefined interval (once per second).  This method checks to see if either of the two
138      * timers has expired, and if so, will rebuild the provisioning string, and poke all the nodes and other PODs.  The
139      * timers are then reset to 0.
140      */
141     @Override
142     public void run() {
143         try {
144             if (timer1 > 0) {
145                 long now = System.currentTimeMillis();
146                 boolean fire = false;
147                 synchronized (thisPod) {
148                     if (now > timer1 || now > timer2) {
149                         timer1 = timer2 = 0;
150                         fire = true;
151                     }
152                 }
153                 if (fire) {
154                     pokeNodes();
155                 }
156             }
157         } catch (Exception e) {
158             logger.warn("PROV0020: Caught exception in Poker: " + e);
159             e.printStackTrace();
160         }
161     }
162
163     private void pokeNodes() {
164         // Rebuild the prov string
165         provString = buildProvisioningString();
166         // Only the active POD should poke nodes, etc.
167         boolean active = SynchronizerTask.getSynchronizer().isActive();
168         if (active) {
169             // Poke all the DR nodes
170             for (String n : BaseServlet.getNodes()) {
171                 pokeNode(n);
172             }
173             // Poke the pod that is not us
174             for (String n : BaseServlet.getPods()) {
175                 if (n.length() > 0 && !n.equals(thisPod)) {
176                     pokeNode(n);
177                 }
178             }
179         }
180     }
181
182     private void pokeNode(final String nodename) {
183         logger.debug("PROV0012 Poking node " + nodename + " ...");
184         String nodeUrl = String.format(POKE_URL_TEMPLATE, nodename + ":" + DB.HTTP_PORT);
185         Runnable r = () -> {
186             try {
187                 URL url = new URL(nodeUrl);
188                 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
189                 conn.setConnectTimeout(60000);    //Fixes for Itrack DATARTR-3, poke timeout
190                 conn.connect();
191                 conn.getContentLength();    // Force the GET through
192                 conn.disconnect();
193             } catch (MalformedURLException e) {
194                 logger.warn("PROV0013 MalformedURLException Error poking node at " + nodeUrl + " : " + e.getMessage());
195             } catch (IOException e) {
196                 logger.warn("PROV0013 IOException Error poking node at " + nodeUrl + " : " + e.getMessage());
197             }
198         };
199         r.run();
200     }
201
202     private String buildProvisioningString() {
203         StringBuilder sb = new StringBuilder("{\n");
204
205         // Append Feeds to the string
206         String pfx = "\n";
207         sb.append("\"feeds\": [");
208         for (Feed f : Feed.getAllFeeds()) {
209             sb.append(pfx);
210             sb.append(f.asJSONObject().toString());
211             pfx = ",\n";
212         }
213         sb.append("\n],\n");
214
215         //Append groups to the string - Rally:US708115  - 1610
216         pfx = "\n";
217         sb.append("\"groups\": [");
218         for (Group s : Group.getAllgroups()) {
219             sb.append(pfx);
220             sb.append(s.asJSONObject().toString());
221             pfx = ",\n";
222         }
223         sb.append("\n],\n");
224
225         // Append Subscriptions to the string
226         pfx = "\n";
227         sb.append("\"subscriptions\": [");
228         for (Subscription s : Subscription.getAllSubscriptions()) {
229             sb.append(pfx);
230             if (s != null) {
231                 sb.append(s.asJSONObject().toString());
232             }
233             pfx = ",\n";
234         }
235         sb.append("\n],\n");
236
237         // Append Parameters to the string
238         pfx = "\n";
239         sb.append("\"parameters\": {");
240         Map<String, String> props = Parameters.getParameters();
241         Set<String> ivals = new HashSet<String>();
242         String intv = props.get("_INT_VALUES");
243         if (intv != null) {
244             ivals.addAll(Arrays.asList(intv.split("\\|")));
245         }
246         for (String key : new TreeSet<String>(props.keySet())) {
247             String v = props.get(key);
248             sb.append(pfx);
249             sb.append("  \"").append(key).append("\": ");
250             if (ivals.contains(key)) {
251                 // integer value
252                 sb.append(v);
253             } else if (key.endsWith("S")) {
254                 // Split and append array of strings
255                 String[] pp = v.split("\\|");
256                 String p2 = "";
257                 sb.append("[");
258                 for (String t : pp) {
259                     sb.append(p2).append("\"").append(quote(t)).append("\"");
260                     p2 = ",";
261                 }
262                 sb.append("]");
263             } else {
264                 sb.append("\"").append(quote(v)).append("\"");
265             }
266             pfx = ",\n";
267         }
268         sb.append("\n},\n");
269
270         // Append Routes to the string
271         pfx = "\n";
272         sb.append("\"ingress\": [");
273         for (IngressRoute in : IngressRoute.getAllIngressRoutes()) {
274             sb.append(pfx);
275             sb.append(in.asJSONObject().toString());
276             pfx = ",\n";
277         }
278         sb.append("\n],\n");
279
280         pfx = "\n";
281         sb.append("\"egress\": {");
282         for (EgressRoute eg : EgressRoute.getAllEgressRoutes()) {
283             sb.append(pfx);
284             String t = eg.asJSONObject().toString();
285             t = t.substring(1, t.length() - 1);
286             sb.append(t);
287             pfx = ",\n";
288         }
289         sb.append("\n},\n");
290
291         pfx = "\n";
292         sb.append("\"routing\": [");
293         for (NetworkRoute ne : NetworkRoute.getAllNetworkRoutes()) {
294             sb.append(pfx);
295             sb.append(ne.asJSONObject().toString());
296             pfx = ",\n";
297         }
298         sb.append("\n]");
299         sb.append("\n}");
300
301         // Convert to string and verify it is valid JSON
302         String tempProvString = sb.toString();
303         try {
304             new JSONObject(new JSONTokener(tempProvString));
305         } catch (JSONException e) {
306             logger.warn("PROV0016: Possible invalid prov string: " + e);
307         }
308         return tempProvString;
309     }
310
311     private String quote(String s) {
312         StringBuilder sb = new StringBuilder();
313         for (char ch : s.toCharArray()) {
314             if (ch == '\\' || ch == '"') {
315                 sb.append('\\');
316             }
317             sb.append(ch);
318         }
319         return sb.toString();
320     }
321 }