kaqing 2.0.98__py3-none-any.whl → 2.0.203__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (254) hide show
  1. adam/__init__.py +0 -2
  2. adam/app_session.py +9 -12
  3. adam/apps.py +18 -4
  4. adam/batch.py +11 -25
  5. adam/checks/check_utils.py +16 -46
  6. adam/checks/cpu.py +7 -1
  7. adam/checks/cpu_metrics.py +52 -0
  8. adam/checks/disk.py +2 -3
  9. adam/columns/columns.py +3 -1
  10. adam/columns/cpu.py +3 -1
  11. adam/columns/cpu_metrics.py +22 -0
  12. adam/columns/memory.py +3 -4
  13. adam/commands/__init__.py +24 -0
  14. adam/commands/alter_tables.py +37 -63
  15. adam/commands/app/app.py +38 -0
  16. adam/commands/{app_ping.py → app/app_ping.py} +8 -14
  17. adam/commands/app/show_app_actions.py +49 -0
  18. adam/commands/{show → app}/show_app_id.py +8 -11
  19. adam/commands/{show → app}/show_app_queues.py +8 -14
  20. adam/commands/app/utils_app.py +106 -0
  21. adam/commands/audit/audit.py +31 -35
  22. adam/commands/audit/audit_repair_tables.py +26 -48
  23. adam/commands/audit/audit_run.py +50 -0
  24. adam/commands/audit/completions_l.py +15 -0
  25. adam/commands/audit/show_last10.py +36 -0
  26. adam/commands/audit/show_slow10.py +36 -0
  27. adam/commands/audit/show_top10.py +36 -0
  28. adam/commands/audit/utils_show_top10.py +71 -0
  29. adam/commands/bash/__init__.py +5 -0
  30. adam/commands/bash/bash.py +36 -0
  31. adam/commands/bash/bash_completer.py +93 -0
  32. adam/commands/bash/utils_bash.py +16 -0
  33. adam/commands/cassandra/__init__.py +0 -0
  34. adam/commands/cassandra/download_cassandra_log.py +45 -0
  35. adam/commands/cassandra/nodetool.py +64 -0
  36. adam/commands/cassandra/nodetool_commands.py +120 -0
  37. adam/commands/{restart.py → cassandra/restart_cluster.py} +12 -26
  38. adam/commands/cassandra/restart_node.py +51 -0
  39. adam/commands/cassandra/restart_nodes.py +47 -0
  40. adam/commands/cassandra/rollout.py +88 -0
  41. adam/commands/cat.py +36 -0
  42. adam/commands/cd.py +14 -92
  43. adam/commands/check.py +18 -21
  44. adam/commands/cli_commands.py +8 -4
  45. adam/commands/clipboard_copy.py +87 -0
  46. adam/commands/code.py +57 -0
  47. adam/commands/command.py +212 -39
  48. adam/commands/commands_utils.py +20 -28
  49. adam/commands/cql/alter_tables.py +66 -0
  50. adam/commands/cql/completions_c.py +29 -0
  51. adam/commands/cql/cqlsh.py +10 -29
  52. adam/commands/cql/utils_cql.py +305 -0
  53. adam/commands/debug/__init__.py +0 -0
  54. adam/commands/debug/debug.py +22 -0
  55. adam/commands/debug/debug_completes.py +35 -0
  56. adam/commands/debug/debug_timings.py +35 -0
  57. adam/commands/deploy/code_start.py +7 -10
  58. adam/commands/deploy/code_stop.py +4 -21
  59. adam/commands/deploy/code_utils.py +3 -3
  60. adam/commands/deploy/deploy.py +4 -21
  61. adam/commands/deploy/deploy_frontend.py +14 -17
  62. adam/commands/deploy/deploy_pg_agent.py +3 -6
  63. adam/commands/deploy/deploy_pod.py +65 -73
  64. adam/commands/deploy/deploy_utils.py +14 -24
  65. adam/commands/deploy/undeploy.py +4 -21
  66. adam/commands/deploy/undeploy_frontend.py +4 -7
  67. adam/commands/deploy/undeploy_pg_agent.py +6 -8
  68. adam/commands/deploy/undeploy_pod.py +11 -12
  69. adam/commands/devices/__init__.py +0 -0
  70. adam/commands/devices/device.py +149 -0
  71. adam/commands/devices/device_app.py +163 -0
  72. adam/commands/devices/device_auit_log.py +49 -0
  73. adam/commands/devices/device_cass.py +179 -0
  74. adam/commands/devices/device_export.py +87 -0
  75. adam/commands/devices/device_postgres.py +160 -0
  76. adam/commands/devices/devices.py +25 -0
  77. adam/commands/download_cassandra_log.py +45 -0
  78. adam/commands/download_file.py +47 -0
  79. adam/commands/exit.py +1 -4
  80. adam/commands/export/__init__.py +0 -0
  81. adam/commands/export/clean_up_all_export_sessions.py +37 -0
  82. adam/commands/export/clean_up_export_sessions.py +39 -0
  83. adam/commands/export/completions_x.py +11 -0
  84. adam/commands/export/download_export_session.py +40 -0
  85. adam/commands/export/drop_export_database.py +39 -0
  86. adam/commands/export/drop_export_databases.py +37 -0
  87. adam/commands/export/export.py +37 -0
  88. adam/commands/export/export_databases.py +247 -0
  89. adam/commands/export/export_select.py +34 -0
  90. adam/commands/export/export_sessions.py +211 -0
  91. adam/commands/export/export_use.py +49 -0
  92. adam/commands/export/export_x_select.py +48 -0
  93. adam/commands/export/exporter.py +361 -0
  94. adam/commands/export/import_files.py +44 -0
  95. adam/commands/export/import_session.py +44 -0
  96. adam/commands/export/importer.py +82 -0
  97. adam/commands/export/importer_athena.py +150 -0
  98. adam/commands/export/importer_sqlite.py +69 -0
  99. adam/commands/export/show_column_counts.py +45 -0
  100. adam/commands/export/show_export_databases.py +39 -0
  101. adam/commands/export/show_export_session.py +39 -0
  102. adam/commands/export/show_export_sessions.py +37 -0
  103. adam/commands/export/utils_export.py +366 -0
  104. adam/commands/find_files.py +51 -0
  105. adam/commands/find_processes.py +76 -0
  106. adam/commands/generate_report.py +52 -0
  107. adam/commands/head.py +36 -0
  108. adam/commands/help.py +12 -8
  109. adam/commands/intermediate_command.py +52 -0
  110. adam/commands/issues.py +14 -40
  111. adam/commands/kubectl.py +38 -0
  112. adam/commands/login.py +26 -25
  113. adam/commands/ls.py +11 -116
  114. adam/commands/medusa/medusa.py +4 -22
  115. adam/commands/medusa/medusa_backup.py +20 -27
  116. adam/commands/medusa/medusa_restore.py +35 -48
  117. adam/commands/medusa/medusa_show_backupjobs.py +17 -18
  118. adam/commands/medusa/medusa_show_restorejobs.py +13 -18
  119. adam/commands/medusa/utils_medusa.py +15 -0
  120. adam/commands/nodetool.py +8 -19
  121. adam/commands/os/__init__.py +0 -0
  122. adam/commands/os/cat.py +36 -0
  123. adam/commands/os/download_file.py +47 -0
  124. adam/commands/os/find_files.py +51 -0
  125. adam/commands/os/find_processes.py +76 -0
  126. adam/commands/os/head.py +36 -0
  127. adam/commands/os/shell.py +41 -0
  128. adam/commands/param_get.py +11 -14
  129. adam/commands/param_set.py +8 -12
  130. adam/commands/postgres/completions_p.py +22 -0
  131. adam/commands/postgres/postgres.py +47 -55
  132. adam/commands/postgres/postgres_databases.py +269 -0
  133. adam/commands/postgres/postgres_ls.py +4 -8
  134. adam/commands/postgres/postgres_preview.py +5 -9
  135. adam/commands/postgres/utils_postgres.py +79 -0
  136. adam/commands/preview_table.py +10 -61
  137. adam/commands/pwd.py +14 -46
  138. adam/commands/reaper/reaper.py +4 -24
  139. adam/commands/reaper/reaper_forward.py +49 -56
  140. adam/commands/reaper/reaper_forward_session.py +6 -0
  141. adam/commands/reaper/reaper_forward_stop.py +10 -16
  142. adam/commands/reaper/reaper_restart.py +7 -14
  143. adam/commands/reaper/reaper_run_abort.py +8 -33
  144. adam/commands/reaper/reaper_runs.py +43 -58
  145. adam/commands/reaper/reaper_runs_abort.py +29 -49
  146. adam/commands/reaper/reaper_schedule_activate.py +14 -33
  147. adam/commands/reaper/reaper_schedule_start.py +9 -33
  148. adam/commands/reaper/reaper_schedule_stop.py +9 -33
  149. adam/commands/reaper/reaper_schedules.py +4 -14
  150. adam/commands/reaper/reaper_status.py +8 -16
  151. adam/commands/reaper/utils_reaper.py +203 -0
  152. adam/commands/repair/repair.py +4 -22
  153. adam/commands/repair/repair_log.py +5 -11
  154. adam/commands/repair/repair_run.py +27 -34
  155. adam/commands/repair/repair_scan.py +32 -40
  156. adam/commands/repair/repair_stop.py +5 -12
  157. adam/commands/restart_cluster.py +47 -0
  158. adam/commands/restart_node.py +51 -0
  159. adam/commands/restart_nodes.py +47 -0
  160. adam/commands/rollout.py +19 -24
  161. adam/commands/shell.py +12 -4
  162. adam/commands/show/show.py +10 -23
  163. adam/commands/show/show_adam.py +3 -3
  164. adam/commands/show/show_cassandra_repairs.py +37 -0
  165. adam/commands/show/show_cassandra_status.py +47 -51
  166. adam/commands/show/show_cassandra_version.py +5 -18
  167. adam/commands/show/show_cli_commands.py +56 -0
  168. adam/commands/show/show_host.py +1 -1
  169. adam/commands/show/show_login.py +23 -27
  170. adam/commands/show/show_params.py +2 -5
  171. adam/commands/show/show_processes.py +18 -21
  172. adam/commands/show/show_storage.py +11 -20
  173. adam/commands/watch.py +26 -29
  174. adam/config.py +5 -15
  175. adam/embedded_params.py +1 -1
  176. adam/log.py +4 -4
  177. adam/repl.py +105 -133
  178. adam/repl_commands.py +68 -28
  179. adam/repl_session.py +9 -1
  180. adam/repl_state.py +300 -62
  181. adam/sql/async_executor.py +44 -0
  182. adam/sql/lark_completer.py +286 -0
  183. adam/sql/lark_parser.py +604 -0
  184. adam/sql/qingl.lark +1076 -0
  185. adam/sql/sql_completer.py +104 -64
  186. adam/sql/sql_state_machine.py +630 -0
  187. adam/sql/term_completer.py +3 -0
  188. adam/sso/authn_ad.py +6 -8
  189. adam/sso/authn_okta.py +4 -6
  190. adam/sso/cred_cache.py +3 -5
  191. adam/sso/idp.py +9 -12
  192. adam/utils.py +640 -10
  193. adam/utils_athena.py +140 -87
  194. adam/utils_audits.py +102 -0
  195. adam/utils_issues.py +32 -0
  196. adam/utils_k8s/app_clusters.py +28 -0
  197. adam/utils_k8s/app_pods.py +35 -0
  198. adam/utils_k8s/cassandra_clusters.py +34 -21
  199. adam/utils_k8s/cassandra_nodes.py +9 -6
  200. adam/utils_k8s/custom_resources.py +16 -17
  201. adam/utils_k8s/ingresses.py +2 -2
  202. adam/utils_k8s/jobs.py +7 -11
  203. adam/utils_k8s/k8s.py +96 -0
  204. adam/utils_k8s/kube_context.py +3 -6
  205. adam/{pod_exec_result.py → utils_k8s/pod_exec_result.py} +11 -5
  206. adam/utils_k8s/pods.py +146 -75
  207. adam/utils_k8s/secrets.py +4 -4
  208. adam/utils_k8s/service_accounts.py +5 -4
  209. adam/utils_k8s/services.py +2 -2
  210. adam/utils_k8s/statefulsets.py +6 -14
  211. adam/utils_local.py +42 -0
  212. adam/utils_net.py +4 -4
  213. adam/utils_repl/__init__.py +0 -0
  214. adam/utils_repl/appendable_completer.py +6 -0
  215. adam/utils_repl/automata_completer.py +48 -0
  216. adam/utils_repl/repl_completer.py +89 -0
  217. adam/utils_repl/state_machine.py +173 -0
  218. adam/utils_sqlite.py +137 -0
  219. adam/version.py +1 -1
  220. {kaqing-2.0.98.dist-info → kaqing-2.0.203.dist-info}/METADATA +1 -1
  221. kaqing-2.0.203.dist-info/RECORD +277 -0
  222. kaqing-2.0.203.dist-info/top_level.txt +2 -0
  223. teddy/__init__.py +0 -0
  224. teddy/lark_parser.py +436 -0
  225. teddy/lark_parser2.py +618 -0
  226. adam/commands/app.py +0 -67
  227. adam/commands/bash.py +0 -92
  228. adam/commands/cp.py +0 -95
  229. adam/commands/cql/cql_completions.py +0 -11
  230. adam/commands/cql/cql_table_completer.py +0 -8
  231. adam/commands/cql/cql_utils.py +0 -115
  232. adam/commands/describe/describe.py +0 -47
  233. adam/commands/describe/describe_keyspace.py +0 -60
  234. adam/commands/describe/describe_keyspaces.py +0 -49
  235. adam/commands/describe/describe_schema.py +0 -49
  236. adam/commands/describe/describe_table.py +0 -60
  237. adam/commands/describe/describe_tables.py +0 -49
  238. adam/commands/devices.py +0 -118
  239. adam/commands/logs.py +0 -39
  240. adam/commands/postgres/postgres_session.py +0 -240
  241. adam/commands/postgres/postgres_utils.py +0 -31
  242. adam/commands/postgres/psql_completions.py +0 -10
  243. adam/commands/postgres/psql_table_completer.py +0 -11
  244. adam/commands/reaper/reaper_session.py +0 -159
  245. adam/commands/report.py +0 -57
  246. adam/commands/show/show_app_actions.py +0 -53
  247. adam/commands/show/show_commands.py +0 -61
  248. adam/commands/show/show_repairs.py +0 -47
  249. adam/sql/state_machine.py +0 -460
  250. kaqing-2.0.98.dist-info/RECORD +0 -191
  251. kaqing-2.0.98.dist-info/top_level.txt +0 -1
  252. /adam/commands/{describe → app}/__init__.py +0 -0
  253. {kaqing-2.0.98.dist-info → kaqing-2.0.203.dist-info}/WHEEL +0 -0
  254. {kaqing-2.0.98.dist-info → kaqing-2.0.203.dist-info}/entry_points.txt +0 -0
