aboutsummaryrefslogtreecommitdiffstats
path: root/dblib/provider/pom.xml
blob: 730919de03a63e331fbb385f7d2904d29d28d387 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.onap.ccsdk.sli.core</groupId>
		<artifactId>dblib</artifactId>
		<version>0.1.2-SNAPSHOT</version>
	</parent>
	<artifactId>dblib-provider</artifactId>
	<version>0.1.2-SNAPSHOT</version>
	<packaging>bundle</packaging>
	<name>DBLIB Adaptor - Provider</name>
	<url>http://maven.apache.org</url>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
	</properties>
	<dependencies>
		<dependency>
			<groupId>junit</groupId>
			<artifactId>junit</artifactId>
			<version>${junit.version}</version>
			<scope>test</scope>
		</dependency>
        <dependency>
            <groupId>ch.vorburger.mariaDB4j</groupId>
            <artifactId>mariaDB4j</artifactId>
            <version>2.2.3</version>
            <scope>test</scope>
        </dependency>
		<dependency>
			<groupId>equinoxSDK381</groupId>
			<artifactId>org.eclipse.osgi</artifactId>
			<version>${equinox.osgi.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-api</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>jcl-over-slf4j</artifactId>
			<version>${slf4j.version}</version>
		</dependency>
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-simple</artifactId>
			<version>${slf4j.version}</version>
			<scope>test</scope>
		</dependency>
        <dependency>
            <groupId>org.mariadb.jdbc</groupId>
            <artifactId>mariadb-java-client</artifactId>
            <version>${mariadb.connector.version}</version>
        </dependency>
		<dependency>
		    <groupId>org.apache.tomcat</groupId>
		    <artifactId>tomcat-jdbc</artifactId>
		    <version>${tomcat-jdbc.version}</version>
		</dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
        </dependency>
		<dependency>
			<groupId>org.onap.ccsdk.sli.core</groupId>
			<artifactId>utils-provider</artifactId>
			<version>${project.version}</version>
		</dependency>

        <!-- Testing related dependencies -->
        <dependency>
            <groupId>org.mockito</groupId>
            <artifactId>mockito-core</artifactId>
            <scope>test</scope>
        </dependency>
	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.apache.felix</groupId>
				<artifactId>maven-bundle-plugin</artifactId>
				<version>${bundle.plugin.version}</version>
				<extensions>true</extensions>
				<configuration>
					<instructions>
						<Bundle-SymbolicName>org.onap.ccsdk.sli.core.dblib</Bundle-SymbolicName>
						<Export-Package>org.onap.ccsdk.sli.core.dblib;version=${project.version}</Export-Package>
                        <Import-Package>*,org.mariadb.jdbc</Import-Package>
						<Embed-Transitive>true</Embed-Transitive>
					</instructions>
				</configuration>

			</plugin>


		</plugins>
	</build>
</project>
Name.Function.Magic */ .highlight .vc { color: #f8f8f2 } /* Name.Variable.Class */ .highlight .vg { color: #f8f8f2 } /* Name.Variable.Global */ .highlight .vi { color: #f8f8f2 } /* Name.Variable.Instance */ .highlight .vm { color: #f8f8f2 } /* Name.Variable.Magic */ .highlight .il { color: #ae81ff } /* Literal.Number.Integer.Long */ } @media (prefers-color-scheme: light) { .highlight .hll { background-color: #ffffcc } .highlight .c { color: #888888 } /* Comment */ .highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */ .highlight .k { color: #008800; font-weight: bold } /* Keyword */ .highlight .ch { color: #888888 } /* Comment.Hashbang */ .highlight .cm { color: #888888 } /* Comment.Multiline */ .highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */ .highlight .cpf { color: #888888 } /* Comment.PreprocFile */ .highlight .c1 { color: #888888 } /* Comment.Single */ .highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */ .highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */ .highlight .ge { font-style: italic } /* Generic.Emph */ .highlight .gr { color: #aa0000 } /* Generic.Error */ .highlight .gh { color: #333333 } /* Generic.Heading */ .highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */ .highlight .go { color: #888888 } /* Generic.Output */ .highlight .gp { color: #555555 } /* Generic.Prompt */ .highlight .gs { font-weight: bold } /* Generic.Strong */ .highlight .gu { color: #666666 } /* Generic.Subheading */ .highlight .gt { color: #aa0000 } /* Generic.Traceback */ .highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */ .highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */ .highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */ .highlight .kp { color: #008800 } /* Keyword.Pseudo */ .highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */ .highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */ .highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */ .highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */ .highlight .na { color: #336699 } /* Name.Attribute */ .highlight .nb { color: #003388 } /* Name.Builtin */ .highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */ .highlight .no { color: #003366; font-weight: bold } /* Name.Constant */ .highlight .nd { color: #555555 } /* Name.Decorator */ .highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */ .highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */ .highlight .nl { color: #336699; font-style: italic } /* Name.Label */ .highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */ .highlight .py { color: #336699; font-weight: bold } /* Name.Property */ .highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */ .highlight .nv { color: #336699 } /* Name.Variable */ .highlight .ow { color: #008800 } /* Operator.Word */ .highlight .w { color: #bbbbbb } /* Text.Whitespace */ .highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */ .highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */ .highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */ .highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */ .highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */ .highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */ .highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */ .highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */ .highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */ .highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */ .highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */ .highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */ .highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */ .highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */ .highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */ .highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */ .highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */ .highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */ .highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */ .highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */ .highlight .vc { color: #336699 } /* Name.Variable.Class */ .highlight .vg { color: #dd7700 } /* Name.Variable.Global */ .highlight .vi { color: #3333bb } /* Name.Variable.Instance */ .highlight .vm { color: #336699 } /* Name.Variable.Magic */ .highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */ }
#!/usr/bin/env python3
# ============LICENSE_START=======================================================
# Copyright (c) 2017-2022 AT&T Intellectual Property. All rights reserved.
# Copyright (c) 2019 Pantheon.tech. All rights reserved.
# Copyright (c) 2020 Deutsche Telekom. All rights reserved.
# Copyright (c) 2021 Samsung Electronics. All rights reserved.
# Copyright (c) 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.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============LICENSE_END=========================================================
#
#  This is a main process that does the following
#  - Creates the CBS polling process that indicates the periodic download of
#    configuration file from CBS
#  - Creates heartbeat worker process that receives the Heartbeat messages from VNF
#  - Creates DB Monitoring process that generates Control loop event
#  - Download the CBS configuration and populate the DB
#
#  Author  Prakash Hosangady(ph553f@att.com)
import shutil
import logging
import traceback
import os
import sys
import json
import time
import multiprocessing
import subprocess
import yaml
import socket
import os.path as path
import tempfile
from pathlib import Path

import check_health
import htbtworker as heartbeat
import get_logger
import cbs_polling
from mod import trapd_settings as tds
from mod.trapd_get_cbs_config import get_cbs_config

hb_properties_file = path.abspath(path.join(__file__, "../config/hbproperties.yaml"))
_logger = logging.getLogger(__name__)

ABSOLUTE_PATH1 = path.abspath(path.join(__file__, "../htbtworker.py"))
ABSOLUTE_PATH2 = path.abspath(path.join(__file__, "../db_monitoring.py"))
CONFIG_PATH = "../etc/config.json"


def create_database(update_db, jsfile, ip_address, port_num, user_name, password, db_name):
    from psycopg2 import connect

    try:
        con = connect(user=user_name, host=ip_address, password=password)
        database_name = db_name
        con.autocommit = True
        cur = con.cursor()
        cur.execute("SELECT COUNT(*) = 0 FROM pg_catalog.pg_database WHERE datname = %s", (database_name,))
        not_exists_row = cur.fetchone()
        msg = "MSHBT:Create_database:DB not exists? ", not_exists_row
        _logger.info(msg)
        not_exists = not_exists_row[0]
        if not_exists is True:
            _logger.info("MSHBT:Creating database ...")
            cur.execute("CREATE DATABASE %s", (database_name,))
        else:
            _logger.info("MSHBD:Database already exists")
        cur.close()
        con.close()
    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):
    env_pytest = os.getenv("pytest", "")
    if env_pytest == "test":
        hbc_pid = 10
        hbc_src_name = "srvc_name"
        hbc_time = 1584595881
        hbc_state = "RUNNING"
        return hbc_pid, hbc_state, hbc_src_name, hbc_time
    connection_db = heartbeat.postgres_db_open(user_name, password, ip_address, port_num, db_name)
    cur = connection_db.cursor()
    cur.execute("SELECT process_id, source_name, last_accessed_time, current_state FROM hb_common")
    rows = cur.fetchall()
    hbc_pid = rows[0][0]
    hbc_src_name = rows[0][1]
    hbc_time = rows[0][2]
    hbc_state = rows[0][3]
    heartbeat.commit_and_close_db(connection_db)
    cur.close()
    return hbc_pid, hbc_state, hbc_src_name, hbc_time


def create_update_hb_common(update_flg, process_id, state, user_name, password, ip_address, port_num, db_name):
    current_time = int(round(time.time()))
    source_name = socket.gethostname()
    source_name = source_name + "-" + os.getenv("SERVICE_NAME", "")
    env_pytest = os.getenv("pytest", "")
    if env_pytest != "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") is False:
            cur.execute(
                """
                CREATE TABLE hb_common (
                    PROCESS_ID integer primary key,
                    SOURCE_NAME varchar,
                    LAST_ACCESSED_TIME integer,
                    CURRENT_STATE varchar
                )"""
            )
            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:
            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")
        heartbeat.commit_and_close_db(connection_db)
        cur.close()


