Monday, 25 April 2022

How to check the server status in ubuntu?

step: how to run it in a crontab?

10 * * * * /bin/bash /home/ninja/Documents/checkVAserverStatus.sh


code:-

---

import configparser
import socket
import json
import psutil
import subprocess
config = configparser.ConfigParser()
config.read("config.ini")
symServer = config['symphony']

data = {
"camera_name":"none",
"event_time":"none",
"event_type":"none",
"image_url":"none",
"video_url":"none",
"camera_id": symServer["camera_id"]
}

def check():
    ram_used = check_ram()
    hddfree_space = check_directory_size("/")
    gpuRun = check_vadocker()

    if not gpuRun:
        data['policy_id'] = symServer["gpu_policy_id"]
        status = sendEvent(data)

    if ram_used > 95:
        data['policy_id'] = symServer["ram_policy_id"]
        status = sendEvent(data)

    if hddfree_space < 10:
        data['policy_id'] = symServer["hddfull_policy_id"]
        status = sendEvent(data)

def check_ram():
    ram_used = psutil.virtual_memory().percent
    return ram_used

def check_directory_size(path):
    hdd = psutil.disk_usage(path)
    free_space = hdd.free / (2**30)
    return free_space

def check_vadocker():
    subprocess1 = subprocess.Popen('docker ps -a -q --filter ancestor=nvcr.io/nvidia/deepstream:6.0-triton --format="{{.ID}}"',shell=True,stdout=subprocess.PIPE)
    subprocess_return = subprocess1.stdout.read()
    if len(subprocess_return)>5:
        print("docker is running")
        return True
    else:
        print("docker is not running")
        return False

def sendEvent(data):
    try:
        strdata = json.dumps(data)
        print(data)

        # Send data
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server_address = (symServer["server_ip"], int(symServer["server_port"]))
        sock.connect(server_address)

        try:
            # Send data
            sock.sendall(strdata.encode())

            # Look for the response
            amount_received = 0
            amount_expected = 5
            while amount_received < amount_expected:
                data = sock.recv(100)
                amount_received += len(data)
            # print('alerting send')
            return True
        except Exception as e:
            # print("server_ip: ",e)
            return False
        finally:
            # print('-- closing socket')
            sock.close()
            return True
    except Exception as e:
        # print("server_ip: ",e)
        return False

if __name__=="__main__":
    check()

No comments:

Post a Comment