Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -41,15 +41,18 @@
import java.io.IOException;
import java.util.Locale;
import java.util.concurrent.Phaser;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.logging.Level;
import javax.annotation.concurrent.GuardedBy;

class BigQueryJdbcBulkInsertWriter {
private static final BigQueryJdbcCustomLogger LOG =
new BigQueryJdbcCustomLogger(BigQueryJdbcBulkInsertWriter.class.getName());
private StreamWriter streamWriter;
private volatile String streamName;
private volatile Descriptor descriptor;
private final Phaser openRequestCount = new Phaser(1);
private final AtomicBoolean writerClosed = new AtomicBoolean(false);
private final Object streamLock = new Object();

@GuardedBy("streamLock")
Expand All @@ -67,13 +70,14 @@ void initialize(TableName parentTable, BigQueryWriteClient client, RetrySettings
.setWriteStream(stream)
.build();
WriteStream writeStream = client.createWriteStream(createWriteStreamRequest);
this.streamName = writeStream.getName();
this.descriptor =
BQTableSchemaToProtoDescriptor.convertBQTableSchemaToProtoDescriptor(
normalizeTableSchemaFieldNames(writeStream.getTableSchema()));
ProtoSchema protoSchema = ProtoSchemaConverter.convert(this.descriptor);

StreamWriter.Builder streamWriterBuilder =
StreamWriter.newBuilder(writeStream.getName(), client).setWriterSchema(protoSchema);
StreamWriter.newBuilder(this.streamName, client).setWriterSchema(protoSchema);
if (retrySettings != null) {
streamWriterBuilder.setRetrySettings(retrySettings);
}
Expand Down Expand Up @@ -120,37 +124,69 @@ void append(ProtoRows rows, long offset) throws IOException {
}
}

ApiFuture<AppendRowsResponse> future = streamWriter.append(rows, offset);
ApiFutures.addCallback(
future, new AppendCompleteCallback(this), MoreExecutors.directExecutor());
// Register before submitting so a synchronously completed future cannot drop the party count
// to zero (which permanently terminates the Phaser) before registration occurs.
openRequestCount.register();
AppendCompleteCallback callback = new AppendCompleteCallback(this);
try {
ApiFuture<AppendRowsResponse> future = streamWriter.append(rows, offset);
ApiFutures.addCallback(future, callback, MoreExecutors.directExecutor());
} catch (Throwable t) {
callback.done();
throw t;
}
}

long cleanup(BigQueryWriteClient client) {
long cleanup(BigQueryWriteClient client) throws InterruptedException {
LOG.finer("++enter++");
LOG.fine("Cleaning up bulk insert writer for stream: %s", streamWriter.getStreamName());
openRequestCount.arriveAndAwaitAdvance();
streamWriter.close();
String currentStreamName = getStreamName();
LOG.fine("Cleaning up bulk insert writer for stream: %s", currentStreamName);
try {
openRequestCount.awaitAdvanceInterruptibly(openRequestCount.arrive());
} catch (Throwable t) {
closeQuietly();
throw t;
}
closeWriter();

synchronized (this.streamLock) {
if (this.error != null) {
throw this.error;
}
}
Comment on lines +150 to 156

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

If closeWriter() throws a RuntimeException (which is common when the stream is already in a broken state), the exception will propagate immediately and mask the actual append error (this.error). To prevent masking the root cause of the failure, check and throw this.error first, using closeQuietly() to clean up the writer safely if an error is present.

Suggested change
closeWriter();
synchronized (this.streamLock) {
if (this.error != null) {
throw this.error;
}
}
synchronized (this.streamLock) {
if (this.error != null) {
closeQuietly();
throw this.error;
}
}
closeWriter();


FinalizeWriteStreamResponse finalizeResponse =
client.finalizeWriteStream(streamWriter.getStreamName());
FinalizeWriteStreamResponse finalizeResponse = client.finalizeWriteStream(currentStreamName);
LOG.finer("Rows written: %d", finalizeResponse.getRowCount());
return finalizeResponse.getRowCount();
}

void closeQuietly() {
if (this.streamWriter != null && this.writerClosed.compareAndSet(false, true)) {
try {
this.streamWriter.close();
} catch (RuntimeException ex) {
LOG.warning(ex, "Failed to close stream writer during error cleanup.");
}
}
}

private void closeWriter() {
if (this.streamWriter != null && this.writerClosed.compareAndSet(false, true)) {
this.streamWriter.close();
}
}

String getStreamName() {
return streamWriter.getStreamName();
if (this.streamName != null) {
return this.streamName;
}
return this.streamWriter != null ? this.streamWriter.getStreamName() : null;
}

static class AppendCompleteCallback implements ApiFutureCallback<AppendRowsResponse> {

private final BigQueryJdbcBulkInsertWriter parent;
private final AtomicBoolean deregistered = new AtomicBoolean(false);

AppendCompleteCallback(BigQueryJdbcBulkInsertWriter parent) {
this.parent = parent;
Expand All @@ -163,20 +199,25 @@ public void onSuccess(AppendRowsResponse response) {

@Override
public void onFailure(Throwable throwable) {
LOG.warning(
"Append failed for stream %s: %s", parent.getStreamName(), throwable.getMessage());
synchronized (this.parent.streamLock) {
if (this.parent.error == null) {
StorageException storageException = Exceptions.toStorageException(throwable);
this.parent.error =
(storageException != null) ? storageException : new RuntimeException(throwable);
try {
synchronized (this.parent.streamLock) {
if (this.parent.error == null) {
StorageException storageException = Exceptions.toStorageException(throwable);
this.parent.error =
(storageException != null) ? storageException : new RuntimeException(throwable);
}
}
LOG.warning(
"Append failed for stream %s: %s", parent.getStreamName(), throwable.getMessage());
} finally {
done();
}
done();
}

private void done() {
this.parent.openRequestCount.arriveAndDeregister();
void done() {
if (this.deregistered.compareAndSet(false, true)) {
this.parent.openRequestCount.arriveAndDeregister();
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@
import com.google.cloud.bigquery.Field;
import com.google.cloud.bigquery.FieldList;
import com.google.cloud.bigquery.JobStatistics.QueryStatistics;
import com.google.cloud.bigquery.JobStatistics.QueryStatistics.StatementType;
import com.google.cloud.bigquery.QueryJobConfiguration;
import com.google.cloud.bigquery.QueryParameterValue;
import com.google.cloud.bigquery.Schema;
Expand All @@ -31,7 +30,10 @@
import com.google.cloud.bigquery.exception.BigQueryJdbcException;
import com.google.cloud.bigquery.exception.BigQueryJdbcSqlFeatureNotSupportedException;
import com.google.cloud.bigquery.jdbc.telemetry.v1.DriverFeature;
import com.google.cloud.bigquery.jdbc.telemetry.v1.QueryApiType;
import com.google.cloud.bigquery.jdbc.telemetry.v1.StatementExecution;
import com.google.cloud.bigquery.jdbc.telemetry.v1.StatementType;
import com.google.cloud.bigquery.jdbc.telemetry.v1.Status;
import com.google.cloud.bigquery.jdbc.telemetry.v1.TelemetryManager;
import com.google.cloud.bigquery.storage.v1.BatchCommitWriteStreamsRequest;
import com.google.cloud.bigquery.storage.v1.BatchCommitWriteStreamsResponse;
Expand Down Expand Up @@ -74,7 +76,7 @@ class BigQueryPreparedStatement extends BigQueryStatement implements PreparedSta
private static final char POSITIONAL_PARAMETER_CHAR = '?';
// parameterHandler is inherited from BigQueryStatement
protected final int parameterCount;
protected String currentQuery;
protected final String currentQuery;
private Queue<ArrayList<BigQueryJdbcParameter>> batchParameters = new LinkedList<>();
// Both hold statistics.getSchema(), which reports different things per statement type: the rows
// a SELECT returns, versus the columns an INSERT writes.
Expand All @@ -84,6 +86,9 @@ class BigQueryPreparedStatement extends BigQueryStatement implements PreparedSta

BigQueryPreparedStatement(BigQueryConnection connection, String query) throws SQLException {
super(connection);
if (query == null) {
throw new BigQueryJdbcException("SQL query cannot be null.");
}
this.currentQuery = query;
QueryStatistics queryStatistics = describeQueryQuietly();
this.parameterCount = resolveParameterCount(query, queryStatistics);
Expand Down Expand Up @@ -158,7 +163,7 @@ private static StandardSQLTypeName toStandardSqlType(String typeName) {
// Remembers the table and schema of single-table INSERT targets, for the Storage Write API.
// Failure is delegated to executeBatch instead of the constructor.
private void captureInsertMetadata(QueryStatistics statistics) {
if (!StatementType.INSERT.equals(statistics.getStatementType())
if (!QueryStatistics.StatementType.INSERT.equals(statistics.getStatementType())
|| statistics.getSchema() == null
|| statistics.getSchema().getFields() == null
|| statistics.getReferencedTables() == null
Expand All @@ -181,7 +186,7 @@ private void captureInsertMetadata(QueryStatistics statistics) {
// The column names are as they are returned from the query dryRun and may not match the actual
// table column names.
private void captureResultSchema(QueryStatistics statistics) {
if (StatementType.SELECT.equals(statistics.getStatementType())) {
if (QueryStatistics.StatementType.SELECT.equals(statistics.getStatementType())) {
this.resultSchema = statistics.getSchema();
}
}
Expand Down Expand Up @@ -383,24 +388,64 @@ public void addBatch() {
this.batchParameters.add(currentParameterList);
}

@Override
public void clearBatch() {
super.clearBatch();
this.batchParameters.clear();
}

@Override
public void close() throws SQLException {
try {
super.close();
} finally {
this.batchParameters.clear();
}
}

private ArrayList<BigQueryJdbcParameter> deepCopyParameterList(
ArrayList<BigQueryJdbcParameter> parametersList) {
ArrayList<BigQueryJdbcParameter> copiedParameterList = new ArrayList<>();
ArrayList<BigQueryJdbcParameter> copiedParameterList = new ArrayList<>(parametersList.size());
for (BigQueryJdbcParameter parameter : parametersList) {
BigQueryJdbcParameter newParameter = new BigQueryJdbcParameter(parameter);
copiedParameterList.add(newParameter);
copiedParameterList.add(parameter == null ? null : new BigQueryJdbcParameter(parameter));
}
return copiedParameterList;
}

private void validateBatchParameters() throws BigQueryJdbcException {
for (ArrayList<BigQueryJdbcParameter> parameterList : this.batchParameters) {
for (int i = 1; i <= this.parameterCount; i++) {
int arrayIndex = i - 1;
if (parameterList == null
|| parameterList.size() <= arrayIndex
|| parameterList.get(arrayIndex) == null
|| !parameterList.get(arrayIndex).isBound()) {
throw new BigQueryJdbcException(
String.format(
"One or more parameters missing in Prepared statement. No value was set for"
+ " parameter %d of %d.",
i, this.parameterCount));
}
}
}
}

@Override
public int[] executeBatch() throws SQLException {
validateExecution();
int[] result = new int[this.batchParameters.size()];
if (this.batchParameters.isEmpty()) {
return result;
}
try {
validateBatchParameters();
return executeBatchInternal(result);
} finally {
this.batchParameters.clear();
}
}

private int[] executeBatchInternal(int[] result) throws SQLException {
// The constructor's dry run may have happened before the target table existed.
if (this.insertSchema == null
&& this.querySettings.isUseWriteAPI()
Expand All @@ -415,37 +460,41 @@ public int[] executeBatch() throws SQLException {

if (useWriteAPI()) {
long startTime = System.currentTimeMillis();
int fallbackErrorCode = 1000;
StatementExecution.Builder writeApiExecutionBuilder =
StatementExecution.newBuilder()
.setStatementType(
com.google.cloud.bigquery.jdbc.telemetry.v1.StatementType.STATEMENT_TYPE_INSERT)
.setQueryApiType(
com.google.cloud.bigquery.jdbc.telemetry.v1.QueryApiType
.QUERY_API_TYPE_WRITE_API);
try (BigQueryWriteClient writeClient = this.connection.getBigQueryWriteClient()) {
.setStatementType(StatementType.STATEMENT_TYPE_INSERT)
.setQueryApiType(QueryApiType.QUERY_API_TYPE_WRITE_API);
try {
// Lifecycle of the cached BigQueryWriteClient belongs to BigQueryConnection.close().
BigQueryWriteClient writeClient = this.connection.getBigQueryWriteClient();
LOG.info("Using Write API for bulk INSERT operation.");

long rowCount = bulkInsertWithWriteAPI(writeClient);
int[] insertArray = new int[Math.toIntExact(rowCount)];
Arrays.fill(insertArray, 1);

writeApiExecutionBuilder.setStatus(
com.google.cloud.bigquery.jdbc.telemetry.v1.Status.STATUS_SUCCESS);
writeApiExecutionBuilder.setStatus(Status.STATUS_SUCCESS);

return insertArray;

} catch (InterruptedException e) {
Thread.currentThread().interrupt();
writeApiExecutionBuilder
.setStatus(com.google.cloud.bigquery.jdbc.telemetry.v1.Status.STATUS_ERROR)
.setErrorCode(TelemetryManager.extractErrorCode(e));
fallbackErrorCode = TelemetryManager.extractErrorCode(e);
writeApiExecutionBuilder.setStatus(Status.STATUS_ERROR).setErrorCode(fallbackErrorCode);
throw new BigQueryJdbcException("Interrupted during Write API batch", e);
} catch (DescriptorValidationException | IOException e) {
writeApiExecutionBuilder
.setStatus(com.google.cloud.bigquery.jdbc.telemetry.v1.Status.STATUS_ERROR)
.setErrorCode(TelemetryManager.extractErrorCode(e));
} catch (BigQueryJdbcException e) {
fallbackErrorCode = TelemetryManager.extractErrorCode(e);
writeApiExecutionBuilder.setStatus(Status.STATUS_ERROR).setErrorCode(fallbackErrorCode);
throw e;
} catch (DescriptorValidationException | IOException | RuntimeException e) {
fallbackErrorCode = TelemetryManager.extractErrorCode(e);
writeApiExecutionBuilder.setStatus(Status.STATUS_ERROR).setErrorCode(fallbackErrorCode);
throw new BigQueryJdbcException("Failed to execute batch with Write API", e);
} finally {
if (writeApiExecutionBuilder.getStatus() == Status.STATUS_UNSPECIFIED) {
writeApiExecutionBuilder.setStatus(Status.STATUS_ERROR).setErrorCode(fallbackErrorCode);
}
long durationMs = System.currentTimeMillis() - startTime;
TelemetryManager.recordStatementExecution(writeApiExecutionBuilder, durationMs);
TelemetryManager.recordFeatureUsage(DriverFeature.DRIVER_FEATURE_BATCH_OPERATIONS);
Expand Down Expand Up @@ -483,6 +532,10 @@ public int[] executeBatch() throws SQLException {
}
}

BigQueryJdbcBulkInsertWriter createBulkInsertWriter() {
return new BigQueryJdbcBulkInsertWriter();
}

private long bulkInsertWithWriteAPI(BigQueryWriteClient bigQueryWriteClient)
throws DescriptorValidationException,
IOException,
Expand All @@ -491,10 +544,10 @@ private long bulkInsertWithWriteAPI(BigQueryWriteClient bigQueryWriteClient)
LOG.finer("++enter++");
RetrySettings retrySettings = this.connection.getRetrySettings();

BigQueryJdbcBulkInsertWriter bulkInsertWriter = new BigQueryJdbcBulkInsertWriter();
bulkInsertWriter.initialize(this.insertTableName, bigQueryWriteClient, retrySettings);

BigQueryJdbcBulkInsertWriter bulkInsertWriter = createBulkInsertWriter();
long rowCount;
try {
bulkInsertWriter.initialize(this.insertTableName, bigQueryWriteClient, retrySettings);
long offset = 0;
ProtoRows.Builder protoRowsBuilder = ProtoRows.newBuilder();
FieldList fieldLists = this.insertSchema.getFields();
Expand All @@ -518,21 +571,24 @@ private long bulkInsertWithWriteAPI(BigQueryWriteClient bigQueryWriteClient)
protoRowsBuilder = ProtoRows.newBuilder();
}
}
} catch (BigQueryJdbcException e) {
throw new BigQueryJdbcException("BigQueryJdbcException during bulkInsertWithWriteAPI", e);
rowCount = bulkInsertWriter.cleanup(bigQueryWriteClient);
} finally {
bulkInsertWriter.closeQuietly();
}

long rowCount = bulkInsertWriter.cleanup(bigQueryWriteClient);

BatchCommitWriteStreamsRequest commitRequest =
BatchCommitWriteStreamsRequest.newBuilder()
.setParent(this.insertTableName.toString())
.addWriteStreams(bulkInsertWriter.getStreamName())
.build();
BatchCommitWriteStreamsResponse commitResponse =
bigQueryWriteClient.batchCommitWriteStreams(commitRequest);
if (commitResponse.hasCommitTime() == false) {
throw new BigQueryJdbcException("Error committing the streams");
if (!commitResponse.hasCommitTime()) {
String details =
commitResponse.getStreamErrorsList().isEmpty()
? ""
: ": " + commitResponse.getStreamErrorsList();
throw new BigQueryJdbcException("Error committing the streams" + details);
}
LOG.finer("Commit called.");
return rowCount;
Expand Down
Loading
Loading