-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Expand file tree
/
Copy pathcore.py
More file actions
2715 lines (2292 loc) · 84.9 KB
/
core.py
File metadata and controls
2715 lines (2292 loc) · 84.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import print_function
import json
import os
import tarfile
from collections import namedtuple
from datetime import datetime
from tempfile import TemporaryDirectory
from io import BytesIO
from itertools import chain
from typing import (
Any,
Dict,
FrozenSet,
Iterable,
Iterator,
List,
NamedTuple,
Optional,
TYPE_CHECKING,
Tuple,
)
from metaflow.metaflow_current import current
from metaflow.events import Trigger
from metaflow.exception import (
MetaflowInternalError,
MetaflowInvalidPathspec,
MetaflowNamespaceMismatch,
MetaflowNotFound,
)
from metaflow.includefile import IncludedFile
from metaflow.metaflow_config import DEFAULT_METADATA, MAX_ATTEMPTS
from metaflow.metaflow_environment import MetaflowEnvironment
from metaflow.package import MetaflowPackage
from metaflow.packaging_sys import ContentType
from metaflow.plugins import ENVIRONMENTS, METADATA_PROVIDERS
from metaflow.unbounded_foreach import CONTROL_TASK_TAG
from metaflow.util import cached_property, is_stringish, resolve_identity, to_unicode
from .filecache import FileCache
if TYPE_CHECKING:
from metaflow.metadata_provider import MetadataProvider
try:
# python2
import cPickle as pickle
except: # noqa E722
# python3
import pickle
# populated at the bottom of this file
_CLASSES = {}
Metadata = namedtuple("Metadata", ["name", "value", "created_at", "type", "task"])
filecache = None
current_namespace = False
current_metadata = False
def metadata(ms: str) -> str:
"""
Switch Metadata provider.
This call has a global effect. Selecting the local metadata will,
for example, not allow access to information stored in remote
metadata providers.
Note that you don't typically have to call this function directly. Usually
the metadata provider is set through the Metaflow configuration file. If you
need to switch between multiple providers, you can use the `METAFLOW_PROFILE`
environment variable to switch between configurations.
Parameters
----------
ms : str
Can be a path (selects local metadata), a URL starting with http (selects
the service metadata) or an explicit specification <metadata_type>@<info>; as an
example, you can specify local@<path> or service@<url>.
Returns
-------
str
The description of the metadata selected (equivalent to the result of
get_metadata()).
"""
global current_metadata
provider, info = _metadata(ms)
if provider is None:
print(
"Cannot find a metadata provider -- "
"try specifying one explicitly using <type>@<info>",
)
return get_metadata()
current_metadata = provider
if info:
current_metadata.INFO = info
return get_metadata()
def get_metadata() -> str:
"""
Returns the current Metadata provider.
If this is not set explicitly using `metadata`, the default value is
determined through the Metaflow configuration. You can use this call to
check that your configuration is set up properly.
If multiple configuration profiles are present, this call returns the one
selected through the `METAFLOW_PROFILE` environment variable.
Returns
-------
str
Information about the Metadata provider currently selected. This information typically
returns provider specific information (like URL for remote providers or local paths for
local providers).
"""
if current_metadata is False:
default_metadata()
return current_metadata.metadata_str()
def default_metadata() -> str:
"""
Resets the Metadata provider to the default value, that is, to the value
that was used prior to any `metadata` calls.
Returns
-------
str
The result of get_metadata() after resetting the provider.
"""
global current_metadata
# We first check if we are in a flow -- if that is the case, we use the
# metadata provider that is being used there
if current._metadata_str:
return metadata(current._metadata_str)
default = [m for m in METADATA_PROVIDERS if m.TYPE == DEFAULT_METADATA]
if default:
current_metadata = default[0]
else:
from metaflow.plugins.metadata_providers import LocalMetadataProvider
current_metadata = LocalMetadataProvider
return get_metadata()
def namespace(ns: Optional[str]) -> Optional[str]:
"""
Switch namespace to the one provided.
This call has a global effect. No objects outside this namespace
will be accessible. To access all objects regardless of namespaces,
pass None to this call.
Parameters
----------
ns : str, optional
Namespace to switch to or None to ignore namespaces.
Returns
-------
str, optional
Namespace set (result of get_namespace()).
"""
global current_namespace
current_namespace = ns
return get_namespace()
def get_namespace() -> Optional[str]:
"""
Return the current namespace that is currently being used to filter objects.
The namespace is a tag associated with all objects in Metaflow.
Returns
-------
str, optional
The current namespace used to filter objects.
"""
# see a comment about namespace initialization
# in Metaflow.__init__ below
if current_namespace is False:
default_namespace()
return current_namespace
def default_namespace() -> str:
"""
Resets the namespace used to filter objects to the default one, i.e. the one that was
used prior to any `namespace` calls.
Returns
-------
str
The result of get_namespace() after the namespace has been reset.
"""
global current_namespace
current_namespace = resolve_identity()
return get_namespace()
def inspect_spin(datastore_root: str = "."):
"""
Set metadata provider to spin metadata so that users can inspect spin
steps, tasks, and artifacts.
Parameters
----------
datastore_root : str, default "."
The root path to the spin datastore.
"""
metadata_str = f"spin@{datastore_root}"
metadata(metadata_str)
MetaflowArtifacts = NamedTuple
class MetaflowObject(object):
"""
Base class for all Metaflow objects.
Creates a new object of a specific type (Flow, Run, Step, Task, DataArtifact) given
a path to it (its `pathspec`).
Accessing Metaflow objects is done through one of two methods:
- either by directly instantiating it with this class
- or by accessing it through its parent (iterating over
all children or accessing directly using the [] operator)
With this class, you can:
- Get a `Flow`; use `Flow('FlowName')`.
- Get a `Run` of a flow; use `Run('FlowName/RunID')`.
- Get a `Step` of a run; use `Step('FlowName/RunID/StepName')`.
- Get a `Task` of a step, use `Task('FlowName/RunID/StepName/TaskID')`
- Get a `DataArtifact` of a task; use
`DataArtifact('FlowName/RunID/StepName/TaskID/ArtifactName')`.
Attributes
----------
tags : FrozenSet[str]
Tags associated with the run this object belongs to (user and system tags).
user_tags: FrozenSet[str]
User tags associated with the run this object belongs to.
system_tags: FrozenSet[str]
System tags associated with the run this object belongs to.
created_at : datetime
Date and time this object was first created.
parent : MetaflowObject
Parent of this object. The parent of a `Run` is a `Flow` for example
pathspec : str
Pathspec of this object (for example: 'FlowName/RunID' for a `Run`)
path_components : List[str]
Components of the pathspec
origin_pathspec : str, optional
Pathspec of the original object this object was cloned from (in the case of a resume).
None if not applicable.
"""
_NAME = "base"
_CHILD_CLASS = None
_PARENT_CLASS = None
def __init__(
self,
pathspec: Optional[str] = None,
attempt: Optional[int] = None,
_object: Optional["MetaflowObject"] = None,
_parent: Optional["MetaflowObject"] = None,
_namespace_check: bool = True,
_metaflow: Optional["Metaflow"] = None,
_current_namespace: Optional[str] = None,
_current_metadata: Optional[str] = None,
):
# the default namespace is activated lazily at the first
# get_namespace(). The other option of activating
# the namespace at the import time is problematic, since there
# may be other modules that alter environment variables etc.
# which may affect the namespace setting.
self._metaflow = Metaflow(_current_metadata) or _metaflow
self._parent = _parent
self._path_components = None
self._attempt = attempt
self._current_namespace = _current_namespace or get_namespace()
self._namespace_check = _namespace_check
# If the current namespace is False, we disable checking for namespace for this
# and all children objects. Not setting namespace_check to False has the consequence
# of preventing access to children objects after the namespace changes
if self._current_namespace is None:
self._namespace_check = False
if self._attempt is not None:
if self._NAME not in ["task", "artifact"]:
raise MetaflowNotFound(
"Attempts can only be specified for Task or DataArtifact"
)
try:
self._attempt = int(self._attempt)
except ValueError:
raise MetaflowNotFound("Attempt can only be an integer")
if self._attempt < 0:
raise MetaflowNotFound("Attempt can only be non-negative")
elif self._attempt >= MAX_ATTEMPTS:
raise MetaflowNotFound(
"Attempt can only be smaller than %d" % MAX_ATTEMPTS
)
# NOTE: It is possible that no attempt exists, but we can't
# distinguish between "attempt will happen" and "no such
# attempt exists".
if pathspec and _object is None:
ids = pathspec.split("/")
if self._NAME == "flow" and len(ids) != 1:
raise MetaflowInvalidPathspec("Expects Flow('FlowName')")
elif self._NAME == "run" and len(ids) != 2:
raise MetaflowInvalidPathspec("Expects Run('FlowName/RunID')")
elif self._NAME == "step" and len(ids) != 3:
raise MetaflowInvalidPathspec("Expects Step('FlowName/RunID/StepName')")
elif self._NAME == "task" and len(ids) != 4:
raise MetaflowInvalidPathspec(
"Expects Task('FlowName/RunID/StepName/TaskID')"
)
elif self._NAME == "artifact" and len(ids) != 5:
raise MetaflowInvalidPathspec(
"Expects DataArtifact('FlowName/RunID/StepName/TaskID/ArtifactName')"
)
self.id = ids[-1]
self._pathspec = pathspec
self._object = self._get_object(*ids)
else:
self._object = _object
self._pathspec = pathspec
if self._NAME in ("flow", "task"):
self.id = str(self._object[self._NAME + "_id"])
elif self._NAME == "run":
self.id = str(self._object["run_number"])
elif self._NAME == "step":
self.id = str(self._object["step_name"])
elif self._NAME == "artifact":
self.id = str(self._object["name"])
else:
raise MetaflowInternalError(msg="Unknown type: %s" % self._NAME)
self._created_at = datetime.fromtimestamp(self._object["ts_epoch"] / 1000.0)
self._tags = frozenset(
chain(self._object.get("system_tags") or [], self._object.get("tags") or [])
)
self._user_tags = frozenset(self._object.get("tags") or [])
self._system_tags = frozenset(self._object.get("system_tags") or [])
if self._namespace_check and not self._is_in_namespace(self._current_namespace):
raise MetaflowNamespaceMismatch(self._current_namespace)
def _get_object(self, *path_components):
result = self._metaflow.metadata.get_object(
self._NAME, "self", None, self._attempt, *path_components
)
if not result:
raise MetaflowNotFound("%s does not exist" % self)
return result
def __iter__(self) -> Iterator["MetaflowObject"]:
"""
Iterate over all child objects of this object if any.
Note that only children present in the current namespace are returned if and
only if _namespace_check is set.
Yields
------
MetaflowObject
Children of this object
"""
query_filter = {}
# skip namespace filtering if _namespace_check is unset.
if self._namespace_check and self._current_namespace:
query_filter = {"any_tags": self._current_namespace}
unfiltered_children = self._metaflow.metadata.get_object(
self._NAME,
_CLASSES[self._CHILD_CLASS]._NAME,
query_filter,
self._attempt,
*self.path_components,
)
unfiltered_children = unfiltered_children if unfiltered_children else []
children = filter(
lambda x: self._iter_filter(x),
(
_CLASSES[self._CHILD_CLASS](
attempt=self._attempt,
_object=obj,
_parent=self,
_metaflow=self._metaflow,
_namespace_check=self._namespace_check,
_current_namespace=(
self._current_namespace if self._namespace_check else None
),
)
for obj in unfiltered_children
),
)
if children:
return iter(sorted(children, reverse=True, key=lambda x: x.created_at))
else:
return iter([])
def _iter_filter(self, x):
return True
def _filtered_children(self, *tags):
"""
Returns an iterator over all children.
If tags are specified, only children associated with all specified tags
are returned.
"""
for child in self:
if all(tag in child.tags for tag in tags):
yield child
def _ipython_key_completions_(self):
"""Returns available options for ipython auto-complete."""
return [child.id for child in self._filtered_children()]
@classmethod
def _url_token(cls):
return "%ss" % cls._NAME
def is_in_namespace(self) -> bool:
"""
Returns whether this object is in the current namespace.
If the current namespace is None, this will always return True.
Returns
-------
bool
Whether or not the object is in the current namespace
"""
return self._is_in_namespace(current_namespace)
def _is_in_namespace(self, ns: str) -> bool:
"""
Returns whether this object is in namespace passed in.
If the current namespace is None, this will always return True.
Parameters
----------
ns : str
Namespace to check if the object is in.
Returns
-------
bool
Whether or not the object is in the current namespace
"""
if self._NAME == "flow":
return any(True for _ in self)
else:
return ns is None or ns in self._tags
def __str__(self):
if self._attempt is not None:
return "%s('%s', attempt=%d)" % (
self.__class__.__name__,
self.pathspec,
self._attempt,
)
return "%s('%s')" % (self.__class__.__name__, self.pathspec)
def __repr__(self):
return str(self)
def _get_child(self, id):
result = []
for p in self.path_components:
result.append(p)
result.append(id)
return self._metaflow.metadata.get_object(
_CLASSES[self._CHILD_CLASS]._NAME, "self", None, self._attempt, *result
)
def __getitem__(self, id: str) -> "MetaflowObject":
"""
Returns the child object named 'id'.
Parameters
----------
id : str
Name of the child object
Returns
-------
MetaflowObject
Child object
Raises
------
KeyError
If the name does not identify a valid child object
"""
obj = self._get_child(id)
if obj:
return _CLASSES[self._CHILD_CLASS](
attempt=self._attempt,
_object=obj,
_parent=self,
_metaflow=self._metaflow,
_namespace_check=self._namespace_check,
_current_namespace=(
self._current_namespace if self._namespace_check else None
),
)
else:
raise KeyError(id)
def __contains__(self, id: str):
"""
Tests whether a child named 'id' exists.
Parameters
----------
id : str
Name of the child object
Returns
-------
bool
True if the child exists or False otherwise
"""
return bool(self._get_child(id))
def _unpickle_284(self, data):
if len(data) != 3:
raise MetaflowInternalError(
"Unexpected size of array: {}".format(len(data))
)
pathspec, attempt, namespace_check = data
self.__init__(
pathspec=pathspec, attempt=attempt, _namespace_check=namespace_check
)
def _unpickle_2124(self, data):
if len(data) != 4:
raise MetaflowInternalError(
"Unexpected size of array: {}".format(len(data))
)
pathspec, attempt, ns, namespace_check = data
self.__init__(
pathspec=pathspec,
attempt=attempt,
_namespace_check=namespace_check,
_current_namespace=ns,
)
def _unpickle_21227(self, data):
if len(data) != 5:
raise MetaflowInternalError(
"Unexpected size of array: {}".format(len(data))
)
pathspec, attempt, md, ns, namespace_check = data
self.__init__(
pathspec=pathspec,
attempt=attempt,
_namespace_check=namespace_check,
_current_metadata=md,
_current_namespace=ns,
)
_UNPICKLE_FUNC = {
"2.8.4": _unpickle_284,
"2.12.4": _unpickle_2124,
"2.12.27": _unpickle_21227,
}
def __setstate__(self, state):
"""
This function is used during the unpickling operation.
More info here https://docs.python.org/3/library/pickle.html#object.__setstate__
"""
if "version" in state and "data" in state:
version = state["version"]
if version not in self._UNPICKLE_FUNC:
# this happens when an object pickled using a newer version of Metaflow is
# being un-pickled using an older version of Metaflow
raise MetaflowInternalError(
"Unpickling this object requires a Metaflow version greater than or equal to {}".format(
version
)
)
self._UNPICKLE_FUNC[version](self, state["data"])
else:
# For backward compatibility: handles pickled objects that were serialized without a __getstate__ override
# We set namespace_check to False if it doesn't exist so that the user can
# continue accessing this object once unpickled.
self.__init__(
pathspec=state.get("_pathspec", None),
attempt=state.get("_attempt", None),
_namespace_check=state.get("_namespace_check", False),
_current_namespace=None,
)
def __getstate__(self):
"""
This function is used during the pickling operation.
More info here https://docs.python.org/3/library/pickle.html#object.__getstate__
This function is not forward compatible i.e., if this object (or any of the objects deriving
from this object) are pickled (serialized) in a later version of Metaflow, it may not be possible
to unpickle (deserialize) them in a previous version of Metaflow.
"""
# Note that we now record the namespace at the time of the object creation so
# we don't need to force namespace_check to be False and can properly continue
# checking for the namespace even after unpickling since we will know which
# namespace to check.
return {
"version": "2.12.27",
"data": [
self.pathspec,
self._attempt,
self._metaflow.metadata.metadata_str(),
self._current_namespace,
self._namespace_check,
],
}
@property
def tags(self) -> FrozenSet[str]:
"""
Tags associated with this object.
Tags can be user defined or system defined. This returns all tags associated
with the object.
Returns
-------
Set[str]
Tags associated with the object
"""
return self._tags
@property
def system_tags(self) -> FrozenSet[str]:
"""
System defined tags associated with this object.
Returns
-------
Set[str]
System tags associated with the object
"""
return self._system_tags
@property
def user_tags(self) -> FrozenSet[str]:
"""
User defined tags associated with this object.
Returns
-------
Set[str]
User tags associated with the object
"""
return self._user_tags
@property
def created_at(self) -> datetime:
"""
Creation time for this object.
This corresponds to the time the object's existence was first created which typically means
right before any code is run.
Returns
-------
datetime
Date time of this object's creation.
"""
return self._created_at
@property
def origin_pathspec(self) -> Optional[str]:
"""
The pathspec of the object from which the current object was cloned.
Returns:
str, optional
pathspec of the origin object from which current object was cloned.
"""
origin_pathspec = None
if self._NAME == "run":
latest_step = next(self.steps())
if latest_step and latest_step.task:
# If we had a step
task = latest_step.task
origin_run_id = [
m.value for m in task.metadata if m.name == "origin-run-id"
]
if origin_run_id:
origin_pathspec = "%s/%s" % (self.parent.id, origin_run_id[0])
else:
parent_pathspec = self.parent.origin_pathspec if self.parent else None
if parent_pathspec:
my_id = self.id
origin_task_id = None
if self._NAME == "task":
origin_task_id = [
m.value for m in self.metadata if m.name == "origin-task-id"
]
if origin_task_id:
my_id = origin_task_id[0]
else:
my_id = None
if my_id is not None:
origin_pathspec = "%s/%s" % (parent_pathspec, my_id)
return origin_pathspec
@property
def parent(self) -> Optional["MetaflowObject"]:
"""
Returns the parent object of this object or None if none exists.
Returns
-------
MetaflowObject, optional
The parent of this object
"""
if self._NAME == "flow":
return None
# Compute parent from pathspec and cache it.
if self._parent is None:
pathspec = self.pathspec
parent_pathspec = pathspec[: pathspec.rfind("/")]
# Only artifacts and tasks have attempts right now, so we get the
# right parent if we are an artifact.
attempt_to_pass = self._attempt if self._NAME == "artifact" else None
# We can skip the namespace check because if self._NAME = 'run',
# the parent object is guaranteed to be in namespace.
# Otherwise the check is moot for Flow since parent is singular.
self._parent = _CLASSES[self._PARENT_CLASS](
parent_pathspec, attempt=attempt_to_pass, _namespace_check=False
)
return self._parent
@property
def pathspec(self) -> str:
"""
Returns a string representation uniquely identifying this object.
The string is the same as the one you would pass into the constructor
to build this object except if you are looking for a specific attempt of
a task or a data artifact (in which case you need to add `attempt=<attempt>`
in the constructor).
Returns
-------
str
Unique representation of this object
"""
if self._pathspec is None:
if self.parent is None:
self._pathspec = self.id
else:
parent_pathspec = self.parent.pathspec
self._pathspec = os.path.join(parent_pathspec, self.id)
return self._pathspec
@property
def path_components(self) -> List[str]:
"""
List of individual components of the pathspec.
Returns
-------
List[str]
Individual components of the pathspec
"""
if self._path_components is None:
ids = self.pathspec.split("/")
self._path_components = ids
return list(self._path_components)
class MetaflowCode(object):
"""
Snapshot of the code used to execute this `Run`. Instantiate the object through
`Run(...).code` (if any step is executed remotely) or `Task(...).code` for an
individual task. The code package is the same for all steps of a `Run`.
`MetaflowCode` includes a package of the user-defined `FlowSpec` class and supporting
files, as well as a snapshot of the Metaflow library itself.
Currently, `MetaflowCode` objects are stored only for `Run`s that have at least one `Step`
executing outside the user's local environment.
The `TarFile` for the `Run` is given by `Run(...).code.tarball`
Attributes
----------
path : str
Location (in the datastore provider) of the code package.
info : Dict[str, str]
Dictionary of information related to this code-package.
flowspec : str
Source code of the file containing the `FlowSpec` in this code package.
tarball : TarFile
Python standard library `tarfile.TarFile` archive containing all the code.
"""
def __init__(self, flow_name: str, code_package: str):
global filecache
self._flow_name = flow_name
info = json.loads(code_package)
self._path = info["location"]
self._ds_type = info["ds_type"]
self._sha = info["sha"]
self._code_metadata = info.get(
"metadata",
'{"version": 0, "archive_format": "tgz", "mfcontent_version": 0}',
)
self._backend = MetaflowPackage.get_backend(self._code_metadata)
if filecache is None:
filecache = FileCache()
_, blobdata = filecache.get_data(
self._ds_type, self._flow_name, self._path, self._sha
)
self._code_obj = BytesIO(blobdata)
self._info = MetaflowPackage.cls_get_info(self._code_metadata, self._code_obj)
self._code_obj.seek(0)
if self._info:
self._flowspec = MetaflowPackage.cls_get_content(
self._code_metadata, self._code_obj, self._info["script"]
)
self._code_obj.seek(0)
else:
raise MetaflowInternalError("Code package metadata is invalid.")
self._tarball = None
@property
def path(self) -> str:
"""
Location (in the datastore provider) of the code package.
Returns
-------
str
Full path of the code package
"""
return self._path
@property
def info(self) -> Dict[str, str]:
"""
Metadata associated with the code package.
Returns
-------
Dict[str, str]
Dictionary of metadata. Keys and values are strings
"""
return self._info
@property
def flowspec(self) -> str:
"""
Source code of the Python file containing the FlowSpec.
Returns
-------
str
Content of the Python file
"""
return self._flowspec
@property
def tarball(self) -> tarfile.TarFile:
"""
TarFile for this code package.
Returns
-------
TarFile
TarFile for everything in this code package
"""
# We only return one tarball because the different TarFile objects share
# a common bytes buffer (self._code_obj).
if self._tarball is not None:
return self._tarball
if self._backend.type == "tgz":
self._tarball = self._backend.cls_open(self._code_obj)
return self._tarball
raise RuntimeError("Archive is not a tarball")
def extract(self) -> TemporaryDirectory:
"""
Extracts the code package to a temporary directory.
This creates a temporary directory containing all user code
files from the code package. The temporary directory is
automatically deleted when the returned TemporaryDirectory
object is garbage collected or when its cleanup() is called.
To preserve the contents to a permanent location, use
os.replace() which performs a zero-copy move on the same
filesystem:
```python
with task.code.extract() as tmp_dir:
# Move contents to permanent location
for item in os.listdir(tmp_dir):
src = os.path.join(tmp_dir, item)
dst = os.path.join('/path/to/permanent/dir', item)
os.makedirs(os.path.dirname(dst), exist_ok=True)
os.replace(src, dst) # Atomic move operation
```
Returns
-------
TemporaryDirectory
A temporary directory containing the extracted code files.
The directory and its contents are automatically deleted when
this object is garbage collected.
"""
tmp = TemporaryDirectory()
# We save the position we are in _code_obj -- in case tarball is using it at
# the same time -- so we can reset it to not perturb tarball.
pos = self._code_obj.tell()
self._code_obj.seek(0)
MetaflowPackage.cls_extract_into(
self._code_metadata, self._code_obj, tmp.name, ContentType.USER_CONTENT
)
self._code_obj.seek(pos)
return tmp
@property
def script_name(self) -> str:
"""
Returns the filename of the Python script containing the FlowSpec.
This is the main Python file that was used to execute the flow. For example,
if your flow is defined in 'myflow.py', this property will return 'myflow.py'.
Returns
-------
str
Name of the Python file containing the FlowSpec
"""
return self._info["script"]
def __str__(self):
return "<MetaflowCode: %s>" % self._info["script"]
class DataArtifact(MetaflowObject):
"""
A single data artifact and associated metadata. Note that this object does
not contain other objects as it is the leaf object in the hierarchy.
Attributes
----------
data : object
The data contained in this artifact, that is, the object produced during
execution of this run.
sha : string
A unique ID of this artifact.
finished_at : datetime
Corresponds roughly to the `Task.finished_at` time of the parent `Task`.
An alias for `DataArtifact.created_at`.
"""
_NAME = "artifact"
_PARENT_CLASS = "task"
_CHILD_CLASS = None
@property
def data(self) -> Any:
"""
Unpickled representation of the data contained in this artifact.
Returns
-------