Debian Codegraph @

ansible_collections/kubernetes/core/plugins/module_utils/k8s/resource.py

raw symbols SCIP
1 # Copyright: (c) 2021, Red Hat | Ansible
2 # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
3
4 import os
5 from typing import Dict, Iterable, List, Optional, Union, cast
6
7 from ansible.module_utils.urls import Request
8
9 try:
10 import yaml
11 except ImportError:
12 # Handled in module setup
13 pass
14
15
16 class ResourceDefinition(dict):
17 """Representation of a resource definition.
18
19 This is a thin wrapper around a dictionary representation of a resource
20 definition, with a few properties defined for conveniently accessing the
21 commonly used fields.
22 """
23
24 @property
25 def kind(self) -> Optional[str]:
26 return self.get("kind")
27
28 @property
29 def api_version(self) -> Optional[str]:
30 return self.get("apiVersion")
31
32 @property
33 def namespace(self) -> Optional[str]:
34 metadata = self.get("metadata", {})
35 return metadata.get("namespace")
36
37 @property
38 def name(self) -> Optional[str]:
39 metadata = self.get("metadata", {})
40 return metadata.get("name")
41
42
43 def create_definitions(params: Dict) -> List[ResourceDefinition]:
44 """Create a list of ResourceDefinitions from module inputs.
45
46 This will take the module's inputs and return a list of ResourceDefintion
47 objects. The resource definitions returned by this function should be as
48 complete a definition as we can create based on the input. Any *List kinds
49 will be removed and replaced by the resources contained in it.
50 """
51 if params.get("resource_definition"):
52 d = cast(Union[str, List, Dict], params.get("resource_definition"))
53 definitions = from_yaml(d)
54 elif params.get("src"):
55 d = cast(str, params.get("src"))
56 if hasattr(d, "startswith") and d.startswith(("https://", "http://", "ftp://")):
57 data = Request().open("GET", d).read().decode("utf8")
58 definitions = from_yaml(data)
59 else:
60 definitions = from_file(d)
61 else:
62 # We'll create an empty definition and let merge_params set values
63 # from the module parameters.
64 definitions = [{}]
65
66 resource_definitions: List[Dict] = []
67 for definition in definitions:
68 merge_params(definition, params)
69 kind = cast(Optional[str], definition.get("kind"))
70 if kind and kind.endswith("List"):
71 resource_definitions += flatten_list_kind(definition, params)
72 else:
73 resource_definitions.append(definition)
74 return list(map(ResourceDefinition, resource_definitions))
75
76
77 def from_yaml(definition: Union[str, List, Dict]) -> Iterable[Dict]:
78 """Load resource definitions from a yaml definition."""
79 definitions: List[Dict] = []
80 if isinstance(definition, str):
81 definitions += yaml.safe_load_all(definition)
82 elif isinstance(definition, list):
83 for item in definition:
84 if isinstance(item, str):
85 definitions += yaml.safe_load_all(item)
86 else:
87 definitions.append(item)
88 else:
89 definition = cast(Dict, definition)
90 definitions.append(definition)
91 return filter(None, definitions)
92
93
94 def from_file(filepath: str) -> Iterable[Dict]:
95 """Load resource definitions from a path to a yaml file."""
96 path = os.path.normpath(filepath)
97 with open(path, "rb") as f:
98 definitions = list(yaml.safe_load_all(f))
99 return filter(None, definitions)
100
101
102 def merge_params(definition: Dict, params: Dict) -> Dict:
103 """Merge module parameters with the resource definition.
104
105 Fields in the resource definition take precedence over module parameters.
106 """
107 definition.setdefault("kind", params.get("kind"))
108 definition.setdefault("apiVersion", params.get("api_version"))
109 metadata = definition.setdefault("metadata", {})
110 # The following should only be set if we have values for them
111 if params.get("namespace"):
112 metadata.setdefault("namespace", params.get("namespace"))
113 if params.get("name"):
114 metadata.setdefault("name", params.get("name"))
115 if params.get("generate_name"):
116 metadata.setdefault("generateName", params.get("generate_name"))
117 return definition
118
119
120 def flatten_list_kind(definition: Dict, params: Dict) -> List[Dict]:
121 """Replace *List kind with the items it contains.
122
123 This will take a definition for a *List resource and return a list of
124 definitions for the items contained within the List.
125 """
126 items = []
127 kind = cast(str, definition.get("kind"))[:-4]
128 api_version = definition.get("apiVersion")
129 for item in definition.get("items", []):
130 item.setdefault("kind", kind)
131 item.setdefault("apiVersion", api_version)
132 items.append(merge_params(item, params))
133 return items