8014a2
From dd05dbe742384dd22f4a63889c56cb75e4e2f571 Mon Sep 17 00:00:00 2001
8014a2
From: Vit Mojzis <vmojzis@redhat.com>
8014a2
Date: Tue, 9 Nov 2021 18:04:39 +0100
8014a2
Subject: [PATCH] Make sure each section of the inspect exists before accessing
8014a2
8014a2
Fixes: https://github.com/containers/udica/issues/105,
8014a2
       https://github.com/containers/udica/issues/103
8014a2
8014a2
Inspired by:
8014a2
https://github.com/WellIDKRealy/udica/commit/0c56d98b8c58a8a4ceb89b04d700c834c13778fd
8014a2
8014a2
Signed-off-by: Vit Mojzis <vmojzis@redhat.com>
8014a2
---
8014a2
 udica/parse.py | 62 ++++++++++++++++++++++++++++++++++++++------------
8014a2
 1 file changed, 48 insertions(+), 14 deletions(-)
8014a2
8014a2
diff --git a/udica/parse.py b/udica/parse.py
8014a2
index 0797095..59b3dc5 100644
8014a2
--- a/udica/parse.py
8014a2
+++ b/udica/parse.py
8014a2
@@ -29,6 +29,24 @@ ENGINE_DOCKER = "docker"
8014a2
 ENGINE_ALL = [ENGINE_PODMAN, ENGINE_CRIO, ENGINE_DOCKER]
8014a2
 
8014a2
 
8014a2
+# Decorator for verifying that getting value from "data" won't
8014a2
+# result in Key error or Type error
8014a2
+# e.g. in data[0]["HostConfig"]["Devices"]
8014a2
+# missing "HostConfig" key in data[0] produces KeyError and
8014a2
+# data[0]["HostConfig"] == none produces TypeError
8014a2
+def getter_decorator(function):
8014a2
+    # Verify that each element in path exists and return the corresponding value,
8014a2
+    # otherwise return [] -- can be safely processed by iterators
8014a2
+    def wrapper(self, data, *args):
8014a2
+        try:
8014a2
+            value = function(self, data, *args)
8014a2
+            return value if value else []
8014a2
+        except (KeyError, TypeError):
8014a2
+            return []
8014a2
+
8014a2
+    return wrapper
8014a2
+
8014a2
+
8014a2
 def json_is_podman_or_docker_format(json_rep):
8014a2
     """Check if the inspected file is in a format from docker or podman.
8014a2
 
8014a2
@@ -91,19 +109,22 @@ class EngineHelper(abc.ABC):
8014a2
 
8014a2
     def get_caps(self, data, opts):
8014a2
         if opts["Caps"]:
8014a2
-            if opts["Caps"] == "None":
8014a2
+            if opts["Caps"] in ["None", "none"]:
8014a2
                 return []
8014a2
             return opts["Caps"].split(",")
8014a2
         return []
8014a2
 
8014a2
 
8014a2
 class PodmanDockerHelper(EngineHelper):
8014a2
+    @getter_decorator
8014a2
     def get_devices(self, data):
8014a2
         return data[0]["HostConfig"]["Devices"]
8014a2
 
8014a2
+    @getter_decorator
8014a2
     def get_mounts(self, data):
8014a2
         return data[0]["Mounts"]
8014a2
 
8014a2
+    @getter_decorator
8014a2
     def get_ports(self, data):
8014a2
         ports = []
8014a2
         for key, value in data[0]["NetworkSettings"]["Ports"].items():
8014a2
@@ -120,8 +141,13 @@ class PodmanHelper(PodmanDockerHelper):
8014a2
     def __init__(self):
8014a2
         super().__init__(ENGINE_PODMAN)
8014a2
 
8014a2
+    @getter_decorator
8014a2
     def get_caps(self, data, opts):
8014a2
-        if not opts["Caps"]:
8014a2
+        if opts["Caps"]:
8014a2
+            return (
8014a2
+                opts["Caps"].split(",") if opts["Caps"] not in ["None", "none"] else []
8014a2
+            )
8014a2
+        else:
8014a2
             return data[0]["EffectiveCaps"]
8014a2
         return []
8014a2
 
8014a2
@@ -138,18 +164,25 @@ class DockerHelper(PodmanDockerHelper):
8014a2
     def adjust_json_from_docker(self, json_rep):
8014a2
         """If the json comes from a docker call, we need to adjust it to make use
8014a2
         of it."""
8014a2
-
8014a2
-        if not isinstance(json_rep[0]["NetworkSettings"]["Ports"], dict):
8014a2
-            raise Exception(
8014a2
-                "Error parsing docker engine inspection JSON structure, try to specify container engine using '--container-engine' parameter"
8014a2
-            )
8014a2
-
8014a2
-        for item in json_rep[0]["Mounts"]:
8014a2
-            item["source"] = item["Source"]
8014a2
-            if item["Mode"] == "rw":
8014a2
-                item["options"] = "rw"
8014a2
-            if item["Mode"] == "ro":
8014a2
-                item["options"] = "ro"
8014a2
+        try:
8014a2
+            if not isinstance(json_rep[0]["NetworkSettings"]["Ports"], dict):
8014a2
+                raise Exception(
8014a2
+                    "Error parsing docker engine inspection JSON structure, try to specify container engine using '--container-engine' parameter"
8014a2
+                )
8014a2
+        except (KeyError, TypeError):
8014a2
+            # "Ports" not specified in given json file
8014a2
+            pass
8014a2
+
8014a2
+        try:
8014a2
+            for item in json_rep[0]["Mounts"]:
8014a2
+                item["source"] = item["Source"]
8014a2
+                if item["Mode"] == "rw":
8014a2
+                    item["options"] = "rw"
8014a2
+                if item["Mode"] == "ro":
8014a2
+                    item["options"] = "ro"
8014a2
+        except (KeyError, TypeError):
8014a2
+            # "Mounts" not specified in given json file
8014a2
+            pass
8014a2
 
8014a2
 
8014a2
 class CrioHelper(EngineHelper):
8014a2
@@ -161,6 +194,7 @@ class CrioHelper(EngineHelper):
8014a2
         # bind mounting device on the container
8014a2
         return []
8014a2
 
8014a2
+    @getter_decorator
8014a2
     def get_mounts(self, data):
8014a2
         return data["status"]["mounts"]
8014a2
 
8014a2
-- 
8014a2
2.30.2
8014a2