kaqing 2.0.171__py3-none-any.whl → 2.0.204__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 (194) hide show
  1. adam/app_session.py +5 -10
  2. adam/apps.py +18 -4
  3. adam/batch.py +7 -7
  4. adam/checks/check_utils.py +3 -1
  5. adam/checks/disk.py +2 -3
  6. adam/columns/memory.py +3 -4
  7. adam/commands/__init__.py +15 -6
  8. adam/commands/alter_tables.py +26 -41
  9. adam/commands/app/__init__.py +0 -0
  10. adam/commands/{app_cmd.py → app/app.py} +2 -2
  11. adam/commands/{show → app}/show_app_actions.py +7 -15
  12. adam/commands/{show → app}/show_app_queues.py +1 -4
  13. adam/{utils_app.py → commands/app/utils_app.py} +9 -1
  14. adam/commands/audit/audit.py +9 -26
  15. adam/commands/audit/audit_repair_tables.py +5 -7
  16. adam/commands/audit/audit_run.py +1 -1
  17. adam/commands/audit/completions_l.py +15 -0
  18. adam/commands/audit/show_last10.py +2 -14
  19. adam/commands/audit/show_slow10.py +2 -13
  20. adam/commands/audit/show_top10.py +2 -11
  21. adam/commands/audit/utils_show_top10.py +15 -3
  22. adam/commands/bash/bash.py +1 -1
  23. adam/commands/bash/utils_bash.py +1 -1
  24. adam/commands/cassandra/__init__.py +0 -0
  25. adam/commands/cassandra/download_cassandra_log.py +45 -0
  26. adam/commands/cassandra/nodetool.py +64 -0
  27. adam/commands/cassandra/nodetool_commands.py +120 -0
  28. adam/commands/cassandra/restart_cluster.py +47 -0
  29. adam/commands/cassandra/restart_node.py +51 -0
  30. adam/commands/cassandra/restart_nodes.py +47 -0
  31. adam/commands/cassandra/rollout.py +88 -0
  32. adam/commands/cat.py +5 -19
  33. adam/commands/cd.py +7 -9
  34. adam/commands/check.py +10 -18
  35. adam/commands/cli_commands.py +6 -1
  36. adam/commands/{cp.py → clipboard_copy.py} +34 -36
  37. adam/commands/code.py +2 -2
  38. adam/commands/command.py +139 -22
  39. adam/commands/commands_utils.py +14 -12
  40. adam/commands/cql/alter_tables.py +66 -0
  41. adam/commands/cql/completions_c.py +29 -0
  42. adam/commands/cql/cqlsh.py +3 -7
  43. adam/commands/cql/utils_cql.py +23 -61
  44. adam/commands/debug/__init__.py +0 -0
  45. adam/commands/debug/debug.py +22 -0
  46. adam/commands/debug/debug_completes.py +35 -0
  47. adam/commands/debug/debug_timings.py +35 -0
  48. adam/commands/deploy/deploy_pg_agent.py +2 -2
  49. adam/commands/deploy/deploy_pod.py +2 -4
  50. adam/commands/deploy/undeploy_pg_agent.py +2 -2
  51. adam/commands/devices/device.py +40 -9
  52. adam/commands/devices/device_app.py +19 -29
  53. adam/commands/devices/device_auit_log.py +3 -3
  54. adam/commands/devices/device_cass.py +17 -23
  55. adam/commands/devices/device_export.py +12 -11
  56. adam/commands/devices/device_postgres.py +79 -63
  57. adam/commands/devices/devices.py +1 -1
  58. adam/commands/download_cassandra_log.py +45 -0
  59. adam/commands/download_file.py +47 -0
  60. adam/commands/export/clean_up_all_export_sessions.py +3 -3
  61. adam/commands/export/clean_up_export_sessions.py +7 -19
  62. adam/commands/export/completions_x.py +11 -0
  63. adam/commands/export/download_export_session.py +40 -0
  64. adam/commands/export/drop_export_database.py +6 -22
  65. adam/commands/export/drop_export_databases.py +3 -9
  66. adam/commands/export/export.py +1 -17
  67. adam/commands/export/export_databases.py +109 -32
  68. adam/commands/export/export_select.py +8 -55
  69. adam/commands/export/export_sessions.py +211 -0
  70. adam/commands/export/export_use.py +13 -16
  71. adam/commands/export/export_x_select.py +48 -0
  72. adam/commands/export/exporter.py +176 -167
  73. adam/commands/export/import_files.py +44 -0
  74. adam/commands/export/import_session.py +10 -6
  75. adam/commands/export/importer.py +24 -9
  76. adam/commands/export/importer_athena.py +114 -44
  77. adam/commands/export/importer_sqlite.py +45 -23
  78. adam/commands/export/show_column_counts.py +11 -20
  79. adam/commands/export/show_export_databases.py +5 -2
  80. adam/commands/export/show_export_session.py +6 -15
  81. adam/commands/export/show_export_sessions.py +4 -11
  82. adam/commands/export/utils_export.py +79 -27
  83. adam/commands/find_files.py +51 -0
  84. adam/commands/find_processes.py +76 -0
  85. adam/commands/generate_report.py +52 -0
  86. adam/commands/head.py +36 -0
  87. adam/commands/help.py +2 -2
  88. adam/commands/intermediate_command.py +6 -3
  89. adam/commands/login.py +3 -6
  90. adam/commands/ls.py +2 -2
  91. adam/commands/medusa/medusa_backup.py +13 -16
  92. adam/commands/medusa/medusa_restore.py +26 -37
  93. adam/commands/medusa/medusa_show_backupjobs.py +7 -7
  94. adam/commands/medusa/medusa_show_restorejobs.py +6 -6
  95. adam/commands/medusa/utils_medusa.py +15 -0
  96. adam/commands/nodetool.py +3 -8
  97. adam/commands/os/__init__.py +0 -0
  98. adam/commands/os/cat.py +36 -0
  99. adam/commands/os/download_file.py +47 -0
  100. adam/commands/os/find_files.py +51 -0
  101. adam/commands/os/find_processes.py +76 -0
  102. adam/commands/os/head.py +36 -0
  103. adam/commands/os/shell.py +41 -0
  104. adam/commands/param_get.py +10 -12
  105. adam/commands/param_set.py +7 -10
  106. adam/commands/postgres/completions_p.py +22 -0
  107. adam/commands/postgres/postgres.py +25 -40
  108. adam/commands/postgres/postgres_databases.py +269 -0
  109. adam/commands/postgres/utils_postgres.py +33 -20
  110. adam/commands/preview_table.py +4 -2
  111. adam/commands/pwd.py +4 -6
  112. adam/commands/reaper/reaper_forward.py +2 -2
  113. adam/commands/reaper/reaper_run_abort.py +4 -10
  114. adam/commands/reaper/reaper_runs.py +3 -3
  115. adam/commands/reaper/reaper_schedule_activate.py +12 -12
  116. adam/commands/reaper/reaper_schedule_start.py +7 -12
  117. adam/commands/reaper/reaper_schedule_stop.py +7 -12
  118. adam/commands/reaper/utils_reaper.py +13 -6
  119. adam/commands/repair/repair_log.py +1 -4
  120. adam/commands/repair/repair_run.py +3 -8
  121. adam/commands/repair/repair_scan.py +1 -6
  122. adam/commands/repair/repair_stop.py +1 -5
  123. adam/commands/restart_cluster.py +47 -0
  124. adam/commands/restart_node.py +51 -0
  125. adam/commands/restart_nodes.py +47 -0
  126. adam/commands/shell.py +9 -2
  127. adam/commands/show/show.py +4 -4
  128. adam/commands/show/show_adam.py +3 -3
  129. adam/commands/show/show_cassandra_repairs.py +5 -6
  130. adam/commands/show/show_cassandra_status.py +29 -29
  131. adam/commands/show/show_cassandra_version.py +1 -4
  132. adam/commands/show/{show_commands.py → show_cli_commands.py} +3 -6
  133. adam/commands/show/show_login.py +3 -9
  134. adam/commands/show/show_params.py +2 -5
  135. adam/commands/show/show_processes.py +15 -16
  136. adam/commands/show/show_storage.py +9 -8
  137. adam/config.py +4 -5
  138. adam/embedded_params.py +1 -1
  139. adam/log.py +4 -4
  140. adam/repl.py +26 -18
  141. adam/repl_commands.py +32 -20
  142. adam/repl_session.py +9 -1
  143. adam/repl_state.py +39 -10
  144. adam/sql/async_executor.py +44 -0
  145. adam/sql/lark_completer.py +286 -0
  146. adam/sql/lark_parser.py +604 -0
  147. adam/sql/qingl.lark +1076 -0
  148. adam/sql/sql_completer.py +4 -6
  149. adam/sql/sql_state_machine.py +25 -13
  150. adam/sso/authn_ad.py +2 -5
  151. adam/sso/authn_okta.py +2 -4
  152. adam/sso/cred_cache.py +2 -5
  153. adam/sso/idp.py +8 -11
  154. adam/utils.py +299 -105
  155. adam/utils_athena.py +18 -18
  156. adam/utils_audits.py +3 -7
  157. adam/utils_issues.py +2 -2
  158. adam/utils_k8s/app_clusters.py +4 -4
  159. adam/utils_k8s/app_pods.py +8 -6
  160. adam/utils_k8s/cassandra_clusters.py +16 -5
  161. adam/utils_k8s/cassandra_nodes.py +7 -6
  162. adam/utils_k8s/custom_resources.py +11 -17
  163. adam/utils_k8s/jobs.py +7 -11
  164. adam/utils_k8s/k8s.py +14 -5
  165. adam/utils_k8s/kube_context.py +3 -6
  166. adam/{pod_exec_result.py → utils_k8s/pod_exec_result.py} +4 -4
  167. adam/utils_k8s/pods.py +98 -36
  168. adam/utils_k8s/statefulsets.py +5 -2
  169. adam/utils_local.py +42 -0
  170. adam/utils_repl/appendable_completer.py +6 -0
  171. adam/utils_repl/repl_completer.py +45 -2
  172. adam/utils_repl/state_machine.py +3 -3
  173. adam/utils_sqlite.py +58 -30
  174. adam/version.py +1 -1
  175. {kaqing-2.0.171.dist-info → kaqing-2.0.204.dist-info}/METADATA +1 -1
  176. kaqing-2.0.204.dist-info/RECORD +277 -0
  177. kaqing-2.0.204.dist-info/top_level.txt +2 -0
  178. teddy/__init__.py +0 -0
  179. teddy/lark_parser.py +436 -0
  180. teddy/lark_parser2.py +618 -0
  181. adam/commands/cql/cql_completions.py +0 -33
  182. adam/commands/export/export_handlers.py +0 -71
  183. adam/commands/export/export_select_x.py +0 -54
  184. adam/commands/logs.py +0 -37
  185. adam/commands/postgres/postgres_context.py +0 -274
  186. adam/commands/postgres/psql_completions.py +0 -10
  187. adam/commands/report.py +0 -61
  188. adam/commands/restart.py +0 -60
  189. kaqing-2.0.171.dist-info/RECORD +0 -236
  190. kaqing-2.0.171.dist-info/top_level.txt +0 -1
  191. /adam/commands/{app_ping.py → app/app_ping.py} +0 -0
  192. /adam/commands/{show → app}/show_app_id.py +0 -0
  193. {kaqing-2.0.171.dist-info → kaqing-2.0.204.dist-info}/WHEEL +0 -0
  194. {kaqing-2.0.171.dist-info → kaqing-2.0.204.dist-info}/entry_points.txt +0 -0
@@ -1,26 +1,38 @@
1
+ from collections.abc import Callable
2
+ from datetime import datetime
1
3
  import os
2
4
  import boto3
3
5
 
4
- from adam.commands.export.utils_export import ExportTableStatus
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
5
9
  from adam.config import Config
6
- from adam.utils import lines_to_tabular, log, log2, ing
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
7
13
  from adam.utils_athena import Athena
8
- from adam.utils_k8s.statefulsets import StatefulSets
9
14
  from adam.utils_sqlite import SQLite
10
15
 
11
16
  LIKE = 'e%_%'
12
17
 
13
18
  class ExportDatabases:
14
- def run_query(query: str, database: str, show_query=False) -> int:
19
+ def run_query(query: str, database: str, show_query=False, output: Callable[[str], str] = None) -> int:
15
20
  cnt: int = 0
16
21
 
17
22
  if show_query:
18
23
  log2(query)
19
24
 
25
+ log_file = None
20
26
  if database.startswith('s'):
21
- cnt += SQLite.run_query(query, database=database)
27
+ cnt0, log_file = SQLite.run_query(query, database=database, output=output)
28
+ cnt += cnt0
22
29
  else:
23
- cnt += Athena.run_query(query, database=database)
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}')
24
36
 
25
37
  return cnt
26
38
 
@@ -47,15 +59,13 @@ class ExportDatabases:
47
59
  dbs = SQLite.database_names(db)
48
60
  if dbs:
49
61
  with ing(f'Droping {len(dbs)} SQLite databases'):
50
- try:
62
+ with log_exc():
51
63
  for db in dbs:
52
64
  file_path = f'{SQLite.local_db_dir()}/{db}'
53
65
  try:
54
66
  os.remove(file_path)
55
67
  except OSError as e:
56
68
  pass
57
- except:
58
- pass
59
69
 
60
70
  return dbs
61
71
 
@@ -65,49 +75,35 @@ class ExportDatabases:
65
75
  with ing(f'Droping {len(dbs)} Athena databases'):
66
76
  for db in dbs:
67
77
  query = f'DROP DATABASE {db} CASCADE'
68
- if Config().is_debug():
69
- log2(query)
78
+ debug(query)
70
79
  Athena.query(query)
71
80
 
72
81
  with ing(f'Deleting s3 folder: export'):
73
- try:
82
+ with log_exc():
74
83
  if not db:
75
84
  db = ''
76
85
 
77
86
  s3 = boto3.resource('s3')
78
87
  bucket = s3.Bucket(Config().get('export.bucket', 'c3.ops--qing'))
79
88
  bucket.objects.filter(Prefix=f'export/{db}').delete()
