scylla-cqlsh 6.0.26__cp314-cp314t-win32.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 scylla-cqlsh might be problematic. Click here for more details.

cqlshlib/copyutil.py ADDED
@@ -0,0 +1,2756 @@
1
+ # cython: profile=True
2
+
3
+ # Licensed to the Apache Software Foundation (ASF) under one
4
+ # or more contributor license agreements. See the NOTICE file
5
+ # distributed with this work for additional information
6
+ # regarding copyright ownership. The ASF licenses this file
7
+ # to you under the Apache License, Version 2.0 (the
8
+ # "License"); you may not use this file except in compliance
9
+ # with the License. You may obtain a copy of the License at
10
+ #
11
+ # http://www.apache.org/licenses/LICENSE-2.0
12
+ #
13
+ # Unless required by applicable law or agreed to in writing, software
14
+ # distributed under the License is distributed on an "AS IS" BASIS,
15
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ # See the License for the specific language governing permissions and
17
+ # limitations under the License.
18
+
19
+ import csv
20
+ import datetime
21
+ import json
22
+ import glob
23
+ import multiprocessing as mp
24
+ import os
25
+ import platform
26
+ import random
27
+ import re
28
+ import signal
29
+ import struct
30
+ import sys
31
+ import threading
32
+ import time
33
+ import traceback
34
+
35
+ from bisect import bisect_right
36
+ from calendar import timegm
37
+ from collections import defaultdict, namedtuple
38
+ from decimal import Decimal
39
+ from random import randint
40
+ from io import StringIO
41
+ from select import select
42
+ from uuid import UUID
43
+
44
+ import configparser
45
+ from queue import Queue
46
+
47
+ from cassandra import OperationTimedOut
48
+ from cassandra.cluster import Cluster, DefaultConnection
49
+ from cassandra.cqltypes import ReversedType, UserType, VarcharType
50
+ from cassandra.metadata import protect_name, protect_names, protect_value
51
+ from cassandra.policies import RetryPolicy, WhiteListRoundRobinPolicy, DCAwareRoundRobinPolicy, FallthroughRetryPolicy
52
+ from cassandra.query import BatchStatement, BatchType, SimpleStatement, tuple_factory
53
+ from cassandra.util import Date, Time
54
+ from cqlshlib.util import profile_on, profile_off
55
+
56
+ from cqlshlib.cql3handling import CqlRuleSet
57
+ from cqlshlib.displaying import NO_COLOR_MAP
58
+ from cqlshlib.formatting import format_value_default, CqlType, DateTimeFormat, EMPTY, get_formatter, BlobType
59
+ from cqlshlib.sslhandling import ssl_settings
60
+
61
+ PROFILE_ON = False
62
+ STRACE_ON = False
63
+ DEBUG = False # This may be set to True when initializing the task
64
+ # TODO: review this for MacOS, maybe use in ('Linux', 'Darwin')
65
+ IS_LINUX = platform.system() == 'Linux'
66
+
67
+ CopyOptions = namedtuple('CopyOptions', 'copy dialect unrecognized')
68
+
69
+
70
+ def safe_normpath(fname):
71
+ """
72
+ :return the normalized path but only if there is a filename, we don't want to convert
73
+ an empty string (which means no file name) to a dot. Also expand any user variables such as ~ to the full path
74
+ """
75
+ return os.path.normpath(os.path.expanduser(fname)) if fname else fname
76
+
77
+
78
+ def printdebugmsg(msg):
79
+ if DEBUG:
80
+ printmsg(msg)
81
+
82
+
83
+ def printmsg(msg, eol='\n'):
84
+ sys.stdout.write(msg)
85
+ sys.stdout.write(eol)
86
+ sys.stdout.flush()
87
+
88
+
89
+ def noop(*arg, **kwargs):
90
+ pass
91
+
92
+
93
+ class OneWayPipe(object):
94
+ """
95
+ A one way pipe protected by two process level locks, one for reading and one for writing.
96
+ """
97
+ def __init__(self):
98
+ self.reader, self.writer = mp.Pipe(duplex=False)
99
+ self.rlock = mp.Lock()
100
+ self.wlock = mp.Lock()
101
+
102
+ def send(self, obj):
103
+ with self.wlock:
104
+ self.writer.send(obj)
105
+
106
+ def recv(self):
107
+ with self.rlock:
108
+ return self.reader.recv()
109
+
110
+ def close(self):
111
+ self.reader.close()
112
+ self.writer.close()
113
+
114
+
115
+ class ReceivingChannel(object):
116
+ """
117
+ A one way channel that wraps a pipe to receive messages.
118
+ """
119
+ def __init__(self, pipe):
120
+ self.pipe = pipe
121
+
122
+ def recv(self):
123
+ return self.pipe.recv()
124
+
125
+ def close(self):
126
+ self.pipe.close()
127
+
128
+
129
+ class SendingChannel(object):
130
+ """
131
+ A one way channel that wraps a pipe and provides a feeding thread to send messages asynchronously.
132
+ """
133
+ def __init__(self, pipe):
134
+ self.pipe = pipe
135
+ self.pending_messages = Queue()
136
+
137
+ def feed():
138
+ while True:
139
+ try:
140
+ msg = self.pending_messages.get()
141
+ self.pipe.send(msg)
142
+ except Exception as e:
143
+ printmsg('%s: %s' % (e.__class__.__name__, e.message if hasattr(e, 'message') else str(e)))
144
+
145
+ feeding_thread = threading.Thread(target=feed)
146
+ feeding_thread.setDaemon(True)
147
+ feeding_thread.start()
148
+
149
+ def send(self, obj):
150
+ self.pending_messages.put(obj)
151
+
152
+ def num_pending(self):
153
+ return self.pending_messages.qsize() if self.pending_messages else 0
154
+
155
+ def close(self):
156
+ self.pipe.close()
157
+
158
+
159
+ class SendingChannels(object):
160
+ """
161
+ A group of one way channels for sending messages.
162
+ """
163
+ def __init__(self, num_channels):
164
+ self.pipes = [OneWayPipe() for _ in range(num_channels)]
165
+ self.channels = [SendingChannel(p) for p in self.pipes]
166
+ self.num_channels = num_channels
167
+ self._readers = [p.reader for p in self.pipes]
168
+
169
+ def release_readers(self):
170
+ for reader in self._readers:
171
+ reader.close()
172
+
173
+ def close(self):
174
+ for ch in self.channels:
175
+ try:
176
+ ch.close()
177
+ except ValueError:
178
+ pass
179
+
180
+
181
+ class ReceivingChannels(object):
182
+ """
183
+ A group of one way channels for receiving messages.
184
+ """
185
+ def __init__(self, num_channels):
186
+ self.pipes = [OneWayPipe() for _ in range(num_channels)]
187
+ self.channels = [ReceivingChannel(p) for p in self.pipes]
188
+ self._readers = [p.reader for p in self.pipes]
189
+ self._writers = [p.writer for p in self.pipes]
190
+ self._rlocks = [p.rlock for p in self.pipes]
191
+ self._rlocks_by_readers = dict([(p.reader, p.rlock) for p in self.pipes])
192
+ self.num_channels = num_channels
193
+
194
+ self.recv = self.recv_select if IS_LINUX else self.recv_polling
195
+
196
+ def release_writers(self):
197
+ for writer in self._writers:
198
+ writer.close()
199
+
200
+ def recv_select(self, timeout):
201
+ """
202
+ Implementation of the recv method for Linux, where select is available. Receive an object from
203
+ all pipes that are ready for reading without blocking.
204
+ """
205
+ while True:
206
+ try:
207
+ readable, _, _ = select(self._readers, [], [], timeout)
208
+ except OSError:
209
+ raise
210
+ else:
211
+ break
212
+ for r in readable:
213
+ with self._rlocks_by_readers[r]:
214
+ try:
215
+ yield r.recv()
216
+ except EOFError:
217
+ continue
218
+
219
+ def recv_polling(self, timeout):
220
+ """
221
+ Implementation of the recv method for platforms where select() is not available for pipes.
222
+ We poll on all of the readers with a very small timeout. We stop when the timeout specified
223
+ has been received but we may exceed it since we check all processes during each sweep.
224
+ """
225
+ start = time.time()
226
+ while True:
227
+ for i, r in enumerate(self._readers):
228
+ with self._rlocks[i]:
229
+ if r.poll(0.000000001):
230
+ try:
231
+ yield r.recv()
232
+ except EOFError:
233
+ continue
234
+
235
+ if time.time() - start > timeout:
236
+ break
237
+
238
+ def close(self):
239
+ for ch in self.channels:
240
+ try:
241
+ ch.close()
242
+ except ValueError:
243
+ pass
244
+
245
+
246
+ class CopyTask(object):
247
+ """
248
+ A base class for ImportTask and ExportTask
249
+ """
250
+ def __init__(self, shell, ks, table, columns, fname, opts, protocol_version, config_file, direction):
251
+ self.shell = shell
252
+ self.ks = ks
253
+ self.table = table
254
+ self.table_meta = self.shell.get_table_meta(self.ks, self.table)
255
+ self.host = shell.conn.get_control_connection_host()
256
+ self.fname = safe_normpath(fname)
257
+ self.protocol_version = protocol_version
258
+ self.config_file = config_file
259
+
260
+ # if cqlsh is invoked with --debug then set the global debug flag to True
261
+ if shell.debug:
262
+ global DEBUG
263
+ DEBUG = True
264
+
265
+ # do not display messages when exporting to STDOUT unless --debug is set
266
+ self.printmsg = printmsg if self.fname is not None or direction == 'from' or DEBUG else noop
267
+ self.options = self.parse_options(opts, direction)
268
+
269
+ self.num_processes = self.options.copy['numprocesses']
270
+ self.encoding = self.options.copy['encoding']
271
+ self.printmsg('Using %d child processes' % (self.num_processes,))
272
+
273
+ if direction == 'from':
274
+ self.num_processes += 1 # add the feeder process
275
+
276
+ self.processes = []
277
+ self.inmsg = ReceivingChannels(self.num_processes)
278
+ self.outmsg = SendingChannels(self.num_processes)
279
+
280
+ self.columns = CopyTask.get_columns(shell, ks, table, columns)
281
+ self.time_start = time.time()
282
+
283
+ def maybe_read_config_file(self, opts, direction):
284
+ """
285
+ Read optional sections from a configuration file that was specified in the command options or from the default
286
+ cqlshrc configuration file if none was specified.
287
+ """
288
+ config_file = opts.pop('configfile', '')
289
+ if not config_file:
290
+ config_file = self.config_file
291
+
292
+ if not os.path.isfile(config_file):
293
+ return opts
294
+
295
+ configs = configparser.RawConfigParser()
296
+ configs.read_file(open(config_file))
297
+
298
+ ret = dict()
299
+ config_sections = list(['copy', 'copy-%s' % (direction,),
300
+ 'copy:%s.%s' % (self.ks, self.table),
301
+ 'copy-%s:%s.%s' % (direction, self.ks, self.table)])
302
+
303
+ for section in config_sections:
304
+ if configs.has_section(section):
305
+ options = dict(configs.items(section))
306
+ self.printmsg("Reading options from %s:[%s]: %s" % (config_file, section, options))
307
+ ret.update(options)
308
+
309
+ # Update this last so the command line options take precedence over the configuration file options
310
+ if opts:
311
+ self.printmsg("Reading options from the command line: %s" % (opts,))
312
+ ret.update(opts)
313
+
314
+ if self.shell.debug: # this is important for testing, do not remove
315
+ self.printmsg("Using options: '%s'" % (ret,))
316
+
317
+ return ret
318
+
319
+ @staticmethod
320
+ def clean_options(opts):
321
+ """
322
+ Convert all option values to valid string literals unless they are path names
323
+ """
324
+ return dict([(k, v if k not in ['errfile', 'ratefile'] else v)
325
+ for k, v, in opts.items()])
326
+
327
+ def parse_options(self, opts, direction):
328
+ """
329
+ Parse options for import (COPY FROM) and export (COPY TO) operations.
330
+ Extract from opts csv and dialect options.
331
+
332
+ :return: 3 dictionaries: the csv options, the dialect options, any unrecognized options.
333
+ """
334
+ shell = self.shell
335
+ opts = self.clean_options(self.maybe_read_config_file(opts, direction))
336
+
337
+ dialect_options = dict()
338
+ dialect_options['quotechar'] = opts.pop('quote', '"')
339
+ dialect_options['escapechar'] = opts.pop('escape', '\\')
340
+ dialect_options['delimiter'] = opts.pop('delimiter', ',')
341
+ if dialect_options['quotechar'] == dialect_options['escapechar']:
342
+ dialect_options['doublequote'] = True
343
+ del dialect_options['escapechar']
344
+ else:
345
+ dialect_options['doublequote'] = False
346
+
347
+ copy_options = dict()
348
+ copy_options['nullval'] = opts.pop('null', '')
349
+ copy_options['header'] = bool(opts.pop('header', '').lower() == 'true')
350
+ copy_options['encoding'] = opts.pop('encoding', 'utf8')
351
+ copy_options['maxrequests'] = int(opts.pop('maxrequests', 6))
352
+ copy_options['pagesize'] = int(opts.pop('pagesize', 1000))
353
+ # by default the page timeout is 10 seconds per 1000 entries
354
+ # in the page size or 10 seconds if pagesize is smaller
355
+ copy_options['pagetimeout'] = int(opts.pop('pagetimeout', max(10, 10 * (copy_options['pagesize'] / 1000))))
356
+ copy_options['maxattempts'] = int(opts.pop('maxattempts', 5))
357
+ copy_options['dtformats'] = DateTimeFormat(opts.pop('datetimeformat', shell.display_timestamp_format),
358
+ shell.display_date_format, shell.display_nanotime_format,
359
+ milliseconds_only=True)
360
+ copy_options['floatprecision'] = int(opts.pop('floatprecision', '5'))
361
+ copy_options['doubleprecision'] = int(opts.pop('doubleprecision', '12'))
362
+ copy_options['chunksize'] = int(opts.pop('chunksize', 5000))
363
+ copy_options['ingestrate'] = int(opts.pop('ingestrate', 100000))
364
+ copy_options['maxbatchsize'] = int(opts.pop('maxbatchsize', 20))
365
+ copy_options['minbatchsize'] = int(opts.pop('minbatchsize', 10))
366
+ copy_options['reportfrequency'] = float(opts.pop('reportfrequency', 0.25))
367
+ copy_options['consistencylevel'] = shell.consistency_level
368
+ copy_options['decimalsep'] = opts.pop('decimalsep', '.')
369
+ copy_options['thousandssep'] = opts.pop('thousandssep', '')
370
+ copy_options['boolstyle'] = [s.strip() for s in opts.pop('boolstyle', 'True, False').split(',')]
371
+ copy_options['numprocesses'] = int(opts.pop('numprocesses', self.get_num_processes(16)))
372
+ copy_options['begintoken'] = opts.pop('begintoken', '')
373
+ copy_options['endtoken'] = opts.pop('endtoken', '')
374
+ copy_options['maxrows'] = int(opts.pop('maxrows', '-1'))
375
+ copy_options['skiprows'] = int(opts.pop('skiprows', '0'))
376
+ copy_options['skipcols'] = opts.pop('skipcols', '')
377
+ copy_options['maxparseerrors'] = int(opts.pop('maxparseerrors', '-1'))
378
+ copy_options['maxinserterrors'] = int(opts.pop('maxinserterrors', '1000'))
379
+ copy_options['errfile'] = safe_normpath(opts.pop('errfile', 'import_%s_%s.err' % (self.ks, self.table,)))
380
+ copy_options['ratefile'] = safe_normpath(opts.pop('ratefile', ''))
381
+ copy_options['maxoutputsize'] = int(opts.pop('maxoutputsize', '-1'))
382
+ copy_options['preparedstatements'] = bool(opts.pop('preparedstatements', 'true').lower() == 'true')
383
+ copy_options['ttl'] = int(opts.pop('ttl', -1))
384
+
385
+ # Hidden properties, they do not appear in the documentation but can be set in config files
386
+ # or on the cmd line but w/o completion
387
+ copy_options['maxinflightmessages'] = int(opts.pop('maxinflightmessages', '512'))
388
+ copy_options['maxbackoffattempts'] = int(opts.pop('maxbackoffattempts', '12'))
389
+ copy_options['maxpendingchunks'] = int(opts.pop('maxpendingchunks', '24'))
390
+ # set requesttimeout to a value high enough so that maxbatchsize rows will never timeout if the server
391
+ # responds: here we set it to 1 sec per 10 rows but no less than 60 seconds
392
+ copy_options['requesttimeout'] = int(opts.pop('requesttimeout', max(60, 1 * copy_options['maxbatchsize'] / 10)))
393
+ # set childtimeout higher than requesttimeout so that child processes have a chance to report request timeouts
394
+ copy_options['childtimeout'] = int(opts.pop('childtimeout', copy_options['requesttimeout'] + 30))
395
+
396
+ self.check_options(copy_options)
397
+ return CopyOptions(copy=copy_options, dialect=dialect_options, unrecognized=opts)
398
+
399
+ @staticmethod
400
+ def check_options(copy_options):
401
+ """
402
+ Check any options that require a sanity check beyond a simple type conversion and if required
403
+ raise a value error:
404
+
405
+ - boolean styles must be exactly 2, they must be different and they cannot be empty
406
+ """
407
+ bool_styles = copy_options['boolstyle']
408
+ if len(bool_styles) != 2 or bool_styles[0] == bool_styles[1] or not bool_styles[0] or not bool_styles[1]:
409
+ raise ValueError("Invalid boolean styles %s" % copy_options['boolstyle'])
410
+
411
+ @staticmethod
412
+ def get_num_processes(cap):
413
+ """
414
+ Pick a reasonable number of child processes. We need to leave at
415
+ least one core for the parent or feeder process.
416
+ """
417
+ return max(1, min(cap, CopyTask.get_num_cores() - 1))
418
+
419
+ @staticmethod
420
+ def get_num_cores():
421
+ """
422
+ Return the number of cores if available. If the test environment variable
423
+ is set, then return the number carried by this variable. This is to test single-core
424
+ machine more easily.
425
+ """
426
+ try:
427
+ num_cores_for_testing = os.environ.get('CQLSH_COPY_TEST_NUM_CORES', '')
428
+ ret = int(num_cores_for_testing) if num_cores_for_testing else mp.cpu_count()
429
+ printdebugmsg("Detected %d core(s)" % (ret,))
430
+ return ret
431
+ except NotImplementedError:
432
+ printdebugmsg("Failed to detect number of cores, returning 1")
433
+ return 1
434
+
435
+ @staticmethod
436
+ def describe_interval(seconds):
437
+ desc = []
438
+ for length, unit in ((86400, 'day'), (3600, 'hour'), (60, 'minute')):
439
+ num = int(seconds) / length
440
+ if num > 0:
441
+ desc.append('%d %s' % (num, unit))
442
+ if num > 1:
443
+ desc[-1] += 's'
444
+ seconds %= length
445
+ words = '%.03f seconds' % seconds
446
+ if len(desc) > 1:
447
+ words = ', '.join(desc) + ', and ' + words
448
+ elif len(desc) == 1:
449
+ words = desc[0] + ' and ' + words
450
+ return words
451
+
452
+ @staticmethod
453
+ def get_columns(shell, ks, table, columns):
454
+ """
455
+ Return all columns if none were specified or only the columns specified.
456
+ Possible enhancement: introduce a regex like syntax (^) to allow users
457
+ to specify all columns except a few.
458
+ """
459
+ return shell.get_column_names(ks, table) if not columns else columns
460
+
461
+ def close(self):
462
+ self.stop_processes()
463
+ self.inmsg.close()
464
+ self.outmsg.close()
465
+
466
+ def num_live_processes(self):
467
+ return sum(1 for p in self.processes if p.is_alive())
468
+
469
+ @staticmethod
470
+ def get_pid():
471
+ return os.getpid() if hasattr(os, 'getpid') else None
472
+
473
+ @staticmethod
474
+ def trace_process(pid):
475
+ if pid and STRACE_ON:
476
+ os.system("strace -vvvv -c -o strace.{pid}.out -e trace=all -p {pid}&".format(pid=pid))
477
+
478
+ def start_processes(self):
479
+ for i, process in enumerate(self.processes):
480
+ process.start()
481
+ self.trace_process(process.pid)
482
+ self.inmsg.release_writers()
483
+ self.outmsg.release_readers()
484
+ self.trace_process(self.get_pid())
485
+
486
+ def stop_processes(self):
487
+ for process in self.processes:
488
+ process.terminate()
489
+
490
+ def make_params(self):
491
+ """
492
+ Return a dictionary of parameters to be used by the worker processes.
493
+ On platforms using 'spawn' as the default multiprocessing start method,
494
+ this dictionary must be picklable.
495
+ """
496
+ shell = self.shell
497
+
498
+ return dict(ks=self.ks,
499
+ table=self.table,
500
+ local_dc=self.host.datacenter,
501
+ columns=self.columns,
502
+ options=self.options,
503
+ connect_timeout=shell.conn.connect_timeout,
504
+ hostname=self.host.address,
505
+ port=shell.port,
506
+ ssl=shell.ssl,
507
+ auth_provider=shell.auth_provider,
508
+ cql_version=shell.conn.cql_version,
509
+ config_file=self.config_file,
510
+ protocol_version=self.protocol_version,
511
+ debug=shell.debug,
512
+ coverage=shell.coverage,
513
+ coveragerc_path=shell.coveragerc_path
514
+ )
515
+
516
+ def validate_columns(self):
517
+ shell = self.shell
518
+
519
+ if not self.columns:
520
+ shell.printerr("No column specified")
521
+ return False
522
+
523
+ for c in self.columns:
524
+ if c not in self.table_meta.columns:
525
+ shell.printerr('Invalid column name %s' % (c,))
526
+ return False
527
+
528
+ return True
529
+
530
+ def update_params(self, params, i):
531
+ """
532
+ Add the communication pipes to the parameters to be passed to the worker process:
533
+ inpipe is the message pipe flowing from parent to child process, so outpipe from the parent point
534
+ of view and, vice-versa, outpipe is the message pipe flowing from child to parent, so inpipe
535
+ from the parent point of view, hence the two are swapped below.
536
+ """
537
+ params['inpipe'] = self.outmsg.pipes[i]
538
+ params['outpipe'] = self.inmsg.pipes[i]
539
+ return params
540
+
541
+
542
+ class ExportWriter(object):
543
+ """
544
+ A class that writes to one or more csv files, or STDOUT
545
+ """
546
+
547
+ def __init__(self, fname, shell, columns, options):
548
+ self.fname = fname
549
+ self.shell = shell
550
+ self.columns = columns
551
+ self.options = options
552
+ self.header = options.copy['header']
553
+ self.max_output_size = int(options.copy['maxoutputsize'])
554
+ self.current_dest = None
555
+ self.num_files = 0
556
+
557
+ if self.max_output_size > 0:
558
+ if fname is not None:
559
+ self.write = self._write_with_split
560
+ self.num_written = 0
561
+ else:
562
+ shell.printerr("WARNING: maxoutputsize {} ignored when writing to STDOUT".format(self.max_output_size))
563
+ self.write = self._write_without_split
564
+ else:
565
+ self.write = self._write_without_split
566
+
567
+ def open(self):
568
+ self.current_dest = self._get_dest(self.fname)
569
+ if self.current_dest is None:
570
+ return False
571
+
572
+ if self.header:
573
+ writer = csv.writer(self.current_dest.output, **self.options.dialect)
574
+ writer.writerow([str(c) for c in self.columns])
575
+
576
+ return True
577
+
578
+ def close(self):
579
+ self._close_current_dest()
580
+
581
+ def _next_dest(self):
582
+ self._close_current_dest()
583
+ self.current_dest = self._get_dest(self.fname + '.%d' % (self.num_files,))
584
+
585
+ def _get_dest(self, source_name):
586
+ """
587
+ Open the output file if any or else use stdout. Return a namedtuple
588
+ containing the out and a boolean indicating if the output should be closed.
589
+ """
590
+ CsvDest = namedtuple('CsvDest', 'output close')
591
+
592
+ if self.fname is None:
593
+ return CsvDest(output=sys.stdout, close=False)
594
+ else:
595
+ try:
596
+ ret = CsvDest(output=open(source_name, 'w'), close=True)
597
+ self.num_files += 1
598
+ return ret
599
+ except IOError as e:
600
+ self.shell.printerr("Can't open %r for writing: %s" % (source_name, e))
601
+ return None
602
+
603
+ def _close_current_dest(self):
604
+ if self.current_dest and self.current_dest.close:
605
+ self.current_dest.output.close()
606
+ self.current_dest = None
607
+
608
+ def _write_without_split(self, data, _):
609
+ """
610
+ Write the data to the current destination output.
611
+ """
612
+ self.current_dest.output.write(data)
613
+
614
+ def _write_with_split(self, data, num):
615
+ """
616
+ Write the data to the current destination output if we still
617
+ haven't reached the maximum number of rows. Otherwise split
618
+ the rows between the current destination and the next.
619
+ """
620
+ if (self.num_written + num) > self.max_output_size:
621
+ num_remaining = self.max_output_size - self.num_written
622
+ last_switch = 0
623
+ for i, row in enumerate([_f for _f in data.split(os.linesep) if _f]):
624
+ if i == num_remaining:
625
+ self._next_dest()
626
+ last_switch = i
627
+ num_remaining += self.max_output_size
628
+ self.current_dest.output.write(row + '\n')
629
+
630
+ self.num_written = num - last_switch
631
+ else:
632
+ self.num_written += num
633
+ self.current_dest.output.write(data)
634
+
635
+
636
+ class ExportTask(CopyTask):
637
+ """
638
+ A class that exports data to .csv by instantiating one or more processes that work in parallel (ExportProcess).
639
+ """
640
+ def __init__(self, shell, ks, table, columns, fname, opts, protocol_version, config_file):
641
+ CopyTask.__init__(self, shell, ks, table, columns, fname, opts, protocol_version, config_file, 'to')
642
+
643
+ options = self.options
644
+ self.begin_token = int(options.copy['begintoken']) if options.copy['begintoken'] else None
645
+ self.end_token = int(options.copy['endtoken']) if options.copy['endtoken'] else None
646
+ self.writer = ExportWriter(fname, shell, columns, options)
647
+
648
+ def run(self):
649
+ """
650
+ Initiates the export by starting the worker processes.
651
+ Then hand over control to export_records.
652
+ """
653
+ shell = self.shell
654
+
655
+ if self.options.unrecognized:
656
+ shell.printerr('Unrecognized COPY TO options: %s' % ', '.join(list(self.options.unrecognized.keys())))
657
+ return
658
+
659
+ if not self.validate_columns():
660
+ return 0
661
+
662
+ ranges = self.get_ranges()
663
+ if not ranges:
664
+ return 0
665
+
666
+ if not self.writer.open():
667
+ return 0
668
+
669
+ columns = "[" + ", ".join(self.columns) + "]"
670
+ self.printmsg("\nStarting copy of %s.%s with columns %s." % (self.ks, self.table, columns))
671
+
672
+ params = self.make_params()
673
+ for i in range(self.num_processes):
674
+ self.processes.append(ExportProcess(self.update_params(params, i)))
675
+
676
+ self.start_processes()
677
+
678
+ try:
679
+ self.export_records(ranges)
680
+ finally:
681
+ self.close()
682
+
683
+ def close(self):
684
+ CopyTask.close(self)
685
+ self.writer.close()
686
+
687
+ def get_ranges(self):
688
+ """
689
+ return a queue of tuples, where the first tuple entry is a token range (from, to]
690
+ and the second entry is a list of hosts that own that range. Each host is responsible
691
+ for all the tokens in the range (from, to].
692
+
693
+ The ring information comes from the driver metadata token map, which is built by
694
+ querying System.PEERS.
695
+
696
+ We only consider replicas that are in the local datacenter. If there are no local replicas
697
+ we use the cqlsh session host.
698
+ """
699
+ shell = self.shell
700
+ hostname = self.host.address
701
+ local_dc = self.host.datacenter
702
+ ranges = dict()
703
+ min_token = self.get_min_token()
704
+ begin_token = self.begin_token
705
+ end_token = self.end_token
706
+
707
+ def make_range(prev, curr):
708
+ """
709
+ Return the intersection of (prev, curr) and (begin_token, end_token),
710
+ return None if the intersection is empty
711
+ """
712
+ ret = (prev, curr)
713
+ if begin_token:
714
+ if curr < begin_token:
715
+ return None
716
+ elif (prev is None) or (prev < begin_token):
717
+ ret = (begin_token, curr)
718
+
719
+ if end_token:
720
+ if (ret[0] is not None) and (ret[0] > end_token):
721
+ return None
722
+ elif (curr is not None) and (curr > end_token):
723
+ ret = (ret[0], end_token)
724
+
725
+ return ret
726
+
727
+ def make_range_data(replicas=None):
728
+ hosts = []
729
+ if replicas:
730
+ for r in replicas:
731
+ if r.is_up is not False and r.datacenter == local_dc:
732
+ hosts.append(r.address)
733
+ if not hosts:
734
+ hosts.append(hostname) # fallback to default host if no replicas in current dc
735
+ return {'hosts': tuple(hosts), 'attempts': 0, 'rows': 0, 'workerno': -1}
736
+
737
+ if begin_token and begin_token < min_token:
738
+ shell.printerr('Begin token %d must be bigger or equal to min token %d' % (begin_token, min_token))
739
+ return ranges
740
+
741
+ if begin_token and end_token and begin_token > end_token:
742
+ shell.printerr('Begin token %d must be smaller than end token %d' % (begin_token, end_token))
743
+ return ranges
744
+
745
+ if shell.conn.metadata.token_map is None or min_token is None:
746
+ ranges[(begin_token, end_token)] = make_range_data()
747
+ return ranges
748
+
749
+ ring = list(shell.get_ring(self.ks).items())
750
+ ring.sort()
751
+
752
+ if not ring:
753
+ # If the ring is empty we get the entire ring from the host we are currently connected to
754
+ ranges[(begin_token, end_token)] = make_range_data()
755
+ elif len(ring) == 1:
756
+ # If there is only one token we get the entire ring from the replicas for that token
757
+ ranges[(begin_token, end_token)] = make_range_data(ring[0][1])
758
+ else:
759
+ # else we loop on the ring
760
+ first_range_data = None
761
+ previous = None
762
+ for token, replicas in ring:
763
+ if not first_range_data:
764
+ first_range_data = make_range_data(replicas) # we use it at the end when wrapping around
765
+
766
+ if token.value == min_token:
767
+ continue # avoids looping entire ring
768
+
769
+ current_range = make_range(previous, token.value)
770
+ if not current_range:
771
+ continue
772
+
773
+ ranges[current_range] = make_range_data(replicas)
774
+ previous = token.value
775
+
776
+ # For the last ring interval we query the same replicas that hold the first token in the ring
777
+ if previous is not None and (not end_token or previous < end_token):
778
+ ranges[(previous, end_token)] = first_range_data
779
+ # TODO: fix this logic added in 4.0: if previous is None, then it can't be compared with less than
780
+ elif previous is None and (not end_token or previous < end_token):
781
+ previous = begin_token if begin_token else min_token
782
+ ranges[(previous, end_token)] = first_range_data
783
+
784
+ if not ranges:
785
+ shell.printerr('Found no ranges to query, check begin and end tokens: %s - %s' % (begin_token, end_token))
786
+
787
+ return ranges
788
+
789
+ def get_min_token(self):
790
+ """
791
+ :return the minimum token, which depends on the partitioner.
792
+ For partitioners that do not support tokens we return None, in
793
+ this cases we will not work in parallel, we'll just send all requests
794
+ to the cqlsh session host.
795
+ """
796
+ partitioner = self.shell.conn.metadata.partitioner
797
+
798
+ if partitioner.endswith('RandomPartitioner'):
799
+ return -1
800
+ elif partitioner.endswith('Murmur3Partitioner'):
801
+ return -(2 ** 63) # Long.MIN_VALUE in Java
802
+ else:
803
+ return None
804
+
805
+ def send_work(self, ranges, tokens_to_send):
806
+ prev_worker_no = ranges[tokens_to_send[0]]['workerno']
807
+ i = prev_worker_no + 1 if -1 <= prev_worker_no < (self.num_processes - 1) else 0
808
+
809
+ for token_range in tokens_to_send:
810
+ ranges[token_range]['workerno'] = i
811
+ self.outmsg.channels[i].send((token_range, ranges[token_range]))
812
+ ranges[token_range]['attempts'] += 1
813
+
814
+ i = i + 1 if i < self.num_processes - 1 else 0
815
+
816
+ def export_records(self, ranges):
817
+ """
818
+ Send records to child processes and monitor them by collecting their results
819
+ or any errors. We terminate when we have processed all the ranges or when one child
820
+ process has died (since in this case we will never get any ACK for the ranges
821
+ processed by it and at the moment we don't keep track of which ranges a
822
+ process is handling).
823
+ """
824
+ shell = self.shell
825
+ processes = self.processes
826
+ meter = RateMeter(log_fcn=self.printmsg,
827
+ update_interval=self.options.copy['reportfrequency'],
828
+ log_file=self.options.copy['ratefile'])
829
+ total_requests = len(ranges)
830
+ max_attempts = self.options.copy['maxattempts']
831
+
832
+ self.send_work(ranges, list(ranges.keys()))
833
+
834
+ num_processes = len(processes)
835
+ succeeded = 0
836
+ failed = 0
837
+ while (failed + succeeded) < total_requests and self.num_live_processes() == num_processes:
838
+ for token_range, result in self.inmsg.recv(timeout=0.1):
839
+ if token_range is None and result is None: # a request has finished
840
+ succeeded += 1
841
+ elif isinstance(result, Exception): # an error occurred
842
+ # This token_range failed, retry up to max_attempts if no rows received yet,
843
+ # If rows were already received we'd risk duplicating data.
844
+ # Note that there is still a slight risk of duplicating data, even if we have
845
+ # an error with no rows received yet, it's just less likely. To avoid retrying on
846
+ # all timeouts would however mean we could risk not exporting some rows.
847
+ if ranges[token_range]['attempts'] < max_attempts and ranges[token_range]['rows'] == 0:
848
+ shell.printerr('Error for %s: %s (will try again later attempt %d of %d)'
849
+ % (token_range, result, ranges[token_range]['attempts'], max_attempts))
850
+ self.send_work(ranges, [token_range])
851
+ else:
852
+ shell.printerr('Error for %s: %s (permanently given up after %d rows and %d attempts)'
853
+ % (token_range, result, ranges[token_range]['rows'],
854
+ ranges[token_range]['attempts']))
855
+ failed += 1
856
+ else: # partial result received
857
+ data, num = result
858
+ self.writer.write(data, num)
859
+ meter.increment(n=num)
860
+ ranges[token_range]['rows'] += num
861
+
862
+ if self.num_live_processes() < len(processes):
863
+ for process in processes:
864
+ if not process.is_alive():
865
+ shell.printerr('Child process %d died with exit code %d' % (process.pid, process.exitcode))
866
+
867
+ if succeeded < total_requests:
868
+ shell.printerr('Exported %d ranges out of %d total ranges, some records might be missing'
869
+ % (succeeded, total_requests))
870
+
871
+ self.printmsg("\n%d rows exported to %d files in %s." %
872
+ (meter.get_total_records(),
873
+ self.writer.num_files,
874
+ self.describe_interval(time.time() - self.time_start)))
875
+
876
+
877
+ class FilesReader(object):
878
+ """
879
+ A wrapper around a csv reader to keep track of when we have
880
+ exhausted reading input files. We are passed a comma separated
881
+ list of paths, where each path is a valid glob expression.
882
+ We generate a source generator and we read each source one
883
+ by one.
884
+ """
885
+ def __init__(self, fname, options):
886
+ self.chunk_size = options.copy['chunksize']
887
+ self.header = options.copy['header']
888
+ self.max_rows = options.copy['maxrows']
889
+ self.skip_rows = options.copy['skiprows']
890
+ self.fname = fname
891
+ self.sources = None # might be initialised directly here? (see CASSANDRA-17350)
892
+ self.num_sources = 0
893
+ self.current_source = None
894
+ self.num_read = 0
895
+
896
+ @staticmethod
897
+ def get_source(paths):
898
+ """
899
+ Return a source generator. Each source is a named tuple
900
+ wrapping the source input, file name and a boolean indicating
901
+ if it requires closing.
902
+ """
903
+ def make_source(fname):
904
+ try:
905
+ return open(fname, 'r')
906
+ except IOError as e:
907
+ raise IOError("Can't open %r for reading: %s" % (fname, e))
908
+
909
+ for path in paths.split(','):
910
+ path = path.strip()
911
+ if os.path.isfile(path):
912
+ yield make_source(path)
913
+ else:
914
+ result = glob.glob(path)
915
+ if len(result) == 0:
916
+ raise IOError("Can't open %r for reading: no matching file found" % (path,))
917
+
918
+ for f in result:
919
+ yield make_source(f)
920
+
921
+ def start(self):
922
+ self.sources = self.get_source(self.fname)
923
+ self.next_source()
924
+
925
+ @property
926
+ def exhausted(self):
927
+ return not self.current_source
928
+
929
+ def next_source(self):
930
+ """
931
+ Close the current source, if any, and open the next one. Return true
932
+ if there is another source, false otherwise.
933
+ """
934
+ self.close_current_source()
935
+ while self.current_source is None:
936
+ try:
937
+ self.current_source = next(self.sources)
938
+ if self.current_source:
939
+ self.num_sources += 1
940
+ except StopIteration:
941
+ return False
942
+
943
+ if self.header:
944
+ next(self.current_source)
945
+
946
+ return True
947
+
948
+ def close_current_source(self):
949
+ if not self.current_source:
950
+ return
951
+
952
+ self.current_source.close()
953
+ self.current_source = None
954
+
955
+ def close(self):
956
+ self.close_current_source()
957
+
958
+ def read_rows(self, max_rows):
959
+ if not self.current_source:
960
+ return []
961
+
962
+ rows = []
963
+ for i in range(min(max_rows, self.chunk_size)):
964
+ try:
965
+ row = next(self.current_source)
966
+ self.num_read += 1
967
+
968
+ if 0 <= self.max_rows < self.num_read:
969
+ self.next_source()
970
+ break
971
+
972
+ if self.num_read > self.skip_rows:
973
+ rows.append(row)
974
+
975
+ except StopIteration:
976
+ self.next_source()
977
+ break
978
+
979
+ return [_f for _f in rows if _f]
980
+
981
+
982
+ class PipeReader(object):
983
+ """
984
+ A class for reading rows received on a pipe, this is used for reading input from STDIN
985
+ """
986
+ def __init__(self, inpipe, options):
987
+ self.inpipe = inpipe
988
+ self.chunk_size = options.copy['chunksize']
989
+ self.header = options.copy['header']
990
+ self.max_rows = options.copy['maxrows']
991
+ self.skip_rows = options.copy['skiprows']
992
+ self.num_read = 0
993
+ self.exhausted = False
994
+ self.num_sources = 1
995
+
996
+ def start(self):
997
+ pass
998
+
999
+ def read_rows(self, max_rows):
1000
+ rows = []
1001
+ for i in range(min(max_rows, self.chunk_size)):
1002
+ row = self.inpipe.recv()
1003
+ if row is None:
1004
+ self.exhausted = True
1005
+ break
1006
+
1007
+ self.num_read += 1
1008
+ if 0 <= self.max_rows < self.num_read:
1009
+ self.exhausted = True
1010
+ break # max rows exceeded
1011
+
1012
+ if self.header or self.num_read < self.skip_rows:
1013
+ self.header = False # skip header or initial skip_rows rows
1014
+ continue
1015
+
1016
+ rows.append(row)
1017
+
1018
+ return rows
1019
+
1020
+
1021
+ class ImportProcessResult(object):
1022
+ """
1023
+ An object sent from ImportProcess instances to the parent import task in order to indicate progress.
1024
+ """
1025
+ def __init__(self, imported=0):
1026
+ self.imported = imported
1027
+
1028
+
1029
+ class FeedingProcessResult(object):
1030
+ """
1031
+ An object sent from FeedingProcess instances to the parent import task in order to indicate progress.
1032
+ """
1033
+ def __init__(self, sent, reader):
1034
+ self.sent = sent
1035
+ self.num_sources = reader.num_sources
1036
+ self.skip_rows = reader.skip_rows
1037
+
1038
+
1039
+ class ImportTaskError(object):
1040
+ """
1041
+ An object sent from child processes (feeder or workers) to the parent import task to indicate an error.
1042
+ """
1043
+ def __init__(self, name, msg, rows=None, attempts=1, final=True):
1044
+ self.name = name
1045
+ self.msg = msg
1046
+ self.rows = rows if rows else []
1047
+ self.attempts = attempts
1048
+ self.final = final
1049
+
1050
+ def is_parse_error(self):
1051
+ """
1052
+ We treat read and parse errors as unrecoverable and we have different global counters for giving up when
1053
+ a maximum has been reached. We consider value and type errors as parse errors as well since they
1054
+ are typically non recoverable.
1055
+ """
1056
+ name = self.name
1057
+ return name.startswith('ValueError') or name.startswith('TypeError') or \
1058
+ name.startswith('ParseError') or name.startswith('IndexError') or name.startswith('ReadError')
1059
+
1060
+
1061
+ class ImportErrorHandler(object):
1062
+ """
1063
+ A class for managing import errors
1064
+ """
1065
+ def __init__(self, task):
1066
+ self.shell = task.shell
1067
+ self.options = task.options
1068
+ self.max_attempts = self.options.copy['maxattempts']
1069
+ self.max_parse_errors = self.options.copy['maxparseerrors']
1070
+ self.max_insert_errors = self.options.copy['maxinserterrors']
1071
+ self.err_file = self.options.copy['errfile']
1072
+ self.parse_errors = 0
1073
+ self.insert_errors = 0
1074
+ self.num_rows_failed = 0
1075
+
1076
+ if os.path.isfile(self.err_file):
1077
+ now = datetime.datetime.now()
1078
+ old_err_file = self.err_file + now.strftime('.%Y%m%d_%H%M%S')
1079
+ printdebugmsg("Renaming existing %s to %s\n" % (self.err_file, old_err_file))
1080
+ os.rename(self.err_file, old_err_file)
1081
+
1082
+ def max_exceeded(self):
1083
+ if self.insert_errors > self.max_insert_errors >= 0:
1084
+ self.shell.printerr("Exceeded maximum number of insert errors %d" % self.max_insert_errors)
1085
+ return True
1086
+
1087
+ if self.parse_errors > self.max_parse_errors >= 0:
1088
+ self.shell.printerr("Exceeded maximum number of parse errors %d" % self.max_parse_errors)
1089
+ return True
1090
+
1091
+ return False
1092
+
1093
+ def add_failed_rows(self, rows):
1094
+ self.num_rows_failed += len(rows)
1095
+
1096
+ with open(self.err_file, "a") as f:
1097
+ writer = csv.writer(f, **self.options.dialect)
1098
+ for row in rows:
1099
+ writer.writerow(row)
1100
+
1101
+ def handle_error(self, err):
1102
+ """
1103
+ Handle an error by printing the appropriate error message and incrementing the correct counter.
1104
+ """
1105
+ shell = self.shell
1106
+
1107
+ if err.is_parse_error():
1108
+ self.parse_errors += len(err.rows)
1109
+ self.add_failed_rows(err.rows)
1110
+ shell.printerr("Failed to import %d rows: %s - %s, given up without retries"
1111
+ % (len(err.rows), err.name, err.msg))
1112
+ else:
1113
+ if not err.final:
1114
+ shell.printerr("Failed to import %d rows: %s - %s, will retry later, attempt %d of %d"
1115
+ % (len(err.rows), err.name, err.msg, err.attempts, self.max_attempts))
1116
+ else:
1117
+ self.insert_errors += len(err.rows)
1118
+ self.add_failed_rows(err.rows)
1119
+ shell.printerr("Failed to import %d rows: %s - %s, given up after %d attempts"
1120
+ % (len(err.rows), err.name, err.msg, err.attempts))
1121
+
1122
+
1123
+ class ImportTask(CopyTask):
1124
+ """
1125
+ A class to import data from .csv by instantiating one or more processes
1126
+ that work in parallel (ImportProcess).
1127
+ """
1128
+ def __init__(self, shell, ks, table, columns, fname, opts, protocol_version, config_file):
1129
+ CopyTask.__init__(self, shell, ks, table, columns, fname, opts, protocol_version, config_file, 'from')
1130
+
1131
+ options = self.options
1132
+ self.skip_columns = [c.strip() for c in self.options.copy['skipcols'].split(',')]
1133
+ self.valid_columns = [c for c in self.columns if c not in self.skip_columns]
1134
+ self.receive_meter = RateMeter(log_fcn=self.printmsg,
1135
+ update_interval=options.copy['reportfrequency'],
1136
+ log_file=options.copy['ratefile'])
1137
+ self.error_handler = ImportErrorHandler(self)
1138
+ self.feeding_result = None
1139
+ self.sent = 0
1140
+
1141
+ def make_params(self):
1142
+ ret = CopyTask.make_params(self)
1143
+ ret['skip_columns'] = self.skip_columns
1144
+ ret['valid_columns'] = self.valid_columns
1145
+ return ret
1146
+
1147
+ def validate_columns(self):
1148
+ if not CopyTask.validate_columns(self):
1149
+ return False
1150
+
1151
+ shell = self.shell
1152
+ if not self.valid_columns:
1153
+ shell.printerr("No valid column specified")
1154
+ return False
1155
+
1156
+ for c in self.table_meta.primary_key:
1157
+ if c.name not in self.valid_columns:
1158
+ shell.printerr("Primary key column '%s' missing or skipped" % (c.name,))
1159
+ return False
1160
+
1161
+ return True
1162
+
1163
+ def run(self):
1164
+ shell = self.shell
1165
+
1166
+ if self.options.unrecognized:
1167
+ shell.printerr('Unrecognized COPY FROM options: %s' % ', '.join(list(self.options.unrecognized.keys())))
1168
+ return
1169
+
1170
+ if not self.validate_columns():
1171
+ return 0
1172
+
1173
+ columns = "[" + ", ".join(self.valid_columns) + "]"
1174
+ self.printmsg("\nStarting copy of %s.%s with columns %s." % (self.ks, self.table, columns))
1175
+
1176
+ try:
1177
+ params = self.make_params()
1178
+
1179
+ for i in range(self.num_processes - 1):
1180
+ self.processes.append(ImportProcess(self.update_params(params, i)))
1181
+
1182
+ feeder = FeedingProcess(self.outmsg.pipes[-1], self.inmsg.pipes[-1],
1183
+ self.outmsg.pipes[:-1], self.fname, self.options)
1184
+ self.processes.append(feeder)
1185
+
1186
+ self.start_processes()
1187
+
1188
+ pr = profile_on() if PROFILE_ON else None
1189
+
1190
+ self.import_records()
1191
+
1192
+ if pr:
1193
+ profile_off(pr, file_name='parent_profile_%d.txt' % (os.getpid(),))
1194
+
1195
+ except Exception as exc:
1196
+ shell.printerr(str(exc))
1197
+ if shell.debug:
1198
+ traceback.print_exc()
1199
+ return 0
1200
+ finally:
1201
+ self.close()
1202
+
1203
+ def send_stdin_rows(self):
1204
+ """
1205
+ We need to pass stdin rows to the feeder process as it is not safe to pickle or share stdin
1206
+ directly (in case of file the child process would close it). This is a very primitive support
1207
+ for STDIN import in that we we won't start reporting progress until STDIN is fully consumed. I
1208
+ think this is reasonable.
1209
+ """
1210
+ shell = self.shell
1211
+
1212
+ self.printmsg("[Use . on a line by itself to end input]")
1213
+ for row in shell.use_stdin_reader(prompt='[copy] ', until=r'.'):
1214
+ self.outmsg.channels[-1].send(row)
1215
+
1216
+ self.outmsg.channels[-1].send(None)
1217
+ if shell.tty:
1218
+ print()
1219
+
1220
+ def import_records(self):
1221
+ """
1222
+ Keep on running until we have stuff to receive or send and until all processes are running.
1223
+ Send data (batches or retries) up to the max ingest rate. If we are waiting for stuff to
1224
+ receive check the incoming queue.
1225
+ """
1226
+ if not self.fname:
1227
+ self.send_stdin_rows()
1228
+
1229
+ child_timeout = self.options.copy['childtimeout']
1230
+ last_recv_num_records = 0
1231
+ last_recv_time = time.time()
1232
+
1233
+ while self.feeding_result is None or self.receive_meter.total_records < self.feeding_result.sent:
1234
+ self.receive_results()
1235
+
1236
+ if self.feeding_result is not None:
1237
+ if self.receive_meter.total_records != last_recv_num_records:
1238
+ last_recv_num_records = self.receive_meter.total_records
1239
+ last_recv_time = time.time()
1240
+ elif (time.time() - last_recv_time) > child_timeout:
1241
+ self.shell.printerr("No records inserted in {} seconds, aborting".format(child_timeout))
1242
+ break
1243
+
1244
+ if self.error_handler.max_exceeded() or not self.all_processes_running():
1245
+ break
1246
+
1247
+ if self.error_handler.num_rows_failed:
1248
+ self.shell.printerr("Failed to process %d rows; failed rows written to %s" %
1249
+ (self.error_handler.num_rows_failed,
1250
+ self.error_handler.err_file))
1251
+
1252
+ if not self.all_processes_running():
1253
+ self.shell.printerr("{} child process(es) died unexpectedly, aborting"
1254
+ .format(self.num_processes - self.num_live_processes()))
1255
+ else:
1256
+ if self.error_handler.max_exceeded():
1257
+ self.processes[-1].terminate() # kill the feeder
1258
+
1259
+ for i, _ in enumerate(self.processes):
1260
+ if self.processes[i].is_alive():
1261
+ self.outmsg.channels[i].send(None)
1262
+
1263
+ # allow time for worker processes to exit cleanly
1264
+ attempts = 50 # 100 milliseconds per attempt, so 5 seconds total
1265
+ while attempts > 0 and self.num_live_processes() > 0:
1266
+ time.sleep(0.1)
1267
+ attempts -= 1
1268
+
1269
+ self.printmsg("\n%d rows imported from %d files in %s (%d skipped)." %
1270
+ (self.receive_meter.get_total_records() - self.error_handler.num_rows_failed,
1271
+ self.feeding_result.num_sources if self.feeding_result else 0,
1272
+ self.describe_interval(time.time() - self.time_start),
1273
+ self.feeding_result.skip_rows if self.feeding_result else 0))
1274
+
1275
+ def all_processes_running(self):
1276
+ return self.num_live_processes() == len(self.processes)
1277
+
1278
+ def receive_results(self):
1279
+ """
1280
+ Receive results from the worker processes, which will send the number of rows imported
1281
+ or from the feeder process, which will send the number of rows sent when it has finished sending rows.
1282
+ """
1283
+ aggregate_result = ImportProcessResult()
1284
+ try:
1285
+ for result in self.inmsg.recv(timeout=0.1):
1286
+ if isinstance(result, ImportProcessResult):
1287
+ aggregate_result.imported += result.imported
1288
+ elif isinstance(result, ImportTaskError):
1289
+ self.error_handler.handle_error(result)
1290
+ elif isinstance(result, FeedingProcessResult):
1291
+ self.feeding_result = result
1292
+ else:
1293
+ raise ValueError("Unexpected result: %s" % (result,))
1294
+ finally:
1295
+ self.receive_meter.increment(aggregate_result.imported)
1296
+
1297
+
1298
+ class FeedingProcess(mp.Process):
1299
+ """
1300
+ A process that reads from import sources and sends chunks to worker processes.
1301
+ """
1302
+ def __init__(self, inpipe, outpipe, worker_pipes, fname, options):
1303
+ super(FeedingProcess, self).__init__(target=self.run)
1304
+ self.inpipe = inpipe
1305
+ self.outpipe = outpipe
1306
+ self.worker_pipes = worker_pipes
1307
+ self.inmsg = None # might be initialised directly here? (see CASSANDRA-17350)
1308
+ self.outmsg = None # might be initialised directly here? (see CASSANDRA-17350)
1309
+ self.worker_channels = None # might be initialised directly here? (see CASSANDRA-17350)
1310
+ self.reader = FilesReader(fname, options) if fname else PipeReader(inpipe, options)
1311
+ self.send_meter = RateMeter(log_fcn=None, update_interval=1)
1312
+ self.ingest_rate = options.copy['ingestrate']
1313
+ self.num_worker_processes = options.copy['numprocesses']
1314
+ self.max_pending_chunks = options.copy['maxpendingchunks']
1315
+ self.chunk_id = 0
1316
+
1317
+ def on_fork(self):
1318
+ """
1319
+ Create the channels and release any parent connections after forking,
1320
+ see CASSANDRA-11749 for details.
1321
+ """
1322
+ self.inmsg = ReceivingChannel(self.inpipe)
1323
+ self.outmsg = SendingChannel(self.outpipe)
1324
+ self.worker_channels = [SendingChannel(p) for p in self.worker_pipes]
1325
+
1326
+ def run(self):
1327
+ pr = profile_on() if PROFILE_ON else None
1328
+
1329
+ self.inner_run()
1330
+
1331
+ if pr:
1332
+ profile_off(pr, file_name='feeder_profile_%d.txt' % (os.getpid(),))
1333
+
1334
+ def inner_run(self):
1335
+ """
1336
+ Send one batch per worker process to the queue unless we have exceeded the ingest rate.
1337
+ In the export case we queue everything and let the worker processes throttle using max_requests,
1338
+ here we throttle using the ingest rate in the feeding process because of memory usage concerns.
1339
+ When finished we send back to the parent process the total number of rows sent.
1340
+ """
1341
+
1342
+ self.on_fork()
1343
+
1344
+ reader = self.reader
1345
+ try:
1346
+ reader.start()
1347
+ except IOError as exc:
1348
+ self.outmsg.send(
1349
+ ImportTaskError(exc.__class__.__name__, exc.message if hasattr(exc, 'message') else str(exc)))
1350
+
1351
+ channels = self.worker_channels
1352
+ max_pending_chunks = self.max_pending_chunks
1353
+ sent = 0
1354
+ failed_attempts = 0
1355
+
1356
+ while not reader.exhausted:
1357
+ channels_eligible = [c for c in channels if c.num_pending() < max_pending_chunks]
1358
+ if not channels_eligible:
1359
+ failed_attempts += 1
1360
+ delay = randint(1, pow(2, failed_attempts))
1361
+ printdebugmsg("All workers busy, sleeping for %d second(s)" % (delay,))
1362
+ time.sleep(delay)
1363
+ continue
1364
+ elif failed_attempts > 0:
1365
+ failed_attempts = 0
1366
+
1367
+ for ch in channels_eligible:
1368
+ try:
1369
+ max_rows = self.ingest_rate - self.send_meter.current_record
1370
+ if max_rows <= 0:
1371
+ self.send_meter.maybe_update(sleep=False)
1372
+ continue
1373
+
1374
+ rows = reader.read_rows(max_rows)
1375
+ if rows:
1376
+ sent += self.send_chunk(ch, rows)
1377
+ except Exception as exc:
1378
+ self.outmsg.send(
1379
+ ImportTaskError(exc.__class__.__name__, exc.message if hasattr(exc, 'message') else str(exc)))
1380
+
1381
+ if reader.exhausted:
1382
+ break
1383
+
1384
+ # send back to the parent process the number of rows sent to the worker processes
1385
+ self.outmsg.send(FeedingProcessResult(sent, reader))
1386
+
1387
+ # wait for poison pill (None)
1388
+ self.inmsg.recv()
1389
+
1390
+ def send_chunk(self, ch, rows):
1391
+ self.chunk_id += 1
1392
+ num_rows = len(rows)
1393
+ self.send_meter.increment(num_rows)
1394
+ ch.send({'id': self.chunk_id, 'rows': rows, 'imported': 0, 'num_rows_sent': num_rows})
1395
+ return num_rows
1396
+
1397
+ def close(self):
1398
+ self.reader.close()
1399
+ self.inmsg.close()
1400
+ self.outmsg.close()
1401
+
1402
+ for ch in self.worker_channels:
1403
+ ch.close()
1404
+
1405
+
1406
+ class ChildProcess(mp.Process):
1407
+ """
1408
+ An child worker process, this is for common functionality between ImportProcess and ExportProcess.
1409
+ """
1410
+
1411
+ def __init__(self, params, target):
1412
+ super(ChildProcess, self).__init__(target=target)
1413
+ self.inpipe = params['inpipe']
1414
+ self.outpipe = params['outpipe']
1415
+ self.inmsg = None # might be initialised directly here? (see CASSANDRA-17350)
1416
+ self.outmsg = None # might be initialised directly here? (see CASSANDRA-17350)
1417
+ self.ks = params['ks']
1418
+ self.table = params['table']
1419
+ self.local_dc = params['local_dc']
1420
+ self.columns = params['columns']
1421
+ self.debug = params['debug']
1422
+ self.port = params['port']
1423
+ self.hostname = params['hostname']
1424
+ self.connect_timeout = params['connect_timeout']
1425
+ self.cql_version = params['cql_version']
1426
+ self.auth_provider = params['auth_provider']
1427
+ self.ssl = params['ssl']
1428
+ self.protocol_version = params['protocol_version']
1429
+ self.config_file = params['config_file']
1430
+
1431
+ options = params['options']
1432
+ self.date_time_format = options.copy['dtformats']
1433
+ self.consistency_level = options.copy['consistencylevel']
1434
+ self.decimal_sep = options.copy['decimalsep']
1435
+ self.thousands_sep = options.copy['thousandssep']
1436
+ self.boolean_styles = options.copy['boolstyle']
1437
+ self.max_attempts = options.copy['maxattempts']
1438
+ self.encoding = options.copy['encoding']
1439
+ # Here we inject some failures for testing purposes, only if this environment variable is set
1440
+ if os.environ.get('CQLSH_COPY_TEST_FAILURES', ''):
1441
+ self.test_failures = json.loads(os.environ.get('CQLSH_COPY_TEST_FAILURES', ''))
1442
+ else:
1443
+ self.test_failures = None
1444
+ # attributes for coverage
1445
+ self.coverage = params['coverage']
1446
+ self.coveragerc_path = params['coveragerc_path']
1447
+ self.coverage_collection = None
1448
+ self.sigterm_handler = None
1449
+ self.sighup_handler = None
1450
+
1451
+ def on_fork(self):
1452
+ """
1453
+ Create the channels and release any parent connections after forking, see CASSANDRA-11749 for details.
1454
+ """
1455
+ self.inmsg = ReceivingChannel(self.inpipe)
1456
+ self.outmsg = SendingChannel(self.outpipe)
1457
+
1458
+ def close(self):
1459
+ printdebugmsg("Closing queues...")
1460
+ self.inmsg.close()
1461
+ self.outmsg.close()
1462
+
1463
+ def start_coverage(self):
1464
+ import coverage
1465
+ self.coverage_collection = coverage.Coverage(config_file=self.coveragerc_path)
1466
+ self.coverage_collection.start()
1467
+
1468
+ # save current handlers for SIGTERM and SIGHUP
1469
+ self.sigterm_handler = signal.getsignal(signal.SIGTERM)
1470
+ self.sighup_handler = signal.getsignal(signal.SIGTERM)
1471
+
1472
+ def handle_sigterm():
1473
+ self.stop_coverage()
1474
+ self.close()
1475
+ self.terminate()
1476
+
1477
+ # set custom handler for SIGHUP and SIGTERM
1478
+ # needed to make sure coverage data is saved
1479
+ signal.signal(signal.SIGTERM, handle_sigterm)
1480
+ signal.signal(signal.SIGHUP, handle_sigterm)
1481
+
1482
+ def stop_coverage(self):
1483
+ self.coverage_collection.stop()
1484
+ self.coverage_collection.save()
1485
+ signal.signal(signal.SIGTERM, self.sigterm_handler)
1486
+ signal.signal(signal.SIGHUP, self.sighup_handler)
1487
+
1488
+
1489
+ class ExpBackoffRetryPolicy(RetryPolicy):
1490
+ """
1491
+ A retry policy with exponential back-off for read timeouts and write timeouts
1492
+ """
1493
+ def __init__(self, parent_process):
1494
+ RetryPolicy.__init__(self)
1495
+ self.max_attempts = parent_process.max_attempts
1496
+
1497
+ def on_read_timeout(self, query, consistency, required_responses,
1498
+ received_responses, data_retrieved, retry_num):
1499
+ return self._handle_timeout(consistency, retry_num)
1500
+
1501
+ def on_write_timeout(self, query, consistency, write_type,
1502
+ required_responses, received_responses, retry_num):
1503
+ return self._handle_timeout(consistency, retry_num)
1504
+
1505
+ def _handle_timeout(self, consistency, retry_num):
1506
+ delay = self.backoff(retry_num)
1507
+ if delay > 0:
1508
+ printdebugmsg("Timeout received, retrying after %d seconds" % (delay,))
1509
+ time.sleep(delay)
1510
+ return self.RETRY, consistency
1511
+ elif delay == 0:
1512
+ printdebugmsg("Timeout received, retrying immediately")
1513
+ return self.RETRY, consistency
1514
+ else:
1515
+ printdebugmsg("Timeout received, giving up after %d attempts" % (retry_num + 1))
1516
+ return self.RETHROW, None
1517
+
1518
+ def backoff(self, retry_num):
1519
+ """
1520
+ Perform exponential back-off up to a maximum number of times, where
1521
+ this maximum is per query.
1522
+ To back-off we should wait a random number of seconds
1523
+ between 0 and 2^c - 1, where c is the number of total failures.
1524
+
1525
+ :return : the number of seconds to wait for, -1 if we should not retry
1526
+ """
1527
+ if retry_num >= self.max_attempts:
1528
+ return -1
1529
+
1530
+ delay = randint(0, pow(2, retry_num + 1) - 1)
1531
+ return delay
1532
+
1533
+
1534
+ class ExportSession(object):
1535
+ """
1536
+ A class for connecting to a cluster and storing the number
1537
+ of requests that this connection is processing. It wraps the methods
1538
+ for executing a query asynchronously and for shutting down the
1539
+ connection to the cluster.
1540
+ """
1541
+ def __init__(self, cluster, export_process):
1542
+ session = cluster.connect(export_process.ks)
1543
+ session.row_factory = tuple_factory
1544
+ session.default_fetch_size = export_process.options.copy['pagesize']
1545
+ session.default_timeout = export_process.options.copy['pagetimeout']
1546
+
1547
+ printdebugmsg("Created connection to %s with page size %d and timeout %d seconds per page"
1548
+ % (cluster.contact_points, session.default_fetch_size, session.default_timeout))
1549
+
1550
+ self.cluster = cluster
1551
+ self.session = session
1552
+ self.requests = 1
1553
+ self.lock = threading.Lock()
1554
+ self.consistency_level = export_process.consistency_level
1555
+
1556
+ def add_request(self):
1557
+ with self.lock:
1558
+ self.requests += 1
1559
+
1560
+ def complete_request(self):
1561
+ with self.lock:
1562
+ self.requests -= 1
1563
+
1564
+ def num_requests(self):
1565
+ with self.lock:
1566
+ return self.requests
1567
+
1568
+ def execute_async(self, query):
1569
+ return self.session.execute_async(SimpleStatement(query, consistency_level=self.consistency_level))
1570
+
1571
+ def shutdown(self):
1572
+ self.cluster.shutdown()
1573
+
1574
+
1575
+ class ExportProcess(ChildProcess):
1576
+ """
1577
+ An child worker process for the export task, ExportTask.
1578
+ """
1579
+
1580
+ def __init__(self, params):
1581
+ ChildProcess.__init__(self, params=params, target=self.run)
1582
+ options = params['options']
1583
+ self.float_precision = options.copy['floatprecision']
1584
+ self.double_precision = options.copy['doubleprecision']
1585
+ self.nullval = options.copy['nullval']
1586
+ self.max_requests = options.copy['maxrequests']
1587
+
1588
+ self.hosts_to_sessions = dict()
1589
+ self.formatters = dict()
1590
+ self.options = options
1591
+
1592
+ def run(self):
1593
+ if self.coverage:
1594
+ self.start_coverage()
1595
+ try:
1596
+ self.inner_run()
1597
+ finally:
1598
+ if self.coverage:
1599
+ self.stop_coverage()
1600
+ self.close()
1601
+
1602
+ def inner_run(self):
1603
+ """
1604
+ The parent sends us (range, info) on the inbound queue (inmsg)
1605
+ in order to request us to process a range, for which we can
1606
+ select any of the hosts in info, which also contains other information for this
1607
+ range such as the number of attempts already performed. We can signal errors
1608
+ on the outbound queue (outmsg) by sending (range, error) or
1609
+ we can signal a global error by sending (None, error).
1610
+ We terminate when the inbound queue is closed.
1611
+ """
1612
+
1613
+ self.on_fork()
1614
+
1615
+ while True:
1616
+ if self.num_requests() > self.max_requests:
1617
+ time.sleep(0.001) # 1 millisecond
1618
+ continue
1619
+
1620
+ token_range, info = self.inmsg.recv()
1621
+ self.start_request(token_range, info)
1622
+
1623
+ @staticmethod
1624
+ def get_error_message(err, print_traceback=False):
1625
+ if isinstance(err, str):
1626
+ msg = err
1627
+ elif isinstance(err, BaseException):
1628
+ msg = "%s - %s" % (err.__class__.__name__, err)
1629
+ if print_traceback and sys.exc_info()[1] == err:
1630
+ traceback.print_exc()
1631
+ else:
1632
+ msg = str(err)
1633
+ return msg
1634
+
1635
+ def report_error(self, err, token_range):
1636
+ msg = self.get_error_message(err, print_traceback=self.debug)
1637
+ printdebugmsg(msg)
1638
+ self.send((token_range, Exception(msg)))
1639
+
1640
+ def send(self, response):
1641
+ self.outmsg.send(response)
1642
+
1643
+ def start_request(self, token_range, info):
1644
+ """
1645
+ Begin querying a range by executing an async query that
1646
+ will later on invoke the callbacks attached in attach_callbacks.
1647
+ """
1648
+ session = self.get_session(info['hosts'], token_range)
1649
+ if session:
1650
+ metadata = session.cluster.metadata.keyspaces[self.ks].tables[self.table]
1651
+ query = self.prepare_query(metadata.partition_key, token_range, info['attempts'])
1652
+ future = session.execute_async(query)
1653
+ self.attach_callbacks(token_range, future, session)
1654
+
1655
+ def num_requests(self):
1656
+ return sum(session.num_requests() for session in list(self.hosts_to_sessions.values()))
1657
+
1658
+ def get_session(self, hosts, token_range):
1659
+ """
1660
+ We return a session connected to one of the hosts passed in, which are valid replicas for
1661
+ the token range. We sort replicas by favouring those without any active requests yet or with the
1662
+ smallest number of requests. If we fail to connect we report an error so that the token will
1663
+ be retried again later.
1664
+
1665
+ :return: An ExportSession connected to the chosen host.
1666
+ """
1667
+ # sorted replicas favouring those with no connections yet
1668
+ hosts = sorted(hosts,
1669
+ key=lambda hh: 0 if hh not in self.hosts_to_sessions else self.hosts_to_sessions[hh].requests)
1670
+
1671
+ errors = []
1672
+ ret = None
1673
+ for host in hosts:
1674
+ try:
1675
+ ret = self.connect(host)
1676
+ except Exception as e:
1677
+ errors.append(self.get_error_message(e))
1678
+
1679
+ if ret:
1680
+ if errors:
1681
+ printdebugmsg("Warning: failed to connect to some replicas: %s" % (errors,))
1682
+ return ret
1683
+
1684
+ self.report_error("Failed to connect to all replicas %s for %s, errors: %s" % (hosts, token_range, errors),
1685
+ token_range)
1686
+ return None
1687
+
1688
+ def connect(self, host):
1689
+ if host in list(self.hosts_to_sessions.keys()):
1690
+ session = self.hosts_to_sessions[host]
1691
+ session.add_request()
1692
+ return session
1693
+
1694
+ new_cluster = Cluster(
1695
+ contact_points=(host,),
1696
+ port=self.port,
1697
+ cql_version=self.cql_version,
1698
+ protocol_version=self.protocol_version,
1699
+ auth_provider=self.auth_provider,
1700
+ ssl_context=ssl_settings(host, self.config_file) if self.ssl else None,
1701
+ load_balancing_policy=WhiteListRoundRobinPolicy([host]),
1702
+ default_retry_policy=ExpBackoffRetryPolicy(self),
1703
+ compression=None,
1704
+ control_connection_timeout=self.connect_timeout,
1705
+ connect_timeout=self.connect_timeout,
1706
+ idle_heartbeat_interval=0)
1707
+ session = ExportSession(new_cluster, self)
1708
+ self.hosts_to_sessions[host] = session
1709
+ return session
1710
+
1711
+ def attach_callbacks(self, token_range, future, session):
1712
+ metadata = session.cluster.metadata
1713
+ ks_meta = metadata.keyspaces[self.ks]
1714
+ table_meta = ks_meta.tables[self.table]
1715
+ cql_types = [CqlType(table_meta.columns[c].cql_type, ks_meta) for c in self.columns]
1716
+
1717
+ def result_callback(rows):
1718
+ if future.has_more_pages:
1719
+ future.start_fetching_next_page()
1720
+ self.write_rows_to_csv(token_range, rows, cql_types)
1721
+ else:
1722
+ self.write_rows_to_csv(token_range, rows, cql_types)
1723
+ self.send((None, None))
1724
+ session.complete_request()
1725
+
1726
+ def err_callback(err):
1727
+ self.report_error(err, token_range)
1728
+ session.complete_request()
1729
+
1730
+ future.add_callbacks(callback=result_callback, errback=err_callback)
1731
+
1732
+ def write_rows_to_csv(self, token_range, rows, cql_types):
1733
+ if not rows:
1734
+ return # no rows in this range
1735
+
1736
+ try:
1737
+ output = StringIO()
1738
+ writer = csv.writer(output, **self.options.dialect)
1739
+
1740
+ for row in rows:
1741
+ writer.writerow(list(map(self.format_value, row, cql_types)))
1742
+
1743
+ data = (output.getvalue(), len(rows))
1744
+ self.send((token_range, data))
1745
+ output.close()
1746
+
1747
+ except Exception as e:
1748
+ self.report_error(e, token_range)
1749
+
1750
+ def format_value(self, val, cqltype):
1751
+ if val is None or val == EMPTY:
1752
+ return format_value_default(self.nullval, colormap=NO_COLOR_MAP)
1753
+
1754
+ formatter = self.formatters.get(cqltype, None)
1755
+ if not formatter:
1756
+ formatter = get_formatter(val, cqltype)
1757
+ self.formatters[cqltype] = formatter
1758
+
1759
+ if not hasattr(cqltype, 'precision'):
1760
+ cqltype.precision = self.double_precision if cqltype.type_name == 'double' else self.float_precision
1761
+
1762
+ formatted = formatter(val, cqltype=cqltype,
1763
+ encoding=self.encoding, colormap=NO_COLOR_MAP, date_time_format=self.date_time_format,
1764
+ float_precision=cqltype.precision, nullval=self.nullval, quote=False,
1765
+ decimal_sep=self.decimal_sep, thousands_sep=self.thousands_sep,
1766
+ boolean_styles=self.boolean_styles)
1767
+ return formatted
1768
+
1769
+ def close(self):
1770
+ ChildProcess.close(self)
1771
+ for session in list(self.hosts_to_sessions.values()):
1772
+ session.shutdown()
1773
+
1774
+ def prepare_query(self, partition_key, token_range, attempts):
1775
+ """
1776
+ Return the export query or a fake query with some failure injected.
1777
+ """
1778
+ if self.test_failures:
1779
+ return self.maybe_inject_failures(partition_key, token_range, attempts)
1780
+ else:
1781
+ return self.prepare_export_query(partition_key, token_range)
1782
+
1783
+ def maybe_inject_failures(self, partition_key, token_range, attempts):
1784
+ """
1785
+ Examine self.test_failures and see if token_range is either a token range
1786
+ supposed to cause a failure (failing_range) or to terminate the worker process
1787
+ (exit_range). If not then call prepare_export_query(), which implements the
1788
+ normal behavior.
1789
+ """
1790
+ start_token, end_token = token_range
1791
+
1792
+ if not start_token or not end_token:
1793
+ # exclude first and last ranges to make things simpler
1794
+ return self.prepare_export_query(partition_key, token_range)
1795
+
1796
+ if 'failing_range' in self.test_failures:
1797
+ failing_range = self.test_failures['failing_range']
1798
+ if start_token >= failing_range['start'] and end_token <= failing_range['end']:
1799
+ if attempts < failing_range['num_failures']:
1800
+ return 'SELECT * from bad_table'
1801
+
1802
+ if 'exit_range' in self.test_failures:
1803
+ exit_range = self.test_failures['exit_range']
1804
+ if start_token >= exit_range['start'] and end_token <= exit_range['end']:
1805
+ sys.exit(1)
1806
+
1807
+ return self.prepare_export_query(partition_key, token_range)
1808
+
1809
+ def prepare_export_query(self, partition_key, token_range):
1810
+ """
1811
+ Return a query where we select all the data for this token range
1812
+ """
1813
+ pk_cols = ", ".join(protect_names(col.name for col in partition_key))
1814
+ columnlist = ', '.join(protect_names(self.columns))
1815
+ start_token, end_token = token_range
1816
+ query = 'SELECT %s FROM %s.%s' % (columnlist, protect_name(self.ks), protect_name(self.table))
1817
+ if start_token is not None or end_token is not None:
1818
+ query += ' WHERE'
1819
+ if start_token is not None:
1820
+ query += ' token(%s) > %s' % (pk_cols, start_token)
1821
+ if start_token is not None and end_token is not None:
1822
+ query += ' AND'
1823
+ if end_token is not None:
1824
+ query += ' token(%s) <= %s' % (pk_cols, end_token)
1825
+ return query
1826
+
1827
+
1828
+ class ParseError(Exception):
1829
+ """ We failed to parse an import record """
1830
+ pass
1831
+
1832
+
1833
+ class ImmutableDict(frozenset):
1834
+ """
1835
+ Immutable dictionary implementation to represent map types.
1836
+ We need to pass BoundStatement.bind() a dict() because it calls iteritems(),
1837
+ except we can't create a dict with another dict as the key, hence we use a class
1838
+ that adds iteritems to a frozen set of tuples (which is how dict are normally made
1839
+ immutable in python).
1840
+ Must be declared in the top level of the module to be available for pickling.
1841
+ """
1842
+ iteritems = frozenset.__iter__
1843
+
1844
+ def items(self):
1845
+ for k, v in self.iteritems():
1846
+ yield k, v
1847
+
1848
+
1849
+ class ImportConversion(object):
1850
+ """
1851
+ A class for converting strings to values when importing from csv, used by ImportProcess,
1852
+ the parent.
1853
+ """
1854
+ def __init__(self, parent, table_meta, statement=None):
1855
+ self.ks = parent.ks
1856
+ self.table = parent.table
1857
+ self.columns = parent.valid_columns
1858
+ self.nullval = parent.nullval
1859
+ self.decimal_sep = parent.decimal_sep
1860
+ self.thousands_sep = parent.thousands_sep
1861
+ self.boolean_styles = parent.boolean_styles
1862
+ self.date_time_format = parent.date_time_format.timestamp_format
1863
+ self.debug = parent.debug
1864
+ self.encoding = parent.encoding
1865
+
1866
+ self.table_meta = table_meta
1867
+ self.primary_key_indexes = [self.columns.index(col.name) for col in self.table_meta.primary_key]
1868
+ self.partition_key_indexes = [self.columns.index(col.name) for col in self.table_meta.partition_key]
1869
+
1870
+ if statement is None:
1871
+ self.use_prepared_statements = False
1872
+ statement = self._get_primary_key_statement(parent, table_meta)
1873
+ else:
1874
+ self.use_prepared_statements = True
1875
+
1876
+ self.is_counter = parent.is_counter(table_meta)
1877
+ self.proto_version = statement.protocol_version
1878
+
1879
+ # the cql types and converters for the prepared statement, either the full statement or only the primary keys
1880
+ self.cqltypes = [c.type for c in statement.column_metadata]
1881
+ self.converters = [self._get_converter(c.type) for c in statement.column_metadata]
1882
+
1883
+ # the cql types for the entire statement, these are the same as the types above but
1884
+ # only when using prepared statements
1885
+ self.coltypes = [table_meta.columns[name].cql_type for name in parent.valid_columns]
1886
+ # these functions are used for non-prepared statements to protect values with quotes if required
1887
+ self.protectors = [self._get_protector(t) for t in self.coltypes]
1888
+
1889
+ @staticmethod
1890
+ def _get_protector(t):
1891
+ if t in ('ascii', 'text', 'timestamp', 'date', 'time', 'inet'):
1892
+ return lambda v: protect_value(v)
1893
+ else:
1894
+ return lambda v: v
1895
+
1896
+ @staticmethod
1897
+ def _get_primary_key_statement(parent, table_meta):
1898
+ """
1899
+ We prepare a query statement to find out the types of the partition key columns so we can
1900
+ route the update query to the correct replicas. As far as I understood this is the easiest
1901
+ way to find out the types of the partition columns, we will never use this prepared statement
1902
+ """
1903
+ where_clause = ' AND '.join(['%s = ?' % (protect_name(c.name)) for c in table_meta.partition_key])
1904
+ select_query = 'SELECT * FROM %s.%s WHERE %s' % (protect_name(parent.ks),
1905
+ protect_name(parent.table),
1906
+ where_clause)
1907
+ return parent.session.prepare(select_query)
1908
+
1909
+ @staticmethod
1910
+ def unprotect(v):
1911
+ if v is not None:
1912
+ return CqlRuleSet.dequote_value(v)
1913
+
1914
+ def _get_converter(self, cql_type):
1915
+ """
1916
+ Return a function that converts a string into a value the can be passed
1917
+ into BoundStatement.bind() for the given cql type. See cassandra.cqltypes
1918
+ for more details.
1919
+ """
1920
+ unprotect = self.unprotect
1921
+
1922
+ def convert(t, v):
1923
+ v = unprotect(v)
1924
+ if v == self.nullval:
1925
+ return self.get_null_val()
1926
+ return converters.get(t.typename, convert_unknown)(v, ct=t)
1927
+
1928
+ def convert_mandatory(t, v):
1929
+ v = unprotect(v)
1930
+ # we can't distinguish between empty strings and null values in csv. Null values are not supported in
1931
+ # collections, so it must be an empty string.
1932
+ if v == self.nullval and not issubclass(t, VarcharType):
1933
+ raise ParseError('Empty values are not allowed')
1934
+ return converters.get(t.typename, convert_unknown)(v, ct=t)
1935
+
1936
+ def convert_blob(v, **_):
1937
+ if sys.version_info.major >= 3:
1938
+ return bytes.fromhex(v[2:])
1939
+ else:
1940
+ return BlobType(v[2:].decode("hex"))
1941
+
1942
+ def convert_text(v, **_):
1943
+ return str(v)
1944
+
1945
+ def convert_uuid(v, **_):
1946
+ return UUID(v)
1947
+
1948
+ def convert_bool(v, **_):
1949
+ return True if v.lower() == self.boolean_styles[0].lower() else False
1950
+
1951
+ def get_convert_integer_fcn(adapter=int):
1952
+ """
1953
+ Return a slow and a fast integer conversion function depending on self.thousands_sep
1954
+ """
1955
+ if self.thousands_sep:
1956
+ return lambda v, ct=cql_type: adapter(v.replace(self.thousands_sep, ''))
1957
+ else:
1958
+ return lambda v, ct=cql_type: adapter(v)
1959
+
1960
+ def get_convert_decimal_fcn(adapter=float):
1961
+ """
1962
+ Return a slow and a fast decimal conversion function depending on self.thousands_sep and self.decimal_sep
1963
+ """
1964
+ empty_str = ''
1965
+ dot_str = '.'
1966
+ if self.thousands_sep and self.decimal_sep:
1967
+ return lambda v, ct=cql_type: \
1968
+ adapter(v.replace(self.thousands_sep, empty_str).replace(self.decimal_sep, dot_str))
1969
+ elif self.thousands_sep:
1970
+ return lambda v, ct=cql_type: adapter(v.replace(self.thousands_sep, empty_str))
1971
+ elif self.decimal_sep:
1972
+ return lambda v, ct=cql_type: adapter(v.replace(self.decimal_sep, dot_str))
1973
+ else:
1974
+ return lambda v, ct=cql_type: adapter(v)
1975
+
1976
+ def split(val, sep=','):
1977
+ """
1978
+ Split "val" into a list of values whenever the separator "sep" is found, but
1979
+ ignore separators inside parentheses or single quotes, except for the two
1980
+ outermost parentheses, which will be ignored. This method is called when parsing composite
1981
+ types, "val" should be at least 2 characters long, the first char should be an
1982
+ open parenthesis and the last char should be a matching closing parenthesis. We could also
1983
+ check exactly which parenthesis type depending on the caller, but I don't want to enforce
1984
+ too many checks that don't necessarily provide any additional benefits, and risk breaking
1985
+ data that could previously be imported, even if strictly speaking it is incorrect CQL.
1986
+ For example, right now we accept sets that start with '[' and ']', I don't want to break this
1987
+ by enforcing '{' and '}' in a minor release.
1988
+ """
1989
+ def is_open_paren(cc):
1990
+ return cc == '{' or cc == '[' or cc == '('
1991
+
1992
+ def is_close_paren(cc):
1993
+ return cc == '}' or cc == ']' or cc == ')'
1994
+
1995
+ def paren_match(c1, c2):
1996
+ return (c1 == '{' and c2 == '}') or (c1 == '[' and c2 == ']') or (c1 == '(' and c2 == ')')
1997
+
1998
+ if len(val) < 2 or not paren_match(val[0], val[-1]):
1999
+ raise ParseError('Invalid composite string, it should start and end with matching parentheses: {}'
2000
+ .format(val))
2001
+
2002
+ ret = []
2003
+ last = 1
2004
+ level = 0
2005
+ quote = False
2006
+ for i, c in enumerate(val):
2007
+ if c == '\'':
2008
+ quote = not quote
2009
+ elif not quote:
2010
+ if is_open_paren(c):
2011
+ level += 1
2012
+ elif is_close_paren(c):
2013
+ level -= 1
2014
+ elif c == sep and level == 1:
2015
+ ret.append(val[last:i])
2016
+ last = i + 1
2017
+ else:
2018
+ if last < len(val) - 1:
2019
+ ret.append(val[last:-1])
2020
+
2021
+ return ret
2022
+
2023
+ # this should match all possible CQL and CQLSH datetime formats
2024
+ p = re.compile(r"(\d{4})-(\d{2})-(\d{2})\s?(?:'T')?" # YYYY-MM-DD[( |'T')]
2025
+ + r"(?:(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{1,6}))?))?" # [HH:MM[:SS[.NNNNNN]]]
2026
+ + r"(?:([+\-])(\d{2}):?(\d{2}))?") # [(+|-)HH[:]MM]]
2027
+
2028
+ def convert_datetime(val, **_):
2029
+ try:
2030
+ dtval = datetime.datetime.strptime(val, self.date_time_format)
2031
+ return dtval.timestamp() * 1000
2032
+ except ValueError:
2033
+ pass # if it's not in the default format we try CQL formats
2034
+
2035
+ m = p.match(val)
2036
+ if not m:
2037
+ try:
2038
+ # in case of overflow COPY TO prints dates as milliseconds from the epoch, see
2039
+ # deserialize_date_fallback_int in cqlsh.py
2040
+ return int(val)
2041
+ except ValueError:
2042
+ raise ValueError("can't interpret %r as a date with format %s or as int" % (val,
2043
+ self.date_time_format))
2044
+
2045
+ # https://docs.python.org/3/library/time.html#time.struct_time
2046
+ tval = time.struct_time((int(m.group(1)), int(m.group(2)), int(m.group(3)), # year, month, day
2047
+ int(m.group(4)) if m.group(4) else 0, # hour
2048
+ int(m.group(5)) if m.group(5) else 0, # minute
2049
+ int(m.group(6)) if m.group(6) else 0, # second
2050
+ 0, 1, -1)) # day of week, day of year, dst-flag
2051
+
2052
+ # convert sub-seconds (a number between 1 and 6 digits) to milliseconds
2053
+ milliseconds = 0 if not m.group(7) else int(m.group(7)) * pow(10, 3 - len(m.group(7)))
2054
+
2055
+ if m.group(8):
2056
+ offset = (int(m.group(9)) * 3600 + int(m.group(10)) * 60) * int(m.group(8) + '1')
2057
+ else:
2058
+ offset = -time.timezone
2059
+
2060
+ # scale seconds to millis for the raw value
2061
+ return ((timegm(tval) + offset) * 1000) + milliseconds
2062
+
2063
+ def convert_date(v, **_):
2064
+ return Date(v)
2065
+
2066
+ def convert_time(v, **_):
2067
+ return Time(v)
2068
+
2069
+ def convert_tuple(val, ct=cql_type):
2070
+ return tuple(convert_mandatory(t, v) for t, v in zip(ct.subtypes, split(val)))
2071
+
2072
+ def convert_list(val, ct=cql_type):
2073
+ return tuple(convert_mandatory(ct.subtypes[0], v) for v in split(val))
2074
+
2075
+ def convert_set(val, ct=cql_type):
2076
+ return frozenset(convert_mandatory(ct.subtypes[0], v) for v in split(val))
2077
+
2078
+ def convert_map(val, ct=cql_type):
2079
+ """
2080
+ See ImmutableDict above for a discussion of why a special object is needed here.
2081
+ """
2082
+ split_format_str = '{%s}'
2083
+ sep = ':'
2084
+ return ImmutableDict(frozenset((convert_mandatory(ct.subtypes[0], v[0]), convert(ct.subtypes[1], v[1]))
2085
+ for v in [split(split_format_str % vv, sep=sep) for vv in split(val)]))
2086
+
2087
+ def convert_user_type(val, ct=cql_type):
2088
+ """
2089
+ A user type is a dictionary except that we must convert each key into
2090
+ an attribute, so we are using named tuples. It must also be hashable,
2091
+ so we cannot use dictionaries. Maybe there is a way to instantiate ct
2092
+ directly but I could not work it out.
2093
+ Also note that it is possible that the subfield names in the csv are in the
2094
+ wrong order, so we must sort them according to ct.fieldnames, see CASSANDRA-12959.
2095
+ """
2096
+ split_format_str = '{%s}'
2097
+ sep = ':'
2098
+ vals = [v for v in [split(split_format_str % vv, sep=sep) for vv in split(val)]]
2099
+ dict_vals = dict((unprotect(v[0]), v[1]) for v in vals)
2100
+ sorted_converted_vals = [(n, convert(t, dict_vals[n]) if n in dict_vals else self.get_null_val())
2101
+ for n, t in zip(ct.fieldnames, ct.subtypes)]
2102
+ ret_type = namedtuple(ct.typename, [v[0] for v in sorted_converted_vals])
2103
+ return ret_type(*tuple(v[1] for v in sorted_converted_vals))
2104
+
2105
+ def convert_single_subtype(val, ct=cql_type):
2106
+ return converters.get(ct.subtypes[0].typename, convert_unknown)(val, ct=ct.subtypes[0])
2107
+
2108
+ def convert_unknown(val, ct=cql_type):
2109
+ if issubclass(ct, UserType):
2110
+ return convert_user_type(val, ct=ct)
2111
+ elif issubclass(ct, ReversedType):
2112
+ return convert_single_subtype(val, ct=ct)
2113
+
2114
+ printdebugmsg("Unknown type %s (%s) for val %s" % (ct, ct.typename, val))
2115
+ return val
2116
+
2117
+ converters = {
2118
+ 'blob': convert_blob,
2119
+ 'decimal': get_convert_decimal_fcn(adapter=Decimal),
2120
+ 'uuid': convert_uuid,
2121
+ 'boolean': convert_bool,
2122
+ 'tinyint': get_convert_integer_fcn(),
2123
+ 'ascii': convert_text,
2124
+ 'float': get_convert_decimal_fcn(),
2125
+ 'double': get_convert_decimal_fcn(),
2126
+ 'bigint': get_convert_integer_fcn(adapter=int),
2127
+ 'int': get_convert_integer_fcn(),
2128
+ 'varint': get_convert_integer_fcn(),
2129
+ 'inet': convert_text,
2130
+ 'counter': get_convert_integer_fcn(adapter=int),
2131
+ 'timestamp': convert_datetime,
2132
+ 'timeuuid': convert_uuid,
2133
+ 'date': convert_date,
2134
+ 'smallint': get_convert_integer_fcn(),
2135
+ 'time': convert_time,
2136
+ 'text': convert_text,
2137
+ 'varchar': convert_text,
2138
+ 'list': convert_list,
2139
+ 'set': convert_set,
2140
+ 'map': convert_map,
2141
+ 'tuple': convert_tuple,
2142
+ 'frozen': convert_single_subtype,
2143
+ }
2144
+
2145
+ return converters.get(cql_type.typename, convert_unknown)
2146
+
2147
+ def get_null_val(self):
2148
+ """
2149
+ Return the null value that is inserted for fields that are missing from csv files.
2150
+ For counters we should return zero so that the counter value won't be incremented.
2151
+ For everything else we return nulls, this means None if we use prepared statements
2152
+ or "NULL" otherwise. Note that for counters we never use prepared statements, so we
2153
+ only check is_counter when use_prepared_statements is false.
2154
+ """
2155
+ return None if self.use_prepared_statements else ("0" if self.is_counter else "NULL")
2156
+
2157
+ def convert_row(self, row):
2158
+ """
2159
+ Convert the row into a list of parsed values if using prepared statements, else simply apply the
2160
+ protection functions to escape values with quotes when required. Also check on the row length and
2161
+ make sure primary partition key values aren't missing.
2162
+ """
2163
+ converters = self.converters if self.use_prepared_statements else self.protectors
2164
+
2165
+ if len(row) != len(converters):
2166
+ raise ParseError('Invalid row length %d should be %d' % (len(row), len(converters)))
2167
+
2168
+ for i in self.primary_key_indexes:
2169
+ if row[i] == self.nullval:
2170
+ raise ParseError(self.get_null_primary_key_message(i))
2171
+
2172
+ def convert(c, v):
2173
+ try:
2174
+ return c(v) if v != self.nullval else self.get_null_val()
2175
+ except Exception as e:
2176
+ # if we could not convert an empty string, then self.nullval has been set to a marker
2177
+ # because the user needs to import empty strings, except that the converters for some types
2178
+ # will fail to convert an empty string, in this case the null value should be inserted
2179
+ # see CASSANDRA-12794
2180
+ if v == '':
2181
+ return self.get_null_val()
2182
+
2183
+ if self.debug:
2184
+ traceback.print_exc()
2185
+ raise ParseError("Failed to parse %s : %s" % (v, e.message if hasattr(e, 'message') else str(e)))
2186
+
2187
+ return [convert(conv, val) for conv, val in zip(converters, row)]
2188
+
2189
+ def get_null_primary_key_message(self, idx):
2190
+ message = "Cannot insert null value for primary key column '%s'." % (self.columns[idx],)
2191
+ if self.nullval == '':
2192
+ message += " If you want to insert empty strings, consider using" \
2193
+ " the WITH NULL=<marker> option for COPY."
2194
+ return message
2195
+
2196
+ def get_row_partition_key_values_fcn(self):
2197
+ """
2198
+ Return a function to convert a row into a string composed of the partition key values serialized
2199
+ and binary packed (the tokens on the ring). Depending on whether we are using prepared statements, we
2200
+ may have to convert the primary key values first, so we have two different serialize_value implementations.
2201
+ We also return different functions depending on how many partition key indexes we have (single or multiple).
2202
+ See also BoundStatement.routing_key.
2203
+ """
2204
+ def serialize_value_prepared(n, v):
2205
+ return self.cqltypes[n].serialize(v, self.proto_version)
2206
+
2207
+ def serialize_value_not_prepared(n, v):
2208
+ return self.cqltypes[n].serialize(self.converters[n](self.unprotect(v)), self.proto_version)
2209
+
2210
+ partition_key_indexes = self.partition_key_indexes
2211
+ serialize = serialize_value_prepared if self.use_prepared_statements else serialize_value_not_prepared
2212
+
2213
+ def serialize_row_single(row):
2214
+ return serialize(partition_key_indexes[0], row[partition_key_indexes[0]])
2215
+
2216
+ def serialize_row_multiple(row):
2217
+ pk_values = []
2218
+ for i in partition_key_indexes:
2219
+ val = serialize(i, row[i])
2220
+ length = len(val)
2221
+ pk_values.append(struct.pack(">H%dsB" % length, length, val, 0))
2222
+
2223
+ return b"".join(pk_values)
2224
+
2225
+ if len(partition_key_indexes) == 1:
2226
+ return serialize_row_single
2227
+ return serialize_row_multiple
2228
+
2229
+
2230
+ class TokenMap(object):
2231
+ """
2232
+ A wrapper around the metadata token map to speed things up by caching ring token *values* and
2233
+ replicas. It is very important that we use the token values, which are primitive types, rather
2234
+ than the tokens classes when calling bisect_right() in split_batches(). If we use primitive values,
2235
+ the bisect is done in compiled code whilst with token classes each comparison requires a call
2236
+ into the interpreter to perform the cmp operation defined in Python. A simple test with 1 million bisect
2237
+ operations on an array of 2048 tokens was done in 0.37 seconds with primitives and 2.25 seconds with
2238
+ token classes. This is significant for large datasets because we need to do a bisect for each single row,
2239
+ and if VNODES are used, the size of the token map can get quite large too.
2240
+ """
2241
+ def __init__(self, ks, hostname, local_dc, session):
2242
+
2243
+ self.ks = ks
2244
+ self.hostname = hostname
2245
+ self.local_dc = local_dc
2246
+ self.metadata = session.cluster.metadata
2247
+
2248
+ self._initialize_ring()
2249
+
2250
+ # Note that refresh metadata is disabled by default and we currently do not intercept it
2251
+ # If hosts are added, removed or moved during a COPY operation our token map is no longer optimal
2252
+ # However we can cope with hosts going down and up since we filter for replicas that are up when
2253
+ # making each batch
2254
+
2255
+ def _initialize_ring(self):
2256
+ token_map = self.metadata.token_map
2257
+ if token_map is None:
2258
+ self.ring = [0]
2259
+ self.replicas = [(self.metadata.get_host(self.hostname),)]
2260
+ self.pk_to_token_value = lambda pk: 0
2261
+ return
2262
+
2263
+ token_map.rebuild_keyspace(self.ks, build_if_absent=True)
2264
+ tokens_to_hosts = token_map.tokens_to_hosts_by_ks.get(self.ks, None)
2265
+ from_key = token_map.token_class.from_key
2266
+
2267
+ self.ring = [token.value for token in token_map.ring]
2268
+ self.replicas = [tuple(tokens_to_hosts[token]) for token in token_map.ring]
2269
+ self.pk_to_token_value = lambda pk: from_key(pk).value
2270
+
2271
+ @staticmethod
2272
+ def get_ring_pos(ring, val):
2273
+ idx = bisect_right(ring, val)
2274
+ return idx if idx < len(ring) else 0
2275
+
2276
+ def filter_replicas(self, hosts):
2277
+ shuffled = tuple(sorted(hosts, key=lambda k: random.random()))
2278
+ return [r for r in shuffled if r.is_up is not False and r.datacenter == self.local_dc] if hosts else ()
2279
+
2280
+
2281
+ class FastTokenAwarePolicy(DCAwareRoundRobinPolicy):
2282
+ """
2283
+ Send to any replicas attached to the query, or else fall back to DCAwareRoundRobinPolicy. Perform
2284
+ exponential back-off if too many in flight requests to all replicas are already in progress.
2285
+ """
2286
+
2287
+ def __init__(self, parent):
2288
+ DCAwareRoundRobinPolicy.__init__(self, parent.local_dc, 0)
2289
+ self.max_backoff_attempts = parent.max_backoff_attempts
2290
+ self.max_inflight_messages = parent.max_inflight_messages
2291
+
2292
+ def make_query_plan(self, working_keyspace=None, query=None):
2293
+ """
2294
+ Extend TokenAwarePolicy.make_query_plan() so that we choose the same replicas in preference
2295
+ and most importantly we avoid repeating the (slow) bisect. We also implement a backoff policy
2296
+ by sleeping an exponentially larger delay in case all connections to eligible replicas have
2297
+ too many in flight requests.
2298
+ """
2299
+ connections = ConnectionWrapper.connections
2300
+ replicas = list(query.replicas) if hasattr(query, 'replicas') else []
2301
+ replicas.extend([r for r in DCAwareRoundRobinPolicy.make_query_plan(self, working_keyspace, query)
2302
+ if r not in replicas])
2303
+
2304
+ if replicas:
2305
+ def replica_is_not_overloaded(r):
2306
+ if r.address in connections:
2307
+ conn = connections[r.address]
2308
+ return conn.in_flight < min(conn.max_request_id, self.max_inflight_messages)
2309
+ return True
2310
+
2311
+ for i in range(self.max_backoff_attempts):
2312
+ for r in filter(replica_is_not_overloaded, replicas):
2313
+ yield r
2314
+
2315
+ # the back-off starts at 10 ms (0.01) and it can go up to to 2^max_backoff_attempts,
2316
+ # which is currently 12, so 2^12 = 4096 = ~40 seconds when dividing by 0.01
2317
+ delay = randint(1, pow(2, i + 1)) * 0.01
2318
+ printdebugmsg("All replicas busy, sleeping for %d second(s)..." % (delay,))
2319
+ time.sleep(delay)
2320
+
2321
+ printdebugmsg("Replicas too busy, given up")
2322
+
2323
+
2324
+ class ConnectionWrapper(DefaultConnection):
2325
+ """
2326
+ A wrapper to the driver default connection that helps in keeping track of messages in flight.
2327
+ The newly created connection is registered into a global dictionary so that FastTokenAwarePolicy
2328
+ is able to determine if a connection has too many in flight requests.
2329
+ """
2330
+ connections = {}
2331
+
2332
+ def __init__(self, *args, **kwargs):
2333
+ DefaultConnection.__init__(self, *args, **kwargs)
2334
+ self.connections[self.host] = self
2335
+
2336
+
2337
+ class ImportProcess(ChildProcess):
2338
+
2339
+ def __init__(self, params):
2340
+ ChildProcess.__init__(self, params=params, target=self.run)
2341
+
2342
+ self.skip_columns = params['skip_columns']
2343
+ self.valid_columns = [c for c in params['valid_columns']]
2344
+ self.skip_column_indexes = [i for i, c in enumerate(self.columns) if c in self.skip_columns]
2345
+
2346
+ options = params['options']
2347
+ self.nullval = options.copy['nullval']
2348
+ self.max_attempts = options.copy['maxattempts']
2349
+ self.min_batch_size = options.copy['minbatchsize']
2350
+ self.max_batch_size = options.copy['maxbatchsize']
2351
+ self.use_prepared_statements = options.copy['preparedstatements']
2352
+ self.ttl = options.copy['ttl']
2353
+ self.max_inflight_messages = options.copy['maxinflightmessages']
2354
+ self.max_backoff_attempts = options.copy['maxbackoffattempts']
2355
+ self.request_timeout = options.copy['requesttimeout']
2356
+
2357
+ self.dialect_options = options.dialect
2358
+ self._session = None
2359
+ self.query = None
2360
+ self.conv = None
2361
+ self.make_statement = None
2362
+
2363
+ @property
2364
+ def session(self):
2365
+ if not self._session:
2366
+ cluster = Cluster(
2367
+ contact_points=(self.hostname,),
2368
+ port=self.port,
2369
+ cql_version=self.cql_version,
2370
+ protocol_version=self.protocol_version,
2371
+ auth_provider=self.auth_provider,
2372
+ load_balancing_policy=FastTokenAwarePolicy(self),
2373
+ ssl_context=ssl_settings(self.hostname, self.config_file) if self.ssl else None,
2374
+ default_retry_policy=FallthroughRetryPolicy(), # we throw on timeouts and retry in the error callback
2375
+ compression=None,
2376
+ control_connection_timeout=self.connect_timeout,
2377
+ connect_timeout=self.connect_timeout,
2378
+ idle_heartbeat_interval=0,
2379
+ connection_class=ConnectionWrapper)
2380
+
2381
+ self._session = cluster.connect(self.ks)
2382
+ self._session.default_timeout = self.request_timeout
2383
+ return self._session
2384
+
2385
+ def run(self):
2386
+ if self.coverage:
2387
+ self.start_coverage()
2388
+
2389
+ try:
2390
+ pr = profile_on() if PROFILE_ON else None
2391
+
2392
+ self.on_fork()
2393
+ self.inner_run(*self.make_params())
2394
+
2395
+ if pr:
2396
+ profile_off(pr, file_name='worker_profile_%d.txt' % (os.getpid(),))
2397
+
2398
+ except Exception as exc:
2399
+ self.report_error(exc)
2400
+
2401
+ finally:
2402
+ if self.coverage:
2403
+ self.stop_coverage()
2404
+ self.close()
2405
+
2406
+ def close(self):
2407
+ if self._session:
2408
+ self._session.cluster.shutdown()
2409
+ ChildProcess.close(self)
2410
+
2411
+ def is_counter(self, table_meta):
2412
+ return "counter" in [table_meta.columns[name].cql_type for name in self.valid_columns]
2413
+
2414
+ def make_params(self):
2415
+ metadata = self.session.cluster.metadata
2416
+ table_meta = metadata.keyspaces[self.ks].tables[self.table]
2417
+
2418
+ prepared_statement = None
2419
+ if self.is_counter(table_meta):
2420
+ query = 'UPDATE %s.%s SET %%s WHERE %%s' % (protect_name(self.ks), protect_name(self.table))
2421
+ make_statement = self.wrap_make_statement(self.make_counter_batch_statement)
2422
+ elif self.use_prepared_statements:
2423
+ query = 'INSERT INTO %s.%s (%s) VALUES (%s)' % (protect_name(self.ks),
2424
+ protect_name(self.table),
2425
+ ', '.join(protect_names(self.valid_columns),),
2426
+ ', '.join(['?' for _ in self.valid_columns]))
2427
+ if self.ttl >= 0:
2428
+ query += 'USING TTL %s' % (self.ttl,)
2429
+ query = self.session.prepare(query)
2430
+ query.consistency_level = self.consistency_level
2431
+ prepared_statement = query
2432
+ make_statement = self.wrap_make_statement(self.make_prepared_batch_statement)
2433
+ else:
2434
+ query = 'INSERT INTO %s.%s (%s) VALUES (%%s)' % (protect_name(self.ks),
2435
+ protect_name(self.table),
2436
+ ', '.join(protect_names(self.valid_columns),))
2437
+ if self.ttl >= 0:
2438
+ query += 'USING TTL %s' % (self.ttl,)
2439
+ make_statement = self.wrap_make_statement(self.make_non_prepared_batch_statement)
2440
+
2441
+ conv = ImportConversion(self, table_meta, prepared_statement)
2442
+ tm = TokenMap(self.ks, self.hostname, self.local_dc, self.session)
2443
+ return query, conv, tm, make_statement
2444
+
2445
+ def inner_run(self, query, conv, tm, make_statement):
2446
+ """
2447
+ Main run method. Note that we bind self methods that are called inside loops
2448
+ for performance reasons.
2449
+ """
2450
+ self.query = query
2451
+ self.conv = conv
2452
+ self.make_statement = make_statement
2453
+
2454
+ convert_rows = self.convert_rows
2455
+ split_into_batches = self.split_into_batches
2456
+ result_callback = self.result_callback
2457
+ err_callback = self.err_callback
2458
+ session = self.session
2459
+
2460
+ while True:
2461
+ chunk = self.inmsg.recv()
2462
+ if chunk is None:
2463
+ break
2464
+
2465
+ try:
2466
+ chunk['rows'] = convert_rows(conv, chunk)
2467
+ for replicas, batch in split_into_batches(chunk, conv, tm):
2468
+ statement = make_statement(query, conv, chunk, batch, replicas)
2469
+ if statement:
2470
+ future = session.execute_async(statement)
2471
+ future.add_callbacks(callback=result_callback, callback_args=(batch, chunk),
2472
+ errback=err_callback, errback_args=(batch, chunk, replicas))
2473
+ # do not handle else case, if a statement could not be created, the exception is handled
2474
+ # in self.wrap_make_statement and the error is reported, if a failure is injected that
2475
+ # causes the statement to be None, then we should not report the error so that we can test
2476
+ # the parent process handling missing batches from child processes
2477
+
2478
+ except Exception as exc:
2479
+ self.report_error(exc, chunk, chunk['rows'])
2480
+
2481
+ def wrap_make_statement(self, inner_make_statement):
2482
+ def make_statement(query, conv, chunk, batch, replicas):
2483
+ try:
2484
+ return inner_make_statement(query, conv, batch, replicas)
2485
+ except Exception as exc:
2486
+ print("Failed to make batch statement: {}".format(exc))
2487
+ self.report_error(exc, chunk, batch['rows'])
2488
+ return None
2489
+
2490
+ def make_statement_with_failures(query, conv, chunk, batch, replicas):
2491
+ failed_batch, apply_failure = self.maybe_inject_failures(batch)
2492
+ if apply_failure:
2493
+ return failed_batch
2494
+ return make_statement(query, conv, chunk, batch, replicas)
2495
+
2496
+ return make_statement_with_failures if self.test_failures else make_statement
2497
+
2498
+ def make_counter_batch_statement(self, query, conv, batch, replicas):
2499
+ statement = BatchStatement(batch_type=BatchType.COUNTER, consistency_level=self.consistency_level)
2500
+ statement.replicas = replicas
2501
+ statement.keyspace = self.ks
2502
+ for row in batch['rows']:
2503
+ where_clause = []
2504
+ set_clause = []
2505
+ for i, value in enumerate(row):
2506
+ if i in conv.primary_key_indexes:
2507
+ where_clause.append("{}={}".format(self.valid_columns[i], str(value)))
2508
+ else:
2509
+ set_clause.append("{}={}+{}".format(self.valid_columns[i], self.valid_columns[i], str(value)))
2510
+
2511
+ full_query_text = query % (','.join(set_clause), ' AND '.join(where_clause))
2512
+ statement.add(full_query_text)
2513
+ return statement
2514
+
2515
+ def make_prepared_batch_statement(self, query, _, batch, replicas):
2516
+ """
2517
+ Return a batch statement. This is an optimized version of:
2518
+
2519
+ statement = BatchStatement(batch_type=BatchType.UNLOGGED, consistency_level=self.consistency_level)
2520
+ for row in batch['rows']:
2521
+ statement.add(query, row)
2522
+
2523
+ We could optimize further by removing bound_statements altogether but we'd have to duplicate much
2524
+ more driver's code (BoundStatement.bind()).
2525
+ """
2526
+ statement = BatchStatement(batch_type=BatchType.UNLOGGED, consistency_level=self.consistency_level)
2527
+ statement.replicas = replicas
2528
+ statement.keyspace = self.ks
2529
+ statement._statements_and_parameters = [(True, query.query_id, query.bind(r).values) for r in batch['rows']]
2530
+ return statement
2531
+
2532
+ def make_non_prepared_batch_statement(self, query, _, batch, replicas):
2533
+ statement = BatchStatement(batch_type=BatchType.UNLOGGED, consistency_level=self.consistency_level)
2534
+ statement.replicas = replicas
2535
+ statement.keyspace = self.ks
2536
+ field_sep = ','
2537
+ statement._statements_and_parameters = [(False, query % (field_sep.join(r),), ()) for r in batch['rows']]
2538
+ return statement
2539
+
2540
+ def convert_rows(self, conv, chunk):
2541
+ """
2542
+ Return converted rows and report any errors during conversion.
2543
+ """
2544
+ def filter_row_values(row):
2545
+ return [v for i, v in enumerate(row) if i not in self.skip_column_indexes]
2546
+
2547
+ if self.skip_column_indexes:
2548
+ rows = [filter_row_values(r) for r in list(csv.reader(chunk['rows'], **self.dialect_options))]
2549
+ else:
2550
+ rows = list(csv.reader(chunk['rows'], **self.dialect_options))
2551
+
2552
+ errors = defaultdict(list)
2553
+
2554
+ def convert_row(r):
2555
+ try:
2556
+ return conv.convert_row(r)
2557
+ except Exception as err:
2558
+ errors[err.message if hasattr(err, 'message') else str(err)].append(r)
2559
+ return None
2560
+
2561
+ converted_rows = [_f for _f in [convert_row(r) for r in rows] if _f]
2562
+
2563
+ if errors:
2564
+ for msg, rows in errors.items():
2565
+ self.report_error(ParseError(msg), chunk, rows)
2566
+ return converted_rows
2567
+
2568
+ def maybe_inject_failures(self, batch):
2569
+ """
2570
+ Examine self.test_failures and see if the batch is a batch
2571
+ supposed to cause a failure (failing_batch), or to terminate the worker process
2572
+ (exit_batch), or not to be sent (unsent_batch).
2573
+
2574
+ @return any statement that will cause a failure or None if the statement should not be sent
2575
+ plus a boolean indicating if a failure should be applied at all
2576
+ """
2577
+ if 'failing_batch' in self.test_failures:
2578
+ failing_batch = self.test_failures['failing_batch']
2579
+ if failing_batch['id'] == batch['id']:
2580
+ if batch['attempts'] < failing_batch['failures']:
2581
+ statement = SimpleStatement("INSERT INTO badtable (a, b) VALUES (1, 2)",
2582
+ consistency_level=self.consistency_level)
2583
+ return statement, True # use this statement, which will cause an error
2584
+
2585
+ if 'exit_batch' in self.test_failures:
2586
+ exit_batch = self.test_failures['exit_batch']
2587
+ if exit_batch['id'] == batch['id']:
2588
+ sys.exit(1)
2589
+
2590
+ if 'unsent_batch' in self.test_failures:
2591
+ unsent_batch = self.test_failures['unsent_batch']
2592
+ if unsent_batch['id'] == batch['id']:
2593
+ return None, True # do not send this batch, which will cause missing acks in the parent process
2594
+
2595
+ return None, False # carry on as normal, do not apply any failures
2596
+
2597
+ @staticmethod
2598
+ def make_batch(batch_id, rows, attempts=1):
2599
+ return {'id': batch_id, 'rows': rows, 'attempts': attempts}
2600
+
2601
+ def split_into_batches(self, chunk, conv, tm):
2602
+ """
2603
+ Batch rows by ring position or replica.
2604
+ If there are at least min_batch_size rows for a ring position then split these rows into
2605
+ groups of max_batch_size and send a batch for each group, using all replicas for this ring position.
2606
+ Otherwise, we are forced to batch by replica, and here unfortunately we can only choose one replica to
2607
+ guarantee common replicas across partition keys. We are typically able
2608
+ to batch by ring position for small clusters or when VNODES are not used. For large clusters with VNODES
2609
+ it may not be possible, in this case it helps to increase the CHUNK SIZE but up to a limit, otherwise
2610
+ we may choke the cluster.
2611
+ """
2612
+
2613
+ rows_by_ring_pos = defaultdict(list)
2614
+ errors = defaultdict(list)
2615
+
2616
+ min_batch_size = self.min_batch_size
2617
+ max_batch_size = self.max_batch_size
2618
+ ring = tm.ring
2619
+
2620
+ get_row_partition_key_values = conv.get_row_partition_key_values_fcn()
2621
+ pk_to_token_value = tm.pk_to_token_value
2622
+ get_ring_pos = tm.get_ring_pos
2623
+ make_batch = self.make_batch
2624
+
2625
+ for row in chunk['rows']:
2626
+ try:
2627
+ pk = get_row_partition_key_values(row)
2628
+ rows_by_ring_pos[get_ring_pos(ring, pk_to_token_value(pk))].append(row)
2629
+ except Exception as e:
2630
+ errors[e.message if hasattr(e, 'message') else str(e)].append(row)
2631
+
2632
+ if errors:
2633
+ for msg, rows in errors.items():
2634
+ self.report_error(ParseError(msg), chunk, rows)
2635
+
2636
+ replicas = tm.replicas
2637
+ filter_replicas = tm.filter_replicas
2638
+ rows_by_replica = defaultdict(list)
2639
+ for ring_pos, rows in rows_by_ring_pos.items():
2640
+ if len(rows) > min_batch_size:
2641
+ for i in range(0, len(rows), max_batch_size):
2642
+ yield filter_replicas(replicas[ring_pos]), make_batch(chunk['id'], rows[i:i + max_batch_size])
2643
+ else:
2644
+ # select only the first valid replica to guarantee more overlap or none at all
2645
+ # TODO: revisit tuple wrapper
2646
+ rows_by_replica[tuple(filter_replicas(replicas[ring_pos])[:1])].extend(rows)
2647
+
2648
+ # Now send the batches by replica
2649
+ for replicas, rows in rows_by_replica.items():
2650
+ for i in range(0, len(rows), max_batch_size):
2651
+ yield replicas, make_batch(chunk['id'], rows[i:i + max_batch_size])
2652
+
2653
+ def result_callback(self, _, batch, chunk):
2654
+ self.update_chunk(batch['rows'], chunk)
2655
+
2656
+ def err_callback(self, response, batch, chunk, replicas):
2657
+ if isinstance(response, OperationTimedOut) and chunk['imported'] == chunk['num_rows_sent']:
2658
+ return # occasionally the driver sends false timeouts for rows already processed (PYTHON-652)
2659
+ err_is_final = batch['attempts'] >= self.max_attempts
2660
+ self.report_error(response, chunk, batch['rows'], batch['attempts'], err_is_final)
2661
+ if not err_is_final:
2662
+ batch['attempts'] += 1
2663
+ statement = self.make_statement(self.query, self.conv, chunk, batch, replicas)
2664
+ future = self.session.execute_async(statement)
2665
+ future.add_callbacks(callback=self.result_callback, callback_args=(batch, chunk),
2666
+ errback=self.err_callback, errback_args=(batch, chunk, replicas))
2667
+
2668
+ # TODO: review why this is defined twice
2669
+ def report_error(self, err, chunk=None, rows=None, attempts=1, final=True):
2670
+ if self.debug and sys.exc_info()[1] == err:
2671
+ traceback.print_exc()
2672
+ err_msg = err.message if hasattr(err, 'message') else str(err)
2673
+ self.outmsg.send(ImportTaskError(err.__class__.__name__, err_msg, rows, attempts, final))
2674
+ if final and chunk is not None:
2675
+ self.update_chunk(rows, chunk)
2676
+
2677
+ def update_chunk(self, rows, chunk):
2678
+ chunk['imported'] += len(rows)
2679
+ if chunk['imported'] == chunk['num_rows_sent']:
2680
+ self.outmsg.send(ImportProcessResult(chunk['num_rows_sent']))
2681
+
2682
+
2683
+ class RateMeter(object):
2684
+
2685
+ def __init__(self, log_fcn, update_interval=0.25, log_file=''):
2686
+ self.log_fcn = log_fcn # the function for logging, may be None to disable logging
2687
+ self.update_interval = update_interval # how often we update in seconds
2688
+ self.log_file = log_file # an optional file where to log statistics in addition to stdout
2689
+ self.start_time = time.time() # the start time
2690
+ self.last_checkpoint_time = self.start_time # last time we logged
2691
+ self.current_rate = 0.0 # rows per second
2692
+ self.current_record = 0 # number of records since we last updated
2693
+ self.total_records = 0 # total number of records
2694
+
2695
+ if os.path.isfile(self.log_file):
2696
+ os.unlink(self.log_file)
2697
+
2698
+ def increment(self, n=1):
2699
+ self.current_record += n
2700
+ self.maybe_update()
2701
+
2702
+ def maybe_update(self, sleep=False):
2703
+ if self.current_record == 0:
2704
+ return
2705
+
2706
+ new_checkpoint_time = time.time()
2707
+ time_difference = new_checkpoint_time - self.last_checkpoint_time
2708
+ if time_difference >= self.update_interval:
2709
+ self.update(new_checkpoint_time)
2710
+ self.log_message()
2711
+ elif sleep:
2712
+ remaining_time = time_difference - self.update_interval
2713
+ if remaining_time > 0.000001:
2714
+ time.sleep(remaining_time)
2715
+
2716
+ def update(self, new_checkpoint_time):
2717
+ time_difference = new_checkpoint_time - self.last_checkpoint_time
2718
+ if time_difference >= 1e-09:
2719
+ self.current_rate = self.get_new_rate(self.current_record / time_difference)
2720
+
2721
+ self.last_checkpoint_time = new_checkpoint_time
2722
+ self.total_records += self.current_record
2723
+ self.current_record = 0
2724
+
2725
+ def get_new_rate(self, new_rate):
2726
+ """
2727
+ return the rate of the last period: this is the new rate but
2728
+ averaged with the last rate to smooth a bit
2729
+ """
2730
+ if self.current_rate == 0.0:
2731
+ return new_rate
2732
+ else:
2733
+ return (self.current_rate + new_rate) / 2.0
2734
+
2735
+ def get_avg_rate(self):
2736
+ """
2737
+ return the average rate since we started measuring
2738
+ """
2739
+ time_difference = time.time() - self.start_time
2740
+ return self.total_records / time_difference if time_difference >= 1e-09 else 0
2741
+
2742
+ def log_message(self):
2743
+ if not self.log_fcn:
2744
+ return
2745
+
2746
+ output = 'Processed: %d rows; Rate: %7.0f rows/s; Avg. rate: %7.0f rows/s\r' % \
2747
+ (self.total_records, self.current_rate, self.get_avg_rate())
2748
+ self.log_fcn(output, eol='\r')
2749
+ if self.log_file:
2750
+ with open(self.log_file, "a") as f:
2751
+ f.write(output + '\n')
2752
+
2753
+ def get_total_records(self):
2754
+ self.update(time.time())
2755
+ self.log_message()
2756
+ return self.total_records