-
Notifications
You must be signed in to change notification settings - Fork 0
/
dbd_server
executable file
·567 lines (467 loc) · 19.4 KB
/
dbd_server
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
#!/usr/bin/env python
import datetime
import functools
import json
import logging
import socket
import sys
import time
import traceback
import argparse
try:
import argcomplete
except ImportError:
argcomplete = None
from dateutil import tz
from flask import Flask, abort, render_template, request, Response
import MySQLdb, _mysql_exceptions
import paste.httpserver
__version__ = '1.0.1'
# Default args
HTTP_DEFAULT_ADDRESS = '0.0.0.0'
HTTP_DEFAULT_PORT = 8888
HTTP_DEFAULT_SSL_PRIVATE_KEY = 'ssl.key'
HTTP_DEFAULT_SSL_PUBLIC_KEY = 'ssl.crt'
DB_DEFAULT_PORT = 3306
NULL_MAGIC_STRING = '$$NULL$$'
app = application = Flask(__name__.split('.')[0])
logger = logging.getLogger(__name__)
quote = MySQLdb.escape_string
arguments = {} # Parsed arguments
def requires_auth(f):
"""
Authentication decorator used for Flask endpoints.
If you're mounting this script as a WSGI endpoint and you're using Apache,
ensure WSGIPassAuthorization=On in Apache's config, or auth will always fail.
"""
@functools.wraps(f)
def requires_auth_decorated(*args, **kwargs):
expected_username = arguments.get('listen_username')
expected_password = arguments.get('listen_password')
if expected_username and expected_password:
# Authentication is required (since user and pass configured)
creds = request.authorization
if (not creds) or (not (creds.username == expected_username and creds.password == expected_password)):
# Authentication failed or credentials not provided
logger.warn('Login failed for %s when accessing %s' % (request.remote_addr, request.url))
return make_text_response('Authentication failed\n', 401)
# Pass through
return f(*args, **kwargs)
return requires_auth_decorated
def requires_acceptance_of(mime_types):
"""
Accept mime-type decorator used for Flask endpoints.
"""
def inner_fn(f):
def requires_acceptance_of_decorated(*args, **kwargs):
best_match = request.accept_mimetypes.best_match(mime_types)
if best_match is None:
# 506 Not Acceptable
return make_text_response('Only acceptable MIME types are: %s\n' % (', '.join(mime_types)), 506)
else:
return f(*args, **kwargs)
return functools.wraps(f)(requires_acceptance_of_decorated)
return inner_fn
@app.errorhandler(Exception)
def error_handler(exc):
"""
Error handler for uncaught exceptions.
"""
trace = traceback.format_exc()
logger.error(exc)
logger.error(trace)
return json.dumps({
'exception': exc.__class__.__name__,
'message': str(exc),
'traceback_lines': trace.splitlines(),
'traceback': trace
}), 500, {
'Content-Type': 'application/json'
}
@app.route('/favicon.ico')
@app.route('/index.html')
def favicon():
"""
Files that the browser may automatically ask for.
"""
abort(404)
@app.route('/<string:database>/')
@requires_auth
@requires_acceptance_of(['text/csv'])
def tables(database):
"""
CSV list of all supported tables.
"""
if not is_supported_database(database):
return make_text_response('Database "%s" is unsupported or unavailable' % database, 404)
conn = get_db_connection()
try:
supported_tables = dependency_sort_tables(conn, database,
get_autoupdate_timestamp_columns(conn, database).keys())
return make_csv_response([(row,) for row in supported_tables], ['table'])
finally:
conn.close()
@app.route('/')
def databases():
supported_databases = get_supported_databases()
return make_csv_response([(row,) for row in supported_databases], ['database'])
@app.route('/<string:database>/<string:table>/')
@requires_auth
@requires_acceptance_of(['text/csv'])
def updated_rows(database, table):
"""
CSV list of all rows modified since :since: (in the query args) in the given table.
"""
if not is_supported_database(database):
return make_text_response('Database "%s" is unsupported or unavailable' % database, 404)
conn = get_db_connection()
try:
timestamp_columns = get_autoupdate_timestamp_columns(conn, database)
# There can only be one auto-updating timestamp column in a table
ts_column = timestamp_columns.get(table)
if ts_column is None:
return make_text_response('Table "%s" does not have an auto-updated timestamp column\n', 404)
# Since filter
since = get_datetime_arg('since')
# Column projection
columns = get_projection(conn, database, table,
include_columns=get_list_arg('include_columns'),
exclude_columns=get_list_arg('exclude_columns'))
if len(columns) == 0:
return make_text_response('No matching columns found\n', 400)
# Build query to fetch updated rows
cursor = conn.cursor()
# Filter
where_expr = []
where_args = []
if since is not None:
where_expr.append('`%s` > %%s' % quote(ts_column))
where_args.append(since.astimezone(get_db_timezone(conn)).replace(tzinfo=None))
if len(where_expr):
where_stmt = ' where ' + ' and '.join(where_expr)
else:
where_stmt = ''
query = """
select `%(projection)s`
from `%(database)s`.`%(table)s`
%(where_stmt)s
order by `%(ts_column)s`
lock in share mode
""" % dict(
projection='`, `'.join(map(quote, columns)),
database=quote(database),
table=quote(table),
where_stmt=where_stmt,
ts_column=quote(ts_column))
# Execute query
logger.info('Querying %s...' % table)
logger.debug(query % tuple(where_args))
cursor.execute(query, where_args)
return make_csv_response(cursor.fetchall(), columns)
finally:
conn.close()
def make_csv_response(row_iter, column_names):
"""
Helper that constructs a streaming CSV response to send back to the client.
"""
return Response(CSVGenerator()(row_iter, column_names),
headers={'Content-Type': 'text/csv'})
def make_text_response(message, status_code):
"""
Helper that constructs a text response to send back to the client.
"""
return Response(message, status_code,
headers={'Content-Type': 'text/plain'})
class CSVGenerator(object):
def __init__(self,
sep_char=',',
quote_char='"',
escape_char='\\',
newline_char='\n'):
self.sep_char = sep_char
self.quote_char = quote_char
self.escape_char = escape_char
self.newline_char = newline_char
def __call__(self, row_iterator, column_names):
"""
Generator streams rows to the client as they are fetched.
This prevents server-side buffering of results, which could eat alot of memory.
"""
assert len(column_names) > 0
emit_header = True
for row in row_iterator:
assert len(row) == len(column_names), '%d != %d' % (len(row), len(column_names))
# Emit header as first row
if emit_header:
yield self._encode_row(column_names, column_names)
emit_header = False
yield self._encode_row(row, column_names)
def _encode_row(self, row, column_names):
"""
Encodes a row in CSV format.
Used instead of csvwriter since it's quicker.
"""
encoded_row = []
for column_idx, column in enumerate(column_names):
encoded_row.append(self._encode_column(row[column_idx]))
return ','.join(encoded_row) + self.newline_char
def _encode_column(self, data):
"""
Encodes and quotes a single CSV column.
"""
if data is None:
return NULL_MAGIC_STRING
else:
escaped = str(data) \
.replace('\0', '') \
.replace(self.escape_char, self.escape_char * 2) \
.replace(self.quote_char, self.escape_char + self.quote_char)
return self.quote_char + escaped + self.quote_char
def get_projection(conn, database, table, include_columns=None, exclude_columns=None):
"""
Determine projection for a table based on intersection of include_columns and
available columns (defined in schema) with the exception of exclude_columns.
"""
cursor = conn.cursor()
cursor.execute("""
select column_name
from information_schema.columns
where table_schema = %s and table_name = %s
order by ordinal_position
""", (database, table))
def column_matches(column_name):
if len(include_columns):
if column_name not in include_columns:
return False
if len(exclude_columns):
if column_name in exclude_columns:
return False
return True
return [r[0] for r in cursor.fetchall() if column_matches(r[0])]
def is_supported_database(database_name):
return database_name in get_supported_databases()
def get_supported_databases():
"""
Returns a list of supported database names.
If the --db-databases argument was specified, then return the intersection.
"""
conn = get_db_connection()
try:
cursor = conn.cursor()
cursor.execute("""
select schema_name
from information_schema.schemata
order by schema_name
""")
all_databases = set([row[0] for row in cursor.fetchall()])
if arguments['source_databases']:
database_names = set(arguments['source_databases'].split(','))
return database_names.intersection(all_databases)
else:
return all_databases
finally:
conn.close()
def dependency_sort_tables(conn, database, table_names):
table_set = "', '".join(map(quote, table_names))
cursor = conn.cursor()
query = """
select distinct
kcu.table_name,
kcu.referenced_table_name
from information_schema.table_constraints tc
join information_schema.key_column_usage kcu on
kcu.constraint_schema = tc.constraint_schema and
kcu.constraint_name = tc.constraint_name and
kcu.table_schema = tc.table_schema and
kcu.table_name = tc.table_name
where
tc.constraint_type = 'FOREIGN KEY' and
tc.table_schema = '%s' and
tc.table_name in ('%s') and
kcu.referenced_table_name in ('%s')
order by
kcu.table_name,
kcu.referenced_table_name
""" % (quote(database), table_set, table_set)
logger.debug('depsort query: %s' % query)
cursor.execute(query)
deps = [(row[0], row[1]) for row in cursor.fetchall()]
logger.debug('deps: %s' % deps)
dep_sorted = table_names
#assert dep_sorted == ['applicant_watchers', 'job_app_notes', 'job_app'], dep_sorted
# TODO: implement!
return dep_sorted
def get_autoupdate_timestamp_columns(conn, database):
"""
Returns a dict of {table_name: timestamped_column_name} for only the
tables that have auto-updated timestamps.
"""
cursor = conn.cursor()
cursor.execute("""
select
table_name,
column_name
from information_schema.columns
where
table_schema = %s and
data_type = 'timestamp' and
extra = 'on update CURRENT_TIMESTAMP'
order by table_name
""", (database,))
# There shouldn't be any duplicate entries for tables in this list, since
# MySQL specifies that there can only be one auto-updated timestamp column.
return dict(map(lambda r: (r[0], r[1]), cursor.fetchall()))
def get_datetime_arg(key, args=None):
"""
Get a query argument containing a date and time.
Assumes argument is in UTC timezone.
Returns None if nothing found.
Raises a ValueError on parse failure.
"""
if args is None:
args = request.args
utc_tz = tz.gettz('GMT')
# Parse formats to try (in order)
formats = [
'%Y-%m-%d %H:%M:%S',
'%Y-%m-%d'
]
if key in request.args:
for format in formats:
try:
return datetime.datetime \
.strptime(request.args['since'], format) \
.replace(tzinfo=utc_tz)
except ValueError:
continue
raise ValueError('"%s" argument is not in the correct format' % key)
def get_list_arg(key, args=None):
"""
Get a query argument containing a comma-separated list of values.
Returns an empty list if nothing found.
"""
if args is None:
args = request.args
if key in request.args:
value = request.args[key].split(',')
else:
value = []
return value
def get_system_timezone():
tz_name = time.strftime('%Z', time.gmtime())
return tz.gettz(tz_name)
def get_db_timezone(conn):
cursor = conn.cursor()
cursor.execute("select @@session.time_zone")
row = cursor.fetchone()
if row is None or row[0] == 'SYSTEM':
return get_system_timezone()
return tz.gettz(row[0])
def get_db_connection():
"""
Gets a connection to the database server.
"""
return MySQLdb.connect(host=arguments['source_host'],
port=arguments['source_port'],
user=arguments['source_username'],
passwd=arguments['source_password'],
db='information_schema')
def init_logger():
logging.basicConfig(level=logging.DEBUG if arguments['debug'] else logging.INFO,
format='%(asctime)s | %(levelname)-5s | %(name)s: %(message)s')
def main():
"""
Run as a standalone web server from the command line.
Don't do this in production. Use your web server to mount this script as a WSGI endpoint instead.
"""
init_logger()
debug = arguments['debug']
#logger.debug('Arguments: %s' % json.dumps(arguments))
# Test database connection
try:
logger.debug('Test database connection at %(source_username)s@%(source_host)s:%(source_port)d...' % (arguments))
conn = get_db_connection()
cursor = conn.cursor()
cursor.execute('select 1')
conn.close()
except _mysql_exceptions.OperationalError, ex:
code, message = ex.args
logger.error('MySQL error %s: %s' % (code, message))
return 1
# Start web server
try:
if debug:
app.debug = True
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 # Don't cache files
use_ssl = arguments['listen_ssl']
if use_ssl:
try:
from OpenSSL import SSL
ssl_context = SSL.Context(SSL.SSLv23_METHOD)
ssl_context.use_privatekey_file(arguments['ssl_private_key'])
ssl_context.use_publickey_file(arguments['ssl_public_key'])
except ImportError:
logger.error('You enabled SSL mode, but the OpenSSL module not installed! '
'Please "pip install pyopenssl" to satisfy this dependency.')
return 1
else:
ssl_context = None
logger.info('Starting server on %s://%s:%d' % (
('https' if use_ssl else 'http'), arguments['listen_address'], arguments['listen_port']))
paste.httpserver.serve(app,
host=arguments['listen_address'],
port=arguments['listen_port'],
ssl_context=ssl_context,
use_threadpool=True)
return 0
except socket.error, ex:
print 'Socket error: %s' % ex
return 1
if __name__ == '__main__':
parser = argparse.ArgumentParser(#prog='dbdump',
description='Web server that sends changed database records to clients. '
'Client can request all changed records that occurred since a '
'specific date and time.',
epilog='For more information and additional help, please visit '
'https://github.com/LumaPictures/dbdump')
# HTTP server
server_group = parser.add_argument_group('Web Server', 'HTTP server that listens for dbd_puller clients.')
server_group.add_argument('-a', '--listen-address', metavar='IP', default=HTTP_DEFAULT_ADDRESS,
help='Listener interface address (default: %s)' % HTTP_DEFAULT_ADDRESS)
server_group.add_argument('-P', '--listen-port', metavar='PORT', type=int, default=HTTP_DEFAULT_PORT,
help='Listener port (default: %d)' % HTTP_DEFAULT_PORT)
server_group.add_argument('-u', '--listen-username', metavar='USERNAME',
help='Username required for connecting HTTP clients')
server_group.add_argument('-p', '--listen-password', metavar='PASSWORD',
help='Password required for connecting HTTP clients')
# SSL mode
server_group.add_argument('-s', '--listen-ssl', action='store_true',
help='Require SSL encryption')
server_group.add_argument('--ssl-private-key', metavar='FILE_PATH', default=HTTP_DEFAULT_SSL_PRIVATE_KEY,
help='Private key file in OpenSSL format (default: %s)' % HTTP_DEFAULT_SSL_PRIVATE_KEY)
server_group.add_argument('--ssl-public-key', metavar='FILE_PATH', default=HTTP_DEFAULT_SSL_PUBLIC_KEY,
help='Public key file in OpenSSL format (default: %s)' % HTTP_DEFAULT_SSL_PUBLIC_KEY)
# Database client
db_group = parser.add_argument_group('Source Database', 'MySQL database server where changes are being monitored. '
'All qualified tables must have an auto-updating TIMESTAMP column.')
db_group.add_argument('--source-host', metavar='HOST_OR_IP', required=True,
help='Database server host')
db_group.add_argument('--source-port', type=int, metavar='PORT', default=DB_DEFAULT_PORT,
help='Database server port (default: %d)' % DB_DEFAULT_PORT)
db_group.add_argument('--source-username', metavar='USERNAME', required=True,
help='Database username')
db_group.add_argument('--source-password', metavar='PASSWORD', default=None,
help='Database password')
db_group.add_argument('--source-databases', metavar='database1,databaseN,...',
help='Databases to expose (default: all databases)')
# Misc options
parser.add_argument('-d', '--debug', action='store_true',
help='Enable debug mode (shows more detailed logging and '
'auto-restarts web server when script files change)')
parser.add_argument('--version', action='version',
version='%%(prog)s (version %s)' % __version__,
help='Display version and exit')
if argcomplete:
argcomplete.autocomplete(parser)
arguments = vars(parser.parse_args())
sys.exit(main())