Ejemplo n.º 1
0
def check_memory(c):

    '''Collect memory percent, used, free, available'''
      
    # svmem(total=2749374464, available=1501151232, percent=45.4, used=979968000, 
    # free=736043008, active=1145720832, inactive=590102528, buffers=107663360, 
    # cached=925700096, shared=86171648)
    
    memory = psutil.virtual_memory()
    
    m1  = CheckItem('memory_percent',memory.percent,"Memory used (percent)", unit = '%')
    c.add_item(m1)

    m2  = CheckItem('memory_used',memory.used,"Memory used (bytes)", unit='bytes')
    h_used = m2.human()
    c.add_item(m2)

    m3  = CheckItem('memory_available',memory.available,"Memory available (bytes)", unit='bytes')
    h_avail = m3.human()
    c.add_item(m3)

    m4  = CheckItem('memory_total',memory.total,"Memory total (bytes)", unit='bytes')
    h_total = m4.human()
    c.add_item(m4)


    c.add_message("used {} % - used {} - avail {} - total {}".format(memory.percent, h_used, h_avail, h_total) )

    return c
Ejemplo n.º 2
0
def check_url(c):

    '''Get a URL and check response code and pattern in the response body.'''

    # OUTPUT:
    # cmt_url
    # cmt_url_name
    # cmt_url_msec

    name         = c.name
    url          = c.conf['url']
    pattern      = c.conf.get('pattern',"")
    my_redirects = c.conf.get("allow_redirects",False) == True
    my_sslverify = c.conf.get("ssl_verify",False) == True
    my_host      = c.conf.get("host","")

    ci = CheckItem('url_name',name,'')
    c.add_item(ci)

    ci = CheckItem('url',url,'')
    c.add_item(ci)


    start_time = time.time()

    headers = {}
    if my_host != "":
        headers['Host'] = my_host

    try:
        resp = requests.get(url, headers = headers, timeout=5, verify=my_sslverify, allow_redirects = my_redirects)
    except:
        c.alert += 1
        c.add_message("{} - {} [Host: {}] - no response to query".format(name,url, my_host))
        return c

    elapsed_time = int ( 1000 * (time.time() - start_time) )
    ci = CheckItem('url_msec',elapsed_time,unit='ms')
    c.add_item(ci) 

    if resp.status_code != 200:
        c.alert += 1
        c.add_message("{} - {} [Host: {}]- bad http code response ({})".format(name,url, my_host, resp.status_code))
        return c

    # check pattern
    mysearch = re.search(pattern,resp.text)
    if not mysearch:
        c.alert += 1
        c.add_message("expected pattern not found for {} ({} [Host: {}])".format(name, url, my_sslverify))
        return c

    c.add_message("{} - {} [Host: {}] - http={} - {} ms ; pattern OK".format(name, url, my_host, resp.status_code, elapsed_time))
    return c
Ejemplo n.º 3
0
def check_mount(c):
    '''Checks mount points
       OUTPUT
         - cmt_mount
    '''

    partitions = psutil.disk_partitions(all=False)

    if cmt.ARGS["available"]:
        print("-" * 25)
        print("Available mountpoints :")
        print("-" * 25)
        for p in partitions:
            print(p)
        print("-" * 25)
        return c

    #sdiskpart(device='/dev/sda1', mountpoint='/', fstype='ext4',
    #               opts='rw,relatime,errors=remount-ro,data=ordered')

    path = c.conf['path']

    ci = CheckItem('mount', path)
    c.add_item(ci)

    for part in partitions:
        if part.mountpoint == path:
            c.add_message("path {} found".format(path))
            return c

    c.alert += 1
    c.add_message("path {} not found".format(path))

    return c
Ejemplo n.º 4
0
def check_ping(c):
    '''Ping a remote host and return availability
       Output:
          - cmt_ping
    '''

    host = c.conf['host']

    ci = CheckItem('ping', host)
    c.add_item(ci)

    #response = os.system("ping -c 1 -W 2 " + host + "> /dev/null 2>&1")
    proc = subprocess.Popen(
        ["ping", "-c", "1", "-W"
         "2", host],
        stdout=subprocess.DEVNULL,
        stderr=subprocess.DEVNULL,
    )  # starts the process
    proc.wait()  # waits for it to finish (there's a timeout option)
    response = proc.returncode

    if response == 0:
        c.add_message("{} ok".format(host))
    else:
        c.alert += 1
        c.add_message("{} not responding".format(host))

    return c
Ejemplo n.º 5
0
def check_cpu(c):
    '''Get CPU percentage. No alert. Send cpu float value.'''

    cpu = psutil.cpu_percent(interval=2)

    # c.persist['cpu'] = cpu

    i = CheckItem('cpu', cpu, "CPU Percentage", unit='%')
    c.add_item(i)

    c.add_message("usage : {} %".format(cpu))
    return c
Ejemplo n.º 6
0
def check_boottime(c):

    #c = Check(module='boottime')
    boottime = int(time.time() - psutil.boot_time())
    days = int(boottime / 86400)

    m1 = CheckItem('boottime_seconds',
                   boottime,
                   "Seconds since last reboot",
                   unit='seconds')
    h_sec = m1.human()
    c.add_item(m1)

    m2 = CheckItem('boottime_days',
                   days,
                   'Days since last reboot',
                   unit='days')
    c.add_item(m2)

    c.add_message("days since last reboot : {} days - {} sec.".format(
        days, h_sec))
    return c
Ejemplo n.º 7
0
def check_load(c):
    

    # (1.17, 0.86, 0.52)
    load = os.getloadavg()

    l1  = CheckItem('load1',load[0])
    l1.description ='CPU Load Average, one minute'
    c.add_item(l1)

    l5  = CheckItem('load5',load[1])
    l5.description='CPU Load Average, 5 minutes'
    c.add_item(l5)

    l15 = CheckItem('load15',load[2])
    l15.description='CPU Load Average, 15 minutes'
    c.add_item(l15)
    
    c.add_message("1/5/15 min : {}  {}  {}".format(load[0], load[1], load[2]))
    return c
Ejemplo n.º 8
0
def check_swap(c):

    # sswap(total=2147479552, used=0, free=2147479552, percent=0.0, sin=0, sout=0)
    swap = psutil.swap_memory()

    m1 = CheckItem('swap_percent',swap.percent,"Swap used (percent)", unit = '%')
    c.add_item(m1)

    m2 = CheckItem('swap_used',swap.used,'Swap used (bytes)', unit = 'bytes')
    h_used = m2.human()
    c.add_item(m2)

    m3 = CheckItem('swap_total',swap.total,'Swap total (bytes)', unit = 'bytes')
    h_total = m3.human()
    c.add_item(m3)


    c.add_message("used: {} % /  {} - total {}".format(swap.percent, h_used, h_total))
    return c
Ejemplo n.º 9
0
def check_process(c):

    # --available option ?
    if cmt.ARGS["available"]:
        print("-" * 25)
        print("Process available :")
        print("-" * 25)
        for p in psutil.process_iter():
            try:
                # Get process name & pid from process object.
                print(p.name())
                #print(processName , ' ::: ', processID)
            except (psutil.NoSuchProcess, psutil.AccessDenied,
                    psutil.ZombieProcess):
                pass
        print("-" * 25)
        return c

    # real check

    name = c.name
    psname = c.conf['psname']

    #{'name': 'python3', 'cpu_times': pcputimes(user=0.39, system=0.3,
    #    children_user=0.0, children_system=0.0),
    #    'memory_info': pmem(rss=27049984, vms=123904000, shared=13443072, text=3883008,
    #    lib=0, data=13901824, dirty=0), 'username': '******', 'pid': 3125}
    #for proc in psutil.process_iter(['pid', 'name', 'username','cpu_times','memory_info']):
    #     #print(proc.info)

    ci = CheckItem('process_name', name, "")
    c.add_item(ci)

    for proc in psutil.process_iter():

        try:
            # Get process name & pid from process object.
            processName = proc.name()
            processID = proc.pid
            #print(processName , ' ::: ', processID)
        except (psutil.NoSuchProcess, psutil.AccessDenied,
                psutil.ZombieProcess):
            pass

        # pinfo = proc.as_dict(attrs=['name','pid','memory_info','cpu_times'])
        if processName == psname:

            mem = proc.memory_info().rss
            ci = CheckItem('process_memory', mem, "rss", unit="bytes")
            h_mem = ci.human()
            c.add_item(ci)

            cpu = proc.cpu_times().user
            ci = CheckItem('process_cpu',
                           cpu,
                           "cpu time, user",
                           unit='seconds')
            c.add_item(ci)

            c.add_message("{} found ({}) - memory rss {} - cpu {} sec.".format(
                name, psname, h_mem, cpu))
            return c

    c.alert += 1
    c.add_message("{} missing ({})".format(name, psname))

    return c
