kaqing 2.0.145__py3-none-any.whl → 2.0.172__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.

Potentially problematic release.


This version of kaqing might be problematic. Click here for more details.

Files changed (172) hide show
  1. adam/__init__.py +0 -2
  2. adam/app_session.py +8 -11
  3. adam/batch.py +3 -3
  4. adam/checks/check_utils.py +14 -46
  5. adam/checks/cpu.py +7 -1
  6. adam/checks/cpu_metrics.py +52 -0
  7. adam/checks/disk.py +2 -3
  8. adam/columns/columns.py +3 -1
  9. adam/columns/cpu.py +3 -1
  10. adam/columns/cpu_metrics.py +22 -0
  11. adam/columns/memory.py +3 -4
  12. adam/commands/__init__.py +18 -0
  13. adam/commands/alter_tables.py +43 -47
  14. adam/commands/audit/audit.py +22 -23
  15. adam/commands/audit/audit_repair_tables.py +14 -17
  16. adam/commands/audit/audit_run.py +15 -23
  17. adam/commands/audit/show_last10.py +10 -13
  18. adam/commands/audit/show_slow10.py +10 -13
  19. adam/commands/audit/show_top10.py +10 -13
  20. adam/commands/audit/utils_show_top10.py +2 -3
  21. adam/commands/bash/__init__.py +5 -0
  22. adam/commands/bash/bash.py +7 -104
  23. adam/commands/bash/utils_bash.py +16 -0
  24. adam/commands/cat.py +13 -19
  25. adam/commands/cd.py +8 -10
  26. adam/commands/check.py +20 -21
  27. adam/commands/cli_commands.py +2 -3
  28. adam/commands/code.py +20 -23
  29. adam/commands/command.py +120 -39
  30. adam/commands/commands_utils.py +8 -17
  31. adam/commands/cp.py +33 -39
  32. adam/commands/cql/cql_completions.py +9 -4
  33. adam/commands/cql/cqlsh.py +10 -30
  34. adam/commands/cql/{cql_utils.py → utils_cql.py} +149 -15
  35. adam/commands/deploy/code_start.py +7 -10
  36. adam/commands/deploy/code_stop.py +4 -21
  37. adam/commands/deploy/code_utils.py +3 -3
  38. adam/commands/deploy/deploy.py +4 -27
  39. adam/commands/deploy/deploy_frontend.py +14 -17
  40. adam/commands/deploy/deploy_pg_agent.py +2 -5
  41. adam/commands/deploy/deploy_pod.py +64 -68
  42. adam/commands/deploy/undeploy.py +4 -27
  43. adam/commands/deploy/undeploy_frontend.py +4 -7
  44. adam/commands/deploy/undeploy_pg_agent.py +4 -7
  45. adam/commands/deploy/undeploy_pod.py +9 -12
  46. adam/commands/devices/device.py +93 -2
  47. adam/commands/devices/device_app.py +37 -10
  48. adam/commands/devices/device_auit_log.py +8 -2
  49. adam/commands/devices/device_cass.py +47 -7
  50. adam/commands/devices/device_export.py +2 -2
  51. adam/commands/devices/device_postgres.py +41 -6
  52. adam/commands/exit.py +1 -4
  53. adam/commands/export/clean_up_all_export_sessions.py +37 -0
  54. adam/commands/export/clean_up_export_sessions.py +18 -7
  55. adam/commands/export/drop_export_database.py +15 -18
  56. adam/commands/export/drop_export_databases.py +6 -9
  57. adam/commands/export/export.py +8 -38
  58. adam/commands/export/export_databases.py +16 -12
  59. adam/commands/export/export_handlers.py +71 -0
  60. adam/commands/export/export_select.py +33 -24
  61. adam/commands/export/export_use.py +12 -15
  62. adam/commands/export/exporter.py +37 -48
  63. adam/commands/export/import_session.py +4 -32
  64. adam/commands/export/importer_athena.py +4 -7
  65. adam/commands/export/importer_sqlite.py +19 -27
  66. adam/commands/export/show_column_counts.py +13 -22
  67. adam/commands/export/show_export_databases.py +3 -6
  68. adam/commands/export/show_export_session.py +10 -13
  69. adam/commands/export/show_export_sessions.py +8 -11
  70. adam/commands/export/utils_export.py +24 -1
  71. adam/commands/intermediate_command.py +49 -0
  72. adam/commands/issues.py +11 -43
  73. adam/commands/kubectl.py +3 -6
  74. adam/commands/login.py +22 -24
  75. adam/commands/logs.py +3 -6
  76. adam/commands/ls.py +8 -9
  77. adam/commands/medusa/medusa.py +4 -22
  78. adam/commands/medusa/medusa_backup.py +20 -24
  79. adam/commands/medusa/medusa_restore.py +29 -33
  80. adam/commands/medusa/medusa_show_backupjobs.py +14 -18
  81. adam/commands/medusa/medusa_show_restorejobs.py +11 -18
  82. adam/commands/nodetool.py +6 -15
  83. adam/commands/param_get.py +11 -12
  84. adam/commands/param_set.py +9 -10
  85. adam/commands/postgres/postgres.py +29 -37
  86. adam/commands/postgres/postgres_context.py +47 -23
  87. adam/commands/postgres/postgres_ls.py +4 -8
  88. adam/commands/postgres/postgres_preview.py +5 -9
  89. adam/commands/postgres/psql_completions.py +1 -1
  90. adam/commands/postgres/utils_postgres.py +66 -0
  91. adam/commands/preview_table.py +5 -44
  92. adam/commands/pwd.py +13 -16
  93. adam/commands/reaper/reaper.py +4 -27
  94. adam/commands/reaper/reaper_forward.py +48 -55
  95. adam/commands/reaper/reaper_forward_session.py +6 -0
  96. adam/commands/reaper/reaper_forward_stop.py +10 -16
  97. adam/commands/reaper/reaper_restart.py +7 -14
  98. adam/commands/reaper/reaper_run_abort.py +11 -30
  99. adam/commands/reaper/reaper_runs.py +42 -57
  100. adam/commands/reaper/reaper_runs_abort.py +29 -49
  101. adam/commands/reaper/reaper_schedule_activate.py +11 -30
  102. adam/commands/reaper/reaper_schedule_start.py +10 -29
  103. adam/commands/reaper/reaper_schedule_stop.py +10 -29
  104. adam/commands/reaper/reaper_schedules.py +4 -14
  105. adam/commands/reaper/reaper_status.py +8 -16
  106. adam/commands/reaper/utils_reaper.py +196 -0
  107. adam/commands/repair/repair.py +4 -22
  108. adam/commands/repair/repair_log.py +5 -11
  109. adam/commands/repair/repair_run.py +27 -34
  110. adam/commands/repair/repair_scan.py +32 -38
  111. adam/commands/repair/repair_stop.py +5 -11
  112. adam/commands/report.py +27 -29
  113. adam/commands/restart.py +25 -26
  114. adam/commands/rollout.py +19 -24
  115. adam/commands/shell.py +10 -4
  116. adam/commands/show/show.py +10 -26
  117. adam/commands/show/show_cassandra_repairs.py +35 -0
  118. adam/commands/show/show_cassandra_status.py +32 -43
  119. adam/commands/show/show_cassandra_version.py +5 -18
  120. adam/commands/show/show_commands.py +19 -24
  121. adam/commands/show/show_host.py +1 -1
  122. adam/commands/show/show_login.py +20 -27
  123. adam/commands/show/show_processes.py +15 -19
  124. adam/commands/show/show_storage.py +10 -20
  125. adam/commands/watch.py +26 -29
  126. adam/config.py +4 -16
  127. adam/embedded_params.py +1 -1
  128. adam/log.py +4 -4
  129. adam/pod_exec_result.py +3 -3
  130. adam/repl.py +29 -32
  131. adam/repl_commands.py +11 -11
  132. adam/repl_state.py +52 -26
  133. adam/sql/sql_completer.py +4 -6
  134. adam/sql/sql_state_machine.py +21 -14
  135. adam/sso/authn_ad.py +6 -8
  136. adam/sso/authn_okta.py +4 -6
  137. adam/sso/cred_cache.py +3 -5
  138. adam/sso/idp.py +9 -12
  139. adam/utils.py +393 -33
  140. adam/utils_athena.py +14 -13
  141. adam/utils_audits.py +12 -12
  142. adam/utils_issues.py +32 -0
  143. adam/utils_k8s/app_clusters.py +13 -18
  144. adam/utils_k8s/app_pods.py +2 -0
  145. adam/utils_k8s/cassandra_clusters.py +21 -18
  146. adam/utils_k8s/custom_resources.py +16 -17
  147. adam/utils_k8s/ingresses.py +2 -2
  148. adam/utils_k8s/jobs.py +7 -11
  149. adam/utils_k8s/k8s.py +87 -0
  150. adam/utils_k8s/pods.py +14 -76
  151. adam/utils_k8s/secrets.py +4 -4
  152. adam/utils_k8s/service_accounts.py +5 -4
  153. adam/utils_k8s/services.py +2 -2
  154. adam/utils_k8s/statefulsets.py +1 -12
  155. adam/utils_repl/state_machine.py +3 -3
  156. adam/utils_sqlite.py +78 -42
  157. adam/version.py +1 -1
  158. {kaqing-2.0.145.dist-info → kaqing-2.0.172.dist-info}/METADATA +1 -1
  159. kaqing-2.0.172.dist-info/RECORD +230 -0
  160. adam/commands/app.py +0 -67
  161. adam/commands/app_ping.py +0 -44
  162. adam/commands/export/clean_up_export_session.py +0 -53
  163. adam/commands/postgres/postgres_utils.py +0 -31
  164. adam/commands/reaper/reaper_session.py +0 -159
  165. adam/commands/show/show_app_actions.py +0 -56
  166. adam/commands/show/show_app_id.py +0 -47
  167. adam/commands/show/show_app_queues.py +0 -45
  168. adam/commands/show/show_repairs.py +0 -47
  169. kaqing-2.0.145.dist-info/RECORD +0 -227
  170. {kaqing-2.0.145.dist-info → kaqing-2.0.172.dist-info}/WHEEL +0 -0
  171. {kaqing-2.0.145.dist-info → kaqing-2.0.172.dist-info}/entry_points.txt +0 -0
  172. {kaqing-2.0.145.dist-info → kaqing-2.0.172.dist-info}/top_level.txt +0 -0
