56 lines
1.4 KiB
Python
56 lines
1.4 KiB
Python
#!/usr/bin/python3
|
|
|
|
import subprocess as sp
|
|
import json
|
|
import time, re
|
|
|
|
qmbin = "/usr/sbin/qm"
|
|
|
|
# Read DB from file
|
|
def read_json_from_file(filepath):
|
|
with open(filepath, 'r') as file:
|
|
data = json.load(file)
|
|
return data
|
|
|
|
# Alive check for host
|
|
def ping(ip):
|
|
status,result = sp.getstatusoutput("ping -c1 -w2 " + ip)
|
|
return status
|
|
|
|
def vmstat(id):
|
|
vm_status = "dnd"
|
|
status,result = sp.getstatusoutput(qmbin + " status " + str(id))
|
|
match = re.search(r"status: (.+)", result)
|
|
if match:
|
|
vm_status = match.group(1)
|
|
return vm_status
|
|
|
|
# timeout
|
|
shutdown_timeout = 5
|
|
|
|
# DB file
|
|
file_path = '/root/svs-watchdog.json'
|
|
|
|
# Read DB to mem
|
|
vms = read_json_from_file(file_path)
|
|
|
|
# Monitor VMs
|
|
for vm in vms:
|
|
ip = vm['ip']
|
|
down = vm['down']
|
|
|
|
if ping(ip) == 0:
|
|
vm['down'] = 0
|
|
else:
|
|
vm['down'] = down + 1
|
|
if vmstat(vm['id']) == 'runnnig' and vm['down'] >= shutdown_timeout:
|
|
status,result = sp.getstatusoutput(qmbin + " stop " + str(vm['id']) + " --overrule-shutdown 1")
|
|
else:
|
|
if vmstat(vm['id']) == 'stopped' and vm['down'] >= shutdown_timeout:
|
|
status,result = sp.getstatusoutput(qmbin + " start " + str(vm['id']))
|
|
vm['down'] = 0
|
|
|
|
# Update the status
|
|
with open(file_path, "w") as file:
|
|
json.dump(vms, file)
|