-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathrecipe.py
2576 lines (1944 loc) · 94.1 KB
/
recipe.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
from ..utils import DataikuException
from .utils import DSSTaggableObjectSettings
from .discussion import DSSObjectDiscussions
import json, logging, warnings
from .utils import DSSTaggableObjectListItem, DSSTaggableObjectSettings
try:
basestring
except NameError:
basestring = str
class DSSRecipeListItem(DSSTaggableObjectListItem):
"""
An item in a list of recipes.
.. important::
Do not instantiate directly, use :meth:`dataikuapi.dss.project.DSSProject.list_recipes()`
"""
def __init__(self, client, data):
super(DSSRecipeListItem, self).__init__(data)
self.client = client
def to_recipe(self):
"""
Gets a handle corresponding to this recipe.
:rtype: :class:`DSSRecipe`
"""
return DSSRecipe(self.client, self._data["projectKey"], self._data["name"])
@property
def name(self):
"""
Get the name of the recipe.
:rtype: string
"""
return self._data["name"]
@property
def id(self):
"""
Get the identifier of the recipe.
For recipes, the name is the identifier.
:rtype: string
"""
return self._data["name"]
@property
def type(self):
"""
Get the type of the recipe.
:return: a recipe type, for example 'sync' or 'join'
:rtype: string
"""
return self._data["type"]
class DSSRecipe(object):
"""
A handle to an existing recipe on the DSS instance.
.. important::
Do not instantiate directly, use :meth:`dataikuapi.dss.project.DSSProject.get_recipe()`
"""
def __init__(self, client, project_key, recipe_name):
self.client = client
self.project_key = project_key
self.recipe_name = recipe_name
@property
def id(self):
"""
Get the identifier of the recipe.
For recipes, the name is the identifier.
:rtype: string
"""
return self.recipe_name
@property
def name(self):
"""
Get the name of the recipe.
:rtype: string
"""
return self.recipe_name
def compute_schema_updates(self):
"""
Computes which updates are required to the outputs of this recipe.
This method only computes which changes would be needed to make the schema of the outputs
of the recipe match the actual schema that the recipe will produce. To effectively apply
these changes to the outputs, you can use the :meth:`~RequiredSchemaUpdates.apply()` on
the returned object.
.. note::
Not all recipe types can compute automatically the schema of their outputs. Code
recipes like Python recipes, notably can't. This method raises an exception in
these cases.
Usage example:
.. code-block:: python
required_updates = recipe.compute_schema_updates()
if required_updates.any_action_required():
print("Some schemas will be updated")
# Note that you can call apply even if no changes are required. This will be noop
required_updates.apply()
:return: an object containing the required updates
:rtype: :class:`RequiredSchemaUpdates`
"""
data = self.client._perform_json(
"GET", "/projects/%s/recipes/%s/schema-update" % (self.project_key, self.recipe_name))
return RequiredSchemaUpdates(self, data)
def run(self, job_type="NON_RECURSIVE_FORCED_BUILD", partitions=None, wait=True, no_fail=False):
"""
Starts a new job to run this recipe and wait for it to complete.
Raises if the job failed.
.. code-block:: python
job = recipe.run()
print("Job %s done" % job.id)
:param string job_type: job type. One of RECURSIVE_BUILD, NON_RECURSIVE_FORCED_BUILD or RECURSIVE_FORCED_BUILD
:param string partitions: if the outputs are partitioned, a partition spec. A spec is a comma-separated list of partition
identifiers, and a partition identifier is a pipe-separated list of values for the partitioning
dimensions
:param boolean no_fail: if True, does not raise if the job failed
:param boolean wait: if True, the method waits for the job complettion. If False, the method returns immediately
:return: a job handle corresponding to the recipe run
:rtype: :class:`dataikuapi.dss.job.DSSJob`
"""
project = self.client.get_project(self.project_key)
outputs = project.get_flow().get_graph().get_successor_computables(self)
if len(outputs) == 0:
raise Exception("recipe has no outputs, can't run it")
first_output = outputs[0]
object_type_map = {
"COMPUTABLE_DATASET": "DATASET",
"COMPUTABLE_FOLDER": "MANAGED_FOLDER",
"COMPUTABLE_SAVED_MODEL": "SAVED_MODEL",
"COMPUTABLE_STREAMING_ENDPOINT": "STREAMING_ENDPOINT",
"COMPUTABLE_MODEL_EVALUATION_STORE": "MODEL_EVALUATION_STORE"
}
if first_output["type"] in object_type_map:
jd = project.new_job(job_type)
jd.with_output(first_output["ref"], object_type=object_type_map[first_output["type"]], partition=partitions)
else:
raise Exception("Recipe has unsupported output type {}, can't run it".format(first_output["type"]))
if wait:
return jd.start_and_wait(no_fail)
else:
return jd.start()
def delete(self):
"""
Delete the recipe.
"""
return self.client._perform_empty(
"DELETE", "/projects/%s/recipes/%s" % (self.project_key, self.recipe_name))
def rename(self, new_name):
"""
Rename the recipe with the new specified name
:param str new_name: the new name of the recipe
"""
if self.recipe_name == new_name:
raise ValueError("Recipe name is already " + new_name)
obj = {
"oldName": self.recipe_name,
"newName": new_name
}
self.client._perform_empty("POST", "/projects/%s/actions/renameRecipe" % self.project_key, body=obj)
self.recipe_name = new_name
def get_settings(self):
"""
Get the settings of the recipe, as a :class:`DSSRecipeSettings` or one of its subclasses.
Some recipes have a dedicated class for the settings, with additional helpers to read and modify the settings
Once you are done modifying the returned settings object, you can call :meth:`~DSSRecipeSettings.save` on it
in order to save the modifications to the DSS recipe.
:rtype: :class:`DSSRecipeSettings` or a subclass
"""
data = self.client._perform_json(
"GET", "/projects/%s/recipes/%s" % (self.project_key, self.recipe_name))
type = data["recipe"]["type"]
if type == "generate_features":
return GenerateFeaturesRecipeSettings(self, data)
if type == "grouping":
return GroupingRecipeSettings(self, data)
if type == "upsert":
return UpsertRecipeSettings(self, data)
elif type == "window":
return WindowRecipeSettings(self, data)
elif type == "sync":
return SyncRecipeSettings(self, data)
elif type == "pivot":
return PivotRecipeSettings(self, data)
elif type == "sort":
return SortRecipeSettings(self, data)
elif type == "topn":
return TopNRecipeSettings(self, data)
elif type == "distinct":
return DistinctRecipeSettings(self, data)
elif type == "join":
return JoinRecipeSettings(self, data)
elif type == "vstack":
return StackRecipeSettings(self, data)
elif type == "sampling":
return SamplingRecipeSettings(self, data)
elif type == "split":
return SplitRecipeSettings(self, data)
elif type == "prepare" or type == "shaker":
return PrepareRecipeSettings(self, data)
#elif type == "prediction_scoring":
#elif type == "clustering_scoring":
elif type == "download":
return DownloadRecipeSettings(self, data)
elif type == 'export':
return ExportRecipeSettings(self, data)
#elif type == "sql_query":
# return WindowRecipeSettings(self, data)
elif type in ["python", "r", "sql_script", "pyspark", "sparkr", "spark_scala", "shell", "spark_sql_query"]:
return CodeRecipeSettings(self, data)
else:
return DSSRecipeSettings(self, data)
def get_definition_and_payload(self):
"""
Get the definition of the recipe.
.. attention::
Deprecated. Use :meth:`get_settings`
:return: an object holding both the raw definition of the recipe (the type, which inputs and outputs, engine settings...)
and the payload (SQL script, Python code, join definition,... depending on type)
:rtype: :class:`DSSRecipeDefinitionAndPayload`
"""
warnings.warn("Recipe.get_definition_and_payload is deprecated, please use get_settings", DeprecationWarning)
data = self.client._perform_json(
"GET", "/projects/%s/recipes/%s" % (self.project_key, self.recipe_name))
return DSSRecipeDefinitionAndPayload(self, data)
def set_definition_and_payload(self, definition):
"""
Set the definition of the recipe.
.. attention::
Deprecated. Use :meth:`get_settings` then :meth:`DSSRecipeSettings.save()`
.. important::
The **definition** parameter should come from a call to :meth:`get_definition()`
:param object definition: a recipe definition, as returned by :meth:`get_definition()`
"""
warnings.warn("Recipe.set_definition_and_payload is deprecated, please use get_settings", DeprecationWarning)
definition._payload_to_str()
return self.client._perform_json(
"PUT", "/projects/%s/recipes/%s" % (self.project_key, self.recipe_name),
body=definition.data)
def get_status(self):
"""
Gets the status of this recipe.
The status of a recipe is made of messages from checks performed by DSS on the recipe, of messages related
to engines availability for the recipe, of messages about testing the recipe on the engine, ...
:return: an object to interact with the status
:rtype: :class:`dataikuapi.dss.recipe.DSSRecipeStatus`
"""
data = self.client._perform_json(
"GET", "/projects/%s/recipes/%s/status" % (self.project_key, self.recipe_name))
return DSSRecipeStatus(self.client, data)
def get_metadata(self):
"""
Get the metadata attached to this recipe.
The metadata contains label, description checklists, tags and custom metadata of the recipe
:return: the metadata as a dict, with fields:
* **label** : label of the object (not defined for recipes)
* **description** : description of the object (not defined for recipes)
* **checklists** : checklists of the object, as a dict with a **checklists** field, which is a list of checklists, each a dict.
* **tags** : list of tags, each a string
* **custom** : custom metadata, as a dict with a **kv** field, which is a dict with any contents the user wishes
* **customFields** : dict of custom field info (not defined for recipes)
:rtype: dict
"""
return self.client._perform_json(
"GET", "/projects/%s/recipes/%s/metadata" % (self.project_key, self.recipe_name))
def set_metadata(self, metadata):
"""
Set the metadata on this recipe.
.. important::
You should only set a **metadata** object that has been retrieved using :meth:`get_metadata()`.
:params dict metadata: the new state of the metadata for the recipe.
"""
return self.client._perform_json(
"PUT", "/projects/%s/recipes/%s/metadata" % (self.project_key, self.recipe_name),
body=metadata)
def get_object_discussions(self):
"""
Get a handle to manage discussions on the recipe.
:return: the handle to manage discussions
:rtype: :class:`dataikuapi.dss.discussion.DSSObjectDiscussions`
"""
return DSSObjectDiscussions(self.client, self.project_key, "RECIPE", self.recipe_name)
def get_continuous_activity(self):
"""
Get a handle on the associated continuous activity.
.. note::
Should only be used on continuous recipes.
:rtype: :class:`dataikuapi.dss.continuousactivity.DSSContinuousActivity`
"""
from .continuousactivity import DSSContinuousActivity
return DSSContinuousActivity(self.client, self.project_key, self.recipe_name)
def move_to_zone(self, zone):
"""
Move this object to a flow zone.
:param object zone: a :class:`dataikuapi.dss.flow.DSSFlowZone` where to move the object
"""
if isinstance(zone, basestring):
zone = self.client.get_project(self.project_key).get_flow().get_zone(zone)
zone.add_item(self)
class DSSRecipeStatus(object):
"""
Status of a recipe.
.. important::
Do not instantiate directly, use :meth:`DSSRecipe.get_status`
"""
def __init__(self, client, data):
self.client = client
self.data = data
def get_selected_engine_details(self):
"""
Get the selected engine for this recipe.
This method will raise if there is no selected engine, whether it's because the present recipe type
has no notion of engine, or because DSS couldn't find any viable engine for running the recipe.
:return: a dict of the details of the selected engine. The type of engine is in a **type** field. Depending
on the type, additional field will give more details, like whether some aggregations are possible.
:rtype: dict
"""
if not "selectedEngine" in self.data:
raise ValueError("This recipe doesn't have a selected engine")
return self.data["selectedEngine"]
def get_engines_details(self):
"""
Get details about all possible engines for this recipe.
This method will raise if there is no engine, whether it's because the present recipe type
has no notion of engine, or because DSS couldn't find any viable engine for running the recipe.
:return: a list of dict of the details of each possible engine. See :meth:`get_selected_engine_details()` for the fields of each dict.
:rtype: list[dict]
"""
if not "engines" in self.data:
raise ValueError("This recipe doesn't have engines")
return self.data["engines"]
def get_status_severity(self):
"""
Get the overall status of the recipe.
This is the final result of checking the different parts of the recipe, and depends on the recipe type. Examples
of checks done include:
- checking the validity of the formulas in computed columns or filters
- checking if some of the input columns retrieved by joins overlap
- checking against the SQL database if the generated SQL is valid
:return: SUCCESS, WARNING, ERROR or INFO. None if the status has no message at all.
:rtype: string
"""
return self.data["allMessagesForFrontend"].get("maxSeverity")
def get_status_messages(self, as_objects=False):
"""
Returns status messages for this recipe.
:param boolean as_objects: if True, return a list of :class:`dataikuapi.dss.utils.DSSInfoMessage`. If False, as a list
of raw dicts.
:return: if **as_objects** is True, a list of :class:`dataikuapi.dss.utils.DSSInfoMessage`, otherwise a list of
message information, each one a dict of:
* **severity** : severity of the error in the message. Possible values are SUCCESS, INFO, WARNING, ERROR
* **isFatal** : for ERROR **severity**, whether the error is considered fatal to the operation
* **code** : a string with a well-known code documented in `DSS doc <https://doc.dataiku.com/dss/latest/troubleshooting/errors/index.html>`_
* **title** : short message
* **message** : the error message
* **details** : a more detailed error description
:rtype: list
"""
if as_objects:
return [DSSInfoMessage(message) for message in self.data["allMessagesForFrontend"].get("messages", [])]
else:
return self.data["allMessagesForFrontend"]["messages"]
class DSSRecipeSettings(DSSTaggableObjectSettings):
"""
Settings of a recipe.
.. important::
Do not instantiate directly, use :meth:`DSSRecipe.get_settings`
"""
def __init__(self, recipe, data):
super(DSSRecipeSettings, self).__init__(data["recipe"])
self.recipe = recipe
self.data = data
self.recipe_settings = self.data["recipe"]
self._str_payload = self.data.get("payload", None)
self._obj_payload = None
def save(self):
"""
Save back the recipe in DSS.
"""
self._payload_to_str()
return self.recipe.client._perform_json(
"PUT", "/projects/%s/recipes/%s" % (self.recipe.project_key, self.recipe.recipe_name),
body=self.data)
@property
def type(self):
"""
Get the type of the recipe.
:return: a type, like 'sync', 'python' or 'join'
:rtype: string
"""
return self.recipe_settings["type"]
@property
def str_payload(self):
"""
The raw "payload" of the recipe.
This is exactly the data persisted on disk.
:return: for code recipes, the payload will be the script of the recipe. For visual recipes,
the payload is a JSON of settings that are specific to the recipe type, like the
definitions of the aggregations for a grouping recipe.
:rtype: string
"""
self._payload_to_str()
return self._str_payload
@str_payload.setter
def str_payload(self, payload):
self._str_payload = payload
self._obj_payload = None
@property
def obj_payload(self):
"""
The "payload" of the recipe, parsed from JSON.
.. note::
Do not use on code recipes, their payload isn't JSON-encoded.
:return: settings that are specific to the recipe type, like the definitions of the
aggregations for a grouping recipe.
:rtype: dict
"""
self._payload_to_obj()
return self._obj_payload
@property
def raw_params(self):
"""
The non-payload settings of the recipe.
:return: recipe type-specific settings that aren't stored in the payload. Typically
this comprises engine settings.
:rtype: dict
"""
return self.recipe_settings["params"]
def _payload_to_str(self):
if self._obj_payload is not None:
self._str_payload = json.dumps(self._obj_payload)
self._obj_payload = None
if self._str_payload is not None:
self.data["payload"] = self._str_payload
def _payload_to_obj(self):
if self._str_payload is not None:
self._obj_payload = json.loads(self._str_payload)
self._str_payload = None
def get_recipe_raw_definition(self):
"""
Get the recipe definition.
:return: the part of the recipe's settings that aren't stored in the payload, as a dict. Notable fields are:
* **name** and **projectKey** : identifiers of the recipe
* **type** : type of the recipe
* **params** : type-specific parameters of the recipe (on top of what is in the payload)
* **inputs** : input roles to the recipe, as a dict of role name to role, where a role is a dict with an **items** field consisting of a list of one dict per input object. Each individual input has fields:
* **ref** : a dataset name or a managed folder id or a saved model id. Should be prefixed by the project key for exposed items, like in "PROJECT_KEY.dataset_name"
* **deps** : for partitioned inputs, a list of partition dependencies mapping output dimensions to dimensions in this input. Each partition dependency is a dict.
* **outputs** : output roles to the recipe, as a dict of role name to role, where a role is a dict with a **items** field consisting of a list of one dict per output object. Each individual output has fields:
* **ref** : a dataset name or a managed folder id or a saved model id. Should be prefixed by the project key for exposed items, like in "PROJECT_KEY.dataset_name"
* **appendMode** : if True, the recipe should append into the output; if False, the recipe should overwrite the output when running
:rtype: dict
"""
return self.recipe_settings
def get_recipe_inputs(self):
"""
Get the inputs to this recipe.
:rtype: dict
"""
return self.recipe_settings.get('inputs')
def get_recipe_outputs(self):
"""
Get the outputs of this recipe.
:rtype: dict
"""
return self.recipe_settings.get('outputs')
def get_recipe_params(self):
"""
The non-payload settings of the recipe.
:return: recipe type-specific settings that aren't stored in the payload. Typically
this comprises engine settings.
:rtype: dict
"""
return self.recipe_settings.get('params')
def get_payload(self):
"""
The raw "payload" of the recipe.
This is exactly the data persisted on disk.
:return: for code recipes, the payload will be the script of the recipe. For visual recipes,
the payload is a JSON of settings that are specific to the recipe type, like the
definitions of the aggregations for a grouping recipe.
:rtype: string
"""
self._payload_to_str()
return self._str_payload
def get_json_payload(self):
"""
The "payload" of the recipe, parsed from JSON.
.. note::
Do not use on code recipes, their payload isn't JSON-encoded.
:return: settings that are specific to the recipe type, like the definitions of the
aggregations for a grouping recipe.
:rtype: dict
"""
self._payload_to_obj()
return self._obj_payload
def set_payload(self, payload):
"""
Set the payload of this recipe.
:param string payload: the payload, as a string
"""
self._str_payload = payload
self._obj_payload = None
def set_json_payload(self, payload):
"""
Set the payload of this recipe.
:param dict payload: the payload, as a dict. Will be converted to JSON internally.
"""
self._str_payload = None
self._obj_payload = payload
def has_input(self, input_ref):
"""
Whether a ref is part of the recipe's inputs.
:param string input_ref: a ref to an object in DSS, i.e. a dataset name or a managed folder id or a saved model id.
Should be prefixed by the project key for exposed items, like in "PROJECT_KEY.dataset_name"
:rtype: boolean
"""
inputs = self.get_recipe_inputs()
for (input_role_name, input_role) in inputs.items():
for item in input_role.get("items", []):
if item.get("ref", None) == input_ref:
return True
return False
def has_output(self, output_ref):
"""
Whether a ref is part of the recipe's outputs.
:param string output_ref: a ref to an object in DSS, i.e. a dataset name or a managed folder id or a saved model id.
Should be prefixed by the project key for exposed items, like in "PROJECT_KEY.dataset_name"
:rtype: boolean
"""
outputs = self.get_recipe_outputs()
for (output_role_name, output_role) in outputs.items():
for item in output_role.get("items", []):
if item.get("ref", None) == output_ref:
return True
return False
def replace_input(self, current_input_ref, new_input_ref):
"""
Replaces an input of this recipe by another.
If the **current_input_ref** isn't part of the recipe's inputs, this method has no effect.
:param string current_input_ref: a ref to an object in DSS, i.e. a dataset name or a managed folder id or a saved model id,
that is currently input to the recipe
:param string new_input_ref: a ref to an object in DSS, i.e. a dataset name or a managed folder id or a saved model id, that
**current_input_ref** should be replaced with.
"""
inputs = self.get_recipe_inputs()
for (input_role_name, input_role) in inputs.items():
for item in input_role.get("items", []):
if item.get("ref", None) == current_input_ref:
item["ref"] = new_input_ref
def replace_output(self, current_output_ref, new_output_ref):
"""
Replaces an output of this recipe by another.
If the **current_output_ref** isn't part of the recipe's outputs, this method has no effect.
:param string current_output_ref: a ref to an object in DSS, i.e. a dataset name or a managed folder id or a saved model id,
that is currently output to the recipe
:param string new_output_ref: a ref to an object in DSS, i.e. a dataset name or a managed folder id or a saved model id, that
**current_output_ref** should be replaced with.
"""
outputs = self.get_recipe_outputs()
for (output_role_name, output_role) in outputs.items():
for item in output_role.get("items", []):
if item.get("ref", None) == current_output_ref:
item["ref"] = new_output_ref
def add_input(self, role, ref, partition_deps=None):
"""
Add an input to the recipe.
For most recipes, there is only one role, named "main". Some few recipes have additional roles,
like scoring recipes which have a "model" role. Check the roles known to the recipe with
:meth:`get_recipe_inputs()`.
:param string role: name of the role of the recipe in which to add **ref** as input
:param string ref: a ref to an object in DSS, i.e. a dataset name or a managed folder id or a saved model id
:param list partition_deps: if **ref** points to a partitioned object, a list of partition dependencies, one
per dimension in the partitioning scheme
"""
if partition_deps is None:
partition_deps = []
self._get_or_create_input_role(role)["items"].append({"ref": ref, "deps": partition_deps})
def add_output(self, role, ref, append_mode=False):
"""
Add an output to the recipe.
For most recipes, there is only one role, named "main". Some few recipes have additional roles,
like evaluation recipes which have a "metrics" role. Check the roles known to the recipe with
:meth:`get_recipe_outputs()`.
:param string role: name of the role of the recipe in which to add **ref** as input
:param string ref: a ref to an object in DSS, i.e. a dataset name or a managed folder id or a saved model id
:param list partition_deps: if **ref** points to a partitioned object, a list of partition dependencies, one
per dimension in the partitioning scheme
"""
self._get_or_create_output_role(role)["items"].append({"ref": ref, "appendMode": append_mode})
def _get_or_create_input_role(self, role):
inputs = self.get_recipe_inputs()
if not role in inputs:
role_obj = {"items": []}
inputs[role] = role_obj
return inputs[role]
def _get_or_create_output_role(self, role):
outputs = self.get_recipe_outputs()
if not role in outputs:
role_obj = {"items": []}
outputs[role] = role_obj
return outputs[role]
def _get_flat_inputs(self):
ret = []
for role_key, role_obj in self.get_recipe_inputs().items():
for item in role_obj["items"]:
ret.append((role_key, item))
return ret
def _get_flat_outputs(self):
ret = []
for role_key, role_obj in self.get_recipe_outputs().items():
for item in role_obj["items"]:
ret.append((role_key, item))
return ret
def get_flat_input_refs(self):
"""
List all input refs of this recipe, regardless of the input role.
:return: a list of refs, i.e. of dataset names or managed folder ids or saved model ids
:rtype: list[string]
"""
ret = []
for role_key, role_obj in self.get_recipe_inputs().items():
for item in role_obj["items"]:
ret.append(item["ref"])
return ret
def get_flat_output_refs(self):
"""
List all output refs of this recipe, regardless of the input role.
:return: a list of refs, i.e. of dataset names or managed folder ids or saved model ids
:rtype: list[string]
"""
ret = []
for role_key, role_obj in self.get_recipe_outputs().items():
for item in role_obj["items"]:
ret.append(item["ref"])
return ret
class DSSRecipeDefinitionAndPayload(DSSRecipeSettings):
"""
Settings of a recipe.
.. note::
Deprecated. Alias to :class:`DSSRecipeSettings`, use :meth:`DSSRecipe.get_settings()` instead.
"""
pass
class RequiredSchemaUpdates(object):
"""
Handle on a set of required updates to the schema of the outputs of a recipe.
.. important::
Do not instantiate directly, use :meth:`DSSRecipe.compute_schema_updates()`
For example, changes can be new columns in the output of a Group recipe when new aggregates
are activated in the recipe's settings.
"""
def __init__(self, recipe, data):
self.recipe = recipe
self.data = data
self.drop_and_recreate = True
self.synchronize_metastore = True
def any_action_required(self):
"""
Whether there are changes at all.
:rtype: boolean
"""
return self.data["totalIncompatibilities"] > 0
def apply(self):
"""
Apply the changes.
All the updates found to be required are applied, for each of the recipe's outputs.
"""
results = []
for computable in self.data["computables"]:
osu = {
"computableType": computable["type"],
# dirty
"computableId": computable["type"] == "DATASET" and computable["datasetName"] or computable["id"],
"newSchema": computable["newSchema"],
"dropAndRecreate": self.drop_and_recreate,
"synchronizeMetastore" : self.synchronize_metastore
}
results.append(self.recipe.client._perform_json("POST",
"/projects/%s/recipes/%s/actions/updateOutputSchema" % (self.recipe.project_key, self.recipe.recipe_name),
body=osu))
return results
#####################################################
# Recipes creation infrastructure
#####################################################
class DSSRecipeCreator(object):
"""
Helper to create new recipes.
.. important::
Do not instantiate directly, use :meth:`dataikuapi.dss.project.DSSProject.new_recipe()` instead.
"""
def __init__(self, type, name, project):
self.project = project
self.recipe_proto = {
"inputs" : {},
"outputs" : {},
"type" : type,
"name" : name
}
self.creation_settings = {
}
def set_name(self, name):
"""
Set the name of the recipe-to-be-created.
:param string name: a recipe name. Should only use alphanum letters and underscores. Cannot contain dots.
"""
self.recipe_proto["name"] = name
def _build_ref(self, object_id, project_key=None):
if project_key is not None and project_key != self.project.project_key:
return project_key + '.' + object_id
else:
return object_id
def _with_input(self, dataset_name, project_key=None, role="main"):
role_obj = self.recipe_proto["inputs"].get(role, None)
if role_obj is None:
role_obj = { "items" : [] }
self.recipe_proto["inputs"][role] = role_obj
role_obj["items"].append({'ref':self._build_ref(dataset_name, project_key)})
return self
def _with_output(self, dataset_name, append=False, role="main"):
role_obj = self.recipe_proto["outputs"].get(role, None)
if role_obj is None:
role_obj = { "items" : [] }
self.recipe_proto["outputs"][role] = role_obj
role_obj["items"].append({'ref':self._build_ref(dataset_name, None), 'appendMode': append})
return self
def _get_input_refs(self):
ret = []
for role_key, role_obj in self.recipe_proto["inputs"].items():
for item in role_obj["items"]:
ret.append(item["ref"])
return ret
def with_input(self, input_id, project_key=None, role="main"):
"""
Add an existing object as input to the recipe-to-be-created.
:param string input_id: name of the dataset, or identifier of the managed folder
or identifier of the saved model
:param string project_key: project containing the object, if different from the one where the recipe is created
:param string role: the role of the recipe in which the input should be added. Most recipes only have one
role named "main".
"""
return self._with_input(input_id, project_key, role)
def with_output(self, output_id, append=False, role="main"):
"""
Add an existing object as output to the recipe-to-be-created.
The output dataset must already exist.
:param string output_id: name of the dataset, or identifier of the managed folder
or identifier of the saved model
:param boolean append: whether the recipe should append or overwrite the output when running
(note: not available for all dataset types)
:param string role: the role of the recipe in which the input should be added. Most recipes only have one
role named "main".
"""
return self._with_output(output_id, append, role)
def build(self):
"""
Create the recipe.
.. note::
Deprecated. Alias to :meth:`create()`
"""
return self.create()
def create(self):
"""
Creates the new recipe in the project, and return a handle to interact with it.
:rtype: :class:`dataikuapi.dss.recipe.DSSRecipe`
"""
self._finish_creation_settings()
return self.project.create_recipe(self.recipe_proto, self.creation_settings)
def set_raw_mode(self):
"""
Activate raw creation mode.
.. caution::
For advanced uses only.
In this mode, the field "recipe_proto" of this recipe creator is used as-is to create the recipe,
and if it exists, the value of creation_settings["rawPayload"] is used as the payload of the
created recipe. No checks of existence or validity of the inputs or outputs are done, and no
output is auto-created.
"""
self.creation_settings["rawCreation"] = True
def _finish_creation_settings(self):
pass
class SingleOutputRecipeCreator(DSSRecipeCreator):
"""
Create a recipe that has a single output.
.. important::
Do not instantiate directly, use :meth:`dataikuapi.dss.project.DSSProject.new_recipe()` instead.
"""
def __init__(self, type, name, project):
DSSRecipeCreator.__init__(self, type, name, project)
self.create_output_dataset = None
self.output_dataset_settings = None
self.create_output_folder = None
self.output_folder_settings = None
def with_existing_output(self, output_id, append=False):
"""
Add an existing object as output to the recipe-to-be-created.
The output dataset must already exist.
:param string output_id: name of the dataset, or identifier of the managed folder
or identifier of the saved model
:param boolean append: whether the recipe should append or overwrite the output when running