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.provisioning;
27 import java.io.ByteArrayOutputStream;
29 import java.io.IOException;
30 import java.io.InputStream;
31 import java.nio.file.FileStore;
32 import java.nio.file.FileSystem;
33 import java.nio.file.Files;
34 import java.nio.file.Path;
35 import java.nio.file.Paths;
36 import java.nio.file.StandardCopyOption;
37 import java.util.Properties;
39 import javax.servlet.http.HttpServletRequest;
40 import javax.servlet.http.HttpServletResponse;
42 import org.json.JSONArray;
43 import org.onap.dmaap.datarouter.provisioning.beans.EventLogRecord;
44 import org.onap.dmaap.datarouter.provisioning.beans.LogRecord;
45 import org.onap.dmaap.datarouter.provisioning.beans.Parameters;
46 import org.onap.dmaap.datarouter.provisioning.eelf.EelfMsgs;
47 import org.onap.dmaap.datarouter.provisioning.utils.DB;
48 import org.onap.dmaap.datarouter.provisioning.utils.LogfileLoader;
49 import org.onap.dmaap.datarouter.provisioning.utils.RLEBitSet;
51 import com.att.eelf.configuration.EELFLogger;
52 import com.att.eelf.configuration.EELFManager;
54 import static org.onap.dmaap.datarouter.provisioning.utils.HttpServletUtils.sendResponseError;
58 * This servlet handles requests to URLs under /internal on the provisioning server. These include:
60 * <div class="contentContainer">
61 * <table class="packageSummary" border="0" cellpadding="3" cellspacing="0">
62 * <caption><span>URL Path Summary</span><span class="tabEnd"> </span></caption>
64 * <th class="colFirst" width="15%">URL Path</th>
65 * <th class="colOne">Method</th>
66 * <th class="colLast">Purpose</th>
68 * <tr class="altColor">
69 * <td class="colFirst">/internal/prov</td>
70 * <td class="colOne">GET</td>
71 * <td class="colLast">used to GET a full JSON copy of the provisioning data.</td>
73 * <tr class="rowColor">
74 * <td class="colFirst">/internal/fetchProv</td>
75 * <td class="colOne">GET</td>
76 * <td class="colLast">used to signal to a standby POD that the provisioning data should be fetched from the active
79 * <tr class="altColor">
80 * <td class="colFirst" rowspan="2">/internal/logs</td>
81 * <td class="colOne">GET</td>
82 * <td class="colLast">used to GET an index of log files and individual logs for this provisioning server.</td>
84 * <tr class="altColor">
85 * <td class="colOne">POST</td>
86 * <td class="colLast">used to POST log files from the individual nodes to this provisioning server.</td>
88 * <tr class="rowColor">
89 * <td class="colFirst" rowspan="4">/internal/api</td>
90 * <td class="colOne">GET</td>
91 * <td class="colLast">used to GET an individual parameter value. The parameter name is specified by the path after
94 * <tr class="rowColor">
95 * <td class="colOne">PUT</td>
96 * <td class="colLast">used to set an individual parameter value. The parameter name is specified by the path after
99 * <tr class="rowColor">
100 * <td class="colOne">DELETE</td>
101 * <td class="colLast">used to remove an individual parameter value. The parameter name is specified by the path after
104 * <tr class="rowColor">
105 * <td class="colOne">POST</td>
106 * <td class="colLast">used to create a new individual parameter value. The parameter name is specified by the path
109 * <tr class="altColor">
110 * <td class="colFirst">/internal/halt</td>
111 * <td class="colOne">GET</td>
112 * <td class="colLast">used to halt the server (must be accessed from 127.0.0.1).</td>
114 * <tr class="rowColor">
115 * <td class="colFirst" rowspan="2">/internal/drlogs</td>
116 * <td class="colOne">GET</td>
117 * <td class="colLast">used to get a list of DR log entries available for retrieval.
118 * Note: these are the actual data router log entries sent to the provisioning server by the nodes, not the provisioning
119 * server's internal logs (access via /internal/logs above). The range is returned as a list of record sequence
122 * <tr class="rowColor">
123 * <td class="colOne">POST</td>
124 * <td class="colLast">used to retrieve specific log entries.
125 * The sequence numbers of the records to fetch are POST-ed; the records matching the sequence numbers are
128 * <tr class="altColor">
129 * <td class="colFirst">/internal/route/*</td>
130 * <td class="colOne">*</td>
131 * <td class="colLast">URLs under this path are handled via the {@link org.onap.dmaap.datarouter.provisioning.RouteServlet}</td>
136 * Authorization to use these URLs is a little different than for other URLs on the provisioning server. For the most
137 * part, the IP address that the request comes from should be either:
140 * <li>an IP address of a provisioning server, or</li>
141 * <li>the IP address of a node (to allow access to /internal/prov), or</li>
142 * <li>an IP address from the "<i>special subnet</i>" which is configured with
143 * the PROV_SPECIAL_SUBNET parameter.
146 * In addition, requests to /internal/halt can ONLY come from localhost (127.0.0.1) on the HTTP port.
149 * All DELETE/GET/PUT/POST requests made to /internal/api on this servlet on the standby server are proxied to the
150 * active server (using the {@link ProxyServlet}) if it is up and reachable.
154 * @version $Id: InternalServlet.java,v 1.23 2014/03/24 18:47:10 eby Exp $
156 @SuppressWarnings("serial")
157 public class InternalServlet extends ProxyServlet {
159 private static Integer logseq = 0; // another piece of info to make log spool file names unique
160 //Adding EELF Logger Rally:US664892
161 private static EELFLogger eelflogger = EELFManager.getInstance()
162 .getLogger("org.onap.dmaap.datarouter.provisioning.InternalServlet");
165 * Delete a parameter at the address /internal/api/<parameter>. See the <b>Internal API</b> document for
166 * details on how this method should be invoked.
169 public void doDelete(HttpServletRequest req, HttpServletResponse resp) {
170 setIpAndFqdnForEelf("doDelete");
171 eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER), getIdFromPath(req) + "");
172 EventLogRecord elr = new EventLogRecord(req);
173 if (!isAuthorizedForInternal(req)) {
174 elr.setMessage("Unauthorized.");
175 elr.setResult(HttpServletResponse.SC_FORBIDDEN);
176 eventlogger.info(elr);
177 sendResponseError(resp, HttpServletResponse.SC_FORBIDDEN, "Unauthorized.", eventlogger);
181 String path = req.getPathInfo();
182 if (path.startsWith("/api/")) {
183 if (isProxyOK(req) && isProxyServer()) {
185 super.doDelete(req, resp);
186 } catch (IOException ioe) {
187 intlogger.error("IOException" + ioe.getMessage());
191 String key = path.substring(5);
192 if (key.length() > 0) {
193 Parameters param = Parameters.getParameter(key);
195 if (doDelete(param)) {
196 elr.setResult(HttpServletResponse.SC_OK);
197 eventlogger.info(elr);
198 resp.setStatus(HttpServletResponse.SC_OK);
199 provisioningDataChanged();
200 provisioningParametersChanged();
202 // Something went wrong with the DELETE
203 elr.setResult(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
204 eventlogger.info(elr);
205 sendResponseError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, DB_PROBLEM_MSG, eventlogger);
211 sendResponseError(resp, HttpServletResponse.SC_NOT_FOUND, "Bad URL.", eventlogger);
215 * Get some information (such as a parameter) underneath the /internal/ namespace. See the <b>Internal API</b>
216 * document for details on how this method should be invoked.
219 public void doGet(HttpServletRequest req, HttpServletResponse resp) {
220 setIpAndFqdnForEelf("doGet");
221 eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER), getIdFromPath(req) + "");
222 String path = req.getPathInfo();
223 Properties props = (new DB()).getProperties();
224 if (path.equals("/halt") && !req.isSecure()) {
225 // request to halt the server - can ONLY come from localhost
226 String remote = req.getRemoteAddr();
227 if (remote.equals(props.getProperty("org.onap.dmaap.datarouter.provserver.localhost"))) {
228 intlogger.info("PROV0009 Request to HALT received.");
229 resp.setStatus(HttpServletResponse.SC_OK);
232 intlogger.info("PROV0010 Disallowed request to HALT received from " + remote);
233 resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
238 EventLogRecord elr = new EventLogRecord(req);
239 if (!isAuthorizedForInternal(req)) {
240 elr.setMessage("Unauthorized.");
241 elr.setResult(HttpServletResponse.SC_FORBIDDEN);
242 eventlogger.info(elr);
243 sendResponseError(resp, HttpServletResponse.SC_FORBIDDEN, "Unauthorized.", eventlogger);
246 if (path.equals("/fetchProv") && !req.isSecure()) {
247 // if request came from active_pod or standby_pod and it is not us, reload prov data
248 SynchronizerTask s = SynchronizerTask.getSynchronizer();
250 resp.setStatus(HttpServletResponse.SC_OK);
253 if (path.equals("/prov")) {
254 if (isProxyOK(req) && isProxyServer()) {
256 if (super.doGetWithFallback(req, resp)) {
259 } catch (IOException ioe) {
260 intlogger.error("IOException" + ioe.getMessage());
262 // fall back to returning the local data if the remote is unreachable
263 intlogger.info("Active server unavailable; falling back to local copy.");
265 Poker p = Poker.getPoker();
266 resp.setStatus(HttpServletResponse.SC_OK);
267 resp.setContentType(PROVFULL_CONTENT_TYPE2);
269 resp.getOutputStream().print(p.getProvisioningString());
270 } catch (IOException ioe) {
271 intlogger.error("IOException" + ioe.getMessage());
275 if (path.equals("/logs") || path.equals("/logs/")) {
276 resp.setStatus(HttpServletResponse.SC_OK);
277 resp.setContentType("application/json");
279 resp.getOutputStream().print(generateLogfileList().toString());
280 } catch (IOException ioe) {
281 intlogger.error("IOException" + ioe.getMessage());
285 if (path.startsWith("/logs/")) {
286 String logdir = props.getProperty("org.onap.dmaap.datarouter.provserver.accesslog.dir");
287 String logfile = path.substring(6);
288 if (logdir != null && logfile != null && logfile.indexOf('/') < 0) {
289 File log = new File(logdir + "/" + logfile);
290 if (log.exists() && log.isFile()) {
291 resp.setStatus(HttpServletResponse.SC_OK);
292 resp.setContentType("text/plain");
293 Path logpath = Paths.get(log.getAbsolutePath());
295 Files.copy(logpath, resp.getOutputStream());
296 } catch (IOException ioe) {
297 intlogger.error("IOException" + ioe.getMessage());
302 sendResponseError(resp, HttpServletResponse.SC_NO_CONTENT, "No file.", eventlogger);
305 if (path.startsWith("/api/")) {
306 if (isProxyOK(req) && isProxyServer()) {
308 super.doGet(req, resp);
309 } catch (IOException ioe) {
310 intlogger.error("IOException" + ioe.getMessage());
314 String key = path.substring(5);
315 if (key.length() > 0) {
316 Parameters param = Parameters.getParameter(key);
318 resp.setStatus(HttpServletResponse.SC_OK);
319 resp.setContentType("text/plain");
321 resp.getOutputStream().print(param.getValue() + "\n");
322 } catch (IOException ioe) {
323 intlogger.error("IOException" + ioe.getMessage());
329 if (path.equals("/drlogs") || path.equals("/drlogs/")) {
330 // Special POD <=> POD API to determine what log file records are loaded here
331 LogfileLoader lfl = LogfileLoader.getLoader();
332 resp.setStatus(HttpServletResponse.SC_OK);
333 resp.setContentType("text/plain");
335 resp.getOutputStream().print(lfl.getBitSet().toString());
336 } catch (IOException ioe) {
337 intlogger.error("IOException" + ioe.getMessage());
341 sendResponseError(resp, HttpServletResponse.SC_NOT_FOUND, "Bad URL.", eventlogger);
345 * Modify a parameter at the address /internal/api/<parameter>. See the <b>Internal API</b> document for
346 * details on how this method should be invoked.
349 public void doPut(HttpServletRequest req, HttpServletResponse resp) {
350 setIpAndFqdnForEelf("doPut");
351 eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER), getIdFromPath(req) + "");
352 EventLogRecord elr = new EventLogRecord(req);
353 if (!isAuthorizedForInternal(req)) {
354 elr.setMessage("Unauthorized.");
355 elr.setResult(HttpServletResponse.SC_FORBIDDEN);
356 eventlogger.info(elr);
357 sendResponseError(resp, HttpServletResponse.SC_FORBIDDEN, "Unauthorized.", eventlogger);
360 String path = req.getPathInfo();
361 if (path.startsWith("/api/")) {
362 if (isProxyOK(req) && isProxyServer()) {
364 super.doPut(req, resp);
365 } catch (IOException ioe) {
366 intlogger.error("IOException" + ioe.getMessage());
370 String key = path.substring(5);
371 if (key.length() > 0) {
372 Parameters param = Parameters.getParameter(key);
374 String t = catValues(req.getParameterValues("val"));
376 if (doUpdate(param)) {
377 elr.setResult(HttpServletResponse.SC_OK);
378 eventlogger.info(elr);
379 resp.setStatus(HttpServletResponse.SC_OK);
380 provisioningDataChanged();
381 provisioningParametersChanged();
383 // Something went wrong with the UPDATE
384 elr.setResult(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
385 eventlogger.info(elr);
386 sendResponseError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, DB_PROBLEM_MSG, eventlogger);
392 sendResponseError(resp, HttpServletResponse.SC_NOT_FOUND, "Bad URL.", eventlogger);
396 * Create some new information (such as a parameter or log entries) underneath the /internal/ namespace. See the
397 * <b>Internal API</b> document for details on how this method should be invoked.
399 @SuppressWarnings("resource")
401 public void doPost(HttpServletRequest req, HttpServletResponse resp) {
402 setIpAndFqdnForEelf("doPost");
403 eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF, req.getHeader(BEHALF_HEADER));
404 EventLogRecord elr = new EventLogRecord(req);
405 if (!isAuthorizedForInternal(req)) {
406 elr.setMessage("Unauthorized.");
407 elr.setResult(HttpServletResponse.SC_FORBIDDEN);
408 eventlogger.info(elr);
409 sendResponseError(resp, HttpServletResponse.SC_FORBIDDEN, "Unauthorized.", eventlogger);
413 String path = req.getPathInfo();
414 if (path.startsWith("/api/")) {
415 if (isProxyOK(req) && isProxyServer()) {
417 super.doPost(req, resp);
418 } catch (IOException ioe) {
419 intlogger.error("IOException" + ioe.getMessage());
423 String key = path.substring(5);
424 if (key.length() > 0) {
425 Parameters param = Parameters.getParameter(key);
427 String t = catValues(req.getParameterValues("val"));
428 param = new Parameters(key, t);
429 if (doInsert(param)) {
430 elr.setResult(HttpServletResponse.SC_OK);
431 eventlogger.info(elr);
432 resp.setStatus(HttpServletResponse.SC_OK);
433 provisioningDataChanged();
434 provisioningParametersChanged();
436 // Something went wrong with the INSERT
437 elr.setResult(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
438 eventlogger.info(elr);
439 sendResponseError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, DB_PROBLEM_MSG, eventlogger);
446 if (path.equals("/logs") || path.equals("/logs/")) {
447 String ctype = req.getHeader("Content-Type");
448 if (ctype == null || !ctype.equals("text/plain")) {
449 elr.setResult(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
450 elr.setMessage("Bad media type: " + ctype);
451 resp.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
452 eventlogger.info(elr);
455 String spooldir = (new DB()).getProperties().getProperty("org.onap.dmaap.datarouter.provserver.spooldir");
456 String spoolname = String.format("%d-%d-", System.currentTimeMillis(), Thread.currentThread().getId());
457 synchronized (logseq) {
458 // perhaps unnecessary, but it helps make the name unique
459 spoolname += logseq.toString();
462 String encoding = req.getHeader("Content-Encoding");
463 if (encoding != null) {
464 if (encoding.trim().equals("gzip")) {
467 elr.setResult(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
468 resp.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
469 eventlogger.info(elr);
473 // Determine space available -- available space must be at least 5%
474 FileSystem fs = (Paths.get(spooldir)).getFileSystem();
477 for (FileStore store : fs.getFileStores()) {
479 total += store.getTotalSpace();
480 avail += store.getUsableSpace();
481 } catch (IOException ioe) {
482 intlogger.error("IOException" + ioe.getMessage());
487 } catch (Exception e) {
489 if (((avail * 100) / total) < 5) {
490 elr.setResult(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
491 resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
492 eventlogger.info(elr);
495 Path tmppath = Paths.get(spooldir, spoolname);
496 Path donepath = Paths.get(spooldir, "IN." + spoolname);
498 Files.copy(req.getInputStream(), Paths.get(spooldir, spoolname), StandardCopyOption.REPLACE_EXISTING);
499 Files.move(tmppath, donepath, StandardCopyOption.REPLACE_EXISTING);
500 elr.setResult(HttpServletResponse.SC_CREATED);
501 resp.setStatus(HttpServletResponse.SC_CREATED);
502 eventlogger.info(elr);
503 LogfileLoader.getLoader(); // This starts the logfile loader "task"
504 } catch (IOException ioe) {
505 intlogger.error("IOException" + ioe.getMessage());
510 if (path.equals("/drlogs") || path.equals("/drlogs/")) {
511 // Receive post request and generate log entries
512 String ctype = req.getHeader("Content-Type");
513 if (ctype == null || !ctype.equals("text/plain")) {
514 elr.setResult(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
515 elr.setMessage("Bad media type: " + ctype);
516 resp.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
517 eventlogger.info(elr);
521 InputStream is = req.getInputStream();
522 ByteArrayOutputStream bos = new ByteArrayOutputStream();
524 while ((ch = is.read()) >= 0) {
527 RLEBitSet bs = new RLEBitSet(bos.toString()); // The set of records to retrieve
528 elr.setResult(HttpServletResponse.SC_OK);
529 resp.setStatus(HttpServletResponse.SC_OK);
530 resp.setContentType("text/plain");
531 LogRecord.printLogRecords(resp.getOutputStream(), bs);
532 eventlogger.info(elr);
533 } catch (IOException ioe) {
534 intlogger.error("IOException" + ioe.getMessage());
539 elr.setResult(HttpServletResponse.SC_NOT_FOUND);
540 sendResponseError(resp, HttpServletResponse.SC_NOT_FOUND, "Bad URL.", eventlogger);
541 eventlogger.info(elr);
544 private String catValues(String[] v) {
545 StringBuilder sb = new StringBuilder();
554 return sb.toString();
557 private JSONArray generateLogfileList() {
558 JSONArray ja = new JSONArray();
559 Properties p = (new DB()).getProperties();
560 String s = p.getProperty("org.onap.dmaap.datarouter.provserver.accesslog.dir");
562 String[] dirs = s.split(",");
563 for (String dir : dirs) {
564 File f = new File(dir);
565 String[] list = f.list();
567 for (String s2 : list) {
568 if (!s2.startsWith(".")) {