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 org.onap.dmaap.datarouter.node.NodeUtils.sendResponseError;
29 import com.att.eelf.configuration.EELFLogger;
30 import com.att.eelf.configuration.EELFManager;
32 import java.io.FileOutputStream;
33 import java.io.FileWriter;
34 import java.io.IOException;
35 import java.io.InputStream;
36 import java.io.OutputStream;
37 import java.io.Writer;
38 import java.nio.file.Files;
39 import java.nio.file.Path;
40 import java.nio.file.Paths;
41 import java.util.Enumeration;
42 import java.util.regex.Pattern;
43 import javax.servlet.ServletException;
44 import javax.servlet.http.HttpServlet;
45 import javax.servlet.http.HttpServletRequest;
46 import javax.servlet.http.HttpServletResponse;
47 import org.apache.log4j.Logger;
48 import org.onap.dmaap.datarouter.node.eelf.EelfMsgs;
52 * Servlet for handling all http and https requests to the data router node
54 * Handled requests are:
56 * GET http://<i>node</i>/internal/fetchProv - fetch the provisioning data
58 * PUT/DELETE https://<i>node</i>/internal/publish/<i>fileid</i> - n2n transfer
60 * PUT/DELETE https://<i>node</i>/publish/<i>feedid</i>/<i>fileid</i> - publsh request
62 public class NodeServlet extends HttpServlet {
64 private static Logger logger = Logger.getLogger("org.onap.dmaap.datarouter.node.NodeServlet");
65 private static NodeConfigManager config;
66 private static Pattern MetaDataPattern;
67 //Adding EELF Logger Rally:US664892
68 private static EELFLogger eelflogger = EELFManager.getInstance()
69 .getLogger(NodeServlet.class);
72 final String ws = "\\s*";
73 // assume that \\ and \" have been replaced by X
74 final String string = "\"[^\"]*\"";
75 //String string = "\"(?:[^\"\\\\]|\\\\.)*\"";
76 final String number = "[+-]?(?:\\.\\d+|(?:0|[1-9]\\d*)(?:\\.\\d*)?)(?:[eE][+-]?\\d+)?";
77 final String value = "(?:" + string + "|" + number + "|null|true|false)";
78 final String item = string + ws + ":" + ws + value + ws;
79 final String object = ws + "\\{" + ws + "(?:" + item + "(?:" + "," + ws + item + ")*)?\\}" + ws;
80 MetaDataPattern = Pattern.compile(object, Pattern.DOTALL);
84 * Get the NodeConfigurationManager
87 config = NodeConfigManager.getInstance();
88 logger.info("NODE0101 Node Servlet Configured");
91 private boolean down(HttpServletResponse resp) throws IOException {
92 if (config.isShutdown() || !config.isConfigured()) {
93 sendResponseError(resp, HttpServletResponse.SC_SERVICE_UNAVAILABLE, logger);
94 logger.info("NODE0102 Rejecting request: Service is being quiesced");
101 * Handle a GET for /internal/fetchProv
103 protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
104 NodeUtils.setIpAndFqdnForEelf("doGet");
105 NodeUtils.setRequestIdAndInvocationId(req);
106 eelflogger.info(EelfMsgs.ENTRY);
108 eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-ATT-DR-ON-BEHALF-OF"),
109 getIdFromPath(req) + "");
115 } catch (IOException ioe) {
116 logger.error("IOException" + ioe.getMessage());
118 String path = req.getPathInfo();
119 String qs = req.getQueryString();
120 String ip = req.getRemoteAddr();
122 path = path + "?" + qs;
124 if ("/internal/fetchProv".equals(path)) {
126 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
128 } else if (path.startsWith("/internal/resetSubscription/")) {
129 String subid = path.substring(28);
130 if (subid.length() != 0 && subid.indexOf('/') == -1) {
131 NodeMain.resetQueue(subid, ip);
132 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
137 logger.info("NODE0103 Rejecting invalid GET of " + path + " from " + ip);
138 sendResponseError(resp, HttpServletResponse.SC_NOT_FOUND, logger);
140 eelflogger.info(EelfMsgs.EXIT);
145 * Handle all PUT requests
147 protected void doPut(HttpServletRequest req, HttpServletResponse resp) {
148 NodeUtils.setIpAndFqdnForEelf("doPut");
149 NodeUtils.setRequestIdAndInvocationId(req);
150 eelflogger.info(EelfMsgs.ENTRY);
151 eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-ATT-DR-ON-BEHALF-OF"),
152 getIdFromPath(req) + "");
154 common(req, resp, true);
155 } catch (IOException ioe) {
156 logger.error("IOException" + ioe.getMessage());
157 eelflogger.info(EelfMsgs.EXIT);
158 } catch (ServletException se) {
159 logger.error("ServletException" + se.getMessage());
160 eelflogger.info(EelfMsgs.EXIT);
165 * Handle all DELETE requests
167 protected void doDelete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
168 NodeUtils.setIpAndFqdnForEelf("doDelete");
169 NodeUtils.setRequestIdAndInvocationId(req);
170 eelflogger.info(EelfMsgs.ENTRY);
171 eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader("X-ATT-DR-ON-BEHALF-OF"),
172 getIdFromPath(req) + "");
174 common(req, resp, false);
175 } catch (IOException ioe) {
176 logger.error("IOException" + ioe.getMessage());
177 eelflogger.info(EelfMsgs.EXIT);
178 } catch (ServletException se) {
179 logger.error("ServletException" + se.getMessage());
180 eelflogger.info(EelfMsgs.EXIT);
185 private void common(HttpServletRequest req, HttpServletResponse resp, boolean isput)
186 throws ServletException, IOException {
188 eelflogger.info(EelfMsgs.EXIT);
191 if (!req.isSecure()) {
193 "NODE0104 Rejecting insecure PUT or DELETE of " + req.getPathInfo() + " from " + req
195 resp.sendError(HttpServletResponse.SC_FORBIDDEN, "https required on publish requests");
196 eelflogger.info(EelfMsgs.EXIT);
199 String fileid = req.getPathInfo();
200 if (fileid == null) {
201 logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
203 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
204 "Invalid request URI. Expecting <feed-publishing-url>/<fileid>.");
205 eelflogger.info(EelfMsgs.EXIT);
208 String feedid = null;
210 String credentials = req.getHeader("Authorization");
211 if (credentials == null) {
212 logger.info("NODE0106 Rejecting unauthenticated PUT or DELETE of " + req.getPathInfo() + " from " + req
214 resp.sendError(HttpServletResponse.SC_FORBIDDEN, "Authorization header required");
215 eelflogger.info(EelfMsgs.EXIT);
218 String ip = req.getRemoteAddr();
219 String lip = req.getLocalAddr();
221 String xpubid = null;
222 String rcvd = NodeUtils.logts(System.currentTimeMillis()) + ";from=" + ip + ";by=" + lip;
223 Target[] targets = null;
224 if (fileid.startsWith("/publish/")) {
225 fileid = fileid.substring(9);
226 int i = fileid.indexOf('/');
227 if (i == -1 || i == fileid.length() - 1) {
228 logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
230 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
231 "Invalid request URI. Expecting <feed-publishing-url>/<fileid>. Possible missing fileid.");
232 eelflogger.info(EelfMsgs.EXIT);
235 feedid = fileid.substring(0, i);
236 fileid = fileid.substring(i + 1);
237 pubid = config.getPublishId();
238 xpubid = req.getHeader("X-ATT-DR-PUBLISH-ID");
239 targets = config.getTargets(feedid);
240 } else if (fileid.startsWith("/internal/publish/")) {
241 if (!config.isAnotherNode(credentials, ip)) {
242 logger.info("NODE0107 Rejecting unauthorized node-to-node transfer attempt from " + ip);
243 resp.sendError(HttpServletResponse.SC_FORBIDDEN);
244 eelflogger.info(EelfMsgs.EXIT);
247 fileid = fileid.substring(18);
248 pubid = req.getHeader("X-ATT-DR-PUBLISH-ID");
249 targets = config.parseRouting(req.getHeader("X-ATT-DR-ROUTING"));
251 logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
253 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
254 "Invalid request URI. Expecting <feed-publishing-url>/<fileid>.");
255 eelflogger.info(EelfMsgs.EXIT);
258 if (fileid.indexOf('/') != -1) {
259 logger.info("NODE0105 Rejecting bad URI for PUT or DELETE of " + req.getPathInfo() + " from " + req
261 resp.sendError(HttpServletResponse.SC_NOT_FOUND,
262 "Invalid request URI. Expecting <feed-publishing-url>/<fileid>.");
263 eelflogger.info(EelfMsgs.EXIT);
266 String qs = req.getQueryString();
268 fileid = fileid + "?" + qs;
270 String hp = config.getMyName();
271 int xp = config.getExtHttpsPort();
275 String logurl = "https://" + hp + "/internal/publish/" + fileid;
276 if (feedid != null) {
277 logurl = "https://" + hp + "/publish/" + feedid + "/" + fileid;
278 String reason = config.isPublishPermitted(feedid, credentials, ip);
279 if (reason != null) {
281 "NODE0111 Rejecting unauthorized publish attempt to feed " + feedid + " fileid " + fileid
283 + ip + " reason " + reason);
284 resp.sendError(HttpServletResponse.SC_FORBIDDEN, reason);
285 eelflogger.info(EelfMsgs.EXIT);
288 user = config.getAuthUser(feedid, credentials);
289 String newnode = config.getIngressNode(feedid, user, ip);
290 if (newnode != null) {
292 int iport = config.getExtHttpsPort();
296 String redirto = "https://" + newnode + port + "/publish/" + feedid + "/" + fileid;
298 "NODE0108 Redirecting publish attempt for feed " + feedid + " user " + user + " ip " + ip
301 resp.sendRedirect(redirto);
302 eelflogger.info(EelfMsgs.EXIT);
305 resp.setHeader("X-ATT-DR-PUBLISH-ID", pubid);
307 String fbase = config.getSpoolDir() + "/" + pubid;
308 File data = new File(fbase);
309 File meta = new File(fbase + ".M");
310 OutputStream dos = null;
312 InputStream is = null;
314 StringBuffer mx = new StringBuffer();
315 mx.append(req.getMethod()).append('\t').append(fileid).append('\n');
316 Enumeration hnames = req.getHeaderNames();
318 Boolean hasRequestIdHeader = false;
319 Boolean hasInvocationIdHeader = false;
320 while (hnames.hasMoreElements()) {
321 String hn = (String) hnames.nextElement();
322 String hnlc = hn.toLowerCase();
323 if ((isput && ("content-type".equals(hnlc) ||
324 "content-language".equals(hnlc) ||
325 "content-md5".equals(hnlc) ||
326 "content-range".equals(hnlc))) ||
327 "x-att-dr-meta".equals(hnlc) ||
328 (feedid == null && "x-att-dr-received".equals(hnlc)) ||
329 (hnlc.startsWith("x-") && !hnlc.startsWith("x-att-dr-"))) {
330 Enumeration hvals = req.getHeaders(hn);
331 while (hvals.hasMoreElements()) {
332 String hv = (String) hvals.nextElement();
333 if ("content-type".equals(hnlc)) {
336 if ("x-onap-requestid".equals(hnlc)) {
337 hasRequestIdHeader = true;
339 if ("x-invocationid".equals(hnlc)) {
340 hasInvocationIdHeader = true;
342 if ("x-att-dr-meta".equals(hnlc)) {
343 if (hv.length() > 4096) {
345 "NODE0109 Rejecting publish attempt with metadata too long for feed " + feedid
346 + " user " + user + " ip " + ip);
347 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Metadata too long");
348 eelflogger.info(EelfMsgs.EXIT);
351 if (!MetaDataPattern.matcher(hv.replaceAll("\\\\.", "X")).matches()) {
353 "NODE0109 Rejecting publish attempt with malformed metadata for feed " + feedid
354 + " user " + user + " ip " + ip);
355 resp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Malformed metadata");
356 eelflogger.info(EelfMsgs.EXIT);
360 mx.append(hn).append('\t').append(hv).append('\n');
364 if(!hasRequestIdHeader){
365 mx.append("X-ONAP-RequestID\t").append(MDC.get("RequestId")).append('\n');
367 if(!hasInvocationIdHeader){
368 mx.append("X-InvocationID\t").append(MDC.get("InvocationId")).append('\n');
370 mx.append("X-ATT-DR-RECEIVED\t").append(rcvd).append('\n');
371 String metadata = mx.toString();
372 byte[] buf = new byte[1024 * 1024];
375 is = req.getInputStream();
376 dos = new FileOutputStream(data);
377 while ((i = is.read(buf)) > 0) {
378 dos.write(buf, 0, i);
384 } catch (IOException ioe) {
387 exlen = Long.parseLong(req.getHeader("Content-Length"));
388 } catch (Exception e) {
390 StatusLog.logPubFail(pubid, feedid, logurl, req.getMethod(), ctype, exlen, data.length(), ip, user,
392 eelflogger.info(EelfMsgs.EXIT);
395 Path dpath = Paths.get(fbase);
396 for (Target t : targets) {
397 DestInfo di = t.getDestInfo();
399 // TODO: unknown destination
402 String dbase = di.getSpool() + "/" + pubid;
403 Files.createLink(Paths.get(dbase), dpath);
404 mw = new FileWriter(meta);
406 if (di.getSubId() == null) {
407 mw.write("X-ATT-DR-ROUTING\t" + t.getRouting() + "\n");
410 meta.renameTo(new File(dbase + ".M"));
412 resp.setStatus(HttpServletResponse.SC_NO_CONTENT);
413 resp.getOutputStream().close();
414 StatusLog.logPub(pubid, feedid, logurl, req.getMethod(), ctype, data.length(), ip, user,
415 HttpServletResponse.SC_NO_CONTENT);
416 } catch (IOException ioe) {
418 "NODE0110 IO Exception receiving publish attempt for feed " + feedid + " user " + user + " ip " + ip
419 + " " + ioe.toString(), ioe);
420 eelflogger.info(EelfMsgs.EXIT);
426 } catch (Exception e) {
432 } catch (Exception e) {
438 } catch (Exception e) {
443 } catch (Exception e) {
447 } catch (Exception e) {
452 private int getIdFromPath(HttpServletRequest req) {
453 String path = req.getPathInfo();
454 if (path == null || path.length() < 2) {
458 return Integer.parseInt(path.substring(1));
459 } catch (NumberFormatException e) {