/
operation.rb
577 lines (482 loc) · 13.7 KB
/
operation.rb
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
568
569
570
571
572
573
574
575
576
577
require 'rest_client'
require 'sequel'
require 'zlib'
require 'taps/progress_bar'
require 'taps/config'
require 'taps/utils'
require 'taps/data_stream'
require 'taps/errors'
# disable warnings, rest client makes a lot of noise right now
$VERBOSE = nil
module Taps
class Operation
attr_reader :database_url, :remote_url, :opts
attr_reader :session_uri
def initialize(database_url, remote_url, opts={})
@database_url = database_url
@remote_url = remote_url
@opts = opts
@exiting = false
@session_uri = opts[:session_uri]
end
def file_prefix
"op"
end
def skip_schema?
!!opts[:skip_schema]
end
def indexes_first?
!!opts[:indexes_first]
end
def table_filter
opts[:table_filter]
end
def exclude_tables
opts[:exclude_tables] || []
end
def apply_table_filter(tables)
return tables unless table_filter || exclude_tables
re = table_filter ? Regexp.new(table_filter) : nil
if tables.kind_of?(Hash)
ntables = {}
tables.each do |t, d|
if !exclude_tables.include?(t.to_s) && (!re || !re.match(t.to_s).nil?)
ntables[t] = d
end
end
ntables
else
tables.reject { |t| exclude_tables.include?(t.to_s) || (re && re.match(t.to_s).nil?) }
end
end
def log
Taps.log
end
def store_session
file = "#{file_prefix}_#{Time.now.strftime("%Y%m%d%H%M")}.dat"
puts "\nSaving session to #{file}.."
File.open(file, 'w') do |f|
f.write(OkJson.encode(to_hash))
end
end
def to_hash
{
:klass => self.class.to_s,
:database_url => database_url,
:remote_url => remote_url,
:session_uri => session_uri,
:stream_state => stream_state,
:completed_tables => completed_tables,
:table_filter => table_filter,
}
end
def exiting?
!!@exiting
end
def setup_signal_trap
trap("INT") {
puts "\nCompleting current action..."
@exiting = true
}
trap("TERM") {
puts "\nCompleting current action..."
@exiting = true
}
end
def resuming?
opts[:resume] == true
end
def default_chunksize
opts[:default_chunksize]
end
def completed_tables
opts[:completed_tables] ||= []
end
def stream_state
opts[:stream_state] ||= {}
end
def stream_state=(val)
opts[:stream_state] = val
end
def compression_disabled?
!!opts[:disable_compression]
end
def db
@db ||= Sequel.connect(database_url)
end
def server
@server ||= RestClient::Resource.new(remote_url)
end
def session_resource
@session_resource ||= begin
@session_uri ||= server['sessions'].post('', http_headers).to_s
server[@session_uri]
end
end
def set_session(uri)
session_uri = uri
@session_resource = server[session_uri]
end
def close_session
@session_resource.delete(http_headers) if @session_resource
end
def safe_url(url)
url.sub(/\/\/(.+?)?:(.*?)@/, '//\1:[hidden]@')
end
def safe_remote_url
safe_url(remote_url)
end
def safe_database_url
safe_url(database_url)
end
def http_headers(extra = {})
base = { :taps_version => Taps.version }
if compression_disabled?
base[:accept_encoding] = ""
else
base[:accept_encoding] = "gzip, deflate"
end
base.merge(extra)
end
def format_number(num)
num.to_s.gsub(/(\d)(?=(\d\d\d)+(?!\d))/, "\\1,")
end
def verify_server
begin
server['/'].get(http_headers)
rescue RestClient::RequestFailed => e
if e.http_code == 417
puts "#{safe_remote_url} is running a different minor version of taps."
puts "#{e.response.to_s}"
exit(1)
else
raise
end
rescue RestClient::Unauthorized
puts "Bad credentials given for #{safe_remote_url}"
exit(1)
rescue Errno::ECONNREFUSED
puts "Can't connect to #{safe_remote_url}. Please check that it's running"
exit(1)
end
end
def catch_errors(&blk)
verify_server
begin
blk.call
close_session
rescue RestClient::Exception, Taps::BaseError => e
store_session
if e.kind_of?(Taps::BaseError)
puts "!!! Caught Server Exception"
puts "#{e.class}: #{e.message}"
puts "\n#{e.original_backtrace}" if e.original_backtrace
exit(1)
elsif e.respond_to?(:response)
puts "!!! Caught Server Exception"
puts "HTTP CODE: #{e.http_code}"
puts "#{e.response.to_s}"
exit(1)
else
raise
end
end
end
def self.factory(type, database_url, remote_url, opts)
type = :resume if opts[:resume]
klass = case type
when :pull then Taps::Pull
when :push then Taps::Push
when :resume then eval(opts[:klass])
else raise "Unknown Operation Type -> #{type}"
end
klass.new(database_url, remote_url, opts)
end
end
class Pull < Operation
def file_prefix
"pull"
end
def to_hash
super.merge(:remote_tables_info => remote_tables_info)
end
def run
catch_errors do
unless resuming?
pull_schema if !skip_schema?
pull_indexes if indexes_first? && !skip_schema?
end
setup_signal_trap
pull_partial_data if resuming?
pull_data
pull_indexes if !indexes_first? && !skip_schema?
pull_reset_sequences
end
end
def pull_schema
puts "Receiving schema"
progress = ProgressBar.new('Schema', tables.size)
tables.each do |table_name, count|
schema_data = session_resource['pull/schema'].post({:table_name => table_name}, http_headers).to_s
log.debug "Table: #{table_name}\n#{schema_data}\n"
output = Taps::Utils.load_schema(database_url, schema_data)
puts output if output
progress.inc(1)
end
progress.finish
end
def pull_data
puts "Receiving data"
puts "#{tables.size} tables, #{format_number(record_count)} records"
tables.each do |table_name, count|
progress = ProgressBar.new(table_name.to_s, count)
stream = Taps::DataStream.factory(db, {
:chunksize => default_chunksize,
:table_name => table_name
})
pull_data_from_table(stream, progress)
end
end
def pull_partial_data
return if stream_state == {}
table_name = stream_state[:table_name]
record_count = tables[table_name.to_s]
puts "Resuming #{table_name}, #{format_number(record_count)} records"
progress = ProgressBar.new(table_name.to_s, record_count)
stream = Taps::DataStream.factory(db, stream_state)
pull_data_from_table(stream, progress)
end
def pull_data_from_table(stream, progress)
loop do
begin
if exiting?
store_session
exit 0
end
size = stream.fetch_remote(session_resource['pull/table'], http_headers)
break if stream.complete?
progress.inc(size) unless exiting?
stream.error = false
self.stream_state = stream.to_hash
rescue Taps::CorruptedData => e
puts "Corrupted Data Received #{e.message}, retrying..."
stream.error = true
next
end
end
progress.finish
completed_tables << stream.table_name.to_s
self.stream_state = {}
end
def tables
h = {}
remote_tables_info.each do |table_name, count|
next if completed_tables.include?(table_name.to_s)
h[table_name.to_s] = count
end
h
end
def record_count
@record_count ||= remote_tables_info.values.inject(0) { |a,c| a += c }
end
def remote_tables_info
opts[:remote_tables_info] ||= fetch_remote_tables_info
end
def fetch_remote_tables_info
retries = 0
max_retries = 10
begin
tables = OkJson.decode(session_resource['pull/table_names'].get(http_headers).to_s)
rescue RestClient::Exception
retries += 1
retry if retries <= max_retries
puts "Unable to fetch tables information from #{remote_url}. Please check the server log."
exit(1)
end
data = {}
apply_table_filter(tables).each do |table_name|
retries = 0
begin
count = session_resource['pull/table_count'].post({:table => table_name}, http_headers).to_s.to_i
data[table_name] = count
rescue RestClient::Exception
retries += 1
retry if retries <= max_retries
puts "Unable to fetch tables information from #{remote_url}. Please check the server log."
exit(1)
end
end
data
end
def pull_indexes
puts "Receiving indexes"
idxs = OkJson.decode(session_resource['pull/indexes'].get(http_headers).to_s)
apply_table_filter(idxs).each do |table, indexes|
next unless indexes.size > 0
progress = ProgressBar.new(table, indexes.size)
indexes.each do |idx|
output = Taps::Utils.load_indexes(database_url, idx)
puts output if output
progress.inc(1)
end
progress.finish
end
end
def pull_reset_sequences
puts "Resetting sequences"
output = Taps::Utils.schema_bin(:reset_db_sequences, database_url)
puts output if output
end
end
class Push < Operation
def file_prefix
"push"
end
def to_hash
super.merge(:local_tables_info => local_tables_info)
end
def run
catch_errors do
unless resuming?
push_schema if !skip_schema?
push_indexes if indexes_first? && !skip_schema?
end
setup_signal_trap
push_partial_data if resuming?
push_data
push_indexes if !indexes_first? && !skip_schema?
push_reset_sequences
end
end
def push_indexes
idxs = OkJson.decode(Taps::Utils.schema_bin(:indexes_individual, database_url))
return unless idxs.size > 0
puts "Sending indexes"
apply_table_filter(idxs).each do |table, indexes|
next unless indexes.size > 0
progress = ProgressBar.new(table, indexes.size)
indexes.each do |idx|
session_resource['push/indexes'].post(idx, http_headers)
progress.inc(1)
end
progress.finish
end
end
def push_schema
puts "Sending schema"
progress = ProgressBar.new('Schema', tables.size)
tables.each do |table, count|
schema_data = Taps::Utils.schema_bin(:dump_table, database_url, table)
log.debug "Table: #{table}\n#{schema_data}\n"
session_resource['push/schema'].post(schema_data, http_headers)
progress.inc(1)
end
progress.finish
end
def push_reset_sequences
puts "Resetting sequences"
session_resource['push/reset_sequences'].post('', http_headers)
end
def push_partial_data
return if stream_state == {}
table_name = stream_state[:table_name]
record_count = tables[table_name.to_s]
puts "Resuming #{table_name}, #{format_number(record_count)} records"
progress = ProgressBar.new(table_name.to_s, record_count)
stream = Taps::DataStream.factory(db, stream_state)
push_data_from_table(stream, progress)
end
def push_data
puts "Sending data"
puts "#{tables.size} tables, #{format_number(record_count)} records"
tables.each do |table_name, count|
stream = Taps::DataStream.factory(db,
:table_name => table_name,
:chunksize => default_chunksize)
progress = ProgressBar.new(table_name.to_s, count)
push_data_from_table(stream, progress)
end
end
def push_data_from_table(stream, progress)
loop do
if exiting?
store_session
exit 0
end
row_size = 0
chunksize = stream.state[:chunksize]
begin
chunksize = Taps::Utils.calculate_chunksize(chunksize) do |c|
stream.state[:chunksize] = c.to_i
encoded_data, row_size, elapsed_time = nil
d1 = c.time_delta do
encoded_data, row_size, elapsed_time = stream.fetch
end
break if stream.complete?
data = nil
d2 = c.time_delta do
data = {
:state => stream.to_hash,
:checksum => Taps::Utils.checksum(encoded_data).to_s
}
end
begin
content, content_type = nil
d3 = c.time_delta do
content, content_type = Taps::Multipart.create do |r|
r.attach :name => :encoded_data,
:payload => encoded_data,
:content_type => 'application/octet-stream'
r.attach :name => :json,
:payload => OkJson.encode(data),
:content_type => 'application/json'
end
end
session_resource['push/table'].post(content, http_headers(:content_type => content_type))
self.stream_state = stream.to_hash
rescue => e
Taps::Utils.reraise_server_exception(e)
end
c.idle_secs = (d1 + d2 + d3)
elapsed_time
end
rescue Taps::CorruptedData => e
# retry the same data, it got corrupted somehow.
next
rescue Taps::DuplicatePrimaryKeyError => e
# verify the stream and retry it
stream = stream.verify_remote_stream(session_resource['push/verify_stream'], http_headers)
next
end
stream.state[:chunksize] = chunksize
progress.inc(row_size)
stream.increment(row_size)
break if stream.complete?
end
progress.finish
completed_tables << stream.table_name.to_s
self.stream_state = {}
end
def local_tables_info
opts[:local_tables_info] ||= fetch_local_tables_info
end
def tables
h = {}
local_tables_info.each do |table_name, count|
next if completed_tables.include?(table_name.to_s)
h[table_name.to_s] = count
end
h
end
def record_count
@record_count ||= local_tables_info.values.inject(0) { |a,c| a += c }
end
def fetch_local_tables_info
tables_with_counts = {}
db.tables.each do |table|
tables_with_counts[table] = db[table.to_sym.identifier].count
end
apply_table_filter(tables_with_counts)
end
end
end