Search in sources :

Example 21 with TableDataInsertAllResponse

use of com.google.api.services.bigquery.model.TableDataInsertAllResponse in project beam by apache.

the class BigqueryClient method insertDataToTable.

/**
 * Inserts rows to a table using a BigQuery streaming write.
 */
public void insertDataToTable(String projectId, String datasetId, String tableName, List<Map<String, Object>> rows) throws IOException, InterruptedException {
    Sleeper sleeper = Sleeper.DEFAULT;
    BackOff backoff = BackOffAdapter.toGcpBackOff(BACKOFF_FACTORY.backoff());
    IOException lastException = null;
    do {
        if (lastException != null) {
            LOG.warn("Retrying insert table ({}) after exception", tableName, lastException);
        }
        try {
            List<Rows> dataRows = rows.stream().map(row -> new Rows().setJson(row)).collect(Collectors.toList());
            TableDataInsertAllResponse response = this.bqClient.tabledata().insertAll(projectId, datasetId, tableName, new TableDataInsertAllRequest().setRows(dataRows)).execute();
            if (response != null && (response.getInsertErrors() == null || response.getInsertErrors().isEmpty())) {
                LOG.info("Successfully inserted data into table : " + tableName);
                return;
            } else {
                if (response == null || response.getInsertErrors() == null) {
                    lastException = new IOException("Expected valid response from insert data job, but received null.");
                } else {
                    lastException = new IOException(String.format("Got insertion error (%s)", response.getInsertErrors().toString()));
                }
            }
        } catch (IOException e) {
            // ignore and retry
            lastException = e;
        }
    } while (BackOffUtils.next(sleeper, backoff));
    throw new RuntimeException(String.format("Unable to get BigQuery response after retrying %d times for table (%s)", MAX_QUERY_RETRIES, tableName), lastException);
}
Also used : DatasetReference(com.google.api.services.bigquery.model.DatasetReference) LoggerFactory(org.slf4j.LoggerFactory) Random(java.util.Random) Data(com.google.api.client.util.Data) QueryRequest(com.google.api.services.bigquery.model.QueryRequest) Transport(org.apache.beam.sdk.extensions.gcp.util.Transport) Map(java.util.Map) TableRow(com.google.api.services.bigquery.model.TableRow) TableSchema(com.google.api.services.bigquery.model.TableSchema) Internal(org.apache.beam.sdk.annotations.Internal) Collection(java.util.Collection) HttpTransport(com.google.api.client.http.HttpTransport) Credentials(com.google.auth.Credentials) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) List(java.util.List) TableDataInsertAllResponse(com.google.api.services.bigquery.model.TableDataInsertAllResponse) TableDataInsertAllRequest(com.google.api.services.bigquery.model.TableDataInsertAllRequest) HttpCredentialsAdapter(com.google.auth.http.HttpCredentialsAdapter) ImmutableList(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList) BackOff(com.google.api.client.util.BackOff) Dataset(com.google.api.services.bigquery.model.Dataset) TableList(com.google.api.services.bigquery.model.TableList) Duration(org.joda.time.Duration) Rows(com.google.api.services.bigquery.model.TableDataInsertAllRequest.Rows) Tables(com.google.api.services.bigquery.model.TableList.Tables) GetQueryResultsResponse(com.google.api.services.bigquery.model.GetQueryResultsResponse) BackOffAdapter(org.apache.beam.sdk.extensions.gcp.util.BackOffAdapter) Preconditions.checkArgument(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkArgument) Job(com.google.api.services.bigquery.model.Job) Nonnull(javax.annotation.Nonnull) Sleeper(com.google.api.client.util.Sleeper) Nullable(org.checkerframework.checker.nullness.qual.Nullable) QueryResponse(com.google.api.services.bigquery.model.QueryResponse) TableReference(com.google.api.services.bigquery.model.TableReference) TableFieldSchema(com.google.api.services.bigquery.model.TableFieldSchema) FluentBackoff(org.apache.beam.sdk.util.FluentBackoff) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) ClassInfo(com.google.api.client.util.ClassInfo) GoogleCredentials(com.google.auth.oauth2.GoogleCredentials) Lists(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Lists) IOException(java.io.IOException) Table(com.google.api.services.bigquery.model.Table) BackOffUtils(com.google.api.client.util.BackOffUtils) Bigquery(com.google.api.services.bigquery.Bigquery) Preconditions.checkState(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Preconditions.checkState) JsonFactory(com.google.api.client.json.JsonFactory) JobConfigurationQuery(com.google.api.services.bigquery.model.JobConfigurationQuery) BigqueryScopes(com.google.api.services.bigquery.BigqueryScopes) JobConfiguration(com.google.api.services.bigquery.model.JobConfiguration) TableDataInsertAllRequest(com.google.api.services.bigquery.model.TableDataInsertAllRequest) TableDataInsertAllResponse(com.google.api.services.bigquery.model.TableDataInsertAllResponse) Sleeper(com.google.api.client.util.Sleeper) IOException(java.io.IOException) BackOff(com.google.api.client.util.BackOff) Rows(com.google.api.services.bigquery.model.TableDataInsertAllRequest.Rows)

Example 22 with TableDataInsertAllResponse

use of com.google.api.services.bigquery.model.TableDataInsertAllResponse in project beam by apache.

the class BigQueryServicesImplTest method testInsertStoppedRetry.

/**
 * Tests that {@link DatasetServiceImpl#insertAll} can stop quotaExceeded retry attempts.
 */
@Test
public void testInsertStoppedRetry() throws Exception {
    TableReference ref = new TableReference().setProjectId("project").setDatasetId("dataset").setTableId("table");
    List<FailsafeValueInSingleWindow<TableRow, TableRow>> rows = new ArrayList<>();
    rows.add(wrapValue(new TableRow()));
    MockSetupFunction quotaExceededResponse = response -> {
        when(response.getStatusCode()).thenReturn(403);
        when(response.getContentType()).thenReturn(Json.MEDIA_TYPE);
        when(response.getContent()).thenReturn(toStream(errorWithReasonAndStatus("quotaExceeded", 403)));
    };
    // Respond 403 four times, then valid payload.
    setupMockResponses(quotaExceededResponse, quotaExceededResponse, quotaExceededResponse, quotaExceededResponse, response -> {
        when(response.getContentType()).thenReturn(Json.MEDIA_TYPE);
        when(response.getStatusCode()).thenReturn(200);
        when(response.getContent()).thenReturn(toStream(new TableDataInsertAllResponse()));
    });
    thrown.expect(RuntimeException.class);
    // Google-http-client 1.39.1 and higher does not read the content of the response with error
    // status code. How can we ensure appropriate exception is thrown?
    thrown.expectMessage("quotaExceeded");
    DatasetServiceImpl dataService = new DatasetServiceImpl(bigquery, null, PipelineOptionsFactory.create());
    dataService.insertAll(ref, rows, null, BackOffAdapter.toGcpBackOff(TEST_BACKOFF.backoff()), TEST_BACKOFF, new MockSleeper(), InsertRetryPolicy.alwaysRetry(), null, null, false, false, false, null);
    verifyAllResponsesAreRead();
    verifyWriteMetricWasSet("project", "dataset", "table", "quotaexceeded", 1);
}
Also used : MetricName(org.apache.beam.sdk.metrics.MetricName) ExpectedLogs(org.apache.beam.sdk.testing.ExpectedLogs) ReadRowsResponse(com.google.cloud.bigquery.storage.v1.ReadRowsResponse) MockSleeper(com.google.api.client.testing.util.MockSleeper) ValueInSingleWindow(org.apache.beam.sdk.values.ValueInSingleWindow) ErrorInfo(com.google.api.client.googleapis.json.GoogleJsonError.ErrorInfo) MockitoAnnotations(org.mockito.MockitoAnnotations) GoogleJsonErrorContainer(com.google.api.client.googleapis.json.GoogleJsonErrorContainer) Strings(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Strings) GenericJson(com.google.api.client.json.GenericJson) GlobalWindow(org.apache.beam.sdk.transforms.windowing.GlobalWindow) Status(io.grpc.Status) JobServiceImpl(org.apache.beam.sdk.io.gcp.bigquery.BigQueryServicesImpl.JobServiceImpl) FastNanoClockAndSleeper(org.apache.beam.sdk.extensions.gcp.util.FastNanoClockAndSleeper) Json(com.google.api.client.json.Json) Mockito.atLeastOnce(org.mockito.Mockito.atLeastOnce) HttpResponseException(com.google.api.client.http.HttpResponseException) Matchers.instanceOf(org.hamcrest.Matchers.instanceOf) MockLowLevelHttpRequest(com.google.api.client.testing.http.MockLowLevelHttpRequest) Assert.assertFalse(org.junit.Assert.assertFalse) Matchers.is(org.hamcrest.Matchers.is) Metadata(io.grpc.Metadata) RetryBoundedBackOff(com.google.cloud.hadoop.util.RetryBoundedBackOff) Matchers.containsString(org.hamcrest.Matchers.containsString) DatasetServiceImpl(org.apache.beam.sdk.io.gcp.bigquery.BigQueryServicesImpl.DatasetServiceImpl) Mockito.mock(org.mockito.Mockito.mock) MockHttpTransport(com.google.api.client.testing.http.MockHttpTransport) MonitoringInfoMetricName(org.apache.beam.runners.core.metrics.MonitoringInfoMetricName) Duration(org.joda.time.Duration) RunWith(org.junit.runner.RunWith) ArrayList(java.util.ArrayList) JobReference(com.google.api.services.bigquery.model.JobReference) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Before(org.junit.Before) TableReference(com.google.api.services.bigquery.model.TableReference) RetryHttpRequestInitializer(org.apache.beam.sdk.extensions.gcp.util.RetryHttpRequestInitializer) TableFieldSchema(com.google.api.services.bigquery.model.TableFieldSchema) GoogleJsonError(com.google.api.client.googleapis.json.GoogleJsonError) ReadSession(com.google.cloud.bigquery.storage.v1.ReadSession) MetricsContainerImpl(org.apache.beam.runners.core.metrics.MetricsContainerImpl) Assert.assertTrue(org.junit.Assert.assertTrue) Mockito.times(org.mockito.Mockito.times) IOException(java.io.IOException) Test(org.junit.Test) ApiException(com.google.api.gax.rpc.ApiException) MetricsEnvironment(org.apache.beam.sdk.metrics.MetricsEnvironment) Mockito.never(org.mockito.Mockito.never) Assert.assertNull(org.junit.Assert.assertNull) Bigquery(com.google.api.services.bigquery.Bigquery) StatusCode(com.google.api.gax.rpc.StatusCode) Assert.assertEquals(org.junit.Assert.assertEquals) CreateReadSessionRequest(com.google.cloud.bigquery.storage.v1.CreateReadSessionRequest) SplitReadStreamRequest(com.google.cloud.bigquery.storage.v1.SplitReadStreamRequest) ApiErrorExtractor(com.google.cloud.hadoop.util.ApiErrorExtractor) ReadRowsRequest(com.google.cloud.bigquery.storage.v1.ReadRowsRequest) GoogleJsonResponseException(com.google.api.client.googleapis.json.GoogleJsonResponseException) ByteArrayInputStream(java.io.ByteArrayInputStream) Transport(org.apache.beam.sdk.extensions.gcp.util.Transport) TableRow(com.google.api.services.bigquery.model.TableRow) Assert.fail(org.junit.Assert.fail) TableSchema(com.google.api.services.bigquery.model.TableSchema) FailsafeValueInSingleWindow(org.apache.beam.sdk.values.FailsafeValueInSingleWindow) JacksonFactory(com.google.api.client.json.jackson2.JacksonFactory) PaneInfo(org.apache.beam.sdk.transforms.windowing.PaneInfo) Parser(com.google.protobuf.Parser) List(java.util.List) JobStatus(com.google.api.services.bigquery.model.JobStatus) TableDataInsertAllResponse(com.google.api.services.bigquery.model.TableDataInsertAllResponse) TableDataInsertAllRequest(com.google.api.services.bigquery.model.TableDataInsertAllRequest) ImmutableList(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList) BackOff(com.google.api.client.util.BackOff) ErrorProto(com.google.api.services.bigquery.model.ErrorProto) ArgumentMatchers.any(org.mockito.ArgumentMatchers.any) Assert.assertThrows(org.junit.Assert.assertThrows) HashMap(java.util.HashMap) PipelineOptionsFactory(org.apache.beam.sdk.options.PipelineOptionsFactory) BackOffAdapter(org.apache.beam.sdk.extensions.gcp.util.BackOffAdapter) RetryInfo(com.google.rpc.RetryInfo) Verify(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.base.Verify) MonitoringInfoConstants(org.apache.beam.runners.core.metrics.MonitoringInfoConstants) Job(com.google.api.services.bigquery.model.Job) ExpectedException(org.junit.rules.ExpectedException) Sleeper(com.google.api.client.util.Sleeper) GcpResourceIdentifiers(org.apache.beam.runners.core.metrics.GcpResourceIdentifiers) FluentBackoff(org.apache.beam.sdk.util.FluentBackoff) Iterator(java.util.Iterator) Assert.assertNotNull(org.junit.Assert.assertNotNull) Lists(org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.Lists) Mockito.when(org.mockito.Mockito.when) JUnit4(org.junit.runners.JUnit4) InsertErrors(com.google.api.services.bigquery.model.TableDataInsertAllResponse.InsertErrors) Table(com.google.api.services.bigquery.model.Table) Mockito.verify(org.mockito.Mockito.verify) LowLevelHttpResponse(com.google.api.client.http.LowLevelHttpResponse) Rule(org.junit.Rule) SplitReadStreamResponse(com.google.cloud.bigquery.storage.v1.SplitReadStreamResponse) TableDataList(com.google.api.services.bigquery.model.TableDataList) InputStream(java.io.InputStream) TableReference(com.google.api.services.bigquery.model.TableReference) DatasetServiceImpl(org.apache.beam.sdk.io.gcp.bigquery.BigQueryServicesImpl.DatasetServiceImpl) TableRow(com.google.api.services.bigquery.model.TableRow) TableDataInsertAllResponse(com.google.api.services.bigquery.model.TableDataInsertAllResponse) ArrayList(java.util.ArrayList) FailsafeValueInSingleWindow(org.apache.beam.sdk.values.FailsafeValueInSingleWindow) MockSleeper(com.google.api.client.testing.util.MockSleeper) Test(org.junit.Test)