80
- except:
81
- pass
82
89
 
83
90
  return dbs
84
91
 
85
- def display_export_db(export_session: str):
86
- if not export_session:
92
+ def show_database(database: str):
93
+ if not database:
87
94
  return
88
95
 
89
- Athena.clear_cache()
96
+ ExportDatabases.clear_cache()
90
97
 
91
98
  keyspaces = {}
92
- for table in ExportDatabases.table_names(export_session):
99
+ for table in ExportDatabases.table_names(database):
93
100
  keyspace = table.split('.')[0]
94
101
  if keyspace in keyspaces:
95
102
  keyspaces[keyspace] += 1
96
103
  else:
97
104
  keyspaces[keyspace] = 1
98
105
 
99
- log(lines_to_tabular([f'{k},{v}' for k, v in keyspaces.items()], header='SCHEMA,# of TABLES', separator=','))
100
-
101
- def disply_export_session(sts: str, pod: str, namespace: str, session: str):
102
- if not pod:
103
- pod = StatefulSets.pod_names(sts, namespace)[0]
104
-
105
- if not pod:
106
- return
107
-
108
- tables, _ = ExportTableStatus.from_session(sts, pod, namespace, session)
109
- log()
110
- log(lines_to_tabular([f'{table.keyspace}\t{table.table}\t{table.target_table}\t{"export_completed_pending_import" if table.status == "pending_import" else table.status}' for table in tables], header='KEYSPACE\tTABLE\tTARGET_TABLE\tSTATUS', separator='\t'))
106
+ tabulize(keyspaces.items(), lambda a: f'{a[0]},{a[1]}', header='SCHEMA,# of TABLES', separator=',')
111
107
 
