-
Notifications
You must be signed in to change notification settings - Fork 86
Expand file tree
/
Copy pathBigQuerySQLEngine.java
More file actions
409 lines (346 loc) · 15.3 KB
/
BigQuerySQLEngine.java
File metadata and controls
409 lines (346 loc) · 15.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
/*
* Copyright © 2021 Cask Data, Inc.
*
* 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.
*/
package io.cdap.plugin.gcp.bigquery.sqlengine;
import com.google.auth.Credentials;
import com.google.cloud.bigquery.BigQuery;
import com.google.cloud.bigquery.BigQueryException;
import com.google.cloud.bigquery.Job;
import com.google.cloud.bigquery.TableId;
import com.google.cloud.storage.Storage;
import com.google.common.annotations.VisibleForTesting;
import io.cdap.cdap.api.RuntimeContext;
import io.cdap.cdap.api.annotation.Description;
import io.cdap.cdap.api.annotation.Name;
import io.cdap.cdap.api.annotation.Plugin;
import io.cdap.cdap.api.data.format.StructuredRecord;
import io.cdap.cdap.etl.api.PipelineConfigurer;
import io.cdap.cdap.etl.api.engine.sql.BatchSQLEngine;
import io.cdap.cdap.etl.api.engine.sql.SQLEngineException;
import io.cdap.cdap.etl.api.engine.sql.dataset.SQLDataset;
import io.cdap.cdap.etl.api.engine.sql.dataset.SQLPullDataset;
import io.cdap.cdap.etl.api.engine.sql.dataset.SQLPushDataset;
import io.cdap.cdap.etl.api.engine.sql.request.SQLJoinDefinition;
import io.cdap.cdap.etl.api.engine.sql.request.SQLJoinRequest;
import io.cdap.cdap.etl.api.engine.sql.request.SQLPullRequest;
import io.cdap.cdap.etl.api.engine.sql.request.SQLPushRequest;
import io.cdap.cdap.etl.api.join.JoinCondition;
import io.cdap.cdap.etl.api.join.JoinDefinition;
import io.cdap.cdap.etl.api.join.JoinStage;
import io.cdap.plugin.gcp.bigquery.sink.BigQuerySinkUtils;
import io.cdap.plugin.gcp.bigquery.sqlengine.util.BigQuerySQLEngineUtils;
import io.cdap.plugin.gcp.bigquery.util.BigQueryUtil;
import io.cdap.plugin.gcp.common.GCPUtils;
import org.apache.avro.generic.GenericData;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.NullWritable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* SQL Engine implementation using BigQuery as the execution engine.
*/
@Plugin(type = BatchSQLEngine.PLUGIN_TYPE)
@Name(BigQuerySQLEngine.NAME)
@Description("BigQuery SQLEngine implementation, used to push down certain pipeline steps into BigQuery. "
+ "A GCS bucket is used as staging for the read/write operations performed by this engine. "
+ "BigQuery is Google's serverless, highly scalable, enterprise data warehouse.")
public class BigQuerySQLEngine
extends BatchSQLEngine<LongWritable, GenericData.Record, StructuredRecord, NullWritable> {
private static final Logger LOG = LoggerFactory.getLogger(BigQuerySQLEngine.class);
public static final String NAME = "BigQueryPushdownEngine";
private final BigQuerySQLEngineConfig sqlEngineConfig;
private BigQuery bigQuery;
private Storage storage;
private Configuration configuration;
private String project;
private String location;
private String dataset;
private String bucket;
private String runId;
private Map<String, String> tableNames;
private Map<String, BigQuerySQLDataset> datasets;
@SuppressWarnings("unused")
public BigQuerySQLEngine(BigQuerySQLEngineConfig sqlEngineConfig) {
this.sqlEngineConfig = sqlEngineConfig;
}
@Override
public void configurePipeline(PipelineConfigurer pipelineConfigurer) {
super.configurePipeline(pipelineConfigurer);
// Validate configuration and throw exception if the supplied configuration is invalid.
sqlEngineConfig.validate();
}
@Override
public void prepareRun(RuntimeContext context) throws Exception {
super.prepareRun(context);
// Validate configuration and throw exception if the supplied configuration is invalid.
sqlEngineConfig.validate();
runId = BigQuerySQLEngineUtils.newIdentifier();
tableNames = new HashMap<>();
datasets = new HashMap<>();
String serviceAccount = sqlEngineConfig.getServiceAccount();
Credentials credentials = serviceAccount == null ?
null : GCPUtils.loadServiceAccountCredentials(serviceAccount, sqlEngineConfig.isServiceAccountFilePath());
project = sqlEngineConfig.getProject();
dataset = sqlEngineConfig.getDataset();
bucket = sqlEngineConfig.getBucket() != null ? sqlEngineConfig.getBucket() : "bqpushdown-" + runId;
location = sqlEngineConfig.getLocation();
// Initialize BQ and GCS clients.
bigQuery = GCPUtils.getBigQuery(project, credentials);
storage = GCPUtils.getStorage(project, credentials);
String cmekKey = context.getRuntimeArguments().get(GCPUtils.CMEK_KEY);
configuration = BigQueryUtil.getBigQueryConfig(sqlEngineConfig.getServiceAccount(), sqlEngineConfig.getProject(),
cmekKey, sqlEngineConfig.getServiceAccountType());
// Create resources needed for this execution
BigQuerySinkUtils.createResources(bigQuery, storage, dataset, bucket, sqlEngineConfig.getLocation(), cmekKey);
// Configure GCS bucket that is used to stage temporary files.
// If the bucket is created for this run, mar it for deletion after executon is completed
BigQuerySinkUtils.configureBucket(configuration, bucket, runId, sqlEngineConfig.getBucket() == null);
}
@Override
public void onRunFinish(boolean succeeded, RuntimeContext context) {
super.onRunFinish(succeeded, context);
String gcsPath;
// If the bucket was created for this run, we should delete it.
// Otherwise, just clean the directory within the provided bucket.
if (sqlEngineConfig.getBucket() == null) {
gcsPath = String.format("gs://%s", bucket);
} else {
gcsPath = String.format(BigQuerySinkUtils.GS_PATH_FORMAT, bucket, runId);
}
try {
BigQueryUtil.deleteTemporaryDirectory(configuration, gcsPath);
} catch (IOException e) {
LOG.warn("Failed to delete temporary directory '{}': {}", gcsPath, e.getMessage());
}
}
@Override
public SQLPushDataset<StructuredRecord, StructuredRecord, NullWritable> getPushProvider(SQLPushRequest sqlPushRequest)
throws SQLEngineException {
try {
BigQueryPushDataset pushDataset =
BigQueryPushDataset.getInstance(sqlPushRequest,
sqlEngineConfig,
configuration,
bigQuery,
project,
dataset,
bucket,
runId);
LOG.info("Executing Push operation for dataset {} stored in table {}",
sqlPushRequest.getDatasetName(),
pushDataset.getBigQueryTableName());
datasets.put(sqlPushRequest.getDatasetName(), pushDataset);
return pushDataset;
} catch (IOException ioe) {
throw new SQLEngineException(ioe);
}
}
@Override
public SQLPullDataset<StructuredRecord, LongWritable, GenericData.Record> getPullProvider(
SQLPullRequest sqlPullRequest) throws SQLEngineException {
if (!datasets.containsKey(sqlPullRequest.getDatasetName())) {
throw new SQLEngineException(String.format("Trying to pull non-existing dataset: '%s",
sqlPullRequest.getDatasetName()));
}
String table = datasets.get(sqlPullRequest.getDatasetName()).getBigQueryTableName();
LOG.info("Executing Pull operation for dataset {} stored in table {}", sqlPullRequest.getDatasetName(), table);
try {
return BigQueryPullDataset.getInstance(sqlPullRequest,
configuration,
bigQuery,
project,
dataset,
table,
bucket,
runId);
} catch (IOException ioe) {
throw new SQLEngineException(ioe);
}
}
@Override
public boolean exists(String datasetName) throws SQLEngineException {
return datasets.containsKey(datasetName);
}
@Override
public boolean canJoin(SQLJoinDefinition sqlJoinDefinition) {
boolean canJoin = isValidJoinDefinition(sqlJoinDefinition);
LOG.info("Validating join for stage '{}' can be executed on BigQuery: {}",
sqlJoinDefinition.getDatasetName(),
canJoin);
return canJoin;
}
@VisibleForTesting
protected static boolean isValidJoinDefinition(SQLJoinDefinition sqlJoinDefinition) {
List<String> validationProblems = new ArrayList<>();
JoinDefinition joinDefinition = sqlJoinDefinition.getJoinDefinition();
// Ensure none of the input schemas contains unsupported types or invalid stage names.
for (JoinStage inputStage : joinDefinition.getStages()) {
// Validate input stage schema and identifier
BigQuerySQLEngineUtils.validateInputStage(inputStage, validationProblems);
}
// Ensure the output schema doesn't contain unsupported types
BigQuerySQLEngineUtils.validateOutputSchema(joinDefinition.getOutputSchema(), validationProblems);
// Ensure expression joins have valid aliases
if (joinDefinition.getCondition().getOp() == JoinCondition.Op.EXPRESSION) {
BigQuerySQLEngineUtils
.validateOnExpressionJoinCondition((JoinCondition.OnExpression) joinDefinition.getCondition(),
validationProblems);
}
// Validate join stages for join on keys
if (joinDefinition.getCondition().getOp() == JoinCondition.Op.KEY_EQUALITY) {
BigQuerySQLEngineUtils.validateJoinOnKeyStages(joinDefinition, validationProblems);
}
if (!validationProblems.isEmpty()) {
LOG.warn("Join operation for stage '{}' could not be executed in BigQuery. Issues found: {}.",
sqlJoinDefinition.getDatasetName(),
String.join("; ", validationProblems));
}
return validationProblems.isEmpty();
}
@Override
public SQLDataset join(SQLJoinRequest sqlJoinRequest) throws SQLEngineException {
LOG.info("Executing join operation for dataset {}", sqlJoinRequest.getDatasetName());
BigQueryJoinDataset joinDataset = BigQueryJoinDataset.getInstance(sqlJoinRequest,
getStageNameToBQTableNameMap(),
sqlEngineConfig,
bigQuery,
project,
dataset,
runId);
LOG.info("Executed join operation for dataset {}", sqlJoinRequest.getDatasetName());
datasets.put(sqlJoinRequest.getDatasetName(), joinDataset);
return joinDataset;
}
@Override
public void cleanup(String datasetName) throws SQLEngineException {
BigQuerySQLDataset bqDataset = datasets.get(datasetName);
if (bqDataset == null) {
return;
}
LOG.info("Cleaning up dataset {}", datasetName);
SQLEngineException ex = null;
// Cancel BQ job
try {
cancelJob(datasetName, bqDataset);
} catch (BigQueryException e) {
LOG.error("Exception when cancelling BigQuery job '{}' for stage '{}': {}",
bqDataset.getJobId(), datasetName, e.getMessage());
ex = new SQLEngineException(String.format("Exception when executing cleanup for stage '%s'", datasetName), e);
}
// Delete BQ Table
try {
deleteTable(datasetName, bqDataset);
} catch (BigQueryException e) {
LOG.error("Exception when deleting BigQuery table '{}' for stage '{}': {}",
bqDataset.getBigQueryTableName(), datasetName, e.getMessage());
if (ex == null) {
ex = new SQLEngineException(String.format("Exception when executing cleanup for stage '%s'", datasetName), e);
} else {
ex.addSuppressed(e);
}
}
// Delete temporary folder
try {
deleteTempFolder(bqDataset);
} catch (IOException e) {
LOG.error("Failed to delete temporary directory '{}' for stage '{}': {}",
bqDataset.getGCSPath(), datasetName, e.getMessage());
if (ex == null) {
ex = new SQLEngineException(String.format("Exception when executing cleanup for stage '%s'", datasetName), e);
} else {
ex.addSuppressed(e);
}
}
// Throw all collected exceptions, if any.
if (ex != null) {
throw ex;
}
}
/**
* Get a map that contains stage names as keys and BigQuery tables as Values.
*
* @return map representing all stages currently pushed to BQ.
*/
protected Map<String, String> getStageNameToBQTableNameMap() {
return datasets.entrySet()
.stream()
.collect(Collectors.toMap(
Map.Entry::getKey,
e -> e.getValue().getBigQueryTableName()
));
}
/**
* Stops the running job for the supplied dataset
*
* @param stageName the name of the stage in CDAP
* @param bqDataset the BigQuery Dataset Instance
*/
protected void cancelJob(String stageName, BigQuerySQLDataset bqDataset) throws BigQueryException {
// Skip cancellation if tables need to be retained.
if (sqlEngineConfig.shouldRetainTables()) {
return;
}
String jobId = bqDataset.getJobId();
// If this dataset does not specify a job ID, there's no need to cancel any job
if (jobId == null) {
return;
}
String tableName = bqDataset.getBigQueryTableName();
Job job = bigQuery.getJob(jobId);
if (job == null) {
return;
}
if (!job.cancel()) {
LOG.error("Unable to cancel BigQuery job '{}' for table '{}' and stage '{}'", jobId, tableName, stageName);
}
}
/**
* Deletes the BigQuery table for the supplied dataset
*
* @param stageName the name of the stage in CDAP
* @param bqDataset the BigQuery Dataset Instance
*/
protected void deleteTable(String stageName, BigQuerySQLDataset bqDataset) throws BigQueryException {
// Skip deletion if tables need to be retained.
if (sqlEngineConfig.shouldRetainTables()) {
return;
}
String tableName = bqDataset.getBigQueryTableName();
TableId tableId = TableId.of(project, dataset, tableName);
if (!bigQuery.delete(tableId)) {
LOG.error("Unable to delete BigQuery table '{}' for stage '{}'", tableName, stageName);
}
}
/**
* Deletes the temporary folder used by a certain BQ dataset.
*
* @param bqDataset the BigQuery Dataset Instance
*/
protected void deleteTempFolder(BigQuerySQLDataset bqDataset) throws IOException {
String gcsPath = bqDataset.getGCSPath();
// If this dataset does not use temporary storage, skip this step
if (gcsPath == null) {
return;
}
BigQueryUtil.deleteTemporaryDirectory(configuration, gcsPath);
}
}