-
Notifications
You must be signed in to change notification settings - Fork 38
/
dataflow.py
1874 lines (1602 loc) · 63.1 KB
/
dataflow.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
#!/usr/bin/env python
# -*- coding: utf-8; -*-
# Copyright (c) 2020, 2022 Oracle and/or its affiliates.
# Licensed under the Universal Permissive License v 1.0 as shown at https://oss.oracle.com/licenses/upl/
import os
from datetime import datetime
from types import MethodType
import time
import pathlib
import json
import re
import uuid
from urllib.parse import urlparse
from pathlib import Path
from pandas import DataFrame
from ast import literal_eval
from IPython.display import display
from jinja2 import Environment, PackageLoader
from ads.common import oci_client, auth, logger
from ads.common.utils import FileOverwriteError
from oci.data_flow.models import (
CreateApplicationDetails,
Application,
ApplicationParameter,
ApplicationSummary,
UpdateApplicationDetails,
CreateRunDetails,
Run,
UpdateRunDetails,
RunSummary,
)
from oci.exceptions import ServiceError
from ads.common import utils
from ads.dataflow.dataflowsummary import SummaryList
from ads.config import NB_SESSION_COMPARTMENT_OCID, TENANCY_OCID, OCI_REGION_METADATA
env = Environment(loader=PackageLoader("ads", "templates"))
create_application_details_attributes = CreateApplicationDetails().swagger_types.keys()
update_application_details_attributes = UpdateApplicationDetails().swagger_types.keys()
application_attributes = list(Application().swagger_types.keys())
create_run_details_attributes = CreateRunDetails().swagger_types.keys()
update_run_details_attributes = UpdateRunDetails().swagger_types.keys()
run_attributes = list(Run().swagger_types.keys())
class SPARK_VERSION(str):
v2_4_4 = "2.4.4"
v3_0_2 = "3.0.2"
class DataFlow:
def __init__(
self,
compartment_id=None,
dataflow_base_folder="/home/datascience/dataflow",
os_auth=None,
df_auth=None,
):
# create iff not found dataflow_base_folder
self.dataflow_base_folder = dataflow_base_folder
self.os_auth = os_auth if os_auth else auth.default_signer()
self.df_auth = df_auth if df_auth else auth.default_signer()
self.compartment_id = (
NB_SESSION_COMPARTMENT_OCID if compartment_id is None else compartment_id
)
if self.compartment_id is None:
raise ValueError("compartment_id needs to be specified.")
self.display_name = None
self.driver_shape = None
self.executor_shape = None
self.file_uri = None
self.archive_uri = None
self.language = None
self.logs_bucket_uri = None
self.num_executors = None
self.spark_version = None
self.warehouse_bucket_uri = None
self.object_storage_client = oci_client.OCIClientFactory(
**self.os_auth
).object_storage
self.df_client = oci_client.OCIClientFactory(**self.df_auth).dataflow
self.region = (
self.df_auth["config"]["region"]
if "config" in self.df_auth and "region" in self.df_auth["config"]
else (
literal_eval(OCI_REGION_METADATA)["regionIdentifier"]
if OCI_REGION_METADATA
else None
)
)
if not self.region:
logger.warning(
"Region information not found from oci config file. Set region in the OCI config file"
)
try:
self.namespace = self.object_storage_client.get_namespace().data
except ServiceError as se:
if se.status == 404:
raise ValueError(
f'The compartment_id "{self.compartment_id}" have to be '
f"in same tenancy as current user "
) from se
else:
raise
self.short_id_index = {}
# Currently Data Flow only supports VM.Standard.2 series
# VM_shapes dict needs to be updated if any change from Data Flow
self.VM_shapes = {
"VM.Standard2.1",
"VM.Standard2.2",
"VM.Standard2.4",
"VM.Standard2.8",
"VM.Standard2.16",
"VM.Standard2.24", # not available in some tenancy
}
def __iter__(self):
return self.list_apps().__iter__()
def __len__(self):
return len(self.list_apps())
def _decorate_app(self, app):
app.swagger_types["short_id"] = "str"
app.ocid = app.id
def to_dataframe(app_self):
if "arguments" in application_attributes:
application_attributes.remove("arguments")
df = DataFrame.from_dict(
{
key: getattr(app_self, key)
for key in application_attributes
if hasattr(app_self, key)
},
orient="index",
columns=[""],
)
return df
def show_in_notebook(app_self):
"""
Describe the project by showing its properties
"""
display(app_self)
def _repr_html_(app_self):
return (
app_self.to_dataframe()
.style.set_properties(**{"margin-left": "0px"})
.render()
)
app.to_dataframe = MethodType(to_dataframe, app)
app.show_in_notebook = MethodType(show_in_notebook, app)
app._repr_html_ = MethodType(_repr_html_, app)
return app
def prepare_app(
self,
display_name: str,
script_bucket: str,
pyspark_file_path: str,
spark_version: str = SPARK_VERSION.v2_4_4,
compartment_id: str = None,
archive_path: str = None,
archive_bucket: str = None,
logs_bucket: str = "dataflow-logs",
driver_shape: str = "VM.Standard2.4",
executor_shape: str = "VM.Standard2.4",
num_executors: int = 1,
arguments: list = [],
script_parameters: dict = [],
) -> dict:
"""
Check if the parameters provided by users to create an application are
valid and then prepare app_configuration for creating an app or saving
for future reuse.
Parameters
----------
display_name: str, required
A user-friendly name. This name is not necessarily unique.
script_bucket: str, required
bucket in object storage to upload the pyspark file
pyspark_file_path: str, required
path to the pyspark file
spark_version: str
Allowed values are "2.4.4", "3.0.2".
compartment_id: str
OCID of the compartment to create a dataflow app. If not
provided, compartment_id will use the same as the notebook session.
archive_path: str, optional
path to the archive file
archive_bucket: str, optional
bucket in object storage to upload the archive file
logs_bucket: str, default is 'dataflow-logs'
bucket in object storage to put run logs
driver_shape: str
The value to assign to the driver_shape property of this
CreateApplicationDetails.
Allowed values for this property are: "VM.Standard2.1",
"VM.Standard2.2", "VM.Standard2.4", "VM.Standard2.8",
"VM.Standard2.16", "VM.Standard2.24".
executor_shape: str
The value to assign to the executor_shape property of this
CreateApplicationDetails.
Allowed values for this property are: "VM.Standard2.1",
"VM.Standard2.2", "VM.Standard2.4", "VM.Standard2.8",
"VM.Standard2.16", "VM.Standard2.24".
num_executors: int
The number of executor VMs requested.
arguments: list of str
The values passed into the command line string to run the application
script_parameters: dict
The value of the parameters passed to the running application as
command line arguments for the pyspark script.
Returns
-------
app_configuration: dictionary containing all the validated params for CreateApplicationDetails.
"""
if not self._check_bucket_exist(script_bucket):
raise ValueError(
"The bucket {} does not exist in object storage".format(script_bucket)
)
else:
self.script_bucket = script_bucket
if not self._check_bucket_exist(logs_bucket):
raise ValueError(
"The log bucket {} does not exist in object storage".format(logs_bucket)
)
else:
self.logs_bucket_uri = (
self.warehouse_bucket_uri
) = f"oci://{logs_bucket}@{self.namespace}"
# check if local path of script file is valid
self._check_valid_path(pyspark_file_path)
if archive_path:
# check if local path of archive file is valid
self._check_valid_path(archive_path)
if archive_bucket is None:
# use script bucket by default if archive_bucket not provided
archive_bucket = script_bucket
else:
if not self._check_bucket_exist(archive_bucket):
raise ValueError(
"The bucket {} does not exist in object storage".format(
archive_bucket
)
)
# check whether the params have valid input type and value
self._check_valid_param(
display_name, driver_shape, executor_shape, num_executors
)
# when user try to specify a non-python application, we throw warnings
if self.language is not None and self.language != "PYTHON":
logger.warning("ADS only supports Python.")
app_compartment_id = (
self.compartment_id if compartment_id is None else compartment_id
)
app_configuration = {
"compartment_id": app_compartment_id,
"language": "PYTHON",
"pyspark_file_path": pyspark_file_path,
"script_bucket": self.script_bucket,
"archive_path": archive_path,
"archive_bucket": archive_bucket,
"logs_bucket": logs_bucket,
"display_name": self.display_name,
"driver_shape": self.driver_shape,
"executor_shape": self.executor_shape,
"num_executors": self.num_executors,
"spark_version": spark_version,
}
# here we handle the case where users specify arguments
if arguments:
# check if the arguments are valid
for arg in arguments:
if not isinstance(arg, str):
raise TypeError("Arguments must be a list of str.")
if re.match("\$\{([^}]+)\}", arg):
arg_name = arg.strip("${}")
if " " in arg_name:
raise ValueError(
f"With {arg} in the format of "
"${var}, space is not allowed in "
f"{arg_name}"
)
if arg_name not in script_parameters:
logger.warning(
f"With `{arg}` in the format of "
"`${var}`, "
f"the argument `{arg_name}` will be replaced by the value provided in script parameters when passed in. "
f"While arguments not in this format are passed to the PySpark script verbatim."
f"Therefore, `{arg_name}` must be a valid key in script parameters."
)
raise KeyError(
f"{arg_name} doesn't exist in script parameters, thus {arg} is not valid."
)
# convert script parameters to be a list of tuples
app_configuration["script_parameters"] = [
(k, script_parameters[k]) for k in script_parameters
]
app_configuration["arguments"] = arguments
return app_configuration
def template(
self,
job_type: str = "standard_pyspark",
script_str: str = "",
file_dir: str = None,
file_name: str = None,
) -> str:
"""
Populate a prewritten pyspark or sparksql python script with
user's choice to write additional lines and save in local directory.
Parameters
----------
job_type: str, default is 'standard_pyspark'
Currently supports two types, 'standard_pyspark' or 'sparksql'
script_str: str, optional, default is ''
code provided by user to write in the python script
file_dir: str, optional
Directory to save the python script in local directory
file_name: str, optional
name of the python script to save to the local directory
Returns
-------
script_path: str
Path to the template generated python file in local directory
"""
if file_dir is None:
file_dir = self.dataflow_base_folder
if not os.path.isdir(file_dir):
os.mkdir(file_dir)
if file_name is None:
creation_time = datetime.now().strftime("%Y-%m-%d-%H-%M-%S")
file_name = f"{job_type}_{creation_time}.py"
script_path = os.path.join(file_dir, file_name)
if os.path.exists(script_path):
logger.info(f"Overwriting {script_path}.")
if job_type == "standard_pyspark":
self._get_pyspark_template(script_path, script_str)
elif job_type == "sparksql":
self._get_sparksql_template(script_path, script_str)
else:
raise ValueError(
"Currently only supports template for two job types, 'standard_pyspark' or 'sparksql'"
)
relative_path = os.path.relpath(script_path)
# FileLink has to be tested with router to check compatibility. Till then let us comment it (ODSC-8310)
# return display(FileLink(relative_path))
logger.info(f"Code generated: {script_path}.")
return script_path
def _get_pyspark_template(self, script_path, script_str: str = ""):
"""
Create a prewriiten pyspark script
Parameters
----------
script_path: str
Path to the template generated python file in local directory
script_str: str, optional, default is ''
code provided by user to write in the python script
Returns
-------
None
"""
pyspark_template = env.get_template("dataflow_pyspark.jinja2")
with open(script_path, "w") as fp:
fp.write(pyspark_template.render(script_str=script_str))
def _get_sparksql_template(self, script_path, script_str):
"""
Create a prewriiten sparksql python script
Parameters
----------
script_path: str
Path to the template generated python file in local directory
script_str: str, optional, default is ''
code provided by user to write in the python script
Returns
-------
None
"""
pyspark_template = env.get_template("dataflow_sparksql.jinja2")
with open(script_path, "w") as fp:
fp.write(pyspark_template.render(script_str=script_str))
def _check_valid_path(self, file_path):
"""
Returns
-------
valid_path: bool
whether the provided file path is valid
"""
file_dir = os.path.dirname(file_path)
if len(file_dir) > 0 and not os.path.exists(file_dir):
raise ValueError("The directoy of file {} does not exist".format(file_path))
elif not os.path.exists(file_path):
raise ValueError(
" The directoy of the file {} is valid but the file does not exist".format(
file_path
)
)
return True
def _check_valid_param(
self, display_name, driver_shape, executor_shape, num_executors
):
"""
Returns
-------
valid_param: bool
whether the params have valid input type and value
"""
if not isinstance(display_name, str):
raise TypeError("param 'display_name' must be string")
else:
self.display_name = display_name
if not isinstance(driver_shape, str):
raise TypeError("param 'driver_shape' must be string")
elif driver_shape not in self.VM_shapes:
raise ValueError("param 'driver_shape' is not a valid VM shape")
else:
self.driver_shape = driver_shape
if not isinstance(executor_shape, str):
raise TypeError("param 'executor_shape' must be string")
elif executor_shape not in self.VM_shapes:
raise ValueError("param 'executor_shape' is not a valid VM shape")
else:
self.executor_shape = executor_shape
if not isinstance(num_executors, int):
raise TypeError("param 'num_executors' must be an integer")
elif num_executors < 1:
raise ValueError("param 'num_executors' has a minimum value of 1")
else:
self.num_executors = num_executors
return True
def _check_bucket_exist(self, bucket_name: str) -> bool:
"""
Returns
-------
bucket_exist: bool
whether the bucket already exists in the object storage
"""
try:
bucket_response = self.object_storage_client.head_bucket(
self.namespace, bucket_name
)
except ServiceError as se:
if se.status == 404:
raise KeyError(
f"The bucket {bucket_name} does not exist in object storage"
) from se
else:
raise
return True
def _download(self, bucket_name, script_uri, target_folder):
remote_pyspark_file_name = urlparse(script_uri).path[1:]
local_pyspark_file_name = remote_pyspark_file_name
if "/" in remote_pyspark_file_name:
local_pyspark_file_name = remote_pyspark_file_name.replace("/", "_")
if local_pyspark_file_name.endswith(".py"):
local_pyspark_file_name = (
local_pyspark_file_name.rstrip(".py")
+ "_"
+ str(uuid.uuid4())[-6:]
+ ".py"
)
else:
local_pyspark_file_name += "_" + str(uuid.uuid4())[-6:]
destination_pyspark_file = f"{target_folder}/{local_pyspark_file_name}"
if not os.path.exists(destination_pyspark_file):
with open(destination_pyspark_file, "wb") as f:
f.write(
self.object_storage_client.get_object(
self.namespace, bucket_name, remote_pyspark_file_name
).data.content
)
return destination_pyspark_file
else:
raise ValueError(
f"The app script file ({remote_pyspark_file_name}) already exists in {target_folder}"
)
def _create_or_load_app(
self,
app_config: dict,
file_uri: str,
archive_uri: str = None,
app_dir: str = None,
) -> object:
with utils.get_progress_bar(2) as progress:
progress.update()
#
# common to load & create
#
self.display_name = app_config["display_name"]
self.driver_shape = app_config["driver_shape"]
self.executor_shape = app_config["executor_shape"]
self.num_executors = app_config["num_executors"]
self.logs_bucket_uri = (
self.warehouse_bucket_uri
) = f"oci://{app_config['logs_bucket']}@{self.namespace}"
app_details = CreateApplicationDetails(
compartment_id=app_config["compartment_id"],
language="PYTHON",
display_name=self.display_name,
driver_shape=self.driver_shape,
executor_shape=self.executor_shape,
file_uri=file_uri,
archive_uri=archive_uri,
logs_bucket_uri=self.logs_bucket_uri,
num_executors=self.num_executors,
spark_version=app_config.get("spark_version", SPARK_VERSION.v2_4_4),
warehouse_bucket_uri=self.warehouse_bucket_uri,
arguments=app_config.get("arguments", []),
parameters=[
ApplicationParameter(name=k, value=str(v))
for (k, v) in app_config.get("script_parameters", [])
],
)
new_app = self.df_client.create_application(app_details)
progress.update("Done")
# # add app_config to app obj as an attribute
# new_app.data.configuration = app_config
# make app dir
if app_dir is None:
app_dir = f"{self.dataflow_base_folder}/{self.display_name}_{str(uuid.uuid4())[-6:]}"
pathlib.Path(app_dir).mkdir(parents=True, exist_ok=True)
return DataFlowApp(
app_config,
new_app,
app_dir,
f"https://console."
f"{self.region}.oraclecloud.com/data-flow/apps/details/{new_app.data.id}",
os_auth=self.os_auth,
df_auth=self.df_auth,
)
def create_app(
self, app_config: dict, overwrite_script=False, overwrite_archive=False
) -> object:
"""
Create a new dataflow application with the supplied app config.
app_config contains parameters needed to create a new application,
according to oci.data_flow.models.CreateApplicationDetails.
Parameters
----------
app_config: dict
the config file that contains all necessary parameters used to create a dataflow app
overwrite_script: bool
whether to overwrite the existing pyscript script on Object Storage
overwrite_archive: bool
whether to overwrite the existing archive file on Object Storage
Returns
-------
df_app: oci.dataflow.models.Application
New dataflow application.
"""
#
# upload pyspark_file_path to OCI object storage
#
try:
self._upload(
app_config["pyspark_file_path"],
app_config["script_bucket"],
overwrite=overwrite_script,
)
except FileOverwriteError:
raise ValueError(
"You have a file with the same key in your bucket on object storage. Rename your file or set overwrite_script option to True."
)
script_name = os.path.basename(app_config["pyspark_file_path"])
file_uri = f'oci://{app_config["script_bucket"]}@{self.namespace}/{script_name}'
# upload archive file to object storage if specified
if app_config["archive_path"] is None:
return self._create_or_load_app(app_config, file_uri)
else:
try:
self._upload(
app_config["archive_path"],
app_config["archive_bucket"],
overwrite=overwrite_archive,
)
except FileOverwriteError:
raise ValueError(
"You have a file with the same key in your bucket on object storage. Rename your file or set overwrite_archive option to True."
)
archive_name = os.path.basename(app_config["archive_path"])
archive_uri = (
f'oci://{app_config["archive_bucket"]}@{self.namespace}/{archive_name}'
)
return self._create_or_load_app(
app_config, file_uri, archive_uri=archive_uri
)
def _upload(self, local_path, bucket_name, overwrite=False):
"""
upload local files to object storage
Parameters
----------
local_path: str
the file path
bucket_name: str
bucket name on object storage to upload the file
overwrite: bool
whether to overwrite the existing file on Object Storage
Returns
-------
None
"""
object_name = os.path.basename(local_path)
if self._check_object_exist(object_name, bucket_name):
if not overwrite:
raise FileOverwriteError()
else:
logger.warning(
"You have a file with the same key in your bucket on object storage. It will be overwritten per your request."
)
with open(local_path, "rb") as in_file:
self.object_storage_client.put_object(
self.namespace, bucket_name, object_name, in_file
)
logger.info(f"Finished uploading `{object_name}`.")
def _check_object_exist(self, object_name: str, bucket_name: str) -> bool:
"""
Parameters
----------
object_name: str
the file name on object storage
bucket_name: str
bucket name on object storage
Returns
-------
bool
whether the file already exists in the bucket in object storage
"""
object_exist = self._check_object_exist_helper(
object_name, bucket_name, start=None
)
if object_exist:
logger.info(
f"The file object `{object_name}` "
f"already exists in bucket `{bucket_name}`."
)
else:
logger.info(
f"The file object `{object_name}` "
f"does not exist in bucket `{bucket_name}` and will be uploaded."
)
return object_exist
def _check_object_exist_helper(
self, object_name: str, bucket_name: str, start: str = None
) -> bool:
"""
Parameters
----------
object_name: str
the file name on object storage
bucket_name: str
bucket name on object storage
start: str
Object names returned by a list query must be greater or equal to this parameter.
Returns
-------
bool
whether the file already exists in the bucket in object storage
"""
object_exist = False
list_objects_response = self.object_storage_client.list_objects(
self.namespace, bucket_name, start=start
)
objects_list = list_objects_response.data.objects
for object_item in objects_list:
if object_item.name == object_name:
object_exist = True
next_start_with = list_objects_response.data.next_start_with
if object_exist or not next_start_with:
return object_exist
else:
return self._check_object_exist_helper(
object_name, bucket_name, start=next_start_with
)
def list_apps(
self,
include_deleted: bool = False,
compartment_id: str = None,
datetime_format: str = utils.date_format,
**kwargs,
) -> object:
"""
List all apps in a given compartment, or in the current notebook session's compartment.
Parameters
----------
include_deleted: bool, optional, default=False
Whether to include deleted apps in the returned list.
compartment_id: str, optional, default: NB_SESSION_COMPARTMENT_OCID
The compartment specified to list apps.
datetime_format: str, optional, default: '%Y-%m-%d %H:%M:%S'
Change format for date time fields.
Returns
-------
dsl: List
List of Dataflow applications.
"""
app_compartment_id = (
self.compartment_id if compartment_id is None else compartment_id
)
list_applications_response = self.df_client.list_applications(
app_compartment_id, **kwargs
).data
# handle empty list
if list_applications_response is None:
logger.warning("No applications found.")
return
application_list_filtered = [
self._decorate_app(app)
for app in list_applications_response
if include_deleted
or Application.lifecycle_state != ApplicationSummary.LIFECYCLE_STATE_DELETED
]
dsl = SummaryList(
entity_list=application_list_filtered,
datetime_format=datetime_format,
)
self.short_id_index.update(dsl.short_id_index)
return dsl
def get_app(self, app_id: str):
"""
Get the Project based on app_id.
Parameters
----------
app_id: str, required
The OCID of the dataflow app to get.
Returns
-------
app: oci.dataflow.models.Application
The oci.dataflow.models.Application with the matching ID.
"""
if not app_id.startswith("ocid"):
app_id = self.short_id_index[app_id]
try:
get_app_response = self.df_client.get_application(app_id)
except ServiceError as se:
if se.status == 404:
raise KeyError(se.message) from se
else:
raise
return self._decorate_app(get_app_response.data)
def load_app(
self,
app_id: str,
target_folder: str = None,
) -> object:
"""
Load an existing dataflow application based on application id.
The existing dataflow application can be created either from dataflow
service or the dataflow integration of ADS.
Parameters
----------
app_id: str, required
The OCID of the dataflow app to load.
target_folder: str, optional,
the folder to store the local artifacts of this application.
If not specified, the target_folder will use the
dataflow_base_folder by default.
Returns
-------
dfa: ads.dataflow.dataflow.DataFlowApp
A dataflow application of type ads.dataflow.dataflow.DataFlowApp
"""
# support short id when loading an application by getting ocid based on
# provided short id
if not app_id.startswith("ocid"):
app_id = self.short_id_index[app_id]
# get app response that fetched using df client
try:
get_app_response = self.df_client.get_application(app_id)
except ServiceError as se:
if se.status == 404:
raise KeyError(se.message) from se
else:
raise
# if users try to load a non-python application, we throw a warning
if get_app_response.data.language != "PYTHON":
logger.warning("ADS only supports Python.")
return
# for apps created with default logs bucket, logs_bucket_uri attribute in app response will be empty string
# set default value manually for logs_bucket
if get_app_response.data.logs_bucket_uri == "":
logger.info(
"Using the default logs bucket 'dataflow-logs'. Set the parameter `logs_bucket_uri` to use a different bucket."
)
logs_bucket = "dataflow-logs"
else:
logs_bucket = re.split(r"[@/]", get_app_response.data.logs_bucket_uri)[2]
# reform app config from app response
app_config = {
"compartment_id": get_app_response.data.compartment_id,
"language": get_app_response.data.language,
"script_bucket": re.split(r"[@/]", get_app_response.data.file_uri)[2],
"logs_bucket": logs_bucket,
"archive_path": None,
"archive_bucket": None,
"display_name": get_app_response.data.display_name,
"driver_shape": get_app_response.data.driver_shape,
"executor_shape": get_app_response.data.executor_shape,
"num_executors": get_app_response.data.num_executors,
"spark_version": get_app_response.data.spark_version,
"arguments": get_app_response.data.arguments,
"script_parameters": [
(param.name, param.value) for param in get_app_response.data.parameters
],
}
# set the default value to target_folder to dataflow_base_folder
if target_folder is None:
target_folder = self.dataflow_base_folder
app_dir = (
f"{target_folder}/{app_config['display_name']}_{str(uuid.uuid4())[-6:]}"
)
pathlib.Path(app_dir).mkdir(parents=True, exist_ok=True)
app_config["pyspark_file_path"] = self._download(
app_config["script_bucket"], get_app_response.data.file_uri, app_dir
)
if get_app_response.data.archive_uri != "":
app_config["archive_bucket"] = re.split(
r"[@/]", get_app_response.data.archive_uri
)[2]
app_config["archive_path"] = self._download(
app_config["archive_bucket"], get_app_response.data.archive_uri, app_dir
)
return DataFlowApp(
app_config,
get_app_response,
app_dir,
f"https://console.{self.region}.oraclecloud.com/data-flow/apps/details/{get_app_response.data.id}",
os_auth=self.os_auth,
df_auth=self.df_auth,
)
class DataFlowApp(DataFlow):
def __init__(self, app_config, app_response, app_dir, oci_link, **kwargs):
super().__init__(compartment_id=app_config["compartment_id"], **kwargs)
self._config = app_config
self.app_response = app_response
self.app_dir = app_dir
self._oci_link = oci_link
def __iter__(self):
return self.list_runs().__iter__()
def __len__(self):
return len(self.list_runs())
def __repr__(self):
return self._config["display_name"]
def _decorate_run(self, run):
run.swagger_types["short_id"] = "str"
run.ocid = run.id
def to_dataframe(run_self):
if "arguments" in run_attributes:
run_attributes.remove("arguments")
df = DataFrame.from_dict(
{
key: getattr(run_self, key)
for key in run_attributes
if hasattr(run_self, key)
},
orient="index",
columns=[""],
)
return df
def show_in_notebook(run_self):
"""
Describe the project by showing it's properties
"""
display(run_self)
def _repr_html_(run_self):
return (
run_self.to_dataframe()
.style.set_properties(**{"margin-left": "0px"})
.render()
)
run.to_dataframe = MethodType(to_dataframe, run)
run.show_in_notebook = MethodType(show_in_notebook, run)
run._repr_html_ = MethodType(_repr_html_, run)
return run
@property
def config(self) -> dict:
"""
Retrieve the app_config file used to create the data flow app