Google cloud vision crashes on Image Annotator Client creation - google-cloud-vision

I'm using google cloud vision to detect and extract text from images.
It was working fine but suddenly started to crash without any exceptions caught.
I could not reproduce this locally, only occurs on the staging environment (Amazon EC2)
I know this question was asked before but it was not answered properly.
public ImageAnnotatorClient getInstance() throws IOException {
try {
if (imageAnnotatorClient == null) {
log.info("creating Image Annotator Client ...");
log.info("creating ServiceAccountCredentials ...");
var credentialStream = new ByteArrayInputStream(
propertiesService.get("GOOGLE_VISION_SERVICE_ACCOUNT_CREDENTIAL").getBytes());
Credentials myCredentials = ServiceAccountCredentials.fromStream(credentialStream);
log.info("creating Image Annotator Settings ...");
ImageAnnotatorSettings imageAnnotatorSettings =
ImageAnnotatorSettings.newBuilder()
.setCredentialsProvider(FixedCredentialsProvider.create(myCredentials))
.build();
imageAnnotatorClient = ImageAnnotatorClient.create(imageAnnotatorSettings);
log.info("created Image Annotator Client successfully, used credentials:\n" + propertiesService.get("GOOGLE_VISION_SERVICE_ACCOUNT_CREDENTIAL"));
}
return imageAnnotatorClient;
}catch(Exception e){
log.error(e.getMessage());
throw new QalamException(Error.builder().message("could not create ImageAnnotatorClient : " + e.getMessage()).build());
}
}
The code doesn't reach the last logging line in the code and crashes.
and this is what I get in the logs:
A fatal error has been detected by the Java Runtime Environment:
SIGSEGV (0xb) at pc=0x0000000000003fd6, pid=1, tid=52
JRE version: OpenJDK Runtime Environment (17.0+14) (build 17-ea+14)
Java VM: OpenJDK 64-Bit Server VM (17-ea+14, mixed mode, sharing, tiered, compressed oops, compressed class ptrs, g1 gc, linux-amd64)
Problematic frame:
C 0x0000000000003fd6
Core dump will be written. Default location: /home/app/core.1
An error report file with more information is saved as:
/home/app/hs_err_pid1.log

Related

"sbt server is already booting." error when launching sbt from wsl2 ubuntu

I've installed sbt using sdkman on wsl2 ubuntu setup. Currently sbt 1.4.2 is installed. When I try to launch it from the terminal it gives
sbt server is already booting. Create a new server? y/n (default y) if I choose n, nothing happens. If I choose y, then sbt starts. What I want to do is to be able to start sbt without that error message. Because this behaviour breaks metals on visual studio code.
I checked the sbt source code and found that the method below prints the error message - in sbt/main/src/main/scala/sbt/Main.scala
private def getSocketOrExit(
configuration: xsbti.AppConfiguration
): (Option[BootServerSocket], Option[Exit]) =
try (Some(new BootServerSocket(configuration)) -> None)
catch {
case _: ServerAlreadyBootingException
if System.console != null && !ITerminal.startedByRemoteClient =>
println("sbt server is already booting. Create a new server? y/n (default y)")
val exit = ITerminal.get.withRawInput(System.in.read) match {
case 110 => Some(Exit(1))
case _ => None
}
(None, exit)
case _: ServerAlreadyBootingException =>
if (SysProp.forceServerStart) (None, None)
else (None, Some(Exit(2)))
}
}
So, calling new BootServerSocket(configuration) throws an exception. Exception source is the method below from BootServerSocket.java;
static ServerSocket newSocket(final String sock) throws ServerAlreadyBootingException {
ServerSocket socket = null;
String name = socketName(sock);
try {
if (!isWindows) Files.deleteIfExists(Paths.get(sock));
socket =
isWindows
? new Win32NamedPipeServerSocket(name, false, Win32SecurityLevel.OWNER_DACL)
: new UnixDomainServerSocket(name);
return socket;
} catch (final IOException e) {
throw new ServerAlreadyBootingException();
}
}
I checked the isWindows method and it returns false. So the new UnixDomainServerSocket(name) part is running. And somehow it can't create a unix domain server socket. That's all I found out. Is there a way to fix this? Or is this a bug?
After moving my project files to a directory within wsl2, problem is solved. My project files were in a Windows directory before.

Realm doesn’t work with xUnite and .net core

