kaqing 2.0.115__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 (187) 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 +24 -25
  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 -14
  20. adam/commands/audit/utils_show_top10.py +2 -3
  21. adam/commands/bash/__init__.py +5 -0
  22. adam/commands/bash/bash.py +8 -96
  23. adam/commands/bash/utils_bash.py +16 -0
  24. adam/commands/cat.py +14 -19
  25. adam/commands/cd.py +12 -100
  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 +123 -39
  30. adam/commands/commands_utils.py +8 -17
  31. adam/commands/cp.py +33 -39
  32. adam/commands/cql/cql_completions.py +28 -10
  33. adam/commands/cql/cqlsh.py +10 -30
  34. adam/commands/cql/utils_cql.py +343 -0
  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 +65 -73
  42. adam/commands/deploy/deploy_utils.py +14 -24
  43. adam/commands/deploy/undeploy.py +4 -27
  44. adam/commands/deploy/undeploy_frontend.py +4 -7
  45. adam/commands/deploy/undeploy_pg_agent.py +5 -7
  46. adam/commands/deploy/undeploy_pod.py +11 -12
  47. adam/commands/devices/__init__.py +0 -0
  48. adam/commands/devices/device.py +118 -0
  49. adam/commands/devices/device_app.py +173 -0
  50. adam/commands/devices/device_auit_log.py +49 -0
  51. adam/commands/devices/device_cass.py +185 -0
  52. adam/commands/devices/device_export.py +86 -0
  53. adam/commands/devices/device_postgres.py +144 -0
  54. adam/commands/devices/devices.py +25 -0
  55. adam/commands/exit.py +1 -4
  56. adam/commands/export/clean_up_all_export_sessions.py +37 -0
  57. adam/commands/export/clean_up_export_sessions.py +51 -0
  58. adam/commands/export/drop_export_database.py +55 -0
  59. adam/commands/export/drop_export_databases.py +43 -0
  60. adam/commands/export/export.py +19 -26
  61. adam/commands/export/export_databases.py +174 -0
  62. adam/commands/export/export_handlers.py +71 -0
  63. adam/commands/export/export_select.py +48 -22
  64. adam/commands/export/export_select_x.py +54 -0
  65. adam/commands/export/export_use.py +19 -23
  66. adam/commands/export/exporter.py +353 -0
  67. adam/commands/export/import_session.py +40 -0
  68. adam/commands/export/importer.py +67 -0
  69. adam/commands/export/importer_athena.py +77 -0
  70. adam/commands/export/importer_sqlite.py +39 -0
  71. adam/commands/export/show_column_counts.py +54 -0
  72. adam/commands/export/show_export_databases.py +36 -0
  73. adam/commands/export/show_export_session.py +48 -0
  74. adam/commands/export/show_export_sessions.py +44 -0
  75. adam/commands/export/utils_export.py +223 -162
  76. adam/commands/help.py +1 -1
  77. adam/commands/intermediate_command.py +49 -0
  78. adam/commands/issues.py +11 -43
  79. adam/commands/kubectl.py +3 -6
  80. adam/commands/login.py +22 -24
  81. adam/commands/logs.py +3 -6
  82. adam/commands/ls.py +11 -128
  83. adam/commands/medusa/medusa.py +4 -22
  84. adam/commands/medusa/medusa_backup.py +20 -24
  85. adam/commands/medusa/medusa_restore.py +29 -33
  86. adam/commands/medusa/medusa_show_backupjobs.py +14 -18
  87. adam/commands/medusa/medusa_show_restorejobs.py +11 -18
  88. adam/commands/nodetool.py +6 -15
  89. adam/commands/param_get.py +11 -12
  90. adam/commands/param_set.py +9 -10
  91. adam/commands/postgres/postgres.py +41 -34
  92. adam/commands/postgres/postgres_context.py +57 -24
  93. adam/commands/postgres/postgres_ls.py +4 -8
  94. adam/commands/postgres/postgres_preview.py +5 -9
  95. adam/commands/postgres/psql_completions.py +1 -1
  96. adam/commands/postgres/utils_postgres.py +66 -0
  97. adam/commands/preview_table.py +5 -44
  98. adam/commands/pwd.py +14 -47
  99. adam/commands/reaper/reaper.py +4 -27
  100. adam/commands/reaper/reaper_forward.py +48 -55
  101. adam/commands/reaper/reaper_forward_session.py +6 -0
  102. adam/commands/reaper/reaper_forward_stop.py +10 -16
  103. adam/commands/reaper/reaper_restart.py +7 -14
  104. adam/commands/reaper/reaper_run_abort.py +11 -30
  105. adam/commands/reaper/reaper_runs.py +42 -57
  106. adam/commands/reaper/reaper_runs_abort.py +29 -49
  107. adam/commands/reaper/reaper_schedule_activate.py +11 -30
  108. adam/commands/reaper/reaper_schedule_start.py +10 -29
  109. adam/commands/reaper/reaper_schedule_stop.py +10 -29
  110. adam/commands/reaper/reaper_schedules.py +4 -14
  111. adam/commands/reaper/reaper_status.py +8 -16
  112. adam/commands/reaper/utils_reaper.py +196 -0
  113. adam/commands/repair/repair.py +4 -22
  114. adam/commands/repair/repair_log.py +5 -11
  115. adam/commands/repair/repair_run.py +27 -34
  116. adam/commands/repair/repair_scan.py +32 -38
  117. adam/commands/repair/repair_stop.py +5 -11
  118. adam/commands/report.py +27 -29
  119. adam/commands/restart.py +25 -26
  120. adam/commands/rollout.py +19 -24
  121. adam/commands/shell.py +10 -4
  122. adam/commands/show/show.py +10 -25
  123. adam/commands/show/show_cassandra_repairs.py +35 -0
  124. adam/commands/show/show_cassandra_status.py +32 -43
  125. adam/commands/show/show_cassandra_version.py +5 -18
  126. adam/commands/show/show_commands.py +19 -24
  127. adam/commands/show/show_host.py +1 -1
  128. adam/commands/show/show_login.py +20 -27
  129. adam/commands/show/show_processes.py +15 -19
  130. adam/commands/show/show_storage.py +10 -20
  131. adam/commands/watch.py +26 -29
  132. adam/config.py +5 -14
  133. adam/embedded_params.py +1 -1
  134. adam/log.py +4 -4
  135. adam/pod_exec_result.py +3 -3
  136. adam/repl.py +40 -103
  137. adam/repl_commands.py +32 -16
  138. adam/repl_state.py +57 -28
  139. adam/sql/sql_completer.py +44 -28
  140. adam/sql/sql_state_machine.py +89 -28
  141. adam/sso/authn_ad.py +6 -8
  142. adam/sso/authn_okta.py +4 -6
  143. adam/sso/cred_cache.py +3 -5
  144. adam/sso/idp.py +9 -12
  145. adam/utils.py +435 -6
  146. adam/utils_athena.py +57 -37
  147. adam/utils_audits.py +12 -14
  148. adam/utils_issues.py +32 -0
  149. adam/utils_k8s/app_clusters.py +13 -18
  150. adam/utils_k8s/app_pods.py +2 -0
  151. adam/utils_k8s/cassandra_clusters.py +22 -19
  152. adam/utils_k8s/cassandra_nodes.py +2 -2
  153. adam/utils_k8s/custom_resources.py +16 -17
  154. adam/utils_k8s/ingresses.py +2 -2
  155. adam/utils_k8s/jobs.py +7 -11
  156. adam/utils_k8s/k8s.py +87 -0
  157. adam/utils_k8s/pods.py +40 -77
  158. adam/utils_k8s/secrets.py +4 -4
  159. adam/utils_k8s/service_accounts.py +5 -4
  160. adam/utils_k8s/services.py +2 -2
  161. adam/utils_k8s/statefulsets.py +1 -12
  162. adam/utils_net.py +4 -4
  163. adam/utils_repl/__init__.py +0 -0
  164. adam/utils_repl/automata_completer.py +48 -0
  165. adam/utils_repl/repl_completer.py +46 -0
  166. adam/utils_repl/state_machine.py +173 -0
  167. adam/utils_sqlite.py +137 -0
  168. adam/version.py +1 -1
  169. {kaqing-2.0.115.dist-info → kaqing-2.0.172.dist-info}/METADATA +1 -1
  170. kaqing-2.0.172.dist-info/RECORD +230 -0
  171. adam/commands/app.py +0 -67
  172. adam/commands/app_ping.py +0 -44
  173. adam/commands/cql/cql_utils.py +0 -204
  174. adam/commands/devices.py +0 -147
  175. adam/commands/export/export_on_x.py +0 -76
  176. adam/commands/export/export_rmdbs.py +0 -65
  177. adam/commands/postgres/postgres_utils.py +0 -31
  178. adam/commands/reaper/reaper_session.py +0 -159
  179. adam/commands/show/show_app_actions.py +0 -56
  180. adam/commands/show/show_app_id.py +0 -47
  181. adam/commands/show/show_app_queues.py +0 -45
  182. adam/commands/show/show_repairs.py +0 -47
  183. adam/utils_export.py +0 -42
  184. kaqing-2.0.115.dist-info/RECORD +0 -203
  185. {kaqing-2.0.115.dist-info → kaqing-2.0.172.dist-info}/WHEEL +0 -0
  186. {kaqing-2.0.115.dist-info → kaqing-2.0.172.dist-info}/entry_points.txt +0 -0
  187. {kaqing-2.0.115.dist-info → kaqing-2.0.172.dist-info}/top_level.txt +0 -0
