osdf rearchitecture into apps and libs
[optf/osdf.git] / osdf / utils / mdc_utils.py
1 # -------------------------------------------------------------------------
2 #   Copyright (c) 2019 AT&T Intellectual Property
3 #
4 #   Licensed under the Apache License, Version 2.0 (the "License");
5 #   you may not use this file except in compliance with the License.
6 #   You may obtain a copy of the License at
7 #
8 #       http://www.apache.org/licenses/LICENSE-2.0
9 #
10 #   Unless required by applicable law or agreed to in writing, software
11 #   distributed under the License is distributed on an "AS IS" BASIS,
12 #   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 #   See the License for the specific language governing permissions and
14 #   limitations under the License.
15 #
16 # -------------------------------------------------------------------------
17 #
18
19 import socket
20 import threading
21 import uuid
22
23 from onaplogging.mdcContext import MDC
24
25
26 def default_server_info():
27     # If not set or purposely set = None, then set default
28     if MDC.get('server') is None:
29         try:
30             server = socket.getfqdn()
31         except Exception as err:
32             try:
33                 server = socket.gethostname()
34             except Exception as err:
35                 server = ''
36         MDC.put('server', server)
37     if MDC.get('serverIPAddress') is None:
38         try:
39             server_ip_address = socket.gethostbyname(self._fields['server'])
40         except Exception:
41             server_ip_address = ""
42         MDC.put('serverIPAddress', server_ip_address)
43
44
45 def default_mdc():
46     MDC.put('instanceUUID', uuid.uuid1())
47     MDC.put('serviceName', 'OOF_OSDF')
48     MDC.put('threadID', threading.currentThread().getName())
49     default_server_info()
50     MDC.put('requestID', 'N/A')
51     MDC.put('partnerName', 'N/A')
52
53
54 def mdc_from_json(request_json):
55     default_mdc()
56     MDC.put('requestID', request_json['requestInfo']['requestId'])
57     MDC.put('partnerName', request_json['requestInfo']['sourceId'])
58
59
60 def clear_mdc():
61     MDC.clear()