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, 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, 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) {
223 waitForFileProcessFailureTimer = (long) (Double.parseDouble(getProvParam("DELIVERY_FILE_PROCESS_INTERVAL")) * 1000);
224 } catch (Exception e) {
227 maxfailuretimer = (long) (Double.parseDouble(getProvParam("DELIVERY_MAX_RETRY_INTERVAL")) * 1000);
228 } catch (Exception e) {
231 expirationtimer = (long) (Double.parseDouble(getProvParam("DELIVERY_MAX_AGE")) * 1000);
232 } catch (Exception e) {
235 failurebackoff = Double.parseDouble(getProvParam("DELIVERY_RETRY_RATIO"));
236 } catch (Exception e) {
239 deliverythreads = Integer.parseInt(getProvParam("DELIVERY_THREADS"));
240 } catch (Exception e) {
243 fairfilelimit = Integer.parseInt(getProvParam("FAIR_FILE_LIMIT"));
244 } catch (Exception e) {
247 fairtimelimit = (long) (Double.parseDouble(getProvParam("FAIR_TIME_LIMIT")) * 1000);
248 } catch (Exception e) {
251 fdpstart = Double.parseDouble(getProvParam("FREE_DISK_RED_PERCENT")) / 100.0;
252 } catch (Exception e) {
255 fdpstop = Double.parseDouble(getProvParam("FREE_DISK_YELLOW_PERCENT")) / 100.0;
256 } catch (Exception e) {
258 if (fdpstart < 0.01) {
261 if (fdpstart > 0.5) {
264 if (fdpstop < fdpstart) {
272 private void fetchconfig() {
274 eelfLogger.info("NodeConfigMan.fetchConfig: provurl:: " + provurl);
275 Reader r = new InputStreamReader((new URL(provurl)).openStream());
276 config = new NodeConfig(new ProvData(r), myname, spooldir, port, nak);
278 configtasks.startRun();
280 while ((rr = configtasks.next()) != null) {
283 } catch (Exception e) {
284 eelfLogger.error("NODE0518 Exception fetchconfig: " + e);
287 } catch (Exception e) {
288 NodeUtils.setIpAndFqdnForEelf("fetchconfigs");
289 eelfLogger.error(EelfMsgs.MESSAGE_CONF_FAILED, e.toString());
290 eelfLogger.error("NODE0306 Configuration failed " + e.toString() + " - try again later", e.getMessage());
296 * Process a gofetch request from a particular IP address. If the IP address is not an IP address we would go to to
297 * fetch the provisioning data, ignore the request. If the data has been fetched very recently (default 10
298 * seconds), wait a while before fetching again.
300 public synchronized void gofetch(String remoteAddr) {
301 if (provcheck.isReachable(remoteAddr)) {
302 eelfLogger.info("NODE0307 Received configuration fetch request from provisioning server " + remoteAddr);
305 eelfLogger.info("NODE0308 Received configuration fetch request from unexpected server " + remoteAddr);
312 public boolean isConfigured() {
313 return (config != null);
319 public boolean isShutdown() {
320 return (quiesce.exists());
324 * Given a routing string, get the targets.
326 * @param routing Target string
327 * @return array of targets
329 public Target[] parseRouting(String routing) {
330 return (config.parseRouting(routing));
334 * Given a set of credentials and an IP address, is this request from another node?
336 * @param credentials Credentials offered by the supposed node
337 * @param ip IP address the request came from
338 * @return If the credentials and IP address are recognized, true, otherwise false.
340 public boolean isAnotherNode(String credentials, String ip) {
341 return (config.isAnotherNode(credentials, ip));
345 * Check whether publication is allowed.
347 * @param feedid The ID of the feed being requested
348 * @param credentials The offered credentials
349 * @param ip The requesting IP address
350 * @return True if the IP and credentials are valid for the specified feed.
352 public String isPublishPermitted(String feedid, String credentials, String ip) {
353 return (config.isPublishPermitted(feedid, credentials, ip));
357 * Check whether delete file is allowed.
359 * @param subId The ID of the subscription being requested
360 * @return True if the delete file is permitted for the subscriber.
362 public boolean isDeletePermitted(String subId) {
363 return (config.isDeletePermitted(subId));
367 * Check whether publication is allowed for AAF Feed.
369 * @param feedid The ID of the feed being requested
370 * @param ip The requesting IP address
371 * @return True if the IP and credentials are valid for the specified feed.
373 public String isPublishPermitted(String feedid, String ip) {
374 return(config.isPublishPermitted(feedid, ip));
378 * Check who the user is given the feed ID and the offered credentials.
380 * @param feedid The ID of the feed specified
381 * @param credentials The offered credentials
382 * @return Null if the credentials are invalid or the user if they are valid.
384 public String getAuthUser(String feedid, String credentials) {
385 return (config.getAuthUser(feedid, credentials));
389 * AAF changes: TDP EPIC US# 307413
390 * Check AAF_instance for feed ID in NodeConfig
391 * @param feedid The ID of the feed specified
393 public String getAafInstance(String feedid) {
394 return(config.getAafInstance(feedid));
398 * Check if the publish request should be sent to another node based on the feedid, user, and source IP address.
400 * @param feedid The ID of the feed specified
401 * @param user The publishing user
402 * @param ip The IP address of the publish endpoint
403 * @return Null if the request should be accepted or the correct hostname if it should be sent to another node.
405 public String getIngressNode(String feedid, String user, String ip) {
406 return (config.getIngressNode(feedid, user, ip));
410 * Get a provisioned configuration parameter (from the provisioning server configuration)
412 * @param name The name of the parameter
413 * @return The value of the parameter or null if it is not defined.
415 public String getProvParam(String name) {
416 return (config.getProvParam(name));
420 * Get a provisioned configuration parameter (from the provisioning server configuration)
422 * @param name The name of the parameter
423 * @param defaultValue The value to use if the parameter is not defined
424 * @return The value of the parameter or deflt if it is not defined.
426 public String getProvParam(String name, String defaultValue) {
427 name = config.getProvParam(name);
435 * Generate a publish ID
437 public String getPublishId() {
442 * Get all the outbound spooling destinations. This will include both subscriptions and nodes.
444 public DestInfo[] getAllDests() {
445 return (config.getAllDests());
449 * Register a task to run whenever the configuration changes
451 public void registerConfigTask(Runnable task) {
452 configtasks.addTask(task);
456 * Deregister a task to run whenever the configuration changes
458 public void deregisterConfigTask(Runnable task) {
459 configtasks.removeTask(task);
463 * Get the URL to deliver a message to.
465 * @param destinationInfo The destination information
466 * @param fileid The file ID
467 * @return The URL to deliver to
469 public String getDestURL(DestInfo destinationInfo, String fileid) {
470 String subid = destinationInfo.getSubId();
471 String purl = destinationInfo.getURL();
472 if (followredirects && subid != null) {
473 purl = rdmgr.lookup(subid, purl);
475 return (purl + "/" + fileid);
479 * Is a destination redirected?
481 public boolean isDestRedirected(DestInfo destinfo) {
482 return (followredirects && rdmgr.isRedirected(destinfo.getSubId()));
486 * Set up redirection on receipt of a 3XX from a target URL
488 public boolean handleRedirection(DestInfo destinationInfo, String redirto, String fileid) {
489 fileid = "/" + fileid;
490 String subid = destinationInfo.getSubId();
491 String purl = destinationInfo.getURL();
492 if (followredirects && subid != null && redirto.endsWith(fileid)) {
493 redirto = redirto.substring(0, redirto.length() - fileid.length());
494 if (!redirto.equals(purl)) {
495 rdmgr.redirect(subid, purl, redirto);
503 * Set up redirection on receipt of a 3XX from a target URL
505 public boolean handleRedirectionSubLevel(DeliveryTask task, DestInfo destinfo, String redirto, String fileid) {
506 fileid = "/" + fileid;
507 String subid = destinfo.getSubId();
508 String purl = destinfo.getURL();
509 if (task.getFollowRedirects() && subid != null && redirto.endsWith(fileid)) {
510 redirto = redirto.substring(0, redirto.length() - fileid.length());
511 if (!redirto.equals(purl)) {
512 rdmgr.redirect(subid, purl, redirto);
520 * Handle unreachable target URL
522 public void handleUnreachable(DestInfo destinationInfo) {
523 String subid = destinationInfo.getSubId();
524 if (followredirects && subid != null) {
530 * Get the timeout before retrying after an initial delivery failure
532 public long getInitFailureTimer() {
533 return (initfailuretimer);
537 * Get the timeout before retrying after delivery and wait for file processing
539 public long getWaitForFileProcessFailureTimer() {
540 return (waitForFileProcessFailureTimer);
544 * Get the maximum timeout between delivery attempts
546 public long getMaxFailureTimer() {
547 return (maxfailuretimer);
551 * Get the ratio between consecutive delivery attempts
553 public double getFailureBackoff() {
554 return (failurebackoff);
558 * Get the expiration timer for deliveries
560 public long getExpirationTimer() {
561 return (expirationtimer);
565 * Get the maximum number of file delivery attempts before checking if another queue has work to be performed.
567 public int getFairFileLimit() {
568 return (fairfilelimit);
572 * Get the maximum amount of time spent delivering files before checking if another queue has work to be performed.
574 public long getFairTimeLimit() {
575 return (fairtimelimit);
579 * Get the targets for a feed
581 * @param feedid The feed ID
582 * @return The targets this feed should be delivered to
584 public Target[] getTargets(String feedid) {
585 return (config.getTargets(feedid));
589 * Get the creation date for a feed
590 * @param feedid The feed ID
591 * @return the timestamp of creation date of feed id passed
593 public String getCreatedDate(String feedid) {
594 return(config.getCreatedDate(feedid));
598 * Get the spool directory for temporary files
600 public String getSpoolDir() {
601 return (spooldir + "/f");
605 * Get the base directory for spool directories
607 public String getSpoolBase() {
612 * Get the key store type
614 public String getKSType() {
619 * Get the key store file
621 public String getKSFile() {
626 * Get the key store password
628 public String getKSPass() {
633 * Get the key password
635 public String getKPass() {
642 public int getHttpPort() {
649 public int getHttpsPort() {
654 * Get the externally visible https port
656 public int getExtHttpsPort() {
661 * Get the external name of this machine
663 public String getMyName() {
668 * Get the number of threads to use for delivery
670 public int getDeliveryThreads() {
671 return (deliverythreads);
675 * Get the URL for uploading the event log data
677 public String getEventLogUrl() {
678 return (eventlogurl);
682 * Get the prefix for the names of event log files
684 public String getEventLogPrefix() {
685 return (eventlogprefix);
689 * Get the suffix for the names of the event log files
691 public String getEventLogSuffix() {
692 return (eventlogsuffix);
696 * Get the interval between event log file rollovers
698 public String getEventLogInterval() {
699 return (eventloginterval);
703 * Should I follow redirects from subscribers?
705 public boolean isFollowRedirects() {
706 return (followredirects);
710 * Get the directory where the event and node log files live
712 public String getLogDir() {
717 * How long do I keep log files (in milliseconds)
719 public long getLogRetention() {
720 return (logretention);
726 public Timer getTimer() {
731 * Get the feed ID for a subscription
733 * @param subid The subscription ID
734 * @return The feed ID
736 public String getFeedId(String subid) {
737 return (config.getFeedId(subid));
741 * Get the authorization string this node uses
743 * @return The Authorization string for this node
745 public String getMyAuth() {
746 return (config.getMyAuth());
750 * Get the fraction of free spool disk space where we start throwing away undelivered files. This is
751 * FREE_DISK_RED_PERCENT / 100.0. Default is 0.05. Limited by 0.01 <= FreeDiskStart <= 0.5.
753 public double getFreeDiskStart() {
758 * Get the fraction of free spool disk space where we stop throwing away undelivered files. This is
759 * FREE_DISK_YELLOW_PERCENT / 100.0. Default is 0.2. Limited by FreeDiskStart <= FreeDiskStop <= 0.5.
761 public double getFreeDiskStop() {
766 * Disable and enable protocols
768 public String[] getEnabledprotocols() {
769 return enabledprotocols;
771 public void setEnabledprotocols(String[] enabledprotocols) {
772 this.enabledprotocols = enabledprotocols.clone();
776 * Get the spool directory for a subscription
778 public String getSpoolDir(String subid, String remoteaddr) {
779 if (provcheck.isFrom(remoteaddr)) {
780 String sdir = config.getSpoolDir(subid);
782 eelfLogger.info("NODE0310 Received subscription reset request for subscription " + subid
783 + " from provisioning server " + remoteaddr);
785 eelfLogger.info("NODE0311 Received subscription reset request for unknown subscription " + subid
786 + " from provisioning server " + remoteaddr);
790 eelfLogger.info("NODE0312 Received subscription reset request from unexpected server " + remoteaddr);
795 public String getAafType() {
798 public void setAafType(String aafType) {
799 this.aafType = aafType;
801 public String getAafInstance() {
804 public void setAafInstance(String aafInstance) {
805 this.aafInstance = aafInstance;
807 public String getAafAction() {
810 public void setAafAction(String aafAction) {
811 this.aafAction = aafAction;
814 * Get aafURL from SWM variable
816 public String getAafURL() {
819 public void setAafURL(String aafURL) {
820 this.aafURL = aafURL;
823 public boolean getCadiEnabeld() {
826 public void setCadiEnabled(boolean cadiEnabled) {
827 this.cadiEnabled = cadiEnabled;
831 * Builds the permissions string to be verified
833 * @param aafInstance The aaf instance
834 * @return The permissions
836 protected String getPermission(String aafInstance) {
838 String type = getAafType();
839 String action = getAafAction();
840 if (aafInstance == null || aafInstance.equals("")) {
841 aafInstance = getAafInstance();
843 return type + "|" + aafInstance + "|" + action;
844 } catch (Exception e) {
845 eelfLogger.error("NODE0543 NodeConfigManager.getPermission: ", e.getMessage());