aboutsummaryrefslogtreecommitdiffstats
path: root/ajsc-aai/src/main/java/org/openecomp/aai/interceptors/AAILogJAXRSInInterceptor.java
blob: 448f8b98095a37905a065ad01f9a5ae203f2b033 (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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
/*-
 * ============LICENSE_START=======================================================
 * org.openecomp.aai
 * ================================================================================
 * 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.aai.interceptors;

import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.ws.rs.core.MediaType;

import org.apache.commons.io.IOUtils;
import org.apache.cxf.helpers.CastUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.interceptor.LoggingMessage;
import org.apache.cxf.jaxrs.ext.MessageContext;
import org.apache.cxf.jaxrs.interceptor.JAXRSInInterceptor;
import org.apache.cxf.message.Message;
import org.openecomp.aai.exceptions.AAIException;
import org.openecomp.aai.logging.AAILogger;
import org.openecomp.aai.logging.LogLine;
import org.openecomp.aai.rest.util.EchoResponse;
import org.openecomp.aai.util.AAIConfig;
import org.openecomp.aai.util.AAIConstants;
import org.openecomp.aai.util.HbaseSaltPrefixer;
import org.slf4j.MDC;

public class AAILogJAXRSInInterceptor extends JAXRSInInterceptor {

	protected final String COMPONENT = "aairest";
	protected final String CAMEL_REQUEST ="CamelHttpUrl";
	private static final Pattern uuidPattern = Pattern.compile("^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$");
	
	/**
	 * {@inheritDoc}
	 */
	public void handleMessage(Message message) {
		boolean go = false;
		AAILogger aaiLogger = new AAILogger(AAILogJAXRSInInterceptor.class.getName());
		LogLine logline = new LogLine();
		LogLine auditLogline = new LogLine();
		String uri = null;
		String query = null;
		try {
		
			uri = (String)message.get(CAMEL_REQUEST);
			if (uri != null) { 
				query = (String)message.get(Message.QUERY_STRING);
			}
			
			if (AAIConfig.get(AAIConstants.AAI_LOGGING_HBASE_INTERCEPTOR).equalsIgnoreCase("true") &&
					AAIConfig.get(AAIConstants.AAI_LOGGING_HBASE_ENABLED).equalsIgnoreCase("true")) {
				go = true;
				message.getExchange().put("AAI_LOGGING_HBASE_ENABLED", 1);
				if (AAIConfig.get(AAIConstants.AAI_LOGGING_HBASE_LOGREQUEST).equalsIgnoreCase("true") ) {
					message.getExchange().put("AAI_LOGGING_HBASE_LOGREQUEST", 1);
				}
				if (AAIConfig.get(AAIConstants.AAI_LOGGING_HBASE_LOGRESPONSE).equalsIgnoreCase("true") ) {
					message.getExchange().put("AAI_LOGGING_HBASE_LOGRESPONSE", 1);
				}
			}
			if (AAIConfig.get(AAIConstants.AAI_LOGGING_TRACE_ENABLED).equalsIgnoreCase("true") ) {
				go = true;
				message.getExchange().put("AAI_LOGGING_TRACE_ENABLED", 1);
				if (AAIConfig.get(AAIConstants.AAI_LOGGING_TRACE_LOGREQUEST).equalsIgnoreCase("true") ) {
					message.getExchange().put("AAI_LOGGING_TRACE_LOGREQUEST", 1);
				}
				if (AAIConfig.get(AAIConstants.AAI_LOGGING_TRACE_LOGRESPONSE).equalsIgnoreCase("true") ) {
					message.getExchange().put("AAI_LOGGING_TRACE_LOGRESPONSE", 1);
				}
			}
		} catch (AAIException e1) {
			logline.add("Property", AAIConstants.AAI_LOGGING_TRACE_ENABLED);
			logline.add("Property", AAIConstants.AAI_LOGGING_HBASE_ENABLED);
			aaiLogger.error(e1.getErrorObject(), logline);
		}
		
		if (uri.contains(EchoResponse.echoPath)) {
			// if it's a health check, we don't want to log ANYTHING if it's a lightweight one
			if (query == null) {
				if (message.getExchange().containsKey("AAI_LOGGING_HBASE_ENABLED")) {
					message.getExchange().remove("AAI_LOGGING_HBASE_ENABLED");
				}
				if (message.getExchange().containsKey("AAI_LOGGING_TRACE_ENABLED")) { 
					message.getExchange().remove("AAI_LOGGING_TRACE_ENABLED");
				}
				go = false;
			}
		}
		else if (uri.contains("/translog/")) {
			// if it's a translog query, we don't want to log the responses
			if (message.getExchange().containsKey("AAI_LOGGING_HBASE_LOGRESPONSE")) {
				message.getExchange().remove("AAI_LOGGING_HBASE_LOGRESPONSE");
			}
			if (message.getExchange().containsKey("AAI_LOGGING_TRACE_LOGRESPONSE")) {
				message.getExchange().remove("AAI_LOGGING_TRACE_LOGRESPONSE");
			}
		}
		
		if (go == false) { // there's nothing to do 
			return;
		}

		// DONE: get a TXID based on hostname, time (YYYYMMDDHHMMSSMILLIS,  and LoggingMessage.nextId(); 20150326145301-1
		String now = genDate(aaiLogger, logline);

		message.getExchange().put("AAI_RQST_TM", now);

		String id = (String)message.getExchange().get(LoggingMessage.ID_KEY);

		String fullId = null;
		try {
			if (id == null) {
				id = LoggingMessage.nextId();
			}
			fullId = AAIConfig.get(AAIConstants.AAI_NODENAME) + "-" + now + "-" + id;
			fullId = HbaseSaltPrefixer.getInstance().prependSalt(fullId);
			message.getExchange().put(LoggingMessage.ID_KEY, fullId);
		} catch (AAIException e1) {
			aaiLogger.debug(logline, "config problem", e1);
		}
		if (fullId == null) { 
			fullId = now + "-" + id;
			fullId = HbaseSaltPrefixer.getInstance().prependSalt(fullId);
		}
		message.put(LoggingMessage.ID_KEY, fullId);
		final LoggingMessage buffer = new LoggingMessage("Message", fullId);

		Integer responseCode = (Integer)message.get(Message.RESPONSE_CODE);
		if (responseCode != null) {
			buffer.getResponseCode().append(responseCode);
		}

		String encoding = (String)message.get(Message.ENCODING);

		if (encoding != null) {
			buffer.getEncoding().append(encoding);
		}
		String httpMethod = (String)message.get(Message.HTTP_REQUEST_METHOD);
		if (httpMethod != null) {
			buffer.getHttpMethod().append(httpMethod);
		}

		String ct = (String)message.get(Message.CONTENT_TYPE);
		if (ct != null) {
			if ("*/*".equals(ct)) {
				message.put(Message.CONTENT_TYPE, MediaType.APPLICATION_JSON);
				ct = MediaType.APPLICATION_JSON;
			}
			buffer.getContentType().append(ct);

		}
		Object headers = message.get(Message.PROTOCOL_HEADERS);
		if (headers != null) {
			buffer.getHeader().append(headers);
			
			Map<String, List<String>> headersList = CastUtils.cast((Map<?, ?>)message.get(Message.PROTOCOL_HEADERS));
			String transId = "";
			String fromAppId = null;
			List<String> xt = headersList.get("X-TransactionId");
			String newTransId = transId;
			boolean missingTransId = false;
			boolean replacedTransId = false;
			String logMsg = null;
			if (xt != null) {
				for (String transIdValue : xt) {
					transId = transIdValue;
				}	
				Matcher matcher = uuidPattern.matcher(transId);
				if (!matcher.find()) {
					replacedTransId = true;
					// check if there's a colon, and check the first group?
					if (transId.contains(":")) {
						String[] uuidParts = transId.split(":");
						Matcher matcher2 = uuidPattern.matcher(uuidParts[0]);
						if (matcher2.find()) { 
							newTransId = uuidParts[0];
						} else {
							// punt, we tried to find it, it has a colon but no UUID-1
							newTransId = UUID.randomUUID().toString();
						}
					} else {
						newTransId = UUID.randomUUID().toString();
					}
				}
			} else { 
				newTransId = UUID.randomUUID().toString();
				missingTransId = true;
			}
						
			if (missingTransId || replacedTransId) {
				List<String> txList = new ArrayList<String>();
				txList.add(newTransId);
				headersList.put("X-TransactionId", txList);
				if (missingTransId) { 
					logMsg = "Missing requestID. Assigned " + newTransId;
				} else if (replacedTransId) { 
					logMsg = "Replaced invalid requestID of " + transId + " Assigned " + newTransId;
				}
				MDC.put("RequestId",newTransId);
			}
			else {
				MDC.put("RequestId",transId);
			}
			
			
			List<String> fromAppIdList = headersList.get("X-FromAppId");
			if (fromAppIdList != null) {
				for (String fromAppIdValue : fromAppIdList) {
					fromAppId = fromAppIdValue;
				}
				MDC.put("PartnerName",fromAppId);
			}
			
			List<String> contentType = headersList.get("Content-Type");
			if (contentType == null) {
				ct = (String)message.get(Message.CONTENT_TYPE);
				headersList.put(Message.CONTENT_TYPE, Collections.singletonList(ct));
			}
			logline.init(COMPONENT, newTransId, fromAppId, "interceptIn");
			auditLogline.init(COMPONENT, newTransId, fromAppId, "REST " + httpMethod + " "
					+ ((query != null)? uri+"?"+query : uri));
			if (logMsg != null) {
				logline.add(logMsg, true);
			}
			logline.add("HbaseTxId", fullId);
			aaiLogger.info(logline, true, "0");
		}


		if (uri != null) {
			buffer.getAddress().append(uri);
			if (query != null) {
				buffer.getAddress().append("?").append(query);
			}
		}

		InputStream is = message.getContent(InputStream.class);
		if (is != null) {
			try {
				String currentPayload = IOUtils.toString(is, "UTF-8");
				IOUtils.closeQuietly(is);
				buffer.getPayload().append(currentPayload);
				is = IOUtils.toInputStream(currentPayload, "UTF-8");
				message.setContent(InputStream.class, is);
				IOUtils.closeQuietly(is);
			} catch (Exception e) { 
				// It's ok to not have request input content
				// throw new Fault(e); 
			}
		}

		// this will be saved in the message exchange, and can be pulled out later...
		message.getExchange().put(fullId + "_REQUEST", buffer.toString());
		message.getExchange().put("AUDIT_LOGLINE", auditLogline);

	}

	/**
	 * Gen date.
	 *
	 * @param aaiLogger the aai logger
	 * @param logline the logline
	 * @return the string
	 */
	protected String genDate(AAILogger aaiLogger, LogLine logline) {
		Date date = new Date();
		DateFormat formatter = null;
		try {
			formatter = new SimpleDateFormat(AAIConfig.get(AAIConstants.HBASE_TABLE_TIMESTAMP_FORMAT));
		} catch (AAIException ex) {
			logline.add("Property", AAIConstants.HBASE_TABLE_TIMESTAMP_FORMAT);
			aaiLogger.error(ex.getErrorObject(), logline);
		} finally {
			if (formatter == null) {
				formatter = new SimpleDateFormat("YYMMdd-HH:mm:ss:SSS");
			}
		}

		return formatter.format(date);
	}

}