Add vfc-vnflcm log integration config
[vfc/gvnfm/vnflcm.git] / lcm / lcm / 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 from onaplogging.mdcContext import MDC
15
16 from lcm.pub.config.config import FORWARDED_FOR_FIELDS, SERVICE_NAME
17
18
19 class LogContextMiddleware(object):
20     #  the last IP behind multiple proxies,  if no exist proxies
21     #  get local host ip.
22     def _getLastIp(self, request):
23
24         ip = ""
25         try:
26             for field in FORWARDED_FOR_FIELDS:
27                 if field in request.META:
28                     if ',' in request.META[field]:
29                         parts = request.META[field].split(',')
30                         ip = parts[-1].strip().split(":")[0]
31                     else:
32                         ip = request.META[field].split(":")[0]
33
34             if ip == "":
35                 ip = request.META.get("HTTP_HOST").split(":")[0]
36
37         except Exception:
38             pass
39
40         return ip
41
42     def process_request(self, request):
43         # Fetch TRANSACTIONID Id and pass to plugin server
44         ReqeustID = request.META.get("HTTP_X_TRANSACTIONID", None)
45         if ReqeustID is None:
46             ReqeustID = uuid.uuid3(uuid.NAMESPACE_URL, SERVICE_NAME)
47             request.META["HTTP_X_TRANSACTIONID"] = ReqeustID
48         MDC.put("requestID", ReqeustID)
49         # generate the unique  id
50         InovocationID = uuid.uuid3(uuid.NAMESPACE_DNS, SERVICE_NAME)
51         MDC.put("invocationID", InovocationID)
52         MDC.put("serviceName", SERVICE_NAME)
53         # access ip
54         MDC.put("serviceIP", self._getLastIp(request))
55
56         return None
57
58     def process_response(self, request, response):
59         MDC.clear()
60         return response