forked from logicalclocks/hopsworks-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstorage_connector.py
1771 lines (1542 loc) · 62.1 KB
/
storage_connector.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
#
# Copyright 2020 Logical Clocks AB
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from __future__ import annotations
import base64
import logging
import os
import posixpath
import re
import warnings
from abc import ABC, abstractmethod
from typing import Any, Dict, List, Optional, TypeVar, Union
import humps
import pandas as pd
from hopsworks_common import client
from hopsworks_common.core.constants import HAS_NUMPY, HAS_POLARS
from hsfs import engine
from hsfs.core import storage_connector_api
if HAS_NUMPY:
import numpy as np
if HAS_POLARS:
import polars as pl
_logger = logging.getLogger(__name__)
class StorageConnector(ABC):
HOPSFS = "HOPSFS"
S3 = "S3"
JDBC = "JDBC"
REDSHIFT = "REDSHIFT"
ADLS = "ADLS"
SNOWFLAKE = "SNOWFLAKE"
KAFKA = "KAFKA"
GCS = "GCS"
BIGQUERY = "BIGQUERY"
NOT_FOUND_ERROR_CODE = 270042
def __init__(
self,
id: Optional[int],
name: str,
description: Optional[str],
featurestore_id: int,
**kwargs,
) -> None:
self._id = id
self._name = name
self._description = description
self._featurestore_id = featurestore_id
self._storage_connector_api = storage_connector_api.StorageConnectorApi()
@classmethod
def from_response_json(
cls, json_dict: Dict[str, Any]
) -> Union[
"StorageConnector",
"HopsFSConnector",
"S3Connector",
"RedshiftConnector",
"AdlsConnector",
"SnowflakeConnector",
]:
json_decamelized = humps.decamelize(json_dict)
_ = json_decamelized.pop("type", None)
for subcls in cls.__subclasses__():
if subcls.type == json_decamelized["storage_connector_type"]:
_ = json_decamelized.pop("storage_connector_type")
return subcls(**json_decamelized)
raise ValueError
def update_from_response_json(
self, json_dict: Dict[str, Any]
) -> Union[
"StorageConnector",
"HopsFSConnector",
"S3Connector",
"RedshiftConnector",
"AdlsConnector",
"SnowflakeConnector",
]:
json_decamelized = humps.decamelize(json_dict)
_ = json_decamelized.pop("type", None)
if self.type == json_decamelized["storage_connector_type"]:
_ = json_decamelized.pop("storage_connector_type")
self.__init__(**json_decamelized)
else:
raise ValueError("Failed to update storage connector information.")
return self
def to_dict(self) -> Dict[str, Optional[Union[int, str]]]:
return {
"id": self._id,
"name": self._name,
"featurestoreId": self._featurestore_id,
"storageConnectorType": self.type,
}
@property
def type(self) -> Optional[str]:
"""Type of the connector as string, e.g. "HOPFS, S3, ADLS, REDSHIFT, JDBC or SNOWFLAKE."""
return self._type
@property
def id(self) -> Optional[int]:
"""Id of the storage connector uniquely identifying it in the Feature store."""
return self._id
@property
def name(self) -> str:
"""Name of the storage connector."""
return self._name
@property
def description(self) -> Optional[str]:
"""User provided description of the storage connector."""
return self._description
@abstractmethod
def spark_options(self) -> None:
pass
def prepare_spark(self, path: Optional[str] = None) -> Optional[str]:
return path
def read(
self,
query: Optional[str] = None,
data_format: Optional[str] = None,
options: Optional[Dict[str, Any]] = None,
path: Optional[str] = None,
dataframe_type: str = "default",
) -> Union[
TypeVar("pyspark.sql.DataFrame"),
TypeVar("pyspark.RDD"),
pd.DataFrame,
np.ndarray,
pl.DataFrame,
]:
"""Reads a query or a path into a dataframe using the storage connector.
Note, paths are only supported for object stores like S3, HopsFS and ADLS, while
queries are meant for JDBC or databases like Redshift and Snowflake.
# Arguments
query: By default, the storage connector will read the table configured together
with the connector, if any. It's possible to overwrite this by passing a SQL
query here. Defaults to `None`.
data_format: When reading from object stores such as S3, HopsFS and ADLS, specify
the file format to be read, e.g. `csv`, `parquet`.
options: Any additional key/value options to be passed to the connector.
path: Path to be read from within the bucket of the storage connector. Not relevant
for JDBC or database based connectors such as Snowflake, JDBC or Redshift.
dataframe_type: str, optional. The type of the returned dataframe.
Possible values are `"default"`, `"spark"`,`"pandas"`, `"polars"`, `"numpy"` or `"python"`.
Defaults to "default", which maps to Spark dataframe for the Spark Engine and Pandas dataframe for the Python engine.
# Returns
`DataFrame`.
"""
return engine.get_instance().read(
self, data_format, options or {}, path, dataframe_type
)
def refetch(self) -> None:
"""
Refetch storage connector.
"""
self._storage_connector_api.refetch(self)
def _get_path(self, sub_path: str) -> None:
return None
def connector_options(self) -> Dict[str, Any]:
"""Return prepared options to be passed to an external connector library.
Not implemented for this connector type.
"""
return {}
def get_feature_groups_provenance(self):
"""Get the generated feature groups using this storage connector, based on explicit
provenance. These feature groups can be accessible or inaccessible. Explicit
provenance does not track deleted generated feature group links, so deleted
will always be empty.
For inaccessible feature groups, only a minimal information is returned.
# Returns
`Links`: the feature groups generated using this storage connector or `None` if none were created
# Raises
`hopsworks.client.exceptions.RestAPIError`: In case the backend encounters an issue
"""
links = self._storage_connector_api.get_feature_groups_provenance(self)
if not links.is_empty():
return links
def get_feature_groups(self):
"""Get the feature groups using this storage connector, based on explicit
provenance. Only the accessible feature groups are returned.
For more items use the base method - get_feature_groups_provenance
# Returns
`List[FeatureGroup]`: List of feature groups.
"""
feature_groups_provenance = self.get_feature_groups_provenance()
if feature_groups_provenance and (
feature_groups_provenance.inaccessible or feature_groups_provenance.deleted
):
_logger.info(
"There are deleted or inaccessible feature groups. For more details access `get_feature_groups_provenance`"
)
if feature_groups_provenance and feature_groups_provenance.accessible:
return feature_groups_provenance.accessible
else:
return []
class HopsFSConnector(StorageConnector):
type = StorageConnector.HOPSFS
def __init__(
self,
id: Optional[int],
name: str,
featurestore_id: int,
description: Optional[str] = None,
# members specific to type of connector
hopsfs_path: Optional[str] = None,
dataset_name: Optional[str] = None,
**kwargs,
) -> None:
super().__init__(id, name, description, featurestore_id)
# HopsFS
self._hopsfs_path = hopsfs_path
self._dataset_name = dataset_name
def spark_options(self) -> Dict[str, Any]:
"""Return prepared options to be passed to Spark, based on the additional
arguments.
"""
return {}
def _get_path(self, sub_path: str) -> str:
return os.path.join(self._hopsfs_path, sub_path)
class S3Connector(StorageConnector):
type = StorageConnector.S3
def __init__(
self,
id: Optional[int],
name: str,
featurestore_id: Optional[int],
description: Optional[str] = None,
# members specific to type of connector
access_key: Optional[str] = None,
secret_key: Optional[str] = None,
server_encryption_algorithm: Optional[str] = None,
server_encryption_key: Optional[str] = None,
bucket: Optional[str] = None,
path: Optional[str] = None,
region: Optional[str] = None,
session_token: Optional[str] = None,
iam_role: Optional[str] = None,
arguments: Optional[Dict[str, Any]] = None,
**kwargs,
) -> None:
super().__init__(id, name, description, featurestore_id)
# S3
self._access_key = access_key
self._secret_key = secret_key
self._server_encryption_algorithm = server_encryption_algorithm
self._server_encryption_key = server_encryption_key
self._bucket = bucket
self._path = path
self._region = region
self._session_token = session_token
self._iam_role = iam_role
self._arguments = (
{opt["name"]: opt["value"] for opt in arguments} if arguments else {}
)
@property
def access_key(self) -> Optional[str]:
"""Access key."""
return self._access_key
@property
def secret_key(self) -> Optional[str]:
"""Secret key."""
return self._secret_key
@property
def server_encryption_algorithm(self) -> Optional[str]:
"""Encryption algorithm if server-side S3 bucket encryption is enabled."""
return self._server_encryption_algorithm
@property
def server_encryption_key(self) -> Optional[str]:
"""Encryption key if server-side S3 bucket encryption is enabled."""
return self._server_encryption_key
@property
def bucket(self) -> Optional[str]:
"""Return the bucket for S3 connectors."""
return self._bucket
@property
def region(self) -> Optional[str]:
"""Return the region for S3 connectors."""
return self._region
@property
def session_token(self) -> Optional[str]:
"""Session token."""
return self._session_token
@property
def iam_role(self) -> Optional[str]:
"""IAM role."""
return self._iam_role
@property
def path(self) -> Optional[str]:
"""If the connector refers to a path (e.g. S3) - return the path of the connector"""
return posixpath.join(
"s3://" + self._bucket, *os.path.split(self._path if self._path else "")
)
@property
def arguments(self) -> Optional[Dict[str, Any]]:
return self._arguments
def spark_options(self) -> Dict[str, str]:
"""Return prepared options to be passed to Spark, based on the additional
arguments.
"""
return self._arguments
def prepare_spark(self, path: Optional[str] = None) -> Optional[str]:
"""Prepare Spark to use this Storage Connector.
```python
conn.prepare_spark()
spark.read.format("json").load("s3a://[bucket]/path")
# or
spark.read.format("json").load(conn.prepare_spark("s3a://[bucket]/path"))
```
# Arguments
path: Path to prepare for reading from cloud storage. Defaults to `None`.
"""
self.refetch()
return engine.get_instance().setup_storage_connector(self, path)
def connector_options(self) -> Dict[str, Any]:
"""Return options to be passed to an external S3 connector library"""
self.refetch()
options = {
"access_key": self.access_key,
"secret_key": self.secret_key,
"session_token": self.session_token,
"region": self.region,
}
if self.arguments.get("fs.s3a.endpoint"):
options["endpoint"] = self.arguments.get("fs.s3a.endpoint")
return options
def read(
self,
query: Optional[str] = None,
data_format: Optional[str] = None,
options: Optional[Dict[str, Any]] = None,
path: str = "",
dataframe_type: str = "default",
) -> Union[
TypeVar("pyspark.sql.DataFrame"),
TypeVar("pyspark.RDD"),
pd.DataFrame,
np.ndarray,
pl.DataFrame,
]:
"""Reads a query or a path into a dataframe using the storage connector.
Note, paths are only supported for object stores like S3, HopsFS and ADLS, while
queries are meant for JDBC or databases like Redshift and Snowflake.
# Arguments
query: Not relevant for S3 connectors.
data_format: The file format of the files to be read, e.g. `csv`, `parquet`.
options: Any additional key/value options to be passed to the S3 connector.
path: Path within the bucket to be read.
dataframe_type: str, optional. The type of the returned dataframe.
Possible values are `"default"`, `"spark"`,`"pandas"`, `"polars"`, `"numpy"` or `"python"`.
Defaults to "default", which maps to Spark dataframe for the Spark Engine and Pandas dataframe for the Python engine.
# Returns
`DataFrame`.
"""
self.refetch()
options = (
{**self.spark_options(), **options}
if options is not None
else self.spark_options()
)
if not path.startswith(("s3://", "s3a://")):
path = self._get_path(path)
print(
"Prepending default bucket specified on connector, final path: {}".format(
path
)
)
return engine.get_instance().read(
self, data_format, options, path, dataframe_type
)
def _get_path(self, sub_path: str) -> str:
return posixpath.join(self.path, *os.path.split(sub_path))
class RedshiftConnector(StorageConnector):
type = StorageConnector.REDSHIFT
JDBC_FORMAT = "jdbc"
def __init__(
self,
id: Optional[int],
name: str,
featurestore_id: int,
description: Optional[str] = None,
# members specific to type of connector
cluster_identifier: Optional[str] = None,
database_driver: Optional[str] = None,
database_endpoint: Optional[str] = None,
database_name: Optional[str] = None,
database_port: Optional[Union[int, str]] = None,
table_name: Optional[str] = None,
database_user_name: Optional[str] = None,
auto_create: Optional[bool] = None,
database_password: Optional[str] = None,
database_group: Optional[str] = None,
iam_role: Optional[Any] = None,
arguments: Optional[Dict[str, Any]] = None,
expiration: Optional[Union[int, str]] = None,
**kwargs,
) -> None:
super().__init__(id, name, description, featurestore_id)
# Redshift
self._cluster_identifier = cluster_identifier
self._database_driver = database_driver
self._database_endpoint = database_endpoint
self._database_name = database_name
self._database_port = database_port
self._table_name = table_name
self._database_user_name = database_user_name
self._auto_create = auto_create
self._database_password = database_password
self._database_group = database_group
self._iam_role = iam_role
self._arguments = (
{arg["name"]: arg.get("value", None) for arg in arguments}
if isinstance(arguments, list)
else arguments
)
self._expiration = expiration
@property
def cluster_identifier(self) -> Optional[str]:
"""Cluster identifier for redshift cluster."""
return self._cluster_identifier
@property
def database_driver(self) -> Optional[str]:
"""Database endpoint for redshift cluster."""
return self._database_driver
@property
def database_endpoint(self) -> Optional[str]:
"""Database endpoint for redshift cluster."""
return self._database_endpoint
@property
def database_name(self) -> Optional[str]:
"""Database name for redshift cluster."""
return self._database_name
@property
def database_port(self) -> Optional[Union[int, str]]:
"""Database port for redshift cluster."""
return self._database_port
@property
def table_name(self) -> Optional[str]:
"""Table name for redshift cluster."""
return self._table_name
@property
def database_user_name(self) -> Optional[str]:
"""Database username for redshift cluster."""
return self._database_user_name
@property
def auto_create(self) -> Optional[bool]:
"""Database username for redshift cluster."""
return self._auto_create
@property
def database_group(self) -> Optional[str]:
"""Database username for redshift cluster."""
return self._database_group
@property
def database_password(self) -> Optional[str]:
"""Database password for redshift cluster."""
return self._database_password
@property
def iam_role(self) -> Optional[Any]:
"""IAM role."""
return self._iam_role
@property
def expiration(self) -> Optional[Union[int, str]]:
"""Cluster temporary credential expiration time."""
return self._expiration
@property
def arguments(self) -> Optional[str]:
"""Additional JDBC, REDSHIFT, or Snowflake arguments."""
if isinstance(self._arguments, dict):
return ",".join(
[k + ("" if v is None else "=" + v) for k, v in self._arguments.items()]
)
return self._arguments
def spark_options(self) -> Dict[str, Any]:
"""Return prepared options to be passed to Spark, based on the additional
arguments.
"""
connstr = (
"jdbc:redshift://"
+ self._cluster_identifier
+ "."
+ self._database_endpoint
+ ":"
+ str(self._database_port)
+ "/"
+ self._database_name
)
if isinstance(self.arguments, str):
connstr = connstr + "?" + self.arguments
props = {
"url": connstr,
"driver": self._database_driver,
"user": self._database_user_name,
"password": self._database_password,
}
if self._table_name is not None:
props["dbtable"] = self._table_name
return props
def read(
self,
query: Optional[str] = None,
data_format: Optional[str] = None,
options: Optional[Dict[str, Any]] = None,
path: Optional[str] = None,
dataframe_type: str = "default",
) -> Union[
TypeVar("pyspark.sql.DataFrame"),
TypeVar("pyspark.RDD"),
pd.DataFrame,
np.ndarray,
pl.DataFrame,
]:
"""Reads a table or query into a dataframe using the storage connector.
# Arguments
query: By default, the storage connector will read the table configured together
with the connector, if any. It's possible to overwrite this by passing a SQL
query here. Defaults to `None`.
data_format: Not relevant for JDBC based connectors such as Redshift.
options: Any additional key/value options to be passed to the JDBC connector.
path: Not relevant for JDBC based connectors such as Redshift.
dataframe_type: str, optional. The type of the returned dataframe.
Possible values are `"default"`, `"spark"`,`"pandas"`, `"polars"`, `"numpy"` or `"python"`.
Defaults to "default", which maps to Spark dataframe for the Spark Engine and Pandas dataframe for the Python engine.
# Returns
`DataFrame`.
"""
# refetch to update temporary credentials
self._storage_connector_api.refetch(self)
options = (
{**self.spark_options(), **options}
if options is not None
else self.spark_options()
)
if query:
options["query"] = query
# if table also specified we override to use query
options.pop("dbtable", None)
return engine.get_instance().read(
self, self.JDBC_FORMAT, options, None, dataframe_type
)
def refetch(self) -> None:
"""
Refetch storage connector in order to retrieve updated temporary credentials.
"""
self._storage_connector_api.refetch(self)
class AdlsConnector(StorageConnector):
type = StorageConnector.ADLS
def __init__(
self,
id: Optional[int],
name: str,
featurestore_id: int,
description: Optional[str] = None,
# members specific to type of connector
generation: Optional[str] = None,
directory_id: Optional[str] = None,
application_id: Optional[str] = None,
service_credential: Optional[str] = None,
account_name: Optional[str] = None,
container_name: Optional[str] = None,
spark_options: Optional[Dict[str, Any]] = None,
**kwargs,
) -> None:
super().__init__(id, name, description, featurestore_id)
# ADL
self._generation = generation
self._directory_id = directory_id
self._application_id = application_id
self._account_name = account_name
self._service_credential = service_credential
self._container_name = container_name
self._spark_options = (
{opt["name"]: opt["value"] for opt in spark_options}
if spark_options
else {}
)
@property
def generation(self) -> Optional[str]:
"""Generation of the ADLS storage connector"""
return self._generation
@property
def directory_id(self) -> Optional[str]:
"""Directory ID of the ADLS storage connector"""
return self._directory_id
@property
def application_id(self) -> Optional[str]:
"""Application ID of the ADLS storage connector"""
return self._application_id
@property
def account_name(self) -> Optional[str]:
"""Account name of the ADLS storage connector"""
return self._account_name
@property
def container_name(self) -> Optional[str]:
"""Container name of the ADLS storage connector"""
return self._container_name
@property
def service_credential(self) -> Optional[str]:
"""Service credential of the ADLS storage connector"""
return self._service_credential
@property
def path(self) -> Optional[str]:
"""If the connector refers to a path (e.g. ADLS) - return the path of the connector"""
if self.generation == 2:
return "abfss://{}@{}.dfs.core.windows.net".format(
self.container_name, self.account_name
)
else:
return "adl://{}.azuredatalakestore.net".format(self.account_name)
def spark_options(self) -> Dict[str, Any]:
"""Return prepared options to be passed to Spark, based on the additional
arguments.
"""
return self._spark_options
def prepare_spark(self, path: Optional[str] = None) -> Optional[str]:
"""Prepare Spark to use this Storage Connector.
```python
conn.prepare_spark()
spark.read.format("json").load("abfss://[container-name]@[account_name].dfs.core.windows.net/[path]")
# or
spark.read.format("json").load(conn.prepare_spark("abfss://[container-name]@[account_name].dfs.core.windows.net/[path]"))
```
# Arguments
path: Path to prepare for reading from cloud storage. Defaults to `None`.
"""
return engine.get_instance().setup_storage_connector(self, path)
def _get_path(self, sub_path: str) -> str:
return os.path.join(self.path, sub_path)
def read(
self,
query: Optional[str] = None,
data_format: Optional[str] = None,
options: Optional[Dict[str, Any]] = None,
path: str = "",
dataframe_type: str = "default",
) -> Union[
TypeVar("pyspark.sql.DataFrame"),
TypeVar("pyspark.RDD"),
pd.DataFrame,
np.ndarray,
pl.DataFrame,
]:
"""Reads a path into a dataframe using the storage connector.
# Arguments
query: Not relevant for ADLS connectors.
data_format: The file format of the files to be read, e.g. `csv`, `parquet`.
options: Any additional key/value options to be passed to the ADLS connector.
path: Path within the bucket to be read. For example, path=`path` will read directly from the container specified on connector by constructing the URI as 'abfss://[container-name]@[account_name].dfs.core.windows.net/[path]'.
If no path is specified default container path will be used from connector.
dataframe_type: str, optional. The type of the returned dataframe.
Possible values are `"default"`, `"spark"`,`"pandas"`, `"polars"`, `"numpy"` or `"python"`.
Defaults to "default", which maps to Spark dataframe for the Spark Engine and Pandas dataframe for the Python engine.
# Returns
`DataFrame`.
"""
path = path.strip()
if not path.startswith("abfss://") or path.startswith("adl://"):
path = self._get_path(path)
print(
"Using default container specified on connector, final path: {}".format(
path
)
)
return engine.get_instance().read(
self, data_format, options or {}, path, dataframe_type
)
class SnowflakeConnector(StorageConnector):
type = StorageConnector.SNOWFLAKE
SNOWFLAKE_FORMAT = "net.snowflake.spark.snowflake"
def __init__(
self,
id: Optional[int],
name: str,
featurestore_id: Optional[int],
description: Optional[str] = None,
# members specific to type of connector
database: Optional[str] = None,
password: Optional[str] = None,
token: Optional[str] = None,
role: Optional[Any] = None,
schema: Optional[str] = None,
table: Optional[str] = None,
url: Optional[str] = None,
user: Optional[Any] = None,
warehouse: Optional[str] = None,
application: Optional[Any] = None,
sf_options: Optional[Dict[str, Any]] = None,
**kwargs,
) -> None:
super().__init__(id, name, description, featurestore_id)
# SNOWFLAKE
self._url = url
self._warehouse = warehouse
self._database = database
self._user = user
self._password = password
self._token = token
self._schema = schema
self._table = table
self._role = role
self._application = application
self._options = (
{opt["name"]: opt["value"] for opt in sf_options} if sf_options else {}
)
@property
def url(self) -> Optional[str]:
"""URL of the Snowflake storage connector"""
return self._url
@property
def warehouse(self) -> Optional[str]:
"""Warehouse of the Snowflake storage connector"""
return self._warehouse
@property
def database(self) -> Optional[str]:
"""Database of the Snowflake storage connector"""
return self._database
@property
def user(self) -> Optional[Any]:
"""User of the Snowflake storage connector"""
return self._user
@property
def password(self) -> Optional[str]:
"""Password of the Snowflake storage connector"""
return self._password
@property
def token(self) -> Optional[str]:
"""OAuth token of the Snowflake storage connector"""
return self._token
@property
def schema(self) -> Optional[str]:
"""Schema of the Snowflake storage connector"""
return self._schema
@property
def table(self) -> Optional[str]:
"""Table of the Snowflake storage connector"""
return self._table
@property
def role(self) -> Optional[Any]:
"""Role of the Snowflake storage connector"""
return self._role
@property
def account(self) -> Optional[str]:
"""Account of the Snowflake storage connector"""
return self._url.replace("https://", "").replace(".snowflakecomputing.com", "")
@property
def application(self) -> Any:
"""Application of the Snowflake storage connector"""
return self._application
@property
def options(self) -> Optional[Dict[str, Any]]:
"""Additional options for the Snowflake storage connector"""
return self._options
def snowflake_connector_options(self) -> Optional[Dict[str, Any]]:
"""Alias for `connector_options`"""
return self.connector_options()
def connector_options(self) -> Optional[Dict[str, Any]]:
"""In order to use the `snowflake.connector` Python library, this method
prepares a Python dictionary with the needed arguments for you to connect to
a Snowflake database.
```python
import snowflake.connector
sc = fs.get_storage_connector("snowflake_conn")
ctx = snowflake.connector.connect(**sc.connector_options())
```
"""
props = {
"user": self._user,
"account": self.account,
"database": self._database + "/" + self._schema,
}
if self._password:
props["password"] = self._password
else:
props["authenticator"] = "oauth"
props["token"] = self._token
if self._warehouse:
props["warehouse"] = self._warehouse
if self._application:
props["application"] = self._application
return props
def spark_options(self) -> Dict[str, Any]:
"""Return prepared options to be passed to Spark, based on the additional
arguments.
"""
props = self._options
props["sfURL"] = self._url
props["sfSchema"] = self._schema
props["sfDatabase"] = self._database
props["sfUser"] = self._user
if self._password:
props["sfPassword"] = self._password
else:
props["sfAuthenticator"] = "oauth"
props["sfToken"] = self._token
if self._warehouse:
props["sfWarehouse"] = self._warehouse
if self._application:
props["application"] = self._application
if self._role:
props["sfRole"] = self._role
if self._table:
props["dbtable"] = self._table
return props
def read(
self,
query: Optional[str] = None,
data_format: Optional[str] = None,
options: Optional[Dict[str, Any]] = None,
path: Optional[str] = None,
dataframe_type: str = "default",
) -> Union[
TypeVar("pyspark.sql.DataFrame"),
TypeVar("pyspark.RDD"),
pd.DataFrame,
np.ndarray,
pl.DataFrame,
]:
"""Reads a table or query into a dataframe using the storage connector.
# Arguments
query: By default, the storage connector will read the table configured together
with the connector, if any. It's possible to overwrite this by passing a SQL
query here. Defaults to `None`.
data_format: Not relevant for Snowflake connectors.
options: Any additional key/value options to be passed to the engine.
path: Not relevant for Snowflake connectors.
dataframe_type: str, optional. The type of the returned dataframe.
Possible values are `"default"`, `"spark"`,`"pandas"`, `"polars"`, `"numpy"` or `"python"`.
Defaults to "default", which maps to Spark dataframe for the Spark Engine and Pandas dataframe for the Python engine.
# Returns
`DataFrame`.
"""
options = (
{**self.spark_options(), **options}
if options is not None
else self.spark_options()
)
if query:
options["query"] = query
# if table also specified we override to use query
options.pop("dbtable", None)
return engine.get_instance().read(
self, self.SNOWFLAKE_FORMAT, options, None, dataframe_type
)
class JdbcConnector(StorageConnector):
type = StorageConnector.JDBC
JDBC_FORMAT = "jdbc"
def __init__(
self,
id: Optional[int],
name: str,
featurestore_id: int,
description: Optional[str] = None,
# members specific to type of connector