adam/commands/command.py CHANGED
@@ -2,10 +2,10 @@ from abc import abstractmethod
2
2
  import copy
3
3
  import subprocess
4
4
  import sys
5
+ from typing import Union
5
6
 
6
- from adam.commands.command_helpers import ClusterCommandHelper
7
7
  from adam.repl_state import ReplState, RequiredState
8
- from adam.utils import is_lambda, lines_to_tabular, log, log2
8
+ from adam.utils import is_lambda
9
9
 
10
10
  repl_cmds: list['Command'] = []
11
11
 
@@ -44,7 +44,10 @@ class Command:
44
44
  def required(self) -> RequiredState:
45
45
  return None
46
46
 
47
- def validate_state(self, state: ReplState, show_err=True):
47
+ def validate(self, args: list[str], state: ReplState, apply = True):
48
+ return ValidateHandler(self, args, state, apply = apply)
49
+
50
+ def validate_state(self, state: ReplState, show_err = True):
48
51
  return state.validate(self.required(), show_err=show_err)
49
52
 
50
53
  def help(self, _: ReplState) -> str:
@@ -93,17 +96,50 @@ class Command:
93
96
  args.extend(['--help'])
94
97
  subprocess.run(args)
95
98
 
96
- def extract_options(args: list[str], names: list[str]):
97
- found: list[str] = []
99
+ def extract_options(args: list[str], trailing: Union[str, list[str]] = [], sequence: list[str] = [], options: list[str] = []):
100
+ found_options: list[str] = []
101
+ found_trailing = None
102
+ found_sequence = None
103
+
104
+ if trailing is None:
105
+ trailing = []
106
+ elif isinstance(trailing, str):
107
+ trailing = [trailing]
108
+
109
+ if options is None:
110
+ options = []
111
+ elif isinstance(options, str):
112
+ options = [options]
113
+
114
+ if args and trailing:
115
+ while args[-1] in trailing:
116
+ found_trailing = True
117
+ args = args[:-1]
118
+
119
+ if args and sequence:
120
+ args, found_sequence = Command.extract_option_sequence(args, sequence)
98
121
 