def create_update_vnf_table_1(jsfile, update_db, connection_db):
    with open(jsfile, "r") as outfile:
        cfg = json.load(outfile)
    hbcfg = cfg["heartbeat_config"]
    jhbcfg = json.loads(hbcfg)
    env_pytest = os.getenv("pytest", "")
    if env_pytest == "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") is False:
            cur.execute(
                """
                CREATE TABLE vnf_table_1 (
                    EVENT_NAME varchar primary key,
                    HEARTBEAT_MISSED_COUNT integer,
                    HEARTBEAT_INTERVAL integer,
                    CLOSED_CONTROL_LOOP_NAME varchar,
                    POLICY_VERSION varchar,
                    POLICY_NAME varchar,
                    POLICY_SCOPE varchar,
                    TARGET_TYPE varchar,
                    TARGET varchar,
                    VERSION varchar,
                    SOURCE_NAME_COUNT integer,
                    VALIDITY_FLAG integer
                )"""
            )
            _logger.info("MSHBT:Created vnf_table_1 table")
        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
        cur.execute("SELECT event_name FROM vnf_table_1")
        vnf_list = [item[0] for item in cur.fetchall()]
    for vnf in jhbcfg["vnfs"]:
        nfc = vnf["eventName"]
        validity_flag = 1
        source_name_count = 0
        missed = vnf["heartbeatcountmissed"]
        intvl = vnf["heartbeatinterval"]
        clloop = vnf["closedLoopControlName"]
        policy_version = vnf["policyVersion"]
        policy_name = vnf["policyName"]
        policy_scope = vnf["policyScope"]
        target_type = vnf["target_type"]
        target = vnf["target"]
        version = vnf["version"]

        if env_pytest == "test":
            # skip executing SQL in test
            continue
        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,
                    policy_version,
                    policy_name,
                    policy_scope,
                    target_type,
                    target,
                    version,
                    source_name_count,
                    validity_flag,
                ),
            )
            _logger.debug("Inserted new event_name = %s into vnf_table_1", nfc)
        else:
            cur.execute(
                """UPDATE vnf_table_1 SET HEARTBEAT_MISSED_COUNT = %s, HEARTBEAT_INTERVAL = %s,
                CLOSED_CONTROL_LOOP_NAME = %s, POLICY_VERSION = %s, POLICY_NAME = %s, POLICY_SCOPE = %s,
                TARGET_TYPE = %s, TARGET = %s, VERSION = %s, VALIDITY_FLAG = %s where EVENT_NAME = %s""",
                (
                    missed,
                    intvl,
                    clloop,
                    policy_version,
                    policy_name,
                    policy_scope,
                    target_type,
                    target,
                    version,
                    validity_flag,
                    nfc,
                ),
            )
    if env_pytest != "test":
        cur.close()
    _logger.info("MSHBT:Updated vnf_table_1 as per the json configuration file")


