kaqing 2.0.110__py3-none-any.whl → 2.0.214__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 (251) hide show
  1. adam/__init__.py +0 -2
  2. adam/app_session.py +9 -12
  3. adam/apps.py +18 -4
  4. adam/batch.py +19 -19
  5. adam/checks/check_utils.py +16 -46
  6. adam/checks/cpu.py +7 -1
  7. adam/checks/cpu_metrics.py +52 -0
  8. adam/checks/disk.py +2 -3
  9. adam/columns/columns.py +3 -1
  10. adam/columns/cpu.py +3 -1
  11. adam/columns/cpu_metrics.py +22 -0
  12. adam/columns/memory.py +3 -4
  13. adam/commands/__init__.py +24 -0
  14. adam/commands/app/app.py +38 -0
  15. adam/commands/{app_ping.py → app/app_ping.py} +7 -13
  16. adam/commands/{login.py → app/login.py} +22 -24
  17. adam/commands/app/show_app_actions.py +49 -0
  18. adam/commands/{show → app}/show_app_id.py +8 -11
  19. adam/commands/{show → app}/show_app_queues.py +7 -14
  20. adam/commands/app/show_login.py +56 -0
  21. adam/commands/app/utils_app.py +106 -0
  22. adam/commands/audit/audit.py +22 -40
  23. adam/commands/audit/audit_repair_tables.py +15 -19
  24. adam/commands/audit/audit_run.py +15 -22
  25. adam/commands/audit/completions_l.py +15 -0
  26. adam/commands/audit/show_last10.py +4 -18
  27. adam/commands/audit/show_slow10.py +4 -17
  28. adam/commands/audit/show_top10.py +4 -16
  29. adam/commands/audit/utils_show_top10.py +15 -3
  30. adam/commands/bash/__init__.py +5 -0
  31. adam/commands/bash/bash.py +36 -0
  32. adam/commands/bash/bash_completer.py +93 -0
  33. adam/commands/bash/utils_bash.py +16 -0
  34. adam/commands/cassandra/__init__.py +0 -0
  35. adam/commands/cassandra/download_cassandra_log.py +45 -0
  36. adam/commands/{restart.py → cassandra/restart_cluster.py} +12 -26
  37. adam/commands/cassandra/restart_node.py +51 -0
  38. adam/commands/cassandra/restart_nodes.py +47 -0
  39. adam/commands/{rollout.py → cassandra/rollout.py} +20 -25
  40. adam/commands/cassandra/show_cassandra_repairs.py +37 -0
  41. adam/commands/cassandra/show_cassandra_status.py +117 -0
  42. adam/commands/{show → cassandra}/show_cassandra_version.py +5 -18
  43. adam/commands/cassandra/show_processes.py +50 -0
  44. adam/commands/cassandra/show_storage.py +44 -0
  45. adam/commands/{watch.py → cassandra/watch.py} +26 -29
  46. adam/commands/cli/__init__.py +0 -0
  47. adam/commands/{cli_commands.py → cli/cli_commands.py} +8 -4
  48. adam/commands/cli/clipboard_copy.py +86 -0
  49. adam/commands/cli/show_cli_commands.py +56 -0
  50. adam/commands/code.py +57 -0
  51. adam/commands/command.py +211 -40
  52. adam/commands/commands_utils.py +20 -27
  53. adam/commands/config/__init__.py +0 -0
  54. adam/commands/{param_get.py → config/param_get.py} +11 -14
  55. adam/commands/{param_set.py → config/param_set.py} +8 -12
  56. adam/commands/{show → config}/show_params.py +2 -5
  57. adam/commands/cql/alter_tables.py +66 -0
  58. adam/commands/cql/completions_c.py +29 -0
  59. adam/commands/cql/cqlsh.py +10 -32
  60. adam/commands/cql/utils_cql.py +306 -0
  61. adam/commands/debug/__init__.py +0 -0
  62. adam/commands/debug/debug.py +22 -0
  63. adam/commands/debug/debug_completes.py +35 -0
  64. adam/commands/debug/debug_timings.py +35 -0
  65. adam/commands/debug/show_offloaded_completes.py +45 -0
  66. adam/commands/deploy/code_start.py +7 -10
  67. adam/commands/deploy/code_stop.py +4 -21
  68. adam/commands/deploy/code_utils.py +3 -3
  69. adam/commands/deploy/deploy.py +4 -27
  70. adam/commands/deploy/deploy_frontend.py +14 -17
  71. adam/commands/deploy/deploy_pg_agent.py +3 -6
  72. adam/commands/deploy/deploy_pod.py +65 -73
  73. adam/commands/deploy/deploy_utils.py +14 -24
  74. adam/commands/deploy/undeploy.py +4 -27
  75. adam/commands/deploy/undeploy_frontend.py +4 -7
  76. adam/commands/deploy/undeploy_pg_agent.py +6 -8
  77. adam/commands/deploy/undeploy_pod.py +11 -12
  78. adam/commands/devices/__init__.py +0 -0
  79. adam/commands/devices/device.py +149 -0
  80. adam/commands/devices/device_app.py +163 -0
  81. adam/commands/devices/device_auit_log.py +49 -0
  82. adam/commands/devices/device_cass.py +179 -0
  83. adam/commands/devices/device_export.py +87 -0
  84. adam/commands/devices/device_postgres.py +160 -0
  85. adam/commands/devices/devices.py +25 -0
  86. adam/commands/diag/__init__.py +0 -0
  87. adam/commands/{check.py → diag/check.py} +16 -25
  88. adam/commands/diag/generate_report.py +52 -0
  89. adam/commands/diag/issues.py +43 -0
  90. adam/commands/exit.py +1 -4
  91. adam/commands/export/__init__.py +0 -0
  92. adam/commands/export/clean_up_all_export_sessions.py +37 -0
  93. adam/commands/export/clean_up_export_sessions.py +39 -0
  94. adam/commands/export/completions_x.py +11 -0
  95. adam/commands/export/download_export_session.py +40 -0
  96. adam/commands/export/drop_export_database.py +39 -0
  97. adam/commands/export/drop_export_databases.py +37 -0
  98. adam/commands/export/export.py +37 -0
  99. adam/commands/export/export_databases.py +251 -0
  100. adam/commands/export/export_select.py +34 -0
  101. adam/commands/export/export_sessions.py +210 -0
  102. adam/commands/export/export_use.py +49 -0
  103. adam/commands/export/export_x_select.py +48 -0
  104. adam/commands/export/exporter.py +419 -0
  105. adam/commands/export/import_files.py +44 -0
  106. adam/commands/export/import_session.py +40 -0
  107. adam/commands/export/importer.py +81 -0
  108. adam/commands/export/importer_athena.py +157 -0
  109. adam/commands/export/importer_sqlite.py +78 -0
  110. adam/commands/export/show_column_counts.py +45 -0
  111. adam/commands/export/show_export_databases.py +39 -0
  112. adam/commands/export/show_export_session.py +39 -0
  113. adam/commands/export/show_export_sessions.py +37 -0
  114. adam/commands/export/utils_export.py +366 -0
  115. adam/commands/fs/__init__.py +0 -0
  116. adam/commands/fs/cat.py +36 -0
  117. adam/commands/fs/cat_local.py +42 -0
  118. adam/commands/fs/cd.py +41 -0
  119. adam/commands/fs/download_file.py +47 -0
  120. adam/commands/fs/find_files.py +51 -0
  121. adam/commands/fs/find_processes.py +76 -0
  122. adam/commands/fs/head.py +36 -0
  123. adam/commands/fs/ls.py +41 -0
  124. adam/commands/fs/ls_local.py +40 -0
  125. adam/commands/fs/pwd.py +45 -0
  126. adam/commands/fs/rm.py +18 -0
  127. adam/commands/fs/rm_downloads.py +39 -0
  128. adam/commands/fs/rm_logs.py +38 -0
  129. adam/commands/{shell.py → fs/shell.py} +12 -4
  130. adam/commands/{show → fs}/show_adam.py +3 -3
  131. adam/commands/{show → fs}/show_host.py +1 -1
  132. adam/commands/help.py +5 -3
  133. adam/commands/intermediate_command.py +52 -0
  134. adam/commands/kubectl.py +38 -0
  135. adam/commands/medusa/medusa.py +4 -22
  136. adam/commands/medusa/medusa_backup.py +20 -27
  137. adam/commands/medusa/medusa_restore.py +35 -48
  138. adam/commands/medusa/medusa_show_backupjobs.py +16 -18
  139. adam/commands/medusa/medusa_show_restorejobs.py +13 -18
  140. adam/commands/medusa/utils_medusa.py +15 -0
  141. adam/commands/nodetool/__init__.py +0 -0
  142. adam/commands/{nodetool.py → nodetool/nodetool.py} +9 -20
  143. adam/commands/postgres/completions_p.py +22 -0
  144. adam/commands/postgres/postgres.py +47 -55
  145. adam/commands/postgres/postgres_databases.py +269 -0
  146. adam/commands/postgres/postgres_ls.py +5 -9
  147. adam/commands/postgres/postgres_preview.py +5 -9
  148. adam/commands/postgres/utils_postgres.py +80 -0
  149. adam/commands/preview_table.py +8 -44
  150. adam/commands/reaper/reaper.py +4 -27
  151. adam/commands/reaper/reaper_forward.py +49 -56
  152. adam/commands/reaper/reaper_forward_session.py +6 -0
  153. adam/commands/reaper/reaper_forward_stop.py +10 -16
  154. adam/commands/reaper/reaper_restart.py +7 -14
  155. adam/commands/reaper/reaper_run_abort.py +8 -33
  156. adam/commands/reaper/reaper_runs.py +43 -58
  157. adam/commands/reaper/reaper_runs_abort.py +29 -49
  158. adam/commands/reaper/reaper_schedule_activate.py +14 -33
  159. adam/commands/reaper/reaper_schedule_start.py +9 -33
  160. adam/commands/reaper/reaper_schedule_stop.py +9 -33
  161. adam/commands/reaper/reaper_schedules.py +4 -14
  162. adam/commands/reaper/reaper_status.py +8 -16
  163. adam/commands/reaper/utils_reaper.py +203 -0
  164. adam/commands/repair/repair.py +4 -22
  165. adam/commands/repair/repair_log.py +5 -11
  166. adam/commands/repair/repair_run.py +27 -34
  167. adam/commands/repair/repair_scan.py +32 -40
  168. adam/commands/repair/repair_stop.py +5 -12
  169. adam/commands/show.py +40 -0
  170. adam/config.py +5 -15
  171. adam/embedded_params.py +1 -1
  172. adam/log.py +4 -4
  173. adam/repl.py +83 -116
  174. adam/repl_commands.py +86 -45
  175. adam/repl_session.py +9 -1
  176. adam/repl_state.py +176 -40
  177. adam/sql/async_executor.py +62 -0
  178. adam/sql/lark_completer.py +286 -0
  179. adam/sql/lark_parser.py +604 -0
  180. adam/sql/qingl.lark +1076 -0
  181. adam/sql/sql_completer.py +52 -27
  182. adam/sql/sql_state_machine.py +131 -19
  183. adam/sso/authn_ad.py +6 -8
  184. adam/sso/authn_okta.py +4 -6
  185. adam/sso/cred_cache.py +4 -9
  186. adam/sso/idp.py +9 -12
  187. adam/utils.py +670 -31
  188. adam/utils_athena.py +145 -0
  189. adam/utils_audits.py +12 -103
  190. adam/utils_issues.py +32 -0
  191. adam/utils_k8s/app_clusters.py +35 -0
  192. adam/utils_k8s/app_pods.py +41 -0
  193. adam/utils_k8s/cassandra_clusters.py +35 -20
  194. adam/utils_k8s/cassandra_nodes.py +15 -6
  195. adam/utils_k8s/custom_resources.py +16 -17
  196. adam/utils_k8s/ingresses.py +2 -2
  197. adam/utils_k8s/jobs.py +7 -11
  198. adam/utils_k8s/k8s.py +96 -0
  199. adam/utils_k8s/kube_context.py +3 -6
  200. adam/{pod_exec_result.py → utils_k8s/pod_exec_result.py} +13 -4
  201. adam/utils_k8s/pods.py +159 -89
  202. adam/utils_k8s/secrets.py +4 -4
  203. adam/utils_k8s/service_accounts.py +5 -4
  204. adam/utils_k8s/services.py +2 -2
  205. adam/utils_k8s/statefulsets.py +6 -14
  206. adam/utils_local.py +80 -0
  207. adam/utils_net.py +4 -4
  208. adam/utils_repl/__init__.py +0 -0
  209. adam/utils_repl/appendable_completer.py +6 -0
  210. adam/utils_repl/automata_completer.py +48 -0
  211. adam/utils_repl/repl_completer.py +93 -0
  212. adam/utils_repl/state_machine.py +173 -0
  213. adam/utils_sqlite.py +132 -0
  214. adam/version.py +1 -1
  215. {kaqing-2.0.110.dist-info → kaqing-2.0.214.dist-info}/METADATA +1 -1
  216. kaqing-2.0.214.dist-info/RECORD +272 -0
  217. kaqing-2.0.214.dist-info/top_level.txt +2 -0
  218. teddy/__init__.py +0 -0
  219. teddy/lark_parser.py +436 -0
  220. teddy/lark_parser2.py +618 -0
  221. adam/commands/alter_tables.py +0 -81
  222. adam/commands/app.py +0 -67
  223. adam/commands/bash.py +0 -150
  224. adam/commands/cd.py +0 -125
  225. adam/commands/cp.py +0 -95
  226. adam/commands/cql/cql_completions.py +0 -15
  227. adam/commands/cql/cql_utils.py +0 -112
  228. adam/commands/devices.py +0 -118
  229. adam/commands/issues.py +0 -75
  230. adam/commands/logs.py +0 -40
  231. adam/commands/ls.py +0 -146
  232. adam/commands/postgres/postgres_context.py +0 -239
  233. adam/commands/postgres/postgres_utils.py +0 -31
  234. adam/commands/postgres/psql_completions.py +0 -10
  235. adam/commands/pwd.py +0 -77
  236. adam/commands/reaper/reaper_session.py +0 -159
  237. adam/commands/report.py +0 -63
  238. adam/commands/show/show.py +0 -54
  239. adam/commands/show/show_app_actions.py +0 -56
  240. adam/commands/show/show_cassandra_status.py +0 -128
  241. adam/commands/show/show_commands.py +0 -61
  242. adam/commands/show/show_login.py +0 -63
  243. adam/commands/show/show_processes.py +0 -53
  244. adam/commands/show/show_repairs.py +0 -47
  245. adam/commands/show/show_storage.py +0 -52
  246. kaqing-2.0.110.dist-info/RECORD +0 -187
  247. kaqing-2.0.110.dist-info/top_level.txt +0 -1
  248. /adam/commands/{show → app}/__init__.py +0 -0
  249. /adam/commands/{nodetool_commands.py → nodetool/nodetool_commands.py} +0 -0
  250. {kaqing-2.0.110.dist-info → kaqing-2.0.214.dist-info}/WHEEL +0 -0
  251. {kaqing-2.0.110.dist-info → kaqing-2.0.214.dist-info}/entry_points.txt +0 -0
