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 static java.lang.System.exit;
29 import com.att.eelf.configuration.EELFLogger;
30 import com.att.eelf.configuration.EELFManager;
32 import java.io.FileInputStream;
33 import java.io.IOException;
34 import java.io.InputStreamReader;
35 import java.io.Reader;
37 import java.nio.file.Files;
38 import java.util.Objects;
39 import java.util.Properties;
40 import java.util.Timer;
41 import org.onap.dmaap.datarouter.node.eelf.EelfMsgs;
45 * Maintain the configuration of a Data Router node
47 * <p>The NodeConfigManager is the single point of contact for servlet, delivery, event logging, and log retention
48 * subsystems to access configuration information.
50 * <p>There are two basic sets of configuration data. The static local configuration data, stored in a local
51 * configuration file (created as part of installation by SWM), and the dynamic global configuration data fetched from
52 * the data router provisioning server.
54 public class NodeConfigManager implements DeliveryQueueHelper {
56 private static final String NODE_CONFIG_MANAGER = "NodeConfigManager";
57 private static EELFLogger eelfLogger = EELFManager.getInstance().getLogger(NodeConfigManager.class);
58 private static NodeConfigManager base = new NodeConfigManager();
60 private Timer timer = new Timer("Node Configuration Timer", true);
61 private long maxfailuretimer;
62 private long initfailuretimer;
63 private long waitForFileProcessFailureTimer;
64 private long expirationtimer;
65 private double failurebackoff;
66 private long fairtimelimit;
67 private int fairfilelimit;
68 private double fdpstart;
69 private double fdpstop;
70 private int deliverythreads;
71 private String provurl;
72 private String provhost;
73 private IsFrom provcheck;
77 private String spooldir;
78 private String logdir;
79 private long logretention;
80 private String redirfile;
81 private String kstype;
82 private String ksfile;
83 private String kspass;
85 private String tstype;
86 private String tsfile;
87 private String tspass;
88 private String myname;
89 private RedirManager rdmgr;
90 private RateLimitedOperation pfetcher;
91 private NodeConfig config;
93 private PublishId pid;
95 private TaskList configtasks = new TaskList();
96 private String eventlogurl;
97 private String eventlogprefix;
98 private String eventlogsuffix;
99 private String eventloginterval;
100 private boolean followredirects;
101 private String[] enabledprotocols;
102 private String aafType;
103 private String aafInstance;
104 private String aafAction;
105 private boolean cadiEnabled;
106 private NodeAafPropsUtils nodeAafPropsUtils;
110 * Initialize the configuration of a Data Router node.
112 private NodeConfigManager() {
114 Properties drNodeProperties = new Properties();
115 try (FileInputStream fileInputStream = new FileInputStream(System
116 .getProperty("org.onap.dmaap.datarouter.node.properties", "/opt/app/datartr/etc/node.properties"))) {
117 eelfLogger.debug("NODE0301 Loading local config file node.properties");
118 drNodeProperties.load(fileInputStream);
119 } catch (Exception e) {
120 NodeUtils.setIpAndFqdnForEelf(NODE_CONFIG_MANAGER);
121 eelfLogger.error(EelfMsgs.MESSAGE_PROPERTIES_LOAD_ERROR, e,
122 System.getProperty("org.onap.dmaap.datarouter.node.properties",
123 "/opt/app/datartr/etc/node.properties"));
125 provurl = drNodeProperties.getProperty("ProvisioningURL", "https://dmaap-dr-prov:8443/internal/prov");
126 String aafPropsFilePath = drNodeProperties
127 .getProperty("AAFPropsFilePath", "/opt/app/osaaf/local/org.onap.dmaap-dr.props");
129 nodeAafPropsUtils = new NodeAafPropsUtils(new File(aafPropsFilePath));
130 } catch (IOException e) {
131 eelfLogger.error("NODE0314 Failed to load AAF props. Exiting", e);
135 * START - AAF changes: TDP EPIC US# 307413
136 * Pull AAF settings from node.properties
138 aafType = drNodeProperties.getProperty("AAFType", "org.onap.dmaap-dr.feed");
139 aafInstance = drNodeProperties.getProperty("AAFInstance", "legacy");
140 aafAction = drNodeProperties.getProperty("AAFAction", "publish");
141 cadiEnabled = Boolean.parseBoolean(drNodeProperties.getProperty("CadiEnabled", "false"));
143 * END - AAF changes: TDP EPIC US# 307413
144 * Pull AAF settings from node.properties
146 //Disable and enable protocols*/
147 enabledprotocols = ((drNodeProperties.getProperty("NodeHttpsProtocols")).trim()).split("\\|");
149 provhost = (new URL(provurl)).getHost();
150 } catch (Exception e) {
151 NodeUtils.setIpAndFqdnForEelf(NODE_CONFIG_MANAGER);
152 eelfLogger.error(EelfMsgs.MESSAGE_BAD_PROV_URL, e, provurl);
155 eelfLogger.debug("NODE0303 Provisioning server is " + provhost);
156 eventlogurl = drNodeProperties.getProperty("LogUploadURL", "https://feeds-drtr.web.att.com/internal/logs");
157 provcheck = new IsFrom(provhost);
158 gfport = Integer.parseInt(drNodeProperties.getProperty("IntHttpPort", "8080"));
159 svcport = Integer.parseInt(drNodeProperties.getProperty("IntHttpsPort", "8443"));
160 port = Integer.parseInt(drNodeProperties.getProperty("ExtHttpsPort", "443"));
161 spooldir = drNodeProperties.getProperty("SpoolDir", "spool");
162 File fdir = new File(spooldir + "/f");
164 for (File junk : Objects.requireNonNull(fdir.listFiles())) {
166 Files.deleteIfExists(junk.toPath());
167 } catch (IOException e) {
168 eelfLogger.error("NODE0313 Failed to clear junk files from " + fdir.getPath(), e);
171 logdir = drNodeProperties.getProperty("LogDir", "logs");
172 (new File(logdir)).mkdirs();
173 logretention = Long.parseLong(drNodeProperties.getProperty("LogRetention", "30")) * 86400000L;
174 eventlogprefix = logdir + "/events";
175 eventlogsuffix = ".log";
176 redirfile = drNodeProperties.getProperty("RedirectionFile", "etc/redirections.dat");
177 kstype = drNodeProperties.getProperty("KeyStoreType", "PKCS12");
178 ksfile = nodeAafPropsUtils.getPropAccess().getProperty("cadi_keystore");
179 kspass = nodeAafPropsUtils.getDecryptedPass("cadi_keystore_password");
180 kpass = nodeAafPropsUtils.getDecryptedPass("cadi_keystore_password");
181 tstype = drNodeProperties.getProperty("TrustStoreType", "jks");
182 tsfile = nodeAafPropsUtils.getPropAccess().getProperty("cadi_truststore");
183 tspass = nodeAafPropsUtils.getDecryptedPass("cadi_truststore_password");
184 if (tsfile != null && tsfile.length() > 0) {
185 System.setProperty("javax.net.ssl.trustStoreType", tstype);
186 System.setProperty("javax.net.ssl.trustStore", tsfile);
187 System.setProperty("javax.net.ssl.trustStorePassword", tspass);
189 nak = drNodeProperties.getProperty("NodeAuthKey", "Node123!");
190 quiesce = new File(drNodeProperties.getProperty("QuiesceFile", "etc/SHUTDOWN"));
191 myname = NodeUtils.getCanonicalName(kstype, ksfile, kspass);
192 if (myname == null) {
193 NodeUtils.setIpAndFqdnForEelf(NODE_CONFIG_MANAGER);
194 eelfLogger.error(EelfMsgs.MESSAGE_KEYSTORE_FETCH_ERROR, ksfile);
195 eelfLogger.error("NODE0309 Unable to fetch canonical name from keystore file " + ksfile);
198 eelfLogger.debug("NODE0304 My certificate says my name is " + myname);
199 pid = new PublishId(myname);
200 long minrsinterval = Long.parseLong(drNodeProperties.getProperty("MinRedirSaveInterval", "10000"));
201 long minpfinterval = Long.parseLong(drNodeProperties.getProperty("MinProvFetchInterval", "10000"));
202 rdmgr = new RedirManager(redirfile, minrsinterval, timer);
203 pfetcher = new RateLimitedOperation(minpfinterval, timer) {
208 eelfLogger.debug("NODE0305 Attempting to fetch configuration at " + provurl);
213 * Get the default node configuration manager.
215 public static NodeConfigManager getInstance() {
219 private void localconfig() {
220 followredirects = Boolean.parseBoolean(getProvParam("FOLLOW_REDIRECTS", "false"));
221 eventloginterval = getProvParam("LOGROLL_INTERVAL", "30s");
222 initfailuretimer = 10000;
223 waitForFileProcessFailureTimer = 600000;
224 maxfailuretimer = 3600000;
225 expirationtimer = 86400000;
226 failurebackoff = 2.0;
227 deliverythreads = 40;
229 fairtimelimit = 60000;
233 initfailuretimer = (long) (Double.parseDouble(getProvParam("DELIVERY_INIT_RETRY_INTERVAL")) * 1000);
234 } catch (Exception e) {
235 eelfLogger.trace("Error parsing DELIVERY_INIT_RETRY_INTERVAL", e);
238 waitForFileProcessFailureTimer = (long) (Double.parseDouble(getProvParam("DELIVERY_FILE_PROCESS_INTERVAL"))
240 } catch (Exception e) {
241 eelfLogger.trace("Error parsing DELIVERY_FILE_PROCESS_INTERVAL", e);
244 maxfailuretimer = (long) (Double.parseDouble(getProvParam("DELIVERY_MAX_RETRY_INTERVAL")) * 1000);
245 } catch (Exception e) {
246 eelfLogger.trace("Error parsing DELIVERY_MAX_RETRY_INTERVAL", e);
249 expirationtimer = (long) (Double.parseDouble(getProvParam("DELIVERY_MAX_AGE")) * 1000);
250 } catch (Exception e) {
251 eelfLogger.trace("Error parsing DELIVERY_MAX_AGE", e);
254 failurebackoff = Double.parseDouble(getProvParam("DELIVERY_RETRY_RATIO"));
255 } catch (Exception e) {
256 eelfLogger.trace("Error parsing DELIVERY_RETRY_RATIO", e);
259 deliverythreads = Integer.parseInt(getProvParam("DELIVERY_THREADS"));
260 } catch (Exception e) {
261 eelfLogger.trace("Error parsing DELIVERY_THREADS", e);
264 fairfilelimit = Integer.parseInt(getProvParam("FAIR_FILE_LIMIT"));
265 } catch (Exception e) {
266 eelfLogger.trace("Error parsing FAIR_FILE_LIMIT", e);
269 fairtimelimit = (long) (Double.parseDouble(getProvParam("FAIR_TIME_LIMIT")) * 1000);
270 } catch (Exception e) {
271 eelfLogger.trace("Error parsing FAIR_TIME_LIMIT", e);
274 fdpstart = Double.parseDouble(getProvParam("FREE_DISK_RED_PERCENT")) / 100.0;
275 } catch (Exception e) {
276 eelfLogger.trace("Error parsing FREE_DISK_RED_PERCENT", e);
279 fdpstop = Double.parseDouble(getProvParam("FREE_DISK_YELLOW_PERCENT")) / 100.0;
280 } catch (Exception e) {
281 eelfLogger.trace("Error parsing FREE_DISK_YELLOW_PERCENT", e);
283 if (fdpstart < 0.01) {
286 if (fdpstart > 0.5) {
289 if (fdpstop < fdpstart) {
297 private void fetchconfig() {
299 eelfLogger.debug("NodeConfigMan.fetchConfig: provurl:: " + provurl);
300 URL url = new URL(provurl);
301 Reader reader = new InputStreamReader(url.openStream());
302 config = new NodeConfig(new ProvData(reader), myname, spooldir, port, nak);
304 configtasks.startRun();
306 } catch (Exception e) {
307 NodeUtils.setIpAndFqdnForEelf("fetchconfigs");
308 eelfLogger.error(EelfMsgs.MESSAGE_CONF_FAILED, e.toString());
309 eelfLogger.error("NODE0306 Configuration failed " + e.toString() + " - try again later", e);
314 private void runTasks() {
316 while ((rr = configtasks.next()) != null) {
319 } catch (Exception e) {
320 eelfLogger.error("NODE0518 Exception fetchconfig: " + e);
326 * Process a gofetch request from a particular IP address. If the IP address is not an IP address we would go to to
327 * fetch the provisioning data, ignore the request. If the data has been fetched very recently (default 10
328 * seconds), wait a while before fetching again.
330 synchronized void gofetch(String remoteAddr) {
331 if (provcheck.isReachable(remoteAddr)) {
332 eelfLogger.debug("NODE0307 Received configuration fetch request from provisioning server " + remoteAddr);
335 eelfLogger.debug("NODE0308 Received configuration fetch request from unexpected server " + remoteAddr);
342 boolean isConfigured() {
343 return config != null;
349 boolean isShutdown() {
350 return quiesce.exists();
354 * Given a routing string, get the targets.
356 * @param routing Target string
357 * @return array of targets
359 Target[] parseRouting(String routing) {
360 return config.parseRouting(routing);
364 * Given a set of credentials and an IP address, is this request from another node.
366 * @param credentials Credentials offered by the supposed node
367 * @param ip IP address the request came from
368 * @return If the credentials and IP address are recognized, true, otherwise false.
370 boolean isAnotherNode(String credentials, String ip) {
371 return config.isAnotherNode(credentials, ip);
375 * Check whether publication is allowed.
377 * @param feedid The ID of the feed being requested
378 * @param credentials The offered credentials
379 * @param ip The requesting IP address
380 * @return True if the IP and credentials are valid for the specified feed.
382 String isPublishPermitted(String feedid, String credentials, String ip) {
383 return config.isPublishPermitted(feedid, credentials, ip);
387 * Check whether publication is allowed for AAF Feed.
389 * @param feedid The ID of the feed being requested
390 * @param ip The requesting IP address
391 * @return True if the IP and credentials are valid for the specified feed.
393 String isPublishPermitted(String feedid, String ip) {
394 return config.isPublishPermitted(feedid, ip);
398 * Check whether delete file is allowed.
400 * @param subId The ID of the subscription being requested
401 * @return True if the delete file is permitted for the subscriber.
403 boolean isDeletePermitted(String subId) {
404 return config.isDeletePermitted(subId);
408 * Check who the user is given the feed ID and the offered credentials.
410 * @param feedid The ID of the feed specified
411 * @param credentials The offered credentials
412 * @return Null if the credentials are invalid or the user if they are valid.
414 String getAuthUser(String feedid, String credentials) {
415 return config.getAuthUser(feedid, credentials);
419 * AAF changes: TDP EPIC US# 307413 Check AAF_instance for feed ID in NodeConfig.
421 * @param feedid The ID of the feed specified
423 String getAafInstance(String feedid) {
424 return config.getAafInstance(feedid);
427 String getAafInstance() {
432 * Check if the publish request should be sent to another node based on the feedid, user, and source IP address.
434 * @param feedid The ID of the feed specified
435 * @param user The publishing user
436 * @param ip The IP address of the publish endpoint
437 * @return Null if the request should be accepted or the correct hostname if it should be sent to another node.
439 String getIngressNode(String feedid, String user, String ip) {
440 return config.getIngressNode(feedid, user, ip);
444 * Get a provisioned configuration parameter (from the provisioning server configuration).
446 * @param name The name of the parameter
447 * @return The value of the parameter or null if it is not defined.
449 private String getProvParam(String name) {
450 return config.getProvParam(name);
454 * Get a provisioned configuration parameter (from the provisioning server configuration).
456 * @param name The name of the parameter
457 * @param defaultValue The value to use if the parameter is not defined
458 * @return The value of the parameter or deflt if it is not defined.
460 private String getProvParam(String name, String defaultValue) {
461 name = config.getProvParam(name);
469 * Generate a publish ID.
471 public String getPublishId() {
476 * Get all the outbound spooling destinations. This will include both subscriptions and nodes.
478 DestInfo[] getAllDests() {
479 return config.getAllDests();
483 * Register a task to run whenever the configuration changes.
485 void registerConfigTask(Runnable task) {
486 configtasks.addTask(task);
490 * Deregister a task to run whenever the configuration changes.
492 void deregisterConfigTask(Runnable task) {
493 configtasks.removeTask(task);
497 * Get the URL to deliver a message to.
499 * @param destinationInfo The destination information
500 * @param fileid The file ID
501 * @return The URL to deliver to
503 public String getDestURL(DestInfo destinationInfo, String fileid) {
504 String subid = destinationInfo.getSubId();
505 String purl = destinationInfo.getURL();
506 if (followredirects && subid != null) {
507 purl = rdmgr.lookup(subid, purl);
509 return (purl + "/" + fileid);
513 * Set up redirection on receipt of a 3XX from a target URL.
515 public boolean handleRedirection(DestInfo destinationInfo, String redirto, String fileid) {
516 fileid = "/" + fileid;
517 String subid = destinationInfo.getSubId();
518 String purl = destinationInfo.getURL();
519 if (followredirects && 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 Target[] getTargets(String feedid) {
595 return config.getTargets(feedid);
599 * Get the spool directory for temporary files.
601 String getSpoolDir() {
602 return spooldir + "/f";
606 * Get the spool directory for a subscription.
608 String getSpoolDir(String subid, String remoteaddr) {
609 if (provcheck.isFrom(remoteaddr)) {
610 String sdir = config.getSpoolDir(subid);
612 eelfLogger.debug("NODE0310 Received subscription reset request for subscription " + subid
613 + " from provisioning server " + remoteaddr);
615 eelfLogger.debug("NODE0311 Received subscription reset request for unknown subscription " + subid
616 + " from provisioning server " + remoteaddr);
620 eelfLogger.debug("NODE0312 Received subscription reset request from unexpected server " + remoteaddr);
626 * Get the base directory for spool directories.
628 String getSpoolBase() {
633 * Get the key store type.
640 * Get the key store file.
647 * Get the key store password.
654 * Get the key password.
681 * Get the https port.
688 * Get the externally visible https port.
690 int getExtHttpsPort() {
695 * Get the external name of this machine.
702 * Get the number of threads to use for delivery.
704 int getDeliveryThreads() {
705 return deliverythreads;
709 * Get the URL for uploading the event log data.
711 String getEventLogUrl() {
716 * Get the prefix for the names of event log files.
718 String getEventLogPrefix() {
719 return eventlogprefix;
723 * Get the suffix for the names of the event log files.
725 String getEventLogSuffix() {
726 return eventlogsuffix;
730 * Get the interval between event log file rollovers.
732 String getEventLogInterval() {
733 return eventloginterval;
737 * Should I follow redirects from subscribers.
739 public boolean isFollowRedirects() {
740 return followredirects;
744 * Get the directory where the event and node log files live.
751 * How long do I keep log files (in milliseconds).
753 long getLogRetention() {
760 public Timer getTimer() {
765 * Get the feed ID for a subscription.
767 * @param subid The subscription ID
768 * @return The feed ID
770 public String getFeedId(String subid) {
771 return config.getFeedId(subid);
775 * Get the authorization string this node uses.
777 * @return The Authorization string for this node
780 return config.getMyAuth();
784 * Get the fraction of free spool disk space where we start throwing away undelivered files. This is
785 * FREE_DISK_RED_PERCENT / 100.0. Default is 0.05. Limited by 0.01 <= FreeDiskStart <= 0.5.
787 double getFreeDiskStart() {
792 * Get the fraction of free spool disk space where we stop throwing away undelivered files. This is
793 * FREE_DISK_YELLOW_PERCENT / 100.0. Default is 0.2. Limited by FreeDiskStart <= FreeDiskStop <= 0.5.
795 double getFreeDiskStop() {
800 * Disable and enable protocols.
802 String[] getEnabledprotocols() {
803 return enabledprotocols;
806 String getAafType() {
810 String getAafAction() {
814 boolean getCadiEnabled() {
818 NodeAafPropsUtils getNodeAafPropsUtils() {
819 return nodeAafPropsUtils;
823 * Builds the permissions string to be verified.
825 * @param aafInstance The aaf instance
826 * @return The permissions
828 String getPermission(String aafInstance) {
830 String type = getAafType();
831 String action = getAafAction();
832 if ("".equals(aafInstance)) {
833 aafInstance = getAafInstance();
835 return type + "|" + aafInstance + "|" + action;
836 } catch (Exception e) {
837 eelfLogger.error("NODE0543 NodeConfigManager.getPermission: ", e);