def hb_worker_process(config_file_path):
    subprocess.call([ABSOLUTE_PATH1, config_file_path])
    sys.stdout.flush()
    _logger.info("MSHBT:Creaated Heartbeat worker process")
    return


def db_monitoring_process(current_pid, jsfile):
    subprocess.call([ABSOLUTE_PATH2, str(current_pid), jsfile])
    sys.stdout.flush()
    _logger.info("MSHBT:Creaated DB Monitoring process")
    return


def read_hb_properties_default():
    # Read the hbproperties.yaml for postgress and CBS related data
    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)
    ):
        ip_address = a["pg_ipAddress"]
        port_num = a["pg_portNum"]
        user_name = a["pg_userName"]
        password = a["pg_passwd"]
    else:
        ip_address = os.getenv("pg_ipAddress")
        port_num = os.getenv("pg_portNum")
        user_name = os.getenv("pg_userName")
        password = os.getenv("pg_passwd")

    db_name = a["pg_dbName"]
    db_name = db_name.lower()
    cbs_polling_required = a["CBS_polling_allowed"]
    cbs_polling_interval = a["CBS_polling_interval"]
    s.close()
    return ip_address, port_num, user_name, password, db_name, cbs_polling_required, cbs_polling_interval


def read_hb_properties(jsfile):
    try:
        with open(jsfile, "r") as outfile:
            cfg = json.load(outfile)
    except Exception as err:
        msg = "CBS Json file load error - " + str(err)
        _logger.error(msg)
        return read_hb_properties_default()

    try:
        ip_address = str(cfg["pg_ipAddress"])
        port_num = str(cfg["pg_portNum"])
        user_name = str(cfg["pg_userName"])
        password = str(cfg["pg_passwd"])
        db_name = str(cfg["pg_dbName"])
        db_name = db_name.lower()
        cbs_polling_required = str(cfg["CBS_polling_allowed"])
        cbs_polling_interval = str(cfg["CBS_polling_interval"])
        consumer_id = str(cfg["consumerID"])
        group_id = str(cfg["groupID"])
        os.environ["consumerID"] = consumer_id
        os.environ["groupID"] = group_id
        if "SERVICE_NAME" in cfg:
            os.environ["SERVICE_NAME"] = str(cfg["SERVICE_NAME"])
    except Exception as err:
        msg = "CBS Json file read parameter error - " + str(err)
        _logger.error(msg)
        return read_hb_properties_default()
    return ip_address, port_num, user_name, password, db_name, cbs_polling_required, cbs_polling_interval


