|
| 1 | +import os |
| 2 | +import subprocess |
| 3 | + |
| 4 | +import pexpect |
| 5 | +from pexpect import replwrap |
| 6 | + |
| 7 | + |
| 8 | +def kubectl_get_deployment_pod(namespace, labels): |
| 9 | + return subprocess.check_output(["kubectl", "-n", namespace, "get", "pod", "-l", labels, "-o", "jsonpath={.items[0].metadata.name}"], text=True).strip() |
| 10 | + |
| 11 | + |
| 12 | +def kubectl_exec_bash(namespace, pod, container): |
| 13 | + bashrc = os.path.join(os.path.dirname(replwrap.__file__), 'bashrc.sh') |
| 14 | + subprocess.check_call([ |
| 15 | + "kubectl", "-n", namespace, "cp", "-c", container, bashrc, f"{pod}:/tmp/bashrc.sh" |
| 16 | + ]) |
| 17 | + return replwrap._repl_sh("kubectl", [ |
| 18 | + "-n", namespace, "exec", "-c", container, "-it", pod, "--", "bash", '--rcfile', "/tmp/bashrc.sh" |
| 19 | + ], non_printable_insert='\\[\\]') |
| 20 | + |
| 21 | + |
| 22 | +def main_odata(allow_delete=True): |
| 23 | + print("Starting odata ckan resources cleanup...") |
| 24 | + ckan_bash = kubectl_exec_bash("odata", kubectl_get_deployment_pod("odata", "app=ckan"), "ckan") |
| 25 | + num_deleted_files = 0 |
| 26 | + num_resources = 0 |
| 27 | + for resource_id in subprocess.check_output([ |
| 28 | + "kubectl", "-n", "odata", "exec", "deploy/db", "--", "su", "-", "postgres", "-c", |
| 29 | + "psql -dckan -nqtc \"select id from resource where state = 'deleted' and last_modified < now() - interval '10 day';\"" |
| 30 | + ], text=True).splitlines(): |
| 31 | + num_resources += 1 |
| 32 | + if num_resources % 100 == 0: |
| 33 | + print(f"Checked {num_resources} deleted resources, deleted {num_deleted_files} files") |
| 34 | + resource_id = resource_id.strip() |
| 35 | + if resource_id: |
| 36 | + resource_path = os.path.join( |
| 37 | + "/var", "lib", "ckan", "data", "resources", |
| 38 | + resource_id[:3], |
| 39 | + resource_id[3:6], |
| 40 | + resource_id[6:] |
| 41 | + ) |
| 42 | + if allow_delete: |
| 43 | + out = ckan_bash.run_command(f'rm "{resource_path}"\n').strip() |
| 44 | + out = out.split("\n")[1:] |
| 45 | + if len(out) == 0: |
| 46 | + num_deleted_files += 1 |
| 47 | + else: |
| 48 | + assert "No such file or directory" in "\n".join(out) |
| 49 | + else: |
| 50 | + print(ckan_bash.run_command(f"ls -lah \"{resource_path}\" || true\n").strip().encode()) |
| 51 | + print(f"Checked {num_resources} deleted resources, deleted {num_deleted_files} files") |
| 52 | + ckan_bash.child.sendline("exit") |
| 53 | + ckan_bash.child.expect(pexpect.EOF) |
| 54 | + print("Great Success!") |
0 commit comments