Improve coverage of multicloud-azure plugin
[multicloud/azure.git] / azure / multicloud_azure / middleware.py
1 # Copyright (c) 2018 Amdocs
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
14 import uuid
15 from onaplogging.mdcContext import MDC
16 from multicloud_azure.pub.config.config import SERVICE_NAME
17 from multicloud_azure.pub.config.config import FORWARDED_FOR_FIELDS
18
19
20 class LogContextMiddleware(object):
21
22     #  the last IP behind multiple proxies,  if no exist proxies
23     #  get local host ip.
24     def _getLastIp(self, request):
25
26         ip = ""
27         try:
28             for field in FORWARDED_FOR_FIELDS:
29                 if field in request.META:
30                     if ',' in request.META[field]:
31                         parts = request.META[field].split(',')
32                         ip = parts[-1].strip().split(":")[0]
33                     else:
34                         ip = request.META[field].split(":")[0]
35
36             if ip == "":
37                 ip = request.META.get("HTTP_HOST").split(":")[0]
38
39         except Exception:
40             pass
41
42         return ip
43
44     def process_request(self, request):
45
46         ReqeustID = request.META.get("HTTP_X_TRANSACTIONID", None)
47         if ReqeustID is None:
48             ReqeustID = str(uuid.uuid3(uuid.NAMESPACE_URL, SERVICE_NAME))
49         MDC.put("requestID", ReqeustID)
50         InovocationID = str(uuid.uuid4())
51         MDC.put("invocationID", InovocationID)
52         MDC.put("serviceName", SERVICE_NAME)
53         MDC.put("serviceIP", self._getLastIp(request))
54         return None
55
56     def process_response(self, request, response):
57
58         MDC.clear()
59         return response