adam/utils_athena.py ADDED
@@ -0,0 +1,145 @@
1
+ from collections.abc import Callable
2
+ import functools
3
+ import time
4
+ import boto3
5
+ import botocore
6
+
7
+ from adam.config import Config
8
+ from adam.utils import tabulize, log, log2, log_exc, wait_log
9
+
10
+ # no state utility class
11
+ class Athena:
12
+ @functools.lru_cache()
13
+ def database_names(like: str = None):
14
+ # this function is called only from export currently
15
+ wait_log(f'Inspecting export database schema...')
16
+
17
+ query = f"SELECT schema_name FROM information_schema.schemata WHERE schema_name <> 'information_schema'"
18
+ if like:
19
+ query = f"{query} AND schema_name like '{like}'"
20
+
21
+ with log_exc():
22
+ state, reason, rs = Athena.query(query)
23
+ if rs:
24
+ names = []
25
+ for row in rs[1:]:
26
+ row_data = [col.get('VarCharValue') if col else '' for col in row['Data']]
27
+ names.append(row_data[0])
28
+
29
+ return names
30
+
31
+ return []
32
+
33
+ def clear_cache(cache: str = None):
34
+ if not cache or cache == 'databases':
35
+ Athena.database_names.cache_clear()
36
+ if not cache or cache == 'tables':
37
+ Athena.table_names.cache_clear()
38
+ if not cache or cache == 'columns':
39
+ Athena.column_names.cache_clear()
40
+
41
+ @functools.lru_cache()
42
+ def table_names(database: str = 'audit', function: str = 'audit'):
43
+ table_names = []
44
+ try:
45
+ region_name = Config().get(f'{function}.athena.region', 'us-west-2')
46
+ database_name = Config().get(f'{function}.athena.database', database)
47
+ catalog_name = Config().get(f'{function}.athena.catalog', 'AwsDataCatalog')
48
+
49
+ athena_client = boto3.client('athena', region_name=region_name)
50
+ paginator = athena_client.get_paginator('list_table_metadata')
51
+
52
+ for page in paginator.paginate(CatalogName=catalog_name, DatabaseName=database_name):
53
+ for table_metadata in page.get('TableMetadataList', []):
54
+ table_names.append(table_metadata['Name'])
55
+ except botocore.exceptions.NoCredentialsError as e:
56
+ # aws credentials not found
57
+ if function == 'audit':
58
+ log2(f'Please configure AWS credentials to Audit Log Database.')
59
+ except:
60
+ pass
61
+
62
+ return table_names
63
+
64
+ @functools.lru_cache()
65
+ def column_names(tables: list[str] = [], database: str = None, function: str = 'audit', partition_cols_only = False):
66
+ with log_exc():
67
+ if not database:
68
+ database = Config().get(f'{function}.athena.database', 'audit')
69
+
70
+ if not tables:
71
+ tables = Config().get(f'{function}.athena.tables', 'audit').split(',')
72
+
73
+ table_names = "'" + "','".join([table.strip() for table in tables]) + "'"
74
+
75
+ query = f"select column_name from information_schema.columns where table_name in ({table_names}) and table_schema = '{database}'"
76
+ if partition_cols_only:
77
+ query = f"{query} and extra_info = 'partition key'"
78
+
79
+ _, _, rs = Athena.query(query)
80
+ if rs:
81
+ return [row['Data'][0].get('VarCharValue') for row in rs[1:]]
82
+
83
+ return []
84
+
85
+ def run_query(sql: str, database: str = None, output: Callable[[str], str] = None):
86
+ state, reason, rs = Athena.query(sql, database)
87
+
88
+ log_file = None
89
+ if state == 'SUCCEEDED':
90
+ if rs:
91
+ column_info = rs[0]['Data']
92
+ columns = [col.get('VarCharValue') for col in column_info]
93
+ out = tabulize(rs[1:],
94
+ lambda r: '\t'.join(col.get('VarCharValue') if col else '' for col in r['Data']),
95
+ header='\t'.join(columns),
96
+ separator='\t',
97
+ to=0)
98
+ if output:
99
+ log_file = output(out)
100
+ else:
101
+ log(out)
102
+
103
+ return len(rs)-1, log_file
104
+ else:
105
+ log2(f"Query failed or was cancelled. State: {state}")
106
+ log2(f"Reason: {reason}")
107
+
108
+ return 0, log_file
109
+
110
+ def query(sql: str, database: str = None, function: str = 'audit') -> tuple[str, str, list]:
111
+ region_name = Config().get(f'{function}.athena.region', 'us-west-2')
112
+ athena_client = boto3.client('athena', region_name=region_name)
113
+
114
+ if not database:
115
+ database = Config().get(f'{function}.athena.database', 'audit')
116
+
117
+ s3_output_location = Config().get(f'{function}.athena.output', f's3://s3.ops--{function}/ddl/results')
118
+
119
+ response = athena_client.start_query_execution(
120
+ QueryString=sql,
121
+ QueryExecutionContext={
122
+ 'Database': database
123
+ },
124
+ ResultConfiguration={
125
+ 'OutputLocation': s3_output_location
126
+ }
127
+ )
128
+
129
+ query_execution_id = response['QueryExecutionId']
130
+
131
+ while True:
132
+ query_status = athena_client.get_query_execution(QueryExecutionId=query_execution_id)
133
+ state = query_status['QueryExecution']['Status']['State']
134
+ if state in ['SUCCEEDED', 'FAILED', 'CANCELLED']:
135
+ break
136
+ time.sleep(1)
137
+
138
+ if state == 'SUCCEEDED':
139
+ results_response = athena_client.get_query_results(QueryExecutionId=query_execution_id)
140
+ if results_response['ResultSet']['Rows']:
141
+ return (state, None, results_response['ResultSet']['Rows'])
142
+
143
+ return (state, None, [])
144
+ else:
145
+ return (state, query_status['QueryExecution']['Status'].get('StateChangeReason'), [])
adam/utils_audits.py CHANGED
@@ -1,12 +1,11 @@
1
1
  from datetime import datetime
