Commit 71ba4e3d authored by kesnar's avatar kesnar
Browse files

feat: add python scripts for kpi collection

parent f66fe9e8
Loading
Loading
Loading
Loading
+18 −15
Original line number Diff line number Diff line
@@ -44,17 +44,20 @@ monitoring_client = MonitoringClient(get_setting('MONITORINGSERVICE_SERVICE_HOST
context_client = ContextClient(get_setting('CONTEXTSERVICE_SERVICE_HOST'), get_setting('CONTEXTSERVICE_SERVICE_PORT_GRPC'))

### Locks and common variables
ping_trigger = threading.Lock()
kpi_id_trigger = threading.Lock()
enabled_lock = threading.Lock()
kpi_id_lock = threading.Lock()
kpi_id = KpiId()
should_ping = True
enabled = False

### Define the path to the Unix socket
socket_path = "./tmp/sock"
socket_path = "/home/nuc8/tfs-develop/ngsdn-tutorial/tmp/sock"
#socket_path = "./tmp/sock"
if os.path.exists(socket_path):
    os.remove(socket_path)

def thread_context_func():
    global kpi_id
    global enabled
    while True:
        # Listen to ContextService/GetServiceEvents stream 
        events = context_client.GetServiceEvents(Empty())
@@ -69,24 +72,25 @@ def thread_context_func():
                        kpi_id_list = [],
                        device_id = None,
                        endpoint_id = None,
                        kpi_description = f"Latency value for service {event_service_uuid}",
                        kpi_description = f"Loss Ratio for service {event_service_uuid}",
                        service_id = event_service,
                        kpi_sample_type = KpiSampleType.KPISAMPLETYPE_UNKNOWN
                        )
                response = monitoring_client.SetKpi(kpi_descriptor)
                print(response)
                with kpi_id_trigger:
                    global kpi_id
                with kpi_id_lock:
                    kpi_id = response
                    print(kpi_id)
                with ping_trigger:
                    should_ping = True
                with enabled_lock:
                    enabled = True
            elif event_type == 3:
                print(f"stream: New REMOVE event:\n{event_service}")
                with ping_trigger:
                    should_ping = False
                with enabled_lock:
                    enabled = False

def thread_kpi_func():
    global kpi_id
    global enabled
    try:
        # Create socket object
        server_socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
@@ -107,12 +111,11 @@ def thread_kpi_func():
            data = connection.recv(1024)

            if data:
                with ping_trigger:
                    if should_ping: 
                with enabled_lock:
                    if enabled: 
                        data = data.decode()
                        print(f"Received: {data}")
                        with kpi_id_trigger:
                            global kpi_id
                        with kpi_id_lock:
                            
                            now = time.time()

+26 −25
Original line number Diff line number Diff line
import socket
import re
import time
import subprocess
import socket, re, time, subprocess, sys

socket_path = "./tmp/sock"
socket_path = "/tmp/sock"
#socket_path = "./tmp/sock"

def get_kpi_value():
    hostname = "8.8.8.8"
def main():
    hostname = sys.argv[1]
    count = 1
    wait = 5

    total_pings = 0
    successful_pings = 0
    try:
        while True:
            start_time = time.time()

            try:
                # Run the ping command and capture the output
                result = subprocess.check_output(["ping", "-W", str(wait), "-c", str(count), hostname], universal_newlines=True)

                response_time = float(re.findall(r"time=([0-9.]+) ms", result)[0])
        successful_pings += 1

            except subprocess.CalledProcessError as e:
                # If ping fails return negative response_time
                response_time = -1

            # Calculate new loss_ratio
            if response_time != -1:
                successful_pings += 1
            total_pings += 1
    moving_loss_ratio = round(((total_pings - successful_pings) / total_pings * 100), 2)
            moving_loss_ratio = round(((total_pings - successful_pings) / float(total_pings) * 100), 2)

            print("Total pings: {}".format(total_pings))
            print("Successful pings: {}".format(successful_pings))

            print("Packet loss: {}%".format(moving_loss_ratio))
            print("Latency: {} ms".format(response_time))
    return response_time

def main():
    try:
        while True:
            start_time = time.time()

            # Ping and capture latency and packet loss
            data = str(get_kpi_value())
            data = str(moving_loss_ratio)

            # Write results in socket
            try:
@@ -46,7 +47,7 @@ def main():
            except Exception as e:
                print(e)

            # Calculate the time taken by get_kpi_value()
            # Calculate the time taken by ping
            execution_time = time.time() - start_time
            # Wait the rest of the time
            wait_time = max(0, 6 - execution_time)