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 final Object lock = new Object();
160 private static Integer logseq = 0; // another piece of info to make log spool file names unique
161 //Adding EELF Logger Rally:US664892
162 private static EELFLogger eelflogger = EELFManager.getInstance()
163 .getLogger(InternalServlet.class);
166 * Delete a parameter at the address /internal/api/<parameter>. See the <b>Internal API</b> document for
167 * details on how this method should be invoked.
170 public void doDelete(HttpServletRequest req, HttpServletResponse resp) {
171 setIpFqdnRequestIDandInvocationIDForEelf("doDelete", req);
172 eelflogger.info(EelfMsgs.ENTRY);
174 eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER), getIdFromPath(req) + "");
175 EventLogRecord elr = new EventLogRecord(req);
176 if (!isAuthorizedForInternal(req)) {
177 elr.setMessage("Unauthorized.");
178 elr.setResult(HttpServletResponse.SC_FORBIDDEN);
179 eventlogger.info(elr);
180 sendResponseError(resp, HttpServletResponse.SC_FORBIDDEN, "Unauthorized.", eventlogger);
184 String path = req.getPathInfo();
185 if (path.startsWith("/api/")) {
186 if (isProxyOK(req) && isProxyServer()) {
187 super.doDelete(req, resp);
190 String key = path.substring(5);
191 if (key.length() > 0) {
192 Parameters param = Parameters.getParameter(key);
194 if (doDelete(param)) {
195 elr.setResult(HttpServletResponse.SC_OK);
196 eventlogger.info(elr);
197 resp.setStatus(HttpServletResponse.SC_OK);
198 provisioningDataChanged();
199 provisioningParametersChanged();
201 // Something went wrong with the DELETE
202 elr.setResult(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
203 eventlogger.info(elr);
204 sendResponseError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, DB_PROBLEM_MSG, eventlogger);
210 sendResponseError(resp, HttpServletResponse.SC_NOT_FOUND, "Bad URL.", eventlogger);
212 eelflogger.info(EelfMsgs.EXIT);
217 * Get some information (such as a parameter) underneath the /internal/ namespace. See the <b>Internal API</b>
218 * document for details on how this method should be invoked.
221 public void doGet(HttpServletRequest req, HttpServletResponse resp) {
222 setIpFqdnRequestIDandInvocationIDForEelf("doGet",req);
223 eelflogger.info(EelfMsgs.ENTRY);
225 eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER), getIdFromPath(req) + "");
226 String path = req.getPathInfo();
227 Properties props = (new DB()).getProperties();
228 if (path.equals("/halt") && !req.isSecure()) {
229 // request to halt the server - can ONLY come from localhost
230 String remote = req.getRemoteAddr();
231 if (remote.equals(props.getProperty("org.onap.dmaap.datarouter.provserver.localhost"))) {
232 intlogger.info("PROV0009 Request to HALT received.");
233 resp.setStatus(HttpServletResponse.SC_OK);
236 intlogger.info("PROV0010 Disallowed request to HALT received from " + remote);
237 resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
242 EventLogRecord elr = new EventLogRecord(req);
243 if (!isAuthorizedForInternal(req)) {
244 elr.setMessage("Unauthorized.");
245 elr.setResult(HttpServletResponse.SC_FORBIDDEN);
246 eventlogger.info(elr);
247 sendResponseError(resp, HttpServletResponse.SC_FORBIDDEN, "Unauthorized.", eventlogger);
250 if (path.equals("/fetchProv") && !req.isSecure()) {
251 // if request came from active_pod or standby_pod and it is not us, reload prov data
252 SynchronizerTask s = SynchronizerTask.getSynchronizer();
254 resp.setStatus(HttpServletResponse.SC_OK);
257 if (path.equals("/prov")) {
258 if (isProxyOK(req) && isProxyServer()) {
259 if (super.doGetWithFallback(req, resp)) {
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()) {
307 super.doGet(req, resp);
310 String key = path.substring(5);
311 if (key.length() > 0) {
312 Parameters param = Parameters.getParameter(key);
314 resp.setStatus(HttpServletResponse.SC_OK);
315 resp.setContentType("text/plain");
317 resp.getOutputStream().print(param.getValue() + "\n");
318 } catch (IOException ioe) {
319 intlogger.error("IOException" + ioe.getMessage());
325 if (path.equals("/drlogs") || path.equals("/drlogs/")) {
326 // Special POD <=> POD API to determine what log file records are loaded here
327 LogfileLoader lfl = LogfileLoader.getLoader();
328 resp.setStatus(HttpServletResponse.SC_OK);
329 resp.setContentType("text/plain");
331 resp.getOutputStream().print(lfl.getBitSet().toString());
332 } catch (IOException ioe) {
333 intlogger.error("IOException" + ioe.getMessage());
337 sendResponseError(resp, HttpServletResponse.SC_NOT_FOUND, "Bad URL.", eventlogger);
339 eelflogger.info(EelfMsgs.EXIT);
344 * Modify a parameter at the address /internal/api/<parameter>. See the <b>Internal API</b> document for
345 * details on how this method should be invoked.
348 public void doPut(HttpServletRequest req, HttpServletResponse resp) {
349 setIpFqdnRequestIDandInvocationIDForEelf("doPut", req);
350 eelflogger.info(EelfMsgs.ENTRY);
352 eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER), getIdFromPath(req) + "");
353 EventLogRecord elr = new EventLogRecord(req);
354 if (!isAuthorizedForInternal(req)) {
355 elr.setMessage("Unauthorized.");
356 elr.setResult(HttpServletResponse.SC_FORBIDDEN);
357 eventlogger.info(elr);
358 sendResponseError(resp, HttpServletResponse.SC_FORBIDDEN, "Unauthorized.", eventlogger);
361 String path = req.getPathInfo();
362 if (path.startsWith("/api/")) {
363 if (isProxyOK(req) && isProxyServer()) {
364 super.doPut(req, resp);
367 String key = path.substring(5);
368 if (key.length() > 0) {
369 Parameters param = Parameters.getParameter(key);
371 String t = catValues(req.getParameterValues("val"));
373 if (doUpdate(param)) {
374 elr.setResult(HttpServletResponse.SC_OK);
375 eventlogger.info(elr);
376 resp.setStatus(HttpServletResponse.SC_OK);
377 provisioningDataChanged();
378 provisioningParametersChanged();
380 // Something went wrong with the UPDATE
381 elr.setResult(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
382 eventlogger.info(elr);
383 sendResponseError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, DB_PROBLEM_MSG, eventlogger);
389 sendResponseError(resp, HttpServletResponse.SC_NOT_FOUND, "Bad URL.", eventlogger);
391 eelflogger.info(EelfMsgs.EXIT);
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 setIpFqdnRequestIDandInvocationIDForEelf("doPost", req);
403 eelflogger.info(EelfMsgs.ENTRY);
405 eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF, req.getHeader(BEHALF_HEADER));
406 EventLogRecord elr = new EventLogRecord(req);
407 if (!isAuthorizedForInternal(req)) {
408 elr.setMessage("Unauthorized.");
409 elr.setResult(HttpServletResponse.SC_FORBIDDEN);
410 eventlogger.info(elr);
411 sendResponseError(resp, HttpServletResponse.SC_FORBIDDEN, "Unauthorized.", eventlogger);
415 String path = req.getPathInfo();
416 if (path.startsWith("/api/")) {
417 if (isProxyOK(req) && isProxyServer()) {
418 super.doPost(req, resp);
421 String key = path.substring(5);
422 if (key.length() > 0) {
423 Parameters param = Parameters.getParameter(key);
425 String t = catValues(req.getParameterValues("val"));
426 param = new Parameters(key, t);
427 if (doInsert(param)) {
428 elr.setResult(HttpServletResponse.SC_OK);
429 eventlogger.info(elr);
430 resp.setStatus(HttpServletResponse.SC_OK);
431 provisioningDataChanged();
432 provisioningParametersChanged();
434 // Something went wrong with the INSERT
435 elr.setResult(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
436 eventlogger.info(elr);
437 sendResponseError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, DB_PROBLEM_MSG, eventlogger);
444 if (path.equals("/logs") || path.equals("/logs/")) {
445 String ctype = req.getHeader("Content-Type");
446 if (ctype == null || !ctype.equals("text/plain")) {
447 elr.setResult(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
448 elr.setMessage("Bad media type: " + ctype);
449 resp.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
450 eventlogger.info(elr);
453 String spooldir = (new DB()).getProperties().getProperty("org.onap.dmaap.datarouter.provserver.spooldir");
454 String spoolname = String.format("%d-%d-", System.currentTimeMillis(), Thread.currentThread().getId());
455 synchronized (lock) {
456 // perhaps unnecessary, but it helps make the name unique
457 spoolname += logseq.toString();
460 String encoding = req.getHeader("Content-Encoding");
461 if (encoding != null) {
462 if (encoding.trim().equals("gzip")) {
465 elr.setResult(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
466 resp.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
467 eventlogger.info(elr);
471 // Determine space available -- available space must be at least 5%
472 FileSystem fs = (Paths.get(spooldir)).getFileSystem();
475 for (FileStore store : fs.getFileStores()) {
477 total += store.getTotalSpace();
478 avail += store.getUsableSpace();
479 } catch (IOException ioe) {
480 intlogger.error("IOException" + ioe.getMessage());
485 } catch (Exception e) {
487 if (((avail * 100) / total) < 5) {
488 elr.setResult(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
489 resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
490 eventlogger.info(elr);
493 Path tmppath = Paths.get(spooldir, spoolname);
494 Path donepath = Paths.get(spooldir, "IN." + spoolname);
496 Files.copy(req.getInputStream(), Paths.get(spooldir, spoolname), StandardCopyOption.REPLACE_EXISTING);
497 Files.move(tmppath, donepath, StandardCopyOption.REPLACE_EXISTING);
498 elr.setResult(HttpServletResponse.SC_CREATED);
499 resp.setStatus(HttpServletResponse.SC_CREATED);
500 eventlogger.info(elr);
501 LogfileLoader.getLoader(); // This starts the logfile loader "task"
502 } catch (IOException ioe) {
503 intlogger.error("IOException" + ioe.getMessage());
508 if (path.equals("/drlogs") || path.equals("/drlogs/")) {
509 // Receive post request and generate log entries
510 String ctype = req.getHeader("Content-Type");
511 if (ctype == null || !ctype.equals("text/plain")) {
512 elr.setResult(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
513 elr.setMessage("Bad media type: " + ctype);
514 resp.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
515 eventlogger.info(elr);
519 InputStream is = req.getInputStream();
520 ByteArrayOutputStream bos = new ByteArrayOutputStream();
522 while ((ch = is.read()) >= 0) {
525 RLEBitSet bs = new RLEBitSet(bos.toString()); // The set of records to retrieve
526 elr.setResult(HttpServletResponse.SC_OK);
527 resp.setStatus(HttpServletResponse.SC_OK);
528 resp.setContentType("text/plain");
529 LogRecord.printLogRecords(resp.getOutputStream(), bs);
530 eventlogger.info(elr);
531 } catch (IOException ioe) {
532 intlogger.error("IOException" + ioe.getMessage());
537 elr.setResult(HttpServletResponse.SC_NOT_FOUND);
538 sendResponseError(resp, HttpServletResponse.SC_NOT_FOUND, "Bad URL.", eventlogger);
539 eventlogger.info(elr);
541 eelflogger.info(EelfMsgs.EXIT);
545 private String catValues(String[] v) {
546 StringBuilder sb = new StringBuilder();
555 return sb.toString();
558 private JSONArray generateLogfileList() {
559 JSONArray ja = new JSONArray();
560 Properties p = (new DB()).getProperties();
561 String s = p.getProperty("org.onap.dmaap.datarouter.provserver.accesslog.dir");
563 String[] dirs = s.split(",");
564 for (String dir : dirs) {
565 File f = new File(dir);
566 String[] list = f.list();
568 for (String s2 : list) {
569 if (!s2.startsWith(".")) {