-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstorage.py
190 lines (157 loc) · 6.48 KB
/
storage.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
import base64
import hashlib
import logging
import os
from typing import Any, Optional
from kapitan.resources import inventory
from .common import (
ConfigDataSpec,
ConfigMapSpec,
KubernetesResource,
SecretSpec,
SharedConfigSpec,
TransformTypes,
kgenlib,
)
logger = logging.getLogger(__name__)
class SharedConfig(KubernetesResource):
"""Shared base class for both ConfigMap and Secret components."""
config: SharedConfigSpec
workload: Optional[Any] = None
@staticmethod
def encode_string(unencoded_string):
"""Encode a string using base64."""
return base64.b64encode(unencoded_string.encode("ascii")).decode("ascii")
def add_directory(self, directory, encode=False, stringdata=False, basedir=None):
"""Add contents of files in a directory."""
if basedir is None:
basedir = directory
if directory and os.path.isdir(directory):
logger.debug(f"Adding files from directory {directory} to {self.name}.")
for filename in os.listdir(directory):
path = os.path.join(directory, filename)
if os.path.isfile(path):
with open(path, "r") as f:
file_content = f.read()
self.add_item(
os.path.relpath(path, basedir).replace(os.sep, "_"),
file_content,
request_encode=encode,
stringdata=stringdata,
)
else:
self.add_directory(path, encode, stringdata, basedir=basedir)
def add_item(self, key, value, request_encode=False, stringdata=False):
"""Add a single item to the resource."""
encode = not stringdata and request_encode
field = "stringData" if stringdata else "data"
self.root[field][key] = self.encode_string(value) if encode else value
logger.debug(f"Added item with key '{key}' to {self.name}.")
def add_from_spec(self, key, spec: ConfigDataSpec, stringdata=False):
"""Add data from a specification dictionary."""
logger.debug(f"Adding item from spec {spec} to {self.name}.")
encode = spec.b64_encode
value = None
transform = spec.transform
if spec.value:
value = spec.value
if transform != TransformTypes.NONE:
logger.debug(f"Transforming {key} with {transform}.")
if (
transform == TransformTypes.AUTO
and key.endswith(".json")
or transform == TransformTypes.JSON
):
value = kgenlib.render_json(value)
elif (
transform == TransformTypes.AUTO
and (key.endswith(".yaml") or key.endswith(".yml"))
or transform == TransformTypes.YAML
):
value = kgenlib.render_yaml(value)
elif spec.template:
context = spec.values.copy()
context["inventory"] = inventory(None)
context["inventory_global"] = inventory(None, None)
value = kgenlib.render_jinja(spec.template, context)
elif spec.file:
with open(spec.file, "r") as f:
value = f.read()
if value:
self.add_item(key, value, request_encode=encode, stringdata=stringdata)
def versioning(self):
import json
"""Handle versioning for the resource."""
if self.config.versioned:
keys_of_interest = ["data", "binaryData", "stringData"]
subset = {
key: value
for key, value in self.root.to_dict().items()
if key in keys_of_interest
}
# Create a sorted representation for the subset
canonical_representation = json.dumps(subset, sort_keys=True)
self.hash = hashlib.sha256(canonical_representation.encode()).hexdigest()[
:8
]
self.rendered_name = f"{self.name}-{self.hash}"
self.root.metadata.name = self.rendered_name
logger.debug(f"Versioning enabled for {self.name}. Using hash {self.hash}.")
def body(self):
"""Shared logic for building the body of both Secret and ConfigMap."""
logger.debug(f"Building body for {self.name}.")
super().body()
self.items = self.config.items
for key, spec in self.config.data.items():
self.add_from_spec(key, spec)
self.add_directory(self.config.directory)
self.post_setup()
self.versioning()
if self.workload:
self.add_label("name", self.workload.root.metadata.name)
self.workload.add_volumes_for_object(self)
def post_setup(self):
"""Method to be overridden in derived classes for extra setups."""
pass
class ComponentConfig(SharedConfig):
"""Specific implementation of ConfigMap."""
kind: str = "ConfigMap"
api_version: str = "v1"
config: ConfigMapSpec
class ComponentSecret(SharedConfig):
"""Specific implementation of Secret."""
kind: str = "Secret"
api_version: str = "v1"
config: SecretSpec
def post_setup(self):
"""Specific setups for the Secret."""
self.root.type = self.config.type
logger.debug(f"Setting Secret type for {self.name} as {self.root.type}.")
for key, spec in self.config.string_data.items():
self.add_from_spec(key, spec, stringdata=True)
@kgenlib.register_generator(
path="generators.kubernetes.secrets",
apply_patches=["generators.manifest.default_resource"],
)
class SecretGenerator(kgenlib.BaseStore):
def body(self):
logger.debug(f"Generating Secret for {self.name}.")
namespace = self.config.get(
"namespace", self.inventory.parameters.get("namespace", None)
)
self.add(
ComponentSecret(name=self.name, config=self.config, namespace=namespace)
)
@kgenlib.register_generator(
path="generators.kubernetes.config_maps",
apply_patches=["generators.manifest.default_resource"],
)
class ConfigGenerator(kgenlib.BaseStore):
def body(self):
logger.debug(f"Generating ConfigMap for {self.name}.")
namespace = self.config.get(
"namespace", self.inventory.parameters.get("namespace", None)
)
self.add(
ComponentConfig(name=self.name, config=self.config, namespace=namespace)
)