简体   繁体   中英

Using sys.exit in for loops

I am writing a small python script that iterates through a large json output and grabs the information I need and puts it into small dictionaries. It then iterates through the dictionaries to look for an key called restartcount . If the count is more than more than 3 but less than 5 it prints warning . If greater than 5 it prints critical . However this script is set to be a nagios plugin which requires exit codes to be placed with warning sys.exit(1) , and sys.exit(2) for critical. If you look at my script I use my function to grab the info I need into a small dictionary, then run a for loop. If I place a sys.exit after inside any if statement I iterate only through the first dictionary and the rest are not checked. Any help will be appreciated as to how to incorporate the exit codes without losing skipping or missing any information.

Code:

import urllib2
import json
import argparse
from sys import exit

def get_content(pod):
    kube = {}
    kube['name'] = pod["metadata"]["name"]
    kube['phase'] = pod["status"]["phase"]
    kube['restartcount'] = pod["status"]["containerStatuses"][0]["restartCount"]
    return kube

if __name__ == '__main__':
    parser = argparse.ArgumentParser( description='Monitor Kubernetes Pods' )
    parser.add_argument('-w', '--warning', type=int, help='levels we should look into',default=3)
    parser.add_argument('-c', '--critical', type=int, help='its gonna explode',default=5)
    parser.add_argument('-p', '--port', type=int, help='port to access api server',default=8080)
    args = parser.parse_args()

try:
    api_call = "http://localhost:{}/api/v1/namespaces/default/pods/".format(args.port)
    req = urllib2.urlopen(api_call).read()
    content = json.loads(req)
except urllib2.URLError:
    print 'URL Error. Please re-check the API call'
    exit(2)


for pods in content.get("items"):
    try:
        block = get_content(pods)
        print block
    except KeyError:
        print 'Container Failed'
        exit(2)

    if block["restartcount"] >= args.warning and block["restartcount"] < args.critical:
        print "WARNING | {} restart count  is {}".format(block["name"], block["restartcount"])

    if block["restartcount"] >= args.critical:
        print "CRITICAL | {} restart count  is {}".format(block["name"], block["restartcount"])

what the block variable looks like:

{'phase': u'Running', 'restartcount': 0, 'name': u'pixels-1.0.9-k1v5u'}

Create a variable called something like exit_status . Initialize it to 0, and set it as needed in your code (eg where you are currently calling exit ). At the end of program execution, call sys.exit(exit_status) (and no where else).

Rewriting the last section of your code:

exit_status = 0
for pods in content.get("items"):
    try:
        block = get_content(pods)
        print block
    except KeyError:
        print 'Container Failed'
        exit(2)

    if block["restartcount"] >= args.warning and block["restartcount"] < args.critical:
        print "WARNING | {} restart count  is {}".format(block["name"], block["restartcount"])
        if exit_status < 1: exit_status = 1

    if block["restartcount"] >= args.critical:
        print "CRITICAL | {} restart count  is {}".format(block["name"], block["restartcount"])
        exit_status = 2

sys.exit(exit_status)

可变方法是正确的问题是,当您进一步检查时,可能已经将其设置为2时将其设置为1,所以我建议在此处添加一个条件,如果它已经为2,则不要将其设置为1。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM