2022-05-16 17:09:33 +01:00
|
|
|
from collections.abc import Mapping, Sequence
|
2022-03-10 14:26:22 +00:00
|
|
|
import json
|
2022-05-17 08:13:50 +01:00
|
|
|
from typing import List, Any
|
2022-03-10 14:26:22 +00:00
|
|
|
|
|
|
|
from app import app
|
2022-05-16 17:09:33 +01:00
|
|
|
from app.lists import lists
|
2022-04-22 14:01:16 +01:00
|
|
|
from app.models.base import MirrorList
|
2022-05-08 17:20:04 +01:00
|
|
|
from app.terraform.terraform import TerraformAutomation
|
2022-03-10 14:26:22 +00:00
|
|
|
|
|
|
|
|
2022-05-16 17:09:33 +01:00
|
|
|
def obfuscator(obj: Any) -> Any:
|
|
|
|
if isinstance(obj, str):
|
|
|
|
return "".join([f"!AAA!{hex(ord(c))[2:].zfill(4)}" for c in obj])
|
|
|
|
if isinstance(obj, Mapping):
|
|
|
|
return {obfuscator(k): obfuscator(v) for k, v in obj.items()}
|
|
|
|
if isinstance(obj, Sequence):
|
|
|
|
return [obfuscator(i) for i in obj]
|
|
|
|
return obj
|
|
|
|
|
|
|
|
|
|
|
|
def json_encode(obj: Any, obfuscate: bool) -> str:
|
|
|
|
if obfuscate:
|
|
|
|
obj = obfuscator(obj)
|
2022-06-23 13:42:45 +01:00
|
|
|
result = json.dumps(obj, sort_keys=True).replace("!AAA!", "\\u")
|
|
|
|
return result
|
2022-05-16 17:09:33 +01:00
|
|
|
return json.dumps(obj, indent=2, sort_keys=True)
|
|
|
|
|
|
|
|
|
|
|
|
def javascript_encode(obj: Any, obfuscate: bool) -> str:
|
2022-05-19 12:27:47 +01:00
|
|
|
return "var mirrors = " + json_encode(obj, obfuscate) + ";"
|
2022-05-16 17:09:33 +01:00
|
|
|
|
|
|
|
|
2022-05-08 17:20:04 +01:00
|
|
|
class ListAutomation(TerraformAutomation):
|
2022-05-16 11:44:03 +01:00
|
|
|
template: str
|
|
|
|
"""
|
|
|
|
Terraform configuration template using Jinja 2.
|
|
|
|
"""
|
|
|
|
|
|
|
|
template_parameters: List[str]
|
|
|
|
"""
|
|
|
|
List of parameters to be read from the application configuration for use
|
|
|
|
in the templating of the Terraform configuration.
|
|
|
|
"""
|
|
|
|
|
|
|
|
def tf_generate(self) -> None:
|
2022-05-08 17:20:04 +01:00
|
|
|
self.tf_write(
|
2022-03-10 14:26:22 +00:00
|
|
|
self.template,
|
|
|
|
lists=MirrorList.query.filter(
|
2022-05-16 13:29:48 +01:00
|
|
|
MirrorList.destroyed.is_(None),
|
2022-03-10 14:26:22 +00:00
|
|
|
MirrorList.provider == self.provider,
|
|
|
|
).all(),
|
|
|
|
global_namespace=app.config['GLOBAL_NAMESPACE'],
|
|
|
|
**{
|
|
|
|
k: app.config[k.upper()]
|
|
|
|
for k in self.template_parameters
|
|
|
|
}
|
|
|
|
)
|
2022-06-23 13:42:45 +01:00
|
|
|
for key, formatter in lists.items():
|
2022-05-16 17:09:33 +01:00
|
|
|
for obfuscate in [True, False]:
|
2022-06-23 13:42:45 +01:00
|
|
|
with open(self.working_directory(f"{key}{'.jsno' if obfuscate else '.json'}"),
|
|
|
|
'w', encoding="utf-8") as out:
|
|
|
|
out.write(json_encode(formatter(), obfuscate))
|
|
|
|
with open(self.working_directory(f"{key}{'.jso' if obfuscate else '.js'}"),
|
|
|
|
'w', encoding="utf-8") as out:
|
|
|
|
out.write(javascript_encode(formatter(), obfuscate))
|