Skip to content

Commit 170fc3b

Browse files
committed
Add BigQuery Error Details Provider
1 parent 601f62b commit 170fc3b

File tree

12 files changed

+235
-74
lines changed

12 files changed

+235
-74
lines changed

src/e2e-test/resources/errorMessage.properties

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ errorMessageInvalidBucketName=Invalid bucket name in path
2828
errorMessageInvalidFormat=Input has multi-level structure that cannot be represented appropriately as csv. \
2929
Consider using json, avro or parquet to write data.
3030
errorMessageMultipleFileWithFirstRowAsHeaderDisabled=Spark program 'phase-1' failed with error: Found a row with 6 fields when the schema only contains 4 fields. Check that the schema contains the right number of fields.. Please check the system logs for more details.
31-
errorMessageMultipleFileWithFirstRowAsHeaderEnabled=Spark program 'phase-1' failed with error: For input string:
31+
errorMessageMultipleFileWithFirstRowAsHeaderEnabled=Spark program 'phase-1' failed with error:
3232
errorMessageMultipleFileWithoutClearDefaultSchema=Spark program 'phase-1' failed with error: Found a row with 4 fields when the schema only contains 2 fields.
3333
errorMessageInvalidSourcePath=Invalid bucket name in path 'abc@'. Bucket name should
3434
errorMessageInvalidDestPath=Invalid bucket name in path 'abc@'. Bucket name should
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
/*
2+
* Copyright © 2024 Cask Data, Inc.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
5+
* use this file except in compliance with the License. You may obtain a copy of
6+
* the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12+
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13+
* License for the specific language governing permissions and limitations under
14+
* the License.
15+
*/
16+
17+
package io.cdap.plugin.gcp.bigquery.common;
18+
19+
import io.cdap.plugin.gcp.common.GCPErrorDetailsProvider;
20+
21+
/**
22+
* A custom ErrorDetailsProvider for BigQuery plugins.
23+
*/
24+
public class BigQueryErrorDetailsProvider extends GCPErrorDetailsProvider {
25+
26+
@Override
27+
protected String getExternalDocumentationLink() {
28+
return "https://cloud.google.com/bigquery/docs/error-messages";
29+
}
30+
}

src/main/java/io/cdap/plugin/gcp/bigquery/sink/AbstractBigQuerySink.java

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,9 @@
3434
import io.cdap.cdap.etl.api.FailureCollector;
3535
import io.cdap.cdap.etl.api.batch.BatchSink;
3636
import io.cdap.cdap.etl.api.batch.BatchSinkContext;
37+
import io.cdap.cdap.etl.api.exception.ErrorDetailsProviderSpec;
3738
import io.cdap.plugin.common.Asset;
39+
import io.cdap.plugin.gcp.bigquery.common.BigQueryErrorDetailsProvider;
3840
import io.cdap.plugin.gcp.bigquery.sink.lib.BigQueryTableFieldSchema;
3941
import io.cdap.plugin.gcp.bigquery.util.BigQueryConstants;
4042
import io.cdap.plugin.gcp.bigquery.util.BigQueryTypeSize;
@@ -116,6 +118,8 @@ public final void prepareRun(BatchSinkContext context) throws Exception {
116118
storage, bucket, bucketName,
117119
config.getLocation(), cmekKeyName);
118120
}
121+
// set error details provider
122+
context.setErrorDetailsProvider(new ErrorDetailsProviderSpec(BigQueryErrorDetailsProvider.class.getName()));
119123
prepareRunInternal(context, bigQuery, bucketName);
120124
}
121125

@@ -124,9 +128,9 @@ public void onRunFinish(boolean succeeded, BatchSinkContext context) {
124128
String gcsPath;
125129
String bucket = getConfig().getBucket();
126130
if (bucket == null) {
127-
gcsPath = String.format("gs://%s", runUUID.toString());
131+
gcsPath = String.format("gs://%s", runUUID);
128132
} else {
129-
gcsPath = String.format(gcsPathFormat, bucket, runUUID.toString());
133+
gcsPath = String.format(gcsPathFormat, bucket, runUUID);
130134
}
131135
try {
132136
BigQueryUtil.deleteTemporaryDirectory(baseConfiguration, gcsPath);
@@ -327,9 +331,8 @@ private void validateRecordDepth(@Nullable Schema schema, FailureCollector colle
327331
*
328332
* @return Hadoop configuration
329333
*/
330-
protected Configuration getOutputConfiguration() throws IOException {
331-
Configuration configuration = new Configuration(baseConfiguration);
332-
return configuration;
334+
protected Configuration getOutputConfiguration() {
335+
return new Configuration(baseConfiguration);
333336
}
334337

335338
/**

src/main/java/io/cdap/plugin/gcp/bigquery/sink/BigQueryOutputFormat.java

Lines changed: 53 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,10 @@
6161
import com.google.common.base.Strings;
6262
import com.google.common.collect.Lists;
6363
import io.cdap.cdap.api.data.format.StructuredRecord;
64+
import io.cdap.cdap.api.exception.ErrorCategory;
65+
import io.cdap.cdap.api.exception.ErrorType;
66+
import io.cdap.cdap.api.exception.ErrorUtils;
67+
import io.cdap.cdap.etl.api.exception.ErrorPhase;
6468
import io.cdap.plugin.gcp.bigquery.sink.lib.BigQueryStrings;
6569
import io.cdap.plugin.gcp.bigquery.source.BigQueryFactoryWithScopes;
6670
import io.cdap.plugin.gcp.bigquery.util.BigQueryConstants;
@@ -103,6 +107,7 @@
103107
*/
104108
public class BigQueryOutputFormat extends ForwardingBigQueryFileOutputFormat<StructuredRecord, NullWritable> {
105109
private static final Logger LOG = LoggerFactory.getLogger(BigQueryOutputFormat.class);
110+
private static final String errorMessageFormat = "Error occurred in the phase: '%s'. Error message: %s";
106111

107112
@Override
108113
public RecordWriter<StructuredRecord, NullWritable> getRecordWriter(TaskAttemptContext taskAttemptContext)
@@ -165,19 +170,31 @@ public void checkOutputSpecs(JobContext job) throws FileAlreadyExistsException,
165170
// Error if the output path already exists.
166171
FileSystem outputFileSystem = outputPath.getFileSystem(conf);
167172
if (outputFileSystem.exists(outputPath)) {
168-
throw new IOException("The output path '" + outputPath + "' already exists.");
173+
String errorMessage = String.format("The output path '%s' already exists.", outputPath);
174+
throw ErrorUtils.getProgramFailureException(
175+
new ErrorCategory(ErrorCategory.ErrorCategoryEnum.PLUGIN), errorMessage,
176+
String.format(errorMessageFormat, ErrorPhase.VALIDATING_OUTPUT_SPECS, errorMessage), ErrorType.SYSTEM, true,
177+
new IOException(errorMessage));
169178
}
170179

171180
// Error if compression is set as there's mixed support in BigQuery.
172181
if (FileOutputFormat.getCompressOutput(job)) {
173-
throw new IOException("Compression isn't supported for this OutputFormat.");
182+
String errorMessage = "Compression isn't supported for this OutputFormat.";
183+
throw ErrorUtils.getProgramFailureException(
184+
new ErrorCategory(ErrorCategory.ErrorCategoryEnum.PLUGIN), errorMessage,
185+
String.format(errorMessageFormat, ErrorPhase.VALIDATING_OUTPUT_SPECS, errorMessage), ErrorType.SYSTEM, true,
186+
new IOException(errorMessage));
174187
}
175188

176189
// Error if unable to create a BigQuery helper.
177190
try {
178191
new BigQueryFactoryWithScopes(GCPUtils.BIGQUERY_SCOPES).getBigQueryHelper(conf);
179192
} catch (GeneralSecurityException gse) {
180-
throw new IOException("Failed to create BigQuery client", gse);
193+
String errorMessage = "Failed to create BigQuery client";
194+
throw ErrorUtils.getProgramFailureException(
195+
new ErrorCategory(ErrorCategory.ErrorCategoryEnum.PLUGIN), errorMessage,
196+
String.format(errorMessageFormat, ErrorPhase.VALIDATING_OUTPUT_SPECS, errorMessage), ErrorType.SYSTEM, true,
197+
new IOException(errorMessage, gse));
181198
}
182199

183200
// Let delegate process its checks.
@@ -208,7 +225,11 @@ public static class BigQueryOutputCommitter extends ForwardingBigQueryFileOutput
208225
BigQueryFactory bigQueryFactory = new BigQueryFactoryWithScopes(GCPUtils.BIGQUERY_SCOPES);
209226
this.bigQueryHelper = bigQueryFactory.getBigQueryHelper(context.getConfiguration());
210227
} catch (GeneralSecurityException e) {
211-
throw new IOException("Failed to create Bigquery client.", e);
228+
String errorMessage = "Failed to create BigQuery client";
229+
throw ErrorUtils.getProgramFailureException(
230+
new ErrorCategory(ErrorCategory.ErrorCategoryEnum.PLUGIN), errorMessage,
231+
String.format(errorMessageFormat, ErrorPhase.COMMITTING, errorMessage), ErrorType.SYSTEM, true,
232+
new IOException(errorMessage, e));
212233
}
213234
}
214235

@@ -266,7 +287,11 @@ public void commitJob(JobContext jobContext) throws IOException {
266287
writeDisposition, sourceUris, partitionType, timePartitioningType, range, partitionByField,
267288
requirePartitionFilter, clusteringOrderList, tableExists, jobLabelKeyValue, conf);
268289
} catch (Exception e) {
269-
throw new IOException("Failed to import GCS into BigQuery. ", e);
290+
String errorMessage = "Failed to import GCS into BigQuery.";
291+
throw ErrorUtils.getProgramFailureException(
292+
new ErrorCategory(ErrorCategory.ErrorCategoryEnum.PLUGIN), errorMessage,
293+
String.format(errorMessageFormat, ErrorPhase.COMMITTING, errorMessage), ErrorType.SYSTEM, true,
294+
new IOException(errorMessage, e));
270295
}
271296

272297
cleanup(jobContext);
@@ -566,26 +591,33 @@ private static void waitForJobCompletion(BigQueryHelper bigQueryHelper, String p
566591
int numOfErrors;
567592
String errorMessage;
568593
if (errors == null || errors.isEmpty()) {
569-
errorMessage = pollJob.getStatus().getErrorResult().getMessage();
594+
errorMessage = String.format("reason: %s, %s", pollJob.getStatus().getErrorResult().getReason(),
595+
pollJob.getStatus().getErrorResult().getMessage());
570596
numOfErrors = 1;
571597
} else {
572598
errorMessage = errors.get(errors.size() - 1).getMessage();
573599
numOfErrors = errors.size();
574600
}
575601
// Only add first error message in the exception. For other errors user should look at BigQuery job logs.
576-
throw new IOException(String.format("Error occurred while importing data to BigQuery '%s'." +
577-
" There are total %s error(s) for BigQuery job %s. Please look at " +
578-
"BigQuery job logs for more information.",
579-
errorMessage, numOfErrors, jobReference.getJobId()));
602+
String errorMessageException = String.format("Error occurred while importing data to BigQuery '%s'." +
603+
" There are total %s error(s) for BigQuery job %s. Please look at " +
604+
"BigQuery job logs for more information.",
605+
errorMessage, numOfErrors, jobReference.getJobId());
606+
throw ErrorUtils.getProgramFailureException(
607+
new ErrorCategory(ErrorCategory.ErrorCategoryEnum.PLUGIN), errorMessageException,
608+
String.format(errorMessageFormat, ErrorPhase.COMMITTING, errorMessageException), ErrorType.UNKNOWN, true,
609+
new IOException(errorMessageException));
610+
580611
}
581612
} else {
582613
long millisToWait = pollBackOff.nextBackOffMillis();
583614
if (millisToWait == BackOff.STOP) {
584-
throw new IOException(
585-
String.format(
586-
"Job %s failed to complete after %s millis.",
587-
jobReference.getJobId(),
588-
elapsedTime));
615+
String errorMessage = String.format("Job %s failed to complete after %s millis.", jobReference.getJobId()
616+
, elapsedTime);
617+
throw ErrorUtils.getProgramFailureException(
618+
new ErrorCategory(ErrorCategory.ErrorCategoryEnum.PLUGIN), errorMessage,
619+
String.format(errorMessageFormat, ErrorPhase.COMMITTING, errorMessage), ErrorType.UNKNOWN, true,
620+
new IOException(errorMessage));
589621
}
590622
// Pause execution for the configured duration before polling job status again.
591623
Thread.sleep(millisToWait);
@@ -621,8 +653,12 @@ private static Optional<TableSchema> getTableSchema(Configuration conf) throws I
621653
TableSchema tableSchema = createTableSchemaFromFields(fieldsJson);
622654
return Optional.of(tableSchema);
623655
} catch (IOException e) {
624-
throw new IOException(
625-
"Unable to parse key '" + BigQueryConfiguration.OUTPUT_TABLE_SCHEMA.getKey() + "'.", e);
656+
String errorMessage = String.format("Unable to parse key '%s'.",
657+
BigQueryConfiguration.OUTPUT_TABLE_SCHEMA.getKey());
658+
throw ErrorUtils.getProgramFailureException(
659+
new ErrorCategory(ErrorCategory.ErrorCategoryEnum.PLUGIN), errorMessage,
660+
String.format(errorMessageFormat, ErrorPhase.COMMITTING, errorMessage), ErrorType.SYSTEM, true,
661+
new IOException(errorMessage, e));
626662
}
627663
}
628664
return Optional.empty();

src/main/java/io/cdap/plugin/gcp/bigquery/sink/BigQueryRecordToJson.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -189,7 +189,7 @@ private static void writeSimpleTypes(JsonWriter writer, String name, boolean isA
189189
} else if (jsonString.startsWith("[") && jsonString.endsWith("]")) {
190190
writeJsonArrayToWriter(gson.fromJson(jsonString, JsonArray.class), writer);
191191
} else {
192-
throw new IllegalStateException(String.format("Expected value of Field '%s' to be a valid JSON " +
192+
throw new IllegalArgumentException(String.format("Expected value of Field '%s' to be a valid JSON " +
193193
"object or array.", name));
194194
}
195195
break;

0 commit comments

Comments
 (0)