diff --git a/src/tasks_downstream.py b/src/tasks_downstream.py index 777ca96..489d545 100644 --- a/src/tasks_downstream.py +++ b/src/tasks_downstream.py @@ -764,6 +764,101 @@ def down(c, purge=False): c.run(cmd, pty=True) +def check_make_yaml(filename): + yaml_exists = os.path.exists(PROJECT_ROOT / filename) + if not yaml_exists: + # Create empty yaml file + with open(PROJECT_ROOT / filename, "w") as f: + f.write("namespaces: []\n") + + +@task( + help={ + "command": "Command to run in the container. " + "Options: ['shell', 'logs', 'bash', 'upgradelog', 'pgactivity', 'removens']", + } +) +def kube(c, command, namespace=None): + """Run a kubectl command in the provided namespace.""" + namespace = namespace.strip() + command = command.strip().lower() + filename = ".glo.yaml" + check_make_yaml(filename) + + namespaces = yaml.safe_load((PROJECT_ROOT / filename).read_text()).get( + "namespaces", [] + ) + + # Fetch the namespace from a .glo.yaml file + if namespace is None: + if len(namespaces) == 1: + namespace = namespaces[0] + elif len(namespaces) > 1: + _logger.warning( + "Select a namespace: (use -n {MyNamespace} to add a new one)" + ) + counter = 0 + for namespace in namespaces: + _logger.warning(f" [{counter}] {namespace}") + counter += 1 + response = input("Default [0]: ") + if not response: + namespace = namespaces[0] + else: + try: + namespace = namespaces[int(response)] + except IndexError: + _logger.error("Namespace not found. Please try again.") + return False + else: + _logger.error( + "Namespace not provided or found in .glo.yaml file. " + "Please provide a namespace.\n" + "Use: invoke kube {command} -n MyNamespace" + ) + return False + else: + if namespace not in namespaces: + # Add new namespace to the .glo.yaml file + namespaces.append(namespace) + yaml.safe_dump( + {"namespaces": namespaces}, + (PROJECT_ROOT / filename).open("w"), + ) + + if command == "shell": + cmd = ( + f"kubectl exec deployment/odoo-web -it -n {namespace}" + " -- odoo shell --no-http" + ) + elif command == "logs": + cmd = f"kubectl logs -f deployment/odoo-web -n {namespace} --all-containers" + elif command == "bash": + cmd = f"kubectl exec deployment/odoo-web -it -n {namespace} -- bash" + elif command == "upgradelog": + cmd = f"kubectl logs -f job/odoo-upgrade -n {namespace}" + elif command == "pgactivity": + cmd = f"kubectl exec deployment/odoo-web -it -n {namespace} -- pg_activity" + elif command == "removens": + if namespace in namespaces: + namespaces.remove(namespace) + yaml.safe_dump( + {"namespaces": namespaces}, + (PROJECT_ROOT / filename).open("w"), + ) + _logger.warning(f"Namespace {namespace} removed from {filename}") + else: + _logger.error(f"Namespace {namespace} not found in {filename}") + return + else: + _logger.error( + f"Command {command} not found.\n" + "Options: ['shell', 'logs', 'bash', 'upgradelog', 'pgactivity']" + ) + return + c.run(cmd, pty=True) + + @task() def preparedb(c, database=False): """