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;
29 import org.onap.dmaap.datarouter.node.eelf.EelfMsgs;
32 import java.io.FileInputStream;
33 import java.io.InputStreamReader;
34 import java.io.Reader;
36 import java.util.Properties;
37 import java.util.Timer;
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.
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(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 * Get the default node configuration manager
108 public static NodeConfigManager getInstance() {
113 * Initialize the configuration of a Data Router node
115 private NodeConfigManager() {
117 Properties drNodeProperties = new Properties();
119 eelfLogger.info("NODE0301 Loading local config file node.properties");
120 drNodeProperties.load(new FileInputStream(System
121 .getProperty("org.onap.dmaap.datarouter.node.properties", "/opt/app/datartr/etc/node.properties")));
122 } catch (Exception e) {
123 NodeUtils.setIpAndFqdnForEelf("NodeConfigManager");
124 eelfLogger.error(EelfMsgs.MESSAGE_PROPERTIES_LOAD_ERROR, e, System.getProperty("org.onap.dmaap.datarouter.node.properties", "/opt/app/datartr/etc/node.properties"));
126 provurl = drNodeProperties.getProperty("ProvisioningURL", "https://dmaap-dr-prov:8443/internal/prov");
128 * START - AAF changes: TDP EPIC US# 307413
129 * Pull AAF settings from node.properties
131 aafType = drNodeProperties.getProperty("AAFType", "org.onap.dmaap-dr.feed");
132 aafInstance = drNodeProperties.getProperty("AAFInstance", "legacy");
133 aafAction = drNodeProperties.getProperty("AAFAction", "publish");
134 aafURL = drNodeProperties.getProperty("AafUrl", "https://aaf-onap-test.osaaf.org:8095");
135 cadiEnabled = Boolean.parseBoolean(drNodeProperties.getProperty("CadiEnabled", "false"));
137 * END - AAF changes: TDP EPIC US# 307413
138 * Pull AAF settings from node.properties
140 //Disable and enable protocols*/
141 enabledprotocols = ((drNodeProperties.getProperty("NodeHttpsProtocols")).trim()).split("\\|");
144 provhost = (new URL(provurl)).getHost();
145 } catch (Exception e) {
146 NodeUtils.setIpAndFqdnForEelf("NodeConfigManager");
147 eelfLogger.error(EelfMsgs.MESSAGE_BAD_PROV_URL, e, provurl);
150 eelfLogger.info("NODE0303 Provisioning server is " + provhost);
151 eventlogurl = drNodeProperties.getProperty("LogUploadURL", "https://feeds-drtr.web.att.com/internal/logs");
152 provcheck = new IsFrom(provhost);
153 gfport = Integer.parseInt(drNodeProperties.getProperty("IntHttpPort", "8080"));
154 svcport = Integer.parseInt(drNodeProperties.getProperty("IntHttpsPort", "8443"));
155 port = Integer.parseInt(drNodeProperties.getProperty("ExtHttpsPort", "443"));
156 long minpfinterval = Long.parseLong(drNodeProperties.getProperty("MinProvFetchInterval", "10000"));
157 long minrsinterval = Long.parseLong(drNodeProperties.getProperty("MinRedirSaveInterval", "10000"));
158 spooldir = drNodeProperties.getProperty("SpoolDir", "spool");
159 File fdir = new File(spooldir + "/f");
161 for (File junk : fdir.listFiles()) {
166 logdir = drNodeProperties.getProperty("LogDir", "logs");
167 (new File(logdir)).mkdirs();
168 logretention = Long.parseLong(drNodeProperties.getProperty("LogRetention", "30")) * 86400000L;
169 eventlogprefix = logdir + "/events";
170 eventlogsuffix = ".log";
171 String redirfile = drNodeProperties.getProperty("RedirectionFile", "etc/redirections.dat");
172 kstype = drNodeProperties.getProperty("KeyStoreType", "jks");
173 ksfile = drNodeProperties.getProperty("KeyStoreFile", "etc/keystore");
174 kspass = drNodeProperties.getProperty("KeyStorePassword", "changeme");
175 kpass = drNodeProperties.getProperty("KeyPassword", "changeme");
176 tstype = drNodeProperties.getProperty("TrustStoreType", "jks");
177 tsfile = drNodeProperties.getProperty("TrustStoreFile");
178 tspass = drNodeProperties.getProperty("TrustStorePassword", "changeme");
179 if (tsfile != null && tsfile.length() > 0) {
180 System.setProperty("javax.net.ssl.trustStoreType", tstype);
181 System.setProperty("javax.net.ssl.trustStore", tsfile);
182 System.setProperty("javax.net.ssl.trustStorePassword", tspass);
184 nak = drNodeProperties.getProperty("NodeAuthKey", "Node123!");
185 quiesce = new File(drNodeProperties.getProperty("QuiesceFile", "etc/SHUTDOWN"));
186 myname = NodeUtils.getCanonicalName(kstype, ksfile, kspass);
187 if (myname == null) {
188 NodeUtils.setIpAndFqdnForEelf("NodeConfigManager");
189 eelfLogger.error(EelfMsgs.MESSAGE_KEYSTORE_FETCH_ERROR, ksfile);
190 eelfLogger.error("NODE0309 Unable to fetch canonical name from keystore file " + ksfile);
193 eelfLogger.info("NODE0304 My certificate says my name is " + myname);
194 pid = new PublishId(myname);
195 rdmgr = new RedirManager(redirfile, minrsinterval, timer);
196 pfetcher = new RateLimitedOperation(minpfinterval, timer) {
201 eelfLogger.info("NODE0305 Attempting to fetch configuration at " + provurl);
205 private void localconfig() {
206 followredirects = Boolean.parseBoolean(getProvParam("FOLLOW_REDIRECTS", "false"));
207 eventloginterval = getProvParam("LOGROLL_INTERVAL", "30s");
208 initfailuretimer = 10000;
209 waitForFileProcessFailureTimer = 600000;
210 maxfailuretimer = 3600000;
211 expirationtimer = 86400000;
212 failurebackoff = 2.0;
213 deliverythreads = 40;
215 fairtimelimit = 60000;
219 initfailuretimer = (long) (Double.parseDouble(getProvParam("DELIVERY_INIT_RETRY_INTERVAL")) * 1000);
220 } catch (Exception e) {
221 eelfLogger.error("Error parsing DELIVERY_INIT_RETRY_INTERVAL", e);
224 waitForFileProcessFailureTimer = (long) (Double.parseDouble(getProvParam("DELIVERY_FILE_PROCESS_INTERVAL")) * 1000);
225 } catch (Exception e) {
226 eelfLogger.error("Error parsing DELIVERY_FILE_PROCESS_INTERVAL", e);
229 maxfailuretimer = (long) (Double.parseDouble(getProvParam("DELIVERY_MAX_RETRY_INTERVAL")) * 1000);
230 } catch (Exception e) {
231 eelfLogger.error("Error parsing DELIVERY_MAX_RETRY_INTERVAL", e);
234 expirationtimer = (long) (Double.parseDouble(getProvParam("DELIVERY_MAX_AGE")) * 1000);
235 } catch (Exception e) {
236 eelfLogger.error("Error parsing DELIVERY_MAX_AGE", e);
239 failurebackoff = Double.parseDouble(getProvParam("DELIVERY_RETRY_RATIO"));
240 } catch (Exception e) {
241 eelfLogger.error("Error parsing DELIVERY_RETRY_RATIO", e);
244 deliverythreads = Integer.parseInt(getProvParam("DELIVERY_THREADS"));
245 } catch (Exception e) {
246 eelfLogger.error("Error parsing DELIVERY_THREADS", e);
249 fairfilelimit = Integer.parseInt(getProvParam("FAIR_FILE_LIMIT"));
250 } catch (Exception e) {
251 eelfLogger.error("Error parsing FAIR_FILE_LIMIT", e);
254 fairtimelimit = (long) (Double.parseDouble(getProvParam("FAIR_TIME_LIMIT")) * 1000);
255 } catch (Exception e) {
256 eelfLogger.error("Error parsing FAIR_TIME_LIMIT", e);
259 fdpstart = Double.parseDouble(getProvParam("FREE_DISK_RED_PERCENT")) / 100.0;
260 } catch (Exception e) {
261 eelfLogger.error("Error parsing FREE_DISK_RED_PERCENT", e);
264 fdpstop = Double.parseDouble(getProvParam("FREE_DISK_YELLOW_PERCENT")) / 100.0;
265 } catch (Exception e) {
266 eelfLogger.error("Error parsing FREE_DISK_YELLOW_PERCENT", e);
268 if (fdpstart < 0.01) {
271 if (fdpstart > 0.5) {
274 if (fdpstop < fdpstart) {
282 private void fetchconfig() {
284 eelfLogger.info("NodeConfigMan.fetchConfig: provurl:: " + provurl);
285 Reader r = new InputStreamReader((new URL(provurl)).openStream());
286 config = new NodeConfig(new ProvData(r), myname, spooldir, port, nak);
288 configtasks.startRun();
290 while ((rr = configtasks.next()) != null) {
293 } catch (Exception e) {
294 eelfLogger.error("NODE0518 Exception fetchconfig: " + e);
297 } catch (Exception e) {
298 NodeUtils.setIpAndFqdnForEelf("fetchconfigs");
299 eelfLogger.error(EelfMsgs.MESSAGE_CONF_FAILED, e.toString());
300 eelfLogger.error("NODE0306 Configuration failed " + e.toString() + " - try again later", e);
306 * Process a gofetch request from a particular IP address. If the IP address is not an IP address we would go to to
307 * fetch the provisioning data, ignore the request. If the data has been fetched very recently (default 10
308 * seconds), wait a while before fetching again.
310 public synchronized void gofetch(String remoteAddr) {
311 if (provcheck.isReachable(remoteAddr)) {
312 eelfLogger.info("NODE0307 Received configuration fetch request from provisioning server " + remoteAddr);
315 eelfLogger.info("NODE0308 Received configuration fetch request from unexpected server " + remoteAddr);
322 public boolean isConfigured() {
323 return (config != null);
329 public boolean isShutdown() {
330 return (quiesce.exists());
334 * Given a routing string, get the targets.
336 * @param routing Target string
337 * @return array of targets
339 public Target[] parseRouting(String routing) {
340 return (config.parseRouting(routing));
344 * Given a set of credentials and an IP address, is this request from another node?
346 * @param credentials Credentials offered by the supposed node
347 * @param ip IP address the request came from
348 * @return If the credentials and IP address are recognized, true, otherwise false.
350 public boolean isAnotherNode(String credentials, String ip) {
351 return (config.isAnotherNode(credentials, ip));
355 * Check whether publication is allowed.
357 * @param feedid The ID of the feed being requested
358 * @param credentials The offered credentials
359 * @param ip The requesting IP address
360 * @return True if the IP and credentials are valid for the specified feed.
362 public String isPublishPermitted(String feedid, String credentials, String ip) {
363 return (config.isPublishPermitted(feedid, credentials, ip));
367 * Check whether delete file is allowed.
369 * @param subId The ID of the subscription being requested
370 * @return True if the delete file is permitted for the subscriber.
372 public boolean isDeletePermitted(String subId) {
373 return (config.isDeletePermitted(subId));
377 * Check whether publication is allowed for AAF Feed.
379 * @param feedid The ID of the feed being requested
380 * @param ip The requesting IP address
381 * @return True if the IP and credentials are valid for the specified feed.
383 public String isPublishPermitted(String feedid, String ip) {
384 return(config.isPublishPermitted(feedid, ip));
388 * Check who the user is given the feed ID and the offered credentials.
390 * @param feedid The ID of the feed specified
391 * @param credentials The offered credentials
392 * @return Null if the credentials are invalid or the user if they are valid.
394 public String getAuthUser(String feedid, String credentials) {
395 return (config.getAuthUser(feedid, credentials));
399 * AAF changes: TDP EPIC US# 307413
400 * Check AAF_instance for feed ID in NodeConfig
401 * @param feedid The ID of the feed specified
403 public String getAafInstance(String feedid) {
404 return(config.getAafInstance(feedid));
408 * Check if the publish request should be sent to another node based on the feedid, user, and source IP address.
410 * @param feedid The ID of the feed specified
411 * @param user The publishing user
412 * @param ip The IP address of the publish endpoint
413 * @return Null if the request should be accepted or the correct hostname if it should be sent to another node.
415 public String getIngressNode(String feedid, String user, String ip) {
416 return (config.getIngressNode(feedid, user, ip));
420 * Get a provisioned configuration parameter (from the provisioning server configuration)
422 * @param name The name of the parameter
423 * @return The value of the parameter or null if it is not defined.
425 public String getProvParam(String name) {
426 return (config.getProvParam(name));
430 * Get a provisioned configuration parameter (from the provisioning server configuration)
432 * @param name The name of the parameter
433 * @param defaultValue The value to use if the parameter is not defined
434 * @return The value of the parameter or deflt if it is not defined.
436 public String getProvParam(String name, String defaultValue) {
437 name = config.getProvParam(name);
445 * Generate a publish ID
447 public String getPublishId() {
452 * Get all the outbound spooling destinations. This will include both subscriptions and nodes.
454 public DestInfo[] getAllDests() {
455 return (config.getAllDests());
459 * Register a task to run whenever the configuration changes
461 public void registerConfigTask(Runnable task) {
462 configtasks.addTask(task);
466 * Deregister a task to run whenever the configuration changes
468 public void deregisterConfigTask(Runnable task) {
469 configtasks.removeTask(task);
473 * Get the URL to deliver a message to.
475 * @param destinationInfo The destination information
476 * @param fileid The file ID
477 * @return The URL to deliver to
479 public String getDestURL(DestInfo destinationInfo, String fileid) {
480 String subid = destinationInfo.getSubId();
481 String purl = destinationInfo.getURL();
482 if (followredirects && subid != null) {
483 purl = rdmgr.lookup(subid, purl);
485 return (purl + "/" + fileid);
489 * Is a destination redirected?
491 public boolean isDestRedirected(DestInfo destinfo) {
492 return (followredirects && rdmgr.isRedirected(destinfo.getSubId()));
496 * Set up redirection on receipt of a 3XX from a target URL
498 public boolean handleRedirection(DestInfo destinationInfo, String redirto, String fileid) {
499 fileid = "/" + fileid;
500 String subid = destinationInfo.getSubId();
501 String purl = destinationInfo.getURL();
502 if (followredirects && subid != null && redirto.endsWith(fileid)) {
503 redirto = redirto.substring(0, redirto.length() - fileid.length());
504 if (!redirto.equals(purl)) {
505 rdmgr.redirect(subid, purl, redirto);
513 * Set up redirection on receipt of a 3XX from a target URL
515 public boolean handleRedirectionSubLevel(DeliveryTask task, DestInfo destinfo, String redirto, String fileid) {
516 fileid = "/" + fileid;
517 String subid = destinfo.getSubId();
518 String purl = destinfo.getURL();
519 if (task.getFollowRedirects() && subid != null && redirto.endsWith(fileid)) {
520 redirto = redirto.substring(0, redirto.length() - fileid.length());
521 if (!redirto.equals(purl)) {
522 rdmgr.redirect(subid, purl, redirto);
530 * Handle unreachable target URL
532 public void handleUnreachable(DestInfo destinationInfo) {
533 String subid = destinationInfo.getSubId();
534 if (followredirects && subid != null) {
540 * Get the timeout before retrying after an initial delivery failure
542 public long getInitFailureTimer() {
543 return (initfailuretimer);
547 * Get the timeout before retrying after delivery and wait for file processing
549 public long getWaitForFileProcessFailureTimer() {
550 return (waitForFileProcessFailureTimer);
554 * Get the maximum timeout between delivery attempts
556 public long getMaxFailureTimer() {
557 return (maxfailuretimer);
561 * Get the ratio between consecutive delivery attempts
563 public double getFailureBackoff() {
564 return (failurebackoff);
568 * Get the expiration timer for deliveries
570 public long getExpirationTimer() {
571 return (expirationtimer);
575 * Get the maximum number of file delivery attempts before checking if another queue has work to be performed.
577 public int getFairFileLimit() {
578 return (fairfilelimit);
582 * Get the maximum amount of time spent delivering files before checking if another queue has work to be performed.
584 public long getFairTimeLimit() {
585 return (fairtimelimit);
589 * Get the targets for a feed
591 * @param feedid The feed ID
592 * @return The targets this feed should be delivered to
594 public Target[] getTargets(String feedid) {
595 return (config.getTargets(feedid));
599 * Get the creation date for a feed
600 * @param feedid The feed ID
601 * @return the timestamp of creation date of feed id passed
603 public String getCreatedDate(String feedid) {
604 return(config.getCreatedDate(feedid));
608 * Get the spool directory for temporary files
610 public String getSpoolDir() {
611 return (spooldir + "/f");
615 * Get the base directory for spool directories
617 public String getSpoolBase() {
622 * Get the key store type
624 public String getKSType() {
629 * Get the key store file
631 public String getKSFile() {
636 * Get the key store password
638 public String getKSPass() {
643 * Get the key password
645 public String getKPass() {
652 public int getHttpPort() {
659 public int getHttpsPort() {
664 * Get the externally visible https port
666 public int getExtHttpsPort() {
671 * Get the external name of this machine
673 public String getMyName() {
678 * Get the number of threads to use for delivery
680 public int getDeliveryThreads() {
681 return (deliverythreads);
685 * Get the URL for uploading the event log data
687 public String getEventLogUrl() {
688 return (eventlogurl);
692 * Get the prefix for the names of event log files
694 public String getEventLogPrefix() {
695 return (eventlogprefix);
699 * Get the suffix for the names of the event log files
701 public String getEventLogSuffix() {
702 return (eventlogsuffix);
706 * Get the interval between event log file rollovers
708 public String getEventLogInterval() {
709 return (eventloginterval);
713 * Should I follow redirects from subscribers?
715 public boolean isFollowRedirects() {
716 return (followredirects);
720 * Get the directory where the event and node log files live
722 public String getLogDir() {
727 * How long do I keep log files (in milliseconds)
729 public long getLogRetention() {
730 return (logretention);
736 public Timer getTimer() {
741 * Get the feed ID for a subscription
743 * @param subid The subscription ID
744 * @return The feed ID
746 public String getFeedId(String subid) {
747 return (config.getFeedId(subid));
751 * Get the authorization string this node uses
753 * @return The Authorization string for this node
755 public String getMyAuth() {
756 return (config.getMyAuth());
760 * Get the fraction of free spool disk space where we start throwing away undelivered files. This is
761 * FREE_DISK_RED_PERCENT / 100.0. Default is 0.05. Limited by 0.01 <= FreeDiskStart <= 0.5.
763 public double getFreeDiskStart() {
768 * Get the fraction of free spool disk space where we stop throwing away undelivered files. This is
769 * FREE_DISK_YELLOW_PERCENT / 100.0. Default is 0.2. Limited by FreeDiskStart <= FreeDiskStop <= 0.5.
771 public double getFreeDiskStop() {
776 * Disable and enable protocols
778 public String[] getEnabledprotocols() {
779 return enabledprotocols;
781 public void setEnabledprotocols(String[] enabledprotocols) {
782 this.enabledprotocols = enabledprotocols.clone();
786 * Get the spool directory for a subscription
788 public String getSpoolDir(String subid, String remoteaddr) {
789 if (provcheck.isFrom(remoteaddr)) {
790 String sdir = config.getSpoolDir(subid);
792 eelfLogger.info("NODE0310 Received subscription reset request for subscription " + subid
793 + " from provisioning server " + remoteaddr);
795 eelfLogger.info("NODE0311 Received subscription reset request for unknown subscription " + subid
796 + " from provisioning server " + remoteaddr);
800 eelfLogger.info("NODE0312 Received subscription reset request from unexpected server " + remoteaddr);
805 public String getAafType() {
808 public void setAafType(String aafType) {
809 this.aafType = aafType;
811 public String getAafInstance() {
814 public void setAafInstance(String aafInstance) {
815 this.aafInstance = aafInstance;
817 public String getAafAction() {
820 public void setAafAction(String aafAction) {
821 this.aafAction = aafAction;
824 * Get aafURL from SWM variable
826 public String getAafURL() {
829 public void setAafURL(String aafURL) {
830 this.aafURL = aafURL;
833 public boolean getCadiEnabeld() {
836 public void setCadiEnabled(boolean cadiEnabled) {
837 this.cadiEnabled = cadiEnabled;
841 * Builds the permissions string to be verified
843 * @param aafInstance The aaf instance
844 * @return The permissions
846 protected String getPermission(String aafInstance) {
848 String type = getAafType();
849 String action = getAafAction();
850 if (aafInstance == null || aafInstance.equals("")) {
851 aafInstance = getAafInstance();
853 return type + "|" + aafInstance + "|" + action;
854 } catch (Exception e) {
855 eelfLogger.error("NODE0543 NodeConfigManager.getPermission: ", e);