Update O-RU Fronthaul Recovery usecase
[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/distributed-unit-functions=[O-DU-ID]/radio-resource-management-policy-ratio=rrm-pol-1"
28 FAUILT_ID = "28"
29
30 UNLOCK_MESSAGE = {
31     "o-ran-sc-du-hello-world:radio-resource-management-policy-ratio":
32     [
33         {
34             "id":"rrm-pol-1",
35             "radio-resource-management-policy-max-ratio":25,
36             "radio-resource-management-policy-members":
37                 [
38                     {
39                         "mobile-country-code":"310",
40                         "mobile-network-code":"150",
41                         "slice-differentiator":1,
42                         "slice-service-type":1
43                     }
44                 ],
45             "radio-resource-management-policy-min-ratio":15,
46             "user-label":"rrm-pol-1",
47             "resource-type":"prb",
48             "radio-resource-management-policy-dedicated-ratio":20,
49             "administrative-state":"unlocked"
50         }
51     ]
52 }
53
54
55 def is_message_new_link_failure(message):
56     msg_as_json = json.loads(message)
57     event_headers = msg_as_json["event"]["commonEventHeader"]
58
59     link_failure = False
60     if (event_headers["domain"] == "fault"):
61         fault_fields = msg_as_json["event"]["faultFields"]
62         link_failure = fault_fields["alarmCondition"] == FAUILT_ID and fault_fields["eventSeverity"] != "NORMAL"
63
64     return link_failure
65
66
67 def is_message_clear_link_failure(message):
68     msg_as_json = json.loads(message)
69     event_headers = msg_as_json["event"]["commonEventHeader"]
70
71     link_failure_clear = False
72     if (event_headers["domain"] == "fault"):
73         fault_fields = msg_as_json["event"]["faultFields"]
74         link_failure_clear = fault_fields["alarmCondition"] == FAUILT_ID and fault_fields["eventSeverity"] == "NORMAL"
75
76     return link_failure_clear
77
78
79 def handle_link_failure(message, o_ru_to_o_du_map, sdnr_address, sdnr_user, sdnr_pwd):
80     verboseprint("Got a link failure: ")
81     alarm_msg_as_json = json.loads(message)
82     event_headers = alarm_msg_as_json["event"]["commonEventHeader"]
83     o_ru_id = event_headers["sourceName"]
84     verboseprint("O-RU ID: " + o_ru_id)
85     if o_ru_id in o_ru_to_o_du_map:
86         o_du_id = o_ru_to_o_du_map[o_ru_id]
87         verboseprint("O-DU ID: " + o_du_id)
88         unlock_msg = json.loads(json.dumps(UNLOCK_MESSAGE))
89         send_path = SDNR_PATH.replace("[O-DU-ID]", o_du_id)
90         requests.put(sdnr_address + send_path, auth=(sdnr_user, sdnr_pwd), json=unlock_msg)
91     else:
92         print("ERROR: No mapping for O-RU ID: " + o_ru_id)
93
94
95 def handle_clear_link_failure(message):
96     msg_as_json = json.loads(message)
97     event_headers = msg_as_json["event"]["commonEventHeader"]
98     o_ru_id = event_headers["sourceName"]
99     verboseprint("Cleared Link Failure for O-RU ID: " + o_ru_id)
100
101
102 def read_o_ru_to_o_du_map_from_file(map_file):
103     file = open(map_file, "r")
104     contents = file.read()
105     dictionary = ast.literal_eval(contents)
106     file.close()
107     return dictionary
108
109
110 def poll_and_handle_messages(mr_address, sdnr_address, sdnr_user, sdnr_pwd):
111     while True:
112         try:
113             verboseprint("Polling")
114             response = requests.get(mr_address)
115             messages = response.json()
116             for message in messages:
117                 if (is_message_new_link_failure(message)):
118                     handle_link_failure(message, o_ru_to_o_du_map, sdnr_address, sdnr_user, sdnr_pwd)
119                 elif (is_message_clear_link_failure(message)):
120                     handle_clear_link_failure(message)
121         except Exception as inst:
122             print(inst)
123
124         time.sleep(pollTime)
125
126
127 if __name__ == '__main__':
128     parser = argparse.ArgumentParser(prog='PROG')
129     parser.add_argument('--mrHost', help='The URL of the MR host (default: %(default)s)', default="http://message-router.onap")
130     parser.add_argument('--mrPort', help='The port of the MR host (default: %(default)d)', type=int, default=3904)
131     parser.add_argument('--mrTopic', help='The topic to poll messages from (default: %(default)s)', default="unauthenticated.SEC_FAULT_OUTPUT")
132     parser.add_argument('--sdnrHost', help='The URL of the SNDR host (default: %(default)s)', default="http://localhost")
133     parser.add_argument('--sdnrPort', help='The port of the SDNR host (default: %(default)d)', type=int, default=9990)
134     parser.add_argument('--sdnrUser', help='Username for SDNR', default="admin")
135     parser.add_argument('--sdnrPwd', help='Password for SDNR', default="Kp8bJ4SXszM0WXlhak3eHlcse2gAw84vaoGGmJvUy2U")
136     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")
137     parser.add_argument('--pollTime', help='The time between polls (default: %(default)d)', type=int, default=10)
138     parser.add_argument('-v', '--verbose', action='store_true', help='Turn on verbose printing')
139     parser.add_argument('--version', action='version', version='%(prog)s 1.0')
140     args = vars(parser.parse_args())
141     mr_host = args["mrHost"]
142     if os.getenv("MR-HOST") is not None:
143         mr_host = os.getenv("MR-HOST")
144         print("Using MR Host from os: " + mr_host)
145     mr_port = args["mrPort"]
146     if os.getenv("MR-PORT") is not None:
147         mr_port = os.getenv("MR-PORT")
148         print("Using MR Port from os: " + mr_port)
149     mr_topic = args["mrTopic"]
150     sdnr_host = args["sdnrHost"]
151     if os.getenv("SDNR-HOST") is not None:
152         sdnr_host = os.getenv("SDNR-HOST")
153         print("Using SNDR Host from os: " + sdnr_host)
154     sdnr_port = args["sdnrPort"]
155     if os.getenv("SDNR-PORT") is not None:
156         sdnr_port = os.getenv("SDNR-PORT")
157         print("Using SNDR Host from os: " + sdnr_port)
158     sdnr_user = args["sdnrUser"]
159     if os.getenv("SDNR-USER") is not None:
160         sdnr_user = os.getenv("SDNR-USER")
161         print("Using SNDR User from os: " + sdnr_user)
162     sdnr_pwd = args["sdnrPwd"]
163     if os.getenv("SDNR-PWD") is not None:
164         sdnr_pwd = os.getenv("SDNR-PWD")
165         print("Using SNDR Password from os: " + sdnr_pwd)
166     o_ru_to_o_du_map = read_o_ru_to_o_du_map_from_file(args["oRuTooDuMapFile"])
167     pollTime = args["pollTime"]
168
169     if os.getenv("VERBOSE") is not None or args["verbose"]:
170
171         def verboseprint(*args, **kwargs):
172             print(*args, **kwargs)
173
174     else:
175         verboseprint = lambda *a, **k: None  # do-nothing function
176
177     verboseprint("Using MR address: " + mr_host + ":" + str(mr_port) + " and topic: " + mr_topic)
178     verboseprint("Using SDNR address: " + sdnr_host + ":" + str(sdnr_port))
179     verboseprint("Starting with " + str(pollTime) + " seconds between polls")
180     mr_address = mr_host + ":" + str(mr_port) + MR_PATH.replace("[TOPIC]", mr_topic)
181     sdnr_address = sdnr_host + ":" + str(sdnr_port)
182
183     poll_and_handle_messages(mr_address, sdnr_address, sdnr_user, sdnr_pwd)