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