datarouter-node clean code - remove tabs
[dmaap/datarouter.git] / datarouter-node / src / main / java / org / onap / dmaap / datarouter / node / NodeConfigManager.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
25 package org.onap.dmaap.datarouter.node;
26
27 import java.net.*;
28 import java.util.*;
29 import java.io.*;
30
31 import org.apache.log4j.Logger;
32 import org.onap.dmaap.datarouter.node.eelf.EelfMsgs;
33
34 import com.att.eelf.configuration.EELFLogger;
35 import com.att.eelf.configuration.EELFManager;
36
37
38 /**
39  * Maintain the configuration of a Data Router node
40  * <p>
41  * The NodeConfigManager is the single point of contact for servlet, delivery, event logging, and log retention subsystems to access configuration information.  (Log4J has its own configuration mechanism).
42  * <p>
43  * There are two basic sets of configuration data.  The
44  * static local configuration data, stored in a local configuration file (created
45  * as part of installation by SWM), and the dynamic global
46  * configuration data fetched from the data router provisioning server.
47  */
48 public class NodeConfigManager implements DeliveryQueueHelper {
49     private static EELFLogger eelflogger = EELFManager.getInstance().getLogger("org.onap.dmaap.datarouter.node.NodeConfigManager");
50     private static Logger logger = Logger.getLogger("org.onap.dmaap.datarouter.node.NodeConfigManager");
51     private static NodeConfigManager base = new NodeConfigManager();
52
53     private Timer timer = new Timer("Node Configuration Timer", true);
54     private long maxfailuretimer;
55     private long initfailuretimer;
56     private long expirationtimer;
57     private double failurebackoff;
58     private long fairtimelimit;
59     private int fairfilelimit;
60     private double fdpstart;
61     private double fdpstop;
62     private int deliverythreads;
63     private String provurl;
64     private String provhost;
65     private IsFrom provcheck;
66     private int gfport;
67     private int svcport;
68     private int port;
69     private String spooldir;
70     private String logdir;
71     private long logretention;
72     private String redirfile;
73     private String kstype;
74     private String ksfile;
75     private String kspass;
76     private String kpass;
77     private String tstype;
78     private String tsfile;
79     private String tspass;
80     private String myname;
81     private RedirManager rdmgr;
82     private RateLimitedOperation pfetcher;
83     private NodeConfig config;
84     private File quiesce;
85     private PublishId pid;
86     private String nak;
87     private TaskList configtasks = new TaskList();
88     private String eventlogurl;
89     private String eventlogprefix;
90     private String eventlogsuffix;
91     private String eventloginterval;
92     private boolean followredirects;
93
94
95     /**
96      * Get the default node configuration manager
97      */
98     public static NodeConfigManager getInstance() {
99         return (base);
100     }
101
102     /**
103      * Initialize the configuration of a Data Router node
104      */
105     private NodeConfigManager() {
106         Properties p = new Properties();
107         try {
108             p.load(new FileInputStream(System.getProperty("org.onap.dmaap.datarouter.node.ConfigFile", "/opt/app/datartr/etc/node.properties")));
109         } catch (Exception e) {
110
111             NodeUtils.setIpAndFqdnForEelf("NodeConfigManager");
112             eelflogger.error(EelfMsgs.MESSAGE_PROPERTIES_LOAD_ERROR);
113             logger.error("NODE0301 Unable to load local configuration file " + System.getProperty("org.onap.dmaap.datarouter.node.ConfigFile", "/opt/app/datartr/etc/node.properties"), e);
114         }
115         provurl = p.getProperty("ProvisioningURL", "https://feeds-drtr.web.att.com/internal/prov");
116         try {
117             provhost = (new URL(provurl)).getHost();
118         } catch (Exception e) {
119             NodeUtils.setIpAndFqdnForEelf("NodeConfigManager");
120             eelflogger.error(EelfMsgs.MESSAGE_BAD_PROV_URL, provurl);
121             logger.error("NODE0302 Bad provisioning server URL " + provurl);
122             System.exit(1);
123         }
124         logger.info("NODE0303 Provisioning server is " + provhost);
125         eventlogurl = p.getProperty("LogUploadURL", "https://feeds-drtr.web.att.com/internal/logs");
126         provcheck = new IsFrom(provhost);
127         gfport = Integer.parseInt(p.getProperty("IntHttpPort", "8080"));
128         svcport = Integer.parseInt(p.getProperty("IntHttpsPort", "8443"));
129         port = Integer.parseInt(p.getProperty("ExtHttpsPort", "443"));
130         long minpfinterval = Long.parseLong(p.getProperty("MinProvFetchInterval", "10000"));
131         long minrsinterval = Long.parseLong(p.getProperty("MinRedirSaveInterval", "10000"));
132         spooldir = p.getProperty("SpoolDir", "spool");
133         File fdir = new File(spooldir + "/f");
134         fdir.mkdirs();
135         for (File junk : fdir.listFiles()) {
136             if (junk.isFile()) {
137                 junk.delete();
138             }
139         }
140         logdir = p.getProperty("LogDir", "logs");
141         (new File(logdir)).mkdirs();
142         logretention = Long.parseLong(p.getProperty("LogRetention", "30")) * 86400000L;
143         eventlogprefix = logdir + "/events";
144         eventlogsuffix = ".log";
145         String redirfile = p.getProperty("RedirectionFile", "etc/redirections.dat");
146         kstype = p.getProperty("KeyStoreType", "jks");
147         ksfile = p.getProperty("KeyStoreFile", "etc/keystore");
148         kspass = p.getProperty("KeyStorePassword", "changeme");
149         kpass = p.getProperty("KeyPassword", "changeme");
150         tstype = p.getProperty("TrustStoreType", "jks");
151         tsfile = p.getProperty("TrustStoreFile");
152         tspass = p.getProperty("TrustStorePassword", "changeme");
153         if (tsfile != null && tsfile.length() > 0) {
154             System.setProperty("javax.net.ssl.trustStoreType", tstype);
155             System.setProperty("javax.net.ssl.trustStore", tsfile);
156             System.setProperty("javax.net.ssl.trustStorePassword", tspass);
157         }
158         nak = p.getProperty("NodeAuthKey", "Node123!");
159         quiesce = new File(p.getProperty("QuiesceFile", "etc/SHUTDOWN"));
160         myname = NodeUtils.getCanonicalName(kstype, ksfile, kspass);
161         if (myname == null) {
162             NodeUtils.setIpAndFqdnForEelf("NodeConfigManager");
163             eelflogger.error(EelfMsgs.MESSAGE_KEYSTORE_FETCH_ERROR, ksfile);
164             logger.error("NODE0309 Unable to fetch canonical name from keystore file " + ksfile);
165             System.exit(1);
166         }
167         logger.info("NODE0304 My certificate says my name is " + myname);
168         pid = new PublishId(myname);
169         rdmgr = new RedirManager(redirfile, minrsinterval, timer);
170         pfetcher = new RateLimitedOperation(minpfinterval, timer) {
171             public void run() {
172                 fetchconfig();
173             }
174         };
175         logger.info("NODE0305 Attempting to fetch configuration at " + provurl);
176         pfetcher.request();
177     }
178
179     private void localconfig() {
180         followredirects = Boolean.parseBoolean(getProvParam("FOLLOW_REDIRECTS", "false"));
181         eventloginterval = getProvParam("LOGROLL_INTERVAL", "5m");
182         initfailuretimer = 10000;
183         maxfailuretimer = 3600000;
184         expirationtimer = 86400000;
185         failurebackoff = 2.0;
186         deliverythreads = 40;
187         fairfilelimit = 100;
188         fairtimelimit = 60000;
189         fdpstart = 0.05;
190         fdpstop = 0.2;
191         try {
192             initfailuretimer = (long) (Double.parseDouble(getProvParam("DELIVERY_INIT_RETRY_INTERVAL")) * 1000);
193         } catch (Exception e) {
194         }
195         try {
196             maxfailuretimer = (long) (Double.parseDouble(getProvParam("DELIVERY_MAX_RETRY_INTERVAL")) * 1000);
197         } catch (Exception e) {
198         }
199         try {
200             expirationtimer = (long) (Double.parseDouble(getProvParam("DELIVERY_MAX_AGE")) * 1000);
201         } catch (Exception e) {
202         }
203         try {
204             failurebackoff = Double.parseDouble(getProvParam("DELIVERY_RETRY_RATIO"));
205         } catch (Exception e) {
206         }
207         try {
208             deliverythreads = Integer.parseInt(getProvParam("DELIVERY_THREADS"));
209         } catch (Exception e) {
210         }
211         try {
212             fairfilelimit = Integer.parseInt(getProvParam("FAIR_FILE_LIMIT"));
213         } catch (Exception e) {
214         }
215         try {
216             fairtimelimit = (long) (Double.parseDouble(getProvParam("FAIR_TIME_LIMIT")) * 1000);
217         } catch (Exception e) {
218         }
219         try {
220             fdpstart = Double.parseDouble(getProvParam("FREE_DISK_RED_PERCENT")) / 100.0;
221         } catch (Exception e) {
222         }
223         try {
224             fdpstop = Double.parseDouble(getProvParam("FREE_DISK_YELLOW_PERCENT")) / 100.0;
225         } catch (Exception e) {
226         }
227         if (fdpstart < 0.01) {
228             fdpstart = 0.01;
229         }
230         if (fdpstart > 0.5) {
231             fdpstart = 0.5;
232         }
233         if (fdpstop < fdpstart) {
234             fdpstop = fdpstart;
235         }
236         if (fdpstop > 0.5) {
237             fdpstop = 0.5;
238         }
239     }
240
241     private void fetchconfig() {
242         try {
243             System.out.println("provurl:: " + provurl);
244             Reader r = new InputStreamReader((new URL(provurl)).openStream());
245             config = new NodeConfig(new ProvData(r), myname, spooldir, port, nak);
246             localconfig();
247             configtasks.startRun();
248             Runnable rr;
249             while ((rr = configtasks.next()) != null) {
250                 try {
251                     rr.run();
252                 } catch (Exception e) {
253                 }
254             }
255         } catch (Exception e) {
256             e.printStackTrace();
257             NodeUtils.setIpAndFqdnForEelf("fetchconfigs");
258             eelflogger.error(EelfMsgs.MESSAGE_CONF_FAILED, e.toString());
259             logger.error("NODE0306 Configuration failed " + e.toString() + " - try again later", e);
260             pfetcher.request();
261         }
262     }
263
264     /**
265      * Process a gofetch request from a particular IP address.  If the
266      * IP address is not an IP address we would go to to fetch the
267      * provisioning data, ignore the request.  If the data has been
268      * fetched very recently (default 10 seconds), wait a while before fetching again.
269      */
270     public synchronized void gofetch(String remoteaddr) {
271         if (provcheck.isFrom(remoteaddr)) {
272             logger.info("NODE0307 Received configuration fetch request from provisioning server " + remoteaddr);
273             pfetcher.request();
274         } else {
275             logger.info("NODE0308 Received configuration fetch request from unexpected server " + remoteaddr);
276         }
277     }
278
279     /**
280      * Am I configured?
281      */
282     public boolean isConfigured() {
283         return (config != null);
284     }
285
286     /**
287      * Am I shut down?
288      */
289     public boolean isShutdown() {
290         return (quiesce.exists());
291     }
292
293     /**
294      * Given a routing string, get the targets.
295      *
296      * @param routing Target string
297      * @return array of targets
298      */
299     public Target[] parseRouting(String routing) {
300         return (config.parseRouting(routing));
301     }
302
303     /**
304      * Given a set of credentials and an IP address, is this request from another node?
305      *
306      * @param credentials Credentials offered by the supposed node
307      * @param ip          IP address the request came from
308      * @return If the credentials and IP address are recognized, true, otherwise false.
309      */
310     public boolean isAnotherNode(String credentials, String ip) {
311         return (config.isAnotherNode(credentials, ip));
312     }
313
314     /**
315      * Check whether publication is allowed.
316      *
317      * @param feedid      The ID of the feed being requested
318      * @param credentials The offered credentials
319      * @param ip          The requesting IP address
320      * @return True if the IP and credentials are valid for the specified feed.
321      */
322     public String isPublishPermitted(String feedid, String credentials, String ip) {
323         return (config.isPublishPermitted(feedid, credentials, ip));
324     }
325
326     /**
327      * Check who the user is given the feed ID and the offered credentials.
328      *
329      * @param feedid      The ID of the feed specified
330      * @param credentials The offered credentials
331      * @return Null if the credentials are invalid or the user if they are valid.
332      */
333     public String getAuthUser(String feedid, String credentials) {
334         return (config.getAuthUser(feedid, credentials));
335     }
336
337     /**
338      * Check if the publish request should be sent to another node based on the feedid, user, and source IP address.
339      *
340      * @param feedid The ID of the feed specified
341      * @param user   The publishing user
342      * @param ip     The IP address of the publish endpoint
343      * @return Null if the request should be accepted or the correct hostname if it should be sent to another node.
344      */
345     public String getIngressNode(String feedid, String user, String ip) {
346         return (config.getIngressNode(feedid, user, ip));
347     }
348
349     /**
350      * Get a provisioned configuration parameter (from the provisioning server configuration)
351      *
352      * @param name The name of the parameter
353      * @return The value of the parameter or null if it is not defined.
354      */
355     public String getProvParam(String name) {
356         return (config.getProvParam(name));
357     }
358
359     /**
360      * Get a provisioned configuration parameter (from the provisioning server configuration)
361      *
362      * @param name  The name of the parameter
363      * @param deflt The value to use if the parameter is not defined
364      * @return The value of the parameter or deflt if it is not defined.
365      */
366     public String getProvParam(String name, String deflt) {
367         name = config.getProvParam(name);
368         if (name == null) {
369             name = deflt;
370         }
371         return (name);
372     }
373
374     /**
375      * Generate a publish ID
376      */
377     public String getPublishId() {
378         return (pid.next());
379     }
380
381     /**
382      * Get all the outbound spooling destinations.
383      * This will include both subscriptions and nodes.
384      */
385     public DestInfo[] getAllDests() {
386         return (config.getAllDests());
387     }
388
389     /**
390      * Register a task to run whenever the configuration changes
391      */
392     public void registerConfigTask(Runnable task) {
393         configtasks.addTask(task);
394     }
395
396     /**
397      * Deregister a task to run whenever the configuration changes
398      */
399     public void deregisterConfigTask(Runnable task) {
400         configtasks.removeTask(task);
401     }
402
403     /**
404      * Get the URL to deliver a message to.
405      *
406      * @param destinfo The destination information
407      * @param fileid   The file ID
408      * @return The URL to deliver to
409      */
410     public String getDestURL(DestInfo destinfo, String fileid) {
411         String subid = destinfo.getSubId();
412         String purl = destinfo.getURL();
413         if (followredirects && subid != null) {
414             purl = rdmgr.lookup(subid, purl);
415         }
416         return (purl + "/" + fileid);
417     }
418
419     /**
420      * Is a destination redirected?
421      */
422     public boolean isDestRedirected(DestInfo destinfo) {
423         return (followredirects && rdmgr.isRedirected(destinfo.getSubId()));
424     }
425
426     /**
427      * Set up redirection on receipt of a 3XX from a target URL
428      */
429     public boolean handleRedirection(DestInfo destinfo, String redirto, String fileid) {
430         fileid = "/" + fileid;
431         String subid = destinfo.getSubId();
432         String purl = destinfo.getURL();
433         if (followredirects && subid != null && redirto.endsWith(fileid)) {
434             redirto = redirto.substring(0, redirto.length() - fileid.length());
435             if (!redirto.equals(purl)) {
436                 rdmgr.redirect(subid, purl, redirto);
437                 return (true);
438             }
439         }
440         return (false);
441     }
442
443     /**
444      * Handle unreachable target URL
445      */
446     public void handleUnreachable(DestInfo destinfo) {
447         String subid = destinfo.getSubId();
448         if (followredirects && subid != null) {
449             rdmgr.forget(subid);
450         }
451     }
452
453     /**
454      * Get the timeout before retrying after an initial delivery failure
455      */
456     public long getInitFailureTimer() {
457         return (initfailuretimer);
458     }
459
460     /**
461      * Get the maximum timeout between delivery attempts
462      */
463     public long getMaxFailureTimer() {
464         return (maxfailuretimer);
465     }
466
467     /**
468      * Get the ratio between consecutive delivery attempts
469      */
470     public double getFailureBackoff() {
471         return (failurebackoff);
472     }
473
474     /**
475      * Get the expiration timer for deliveries
476      */
477     public long getExpirationTimer() {
478         return (expirationtimer);
479     }
480
481     /**
482      * Get the maximum number of file delivery attempts before checking
483      * if another queue has work to be performed.
484      */
485     public int getFairFileLimit() {
486         return (fairfilelimit);
487     }
488
489     /**
490      * Get the maximum amount of time spent delivering files before
491      * checking if another queue has work to be performed.
492      */
493     public long getFairTimeLimit() {
494         return (fairtimelimit);
495     }
496
497     /**
498      * Get the targets for a feed
499      *
500      * @param feedid The feed ID
501      * @return The targets this feed should be delivered to
502      */
503     public Target[] getTargets(String feedid) {
504         return (config.getTargets(feedid));
505     }
506
507     /**
508      * Get the spool directory for temporary files
509      */
510     public String getSpoolDir() {
511         return (spooldir + "/f");
512     }
513
514     /**
515      * Get the base directory for spool directories
516      */
517     public String getSpoolBase() {
518         return (spooldir);
519     }
520
521     /**
522      * Get the key store type
523      */
524     public String getKSType() {
525         return (kstype);
526     }
527
528     /**
529      * Get the key store file
530      */
531     public String getKSFile() {
532         return (ksfile);
533     }
534
535     /**
536      * Get the key store password
537      */
538     public String getKSPass() {
539         return (kspass);
540     }
541
542     /**
543      * Get the key password
544      */
545     public String getKPass() {
546         return (kpass);
547     }
548
549     /**
550      * Get the http port
551      */
552     public int getHttpPort() {
553         return (gfport);
554     }
555
556     /**
557      * Get the https port
558      */
559     public int getHttpsPort() {
560         return (svcport);
561     }
562
563     /**
564      * Get the externally visible https port
565      */
566     public int getExtHttpsPort() {
567         return (port);
568     }
569
570     /**
571      * Get the external name of this machine
572      */
573     public String getMyName() {
574         return (myname);
575     }
576
577     /**
578      * Get the number of threads to use for delivery
579      */
580     public int getDeliveryThreads() {
581         return (deliverythreads);
582     }
583
584     /**
585      * Get the URL for uploading the event log data
586      */
587     public String getEventLogUrl() {
588         return (eventlogurl);
589     }
590
591     /**
592      * Get the prefix for the names of event log files
593      */
594     public String getEventLogPrefix() {
595         return (eventlogprefix);
596     }
597
598     /**
599      * Get the suffix for the names of the event log files
600      */
601     public String getEventLogSuffix() {
602         return (eventlogsuffix);
603     }
604
605     /**
606      * Get the interval between event log file rollovers
607      */
608     public String getEventLogInterval() {
609         return (eventloginterval);
610     }
611
612     /**
613      * Should I follow redirects from subscribers?
614      */
615     public boolean isFollowRedirects() {
616         return (followredirects);
617     }
618
619     /**
620      * Get the directory where the event and node log files live
621      */
622     public String getLogDir() {
623         return (logdir);
624     }
625
626     /**
627      * How long do I keep log files (in milliseconds)
628      */
629     public long getLogRetention() {
630         return (logretention);
631     }
632
633     /**
634      * Get the timer
635      */
636     public Timer getTimer() {
637         return (timer);
638     }
639
640     /**
641      * Get the feed ID for a subscription
642      *
643      * @param subid The subscription ID
644      * @return The feed ID
645      */
646     public String getFeedId(String subid) {
647         return (config.getFeedId(subid));
648     }
649
650     /**
651      * Get the authorization string this node uses
652      *
653      * @return The Authorization string for this node
654      */
655     public String getMyAuth() {
656         return (config.getMyAuth());
657     }
658
659     /**
660      * Get the fraction of free spool disk space where we start throwing away undelivered files.  This is FREE_DISK_RED_PERCENT / 100.0.  Default is 0.05.  Limited by 0.01 <= FreeDiskStart <= 0.5.
661      */
662     public double getFreeDiskStart() {
663         return (fdpstart);
664     }
665
666     /**
667      * Get the fraction of free spool disk space where we stop throwing away undelivered files.  This is FREE_DISK_YELLOW_PERCENT / 100.0.  Default is 0.2.  Limited by FreeDiskStart <= FreeDiskStop <= 0.5.
668      */
669     public double getFreeDiskStop() {
670         return (fdpstop);
671     }
672
673     /**
674      * Get the spool directory for a subscription
675      */
676     public String getSpoolDir(String subid, String remoteaddr) {
677         if (provcheck.isFrom(remoteaddr)) {
678             String sdir = config.getSpoolDir(subid);
679             if (sdir != null) {
680                 logger.info("NODE0310 Received subscription reset request for subscription " + subid + " from provisioning server " + remoteaddr);
681             } else {
682                 logger.info("NODE0311 Received subscription reset request for unknown subscription " + subid + " from provisioning server " + remoteaddr);
683             }
684             return (sdir);
685         } else {
686             logger.info("NODE0312 Received subscription reset request from unexpected server " + remoteaddr);
687             return (null);
688         }
689     }
690 }