From remote machine getting connection refused for GCP Bigquery - google-cloud-platform

I am running a sample code from google to get a simple select query. Which is working fine in my local but from my k8s environment I am getting the below error
Exception in thread "main" com.google.cloud.bigquery.BigQueryException: Error getting access token for service account: connect timed out
at com.google.cloud.bigquery.spi.v2.HttpBigQueryRpc.translate(HttpBigQueryRpc.java:115)
at com.google.cloud.bigquery.spi.v2.HttpBigQueryRpc.create(HttpBigQueryRpc.java:220)
at com.google.cloud.bigquery.BigQueryImpl$5.call(BigQueryImpl.java:369)
at com.google.cloud.bigquery.BigQueryImpl$5.call(BigQueryImpl.java:366)
at com.google.api.gax.retrying.DirectRetryingExecutor.submit(DirectRetryingExecutor.java:105)
at com.google.cloud.RetryHelper.run(RetryHelper.java:76)
at com.google.cloud.RetryHelper.runWithRetries(RetryHelper.java:50)
at com.google.cloud.bigquery.BigQueryImpl.create(BigQueryImpl.java:365)
at com.google.cloud.bigquery.BigQueryImpl.create(BigQueryImpl.java:340)
at com.rakuten.dps.dataplatform.ingest.utility.BQ_test.main(BQ_test.java:67)
Caused by: java.io.IOException: Error getting access token for service account: connect timed out
at com.google.auth.oauth2.ServiceAccountCredentials.refreshAccessToken(ServiceAccountCredentials.java:444)
at com.google.auth.oauth2.OAuth2Credentials.refresh(OAuth2Credentials.java:157)
at com.google.auth.oauth2.OAuth2Credentials.getRequestMetadata(OAuth2Credentials.java:145)
at com.google.auth.oauth2.ServiceAccountCredentials.getRequestMetadata(ServiceAccountCredentials.java:603)
at com.google.auth.http.HttpCredentialsAdapter.initialize(HttpCredentialsAdapter.java:91)
at com.google.cloud.http.HttpTransportOptions$1.initialize(HttpTransportOptions.java:159)
at com.google.api.client.http.HttpRequestFactory.buildRequest(HttpRequestFactory.java:88)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.buildHttpRequest(AbstractGoogleClientRequest.java:422)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:541)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:474)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:591)
at com.google.cloud.bigquery.spi.v2.HttpBigQueryRpc.create(HttpBigQueryRpc.java:218)
... 8 more
Caused by: java.net.SocketTimeoutException: connect timed out
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:607)
at sun.security.ssl.SSLSocketImpl.connect(SSLSocketImpl.java:284)
at sun.net.NetworkClient.doConnect(NetworkClient.java:175)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:463)
at sun.net.www.http.HttpClient.openServer(HttpClient.java:558)
at sun.net.www.protocol.https.HttpsClient.<init>(HttpsClient.java:264)
at sun.net.www.protocol.https.HttpsClient.New(HttpsClient.java:367)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.getNewHttpClient(AbstractDelegateHttpsURLConnection.java:191)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1162)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1056)
at sun.net.www.protocol.https.AbstractDelegateHttpsURLConnection.connect(AbstractDelegateHttpsURLConnection.java:177)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream0(HttpURLConnection.java:1340)
at sun.net.www.protocol.http.HttpURLConnection.getOutputStream(HttpURLConnection.java:1315)
at sun.net.www.protocol.https.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java:264)
at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:113)
at com.google.api.client.http.javanet.NetHttpRequest.execute(NetHttpRequest.java:84)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:1012)
at com.google.auth.oauth2.ServiceAccountCredentials.refreshAccessToken(ServiceAccountCredentials.java:441)
... 19 more
Below is the sample Code:
public class BQ_test {
private static final Logger logger = LoggerFactory.getLogger(BQ_test.class);
public static void main(String[] args) {
Job queryJob = null;
String actualValue = "";
NetHttpTransport transport = new NetHttpTransport();
JsonFactory jsonFactory = new JacksonFactory();
String query = "SELECT * FROM `iconic-parsec-315409.bookmark_BQ.sbm_item_tbl``";
String projectId = "iconic-parsec-315409";
File credentialsPath = new File("/tmp/iconic-parsec-315409-823ef1c38a9d.json");
GoogleCredentials credentials;
try {
FileInputStream serviceAccountStream = new FileInputStream(credentialsPath);
credentials = ServiceAccountCredentials.fromStream(serviceAccountStream);
if (credentials.createScopedRequired()) {
Collection<String> bigqueryScopes = BigqueryScopes.all();
credentials = credentials.createScoped(bigqueryScopes);
}
BigQuery bigquery = BigQueryOptions
.newBuilder()
.setCredentials(credentials)
.setProjectId(projectId)
.build()
.getService();
QueryJobConfiguration queryConfig =
QueryJobConfiguration.newBuilder(query)
.setUseLegacySql(false)
.setJobTimeoutMs(180000L)
.build();
// Create a job ID so that we can safely retry.
JobId jobId = JobId.of(UUID.randomUUID().toString());
queryJob = bigquery.create(JobInfo.newBuilder(queryConfig).setJobId(jobId).build());
// Wait for the query to complete.
queryJob = queryJob.waitFor();
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
// Check for errors
if (queryJob == null) {
throw new RuntimeException("Job no longer exists");
} else if (queryJob.getStatus().getError() != null) {
// You can also look at queryJob.getStatus().getExecutionErrors() for all
// errors, not just the latest one.
throw new RuntimeException(queryJob.getStatus().getError().toString());
}
// Get the results.
TableResult result = null;
try {
result = queryJob.getQueryResults();
// Print all pages of the results.
// writeFvLToOrcFile(result,"/Users/susanta.a.adhikary/Downloads/test.orc");
for (FieldValueList row : result.iterateAll()) {
// String type
actualValue = row.get("sbm_item_id").getStringValue();
System.out.println(actualValue);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
I tried curl -I "https://oauth2.googleapis.com/token" from my remote k8s pod and getting
HTTP/2 404
content-type: text/html
date: Sun, 04 Jul 2021 05:54:09 GMT
server: scaffolding on HTTPServer2
So I dont think its a EGRESS issue.
The Data location is US-east-1 for GCP and the pod local timezone is UTC, I am not sure if its a NTP sync issue. Need Advice. Same Code runs fine from my local with the same serviceaccount key. ( Just to mention I have done a kubectl cp to move the serviceaccount.json to the pod for testing later I'll create a configmap or something)

Related

How can i solve proxy problem when using AWS device farm?

I'm trying to execute aws device farm example code that we can get below site.
https://docs.aws.amazon.com/devicefarm/latest/testgrid/getting-started-local.html
// Import the AWS SDK for Java 2.x Device Farm client:
...
// in your tests ...
public class MyTests {
// ... When you set up your test suite
private static RemoteWebDriver driver;
#Before
void setUp() {
String myProjectARN = "...";
DeviceFarmClient client = DeviceFarmClient.builder().region(Region.US_WEST_2).build();
CreateTestGridUrlRequest request = CreateTestGridUrlRequest.builder()
.expiresInSeconds(300)
.projectArn(myProjectARN)
.build();
CreateTestGridUrlResponse response = client.createTest.GridUrl(request);
URL testGridUrl = new URL(response.url());
// You can now pass this URL into RemoteWebDriver.
WebDriver driver = new RemoteWebDriver(testGridUrl, DesiredCapabilities.firefox());
}
#After
void tearDown() {
// make sure to close your WebDriver:
driver.quit();
}
}
After executing above codes, the error was occurred and the message is like this.
java.net.UnknownHostException: devicefarm.us-westt-2.amazonaws.com
I guess the code can't resolve host because of proxy server.
How can i resolve this problem?
Thanks.
Can you please confirm which line throws java.net.UnknownHostException: devicefarm.us-westt-2.amazonaws.com. Is it client.createTest.GridUrl(request) or WebDriver driver = new RemoteWebDriver(testGridUrl, DesiredCapabilities.firefox());
If it is the client.createTest.GridUrl(request), then please follow Proxy Configuration mentioned at https://docs.aws.amazon.com/sdk-for-java/v1/developer-guide/section-client-configuration.html
My current setUp method is like this.
#Before
public void setUp() {
try {
ProxyConfiguration.Builder proxyConfig = ProxyConfiguration.builder();
proxyConfig.endpoint(new URI("<YOUR PROXY URL>"));
proxyConfig.username("<YOUR USER ID>");
proxyConfig.password("YOUR PASSWORD");
ApacheHttpClient.Builder httpClientBuilder =
ApacheHttpClient.builder()
.proxyConfiguration(proxyConfig.build());
String myARN = "<YOUR ARN>";
DeviceFarmClient client = DeviceFarmClient.builder()
.credentialsProvider(DefaultCredentialsProvider.create())
.region(Region.US_WEST_2)
.httpClientBuilder(httpClientBuilder)
.overrideConfiguration(ClientOverrideConfiguration.builder().build())
.build();
CreateTestGridUrlRequest request = CreateTestGridUrlRequest.builder()
.expiresInSeconds(300) // 5 minutes
.projectArn(myARN)
.build();
URL testGridUrl = null;
CreateTestGridUrlResponse response = client.createTestGridUrl(request);
testGridUrl = new URL(response.url());
driver = new RemoteWebDriver(testGridUrl, DesiredCapabilities.chrome());
} catch (Exception e) {
e.printStackTrace();
}
}
Thank you again.

AWS Java SDK v2.10: QuickSightClient throws SdkClientException When Delete is Successful

quickSightClient.deleteUser(deleteUserRequest) throws a null pointer exception because it fails to marshall the 204 No Content response, which AWS Quicksight returns after successfully deleting a user.
My Questions:
Is there a better way to handle or avoid this problem than using a try/catch to swallow the error (see below)?
Should I report this as an bug in their GitHub project? I reported this GitHub Issue.
My Code:
private void deleteQuickSightUser() {
String awsAccountId = "..."
String roleName = "cc-embedding_quicksight_dashboard_role"
String email = "person#company.com"
String namespace = "default"
String roleArn = "arn:aws:iam::$awsAccountId:role/$roleName"
QuickSightClient quickSightClient = QuickSightClient.create()
User user = quickSightClient.listUsers(ListUsersRequest.builder()
.awsAccountId(awsAccountId)
.namespace(namespace)
.build()
).userList().find { it.email() == email }
if (user) {
log.error("found the $email user with username: $user.userName")
DeleteUserRequest deleteUserRequest = DeleteUserRequest.builder()
.awsAccountId(awsAccountId)
.namespace(namespace)
.userName(user.userName)
.build()
try {
/* *** THE FOLLOWING LINE THROWS THE EXCEPTION *** */
quickSightClient.deleteUser(deleteUserRequest)
} catch (SdkClientException e) {
log.error(e.message)
}
log.error("deleted user $user.email")
}
}
The Exception
2020-01-03 09:53:36.168 ERROR --- [nio-8080-exec-2] o.g.web.errors.GrailsExceptionResolver : NullPointerException occurred when processing request: [GET] /
Stacktrace follows:
java.lang.reflect.InvocationTargetException: null
at org.grails.core.DefaultGrailsControllerClass$ReflectionInvoker.invoke(DefaultGrailsControllerClass.java:211)
at org.grails.core.DefaultGrailsControllerClass.invoke(DefaultGrailsControllerClass.java:188)
at org.grails.web.mapping.mvc.UrlMappingsInfoHandlerAdapter.handle(UrlMappingsInfoHandlerAdapter.groovy:90)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at org.grails.web.servlet.mvc.GrailsWebRequestFilter.doFilterInternal(GrailsWebRequestFilter.java:77)
at org.grails.web.filters.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:67)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(Thread.java:745)
Caused by: software.amazon.awssdk.core.exception.SdkClientException: Unable to unmarshall response (null). Response Code: 204, Response Text: No Content
at software.amazon.awssdk.core.exception.SdkClientException$BuilderImpl.build(SdkClientException.java:97)
at software.amazon.awssdk.core.internal.http.pipeline.stages.HandleResponseStage.handleSuccessResponse(HandleResponseStage.java:100)
at software.amazon.awssdk.core.internal.http.pipeline.stages.HandleResponseStage.handleResponse(HandleResponseStage.java:70)
at software.amazon.awssdk.core.internal.http.pipeline.stages.HandleResponseStage.execute(HandleResponseStage.java:58)
at software.amazon.awssdk.core.internal.http.pipeline.stages.HandleResponseStage.execute(HandleResponseStage.java:41)
at software.amazon.awssdk.core.internal.http.pipeline.RequestPipelineBuilder$ComposingRequestPipelineStage.execute(RequestPipelineBuilder.java:206)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallAttemptTimeoutTrackingStage.execute(ApiCallAttemptTimeoutTrackingStage.java:73)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallAttemptTimeoutTrackingStage.execute(ApiCallAttemptTimeoutTrackingStage.java:42)
at software.amazon.awssdk.core.internal.http.pipeline.stages.TimeoutExceptionHandlingStage.execute(TimeoutExceptionHandlingStage.java:77)
at software.amazon.awssdk.core.internal.http.pipeline.stages.TimeoutExceptionHandlingStage.execute(TimeoutExceptionHandlingStage.java:39)
at software.amazon.awssdk.core.internal.http.pipeline.stages.RetryableStage$RetryExecutor.doExecute(RetryableStage.java:113)
at software.amazon.awssdk.core.internal.http.pipeline.stages.RetryableStage$RetryExecutor.execute(RetryableStage.java:86)
at software.amazon.awssdk.core.internal.http.pipeline.stages.RetryableStage.execute(RetryableStage.java:62)
at software.amazon.awssdk.core.internal.http.pipeline.stages.RetryableStage.execute(RetryableStage.java:42)
at software.amazon.awssdk.core.internal.http.pipeline.RequestPipelineBuilder$ComposingRequestPipelineStage.execute(RequestPipelineBuilder.java:206)
at software.amazon.awssdk.core.internal.http.StreamManagingStage.execute(StreamManagingStage.java:57)
at software.amazon.awssdk.core.internal.http.StreamManagingStage.execute(StreamManagingStage.java:37)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallTimeoutTrackingStage.executeWithTimer(ApiCallTimeoutTrackingStage.java:80)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallTimeoutTrackingStage.execute(ApiCallTimeoutTrackingStage.java:60)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ApiCallTimeoutTrackingStage.execute(ApiCallTimeoutTrackingStage.java:42)
at software.amazon.awssdk.core.internal.http.pipeline.RequestPipelineBuilder$ComposingRequestPipelineStage.execute(RequestPipelineBuilder.java:206)
at software.amazon.awssdk.core.internal.http.pipeline.RequestPipelineBuilder$ComposingRequestPipelineStage.execute(RequestPipelineBuilder.java:206)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ExecutionFailureExceptionReportingStage.execute(ExecutionFailureExceptionReportingStage.java:37)
at software.amazon.awssdk.core.internal.http.pipeline.stages.ExecutionFailureExceptionReportingStage.execute(ExecutionFailureExceptionReportingStage.java:26)
at software.amazon.awssdk.core.internal.http.AmazonSyncHttpClient$RequestExecutionBuilderImpl.execute(AmazonSyncHttpClient.java:240)
at software.amazon.awssdk.core.client.handler.BaseSyncClientHandler.invoke(BaseSyncClientHandler.java:96)
at software.amazon.awssdk.core.client.handler.BaseSyncClientHandler.execute(BaseSyncClientHandler.java:120)
at software.amazon.awssdk.core.client.handler.BaseSyncClientHandler.execute(BaseSyncClientHandler.java:73)
at software.amazon.awssdk.core.client.handler.SdkSyncClientHandler.execute(SdkSyncClientHandler.java:44)
at software.amazon.awssdk.awscore.client.handler.AwsSyncClientHandler.execute(AwsSyncClientHandler.java:55)
at software.amazon.awssdk.services.quicksight.DefaultQuickSightClient.deleteUser(DefaultQuickSightClient.java:1341)
at grails4test.ApplicationController.deleteUser(ApplicationController.groovy:85)
at grails4test.ApplicationController.doStuff(ApplicationController.groovy:44)
at grails4test.ApplicationController.index(ApplicationController.groovy:23)
... 13 common frames omitted
Caused by: java.lang.NullPointerException: null
at software.amazon.awssdk.core.io.SdkFilterInputStream.read(SdkFilterInputStream.java:66)
at com.fasterxml.jackson.core.json.ByteSourceJsonBootstrapper.ensureLoaded(ByteSourceJsonBootstrapper.java:522)
at com.fasterxml.jackson.core.json.ByteSourceJsonBootstrapper.detectEncoding(ByteSourceJsonBootstrapper.java:129)
at com.fasterxml.jackson.core.json.ByteSourceJsonBootstrapper.constructParser(ByteSourceJsonBootstrapper.java:246)
at com.fasterxml.jackson.core.JsonFactory._createParser(JsonFactory.java:1315)
at com.fasterxml.jackson.core.JsonFactory.createParser(JsonFactory.java:820)
at software.amazon.awssdk.protocols.json.internal.dom.JsonDomParser.parse(JsonDomParser.java:39)
at software.amazon.awssdk.protocols.json.internal.unmarshall.JsonProtocolUnmarshaller.unmarshall(JsonProtocolUnmarshaller.java:167)
at software.amazon.awssdk.protocols.json.internal.unmarshall.JsonResponseHandler.handle(JsonResponseHandler.java:79)
at software.amazon.awssdk.protocols.json.internal.unmarshall.JsonResponseHandler.handle(JsonResponseHandler.java:36)
at software.amazon.awssdk.protocols.json.internal.unmarshall.AwsJsonResponseHandler.handle(AwsJsonResponseHandler.java:43)
at software.amazon.awssdk.awscore.client.handler.AwsSyncClientHandler$Crc32ValidationResponseHandler.handle(AwsSyncClientHandler.java:88)
at software.amazon.awssdk.core.client.handler.BaseClientHandler.lambda$interceptorCalling$2(BaseClientHandler.java:151)
at software.amazon.awssdk.core.client.handler.AttachHttpMetadataResponseHandler.handle(AttachHttpMetadataResponseHandler.java:40)
at software.amazon.awssdk.core.client.handler.AttachHttpMetadataResponseHandler.handle(AttachHttpMetadataResponseHandler.java:28)
at software.amazon.awssdk.core.internal.http.pipeline.stages.HandleResponseStage.handleSuccessResponse(HandleResponseStage.java:89)
... 45 common frames omitted
I think you should use try/catch for now and report this as a bug. What does the stack trace look like?

AmazonS3 error while downloading the file using java

I am getting the following exception while trying to download a file from AmazonS3 bucket. This is working fine from Java IDE but when I run the same code from other java based product it is failing. I have loaded all the client needed jar files,
VENDOR_JAR=/u01/app/sterling/jar/amazons3/1_0/aws-java-sdk-core-1.11.250.jar
VENDOR_JAR=/u01/app/sterling/jar/amazons3/1_0/aws-java-sdk-s3-1.11.250.jar
VENDOR_JAR=/u01/app/sterling/jar/amazons3/1_0/httpclient-4.5.2.jar
VENDOR_JAR=/u01/app/sterling/jar/amazons3/1_0/httpcore-4.4.4.jar
VENDOR_JAR=/u01/app/sterling/jar/amazons3/1_0/jackson-annotations-2.6.0.jar
VENDOR_JAR=/u01/app/sterling/jar/amazons3/1_0/jackson-core-2.6.7.jar
VENDOR_JAR=/u01/app/sterling/jar/amazons3/1_0/jackson-databind-2.6.7.1.jar
VENDOR_JAR=/u01/app/sterling/jar/amazons3/1_0/joda-time-2.8.1.jar
Caused by: java.net.SocketException: Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:168)
at com.sun.net.ssl.internal.ssl.InputRecord.readFully(InputRecord.java:293)
at com.sun.net.ssl.internal.ssl.InputRecord.read(InputRecord.java:331)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.readRecord(SSLSocketImpl.java:798)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.performInitialHandshake(SSLSocketImpl.java:1138)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1165)
at com.sun.net.ssl.internal.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:1149)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:394)
at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:353)
at com.amazonaws.http.conn.ssl.SdkTLSSocketFactory.connectSocket(SdkTLSSocketFactory.java:132)
at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:141)
at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.amazonaws.http.conn.ClientConnectionManagerFactory$Handler.invoke(ClientConnectionManagerFactory.java:76)
at com.amazonaws.http.conn.$Proxy15.connect(Unknown Source)
at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380)
at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184)
at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:82)
at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:55)
at com.amazonaws.http.apache.client.impl.SdkHttpClient.execute(SdkHttpClient.java:72)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeOneRequest(AmazonHttpClient.java:1236)
at com.amazonaws.http.AmazonHttpClient$RequestExecutor.executeHelper(AmazonHttpClient.java:1056)
... 24 more
Java Code:
AWSCredentials credentials = new BasicAWSCredentials(accessKey, secretKey);
AmazonS3 s3Client = new AmazonS3Client(credentials);
System.out.println("Initialized Client Finally!!");
S3Object object = s3Client.getObject(new GetObjectRequest(bucketName, fileName));
displayTextInputStream(object.getObjectContent());
public void displayTextInputStream(InputStream input)throws IOException {
System.out.println("Inside displayTextInputStream()..........");
// Read one text line at a time and display.
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
while (true) {
String line = reader.readLine();
if (line == null) break;
System.out.println(" " + line);
}
System.out.println();
}