@@ -0,0 +1,11 @@
1
+ from adam.commands.export.export_databases import ExportDatabases
2
+ from adam.repl_state import ReplState
3
+ from adam.sql.lark_completer import LarkCompleter
4
+ from adam.utils_athena import Athena
5
+
6
+ def completions_x(state: ReplState):
7
+ return LarkCompleter(expandables={
8
+ 'tables': lambda x: ExportDatabases.table_names(state.export_session),
9
+ 'export-databases': lambda x: ExportDatabases.database_names(),
10
+ 'columns': lambda x: Athena.column_names(database=state.export_session, function='export'),
11
+ }, variant=ReplState.X).completions_for_nesting()
@@ -0,0 +1,40 @@
1
+ from adam.commands import validate_args
2
+ from adam.commands.command import Command
3
+ from adam.commands.export.export_sessions import ExportSessions, export_session
4
+ from adam.repl_state import ReplState, RequiredState
5
+
6
+ class DownloadExportSession(Command):
7
+ COMMAND = 'download export session'
8
+
9
+ # the singleton pattern
10
+ def __new__(cls, *args, **kwargs):
11
+ if not hasattr(cls, 'instance'): cls.instance = super(DownloadExportSession, cls).__new__(cls)
12
+
13
+ return cls.instance
14
+
15
+ def __init__(self, successor: Command=None):
16
+ super().__init__(successor)
17
+
18
+ def command(self):
19
+ return DownloadExportSession.COMMAND
20
+
21
+ def required(self):
22
+ return RequiredState.CLUSTER_OR_POD
23
+
24
+ def run(self, cmd: str, state: ReplState):
25
+ if not(args := self.args(cmd)):
26
+ return super().run(cmd, state)
27
+
28
+ with self.validate(args, state) as (args, state):
29
+ with validate_args(args, state, name='export session') as session:
30
+ with export_session(state) as sessions:
31
+ sessions.download_session(session)
32
+
33
+ return state
34
+
35
+ def completion(self, state: ReplState):
36
+ return {}
37
+ # return super().completion(state, {session: None for session in ExportSessions.export_session_names(state.sts, state.pod, state.namespace, export_state='pending_import')})
38
+
39
+ def help(self, _: ReplState):
40
+ return f'{DownloadExportSession.COMMAND} <export-session-name>\t download csv files in export session'
@@ -0,0 +1,39 @@
1
+ from adam.commands import validate_args
2
+ from adam.commands.command import Command
3
+ from adam.commands.export.export_databases import export_db
4
+ from adam.repl_state import ReplState
5
+
6
+ class DropExportDatabase(Command):
7
+ COMMAND = 'drop export database'
8
+
9
+ # the singleton pattern
10
+ def __new__(cls, *args, **kwargs):
11
+ if not hasattr(cls, 'instance'): cls.instance = super(DropExportDatabase, cls).__new__(cls)
12
+
13
+ return cls.instance
14
+
15
+ def __init__(self, successor: Command=None):
16
+ super().__init__(successor)
17
+
18
+ def command(self):
19
+ return DropExportDatabase.COMMAND
20
+
21
+ def required(self):
22
+ return [ReplState.C, ReplState.X]
23
+
24
+ def run(self, cmd: str, state: ReplState):
25
+ if not(args := self.args(cmd)):
26
+ return super().run(cmd, state)
27
+
28
+ with self.validate(args, state) as (args, state):
29
+ with validate_args(args, state, name='database name') as db:
30
+ with export_db(state) as dbs:
31
+ dbs.drop(args[0])
32
+
33
+ return state
34
+
35
+ def completion(self, _: ReplState):
36
+ return {}
37
+
38
+ def help(self, _: ReplState):
39
+ return f'{DropExportDatabase.COMMAND} <export-database-name>\t drop export database'
@@ -0,0 +1,37 @@
1
+ from adam.commands.command import Command
2
+ from adam.commands.export.export_databases import export_db
3
+ from adam.repl_state import ReplState
4
+
5
+ class DropExportDatabases(Command):
6
+ COMMAND = 'drop all export databases'
7
+
8
+ # the singleton pattern
9
+ def __new__(cls, *args, **kwargs):
10
+ if not hasattr(cls, 'instance'): cls.instance = super(DropExportDatabases, cls).__new__(cls)
11
+
12
+ return cls.instance
13
+
14
+ def __init__(self, successor: Command=None):
15
+ super().__init__(successor)
16
+
17
+ def command(self):
18
+ return DropExportDatabases.COMMAND
19
+
20
+ def required(self):
21
+ return [ReplState.C, ReplState.X]
22
+
23
+ def run(self, cmd: str, state: ReplState):
24
+ if not(args := self.args(cmd)):
25
+ return super().run(cmd, state)
26
+
27
+ with self.validate(args, state) as (args, state):
28
+ with export_db(state) as dbs:
29
+ dbs.drop_all()
30
+
31
+ return state
32
+
33
+ def completion(self, _: ReplState):
34
+ return {}
35
+
36
+ def help(self, _: ReplState):
37
+ return f'{DropExportDatabases.COMMAND}\t drop all export databases'
@@ -0,0 +1,37 @@
1
+ from adam.commands import extract_options
2
+ from adam.commands.command import Command
3
+ from adam.commands.export.exporter import export
4
+ from adam.repl_state import ReplState, RequiredState
5
+
6
+ class ExportTables(Command):
7
+ COMMAND = 'export'
8
+
9
+ # the singleton pattern
10
+ def __new__(cls, *args, **kwargs):
11
+ if not hasattr(cls, 'instance'): cls.instance = super(ExportTables, cls).__new__(cls)
12
+
13
+ return cls.instance
14
+
15
+ def __init__(self, successor: Command=None):
16
+ super().__init__(successor)
17
+
18
+ def command(self):
19
+ return ExportTables.COMMAND
20
+
21
+ def required(self):
22
+ return RequiredState.CLUSTER_OR_POD
23
+
24
+ def run(self, cmd: str, state: ReplState):
25
+ if not(args := self.args(cmd)):
26
+ return super().run(cmd, state)
27
+
28
+ with self.validate(args, state) as (args, state):
29
+ with extract_options(args, '--export-only') as (args, export_only):
30
+ with export(state) as exporter:
31
+ return exporter.export(args, export_only=export_only)
32
+
33
+ def completion(self, state: ReplState):
34
+ return {}
35
+
36
+ def help(self, _: ReplState):
37
+ return f'{ExportTables.COMMAND} [* [in KEYSPACE]] | [TABLE] [as target-name] [with consistency <level>]\t export tables to Sqlite, Athena or CSV file'
@@ -0,0 +1,247 @@
1
+ from collections.abc import Callable
2
+ from datetime import datetime
3
+ import os
4
+ import boto3
5
+
6
+ from adam.commands.export.export_sessions import ExportSessions
7
+ from adam.commands.export.importer import Importer
8
+ from adam.commands.export.utils_export import export_log_prefix
9
+ from adam.config import Config
10
+ from adam.repl_session import ReplSession
11
+ from adam.repl_state import ReplState
12
+ from adam.utils import debug, log_timing, tabulize, log2, ing, log_exc
13
+ from adam.utils_athena import Athena
14
+ from adam.utils_sqlite import SQLite
15
+
16
+ LIKE = 'e%_%'
17
+
18
+ class ExportDatabases:
19
+ def run_query(query: str, database: str, show_query=False, output: Callable[[str], str] = None) -> int:
20
+ cnt: int = 0
21
+
22
+ if show_query:
23
+ log2(query)
24
+
25
+ log_file = None
26
+ if database.startswith('s'):
27
+ cnt0, log_file = SQLite.run_query(query, database=database, output=output)
28
+ cnt += cnt0
29
+ else:
30
+ cnt0, log_file = Athena.run_query(query, database=database, output=output)
31
+ cnt += cnt0
32
+
33
+ if Config().get('repl.history.push-cat-log-file', True):
34
+ if log_file and ReplSession().prompt_session:
35
+ ReplSession().prompt_session.history.append_string(f':sh cat {log_file}')
36
+
37
+ return cnt
38
+
39
+ def sessions_from_dbs(dbs: list[str]):
40
+
41
+ sessions = set()
42
+
43
+ for db in dbs:
44
+ sessions.add(db.split('_')[0])
45
+
46
+ return list(sessions)
47
+
48
+ def drop_export_dbs(db: str = None):
49
+ dbs: list[str] = []
50
+
51
+ if not db or db.startswith('s'):
52
+ dbs.extend(ExportDatabases.drop_sqlite_dbs(db))
53
+ if not db or db.startswith('e'):
54
+ dbs.extend(ExportDatabases.drop_athena_dbs(db))
55
+
56
+ return dbs
57
+
58
+ def drop_sqlite_dbs(db: str = None):
59
+ dbs = SQLite.database_names(db)
60
+ if dbs:
61
+ with ing(f'Droping {len(dbs)} SQLite databases'):
62
+ with log_exc():
63
+ for db in dbs:
64
+ file_path = f'{SQLite.local_db_dir()}/{db}'
65
+ try:
66
+ os.remove(file_path)
67
+ except OSError as e:
68
+ pass
69
+
70
+ return dbs
71
+
72
+ def drop_athena_dbs(db: str = None):
73
+ dbs = Athena.database_names(f'{db}_%' if db else LIKE)
74
+ if dbs:
75
+ with ing(f'Droping {len(dbs)} Athena databases'):
76
+ for db in dbs:
77
+ query = f'DROP DATABASE {db} CASCADE'
78
+ debug(query)
79
+ Athena.query(query)
80
+
81
+ with ing(f'Deleting s3 folder: export'):
82
+ with log_exc():
83
+ if not db:
84
+ db = ''
85
+
86
+ s3 = boto3.resource('s3')
87
+ bucket = s3.Bucket(Config().get('export.bucket', 'c3.ops--qing'))
88
+ bucket.objects.filter(Prefix=f'export/{db}').delete()
89
+
90
+ return dbs
91
+
92
+ def show_database(database: str):
93
+ if not database:
94
+ return
95
+
96
+ ExportDatabases.clear_cache()
97
+
98
+ keyspaces = {}
99
+ for table in ExportDatabases.table_names(database):
100
+ keyspace = table.split('.')[0]
101
+ if keyspace in keyspaces:
102
+ keyspaces[keyspace] += 1
103
+ else:
104
+ keyspaces[keyspace] = 1
105
+
106
+ tabulize(keyspaces.items(), lambda a: f'{a[0]},{a[1]}', header='SCHEMA,# of TABLES', separator=',')
107
+
108
+ def database_names():
109
+ return ExportDatabases.copy_database_names() + ExportDatabases.export_database_names()
110
+
111
+ def copy_database_names():
112
+ return list({n.split('_')[0] for n in SQLite.database_names()})
113
+
114
+ def export_database_names():
115
+ with log_timing('ExportDatabases.Athena.database_names'):
116
+ return list({n.split('_')[0] for n in Athena.database_names(LIKE)})
117
+
118
+ def database_names_with_keyspace_cnt(importer: str = None):
119
+ r = {}
120
+
121
+ names = []
122
+ if not importer:
123
+ names = SQLite.database_names() + Athena.database_names(LIKE)
124
+ elif importer == 'athena':
125
+ names = Athena.database_names(LIKE)
126
+ else:
127
+ names = SQLite.database_names()
128
+
129
+ for n in names:
130
+ tokens = n.split('_')
131
+ name = tokens[0]
132
+ keyspace = None
133
+ if len(tokens) > 1:
134
+ keyspace = tokens[1].replace('.db', '')
135
+
136
+ if keyspace == 'root':
137
+ continue
138
+
139
+ if name in r:
140
+ r[name] += 1
141
+ else:
142
+ r[name] = 1
143
+
144
+ return r
145
+
146
+ def table_names(session: str):
147
+ tables = []
148
+
149
+ for session in ExportDatabases._session_database_names(session):
150
+ if session.startswith('s'):
151
+ for table in SQLite.table_names(database=session):
152
+ tables.append(f'{SQLite.keyspace(session)}.{table}')
153
+ else:
154
+ for table in Athena.table_names(database=session, function='export'):
155
+ tables.append(f'{session}.{table}')
156
+
157
+ return tables
158
+
159
+ def _session_database_names(db: str):
160
+ eprefix = db
161
+ if '_' in db:
162
+ eprefix = db.split('_')[0]
163
+
164
+ if db.startswith('s'):
165
+ return SQLite.database_names(prefix=f'{eprefix}_')
166
+ else:
167
+ return Athena.database_names(like=f'{eprefix}_%')
168
+
169
+ def drop_databases(sts: str, pod: str, namespace: str, database: str = None):
170
+ importer = None
171
+ if database:
172
+ importer = Importer.importer_from_session(database)
173
+
174
+ sessions_done = ExportSessions.export_session_names(sts, pod, namespace, importer=importer, export_state='done')
175
+ sessions = ExportDatabases.sessions_from_dbs(ExportDatabases.drop_export_dbs(database))
176
+ if sessions_done and sessions:
177
+ intersects = list(set(sessions_done) & set(sessions))
178
+ with ing(f'Cleaning up {len(intersects)} completed sessions'):
179
+ ExportSessions.clean_up_sessions(sts, pod, namespace, list(intersects))
180
+ ExportSessions.clear_export_session_cache()
181
+
182
+ def clear_cache(database: str = None):
183
+ if not database or database.startswith('s'):
184
+ SQLite.clear_cache()
185
+ if not database or database.startswith('e'):
186
+ Athena.clear_cache()
187
+
188
+ def show_databases(importer: str = None):
189
+ lines = [f'{k}\t{v}' for k, v in ExportDatabases.database_names_with_keyspace_cnt(importer).items()]
190
+ tabulize(lines, header='NAME\tKEYSPACES', separator='\t')
191
+
192
+ class ExportDatabaseService:
193
+ def __init__(self, handler: 'ExportDatabaseHandler'):
194
+ self.handler = handler
195
+
196
+ def sql(self, query: str, database: str = None, backgrounded = False):
197
+ if not database:
198
+ database = self.handler.state.export_session
199
+
200
+ def output(out: str):
201
+ # log_prefix = Config().get('export.log-prefix', '/tmp/qing')
202
+ log_file = f'{export_log_prefix()}-{datetime.now().strftime("%d%H%M%S")}-export.log'
203
+
204
+ with open(log_file, 'w') as f:
205
+ f.write(out)
206
+
207
+ return log_file
208
+
209
+ ExportDatabases.run_query(query, database, output = output if backgrounded else None, show_query = not backgrounded)
210
+
211
+ def drop(self, database: str):
212
+ state = self.handler.state
213
+
214
+ ExportDatabases.drop_databases(state.sts, state.pod, state.namespace, database)
215
+ ExportDatabases.clear_cache(database)
216
+ if state.export_session == database:
217
+ state.export_session = None
218
+
219
+ def drop_all(self):
220
+ state = self.handler.state
221
+
222
+ ExportDatabases.drop_databases(state.sts, state.pod, state.namespace)
223
+ ExportDatabases.clear_cache()
224
+
225
+ state.export_session = None
226
+
227
+ def show_databases(self, importer: str = None):
228
+ ExportDatabases.show_databases(importer)
229
+
230
+ def show_database(self, database: str = None):
231
+ if not database:
232
+ database = self.handler.state.export_session
233
+
234
+ ExportDatabases.show_database(database)
235
+
236
+ class ExportDatabaseHandler:
237
+ def __init__(self, state: ReplState = None):
238
+ self.state = state
239
+
240
+ def __enter__(self):
241
+ return ExportDatabaseService(self)
242
+
243
+ def __exit__(self, exc_type, exc_val, exc_tb):
244
+ return False
245
+
246
+ def export_db(state: ReplState = None):
247
+ return ExportDatabaseHandler(state)
@@ -0,0 +1,34 @@
1
+ from adam.commands.command import Command
2
+ from adam.commands.export.completions_x import completions_x
3
+ from adam.repl_state import ReplState, RequiredState
4
+
5
+ # No action body, only for a help entry and auto-completion
6
+ class ExportSelect(Command):
7
+ COMMAND = 'select_on_x'
8
+
9
+ # the singleton pattern
10
+ def __new__(cls, *args, **kwargs):
11
+ if not hasattr(cls, 'instance'): cls.instance = super(ExportSelect, cls).__new__(cls)
12
+
13
+ return cls.instance
14
+
15
+ def __init__(self, successor: Command=None):
16
+ super().__init__(successor)
17
+
18
+ def command(self):
19
+ return ExportSelect.COMMAND
20
+
21
+ def required(self):
22
+ return RequiredState.EXPORT_DB
23
+
24
+ def completion(self, state: ReplState):
25
+ if state.device != ReplState.X:
26
+ return {}
27
+
28
+ if state.export_session:
29
+ return completions_x(state)
30
+
31
+ return {}
32
+
33
+ def help(self, _: ReplState):
34
+ return f'<sql-select-statements>\t run queries on export database'
@@ -0,0 +1,211 @@
1
+ import functools
2
+ import os
3
+ import re
4
+
5
+ from adam.commands.export.importer import Importer
6
+ from adam.commands.export.utils_export import ExportTableStatus, csv_dir, export_log_prefix, find_files, os_system_exec
7
+ from adam.config import Config
8
+ from adam.repl_state import ReplState
9
+ from adam.utils import log2, tabulize, log, parallelize
10
+ from adam.utils_k8s.cassandra_nodes import CassandraNodes
11
+ from adam.utils_k8s.pods import Pods
12
+ from adam.utils_k8s.statefulsets import StatefulSets
13
+ from adam.utils_local import local_tmp_dir
14
+
15
+ class ExportSessions:
16
+ def clear_export_session_cache():
17
+ ExportSessions.find_export_sessions.cache_clear()
18
+ ExportSessions.export_session_names.cache_clear()
19
+
20
+ @functools.lru_cache()
21
+ def export_session_names(sts: str, pod: str, namespace: str, importer: str = None, export_state = None):
22
+ if not sts or not namespace:
23
+ return []
24
+
25
+ if not pod:
26
+ pod = StatefulSets.pod_names(sts, namespace)[0]
27
+
28
+ if not pod:
29
+ return []
30
+
31
+ return [session for session, state in ExportSessions.find_export_sessions(pod, namespace, importer).items() if not export_state or state == export_state]
32
+
33
+ @functools.lru_cache()
34
+ def find_export_sessions(pod: str, namespace: str, importer: str = None, limit = 100):
35
+ sessions: dict[str, str] = {}
36
+
37
+ prefix = Importer.prefix_from_importer(importer)
38
+
39
+ log_files: list[str] = find_files(pod, namespace, f'{export_log_prefix()}-{prefix}*_*.log*')
40
+
41
+ if not log_files:
42
+ return {}
43
+
44
+ for log_file in log_files[:limit]:
45
+ m = re.match(f'{export_log_prefix()}-([ces].*?)_.*\.log?(.*)', log_file)
46
+ if m:
47
+ s = m.group(1)
48
+ state = m.group(2) # '', '.pending_import', '.done'
49
+ if state:
50
+ state = state.strip('.')
51
+ else:
52
+ state = 'in_export'
53
+
54
+ if s not in sessions:
55
+ sessions[s] = state
56
+ elif sessions[s] == 'done' and state != 'done':
57
+ sessions[s] = state
58
+
59
+ return sessions
60
+
61
+ def clean_up_all_sessions(sts: str, pod: str, namespace: str):
62
+ if not sts or not namespace:
63
+ return False
64
+
65
+ if not pod:
66
+ pod = StatefulSets.pod_names(sts, namespace)[0]
67
+
68
+ CassandraNodes.exec(pod, namespace, f'rm -rf {csv_dir()}/*', show_out=Config().is_debug(), shell='bash')
69
+ cmd = f'rm -rf {export_log_prefix()}-*.log*'
70
+ os_system_exec(cmd, show_out=Config().is_debug())
71
+
72
+ return True
73
+
74
+ def clean_up_sessions(sts: str, pod: str, namespace: str, sessions: list[str], max_workers = 0):
75
+ if not sessions:
76
+ return []
77
+
78
+ if not max_workers:
79
+ max_workers = Config().action_workers('export', 8)
80
+
81
+ with parallelize(sessions,
82
+ max_workers,
83
+ msg='Cleaning|Cleaned up {size} export sessions') as exec:
84
+ cnt_tuples = exec.map(lambda session: ExportSessions.clean_up_session(sts, pod, namespace, session, True))
85
+ csv_cnt = 0
86
+ log_cnt = 0
87
+ for (csv, log) in cnt_tuples:
88
+ csv_cnt += csv
89
+ log_cnt += log
90
+
91
+ return csv_cnt, log_cnt
92
+
93
+ def clean_up_session(sts: str, pod: str, namespace: str, session: str, multi_tables = True):
94
+ if not sts or not namespace:
95
+ return 0, 0
96
+
97
+ if not pod:
98
+ pod = StatefulSets.pod_names(sts, namespace)[0]
99
+
100
+ if not pod:
101
+ return 0, 0
102
+
103
+ csv_cnt = 0
104
+ log_cnt = 0
105
+
106
+ log_files: list[str] = find_files(pod, namespace, f'{export_log_prefix()}-{session}_*.log*')
107
+
108
+ for log_file in log_files:
109
+ m = re.match(f'{export_log_prefix()}-{session}_(.*?)\.(.*?)\.log.*', log_file)
110
+ if m:
111
+ table = m.group(2)
112
+
113
+ CassandraNodes.exec(pod, namespace, f'rm -rf {csv_dir()}/{session}_{table}', show_out=not multi_tables, shell='bash')
114
+ csv_cnt += 1
115
+
116
+ cmd = f'rm -rf {log_file}'
117
+ os_system_exec(cmd, show_out=not multi_tables)
118
+ log_cnt += 1
119
+
120
+ return csv_cnt, log_cnt
121
+
122
+ def show_session(sts: str, pod: str, namespace: str, session: str):
123
+ if not pod:
124
+ pod = StatefulSets.pod_names(sts, namespace)[0]
125
+
126
+ if not pod:
127
+ return
128
+
129
+ tables, _ = ExportTableStatus.from_session(sts, pod, namespace, session)
130
+ log()
131
+ tabulize(tables,
132
+ lambda t: f'{t.keyspace}\t{t.target_table}\t{"export_completed_pending_import" if t.status == "pending_import" else t.status}\t{t.csv_file}',
133
+ header='KEYSPACE\tTARGET_TABLE\tSTATUS\tCSV_FILES',
134
+ separator='\t')
135
+
136
+ def download_session(sts: str, pod: str, namespace: str, session: str):
137
+ if not pod:
138
+ pod = StatefulSets.pod_names(sts, namespace)[0]
139
+
140
+ if not pod:
141
+ return
142
+
143
+ tables, _ = ExportTableStatus.from_session(sts, pod, namespace, session)
144
+ def download_csv(table):
145
+ from_path: str = table.csv_file
146
+
147
+ to_path = from_path.replace(csv_dir(), local_tmp_dir())
148
+ os.makedirs(os.path.dirname(to_path), exist_ok=True)
149
+ Pods.download_file(pod, 'cassandra', namespace, from_path, to_path)
150
+
151
+ log2(f'[{session}] Downloaded to {to_path}.')
152
+
153
+ with parallelize(tables,
154
+ workers=Config().get('download.workers', 8),
155
+ msg='Downloading|Downloaded {size} csv files') as exec:
156
+ exec.map(download_csv)
157
+
158
+ class ExportSessionService:
159
+ def __init__(self, handler: 'ExportSessionHandler'):
160
+ self.handler = handler
161
+
162
+ def clean_up(self, sessions: list[str]):
163
+ state = self.handler.state
164
+
165
+ csv_cnt, log_cnt = ExportSessions.clean_up_sessions(state.sts, self.pod(), state.namespace, sessions)
166
+
167
+ log(f'Removed {csv_cnt} csv and {log_cnt} log files.')
168
+
169
+ ExportSessions.clear_export_session_cache()
170
+
171
+ def clean_up_all(self):
172
+ state = self.handler.state
173
+
174
+ if ExportSessions.clean_up_all_sessions(state.sts, self.pod(), state.namespace):
175
+ ExportSessions.clear_export_session_cache()
176
+
177
+ def show_all_sessions(self):
178
+ state = self.handler.state
179
+
180
+ sessions = sorted(ExportSessions.find_export_sessions(self.pod(), state.namespace).items(), reverse=True)
181
+ tabulize(sessions, lambda args: f'{args[0]}\t{args[1]}', header='EXPORT_SESSION\tSTATUS', separator='\t')
182
+
183
+ def show_session(self, session: str):
184
+ state = self.handler.state
185
+ ExportSessions.show_session(state.sts, self.pod(), state.namespace, session)
186
+
187
+ def download_session(self, session: str):
188
+ state = self.handler.state
189
+ ExportSessions.download_session(state.sts, self.pod(), state.namespace, session)
190
+
191
+ def pod(self):
192
+ state = self.handler.state
193
+
194
+ pod = state.pod
195
+ if not pod:
196
+ pod = StatefulSets.pod_names(state.sts, state.namespace)[0]
197
+
198
+ return pod
199
+
200
+ class ExportSessionHandler:
201
+ def __init__(self, state: ReplState = None):
202
+ self.state = state
203
+
204
+ def __enter__(self):
205
+ return ExportSessionService(self)
206
+
207
+ def __exit__(self, exc_type, exc_val, exc_tb):
208
+ return False
209
+
210
+ def export_session(state: ReplState = None):
211
+ return ExportSessionHandler(state)