Ejemplo n.º 10
0
def check_folder(c):

    '''Check for various folder attributes '''

    global s_dirs

    path = c.conf['path']

    name = path
    if 'name' in c.conf:
        name = c.conf['name']

    recursive = c.conf.get("recursive",False) == True

    targets = []
    if 'target' in c.conf:
        targets = c.conf['target']

    ci = CheckItem('folder_path',path)
    c.add_item(ci)
    ci = CheckItem('folder_name',name)
    c.add_item(ci)

    if not os.path.exists(path):      
        c.alert += 1
        c.add_message("{} missing".format(path))       
        return c

    # scan
    # ----
    s_count = 0
    s_size = 0
    s_minage = -1
    s_maxage = 0
    s_files = []
    
    #for entry in os.scandir(path):
    if recursive:
        for entry in scanRecurse(path):
                s_files.append(entry.name)
                s_count += 1
                statinfo = os.stat(entry.path)
                s_size += statinfo.st_size
                if statinfo.st_mtime > s_maxage:
                    s_maxage = statinfo.st_mtime
                if statinfo.st_mtime < s_minage or s_minage == -1 :
                    s_minage = statinfo.st_mtime
    else:
        for entry in scanNoRecurse(path):
                s_files.append(entry.name)
                s_count += 1
                statinfo = os.stat(entry.path)
                s_size += statinfo.st_size
                if statinfo.st_mtime > s_maxage:
                    s_maxage = statinfo.st_mtime
                if statinfo.st_mtime < s_minage or s_minage == -1 :
                    s_minage = statinfo.st_mtime


    # file count
    ci = CheckItem('folder_files', s_count, "Number of files in folder " + name, unit="files")
    c.add_item(ci)

    # dirs count
    ci = CheckItem('folder_dirs',s_dirs,"Number of dirs/subdirs in folder " + name, unit="dirs")
    c.add_item(ci)

    # size
    ci = CheckItem('folder_size',s_size,"Total Size (bytes)", unit="bytes")
    c.add_item(ci)

    # age
    now = time.time()
    if s_maxage > 0:
        ci = CheckItem('folder_age_min',"","Min age (seconds)", unit="sec")
        ci.value = int(now - s_maxage)
        c.add_item(ci)
    if s_minage != -1:
        ci = CheckItem('folder_age_max',"","Max age (seconds)", unit="sec")
        ci.value = int(now - s_minage)
        c.add_item(ci)


    # Target checks
    # --------------
    tgcount = 0

    # target : files_min: 4
    if 'files_min' in targets:
        tgcount += 1
        if s_count < targets['files_min']:
            c.alert += 1
            c.add_message ("{} :  too few files ({})".format(path,s_count))
            return c

    # target : files_max: 23
    if 'files_max' in targets:
        tgcount += 1
        if s_count > targets['files_max']:
            c.alert += 1
            c.add_message ("{} : too many files ({})".format(path,s_count))
            return c

    # target : size_max (folder max bytes)
    if 'size_max' in targets:
        tgcount += 1
        if s_size > targets['size_max']:
            c.alert += 1
            c.add_message("{} : too big ({})".format(path,s_size))
            return c            

    # target : size_min (folder min bytes)
    if 'size_min' in targets:
        tgcount += 1
        if s_size < targets['size_min']:
            c.alert += 1
            c.add_message("{} : too small ({})".format(path,s_size))
            return c            

    # target : age_max: 
    if 'age_max' in targets:
        tgcount += 1
        if s_minage != -1:
            if int(now - s_minage) > targets ['age_max']:
                c.alert += 1
                c.add_message("{} : some files too old ({} sec)".format(path,int(now - s_minage)))
                return c                

    # target : age_min: 
    if 'age_min' in targets:
        tgcount += 1
        if s_maxage != 0:
            if int(now - s_maxage) < targets ['age_min']:
                c.alert += 1
                c.add_message("{} : some files too young ({} sec)".format(path,int(now - s_maxage)))
                return c   

    # target : has_file: filename
    if 'has_files' in targets:
        tgcount += 1
        flist = targets['has_files']
        for f in flist:
            if f not in s_files:
                c.alert += 1
                c.add_message("{} : expected file not found ({})".format(path,f))
                return c

    c.add_message("{} ({}) ok - {} files, {} dirs, {} bytes - {} targets OK".format(name, path, s_count, s_dirs, s_size, tgcount))
    return c
Ejemplo n.º 11
0
def check_disk(c):

    #c = Check(module='disk') 
    path = c.conf['path']
    alert_threshold = int(c.conf['alert'])

    # sdiskusage(total=21378641920, used=4809781248, free=15482871808, percent=22.5)
    disk=psutil.disk_usage(path)

    ci = CheckItem('disk',path,"Path")
    c.add_item(ci)

    ci = CheckItem('disk_total',disk[0],"Total (Bytes)", unit='bytes')
    h_total = ci.human()
    c.add_item(ci)

    ci = CheckItem('disk_used',disk[1],"Used (Bytes)", unit='bytes')
    h_used = ci.human()
    c.add_item(ci)

    ci = CheckItem('disk_free',disk[2],"Free (Bytes)", unit='bytes')
    h_free = ci.human()
    c.add_item(ci)

    ci = CheckItem('disk_percent',disk[3],"Used (percent)", unit='%')
    if disk[3] > alert_threshold:
        c.alert += 1
        c.add_message("path : {} - critical capacity ({} %)".format(path,disk[3]))

    else:
        c.add_message("path : {} - used: {} % - used: {} - free: {} - total: {} ".format(path, disk[3],h_used, h_free,h_total))
    
    c.add_item(ci)

    return c