import subprocess import requests import argparse
class resource: file_system = '' disk_size = 0.0 used = 0.0 avail = 0.0 use_percent = 0.0 mounted_on = 0.0 disk_free_threshold = 1 mount_partition = "/"
class resourcesmonitor(resource): def __init__(self): self.__file_system = resource.file_system self.__disk_size = resource.disk_size self.__used = resource.used self.__avail = resource.avail self.__use_percent = resource.use_percent self.__mounted_on = resource.mounted_on self.__disk_free_threshold = resource.disk_free_threshold self.__mount_partition = resource.mount_partition
def show_resource_usage(self): """ print the resource usage of disk. """ print("file_system", "disk_size", "used", "avail", "use_percent", "mounted_on") print(self.__file_system, self.__disk_size, self.__used, self.__avail, self.__use_percent, self.__mounted_on)
def check_resource_usage(self): """ check the disk usage by running the unix 'df -h' command. """ response_df = subprocess.popen(["df", "-h"], stdout=subprocess.pipe) for line in response_df.stdout: split_line = line.decode().split() if split_line[5] == self.__mount_partition: if int(split_line[4][:-1]) > self.__disk_free_threshold: self.__file_system, self.__disk_size, self.__used = split_line[0], split_line[1], split_line[2] self.__avail, self.__use_percent, self.__mounted_on = split_line[3], split_line[4], split_line[5] self.show_resource_usage() self.update_resource_usage_api(self)
def update_resource_usage_api(self, resource): """ call the update api using all resource details. """ update_resource_url = url.format( resource.__file_system, resource.__disk_size, resource.__used, resource.__avail, resource.__use_percent, resource_id )
print(update_resource_url) payload = {} files = {} headers = { 'token': 'bearer apitoken' } try: response = requests.request("get", update_resource_url, headers=headers, data=payload, files=files) if response.ok: print(response.json()) except exception as ex: print("error while calling update api") print(ex)
if __name__ == '__main__': url = "http://yourapi.com/update_server_health_by_server_id?path={}&size={}" \ "&used={}&avail={}&use_percent={}&id={}" parser = argparse.argumentparser(description='disk resource monitor') parser.add_argument('-id', metavar='id', help='id record of server', default=7, type=int) args = parser.parse_args() resource_id = args.id print(resource_id) resource_monitor = resourcesmonitor() resource_monitor.check_resource_usage()
|