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