2
- import functools
3
2
  import getpass
4
3
  import time
5
- import boto3
6
4
  import requests
7
5
 
8
6
  from adam.config import Config
9
- from adam.utils import lines_to_tabular, log, log2
7
+ from adam.utils import OffloadHandler, debug, log2, log_exc, offload
8
+ from adam.utils_athena import Athena
10
9
  from adam.utils_net import get_my_host
11
10
 
12
11
  class AuditMeta:
@@ -34,7 +33,7 @@ class Audits:
34
33
  try:
35
34
  response = requests.post(audit_endpoint, json=payload, timeout=Config().get("audit.timeout", 10))
36
35
  if response.status_code in [200, 201]:
37
- Config().debug(response.text)
36
+ debug(response.text)
38
37
  else:
39
38
  log2(f"Error: {response.status_code} {response.text}")
40
39
  except requests.exceptions.Timeout as e:
@@ -44,15 +43,13 @@ class Audits:
44
43
  checked_in = 0.0
45
44
  cluster_last_checked = 0.0
46
45
 
47
- state, _, rs = Audits.audit_query(f'select partitions_last_checked, clusters_last_checked from meta')
46
+ state, _, rs = Athena.query(f'select partitions_last_checked, clusters_last_checked from meta')
48
47
  if state == 'SUCCEEDED':
49
48
  if len(rs) > 1:
50
- try:
49
+ with log_exc():
51
50
  row = rs[1]['Data']
52
51
  checked_in = float(row[0]['VarCharValue'])
53
52
  cluster_last_checked = float(row[1]['VarCharValue'])
54
- except:
55
- pass
56
53
 
57
54
  return AuditMeta(checked_in, cluster_last_checked)
58
55
 
@@ -69,7 +66,7 @@ class Audits:
69
66
  try:
70
67
  response = requests.post(audit_endpoint, json=payload, timeout=Config().get("audit.timeout", 10))
71
68
  if response.status_code in [200, 201]:
72
- Config().debug(response.text)
69
+ debug(response.text)
73
70
  else:
74
71
  log2(f"Error: {response.status_code} {response.text}")
75
72
  except requests.exceptions.Timeout as e:
@@ -86,108 +83,20 @@ class Audits:
86
83
  f'(select distinct c as name from audit where {Audits.date_from(dt_object)}) as c2',
87
84
  'on c1.name = c2.name where c1.name is null'])
88
85
  log2(query)
89
- state, _, rs = Audits.audit_query(query)
86
+ state, _, rs = Athena.query(query)
90
87
  if state == 'SUCCEEDED':
91
88
  if len(rs) > 1:
92
- try:
89
+ with log_exc():
93
90
  return [r['Data'][0]['VarCharValue'] for r in rs[1:]]
94
- except:
95
- pass
96
91
 
97
92
  return []
98
93
 
99
- @functools.lru_cache()
100
- def audit_table_names():
101
- region_name = Config().get('audit.athena.region', 'us-west-2')
102
- database_name = Config().get('audit.athena.database', 'audit')
103
- catalog_name = Config().get('audit.athena.catalog', 'AwsDataCatalog')
104
-
105
- athena_client = boto3.client('athena', region_name=region_name)
106
- paginator = athena_client.get_paginator('list_table_metadata')
107
-
108
- table_names = []
109
- for page in paginator.paginate(CatalogName=catalog_name, DatabaseName=database_name):
110
- for table_metadata in page.get('TableMetadataList', []):
111
- table_names.append(table_metadata['Name'])
112
-
113
- return table_names
114
-
115
- @functools.lru_cache()
116
- def audit_column_names(tables: list[str] = [], database: str = None, partition_cols_only = False):
117
- if not database:
118
- database = Config().get('audit.athena.database', 'audit')
119
-
120
- if not tables:
121
- tables = Config().get('audit.athena.tables', 'audit').split(',')
122
-
123
- table_names = "'" + "','".join([table.strip() for table in tables]) + "'"
124
-
125
- query = f"select column_name from information_schema.columns where table_name in ({table_names}) and table_schema = '{database}'"
126
- if partition_cols_only:
127
- query = f"{query} and extra_info = 'partition key'"
128
-
129
- _, _, rs = Audits.audit_query(query)
130
- if rs:
131
- return [row['Data'][0].get('VarCharValue') for row in rs[1:]]
132
-
133
- return []
134
-
135
- def run_audit_query(sql: str, database: str = None):
136
- state, reason, rs = Audits.audit_query(sql, database)
137
-
138
- if state == 'SUCCEEDED':
139
- if rs:
140
- column_info = rs[0]['Data']
141
- columns = [col.get('VarCharValue') for col in column_info]
142
- lines = []
143
- for row in rs[1:]:
144
- row_data = [col.get('VarCharValue') if col else '' for col in row['Data']]
145
- lines.append('\t'.join(row_data))
146
-
147
- log(lines_to_tabular(lines, header='\t'.join(columns), separator='\t'))
148
- else:
149
- log2(f"Query failed or was cancelled. State: {state}")
150
- log2(f"Reason: {reason}")
151
-
152
- def audit_query(sql: str, database: str = None) -> tuple[str, str, list]:
153
- athena_client = boto3.client('athena')
154
-
155
- if not database:
156
- database = Config().get('audit.athena.database', 'audit')
157
-
158
- s3_output_location = Config().get('audit.athena.output', 's3://s3.ops--audit/ddl/results')
159
-
160
- response = athena_client.start_query_execution(
161
- QueryString=sql,
162
- QueryExecutionContext={
163
- 'Database': database
164
- },
165
- ResultConfiguration={
166
- 'OutputLocation': s3_output_location
167
- }
168
- )
169
-
170
- query_execution_id = response['QueryExecutionId']
171
-
172
- while True:
173
- query_status = athena_client.get_query_execution(QueryExecutionId=query_execution_id)
174
- state = query_status['QueryExecution']['Status']['State']
175
- if state in ['SUCCEEDED', 'FAILED', 'CANCELLED']:
176
- break
177
- time.sleep(1)
178
-
179
- if state == 'SUCCEEDED':
180
- results_response = athena_client.get_query_results(QueryExecutionId=query_execution_id)
181
- if results_response['ResultSet']['Rows']:
182
- return (state, None, results_response['ResultSet']['Rows'])
183
-
184
- return (state, None, [])
185
- else:
186
- return (state, query_status['QueryExecution']['Status'].get('StateChangeReason'), [])
187
-
188
94
  def date_from(dt_object: datetime):
