Repository navigation
Expand file tree
/
Copy pathe6data_grpc.py
More file actions
2699 lines (2389 loc) · 118 KB
/
Copy pathe6data_grpc.py
File metadata and controls
2699 lines (2389 loc) · 118 KB
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
"""DB-API implementation backed by HiveServer2 (Thrift API)
See http://www.python.org/dev/peps/pep-0249/
Many docstrings in this file are based on the PEP, which is in the public domain.
"""
from __future__ import absolute_import
from __future__ import unicode_literals
import datetime
import logging
import math
import os
import re
import sys
import threading
import time
from contextlib import contextmanager
from concurrent.futures import Future
from decimal import Decimal
from io import BytesIO
from ssl import CERT_NONE, CERT_OPTIONAL, CERT_REQUIRED
import grpc
from grpc._channel import _InactiveRpcError
from e6data_python_connector.cluster_manager import ClusterManager, _oauth_rpc
from e6data_python_connector.common import DBAPITypeObject, ParamEscaper, DBAPICursor, get_ssl_credentials
from e6data_python_connector.constants import (
MAX_RETRY_ATTEMPTS, RETRY_SLEEP_SECONDS, GRPC_ERROR_STRATEGY_MISMATCH, GRPC_ERROR_ACCESS_DENIED,
PRIMITIVE_TYPES
)
from e6data_python_connector.datainputstream import get_query_columns_info, read_rows_from_chunk, \
is_fastbinary_available
from e6data_python_connector.server import e6x_engine_pb2_grpc, e6x_engine_pb2
from e6data_python_connector.oauth import ClientCredentialsTokenProvider
from e6data_python_connector.result_batch import ResultBatchBuffer, decode_result_batches
from e6data_python_connector.result_prefetch import ContinuousResultStream, PendingFetch
from e6data_python_connector.exceptions import (
OAuthNotSupportedError, IncompleteResultError, ProgrammingError, OperationalError)
from e6data_python_connector.strategy import _get_grpc_header
from e6data_python_connector.typeId import *
apilevel = '2.0'
threadsafety = 2 # Threads may share the e6xdb and connections.
paramstyle = 'pyformat' # Python extended format codes, e.g. ...WHERE name=%(name)s
_TIMESTAMP_PATTERN = re.compile(r'(\d+-\d+-\d+ \d+:\d+:\d+(\.\d{,6})?)')
def _cleanup_deadline(timeout):
timeout = 10.0 if timeout is None else timeout
if isinstance(timeout, bool) or not isinstance(timeout, (int, float)) or not math.isfinite(timeout):
raise ValueError('Cleanup timeout must be finite seconds.')
if timeout <= 0:
raise TimeoutError('Cleanup deadline exceeded before dispatch.')
return time.monotonic() + timeout
def _cleanup_remaining(deadline):
remaining = deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError('Cleanup deadline exceeded before dispatch.')
return remaining
ssl_cert_parameter_map = {
"none": CERT_NONE,
"optional": CERT_OPTIONAL,
"required": CERT_REQUIRED,
}
def _parse_timestamp(value):
if value:
match = _TIMESTAMP_PATTERN.match(value)
if match:
if match.group(2):
format = '%Y-%m-%d %H:%M:%S.%f'
# use the pattern to truncate the value
value = match.group()
else:
format = '%Y-%m-%d %H:%M:%S'
value = datetime.datetime.strptime(value, format)
else:
raise Exception(
'Cannot convert "{}" into a datetime'.format(value)
)
else:
value = None
return value
TYPES_CONVERTER = {
"DECIMAL_TYPE": Decimal,
"TIMESTAMP_TYPE": _parse_timestamp
}
def re_auth(func):
def wrapper(self, *args, **kwargs):
if (self.connection._uses_oauth or self._result_batch_v2_enabled
or self.connection.enable_result_batch_v2):
# OAuth retries belong to a safe individual RPC before admission. Never
# replay execute or result retrieval after a query may have been submitted.
return func(self, *args, **kwargs)
max_retry = MAX_RETRY_ATTEMPTS
current_retry = 0
while current_retry < max_retry:
try:
return func(self, *args, **kwargs)
except _InactiveRpcError as e:
current_retry += 1
if current_retry == max_retry:
raise e
if e.code() == grpc.StatusCode.INTERNAL and GRPC_ERROR_ACCESS_DENIED in e.details():
time.sleep(RETRY_SLEEP_SECONDS)
self.connection.get_re_authenticate_session_id()
elif GRPC_ERROR_STRATEGY_MISMATCH in e.details():
# Strategy changed, clear cache and retry
_clear_strategy_cache()
# Force re-authentication which will detect new strategy
self.connection.get_re_authenticate_session_id()
else:
raise e
return wrapper
class HiveParamEscaper(ParamEscaper):
def escape_string(self, item):
# backslashes and single quotes need to be escaped
# Need to decode UTF-8 because of old sqlalchemy.
# Newer SQLAlchemy checks dialect.supports_unicode_binds before encoding Unicode strings
# as byte strings. The old version always encodes Unicode as byte strings, which breaks
# string formatting here.
if isinstance(item, bytes):
item = item.decode('utf-8')
return "'{}'".format(
item
.replace('\\', '\\\\')
.replace("'", "\\'")
.replace('\r', '\\r')
.replace('\n', '\\n')
.replace('\t', '\\t')
)
_escaper = HiveParamEscaper()
# Logger for the module
logger = logging.getLogger(__name__)
def _configure_debug_logging():
"""Enable connector output without changing application logging handlers."""
connector_logger = logging.getLogger('e6data_python_connector')
connector_logger.setLevel(logging.DEBUG)
current = connector_logger
while current is not None:
if any(handler.level <= logging.DEBUG and not isinstance(handler, logging.NullHandler)
for handler in current.handlers):
return
if not current.propagate:
break
current = current.parent
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(
'[%(name)s] %(asctime)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'))
connector_logger.addHandler(handler)
def _log_result_batch_fetch(protocol, rpc_seconds, chunk_count=0, serialized_bytes=0,
decode_seconds=0, status='ok'):
"""Emit bounded metrics without query, identity, or result contents."""
logger.debug(
'Result batch fetch protocol=%s rpc_seconds=%.6f decode_seconds=%.6f '
'chunk_count=%d serialized_bytes=%d status=%s',
protocol, rpc_seconds, decode_seconds, chunk_count, serialized_bytes, status, extra={
'result_batch_protocol': protocol,
'result_batch_rpc_seconds': rpc_seconds,
'result_batch_chunk_count': chunk_count,
'result_batch_serialized_bytes': serialized_bytes,
'result_batch_decode_seconds': decode_seconds,
'result_batch_status': status,
})
def _result_fetch_remaining(deadline):
remaining = deadline - time.monotonic()
if remaining <= 0:
raise TimeoutError('Result fetch deadline exceeded.')
return remaining
# Thread-safe and process-safe storage for active deployment strategy
_strategy_lock = threading.Lock()
_strategy_manager = None
_shared_strategy = None
_local_strategy_cache = {
'active_strategy': None,
'last_check_time': 0,
'pending_strategy': None, # Strategy to use for next query
'query_strategy_map': {}, # Map of query_id to strategy used
'last_transition_time': 0, # Timestamp of last strategy transition
'session_invalidated': False # Flag to invalidate all sessions
}
# Strategy cache timeout in seconds (5 minutes)
STRATEGY_CACHE_TIMEOUT = 300
# Global set to track debug-enabled connections
_debug_connections = set()
def _strategy_debug_log(message):
"""Log strategy debug messages if any connection has debug enabled."""
if _debug_connections:
logger.info(f"[E6DATA_STRATEGY_DEBUG] {time.strftime('%Y-%m-%d %H:%M:%S')} - {message}")
def _get_shared_strategy():
"""Get or create the shared strategy storage."""
return _local_strategy_cache
@contextmanager
def _strategy_guard(deadline=None):
"""Bound cleanup routing admission by the operation's original deadline."""
if deadline is None:
_strategy_lock.acquire()
elif not _strategy_lock.acquire(timeout=_cleanup_remaining(deadline)):
raise TimeoutError('Cleanup deadline exceeded waiting for routing state.')
try:
if deadline is not None:
_cleanup_remaining(deadline)
yield
finally:
_strategy_lock.release()
def _get_active_strategy(deadline=None):
"""Get the active deployment strategy (blue or green) from shared memory."""
with _strategy_guard(deadline):
shared_strategy = _get_shared_strategy()
# current_time = time.time()
# Check if strategy is cached and not expired
# if (shared_strategy['active_strategy'] is not None and
# current_time - shared_strategy['last_check_time'] < STRATEGY_CACHE_TIMEOUT):
if shared_strategy['active_strategy'] is not None:
return shared_strategy['active_strategy']
return None
def _set_active_strategy(strategy):
"""Set the active deployment strategy in shared memory."""
if not strategy:
return
# Normalize strategy to lowercase and validate
normalized_strategy = strategy.lower()
if normalized_strategy not in ['blue', 'green']:
return
with _strategy_lock:
shared_strategy = _get_shared_strategy()
current_time = time.time()
old_strategy = shared_strategy.get('active_strategy')
# Only update transition time if strategy actually changed
if old_strategy != normalized_strategy:
shared_strategy['last_transition_time'] = current_time
_strategy_debug_log(f"Setting active strategy: {old_strategy} -> {normalized_strategy}")
else:
_strategy_debug_log(f"Active strategy unchanged: {normalized_strategy}")
shared_strategy['active_strategy'] = normalized_strategy
shared_strategy['last_check_time'] = current_time
def _clear_strategy_cache():
"""Clear the cached strategy to force re-detection."""
with _strategy_lock:
shared_strategy = _get_shared_strategy()
old_strategy = shared_strategy.get('active_strategy')
if old_strategy:
_strategy_debug_log(f"Clearing strategy cache (was: {old_strategy})")
shared_strategy['active_strategy'] = None
shared_strategy['last_check_time'] = 0
shared_strategy['pending_strategy'] = None
def _set_pending_strategy(strategy, deadline=None):
"""Set the pending strategy to be used for the next query."""
if not strategy:
return
# Normalize strategy to lowercase and validate
normalized_strategy = strategy.lower()
if normalized_strategy not in ['blue', 'green']:
return
with _strategy_guard(deadline):
shared_strategy = _get_shared_strategy()
current_active = shared_strategy['active_strategy']
if normalized_strategy != current_active:
shared_strategy['pending_strategy'] = normalized_strategy
query_count = len(shared_strategy.get('query_strategy_map', {}))
_strategy_debug_log(f"Setting pending strategy: {normalized_strategy} (current: {current_active}, active queries: {query_count})")
def _apply_pending_strategy(deadline=None):
"""Apply the pending strategy as the active strategy."""
with _strategy_guard(deadline):
shared_strategy = _get_shared_strategy()
if shared_strategy['pending_strategy']:
old_strategy = shared_strategy['active_strategy']
new_strategy = shared_strategy['pending_strategy']
current_time = time.time()
_strategy_debug_log(f"Applying pending strategy: {old_strategy} -> {new_strategy}")
shared_strategy['active_strategy'] = new_strategy
shared_strategy['pending_strategy'] = None
shared_strategy['last_check_time'] = current_time
shared_strategy['last_transition_time'] = current_time
shared_strategy['session_invalidated'] = True # Invalidate all sessions
_strategy_debug_log(f"Strategy transition complete. All sessions invalidated.")
return new_strategy
return None
def _invalidate_all_sessions():
"""Invalidate all existing sessions to force fresh connections with new strategy."""
# This is a global flag that all connections will check
shared_strategy = _get_shared_strategy()
shared_strategy['session_invalidated'] = True
def _register_query_strategy(query_id, strategy):
"""Register the strategy used for a specific query."""
if not query_id or not strategy:
return
# Normalize strategy to lowercase and validate
normalized_strategy = strategy.lower()
if normalized_strategy not in ['blue', 'green']:
return
with _strategy_lock:
shared_strategy = _get_shared_strategy()
query_map = shared_strategy.get('query_strategy_map', {})
query_map[query_id] = normalized_strategy
shared_strategy['query_strategy_map'] = query_map
_strategy_debug_log(f"Query {query_id} registered with strategy: {normalized_strategy}")
def _get_query_strategy(query_id, deadline=None):
"""Get the strategy used for a specific query."""
current_active_strategy = _get_active_strategy(deadline=deadline)
if not query_id:
return current_active_strategy
with _strategy_guard(deadline):
shared_strategy = _get_shared_strategy()
query_map = shared_strategy.get('query_strategy_map', {})
return query_map.get(query_id, current_active_strategy)
def _cleanup_query_strategy(query_id, deadline=None):
"""Remove the strategy mapping for a completed query."""
if not query_id:
return
with _strategy_guard(deadline):
shared_strategy = _get_shared_strategy()
query_map = shared_strategy.get('query_strategy_map', {})
if query_id in query_map:
strategy = query_map[query_id]
del query_map[query_id]
shared_strategy['query_strategy_map'] = query_map
remaining_queries = len(query_map)
_strategy_debug_log(f"Query {query_id} completed (was using {strategy}). Remaining active queries: {remaining_queries}")
def _finish_query_cleanup(query_id, new_strategy, deadline):
"""Publish all successful cleanup bookkeeping under one bounded admission."""
with _strategy_guard(deadline):
shared = _get_shared_strategy()
normalized = new_strategy.lower() if isinstance(new_strategy, str) else None
if normalized in ('blue', 'green') and normalized != shared['active_strategy']:
shared['pending_strategy'] = normalized
query_map = shared.get('query_strategy_map', {})
query_map.pop(query_id, None)
shared['query_strategy_map'] = query_map
if not query_map and shared['pending_strategy']:
shared['active_strategy'] = shared['pending_strategy']
shared['pending_strategy'] = None
now = time.time()
shared['last_check_time'] = shared['last_transition_time'] = now
shared['session_invalidated'] = True
def _get_strategy_debug_info():
"""Get debug information about current strategy state."""
with _strategy_lock:
shared_strategy = _get_shared_strategy()
return {
'active_strategy': shared_strategy.get('active_strategy'),
'pending_strategy': shared_strategy.get('pending_strategy'),
'last_check_time': shared_strategy.get('last_check_time', 0),
'last_transition_time': shared_strategy.get('last_transition_time', 0),
'query_count': len(shared_strategy.get('query_strategy_map', {})),
'current_time': time.time()
}
def connect(*args, **kwargs):
"""Constructor for creating a connection to the database. See class :py:class:`Connection` for
arguments.
:returns: a :py:class:`Connection` object.
"""
return Connection(*args, **kwargs)
class Connection(object):
"""Create connection to e6data """
def __init__(
self,
host: str,
port: int,
username: str = None,
password: str = None,
catalog: str = None,
database: str = None,
cluster_name: str = None,
secure: bool = False,
ssl_cert = None,
auto_resume: bool = True,
scheme: str = 'e6data',
grpc_options: dict = None,
debug: bool = False,
require_fastbinary: bool = True,
client_id: str = None,
client_secret: str = None,
token_url: str = None,
oauth_scope: str = None,
access_token: str = None,
client_auth_method: str = 'basic',
enable_result_batch_v2: bool = False,
):
"""
Parameters
----------
host: str
IP address or hostname of e6data cluster
port: int
Port of the e6data engine
username: str
Your e6data Email ID
password: str
Access Token generated in the e6data console
catalog: str
Catalog name
database: str
Database to perform the query on
cluster_name: str
Cluster's name
secure: bool, Optional
Flag to use a secure channel for data transfer
ssl_cert: str or bytes, Optional
Path to CA certificate file (PEM format) or certificate content as bytes for
secure connections. If None, system default CA bundle is used.
auto_resume: bool, Optional
Flag to enable auto resume of the cluster before the query execution
scheme: string, Optional
e6data supported scheme
grpc_options: dict, Optional
Specify gRPC configuration
- keepalive_timeout_ms: This parameter defines the time, in milliseconds, that a gRPC connection should remain idle before sending a keepalive ping to check if the connection is still alive.
- max_receive_message_length: This parameter sets the maximum allowed size (in bytes) for incoming messages on the gRPC server.
- max_send_message_length: Similar to max_receive_message_length, this parameter sets the maximum allowed size (in bytes) for outgoing messages from the gRPC client
- grpc_prepare_timeout: Timeout for prepare statement API call (default to 10 minutes).
- keepalive_time_ms: This parameter defines the time, in milliseconds, Default to 30 seconds
debug: bool, Optional
Flag to enable debug logging for blue-green deployment strategy changes
require_fastbinary: bool, Optional
Flag to require fastbinary module for Thrift deserialization. If True (default),
raises an exception if fastbinary is not available. If False, logs a warning
and continues with pure Python implementation (with reduced performance).
client_id: str, Optional
OAuth 2.0 client id. Supply with client_secret and token_url to authenticate with
the client-credentials grant instead of username/password.
client_secret: str, Optional
OAuth 2.0 client secret.
token_url: str, Optional
Token endpoint of the authorization server.
oauth_scope: str, Optional
Space-delimited scopes to request. Omit to receive the client's full registered set.
access_token: str, Optional
A previously obtained OAuth 2.0 access token, for callers that mint their own. The
connector will not refresh it, so a long-lived connection may outlive the token.
client_auth_method: str, Optional
How the client credentials are presented to the token endpoint -- 'basic' (default,
what the e6data authorization server expects) or 'post'.
Exactly one authentication method must be supplied: username and password, or client_id
with client_secret and token_url, or access_token. Passing more than one is an error rather
than a precedence rule, so a stale credential left in a config file cannot silently win.
"""
from .result_decode_worker import is_decode_worker
if is_decode_worker():
raise ValueError('Connector connections are prohibited in decode workers.')
if not host or not port:
raise ValueError("host or port cannot be empty.")
if not isinstance(enable_result_batch_v2, bool):
raise ValueError('enable_result_batch_v2 must be a boolean.')
self.enable_result_batch_v2 = enable_result_batch_v2
self._result_pid = os.getpid()
self._result_generation = 0
self._result_cursors = set()
self._result_state_lock = threading.Lock()
self._result_closed = False
self._decoder_lease = None
if enable_result_batch_v2:
from .result_decode import validate_decode_runtime
validate_decode_runtime()
normalized = {}
for key, value in (grpc_options or {}).items():
key = key[5:] if key.startswith('grpc.') else key
if key in normalized and normalized[key] != value:
raise ValueError('Conflicting gRPC options after prefix normalization.')
normalized[key] = value
grpc_options = normalized
if enable_result_batch_v2:
limit = normalized.get('max_receive_message_length', -1)
if isinstance(limit, bool) or not isinstance(limit, int) or (limit != -1 and limit <= 0):
raise ValueError('V2 receive limit must be a positive integer or -1 for unlimited.')
normalized['max_receive_message_length'] = limit
if enable_result_batch_v2 and grpc_options is not None and 'grpc_prepare_timeout' in grpc_options:
timeout = grpc_options['grpc_prepare_timeout']
if (isinstance(timeout, bool) or not isinstance(timeout, (int, float))
or not math.isfinite(timeout) or timeout <= 0):
raise ValueError('grpc_prepare_timeout must be positive finite seconds.')
# Count the credential shapes present rather than picking one by precedence: silently
# preferring one over another is how a stale value in a config file ends up authenticating
# a connection nobody meant it to.
supplied = [
bool(username or password),
bool(client_id or client_secret or token_url or oauth_scope),
bool(access_token),
]
if not any(supplied):
raise ValueError(
"No credentials supplied. Provide username and password, or client_id with "
"client_secret and token_url, or access_token."
)
if sum(supplied) > 1:
raise ValueError(
"Supply exactly one authentication method: username/password, OAuth client "
"credentials, or a pre-obtained access_token."
)
self._token_provider = None
self._static_access_token = None
self._oauth_resume_strategy = None
# Guards the single retry after an auto-resume, so a cluster that keeps refusing
# connections cannot drive get_session_id into unbounded recursion.
self._resume_retry_in_progress = False
if supplied[0]:
if not username or not password:
raise ValueError("username or password cannot be empty.")
elif supplied[1]:
if not client_id or not client_secret or not token_url:
raise ValueError(
"client_id, client_secret and token_url are all required for OAuth "
"client-credentials authentication."
)
self._token_provider = ClientCredentialsTokenProvider(
token_url=token_url,
client_id=client_id,
client_secret=client_secret,
scope=oauth_scope,
client_auth_method=client_auth_method,
)
else:
self._static_access_token = access_token
self.__username = username
self.__password = password
self.database = database
self.cluster_name = cluster_name.lower() if cluster_name else cluster_name
self._session_id = None
self._host = host
self._port = port
self._secure_channel = secure
self._ssl_cert = ssl_cert
self.catalog_name = catalog
self._auto_resume = auto_resume
# Store require_fastbinary flag
self._require_fastbinary = require_fastbinary
# Check fastbinary availability at connection creation time
if not is_fastbinary_available():
if require_fastbinary:
raise Exception(
"""
Failed to import fastbinary.
Did you install system dependencies?
Please verify https://github.com/e6x-labs/e6data-python-connector#dependencies
To continue without fastbinary (with reduced performance), set require_fastbinary=False
in the connection parameters.
"""
)
else:
logger.warning(
"fastbinary module is not available. Using pure Python implementation. "
"Performance may be degraded. To enable fastbinary, install system dependencies: "
"https://github.com/e6x-labs/e6data-python-connector#dependencies"
)
self._grpc_options = grpc_options
if self._grpc_options is None:
self._grpc_options = dict()
self.grpc_prepare_timeout = (self._grpc_options.get('grpc_prepare_timeout', 10 * 60)
if enable_result_batch_v2 else
self._grpc_options.get('grpc_prepare_timeout') or 10 * 60)
self.grpc_auto_resume_timeout_seconds = 60 * 5 # 5 minutes
if 'grpc_auto_resume_timeout_seconds' in self._grpc_options:
"""
The default maximum time on client side to wait for the cluster to resume is 5 minutes.
"""
self.grpc_auto_resume_timeout_seconds = self._grpc_options.pop('grpc_auto_resume_timeout_seconds')
# Store debug flag and register with debug connections
self._debug = debug
if self._debug:
_debug_connections.add(id(self))
# Enable comprehensive debugging if debug flag is set
if self._debug:
_configure_debug_logging()
# Note: gRPC C++ core tracing (GRPC_VERBOSITY and GRPC_TRACE) must be set
# BEFORE the gRPC module is imported to take effect. Setting them at runtime
# will not enable HTTP/2 frame logs or low-level tracing.
#
# To enable full gRPC network tracing, set these environment variables
# before starting your Python script:
# export GRPC_VERBOSITY=DEBUG
# export GRPC_TRACE=client_channel,http2
#
# The following runtime settings only affect Python-level logging:
# Enable gRPC Python logging (this works at runtime)
os.environ['GRPC_PYTHON_LOG_LEVEL'] = 'DEBUG'
os.environ['GRPC_PYTHON_LOG_STDERR'] = '1'
# Ensure gRPC logger is at DEBUG level
grpc_logger = logging.getLogger('grpc')
grpc_logger.setLevel(logging.DEBUG)
# Enable gRPC transport logger
grpc_transport_logger = logging.getLogger('grpc._channel')
grpc_transport_logger.setLevel(logging.DEBUG)
# Enable gRPC server logger
grpc_server_logger = logging.getLogger('grpc._server')
grpc_server_logger.setLevel(logging.DEBUG)
# Set e6data connector logger to DEBUG
e6data_logger = logging.getLogger('e6data_python_connector')
e6data_logger.setLevel(logging.DEBUG)
_strategy_debug_log(f"Debug mode enabled for connection {id(self)}")
_strategy_debug_log(f"GRPC_TRACE={os.environ.get('GRPC_TRACE')}")
self._create_client()
@property
def _get_grpc_options(self):
"""
Property to get gRPC options for the connection.
This method checks if the gRPC options are already cached. If not, it creates a copy of the
provided gRPC options and merges them with the default options. The merged options are then
cached for future use.
Returns:
list: A list of tuples containing gRPC options.
"""
if not hasattr(self, '_cached_grpc_options'):
grpc_options = self._grpc_options.copy()
default_options = {
"keepalive_timeout_ms": 900000, # Time in milliseconds to keep the connection alive.
"max_receive_message_length": -1, # Maximum size of received messages.
"max_send_message_length": -1, # Unlimited sent message size.
"grpc_prepare_timeout": self.grpc_prepare_timeout, # Timeout for prepare statement API call.
"keepalive_time_ms": 30000, # Time in milliseconds between keep-alive pings.
"keepalive_permit_without_calls": 1, # Allow keep-alives with no active RPCs.
"http2.max_pings_without_data": 0, # Unlimited pings without data.
"http2.min_time_between_pings_ms": 15000, # Minimum time between pings (15 seconds).
"http2.min_ping_interval_without_data_ms": 15000,
# Minimum interval between pings without data (15 seconds).
}
if grpc_options:
for key, value in grpc_options.items():
default_options[key] = value
self._cached_grpc_options = [(f'grpc.{key}', value) for key, value in default_options.items()]
return self._cached_grpc_options
def _create_client(self):
"""
Creates a gRPC client for the connection.
This method initializes a gRPC channel based on whether a secure channel is required or not.
It then creates a client stub for the QueryEngineService.
If the secure channel is enabled, it uses `grpc.secure_channel` with SSL credentials.
Otherwise, it uses `grpc.insecure_channel`.
The gRPC options are retrieved from the `_get_grpc_options` property.
Raises:
grpc.RpcError: If there is an error in creating the gRPC channel or client stub.
"""
if self._secure_channel:
self._channel = grpc.secure_channel(
target='{}:{}'.format(self._host, self._port),
options=self._get_grpc_options,
credentials=get_ssl_credentials(self._ssl_cert)
)
else:
self._channel = grpc.insecure_channel(
target='{}:{}'.format(self._host, self._port),
options=self._get_grpc_options
)
self._client = e6x_engine_pb2_grpc.QueryEngineServiceStub(self._channel)
@property
def _uses_oauth(self) -> bool:
"""Whether this connection authenticates with an OAuth token rather than credentials."""
return self._token_provider is not None or self._static_access_token is not None
def _bearer_token(self, force_refresh: bool = False, deadline=None, rejected_token=None) -> str:
"""
Returns the access token to present on the current OAuth RPC.
A provider-backed token is refreshed as needed; a token supplied directly by the caller is
returned as given, because we have no way to obtain another one.
"""
if self._token_provider is not None:
return self._token_provider.get_token(force_refresh=force_refresh, deadline=deadline,
rejected_token=rejected_token)
return self._static_access_token
def _build_authenticate_request(self):
"""
Builds the authenticate request.
An OAuth token is never placed in the message -- it travels in call metadata, which is the
gRPC convention and the only form a proxy could inspect. See _authenticate_metadata.
"""
if self._uses_oauth:
return e6x_engine_pb2.AuthenticateRequest()
return e6x_engine_pb2.AuthenticateRequest(
user=self.__username,
password=self.__password
)
def _authenticate_metadata(self, strategy=None, force_token_refresh: bool = False):
"""
Builds the call metadata for authenticate, adding the bearer credential when this connection
authenticates with a token.
Sent as per-call metadata rather than through grpc.CallCredentials deliberately: Python's
call credentials must be composed onto *channel* credentials and are rejected on an insecure
channel, and this connector defaults to plaintext. Metadata works on both.
"""
metadata = list(_get_grpc_header(cluster=self.cluster_name, strategy=strategy))
if self._uses_oauth:
metadata.append(
('authorization', 'Bearer {}'.format(self._bearer_token(force_refresh=force_token_refresh)))
)
return metadata
def _call_metadata(self, engine_ip=None, strategy=None, deadline=None, rejected_token=None):
"""
Builds the call metadata for every RPC other than authenticate.
The bearer travels on each call, not just on authenticate. That is what lets the engine
authorize from the token the caller is presenting right now rather than from a snapshot
taken when the session was minted -- so narrowing or revoking a client's grant takes effect
within the token's lifetime instead of the session's.
Near-free on the wire: the header value is identical call to call, so HPACK indexes it after
the first and each subsequent call carries a reference rather than the token.
"""
metadata = list(_get_grpc_header(engine_ip=engine_ip, cluster=self.cluster_name, strategy=strategy))
if self._uses_oauth:
metadata.append(('authorization', 'Bearer {}'.format(self._bearer_token(
force_refresh=rejected_token is not None, deadline=deadline, rejected_token=rejected_token))))
return metadata
def _oauth_metadata(self, strategy, deadline, rejected_token=None):
if rejected_token is not None and self._token_provider is None:
return None
return self._call_metadata(strategy=strategy, deadline=deadline, rejected_token=rejected_token)
def _authentication_failure(self):
"""
Builds the exception raised when the engine returns no session.
In OAuth mode the failure is genuinely ambiguous and the message says so. An engine built
before the bearerToken field existed ignores it as an unknown field, then sees an empty user
and password and refuses -- which looks exactly like a rejected token. Guessing between the
two would be worse than naming both.
"""
if self._uses_oauth:
return OAuthNotSupportedError(
"The engine returned no session for the supplied OAuth token. Either the token was "
"rejected, or this engine predates OAuth support on authenticate and ignored it -- "
"the two are indistinguishable from the client side. Check that the engine has "
"OAUTH_ENABLED set and trusts the token's issuer, or connect with username and "
"password instead."
)
return ValueError("Invalid credentials.")
def get_re_authenticate_session_id(self):
"""
Re-authenticates the session by closing the current connection and creating a new client.
This method is used to re-establish the session ID by closing the existing gRPC channel,
creating a new client, and then retrieving a new session ID.
Returns:
str: The new session ID after re-authentication.
Raises:
Exception: If there is an error during the re-authentication process.
"""
self.close()
self._create_client()
return self.get_session_id
@property
def get_session_id(self):
"""
To get the session id, if user is not authorised, first authenticate the user.
Also detects the active deployment strategy (blue/green) on first authentication.
Returns the empty string on an OAuth connection: there is no session to get. The access
token is the credential and travels in metadata on every call, so the engine resolves the
identity per request and the sessionId field carries nothing. Left empty rather than
removed because it is a proto3 scalar -- unset costs zero bytes, so the field can stay in
the schema for the credential path without either rail paying for the other.
"""
if self._uses_oauth:
return ''
# Check if we need a fresh connection due to strategy change
shared_strategy = _get_shared_strategy()
pending_strategy = shared_strategy.get('pending_strategy')
active_strategy = shared_strategy.get('active_strategy')
session_invalidated = shared_strategy.get('session_invalidated', False)
# Check if session was invalidated globally
if self._session_id and session_invalidated:
self._session_id = None
self.close()
self._create_client()
# Clear the invalidation flag
shared_strategy['session_invalidated'] = False
# Only create fresh connection if we have no active queries
elif self._session_id and pending_strategy and pending_strategy != active_strategy:
query_map = shared_strategy.get('query_strategy_map', {})
if len(query_map) == 0:
# Apply the pending strategy immediately since no queries are active
_apply_pending_strategy()
# Force complete reconnection with new strategy
self._session_id = None
self.close()
self._create_client()
if not self._session_id:
try:
authenticate_request = self._build_authenticate_request()
# Check if we have a cached strategy
active_strategy = _get_active_strategy()
shared_strategy = _get_shared_strategy()
pending_strategy = shared_strategy.get('pending_strategy')
if active_strategy and not pending_strategy:
# Use cached strategy only if there's no pending strategy
_strategy_debug_log(f"Authenticating with cached strategy: {active_strategy}")
try:
authenticate_response = self._client.authenticate(
authenticate_request,
metadata=self._authenticate_metadata(strategy=active_strategy)
)
self._session_id = authenticate_response.sessionId
if not self._session_id:
raise self._authentication_failure()
# Check for new strategy in authenticate response
if hasattr(authenticate_response, 'new_strategy') and authenticate_response.new_strategy:
new_strategy = authenticate_response.new_strategy.lower()
if new_strategy != active_strategy:
_set_pending_strategy(new_strategy)
_apply_pending_strategy()
self._session_id = None
self.close()
self._create_client()
return self.get_session_id
except _InactiveRpcError as e:
if e.code() == grpc.StatusCode.UNKNOWN and 'status: 456' in e.details():
# Strategy changed, clear cache and retry
_strategy_debug_log(f"Got 456 error with strategy {active_strategy}, clearing cache and retrying")
_clear_strategy_cache()
active_strategy = None
else:
if self._perform_auto_resume(e):
# Cluster resumed, retry with cached strategy
_strategy_debug_log(f"Cluster resumed, retrying with cached strategy {active_strategy}")
active_strategy = None # Force retry
else:
raise e
elif pending_strategy:
# If there's a pending strategy, force re-authentication with new strategy
active_strategy = None
if not active_strategy:
# Check if we have a pending strategy to use
if pending_strategy:
# Use pending strategy and apply it immediately
_apply_pending_strategy()
active_strategy = _get_active_strategy()
strategies = [active_strategy]
else:
# Always try blue first, then green if it fails with 456
strategies = ['blue', 'green']
_strategy_debug_log(f"No cached strategy, will try strategies in order: {strategies}")
last_error = None
for strategy in strategies:
_strategy_debug_log(f"Attempting authentication with strategy: {strategy}.")
try:
authenticate_response = self._client.authenticate(
authenticate_request,
metadata=self._authenticate_metadata(strategy=strategy)
)
self._session_id = authenticate_response.sessionId
if self._session_id:
# Success! Cache this strategy
_strategy_debug_log(f"Authentication successful with strategy: {strategy}")
_set_active_strategy(strategy)
# Check for new strategy in authenticate response
if hasattr(authenticate_response, 'new_strategy') and authenticate_response.new_strategy:
new_strategy = authenticate_response.new_strategy.lower()
if new_strategy != strategy:
_set_pending_strategy(new_strategy)
_apply_pending_strategy()
self.close()
self._create_client()
self._session_id = None
return self.get_session_id
break
except _InactiveRpcError as e:
if e.code() == grpc.StatusCode.UNKNOWN and 'status: 456' in e.details():
# Wrong strategy, try the next one
_strategy_debug_log(f"Strategy {strategy} failed with 456 error, trying next")
last_error = e
continue
else:
if self._perform_auto_resume(e):
# Cluster resumed successfully, retry authentication with current strategy
_strategy_debug_log(f"Cluster resumed, retrying authentication with {strategy}")
continue
else:
# Auto-resume failed, raise the error
raise e
if not self._session_id and last_error:
# Neither strategy worked
raise last_error
if not self._session_id:
raise self._authentication_failure()
except _InactiveRpcError as e:
# Give auto-resume its chance, then surface the failure either way.
#
# This used to call _perform_auto_resume and discard the result, which swallowed
# the error: _session_id stayed None, the property returned None, and the caller