Skip to content

Commit a753ee3

Browse files
committed
fix(cli): align monitoring exit codes and about error handling
1 parent ab9fd90 commit a753ee3

3 files changed

Lines changed: 68 additions & 53 deletions

File tree

checkvsphere/cli.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,7 @@ def run():
6969
for cmd in sorted(cmds):
7070
print(f" {cmd}")
7171
print()
72+
sys.exit(3)
7273

7374

7475
def main():
@@ -106,19 +107,19 @@ def main():
106107
traceback.print_exc(file=sys.stdout)
107108
sys.exit(3)
108109
except ConnectionRefusedError:
109-
print("UNKNOWN - Connection refused")
110+
print("CRITICAL - Connection refused")
110111
raise SystemExit(2)
111112
except vim.fault.VimFault as e:
112113
if hasattr(e, 'msg'):
113-
print(f"ERROR - {e.msg}")
114+
print(f"UNKNOWN - {e.msg}")
114115
else:
115116
# in case there is no msg attribute
116117
# According to the docs there is
117118
# faultCause and faultMessage, but they are empty
118119
# but there is a msg attribute (which is not in the docs)
119120
# i don't know if it is set always
120121
# so fall back to the normal string representation
121-
print(f"ERROR - {e}")
122+
print(f"UNKNOWN - {e}")
122123
if int(os.environ.get("VSPHERE_DEBUG", "0")) > 0:
123124
traceback.print_exc(file=sys.stdout)
124125
raise SystemExit(3)

checkvsphere/tools/cli.py

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
import argparse
2020
import getpass
2121
import os
22+
import sys
2223

2324
__author__ = "VMware, Inc."
2425

@@ -36,6 +37,21 @@ def __call__(self, parser, namespace, values, option_string=None):
3637
setattr(namespace, self.dest, values)
3738

3839

40+
class MonitoringArgumentParser(argparse.ArgumentParser):
41+
def exit(self, status=0, message=None):
42+
if message:
43+
stream = sys.stderr if status else sys.stdout
44+
self._print_message(message, stream)
45+
46+
if status in (0, 2):
47+
status = 3
48+
raise SystemExit(status)
49+
50+
def error(self, message):
51+
self.print_usage(sys.stderr)
52+
self.exit(3, f"{self.prog}: error: {message}\n")
53+
54+
3955
class Parser:
4056
"""
4157
Samples specific argument parser.
@@ -56,7 +72,7 @@ def __init__(self):
5672
One for the standard arguments and one for sample specific arguments.
5773
The standard group cannot be extended.
5874
"""
59-
self._parser = argparse.ArgumentParser(description='Arguments for talking to vCenter')
75+
self._parser = MonitoringArgumentParser(description='Arguments for talking to vCenter')
6076
self._standard_args_group = self._parser.add_argument_group('standard arguments')
6177
self._specific_args_group = self._parser.add_argument_group('sample-specific arguments')
6278

@@ -99,7 +115,7 @@ def __init__(self):
99115
self._standard_args_group.add_argument('--sessionfile',
100116
required=False,
101117
action='store',
102-
help='Path to a file where the sessioncookie'
118+
help='Path to a file where the session cookie '
103119
'will be stored for later reuse. (EXPERIMENTAL)')
104120

105121
self._standard_args_group.add_argument('--match-method',

checkvsphere/vcmd/about.py

Lines changed: 46 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -25,59 +25,57 @@
2525
import logging
2626
import os
2727
from monplugin import Status
28-
from pyVmomi import vim
2928
from ..tools import cli, service_instance
3029

3130

3231
def run():
33-
try:
34-
parser = cli.Parser()
35-
parser.add_optional_arguments({
36-
'name_or_flags': ['--skip-permission'],
37-
'options': {
38-
'action': 'store_true',
39-
'default': False,
40-
'help': 'skips the System.View permission check',
41-
}
42-
})
32+
parser = cli.Parser()
33+
parser.add_optional_arguments({
34+
'name_or_flags': ['--skip-permission'],
35+
'options': {
36+
'action': 'store_true',
37+
'default': False,
38+
'help': 'skips the System.View permission check',
39+
}
40+
})
4341

44-
args = parser.get_args()
45-
si = service_instance.connect(args)
46-
about = si.content.about
47-
status = Status.OK
48-
clock = True
49-
if not args.skip_permission:
50-
try:
51-
clock = si.serverClock
52-
except Exception:
53-
logging.debug("no server clock", exc_info=1)
54-
status = Status.CRITICAL
55-
clock = None
56-
if args.sessionfile:
57-
try:
58-
logging.debug(f"deleting {args.sessionfile}")
59-
os.unlink(args.sessionfile)
60-
except Exception:
61-
logging.debug(f"unlink {args.sessionfile} failed", exc_info=1)
42+
args = parser.get_args()
43+
si = service_instance.connect(args)
44+
about = si.content.about
45+
status = Status.OK
46+
clock = True
47+
if not args.skip_permission:
48+
try:
49+
clock = si.serverClock
50+
except Exception:
51+
logging.debug("no server clock", exc_info=1)
52+
status = Status.CRITICAL
53+
clock = None
54+
if args.sessionfile:
55+
try:
56+
logging.debug(f"deleting {args.sessionfile}")
57+
os.unlink(args.sessionfile)
58+
except Exception:
59+
logging.debug(f"unlink {args.sessionfile} failed", exc_info=1)
6260

63-
out = (
64-
f'{status.name}: '
65-
f'{ "No System.View permission, " if not clock else "" }'
66-
f'{ about.fullName }, '
67-
f'api: { about.apiType }/{ about.apiVersion }, '
68-
f'product: { about.licenseProductName } { about.licenseProductVersion }'
69-
)
70-
print(out)
71-
raise SystemExit(status.value)
72-
except vim.fault.VimFault as e:
73-
if hasattr(e, 'msg'):
74-
print(f"ERROR: {e.msg}")
75-
else:
76-
print(f"ERROR: {e}")
77-
raise SystemExit(2)
78-
except Exception as e:
79-
print(f"ERROR: {e}")
80-
raise SystemExit(2)
61+
out = (
62+
f'{status.name}: '
63+
f'{ "No System.View permission, " if not clock else "" }'
64+
f'{ about.fullName }, '
65+
f'api: { about.apiType }/{ about.apiVersion }, '
66+
f'product: { about.licenseProductName } { about.licenseProductVersion }'
67+
)
68+
print(out)
69+
raise SystemExit(status.value)
8170

8271
if __name__ == "__main__":
83-
run()
72+
try:
73+
run()
74+
except SystemExit as e:
75+
if not isinstance(e.code, int) or e.code > 3 or e.code < 0:
76+
print("UNKNOWN EXIT CODE")
77+
raise SystemExit(Status.UNKNOWN)
78+
raise
79+
except Exception as e:
80+
print("UNKNOWN - " + str(e))
81+
raise SystemExit(Status.UNKNOWN)

0 commit comments

Comments
 (0)