Merge "Add missing conf.py import"
[modeling/etsicatalog.git] / catalog / middleware.py
1 # Copyright (c) 2017-2018 ZTE, Inc.
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at:
6 #
7 #       http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
13 import uuid
14
15 from onaplogging.mdcContext import MDC
16
17 from catalog.pub.config.config import FORWARDED_FOR_FIELDS, SERVICE_NAME
18
19
20 class LogContextMiddleware(object):
21     def __init__(self, get_response):
22         self.get_response = get_response
23
24     #  the last IP behind multiple proxies,  if no exist proxies
25     #  get local host ip.
26     def _getLastIp(self, request):
27
28         ip = ""
29         try:
30             for field in FORWARDED_FOR_FIELDS:
31                 if field in request.META:
32                     if ',' in request.META[field]:
33                         parts = request.META[field].split(',')
34                         ip = parts[-1].strip().split(":")[0]
35                     else:
36                         ip = request.META[field].split(":")[0]
37
38             if ip == "":
39                 ip = request.META.get("HTTP_HOST").split(":")[0]
40
41         except Exception:
42             pass
43
44         return ip
45
46     def process_request(self, request):
47         # Fetch TRANSACTIONID Id and pass to plugin server
48         ReqeustID = request.META.get("HTTP_X_ONAP-RequestID", None)
49         if ReqeustID is None:
50             ReqeustID = uuid.uuid3(uuid.NAMESPACE_URL, SERVICE_NAME)
51             request.META["HTTP_X_ONAP-RequestID"] = ReqeustID
52         MDC.put("requestID", ReqeustID)
53         # generate the unique  id
54         InovocationID = uuid.uuid3(uuid.NAMESPACE_DNS, SERVICE_NAME)
55         MDC.put("invocationID", InovocationID)
56         MDC.put("serviceName", SERVICE_NAME)
57         # access ip
58         MDC.put("serviceIP", self._getLastIp(request))
59
60         return None
61
62     def process_response(self, request, response):
63         MDC.clear()
64         return response
65
66     def __call__(self, request):
67         self.process_request(request)
68         response = self.get_response(request)
69         self.process_response(request, response)
70         return response