efd45e7d6e051dda51bd481019a9d3b3d7f6c15c
[nonrtric.git] / test / usecases / oruclosedlooprecovery / scriptversion / app / main.py
1
2 #  ============LICENSE_START===============================================
3 #  Copyright (C) 2021 Nordix Foundation. All rights reserved.
4 #  ========================================================================
5 #  Licensed under the Apache License, Version 2.0 (the "License");
6 #  you may not use this file except in compliance with the License.
7 #  You may obtain a copy of the License at
8 #
9 #       http://www.apache.org/licenses/LICENSE-2.0
10 #
11 #  Unless required by applicable law or agreed to in writing, software
12 #  distributed under the License is distributed on an "AS IS" BASIS,
13 #  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 #  See the License for the specific language governing permissions and
15 #  limitations under the License.
16 #  ============LICENSE_END=================================================
17 #
18
19 import argparse
20 import ast
21 import json
22 import os
23 import requests
24 import time
25
26 MR_PATH = "/events/[TOPIC]/users/test/"
27 SDNR_PATH = "/rests/data/network-topology:network-topology/topology=topology-netconf/node=[O-DU-ID]/yang-ext:mount/o-ran-sc-du-hello-world:network-function/du-to-ru-connection=[O-RU-ID]"
28 FAUILT_ID = "28"
29
30 UNLOCK_MESSAGE = {
31     "o-ran-sc-du-hello-world:du-to-ru-connection": [
32         {
33             "name":"",
34             "administrative-state":"UNLOCKED"
35         }
36     ]
37 }
38
39
40 def is_message_new_link_failure(message):
41     msg_as_json = json.loads(message)
42     event_headers = msg_as_json["event"]["commonEventHeader"]
43
44     link_failure = False
45     if (event_headers["domain"] == "fault"):
46         fault_fields = msg_as_json["event"]["faultFields"]
47         link_failure = fault_fields["alarmCondition"] == FAUILT_ID and fault_fields["eventSeverity"] != "NORMAL"
48
49     return link_failure
50
51
52 def is_message_clear_link_failure(message):
53     msg_as_json = json.loads(message)
54     event_headers = msg_as_json["event"]["commonEventHeader"]
55
56     link_failure_clear = False
57     if (event_headers["domain"] == "fault"):
58         fault_fields = msg_as_json["event"]["faultFields"]
59         link_failure_clear = fault_fields["alarmCondition"] == FAUILT_ID and fault_fields["eventSeverity"] == "NORMAL"
60
61     return link_failure_clear
62
63
64 def handle_link_failure(message, o_ru_to_o_du_map, sdnr_address):
65     verboseprint("Got a link failure: ")
66     alarm_msg_as_json = json.loads(message)
67     event_headers = alarm_msg_as_json["event"]["commonEventHeader"]
68     o_ru_id = event_headers["sourceName"]
69     verboseprint("O-RU ID: " + o_ru_id)
70     o_du_id = o_ru_to_o_du_map[o_ru_id]
71     verboseprint("O-DU ID: " + o_du_id)
72     unlock_msg = json.loads(json.dumps(UNLOCK_MESSAGE))
73     unlock_msg["o-ran-sc-du-hello-world:du-to-ru-connection"][0]["name"] = o_ru_id
74     send_path = SDNR_PATH.replace("[O-DU-ID]", o_du_id).replace("[O-RU-ID]", o_ru_id)
75     requests.post(sdnr_address + send_path, json=unlock_msg)
76
77
78 def handle_clear_link_failure(message):
79     msg_as_json = json.loads(message)
80     event_headers = msg_as_json["event"]["commonEventHeader"]
81     o_ru_id = event_headers["sourceName"]
82     verboseprint("Cleared Link Failure for O-RU ID: " + o_ru_id)
83
84
85 def read_o_ru_to_o_du_map_from_file(map_file):
86     file = open(map_file, "r")
87     contents = file.read()
88     dictionary = ast.literal_eval(contents)
89     file.close()
90     return dictionary
91
92
93 def poll_and_handle_messages(mr_address, sdnr_address):
94     while True:
95         try:
96             verboseprint("Polling")
97             response = requests.get(mr_address)
98             messages = response.json()
99             for message in messages:
100                 if (is_message_new_link_failure(message)):
101                     handle_link_failure(message, o_ru_to_o_du_map, sdnr_address)
102                 elif (is_message_clear_link_failure(message)):
103                     handle_clear_link_failure(message)
104         except Exception as inst:
105             print(inst)
106
107         time.sleep(pollTime)
108
109
110 if __name__ == '__main__':
111     parser = argparse.ArgumentParser(prog='PROG')
112     parser.add_argument('--mrHost', help='The URL of the MR host (default: %(default)s)', default="http://message-router.onap")
113     parser.add_argument('--mrPort', help='The port of the MR host (default: %(default)d)', type=int, default=3904)
114     parser.add_argument('--mrTopic', help='The topic to poll messages from (default: %(default)s)', default="unauthenticated.SEC_FAULT_OUTPUT")
115     parser.add_argument('--sdnrHost', help='The URL of the SNDR host (default: %(default)s)', default="http://localhost")
116     parser.add_argument('--sdnrPort', help='The port of the SDNR host (default: %(default)d)', type=int, default=9990)
117     parser.add_argument('--oRuTooDuMapFile', help='A file with the mapping between O-RU ID and O-DU ID as a dictionary (default: %(default)s)', default="o-ru-to-o-du-map.txt")
118     parser.add_argument('--pollTime', help='The time between polls (default: %(default)d)', type=int, default=10)
119     parser.add_argument('-v', '--verbose', action='store_true', help='Turn on verbose printing')
120     parser.add_argument('--version', action='version', version='%(prog)s 1.0')
121     args = vars(parser.parse_args())
122     mr_host = args["mrHost"]
123     if os.getenv("MR-HOST") is not None:
124         mr_host = os.getenv("MR-HOST")
125         print("Using MR Host from os: " + mr_host)
126     mr_port = args["mrPort"]
127     if os.getenv("MR-PORT") is not None:
128         mr_port = os.getenv("MR-PORT")
129         print("Using MR Port from os: " + mr_port)
130     mr_topic = args["mrTopic"]
131     sdnr_host = args["sdnrHost"]
132     if os.getenv("SDNR-HOST") is not None:
133         sdnr_host = os.getenv("SDNR-HOST")
134         print("Using SNDR Host from os: " + sdnr_host)
135     sdnr_port = args["sdnrPort"]
136     if os.getenv("SDNR-PORT") is not None:
137         sdnr_port = os.getenv("SDNR-PORT")
138         print("Using SNDR Host from os: " + sdnr_port)
139     o_ru_to_o_du_map = read_o_ru_to_o_du_map_from_file(args["oRuTooDuMapFile"])
140     pollTime = args["pollTime"]
141
142     if os.getenv("VERBOSE") is not None or args["verbose"]:
143
144         def verboseprint(*args, **kwargs):
145             print(*args, **kwargs)
146
147     else:
148         verboseprint = lambda *a, **k: None  # do-nothing function
149
150     verboseprint("Using MR address: " + mr_host + ":" + str(mr_port) + " and topic: " + mr_topic)
151     verboseprint("Using SDNR address: " + sdnr_host + ":" + str(sdnr_port))
152     verboseprint("Starting with " + str(pollTime) + " seconds between polls")
153     mr_address = mr_host + ":" + str(mr_port) + MR_PATH.replace("[TOPIC]", mr_topic)
154     sdnr_address = sdnr_host + ":" + str(sdnr_port)
155
156     poll_and_handle_messages(mr_address, sdnr_address)