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("org.onap.dmaap.datarouter.provisioning.InternalServlet");
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 setIpAndFqdnForEelf("doDelete");
172 eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER), getIdFromPath(req) + "");
173 EventLogRecord elr = new EventLogRecord(req);
174 if (!isAuthorizedForInternal(req)) {
175 elr.setMessage("Unauthorized.");
176 elr.setResult(HttpServletResponse.SC_FORBIDDEN);
177 eventlogger.info(elr);
178 sendResponseError(resp, HttpServletResponse.SC_FORBIDDEN, "Unauthorized.", eventlogger);
182 String path = req.getPathInfo();
183 if (path.startsWith("/api/")) {
184 if (isProxyOK(req) && isProxyServer()) {
185 super.doDelete(req, resp);
188 String key = path.substring(5);
189 if (key.length() > 0) {
190 Parameters param = Parameters.getParameter(key);
192 if (doDelete(param)) {
193 elr.setResult(HttpServletResponse.SC_OK);
194 eventlogger.info(elr);
195 resp.setStatus(HttpServletResponse.SC_OK);
196 provisioningDataChanged();
197 provisioningParametersChanged();
199 // Something went wrong with the DELETE
200 elr.setResult(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
201 eventlogger.info(elr);
202 sendResponseError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, DB_PROBLEM_MSG, eventlogger);
208 sendResponseError(resp, HttpServletResponse.SC_NOT_FOUND, "Bad URL.", eventlogger);
212 * Get some information (such as a parameter) underneath the /internal/ namespace. See the <b>Internal API</b>
213 * document for details on how this method should be invoked.
216 public void doGet(HttpServletRequest req, HttpServletResponse resp) {
217 setIpAndFqdnForEelf("doGet");
218 eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER), getIdFromPath(req) + "");
219 String path = req.getPathInfo();
220 Properties props = (new DB()).getProperties();
221 if (path.equals("/halt") && !req.isSecure()) {
222 // request to halt the server - can ONLY come from localhost
223 String remote = req.getRemoteAddr();
224 if (remote.equals(props.getProperty("org.onap.dmaap.datarouter.provserver.localhost"))) {
225 intlogger.info("PROV0009 Request to HALT received.");
226 resp.setStatus(HttpServletResponse.SC_OK);
229 intlogger.info("PROV0010 Disallowed request to HALT received from " + remote);
230 resp.setStatus(HttpServletResponse.SC_FORBIDDEN);
235 EventLogRecord elr = new EventLogRecord(req);
236 if (!isAuthorizedForInternal(req)) {
237 elr.setMessage("Unauthorized.");
238 elr.setResult(HttpServletResponse.SC_FORBIDDEN);
239 eventlogger.info(elr);
240 sendResponseError(resp, HttpServletResponse.SC_FORBIDDEN, "Unauthorized.", eventlogger);
243 if (path.equals("/fetchProv") && !req.isSecure()) {
244 // if request came from active_pod or standby_pod and it is not us, reload prov data
245 SynchronizerTask s = SynchronizerTask.getSynchronizer();
247 resp.setStatus(HttpServletResponse.SC_OK);
250 if (path.equals("/prov")) {
251 if (isProxyOK(req) && isProxyServer()) {
252 if (super.doGetWithFallback(req, resp)) {
255 // fall back to returning the local data if the remote is unreachable
256 intlogger.info("Active server unavailable; falling back to local copy.");
258 Poker p = Poker.getPoker();
259 resp.setStatus(HttpServletResponse.SC_OK);
260 resp.setContentType(PROVFULL_CONTENT_TYPE2);
262 resp.getOutputStream().print(p.getProvisioningString());
263 } catch (IOException ioe) {
264 intlogger.error("IOException" + ioe.getMessage());
268 if (path.equals("/logs") || path.equals("/logs/")) {
269 resp.setStatus(HttpServletResponse.SC_OK);
270 resp.setContentType("application/json");
272 resp.getOutputStream().print(generateLogfileList().toString());
273 } catch (IOException ioe) {
274 intlogger.error("IOException" + ioe.getMessage());
278 if (path.startsWith("/logs/")) {
279 String logdir = props.getProperty("org.onap.dmaap.datarouter.provserver.accesslog.dir");
280 String logfile = path.substring(6);
281 if (logdir != null && logfile != null && logfile.indexOf('/') < 0) {
282 File log = new File(logdir + "/" + logfile);
283 if (log.exists() && log.isFile()) {
284 resp.setStatus(HttpServletResponse.SC_OK);
285 resp.setContentType("text/plain");
286 Path logpath = Paths.get(log.getAbsolutePath());
288 Files.copy(logpath, resp.getOutputStream());
289 } catch (IOException ioe) {
290 intlogger.error("IOException" + ioe.getMessage());
295 sendResponseError(resp, HttpServletResponse.SC_NO_CONTENT, "No file.", eventlogger);
298 if (path.startsWith("/api/")) {
299 if (isProxyOK(req) && isProxyServer()) {
300 super.doGet(req, resp);
303 String key = path.substring(5);
304 if (key.length() > 0) {
305 Parameters param = Parameters.getParameter(key);
307 resp.setStatus(HttpServletResponse.SC_OK);
308 resp.setContentType("text/plain");
310 resp.getOutputStream().print(param.getValue() + "\n");
311 } catch (IOException ioe) {
312 intlogger.error("IOException" + ioe.getMessage());
318 if (path.equals("/drlogs") || path.equals("/drlogs/")) {
319 // Special POD <=> POD API to determine what log file records are loaded here
320 LogfileLoader lfl = LogfileLoader.getLoader();
321 resp.setStatus(HttpServletResponse.SC_OK);
322 resp.setContentType("text/plain");
324 resp.getOutputStream().print(lfl.getBitSet().toString());
325 } catch (IOException ioe) {
326 intlogger.error("IOException" + ioe.getMessage());
330 sendResponseError(resp, HttpServletResponse.SC_NOT_FOUND, "Bad URL.", eventlogger);
334 * Modify a parameter at the address /internal/api/<parameter>. See the <b>Internal API</b> document for
335 * details on how this method should be invoked.
338 public void doPut(HttpServletRequest req, HttpServletResponse resp) {
339 setIpAndFqdnForEelf("doPut");
340 eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER), getIdFromPath(req) + "");
341 EventLogRecord elr = new EventLogRecord(req);
342 if (!isAuthorizedForInternal(req)) {
343 elr.setMessage("Unauthorized.");
344 elr.setResult(HttpServletResponse.SC_FORBIDDEN);
345 eventlogger.info(elr);
346 sendResponseError(resp, HttpServletResponse.SC_FORBIDDEN, "Unauthorized.", eventlogger);
349 String path = req.getPathInfo();
350 if (path.startsWith("/api/")) {
351 if (isProxyOK(req) && isProxyServer()) {
352 super.doPut(req, resp);
355 String key = path.substring(5);
356 if (key.length() > 0) {
357 Parameters param = Parameters.getParameter(key);
359 String t = catValues(req.getParameterValues("val"));
361 if (doUpdate(param)) {
362 elr.setResult(HttpServletResponse.SC_OK);
363 eventlogger.info(elr);
364 resp.setStatus(HttpServletResponse.SC_OK);
365 provisioningDataChanged();
366 provisioningParametersChanged();
368 // Something went wrong with the UPDATE
369 elr.setResult(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
370 eventlogger.info(elr);
371 sendResponseError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, DB_PROBLEM_MSG, eventlogger);
377 sendResponseError(resp, HttpServletResponse.SC_NOT_FOUND, "Bad URL.", eventlogger);
381 * Create some new information (such as a parameter or log entries) underneath the /internal/ namespace. See the
382 * <b>Internal API</b> document for details on how this method should be invoked.
384 @SuppressWarnings("resource")
386 public void doPost(HttpServletRequest req, HttpServletResponse resp) {
387 setIpAndFqdnForEelf("doPost");
388 eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF, req.getHeader(BEHALF_HEADER));
389 EventLogRecord elr = new EventLogRecord(req);
390 if (!isAuthorizedForInternal(req)) {
391 elr.setMessage("Unauthorized.");
392 elr.setResult(HttpServletResponse.SC_FORBIDDEN);
393 eventlogger.info(elr);
394 sendResponseError(resp, HttpServletResponse.SC_FORBIDDEN, "Unauthorized.", eventlogger);
398 String path = req.getPathInfo();
399 if (path.startsWith("/api/")) {
400 if (isProxyOK(req) && isProxyServer()) {
401 super.doPost(req, resp);
404 String key = path.substring(5);
405 if (key.length() > 0) {
406 Parameters param = Parameters.getParameter(key);
408 String t = catValues(req.getParameterValues("val"));
409 param = new Parameters(key, t);
410 if (doInsert(param)) {
411 elr.setResult(HttpServletResponse.SC_OK);
412 eventlogger.info(elr);
413 resp.setStatus(HttpServletResponse.SC_OK);
414 provisioningDataChanged();
415 provisioningParametersChanged();
417 // Something went wrong with the INSERT
418 elr.setResult(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
419 eventlogger.info(elr);
420 sendResponseError(resp, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, DB_PROBLEM_MSG, eventlogger);
427 if (path.equals("/logs") || path.equals("/logs/")) {
428 String ctype = req.getHeader("Content-Type");
429 if (ctype == null || !ctype.equals("text/plain")) {
430 elr.setResult(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
431 elr.setMessage("Bad media type: " + ctype);
432 resp.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
433 eventlogger.info(elr);
436 String spooldir = (new DB()).getProperties().getProperty("org.onap.dmaap.datarouter.provserver.spooldir");
437 String spoolname = String.format("%d-%d-", System.currentTimeMillis(), Thread.currentThread().getId());
438 synchronized (lock) {
439 // perhaps unnecessary, but it helps make the name unique
440 spoolname += logseq.toString();
443 String encoding = req.getHeader("Content-Encoding");
444 if (encoding != null) {
445 if (encoding.trim().equals("gzip")) {
448 elr.setResult(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
449 resp.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
450 eventlogger.info(elr);
454 // Determine space available -- available space must be at least 5%
455 FileSystem fs = (Paths.get(spooldir)).getFileSystem();
458 for (FileStore store : fs.getFileStores()) {
460 total += store.getTotalSpace();
461 avail += store.getUsableSpace();
462 } catch (IOException ioe) {
463 intlogger.error("IOException" + ioe.getMessage());
468 } catch (Exception e) {
470 if (((avail * 100) / total) < 5) {
471 elr.setResult(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
472 resp.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
473 eventlogger.info(elr);
476 Path tmppath = Paths.get(spooldir, spoolname);
477 Path donepath = Paths.get(spooldir, "IN." + spoolname);
479 Files.copy(req.getInputStream(), Paths.get(spooldir, spoolname), StandardCopyOption.REPLACE_EXISTING);
480 Files.move(tmppath, donepath, StandardCopyOption.REPLACE_EXISTING);
481 elr.setResult(HttpServletResponse.SC_CREATED);
482 resp.setStatus(HttpServletResponse.SC_CREATED);
483 eventlogger.info(elr);
484 LogfileLoader.getLoader(); // This starts the logfile loader "task"
485 } catch (IOException ioe) {
486 intlogger.error("IOException" + ioe.getMessage());
491 if (path.equals("/drlogs") || path.equals("/drlogs/")) {
492 // Receive post request and generate log entries
493 String ctype = req.getHeader("Content-Type");
494 if (ctype == null || !ctype.equals("text/plain")) {
495 elr.setResult(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
496 elr.setMessage("Bad media type: " + ctype);
497 resp.setStatus(HttpServletResponse.SC_UNSUPPORTED_MEDIA_TYPE);
498 eventlogger.info(elr);
502 InputStream is = req.getInputStream();
503 ByteArrayOutputStream bos = new ByteArrayOutputStream();
505 while ((ch = is.read()) >= 0) {
508 RLEBitSet bs = new RLEBitSet(bos.toString()); // The set of records to retrieve
509 elr.setResult(HttpServletResponse.SC_OK);
510 resp.setStatus(HttpServletResponse.SC_OK);
511 resp.setContentType("text/plain");
512 LogRecord.printLogRecords(resp.getOutputStream(), bs);
513 eventlogger.info(elr);
514 } catch (IOException ioe) {
515 intlogger.error("IOException" + ioe.getMessage());
520 elr.setResult(HttpServletResponse.SC_NOT_FOUND);
521 sendResponseError(resp, HttpServletResponse.SC_NOT_FOUND, "Bad URL.", eventlogger);
522 eventlogger.info(elr);
525 private String catValues(String[] v) {
526 StringBuilder sb = new StringBuilder();
535 return sb.toString();
538 private JSONArray generateLogfileList() {
539 JSONArray ja = new JSONArray();
540 Properties p = (new DB()).getProperties();
541 String s = p.getProperty("org.onap.dmaap.datarouter.provserver.accesslog.dir");
543 String[] dirs = s.split(",");
544 for (String dir : dirs) {
545 File f = new File(dir);
546 String[] list = f.list();
548 for (String s2 : list) {
549 if (!s2.startsWith(".")) {