-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy path__main__.py
1906 lines (1710 loc) · 62 KB
/
__main__.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 command line client.
For a description of its usage and parameters, see its documentation:
https://python-docs.synapse.org/build/html/CommandLineClient.html
"""
import argparse
import collections.abc
import csv
import getpass
import json
import logging
import os
import re
import shutil
import signal
import sys
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.resources import SERVICE_NAME, Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter
from opentelemetry.sdk.trace.sampling import ALWAYS_OFF, ALWAYS_ON, ParentBased
import synapseclient
import synapseutils
from synapseclient import Activity
from synapseclient.annotations import Annotations
from synapseclient.core import utils
from synapseclient.core.exceptions import (
SynapseAuthenticationError,
SynapseFileNotFoundError,
SynapseHTTPError,
SynapseNoCredentialsError,
)
from synapseclient.wiki import Wiki
tracer = trace.get_tracer("synapseclient")
def _init_console_logging():
# init a stdout logger for purposes of logging cli activity.
# logging is preferred to writing directly to stdout since it can be
# configured/formatted/suppressed
# but this is not yet universal across the client so it is initialized here
# from cli commands that
# don't still have other direct stdout calls
root = logging.getLogger()
root.setLevel(logging.DEBUG)
handler = logging.StreamHandler(sys.stdout)
handler.setLevel(logging.INFO)
# message only for these cli stdout messages, meant for output directly to be
# viewed by interactive user
formatter = logging.Formatter("%(message)s")
handler.setFormatter(formatter)
root.addHandler(handler)
def query(args, syn):
try:
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
except (AttributeError, ValueError):
# Different OS's have different signals defined. In particular,
# SIGPIPE doesn't exist on Windows. The docs have this to say,
# "On Windows, signal() can only be called with SIGABRT, SIGFPE,
# SIGILL, SIGINT, SIGSEGV, or SIGTERM. A ValueError will be raised
# in any other case."
pass
# TODO: Should use loop over multiple returned values if return is too long
queryString = " ".join(args.queryString)
if re.search("from syn\\d", queryString.lower()):
results = syn.tableQuery(queryString)
reader = csv.reader(open(results.filepath))
for row in reader:
sys.stdout.write("%s\n" % ("\t".join(row)))
else:
sys.stderr.write(
"Input query cannot be parsed. Please see our documentation for "
"writing Synapse query:"
" https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/web/controller/TableExamples.html"
)
def _getIdsFromQuery(queryString, syn, downloadLocation):
"""Helper function that extracts the ids out of returned query."""
if re.search("from syn\\d", queryString.lower()):
tbl = syn.tableQuery(queryString, downloadLocation=downloadLocation)
check_for_id_col = filter(lambda x: x.get("id"), tbl.headers)
assert check_for_id_col, ValueError("Query does not include the id column.")
ids = [x["id"] for x in csv.DictReader(open(tbl.filepath))]
return ids
else:
raise ValueError(
"Input query cannot be parsed. Please see our documentation for "
"writing Synapse query:"
" https://rest-docs.synapse.org/rest/org/sagebionetworks/repo/web/controller/TableExamples.html"
)
@tracer.start_as_current_span("main::get")
def get(args, syn):
syn.multi_threaded = args.multiThreaded
printed_download_message = False
if args.recursive:
if args.version is not None:
raise ValueError(
"You cannot specify a version making a recursive download."
)
_validate_id_arg(args)
synapseutils.syncFromSynapse(
syn,
args.id,
args.downloadLocation,
followLink=args.followLink,
manifest=args.manifest,
)
elif args.queryString is not None:
if args.version is not None or args.id is not None:
raise ValueError(
"You cannot specify a version or id when you are downloading a query."
)
ids = _getIdsFromQuery(args.queryString, syn, args.downloadLocation)
for id in ids:
syn.get(id, downloadLocation=args.downloadLocation)
else:
_validate_id_arg(args)
# search by MD5
if isinstance(args.id, str) and os.path.isfile(args.id):
entity = syn.get(
args.id,
version=args.version,
limitSearch=args.limitSearch,
downloadFile=False,
)
if (
"path" in entity
and entity.path is not None
and os.path.exists(entity.path)
):
syn.logger.info(
"Associated file: %s with synapse ID %s", entity.path, entity.id
)
# normal syn.get operation
else:
entity = syn.get(
args.id,
version=args.version, # limitSearch=args.limitSearch,
followLink=args.followLink,
downloadLocation=args.downloadLocation,
)
if (
"path" in entity
and entity.path is not None
and os.path.exists(entity.path)
):
# The core download functionality of syn.get will print out the message
printed_download_message = True
else:
syn.logger.info(
"WARNING: No files associated with entity %s\n", entity.id
)
syn.logger.info(entity)
if "path" in entity and not printed_download_message:
syn.logger.info("Creating %s", entity.path)
def _validate_id_arg(args):
if args.id is None:
raise ValueError(
f"Missing expected id argument for use with the {args.subparser} command"
)
def manifest(args, syn):
synapseutils.generate_sync_manifest(
syn,
directory_path=args.path,
parent_id=args.parentid,
manifest_path=args.manifest_file,
)
def sync(args, syn):
synapseutils.syncToSynapse(
syn,
manifestFile=args.manifestFile,
dryRun=args.dryRun,
sendMessages=args.sendMessages,
retries=args.retries,
)
def store(args, syn):
# If we are storing a fileEntity we need to have id or parentId
if args.parentid is None and args.id is None and args.file is not None:
raise ValueError(
"synapse store requires at least either parentId or id to be specified."
)
# If both args.FILE and args.file specified raise error
if args.file and args.FILE:
raise ValueError("only specify one file")
if args.type == "File" and not args.file and not args.FILE:
raise ValueError(f"{args.subparser} missing required FILE argument")
_descriptionFile_arg_check(args)
args.file = args.FILE if args.FILE is not None else args.file
args.type = "FileEntity" if args.type == "File" else args.type
# Since force_version defaults to True, negate to determine what
# forceVersion action should be
force_version = not args.noForceVersion
if args.id is not None:
entity = syn.get(args.id, downloadFile=False)
else:
entity = {
"concreteType": "org.sagebionetworks.repo.model.%s" % args.type,
"name": (
utils.guess_file_name(args.file)
if args.file and not args.name
else None
),
"parentId": None,
}
# Overide setting for parameters included in args
entity["name"] = args.name if args.name is not None else entity["name"]
entity["parentId"] = (
args.parentid if args.parentid is not None else entity["parentId"]
)
entity["path"] = args.file if args.file is not None else None
entity["synapseStore"] = not utils.is_url(args.file)
used = syn._convertProvenanceList(args.used, args.limitSearch)
executed = syn._convertProvenanceList(args.executed, args.limitSearch)
entity = syn.store(entity, used=used, executed=executed, forceVersion=force_version)
_create_wiki_description_if_necessary(args, entity, syn)
syn.logger.info("Created/Updated entity: %s\t%s", entity["id"], entity["name"])
# After creating/updating, if there are annotations to add then
# add them
if args.annotations is not None:
# Need to override the args id parameter
setattr(args, "id", entity["id"])
setAnnotations(args, syn)
def _create_wiki_description_if_necessary(args, entity, syn):
"""
store the description in a Wiki
"""
if args.description or args.descriptionFile:
syn.store(
Wiki(
markdown=args.description,
markdownFile=args.descriptionFile,
owner=entity,
)
)
def _descriptionFile_arg_check(args):
"""
checks that descriptionFile(if specified) is a valid file path
"""
if args.descriptionFile:
if not os.path.isfile(args.descriptionFile):
raise ValueError(
"The specified descriptionFile path is not a file or does not exist"
)
def move(args, syn):
"""Moves an entity specified by args.id to args.parentId"""
entity = syn.move(args.id, args.parentid)
syn.logger.info("Moved %s to %s", entity.id, entity.parentId)
def associate(args, syn):
files = []
if args.r:
files = [
os.path.join(dp, f)
for dp, dn, filenames in os.walk(args.path)
for f in filenames
]
if os.path.isfile(args.path):
files = [args.path]
if len(files) == 0:
raise Exception(
(
"The path specified is inaccurate. "
"If it is a directory try using 'associate -r'"
)
)
for fp in files:
try:
ent = syn.get(fp, limitSearch=args.limitSearch)
except SynapseFileNotFoundError:
syn.logger.warning("WARNING: The file %s is not available in Synapse", fp)
else:
syn.logger.info("%s.%i\t%s", ent.id, ent.versionNumber, fp)
def copy(args, syn):
mappings = synapseutils.copy(
syn,
args.id,
args.destinationId,
skipCopyWikiPage=args.skipCopyWiki,
skipCopyAnnotations=args.skipCopyAnnotations,
excludeTypes=args.excludeTypes,
version=args.version,
updateExisting=args.updateExisting,
setProvenance=args.setProvenance,
)
syn.logger.info(mappings)
def cat(args, syn):
try:
signal.signal(signal.SIGPIPE, signal.SIG_DFL)
except (AttributeError, ValueError):
# Different OS's have different signals defined. In particular,
# SIGPIPE doesn't exist one Windows. The docs have this to say,
# "On Windows, signal() can only be called with SIGABRT, SIGFPE,
# SIGILL, SIGINT, SIGSEGV, or SIGTERM. A ValueError will be raised
# in any other case."
pass
entity = syn.get(args.id, version=args.version)
if "path" in entity:
with open(entity.path) as inputfile:
for line in inputfile:
sys.stdout.write(line)
@tracer.start_as_current_span("main::ls")
def ls(args, syn: synapseclient.Synapse):
"""List entities in a Project or Folder"""
syn._list(
args.id,
recursive=args.recursive,
long_format=args.long,
show_modified=args.modified,
)
def show(args, syn):
"""Show metadata for an entity."""
ent = syn.get(args.id, downloadFile=False)
syn.printEntity(ent)
syn.logger.info("Provenance:")
try:
prov = syn.getProvenance(ent)
syn.logger.info(prov)
except SynapseHTTPError:
syn.logger.exception("No Activity specified.")
def delete(args, syn):
if args.version:
syn.delete(args.id, args.version)
syn.logger.info("Deleted entity %s, version %s", args.id, args.version)
else:
syn.delete(args.id)
syn.logger.info("Deleted entity: %s", args.id)
def create(args, syn):
_descriptionFile_arg_check(args)
entity = {
"name": args.name,
"concreteType": "org.sagebionetworks.repo.model.%s" % args.type,
}
if args.parentid is not None:
entity["parentId"] = args.parentid
entity = syn.store(entity)
_create_wiki_description_if_necessary(args, entity, syn)
syn.logger.info("Created entity: %s\t%s\n", entity["id"], entity["name"])
def onweb(args, syn):
syn.onweb(args.id)
def setProvenance(args, syn):
"""Set provenance information on a synapse entity."""
activity = Activity(name=args.name, description=args.description)
if args.used:
for item in syn._convertProvenanceList(args.used, args.limitSearch):
activity.used(item)
if args.executed:
for item in syn._convertProvenanceList(args.executed, args.limitSearch):
activity.used(item, wasExecuted=True)
activity = syn.setProvenance(args.id, activity)
# Display the activity record, if -o or -output specified
if args.output:
if args.output == "STDOUT":
sys.stdout.write(json.dumps(activity))
sys.stdout.write("\n")
else:
with open(args.output, "w") as f:
f.write(json.dumps(activity))
f.write("\n")
else:
syn.logger.info(
"Set provenance record %s on entity %s\n", str(activity["id"]), str(args.id)
)
def getProvenance(args, syn):
activity = syn.getProvenance(args.id, args.version)
if args.output is None or args.output == "STDOUT":
syn.logger.info(json.dumps(activity, sort_keys=True, indent=2))
else:
with open(args.output, "w") as f:
f.write(json.dumps(activity))
f.write("\n")
def setAnnotations(args, syn):
"""Method to set annotations on an entity.
Requires a JSON-formatted string that evaluates to a dict.
Annotations can be updated or overwritten completely.
"""
try:
newannots = json.loads(args.annotations)
except Exception as e:
sys.stderr.write(
"Please check that your JSON string is properly formed and evaluates to a "
"dictionary (key/value pairs). For example, to set an annotations called "
'\'foo\' to the value 1, the format should be \'{"foo": 1, "bar":"quux"}\'.'
)
raise e
if type(newannots) is not dict:
raise TypeError(
"Please check that your JSON string is properly formed and evaluates to a "
"dictionary (key/value pairs). For example, to set an annotations called "
'\'foo\' to the value 1, the format should be \'{"foo": 1, "bar":"quux"}\'.'
)
annots = syn.get_annotations(args.id)
if args.replace:
annots = Annotations(annots.id, annots.etag, newannots)
else:
annots.update(newannots)
syn.set_annotations(annots)
sys.stderr.write("Set annotations on entity %s\n" % (args.id,))
def getAnnotations(args, syn):
annotations = syn.get_annotations(args.id)
if args.output is None or args.output == "STDOUT":
syn.logger.info(json.dumps(annotations, sort_keys=True, indent=2))
else:
with open(args.output, "w") as f:
f.write(json.dumps(annotations))
f.write("\n")
def storeTable(args, syn):
"""Store table given csv"""
table = synapseclient.table.build_table(args.name, args.parentid, args.csv)
table_ent = syn.store(table)
syn.logger.info('{"tableId": "%s"}', table_ent.tableId)
def _replace_existing_config(path, auth_section):
# insert the auth section into the existing config file
# always make a backup of the existing config file,
# but don't overwrite an existing backup
i = 1
cur_config_path = os.path.dirname(os.path.realpath(path))
while True:
copy_filename = f"{path}.backup{i if i > 1 else ''}"
copy_to = os.path.join(cur_config_path, copy_filename)
if not os.path.exists(copy_to):
shutil.copyfile(path, copy_to)
break
i += 1
# find the existing authentication section, we'll replace it wholly with an updated
# section with the new values.
with open(path, "r") as config_o:
config_text = config_o.read()
matcher = re.search(
r"^[ \t]*(\[authentication\].*?)(^[ \t]*\[|\Z)",
config_text,
flags=re.MULTILINE | re.DOTALL,
)
if matcher:
# we matched an existing authentication section
new_config_text = (
config_text[: matcher.start(1)]
+ auth_section
+ config_text[matcher.end(1) :]
)
else:
# weren't able to find an authentication section so
# we write a new authentication section at the start of the file
new_config_text = auth_section + "\n\n" + config_text
return new_config_text
def _generate_new_config(auth_section):
# insert the auth section into the default config template file
script_dir = os.path.dirname(os.path.realpath(__file__))
with open(os.path.join(script_dir, ".synapseConfig"), "r") as config_o:
config_text = config_o.read()
# Replace text in configuration
new_config_text = re.sub(
r"#\[authentication\].*<authtoken>",
auth_section,
config_text,
flags=re.MULTILINE | re.DOTALL,
)
return new_config_text
@tracer.start_as_current_span("main::config")
def config(args, syn):
"""Create/modify a synapse configuration file"""
user, secret = _prompt_for_credentials()
# validate the credentials provided and determine what login
# mechanism was used (authToken)
# this means that writing a config requires connectivity
# (and that the endpoints in the current config point to
# the endpoints of the credentials)
login_key = _authenticate_login(syn, user, secret, silent=True)
auth_section = "[authentication]\n"
if user:
auth_section += f"username={user}\n"
auth_section += f"{login_key.lower()}={secret}\n\n"
if os.path.exists(args.configPath):
config_text = _replace_existing_config(args.configPath, auth_section)
else:
config_text = _generate_new_config(auth_section)
with open(args.configPath, "w") as config_o:
config_o.write(config_text)
def submit(args, syn):
"""
Method to allow challenge participants to submit to an evaluation queue.
Examples::
synapse submit --evaluation 'ra_challenge_Q1_leaderboard' -f ~/testing/testing.txt \
--parentId syn2345030 --used syn2351967 --executed syn2351968
synapse submit --evaluation 2343117 -f ~/testing/testing.txt --parentId syn2345030 \
--used syn2351967 --executed syn2351968
"""
# check if evaluation is a number, if so it is assumed to be a evaluationId else
# it is a evaluationName
if args.evaluation is not None:
try:
args.evaluationID = str(int(args.evaluation))
except ValueError:
args.evaluationName = args.evaluation
# checking if user has entered a evaluation ID or evaluation Name
if args.evaluationID is None and args.evaluationName is None:
raise ValueError("Evaluation ID or Evaluation Name is required\n")
elif args.evaluationID is not None and args.evaluationName is not None:
sys.stderr.write(
"[Warning]: Both Evaluation ID & Evaluation Name are specified \n "
"EvaluationID will be used\n"
)
elif args.evaluationID is None: # get evalID from evalName
try:
args.evaluationID = syn.getEvaluationByName(args.evaluationName)["id"]
except Exception:
raise ValueError(
"Could not find an evaluation named: %s \n" % args.evaluationName
)
# checking if a entity id or file was specified by the user
if args.entity is None and args.file is None:
raise ValueError("Either entityID or filename is required for a submission\n")
elif args.entity is not None and args.file is not None:
sys.stderr.write(
"[Warning]: Both entityID and filename are specified \n "
"entityID will be used\n"
)
elif (
args.entity is None
): # upload the the file to synapse and get synapse entity id for the file
if args.parentid is None:
raise ValueError("parentID required with a file upload\n")
if not os.path.exists(args.file):
raise IOError("file path %s not valid \n" % args.file)
# //ideally this should be factored out
synFile = syn.store(
synapseclient.File(path=args.file, parent=args.parentid),
used=syn._convertProvenanceList(args.used, args.limitSearch),
executed=syn._convertProvenanceList(args.executed, args.limitSearch),
)
args.entity = synFile.id
submission = syn.submit(
args.evaluationID, args.entity, name=args.name, team=args.teamName
)
sys.stdout.write(
"Submitted (id: %s) entity: %s\t%s to Evaluation: %s\n"
% (
submission["id"],
submission["entityId"],
submission["name"],
submission["evaluationId"],
)
)
def get_download_list(args, syn: synapseclient.Synapse) -> None:
"""Download files from the Synapse download cart"""
manifest_path = syn.get_download_list(downloadLocation=args.downloadLocation)
syn.logger.info(f"Manifest file: {manifest_path}")
@tracer.start_as_current_span("main::login")
def login(args, syn: synapseclient.Synapse) -> None:
"""Log in to Synapse"""
login_with_prompt(
syn,
args.synapseUser,
args.synapse_auth_token,
)
profile = syn.getUserProfile()
syn.logger.info(
f"Logged in as: {profile.get('userName', '')} "
f"({profile.get('ownerId', '')})\n\n"
"Use `synapse config` to create or modify a Synapse configuration file. "
"This will allow all commands to authenticate without passing in an Auth Token.\n"
"`synapse login` is only used to verify your credentials are valid to login."
)
def test_encoding() -> None:
"""Test character encoding to help diagnose problems"""
import locale
import platform
print("python version = ", platform.python_version())
print(
"sys.stdout.encoding = ",
(
sys.stdout.encoding
if hasattr(sys.stdout, "encoding")
else "no encoding attribute"
),
)
print("sys.stdout.isatty() = ", sys.stdout.isatty())
print("locale.getpreferredencoding() =", locale.getpreferredencoding())
print("sys.getfilesystemencoding() = ", sys.getfilesystemencoding())
print("PYTHONIOENCODING = ", os.environ.get("PYTHONIOENCODING", None))
print("latin1 chars = D\xe9j\xe0 vu, \xfcml\xf8\xfats")
print(
"Some non-ascii chars = '\u0227\u0188\u0188\u1e17\u019e\u0167\u1e17\u1e13 u\u028dop-\u01ddp\u0131sdn "
"\u0167\u1e17\u1e8b\u0167 \u0192\u01ff\u0159 \u0167\u1e17\u015f\u0167\u012b\u019e\u0260'",
)
def get_sts_token(args, syn):
"""Get an STS storage token for use with the given folder"""
# output is either a dictionary of keys or a string consisting of shell commands
# serialize dictionaries, and pass strings through as they are
resp = syn.get_sts_storage_token(
args.id, args.permission, output_format=args.output
)
if isinstance(resp, collections.abc.Mapping):
sts_string = json.dumps(resp)
else:
sts_string = str(resp)
syn.logger.info(sts_string)
def migrate(args, syn):
"""Migrate Synapse entities to a new storage location"""
_init_console_logging()
result = synapseutils.index_files_for_migration(
syn,
args.id,
args.dest_storage_location_id,
args.db_path,
source_storage_location_ids=args.source_storage_location_ids,
file_version_strategy=args.file_version_strategy,
include_table_files=args.include_table_files,
continue_on_error=args.continue_on_error,
)
counts = result.get_counts_by_status()
indexed_count = counts["INDEXED"]
already_migrated_count = counts["ALREADY_MIGRATED"]
errored_count = counts["ERRORED"]
logging.info(
f"Indexed {indexed_count + already_migrated_count} items, {indexed_count} "
f"needing migration, {already_migrated_count} already stored in destination "
f"storage location ({args.dest_storage_location_id}). "
f"Encountered {errored_count} errors.",
)
if indexed_count == 0:
logging.info("No files found needing migration.")
elif args.dryRun:
logging.info(
f"Dry run, index created at {args.db_path} but "
"skipping migration. Can proceed with "
"migration by running the same command without the dry run option."
)
else:
# there are items to migrate and this is not a dry run, proceed with migration
result = synapseutils.migrate_indexed_files(
syn,
args.db_path,
create_table_snapshots=True,
continue_on_error=args.continue_on_error,
force=args.force,
)
if result:
# result is None if not using the arg and the user declined to
# continue with the migration
counts = result.get_counts_by_status()
migrated_count = counts["MIGRATED"]
errored_count = counts["ERRORED"]
logging.info(
"Completed migration of %s. %s files migrated. %s errors encountered",
args.id,
migrated_count,
errored_count,
)
if args.csv_log_path:
logging.info("Writing csv log to %s", args.csv_log_path)
result.as_csv(args.csv_log_path)
def build_parser():
"""Builds the argument parser and returns the result."""
USED_HELP = (
"Synapse ID, a url, or a local file path (of a file previously"
"uploaded to Synapse) from which the specified entity is derived"
)
EXECUTED_HELP = (
"Synapse ID, a url, or a local file path (of a file previously"
"uploaded to Synapse) that was executed to generate the specified entity"
)
parser = argparse.ArgumentParser(
description="Interfaces with the Synapse repository."
)
parser.add_argument(
"--version",
action="version",
version="Synapse Client %s" % synapseclient.__version__,
)
parser.add_argument(
"-u",
"--username",
dest="synapseUser",
help="Username used to connect to Synapse",
)
parser.add_argument(
"-p",
"--password",
dest="synapse_auth_token",
help="Personal Access Token (aka: Synapse Auth Token) used to connect to Synapse.",
)
parser.add_argument(
"-c",
"--configPath",
dest="configPath",
default=synapseclient.client.CONFIG_FILE,
help="Path to configuration file used to connect to Synapse "
"[default: %(default)s]",
)
parser.add_argument(
"--debug",
dest="debug",
action="store_true",
help="Set to debug mode, additional output and error messages are printed to "
"the console",
)
parser.add_argument(
"--silent",
dest="silent",
action="store_true",
help='"Set to silent mode, console output is suppressed"',
)
parser.add_argument(
"-s",
"--skip-checks",
dest="skip_checks",
action="store_true",
help="suppress checking for version upgrade messages and endpoint redirection",
)
parser.add_argument(
"--otel",
type=str,
dest="otel",
choices=["console", "otlp"],
help="enabled the usage of OpenTelemetry for tracing",
)
subparsers = parser.add_subparsers(
title="commands",
dest="subparser",
description="The following commands are available:",
help='For additional help: "synapse <COMMAND> -h"',
)
parser_get = subparsers.add_parser("get", help="downloads a file from Synapse")
parser_get.add_argument(
"-q",
"--query",
metavar="queryString",
dest="queryString",
type=str,
default=None,
help="Optional query parameter, will fetch all of the entities returned by a "
"query (see query for help).",
)
parser_get.add_argument(
"-v",
"--version",
metavar="VERSION",
type=int,
default=None,
help="Synapse version number of entity to retrieve. Defaults to most "
"recent version.",
)
parser_get.add_argument(
"-r",
"--recursive",
action="store_true",
default=False,
help="Fetches content in Synapse recursively contained in the parentId "
"specified by id.",
)
parser_get.add_argument(
"--followLink",
action="store_true",
default=False,
help="Determines whether the link returns the target Entity.",
)
parser_get.add_argument(
"--limitSearch",
metavar="projId",
type=str,
help="Synapse ID of a container such as project or folder to limit search for "
"files if using a path.",
)
parser_get.add_argument(
"--downloadLocation",
metavar="path",
type=str,
default="./",
help="Directory to download file to [default: %(default)s].",
)
parser_get.add_argument(
"--multiThreaded",
action="store_true",
default=True,
help="Download file using a multiple threaded implementation. "
"This flag will be removed in the future when multi-threaded download "
"is deemed fully stable and becomes the default implementation.",
)
parser_get.add_argument(
"id",
metavar="local path",
nargs="?",
type=str,
help="Synapse ID of form syn123 of desired data object.",
)
# add no manifest option
parser_get.add_argument(
"--manifest",
type=str,
choices=["all", "root", "suppress"],
default="all",
help="Determines whether creating manifest file automatically.",
)
parser_get.set_defaults(func=get)
parser_manifest = subparsers.add_parser(
"manifest", help="Generate manifest for uploading directory tree to Synapse."
)
parser_manifest.add_argument(
"path",
metavar="PATH",
type=str,
help="A path to a file or folder whose manifest will be generated.",
)
parser_manifest.add_argument(
"--parent-id",
metavar="syn123",
type=str,
required=True,
dest="parentid",
help="Synapse ID of project or folder where to upload data.",
)
parser_manifest.add_argument(
"--manifest-file",
metavar="OUTPUT",
help="A TSV output file path where the generated manifest is stored. "
"(default: stdout)",
)
parser_manifest.set_defaults(func=manifest)
parser_sync = subparsers.add_parser(
"sync", help="Synchronize files described in a manifest to Synapse"
)
parser_sync.add_argument(
"--dryRun",
action="store_true",
default=False,
help="Perform validation without uploading.",
)
parser_sync.add_argument(
"--sendMessages",
action="store_true",
default=False,
help="Send notifications via Synapse messaging (email) at specific intervals, "
"on errors and on completion.",
)
parser_sync.add_argument("--retries", metavar="INT", type=int, default=4)
parser_sync.add_argument(
"manifestFile",
metavar="FILE",
type=argparse.FileType("r"),
help=(
"A tsv file with file locations and metadata to be pushed to Synapse. "
"See https://python-docs.synapse.org/build/html/articles/synapseutils.html?highlight=synapseutils#synapseutils.sync.syncToSynapse "
"for details on the format of a manifest."
),
)
parser_sync.set_defaults(func=sync)
parser_store = subparsers.add_parser(
"store", # Python 3.2+ would support alias=['store']
help="uploads and adds a file to Synapse",
)
parent_id_group = parser_store.add_mutually_exclusive_group(required=True)
parent_id_group.add_argument(
"--parentid",
"--parentId",
metavar="syn123",
type=str,
required=False,
dest="parentid",