-
Notifications
You must be signed in to change notification settings - Fork 11
/
spark.py
152 lines (123 loc) · 4.61 KB
/
spark.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
import logging
import os
import re
from urllib.error import HTTPError
from urllib.parse import urljoin
from urllib.request import urlopen
TD_SPARK_BASE_URL = "https://s3.amazonaws.com/td-spark/"
logger = logging.getLogger(__name__)
def download_td_spark(spark_binary_version="3.0.1", version="latest", destination=None):
"""Download a td-spark jar file from S3.
Parameters
----------
spark_binary_version : str, default: '3.0.1'
Apache Spark binary version.
version : str, default: 'latest'
td-spark version.
destination : str, optional
Where a downloaded jar file to be stored.
"""
td_spark_jar_name = f"td-spark-assembly-{version}_spark{spark_binary_version}.jar"
if destination is None:
destination = os.path.join(
os.path.dirname(os.path.abspath(__file__)), td_spark_jar_name
)
download_url = urljoin(TD_SPARK_BASE_URL, td_spark_jar_name)
try:
response = urlopen(download_url)
except HTTPError:
raise RuntimeError("failed to access to the download URL: " + download_url)
logger.info("Downloading td-spark...")
try:
with open(destination, "w+b") as f:
f.write(response.read())
except Exception:
os.remove(destination)
raise
logger.info("Completed to download")
response.close()
def fetch_td_spark_context(
apikey=None,
endpoint=None,
td_spark_path=None,
download_if_missing=True,
spark_configs=None,
):
"""Build TDSparkContext via td-pyspark.
Parameters
----------
apikey : str, optional
Treasure Data API key. If not given, a value of environment variable
``TD_API_KEY`` is used by default.
endpoint : str, optional
Treasure Data API server. If not given, ``https://api.treasuredata.com`` is
used by default. List of available endpoints is:
https://tddocs.atlassian.net/wiki/spaces/PD/pages/1085143/Sites+and+Endpoints
td_spark_path : str, optional
Path to td-spark-assembly-{td-spark-version}_spark{spark-version}.jar.
If not given, seek a path
``TDSparkContextBuilder.default_jar_path()`` by default.
download_if_missing : bool, default: True
Download td-spark if it does not exist at the time of initialization.
spark_configs : dict, optional
Additional Spark configurations to be set via ``SparkConf``'s ``set`` method.
Returns
-------
:class:`td_pyspark.TDSparkContext`
Connection of td-spark
"""
try:
import td_pyspark
from pyspark.conf import SparkConf
from pyspark.sql import SparkSession
from td_pyspark import TDSparkContextBuilder
except ImportError:
raise RuntimeError("td_pyspark is not installed")
apikey = apikey or os.environ.get("TD_API_KEY")
if apikey is None:
raise ValueError(
"either argument 'apikey' or environment variable"
"'TD_API_KEY' should be set"
)
if endpoint is None:
endpoint = os.getenv("TD_API_SERVER", "https://api.treasuredata.com")
conf = (
SparkConf()
.setMaster("local[*]")
.set("spark.serializer", "org.apache.spark.serializer.KryoSerializer")
.set("spark.sql.execution.arrow.pyspark.enabled", "true")
)
if isinstance(spark_configs, dict):
for k, v in spark_configs.items():
conf.set(k, v)
builder = TDSparkContextBuilder(SparkSession.builder.config(conf=conf))
builder.apikey(apikey)
if td_spark_path is None:
td_spark_path = TDSparkContextBuilder.default_jar_path()
else:
td_spark_path = os.path.expanduser(td_spark_path)
available = os.path.exists(td_spark_path)
if not available and download_if_missing:
download_td_spark(version=td_pyspark.__version__, destination=td_spark_path)
elif not available:
raise IOError("td-spark is not found and `download_if_missing` is False")
builder.jars(td_spark_path)
plazma_api = os.getenv("TD_PLAZMA_API")
presto_api = os.getenv("TD_PRESTO_API")
if plazma_api and presto_api:
api_regex = re.compile(r"(?:https?://)?(api(?:-.+?)?)\.")
builder.api_endpoint(api_regex.sub("\\1.", endpoint).strip("/"))
builder.plazma_endpoint(plazma_api)
builder.presto_endpoint(presto_api)
site = "us"
if ".co.jp" in endpoint:
site = "jp"
if "eu01" in endpoint:
site = "eu01"
if "ap02" in endpoint:
site = "ap02"
builder.site(site)
try:
return builder.build()
except Exception as e:
raise RuntimeError("failed to connect to td-spark: " + str(e))