7294b9b5d6780378a49dd5665c52add446c8e8ad
[sdc.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 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
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
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=========================================================
19  */
20
21 package org.openecomp.sdc.logging.servlet;
22
23 import org.openecomp.sdc.logging.api.Logger;
24 import org.openecomp.sdc.logging.api.LoggerFactory;
25 import org.slf4j.MDC;
26
27 import javax.servlet.*;
28 import javax.servlet.http.HttpServletRequest;
29 import java.io.IOException;
30 import java.net.InetAddress;
31 import java.net.UnknownHostException;
32 import java.util.UUID;
33 import java.util.concurrent.atomic.AtomicLong;
34
35
36 /**
37  *
38  * <p>Pushes information required by EELF onto MDC (Mapped Diagnostic Context).</p>
39  *
40  * <p>This is servlet filter that should be configured in <i>web.xml</i> to be used. Example:</p>
41  *
42  * <pre>
43  *
44  *  &lt;filter&gt;
45  *      &lt;filter-name&gt;LoggingServletFilter&lt;/filter-name&gt;
46  *      &lt;filter-class&gt;org.openecomp.sdc.logging.servlet.LoggingFilter&lt;/filter-class&gt;
47  *  &lt;/filter&gt;
48  *
49  *  &lt;filter-mapping&gt;
50  *      &lt;filter-name&gt;LoggingServletFilter&lt;/filter-name&gt;
51  *      &lt;url-pattern&gt;/*&lt;/url-pattern&gt;
52  *  &lt;/filter-mapping&gt;
53  *
54  * </pre>
55  *
56  * @author evitaliy
57  * @since 25/07/2016.
58  */
59 public class LoggingFilter implements Filter {
60
61     // should be cashed to avoid low-level call, but with a timeout to account for IP or FQDN changes
62     private static final HostAddressCache HOST_ADDRESS = new HostAddressCache();
63     private static final String UNKNOWN = "UNKNOWN";
64
65     private final static Logger LOGGER = LoggerFactory.getLogger(LoggingFilter.class);
66
67     public void destroy() {
68     }
69
70     public void doFilter(ServletRequest request, ServletResponse response,
71                          FilterChain chain) throws IOException, ServletException {
72
73         try {
74
75             MDC.clear();
76
77             MDC.put("RequestId", UUID.randomUUID().toString());
78             MDC.put("ServiceInstanceId", "N/A"); // not applicable
79             MDC.put("ServiceName", "ASDC");
80             MDC.put("InstanceUUID", "N/A");
81
82             // For some reason chooses IPv4 or IPv6 in a random way
83             MDC.put("RemoteHost", request.getRemoteHost());
84
85             InetAddress host = HOST_ADDRESS.get();
86
87             String ipAddress, hostName;
88             if (host == null) {
89                 ipAddress = UNKNOWN;
90                 hostName = UNKNOWN;
91             } else {
92                 ipAddress = host.getHostAddress();
93                 hostName = host.getHostName();
94             }
95
96             MDC.put("ServerIPAddress", ipAddress);
97             MDC.put("ServerFQDN", hostName);
98
99             if(request instanceof HttpServletRequest) {
100                 String userName = ((HttpServletRequest) request).getHeader("USER_ID");
101                 MDC.put("PartnerName", userName);
102             }
103             // TODO: Clarify what these stand for
104     //        MDC.put("AlertSeverity", );
105     //        MDC.put("Timer", );
106
107             chain.doFilter(request, response);
108
109         } finally {
110             MDC.clear();
111         }
112     }
113
114     public void init(FilterConfig config) throws ServletException { }
115
116     private static class HostAddressCache {
117
118         private static final long REFRESH_TIME = 1000L;
119
120         private final AtomicLong lastUpdated = new AtomicLong(0L);
121         private InetAddress hostAddress;
122
123         public InetAddress get() {
124
125             long current = System.currentTimeMillis();
126             if (current - lastUpdated.get() > REFRESH_TIME) {
127
128                 synchronized (this) {
129
130                     try {
131                         lastUpdated.set(current); // set now to register the attempt even if failed
132                         hostAddress = InetAddress.getLocalHost();
133                     } catch (UnknownHostException e) {
134                         LOGGER.error("Failed to retrieve local hostname for logging", e);
135                         hostAddress = null;
136                     }
137                 }
138             }
139
140             return hostAddress;
141         }
142     }
143 }