@@ -1,204 +0,0 @@
1
- import functools
2
- import re
3
-
4
- from adam.config import Config
5
- from adam.utils_k8s.cassandra_clusters import CassandraClusters
6
- from adam.utils_k8s.cassandra_nodes import CassandraNodes
7
- from adam.utils_k8s.secrets import Secrets
8
- from adam.pod_exec_result import PodExecResult
9
- from adam.repl_state import ReplState
10
- from adam.utils import log2
11
-
12
- @functools.lru_cache()
13
- def keyspaces(state: ReplState, on_any=False):
14
- if state.pod:
15
- Config().wait_log(f'Inspecting Cassandra Keyspaces on {state.pod}...')
16
- else:
17
- Config().wait_log(f'Inspecting Cassandra Keyspaces...')
18
-
19
- r: list[PodExecResult] = run_cql(state, 'describe keyspaces', show_out=False, on_any=on_any)
20
- if not r:
21
- log2('No pod is available')
22
- return []
23
-
24
- return parse_cql_desc_keyspaces(r.stdout if state.pod else r[0].stdout)
25
-
26
- def cassandra_table_names(state: ReplState, keyspace = None):
27
- return [f'{k}.{t}' for k, ts in tables(state, on_any=True).items() for t in ts if not keyspace or k == keyspace]
28
-
29
- @functools.lru_cache()
30
- def tables(state: ReplState, on_any=False) -> dict[str, list[str]]:
31
- r: list[PodExecResult] = run_cql(state, 'describe tables', show_out=False, on_any=on_any)
32
- if not r:
33
- log2('No pod is available')
34
- return {}
35
-
36
- return parse_cql_desc_tables(r.stdout if state.pod else r[0].stdout)
37
-
38
- @functools.lru_cache()
39
- def table_spec(state: ReplState, table: str, on_any=False) -> 'TableSpec':
40
- r: list[PodExecResult] = run_cql(state, f'describe table {table}', show_out=False, on_any=on_any)
41
- if not r:
42
- log2('No pod is available')
43
- return None
44
-
45
- return parse_cql_desc_table(r.stdout if state.pod else r[0].stdout)
46
-
47
- def run_cql(state: ReplState, cql: str, opts: list = [], show_out = False, use_single_quotes = False, on_any = False, background=False) -> 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}"'
53
-
54
- if state.pod:
55
- return CassandraNodes.exec(state.pod, state.namespace, command, show_out=show_out, background=background)
56
- else:
57
- return CassandraClusters.exec(state.sts, state.namespace, command, show_out=show_out, action='cql', on_any=on_any, background=background)
58
-
59
- def parse_cql_desc_tables(out: str):
60
- # Keyspace data_endpoint_auth
61
- # ---------------------------
62
- # "token"
63
-
64
- # Keyspace reaper_db
65
- # ------------------
66
- # repair_run schema_migration
67
- # repair_run_by_cluster schema_migration_leader
68
-
69
- # Keyspace system
70
- tables_by_keyspace: dict[str, list[str]] = {}
71
- keyspace = None
72
- state = 's0'
73
- for line in out.split('\n'):
74
- if state == 's0':
75
- groups = re.match(r'^Keyspace (.*)$', line)
76
- if groups:
77
- keyspace = groups[1].strip(' \r')
78
- state = 's1'
79
- elif state == 's1':
80
- if line.startswith('---'):
81
- state = 's2'
82
- elif state == 's2':
83
- if not line.strip(' \r'):
84
- state = 's0'
85
- else:
86
- for table in line.split(' '):
87
- if t := table.strip(' \r'):
88
- if not keyspace in tables_by_keyspace:
89
- tables_by_keyspace[keyspace] = []
90
- tables_by_keyspace[keyspace].append(t)
91
-
92
- return tables_by_keyspace
93
-
94
- def parse_cql_desc_keyspaces(out: str) -> list[str]:
95
- #
96
- # Warning: Cannot create directory at `/home/cassandra/.cassandra`. Command history will not be saved. Please check what was the environment property CQL_HISTORY set to.
97
- #
98
- #
99
- # Warning: Using a password on the command line interface can be insecure.
100
- # Recommendation: use the credentials file to securely provide the password.
101
- #
102
- #
103
- # azops88_db system_auth system_traces
104
- # reaper_db system_distributed system_views
105
- # system system_schema system_virtual_schema
106
- #
107
- kses = []
108
- for line in out.split('\n'):
109
- line = line.strip(' \r')
110
- if not line:
111
- continue
112
- if line.startswith('Warning:'):
113
- continue
114
- if line.startswith('Recommendation:'):
115
- continue
116
-
117
- for ks in line.split(' '):
118
- if s := ks.strip(' \r\t'):
119
- kses.append(s)
120
-
121
- return kses
122
-
123
- class ColumnSpec:
124
- def __init__(self, name: str, type: str, key_index = -1):
125
- self.name = name
126
- self.type = type
127
- self.key_index = key_index
128
-
129
- def __eq__(self, other):
130
- if not isinstance(other, ColumnSpec):
131
- return NotImplemented # Or raise TypeError, depending on desired strictness
132
-
133
- # Then, compare the relevant attributes for equality
134
- return self.name == other.name and self.type == other.type and self.key_index == other.key_index
135
-
136
- class TableSpec:
137
- def __init__(self, columns: list[ColumnSpec]):
138
- self.columns = columns
139
-
140
- def row_key(self):
141
- for c in self.columns:
142
- if c.key_index == 0:
143
- return c.name
144
-
145
- def keys(self):
146
- return [c.name for c in self.columns if c.key_index > -1]
147
-
148
- def parse_cql_desc_table(out: str) -> TableSpec:
149
- # CREATE TABLE azops88_db.analyticscontainer_dfeevalhistory (
150
- # id text,
151
- # columnname text,
152
- # version bigint static,
153
- # contentb blob,
154
- # contentbool boolean,
155
- # contentn double,
156
- # contents text,
157
- # PRIMARY KEY (id, columnname)
158
- # ) WITH CLUSTERING ORDER BY (columnname ASC)
159
- # AND additional_write_policy = '99p'
160
- # AND bloom_filter_fp_chance = 0.1
161
- # AND caching = {'keys': 'ALL', 'rows_per_partition': 'NONE'}
162
- # AND cdc = false
163
- # AND comment = ''
164
- # AND compaction = {'class': 'org.apache.cassandra.db.compaction.LeveledCompactionStrategy', 'max_threshold': '32', 'min_threshold': '4'}
165
- # AND compression = {'chunk_length_in_kb': '16', 'class': 'org.apache.cassandra.io.compress.SnappyCompressor'}
166
- # AND memtable = 'default'
167
- # AND crc_check_chance = 1.0
168
- # AND default_time_to_live = 0
169
- # AND extensions = {}
170
- # AND gc_grace_seconds = 3600
171
- # AND max_index_interval = 2048
172
- # AND memtable_flush_period_in_ms = 0
173
- # AND min_index_interval = 128
174
- # AND read_repair = 'BLOCKING'
175
- # AND speculative_retry = '99p';
176
- pkeys = {}
177
- columns: list[ColumnSpec] = []
178
-
179
- state = 's0'
180
- for line in out.split('\n'):
181
- if state == 's0':
182
- if line.startswith('CREATE TABLE'):
183
- state = 's1'
184
- elif state == 's1':
185
- if line.startswith(')'):
186
- state = 's2'
187
- continue
188
-
189
- groups = re.match(r'^\s*PRIMARY KEY\s*\((.*)\).*$', line)
190
- if groups:
191
- pkeys = {n.strip(' '): i for i, n in enumerate(groups[1].strip(' \r').split(','))}
192
- continue
193
-
194
- groups = re.match(r'^\s*(\S*?)\s*(\S*?),.*$', line)
195
- if groups:
196
- columns.append(ColumnSpec(groups[1], groups[2]))
197
- elif state == 's2':
198
- pass
199
-
200
- for column in columns:
201
- if column.name in pkeys.keys():
202
- column.key_index = pkeys[column.name]
203
-
204
- return TableSpec(columns)
adam/commands/devices.py DELETED
@@ -1,147 +0,0 @@
1
- from adam.commands.command import Command
2
- from adam.repl_state import ReplState
3
-
4
- class DeviceExport(Command):
5
- COMMAND = f'{ReplState.X}:'
6
-
7
- # the singleton pattern
8
- def __new__(cls, *args, **kwargs):
9
- if not hasattr(cls, 'instance'): cls.instance = super(DeviceExport, cls).__new__(cls)
10
-
11
- return cls.instance
12
-
13
- def __init__(self, successor: Command=None):
14
- super().__init__(successor)
15
-
16
- def command(self):
17
- return DeviceExport.COMMAND
18
-
19
- def run(self, cmd: str, state: ReplState):
20
- if not self.args(cmd):
21
- return super().run(cmd, state)
22
-
23
- state.device = ReplState.X
24
-
25
- return state
26
-
27
- def completion(self, state: ReplState):
28
- return super().completion(state)
29
-
30
- def help(self, _: ReplState):
31
- return f'{DeviceAuditLog.COMMAND}\t move to Export Database Operations device'
32
-
33
- class DeviceAuditLog(Command):
34
- COMMAND = f'{ReplState.L}:'
35
-
36
- # the singleton pattern
37
- def __new__(cls, *args, **kwargs):
38
- if not hasattr(cls, 'instance'): cls.instance = super(DeviceAuditLog, cls).__new__(cls)
39
-
40
- return cls.instance
41
-
42
- def __init__(self, successor: Command=None):
43
- super().__init__(successor)
44
-
45
- def command(self):
46
- return DeviceAuditLog.COMMAND
47
-
48
- def run(self, cmd: str, state: ReplState):
49
- if not self.args(cmd):
50
- return super().run(cmd, state)
51
-
52
- state.device = ReplState.L
53
-
54
- return state
55
-
56
- def completion(self, state: ReplState):
57
- return super().completion(state)
58
-
59
- def help(self, _: ReplState):
60
- return f'{DeviceAuditLog.COMMAND}\t move to Audit Log Operations device'
61
-
62
- class DeviceCass(Command):
63
- COMMAND = f'{ReplState.C}:'
64
-
65
- # the singleton pattern
66
- def __new__(cls, *args, **kwargs):
67
- if not hasattr(cls, 'instance'): cls.instance = super(DeviceCass, cls).__new__(cls)
68
-
69
- return cls.instance
70
-
71
- def __init__(self, successor: Command=None):
72
- super().__init__(successor)
73
-
74
- def command(self):
75
- return DeviceCass.COMMAND
76
-
77
- def run(self, cmd: str, state: ReplState):
78
- if not self.args(cmd):
79
- return super().run(cmd, state)
80
-
81
- state.device = ReplState.C
82
-
83
- return state
84
-
85
- def completion(self, state: ReplState):
86
- return super().completion(state)
87
-
88
- def help(self, _: ReplState):
89
- return f'{DeviceCass.COMMAND}\t move to Cassandra Operations device'
90
-
91
- class DevicePostgres(Command):
92
- COMMAND = f'{ReplState.P}:'
93
-
94
- # the singleton pattern
95
- def __new__(cls, *args, **kwargs):
96
- if not hasattr(cls, 'instance'): cls.instance = super(DevicePostgres, cls).__new__(cls)
97
-
98
- return cls.instance
99
-
100
- def __init__(self, successor: Command=None):
101
- super().__init__(successor)
102
-
103
- def command(self):
104
- return DevicePostgres.COMMAND
105
-
106
- def run(self, cmd: str, state: ReplState):
107
- if not self.args(cmd):
108
- return super().run(cmd, state)
109
-
110
- state.device = ReplState.P
111
-
112
- return state
113
-
114
- def completion(self, state: ReplState):
115
- return super().completion(state)
116
-
117
- def help(self, _: ReplState):
118
- return f'{DevicePostgres.COMMAND}\t move to Postgres Operations device'
119
-
120
- class DeviceApp(Command):
121
- COMMAND = f'{ReplState.A}:'
122
-
123
- # the singleton pattern
124
- def __new__(cls, *args, **kwargs):
125
- if not hasattr(cls, 'instance'): cls.instance = super(DeviceApp, cls).__new__(cls)
126
-
127
- return cls.instance
128
-
129
- def __init__(self, successor: Command=None):
130
- super().__init__(successor)
131
-
132
- def command(self):
133
- return DeviceApp.COMMAND
134
-
135
- def run(self, cmd: str, state: ReplState):
136
- if not self.args(cmd):
137
- return super().run(cmd, state)
138
-
139
- state.device = ReplState.A
140
-
141
- return state
142
-
143
- def completion(self, state: ReplState):
144
- return super().completion(state)
145
-
146
- def help(self, _: ReplState):
147
- return f'{DeviceApp.COMMAND}\t move to App Operations device'
@@ -1,76 +0,0 @@
1
- from adam.commands.command import Command
2
- from adam.repl_state import ReplState, RequiredState
3
- from adam.sql.sql_completer import SqlCompleter
4
- from adam.utils import log2
5
- from adam.utils_athena import Athena
6
-
7
- class ExportUseX(Command):
8
- COMMAND = 'use'
9
-
10
- # the singleton pattern
11
- def __new__(cls, *args, **kwargs):
12
- if not hasattr(cls, 'instance'): cls.instance = super(ExportUseX, 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 ExportUseX.COMMAND
21
-
22
- def required(self):
23
- return ReplState.X
24
-
25
- def run(self, cmd: str, state: ReplState):
26
- if not(args := self.args(cmd)):
27
- return super().run(cmd, state)
28
-
29
- state, args = self.apply_state(args, state)
30
- if not self.validate_state(state):
31
- return state
32
-
33
- if not args:
34
- if state.in_repl:
35
- log2('Specify database to use.')
36
- else:
37
- log2('* database is missing.')
38
-
39
- Command.display_help()
40
-
41
- return 'command-missing'
42
-
43
- state.export_session = args[0].replace('export_', '') if args[0].startswith('export_') else args[0]
44
- Athena.clear_cache()
45
-
46
- return state
47
-
48
- def completion(self, state: ReplState):
49
- dict = super().completion(state, {n: None for n in Athena.database_names()})
50
-
51
- if state.export_session:
52
- db = f'export_{state.export_session}'
53
- dict = dict | {'select': SqlCompleter(
54
- lambda: Athena.table_names(database=db, function='export'),
55
- dml='select',
56
- columns=lambda table: Athena.column_names(database=db, function='export'),
57
- variant='athena'
58
- )}
59
-
60
- return dict
61
-
62
- def help(self, _: ReplState):
63
- return f'{ExportUseX.COMMAND} <export db name>\t use Export Database'
64
-
65
- # No action body, only for a help entry and auto-completion
66
- class ExportSelectX(Command):
67
- COMMAND = 'select'
68
-
69
- def command(self):
70
- return ExportSelectX.COMMAND
71
-
72
- def required(self):
73
- return RequiredState.EXPORT_DB
74
-
75
- def help(self, _: ReplState):
76
- return f'<sql-select-statements>\t run queries on export database'
@@ -1,65 +0,0 @@
1
- import boto3
2
-
3
- from adam.commands.command import Command
4
- from adam.commands.export.utils_export import ing
5
- from adam.config import Config
6
- from adam.repl_state import ReplState, RequiredState
7
- from adam.utils import log2
8
- from adam.utils_athena import Athena
9
-
10
- class RemoveExportDatabases(Command):
11
- COMMAND = '&rmdbs'
12
-
13
- # the singleton pattern
14
- def __new__(cls, *args, **kwargs):
15
- if not hasattr(cls, 'instance'): cls.instance = super(RemoveExportDatabases, cls).__new__(cls)
16
-
17
- return cls.instance
18
-
19
- def __init__(self, successor: Command=None):
20
- super().__init__(successor)
21
-
22
- def command(self):
23
- return RemoveExportDatabases.COMMAND
24
-
25
- def required(self):
26
- return RequiredState.CLUSTER_OR_POD
27
-
28
- def run(self, cmd: str, state: ReplState):
29
- if not(args := self.args(cmd)):
30
- return super().run(cmd, state)
31
-
32
- state, args = self.apply_state(args, state)
33
- if not self.validate_state(state):
34
- return state
35
-
36
- dbs = Athena.database_names('export_')
37
- def drop_all_exports():
38
- for db in dbs:
39
- query = f'DROP DATABASE {db} CASCADE'
40
- if Config().is_debug():
41
- log2(query)
42
- Athena.query(query)
43
-
44
- if Config().is_debug():
45
- drop_all_exports()
46
- else:
47
- ing(f'Droping {len(dbs)} databases', drop_all_exports)
48
-
49
- def delete_s3_folder():
50
- s3 = boto3.resource('s3')
51
- bucket = s3.Bucket('c3.ops--qing')
52
- bucket.objects.filter(Prefix='export/').delete()
53
-
54
- if Config().is_debug():
55
- delete_s3_folder()
56
- else:
57
- ing(f'Deleting s3 folder: export', delete_s3_folder)
58
-
59
- return state
60
-
61
- def completion(self, state: ReplState):
62
- return super().completion(state)
63
-
64
- def help(self, _: ReplState):
65
- return f'{RemoveExportDatabases.COMMAND}\t remove all export databases'
@@ -1,31 +0,0 @@
1
- import functools
2
-
3
- from adam.commands.postgres.postgres_context import PostgresContext
4
- from adam.config import Config
5
-
6
- TestPG = [False]
7
-
8
- @functools.lru_cache()
9
- def pg_database_names(ns: str, pg_path: str):
10
- if TestPG[0]:
11
- return ['azops88_c3ai_c3']
12
-
13
- Config().wait_log('Inspecting Postgres Databases...')
14
-
15
- pg = PostgresContext.apply(ns, pg_path)
16
- return [db['name'] for db in pg.databases() if db['owner'] == PostgresContext.default_owner()]
17
-
18
- @functools.lru_cache()
19
- def pg_table_names(ns: str, pg_path: str):
20
- if TestPG[0]:
21
- return ['C3_2_XYZ1']
22
-
23
- Config().wait_log('Inspecting Postgres Database...')
24
- return [table['name'] for table in pg_tables(ns, pg_path) if table['schema'] == PostgresContext.default_schema()]
25
-
26
- def pg_tables(ns: str, pg_path: str):
27
- pg = PostgresContext.apply(ns, pg_path)
28
- if pg.db:
29
- return pg.tables()
30
-
31
- return []
@@ -1,159 +0,0 @@
1
- from collections.abc import Callable
2
- import threading
3
- from kubernetes import client
4
- import portforward
5
- import re
6
- import requests
7
- from typing import List, cast
8
-
9
- from adam.config import Config
10
- from adam.utils_k8s.kube_context import KubeContext
11
- from adam.repl_state import ReplState
12
- from adam.utils import lines_to_tabular, log2
13
-
14
- class ReaperSession:
15
- is_forwarding = False
16
- stopping = threading.Event()
17
- schedules_ids_by_cluster: dict[str, list[str]] = {}
18
-
19
- def __init__(self, pod: str, headers: dict[str, str] = None):
20
- self.pod = pod
21
- self.headers = headers
22
-
23
- def login(self, state: ReplState, local_addr: str, remote_addr: str, show_output = True) -> str :
24
- user, pw = state.user_pass(secret_path='reaper.secret')
25
-
26
- response = requests.post(f'http://{local_addr}/login', headers={
27
- 'Accept': '*'
28
- },data={
29
- 'username':user,
30
- 'password':pw})
31
- if show_output:
32
- log2(f'POST {remote_addr}/login')
33
- log2(f' username={user}&password={pw}')
34
-
35
- if int(response.status_code / 100) != 2:
36
- if show_output:
37
- log2("login failed")
38
- return None
39
-
40
- return response.headers['Set-Cookie']
41
-
42
- def port_forwarded(self, state: ReplState, path: str, body: Callable[[str, dict[str, str]], requests.Response], method: str = None, show_output = True):
43
- local_port = Config().get('reaper.port-forward.local-port', 9001)
44
- target_port = 8080
45
-
46
- def f(local_addr: str, remote_addr: str):
47
- if not self.headers:
48
- self.headers = self.cookie_header(state, local_addr, remote_addr, show_output=show_output)
49
-
50
- if show_output and method:
51
- log2(f'{method} {remote_addr}/{path}')
52
- response = body(f'http://{local_addr}/{path}', self.headers)
53
-
54
- if response:
55
- if int(response.status_code / 100) != 2:
56
- if show_output:
57
- log2(response.status_code)
58
- return response
59
-
60
- if show_output:
61
- log2()
62
-
63
- return response if response else 'no-response'
64
-
65
- if KubeContext.in_cluster():
66
- # cs-a526330d23-cs-a526330d23-default-sts-0 ->
67
- # curl http://cs-a526330d23-cs-a526330d23-reaper-service.stgawsscpsr.svc.cluster.local:8080
68
- groups = re.match(r'^(.*?-.*?-.*?-.*?-).*', state.sts)
69
- if groups:
70
- svc_name = Config().get('reaper.service-name', 'reaper-service')
71
- svc = f'{groups[1]}{svc_name}.{state.namespace}.svc.cluster.local:{target_port}'
72
- return f(local_addr=svc, remote_addr=svc)
73
- else:
74
- return None
75
- else:
76
- with portforward.forward(state.namespace, self.pod, local_port, target_port):
77
- return f(local_addr=f'localhost:{local_port}', remote_addr=f'{self.pod}:{target_port}')
78
-
79
- def cookie_header(self, state: ReplState, local_addr, remote_addr, show_output = True):
80
- return {'Cookie': self.login(state, local_addr, remote_addr, show_output=show_output)}
81
-
82
- def create(state: ReplState) -> 'ReaperSession':
83
- pods = ReaperSession.list_reaper_pods(state.sts if state.sts else state.pod, state.namespace)
84
- if pods:
85
- return ReaperSession(pods[0].metadata.name)
86
- else:
87
- log2('No reaper found.')
88
-
89
- return None
90
-
91
- def list_reaper_pods(sts_name: str, namespace: str) -> List[client.V1Pod]:
92
- v1 = client.CoreV1Api()
93
-
94
- # k8ssandra.io/reaper: cs-d0767a536f-cs-d0767a536f-reaper
95
- groups = re.match(Config().get('reaper.pod.cluster-regex', r'(.*?-.*?-.*?-.*?)-.*'), sts_name)
96
- label_selector = Config().get('reaper.pod.label-selector', 'k8ssandra.io/reaper={cluster}-reaper').replace('{cluster}', groups[1])
97
-
98
- return cast(List[client.V1Pod], v1.list_namespaced_pod(namespace, label_selector=label_selector).items)
99
-
100
- def show_schedules(self, state: ReplState, filter: Callable[[list[dict]], dict] = None):
101
- schedules = self.list_schedules(state, filter=filter)
102
- # forced refresh of schedule list
103
- if not filter:
104
- self.schedules_ids_by_cluster[state.sts] = [schedule['id'] for schedule in schedules]
105
- self.show_schedules_tabular(schedules)
106
-
107
- def schedule_ids(self, state: ReplState, show_output = True, filter: Callable[[list[dict]], dict] = None):
108
- schedules = self.list_schedules(state, show_output=show_output, filter=filter)
109
- return [schedule['id'] for schedule in schedules]
110
-
111
- def list_schedules(self, state: ReplState, show_output = True, filter: Callable[[list[dict]], dict] = None) -> list[dict]:
112
- def body(uri: str, headers: dict[str, str]):
113
- return requests.get(uri, headers=headers)
114
-
115
- response = self.port_forwarded(state, 'repair_schedule', body, method='GET', show_output=show_output)
116
- if not response:
117
- return
118
-
119
- res = response.json()
120
- if filter:
121
- res = filter(res)
122
-
123
- return res
124
-
125
- def show_schedules_tabular(self, schedules: list[dict]):
126
- log2(lines_to_tabular([f"{schedule['id']} {schedule['state']} {schedule['cluster_name']} {schedule['keyspace_name']}" for schedule in schedules], 'ID STATE CLUSTER KEYSPACE'))
127
-
128
- def show_schedule(self, state: ReplState, schedule_id: str):
129
- def filter(schedules: list[dict]):
130
- return [schedule for schedule in schedules if schedule['id'] == schedule_id]
131
-
132
- self.show_schedules(state, filter)
133
-
134
- def reaper_spec(self, state: ReplState) -> dict[str, any]:
135
- user, pw = state.user_pass(secret_path='reaper.secret')
136
- local_port = Config().get('reaper.port-forward.local-port', 9001)
137
-
138
- return {
139
- 'pod': self.pod,
140
- 'exec': f'kubectl exec -it {self.pod} -n {state.namespace} -- bash',
141
- 'forward': f'kubectl port-forward pods/{self.pod} -n {state.namespace} {local_port}:8080',
142
- 'web-uri': f'http://localhost:{local_port}/webui',
143
- 'username': user,
144
- 'password': pw
145
- }
146
-
147
- def cached_schedule_ids(state: ReplState) -> list[str]:
148
- if state.sts in ReaperSession.schedules_ids_by_cluster:
149
- return ReaperSession.schedules_ids_by_cluster[state.sts]
150
-
151
- if reaper := ReaperSession.create(state):
152
- Config().wait_log('Inspecting Cassandra Reaper...')
153
-
154
- schedules = reaper.schedule_ids(state, show_output = False)
155
- ReaperSession.schedules_ids_by_cluster[state.sts] = schedules
156
-
157
- return schedules
158
-
159
- return []