189
95
  y = dt_object.strftime("%Y")
190
96
  m = dt_object.strftime("%m")
191
97
  d = dt_object.strftime("%d")
192
98
 
193
- return f"y = '{y}' and m = '{m}' and d >= '{d}' or y = '{y}' and m > '{m}' or y > '{y}'"
99
+ return f"y = '{y}' and m = '{m}' and d >= '{d}' or y = '{y}' and m > '{m}' or y > '{y}'"
100
+
101
+ def offload() -> OffloadHandler:
102
+ return offload(max_workers=Config().get('audit.workers', 3))
adam/utils_issues.py ADDED
@@ -0,0 +1,32 @@
1
+ from adam.checks.check_result import CheckResult
2
+ from adam.checks.issue import Issue
3
+ from adam.repl_session import ReplSession
4
+ from adam.utils import tabulize, log2
5
+
6
+ class IssuesUtils:
7
+ def show(check_results: list[CheckResult], in_repl = False):
8
+ IssuesUtils.show_issues(CheckResult.collect_issues(check_results), in_repl=in_repl)
9
+
10
+ def show_issues(issues: list[Issue], in_repl = False):
11
+ if not issues:
12
+ log2('No issues found.')
13
+ else:
14
+ suggested = 0
15
+ log2(f'* {len(issues)} issues found.')
16
+ lines = []
17
+ for i, issue in enumerate(issues, start=1):
18
+ lines.append(f"{i}||{issue.category}||{issue.desc}")
19
+ lines.append(f"||statefulset||{issue.statefulset}@{issue.namespace}")
20
+ lines.append(f"||pod||{issue.pod}@{issue.namespace}")
21
+ if issue.details:
22
+ lines.append(f"||details||{issue.details}")
23
+
24
+ if issue.suggestion:
25
+ lines.append(f'||suggestion||{issue.suggestion}')
26
+ if in_repl:
27
+ ReplSession().prompt_session.history.append_string(issue.suggestion)
28
+ suggested += 1
29
+ tabulize(lines, separator='||', to=2)
30
+ if suggested:
31
+ log2()
32
+ log2(f'* {suggested} suggested commands are added to history. Press <Up> arrow to access them.')
@@ -0,0 +1,35 @@
1
+ import sys
2
+ from typing import TypeVar
3
+
4
+ from adam.utils_k8s.app_pods import AppPods
5
+ from adam.utils_k8s.pod_exec_result import PodExecResult
6
+ from adam.utils import log, log2
7
+ from adam.utils_k8s.pods import Pods
8
+ from .kube_context import KubeContext
9
+
10
+ T = TypeVar('T')
11
+
12
+ # utility collection on app clusters; methods are all static
13
+ class AppClusters:
14
+ def exec(pods: list[str],
15
+ namespace: str,
16
+ command: str,
17
+ action: str = 'action',
18
+ max_workers=0,
19
+ show_out=True,
20
+ on_any = False,
21
+ shell = '/bin/sh',
22
+ backgrounded = False) -> list[PodExecResult]:
23
+ samples = 1 if on_any else sys.maxsize
24
+ msg = 'd`Running|Ran ' + action + ' command onto {size} pods'
25
+ with Pods.parallelize(pods, max_workers, samples, msg, action=action) as exec:
26
+ results: list[PodExecResult] = exec.map(lambda pod: AppPods.exec(pod, namespace, command, False, False, shell, backgrounded))
27
+ for result in results:
28
+ if KubeContext.show_out(show_out):
29
+ log(result.command)
30
+ if result.stdout:
31
+ log(result.stdout)
32
+ if result.stderr:
33
+ log2(result.stderr)
34
+
35
+ return results
@@ -0,0 +1,41 @@
1
+ import functools
2
+ from typing import List
3
+ from kubernetes import client
4
+
5
+ from adam.config import Config
6
+ from adam.utils_k8s.pods import Pods
7
+ from adam.utils_k8s.pod_exec_result import PodExecResult
8
+ from adam.repl_session import ReplSession
9
+
10
+ # utility collection on app pods; methods are all static
11
+ class AppPods:
12
+ @functools.lru_cache()
13
+ def pod_names(namespace: str, env: str, app: str):
14
+ if not env or not app:
15
+ return []
16
+
17
+ return [pod.metadata.name for pod in AppPods.app_pods(namespace, env, app)]
18
+
19
+ def app_pods(namespace: str, env: str, app: str) -> List[client.V1Pod]:
20
+ v1 = client.CoreV1Api()
21
+
22
+ env_key = Config().get('app.env', 'c3__env-0')
23
+ app_key = Config().get('app.app', 'c3__app-0')
24
+ label_selector = f'applicationGroup=c3,{env_key}=0{env}0,{app_key}=0{app}0'
25
+
26
+ return v1.list_namespaced_pod(namespace, label_selector=label_selector).items
27
+
28
+ def exec(pod_name: str,
29
+ namespace: str,
30
+ command: str,
31
+ show_out = True,
32
+ throw_err = False,
33
+ shell = '/bin/sh',
34
+ backgrounded = False) -> PodExecResult:
35
+ container = Config().get('app.container-name', 'c3-server')
36
+ r = Pods.exec(pod_name, container, namespace, command, show_out = show_out, throw_err = throw_err, shell = shell, backgrounded = backgrounded)
37
+
38
+ if r and r.log_file:
39
+ ReplSession().append_history(f':cat {r.log_file}')
40
+
41
+ return r
@@ -1,33 +1,48 @@
1
- from concurrent.futures import ThreadPoolExecutor
2
1
  import sys