I’m having issues running realm with xUnite and Net core. Here is a very simple test that I want to run
public class UnitTest1
{
[Scenario]
public void Test1()
{
var realm = Realm.GetInstance(new InMemoryConfiguration("Test123"));
realm.Write(() =>
{
realm.Add(new Product());
});
var test = realm.All<Product>().First();
realm.Write(() => realm.RemoveAll());
}
}
I get different exceptions on different machines (Windows & Mac) on line where I try to create a Realm instace with InMemoryConfiguration.
On Mac I get the following exception
libc++abi.dylib: terminating with uncaught exception of type realm::IncorrectThreadException: Realm accessed from incorrect thread.
On Windows I get the following exception when running
ERROR Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host. at
System.Net.Sockets.NetworkStream.Read(Span1 destination) at
System.Net.Sockets.NetworkStream.ReadByte() at
System.IO.BinaryReader.ReadByte() at
System.IO.BinaryReader.Read7BitEncodedInt() at
System.IO.BinaryReader.ReadString() at
Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.LengthPrefixCommunicationChannel.NotifyDataAvailable() at
Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.TcpClientExtensions.MessageLoopAsync(TcpClient client, ICommunicationChannel channel, Action1 errorHandler, CancellationToken cancellationToken) Source: System.Net.Sockets HResult: -2146232800 Inner Exception: An existing connection was forcibly closed by the remote host HResult: -2147467259
I’m using Realm 3.3.0 and xUnit 2.4.1
I’ve tried downgrading to Realm 2.2.0, and it didn’t work either.
The solution to this problem was found in this Github post
The piece of code from that helped me to solve the issue
Realm GetInstanceWithoutCapturingContext(RealmConfiguration config)
{
var context = SynchronizationContext.Current;
SynchronizationContext.SetSynchronizationContext(null);
Realm realm = null;
try
{
realm = Realm.GetInstance(config);
}
finally
{
SynchronizationContext.SetSynchronizationContext(context);
}
return realm;
}
Though it took a while for me to apply this to my solution.
First and foremost, instead of just setting the context to null I am using Nito.AsyncEx.AsyncContext. Because otherwise automatic changes will not be propagated through threads, as realm needs a non-null SynchronizationContext for that feature to work. So, in my case the method looks something like this
public class MockRealmFactory : IRealmFactory
{
private readonly SynchronizationContext _synchronizationContext;
private readonly string _defaultDatabaseId;
public MockRealmFactory()
{
_synchronizationContext = new AsyncContext().SynchronizationContext;
_defaultDatabaseId = Guid.NewGuid().ToString();
}
public Realm GetRealmWithPath(string realmDbPath)
{
var context = SynchronizationContext.Current;
SynchronizationContext.SetSynchronizationContext(_synchronizationContext);
Realm realm;
try
{
realm = Realm.GetInstance(new InMemoryConfiguration(realmDbPath));
}
finally
{
SynchronizationContext.SetSynchronizationContext(context);
}
return realm;
}
}
Further, this fixed a lot of failing unit tests. But I was still receiving that same exception - Realm accessed from incorrect thread. And I had no clue why, cause everything was set correctly. Then I found that the tests that were failing were related to methods where I was using async realm api, in particular realm.WriteAsync. After some more digging I found the following lines in the realm documentation.
It is not a problem if you have set SynchronisationContext.Current but
it will cause WriteAsync to dispatch again on the thread pool, which
may create another worker thread. So, if you are using Current in your
threads, consider calling just Write instead of WriteAsync.
In my code there was no direct need of using the async API. I removed and replaced with sync Write and all the tests became green again! I guess if I find myself in a situation that I do need to use the async API because of some kind of bulk insertions, I'd either mock that specific API, or replace with my own background thread using Task.Run instead of using Realm's version.

When create_task throws exception I cannot catch it in try-catch block