112
108
  def database_names():
113
109
  return ExportDatabases.copy_database_names() + ExportDatabases.export_database_names()
@@ -116,7 +112,8 @@ class ExportDatabases:
116
112
  return list({n.split('_')[0] for n in SQLite.database_names()})
117
113
 
118
114
  def export_database_names():
119
- return list({n.split('_')[0] for n in Athena.database_names(LIKE)})
115
+ with log_timing('ExportDatabases.Athena.database_names'):
116
+ return list({n.split('_')[0] for n in Athena.database_names(LIKE)})
120
117
 
121
118
  def database_names_with_keyspace_cnt(importer: str = None):
122
119
  r = {}
@@ -167,4 +164,84 @@ class ExportDatabases:
167
164
  if db.startswith('s'):
168
165
  return SQLite.database_names(prefix=f'{eprefix}_')
169
166
  else:
170
- return Athena.database_names(like=f'{eprefix}_%')
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)
@@ -1,12 +1,10 @@
1
1
  from adam.commands.command import Command
2
- from adam.commands.export.export_databases import ExportDatabases
2
+ from adam.commands.export.completions_x import completions_x
3
3
  from adam.repl_state import ReplState, RequiredState
4
- from adam.sql.sql_completer import SqlCompleter, SqlVariant
5
- from adam.utils import log2
6
- from adam.utils_athena import Athena
7
4
 
5
+ # No action body, only for a help entry and auto-completion
8
6
  class ExportSelect(Command):
9
- COMMAND = '.select'
7
+ COMMAND = 'select_on_x'
10
8
 
11
9
  # the singleton pattern
12
10
  def __new__(cls, *args, **kwargs):
@@ -23,59 +21,14 @@ class ExportSelect(Command):
23
21
  def required(self):
24
22
  return RequiredState.EXPORT_DB
25
23
 
26
- def run(self, cmd: str, state: ReplState):
27
- if not(args := self.args(cmd)):
28
- return super().run(cmd, state)
29
-
30
- with self.validate(args, state) as (args, state):
31
- if not state.export_session:
32
- if state.in_repl:
33
- if state.device == ReplState.C:
34
- log2("Select an export database first with 'use' command.")
35
- else:
36
- log2('cd to an export database first.')
37
- else:
38
- log2('* export database is missing.')
39
-
40
- Command.display_help()
41
-
42
- return 'command-missing'
43
-
44
- if not args:
45
- if state.in_repl:
46
- log2('Use a SQL statement.')
47
- else:
48
- log2('* SQL statement is missing.')
49
-
50
- Command.display_help()
51
-
52
- return 'command-missing'
53
-
54
- query = ' '.join(args)
55
-
56
- ExportDatabases.run_query(f'select {query}', database=state.export_session)
57
-
58
- return state
59
-
60
24
  def completion(self, state: ReplState):
61
- if not state.export_session:
25
+ if state.device != ReplState.X:
62
26
  return {}
63
27
 
64
- db = state.export_session
65
-
66
- # warm up the caches first time when x: drive is accessed
67
- ExportDatabases.table_names(db)
68
- Athena.column_names(database=db, function='export')
69
- Athena.column_names(partition_cols_only=True, database=db, function='export')
28
+ if state.export_session:
29
+ return completions_x(state)
70
30
 
71
- return {ExportSelect.COMMAND: SqlCompleter(
72
- lambda: ExportDatabases.table_names(db),
73
- dml='select',
74
- expandables={
75
- 'columns':lambda table: Athena.column_names(database=db, function='export'),
76
- },
77
- variant=SqlVariant.ATHENA
78
- )}
31
+ return {}
79
32
 
80
33
  def help(self, _: ReplState):
