forked from guardian/athena-cli
-
Notifications
You must be signed in to change notification settings - Fork 1
/
athena_cli.py
executable file
·445 lines (370 loc) · 14.6 KB
/
athena_cli.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
import argparse
import atexit
import csv
import json
import os
import subprocess
import sys
import time
import uuid
try:
import gnureadline as readline
except ImportError:
import readline
import boto3
import botocore
from botocore.exceptions import ClientError, ParamValidationError
from cmd2 import Cmd, utils
from tabulate import tabulate
LESS = "less -FXRSn"
HISTORY_FILE_SIZE = 500
DEFAULT_WORKGROUP = 'primary'
__version__ = '0.1.13'
class AthenaBatch(object):
def __init__(self, athena, db=None, format='CSV'):
self.athena = athena
self.dbname = db
self.format = format
def execute(self, statement):
execution_id = self.athena.start_query_execution(self.dbname, statement)
if not execution_id:
return
while True:
stats = self.athena.get_query_execution(execution_id)
status = stats['QueryExecution']['Status']['State']
if status in ['SUCCEEDED', 'FAILED', 'CANCELLED']:
break
time.sleep(0.2) # 200ms
if status == 'SUCCEEDED':
results = self.athena.get_query_results(execution_id)
headers = [h['Name'] for h in results['ResultSet']['ResultSetMetadata']['ColumnInfo']]
if self.format in ['CSV', 'CSV_HEADER']:
csv_writer = csv.writer(sys.stdout, quoting=csv.QUOTE_ALL)
if self.format == 'CSV_HEADER':
csv_writer.writerow(headers)
csv_writer.writerows([row for row in self.athena.yield_rows(results, headers)])
elif self.format == 'TSV':
print(tabulate([row for row in self.athena.yield_rows(results, headers)], tablefmt='tsv'))
elif self.format == 'TSV_HEADER':
print(tabulate([row for row in self.athena.yield_rows(results, headers)], headers=headers, tablefmt='tsv'))
elif self.format == 'VERTICAL':
for num, row in enumerate(self.athena.yield_rows(results, headers)):
print('--[RECORD {}]--'.format(num + 1))
print(tabulate(zip(*[headers, row]), tablefmt='presto'))
else: # ALIGNED
print(tabulate([x for x in self.athena.yield_rows(results, headers)], headers=headers, tablefmt='presto'))
if status == 'FAILED':
print(stats['QueryExecution']['Status']['StateChangeReason'])
class AthenaShell(Cmd, object):
multiline_commands = [
'(', 'select', 'desc', 'using', 'with', 'values', 'create', 'table', 'insert', 'delete',
'describe', 'grant', 'revoke', 'explain', 'show', 'use', 'drop', 'alter', 'set', 'reset',
'start', 'commit', 'rollback', 'call', 'prepare', 'deallocate', 'execute', 'msck', 'values',
'SELECT', 'DESC', 'USING', 'WITH', 'VALUES', 'CREATE', 'TABLE', 'INSERT', 'DELETE',
'DESCRIBE', 'GRANT', 'REVOKE', 'EXPLAIN', 'SHOW', 'USE', 'DROP', 'ALTER', 'SET', 'RESET',
'START', 'COMMIT', 'ROLLBACK', 'CALL', 'PREPARE', 'DEALLOCATE', 'EXECUTE', 'MSCK', 'VALUES'
]
def __init__(self, athena, db=None):
super().__init__(multiline_commands=AthenaShell.multiline_commands)
self.allow_cli_args = False
self.athena = athena
self.dbname = db
self.execution_id = None
self.row_count = 0
self.set_prompt()
self.pager = os.environ.get('ATHENA_CLI_PAGER', LESS).split(' ')
self.hist_file = os.path.join(os.path.expanduser("~"), ".athena_history")
self.init_history()
def set_prompt(self):
self.prompt = 'athena:%s> ' % self.dbname if self.dbname else 'athena> '
self.continuation_prompt = ' ' * (len(self.prompt) - 3) + '-> '
def init_history(self):
try:
readline.read_history_file(self.hist_file)
readline.set_history_length(HISTORY_FILE_SIZE)
readline.write_history_file(self.hist_file)
except IOError:
readline.write_history_file(self.hist_file)
atexit.register(self.save_history)
def preloop(self):
if os.path.exists(self.hist_file):
readline.read_history_file(self.hist_file)
def cmdloop_with_cancel(self, intro=None):
try:
self.cmdloop(intro)
except KeyboardInterrupt:
if self.execution_id:
self.athena.stop_query_execution(self.execution_id)
print('\n\n%s' % self.athena.console_link(self.execution_id))
print('\nQuery aborted by user')
else:
print('\r')
self.cmdloop_with_cancel(intro)
def postloop(self):
self.save_history()
def save_history(self):
try:
readline.write_history_file(self.hist_file)
except IOError:
pass
def do_help(self, arg):
help_output = """
Supported commands:
QUIT
SELECT
INSERT INTO
ALTER DATABASE <schema>
ALTER TABLE <table>
CREATE DATABASE <schema>
CREATE TABLE <table>
CREATE TABLE <table> AS <query>
CREATE [OR REPLACE] VIEW <view> AS <query>
DESCRIBE <table>
DESCRIBE <view>
DROP DATABASE <schema>
DROP TABLE <table>
DROP VIEW [IF EXISTS] <view>
MSCK REPAIR TABLE <table>
SHOW COLUMNS FROM <table>
SHOW CREATE TABLE <table>
SHOW CREATE VIEW <view>
SHOW DATABASES [LIKE <pattern>]
SHOW PARTITIONS <table>
SHOW TABLES [IN <schema>] [<pattern>]
SHOW TBLPROPERTIES <table>
SHOW VIEWS [IN <schema>] [LIKE <pattern>]
USE [<catalog>.]<schema>
VALUES row [, ...]
See http://docs.aws.amazon.com/athena/latest/ug/language-reference.html
"""
print(help_output)
def do_quit(self, arg):
print()
return -1
def do_EOF(self, arg):
return self.do_quit(arg)
def do_use(self, schema):
self.dbname = schema.rstrip(';')
self.set_prompt()
def do_set(self, arg):
try:
statement, param_name, val = arg.parsed.raw.split(None, 2)
val = val.strip()
param_name = param_name.strip().lower()
if param_name == 'debug':
self.athena.debug = utils.cast(True, val)
except (ValueError, AttributeError):
self.do_help(arg)
super().do_set(arg)
def default(self, line):
if not line:
return
self.execution_id = self.athena.start_query_execution(self.dbname, line.command_and_args)
if not self.execution_id:
return
while True:
stats = self.athena.get_query_execution(self.execution_id)
status = stats['QueryExecution']['Status']['State']
status_line = 'Query {0}, {1:9}'.format(self.execution_id, status)
sys.stdout.write('\r' + status_line)
sys.stdout.flush()
if status in ['SUCCEEDED', 'FAILED', 'CANCELLED']:
break
time.sleep(0.2) # 200ms
sys.stdout.write('\r' + ' ' * len(status_line) + '\r') # delete query status line
sys.stdout.flush()
if status == 'SUCCEEDED':
results = self.athena.get_query_results(self.execution_id)
headers = [h['Name'] for h in results['ResultSet']['ResultSetMetadata']['ColumnInfo']]
row_count = len(results['ResultSet']['Rows'])
if headers and len(results['ResultSet']['Rows']) and results['ResultSet']['Rows'][0]['Data'][0].get('VarCharValue', None) == headers[0]:
row_count -= 1 # don't count header
process = subprocess.Popen(self.pager, stdin=subprocess.PIPE)
process.stdin.write(tabulate([x for x in self.athena.yield_rows(results, headers)], headers=headers, tablefmt='presto').encode('utf-8'))
process.communicate()
print('(%s rows)\n' % row_count)
print('Query {0}, {1}'.format(self.execution_id, status))
if status == 'FAILED':
print(stats['QueryExecution']['Status']['StateChangeReason'])
print(self.athena.console_link(self.execution_id))
submission_date = stats['QueryExecution']['Status']['SubmissionDateTime']
completion_date = stats['QueryExecution']['Status']['CompletionDateTime']
execution_time = stats['QueryExecution']['Statistics']['EngineExecutionTimeInMillis']
data_scanned = stats['QueryExecution']['Statistics']['DataScannedInBytes']
query_cost = data_scanned / 1000000000000.0 * 5.0
print('Time: {}, CPU Time: {}ms total, Data Scanned: {}, Cost: ${:,.2f}\n'.format(
str(completion_date - submission_date).split('.')[0],
execution_time,
human_readable(data_scanned),
query_cost
))
class Athena(object):
def __init__(self, profile, region=None, bucket=None, workgroup=None, debug=False, encryption=False):
self.session = boto3.Session(profile_name=profile, region_name=region)
self.athena = self.session.client('athena')
self.region = region or os.environ.get('AWS_DEFAULT_REGION', None) or self.session.region_name
self.bucket = bucket or self.default_bucket
self.workgroup = workgroup
self.debug = debug
self.encryption = encryption
@property
def default_bucket(self):
account_id = self.session.client('sts').get_caller_identity().get('Account')
return 's3://{}-query-results-{}-{}'.format(self.session.profile_name or 'aws-athena', account_id, self.region)
def start_query_execution(self, db, query):
try:
if not db:
raise ValueError('Schema must be specified when session schema is not set')
result_configuration = {
'OutputLocation': self.bucket,
}
if self.encryption:
result_configuration['EncryptionConfiguration'] = {
'EncryptionOption': 'SSE_S3'
}
return self.athena.start_query_execution(
QueryString=query,
ClientRequestToken=str(uuid.uuid4()),
QueryExecutionContext={
'Database': db
},
ResultConfiguration=result_configuration,
WorkGroup=self.workgroup
)['QueryExecutionId']
except (ClientError, ParamValidationError, ValueError) as e:
print(e)
return
def get_query_execution(self, execution_id):
try:
return self.athena.get_query_execution(
QueryExecutionId=execution_id
)
except ClientError as e:
print(e)
def get_query_results(self, execution_id):
try:
results = None
paginator = self.athena.get_paginator('get_query_results')
page_iterator = paginator.paginate(
QueryExecutionId=execution_id
)
for page in page_iterator:
if results is None:
results = page
else:
results['ResultSet']['Rows'].extend(page['ResultSet']['Rows'])
except ClientError as e:
sys.exit(e)
if self.debug:
print(json.dumps(results, indent=2))
return results
def stop_query_execution(self, execution_id):
try:
return self.athena.stop_query_execution(
QueryExecutionId=execution_id
)
except ClientError as e:
sys.exit(e)
@staticmethod
def yield_rows(results, headers):
for row in results['ResultSet']['Rows']:
# https://forums.aws.amazon.com/thread.jspa?threadID=256505
if headers and row['Data'][0].get('VarCharValue', None) == headers[0]:
continue # skip header
yield [d.get('VarCharValue', 'NULL') for d in row['Data']]
def console_link(self, execution_id):
return 'https://{0}.console.aws.amazon.com/athena/home?force®ion={0}#query/history/{1}'.format(self.region, execution_id)
def human_readable(size, precision=2):
suffixes = ['B', 'KB', 'MB', 'GB', 'TB']
suffixIndex = 0
while size > 1024 and suffixIndex < 4:
suffixIndex += 1 # increment the index of the suffix
size = size / 1024.0 # apply the division
return "%.*f%s" % (precision, size, suffixes[suffixIndex])
def main():
parser = argparse.ArgumentParser(
prog='athena',
usage='athena [--debug] [--execute <statement>] [--output-format <format>] [--schema <schema>]'
' [--profile <profile>] [--region <region>] [--s3-bucket <bucket>] [--server-side-encryption] [--version]',
description='Athena interactive console'
)
parser.add_argument(
'--debug',
action='store_true',
help='enable debug mode'
)
parser.add_argument(
'--execute',
metavar='STATEMENT',
help='execute statement in batch mode'
)
parser.add_argument(
'--output-format',
choices=('ALIGNED', 'VERTICAL', 'CSV', 'TSV', 'CSV_HEADER', 'TSV_HEADER', 'NULL'),
dest='format',
help='output format for batch mode'
)
parser.add_argument(
'--schema',
'--database',
'--db',
default='default',
help='default schema'
)
parser.add_argument(
'--profile',
help='AWS profile'
)
parser.add_argument(
'--region',
help='AWS region'
)
parser.add_argument(
'--s3-bucket',
'--bucket',
dest='bucket',
help='AWS S3 bucket for query results'
)
parser.add_argument(
'--workgroup',
default=DEFAULT_WORKGROUP,
help='Athena workgroup'
)
parser.add_argument(
'--server-side-encryption',
'--encryption',
dest='encryption',
action='store_true',
help='Use server-side-encryption for query results'
)
parser.add_argument(
'--version',
action='store_true',
help='show version info and exit'
)
args = parser.parse_args()
if args.debug:
boto3.set_stream_logger(name='botocore')
if args.version:
print('Athena CLI %s' % __version__)
sys.exit()
profile = args.profile or os.environ.get('AWS_DEFAULT_PROFILE', None) or os.environ.get('AWS_PROFILE', None)
try:
athena = Athena(
profile,
region=args.region,
bucket=args.bucket,
workgroup=args.workgroup,
debug=args.debug,
encryption=args.encryption
)
except botocore.exceptions.ClientError as e:
sys.exit(e)
if args.execute:
batch = AthenaBatch(athena, db=args.schema, format=args.format)
batch.execute(statement=args.execute)
else:
shell = AthenaShell(athena, db=args.schema)
shell.cmdloop_with_cancel()
if __name__ == '__main__':
main()