Example 23 with TableDataInsertAllResponse

use of com.google.api.services.bigquery.model.TableDataInsertAllResponse in project beam by apache.

the class BigQueryServicesImplTest method testInsertQuotaExceededRetry.

/**
 * Tests that {@link DatasetServiceImpl#insertAll} retries quota exceeded attempts.
 */
@Test
public void testInsertQuotaExceededRetry() throws Exception {
    TableReference ref = new TableReference().setProjectId("project").setDatasetId("dataset").setTableId("table");
    List<FailsafeValueInSingleWindow<TableRow, TableRow>> rows = new ArrayList<>();
    rows.add(wrapValue(new TableRow()));
    // First response is 403 quota exceeded, second response has valid payload.
    setupMockResponses(response -> {
        when(response.getStatusCode()).thenReturn(403);
        when(response.getContentType()).thenReturn(Json.MEDIA_TYPE);
        when(response.getContent()).thenReturn(toStream(errorWithReasonAndStatus("quotaExceeded", 403)));
    }, response -> {
        when(response.getContentType()).thenReturn(Json.MEDIA_TYPE);
        when(response.getStatusCode()).thenReturn(200);
        when(response.getContent()).thenReturn(toStream(new TableDataInsertAllResponse()));
    });
    DatasetServiceImpl dataService = new DatasetServiceImpl(bigquery, null, PipelineOptionsFactory.create());
    dataService.insertAll(ref, rows, null, BackOffAdapter.toGcpBackOff(TEST_BACKOFF.backoff()), TEST_BACKOFF, new MockSleeper(), InsertRetryPolicy.alwaysRetry(), null, null, false, false, false, null);
    verifyAllResponsesAreRead();
    expectedLogs.verifyInfo("BigQuery insertAll error, retrying:");
    verifyWriteMetricWasSet("project", "dataset", "table", "quotaexceeded", 1);
}
Also used : TableReference(com.google.api.services.bigquery.model.TableReference) DatasetServiceImpl(org.apache.beam.sdk.io.gcp.bigquery.BigQueryServicesImpl.DatasetServiceImpl) TableRow(com.google.api.services.bigquery.model.TableRow) TableDataInsertAllResponse(com.google.api.services.bigquery.model.TableDataInsertAllResponse) ArrayList(java.util.ArrayList) FailsafeValueInSingleWindow(org.apache.beam.sdk.values.FailsafeValueInSingleWindow) MockSleeper(com.google.api.client.testing.util.MockSleeper) Test(org.junit.Test)

