Files
o3de/Gems/HttpRequestor/Code/Source/HttpRequestManager.cpp
T
Chris Burel b53bf52e0d Perform global deinitialization when exiting the game launcher (#4131)
* Fix code that deregisters the Atom Scene subsystem from the AzFramework Scene

The AzFramework Scene subsystem API is a generic container based on the
type of argument that is passed to it. It maintains a vector of typeids,
and only one object of any type is stored at a time. The Bootstrap system
component registers the Atom scene as a `ScenePtr` (aka
`AZStd::shared_ptr<RPI:Scene>`) with the AzFramework Scene's generic
subsystem. However, the component was previously deregistering the type by
value, `RPI::Scene`. Since no subsystem for the type `RPI::Scene` was set,
unsetting this type did nothing. The result was that the `RPI::Scene`
object would still be around by the time that all the Atom
`InstanceDatabse`s were being destroyed, resulting in a large number of
errors reported about leaked instances during global shutdown.

This fixes the above issue by passing the `m_defaultScene` as a parameter
to `AzFramework::Scene::UnsetSubsystem`, the same value that is passed to
`SetSubsystem`. This is better, because instead of providing explicit
template arguments (which were specifying the incorrect type), this now
allows the compiler to deduce the correct type, and the syntax is symmetric
with the call to `SetSubsystem`.

Signed-off-by: Chris Burel <burelc@amazon.com>

* Correctly release the AWS API from the `HttpRequestManager` module

This code was incorrectly assuming that
`AWSNativeSDKInit::InitializationManager::Shutdown()` would be called
automatically by the `InitializationManager` itself. However, all that
`InitAwsApi()` does is create an `AZ::EnvironmentVariable`, which is a
ref-counted type, and stores it in a global static. That global static is
defined in a static library (namely `AWSNativeSDKInit`), which is linked
in to the `HttpRequestManager` dynamic lib. Because it is a global static,
it has to be explicitly cleared with the call to `Shutdown()`. Otherwise
the destructor of the EnvironmentVariable doesn't happen until global
destruction, by which time the allocator that is supplied to the AWS SDK
has already been destroyed, and the shutdown of the AWS SDK attempts to use
the already-destroyed allocator.

Signed-off-by: Chris Burel <burelc@amazon.com>

* Avoid blocking the remote console server thread if there are no connections

The Remote console server runs in a separate thread. Previously, it would
directly call `AzSock::Accept()` and block the server thread until some
client connected to it. However, if no client connected, the thread would
continue to be blocked, even if the game launcher tried to exit.

This adds a check to see if there's a client on the socket before calling
`Accept()`, to avoid the deadlock on launcher exit.

Signed-off-by: Chris Burel <burelc@amazon.com>

* Fix a log message to print one message per line

Signed-off-by: Chris Burel <burelc@amazon.com>

* Allow pumping the event loop to close the launcher window

Events from the OS are handled in the game's main loop. The general loop
looks like this:

 * Read events from the OS
 * Tick the game application

One of the events that can come from the OS is that the window hosting the
game is closed. When this event happens, many resources provided by the
renderer are freed, and the game application's `shouldExit` bit is set.
However, when the game's `Tick()` is called, there is lots of code that
assumes the renderer is still there. To avoid crashing in the `Tick()`
call, check if the game should exit after pumping the system events.

Signed-off-by: Chris Burel <burelc@amazon.com>

* Unload the level when exiting the launcher

This ensures that any resources held onto by the level are freed before the
launcher exits.

Signed-off-by: Chris Burel <burelc@amazon.com>

* Add an explicit bus `Disconnect()` call to `AZCoreLogSink`

This is necessary because this bus has virtual functions and can be called
from multiple threads.

Signed-off-by: Chris Burel <burelc@amazon.com>

* Allow normal cleanup to take place when exiting the game launcher

Previously, global cleanup was side-stepped by calling `TerminateProcess`
or `exit`, when quitting the game launcher. This is in contrast to the call
to `_exit` on Linux and Mac when exiting the Editor. That leading `_` makes
a big difference: the former runs object destruction, the latter does not.
Instead of making the launcher exit with `_exit` on Linux, instead, remove
that call and actually run all the atexit code.

This does not modify the Editor's behavior however. It still uses `_exit`
and `TerminateProcess`.

Signed-off-by: Chris Burel <burelc@amazon.com>
2021-09-15 11:48:08 -05:00

197 lines
7.1 KiB
C++

/*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#include <AzFramework/AzFramework_Traits_Platform.h>
#include <AzCore/PlatformDef.h>
// The AWS Native SDK AWSAllocator triggers a warning due to accessing members of std::allocator directly.
// AWSAllocator.h(70): warning C4996: 'std::allocator<T>::pointer': warning STL4010: Various members of std::allocator are deprecated in C++17.
// Use std::allocator_traits instead of accessing these members directly.
// You can define _SILENCE_CXX17_OLD_ALLOCATOR_MEMBERS_DEPRECATION_WARNING or _SILENCE_ALL_CXX17_DEPRECATION_WARNINGS to acknowledge that you have received this warning.
AZ_PUSH_DISABLE_WARNING(4251 4996, "-Wunknown-warning-option")
#include <aws/core/http/HttpClient.h>
#include <aws/core/http/HttpClientFactory.h>
#include <aws/core/http/HttpRequest.h>
#include <aws/core/http/HttpResponse.h>
#include <aws/core/client/ClientConfiguration.h>
AZ_POP_DISABLE_WARNING
#include <AWSNativeSDKInit/AWSNativeSDKInit.h>
#include <AzCore/std/string/conversions.h>
#include "HttpRequestManager.h"
namespace HttpRequestor
{
const char* Manager::s_loggingName = "GemHttpRequestManager";
Manager::Manager()
{
AZStd::thread_desc desc;
desc.m_name = s_loggingName;
desc.m_cpuId = AFFINITY_MASK_USERTHREADS;
m_runThread = true;
AWSNativeSDKInit::InitializationManager::InitAwsApi();
auto function = AZStd::bind(&Manager::ThreadFunction, this);
m_thread = AZStd::thread(function, &desc);
}
Manager::~Manager()
{
AWSNativeSDKInit::InitializationManager::Shutdown();
m_runThread = false;
m_requestConditionVar.notify_all();
if (m_thread.joinable())
{
m_thread.join();
}
}
void Manager::AddRequest(Parameters && httpRequestParameters)
{
{
AZStd::lock_guard<AZStd::mutex> lock(m_requestMutex);
m_requestsToHandle.push(AZStd::move(httpRequestParameters));
}
m_requestConditionVar.notify_all();
}
void Manager::AddTextRequest(TextParameters && httpTextRequestParameters)
{
{
AZStd::lock_guard<AZStd::mutex> lock(m_requestMutex);
m_textRequestsToHandle.push(AZStd::move(httpTextRequestParameters));
}
m_requestConditionVar.notify_all();
}
void Manager::ThreadFunction()
{
// Run the thread as long as directed
while (m_runThread)
{
HandleRequestBatch();
}
}
void Manager::HandleRequestBatch()
{
// Lock mutex and wait for work to be signalled via the condition variable
AZStd::unique_lock<AZStd::mutex> lock(m_requestMutex);
m_requestConditionVar.wait(lock, [&] { return !m_runThread || !m_requestsToHandle.empty() || !m_textRequestsToHandle.empty(); });
// Swap queues
AZStd::queue<Parameters> requestsToHandle;
requestsToHandle.swap(m_requestsToHandle);
AZStd::queue<TextParameters> textRequestsToHandle;
textRequestsToHandle.swap(m_textRequestsToHandle);
// Release lock
lock.unlock();
// Handle requests
while (!requestsToHandle.empty())
{
HandleRequest(requestsToHandle.front());
requestsToHandle.pop();
}
while (!textRequestsToHandle.empty())
{
HandleTextRequest(textRequestsToHandle.front());
textRequestsToHandle.pop();
}
}
void Manager::HandleRequest(const Parameters& httpRequestParameters)
{
Aws::Client::ClientConfiguration config;
config.enableTcpKeepAlive = AZ_TRAIT_AZFRAMEWORK_AWS_ENABLE_TCP_KEEP_ALIVE_SUPPORTED;
std::shared_ptr<Aws::Http::HttpClient> httpClient = Aws::Http::CreateHttpClient(config);
auto httpRequest = Aws::Http::CreateHttpRequest(httpRequestParameters.GetURI(), httpRequestParameters.GetMethod(), Aws::Utils::Stream::DefaultResponseStreamFactoryMethod);
AZ_Assert(httpRequest, "HttpRequest not created!");
for (const auto & it : httpRequestParameters.GetHeaders())
{
httpRequest->SetHeaderValue(it.first.c_str(), it.second.c_str());
}
if( httpRequestParameters.GetBodyStream() != nullptr)
{
httpRequest->AddContentBody(httpRequestParameters.GetBodyStream());
httpRequest->SetContentLength(AZStd::to_string(httpRequestParameters.GetBodyStream()->str().length()).c_str());
}
auto httpResponse = httpClient->MakeRequest(httpRequest);
if (!httpResponse)
{
httpRequestParameters.GetCallback()(Aws::Utils::Json::JsonValue(), Aws::Http::HttpResponseCode::INTERNAL_SERVER_ERROR);
return;
}
if (httpResponse->GetResponseCode() != Aws::Http::HttpResponseCode::OK)
{
httpRequestParameters.GetCallback()(Aws::Utils::Json::JsonValue(), httpResponse->GetResponseCode());
return;
}
Aws::Utils::Json::JsonValue json(httpResponse->GetResponseBody());
if (json.WasParseSuccessful())
{
httpRequestParameters.GetCallback()(AZStd::move(json), httpResponse->GetResponseCode());
}
else
{
httpRequestParameters.GetCallback()(Aws::Utils::Json::JsonValue(), Aws::Http::HttpResponseCode::INTERNAL_SERVER_ERROR);
}
}
void Manager::HandleTextRequest(const TextParameters & httpRequestParameters)
{
Aws::Client::ClientConfiguration config;
config.enableTcpKeepAlive = AZ_TRAIT_AZFRAMEWORK_AWS_ENABLE_TCP_KEEP_ALIVE_SUPPORTED;
std::shared_ptr<Aws::Http::HttpClient> httpClient = Aws::Http::CreateHttpClient(config);
auto httpRequest = Aws::Http::CreateHttpRequest(httpRequestParameters.GetURI(), httpRequestParameters.GetMethod(), Aws::Utils::Stream::DefaultResponseStreamFactoryMethod);
for (const auto & it : httpRequestParameters.GetHeaders())
{
httpRequest->SetHeaderValue(it.first.c_str(), it.second.c_str());
}
if (httpRequestParameters.GetBodyStream() != nullptr)
{
httpRequest->AddContentBody(httpRequestParameters.GetBodyStream());
}
auto httpResponse = httpClient->MakeRequest(httpRequest);
if (!httpResponse)
{
httpRequestParameters.GetCallback()(AZStd::string(), Aws::Http::HttpResponseCode::INTERNAL_SERVER_ERROR);
return;
}
if (httpResponse->GetResponseCode() != Aws::Http::HttpResponseCode::OK)
{
httpRequestParameters.GetCallback()(AZStd::string(), httpResponse->GetResponseCode());
return;
}
// load up the raw output into a string
// TODO(aaj): it feels like there should be some limit maybe 1 MB?
std::istreambuf_iterator<char> eos;
AZStd::string data(std::istreambuf_iterator<char>(httpResponse->GetResponseBody()), eos);
httpRequestParameters.GetCallback()(AZStd::move(data), httpResponse->GetResponseCode());
}
}