-
Notifications
You must be signed in to change notification settings - Fork 17
/
voltdbclient.py
1653 lines (1415 loc) · 58.1 KB
/
voltdbclient.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# This file is part of VoltDB.
# Copyright (C) 2008-2021 VoltDB Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
import sys
if sys.hexversion < 0x03060000:
raise Exception("Python version 3.6 or greater is required.")
import array
import socket
import base64, textwrap
import struct
import datetime
import decimal
import hashlib
import re
import math
import os
import stat
try:
import ssl
ssl_available = True
except ImportError as e:
ssl_available = False
ssl_exception = e
try:
import gssapi
kerberos_available = True
except ImportError as e:
kerberos_available = False
kerberos_exception = e
try:
import jks
pyjks_available = True
except ImportError as e:
pyjks_available = False
pyjks_exception = e
logger = None
def use_logging():
import logging
global logger
logger = logging.getLogger()
def error(text):
if logger:
logger.error(text)
else:
print(text)
decimal.getcontext().prec = 38
def int16toBytes(val):
return [val >> 8 & 0xff,
val >> 0 & 0xff]
def int32toBytes(val):
return [val >> 24 & 0xff,
val >> 16 & 0xff,
val >> 8 & 0xff,
val >> 0 & 0xff]
def int64toBytes(val):
return [val >> 56 & 0xff,
val >> 48 & 0xff,
val >> 40 & 0xff,
val >> 32 & 0xff,
val >> 24 & 0xff,
val >> 16 & 0xff,
val >> 8 & 0xff,
val >> 0 & 0xff]
def isNaN(d):
# Per IEEE 754, 'NaN == NaN' must be false,
# so we cannot check for simple equality
if d == None:
return False
else: # routine misnamed, returns true for 'Inf' too
return math.isnan(d) or math.isinf(d)
class ReadBuffer(object):
"""
Read buffer management class.
"""
def __init__(self):
self.clear()
def clear(self):
self._buf = bytes()
self._off = 0
def buffer_length(self):
return len(self._buf)
def remaining(self):
return (len(self._buf) - self._off)
def get_buffer(self):
return self._buf
def append(self, content):
self._buf += content
def shift(self, size):
self._off += size
def read(self, size):
return self._buf[self._off:self._off+size]
def unpack(self, format, size):
try:
values = struct.unpack_from(format, self._buf, self._off)
except struct.error as e:
error('Exception unpacking %d bytes using format "%s": %s' % (size, format, str(e)))
raise e
self.shift(size)
return values
class FastSerializer:
"Primitive type de/serialization in VoltDB formats"
LITTLE_ENDIAN = '<'
BIG_ENDIAN = '>'
ARRAY = -99
# VoltType enumerations
VOLTTYPE_NULL = 1
VOLTTYPE_TINYINT = 3 # int8
VOLTTYPE_SMALLINT = 4 # int16
VOLTTYPE_INTEGER = 5 # int32
VOLTTYPE_BIGINT = 6 # int64
VOLTTYPE_FLOAT = 8 # float64
VOLTTYPE_STRING = 9
VOLTTYPE_TIMESTAMP = 11 # 8 byte long
VOLTTYPE_DECIMAL = 22 # fixed precision decimal
VOLTTYPE_MONEY = 20 # 8 byte long
VOLTTYPE_VOLTTABLE = 21
VOLTTYPE_VARBINARY = 25
VOLTTYPE_GEOGRAPHY_POINT = 26
VOLTTYPE_GEOGRAPHY = 27
# SQL NULL indicator for object type serializations (string, decimal)
NULL_STRING_INDICATOR = -1
NULL_DECIMAL_INDICATOR = -170141183460469231731687303715884105728
NULL_TINYINT_INDICATOR = -128
NULL_SMALLINT_INDICATOR = -32768
NULL_INTEGER_INDICATOR = -2147483648
NULL_BIGINT_INDICATOR = -9223372036854775808
NULL_FLOAT_INDICATOR = -1.7E308
# default decimal scale
DEFAULT_DECIMAL_SCALE = 12
# protocol constants
AUTH_HANDSHAKE_VERSION = 2
AUTH_SERVICE_NAME = 4
AUTH_HANDSHAKE = 5
# procedure call result codes
PROC_OK = 0
# there are assumptions here about datatype sizes which are
# machine dependent. the program exits with an error message
# if these assumptions are not true. it is further assumed
# that host order is little endian. See isNaN().
# default ssl configuration
if (ssl_available):
DEFAULT_SSL_CONFIG = {
'keyfile': None,
'certfile': None,
'cert_reqs': ssl.CERT_NONE,
'ca_certs': None,
'do_handshake_on_connect': True
}
else:
DEFAULT_SSL_CONFIG = {}
def __init__(self, host = None, port = 21212, usessl = False,
username = "", password = "",
kerberos = False,
dump_file_path = None,
connect_timeout = 8,
procedure_timeout = None,
default_timeout = None,
ssl_config_file = None,
ssl_config = DEFAULT_SSL_CONFIG):
"""
:param host: host string for connection or None
:param port: port for connection or None
:param usessl: switch for use ssl or not
:param username: authentication user name for connection or None
:param password: authentication password for connection or None
:param kerberos: use Kerberos authentication
:param dump_file_path: path to optional dump file or None
:param connect_timeout: timeout (secs) or None for authentication (default=8)
:param procedure_timeout: timeout (secs) or None for procedure calls (default=None)
:param default_timeout: default timeout (secs) or None for all other operations (default=None)
:param ssl_config_file: config file that defines java keystore and truststore files
"""
# connect a socket to host, port and get a file object
self.wbuf = array.array('B')
self.host = host
self.port = port
self.usessl = usessl
if kerberos is None:
self.usekerberos = False
else:
self.usekerberos = kerberos
self.kerberosprinciple = None
self.ssl_config = ssl_config
self.ssl_config_file = ssl_config_file
if not dump_file_path is None:
self.dump_file = open(dump_file_path, "wb")
else:
self.dump_file = None
self.default_timeout = default_timeout
self.procedure_timeout = procedure_timeout
self.socket = None
if self.host != None and self.port != None:
ai = socket.getaddrinfo(host, port, 0, socket.SOCK_STREAM, socket.IPPROTO_TCP, socket.AI_ADDRCONFIG)[0]
# ai = (family, socktype, proto, canonname, sockaddr)
ss = socket.socket(ai[0], ai[1], ai[2])
if self.usessl:
if ssl_available:
self.socket = self.__wrap_socket(ss)
else:
error("ERROR: To use SSL functionality please install the Python ssl module.")
raise ssl_exception
else:
self.socket = ss
self.socket.setblocking(1)
self.socket.setsockopt(socket.SOL_TCP, socket.TCP_NODELAY, 1)
try:
self.socket.connect(ai[4])
except Exception:
error("ERROR: Failed to connect to %s port %s" % (ai[4][0], ai[4][1]))
raise
#if self.usessl:
# print 'Cipher suite: ' + str(self.socket.cipher())
# input can be big or little endian
self.inputBOM = self.BIG_ENDIAN # byte order if input stream
self.localBOM = self.LITTLE_ENDIAN # byte order of host
# Type to reader/writer mappings
self.READER = {self.VOLTTYPE_NULL: self.readNull,
self.VOLTTYPE_TINYINT: self.readByte,
self.VOLTTYPE_SMALLINT: self.readInt16,
self.VOLTTYPE_INTEGER: self.readInt32,
self.VOLTTYPE_BIGINT: self.readInt64,
self.VOLTTYPE_FLOAT: self.readFloat64,
self.VOLTTYPE_STRING: self.readString,
self.VOLTTYPE_VARBINARY: self.readVarbinary,
self.VOLTTYPE_TIMESTAMP: self.readDate,
self.VOLTTYPE_DECIMAL: self.readDecimal,
self.VOLTTYPE_GEOGRAPHY_POINT: self.readGeographyPoint,
self.VOLTTYPE_GEOGRAPHY: self.readGeography}
self.WRITER = {self.VOLTTYPE_NULL: self.writeNull,
self.VOLTTYPE_TINYINT: self.writeByte,
self.VOLTTYPE_SMALLINT: self.writeInt16,
self.VOLTTYPE_INTEGER: self.writeInt32,
self.VOLTTYPE_BIGINT: self.writeInt64,
self.VOLTTYPE_FLOAT: self.writeFloat64,
self.VOLTTYPE_STRING: self.writeString,
self.VOLTTYPE_VARBINARY: self.writeVarbinary,
self.VOLTTYPE_TIMESTAMP: self.writeDate,
self.VOLTTYPE_DECIMAL: self.writeDecimal,
self.VOLTTYPE_GEOGRAPHY_POINT: self.writeGeographyPoint,
self.VOLTTYPE_GEOGRAPHY: self.writeGeography}
self.ARRAY_READER = {self.VOLTTYPE_TINYINT: self.readByteArray,
self.VOLTTYPE_SMALLINT: self.readInt16Array,
self.VOLTTYPE_INTEGER: self.readInt32Array,
self.VOLTTYPE_BIGINT: self.readInt64Array,
self.VOLTTYPE_FLOAT: self.readFloat64Array,
self.VOLTTYPE_STRING: self.readStringArray,
self.VOLTTYPE_TIMESTAMP: self.readDateArray,
self.VOLTTYPE_DECIMAL: self.readDecimalArray,
self.VOLTTYPE_GEOGRAPHY_POINT: self.readGeographyPointArray,
self.VOLTTYPE_GEOGRAPHY: self.readGeographyArray}
self.__compileStructs()
# Check if the value of a given type is NULL
self.NULL_DECIMAL_INDICATOR = \
self.__intToBytes(self.__class__.NULL_DECIMAL_INDICATOR, 0)
self.NullCheck = {self.VOLTTYPE_NULL:
lambda x: None,
self.VOLTTYPE_TINYINT:
lambda x: None if x == self.__class__.NULL_TINYINT_INDICATOR else x,
self.VOLTTYPE_SMALLINT:
lambda x: None if x == self.__class__.NULL_SMALLINT_INDICATOR else x,
self.VOLTTYPE_INTEGER:
lambda x: None if x == self.__class__.NULL_INTEGER_INDICATOR else x,
self.VOLTTYPE_BIGINT:
lambda x: None if x == self.__class__.NULL_BIGINT_INDICATOR else x,
self.VOLTTYPE_FLOAT:
lambda x: None if abs(x - self.__class__.NULL_FLOAT_INDICATOR) < 1e307 else x,
self.VOLTTYPE_STRING:
lambda x: None if x == self.__class__.NULL_STRING_INDICATOR else x,
self.VOLTTYPE_VARBINARY:
lambda x: None if x == self.__class__.NULL_STRING_INDICATOR else x,
self.VOLTTYPE_DECIMAL:
lambda x: None if x == self.NULL_DECIMAL_INDICATOR else x}
self.read_buffer = ReadBuffer()
if self.usekerberos:
if not kerberos_available:
raise RuntimeError("Requested Kerberos authentication but unable to import the GSSAPI package.")
if not self.has_ticket():
raise RuntimeError("Requested Kerberos authentication but no valid ticket found. Authenticate with Kerberos first.")
assert not self.socket is None
self.socket.settimeout(connect_timeout)
self.authenticate(str(self.kerberosprinciple), "")
elif not username is None and not password is None and not host is None:
assert not self.socket is None
self.socket.settimeout(connect_timeout)
self.authenticate(username, password)
if self.socket:
self.socket.settimeout(self.default_timeout)
# Front end to SSL socket support.
#
# The SSL config file contains a sequence of key=value lines which
# are used to provide the arguments to the SSL wrap_socket call:
# Key Value Provides arguments
# ------------------ ------------------------ ------------------
# keystore path to JKS keystore keyfile, certfile
# keystorepassword password for keystore --
# truststore path to JKS truststore ca_certs, cert_reqs
# truststorepassword password for truststore --
# cacerts path to PEM cert chain ca_certs, cert_reqs
# ssl_version ignored --
#
# Thus keystore identifies the client (rarely needed), whereas truststore
# and cacerts identify the server. If truststore and cacerts are both
# specified, cacerts takes precedence.
#
# An empty or missing ssl_config_file results in no certificate checks.
def __wrap_socket(self, ss):
parsed_config = {}
jks_config = {}
if self.ssl_config_file:
with open(os.path.expandvars(os.path.expanduser(self.ssl_config_file)), 'r') as f:
for line in f:
try:
l = line.strip()
if l:
k, v = l.split('=', 1)
parsed_config[k.lower()] = v
except:
raise ValueError('Malformed line in SSL config: ' + line)
if ('keystore' in parsed_config and parsed_config['keystore']) or \
('truststore' in parsed_config and parsed_config['truststore']):
self.__convert_jks_files(ss, parsed_config)
if 'cacerts' in parsed_config and parsed_config['cacerts']:
self.ssl_config['ca_certs'] = parsed_config['cacerts']
self.ssl_config['cert_reqs'] = ssl.CERT_REQUIRED
protocol = ssl.PROTOCOL_TLS
return ssl.wrap_socket(ss,
keyfile=self.ssl_config['keyfile'],
certfile=self.ssl_config['certfile'],
server_side=False,
cert_reqs=self.ssl_config['cert_reqs'],
ssl_version=protocol,
ca_certs=self.ssl_config['ca_certs'])
def __convert_jks_files(self, ss, jks_config):
if not pyjks_available:
error("To use Java KeyStore please install the 'pyjks' module")
raise pyjks_exception
def write_pem(der_bytes, type, f):
f.write("-----BEGIN %s-----\n" % type)
f.write("\r\n".join(textwrap.wrap(base64.b64encode(der_bytes).decode('ascii'), 64)))
f.write("\n-----END %s-----\n" % type)
# extract key and certs
use_key_cert = False
if 'keystore' in jks_config and jks_config['keystore'] and \
'keystorepassword' in jks_config and jks_config['keystorepassword']:
ks = jks.KeyStore.load(jks_config['keystore'], jks_config['keystorepassword'])
keyfile = self.__create(jks_config['keystore'] + '.key.pem')
certfile = self.__create(jks_config['keystore'] + '.cert.pem')
for alias, pk in list(ks.private_keys.items()):
# print("Private key: %s" % pk.alias)
if pk.algorithm_oid == jks.util.RSA_ENCRYPTION_OID:
write_pem(pk.pkey, "RSA PRIVATE KEY", keyfile)
else:
write_pem(pk.pkey_pkcs8, "PRIVATE KEY", keyfile)
for c in pk.cert_chain:
write_pem(c[1], "CERTIFICATE", certfile)
use_key_cert = True
keyfile.close()
certfile.close()
if use_key_cert:
self.ssl_config['keyfile'] = keyfile.name
self.ssl_config['certfile'] = certfile.name
# extract ca certs
use_ca_cert = False
if 'truststore' in jks_config and jks_config['truststore'] and \
'truststorepassword' in jks_config and jks_config['truststorepassword']:
ts = jks.KeyStore.load(jks_config['truststore'], jks_config['truststorepassword'])
cafile = self.__create(jks_config['truststore'] + '.ca.cert.pem')
for alias, c in list(ts.certs.items()):
# print("Certificate: %s" % c.alias)
write_pem(c.cert, "CERTIFICATE", cafile)
use_ca_cert = True
cafile.close()
if use_ca_cert:
self.ssl_config['ca_certs'] = cafile.name
self.ssl_config['cert_reqs'] = ssl.CERT_REQUIRED
def __create(self, filename):
f = open(filename, 'w')
os.chmod(filename, stat.S_IRUSR|stat.S_IWUSR)
return f
def __compileStructs(self):
# Compiled structs for each type
self.byteType = lambda length : '%c%db' % (self.inputBOM, length)
self.ubyteType = lambda length : '%c%dB' % (self.inputBOM, length)
self.int16Type = lambda length : '%c%dh' % (self.inputBOM, length)
self.int32Type = lambda length : '%c%di' % (self.inputBOM, length)
self.int64Type = lambda length : '%c%dq' % (self.inputBOM, length)
self.uint64Type = lambda length : '%c%dQ' % (self.inputBOM, length)
self.float64Type = lambda length : '%c%dd' % (self.inputBOM, length)
self.stringType = lambda length : '%c%ds' % (self.inputBOM, length)
self.varbinaryType = lambda length : '%c%ds' % (self.inputBOM, length)
def close(self):
if self.dump_file != None:
self.dump_file.close()
self.socket.close()
def authenticate(self, username, password):
# Requires sending a length preceded username and password even if
# authentication is turned off.
#protocol version
self.writeByte(1)
#sha256
self.writeByte(1)
# service requested
if (self.usekerberos):
self.writeString("kerberos")
else:
self.writeString("database")
if username:
# utf8 encode supplied username or kerberos principal name
self.writeString(username)
else:
# no username, just output length of 0
self.writeString("")
# password supplied, sha-256 hash it
m = hashlib.sha256()
encoded_password = password.encode("utf-8")
m.update(encoded_password)
pwHash = bytearray(m.digest())
self.wbuf.extend(pwHash)
self.prependLength()
self.flush()
# A length, version number, and status code is returned
try:
self.bufferForRead()
except IOError as e:
error("ERROR: Connection failed. Please check that the host, port, and ssl settings are correct.")
raise e
except socket.timeout:
raise RuntimeError("Authentication timed out after %d seconds."
% self.socket.gettimeout())
version = self.readByte()
status = self.readByte()
if (version == self.AUTH_HANDSHAKE_VERSION):
#service name supplied by VoltDB Server
service_string = self.readString().encode('ascii','ignore')
try:
service_name = gssapi.Name(service_string, name_type=gssapi.NameType.kerberos_principal)
ctx = gssapi.SecurityContext(name=service_name, mech=gssapi.MechType.kerberos)
in_token = None
out_token = ctx.step(in_token)
while not ctx.complete:
self.writeByte(self.AUTH_HANDSHAKE_VERSION)
self.writeByte(self.AUTH_HANDSHAKE)
self.wbuf.extend(out_token)
self.prependLength()
self.flush()
try:
self.bufferForRead()
except IOError as e:
error("ERROR: Connection failed. Please check that the host, port, and ssl settings are correct.")
raise e
except socket.timeout:
raise RuntimeError("Authentication timed out after %d seconds."
% self.socket.gettimeout())
version = self.readByte()
status = self.readByte()
if version != self.AUTH_HANDSHAKE_VERSION or status != self.AUTH_HANDSHAKE:
raise RuntimeError("Authentication failed.")
in_token = self.readVarbinaryContent(self.read_buffer.remaining()).tobytes()
out_token = ctx.step(in_token)
try:
self.bufferForRead()
except IOError as e:
error("ERROR: Connection failed. Please check that the host, port, and ssl settings are correct.")
raise e
except socket.timeout:
raise RuntimeError("Authentication timed out after %d seconds."
% self.socket.gettimeout())
version = self.readByte()
status = self.readByte()
except Exception as e:
raise RuntimeError("Authentication failed.")
if status != 0:
raise RuntimeError("Authentication failed.")
self.readInt32()
self.readInt64()
self.readInt64()
self.readInt32()
for x in range(self.readInt32()):
self.readByte()
def has_ticket(self):
'''
Checks to see if the user has a valid ticket.
'''
default_cred = None
retval = False
try:
default_cred = gssapi.creds.Credentials(usage='initiate')
if default_cred.lifetime > 0:
self.kerberosprinciple = str(default_cred.name)
retval = True
else:
error("ERROR: Kerberos principal found but login expired.")
except gssapi.raw.misc.GSSError as e:
error("ERROR: unable to find default principal from Kerberos cache.")
return retval
def setInputByteOrder(self, bom):
# assuming bom is high bit set?
if bom == 1:
self.inputBOM = self.LITTLE_ENDIAN
else:
self.inputBOM = self.BIG_ENDIAN
# recompile the structs
self.__compileStructs()
def prependLength(self):
# write 32 bit array length at offset 0, NOT including the
# size of this length preceding value. This value is written
# in the network order.
ttllen = self.wbuf.buffer_info()[1] * self.wbuf.itemsize
lenBytes = int32toBytes(ttllen)
#lenBytes = struct.pack(self.inputBOM + 'i', ttllen)
[self.wbuf.insert(0, x) for x in lenBytes[::-1]]
def size(self):
"""Returns the size of the write buffer.
"""
return (self.wbuf.buffer_info()[1] * self.wbuf.itemsize)
def flush(self):
if self.socket is None:
error("ERROR: not connected to server.")
exit(-1)
if self.dump_file != None:
self.dump_file.write(self.wbuf)
self.dump_file.write(b"\n")
self.socket.sendall(self.wbuf.tobytes())
self.wbuf = array.array('B')
def bufferForRead(self):
if self.socket is None:
error("ERROR: not connected to server.")
exit(-1)
# fully buffer a new length preceded message from socket
# read the length. the read until the buffer is completed.
responseprefix = bytes()
while (len(responseprefix) < 4):
responseprefix += self.socket.recv(4 - len(responseprefix))
if responseprefix == b'':
raise IOError("Connection broken")
if self.dump_file != None:
self.dump_file.write(responseprefix)
responseLength = struct.unpack(self.int32Type(1), responseprefix)[0]
self.read_buffer.clear()
remaining = responseLength
while remaining > 0:
message = self.socket.recv(remaining)
self.read_buffer.append(message)
remaining = responseLength - self.read_buffer.buffer_length()
if not self.dump_file is None:
self.dump_file.write(self.read_buffer.get_buffer())
self.dump_file.write(b"\n")
def read(self, type):
if type not in self.READER:
error("ERROR: can't read wire type(%d) yet." % (type))
exit(-2)
return self.READER[type]()
def write(self, type, value):
if type not in self.WRITER:
error("ERROR: can't write wire type(%d) yet." % (type))
exit(-2)
return self.WRITER[type](value)
def readWireType(self):
type = self.readByte()
return self.read(type)
def writeWireType(self, type, value):
if type not in self.WRITER:
error("ERROR: can't write wire type(%d) yet." % (type))
exit(-2)
self.writeByte(type)
return self.write(type, value)
def getRawBytes(self):
return self.wbuf
def writeRawBytes(self, value):
"""Appends the given raw bytes to the end of the write buffer.
"""
self.wbuf.extend(value)
def __str__(self):
return repr(self.wbuf)
def readArray(self, type):
if type not in self.ARRAY_READER:
error("ERROR: can't read wire type(%d) yet." % (type))
exit(-2)
return self.ARRAY_READER[type]()
def readNull(self):
return None
def writeNull(self, value):
return
def writeArray(self, type, array):
if (not array) or (len(array) == 0) or (not type):
return
if type not in self.ARRAY_READER:
error("ERROR: Unsupported date type (%d)." % (type))
exit(-2)
# serialize arrays of bytes as larger values to support
# strings and varbinary input
if type != FastSerializer.VOLTTYPE_TINYINT:
self.writeInt16(len(array))
else:
self.writeInt32(len(array))
for i in array:
self.WRITER[type](i)
def writeWireTypeArray(self, type, array):
if type not in self.ARRAY_READER:
error("ERROR: can't write wire type(%d) yet." % (type))
exit(-2)
self.writeByte(type)
self.writeArray(type, array)
# byte
def readByteArrayContent(self, cnt):
offset = cnt * struct.calcsize('b')
return self.read_buffer.unpack(self.byteType(cnt), offset)
def readByteArray(self):
length = self.readInt32()
val = self.readByteArrayContent(length)
val = list(map(self.NullCheck[self.VOLTTYPE_TINYINT], val))
return val
def readByte(self):
val = self.readByteArrayContent(1)[0]
return self.NullCheck[self.VOLTTYPE_TINYINT](val)
def readByteRaw(self):
val = self.readByteArrayContent(1)[0]
if val > 127:
return val - 256
else:
return val
def writeByte(self, value):
if value == None:
value = self.__class__.NULL_TINYINT_INDICATOR
if value < 0:
value += 256
self.wbuf.append(value)
# int16
def readInt16ArrayContent(self, cnt):
offset = cnt * struct.calcsize('h')
return self.read_buffer.unpack(self.int16Type(cnt), offset)
def readInt16Array(self):
length = self.readInt16()
val = self.readInt16ArrayContent(length)
val = list(map(self.NullCheck[self.VOLTTYPE_SMALLINT], val))
return val
def readInt16(self):
val = self.readInt16ArrayContent(1)[0]
return self.NullCheck[self.VOLTTYPE_SMALLINT](val)
def writeInt16(self, value):
if value == None:
val = self.__class__.NULL_SMALLINT_INDICATOR
else:
val = value
self.wbuf.extend(int16toBytes(val))
# int32
def readInt32ArrayContent(self, cnt):
offset = cnt * struct.calcsize('i')
return self.read_buffer.unpack(self.int32Type(cnt), offset)
def readInt32Array(self):
length = self.readInt16()
val = self.readInt32ArrayContent(length)
val = list(map(self.NullCheck[self.VOLTTYPE_INTEGER], val))
return val
def readInt32(self):
val = self.readInt32ArrayContent(1)[0]
return self.NullCheck[self.VOLTTYPE_INTEGER](val)
def writeInt32(self, value):
if value == None:
val = self.__class__.NULL_INTEGER_INDICATOR
else:
val = value
self.wbuf.extend(int32toBytes(val))
# int64
def readInt64ArrayContent(self, cnt):
offset = cnt * struct.calcsize('q')
return self.read_buffer.unpack(self.int64Type(cnt), offset)
def readInt64Array(self):
length = self.readInt16()
val = self.readInt64ArrayContent(length)
val = list(map(self.NullCheck[self.VOLTTYPE_BIGINT], val))
return val
def readInt64(self):
val = self.readInt64ArrayContent(1)[0]
return self.NullCheck[self.VOLTTYPE_BIGINT](val)
def writeInt64(self, value):
if value == None:
val = self.__class__.NULL_BIGINT_INDICATOR
else:
val = value
self.wbuf.extend(int64toBytes(val))
# float64
def readFloat64ArrayContent(self, cnt):
offset = cnt * struct.calcsize('d')
return self.read_buffer.unpack(self.float64Type(cnt), offset)
def readFloat64Array(self):
length = self.readInt16()
val = self.readFloat64ArrayContent(length)
val = list(map(self.NullCheck[self.VOLTTYPE_FLOAT], val))
return val
def readFloat64(self):
val = self.readFloat64ArrayContent(1)[0]
return self.NullCheck[self.VOLTTYPE_FLOAT](val)
def writeFloat64(self, value):
if value == None:
val = self.__class__.NULL_FLOAT_INDICATOR
else:
val = float(value)
ba = bytearray(struct.pack(self.float64Type(1), val))
self.wbuf.extend(ba)
# string
def readStringContent(self, cnt):
if cnt == 0:
return ""
offset = cnt * struct.calcsize('c')
val = self.read_buffer.unpack(self.stringType(cnt), offset)
return val[0].decode("utf-8")
def readString(self):
# length preceeded (4 byte value) string
length = self.readInt32()
if self.NullCheck[self.VOLTTYPE_STRING](length) == None:
return None
return self.readStringContent(length)
def readStringArray(self):
retval = []
cnt = self.readInt16()
for i in range(cnt):
retval.append(self.readString())
return tuple(retval)
def writeString(self, value):
if value is None:
self.writeInt32(self.NULL_STRING_INDICATOR)
return
encoded_value = value.encode("utf-8")
ba = bytearray(encoded_value)
self.writeInt32(len(encoded_value))
self.wbuf.extend(ba)
# varbinary
def readVarbinaryContent(self, cnt):
if cnt == 0:
return array.array('B', [])
offset = cnt * struct.calcsize('c')
val = self.read_buffer.unpack(self.varbinaryType(cnt), offset)
return array.array('B', val[0])
def readVarbinary(self):
# length preceeded (4 byte value) string
length = self.readInt32()
if self.NullCheck[self.VOLTTYPE_VARBINARY](length) == None:
return None
return self.readVarbinaryContent(length)
def writeVarbinary(self, value):
if value is None:
self.writeInt32(self.NULL_STRING_INDICATOR)
return
self.writeInt32(len(value))
self.wbuf.extend(value)
# date
# The timestamp we receive from the server is a 64-bit integer representing
# microseconds since the epoch. It will be converted to a datetime object in
# the local timezone.
def readDate(self):
raw = self.readInt64()
if raw == None:
return None
# microseconds before or after Jan 1, 1970 UTC
return datetime.datetime.fromtimestamp(raw/1000000.0)
def readDateArray(self):
retval = []
raw = self.readInt64Array()
for i in raw:
val = None
if i != None:
val = datetime.datetime.fromtimestamp(i/1000000.0)
retval.append(val)
return tuple(retval)
def writeDate(self, value):
if value is None:
val = self.__class__.NULL_BIGINT_INDICATOR
else:
seconds = int(value.strftime("%s"))
val = seconds * 1000000 + value.microsecond
self.wbuf.extend(int64toBytes(val))
def readDecimal(self):
offset = 16 * struct.calcsize('b')
if self.NullCheck[self.VOLTTYPE_DECIMAL](self.read_buffer.read(offset)) == None:
self.read_buffer.shift(offset)
return None
val = list(self.read_buffer.unpack(self.ubyteType(16), offset))
mostSignificantBit = 1 << 7
isNegative = (val[0] & mostSignificantBit) != 0
unscaledValue = -(val[0] & mostSignificantBit) << 120
# Clear the highest bit
# Unleash the powers of the butterfly
val[0] &= ~mostSignificantBit
# Get the 2's complement
for x in range(16):
unscaledValue += val[x] << ((15 - x) * 8)
unscaledValue = [int(x) for x in str(abs(unscaledValue))]
return decimal.Decimal((isNegative, tuple(unscaledValue),
-self.__class__.DEFAULT_DECIMAL_SCALE))
def readDecimalArray(self):
retval = []
cnt = self.readInt16()
for i in range(cnt):
retval.append(self.readDecimal())
return tuple(retval)
def __intToBytes(self, value, sign):
value_bytes = bytes()
if sign == 1:
value = ~value + 1 # 2's complement
# Turn into byte array
while value != 0 and value != -1:
byte = value & 0xff
# flip the high order bits to 1 only if the number is negative and
# this is the highest order byte
if value >> 8 == 0 and sign == 1:
mask = 1 << 7
while mask > 0 and (byte & mask) == 0:
byte |= mask
mask >> 1
value_bytes = struct.pack(self.ubyteType(1), byte) + value_bytes
value = value >> 8
if len(value_bytes) > 16:
raise ValueError("Precision of this decimal is >38 digits");
if sign == 1:
ret = struct.pack(self.ubyteType(1), 0xff)
else:
ret = struct.pack(self.ubyteType(1), 0)
# Pad it
ret *= 16 - len(value_bytes)
ret += value_bytes
return ret
def writeDecimal(self, num):
if num is None:
self.wbuf.extend(self.NULL_DECIMAL_INDICATOR)
return
if not isinstance(num, decimal.Decimal):
raise TypeError("num must be of the type decimal.Decimal")
(sign, digits, exponent) = num.as_tuple()
precision = len(digits)
scale = -exponent
if (scale > self.__class__.DEFAULT_DECIMAL_SCALE):
raise ValueError("Scale of this decimal is %d and the max is 12"
% (scale))
rest = precision - scale
if rest > 26:
raise ValueError("Precision to the left of the decimal point is %d"
" and the max is 26" % (rest))
scale_factor = self.__class__.DEFAULT_DECIMAL_SCALE - scale
unscaled_int = int(decimal.Decimal((0, digits, scale_factor)))
data = self.__intToBytes(unscaled_int, sign)
self.wbuf.extend(data)
def writeDecimalString(self, num):
if num is None: