1 /*******************************************************************************
2 * ============LICENSE_START==================================================
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
11 * * http://www.apache.org/licenses/LICENSE-2.0
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====================================================
20 * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
22 ******************************************************************************/
25 package org.onap.dmaap.datarouter.node;
27 import com.att.eelf.configuration.EELFLogger;
28 import com.att.eelf.configuration.EELFManager;
30 import java.io.FileInputStream;
31 import java.io.InputStreamReader;
32 import java.io.Reader;
34 import java.util.Properties;
35 import java.util.Timer;
36 import org.apache.log4j.Logger;
37 import org.onap.dmaap.datarouter.node.eelf.EelfMsgs;
41 * Maintain the configuration of a Data Router node
43 * The NodeConfigManager is the single point of contact for servlet, delivery, event logging, and log retention
44 * subsystems to access configuration information. (Log4J has its own configuration mechanism).
46 * There are two basic sets of configuration data. The static local configuration data, stored in a local configuration
47 * file (created as part of installation by SWM), and the dynamic global configuration data fetched from the data router
48 * provisioning server.
50 public class NodeConfigManager implements DeliveryQueueHelper {
52 private static EELFLogger eelflogger = EELFManager.getInstance()
53 .getLogger("org.onap.dmaap.datarouter.node.NodeConfigManager");
54 private static Logger logger = Logger.getLogger("org.onap.dmaap.datarouter.node.NodeConfigManager");
55 private static NodeConfigManager base = new NodeConfigManager();
57 private Timer timer = new Timer("Node Configuration Timer", true);
58 private long maxfailuretimer;
59 private long initfailuretimer;
60 private long expirationtimer;
61 private double failurebackoff;
62 private long fairtimelimit;
63 private int fairfilelimit;
64 private double fdpstart;
65 private double fdpstop;
66 private int deliverythreads;
67 private String provurl;
68 private String provhost;
69 private IsFrom provcheck;
73 private String spooldir;
74 private String logdir;
75 private long logretention;
76 private String redirfile;
77 private String kstype;
78 private String ksfile;
79 private String kspass;
81 private String tstype;
82 private String tsfile;
83 private String tspass;
84 private String myname;
85 private RedirManager rdmgr;
86 private RateLimitedOperation pfetcher;
87 private NodeConfig config;
89 private PublishId pid;
91 private TaskList configtasks = new TaskList();
92 private String eventlogurl;
93 private String eventlogprefix;
94 private String eventlogsuffix;
95 private String eventloginterval;
96 private boolean followredirects;
100 * Get the default node configuration manager
102 public static NodeConfigManager getInstance() {
107 * Initialize the configuration of a Data Router node
109 private NodeConfigManager() {
110 Properties p = new Properties();
112 p.load(new FileInputStream(System
113 .getProperty("org.onap.dmaap.datarouter.node.properties", "/opt/app/datartr/etc/node.properties")));
114 } catch (Exception e) {
116 NodeUtils.setIpAndFqdnForEelf("NodeConfigManager");
117 eelflogger.error(EelfMsgs.MESSAGE_PROPERTIES_LOAD_ERROR);
118 logger.error("NODE0301 Unable to load local configuration file " + System
119 .getProperty("org.onap.dmaap.datarouter.node.properties", "/opt/app/datartr/etc/node.properties"),
122 provurl = p.getProperty("ProvisioningURL", "https://feeds-drtr.web.att.com/internal/prov");
124 provhost = (new URL(provurl)).getHost();
125 } catch (Exception e) {
126 NodeUtils.setIpAndFqdnForEelf("NodeConfigManager");
127 eelflogger.error(EelfMsgs.MESSAGE_BAD_PROV_URL, provurl);
128 logger.error("NODE0302 Bad provisioning server URL " + provurl);
131 logger.info("NODE0303 Provisioning server is " + provhost);
132 eventlogurl = p.getProperty("LogUploadURL", "https://feeds-drtr.web.att.com/internal/logs");
133 provcheck = new IsFrom(provhost);
134 gfport = Integer.parseInt(p.getProperty("IntHttpPort", "8080"));
135 svcport = Integer.parseInt(p.getProperty("IntHttpsPort", "8443"));
136 port = Integer.parseInt(p.getProperty("ExtHttpsPort", "443"));
137 long minpfinterval = Long.parseLong(p.getProperty("MinProvFetchInterval", "10000"));
138 long minrsinterval = Long.parseLong(p.getProperty("MinRedirSaveInterval", "10000"));
139 spooldir = p.getProperty("SpoolDir", "spool");
140 File fdir = new File(spooldir + "/f");
142 for (File junk : fdir.listFiles()) {
147 logdir = p.getProperty("LogDir", "logs");
148 (new File(logdir)).mkdirs();
149 logretention = Long.parseLong(p.getProperty("LogRetention", "30")) * 86400000L;
150 eventlogprefix = logdir + "/events";
151 eventlogsuffix = ".log";
152 String redirfile = p.getProperty("RedirectionFile", "etc/redirections.dat");
153 kstype = p.getProperty("KeyStoreType", "jks");
154 ksfile = p.getProperty("KeyStoreFile", "etc/keystore");
155 kspass = p.getProperty("KeyStorePassword", "changeme");
156 kpass = p.getProperty("KeyPassword", "changeme");
157 tstype = p.getProperty("TrustStoreType", "jks");
158 tsfile = p.getProperty("TrustStoreFile");
159 tspass = p.getProperty("TrustStorePassword", "changeme");
160 if (tsfile != null && tsfile.length() > 0) {
161 System.setProperty("javax.net.ssl.trustStoreType", tstype);
162 System.setProperty("javax.net.ssl.trustStore", tsfile);
163 System.setProperty("javax.net.ssl.trustStorePassword", tspass);
165 nak = p.getProperty("NodeAuthKey", "Node123!");
166 quiesce = new File(p.getProperty("QuiesceFile", "etc/SHUTDOWN"));
167 myname = NodeUtils.getCanonicalName(kstype, ksfile, kspass);
168 if (myname == null) {
169 NodeUtils.setIpAndFqdnForEelf("NodeConfigManager");
170 eelflogger.error(EelfMsgs.MESSAGE_KEYSTORE_FETCH_ERROR, ksfile);
171 logger.error("NODE0309 Unable to fetch canonical name from keystore file " + ksfile);
174 logger.info("NODE0304 My certificate says my name is " + myname);
175 pid = new PublishId(myname);
176 rdmgr = new RedirManager(redirfile, minrsinterval, timer);
177 pfetcher = new RateLimitedOperation(minpfinterval, timer) {
182 logger.info("NODE0305 Attempting to fetch configuration at " + provurl);
186 private void localconfig() {
187 followredirects = Boolean.parseBoolean(getProvParam("FOLLOW_REDIRECTS", "false"));
188 eventloginterval = getProvParam("LOGROLL_INTERVAL", "5m");
189 initfailuretimer = 10000;
190 maxfailuretimer = 3600000;
191 expirationtimer = 86400000;
192 failurebackoff = 2.0;
193 deliverythreads = 40;
195 fairtimelimit = 60000;
199 initfailuretimer = (long) (Double.parseDouble(getProvParam("DELIVERY_INIT_RETRY_INTERVAL")) * 1000);
200 } catch (Exception e) {
203 maxfailuretimer = (long) (Double.parseDouble(getProvParam("DELIVERY_MAX_RETRY_INTERVAL")) * 1000);
204 } catch (Exception e) {
207 expirationtimer = (long) (Double.parseDouble(getProvParam("DELIVERY_MAX_AGE")) * 1000);
208 } catch (Exception e) {
211 failurebackoff = Double.parseDouble(getProvParam("DELIVERY_RETRY_RATIO"));
212 } catch (Exception e) {
215 deliverythreads = Integer.parseInt(getProvParam("DELIVERY_THREADS"));
216 } catch (Exception e) {
219 fairfilelimit = Integer.parseInt(getProvParam("FAIR_FILE_LIMIT"));
220 } catch (Exception e) {
223 fairtimelimit = (long) (Double.parseDouble(getProvParam("FAIR_TIME_LIMIT")) * 1000);
224 } catch (Exception e) {
227 fdpstart = Double.parseDouble(getProvParam("FREE_DISK_RED_PERCENT")) / 100.0;
228 } catch (Exception e) {
231 fdpstop = Double.parseDouble(getProvParam("FREE_DISK_YELLOW_PERCENT")) / 100.0;
232 } catch (Exception e) {
234 if (fdpstart < 0.01) {
237 if (fdpstart > 0.5) {
240 if (fdpstop < fdpstart) {
248 private void fetchconfig() {
250 System.out.println("provurl:: " + provurl);
251 Reader r = new InputStreamReader((new URL(provurl)).openStream());
252 config = new NodeConfig(new ProvData(r), myname, spooldir, port, nak);
254 configtasks.startRun();
256 while ((rr = configtasks.next()) != null) {
259 } catch (Exception e) {
262 } catch (Exception e) {
263 NodeUtils.setIpAndFqdnForEelf("fetchconfigs");
264 eelflogger.error(EelfMsgs.MESSAGE_CONF_FAILED, e.toString());
265 logger.error("NODE0306 Configuration failed " + e.toString() + " - try again later", e);
271 * Process a gofetch request from a particular IP address. If the IP address is not an IP address we would go to to
272 * fetch the provisioning data, ignore the request. If the data has been fetched very recently (default 10
273 * seconds), wait a while before fetching again.
275 public synchronized void gofetch(String remoteaddr) {
276 if (provcheck.isFrom(remoteaddr)) {
277 logger.info("NODE0307 Received configuration fetch request from provisioning server " + remoteaddr);
280 logger.info("NODE0308 Received configuration fetch request from unexpected server " + remoteaddr);
287 public boolean isConfigured() {
288 return (config != null);
294 public boolean isShutdown() {
295 return (quiesce.exists());
299 * Given a routing string, get the targets.
301 * @param routing Target string
302 * @return array of targets
304 public Target[] parseRouting(String routing) {
305 return (config.parseRouting(routing));
309 * Given a set of credentials and an IP address, is this request from another node?
311 * @param credentials Credentials offered by the supposed node
312 * @param ip IP address the request came from
313 * @return If the credentials and IP address are recognized, true, otherwise false.
315 public boolean isAnotherNode(String credentials, String ip) {
316 return (config.isAnotherNode(credentials, ip));
320 * Check whether publication is allowed.
322 * @param feedid The ID of the feed being requested
323 * @param credentials The offered credentials
324 * @param ip The requesting IP address
325 * @return True if the IP and credentials are valid for the specified feed.
327 public String isPublishPermitted(String feedid, String credentials, String ip) {
328 return (config.isPublishPermitted(feedid, credentials, ip));
332 * Check who the user is given the feed ID and the offered credentials.
334 * @param feedid The ID of the feed specified
335 * @param credentials The offered credentials
336 * @return Null if the credentials are invalid or the user if they are valid.
338 public String getAuthUser(String feedid, String credentials) {
339 return (config.getAuthUser(feedid, credentials));
343 * Check if the publish request should be sent to another node based on the feedid, user, and source IP address.
345 * @param feedid The ID of the feed specified
346 * @param user The publishing user
347 * @param ip The IP address of the publish endpoint
348 * @return Null if the request should be accepted or the correct hostname if it should be sent to another node.
350 public String getIngressNode(String feedid, String user, String ip) {
351 return (config.getIngressNode(feedid, user, ip));
355 * Get a provisioned configuration parameter (from the provisioning server configuration)
357 * @param name The name of the parameter
358 * @return The value of the parameter or null if it is not defined.
360 public String getProvParam(String name) {
361 return (config.getProvParam(name));
365 * Get a provisioned configuration parameter (from the provisioning server configuration)
367 * @param name The name of the parameter
368 * @param deflt The value to use if the parameter is not defined
369 * @return The value of the parameter or deflt if it is not defined.
371 public String getProvParam(String name, String deflt) {
372 name = config.getProvParam(name);
380 * Generate a publish ID
382 public String getPublishId() {
387 * Get all the outbound spooling destinations. This will include both subscriptions and nodes.
389 public DestInfo[] getAllDests() {
390 return (config.getAllDests());
394 * Register a task to run whenever the configuration changes
396 public void registerConfigTask(Runnable task) {
397 configtasks.addTask(task);
401 * Deregister a task to run whenever the configuration changes
403 public void deregisterConfigTask(Runnable task) {
404 configtasks.removeTask(task);
408 * Get the URL to deliver a message to.
410 * @param destinfo The destination information
411 * @param fileid The file ID
412 * @return The URL to deliver to
414 public String getDestURL(DestInfo destinfo, String fileid) {
415 String subid = destinfo.getSubId();
416 String purl = destinfo.getURL();
417 if (followredirects && subid != null) {
418 purl = rdmgr.lookup(subid, purl);
420 return (purl + "/" + fileid);
424 * Is a destination redirected?
426 public boolean isDestRedirected(DestInfo destinfo) {
427 return (followredirects && rdmgr.isRedirected(destinfo.getSubId()));
431 * Set up redirection on receipt of a 3XX from a target URL
433 public boolean handleRedirection(DestInfo destinfo, String redirto, String fileid) {
434 fileid = "/" + fileid;
435 String subid = destinfo.getSubId();
436 String purl = destinfo.getURL();
437 if (followredirects && subid != null && redirto.endsWith(fileid)) {
438 redirto = redirto.substring(0, redirto.length() - fileid.length());
439 if (!redirto.equals(purl)) {
440 rdmgr.redirect(subid, purl, redirto);
448 * Handle unreachable target URL
450 public void handleUnreachable(DestInfo destinfo) {
451 String subid = destinfo.getSubId();
452 if (followredirects && subid != null) {
458 * Get the timeout before retrying after an initial delivery failure
460 public long getInitFailureTimer() {
461 return (initfailuretimer);
465 * Get the maximum timeout between delivery attempts
467 public long getMaxFailureTimer() {
468 return (maxfailuretimer);
472 * Get the ratio between consecutive delivery attempts
474 public double getFailureBackoff() {
475 return (failurebackoff);
479 * Get the expiration timer for deliveries
481 public long getExpirationTimer() {
482 return (expirationtimer);
486 * Get the maximum number of file delivery attempts before checking if another queue has work to be performed.
488 public int getFairFileLimit() {
489 return (fairfilelimit);
493 * Get the maximum amount of time spent delivering files before checking if another queue has work to be performed.
495 public long getFairTimeLimit() {
496 return (fairtimelimit);
500 * Get the targets for a feed
502 * @param feedid The feed ID
503 * @return The targets this feed should be delivered to
505 public Target[] getTargets(String feedid) {
506 return (config.getTargets(feedid));
510 * Get the spool directory for temporary files
512 public String getSpoolDir() {
513 return (spooldir + "/f");
517 * Get the base directory for spool directories
519 public String getSpoolBase() {
524 * Get the key store type
526 public String getKSType() {
531 * Get the key store file
533 public String getKSFile() {
538 * Get the key store password
540 public String getKSPass() {
545 * Get the key password
547 public String getKPass() {
554 public int getHttpPort() {
561 public int getHttpsPort() {
566 * Get the externally visible https port
568 public int getExtHttpsPort() {
573 * Get the external name of this machine
575 public String getMyName() {
580 * Get the number of threads to use for delivery
582 public int getDeliveryThreads() {
583 return (deliverythreads);
587 * Get the URL for uploading the event log data
589 public String getEventLogUrl() {
590 return (eventlogurl);
594 * Get the prefix for the names of event log files
596 public String getEventLogPrefix() {
597 return (eventlogprefix);
601 * Get the suffix for the names of the event log files
603 public String getEventLogSuffix() {
604 return (eventlogsuffix);
608 * Get the interval between event log file rollovers
610 public String getEventLogInterval() {
611 return (eventloginterval);
615 * Should I follow redirects from subscribers?
617 public boolean isFollowRedirects() {
618 return (followredirects);
622 * Get the directory where the event and node log files live
624 public String getLogDir() {
629 * How long do I keep log files (in milliseconds)
631 public long getLogRetention() {
632 return (logretention);
638 public Timer getTimer() {
643 * Get the feed ID for a subscription
645 * @param subid The subscription ID
646 * @return The feed ID
648 public String getFeedId(String subid) {
649 return (config.getFeedId(subid));
653 * Get the authorization string this node uses
655 * @return The Authorization string for this node
657 public String getMyAuth() {
658 return (config.getMyAuth());
662 * Get the fraction of free spool disk space where we start throwing away undelivered files. This is
663 * FREE_DISK_RED_PERCENT / 100.0. Default is 0.05. Limited by 0.01 <= FreeDiskStart <= 0.5.
665 public double getFreeDiskStart() {
670 * Get the fraction of free spool disk space where we stop throwing away undelivered files. This is
671 * FREE_DISK_YELLOW_PERCENT / 100.0. Default is 0.2. Limited by FreeDiskStart <= FreeDiskStop <= 0.5.
673 public double getFreeDiskStop() {
678 * Get the spool directory for a subscription
680 public String getSpoolDir(String subid, String remoteaddr) {
681 if (provcheck.isFrom(remoteaddr)) {
682 String sdir = config.getSpoolDir(subid);
684 logger.info("NODE0310 Received subscription reset request for subscription " + subid
685 + " from provisioning server " + remoteaddr);
687 logger.info("NODE0311 Received subscription reset request for unknown subscription " + subid
688 + " from provisioning server " + remoteaddr);
692 logger.info("NODE0312 Received subscription reset request from unexpected server " + remoteaddr);