diff options
author | Satoshi Fujii <fujii-satoshi@jp.fujitsu.com> | 2021-06-30 06:30:18 +0000 |
---|---|---|
committer | Satoshi Fujii <fujii-satoshi@jp.fujitsu.com> | 2021-06-30 06:37:00 +0000 |
commit | 56f4b548ed1399b97a19ced508568b04812515e6 (patch) | |
tree | 5b00703a458fa5e62920ce22f686bd128403f166 | |
parent | 050acf2b98a82ecb707b69fc6ff4bef6f84b4bd8 (diff) |
Remove extraneous parentheses
Removed unnecessary parentheses from code.
Signed-off-by: Satoshi Fujii <fujii-satoshi@jp.fujitsu.com>
Issue-ID: DCAEGEN2-2837
Change-Id: I9a5f43a4bd894f44d0fc27c0841535faa79a39ac
-rw-r--r-- | Changelog.md | 3 | ||||
-rw-r--r-- | miss_htbt_service/cbs_polling.py | 6 | ||||
-rw-r--r-- | miss_htbt_service/config_notif.py | 22 | ||||
-rw-r--r-- | miss_htbt_service/db_monitoring.py | 46 | ||||
-rw-r--r-- | miss_htbt_service/htbtworker.py | 58 | ||||
-rw-r--r-- | miss_htbt_service/misshtbtd.py | 70 | ||||
-rw-r--r-- | tests/test_check_health.py | 3 |
7 files changed, 105 insertions, 103 deletions
diff --git a/Changelog.md b/Changelog.md index 3a3bbf8..8eec718 100644 --- a/Changelog.md +++ b/Changelog.md @@ -7,6 +7,9 @@ and this project adheres to [Semantic Versioning](http://semver.org/). ## [2.3.1.] - 19/06/2021 ### Security - Fixed SQL injection vulnerability +### Changed +- Cleanup code + - Removed extraneous parentheses ## [2.3.0.] - 18/06/2021 diff --git a/miss_htbt_service/cbs_polling.py b/miss_htbt_service/cbs_polling.py index d2be0d9..8d5af09 100644 --- a/miss_htbt_service/cbs_polling.py +++ b/miss_htbt_service/cbs_polling.py @@ -44,14 +44,14 @@ def pollCBS(current_pid): msg = "CBSP:CBS Polling interval is %d", cbs_polling_interval _logger.info(msg) envPytest = os.getenv('pytest', "") - if (envPytest == 'test'): + if envPytest == 'test': cbs_polling_interval = "30" time.sleep(int(cbs_polling_interval)) hbc_pid, hbc_state, hbc_srcName, hbc_time = db.read_hb_common(user_name, password, ip_address, port_num, db_name) source_name = socket.gethostname() source_name = source_name + "-" + str(os.getenv('SERVICE_NAME', "")) result = True - if (int(current_pid) == int(hbc_pid) and source_name == hbc_srcName and hbc_state == "RUNNING"): + if int(current_pid) == int(hbc_pid) and source_name == hbc_srcName and hbc_state == "RUNNING": _logger.info("CBSP:ACTIVE Instance:Change the state to RECONFIGURATION") state = "RECONFIGURATION" update_flg = 1 @@ -63,5 +63,5 @@ def pollCBS(current_pid): if __name__ == "__main__": current_pid = sys.argv[1] - while (True): + while True: pollCBS(current_pid) diff --git a/miss_htbt_service/config_notif.py b/miss_htbt_service/config_notif.py index 8da1140..053784d 100644 --- a/miss_htbt_service/config_notif.py +++ b/miss_htbt_service/config_notif.py @@ -41,7 +41,7 @@ hb_properties_file = path.abspath(path.join(__file__, "../config/hbproperties.ya def postgres_db_open(username, password, host, port, database_name): envPytest = os.getenv('pytest', "") - if (envPytest == 'test'): + if envPytest == 'test': return True try: connection = psycopg2.connect(database=database_name, user=username, password=password, host=host, port=port) @@ -53,7 +53,7 @@ def postgres_db_open(username, password, host, port, database_name): def db_table_creation_check(connection_db, table_name): envPytest = os.getenv('pytest', "") - if (envPytest == 'test'): + if envPytest == 'test': return True cur = None try: @@ -77,7 +77,7 @@ def db_table_creation_check(connection_db, table_name): def commit_and_close_db(connection_db): envPytest = os.getenv('pytest', "") - if (envPytest == 'test'): + if envPytest == 'test': return True try: connection_db.commit() # <--- makes sure the change is shown in the database @@ -117,7 +117,7 @@ def read_hb_properties(jsfile): try: with open(jsfile, 'r') as outfile: cfg = json.load(outfile) - except(Exception) as err: + except Exception as err: print("Json file read error - %s" % err) return read_hb_properties_default() try: @@ -131,7 +131,7 @@ def read_hb_properties(jsfile): cbs_polling_interval = str(cfg['CBS_polling_interval']) if "SERVICE_NAME" in cfg: os.environ['SERVICE_NAME'] = str(cfg['SERVICE_NAME']) - except(Exception) as err: + except Exception as err: print("Json file read parameter error - %s" % err) return read_hb_properties_default() return ip_address, port_num, user_name, password, db_name, cbs_polling_required, cbs_polling_interval @@ -139,7 +139,7 @@ def read_hb_properties(jsfile): def read_hb_common(user_name, password, ip_address, port_num, db_name): envPytest = os.getenv('pytest', "") - if (envPytest == 'test'): + if envPytest == 'test': hbc_pid = 10 hbc_srcName = "srvc_name" hbc_time = 1541234567 @@ -165,7 +165,7 @@ def update_hb_common(update_flg, process_id, state, user_name, password, ip_addr source_name = socket.gethostname() source_name = source_name + "-" + str(os.getenv('SERVICE_NAME', "")) envPytest = os.getenv('pytest', "") - if (envPytest == 'test'): + if envPytest == 'test': return True connection_db = postgres_db_open(user_name, password, ip_address, port_num, db_name) cur = connection_db.cursor() @@ -182,7 +182,7 @@ def fetch_json_file(download_json="../etc/download1.json", config_json="../etc/c if mod.trapd_get_cbs_config.get_cbs_config(): current_runtime_config_file_name = download_json envPytest = os.getenv('pytest', "") - if (envPytest == 'test'): + if envPytest == 'test': jsfile = "../etc/config.json" return jsfile print("Config_N:current config logged to : %s" % current_runtime_config_file_name) @@ -201,11 +201,11 @@ def config_notif_run(): ip_address, port_num, user_name, password, db_name, cbs_polling_required, cbs_polling_interval = read_hb_properties( jsfile) envPytest = os.getenv('pytest', "") - if (envPytest == 'test'): + if envPytest == 'test': return True connection_db = postgres_db_open(user_name, password, ip_address, port_num, db_name) cur = connection_db.cursor() - if (db_table_creation_check(connection_db, "hb_common") == False): + if db_table_creation_check(connection_db, "hb_common") is False: print("HB_Notif::ERROR::hb_common table not exists - No config download") connection_db.close() else: @@ -214,7 +214,7 @@ def config_notif_run(): update_flg = 1 ret = update_hb_common(update_flg, hbc_pid, state, user_name, password, ip_address, port_num, db_name) # TODO: There is no way for update_hb_common() to return false - if (ret == True): + if ret: print("HB_Notif::hb_common table updated with RECONFIGURATION state") commit_and_close_db(connection_db) return True diff --git a/miss_htbt_service/db_monitoring.py b/miss_htbt_service/db_monitoring.py index fe47fd7..32e8edc 100644 --- a/miss_htbt_service/db_monitoring.py +++ b/miss_htbt_service/db_monitoring.py @@ -40,9 +40,9 @@ def sendControlLoopEvent(CLType, pol_url, policy_version, policy_name, policy_sc closed_control_loop_name, version, target): msg = "DBM:Time to raise Control Loop Event for Control loop typ /target type - ", CLType, target_type _logger.info(msg) - if (CLType == "ONSET"): + if CLType == "ONSET": _logger.info("DBM:Heartbeat not received, raising alarm event") - if (target_type == "VNF"): + if target_type == "VNF": json_object = json.dumps({ "closedLoopEventClient": "DCAE_Heartbeat_MS", "policyVersion": policy_version, @@ -57,8 +57,8 @@ def sendControlLoopEvent(CLType, pol_url, policy_version, policy_name, policy_sc "target": target, "requestID": "8c1b8bd8-06f7-493f-8ed7-daaa4cc481bc", "from": "DCAE" - }); - elif (target_type == "VM"): + }) + elif target_type == "VM": json_object = json.dumps({ "closedLoopEventClient": "DCAE_Heartbeat_MS", "policyVersion": policy_version, @@ -73,13 +73,13 @@ def sendControlLoopEvent(CLType, pol_url, policy_version, policy_name, policy_sc "target": target, "requestID": "8c1b8bd8-06f7-493f-8ed7-daaa4cc481bc", "from": "DCAE" - }); + }) else: return True - elif (CLType == "ABATED"): + elif CLType == "ABATED": _logger.info("DBM:Heartbeat received, clearing alarm event") # last_date_time = datetime.datetime.now() - if (target_type == "VNF"): + if target_type == "VNF": json_object = json.dumps({ "closedLoopEventClient": "DCAE_Heartbeat_MS", "policyVersion": policy_version, @@ -94,8 +94,8 @@ def sendControlLoopEvent(CLType, pol_url, policy_version, policy_name, policy_sc "target": target, "requestID": "8c1b8bd8-06f7-493f-8ed7-daaa4cc481bc", "from": "DCAE" - }); - elif (target_type == "VM"): + }) + elif target_type == "VM": json_object = json.dumps({ "closedLoopEventClient": "DCAE_Heartbeat_MS", "policyVersion": policy_version, @@ -110,7 +110,7 @@ def sendControlLoopEvent(CLType, pol_url, policy_version, policy_name, policy_sc "target": target, "requestID": "8c1b8bd8-06f7-493f-8ed7-daaa4cc481bc", "from": "DCAE" - }); + }) else: return True else: @@ -129,25 +129,25 @@ def sendControlLoopEvent(CLType, pol_url, policy_version, policy_name, policy_sc ret = r.status_code msg = "DBM:Status code for sending the control loop event is", ret _logger.info(msg) - except(Exception) as err: + except Exception as err: msg = 'Message send failure : ', err _logger.error(msg) return True def db_monitoring(current_pid, json_file, user_name, password, ip_address, port_num, db_name): - while (True): + while True: time.sleep(20) envPytest = os.getenv('pytest', "") - if (envPytest == 'test'): + if envPytest == 'test': break try: with open(json_file, 'r') as outfile: cfg = json.load(outfile) pol_url = str(cfg['streams_publishes']['dcae_cl_out']['dmaap_info']['topic_url']) - except(Exception) as err: + except Exception as err: msg = 'Json file process error : ', err _logger.error(msg) continue @@ -157,7 +157,7 @@ def db_monitoring(current_pid, json_file, user_name, password, ip_address, port_ source_name = source_name + "-" + str(os.getenv('SERVICE_NAME', "")) connection_db = pm.postgres_db_open(user_name, password, ip_address, port_num, db_name) cur = connection_db.cursor() - if (int(current_pid) == int(hbc_pid) and source_name == hbc_srcName and hbc_state == "RUNNING"): + if int(current_pid) == int(hbc_pid) and source_name == hbc_srcName and hbc_state == "RUNNING": _logger.info("DBM: Active DB Monitoring Instance") cur.execute("SELECT event_name FROM vnf_table_1") vnf_list = [item[0] for item in cur.fetchall()] @@ -165,7 +165,7 @@ def db_monitoring(current_pid, json_file, user_name, password, ip_address, port_ cur.execute("SELECT current_state FROM hb_common") rows = cur.fetchall() hbc_state = rows[0][0] - if (hbc_state == "RECONFIGURATION"): + if hbc_state == "RECONFIGURATION": _logger.info("DBM:Waiting for hb_common state to become RUNNING") break @@ -185,18 +185,18 @@ def db_monitoring(current_pid, json_file, user_name, password, ip_address, port_ target = rows[0][9] version = rows[0][10] comparision_time = (heartbeat_interval * heartbeat_missed_count) * 1000 - if (validity_flag == 1): + if validity_flag == 1: for source_name_key in range(source_name_count): epoc_time = int(round(time.time() * 1000)) cur.execute("SELECT last_epo_time, source_name, cl_flag FROM vnf_table_2 WHERE " "event_name = %s AND source_name_key = %s", (event_name, (source_name_key + 1))) row = cur.fetchall() - if (len(row) == 0): + if len(row) == 0: continue epoc_time_sec = row[0][0] srcName = row[0][1] cl_flag = row[0][2] - if ((epoc_time - epoc_time_sec) > comparision_time and cl_flag == 0): + if (epoc_time - epoc_time_sec) > comparision_time and cl_flag == 0: sendControlLoopEvent("ONSET", pol_url, policy_version, policy_name, policy_scope, target_type, srcName, epoc_time, closed_control_loop_name, version, target) @@ -204,7 +204,7 @@ def db_monitoring(current_pid, json_file, user_name, password, ip_address, port_ cur.execute("UPDATE vnf_table_2 SET CL_FLAG = %s WHERE EVENT_NAME = %s AND " "source_name_key = %s", (cl_flag, event_name, (source_name_key + 1))) connection_db.commit() - elif ((epoc_time - epoc_time_sec) < comparision_time and cl_flag == 1): + elif (epoc_time - epoc_time_sec) < comparision_time and cl_flag == 1: sendControlLoopEvent("ABATED", pol_url, policy_version, policy_name, policy_scope, target_type, srcName, epoc_time, closed_control_loop_name, version, target) @@ -214,7 +214,7 @@ def db_monitoring(current_pid, json_file, user_name, password, ip_address, port_ connection_db.commit() else: # pragma: no cover - msg = "DBM:DB Monitoring is ignored for %s since validity flag is 0" % (event_name) + msg = "DBM:DB Monitoring is ignored for %s since validity flag is 0" % event_name _logger.info(msg) cur.execute("DELETE FROM vnf_table_2 WHERE EVENT_NAME = %s", (event_name,)) @@ -238,8 +238,8 @@ if __name__ == "__main__": ip_address, port_num, user_name, password, db_name, cbs_polling_required, cbs_polling_interval = db.read_hb_properties(jsfile) msg = "DBM:Parent process ID and json file name", current_pid, jsfile _logger.info(msg) - while (True): + while True: db_monitoring(current_pid, jsfile, user_name, password, ip_address, port_num, db_name) envPytest = os.getenv('pytest', "") - if (envPytest == 'test'): + if envPytest == 'test': break diff --git a/miss_htbt_service/htbtworker.py b/miss_htbt_service/htbtworker.py index bfde762..467b2b7 100644 --- a/miss_htbt_service/htbtworker.py +++ b/miss_htbt_service/htbtworker.py @@ -37,13 +37,13 @@ _logger = get_logger.get_logger(__name__) def read_json_file(i, prefix="../../tests"): - if (i == 0): + if i == 0: with open(path.abspath(path.join(__file__, f"{prefix}/test1.json")), "r") as outfile: cfg = json.load(outfile) - elif (i == 1): + elif i == 1: with open(path.abspath(path.join(__file__, f"{prefix}/test2.json")), "r") as outfile: cfg = json.load(outfile) - elif (i == 2): + elif i == 2: with open(path.abspath(path.join(__file__, f"{prefix}/test3.json")), 'r') as outfile: cfg = json.load(outfile) return cfg @@ -53,21 +53,21 @@ def process_msg(jsfile, user_name, password, ip_address, port_num, db_name): global mr_url i = 0 sleep_duration = 20 - while (True): + while True: time.sleep(sleep_duration) with open(jsfile, 'r') as outfile: cfg = json.load(outfile) mr_url = str(cfg['streams_subscribes']['ves-heartbeat']['dmaap_info']['topic_url']) - while (True): + while True: hbc_pid, hbc_state, hbc_srcName, hbc_time = db.read_hb_common(user_name, password, ip_address, port_num, db_name) - if (hbc_state == "RECONFIGURATION"): + if hbc_state == "RECONFIGURATION": _logger.info("HBT:Waiting for hb_common state to become RUNNING") time.sleep(10) else: break - if (os.getenv('pytest', "") == 'test'): + if os.getenv('pytest', "") == 'test': eventnameList = ["Heartbeat_vDNS", "Heartbeat_vFW", "Heartbeat_xx"] connection_db = 0 else: @@ -84,14 +84,14 @@ def process_msg(jsfile, user_name, password, ip_address, port_num, db_name): msg = "HBT:Getting :" + get_url _logger.info(msg) - if (os.getenv('pytest', "") == 'test'): + if os.getenv('pytest', "") == 'test': jsonobj = read_json_file(i) jobj = [] jobj.append(jsonobj) i = i + 1 msg = "HBT:newly received test message", jobj _logger.info(msg) - if (i >= 3): + if i >= 3: i = 0 break else: @@ -100,9 +100,9 @@ def process_msg(jsfile, user_name, password, ip_address, port_num, db_name): _logger.info(msg) inputString = res.text # If mrstatus in message body indicates some information, not json msg. - if ("mrstatus" in inputString): + if "mrstatus" in inputString: continue - jlist = inputString.split('\n'); + jlist = inputString.split('\n') # Process the DMaaP input message retreived error = False for line in jlist: @@ -113,13 +113,13 @@ def process_msg(jsfile, user_name, password, ip_address, port_num, db_name): _logger.error(msg) error = True break - if (error == True): + if error: continue if len(jobj) == 0: continue for item in jobj: try: - if (os.getenv('pytest', "") == 'test'): + if os.getenv('pytest', "") == 'test': jitem = jsonobj else: jitem = json.loads(item) @@ -127,13 +127,13 @@ def process_msg(jsfile, user_name, password, ip_address, port_num, db_name): lastepo = (jitem['event']['commonEventHeader']['lastEpochMicrosec']) seqnum = (jitem['event']['commonEventHeader']['sequence']) eventName = (jitem['event']['commonEventHeader']['eventName']) - except(Exception) as err: + except Exception as err: msg = "HBT message process error - ", err _logger.error(msg) continue msg = "HBT:Newly received HB event values ::", eventName, lastepo, srcname _logger.info(msg) - if (db_table_creation_check(connection_db, "vnf_table_2") == False): + if db_table_creation_check(connection_db, "vnf_table_2") is False: msg = "HBT:Creating vnf_table_2" _logger.info(msg) cur.execute(""" @@ -148,15 +148,15 @@ def process_msg(jsfile, user_name, password, ip_address, port_num, db_name): else: msg = "HBT:vnf_table_2 is already there" _logger.info(msg) - if (eventName in eventnameList): # pragma: no cover - if (os.getenv('pytest', "") == 'test'): + if eventName in eventnameList: # pragma: no cover + if os.getenv('pytest', "") == 'test': break cur.execute("SELECT source_name_count FROM vnf_table_1 WHERE event_name = %s", (eventName,)) row = cur.fetchone() source_name_count = row[0] source_name_key = source_name_count + 1 cl_flag = 0 - if (source_name_count == 0): # pragma: no cover + if source_name_count == 0: # pragma: no cover msg = "HBT: Insert entry in table_2,source_name_count=0 : ", row _logger.info(msg) cur.execute("INSERT INTO vnf_table_2 VALUES(%s,%s,%s,%s,%s)", @@ -170,10 +170,10 @@ def process_msg(jsfile, user_name, password, ip_address, port_num, db_name): cur.execute("SELECT source_name FROM vnf_table_2 WHERE event_name = %s AND " "source_name_key = %s", (eventName, (source_name_key + 1))) row = cur.fetchall() - if (len(row) == 0): + if len(row) == 0: continue db_srcname = row[0][0] - if (db_srcname == srcname): + if db_srcname == srcname: msg = "HBT: Update vnf_table_2 : ", source_name_key, row _logger.info(msg) cur.execute("UPDATE vnf_table_2 SET LAST_EPO_TIME = %s, SOURCE_NAME = %s " @@ -185,7 +185,7 @@ def process_msg(jsfile, user_name, password, ip_address, port_num, db_name): continue msg = "HBT: The source_name_key and source_name_count are ", source_name_key, source_name_count _logger.info(msg) - if (source_name_count == (source_name_key + 1)): + if source_name_count == (source_name_key + 1): source_name_key = source_name_count + 1 msg = "HBT: Insert entry in table_2 : ", row _logger.info(msg) @@ -197,31 +197,29 @@ def process_msg(jsfile, user_name, password, ip_address, port_num, db_name): _logger.info("HBT:eventName is not being monitored, Igonoring JSON message") commit_db(connection_db) commit_and_close_db(connection_db) - if (os.getenv('pytest', "") != 'test'): + if os.getenv('pytest', "") != 'test': cur.close() def postgres_db_open(username, password, host, port, database_name): - if (os.getenv('pytest', "") == 'test'): + if os.getenv('pytest', "") == 'test': return True connection = psycopg2.connect(database=database_name, user=username, password=password, host=host, port=port) return connection def db_table_creation_check(connection_db, table_name): - if (os.getenv('pytest', "") == 'test'): + if os.getenv('pytest', "") == 'test': return True try: cur = connection_db.cursor() cur.execute("SELECT * FROM information_schema.tables WHERE table_name = %s", (table_name,)) database_names = cur.fetchone() - if (database_names is not None): - if (table_name in database_names): + if database_names is not None: + if table_name in database_names: return True else: return False - - except psycopg2.DatabaseError as e: msg = 'COMMON:Error %s' % e _logger.error(msg) @@ -230,7 +228,7 @@ def db_table_creation_check(connection_db, table_name): def commit_db(connection_db): - if (os.getenv('pytest', "") == 'test'): + if os.getenv('pytest', "") == 'test': return True try: connection_db.commit() # <--- makes sure the change is shown in the database @@ -242,7 +240,7 @@ def commit_db(connection_db): def commit_and_close_db(connection_db): - if (os.getenv('pytest', "") == 'test'): + if os.getenv('pytest', "") == 'test': return True try: connection_db.commit() # <--- makes sure the change is shown in the database diff --git a/miss_htbt_service/misshtbtd.py b/miss_htbt_service/misshtbtd.py index 552e56a..89ae05f 100644 --- a/miss_htbt_service/misshtbtd.py +++ b/miss_htbt_service/misshtbtd.py @@ -71,14 +71,14 @@ def create_database(update_db, jsfile, ip_address, port_num, user_name, password _logger.info("MSHBD:Database already exists") cur.close() con.close() - except(Exception) as err: + except Exception as err: msg = "MSHBD:DB Creation -", err _logger.error(msg) def read_hb_common(user_name, password, ip_address, port_num, db_name): envPytest = os.getenv('pytest', "") - if (envPytest == 'test'): + if envPytest == 'test': hbc_pid = 10 hbc_srcName = "srvc_name" hbc_time = 1584595881 @@ -102,10 +102,10 @@ def create_update_hb_common(update_flg, process_id, state, user_name, password, source_name = socket.gethostname() source_name = source_name + "-" + os.getenv('SERVICE_NAME', "") envPytest = os.getenv('pytest', "") - if (envPytest != 'test'): + if envPytest != 'test': connection_db = heartbeat.postgres_db_open(user_name, password, ip_address, port_num, db_name) cur = connection_db.cursor() - if (heartbeat.db_table_creation_check(connection_db, "hb_common") == False): + if heartbeat.db_table_creation_check(connection_db, "hb_common") is False: cur.execute(""" CREATE TABLE hb_common ( PROCESS_ID integer primary key, @@ -115,7 +115,7 @@ def create_update_hb_common(update_flg, process_id, state, user_name, password, )""") cur.execute("INSERT INTO hb_common VALUES(%s, %s, %s, %s)", (process_id, source_name, current_time, state)) _logger.info("MSHBT:Created hb_common DB and updated new values") - elif (update_flg == 1): + elif update_flg == 1: cur.execute("UPDATE hb_common SET LAST_ACCESSED_TIME = %s, CURRENT_STATE = %s " "WHERE PROCESS_ID = %s AND SOURCE_NAME = %s", (current_time, state, process_id, source_name)) _logger.info("MSHBT:Updated hb_common DB with new values") @@ -129,11 +129,11 @@ def create_update_vnf_table_1(jsfile, update_db, connection_db): hbcfg = cfg['heartbeat_config'] jhbcfg = json.loads(hbcfg) envPytest = os.getenv('pytest', "") - if (envPytest == 'test'): + if envPytest == 'test': vnf_list = ["Heartbeat_vDNS", "Heartbeat_vFW", "Heartbeat_xx"] else: cur = connection_db.cursor() - if (heartbeat.db_table_creation_check(connection_db, "vnf_table_1") == False): + if heartbeat.db_table_creation_check(connection_db, "vnf_table_1") is False: cur.execute(""" CREATE TABLE vnf_table_1 ( EVENT_NAME varchar primary key, @@ -150,7 +150,7 @@ def create_update_vnf_table_1(jsfile, update_db, connection_db): VALIDITY_FLAG integer )""") _logger.info("MSHBT:Created vnf_table_1 table") - if (update_db == 1): + if update_db == 1: cur.execute("UPDATE vnf_table_1 SET VALIDITY_FLAG=0 WHERE VALIDITY_FLAG=1") _logger.info("MSHBT:Set Validity flag to zero in vnf_table_1 table") # Put some initial values into the queue @@ -170,10 +170,10 @@ def create_update_vnf_table_1(jsfile, update_db, connection_db): target = vnf['target'] version = vnf['version'] - if (envPytest == 'test'): + if envPytest == 'test': # skip executing SQL in test continue - if (nfc not in vnf_list): + if nfc not in vnf_list: cur.execute("INSERT INTO vnf_table_1 VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)", (nfc, missed, intvl, clloop, policyVersion, policyName, policyScope, target_type, target, version, source_name_count, validity_flag)) @@ -184,7 +184,7 @@ def create_update_vnf_table_1(jsfile, update_db, connection_db): TARGET_TYPE = %s, TARGET = %s, VERSION = %s, VALIDITY_FLAG = %s where EVENT_NAME = %s""", (missed, intvl, clloop, policyVersion, policyName, policyScope, target_type, target, version, validity_flag, nfc)) - if (envPytest != 'test'): + if envPytest != 'test': cur.close() _logger.info("MSHBT:Updated vnf_table_1 as per the json configuration file") @@ -215,7 +215,7 @@ def read_hb_properties_default(): s = open(hb_properties_file, 'r') a = yaml.full_load(s) - if ((os.getenv('pg_ipAddress') is None) or (os.getenv('pg_portNum') is None) or (os.getenv('pg_userName') is None) or (os.getenv('pg_passwd') is None)): + if (os.getenv('pg_ipAddress') is None) or (os.getenv('pg_portNum') is None) or (os.getenv('pg_userName') is None) or (os.getenv('pg_passwd') is None): ip_address = a['pg_ipAddress'] port_num = a['pg_portNum'] user_name = a['pg_userName'] @@ -238,7 +238,7 @@ def read_hb_properties(jsfile): try: with open(jsfile, 'r') as outfile: cfg = json.load(outfile) - except(Exception) as err: + except Exception as err: msg = "CBS Json file load error - ", err _logger.error(msg) return read_hb_properties_default() @@ -258,7 +258,7 @@ def read_hb_properties(jsfile): os.environ['groupID'] = group_id if "SERVICE_NAME" in cfg: os.environ['SERVICE_NAME'] = str(cfg['SERVICE_NAME']) - except(Exception) as err: + except Exception as err: msg = "CBS Json file read parameter error - ", err _logger.error(msg) return read_hb_properties_default() @@ -268,7 +268,7 @@ def read_hb_properties(jsfile): def fetch_json_file(): if get_cbs_config(): envPytest = os.getenv('pytest', "") - if (envPytest == 'test'): + if envPytest == 'test': current_runtime_config_file_name = "/tmp/opt/app/miss_htbt_service/etc/config.json" else: current_runtime_config_file_name = "../etc/download.json" @@ -297,15 +297,15 @@ def fetch_json_file(): def create_update_db(update_db, jsfile, ip_address, port_num, user_name, password, db_name): envPytest = os.getenv('pytest', "") - if (envPytest != 'test'): # pragma: no cover - if (update_db == 0): + if envPytest != 'test': # pragma: no cover + if update_db == 0: create_database(update_db, jsfile, ip_address, port_num, user_name, password, db_name) msg = "MSHBT: DB parameters -", ip_address, port_num, user_name, password, db_name _logger.info(msg) connection_db = heartbeat.postgres_db_open(user_name, password, ip_address, port_num, db_name) cur = connection_db.cursor() - if (update_db == 0): - if (heartbeat.db_table_creation_check(connection_db, "vnf_table_1") == False): + if update_db == 0: + if heartbeat.db_table_creation_check(connection_db, "vnf_table_1") is False: create_update_vnf_table_1(jsfile, update_db, connection_db) else: create_update_vnf_table_1(jsfile, update_db, connection_db) @@ -314,7 +314,7 @@ def create_update_db(update_db, jsfile, ip_address, port_num, user_name, passwor def create_process(job_list, jsfile, pid_current): - if (len(job_list) == 0): + if len(job_list) == 0: p1 = multiprocessing.Process(target=hb_worker_process, args=(jsfile,)) time.sleep(1) p2 = multiprocessing.Process(target=db_monitoring_process, args=(pid_current, jsfile,)) @@ -341,7 +341,7 @@ def main(): ip_address, port_num, user_name, password, db_name, cbs_polling_required, cbs_polling_interval = read_hb_properties(jsfile) msg = "MSHBT:HB Properties -", ip_address, port_num, user_name, password, db_name, cbs_polling_required, cbs_polling_interval _logger.info(msg) - if (cbs_polling_required == 'True'): + if cbs_polling_required == 'True': p3 = multiprocessing.Process(target=hb_cbs_polling_process, args=(pid_current,)) p3.start() update_db = 0 @@ -353,7 +353,7 @@ def main(): _logger.info(msg) _logger.info("MSHBD:Now be in a continuous loop") i = 0 - while (True): + while True: hbc_pid, hbc_state, hbc_srcName, hbc_time = read_hb_common(user_name, password, ip_address, port_num, db_name) msg = "MSHBT: hb_common values ", hbc_pid, hbc_state, hbc_srcName, hbc_time _logger.info(msg) @@ -364,24 +364,24 @@ def main(): source_name = socket.gethostname() source_name = source_name + "-" + str(os.getenv('SERVICE_NAME', "")) envPytest = os.getenv('pytest', "") - if (envPytest == 'test'): + if envPytest == 'test': if i == 2: hbc_pid = pid_current source_name = hbc_srcName hbc_state = "RECONFIGURATION" - elif (i > 3): + elif i > 3: hbc_pid = pid_current source_name = hbc_srcName hbc_state = "RUNNING" - if (time_difference < 60): - if ((int(hbc_pid) == int(pid_current)) and (source_name == hbc_srcName)): + if time_difference < 60: + if (int(hbc_pid) == int(pid_current)) and (source_name == hbc_srcName): msg = "MSHBD:config status is", hbc_state _logger.info(msg) - if (hbc_state == "RUNNING"): + if hbc_state == "RUNNING": state = "RUNNING" update_flg = 1 create_update_hb_common(update_flg, pid_current, state, user_name, password, ip_address, port_num, db_name) - elif (hbc_state == "RECONFIGURATION"): + elif hbc_state == "RECONFIGURATION": _logger.info("MSHBD:Reconfiguration is in progress,Starting new processes by killing the present processes") jsfile = fetch_json_file() update_db = 1 @@ -395,7 +395,7 @@ def main(): else: _logger.info("MSHBD:Inactive Instance: Process IDs are different, Keep Looping") - if (len(job_list) >= 2): + if len(job_list) >= 2: _logger.info("MSHBD:Inactive Instance: Main and DBM thread are waiting to become ACTIVE") else: jsfile = fetch_json_file() @@ -404,9 +404,9 @@ def main(): job_list = create_process(job_list, jsfile, pid_current) else: _logger.info("MSHBD:Active instance is inactive for long time: Time to switchover") - if ((int(hbc_pid) != int(pid_current)) or (source_name != hbc_srcName)): + if (int(hbc_pid) != int(pid_current)) or (source_name != hbc_srcName): _logger.info("MSHBD:Initiating to become Active Instance") - if (len(job_list) >= 2): + if len(job_list) >= 2: _logger.info("MSHBD:HB and DBM thread are waiting to become ACTIVE") else: jsfile = fetch_json_file() @@ -421,24 +421,24 @@ def main(): time.sleep(25) if os.getenv('pytest', "") == 'test': i = i + 1 - if (i > 5): + if i > 5: _logger.info("Terminating main process for pytest") p3.terminate() time.sleep(1) p3.join() - if (len(job_list) > 0): + if len(job_list) > 0: job_list[0].terminate() time.sleep(1) job_list[0].join() job_list.remove(job_list[0]) - if (len(job_list) > 0): + if len(job_list) > 0: job_list[0].terminate() time.sleep(1) job_list[0].join() job_list.remove(job_list[0]) break - except (Exception) as e: + except Exception as e: msg = "MSHBD:Exception as %s" % (str(traceback.format_exc())) _logger.error(msg) diff --git a/tests/test_check_health.py b/tests/test_check_health.py index a159212..d3088f9 100644 --- a/tests/test_check_health.py +++ b/tests/test_check_health.py @@ -1,6 +1,7 @@ # ============LICENSE_START======================================================= # Copyright (c) 2017-2020 AT&T Intellectual Property. All rights reserved. # Copyright (c) 2019 Pantheon.tech. All rights reserved. +# Copyright 2021 Fujitsu Ltd. # ================================================================================ # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -23,7 +24,7 @@ import io class MockSocket(object): def getsockname(self): - return ('sockname',) + return 'sockname', class MockRequest(object): _sock = MockSocket() |