-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathbackends.py
1623 lines (1354 loc) · 61.4 KB
/
backends.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
import os
import json
from pathlib import PurePosixPath, PurePath
import idlib
import augpathlib as aug
from augpathlib import PathMeta
from pyontutils.utils import Async, deferred
from sparcur import exceptions as exc
from sparcur.utils import log, logd, BlackfynnId, PennsieveId
from sparcur.config import auth
class BlackfynnRemote(aug.RemotePath):
_remote_type = 'blackfynn'
_id_class = BlackfynnId
_api_class = None # set in _setup
_async_rate = None
_local_dataset_name = object()
_exclude_uploaded = False
_base_uri_human = 'https://app.blackfynn.io' # FIXME hardcoded
_base_uri_api = 'https://api.blackfynn.io' # FIXME hardcoded
#_base_uri # FIXME TODO
def __new__(cls, *args, **kwargs):
return super().__new__(cls)
_renew = __new__
def __new__(cls, *args, **kwargs):
cls._setup(*args, **kwargs)
return super().__new__(cls)
@classmethod
def init(cls, *args, **kwargs):
cls._setup(*args, **kwargs)
super().init(*args, **kwargs)
@staticmethod
def _setup(*args, **kwargs):
if BlackfynnRemote.__new__ == BlackfynnRemote._renew:
return # we already ran the imports here
import requests
BlackfynnRemote._requests = requests
# FIXME there should be a better way ...
from sparcur.blackfynn_api import BFLocal, id_to_type
BlackfynnRemote._api_class = BFLocal
BlackfynnRemote._id_to_type = staticmethod(id_to_type)
BlackfynnRemote.__new__ = BlackfynnRemote._renew
from blackfynn import Collection, DataPackage, Organization, File
from blackfynn import Dataset
from blackfynn.models import BaseNode
Dataset._id_to_type = staticmethod(id_to_type)
BlackfynnRemote._Collection = Collection
BlackfynnRemote._DataPackage = DataPackage
BlackfynnRemote._Organization = Organization
BlackfynnRemote._File = File
BlackfynnRemote._Dataset = Dataset
BlackfynnRemote._BaseNode = BaseNode
@property
def uri_human(self):
# org /datasets/ N:dataset /files/ N:collection
# org /datasets/ N:dataset /files/ wat? /N:package # opaque but consistent id??
# org /datasets/ N:dataset /viewer/ N:package
if not self.is_absolute():
self = self.resolve() # relative paths should not have to fail here
oid = self.organization.identifier
did = self._id_class(self.dataset_id)
return self.identifier.uri_human(organization=oid,
dataset=did)
#return self.dataset.uri_human + prefix + id
@property
def uri_api(self):
return self.identifier.uri_api
@property
def errors(self):
yield from self._errors
if self.remote_in_error:
yield 'remote-error'
if self.state == 'UNAVAILABLE':
yield 'remote-unavailable'
@property
def remote_in_error(self):
return self.state == 'ERROR'
@property
def state(self):
if hasattr(self.bfobject, 'state'):
return self.bfobject.state
@staticmethod
def get_file(package, file_id):
files = package.files
if len(files) > 1:
log.critical(f'MORE THAN ONE FILE IN PACKAGE {package.id}')
for file in files:
if file.id == file_id:
return file
else:
msg = f'{package} has no file with id {file_id} but has:\n{files}'
raise FileNotFoundError(msg)
@classmethod
def get_file_url(cls, id, file_id):
if file_id is not None:
return cls._api.get_file_url(id, file_id)
@classmethod
def get_file_by_id(cls, id, file_id, ranges=tuple()):
url = cls.get_file_url(id, file_id)
yield from cls.get_file_by_url(url, ranges=ranges)
@classmethod
def get_file_by_url(cls, url, ranges=tuple()):
""" NOTE THAT THE FIRST YIELD IS HEADERS
valid ranges are (start,) (-start,) (start, end)
"""
kwargs = {}
if ranges:
# TODO validate probably
range_spec = ', '.join(
(str(r[0]) if r[0] < 0 else f'{r[0]}-')
if len(r) == 1 else '-'.join(str(se) for se in r)
for r in ranges)
kwargs['headers'] = {'Range': f'bytes={range_spec}'}
resp = cls._requests.get(url, stream=True, **kwargs)
headers = resp.headers
yield headers
log.debug(f'reading from {url}')
for chunk in resp.iter_content(chunk_size=4096): # FIXME align chunksizes between local and remote
if chunk:
yield chunk
def __init__(self, id_bfo_or_bfr, *, file_id=None, cache=None, local_only=False):
self._seed = id_bfo_or_bfr
if isinstance(self._seed, self._id_class):
if self._seed.file_id is not None:
if file_id is not None:
if self._seed.file_id != file_id:
msg = f'file_id mismatch! {self._seed.file_id} != {file_id}'
raise ValueError(msg)
file_id = self._seed.file_id
self._file_id = file_id
if not [type_ for type_ in (self.__class__,
self._BaseNode,
str,
PathMeta,
self._id_class,)
if isinstance(self._seed, type_)]:
raise TypeError(self._seed)
if cache is not None:
self._cache_setter(cache, update_meta=False)
self._errors = []
self._local_only = local_only
def bfobject_retry(self):
""" try to load a local only id again """
if hasattr(self, '_bfobject') and self._bfobject.id == self._local_dataset_name:
stored = self._bfobject
delattr(self, '_bfobject')
try:
self.bfobject
except BaseException as e:
self._bfobject = stored
raise e
return self._bfobject
@property
def bfobject(self):
if hasattr(self, '_bfobject'):
return self._bfobject
if isinstance(self._seed, self.__class__):
bfobject = self._seed.bfobject
elif isinstance(self._seed, self._BaseNode):
bfobject = self._seed
elif (isinstance(self._seed, str) or
isinstance(self._seed, self._id_class)):
if isinstance(self._seed, self._id_class):
_seed = self._seed.id # FIXME sadly this is the least bad place to do this :/
else:
_seed = self._seed
try:
bfobject = self._api.get(_seed)
except Exception as e: # sigh
if self._local_only:
_class = self._id_to_type(_seed)
if issubclass(_class, self._Dataset):
bfobject = _class(self._local_dataset_name)
bfobject.id = _seed
else:
raise NotImplementedError(f'{_class}') from e
elif (not hasattr(self, '_api') and
_seed.startswith('N:organization:')):
self.__class__.init(_seed)
return self.bfobject
else:
raise e
elif isinstance(self._seed, PathMeta):
bfobject = self._api.get(self._seed.id)
else:
raise TypeError(self._seed)
if hasattr(bfobject, '_json'):
# constructed from a packages query
# which we need in order for things to be fastish
self._bfobject = bfobject
return self._bfobject
if isinstance(bfobject, self._DataPackage):
def transfer(file, bfobject):
file.parent = bfobject.parent
file.dataset = bfobject.dataset
file.state = bfobject.state
file.package = bfobject
return file
files = bfobject.files
parent = bfobject.parent
if files:
if self._file_id is not None:
for file in files:
if file.id == self._file_id:
bfobject = transfer(file, bfobject)
elif len(files) > 1:
log.critical(f'MORE THAN ONE FILE IN PACKAGE {bfobject.id}')
if (len(set(f.size for f in files)) == 1 and
len(set(f.name for f in files)) == 1):
log.critical('Why are there multiple files with the same name and size here?')
file = files[0]
bfobject = transfer(file, bfobject)
else:
msg = f'There are actually multiple files ...\n{files}'
log.critical(msg)
else:
file = files[0]
bfobject = transfer(file, bfobject)
bfobject.parent = parent # sometimes we will just reset a parent to itself
else:
log.warning(f'No files in package {bfobject.id}')
self._bfobject = bfobject
return self._bfobject
def is_anchor(self):
return self.anchor == self
@property
def anchor(self):
""" NOTE: this is a slight depature from the semantics in pathlib
because this returns the path representation NOT the string """
return self.organization
@property
def organization(self):
# organization is the root in this system so
# we do not want to depend on parent to look this up
# nesting organizations is file, but we need to know
# what the 'expected' root is independent of the actual root
# because if you have multiple virtual trees on top of the
# same file system then you need to know the root for
# your current tree assuming that the underlying ids
# can be reused (as in something like dat)
if not hasattr(self.__class__, '_organization'):
self.__class__._organization = self.__class__(
self._api.organization)
return self._organization
def is_organization(self):
return isinstance(self.bfobject, self._Organization)
def is_dataset(self):
return isinstance(self.bfobject, self._Dataset)
@property
def dataset_id(self):
""" save a network transit if we don't need it """
dataset = self._bfobject.dataset
if isinstance(dataset, str):
return dataset
else:
return dataset.id
@property
def dataset(self):
remote = self.__class__(self.dataset_id)
remote.cache_init()
return remote
def get_child_by_id(self, id):
for c in self.children:
if c.id == id:
return c
@property
def from_packages(self):
return hasattr(self.bfobject, '_json')
@property
def stem(self):
name = PurePosixPath(self._name)
return name.stem
@property
def suffix(self):
# FIXME loads of shoddy logic in here
name = PurePosixPath(self._name)
if isinstance(self.bfobject, self._File) and not self.from_packages:
return name.suffix
elif isinstance(self.bfobject, self._Collection):
return ''
elif isinstance(self.bfobject, self._Dataset):
return ''
elif isinstance(self.bfobject, self._Organization):
return ''
else:
if self.from_packages or not list(self.errors):
# still needed for cache.children when remote data is in error
msg = 'should not be needed anymore when using packages'
raise NotImplementedError(msg)
else:
log.warning(f'suffix needed for some reason on {self.uri_api}')
if hasattr(self.bfobject, 'type'):
type = self.bfobject.type.lower() # FIXME ... can we match s3key?
else:
type = None
not_ok_types = ('unknown', 'unsupported', 'generic', 'genericdata')
if type not in not_ok_types:
pass
elif hasattr(self.bfobject, 'properties'):
for p in self.bfobject.properties:
if p.key == 'subtype':
type = p.value.replace(' ', '').lower()
break
return ('.' + type) if type is not None else ''
@property
def _name(self):
name = self.bfobject.name
if isinstance(self.bfobject, self._File) and not self.from_packages:
realname = os.path.basename(self.bfobject.s3_key)
if name != realname: # mega weirdness
if realname.startswith(name):
name = realname
else:
realpath = PurePath(realname)
namepath = PurePath(name)
if namepath.suffixes:
log.critical(f'sigh {namepath!r} -?-> {realpath!r}')
else:
path = namepath
for suffix in realpath.suffixes:
path = path.with_suffix(suffix)
old_name = name
name = path.as_posix()
log.info(f'name {old_name} -> {name}')
if '/' in name:
bads = ','.join(f'{i}' for i, c in enumerate(name) if c == '/')
self._errors.append(f'slashes {bads}')
logd.critical(f'Forward slash in name for {self}')
name = name.replace('/', '_')
self.bfobject.name = name # AND DON'T BOTHER US AGAIN
if name.endswith(' '): # breaks paths on windows
self._errors.append(f'trailing whitespace in {name!r}')
log.critical(f'Trailing whitespace in name for {self}')
name = name.rstrip()
self.bfobject.name = name # AND DON'T BOTHER US AGAIN
return name
@property
def name(self):
bfo = self.bfobject
if isinstance(bfo, self._File) and self.from_packages:
#breakpoint()
# at some point in time the blackfynn process that dumps
# data into whatever is returned by the /packages endpoint
# changed without warning, so there are two different
# schemas implicit in the data returned by the endpoint
# the way we work around the issue is to compare filename
# and name to see if name has a suffix and whether the
# suffixes match, there is a performance cost due to
# having to repeatedly check the same files over and over
# again, but at least this way we can determine whether
# there is a fixed date that we could use as a proxy
f = self.bfobject.filename
n = self.bfobject.name
pf = PurePath(f)
pn = PurePath(n)
sf = pf.suffix
sn = pn.suffix
if (sf and not sn or
sn and sf != sn or
not sf and not sn):
#name.suffix
#name.suffix.suffix
#name.other <<< this case is annoying
#name.other.suffix
return f
#elif sf == sn and len(pf.suffixes) > 1:
#return n
else:
log.debug('New /packages schema detected')
return n
else:
return self.stem + self.suffix
@property
def id(self):
if isinstance(self._seed, self.__class__):
id = self._seed.bfobject.id
elif isinstance(self._seed, self._BaseNode):
if isinstance(self._seed, self._File):
id = self._seed.pkg_id
else:
id = self._seed.id
elif isinstance(self._seed, str):
id = self._seed
elif isinstance(self._seed, PathMeta):
id = self._seed.id
elif isinstance(self._seed, self._id_class):
id = self._seed.id
else:
raise TypeError(self._seed)
# FIXME we can't return BlackfynnId here due to the fact that
# augpathlib assumes that RemotePath.id is a string
return str(id)
@property
def identifier(self):
return BlackfynnId(self.id)
@property
def doi(self):
try:
blob = self.bfobject.doi
#print(blob)
if blob:
return idlib.Doi(blob['doi'])
except exc.NoRemoteFileWithThatIdError as e:
# FIXME crumping datasets here is bad, but so is going to network for this :/
log.exception(e)
if self.cache is not None and self.cache.exists():
self.cache.crumple()
@property
def size(self):
if isinstance(self.bfobject, self._File):
return self.bfobject.size
@property
def created(self):
if not isinstance(self.bfobject, self._Organization):
return self.bfobject.created_at
@property
def updated(self):
if not isinstance(self.bfobject, self._Organization):
return self.bfobject.updated_at
@property
def file_id(self):
if isinstance(self.bfobject, self._File):
return self.bfobject.id
@property
def old_id(self):
return None
def exists(self):
try:
bfo = self.bfobject
if not isinstance(bfo, self._BaseNode):
_cache = bfo.refresh(force=True)
bf = _cache.remote.bfo
return bfo.exists
except exc.NoRemoteFileWithThatIdError as e:
return False
def is_dir(self):
try:
bfo = self.bfobject
return not isinstance(bfo, self._File) and not isinstance(bfo, self._DataPackage)
except Exception as e:
breakpoint()
raise e
def is_file(self):
bfo = self.bfobject
return (isinstance(bfo, self._File) or
isinstance(bfo, self._DataPackage) and
(hasattr(bfo, 'fake_files') and bfo.fake_files
or
not hasattr(bfo, '_json') and
not (not log.warning('going to network for files') and self._has_remote_files())
# massively inefficient but probably shouldn't get here?
))
def _has_remote_files(self):
""" this will fetch """
bfobject = self.bfobject
if not isinstance(bfobject, self._DataPackage):
return False
files = bfobject.files
if not files:
return False
if len(files) > 1:
log.critical(f'{self} has more than one file! Not switching bfobject!')
return True
file, = files
file.parent = bfobject.parent
file.dataset = bfobject.dataset
file.package = bfobject
self._bfobject = file
return True
@property
def checksum(self): # FIXME using a property is inconsistent with LocalPath
if hasattr(self.bfobject, 'checksum'):
checksum = self.bfobject.checksum
if checksum and '-' not in checksum:
return bytes.fromhex(checksum)
@property
def etag(self):
""" NOTE returns checksum, count since it is an etag"""
# FIXME rename to etag in the event that we get proper checksumming ??
if hasattr(self.bfobject, 'checksum'):
checksum = self.bfobject.checksum
if checksum and '-' in checksum:
log.debug(checksum)
if isinstance(checksum, str):
checksum, strcount = checksum.rsplit('-', 1)
count = int(strcount)
#if checksum[-2] == '-': # these are 34 long, i assume the -1 is a check byte?
#return bytes.fromhex(checksum[:-2])
return bytes.fromhex(checksum), count
@property
def chunksize(self):
if hasattr(self.bfobject, 'chunksize'):
return self.bfobject.chunksize
@property
def owner_id(self):
if not isinstance(self.bfobject, self._Organization):
# This seems like an oversight ...
return self.bfobject.owner_id
@property
def parent(self):
if hasattr(self, '_c_parent'):
# WARNING staleness could occure because of this
# wow does it save on the network roundtrips
# for rchildren though
return self._c_parent
if isinstance(self.bfobject, self._Organization):
return self # match behavior of Path
elif isinstance(self.bfobject, self._Dataset):
return self.organization
#parent = self.bfobject._api._context
else:
parent = self.bfobject.parent
if parent is None:
parent = self.bfobject.dataset
if parent:
parent_cache = (
self.cache.parent if self.cache is not None else None)
self._c_parent = self.__class__(parent, cache=parent_cache)
return self._c_parent
@property
def children(self):
yield from self._children()
def _children(self, create_cache=True):
if isinstance(self.bfobject, self._File):
return
elif isinstance(self.bfobject, self._DataPackage):
return # we conflate data packages and files
elif isinstance(self.bfobject, self._Organization):
for dataset in self.bfobject.datasets:
child = self.__class__(dataset)
if create_cache:
self.cache / child # construction will cause registration without needing to assign
assert child.cache
yield child
else:
for bfobject in self.bfobject:
child = self.__class__(bfobject)
if create_cache:
self.cache / child # construction will cause registration without needing to assign
assert child.cache
yield child
@property
def rchildren(self):
# we control exclude uploaded via a class level variable so that
# so that the cache implementation doesn't have to know about it
# since cache shouldn't know anything about why the remote gives
# it certain files, just that it does
yield from self._rchildren(exclude_uploaded=self._exclude_uploaded)
def _dir_or_file(self, child, deleted, exclude_uploaded, skip_existing):
""" skip_existing sould be set if create_cache is set to true """
# FIXME
state = child.bfobject.state
if state != 'READY':
#log.debug (f'{state} {child.name} {child.id}')
if state != 'UPLOADED':
self._errors.append(f'State not READY and not UPLOADED is {state}')
if state == 'DELETING' or state == 'PARENT-DELETING':
deleted.append(child)
return
if exclude_uploaded and state == 'UPLOADED':
logd.warning(f'File in {self.id} is UPLOADED not READY! {child!r}') # TODO
return
if child.is_file():
cid = child.id
existing = [c for c in self.cache.local.children
if (c.is_file() and c.cache or c.is_broken_symlink())
and c.cache.id == cid]
if existing:
unmatched = [e for e in existing if child.name != e.name]
if unmatched and skip_existing:
# NOTE this should run when create_cache is True to avoid
# creating files with duplicate names in the event that
# somehow there was a duplicate name, this is an internal
# implementation detail related to old decisions about how
# to populate the local cache
log.debug(f'skipping {child.name} becuase a file with that '
f'id already exists {unmatched}')
return
return True
def _rchildren(self,
create_cache=True,
# FIXME I am 99% sure that create_cache should default to False
# and I was also 99% sure that I HAD set it to be False by
# default so that remote.rchildren would not populate cache
# but that only cache.rchildren would, however neither of those
# is really correct in order to fix this need to review who is
# calling this for the create cache side effects and fix them
exclude_uploaded=False,
sparse=False,):
if isinstance(self.bfobject, self._File):
return
elif isinstance(self.bfobject, self._DataPackage):
return # should we return files inside packages? are they 1:1?
elif any(isinstance(self.bfobject, t)
for t in (self._Organization, self._Collection)):
for child in self._children(create_cache=create_cache):
yield child
yield from child._rchildren(create_cache=create_cache)
elif isinstance(self.bfobject, self._Dataset):
sparse = sparse or self.cache.is_sparse()
deleted = []
if sparse:
filenames = self._sparse_stems
sbfo = self.bfobject
_parents_yielded = set()
_int_id_map = {}
for bfobject in self.bfobject.packagesByName(filenames=filenames):
child = self.__class__(bfobject)
if child.is_dir() or child.is_file():
if not self._dir_or_file(child, deleted, exclude_uploaded, create_cache):
continue
else:
# probably a package that has files
#log.debug(f'skipping {child} becuase it is neither a directory nor a file')
continue
parent = child
parents = []
while True:
log.debug(parent)
parent_int_id = None
if (parent.from_packages and
'parentId' in parent.bfobject.package._json['content']):
# FIXME HACK
# FIXME incredibly slow, but still faster than non-sparse
parent_int_id = parent.bfobject.package._json['content']['parentId']
if parent_int_id not in _int_id_map:
parent = self.__class__(parent.id)
parent.bfobject
_int_id_map[parent_int_id] = parent.parent
if not parents: # add the child as the last parent
parents.append(parent)
if parent.parent_id in (sbfo, self.id):
break # child yielded below
else:
if parent_int_id is not None:
parent = _int_id_map[parent_int_id]
else:
parent = parent.parent
# TODO create cache
if parent.id not in _parents_yielded:
_parents_yielded.add(parent.id)
# actually yield below in the reverse order
parents.append(parent)
#yield parent
else:
break
if create_cache:
pcache = self.cache
for parent in reversed(parents):
yield parent
pcache = pcache / parent
else:
yield from reversed(parents)
return
for bfobject in self.bfobject.packages:
child = self.__class__(bfobject)
if child.is_dir() or child.is_file():
if not self._dir_or_file(child, deleted, exclude_uploaded, create_cache):
continue
if create_cache:
# FIXME I don't think existing detection is working
# correctly here so this get's triggered incorrectly?
self.cache / child # construction will cause registration without needing to assign
assert child.cache is not None
yield child
else:
# probably a package that has files
log.debug(f'skipping {child} becuase it is neither a directory nor a file')
else: # for loop else
self._deleted = deleted
else:
raise exc.UnhandledTypeError # TODO
def children_pull(self,
existing_caches=tuple(),
only=tuple(),
skip=tuple(),
sparse=tuple()):
""" ONLY USE FOR organization level """
# FIXME this is really a recursive pull for organization level only ...
sname = lambda gen: sorted(gen, key=lambda c: c.name)
def refresh(c):
updated = c.meta.updated
newc = c.refresh()
if newc is None:
return
nupdated = newc.meta.updated
if nupdated != updated:
return newc
existing = sname(existing_caches)
if not self._debug:
skipexisting = {e.id:e for e in
Async(rate=self._async_rate)(deferred(refresh)(e) for e in existing)
if e is not None}
else: # debug ...
skipexisting = {e.id:e for e in
(refresh(e) for e in existing)
if e is not None}
# FIXME
# in theory the remote could change betwee these two loops
# since we currently cannot do a single atomic pull for
# a set of remotes and have them refresh existing files
# in one shot
if not self._debug:
yield from (rc for d in Async(rate=self._async_rate)(
deferred(child.bootstrap)(recursive=True,
only=only,
skip=skip,
sparse=sparse)
for child in sname(self.children)
#if child.id in skipexisting
# TODO when dataset's have a 'anything in me updated'
# field then we can use that to skip things that haven't
# changed (hello git ...)
) for rc in d)
else: # debug
yield from (rc for d in (
child.bootstrap(recursive=True, only=only, skip=skip, sparse=sparse)
for child in sname(self.children))
#if child.id in skipexisting
# TODO when dataset's have a 'anything in me updated'
# field then we can use that to skip things that haven't
# changed (hello git ...)
for rc in d)
def isinstance_bf(self, *types):
return [t for t in types if isinstance(self.bfobject, t)]
def refresh(self, update_cache=False, update_data=False,
update_data_on_cache=False, size_limit_mb=2, force=False):
""" use force if you have a file from packages """
try:
old_meta = self.meta
except exc.NoMetadataRetrievedError as e:
log.error(f'{e}\nYou will need to individually refresh {self.local}')
return
except exc.NoRemoteFileWithThatIdError as e:
log.exception(e)
return
if self.is_file() and not force: # this will tigger a fetch
pass
else:
try:
self._bfobject = self._api.get(self.id)
except exc.NoRemoteFileWithThatIdError as e:
log.exception(e)
return
self.is_file() # trigger fetching file in the no file_id case
if update_cache or update_data:
file_is_different = self.update_cache()
update_existing = file_is_different and self.cache.exists()
udoc = update_data_on_cache and file_is_different
if update_existing or udoc:
size_limit_mb = None
update_data = update_data or update_existing or udoc
if update_data and self.is_file():
self.cache.fetch(size_limit_mb=size_limit_mb)
return self.cache # when a cache calls refresh it needs to know if it no longer exists
@property
def parent_id(self):
# work around inhomogenous
if self == self.organization:
return self.id # this behavior is consistent with how Path.parent works
elif not hasattr(self._bfobject, 'dataset'):
return self.organization.id
else:
pid = getattr(self._bfobject, 'parent')
if pid is None:
ds = self._bfobject.dataset
if isinstance(ds, str):
return ds
else:
# we embed the object instead of just the id now
# so we have to handle that case
return ds.id
def _on_cache_move_error(self, error, cache):
if self.bfobject.package.name != self.bfobject.name:
argh = self.bfobject.name
self.bfobject.name = self.bfobject.package.name
try:
log.critical(f'Non unique filename :( '
f'{cache.name} -> {argh} -> {self.bfobject.name}')
cache.move(remote=self)
finally:
self.bfobject.name = argh
else:
raise error
@property
def _single_file(self):
if isinstance(self.bfobject, self._DataPackage):
files = list(self.bfobject.files)
if len(files) > 1:
raise BaseException('TODO too many files')
file = files[0]
elif isinstance(self.bfobject, self._File):
file = self.bfobject
else:
file = None
return file
@property
def _uri_file(self):
file = self._single_file
if file is not None:
return file.url
@property
def data(self):
uri_file = self._uri_file
if uri_file is None:
return
gen = self.get_file_by_url(uri_file)
try:
self.data_headers = next(gen)
except exc.NoRemoteFileWithThatIdError as e:
raise FileNotFoundError(f'{self}') from e
yield from gen
@data.setter
def data(self):
if hasattr(self, '_seed'):
# upload the new file
# delete the old file
# or move to .trash self._api.bf.move(target, self.id)
# where target is the bfobject for .trash
raise NotImplementedError('TODO')
else: # doesn't exist yet
# see https://github.com/HumanCellAtlas/dcp-cli/pull/252
# for many useful references
raise NotImplementedError('TODO')
def _lchildmeta(self, child):
raise NotImplementedError('pretty sure unused')
# FIXME all of this should be accessible from local and/or cache directly ...
lchild = self.cache.local / child.name # TODO LocalPath.__truediv__ ?
excache = None
lchecksum = None
echecksum = None
modified = False
if lchild.exists() and False: # TODO XXX
lmeta = lchild.meta
lchecksum = lmeta.checksum
excache = lchild.cache
if excache is None:
lmeta = lchild.meta
lmeta.id = None
echecksum = lmeta.checksum
else:
echecksum = excache.checksum
if lchecksum != echecksum:
log.debug(f'file has been modified {lchild}')
modified = True
return lchild, excache, lmeta, lchecksum, echecksum, modified
def _lchild(self, child):
l = self.cache.local