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.onap.dmaap.datarouter.node.eelf.EelfMsgs;
40 * Maintain the configuration of a Data Router node
42 * <p>The NodeConfigManager is the single point of contact for servlet, delivery, event logging, and log retention
43 * subsystems to access configuration information.
45 * <p>There are two basic sets of configuration data. The static local configuration data, stored in a local
46 * configuration file (created as part of installation by SWM), and the dynamic global configuration data fetched from
47 * the data router provisioning server.
49 public class NodeConfigManager implements DeliveryQueueHelper {
51 private static final String CHANGE_ME = "changeme";
52 private static final String NODE_CONFIG_MANAGER = "NodeConfigManager";
53 private static EELFLogger eelfLogger = EELFManager.getInstance().getLogger(NodeConfigManager.class);
54 private static NodeConfigManager base = new NodeConfigManager();
56 private Timer timer = new Timer("Node Configuration Timer", true);
57 private long maxfailuretimer;
58 private long initfailuretimer;
59 private long waitForFileProcessFailureTimer;
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;
97 private String[] enabledprotocols;
98 private String aafType;
99 private String aafInstance;
100 private String aafAction;
101 private String aafURL;
102 private boolean cadiEnabled;
106 * Initialize the configuration of a Data Router node.
108 private NodeConfigManager() {
110 Properties drNodeProperties = new Properties();
112 eelfLogger.info("NODE0301 Loading local config file node.properties");
113 drNodeProperties.load(new FileInputStream(System
114 .getProperty("org.onap.dmaap.datarouter.node.properties", "/opt/app/datartr/etc/node.properties")));
115 } catch (Exception e) {
116 NodeUtils.setIpAndFqdnForEelf(NODE_CONFIG_MANAGER);
117 eelfLogger.error(EelfMsgs.MESSAGE_PROPERTIES_LOAD_ERROR, e,
118 System.getProperty("org.onap.dmaap.datarouter.node.properties",
119 "/opt/app/datartr/etc/node.properties"));
121 provurl = drNodeProperties.getProperty("ProvisioningURL", "https://dmaap-dr-prov:8443/internal/prov");
123 * START - AAF changes: TDP EPIC US# 307413
124 * Pull AAF settings from node.properties
126 aafType = drNodeProperties.getProperty("AAFType", "org.onap.dmaap-dr.feed");
127 aafInstance = drNodeProperties.getProperty("AAFInstance", "legacy");
128 aafAction = drNodeProperties.getProperty("AAFAction", "publish");
129 aafURL = drNodeProperties.getProperty("AafUrl", "https://aaf-onap-test.osaaf.org:8095");
130 cadiEnabled = Boolean.parseBoolean(drNodeProperties.getProperty("CadiEnabled", "false"));
132 * END - AAF changes: TDP EPIC US# 307413
133 * Pull AAF settings from node.properties
135 //Disable and enable protocols*/
136 enabledprotocols = ((drNodeProperties.getProperty("NodeHttpsProtocols")).trim()).split("\\|");
139 provhost = (new URL(provurl)).getHost();
140 } catch (Exception e) {
141 NodeUtils.setIpAndFqdnForEelf(NODE_CONFIG_MANAGER);
142 eelfLogger.error(EelfMsgs.MESSAGE_BAD_PROV_URL, e, provurl);
145 eelfLogger.info("NODE0303 Provisioning server is " + provhost);
146 eventlogurl = drNodeProperties.getProperty("LogUploadURL", "https://feeds-drtr.web.att.com/internal/logs");
147 provcheck = new IsFrom(provhost);
148 gfport = Integer.parseInt(drNodeProperties.getProperty("IntHttpPort", "8080"));
149 svcport = Integer.parseInt(drNodeProperties.getProperty("IntHttpsPort", "8443"));
150 port = Integer.parseInt(drNodeProperties.getProperty("ExtHttpsPort", "443"));
151 spooldir = drNodeProperties.getProperty("SpoolDir", "spool");
152 File fdir = new File(spooldir + "/f");
154 for (File junk : fdir.listFiles()) {
159 logdir = drNodeProperties.getProperty("LogDir", "logs");
160 (new File(logdir)).mkdirs();
161 logretention = Long.parseLong(drNodeProperties.getProperty("LogRetention", "30")) * 86400000L;
162 eventlogprefix = logdir + "/events";
163 eventlogsuffix = ".log";
164 redirfile = drNodeProperties.getProperty("RedirectionFile", "etc/redirections.dat");
165 kstype = drNodeProperties.getProperty("KeyStoreType", "jks");
166 ksfile = drNodeProperties.getProperty("KeyStoreFile", "etc/keystore");
167 kspass = drNodeProperties.getProperty("KeyStorePassword", CHANGE_ME);
168 kpass = drNodeProperties.getProperty("KeyPassword", CHANGE_ME);
169 tstype = drNodeProperties.getProperty("TrustStoreType", "jks");
170 tsfile = drNodeProperties.getProperty("TrustStoreFile");
171 tspass = drNodeProperties.getProperty("TrustStorePassword", CHANGE_ME);
172 if (tsfile != null && tsfile.length() > 0) {
173 System.setProperty("javax.net.ssl.trustStoreType", tstype);
174 System.setProperty("javax.net.ssl.trustStore", tsfile);
175 System.setProperty("javax.net.ssl.trustStorePassword", tspass);
177 nak = drNodeProperties.getProperty("NodeAuthKey", "Node123!");
178 quiesce = new File(drNodeProperties.getProperty("QuiesceFile", "etc/SHUTDOWN"));
179 myname = NodeUtils.getCanonicalName(kstype, ksfile, kspass);
180 if (myname == null) {
181 NodeUtils.setIpAndFqdnForEelf(NODE_CONFIG_MANAGER);
182 eelfLogger.error(EelfMsgs.MESSAGE_KEYSTORE_FETCH_ERROR, ksfile);
183 eelfLogger.error("NODE0309 Unable to fetch canonical name from keystore file " + ksfile);
186 eelfLogger.info("NODE0304 My certificate says my name is " + myname);
187 pid = new PublishId(myname);
188 long minrsinterval = Long.parseLong(drNodeProperties.getProperty("MinRedirSaveInterval", "10000"));
189 long minpfinterval = Long.parseLong(drNodeProperties.getProperty("MinProvFetchInterval", "10000"));
190 rdmgr = new RedirManager(redirfile, minrsinterval, timer);
191 pfetcher = new RateLimitedOperation(minpfinterval, timer) {
196 eelfLogger.info("NODE0305 Attempting to fetch configuration at " + provurl);
201 * Get the default node configuration manager.
203 public static NodeConfigManager getInstance() {
207 private void localconfig() {
208 followredirects = Boolean.parseBoolean(getProvParam("FOLLOW_REDIRECTS", "false"));
209 eventloginterval = getProvParam("LOGROLL_INTERVAL", "30s");
210 initfailuretimer = 10000;
211 waitForFileProcessFailureTimer = 600000;
212 maxfailuretimer = 3600000;
213 expirationtimer = 86400000;
214 failurebackoff = 2.0;
215 deliverythreads = 40;
217 fairtimelimit = 60000;
221 initfailuretimer = (long) (Double.parseDouble(getProvParam("DELIVERY_INIT_RETRY_INTERVAL")) * 1000);
222 } catch (Exception e) {
223 eelfLogger.trace("Error parsing DELIVERY_INIT_RETRY_INTERVAL", e);
226 waitForFileProcessFailureTimer = (long) (Double.parseDouble(getProvParam("DELIVERY_FILE_PROCESS_INTERVAL"))
228 } catch (Exception e) {
229 eelfLogger.trace("Error parsing DELIVERY_FILE_PROCESS_INTERVAL", e);
232 maxfailuretimer = (long) (Double.parseDouble(getProvParam("DELIVERY_MAX_RETRY_INTERVAL")) * 1000);
233 } catch (Exception e) {
234 eelfLogger.trace("Error parsing DELIVERY_MAX_RETRY_INTERVAL", e);
237 expirationtimer = (long) (Double.parseDouble(getProvParam("DELIVERY_MAX_AGE")) * 1000);
238 } catch (Exception e) {
239 eelfLogger.trace("Error parsing DELIVERY_MAX_AGE", e);
242 failurebackoff = Double.parseDouble(getProvParam("DELIVERY_RETRY_RATIO"));
243 } catch (Exception e) {
244 eelfLogger.trace("Error parsing DELIVERY_RETRY_RATIO", e);
247 deliverythreads = Integer.parseInt(getProvParam("DELIVERY_THREADS"));
248 } catch (Exception e) {
249 eelfLogger.trace("Error parsing DELIVERY_THREADS", e);
252 fairfilelimit = Integer.parseInt(getProvParam("FAIR_FILE_LIMIT"));
253 } catch (Exception e) {
254 eelfLogger.trace("Error parsing FAIR_FILE_LIMIT", e);
257 fairtimelimit = (long) (Double.parseDouble(getProvParam("FAIR_TIME_LIMIT")) * 1000);
258 } catch (Exception e) {
259 eelfLogger.trace("Error parsing FAIR_TIME_LIMIT", e);
262 fdpstart = Double.parseDouble(getProvParam("FREE_DISK_RED_PERCENT")) / 100.0;
263 } catch (Exception e) {
264 eelfLogger.trace("Error parsing FREE_DISK_RED_PERCENT", e);
267 fdpstop = Double.parseDouble(getProvParam("FREE_DISK_YELLOW_PERCENT")) / 100.0;
268 } catch (Exception e) {
269 eelfLogger.trace("Error parsing FREE_DISK_YELLOW_PERCENT", e);
271 if (fdpstart < 0.01) {
274 if (fdpstart > 0.5) {
277 if (fdpstop < fdpstart) {
285 private void fetchconfig() {
287 eelfLogger.info("NodeConfigMan.fetchConfig: provurl:: " + provurl);
288 Reader reader = new InputStreamReader((new URL(provurl)).openStream());
289 config = new NodeConfig(new ProvData(reader), myname, spooldir, port, nak);
291 configtasks.startRun();
293 } catch (Exception e) {
294 NodeUtils.setIpAndFqdnForEelf("fetchconfigs");
295 eelfLogger.error(EelfMsgs.MESSAGE_CONF_FAILED, e.toString());
296 eelfLogger.error("NODE0306 Configuration failed " + e.toString() + " - try again later", e);
301 private void runTasks() {
303 while ((rr = configtasks.next()) != null) {
306 } catch (Exception e) {
307 eelfLogger.error("NODE0518 Exception fetchconfig: " + e);
313 * Process a gofetch request from a particular IP address. If the IP address is not an IP address we would go to to
314 * fetch the provisioning data, ignore the request. If the data has been fetched very recently (default 10
315 * seconds), wait a while before fetching again.
317 public synchronized void gofetch(String remoteAddr) {
318 if (provcheck.isReachable(remoteAddr)) {
319 eelfLogger.info("NODE0307 Received configuration fetch request from provisioning server " + remoteAddr);
322 eelfLogger.info("NODE0308 Received configuration fetch request from unexpected server " + remoteAddr);
329 public boolean isConfigured() {
330 return (config != null);
336 public boolean isShutdown() {
337 return (quiesce.exists());
341 * Given a routing string, get the targets.
343 * @param routing Target string
344 * @return array of targets
346 public Target[] parseRouting(String routing) {
347 return (config.parseRouting(routing));
351 * Given a set of credentials and an IP address, is this request from another node.
353 * @param credentials Credentials offered by the supposed node
354 * @param ip IP address the request came from
355 * @return If the credentials and IP address are recognized, true, otherwise false.
357 public boolean isAnotherNode(String credentials, String ip) {
358 return (config.isAnotherNode(credentials, ip));
362 * Check whether publication is allowed.
364 * @param feedid The ID of the feed being requested
365 * @param credentials The offered credentials
366 * @param ip The requesting IP address
367 * @return True if the IP and credentials are valid for the specified feed.
369 public String isPublishPermitted(String feedid, String credentials, String ip) {
370 return (config.isPublishPermitted(feedid, credentials, ip));
374 * Check whether publication is allowed for AAF Feed.
376 * @param feedid The ID of the feed being requested
377 * @param ip The requesting IP address
378 * @return True if the IP and credentials are valid for the specified feed.
380 public String isPublishPermitted(String feedid, String ip) {
381 return (config.isPublishPermitted(feedid, ip));
385 * Check whether delete file is allowed.
387 * @param subId The ID of the subscription being requested
388 * @return True if the delete file is permitted for the subscriber.
390 public boolean isDeletePermitted(String subId) {
391 return (config.isDeletePermitted(subId));
395 * Check who the user is given the feed ID and the offered credentials.
397 * @param feedid The ID of the feed specified
398 * @param credentials The offered credentials
399 * @return Null if the credentials are invalid or the user if they are valid.
401 public String getAuthUser(String feedid, String credentials) {
402 return (config.getAuthUser(feedid, credentials));
406 * AAF changes: TDP EPIC US# 307413 Check AAF_instance for feed ID in NodeConfig.
408 * @param feedid The ID of the feed specified
410 public String getAafInstance(String feedid) {
411 return (config.getAafInstance(feedid));
414 public String getAafInstance() {
419 * Check if the publish request should be sent to another node based on the feedid, user, and source IP address.
421 * @param feedid The ID of the feed specified
422 * @param user The publishing user
423 * @param ip The IP address of the publish endpoint
424 * @return Null if the request should be accepted or the correct hostname if it should be sent to another node.
426 public String getIngressNode(String feedid, String user, String ip) {
427 return (config.getIngressNode(feedid, user, ip));
431 * Get a provisioned configuration parameter (from the provisioning server configuration).
433 * @param name The name of the parameter
434 * @return The value of the parameter or null if it is not defined.
436 public String getProvParam(String name) {
437 return (config.getProvParam(name));
441 * Get a provisioned configuration parameter (from the provisioning server configuration).
443 * @param name The name of the parameter
444 * @param defaultValue The value to use if the parameter is not defined
445 * @return The value of the parameter or deflt if it is not defined.
447 public String getProvParam(String name, String defaultValue) {
448 name = config.getProvParam(name);
456 * Generate a publish ID.
458 public String getPublishId() {
463 * Get all the outbound spooling destinations. This will include both subscriptions and nodes.
465 public DestInfo[] getAllDests() {
466 return (config.getAllDests());
470 * Register a task to run whenever the configuration changes.
472 public void registerConfigTask(Runnable task) {
473 configtasks.addTask(task);
477 * Deregister a task to run whenever the configuration changes.
479 public void deregisterConfigTask(Runnable task) {
480 configtasks.removeTask(task);
484 * Get the URL to deliver a message to.
486 * @param destinationInfo The destination information
487 * @param fileid The file ID
488 * @return The URL to deliver to
490 public String getDestURL(DestInfo destinationInfo, String fileid) {
491 String subid = destinationInfo.getSubId();
492 String purl = destinationInfo.getURL();
493 if (followredirects && subid != null) {
494 purl = rdmgr.lookup(subid, purl);
496 return (purl + "/" + fileid);
500 * Set up redirection on receipt of a 3XX from a target URL.
502 public boolean handleRedirection(DestInfo destinationInfo, String redirto, String fileid) {
503 fileid = "/" + fileid;
504 String subid = destinationInfo.getSubId();
505 String purl = destinationInfo.getURL();
506 if (followredirects && subid != null && redirto.endsWith(fileid)) {
507 redirto = redirto.substring(0, redirto.length() - fileid.length());
508 if (!redirto.equals(purl)) {
509 rdmgr.redirect(subid, purl, redirto);
517 * Handle unreachable target URL.
519 public void handleUnreachable(DestInfo destinationInfo) {
520 String subid = destinationInfo.getSubId();
521 if (followredirects && subid != null) {
527 * Get the timeout before retrying after an initial delivery failure.
529 public long getInitFailureTimer() {
530 return (initfailuretimer);
534 * Get the timeout before retrying after delivery and wait for file processing.
536 public long getWaitForFileProcessFailureTimer() {
537 return (waitForFileProcessFailureTimer);
541 * Get the maximum timeout between delivery attempts.
543 public long getMaxFailureTimer() {
544 return (maxfailuretimer);
548 * Get the ratio between consecutive delivery attempts.
550 public double getFailureBackoff() {
551 return (failurebackoff);
555 * Get the expiration timer for deliveries.
557 public long getExpirationTimer() {
558 return (expirationtimer);
562 * Get the maximum number of file delivery attempts before checking if another queue has work to be performed.
564 public int getFairFileLimit() {
565 return (fairfilelimit);
569 * Get the maximum amount of time spent delivering files before checking if another queue has work to be performed.
571 public long getFairTimeLimit() {
572 return (fairtimelimit);
576 * Get the targets for a feed.
578 * @param feedid The feed ID
579 * @return The targets this feed should be delivered to
581 public Target[] getTargets(String feedid) {
582 return (config.getTargets(feedid));
586 * Get the spool directory for temporary files.
588 public String getSpoolDir() {
589 return (spooldir + "/f");
593 * Get the spool directory for a subscription.
595 public String getSpoolDir(String subid, String remoteaddr) {
596 if (provcheck.isFrom(remoteaddr)) {
597 String sdir = config.getSpoolDir(subid);
599 eelfLogger.info("NODE0310 Received subscription reset request for subscription " + subid
600 + " from provisioning server " + remoteaddr);
602 eelfLogger.info("NODE0311 Received subscription reset request for unknown subscription " + subid
603 + " from provisioning server " + remoteaddr);
607 eelfLogger.info("NODE0312 Received subscription reset request from unexpected server " + remoteaddr);
613 * Get the base directory for spool directories.
615 public String getSpoolBase() {
620 * Get the key store type.
622 public String getKSType() {
627 * Get the key store file.
629 public String getKSFile() {
634 * Get the key store password.
636 public String getKSPass() {
641 * Get the key password.
643 public String getKPass() {
650 public int getHttpPort() {
655 * Get the https port.
657 public int getHttpsPort() {
662 * Get the externally visible https port.
664 public int getExtHttpsPort() {
669 * Get the external name of this machine.
671 public String getMyName() {
676 * Get the number of threads to use for delivery.
678 public int getDeliveryThreads() {
679 return (deliverythreads);
683 * Get the URL for uploading the event log data.
685 public String getEventLogUrl() {
686 return (eventlogurl);
690 * Get the prefix for the names of event log files.
692 public String getEventLogPrefix() {
693 return (eventlogprefix);
697 * Get the suffix for the names of the event log files.
699 public String getEventLogSuffix() {
700 return (eventlogsuffix);
704 * Get the interval between event log file rollovers.
706 public String getEventLogInterval() {
707 return (eventloginterval);
711 * Should I follow redirects from subscribers.
713 public boolean isFollowRedirects() {
714 return (followredirects);
718 * Get the directory where the event and node log files live.
720 public String getLogDir() {
725 * How long do I keep log files (in milliseconds).
727 public long getLogRetention() {
728 return (logretention);
734 public Timer getTimer() {
739 * Get the feed ID for a subscription.
741 * @param subid The subscription ID
742 * @return The feed ID
744 public String getFeedId(String subid) {
745 return (config.getFeedId(subid));
749 * Get the authorization string this node uses.
751 * @return The Authorization string for this node
753 public String getMyAuth() {
754 return (config.getMyAuth());
758 * Get the fraction of free spool disk space where we start throwing away undelivered files. This is
759 * FREE_DISK_RED_PERCENT / 100.0. Default is 0.05. Limited by 0.01 <= FreeDiskStart <= 0.5.
761 public double getFreeDiskStart() {
766 * Get the fraction of free spool disk space where we stop throwing away undelivered files. This is
767 * FREE_DISK_YELLOW_PERCENT / 100.0. Default is 0.2. Limited by FreeDiskStart <= FreeDiskStop <= 0.5.
769 public double getFreeDiskStop() {
774 * Disable and enable protocols.
776 public String[] getEnabledprotocols() {
777 return enabledprotocols;
780 public String getAafType() {
784 public String getAafAction() {
789 * Get aafURL from SWM variable
791 public String getAafURL() {
795 public boolean getCadiEnabled() {
800 * Builds the permissions string to be verified.
802 * @param aafInstance The aaf instance
803 * @return The permissions
805 protected String getPermission(String aafInstance) {
807 String type = getAafType();
808 String action = getAafAction();
809 if ("".equals(aafInstance)) {
810 aafInstance = getAafInstance();
812 return type + "|" + aafInstance + "|" + action;
813 } catch (Exception e) {
814 eelfLogger.error("NODE0543 NodeConfigManager.getPermission: ", e);