Aggregations

TableDataInsertAllResponse (com.google.api.services.bigquery.model.TableDataInsertAllResponse)23 TableReference (com.google.api.services.bigquery.model.TableReference)18 TableRow (com.google.api.services.bigquery.model.TableRow)18 Test (org.junit.Test)18 MockSleeper (com.google.api.client.testing.util.MockSleeper)16 DatasetServiceImpl (org.apache.beam.sdk.io.gcp.bigquery.BigQueryServicesImpl.DatasetServiceImpl)16 FailsafeValueInSingleWindow (org.apache.beam.sdk.values.FailsafeValueInSingleWindow)14 ValueInSingleWindow (org.apache.beam.sdk.values.ValueInSingleWindow)10 ErrorProto (com.google.api.services.bigquery.model.ErrorProto)9 ArrayList (java.util.ArrayList)9 TableDataInsertAllRequest (com.google.api.services.bigquery.model.TableDataInsertAllRequest)8 InsertErrors (com.google.api.services.bigquery.model.TableDataInsertAllResponse.InsertErrors)8 Matchers.containsString (org.hamcrest.Matchers.containsString)8 Bigquery (com.google.api.services.bigquery.Bigquery)6 List (java.util.List)6 Table (com.google.api.services.bigquery.model.Table)5 TableSchema (com.google.api.services.bigquery.model.TableSchema)5 IOException (java.io.IOException)5 Transport (org.apache.beam.sdk.extensions.gcp.util.Transport)5 ImmutableList (org.apache.beam.vendor.guava.v26_0_jre.com.google.common.collect.ImmutableList)5