3
2
  from typing import TypeVar
4
3
 
4
+ from adam.config import Config
5
5
  from adam.utils_k8s.cassandra_nodes import CassandraNodes
6
- from adam.pod_exec_result import PodExecResult
7
- from adam.utils import log2
8
- from .statefulsets import StatefulSets
9
- from .kube_context import KubeContext
6
+ from adam.utils_k8s.pod_exec_result import PodExecResult
7
+ from adam.utils import log, log2
8
+ from adam.utils_k8s.pods import Pods
9
+ from adam.utils_k8s.statefulsets import StatefulSets
10
10
 
11
11
  T = TypeVar('T')
12
12
 
13
13
  # utility collection on cassandra clusters; methods are all static
14
14
  class CassandraClusters:
15
- def exec(statefulset: str, namespace: str, command: str, action: str = 'action',
16
- max_workers=0, show_out=True, on_any = False, shell = '/bin/sh', background = False) -> list[PodExecResult]:
17
- def body(executor: ThreadPoolExecutor, pod: str, namespace: str, show_out: bool):
18
- if executor:
19
- return executor.submit(CassandraNodes.exec, pod, namespace, command, False, False, shell, background)
15
+ def exec(sts: str,
16
+ namespace: str,
17
+ command: str,
18
+ action: str = 'action',
19
+ max_workers=0,
20
+ show_out=True,
21
+ on_any = False,
22
+ shell = '/bin/sh',
23
+ backgrounded = False,
24
+ log_file = None,
25
+ history=True) -> list[PodExecResult]:
20
26
 
21
- return CassandraNodes.exec(pod, namespace, command, show_out=show_out, background=background)
27
+ pods = StatefulSets.pod_names(sts, namespace)
28
+ samples = 1 if on_any else sys.maxsize
29
+ if (backgrounded or command.endswith(' &')) and not log_file:
30
+ log_file = Pods.log_file(command)
22
31
 
23
- def post(result, show_out: bool):
24
- if KubeContext.show_out(show_out):
25
- print(result.command)
26
- if result.stdout:
27
- print(result.stdout)
28
- if result.stderr:
29
- log2(result.stderr, file=sys.stderr)
32
+ msg = 'd`Running|Ran ' + action + ' command onto {size} pods'
33
+ with Pods.parallelize(pods, max_workers, samples, msg, action=action) as exec:
34
+ results: list[PodExecResult] = exec.map(lambda pod: CassandraNodes.exec(pod, namespace, command, False, False, shell, backgrounded, log_file, history))
35
+ for result in results:
36
+ if show_out and not Config().is_debug():
37
+ log(result.command)
38
+ if result.stdout:
39
+ log(result.stdout)
40
+ if result.stderr:
41
+ log2(result.stderr)
30
42
 
31
- return result
43
+ return results
32
44
 
33
- return StatefulSets.on_cluster(statefulset, namespace, body, post=post, action=action, max_workers=max_workers, show_out=show_out, on_any=on_any, background=background)
45
+ def pod_names_by_host_id(sts: str, ns: str):
46
+ pods = StatefulSets.pods(sts, ns)
47
+
48
+ return {CassandraNodes.get_host_id(pod.metadata.name, ns): pod.metadata.name for pod in pods}
@@ -1,17 +1,26 @@
1
1
  from adam.config import Config
2
2
  from adam.utils_k8s.pods import Pods
3
3
  from adam.utils_k8s.secrets import Secrets
4
- from adam.pod_exec_result import PodExecResult
4
+ from adam.utils_k8s.pod_exec_result import PodExecResult
5
5
  from adam.repl_session import ReplSession
6
6
 
7
7
  # utility collection on cassandra nodes; methods are all static
8
8
  class CassandraNodes:
9
- def exec(pod_name: str, namespace: str, command: str, show_out = True, throw_err = False, shell = '/bin/sh', background = False) -> PodExecResult:
10
- r = Pods.exec(pod_name, "cassandra", namespace, command, show_out = show_out, throw_err = throw_err, shell = shell, background = background)
9
+ def exec(pod_name: str,
10
+ namespace: str,
11
+ command: str,
12
+ show_out = True,
13
+ throw_err = False,
14
+ shell = '/bin/sh',
15
+ backgrounded = False,
16
+ log_file = None,
17
+ history = True) -> PodExecResult:
18
+ r = Pods.exec(pod_name, "cassandra", namespace, command, show_out = show_out, throw_err = throw_err, shell = shell, backgrounded = backgrounded, log_file=log_file)
11
19
 
12
- if r and Config().get('repl.history.push-cat-remote-log-file', True):
13
- if r.log_file and ReplSession().prompt_session:
14
- ReplSession().prompt_session.history.append_string(f'bash {r.pod} cat {r.log_file}')
20
+ if history and r and r.log_file:
21
+ entry = f':cat {r.log_file}'
22
+
23
+ ReplSession().append_history(entry)
15
24
 
16
25
  return r
17
26
 
@@ -1,10 +1,10 @@
1
+ import functools
1
2
  import re
2
- import time
3
3
  from kubernetes import client
4
4
 
5
5
  from adam.config import Config
6
6
  from .kube_context import KubeContext
