summaryrefslogtreecommitdiffstats
path: root/catalog-fe/src/main/java/org/openecomp/sdc/fe/servlets/FeProxyServlet.java
blob: 11d4abf4af252831f003c96e166b44b5aec7b222 (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
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
/*-
 * ============LICENSE_START=======================================================
 * SDC
 * ================================================================================
 * Copyright (C) 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=========================================================
 */

package org.openecomp.sdc.fe.servlets;

import java.net.URI;
import java.util.concurrent.TimeUnit;

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

import org.eclipse.jetty.client.api.Response;
import org.openecomp.sdc.common.api.Constants;
import org.openecomp.sdc.common.config.EcompErrorName;
import org.openecomp.sdc.fe.config.Configuration;
import org.openecomp.sdc.fe.config.ConfigurationManager;
import org.openecomp.sdc.fe.config.FeEcompErrorManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;

public class FeProxyServlet extends SSLProxyServlet {
	private static final long serialVersionUID = 1L;
	private static final String URL = "%s://%s:%s%s";
	private static Logger log = LoggerFactory.getLogger(FeProxyServlet.class.getName());
	private static Cache<String, MdcData> mdcDataCache = CacheBuilder.newBuilder().expireAfterWrite(10, TimeUnit.SECONDS).build();

	@Override
	public URI rewriteURI(HttpServletRequest request) {
		try {
			logFeRequest(request);
		} catch (Exception e) {
			FeEcompErrorManager.getInstance().processEcompError(EcompErrorName.FeHttpLoggingError, "FE Request");
			FeEcompErrorManager.getInstance().logFeHttpLoggingError("FE Request");
			log.error("Unexpected FE request logging error :", e);
		}
		String originalUrl = request.getRequestURL().toString();
		String redirectedUrl = getModifiedUrl(request);

		log.debug("FeProxyServlet Redirecting request from: {} , to: {}", originalUrl, redirectedUrl);

		return URI.create(redirectedUrl);
	}

	@Override
	protected void onResponseSuccess(HttpServletRequest request, HttpServletResponse response, Response proxyResponse) {
		try {
			logFeResponse(request, proxyResponse);
		} catch (Exception e) {
			FeEcompErrorManager.getInstance().processEcompError(EcompErrorName.FeHttpLoggingError, "FE Response");
			FeEcompErrorManager.getInstance().logFeHttpLoggingError("FE Response");
			log.error("Unexpected FE response logging error :", e);
		}
		super.onResponseSuccess(request, response, proxyResponse);
	}

	private void logFeRequest(HttpServletRequest httpRequest) {

		MDC.clear();

		Long transactionStartTime = System.currentTimeMillis();
		// UUID - In FE, we are supposed to get the below header from UI.
		// We do not generate it if it's missing - BE does.
		String uuid = httpRequest.getHeader(Constants.X_ECOMP_REQUEST_ID_HEADER);
		String serviceInstanceID = httpRequest.getHeader(Constants.X_ECOMP_SERVICE_ID_HEADER);

		if (uuid != null && uuid.length() > 0) {
			// UserId for logging
			String userId = httpRequest.getHeader(Constants.USER_ID_HEADER);

			String remoteAddr = httpRequest.getRemoteAddr();
			String localAddr = httpRequest.getLocalAddr();

			mdcDataCache.put(uuid, new MdcData(serviceInstanceID, userId, remoteAddr, localAddr, transactionStartTime));

			updateMdc(uuid, serviceInstanceID, userId, remoteAddr, localAddr, null);
		}
		inHttpRequest(httpRequest);
	}

	private void logFeResponse(HttpServletRequest request, Response proxyResponse) {
		String uuid = request.getHeader(Constants.X_ECOMP_REQUEST_ID_HEADER);
		String transactionRoundTime = null;

		if (uuid != null) {
			MdcData mdcData = mdcDataCache.getIfPresent(uuid);
			if (mdcData != null) {
				Long transactionStartTime = mdcData.getTransactionStartTime();
				if (transactionStartTime != null) {// should'n ever be null, but
													// just to be defensive
					transactionRoundTime = Long.toString(System.currentTimeMillis() - transactionStartTime);
				}
				updateMdc(uuid, mdcData.getServiceInstanceID(), mdcData.getUserId(), mdcData.getRemoteAddr(), mdcData.getLocalAddr(), transactionRoundTime);
			}
		}
		outHttpResponse(proxyResponse);

		MDC.clear();
	}

	// Extracted for purpose of clear method name, for logback %M parameter
	private void inHttpRequest(HttpServletRequest httpRequest) {
		log.info("{} {} {}", httpRequest.getMethod(), httpRequest.getRequestURI(), httpRequest.getProtocol());
	}

	// Extracted for purpose of clear method name, for logback %M parameter
	private void outHttpResponse(Response proxyResponse) {
		log.info("SC=\"{}\"", proxyResponse.getStatus());
	}

	private void updateMdc(String uuid, String serviceInstanceID, String userId, String remoteAddr, String localAddr, String transactionStartTime) {
		MDC.put("uuid", uuid);
		MDC.put("serviceInstanceID", serviceInstanceID);
		MDC.put("userId", userId);
		MDC.put("remoteAddr", remoteAddr);
		MDC.put("localAddr", localAddr);
		MDC.put("timer", transactionStartTime);
	}

	private class MdcData {
		private String serviceInstanceID;
		private String userId;
		private String remoteAddr;
		private String localAddr;
		private Long transactionStartTime;

		public MdcData(String serviceInstanceID, String userId, String remoteAddr, String localAddr, Long transactionStartTime) {
			super();
			this.serviceInstanceID = serviceInstanceID;
			this.userId = userId;
			this.remoteAddr = remoteAddr;
			this.localAddr = localAddr;
			this.transactionStartTime = transactionStartTime;
		}

		public Long getTransactionStartTime() {
			return transactionStartTime;
		}

		public String getUserId() {
			return userId;
		}

		public String getRemoteAddr() {
			return remoteAddr;
		}

		public String getLocalAddr() {
			return localAddr;
		}

		public String getServiceInstanceID() {
			return serviceInstanceID;
		}
	}

	public String getModifiedUrl(HttpServletRequest request) {

		Configuration config = getConfiguration(request);
		if (config == null) {
			log.error("failed to retrive configuration.");
		}
		String scheme = config.getBeProtocol();
		String uri = request.getRequestURI().toString();
		StringBuilder url = new StringBuilder();
		url.append(scheme).append("://").append(config.getBeHost());
		url.append(":");
		if (config.getBeProtocol().equals(BE_PROTOCOL.HTTP.getProtocolName())) {
			url.append(config.getBeHttpPort());
		} else {
			url.append(config.getBeSslPort());
		}
		url.append(uri);
		String queryString = request.getQueryString(); // d=789
		if (queryString != null) {
			url.append("?").append(queryString);
		}

		String redirectedUrl = url.toString();
		String onboardingForwardContext = config.getOnboardingForwardContext();
		if (onboardingForwardContext == null || onboardingForwardContext.isEmpty()) {
			onboardingForwardContext = "/onboarding-api";
		}
		redirectedUrl = redirectedUrl.replace("/sdc1/feProxy/dcae-api", "/dcae");
		redirectedUrl = redirectedUrl.replace("/sdc1/feProxy/onboarding-api", onboardingForwardContext);
		redirectedUrl = redirectedUrl.replace("/sdc1/feProxy", "/sdc2");
		return redirectedUrl;

	}

	private Configuration getConfiguration(HttpServletRequest request) {
		Configuration config = ((ConfigurationManager) request.getSession().getServletContext().getAttribute(Constants.CONFIGURATION_MANAGER_ATTR)).getConfiguration();
		return config;
	}
}