aboutsummaryrefslogtreecommitdiffstats
path: root/datarouter-prov/src/main/java/com/att/research/datarouter/provisioning/PublishServlet.java
blob: 2a8e2e3c9a8438e30292902056e18e531c25e656 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
/*******************************************************************************
 * ============LICENSE_START==================================================
 * * org.onap.dmaap
 * * ===========================================================================
 * * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
 * * ===========================================================================
 * * Licensed under the Apache License, Version 2.0 (the "License");
 * * you may not use this file except in compliance with the License.
 * * You may obtain a copy of the License at
 * * 
 *  *      http://www.apache.org/licenses/LICENSE-2.0
 * * 
 *  * Unless required by applicable law or agreed to in writing, software
 * * distributed under the License is distributed on an "AS IS" BASIS,
 * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * * See the License for the specific language governing permissions and
 * * limitations under the License.
 * * ============LICENSE_END====================================================
 * *
 * * ECOMP is a trademark and service mark of AT&T Intellectual Property.
 * *
 ******************************************************************************/


package com.att.research.datarouter.provisioning;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Properties;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONTokener;

import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
import com.att.research.datarouter.provisioning.beans.EventLogRecord;
import com.att.research.datarouter.provisioning.beans.Feed;
import com.att.research.datarouter.provisioning.beans.IngressRoute;
import com.att.research.datarouter.provisioning.eelf.EelfMsgs;
import com.att.research.datarouter.provisioning.utils.*;

/**
 * This servlet handles redirects for the <publishURL> on the provisioning server,
 * which is generated by the provisioning server to handle a particular subscriptions to a feed.
 * See the <b>File Publishing and Delivery API</b> document for details on how these methods
 * should be invoked.
 *
 * @author Robert Eby
 * @version $Id: PublishServlet.java,v 1.8 2014/03/12 19:45:41 eby Exp $
 */
@SuppressWarnings("serial")
public class PublishServlet extends BaseServlet {
	private int next_node;
	private String provstring;
	private List<IngressRoute> irt;
	//Adding EELF Logger Rally:US664892  
    private static EELFLogger eelflogger = EELFManager.getInstance().getLogger("com.att.research.datarouter.provisioning.PublishServlet");
    

	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		next_node = 0;
		provstring = "";
		irt = new ArrayList<IngressRoute>();
	
	}
	@Override
	public void doDelete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		setIpAndFqdnForEelf("doDelete");
		eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER),getIdFromPath(req)+"");
		redirect(req, resp);
	}
	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		setIpAndFqdnForEelf("doGet");
		eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER),getIdFromPath(req)+"");
		redirect(req, resp);
	}
	@Override
	public void doPut(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		setIpAndFqdnForEelf("doPut");
		eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF_AND_FEEDID, req.getHeader(BEHALF_HEADER),getIdFromPath(req)+"");
		redirect(req, resp);
	}
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		setIpAndFqdnForEelf("doPost");
		eelflogger.info(EelfMsgs.MESSAGE_WITH_BEHALF, req.getHeader(BEHALF_HEADER));
		redirect(req, resp);
	}
	private void redirect(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String[] nodes = getNodes();
		if (nodes == null || nodes.length == 0) {
			resp.sendError(HttpServletResponse.SC_SERVICE_UNAVAILABLE, "There are no nodes defined in the DR network.");
		} else {
			EventLogRecord elr = new EventLogRecord(req);
			int feedid = checkPath(req);
			if (feedid < 0) {
				String message = (feedid == -1)
					? "Invalid request - Missing or bad feed number."
					: "Invalid request - Missing file ID.";
				elr.setMessage(message);
				elr.setResult(HttpServletResponse.SC_NOT_FOUND);
				eventlogger.info(elr);

				resp.sendError(HttpServletResponse.SC_NOT_FOUND, message);
			} else {
				// Generate new URL
				String nextnode = getRedirectNode(feedid, req);
				nextnode = nextnode+":"+DB.HTTPS_PORT;
				String newurl = "https://" + nextnode + "/publish" + req.getPathInfo();
				String qs = req.getQueryString();
				if (qs != null)
					newurl += "?" + qs;

				// Log redirect in event log
				String message = "Redirected to: "+newurl;
				elr.setMessage(message);
				elr.setResult(HttpServletResponse.SC_MOVED_PERMANENTLY);
				eventlogger.info(elr);

				resp.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
				resp.setHeader("Location", newurl);
			}
		}
	}
	private String getRedirectNode(int feedid, HttpServletRequest req) {
		// Check to see if the IRT needs to be updated
		Poker p = Poker.getPoker();
		String s = p.getProvisioningString();
		synchronized (provstring) {
			if (irt == null || (s.length() != provstring.length()) || !s.equals(provstring)) {
				// Provisioning string has changed -- update the IRT
				provstring = s;
				JSONObject jo = new JSONObject(new JSONTokener(provstring));
				JSONArray ja = jo.getJSONArray("ingress");
				List<IngressRoute> newlist = new ArrayList<IngressRoute>();
				for (int i = 0; i < ja.length(); i++) {
					IngressRoute iroute = new IngressRoute(ja.getJSONObject(i));
					newlist.add(iroute);
				}
				irt = newlist;
			}
		}

		// Look in IRT for next node
		for (IngressRoute route : irt) {
			if (route.matches(feedid, req)) {
				// pick a node at random from the list
				Collection<String> nodes = route.getNodes();
				String[] arr = nodes.toArray(new String[0]);
				long id = System.currentTimeMillis() % arr.length;
				String node = arr[(int) id];
				intlogger.info("Redirecting to "+node+" because of route "+route);
				return node;
			}
		}

		// No IRT rule matches, do round robin of all active nodes
		String[] nodes = getNodes();
		if (next_node >= nodes.length)	// The list of nodes may have grown/shrunk
			next_node = 0;
		return nodes[next_node++];
	}
	private int checkPath(HttpServletRequest req) {
		String path = req.getPathInfo();
		if (path == null || path.length() < 2)
			return -1;
		path = path.substring(1);
		int ix = path.indexOf('/');
		if (ix < 0 || ix == path.length()-1)
			return -2;
		try {
			int feedid = Integer.parseInt(path.substring(0, ix));
			if (!Feed.isFeedValid(feedid))
				return -1;
			return feedid;
		} catch (NumberFormatException e) {
			return -1;
		}
	}
}