7
- from adam.utils import elapsed_time, lines_to_tabular, log2
7
+ from adam.utils import log2, log_exc
8
8
 
9
9
 
10
10
  # utility collection; methods are all static
@@ -19,14 +19,12 @@ class CustomResources:
19
19
  strip = Config().get('app.strip', '0')
20
20
 
21
21
  v1 = client.CustomObjectsApi()
22
- try:
22
+ with log_exc():
23
23
  c3cassandras = v1.list_cluster_custom_object(group=group, version=v, plural=plural)
24
24
  for c in c3cassandras.items():
25
25
  if c[0] == 'items':
26
26
  for item in c[1]:
27
27
  app_ids_by_ss[f"{item['metadata']['name']}@{item['metadata']['namespace']}"] = item['metadata']['labels'][label].strip(strip)
28
- except Exception:
29
- pass
30
28
 
31
29
  return app_ids_by_ss
32
30
 
@@ -121,11 +119,10 @@ class CustomResources:
121
119
  body = bkspecs
122
120
  pretty = 'true'
123
121
 
124
- try:
122
+ with log_exc(lambda e: "Exception when calling create_medusa_backupjob.create_namespaced_custom_object: %s\n" % e):
125
123
  api_instance.create_namespaced_custom_object(group, version, namespace, plural, body, pretty=pretty)
126
124
  log2(f"create_medusa_backupjob: created Full Backup {bkname}: {api_instance}")
127
- except Exception as e:
128
- log2("Exception when calling create_medusa_backupjob.create_namespaced_custom_object: %s\n" % e)
125
+
129
126
  return None
130
127
 
131
128
  def create_medusa_restorejob(restorejobname: str, bkname: str, dc: str, ns: str):
@@ -154,11 +151,10 @@ class CustomResources:
154
151
  body = rtspecs
155
152
  pretty = 'true'
156
153
 
157
- try:
154
+ with log_exc(lambda e: "Exception when calling create_medusa_restorejob.create_namespaced_custom_object: %s\n" % e):
158
155
  api_instance.create_namespaced_custom_object(group, version, namespace, plural, body, pretty=pretty)
159
156
  log2(f"create_medusa_restorejob: created Restore Job {restorejobname}: {api_instance}")
160
- except Exception as e:
161
- log2("Exception when calling create_medusa_restorejob.create_namespaced_custom_object: %s\n" % e)
157
+
162
158
  return None
163
159
 
164
160
  def medusa_show_backup_names(dc: str, ns: str) -> list[dict]:
@@ -171,6 +167,10 @@ class CustomResources:
171
167
 
172
168
  return None
173
169
 
170
+ def clear_caches():
171
+ CustomResources.medusa_show_backupjobs.cache_clear()
172
+
173
+ @functools.lru_cache()
174
174
  def medusa_show_backupjobs(dc: str, ns: str) -> list[dict]:
175
175
  api_instance = client.CustomObjectsApi()
176
176
  group = 'medusa.k8ssandra.io'
@@ -180,11 +180,10 @@ class CustomResources:
180
180
  pretty = 'true'
181
181
  label_selector = 'cassandra.datastax.com/datacenter=' + dc
182
182
 
183
- try:
183
+ with log_exc(lambda e: "Exception when calling medusa_show_backupjobs.list_namespaced_custom_object: %s\n" % e):
184
184
  api_response = api_instance.list_namespaced_custom_object(group, version, namespace, plural, pretty=pretty, label_selector=label_selector)
185
185
  return api_response['items']
186
- except Exception as e:
187
- log2("Exception when calling medusa_show_backupjobs.list_namespaced_custom_object: %s\n" % e)
186
+
188
187
  return None
189
188
 
190
189
  def medusa_show_restorejobs(dc: str, ns: str):
@@ -196,11 +195,11 @@ class CustomResources:
196
195
  pretty = 'true'
197
196
  label_selector = 'cassandra.datastax.com/datacenter=' + dc
198
197
  rtlist = []
199
- try:
198
+
199
+ with log_exc(lambda e: "Exception when calling medusa_show_restorejobs.list_namespaced_custom_object: %s\n" % e):
200
200
  api_response = api_instance.list_namespaced_custom_object(group, version, namespace, plural, pretty=pretty, label_selector=label_selector)
201
201
  for x in api_response['items']:
202
202
  rtlist.append(f"{x['metadata']['name']}\t{x['metadata']['creationTimestamp']}\t{x['status'].get('finishTime', '')}")
203
203
  return rtlist
204
- except Exception as e:
205
- log2("Exception when calling medusa_show_restorejobs.list_namespaced_custom_object: %s\n" % e)
204
+
206
205
  return None
@@ -1,7 +1,7 @@
1
1
  from kubernetes import client
2
2
 
3
3
  from adam.config import Config
4
- from adam.utils import log2
4
+ from adam.utils import debug, log2
5
5
 
6
6
  # utility collection on ingresses; methods are all static
7
7
  class Ingresses:
@@ -63,7 +63,7 @@ class Ingresses:
63
63
  log2(f"200 Ingress '{name}' in namespace '{namespace}' deleted successfully.")
64
64
  else:
65
65
  api.delete_namespaced_ingress(name=name, namespace=namespace)
66
- Config().debug(f"200 Ingress '{name}' in namespace '{namespace}' deleted successfully.")
66
+ debug(f"200 Ingress '{name}' in namespace '{namespace}' deleted successfully.")
67
67
  except client.ApiException as e:
68
68
  log2(f"Error deleting Ingress: {e}")
69
69