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 tlsEnabled;
106 private boolean cadiEnabled;
107 private NodeAafPropsUtils nodeAafPropsUtils;
111 * Initialize the configuration of a Data Router node.
113 private NodeConfigManager() {
115 Properties drNodeProperties = new Properties();
116 try (FileInputStream fileInputStream = new FileInputStream(System
117 .getProperty("org.onap.dmaap.datarouter.node.properties", "/opt/app/datartr/etc/node.properties"))) {
118 eelfLogger.debug("NODE0301 Loading local config file node.properties");
119 drNodeProperties.load(fileInputStream);
120 } catch (Exception e) {
121 NodeUtils.setIpAndFqdnForEelf(NODE_CONFIG_MANAGER);
122 eelfLogger.error(EelfMsgs.MESSAGE_PROPERTIES_LOAD_ERROR, e,
123 System.getProperty("org.onap.dmaap.datarouter.node.properties",
124 "/opt/app/datartr/etc/node.properties"));
126 provurl = drNodeProperties.getProperty("ProvisioningURL", "https://dmaap-dr-prov:8443/internal/prov");
127 String aafPropsFilePath = drNodeProperties
128 .getProperty("AAFPropsFilePath", "/opt/app/osaaf/local/org.onap.dmaap-dr.props");
130 nodeAafPropsUtils = new NodeAafPropsUtils(new File(aafPropsFilePath));
131 } catch (IOException e) {
132 eelfLogger.error("NODE0314 Failed to load AAF props. Exiting", e);
136 * START - AAF changes: TDP EPIC US# 307413
137 * Pull AAF settings from node.properties
139 aafType = drNodeProperties.getProperty("AAFType", "org.onap.dmaap-dr.feed");
140 aafInstance = drNodeProperties.getProperty("AAFInstance", "legacy");
141 aafAction = drNodeProperties.getProperty("AAFAction", "publish");
142 cadiEnabled = Boolean.parseBoolean(drNodeProperties.getProperty("CadiEnabled", "false"));
144 * END - AAF changes: TDP EPIC US# 307413
145 * Pull AAF settings from node.properties
147 //Disable and enable protocols*/
148 enabledprotocols = ((drNodeProperties.getProperty("NodeHttpsProtocols")).trim()).split("\\|");
150 provhost = (new URL(provurl)).getHost();
151 } catch (Exception e) {
152 NodeUtils.setIpAndFqdnForEelf(NODE_CONFIG_MANAGER);
153 eelfLogger.error(EelfMsgs.MESSAGE_BAD_PROV_URL, e, provurl);
156 eelfLogger.debug("NODE0303 Provisioning server is " + provhost);
157 eventlogurl = drNodeProperties.getProperty("LogUploadURL", "https://feeds-drtr.web.att.com/internal/logs");
158 provcheck = new IsFrom(provhost);
159 gfport = Integer.parseInt(drNodeProperties.getProperty("IntHttpPort", "8080"));
160 svcport = Integer.parseInt(drNodeProperties.getProperty("IntHttpsPort", "8443"));
161 port = Integer.parseInt(drNodeProperties.getProperty("ExtHttpsPort", "443"));
162 spooldir = drNodeProperties.getProperty("SpoolDir", "spool");
163 tlsEnabled = Boolean.parseBoolean(drNodeProperties.getProperty("TlsEnabled", "true"));
165 File fdir = new File(spooldir + "/f");
167 for (File junk : Objects.requireNonNull(fdir.listFiles())) {
169 Files.deleteIfExists(junk.toPath());
170 } catch (IOException e) {
171 eelfLogger.error("NODE0313 Failed to clear junk files from " + fdir.getPath(), e);
174 logdir = drNodeProperties.getProperty("LogDir", "logs");
175 (new File(logdir)).mkdirs();
176 logretention = Long.parseLong(drNodeProperties.getProperty("LogRetention", "30")) * 86400000L;
177 eventlogprefix = logdir + "/events";
178 eventlogsuffix = ".log";
179 redirfile = drNodeProperties.getProperty("RedirectionFile", "etc/redirections.dat");
180 kstype = drNodeProperties.getProperty("KeyStoreType", "PKCS12");
181 ksfile = nodeAafPropsUtils.getPropAccess().getProperty("cadi_keystore");
182 kspass = nodeAafPropsUtils.getDecryptedPass("cadi_keystore_password");
183 kpass = nodeAafPropsUtils.getDecryptedPass("cadi_keystore_password");
184 tstype = drNodeProperties.getProperty("TrustStoreType", "jks");
185 tsfile = nodeAafPropsUtils.getPropAccess().getProperty("cadi_truststore");
186 tspass = nodeAafPropsUtils.getDecryptedPass("cadi_truststore_password");
187 if (tsfile != null && tsfile.length() > 0) {
188 System.setProperty("javax.net.ssl.trustStoreType", tstype);
189 System.setProperty("javax.net.ssl.trustStore", tsfile);
190 System.setProperty("javax.net.ssl.trustStorePassword", tspass);
192 nak = drNodeProperties.getProperty("NodeAuthKey", "Node123!");
193 quiesce = new File(drNodeProperties.getProperty("QuiesceFile", "etc/SHUTDOWN"));
194 myname = NodeUtils.getCanonicalName(kstype, ksfile, kspass);
195 if (myname == null) {
196 NodeUtils.setIpAndFqdnForEelf(NODE_CONFIG_MANAGER);
197 eelfLogger.error(EelfMsgs.MESSAGE_KEYSTORE_FETCH_ERROR, ksfile);
198 eelfLogger.error("NODE0309 Unable to fetch canonical name from keystore file " + ksfile);
201 eelfLogger.debug("NODE0304 My certificate says my name is " + myname);
202 pid = new PublishId(myname);
203 long minrsinterval = Long.parseLong(drNodeProperties.getProperty("MinRedirSaveInterval", "10000"));
204 long minpfinterval = Long.parseLong(drNodeProperties.getProperty("MinProvFetchInterval", "10000"));
205 rdmgr = new RedirManager(redirfile, minrsinterval, timer);
206 pfetcher = new RateLimitedOperation(minpfinterval, timer) {
211 eelfLogger.debug("NODE0305 Attempting to fetch configuration at " + provurl);
216 * Get the default node configuration manager.
218 public static NodeConfigManager getInstance() {
222 private void localconfig() {
223 followredirects = Boolean.parseBoolean(getProvParam("FOLLOW_REDIRECTS", "false"));
224 eventloginterval = getProvParam("LOGROLL_INTERVAL", "30s");
225 initfailuretimer = 10000;
226 waitForFileProcessFailureTimer = 600000;
227 maxfailuretimer = 3600000;
228 expirationtimer = 86400000;
229 failurebackoff = 2.0;
230 deliverythreads = 40;
232 fairtimelimit = 60000;
236 initfailuretimer = (long) (Double.parseDouble(getProvParam("DELIVERY_INIT_RETRY_INTERVAL")) * 1000);
237 } catch (Exception e) {
238 eelfLogger.trace("Error parsing DELIVERY_INIT_RETRY_INTERVAL", e);
241 waitForFileProcessFailureTimer = (long) (Double.parseDouble(getProvParam("DELIVERY_FILE_PROCESS_INTERVAL"))
243 } catch (Exception e) {
244 eelfLogger.trace("Error parsing DELIVERY_FILE_PROCESS_INTERVAL", e);
247 maxfailuretimer = (long) (Double.parseDouble(getProvParam("DELIVERY_MAX_RETRY_INTERVAL")) * 1000);
248 } catch (Exception e) {
249 eelfLogger.trace("Error parsing DELIVERY_MAX_RETRY_INTERVAL", e);
252 expirationtimer = (long) (Double.parseDouble(getProvParam("DELIVERY_MAX_AGE")) * 1000);
253 } catch (Exception e) {
254 eelfLogger.trace("Error parsing DELIVERY_MAX_AGE", e);
257 failurebackoff = Double.parseDouble(getProvParam("DELIVERY_RETRY_RATIO"));
258 } catch (Exception e) {
259 eelfLogger.trace("Error parsing DELIVERY_RETRY_RATIO", e);
262 deliverythreads = Integer.parseInt(getProvParam("DELIVERY_THREADS"));
263 } catch (Exception e) {
264 eelfLogger.trace("Error parsing DELIVERY_THREADS", e);
267 fairfilelimit = Integer.parseInt(getProvParam("FAIR_FILE_LIMIT"));
268 } catch (Exception e) {
269 eelfLogger.trace("Error parsing FAIR_FILE_LIMIT", e);
272 fairtimelimit = (long) (Double.parseDouble(getProvParam("FAIR_TIME_LIMIT")) * 1000);
273 } catch (Exception e) {
274 eelfLogger.trace("Error parsing FAIR_TIME_LIMIT", e);
277 fdpstart = Double.parseDouble(getProvParam("FREE_DISK_RED_PERCENT")) / 100.0;
278 } catch (Exception e) {
279 eelfLogger.trace("Error parsing FREE_DISK_RED_PERCENT", e);
282 fdpstop = Double.parseDouble(getProvParam("FREE_DISK_YELLOW_PERCENT")) / 100.0;
283 } catch (Exception e) {
284 eelfLogger.trace("Error parsing FREE_DISK_YELLOW_PERCENT", e);
286 if (fdpstart < 0.01) {
289 if (fdpstart > 0.5) {
292 if (fdpstop < fdpstart) {
300 private void fetchconfig() {
302 eelfLogger.debug("NodeConfigMan.fetchConfig: provurl:: " + provurl);
303 URL url = new URL(provurl);
304 Reader reader = new InputStreamReader(url.openStream());
305 config = new NodeConfig(new ProvData(reader), myname, spooldir, port, nak);
307 configtasks.startRun();
309 } catch (Exception e) {
310 NodeUtils.setIpAndFqdnForEelf("fetchconfigs");
311 eelfLogger.error(EelfMsgs.MESSAGE_CONF_FAILED, e.toString());
312 eelfLogger.error("NODE0306 Configuration failed " + e.toString() + " - try again later", e);
317 private void runTasks() {
319 while ((rr = configtasks.next()) != null) {
322 } catch (Exception e) {
323 eelfLogger.error("NODE0518 Exception fetchconfig: " + e);
329 * Process a gofetch request from a particular IP address. If the IP address is not an IP address we would go to to
330 * fetch the provisioning data, ignore the request. If the data has been fetched very recently (default 10
331 * seconds), wait a while before fetching again.
333 synchronized void gofetch(String remoteAddr) {
334 if (provcheck.isReachable(remoteAddr)) {
335 eelfLogger.debug("NODE0307 Received configuration fetch request from provisioning server " + remoteAddr);
338 eelfLogger.debug("NODE0308 Received configuration fetch request from unexpected server " + remoteAddr);
345 boolean isConfigured() {
346 return config != null;
352 boolean isShutdown() {
353 return quiesce.exists();
357 * Given a routing string, get the targets.
359 * @param routing Target string
360 * @return array of targets
362 Target[] parseRouting(String routing) {
363 return config.parseRouting(routing);
367 * Given a set of credentials and an IP address, is this request from another node.
369 * @param credentials Credentials offered by the supposed node
370 * @param ip IP address the request came from
371 * @return If the credentials and IP address are recognized, true, otherwise false.
373 boolean isAnotherNode(String credentials, String ip) {
374 return config.isAnotherNode(credentials, ip);
378 * Check whether publication is allowed.
380 * @param feedid The ID of the feed being requested
381 * @param credentials The offered credentials
382 * @param ip The requesting IP address
383 * @return True if the IP and credentials are valid for the specified feed.
385 String isPublishPermitted(String feedid, String credentials, String ip) {
386 return config.isPublishPermitted(feedid, credentials, ip);
390 * Check whether publication is allowed for AAF Feed.
392 * @param feedid The ID of the feed being requested
393 * @param ip The requesting IP address
394 * @return True if the IP and credentials are valid for the specified feed.
396 String isPublishPermitted(String feedid, String ip) {
397 return config.isPublishPermitted(feedid, ip);
401 * Check whether delete file is allowed.
403 * @param subId The ID of the subscription being requested
404 * @return True if the delete file is permitted for the subscriber.
406 boolean isDeletePermitted(String subId) {
407 return config.isDeletePermitted(subId);
411 * Check who the user is given the feed ID and the offered credentials.
413 * @param feedid The ID of the feed specified
414 * @param credentials The offered credentials
415 * @return Null if the credentials are invalid or the user if they are valid.
417 String getAuthUser(String feedid, String credentials) {
418 return config.getAuthUser(feedid, credentials);
422 * AAF changes: TDP EPIC US# 307413 Check AAF_instance for feed ID in NodeConfig.
424 * @param feedid The ID of the feed specified
426 String getAafInstance(String feedid) {
427 return config.getAafInstance(feedid);
430 String getAafInstance() {
435 * Check if the publish request should be sent to another node based on the feedid, user, and source IP address.
437 * @param feedid The ID of the feed specified
438 * @param user The publishing user
439 * @param ip The IP address of the publish endpoint
440 * @return Null if the request should be accepted or the correct hostname if it should be sent to another node.
442 String getIngressNode(String feedid, String user, String ip) {
443 return config.getIngressNode(feedid, user, ip);
447 * Get a provisioned configuration parameter (from the provisioning server configuration).
449 * @param name The name of the parameter
450 * @return The value of the parameter or null if it is not defined.
452 private String getProvParam(String name) {
453 return config.getProvParam(name);
457 * Get a provisioned configuration parameter (from the provisioning server configuration).
459 * @param name The name of the parameter
460 * @param defaultValue The value to use if the parameter is not defined
461 * @return The value of the parameter or deflt if it is not defined.
463 private String getProvParam(String name, String defaultValue) {
464 name = config.getProvParam(name);
472 * Generate a publish ID.
474 public String getPublishId() {
479 * Get all the outbound spooling destinations. This will include both subscriptions and nodes.
481 DestInfo[] getAllDests() {
482 return config.getAllDests();
486 * Register a task to run whenever the configuration changes.
488 void registerConfigTask(Runnable task) {
489 configtasks.addTask(task);
493 * Deregister a task to run whenever the configuration changes.
495 void deregisterConfigTask(Runnable task) {
496 configtasks.removeTask(task);
500 * Get the URL to deliver a message to.
502 * @param destinationInfo The destination information
503 * @param fileid The file ID
504 * @return The URL to deliver to
506 public String getDestURL(DestInfo destinationInfo, String fileid) {
507 String subid = destinationInfo.getSubId();
508 String purl = destinationInfo.getURL();
509 if (followredirects && subid != null) {
510 purl = rdmgr.lookup(subid, purl);
512 return (purl + "/" + fileid);
516 * Set up redirection on receipt of a 3XX from a target URL.
518 public boolean handleRedirection(DestInfo destinationInfo, String redirto, String fileid) {
519 fileid = "/" + fileid;
520 String subid = destinationInfo.getSubId();
521 String purl = destinationInfo.getURL();
522 if (followredirects && subid != null && redirto.endsWith(fileid)) {
523 redirto = redirto.substring(0, redirto.length() - fileid.length());
524 if (!redirto.equals(purl)) {
525 rdmgr.redirect(subid, purl, redirto);
533 * Handle unreachable target URL.
535 public void handleUnreachable(DestInfo destinationInfo) {
536 String subid = destinationInfo.getSubId();
537 if (followredirects && subid != null) {
543 * Get the timeout before retrying after an initial delivery failure.
545 public long getInitFailureTimer() {
546 return initfailuretimer;
550 * Get the timeout before retrying after delivery and wait for file processing.
552 public long getWaitForFileProcessFailureTimer() {
553 return waitForFileProcessFailureTimer;
557 * Get the maximum timeout between delivery attempts.
559 public long getMaxFailureTimer() {
560 return maxfailuretimer;
564 * Get the ratio between consecutive delivery attempts.
566 public double getFailureBackoff() {
567 return failurebackoff;
571 * Get the expiration timer for deliveries.
573 public long getExpirationTimer() {
574 return expirationtimer;
578 * Get the maximum number of file delivery attempts before checking if another queue has work to be performed.
580 public int getFairFileLimit() {
581 return fairfilelimit;
585 * Get the maximum amount of time spent delivering files before checking if another queue has work to be performed.
587 public long getFairTimeLimit() {
588 return fairtimelimit;
592 * Get the targets for a feed.
594 * @param feedid The feed ID
595 * @return The targets this feed should be delivered to
597 Target[] getTargets(String feedid) {
598 return config.getTargets(feedid);
602 * Get the spool directory for temporary files.
604 String getSpoolDir() {
605 return spooldir + "/f";
609 * Get the spool directory for a subscription.
611 String getSpoolDir(String subid, String remoteaddr) {
612 if (provcheck.isFrom(remoteaddr)) {
613 String sdir = config.getSpoolDir(subid);
615 eelfLogger.debug("NODE0310 Received subscription reset request for subscription " + subid
616 + " from provisioning server " + remoteaddr);
618 eelfLogger.debug("NODE0311 Received subscription reset request for unknown subscription " + subid
619 + " from provisioning server " + remoteaddr);
623 eelfLogger.debug("NODE0312 Received subscription reset request from unexpected server " + remoteaddr);
629 * Get the base directory for spool directories.
631 String getSpoolBase() {
636 * Get the key store type.
643 * Get the key store file.
650 * Get the key store password.
657 * Get the key password.
684 * Get the https port.
691 * Get the externally visible https port.
693 int getExtHttpsPort() {
698 * Get the external name of this machine.
705 * Get the number of threads to use for delivery.
707 int getDeliveryThreads() {
708 return deliverythreads;
712 * Get the URL for uploading the event log data.
714 String getEventLogUrl() {
719 * Get the prefix for the names of event log files.
721 String getEventLogPrefix() {
722 return eventlogprefix;
726 * Get the suffix for the names of the event log files.
728 String getEventLogSuffix() {
729 return eventlogsuffix;
733 * Get the interval between event log file rollovers.
735 String getEventLogInterval() {
736 return eventloginterval;
740 * Should I follow redirects from subscribers.
742 public boolean isFollowRedirects() {
743 return followredirects;
747 * Get the directory where the event and node log files live.
754 * How long do I keep log files (in milliseconds).
756 long getLogRetention() {
763 public Timer getTimer() {
768 * Get the feed ID for a subscription.
770 * @param subid The subscription ID
771 * @return The feed ID
773 public String getFeedId(String subid) {
774 return config.getFeedId(subid);
778 * Get the authorization string this node uses.
780 * @return The Authorization string for this node
783 return config.getMyAuth();
787 * Get the fraction of free spool disk space where we start throwing away undelivered files. This is
788 * FREE_DISK_RED_PERCENT / 100.0. Default is 0.05. Limited by 0.01 <= FreeDiskStart <= 0.5.
790 double getFreeDiskStart() {
795 * Get the fraction of free spool disk space where we stop throwing away undelivered files. This is
796 * FREE_DISK_YELLOW_PERCENT / 100.0. Default is 0.2. Limited by FreeDiskStart <= FreeDiskStop <= 0.5.
798 double getFreeDiskStop() {
803 * Disable and enable protocols.
805 String[] getEnabledprotocols() {
806 return enabledprotocols;
809 String getAafType() {
813 String getAafAction() {
817 protected boolean isTlsEnabled() {
821 boolean getCadiEnabled() {
825 NodeAafPropsUtils getNodeAafPropsUtils() {
826 return nodeAafPropsUtils;
830 * Builds the permissions string to be verified.
832 * @param aafInstance The aaf instance
833 * @return The permissions
835 String getPermission(String aafInstance) {
837 String type = getAafType();
838 String action = getAafAction();
839 if ("".equals(aafInstance)) {
840 aafInstance = getAafInstance();
842 return type + "|" + aafInstance + "|" + action;
843 } catch (Exception e) {
844 eelfLogger.error("NODE0543 NodeConfigManager.getPermission: ", e);