Instance created via Service Account unable to use Google Cloud Speech API - authentication error

I followed Google's Quick-Start documentation for the Speech API to enable billing and API for an account. This account has authorized a service account to create Compute instances on its behalf. After creating an instance on the child account, hosting a binary to use the Speech API, I am unable to successfully use the example C# code provided by Google in the C# speech example:
try
{
var speech = SpeechClient.Create();
var response = speech.Recognize(new RecognitionConfig()
{
Encoding = RecognitionConfig.Types.AudioEncoding.Linear16,
LanguageCode = "en"
}, RecognitionAudio.FromFile(audioFiles[0]));
foreach (var result in response.Results)
{
foreach (var alternative in result.Alternatives)
{
Debug.WriteLine(alternative.Transcript);
}
}
} catch (Exception ex)
// ...
}
Requests fail on the SpeechClient.Create() line with the following error:
--------------------------- Grpc.Core.RpcException: Status(StatusCode=Unauthenticated, Detail="Exception occured in
metadata credentials plugin.")
at
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task
task)
at
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task
task)
at Grpc.Core.Internal.AsyncCall`2.UnaryCall(TRequest msg)
at
Grpc.Core.Calls.BlockingUnaryCall[TRequest,TResponse](CallInvocationDetails`2
call, TRequest req)
at
Grpc.Core.DefaultCallInvoker.BlockingUnaryCall[TRequest,TResponse](Method`2
method, String host, CallOptions options, TRequest request)
at
Grpc.Core.Internal.InterceptingCallInvoker.BlockingUnaryCall[TRequest,TResponse](Method`2
method, String host, CallOptions options, TRequest request)
at
Google.Cloud.Speech.V1.Speech.SpeechClient.Recognize(RecognizeRequest
request, CallOptions options)
at
Google.Api.Gax.Grpc.ApiCall.<>c__DisplayClass0_0`2.b__1(TRequest
req, CallSettings cs)
at
Google.Api.Gax.Grpc.ApiCallRetryExtensions.<>c__DisplayClass1_0`2.b__0(TRequest
request, CallSettings callSettings)
at Google.Api.Gax.Grpc.ApiCall`2.Sync(TRequest request,
CallSettings perCallCallSettings)
at
Google.Cloud.Speech.V1.SpeechClientImpl.Recognize(RecognizeRequest
request, CallSettings callSettings)
at Google.Cloud.Speech.V1.SpeechClient.Recognize(RecognitionConfig
config, RecognitionAudio audio, CallSettings callSettings)
at Rc2Solver.frmMain.RecognizeWordsGoogleSpeechApi() in
C:\Users\jorda\Google
Drive\VSProjects\Rc2Solver\Rc2Solver\frmMain.cs:line 1770
--------------------------- OK
I have verified that the Speech API is activated. Here is the scope that the service account uses when creating the Compute instances:
credential = new ServiceAccountCredential(
new ServiceAccountCredential.Initializer(me)
{
Scopes = new[] { ComputeService.Scope.Compute, ComputeService.Scope.CloudPlatform }
}.FromPrivateKey(yk)
);
I have found no information or code online about specifically authorizing or authenticating the Speech API for service account actors. Any help is appreciated.
It turns out the issue was that the Cloud Compute instances needed to be created with a ServiceAccount parameter specified. Otherwise the Cloud instances were not part of a ServiceAccount default credential, which is referenced by the SpeechClient.Create() call. Here is the proper way to create an instance attached to a service account, and it will use the SA tied to the project ID:
service = new ComputeService(new BaseClientService.Initializer() {
HttpClientInitializer = credential,
ApplicationName = "YourAppName"
});
string MyProjectId = "example-project-27172";
var project = await service.Projects.Get(MyProjectId).ExecuteAsync();
ServiceAccount servAcct = new ServiceAccount() {
Email = project.DefaultServiceAccount,
Scopes = new [] {
"https://www.googleapis.com/auth/cloud-platform"
}
};
Instance instance = new Instance() {
MachineType = service.BaseUri + MyProjectId + "/zones/" + targetZone + "/machineTypes/" + "g1-small",
Name = name,
Description = name,
Disks = attachedDisks,
NetworkInterfaces = networkInterfaces,
ServiceAccounts = new [] {
servAcct
},
Metadata = md
};
batchRequest.Queue < Instance > (service.Instances.Insert(instance, MyProjectId, targetZone),
(content, error, i, message) => {
if (error != null) {
AddEventMsg("Error creating instance " + name + ": " + error.ToString());
} else {
AddEventMsg("Instance " + name + " created");
}
});

Amazon API ItemSearch returns (400) Bad Request

I'm using a simple example from Amazon documentation for ItemSearch and I get a strange error:
"The remote server returned an unexpected response: (400) Bad Request."
This is the code:
public static void Main()
{
//Remember to create an instance of the amazon service, including you Access ID.
AWSECommerceServicePortTypeClient service = new AWSECommerceServicePortTypeClient(new BasicHttpBinding(),
new EndpointAddress(
"http://webservices.amazon.com/onca/soap?Service=AWSECommerceService"));
AWSECommerceServicePortTypeClient client = new AWSECommerceServicePortTypeClient(
new BasicHttpBinding(),
new EndpointAddress("http://webservices.amazon.com/onca/soap?Service=AWSECommerceService"));
// prepare an ItemSearch request
ItemSearchRequest request = new ItemSearchRequest();
request.SearchIndex = "Books";
request.Title = "Harry+Potter";
request.ResponseGroup = new string[] { "Small" };
ItemSearch itemSearch = new ItemSearch();
itemSearch.Request = new ItemSearchRequest[] { request };
itemSearch.AWSAccessKeyId = accessKeyId;
// issue the ItemSearch request
try
{
ItemSearchResponse response = client.ItemSearch(itemSearch);
// write out the results
foreach (var item in response.Items[0].Item)
{
Console.WriteLine(item.ItemAttributes.Title);
}
}
catch(Exception e)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e.Message);
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Press any key to quit...");
Clipboard.SetText(e.Message);
}
Console.ReadKey();
What is wrong?
You receive this message because your request is not signed. Starting from August 2009 all requests must be signed.
Here you can see at the example about how to sign amazon requests:
http://developer.amazonwebservices.com/connect/entry.jspa?externalID=2480&categoryID=14