81
- return f'.<sql-select-statements>\t run queries on export database'
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)
@@ -1,9 +1,8 @@
1
+ from adam.commands import validate_args
1
2
  from adam.commands.command import Command
2
- from adam.commands.export.export_databases import ExportDatabases
3
+ from adam.commands.export.export_databases import export_db
3
4
  from adam.repl_state import ReplState
4
5
  from adam.utils import log2
5
- from adam.utils_athena import Athena
6
- from adam.utils_sqlite import SQLite
7
6
 
8
7
  class ExportUse(Command):
9
8
  COMMAND = 'use'
@@ -21,32 +20,30 @@ class ExportUse(Command):
21
20
  return ExportUse.COMMAND
22
21
 
23
22
  def required(self):
24
- return [ReplState.C, ReplState.X]
23
+ return [ReplState.C]
25
24
 
26
25
  def run(self, cmd: str, state: ReplState):
27
26
  if not(args := self.args(cmd)):
28
27
  return super().run(cmd, state)
29
28
 
30
29
  with self.validate(args, state) as (args, state):
31
- if not args:
32
- state.export_session = None
30
+ with validate_args(args, state, at_least=0) as session:
31
+ if not session:
32
+ state.export_session = None
33
33
 
34
- log2('Export database is unset.')
34
+ log2('Export database is unset.')
35
35
 
36
- return state
36
+ return state
37
37
 
38
- state.export_session = args[0]
39
- if state.export_session.startswith('e'):
40
- Athena.clear_cache()
41
- else:
42
- SQLite.clear_cache()
38
+ state.export_session = session
43
39
 
44
- ExportDatabases.display_export_db(state.export_session)
40
+ with export_db(state) as dbs:
41
+ dbs.show_database()
45
42
 
46
- return state
43
+ return state
47
44
 
48
45
  def completion(self, state: ReplState):
49
- return super().completion(state, {n: None for n in ExportDatabases.database_names()})
46
+ return {}
50
47
 
51
48
  def help(self, _: ReplState):
52
49
  return f'{ExportUse.COMMAND} <export-database-name>\t use export database'
@@ -0,0 +1,48 @@
1
+ from adam.commands import extract_trailing_options, validate_args
2
+ from adam.commands.command import Command
3
+ from adam.commands.export.completions_x import completions_x
4
+ from adam.commands.export.export_databases import export_db
5
+ from adam.repl_state import ReplState, RequiredState
6
+
7
+ class ExportXSelect(Command):
8
+ COMMAND = 'xelect'
9
+
10
+ # the singleton pattern
11
+ def __new__(cls, *args, **kwargs):
12
+ if not hasattr(cls, 'instance'): cls.instance = super(ExportXSelect, cls).__new__(cls)
13
+
14
+ return cls.instance
15
+
16
+ def __init__(self, successor: Command=None):
17
+ super().__init__(successor)
18
+
19
+ def command(self):
20
+ return ExportXSelect.COMMAND
21
+
22
+ def required(self):
23
+ return RequiredState.EXPORT_DB
24
+
25
+ def run(self, cmd: str, state: ReplState):
26
+ if not(args := self.args(cmd)):
27
+ return super().run(cmd, state)
28
+
29
+ with self.validate(args, state) as (args, state):
30
+ with extract_trailing_options(args, '&') as (args, backgrounded):
31
+ with validate_args(args, state, name='SQL statement') as query:
32
+ with export_db(state) as dbs:
33
+ dbs.sql(f'select {query}', backgrounded=backgrounded)
34
+
35
+ return state
36
+
37
+ def completion(self, state: ReplState):
38
+ if state.device != ReplState.C:
39
+ return {}
40
+
41
+ if not state.export_session:
42
+ return {}
43
+
44
+ # add only xelect completions to c: drive from lark
45
+ return {ExportXSelect.COMMAND: completions_x(state)[ExportXSelect.COMMAND]}
46
+
47
+ def help(self, _: ReplState):
48
+ return f'xelect...\t run queries on export database'