Skip to contentSkip to conversation

routel: handle errors from ip command

PATCH New Stephen Hemminger 1 participant 1 message May 17

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

PATCH 1/1 routel: handle errors from ip command

When ip exits non-zero, routel crashed with a JSONDecodeError traceback on top of ip's own diagnostic. Use subprocess.run with check=True, propagate ip's exit status, handle a missing ip binary, and wrap the JSON parse so malformed output gives a clean message.

While here, send diagnostics to stderr and drop the assert-as-control- flow (stripped under python -O).

Fixes 6d676ad93408 ("ip: rewrite routel in python")
---
 ip/routel | 28 ++++++++++++++++++++++------
 1 file changed, 22 insertions(+), 6 deletions(-)
ip/routel +22 -6
index 09a90126..51b02d21 100755
@@ -13,7 +13,8 @@ import subprocess
 
 def usage():
     '''Print usage and exit'''
-    print("Usage: {} [tablenr [raw ip args...]]".format(sys.argv[0]))
+    print("Usage: {} [tablenr [raw ip args...]]".format(sys.argv[0]),
+          file=sys.stderr)
     sys.exit(64)
 
 
@@ -23,7 +24,7 @@ def main():
     try:
         opts, args = getopt.getopt(sys.argv[1:], "h46f:", ["help", "family="])
     except getopt.GetoptError as err:
-        print(err)
+        print(err, file=sys.stderr)
         usage()
 
     for opt, arg in opts:
@@ -36,14 +37,29 @@ def main():
         elif opt in ["-f", "--family"]:
             family = arg
         else:
-            assert False, "unhandled option"
+            raise RuntimeError("unhandled option " + opt)
 
     if not args:
         args = ['0']
 
     cmd = ['ip', '-f', family, '-j', 'route', 'list', 'table'] + args
-    process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
-    tbl = json.load(process.stdout)
+    try:
+        result = subprocess.run(cmd, stdout=subprocess.PIPE, check=True)
+    except FileNotFoundError:
+        print("{}: ip: command not found".format(sys.argv[0]),
+              file=sys.stderr)
+        sys.exit(1)
+    except subprocess.CalledProcessError as err:
+        # ip has already written its own diagnostic to stderr
+        sys.exit(err.returncode)
+
+    try:
+        tbl = json.loads(result.stdout)
+    except json.JSONDecodeError as err:
+        print("{}: cannot parse ip output: {}".format(sys.argv[0], err),
+              file=sys.stderr)
+        sys.exit(1)
+
     if family == 'inet':
         fmt = '{:15} {:15} {:15} {:8} {:8}{:<16} {}'
     else:
@@ -54,7 +70,7 @@ def main():
     print(fmt.format(*map(lambda x: x.capitalize(), keys)))
 
     for record in tbl:
-        fields = [record[k] if k in record else '' for k in keys]
+        fields = [record.get(k, '') for k in keys]
         print(fmt.format(*fields))
 
 
Signature · 1 line
2.53.0