def fetch_json_file() -> str:
    """Get configuration from CBS and save it to json file.

    :return: path to saved json file
    """
    # note: this func is called from multiple subprocesses. need to be thread-safe.
    jsfile = CONFIG_PATH
    # Try to get config from CBS. If succeeded, config json is stored to tds.c_config .
    if get_cbs_config():
        # Save config to temporary file
        with tempfile.NamedTemporaryFile("w", delete=False) as temp:
            _logger.info("MSHBD: New config saved to temp file %s", temp.name)
            json.dump(tds.c_config, temp)
        # Swap current config with downloaded config
        os.makedirs(Path(jsfile).parent, exist_ok=True)
        shutil.move(temp.name, jsfile)
    else:
        _logger.warning("MSHBD: CBS Config not available, using local config")
        local_config = "./etc/config.json"
        if Path(local_config).is_file():
            jsfile = local_config
    _logger.info("MSHBD: The json file is %s", jsfile)
    return jsfile


def create_update_db(update_db, jsfile, ip_address, port_num, user_name, password, db_name):
    env_pytest = os.getenv("pytest", "")
    if env_pytest != "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") is False:
                create_update_vnf_table_1(jsfile, update_db, connection_db)
        else:
            create_update_vnf_table_1(jsfile, update_db, connection_db)
        heartbeat.commit_and_close_db(connection_db)
        cur.close()


def create_process(job_list, jsfile, pid_current):
    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,
            ),
        )
        p1.start()
        time.sleep(1)
        p2.start()
        job_list.append(p1)
        job_list.append(p2)
        msg = "MSHBD:jobs list is", job_list
        _logger.info(msg)
    return job_list


def main():
    get_logger.configure_logger("misshtbtd")
    pid_current = os.getpid()
    hc_proc = multiprocessing.Process(target=check_health.start_health_check_server)
    cbs_polling_proc = multiprocessing.Process(target=cbs_polling.cbs_polling_loop, args=(pid_current,))
    try:
        _logger.info("MSHBD:Execution Started")
        # Start health check server
        hc_proc.start()
        _logger.info("MSHBD: Started health check server. PID=%d", hc_proc.pid)

        job_list = []
        jsfile = fetch_json_file()
        (
            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)
        update_db = 0
        create_update_db(update_db, jsfile, ip_address, port_num, user_name, password, db_name)
        state = "RECONFIGURATION"
        update_flg = 0
        create_update_hb_common(update_flg, pid_current, state, user_name, password, ip_address, port_num, db_name)
        if cbs_polling_required == "True":
            # note: cbs_polling process must be started after `hb_common` table created
            cbs_polling_proc.start()
            _logger.info("MSHBD: Started CBS polling process. PID=%d", cbs_polling_proc.pid)
        _logger.info("MSHBD:Current process id is %d", pid_current)
        _logger.info("MSHBD:Now be in a continuous loop")
        i = 0
        while True:
            hbc_pid, hbc_state, hbc_src_name, hbc_time = read_hb_common(
                user_name, password, ip_address, port_num, db_name
            )
            msg = "MSHBT: hb_common values ", hbc_pid, hbc_state, hbc_src_name, hbc_time
            _logger.info(msg)
            current_time = int(round(time.time()))
            time_difference = current_time - hbc_time
            msg = (
                "MSHBD:pid,srcName,state,time,ctime,timeDiff is",
                hbc_pid,
                hbc_src_name,
                hbc_state,
                hbc_time,
                current_time,
                time_difference,
            )
            _logger.info(msg)
            source_name = socket.gethostname()
            source_name = source_name + "-" + str(os.getenv("SERVICE_NAME", ""))
            env_pytest = os.getenv("pytest", "")
            if env_pytest == "test":
                if i == 2:
                    hbc_pid = pid_current
                    source_name = hbc_src_name
                    hbc_state = "RECONFIGURATION"
                elif i > 3:
                    hbc_pid = pid_current
                    source_name = hbc_src_name
                    hbc_state = "RUNNING"
            if time_difference < 60:
                if (int(hbc_pid) == int(pid_current)) and (source_name == hbc_src_name):
                    msg = "MSHBD:config status is", hbc_state
                    _logger.info(msg)
                    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":
                        _logger.info(
                            "MSHBD:Reconfiguration is in progress, "
                            "Starting new processes by killing the present processes"
                        )
                        jsfile = fetch_json_file()
                        update_db = 1
                        create_update_db(update_db, jsfile, ip_address, port_num, user_name, password, db_name)
                        msg = "MSHBD: parameters  passed to DBM and HB are %d and %s", pid_current
                        _logger.info(msg)
                        job_list = create_process(job_list, jsfile, pid_current)
                        state = "RUNNING"
                        update_flg = 1
                        create_update_hb_common(
                            update_flg, pid_current, state, user_name, password, ip_address, port_num, db_name
                        )

                else:
                    _logger.info("MSHBD:Inactive Instance: Process IDs are different, Keep Looping")
                    if len(job_list) >= 2:
                        _logger.info("MSHBD:Inactive Instance: Main and DBM thread are waiting to become ACTIVE")
                    else:
                        jsfile = fetch_json_file()
                        msg = (
                            "MSHBD:Inactive Instance:Creating HB and DBM threads if not created already. "
                            "The param passed %d and %s",
                            jsfile,
                            pid_current,
                        )
                        _logger.info(msg)
                        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_src_name):
                    _logger.info("MSHBD:Initiating to become Active Instance")
                    if len(job_list) >= 2:
                        _logger.info("MSHBD:HB and DBM thread are waiting to become ACTIVE")
                    else:
                        jsfile = fetch_json_file()
                        msg = "MSHBD: Creating HB and DBM threads. The param pssed %d and %s", jsfile, pid_current
                        _logger.info(msg)
                        job_list = create_process(job_list, jsfile, pid_current)
                    hbc_pid, hbc_state, hbc_src_name, hbc_time = read_hb_common(
                        user_name, password, ip_address, port_num, db_name
                    )
                    update_flg = 1
                    create_update_hb_common(
                        update_flg, pid_current, hbc_state, user_name, password, ip_address, port_num, db_name
                    )
                else:
                    _logger.error("MSHBD:ERROR - Active instance is not updating hb_common in 60 sec - ERROR")
            time.sleep(25)
            if os.getenv("pytest", "") == "test":
                i = i + 1
                if i > 5:
                    _logger.info("Terminating main process for pytest")
                    cbs_polling_proc.terminate()
                    time.sleep(1)
                    cbs_polling_proc.join()
                    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:
                        job_list[0].terminate()
                        time.sleep(1)
                        job_list[0].join()
                        job_list.remove(job_list[0])
                    break

    except Exception as e:
        msg = "MSHBD:Exception as %s" % (str(traceback.format_exc()))
        _logger.error(msg)

        msg = "Fatal error. Could not start missing heartbeat service due to: {0}".format(e)
        _logger.error(msg)
    finally:
        # Stop health check server
        if hc_proc.pid is not None:
            hc_proc.terminate()
            hc_proc.join()
        # Stop CBS polling process
        if cbs_polling_proc.pid is not None:
            cbs_polling_proc.terminate()
            cbs_polling_proc.join()


if __name__ == "__main__":
    main()