I try to receive user's PushNotification Channel URI (Windows 10 platform) and for some users application generate exception This operation returned because the timeout.
To handle errors in a task chain I should add a task-based continuation at the end of the chain and handle all errors there (as explained here https://learn.microsoft.com/en-us/windows/uwp/threading-async/asynchronous-programming-in-cpp-universal-windows-platform-apps#handling-errors-in-a-task-chain).
So I did that. But after I call t.get(); system generate Platform::COMException^ exception by it not catch in try-catch block. Why?
There is the code:
{
create_task(PushNotificationChannelManager::CreatePushNotificationChannelForApplicationAsync())
.then([this](PushNotificationChannel^ pnChannel)
{
// ..
// DONE: pnChannel->Uri
// ..
}, task_continuation_context::get_current_winrt_context())
.then([](task<void> t)
{
try
{
t.get(); // <<<< After exec this line app crash!
}
catch (Platform::COMException^ e)
{
OutputDebugString(L"Exception catches!");
}
});
}
There is the full exception message:
Exception thrown at 0x00007FFD9D74A388 in GameName.exe: Microsoft C++
exception: Platform::COMException ^ at memory location 0x000000249A9FEB60.
HRESULT:0x800705B4 This operation returned because the timeout period expired.
WinRT information: This operation returned because the timeout
And Visual Studio throws me to the file c:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\include\exception to block:
[[noreturn]] void _RethrowException() const
{
__ExceptionPtrRethrow(this); // <<<< here everything stoped!
}
UPDATED:
Enviroment:
Visual Studio 2017 (15.7.3)
Project based on cocos2d-x (3.16)
Project Targe Platform Version = 10.0.1493.0
Project Platform Toolset = Visual Studio 2015 (v140)
You can clone cocos2dx project and in MainScene paste code I showed before in onEnter method (or anywhere).
I got a situation when I had crash 100% for me
Uninstall app if it was built before;
Disconnect from the internet;
Build app & launch;
The app will try to detect Channel URI & will crash (but with crash message = WinRT information: The network is not present or not started).
I understand that throwing that exception is normal. But I still cannot understand why when I call t.get() it not catch exception Platform::COMException^

SignalR self host connection issue

I recently created a proof of concept console application using SignalR (self host). It worked a treat for our use. The client connected fine and I was able to send updates from the server to the client. Lovely!
I've now transferred the code from the Console application to a winforms application for a prettier UI. Now that same client won't connect to the server yet it will still connect to the old Console version.
Winforms code:
string url = "http://localhost:8080";
using (WebApp.Start(url))
{
// Let the app know the server is up
}
Console code:
string url = "http://localhost:8080";
using (WebApp.Start(url))
{
Console.WriteLine("Server running on {0}", url);
Console.ReadLine();
}
Client connection code:
if (!connected)
{
int i = 0;
// Try 3 times
while (i <= 2)
{
try
{
string server = Properties.Settings.Default.Server + ":" + Properties.Settings.Default.PortNumber.ToString();
connection = new HubConnection(server);
connection.StateChanged += connection_StateChanged;
hub = connection.CreateHubProxy("MyHub");
connection.Start().Wait();
hub.On<string>("addMessage", param => { UpdateAlarmStatus(param); });
return true;
}
catch (Exception)
{
i++;
}
}
return false;
}
else
{
return true;
}
The error the client is reporting is:
Exception:Thrown: "No connection could be made because the target machine actively refused it" (System.Net.Sockets.SocketException)
A System.Net.Sockets.SocketException was thrown: "No connection could be made because the target machine actively refused it"
Time: 25/01/2015 15:09:23
Thread:Worker Thread[8232]
Why would the target machine (localhost) refuse itself which the Console version doesn't? I've been looking at the code over and over and I cannot see where I'm going wrong. Can anyone point me in the right direction please?
Thank you for reading.
Paul.
I suspect this is an issue with the configuration of your machine/infrastructure rather than the code itself, which looks fine at first glance.
Have you checked the console debug output in Visual Studio? I recently encountered an issue with similar symptoms and that was what gave me the initial clue to keep investigating. In my particular case, an exception was written to the console debug output that didn't make it to the client.
SignalR will normally negotiate with the server automatically to determine the best transport method to use. In a .NET client, the available options are LongPollingTransport, ServerSentEventsTransport and WebSocketTransport. So for some reason, your console app can use at least one of those methods, whereas your WinForms client cannot.
You can perhaps enable tracing to give you more information to work with. To do this, enter the below before you create the hub proxy:
hubConnection.TraceLevel = TraceLevels.All;
hubConnection.TraceWriter = Console.Out;
ASP.NET doco on SignalR tracing

Unhandled exception at 0x ... in w3wp.exe: 0x ... : A heap has been corrupted

I'm building a project in Visual Studio 2012. When I press F5 to run the app, it works just fine, however when I load it up in IIS7 on my Windows Pro box, the first time I make a call to a specific code base, I get the following error.
The thread 'Win32 Thread' (0x4d8) has exited with code 0 (0x0).
Unhandled exception at 0x7797e6c3 in w3wp.exe: 0xC0000374: A heap has been corrupted.
First-chance exception at 0x778e32a0 in w3wp.exe: 0xC0000005: Access violation reading location 0x2039a9f2.
Unhandled exception at 0x778e32a0 in w3wp.exe: 0xC0000005: Access violation reading location 0x2039a9f2.
Now I've attached the w3wp.exe to the VS2012 debugger, but to be honest, I'm not sure how to debug this type of crash.
For reference, the code base that's being called in a WebAPI controller that makes a call to the ActiveHome SDK to control some automation bits.
// GET api/<controller>/5
public StatusModel Post(CommandModel command)
{
var activeHome = new ActiveHomeClass();
// execute command
var info = activeHome.SendAction(command.SendAction, String.Format("{0} {1}", command.Device, command.Command));
// return results
var status = new StatusModel { Device = command.Device, Status = info };
activeHome = null;
return status;
}
Note: I am compiling everything to use x86

Resources