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 CHANGE_ME = "changeme";
57 private static final String NODE_CONFIG_MANAGER = "NodeConfigManager";
58 private static EELFLogger eelfLogger = EELFManager.getInstance().getLogger(NodeConfigManager.class);
59 private static NodeConfigManager base = new NodeConfigManager();
61 private Timer timer = new Timer("Node Configuration Timer", true);
62 private long maxfailuretimer;
63 private long initfailuretimer;
64 private long waitForFileProcessFailureTimer;
65 private long expirationtimer;
66 private double failurebackoff;
67 private long fairtimelimit;
68 private int fairfilelimit;
69 private double fdpstart;
70 private double fdpstop;
71 private int deliverythreads;
72 private String provurl;
73 private String provhost;
74 private IsFrom provcheck;
78 private String spooldir;
79 private String logdir;
80 private long logretention;
81 private String redirfile;
82 private String kstype;
83 private String ksfile;
84 private String kspass;
86 private String tstype;
87 private String tsfile;
88 private String tspass;
89 private String myname;
90 private RedirManager rdmgr;
91 private RateLimitedOperation pfetcher;
92 private NodeConfig config;
94 private PublishId pid;
96 private TaskList configtasks = new TaskList();
97 private String eventlogurl;
98 private String eventlogprefix;
99 private String eventlogsuffix;
100 private String eventloginterval;
101 private boolean followredirects;
102 private String[] enabledprotocols;
103 private String aafType;
104 private String aafInstance;
105 private String aafAction;
106 private String aafURL;
107 private boolean cadiEnabled;
111 * Initialize the configuration of a Data Router node.
113 private NodeConfigManager() {
115 Properties drNodeProperties = new Properties();
117 eelfLogger.debug("NODE0301 Loading local config file node.properties");
118 drNodeProperties.load(new FileInputStream(System
119 .getProperty("org.onap.dmaap.datarouter.node.properties", "/opt/app/datartr/etc/node.properties")));
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");
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("\\|");
143 provhost = (new URL(provurl)).getHost();
144 } catch (Exception e) {
145 NodeUtils.setIpAndFqdnForEelf(NODE_CONFIG_MANAGER);
146 eelfLogger.error(EelfMsgs.MESSAGE_BAD_PROV_URL, e, provurl);
149 eelfLogger.debug("NODE0303 Provisioning server is " + provhost);
150 eventlogurl = drNodeProperties.getProperty("LogUploadURL", "https://feeds-drtr.web.att.com/internal/logs");
151 provcheck = new IsFrom(provhost);
152 gfport = Integer.parseInt(drNodeProperties.getProperty("IntHttpPort", "8080"));
153 svcport = Integer.parseInt(drNodeProperties.getProperty("IntHttpsPort", "8443"));
154 port = Integer.parseInt(drNodeProperties.getProperty("ExtHttpsPort", "443"));
155 spooldir = drNodeProperties.getProperty("SpoolDir", "spool");
156 File fdir = new File(spooldir + "/f");
158 for (File junk : Objects.requireNonNull(fdir.listFiles())) {
160 Files.deleteIfExists(junk.toPath());
161 } catch (IOException e) {
162 eelfLogger.error("NODE0313 Failed to clear junk files from " + fdir.getPath(), e);
165 logdir = drNodeProperties.getProperty("LogDir", "logs");
166 (new File(logdir)).mkdirs();
167 logretention = Long.parseLong(drNodeProperties.getProperty("LogRetention", "30")) * 86400000L;
168 eventlogprefix = logdir + "/events";
169 eventlogsuffix = ".log";
170 redirfile = drNodeProperties.getProperty("RedirectionFile", "etc/redirections.dat");
171 kstype = drNodeProperties.getProperty("KeyStoreType", "jks");
172 ksfile = drNodeProperties.getProperty("KeyStoreFile", "etc/keystore");
173 kspass = drNodeProperties.getProperty("KeyStorePassword", CHANGE_ME);
174 kpass = drNodeProperties.getProperty("KeyPassword", CHANGE_ME);
175 tstype = drNodeProperties.getProperty("TrustStoreType", "jks");
176 tsfile = drNodeProperties.getProperty("TrustStoreFile");
177 tspass = drNodeProperties.getProperty("TrustStorePassword", CHANGE_ME);
178 if (tsfile != null && tsfile.length() > 0) {
179 System.setProperty("javax.net.ssl.trustStoreType", tstype);
180 System.setProperty("javax.net.ssl.trustStore", tsfile);
181 System.setProperty("javax.net.ssl.trustStorePassword", tspass);
183 nak = drNodeProperties.getProperty("NodeAuthKey", "Node123!");
184 quiesce = new File(drNodeProperties.getProperty("QuiesceFile", "etc/SHUTDOWN"));
185 myname = NodeUtils.getCanonicalName(kstype, ksfile, kspass);
186 if (myname == null) {
187 NodeUtils.setIpAndFqdnForEelf(NODE_CONFIG_MANAGER);
188 eelfLogger.error(EelfMsgs.MESSAGE_KEYSTORE_FETCH_ERROR, ksfile);
189 eelfLogger.error("NODE0309 Unable to fetch canonical name from keystore file " + ksfile);
192 eelfLogger.debug("NODE0304 My certificate says my name is " + myname);
193 pid = new PublishId(myname);
194 long minrsinterval = Long.parseLong(drNodeProperties.getProperty("MinRedirSaveInterval", "10000"));
195 long minpfinterval = Long.parseLong(drNodeProperties.getProperty("MinProvFetchInterval", "10000"));
196 rdmgr = new RedirManager(redirfile, minrsinterval, timer);
197 pfetcher = new RateLimitedOperation(minpfinterval, timer) {
202 eelfLogger.debug("NODE0305 Attempting to fetch configuration at " + provurl);
207 * Get the default node configuration manager.
209 public static NodeConfigManager getInstance() {
213 private void localconfig() {
214 followredirects = Boolean.parseBoolean(getProvParam("FOLLOW_REDIRECTS", "false"));
215 eventloginterval = getProvParam("LOGROLL_INTERVAL", "30s");
216 initfailuretimer = 10000;
217 waitForFileProcessFailureTimer = 600000;
218 maxfailuretimer = 3600000;
219 expirationtimer = 86400000;
220 failurebackoff = 2.0;
221 deliverythreads = 40;
223 fairtimelimit = 60000;
227 initfailuretimer = (long) (Double.parseDouble(getProvParam("DELIVERY_INIT_RETRY_INTERVAL")) * 1000);
228 } catch (Exception e) {
229 eelfLogger.trace("Error parsing DELIVERY_INIT_RETRY_INTERVAL", e);
232 waitForFileProcessFailureTimer = (long) (Double.parseDouble(getProvParam("DELIVERY_FILE_PROCESS_INTERVAL"))
234 } catch (Exception e) {
235 eelfLogger.trace("Error parsing DELIVERY_FILE_PROCESS_INTERVAL", e);
238 maxfailuretimer = (long) (Double.parseDouble(getProvParam("DELIVERY_MAX_RETRY_INTERVAL")) * 1000);
239 } catch (Exception e) {
240 eelfLogger.trace("Error parsing DELIVERY_MAX_RETRY_INTERVAL", e);
243 expirationtimer = (long) (Double.parseDouble(getProvParam("DELIVERY_MAX_AGE")) * 1000);
244 } catch (Exception e) {
245 eelfLogger.trace("Error parsing DELIVERY_MAX_AGE", e);
248 failurebackoff = Double.parseDouble(getProvParam("DELIVERY_RETRY_RATIO"));
249 } catch (Exception e) {
250 eelfLogger.trace("Error parsing DELIVERY_RETRY_RATIO", e);
253 deliverythreads = Integer.parseInt(getProvParam("DELIVERY_THREADS"));
254 } catch (Exception e) {
255 eelfLogger.trace("Error parsing DELIVERY_THREADS", e);
258 fairfilelimit = Integer.parseInt(getProvParam("FAIR_FILE_LIMIT"));
259 } catch (Exception e) {
260 eelfLogger.trace("Error parsing FAIR_FILE_LIMIT", e);
263 fairtimelimit = (long) (Double.parseDouble(getProvParam("FAIR_TIME_LIMIT")) * 1000);
264 } catch (Exception e) {
265 eelfLogger.trace("Error parsing FAIR_TIME_LIMIT", e);
268 fdpstart = Double.parseDouble(getProvParam("FREE_DISK_RED_PERCENT")) / 100.0;
269 } catch (Exception e) {
270 eelfLogger.trace("Error parsing FREE_DISK_RED_PERCENT", e);
273 fdpstop = Double.parseDouble(getProvParam("FREE_DISK_YELLOW_PERCENT")) / 100.0;
274 } catch (Exception e) {
275 eelfLogger.trace("Error parsing FREE_DISK_YELLOW_PERCENT", e);
277 if (fdpstart < 0.01) {
280 if (fdpstart > 0.5) {
283 if (fdpstop < fdpstart) {
291 private void fetchconfig() {
293 eelfLogger.debug("NodeConfigMan.fetchConfig: provurl:: " + provurl);
294 Reader reader = new InputStreamReader((new URL(provurl)).openStream());
295 config = new NodeConfig(new ProvData(reader), myname, spooldir, port, nak);
297 configtasks.startRun();
299 } catch (Exception e) {
300 NodeUtils.setIpAndFqdnForEelf("fetchconfigs");
301 eelfLogger.error(EelfMsgs.MESSAGE_CONF_FAILED, e.toString());
302 eelfLogger.error("NODE0306 Configuration failed " + e.toString() + " - try again later", e);
307 private void runTasks() {
309 while ((rr = configtasks.next()) != null) {
312 } catch (Exception e) {
313 eelfLogger.error("NODE0518 Exception fetchconfig: " + e);
319 * Process a gofetch request from a particular IP address. If the IP address is not an IP address we would go to to
320 * fetch the provisioning data, ignore the request. If the data has been fetched very recently (default 10
321 * seconds), wait a while before fetching again.
323 public synchronized void gofetch(String remoteAddr) {
324 if (provcheck.isReachable(remoteAddr)) {
325 eelfLogger.debug("NODE0307 Received configuration fetch request from provisioning server " + remoteAddr);
328 eelfLogger.debug("NODE0308 Received configuration fetch request from unexpected server " + remoteAddr);
335 public boolean isConfigured() {
336 return (config != null);
342 public boolean isShutdown() {
343 return (quiesce.exists());
347 * Given a routing string, get the targets.
349 * @param routing Target string
350 * @return array of targets
352 public Target[] parseRouting(String routing) {
353 return (config.parseRouting(routing));
357 * Given a set of credentials and an IP address, is this request from another node.
359 * @param credentials Credentials offered by the supposed node
360 * @param ip IP address the request came from
361 * @return If the credentials and IP address are recognized, true, otherwise false.
363 public boolean isAnotherNode(String credentials, String ip) {
364 return (config.isAnotherNode(credentials, ip));
368 * Check whether publication is allowed.
370 * @param feedid The ID of the feed being requested
371 * @param credentials The offered credentials
372 * @param ip The requesting IP address
373 * @return True if the IP and credentials are valid for the specified feed.
375 public String isPublishPermitted(String feedid, String credentials, String ip) {
376 return (config.isPublishPermitted(feedid, credentials, ip));
380 * Check whether publication is allowed for AAF Feed.
382 * @param feedid The ID of the feed being requested
383 * @param ip The requesting IP address
384 * @return True if the IP and credentials are valid for the specified feed.
386 public String isPublishPermitted(String feedid, String ip) {
387 return (config.isPublishPermitted(feedid, ip));
391 * Check whether delete file is allowed.
393 * @param subId The ID of the subscription being requested
394 * @return True if the delete file is permitted for the subscriber.
396 public boolean isDeletePermitted(String subId) {
397 return (config.isDeletePermitted(subId));
401 * Check who the user is given the feed ID and the offered credentials.
403 * @param feedid The ID of the feed specified
404 * @param credentials The offered credentials
405 * @return Null if the credentials are invalid or the user if they are valid.
407 public String getAuthUser(String feedid, String credentials) {
408 return (config.getAuthUser(feedid, credentials));
412 * AAF changes: TDP EPIC US# 307413 Check AAF_instance for feed ID in NodeConfig.
414 * @param feedid The ID of the feed specified
416 public String getAafInstance(String feedid) {
417 return (config.getAafInstance(feedid));
420 public String getAafInstance() {
425 * Check if the publish request should be sent to another node based on the feedid, user, and source IP address.
427 * @param feedid The ID of the feed specified
428 * @param user The publishing user
429 * @param ip The IP address of the publish endpoint
430 * @return Null if the request should be accepted or the correct hostname if it should be sent to another node.
432 public String getIngressNode(String feedid, String user, String ip) {
433 return (config.getIngressNode(feedid, user, ip));
437 * Get a provisioned configuration parameter (from the provisioning server configuration).
439 * @param name The name of the parameter
440 * @return The value of the parameter or null if it is not defined.
442 public String getProvParam(String name) {
443 return (config.getProvParam(name));
447 * Get a provisioned configuration parameter (from the provisioning server configuration).
449 * @param name The name of the parameter
450 * @param defaultValue The value to use if the parameter is not defined
451 * @return The value of the parameter or deflt if it is not defined.
453 public String getProvParam(String name, String defaultValue) {
454 name = config.getProvParam(name);
462 * Generate a publish ID.
464 public String getPublishId() {
469 * Get all the outbound spooling destinations. This will include both subscriptions and nodes.
471 public DestInfo[] getAllDests() {
472 return (config.getAllDests());
476 * Register a task to run whenever the configuration changes.
478 public void registerConfigTask(Runnable task) {
479 configtasks.addTask(task);
483 * Deregister a task to run whenever the configuration changes.
485 public void deregisterConfigTask(Runnable task) {
486 configtasks.removeTask(task);
490 * Get the URL to deliver a message to.
492 * @param destinationInfo The destination information
493 * @param fileid The file ID
494 * @return The URL to deliver to
496 public String getDestURL(DestInfo destinationInfo, String fileid) {
497 String subid = destinationInfo.getSubId();
498 String purl = destinationInfo.getURL();
499 if (followredirects && subid != null) {
500 purl = rdmgr.lookup(subid, purl);
502 return (purl + "/" + fileid);
506 * Set up redirection on receipt of a 3XX from a target URL.
508 public boolean handleRedirection(DestInfo destinationInfo, String redirto, String fileid) {
509 fileid = "/" + fileid;
510 String subid = destinationInfo.getSubId();
511 String purl = destinationInfo.getURL();
512 if (followredirects && subid != null && redirto.endsWith(fileid)) {
513 redirto = redirto.substring(0, redirto.length() - fileid.length());
514 if (!redirto.equals(purl)) {
515 rdmgr.redirect(subid, purl, redirto);
523 * Handle unreachable target URL.
525 public void handleUnreachable(DestInfo destinationInfo) {
526 String subid = destinationInfo.getSubId();
527 if (followredirects && subid != null) {
533 * Get the timeout before retrying after an initial delivery failure.
535 public long getInitFailureTimer() {
536 return (initfailuretimer);
540 * Get the timeout before retrying after delivery and wait for file processing.
542 public long getWaitForFileProcessFailureTimer() {
543 return (waitForFileProcessFailureTimer);
547 * Get the maximum timeout between delivery attempts.
549 public long getMaxFailureTimer() {
550 return (maxfailuretimer);
554 * Get the ratio between consecutive delivery attempts.
556 public double getFailureBackoff() {
557 return (failurebackoff);
561 * Get the expiration timer for deliveries.
563 public long getExpirationTimer() {
564 return (expirationtimer);
568 * Get the maximum number of file delivery attempts before checking if another queue has work to be performed.
570 public int getFairFileLimit() {
571 return (fairfilelimit);
575 * Get the maximum amount of time spent delivering files before checking if another queue has work to be performed.
577 public long getFairTimeLimit() {
578 return (fairtimelimit);
582 * Get the targets for a feed.
584 * @param feedid The feed ID
585 * @return The targets this feed should be delivered to
587 public Target[] getTargets(String feedid) {
588 return (config.getTargets(feedid));
592 * Get the spool directory for temporary files.
594 public String getSpoolDir() {
595 return (spooldir + "/f");
599 * Get the spool directory for a subscription.
601 public String getSpoolDir(String subid, String remoteaddr) {
602 if (provcheck.isFrom(remoteaddr)) {
603 String sdir = config.getSpoolDir(subid);
605 eelfLogger.debug("NODE0310 Received subscription reset request for subscription " + subid
606 + " from provisioning server " + remoteaddr);
608 eelfLogger.debug("NODE0311 Received subscription reset request for unknown subscription " + subid
609 + " from provisioning server " + remoteaddr);
613 eelfLogger.debug("NODE0312 Received subscription reset request from unexpected server " + remoteaddr);
619 * Get the base directory for spool directories.
621 public String getSpoolBase() {
626 * Get the key store type.
628 public String getKSType() {
633 * Get the key store file.
635 public String getKSFile() {
640 * Get the key store password.
642 public String getKSPass() {
647 * Get the key password.
649 public String getKPass() {
656 public int getHttpPort() {
661 * Get the https port.
663 public int getHttpsPort() {
668 * Get the externally visible https port.
670 public int getExtHttpsPort() {
675 * Get the external name of this machine.
677 public String getMyName() {
682 * Get the number of threads to use for delivery.
684 public int getDeliveryThreads() {
685 return (deliverythreads);
689 * Get the URL for uploading the event log data.
691 public String getEventLogUrl() {
692 return (eventlogurl);
696 * Get the prefix for the names of event log files.
698 public String getEventLogPrefix() {
699 return (eventlogprefix);
703 * Get the suffix for the names of the event log files.
705 public String getEventLogSuffix() {
706 return (eventlogsuffix);
710 * Get the interval between event log file rollovers.
712 public String getEventLogInterval() {
713 return (eventloginterval);
717 * Should I follow redirects from subscribers.
719 public boolean isFollowRedirects() {
720 return (followredirects);
724 * Get the directory where the event and node log files live.
726 public String getLogDir() {
731 * How long do I keep log files (in milliseconds).
733 public long getLogRetention() {
734 return (logretention);
740 public Timer getTimer() {
745 * Get the feed ID for a subscription.
747 * @param subid The subscription ID
748 * @return The feed ID
750 public String getFeedId(String subid) {
751 return (config.getFeedId(subid));
755 * Get the authorization string this node uses.
757 * @return The Authorization string for this node
759 public String getMyAuth() {
760 return (config.getMyAuth());
764 * Get the fraction of free spool disk space where we start throwing away undelivered files. This is
765 * FREE_DISK_RED_PERCENT / 100.0. Default is 0.05. Limited by 0.01 <= FreeDiskStart <= 0.5.
767 public double getFreeDiskStart() {
772 * Get the fraction of free spool disk space where we stop throwing away undelivered files. This is
773 * FREE_DISK_YELLOW_PERCENT / 100.0. Default is 0.2. Limited by FreeDiskStart <= FreeDiskStop <= 0.5.
775 public double getFreeDiskStop() {
780 * Disable and enable protocols.
782 public String[] getEnabledprotocols() {
783 return enabledprotocols;
786 public String getAafType() {
790 public String getAafAction() {
795 * Get aafURL from SWM variable
797 public String getAafURL() {
801 public boolean getCadiEnabled() {
806 * Builds the permissions string to be verified.
808 * @param aafInstance The aaf instance
809 * @return The permissions
811 protected String getPermission(String aafInstance) {
813 String type = getAafType();
814 String action = getAafAction();
815 if ("".equals(aafInstance)) {
816 aafInstance = getAafInstance();
818 return type + "|" + aafInstance + "|" + action;
819 } catch (Exception e) {
820 eelfLogger.error("NODE0543 NodeConfigManager.getPermission: ", e);