-
Notifications
You must be signed in to change notification settings - Fork 68
/
Copy pathclient.py
6588 lines (5633 loc) · 253 KB
/
client.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
"""
The `Synapse` object encapsulates a connection to the Synapse service and is used for building projects, uploading and
retrieving data, and recording provenance of data analysis.
"""
import asyncio
import collections
import collections.abc
import configparser
import csv
import errno
import functools
import getpass
import hashlib
import json
import logging
import mimetypes
import numbers
import os
import re
import shutil
import sys
import tempfile
import threading
import time
import typing
import urllib.parse as urllib_urlparse
import urllib.request as urllib_request
import warnings
import webbrowser
import zipfile
from concurrent.futures import ThreadPoolExecutor
from http.client import HTTPResponse
from typing import Any, Dict, List, Optional, Tuple, Union
import asyncio_atexit
import httpx
import requests
from deprecated import deprecated
from opentelemetry import trace
from opentelemetry.instrumentation.httpx import HTTPXClientInstrumentor
from opentelemetry.instrumentation.requests import RequestsInstrumentor
from opentelemetry.instrumentation.threading import ThreadingInstrumentor
from opentelemetry.instrumentation.urllib import URLLibInstrumentor
from opentelemetry.trace import Span
import synapseclient
import synapseclient.core.multithread_download as multithread_download
from synapseclient.api import (
get_client_authenticated_s3_profile,
get_config_file,
get_config_section_dict,
get_file_handle_for_download,
get_transfer_config,
)
from synapseclient.core import (
cache,
cumulative_transfer_progress,
exceptions,
sts_transfer,
utils,
)
from synapseclient.core.async_utils import wrap_async_to_sync
from synapseclient.core.constants import concrete_types, config_file_constants
from synapseclient.core.credentials import UserLoginArgs, get_default_credential_chain
from synapseclient.core.download import (
download_by_file_handle,
download_file_entity,
ensure_download_location_is_directory,
)
from synapseclient.core.dozer import doze
from synapseclient.core.exceptions import (
SynapseAuthenticationError,
SynapseError,
SynapseFileNotFoundError,
SynapseHTTPError,
SynapseMalformedEntityError,
SynapseMd5MismatchError,
SynapseNoCredentialsError,
SynapseProvenanceError,
SynapseTimeoutError,
SynapseUnmetAccessRestrictions,
)
from synapseclient.core.logging_setup import (
DEBUG_LOGGER_NAME,
DEFAULT_LOGGER_NAME,
SILENT_LOGGER_NAME,
)
from synapseclient.core.models.dict_object import DictObject
from synapseclient.core.models.permission import Permissions
from synapseclient.core.pool_provider import DEFAULT_NUM_THREADS, get_executor
from synapseclient.core.remote_file_storage_wrappers import S3ClientWrapper, SFTPWrapper
from synapseclient.core.retry import (
DEFAULT_RETRY_STATUS_CODES,
RETRYABLE_CONNECTION_ERRORS,
RETRYABLE_CONNECTION_EXCEPTIONS,
with_retry,
with_retry_time_based_async,
)
from synapseclient.core.upload.multipart_upload_async import (
multipart_upload_file_async,
multipart_upload_string_async,
)
from synapseclient.core.upload.upload_functions_async import (
upload_file_handle as upload_file_handle_async,
)
from synapseclient.core.upload.upload_functions_async import upload_synapse_s3
from synapseclient.core.utils import (
MB,
extract_synapse_id_from_query,
extract_zip_file_to_directory,
find_data_file_handle,
get_properties,
id_of,
is_integer,
is_json,
require_param,
validate_submission_id,
)
from synapseclient.core.version_check import version_check
from .activity import Activity
from .annotations import (
Annotations,
check_annotations_changed,
convert_old_annotation_json,
from_synapse_annotations,
to_synapse_annotations,
)
from .entity import (
Entity,
File,
Folder,
Versionable,
is_container,
is_synapse_entity,
is_versionable,
split_entity_namespaces,
)
from .evaluation import Evaluation, Submission, SubmissionStatus
from .table import (
Column,
CsvFileTable,
Dataset,
EntityViewSchema,
Schema,
SchemaBase,
SubmissionViewSchema,
TableQueryResult,
)
from .team import Team, TeamMember, UserGroupHeader, UserProfile
from .wiki import Wiki, WikiAttachment
tracer = trace.get_tracer("synapseclient")
PRODUCTION_ENDPOINTS = {
"repoEndpoint": "https://repo-prod.prod.sagebase.org/repo/v1",
"authEndpoint": "https://auth-prod.prod.sagebase.org/auth/v1",
"fileHandleEndpoint": "https://file-prod.prod.sagebase.org/file/v1",
"portalEndpoint": "https://www.synapse.org/",
}
STAGING_ENDPOINTS = {
"repoEndpoint": "https://repo-staging.prod.sagebase.org/repo/v1",
"authEndpoint": "https://auth-staging.prod.sagebase.org/auth/v1",
"fileHandleEndpoint": "https://file-staging.prod.sagebase.org/file/v1",
"portalEndpoint": "https://staging.synapse.org/",
}
CONFIG_FILE = os.path.join(os.path.expanduser("~"), ".synapseConfig")
SESSION_FILENAME = ".session"
FILE_BUFFER_SIZE = 2 * MB
CHUNK_SIZE = 5 * MB
QUERY_LIMIT = 1000
CHUNK_UPLOAD_POLL_INTERVAL = 1 # second
ROOT_ENTITY = "syn4489"
PUBLIC = 273949 # PrincipalId of public "user"
AUTHENTICATED_USERS = 273948
DEBUG_DEFAULT = False
REDIRECT_LIMIT = 5
MAX_THREADS_CAP = 128
# Defines the standard retry policy applied to the rest methods
# The retry period needs to span a minute because sending messages is limited to 10 per 60 seconds.
STANDARD_RETRY_PARAMS = {
"retry_status_codes": DEFAULT_RETRY_STATUS_CODES,
"retry_errors": RETRYABLE_CONNECTION_ERRORS,
"retry_exceptions": RETRYABLE_CONNECTION_EXCEPTIONS,
"retries": 60, # Retries for up to about 30 minutes
"wait": 1,
"max_wait": 30,
"back_off": 2,
}
STANDARD_RETRY_ASYNC_PARAMS = {
"retry_status_codes": DEFAULT_RETRY_STATUS_CODES,
"retry_errors": RETRYABLE_CONNECTION_ERRORS,
"retry_exceptions": RETRYABLE_CONNECTION_EXCEPTIONS,
}
# Add additional mimetypes
mimetypes.add_type("text/x-r", ".R", strict=False)
mimetypes.add_type("text/x-r", ".r", strict=False)
mimetypes.add_type("text/tab-separated-values", ".maf", strict=False)
mimetypes.add_type("text/tab-separated-values", ".bed5", strict=False)
mimetypes.add_type("text/tab-separated-values", ".bed", strict=False)
mimetypes.add_type("text/tab-separated-values", ".vcf", strict=False)
mimetypes.add_type("text/tab-separated-values", ".sam", strict=False)
mimetypes.add_type("text/yaml", ".yaml", strict=False)
mimetypes.add_type("text/x-markdown", ".md", strict=False)
mimetypes.add_type("text/x-markdown", ".markdown", strict=False)
DEFAULT_STORAGE_LOCATION_ID = 1
def login(*args, **kwargs):
"""
Convenience method to create a Synapse object and login.
See `synapseclient.Synapse.login` for arguments and usage.
Example: Getting started
Logging in to Synapse using an authToken
import synapseclient
syn = synapseclient.login(authToken="authtoken")
Using environment variable or `.synapseConfig`
import synapseclient
syn = synapseclient.login()
"""
syn = Synapse()
syn.login(*args, **kwargs)
return syn
class Synapse(object):
"""
Constructs a Python client object for the Synapse repository service
Attributes:
repoEndpoint: Location of Synapse repository
authEndpoint: Location of authentication service
fileHandleEndpoint: Location of file service
portalEndpoint: Location of the website
serviceTimeoutSeconds: Wait time before timeout (currently unused)
debug: Print debugging messages if True
skip_checks: Skip version and endpoint checks
configPath: Path to config File with setting for Synapse. Defaults to ~/.synapseConfig
requests_session: A custom [requests.Session object](https://requests.readthedocs.io/en/latest/user/advanced/) that this Synapse instance will use
when making http requests.
cache_root_dir: Root directory for storing cache data
silent: Defaults to False.
Example: Getting started
Logging in to Synapse using an authToken
import synapseclient
syn = synapseclient.login(authToken="authtoken")
Using environment variable or `.synapseConfig`
import synapseclient
syn = synapseclient.login()
"""
_synapse_client = None
_allow_client_caching = True
_enable_open_telemetry = False
# TODO: add additional boolean for write to disk?
def __init__(
self,
repoEndpoint: str = None,
authEndpoint: str = None,
fileHandleEndpoint: str = None,
portalEndpoint: str = None,
debug: bool = None,
skip_checks: bool = False,
configPath: str = CONFIG_FILE,
requests_session: requests.Session = None,
cache_root_dir: str = None,
silent: bool = None,
requests_session_async_synapse: httpx.AsyncClient = None,
requests_session_storage: httpx.Client = None,
asyncio_event_loop: asyncio.AbstractEventLoop = None,
cache_client: bool = True,
) -> "Synapse":
"""
Initialize Synapse object
Arguments:
repoEndpoint: Location of Synapse repository.
authEndpoint: Location of authentication service.
fileHandleEndpoint: Location of file service.
portalEndpoint: Location of the website.
debug: Print debugging messages if True.
skip_checks: Skip version and endpoint checks.
configPath: Path to config File with setting for Synapse.
requests_session: A custom [requests.Session object](https://requests.readthedocs.io/en/latest/user/advanced/) that this Synapse instance will use
when making http requests.
cache_root_dir: Root directory for storing cache data.
silent: Suppresses message.
requests_session_async_synapse: The HTTPX Async client for interacting with
Synapse services.
requests_session_storage: The HTTPX client for interacting with
storage providers like AWS S3 and Google Cloud.
asyncio_event_loop: The event loop that is going to be used while executing
this code. This is optional and only used when you are manually
specifying an async HTTPX client.
cache_client: Whether to cache the Synapse client object in the Synapse module. Defaults to True.
When set to True anywhere a `Synapse` object is optional you do not need to pass an
instance of `Synapse` to that function, method, or class.
When working in a multi-user environment it is
recommended to set this to False, or use
`Synapse.allow_client_caching(False)`.
Raises:
ValueError: Warn for non-boolean debug value.
"""
self._requests_session = requests_session or requests.Session()
# `requests_session_async_synapse` and the thread pools are being stored in
# a dict based on the current running event loop. This is to ensure that the
# connection pooling is maintained within the same event loop. This is to
# prevent the connection pooling from being shared across different event loops.
if requests_session_async_synapse and asyncio_event_loop:
self._requests_session_async_synapse = {
asyncio_event_loop: requests_session_async_synapse
}
else:
self._requests_session_async_synapse = {}
httpx_timeout = httpx.Timeout(70, pool=None)
self._requests_session_storage = requests_session_storage or httpx.Client(
timeout=httpx_timeout
)
cache_root_dir = (
cache.CACHE_ROOT_DIR if cache_root_dir is None else cache_root_dir
)
config_debug = None
# Check for a config file
self.configPath = configPath
if os.path.isfile(configPath):
config = get_config_file(configPath)
if config.has_option("cache", "location"):
cache_root_dir = config.get("cache", "location")
if config.has_section("debug"):
config_debug = True
if debug is None:
debug = config_debug if config_debug is not None else DEBUG_DEFAULT
if not isinstance(debug, bool):
raise ValueError("debug must be set to a bool (either True or False)")
self.debug = debug
self.cache = cache.Cache(cache_root_dir)
self._sts_token_store = sts_transfer.StsTokenStore()
self.setEndpoints(
repoEndpoint, authEndpoint, fileHandleEndpoint, portalEndpoint, skip_checks
)
self.default_headers = {
"content-type": "application/json; charset=UTF-8",
"Accept": "application/json; charset=UTF-8",
}
self.credentials = None
self.silent = silent
self._init_logger() # initializes self.logger
self.skip_checks = skip_checks
self.table_query_sleep = 0.2 # Sleep for 200ms between table query retries
self.table_query_backoff = 1.1
self.table_query_max_sleep = 20
self.table_query_timeout = 600 # in seconds
self.multi_threaded = True # if set to True, multi threaded download will be used for http and https URLs
transfer_config = get_transfer_config(config_path=self.configPath)
self.max_threads = transfer_config["max_threads"]
self._thread_executor = {}
self._process_executor = {}
self._parallel_file_transfer_semaphore = {}
self.use_boto_sts_transfers = transfer_config["use_boto_sts"]
self._parts_transfered_counter = 0
if cache_client and Synapse._allow_client_caching:
Synapse.set_client(synapse_client=self)
def _get_requests_session_async_synapse(
self, asyncio_event_loop: asyncio.AbstractEventLoop
) -> httpx.AsyncClient:
"""
httpx.AsyncClient can only use connection pooling within the same event loop.
As a result an `atexit` handler is used to close the connection when the event
loop is closed. It will also delete the attribute from the object to prevent
it from being reused in the future.
Further documentation can be found here:
<https://github.com/encode/httpx/discussions/2959>
As a result of this issue: It is recommended to use the same event loop for all
requests. This means to enter into an event loop before making any requests.
This is expected to be called from within an AsyncIO loop.
"""
if (
hasattr(self, "_requests_session_async_synapse")
and asyncio_event_loop in self._requests_session_async_synapse
and self._requests_session_async_synapse[asyncio_event_loop] is not None
):
return self._requests_session_async_synapse[asyncio_event_loop]
async def close_connection() -> None:
"""Close connection when event loop exits"""
await self._requests_session_async_synapse[asyncio_event_loop].aclose()
del self._requests_session_async_synapse[asyncio_event_loop]
httpx_timeout = httpx.Timeout(70, pool=None)
self._requests_session_async_synapse.update(
{
asyncio_event_loop: httpx.AsyncClient(
limits=httpx.Limits(max_connections=25),
timeout=httpx_timeout,
)
}
)
asyncio_atexit.register(close_connection)
return self._requests_session_async_synapse[asyncio_event_loop]
def _get_thread_pool_executor(
self, asyncio_event_loop: asyncio.AbstractEventLoop
) -> ThreadPoolExecutor:
"""
Retrieve the thread pool executor for the Synapse client. Or create a new one if
it does not exist. This executor is used for concurrent uploads of data to
storage providers like AWS S3 and Google Cloud Storage.
This is expected to be called from within an AsyncIO loop.
"""
if (
hasattr(self, "_thread_executor")
and asyncio_event_loop in self._thread_executor
and self._thread_executor[asyncio_event_loop] is not None
):
return self._thread_executor[asyncio_event_loop]
def close_pool() -> None:
"""Close pool when event loop exits"""
self._thread_executor[asyncio_event_loop].shutdown(wait=True)
del self._thread_executor[asyncio_event_loop]
self._thread_executor.update(
{asyncio_event_loop: get_executor(thread_count=self.max_threads)}
)
asyncio_atexit.register(close_pool)
return self._thread_executor[asyncio_event_loop]
def _get_parallel_file_transfer_semaphore(
self, asyncio_event_loop: asyncio.AbstractEventLoop
) -> asyncio.Semaphore:
"""
Retrieve the semaphore for the Synapse client. Or create a new one if it does
not exist. This semaphore is used to limit the number of files that can actively
enter the uploading/downloading process.
This is expected to be called from within an AsyncIO loop.
By default the number of files that can enter the "uploading" state will be
limited to 2 * max_threads. This is to ensure that the files that are entering
into the "uploading" state will have priority to finish. Additionally, it means
that there should be a good spread of files getting up to the "uploading"
state, entering the "uploading" state, and finishing the "uploading" state.
If we break these states down into large components they would look like:
- Before "uploading" state: HTTP rest calls to retrieve what data Synapse has
- Entering "uploading" state: MD5 calculation and HTTP rest calls to determine
how/where to upload a file to.
- During "uploading" state: Uploading the file to a storage provider.
- After "uploading" state: HTTP rest calls to finalize the upload.
This has not yet been applied to parallel file downloads. That will take place
later on.
"""
if (
hasattr(self, "_parallel_file_transfer_semaphore")
and asyncio_event_loop in self._parallel_file_transfer_semaphore
and self._parallel_file_transfer_semaphore[asyncio_event_loop] is not None
):
return self._parallel_file_transfer_semaphore[asyncio_event_loop]
self._parallel_file_transfer_semaphore.update(
{asyncio_event_loop: asyncio.Semaphore(max(self.max_threads * 2, 1))}
)
return self._parallel_file_transfer_semaphore[asyncio_event_loop]
# initialize logging
def _init_logger(self):
"""
Initialize logging
"""
logger_name = (
SILENT_LOGGER_NAME
if self.silent
else DEBUG_LOGGER_NAME
if self.debug
else DEFAULT_LOGGER_NAME
)
self.logger = logging.getLogger(logger_name)
logging.getLogger("py.warnings").handlers = self.logger.handlers
@classmethod
def get_client(cls, synapse_client: typing.Union[None, "Synapse"]) -> "Synapse":
"""
Convience function to get an instance of 'Synapse'. The latest instance created
by 'login()' or set via `set_client` will be returned.
When 'logout()' is called it will delete the instance.
Arguments:
synapse_client: An instance of 'Synapse' or None. This is used to simplify logical checks
in cases where synapse is passed into them.
Returns:
An instance of 'Synapse'.
Raises:
SynapseError: No Synapse client instance was provided, and no cached
instance is available. Ensure that either an instance is passed as the
`synapse_client` kwarg, or a cached instance is available.
"""
if synapse_client:
return synapse_client
if not cls._synapse_client:
raise SynapseError(
"No Synapse client instance was provided, and no cached instance is available. Ensure that either an instance is passed as the `synapse_client` kwarg, or a cached instance is available."
)
return cls._synapse_client
@staticmethod
def allow_client_caching(allow_client_caching: bool) -> None:
"""Allows for a global setting to enable or disable caching of the Synapse
client object. **If you are working in a multi-user environment you should set
this to False to prevent any possibility of picking up another user session.**
As a consequence of setting this to false you must pass a Synapse class instance
to any function, method, or class that requires it - If if it is marked as
`Optional`.
"""
Synapse._allow_client_caching = allow_client_caching
@staticmethod
def enable_open_telemetry(enable_open_telemetry: bool) -> None:
"""Determines whether OpenTelemetry is enabled for the Synapse client. This is
used to know whether or not this library will automatically kick off the
instruementation of several dependent libraries including:
- threading
- urllib
- requests
- httpx
When OpenTelemetry is enabled it will automatically start the instrumentation
of these libraries. When it is disabled it will automatically stop the
instrumentation of these libraries.
"""
if enable_open_telemetry and not Synapse._enable_open_telemetry:
set_up_tracing(enabled=True)
elif not enable_open_telemetry and Synapse._enable_open_telemetry:
set_up_tracing(enabled=False)
Synapse._enable_open_telemetry = enable_open_telemetry
@classmethod
def set_client(cls, synapse_client) -> None:
cls._synapse_client = synapse_client
@property
def max_threads(self) -> int:
return self._max_threads
@max_threads.setter
def max_threads(self, value: int):
self._max_threads = min(max(value, 1), MAX_THREADS_CAP)
@property
def username(self) -> Union[str, None]:
# for backwards compatability when username was a part of the Synapse object and not in credentials
return self.credentials.username if self.credentials is not None else None
@deprecated(
version="4.4.0",
reason="To be removed in 5.0.0. "
"Moved to synapseclient/api/configuration_services.py::get_config_file",
)
@functools.lru_cache()
def getConfigFile(self, configPath: str) -> configparser.RawConfigParser:
"""
Retrieves the client configuration information.
Arguments:
configPath: Path to configuration file on local file system
Returns:
A RawConfigParser populated with properties from the user's configuration file.
"""
try:
config = configparser.RawConfigParser()
config.read(configPath) # Does not fail if the file does not exist
return config
except configparser.Error as ex:
raise ValueError(
"Error parsing Synapse config file: {}".format(configPath)
) from ex
def setEndpoints(
self,
repoEndpoint: str = None,
authEndpoint: str = None,
fileHandleEndpoint: str = None,
portalEndpoint: str = None,
skip_checks: bool = False,
) -> None:
"""
Sets the locations for each of the Synapse services (mostly useful for testing).
Arguments:
repoEndpoint: Location of synapse repository
authEndpoint: Location of authentication service
fileHandleEndpoint: Location of file service
portalEndpoint: Location of the website
skip_checks: Skip version and endpoint checks
Example: Switching endpoints
To switch between staging and production endpoints
syn.setEndpoints(**synapseclient.client.STAGING_ENDPOINTS)
syn.setEndpoints(**synapseclient.client.PRODUCTION_ENDPOINTS)
"""
endpoints = {
"repoEndpoint": repoEndpoint,
"authEndpoint": authEndpoint,
"fileHandleEndpoint": fileHandleEndpoint,
"portalEndpoint": portalEndpoint,
}
# For unspecified endpoints, first look in the config file
config = get_config_file(self.configPath)
for point in endpoints.keys():
if endpoints[point] is None and config.has_option("endpoints", point):
endpoints[point] = config.get("endpoints", point)
# Endpoints default to production
for point in endpoints.keys():
if endpoints[point] is None:
endpoints[point] = PRODUCTION_ENDPOINTS[point]
# Update endpoints if we get redirected
if not skip_checks:
response = with_retry(
lambda point=point: self._requests_session.get(
endpoints[point],
allow_redirects=False,
headers=synapseclient.USER_AGENT,
),
verbose=self.debug,
**STANDARD_RETRY_PARAMS,
)
if response.status_code == 301:
endpoints[point] = response.headers["location"]
self.repoEndpoint = endpoints["repoEndpoint"]
self.authEndpoint = endpoints["authEndpoint"]
self.fileHandleEndpoint = endpoints["fileHandleEndpoint"]
self.portalEndpoint = endpoints["portalEndpoint"]
def login(
self,
email: str = None,
silent: bool = False,
authToken: str = None,
) -> None:
"""
Valid combinations of login() arguments:
- authToken
If no login arguments are provided or only username is provided, login() will attempt to log in using
information from these sources (in order of preference):
1. .synapseConfig file (in user home folder unless configured otherwise)
2. User defined arguments during a CLI session
3. User's Personal Access Token (aka: Synapse Auth Token)
from the environment variable: SYNAPSE_AUTH_TOKEN
4. Retrieves user's authentication token from AWS SSM Parameter store (if configured)
Arguments:
email: Synapse user name (or an email address associated with a Synapse account)
authToken: A bearer authorization token, e.g. a
[personal access token](https://python-docs.synapse.org/tutorials/authentication/).
silent: Defaults to False. Suppresses the "Welcome ...!" message.
Example: Logging in
Using an auth token:
syn.login(authToken="authtoken")
> Welcome, Me!
Using an auth token and username. The username is optional but verified
against the username in the auth token:
syn.login(email="my-username", authToken="authtoken")
> Welcome, Me!
"""
# Note: the order of the logic below reflects the ordering in the docstring above.
# Check version before logging in
if not self.skip_checks:
version_check()
# Make sure to invalidate the existing session
self.logout()
credential_provider_chain = get_default_credential_chain()
self.credentials = credential_provider_chain.get_credentials(
syn=self,
user_login_args=UserLoginArgs(
email,
authToken,
),
)
# Final check on login success
if not self.credentials:
raise SynapseNoCredentialsError("No credentials provided.")
if not silent:
display_name = self.credentials.displayname or self.credentials.username
self.logger.info(f"Welcome, {display_name}!\n")
@deprecated(
version="4.4.0",
reason="To be removed in 5.0.0. "
"Moved to synapseclient/api/configuration_services.py::get_config_section_dict",
)
def _get_config_section_dict(self, section_name: str) -> Dict[str, str]:
"""
Get a profile section in the configuration file with the section name.
Arguments:
section_name: The name of the profile section in the configuration file
Returns:
A dictionary containing the configuration profile section content
"""
config = get_config_file(self.configPath)
try:
return dict(config.items(section_name))
except configparser.NoSectionError:
# section not present
return {}
@deprecated(
version="4.4.0",
reason="To be removed in 5.0.0. "
"Moved to synapseclient/api/configuration_services.py::get_config_authentication",
)
def _get_config_authentication(self) -> Dict[str, str]:
"""
Get the authentication section of the configuration file.
Returns:
The authentication section of the configuration file
"""
return get_config_section_dict(
section_name=config_file_constants.AUTHENTICATION_SECTION_NAME,
config_path=self.configPath,
)
@deprecated(
version="4.4.0",
reason="To be removed in 5.0.0. "
"Moved to synapseclient/api/configuration_services.py::get_client_authenticated_s3_profile",
)
def _get_client_authenticated_s3_profile(
self, endpoint: str, bucket: str
) -> Dict[str, str]:
"""
Get the authenticated S3 profile from the configuration file.
Arguments:
endpoint: The location of the target service
bucket: AWS S3 bucket name
Returns:
The authenticated S3 profile
"""
config_section = endpoint + "/" + bucket
return get_config_section_dict(
section_name=config_section, config_path=self.configPath
).get("profile_name", "default")
@deprecated(
version="4.4.0",
reason="To be removed in 5.0.0. "
"Moved to synapseclient/api/configuration_services.py::get_transfer_config",
)
def _get_transfer_config(self) -> Dict[str, str]:
"""
Get the transfer profile from the configuration file.
Raises:
ValueError: Invalid max_threads value. Should be equal or less than 16.
ValueError: Invalid use_boto_sts value. Should be true or false.
Returns:
The transfer profile
"""
# defaults
transfer_config = {"max_threads": DEFAULT_NUM_THREADS, "use_boto_sts": False}
for k, v in get_config_section_dict(
section_name="transfer", config_path=self.configPath
).items():
if v:
if k == "max_threads" and v:
try:
transfer_config["max_threads"] = int(v)
except ValueError as cause:
raise ValueError(
f"Invalid transfer.max_threads config setting {v}"
) from cause
elif k == "use_boto_sts":
lower_v = v.lower()
if lower_v not in ("true", "false"):
raise ValueError(
f"Invalid transfer.use_boto_sts config setting {v}"
)
transfer_config["use_boto_sts"] = "true" == lower_v
return transfer_config
def _is_logged_in(self) -> bool:
"""
Test whether the user is logged in to Synapse.
Returns:
Boolean value indicating current user's login status
"""
# This is a quick sanity check to see if credentials have been
# configured on the client
if self.credentials is None:
return False
# The public can query this command so there is no need to try catch.
user = self.restGET("/userProfile")
if user.get("userName") == "anonymous":
return False
return True
def logout(self) -> None:
"""
Removes authentication information from the Synapse client.
Returns:
None
"""
self.credentials = None
@deprecated(
version="4.0.0",
reason="deprecated with no replacement. The client does not support API keys for "
"authentication. Please use a personal access token instead. This method will "
"be removed in a future release.",
)
def invalidateAPIKey(self):
"""
**Deprecated with no replacement.** The client does not support API keys for
authentication. Please use a
[personal access token](https://python-docs.synapse.org/tutorials/authentication/)
instead. This method will be removed in a future release.
Invalidates authentication across all clients.
Returns:
None
"""
# Logout globally
if self._is_logged_in():
self.restDELETE("/secretKey", endpoint=self.authEndpoint)
@functools.lru_cache()
def get_user_profile_by_username(
self,
username: str = None,
sessionToken: str = None,
) -> UserProfile:
"""
Get the details about a Synapse user.
Retrieves information on the current user if 'id' is omitted or is empty string.
Arguments:
username: The userName of a user
sessionToken: The session token to use to find the user profile
Returns:
The user profile for the user of interest.
Example: Using this function
Getting your own profile
my_profile = syn.get_user_profile_by_username()
Getting another user's profile
freds_profile = syn.get_user_profile_by_username('fredcommo')
"""
is_none = username is None
is_str = isinstance(username, str)
if not is_str and not is_none:
raise TypeError("username must be string or None")
if is_str:
principals = self._findPrincipals(username)
for principal in principals:
if principal.get("userName", None).lower() == username.lower():
id = principal["ownerId"]
break
else:
raise ValueError(f"Can't find user '{username}'")
else:
id = ""
uri = f"/userProfile/{id}"
return UserProfile(
**self.restGET(
uri, headers={"sessionToken": sessionToken} if sessionToken else None
)
)
@functools.lru_cache()
def get_user_profile_by_id(
self,
id: int = None,
sessionToken: str = None,
) -> UserProfile:
"""
Get the details about a Synapse user.
Retrieves information on the current user if 'id' is omitted.
Arguments:
id: The ownerId of a user
sessionToken: The session token to use to find the user profile
Returns:
The user profile for the user of interest.
Example: Using this function
Getting your own profile
my_profile = syn.get_user_profile_by_id()
Getting another user's profile
freds_profile = syn.get_user_profile_by_id(1234567)
"""
if id:
if not isinstance(id, int):
raise TypeError("id must be an 'ownerId' integer")
else:
id = ""
uri = f"/userProfile/{id}"
return UserProfile(
**self.restGET(
uri, headers={"sessionToken": sessionToken} if sessionToken else None
)
)
@functools.lru_cache()
def getUserProfile(
self,
id: Union[str, int, UserProfile, TeamMember] = None,