99
122
  new_args: list[str] = []
100
- for arg in args:
101
- if arg in names:
102
- found.append(arg)
103
- else:
104
- new_args.append(arg)
123
+ if args:
124
+ for arg in args:
125
+ if arg in options:
126
+ found_options.append(arg)
127
+ else:
128
+ new_args.append(arg)
129
+
130
+ return new_args, found_trailing, found_sequence, found_options
131
+
132
+ def extract_option_sequence(args, sequence):
133
+ len_sub = len(sequence)
134
+ len_main = len(args)
135
+ for i in range(len_main - len_sub + 1):
136
+ if args[i:i+len_sub] == sequence:
137
+ new_args = copy.copy(args)
138
+ del new_args[i:i+len_sub]
105
139
 
106
- return new_args, found
140
+ return new_args, True
141
+
142
+ return new_args, False
107
143
 
108
144
  def print_chain(cmd: 'Command'):
109
145
  print(f'{cmd.command()}', end = '')
@@ -112,31 +148,76 @@ class Command:
112
148
  cmd = s
113
149
  print()
114
150
 
115
- def intermediate_run(self, cmd: str, state: ReplState, args: list[str], cmds: list['Command'], separator='\t', display_help=True):
116
- state, _ = self.apply_state(args, state)
117
-
118
- if state.in_repl:
119
- if display_help:
120
- log(lines_to_tabular([c.help(state) for c in cmds], separator=separator))
121
-
122
- return 'command-missing'
123
- else:
124
- # head with the Chain of Responsibility pattern
125
- cmds = Command.chain(cmds)
126
- if not cmds.run(cmd, state):
127
- if display_help:
128
- log2('* Command is missing.')
129
- Command.display_help()
130
- return 'command-missing'
131
-
132
- return state
133
-
134
- def intermediate_help(super_help: str, cmd: str, cmd_list: list['Command'], separator='\t', show_cluster_help=False):
135
- log(super_help)
136
- log()
137
- log('Sub-Commands:')
138
-
139
- log(lines_to_tabular([c.help(ReplState()).replace(f'{cmd} ', ' ', 1) for c in cmd_list], separator=separator))
140
- if show_cluster_help:
141
- log()
142
- ClusterCommandHelper.cluster_help()
151
+ class InvalidState(Exception):
152
+ def __init__(self, state: ReplState):
153
+ super().__init__(f'Invalid state')
154
+
155
+ class ValidateHandler:
156
+ def __init__(self, cmd: Command, args: list[str], state: ReplState, apply = True):
157
+ self.cmd = cmd
158
+ self.args = args
159
+ self.state = state
160
+ self.apply = apply
161
+
162
+ def __enter__(self) -> tuple[list[str], ReplState]:
163
+ state = self.state
164
+ args = self.args
165
+ if self.apply:
166
+ state, args = self.cmd.apply_state(args, state)
167
+
168
+ if not self.cmd.validate_state(state):
169
+ raise InvalidState(state)
170
+
171
+ return args, state
172
+
173
+ def __exit__(self, exc_type, exc_val, exc_tb):
174
+ return False
175
+
176
+ class ExtractOptionsHandler:
177
+ def __init__(self, args: list[str], options: list[str] = None):
178
+ self.args = args
179
+ self.options = options
180
+
181
+ def __enter__(self) -> tuple[list[str], list[str]]:
182
+ args, _, _, options = Command.extract_options(self.args, options=self.options)
183
+ return args, options
184
+
185
+ def __exit__(self, exc_type, exc_val, exc_tb):
186
+ return False
187
+
188
+ class ExtractTrailingOptionsHandler:
189
+ def __init__(self, args: list[str], trailing: list[str] = None):
190
+ self.args = args
191
+ self.trailing = trailing
192
+
193
+ def __enter__(self) -> tuple[list[str], list[str]]:
194
+ args, trailing, _, _ = Command.extract_options(self.args, trailing=self.trailing)
195
+ return args, trailing
196
+
197
+ def __exit__(self, exc_type, exc_val, exc_tb):
198
+ return False
199
+
200
+ class ExtractAllOptionsHandler:
201
+ def __init__(self, args: list[str], trailing: list[str] = None, sequence: list[str] = None, options: list[str] = None):
202
+ self.args = args
203
+ self.trailing = trailing
204
+ self.sequence = sequence
205
+ self.options = options
206
+
207
+ def __enter__(self) -> tuple[list[str], list[str]]:
208
+ return Command.extract_options(self.args, trailing=self.trailing, sequence=self.sequence, options=self.options)
209
+
210
+ def __exit__(self, exc_type, exc_val, exc_tb):
211
+ return False
212
+
213
+ class ExtractSequenceOptionsHandler:
214
+ def __init__(self, args: list[str], sequence: list[str]):
215
+ self.args = args
216
+ self.sequence = sequence
217
+
218
+ def __enter__(self) -> tuple[list[str], list[str]]:
219
+ args, _, sequence, _ = Command.extract_options(self.args, sequence=self.sequence)
220
+ return args, sequence
221
+
222
+ def __exit__(self, exc_type, exc_val, exc_tb):
223
+ return False
@@ -1,10 +1,9 @@
1
- from concurrent.futures import ThreadPoolExecutor
2
1
  from kubernetes import client
3
2
  from typing import List
4
3
 
5
4
  from adam.checks.check_utils import run_checks
6
5
  from adam.columns.columns import Columns, collect_checks
7
- from adam.commands.issues import Issues
6
+ from adam.utils_issues import IssuesUtils
8
7
  from adam.utils_k8s.cassandra_nodes import CassandraNodes
9
8
  from adam.utils_k8s.pods import Pods
10
9
  from adam.utils_k8s.statefulsets import StatefulSets
@@ -20,18 +19,10 @@ def show_pods(pods: List[client.V1Pod], ns: str, show_namespace = True, show_hos
20
19
  if show_host_id:
21
20
  names = [pod.metadata.name for pod in pods]
22
21
 
23
- def get_host_id_with_pod(pod, ns):
24
- return (CassandraNodes.get_host_id(pod, ns), pod)
25
-
26
- def body(executor: ThreadPoolExecutor, pod, ns, show_out):
27
- if executor:
28
- return executor.submit(get_host_id_with_pod, pod, ns)
29
-
30
- id = CassandraNodes.get_host_id(pod, ns)
31
-
32
- return (id, pod)
33
-
34
- host_ids_by_pod = {pod: id for id, pod in Pods.on_pods(names, ns, body, action='get-host-id', show_out=False)}
22
+ msg = 'd`Retrieving|Retrived {size} host ids'
23
+ with Pods.parallelize(names, msg=msg, action = 'get-host-id') as exec:
24
+ host_pods = exec.map(lambda pod: (CassandraNodes.get_host_id(pod, ns), pod))
25
+ host_ids_by_pod = {pod: id for id, pod in host_pods}
35
26
 
36
27
  def line(pod: client.V1Pod):
37
28
  pod_cnt = len(pod.status.container_statuses)
@@ -70,10 +61,10 @@ def show_rollout(sts: str, ns: str):
70
61
  else:
71
62
  log2(f'Cluster has completed rollout {d} ago.')
72
63
 
73
- def show_table(state: ReplState, pods: list[str], cols: str, header: str, show_output=False):
64
+ def show_table(state: ReplState, pods: list[str], cols: str, header: str, show_out=False):
74
65
  columns = Columns.create_columns(cols)
75
66
 
76
- results = run_checks(cluster=state.sts, pod=state.pod, namespace=state.namespace, checks=collect_checks(columns), show_output=show_output)
67
+ results = run_checks(cluster=state.sts, pod=state.pod, namespace=state.namespace, checks=collect_checks(columns), show_out=show_out)
77
68
 
78
69
  def line(pod_name: str):
79
70
  cells = [c.pod_value(results, pod_name) for c in columns]
@@ -84,4 +75,4 @@ def show_table(state: ReplState, pods: list[str], cols: str, header: str, show_o
84
75
 
85
76
  log(lines_to_tabular(lines, header, separator=','))
86
77
 
87
- Issues.show(results, state.in_repl)
78
+ IssuesUtils.show(results, state.in_repl)
adam/commands/cp.py CHANGED
@@ -29,47 +29,41 @@ class ClipboardCopy(Command):
29
29
  if not(args := self.args(cmd)):
30
30
  return super().run(cmd, state)
31
31
 
32
- state, args = self.apply_state(args, state)
33
- if not self.validate_state(state):
34
- return state
35
-
36
- if len(args) < 1:
37
- if state.in_repl:
38
- log2('Key is required.')
39
- log2()
40
- log2('Keys:')
41
- log2(lines_to_tabular([f'{k},{v}' for k, v in CliCommands.values(state, collapse=True).items()], separator=','))
42
- else:
43
- log2('* Key is missing.')
44
- Command.display_help()
45
-
46
- return 'command-missing'
47
-
48
- key = args[0]
49
- if not key in CliCommands.values(state):
50
- if state.in_repl:
51
- log2('Key is required.')
52
- log2()
53
- log2('Keys:')
54
- log2(lines_to_tabular([f'{k},{v}' for k, v in CliCommands.values(state, collapse=True).items()], separator=','))
55
- else:
56
- log2('* Invalid key')
57
- Command.display_help()
58
-
59
- return 'command-invalid'
60
-
61
- value = CliCommands.values(state)[key]
62
- pyperclip.copy(value)
63
- log2('The following line has been copied to clipboard. Use <Ctrl-V> to use it.')
64
- log2(f' {value}')
65
-
66
- return 'value-copied'
32
+ with self.validate(args, state) as (args, state):
33
+ if len(args) < 1:
34
+ if state.in_repl:
35
+ log2('Key is required.')
36
+ log2()
37
+ log2('Keys:')
38
+ log2(lines_to_tabular([f'{k},{v}' for k, v in CliCommands.values(state, collapse=True).items()], separator=','))
39
+ else:
40
+ log2('* Key is missing.')
41
+ Command.display_help()
42
+
43
+ return 'command-missing'
44
+
45
+ key = args[0]
46
+ if not key in CliCommands.values(state):
47
+ if state.in_repl:
48
+ log2('Key is required.')
49
+ log2()
50
+ log2('Keys:')
51
+ log2(lines_to_tabular([f'{k},{v}' for k, v in CliCommands.values(state, collapse=True).items()], separator=','))
52
+ else:
53
+ log2('* Invalid key')
54
+ Command.display_help()
55
+
56
+ return 'command-invalid'
57
+
58
+ value = CliCommands.values(state)[key]
59
+ pyperclip.copy(value)
60
+ log2('The following line has been copied to clipboard. Use <Ctrl-V> to use it.')
61
+ log2(f' {value}')
62
+
63
+ return 'value-copied'
67
64
 
68
65
  def completion(self, state: ReplState):
69
- if state.sts:
70
- return {ClipboardCopy.COMMAND: {key: None for key in CliCommands.values(state).keys()}}
71
-
72
- return {}
66
+ return super().completion(state, lambda: {key: None for key in CliCommands.values(state).keys()})
73
67
 
74
68
  def help(self, _: ReplState):
75
69
  return f"{ClipboardCopy.COMMAND} <key>\t copy a value to clipboard for conveninence"
@@ -1,16 +1,21 @@
1
- from adam.commands.cql.cql_utils import cassandra_keyspaces, cassandra_table_names
1
+ import time
2
+ from adam.commands.cql.utils_cql import cassandra_keyspaces, cassandra_table_names
2
3
  from adam.commands.export.exporter import Exporter
3
4
  from adam.commands.export.export_databases import ExportDatabases
4
5
  from adam.config import Config
5
6
  from adam.repl_state import ReplState
6
7
  from adam.sql.sql_completer import SqlCompleter, SqlVariant
8
+ from adam.utils import log_timing
7
9
 
8
10
  def cql_completions(state: ReplState) -> dict[str, any]:
9
11
  ps = Config().get('cql.alter-tables.gc-grace-periods', '3600,86400,864000,7776000').split(',')
10
12
  # warm up caches
11
- cassandra_keyspaces(state)
12
- cassandra_table_names(state)
13
- ExportDatabases.database_names()
13
+ with log_timing('cassandra_keyspaces'):
14
+ cassandra_keyspaces(state)
15
+ with log_timing('cassandra_table_names'):
16
+ cassandra_table_names(state)
17
+ with log_timing('ExportDatabases.database_names'):
18
+ ExportDatabases.database_names()
14
19
 
15
20
  expandables = {
16
21
  'keyspaces': lambda: cassandra_keyspaces(state),
@@ -1,12 +1,13 @@
1
1
  import click
2
2
 
3
+ from adam.commands import extract_trailing_options
3
4
  from adam.commands.command import Command
4
5
  from adam.commands.command_helpers import ClusterOrPodCommandHelper
5
6
  from adam.commands.cql.cql_completions import cql_completions
7
+ from adam.commands.cql.utils_cql import cassandra
6
8
  from adam.utils_k8s.statefulsets import StatefulSets
7
- from .cql_utils import run_cql
8
9
  from adam.repl_state import ReplState, RequiredState
9
- from adam.utils import log, log2
10
+ from adam.utils import log
10
11
 
11
12
  class Cqlsh(Command):
12
13
  COMMAND = 'cql'
@@ -30,32 +31,10 @@ class Cqlsh(Command):
30
31
  if not(args := self.args(cmd)):
31
32
  return super().run(cmd, state)
32
33
 
33
- state, args = self.apply_state(args, state)
34
- if not self.validate_state(state):
35
- return state
36
-
37
- background = False
38
- opts = []
39
- cqls = []
40
- for index, arg in enumerate(args):
41
- if arg.startswith('--'):
42
- opts.append(arg)
43
- elif index == len(args) -1 and arg == '&':
44
- background = True
45
- elif arg != '-e':
46
- cqls.append(arg)
47
- if not cqls:
48
- if state.in_repl:
49
- log2('Please enter cql statement. e.g. select host_id from system.local')
50
- else:
51
- log2('* CQL statement is missing.')
52
- log2()
53
- Command.display_help()
54
-
55
- return 'no-cql'
56
-
57
- cql = ' '.join(cqls)
58
- return run_cql(state, cql, opts, show_out=True, background=background)
34
+ with self.validate(args, state) as (args, state):
35
+ with extract_trailing_options(args, '&') as (args, backgrounded):
36
+ with cassandra(state) as pods:
37
+ pods.cql(args, background=backgrounded)
59
38
 
60
39
  def completion(self, state: ReplState) -> dict[str, any]:
61
40
  if state.device != state.C:
@@ -63,8 +42,9 @@ class Cqlsh(Command):
63
42
  return {}
64
43
 
65
44
  if state.sts or state.pod:
66
- return cql_completions(state) | \
67
- {f'@{p}': cql_completions(state) for p in StatefulSets.pod_names(state.sts, state.namespace)}
45
+ c = cql_completions(state)
46
+ return c | \
47
+ {f'@{p}': c for p in StatefulSets.pod_names(state.sts, state.namespace)}
68
48
 
69
49
  return {}
70
50
 
@@ -1,20 +1,23 @@
1
1
  import functools
2
2
  import re
3
+ from typing import Union
3
4
 
4
- from adam.config import Config
5
+ from adam.commands.command import Command
6
+ from adam.commands.commands_utils import show_table
5
7
  from adam.utils_k8s.cassandra_clusters import CassandraClusters
6
8
  from adam.utils_k8s.cassandra_nodes import CassandraNodes
7
9
  from adam.utils_k8s.secrets import Secrets
8
10
  from adam.pod_exec_result import PodExecResult
9
11
  from adam.repl_state import ReplState
10
- from adam.utils import log2
12
+ from adam.utils import log2, log_timing, wait_log
13
+ from adam.utils_k8s.statefulsets import StatefulSets
11
14
 
12
15
  @functools.lru_cache()
13
16
  def cassandra_keyspaces(state: ReplState, on_any=True):
14
17
  if state.pod:
15
- Config().wait_log(f'Inspecting Cassandra Keyspaces on {state.pod}...')
18
+ wait_log(f'Inspecting Cassandra Keyspaces on {state.pod}...')
16
19
  else:
17
- Config().wait_log(f'Inspecting Cassandra Keyspaces...')
20
+ wait_log(f'Inspecting Cassandra Keyspaces...')
18
21
 
19
22
  r: list[PodExecResult] = run_cql(state, 'describe keyspaces', show_out=False, on_any=on_any)
20
23
  if not r:
@@ -44,17 +47,21 @@ def table_spec(state: ReplState, table: str, on_any=False) -> 'TableSpec':
44
47
 
45
48
  return parse_cql_desc_table(r.stdout if state.pod else r[0].stdout)
46
49
 
47
- def run_cql(state: ReplState, cql: str, opts: list = [], show_out = False, use_single_quotes = False, on_any = False, background=False, log_file=None) -> list[PodExecResult]:
48
- user, pw = Secrets.get_user_pass(state.sts if state.sts else state.pod, state.namespace, secret_path='cql.secret')
49
- if use_single_quotes:
50
- command = f"cqlsh -u {user} -p {pw} {' '.join(opts)} -e '{cql}'"
51
- else:
52
- command = f'cqlsh -u {user} -p {pw} {" ".join(opts)} -e "{cql}"'
50
+ def run_cql(state: ReplState, cql: str, opts: list = [], show_out = False, show_query = False, use_single_quotes = False, on_any = False, background=False, log_file=None) -> list[PodExecResult]:
51
+ if show_query:
52
+ log2(cql)
53
53
 
54
- if state.pod:
55
- return CassandraNodes.exec(state.pod, state.namespace, command, show_out=show_out, background=background, log_file=log_file)
56
- else:
57
- return CassandraClusters.exec(state.sts, state.namespace, command, show_out=show_out, action='cql', on_any=on_any, background=background, log_file=log_file)
54
+ command = None
55
+ with log_timing('Secrets.get_user_pass'):
56
+ user, pw = Secrets.get_user_pass(state.sts if state.sts else state.pod, state.namespace, secret_path='cql.secret')
57
+ if use_single_quotes:
58
+ command = f"cqlsh -u {user} -p {pw} {' '.join(opts)} -e '{cql}'"
59
+ else:
60
+ command = f'cqlsh -u {user} -p {pw} {" ".join(opts)} -e "{cql}"'
61
+
62
+ with log_timing(cql):
63
+ with cassandra(state) as pods:
64
+ return pods.exec(command, action='cql', show_out=show_out, on_any=on_any, background=background, log_file=log_file)
58
65
 
59
66
  def parse_cql_desc_tables(out: str):
60
67
  # Keyspace data_endpoint_auth
@@ -206,4 +213,131 @@ def parse_cql_desc_table(out: str) -> TableSpec:
206
213
  if column.name in pkeys.keys():
207
214
  column.key_index = pkeys[column.name]
208
215
 
209
- return TableSpec(columns)
216
+ return TableSpec(columns)
217
+
218
+ class CqlShHandler:
219
+ def __init__(self, state: ReplState, opts: list = [], show_out = False, show_query = False, use_single_quotes = False, on_any = False, background=False):
220
+ self.state = state
221
+ self.opts = opts
222
+ self.show_out = show_out
223
+ self.show_query = show_query
224
+ self.use_single_quotes = use_single_quotes
225
+ self.on_any = on_any
226
+ self.backgroud = background
227
+
228
+ def __enter__(self):
229
+ return self.query
230
+
231
+ def __exit__(self, exc_type, exc_val, exc_tb):
232
+ return False
233
+
234
+ def query(self, args: list[str], log_file: str = None):
235
+ query: str = args
236
+ background = self.backgroud
237
+ show_out = self.show_out
238
+
239
+ if isinstance(query, list):
240
+ opts = []
241
+ cqls = []
242
+ for index, arg in enumerate(args):
243
+ if arg.startswith('--'):
244
+ opts.append(arg)
245
+ # elif index == len(args) -1 and arg == '&':
246
+ # background = True
247
+ elif arg != '-e':
248
+ cqls.append(arg)
249
+ if not cqls:
250
+ if self.state.in_repl:
251
+ log2('Please enter cql statement. e.g. select host_id from system.local')
252
+ else:
253
+ log2('* CQL statement is missing.')
254
+ log2()
255
+ Command.display_help()
256
+
257
+ return 'no-cql'
258
+
259
+ query = ' '.join(cqls)
260
+ show_out = True
261
+
262
+ return run_cql(self.state, query, opts=self.opts, show_out=show_out, show_query=self.show_query, use_single_quotes=self.use_single_quotes, on_any=self.on_any, background=background, log_file=log_file)
263
+
264
+ class CassandraPodService:
265
+ def __init__(self, handler: 'CassandraExecHandler'):
266
+ self.handler = handler
267
+
268
+ def exec(self, command: str, action='bash', show_out = True, on_any = False, throw_err = False, shell = '/bin/sh', background = False, log_file = None) -> Union[PodExecResult, list[PodExecResult]]:
269
+ state = self.handler.state
270
+ pod = self.handler.pod
271
+
272
+ if pod:
273
+ return CassandraNodes.exec(pod, state.namespace, command,
274
+ show_out=show_out, throw_err=throw_err, shell=shell, background=background, log_file=log_file)
275
+ elif state.sts:
276
+ return CassandraClusters.exec(state.sts, state.namespace, command, action=action,
277
+ show_out=show_out, on_any=on_any, shell=shell, background=background, log_file=log_file)
278
+
279
+ return []
280
+
281
+ def cql(self, args: list[str], opts: list = [], show_out = False, show_query = False, use_single_quotes = False, on_any = False, background=False, log_file: str = None):
282
+ state = self.handler.state
283
+ query: str = args
284
+
285
+ if isinstance(query, list):
286
+ opts = []
287
+ cqls = []
288
+ for arg in args:
289
+ if arg.startswith('--'):
290
+ opts.append(arg)
291
+ elif arg != '-e':
292
+ cqls.append(arg)
293
+ if not cqls:
294
+ if self.state.in_repl:
295
+ log2('Please enter cql statement. e.g. select host_id from system.local')
296
+ else:
297
+ log2('* CQL statement is missing.')
298
+ log2()
299
+ Command.display_help()
300
+
301
+ return 'no-cql'
302
+
303
+ query = ' '.join(cqls)
304
+ show_out = True
305
+
306
+ return run_cql(state, query, opts=opts, show_out=show_out, show_query=show_query, use_single_quotes=use_single_quotes, on_any=on_any, background=background, log_file=log_file)
307
+
308
+ def display_table(self, cols: str, header: str, show_out = True):
309
+ state = self.handler.state
310
+
311
+ if state.pod:
312
+ show_table(state, [state.pod], cols, header, show_out=show_out)
313
+ elif state.sts:
314
+ pod_names = [pod.metadata.name for pod in StatefulSets.pods(state.sts, state.namespace)]
315
+ show_table(state, pod_names, cols, header, show_out=show_out)
316
+
317
+ def nodetool(self, args: str, show_out = True) -> Union[PodExecResult, list[PodExecResult]]:
318
+ state = self.handler.state
319
+ pod = self.handler.pod
320
+
321
+ user, pw = state.user_pass()
322
+ command = f"nodetool -u {user} -pw {pw} {args}"
323
+
324
+ if pod:
325
+ return CassandraNodes.exec(pod, state.namespace, command, show_out=show_out)
326
+ else:
327
+ return CassandraClusters.exec(state.sts, state.namespace, command, action='nodetool', show_out=show_out)
328
+
329
+ class CassandraExecHandler:
330
+ def __init__(self, state: ReplState, pod: str = None):
331
+ self.state = state
332
+ self.pod = pod
333
+ if not pod and state.pod:
334
+ self.pod = state.pod
335
+
336
+ def __enter__(self):
337
+ return CassandraPodService(self)
338
+
339
+ def __exit__(self, exc_type, exc_val, exc_tb):
340
+ return False
341
+
342
+ def cassandra(state: ReplState, pod: str=None):
343
+ return CassandraExecHandler(state, pod=pod)
@@ -25,19 +25,16 @@ class CodeStart(Command):
25
25
  if not(args := self.args(cmd)):
26
26
  return super().run(cmd, state)
27
27
 
28
- state, args = self.apply_state(args, state)
29
- if not self.validate_state(state):
30
- return state
31
-
32
- log2('This will support c3/c3 only for demo.')
28
+ with self.validate(args, state) as (args, state):
29
+ log2('This will support c3/c3 only for demo.')
33
30
 
34
- stop_user_codes(state.namespace)
35
- try:
36
- start_user_code(state.namespace)
37
- finally:
38
31
  stop_user_codes(state.namespace)
32
+ try:
33
+ start_user_code(state.namespace)
34
+ finally:
35
+ stop_user_codes(state.namespace)
39
36
 
40
- return state
37
+ return state
41
38
 
42
39
  def completion(self, state: ReplState):
43
40
  if state.namespace:
@@ -24,28 +24,11 @@ class CodeStop(Command):
24
24
  if not(args := self.args(cmd)):
25
25
  return super().run(cmd, state)
26
26
 
27
- state, args = self.apply_state(args, state)
28
- if not self.validate_state(state):
29
- return state
30
-
31
- _, dry = Command.extract_options(args, '--dry')
32
- stop_user_codes(state.namespace, dry)
33
-
34
- # if not args:
35
- # log2('Please specify <port>.')
36
- # return state
27
+ with self.validate(args, state) as (args, state):
28
+ _, dry = Command.extract_options(args, '--dry')
29
+ stop_user_codes(state.namespace, dry)
37
30
 
38
- # port = args[0]
39
- # name = f'ops-{port}'
40
- # user = os.getenv("USER")
41
- # label_selector=f'user={user}'
42
- # Ingresses.delete_ingresses(state.namespace, label_selector=label_selector)
43
- # Services.delete_services(state.namespace, label_selector=label_selector)
44
-
45
- # pattern = f'/c3/c3/ops/code/{user}/'
46
- # self.kill_process_by_pattern(pattern)
47
-
48
- return state
31
+ return state
49
32
 
50
33
  def completion(self, state: ReplState):
51
34
  if state.namespace: