diff --git a/.github/workflows/test-embedding.yml b/.github/workflows/test-embedding.yml index 2a0795866..9df6f47a5 100644 --- a/.github/workflows/test-embedding.yml +++ b/.github/workflows/test-embedding.yml @@ -94,6 +94,24 @@ jobs: cmake --build build-provided-consumer --parallel 4 ctest --test-dir build-provided-consumer --output-on-failure + linux-lifetime-sanitizers: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4.4.0 + - name: Install system dependencies + run: sudo apt-get update && sudo apt-get install -y libcurl4-openssl-dev libsqlite3-dev ninja-build zlib1g-dev + - name: Configure ASan and LSan embedding regressions + run: > + cmake -G Ninja -S tests/embedding -B build-lifetimes + -DCMAKE_BUILD_TYPE=RelWithDebInfo + -DMATSDK_EMBEDDING_ADDRESS_SANITIZER=ON + -DMATSDK_SQLITE_PROVIDER=SYSTEM + -DMATSDK_ZLIB_PROVIDER=SYSTEM + - name: Build and run + run: | + cmake --build build-lifetimes --target embedding_test --parallel 4 + ctest --test-dir build-lifetimes --output-on-failure + windows: runs-on: windows-2022 steps: diff --git a/.github/workflows/test-win-latest.yml b/.github/workflows/test-win-latest.yml index c6f19f8aa..298bb4672 100644 --- a/.github/workflows/test-win-latest.yml +++ b/.github/workflows/test-win-latest.yml @@ -56,6 +56,20 @@ jobs: with: vs-version: '[17,)' + - name: Test bundled zlib allocation bounds (Win32) + if: matrix.arch == 'Win32' && matrix.build == 'Release' && matrix.transport == 'WinHTTP' + shell: cmd + run: | + set "VSPATH=" + for /f "usebackq tokens=*" %%i in (`"%ProgramFiles(x86)%\Microsoft Visual Studio\Installer\vswhere.exe" -latest -products * -requires Microsoft.VisualStudio.Component.VC.Tools.x86.x64 -property installationPath`) do set "VSPATH=%%i" + if not defined VSPATH exit /b 1 + set "PATH=%ProgramFiles(x86)%\Microsoft Visual Studio\Installer;%PATH%" + call "%VSPATH%\VC\Auxiliary\Build\vcvars32.bat" >nul + if errorlevel 1 exit /b 1 + cl /nologo /W4 /WX /TC /DZLIB_TEST_REQUIRE_32_BIT tests\zlib-allocation-test.c /Fo"%RUNNER_TEMP%\zlib-allocation-test.obj" /Fe"%RUNNER_TEMP%\zlib-allocation-test.exe" + if errorlevel 1 exit /b 1 + "%RUNNER_TEMP%\zlib-allocation-test.exe" + - name: Test ${{ matrix.transport }} ${{ matrix.arch }} ${{ matrix.build }} shell: cmd run: build-tests.cmd ${{ matrix.arch }} ${{ matrix.build }} "" ${{ matrix.transport }} diff --git a/CMakeLists.txt b/CMakeLists.txt index f56eb8f7f..105ceb21b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -228,7 +228,7 @@ if(TARGET SQLite::SQLite3 AND NOT TARGET SQLite3::SQLite3) matsdk_add_interface_dependency(SQLite3::SQLite3 SQLite::SQLite3) endif() if(MATSDK_SQLITE_PROVIDER_RESOLVED STREQUAL "SYSTEM" AND NOT TARGET SQLite3::SQLite3) - if(APPLE AND NOT MATSDK_USING_VCPKG) + if(APPLE) matsdk_add_apple_system_library(SQLite3::SQLite3 sqlite3) set(MATSDK_SQLITE_DEPENDENCY_KIND APPLE_SYSTEM) else() @@ -253,7 +253,7 @@ if(MATSDK_SQLITE_PROVIDER_RESOLVED STREQUAL "SYSTEM" AND NOT TARGET SQLite3::SQL endif() if(MATSDK_ZLIB_PROVIDER_RESOLVED STREQUAL "SYSTEM" AND NOT TARGET ZLIB::ZLIB) - if(APPLE AND NOT MATSDK_USING_VCPKG) + if(APPLE) matsdk_add_apple_system_library(ZLIB::ZLIB z) set(MATSDK_ZLIB_DEPENDENCY_KIND APPLE_SYSTEM) else() diff --git a/cmake/MatsdkOptions.cmake b/cmake/MatsdkOptions.cmake index ac8a38c7e..41fd4812b 100644 --- a/cmake/MatsdkOptions.cmake +++ b/cmake/MatsdkOptions.cmake @@ -51,6 +51,11 @@ option(MATSDK_BUILD_AZMON "Build Azure Monitor / Application Insights support" ON) option(MATSDK_BUILD_APPLE_HTTP "Build the Apple-native HTTP client" "${APPLE}") +set(MATSDK_APPLE_HTTP_DELEGATE_CLASS "MATStreamingSessionDelegate" CACHE STRING + "Private Objective-C class name for the Apple HTTP session delegate") +if(NOT MATSDK_APPLE_HTTP_DELEGATE_CLASS MATCHES "^[A-Za-z_][A-Za-z0-9_]*$") + message(FATAL_ERROR "MATSDK_APPLE_HTTP_DELEGATE_CLASS must be a C identifier.") +endif() option(MATSDK_USE_WININET "Use WinInet instead of WinHTTP as the Win32 desktop HTTP client" OFF) option(MATSDK_DISABLE_LOGGING diff --git a/docs/embedding-with-cmake.md b/docs/embedding-with-cmake.md index 692d91579..7bcd58f0a 100644 --- a/docs/embedding-with-cmake.md +++ b/docs/embedding-with-cmake.md @@ -61,7 +61,8 @@ Recommended packaged-library policy: | Android | `MINIMAL`, or `NONE` with Room | `VENDORED` | Java/JNI by default | Apple's SQLite and zlib entries are system libraries: consumers link them but -do not ship private copies. A Linux host such as Foundry Local that already +do not ship private copies, including when a vcpkg toolchain is active. Existing +caller-provided canonical targets still take precedence. A Linux host such as Foundry Local that already standardizes on libcurl/OpenSSL should provide `CURL::libcurl` and select `MATSDK_CURL_PROVIDER=SYSTEM`; other self-contained Linux consumers can use the SDK's pinned curl/mbedTLS build. @@ -71,6 +72,19 @@ consumer must set `skipSqliteInitAndShutdown` to `"true"` and leave SQLite's process-wide lifetime to the host. This is the required configuration for coexisting Apple libraries that all link the system `libsqlite3`. +When independently embedded SDK copies coexist in an Apple process, choose a +different private HTTP delegate class name for each copy before adding the SDK: + +```cmake +set(MATSDK_APPLE_HTTP_DELEGATE_CLASS MyProductMATStreamingSessionDelegate + CACHE STRING "" FORCE) +``` + +The default remains `MATStreamingSessionDelegate`. Objective-C class names are +process-global even when C++ symbols are hidden. This setting affects only the +Apple HTTP implementation and does not propagate to consumers or rename public +Objective-C wrapper classes. + ## Non-vcpkg dependency selection When the CPP11 PAL uses the curl HTTP transport outside vcpkg, the SDK normally diff --git a/lib/CMakeLists.txt b/lib/CMakeLists.txt index d44de8ab6..61a5ff272 100644 --- a/lib/CMakeLists.txt +++ b/lib/CMakeLists.txt @@ -376,6 +376,11 @@ else() message(STATUS "Building static SDK library") add_library(mat STATIC ${SRCS}) endif() +if(APPLE AND PAL_IMPLEMENTATION STREQUAL "CPP11" AND (MATSDK_BUILD_APPLE_HTTP OR MATSDK_PLATFORM_IOS)) + # Objective-C class names are process-global, even with hidden symbol visibility. + target_compile_definitions(mat PRIVATE + "MATStreamingSessionDelegate=${MATSDK_APPLE_HTTP_DELEGATE_CLASS}") +endif() target_link_libraries(mat PRIVATE $ $) diff --git a/lib/api/AuthTokensController.cpp b/lib/api/AuthTokensController.cpp index 4a7778aaa..93c0ba806 100644 --- a/lib/api/AuthTokensController.cpp +++ b/lib/api/AuthTokensController.cpp @@ -6,6 +6,7 @@ #include "AuthTokensController.hpp" #include "ILogManager.hpp" #include "utils/Utils.hpp" +#include namespace MAT_NS_BEGIN { @@ -24,8 +25,11 @@ namespace MAT_NS_BEGIN { std::mutex& AuthTokensController::GetMutex() { - static std::mutex mutex; - return mutex; + // Like GetPAL(), this lock must survive late upload workers. + using AuthMutex = std::mutex; + alignas(AuthMutex) static unsigned char storage[sizeof(AuthMutex)]; + static AuthMutex* mutex = ::new (storage) AuthMutex; + return *mutex; } status_t AuthTokensController::SetTicketToken(TicketType type, char const* tokenValue) diff --git a/lib/api/LogManagerFactory.cpp b/lib/api/LogManagerFactory.cpp index f6e68a5c3..0254a6093 100644 --- a/lib/api/LogManagerFactory.cpp +++ b/lib/api/LogManagerFactory.cpp @@ -20,9 +20,7 @@ namespace MAT_NS_BEGIN { - // This mutex has to be recursive because we allow both - // Destroy and destrutor to lock it. destructor could be - // called directly, and Destroy calls destructor. + // Leasing may create and register a new manager under the same lock. std::recursive_mutex ILogManagerInternal::managers_lock; std::set ILogManagerInternal::managers; @@ -31,10 +29,12 @@ namespace MAT_NS_BEGIN /// /// The configuration. /// ILogManager instance - ILogManager* LogManagerFactory::Create(ILogConfiguration& configuration) + ILogManager* LogManagerFactory::Create(ILogConfiguration& configuration, + const std::shared_ptr& owner) { LOCKGUARD(ILogManagerInternal::managers_lock); auto logManager = std::make_unique(configuration); + logManager->m_logConfigurationOwner = owner; ILogManagerInternal::managers.emplace(logManager.get()); return logManager.release(); } @@ -46,20 +46,50 @@ namespace MAT_NS_BEGIN /// status_t LogManagerFactory::Destroy(ILogManager* instance) { - if (instance == nullptr) + RegistryLock lock(ILogManagerInternal::managers_lock); + return tryDestroy(instance, lock, nullptr, {}) ? STATUS_SUCCESS : STATUS_EFAIL; + } + + bool LogManagerFactory::tryDestroy(ILogManager* instance, RegistryLock& lock, + Registry* registry, std::string key) + { + if (!ILogManagerInternal::managers.count(instance)) { - return STATUS_EFAIL; + return false; } - LOCKGUARD(ILogManagerInternal::managers_lock); - auto it = ILogManagerInternal::managers.find(instance); - if (it != std::end(ILogManagerInternal::managers)) + auto manager = static_cast(instance); + if (!manager->BeginTeardown()) + { + return false; + } + + // Keep the lease reserved, but allow callbacks to enter the factory. + lock.unlock(); + bool complete = false; + MATSDK_TRY + { + complete = manager->CompleteTeardown(); + } + MATSDK_CATCH(...) + { + complete = false; + } + lock.lock(); + if (!complete) + { + manager->EndTeardown(); + return false; + } + + if (registry) { - ILogManagerInternal::managers.erase(it); - delete instance; - return STATUS_SUCCESS; + registry->erase(key); } - return STATUS_EFAIL; + ILogManagerInternal::managers.erase(instance); + lock.unlock(); + delete instance; + return true; } // Move guests from ROOT to the new host home @@ -110,22 +140,47 @@ namespace MAT_NS_BEGIN } } - ILogManager* LogManagerFactory::lease(ILogConfiguration& c) + ILogManager* LogManagerFactory::GetOwned(const std::shared_ptr& configuration, status_t& status) + { + auto manager = instance().lease(*configuration, configuration); + status = manager ? STATUS_SUCCESS : STATUS_EFAIL; + return manager; + } + + bool LogManagerFactory::CanAcquireLease(ILogManager* manager) + { + LOCKGUARD(ILogManagerInternal::managers_lock); + return ILogManagerInternal::managers.count(manager) && + static_cast(manager)->CanAcquireLease(); + } + + ILogManager* LogManagerFactory::lease(ILogConfiguration& c, const std::shared_ptr& owner) { std::string name; std::string host; parseConfig(c, name, host); + RegistryLock lock(ILogManagerInternal::managers_lock); + const auto canLease = [&](const Pool& pool) { + // Each distinct C API handle must have its own lease. + return static_cast(pool.instance)->CanAcquireLease() && + (!owner || !pool.names.count(name)); + }; // Exclusive mode if (host.empty()) { // Exclusive hosts are being kept in their own sandbox: high chairs near the bar. - if (!exclusive.count(name)) + auto pool = exclusive.find(name); + if (pool == exclusive.end()) { - exclusive[name] = {{name}, Create(c)}; + pool = exclusive.emplace(name, Pool{{name}, Create(c, owner)}).first; + } + else if (!canLease(pool->second)) + { + return nullptr; } c[CFG_BOOL_HOST_MODE] = true; - return exclusive[name].instance; + return pool->second.instance; } // Shared mode @@ -133,9 +188,14 @@ namespace MAT_NS_BEGIN { // There are some items already. This guest doesn't care // where to go, so it goes to the first host's pool. - shared[shared.begin()->first].names.insert(name); + auto& pool = shared.begin()->second; + if (!canLease(pool)) + { + return nullptr; + } + pool.names.insert(name); c[CFG_BOOL_HOST_MODE] = false; - return shared[shared.begin()->first].instance; + return pool.instance; } if (!shared.count(host)) @@ -145,16 +205,23 @@ namespace MAT_NS_BEGIN // irrespective of whether it's a host or guest if (shared.count(ANYHOST)) { + if (!canLease(shared.find(ANYHOST)->second)) + { + return nullptr; + } rehome(name, host); } else { - shared[host] = {{name}, Create(c)}; + shared[host] = {{name}, Create(c, owner)}; } } - else if (!shared[host].names.count(name)) + else { - // Host already exists, so simply add the new item to it + if (!canLease(shared[host])) + { + return nullptr; + } shared[host].names.insert(name); } @@ -172,19 +239,17 @@ namespace MAT_NS_BEGIN bool LogManagerFactory::release(const std::string& name) { - for (auto& kv : shared) + RegistryLock lock(ILogManagerInternal::managers_lock); + return releaseShared(name, lock); + } + + bool LogManagerFactory::releaseShared(const std::string& name, RegistryLock& lock) + { + for (auto pool = shared.begin(); pool != shared.end(); ++pool) { - const std::string& host = kv.first; - if (kv.second.names.count(name)) + if (pool->second.names.count(name)) { - kv.second.names.erase(name); - if (kv.second.names.empty()) - { - // Last owner is gone, destroy - Destroy(shared[host].instance); - shared.erase(host); - } - return true; + return releaseFrom(shared, pool, name, lock); } } return false; @@ -192,35 +257,30 @@ namespace MAT_NS_BEGIN bool LogManagerFactory::release(const std::string& name, const std::string& host) { + RegistryLock lock(ILogManagerInternal::managers_lock); if (host.empty()) { - if (exclusive.count(name)) - { - auto val = exclusive[name]; - // destroy LM - Destroy(val.instance); - exclusive.erase(name); - return true; - } - return false; + auto pool = exclusive.find(name); + return pool != exclusive.end() && releaseFrom(exclusive, pool, name, lock); } - if ((shared.find(host) != std::end(shared)) && - (shared[host].names.count(name))) + auto pool = shared.find(host); + if (pool != shared.end() && pool->second.names.count(name)) { - shared[host].names.erase(name); - if (shared[host].names.empty()) - { - // Last owner is gone, destroy LM - Destroy(shared[host].instance); - shared.erase(host); - } - return true; + return releaseFrom(shared, pool, name, lock); } - // repeat the same action as above, but this time - // searching for rehomed guests in all hosts - return release(name); + return releaseShared(name, lock); + } + + bool LogManagerFactory::releaseFrom(Registry& registry, Registry::iterator pool, + const std::string& name, RegistryLock& lock) + { + if (pool->second.names.size() == 1) + { + return tryDestroy(pool->second.instance, lock, ®istry, pool->first); + } + return pool->second.names.erase(name) != 0; } void LogManagerFactory::dump() diff --git a/lib/api/LogManagerFactory.hpp b/lib/api/LogManagerFactory.hpp index 63adfb646..58510ea6e 100644 --- a/lib/api/LogManagerFactory.hpp +++ b/lib/api/LogManagerFactory.hpp @@ -12,6 +12,8 @@ #include "NullObjects.hpp" #include +#include +#include #include #include #include @@ -43,6 +45,16 @@ namespace MAT_NS_BEGIN { /// Registry exclusive; + using RegistryLock = std::unique_lock; + + static bool tryDestroy(ILogManager* instance, RegistryLock& lock, + Registry* registry, std::string key); + + bool releaseFrom(Registry& registry, Registry::iterator pool, + const std::string& name, RegistryLock& lock); + + bool releaseShared(const std::string& name, RegistryLock& lock); + protected: LogManagerFactory(); @@ -51,7 +63,8 @@ namespace MAT_NS_BEGIN { const ILogManager* find(const std::string& name); - ILogManager* lease(ILogConfiguration& configuration); + ILogManager* lease(ILogConfiguration& configuration, + const std::shared_ptr& owner = {}); bool release(const std::string& name, const std::string& host); @@ -88,7 +101,8 @@ namespace MAT_NS_BEGIN { /// /// Configuration settings to apply to the telemetry logging system. /// An ILogManager telemetry logging system instance created with the specified configuration and HTTP Client. - static ILogManager* Create(ILogConfiguration& configuration); + static ILogManager* Create(ILogConfiguration& configuration, + const std::shared_ptr& owner = {}); /// /// Destroys a ILogManager instance @@ -125,6 +139,10 @@ namespace MAT_NS_BEGIN { return result; } + static ILogManager* GetOwned(const std::shared_ptr& configuration, status_t& status); + + static bool CanAcquireLease(ILogManager* manager); + static status_t Release(const char* module) { return (instance().release(module)) ? diff --git a/lib/api/LogManagerImpl.cpp b/lib/api/LogManagerImpl.cpp index dd943fd6c..2ab59381b 100644 --- a/lib/api/LogManagerImpl.cpp +++ b/lib/api/LogManagerImpl.cpp @@ -381,7 +381,7 @@ namespace MAT_NS_BEGIN { MATSDK_TRY { - FlushAndTeardown(); + FlushAndTeardownWithStatus(); } #if HAVE_EXCEPTIONS MATSDK_CATCH(const std::exception& e) @@ -412,6 +412,30 @@ namespace MAT_NS_BEGIN } void LogManagerImpl::FlushAndTeardown() + { + if (!FlushAndTeardownWithStatus()) + { +#if HAVE_EXCEPTIONS + throw std::runtime_error("Log manager teardown did not complete"); +#endif + } + } + + bool LogManagerImpl::FlushAndTeardownWithStatus() + { + if (!BeginTeardown()) + { + return false; + } + struct ResetOnExit + { + LogManagerImpl& manager; + ~ResetOnExit() { manager.EndTeardown(); } + } reset{*this}; + return CompleteTeardown(); + } + + bool LogManagerImpl::CompleteTeardown() { PauseActivity(); WaitPause(); @@ -449,7 +473,41 @@ namespace MAT_NS_BEGIN if (m_isSystemStarted && m_system) { - m_system->stop(); +#if HAVE_EXCEPTIONS + if (m_systemStopFailure) + { + std::rethrow_exception(m_systemStopFailure); + } +#endif + MATSDK_TRY + { + if (m_storageShutdownPending) + { + // The telemetry system already drained and stopped its upload pipeline. + m_offlineStorage->Shutdown(); + } + else + { + m_system->stop(); + } + } +#if HAVE_EXCEPTIONS + MATSDK_CATCH(...) + { + m_storageShutdownPending = m_offlineStorage && m_offlineStorage->IsShutdownPending(); + if (!m_storageShutdownPending) + { + // The system's one-shot stop failed before storage became retryable. + m_systemStopFailure = std::current_exception(); + } + throw; + } +#endif + m_storageShutdownPending = m_offlineStorage && m_offlineStorage->IsShutdownPending(); + if (m_storageShutdownPending) + { + return false; + } LOG_TRACE("Telemetry system stopped"); } m_system = nullptr; @@ -471,6 +529,7 @@ namespace MAT_NS_BEGIN LOG_INFO("Shutdown complete in %lld ms", shutTime); } m_alive = false; + return true; } status_t LogManagerImpl::Flush() @@ -682,7 +741,7 @@ namespace MAT_NS_BEGIN { { LOCKGUARD(m_lock); - if (!m_alive) + if (!CanAcquireLease()) { return nullptr; } @@ -695,7 +754,7 @@ namespace MAT_NS_BEGIN std::string hash = normalizedTenantToken + "/" + normalizedSource; LOCKGUARD(m_lock); - if (!m_alive) + if (!CanAcquireLease()) { return nullptr; } diff --git a/lib/api/LogManagerImpl.hpp b/lib/api/LogManagerImpl.hpp index 75e062868..48a9c27ac 100644 --- a/lib/api/LogManagerImpl.hpp +++ b/lib/api/LogManagerImpl.hpp @@ -32,7 +32,9 @@ #include "IDataInspector.hpp" #include "offline/LogSessionDataProvider.hpp" +#include #include +#include #include #include @@ -131,6 +133,8 @@ namespace MAT_NS_BEGIN using LoggerMap = std::map>; + class OfflineStorageHandler; + class DeadLoggers { public: @@ -155,6 +159,7 @@ namespace MAT_NS_BEGIN virtual void Configure() final; virtual void FlushAndTeardown() final; + bool FlushAndTeardownWithStatus(); virtual status_t Flush() final; virtual status_t UploadNow() final; @@ -316,6 +321,7 @@ namespace MAT_NS_BEGIN MATSDK_LOG_DECL_COMPONENT_CLASS(); static DeadLoggers s_deadLoggers; + std::shared_ptr m_logConfigurationOwner; std::recursive_mutex m_lock; LoggerMap m_loggers; ContextFieldsProvider m_context; @@ -332,9 +338,13 @@ namespace MAT_NS_BEGIN AuthTokensController m_authTokensController; - std::unique_ptr m_offlineStorage; + std::unique_ptr m_offlineStorage; std::unique_ptr m_logSessionDataProvider; bool m_isSystemStarted{}; + bool m_storageShutdownPending{}; +#if HAVE_EXCEPTIONS + std::exception_ptr m_systemStopFailure; +#endif std::unique_ptr m_system; bool m_alive; @@ -358,6 +368,15 @@ namespace MAT_NS_BEGIN Paused }; PauseState m_pause_state = PauseState::Active; + + private: + friend class LogManagerFactory; + enum class TeardownState { Open, InProgress, Retiring }; + bool BeginTeardown() noexcept { return m_teardownState.exchange(TeardownState::InProgress) != TeardownState::InProgress; } + void EndTeardown() noexcept { m_teardownState = TeardownState::Retiring; } + bool CanAcquireLease() const noexcept { return m_teardownState == TeardownState::Open; } + bool CompleteTeardown(); + std::atomic m_teardownState{TeardownState::Open}; }; } diff --git a/lib/api/capi.cpp b/lib/api/capi.cpp index 92bef825e..3ed82dcf5 100644 --- a/lib/api/capi.cpp +++ b/lib/api/capi.cpp @@ -8,6 +8,8 @@ #if !defined (ANDROID) || defined(ENABLE_CAPI_HTTP_CLIENT) #include "http/HttpClient_CAPI.hpp" #endif +#include "LogManagerFactory.hpp" +#include "LogManagerImpl.hpp" #include "LogManagerProvider.hpp" #include "mat.h" #include "pal/TaskDispatcher_CAPI.hpp" @@ -26,7 +28,14 @@ static const char * libSemver = TELEMETRY_EVENTS_VERSION; using namespace MAT; static std::mutex mtx; -static std::map clients; +static std::map> clients; + +static std::shared_ptr find_open_client(evt_handle_t handle) +{ + LOCKGUARD(mtx); + const auto it = clients.find(handle); + return (it != clients.end() && it->second->logmanager) ? it->second : nullptr; +} /// /// Convert from C API handle to internal C API client struct. @@ -41,9 +50,7 @@ static std::map clients; /// capi_client * MAT::capi_get_client(evt_handle_t handle) { - LOCKGUARD(mtx); - const auto it = clients.find(handle); - return (it != clients.cend()) ? &(it->second) : nullptr; + return find_open_client(handle).get(); } /// @@ -51,8 +58,16 @@ capi_client * MAT::capi_get_client(evt_handle_t handle) /// static void remove_client(evt_handle_t handle) { - LOCKGUARD(mtx); - clients.erase(handle); + std::shared_ptr client; + { + LOCKGUARD(mtx); + const auto it = clients.find(handle); + if (it != clients.end()) + { + client = std::move(it->second); + clients.erase(it); + } + } } #define VERIFY_CLIENT_HANDLE(client, ctx) \ @@ -60,8 +75,8 @@ static void remove_client(evt_handle_t handle) { \ return EFAULT; /* bad address */ \ }; \ - auto client = MAT::capi_get_client(ctx->handle); \ - if ((client == nullptr) || (client->logmanager == nullptr)) \ + auto client = find_open_client(ctx->handle); \ + if (!client) \ { \ return ENOENT; \ }; @@ -86,120 +101,106 @@ static evt_status_t mat_open_core( } evt_handle_t code = static_cast(hashCode(config)); - bool isHashFound = false; - // Find the next available spare hashcode - do + bool reserved = false; + MATSDK_TRY { - const auto client = MAT::capi_get_client(code); - if (client != nullptr) + auto client = std::make_shared(); + client->ctx_data = config; + std::shared_ptr duplicate; + ILogManager* duplicateManager = nullptr; + { + LOCKGUARD(mtx); + for (;; ++code) + { + const auto existing = clients.find(code); + if (existing == clients.end()) + { + clients.emplace(code, client); + reserved = true; + break; + } + if (existing->second->ctx_data == config) + { + duplicate = existing->second; + duplicateManager = duplicate->logmanager; + break; + } + } + } + + if (duplicate) { - if (client->ctx_data == config) + // Don't hold the handle lock while the factory verifies the manager's lifetime. + if (LogManagerFactory::CanAcquireLease(duplicateManager) && find_open_client(code) == duplicate) { - // Guest instance with the same config is already open. - // Return its handle so the caller still gets a usable handle - // (rather than leaving ctx->handle uninitialized), and set - // ctx->result to match the returned status like the other paths. ctx->handle = code; ctx->result = static_cast(EALREADY); return EALREADY; } - // hash code is assigned to another client, increment and retry - // with the next empty slot - code++; - continue; - }; - isHashFound = true; - } while (!isHashFound); - - // JSON configuration must start with { - if (config[0] == '{') - { - // Create new configuration object from JSON - clients[code].config = MAT::FromJSON(config); - } - else - { - // Assume that the config string is a token, not JSON. - // That approach allows to consume the lightweght C API without JSON parser compiled in. - std::string moduleName = "CAPI-Client-"; - moduleName += std::to_string(code); - clients[code].config = - { - { CFG_STR_FACTORY_NAME, moduleName }, - { "version", "1.0.0" }, - { CFG_MAP_FACTORY_CONFIG, - { - { CFG_STR_FACTORY_HOST, "*" }, - { CFG_STR_CONTEXT_SCOPE, CONTEXT_SCOPE_NONE } - } - }, - { CFG_STR_PRIMARY_TOKEN, config } - }; - } + ctx->handle = 0; + ctx->result = static_cast(EFAULT); + return EFAULT; + } - // Remember the original config string. Needed to avoid hash code collisions - clients[code].ctx_data = config; + if (config[0] == '{') + { + client->config = MAT::FromJSON(config); + } + else + { + std::string moduleName = "CAPI-Client-" + std::to_string(code); + client->config = + { + { CFG_STR_FACTORY_NAME, moduleName }, + { "version", "1.0.0" }, + { CFG_MAP_FACTORY_CONFIG, + { + { CFG_STR_FACTORY_HOST, "*" }, + { CFG_STR_CONTEXT_SCOPE, CONTEXT_SCOPE_NONE } + } + }, + { CFG_STR_PRIMARY_TOKEN, config } + }; + } #if !defined (ANDROID) || defined(ENABLE_CAPI_HTTP_CLIENT) - // Create custom HttpClient - if (httpSendFn != nullptr && httpCancelFn != nullptr) - { -#if HAVE_EXCEPTIONS - try -#endif + if (httpSendFn != nullptr && httpCancelFn != nullptr) { auto http = std::make_shared(httpSendFn, httpCancelFn); - clients[code].http = http; - clients[code].config.AddModule(CFG_MODULE_HTTP_CLIENT, http); + client->http = http; + client->config.AddModule(CFG_MODULE_HTTP_CLIENT, http); } -#if HAVE_EXCEPTIONS - catch (...) - { - // Roll back the partially-populated client so a later open with the - // same config does not find stale half-initialized state. - remove_client(code); - ctx->result = static_cast(EFAULT); - ctx->handle = 0; - return EFAULT; - } -#endif - } -#endif - // Create custom worker thread - if (taskDispatcherQueueFn != nullptr && taskDispatcherCancelFn != nullptr && taskDispatcherJoinFn != nullptr) - { -#if HAVE_EXCEPTIONS - try #endif + if (taskDispatcherQueueFn != nullptr && taskDispatcherCancelFn != nullptr && taskDispatcherJoinFn != nullptr) { - auto taskDispatcher = std::make_shared(taskDispatcherQueueFn, taskDispatcherCancelFn, taskDispatcherJoinFn); - clients[code].taskDispatcher = taskDispatcher; - clients[code].config.AddModule(CFG_MODULE_TASK_DISPATCHER, taskDispatcher); + auto taskDispatcher = std::make_shared( + taskDispatcherQueueFn, taskDispatcherCancelFn, taskDispatcherJoinFn); + client->taskDispatcher = taskDispatcher; + client->config.AddModule(CFG_MODULE_TASK_DISPATCHER, taskDispatcher); } -#if HAVE_EXCEPTIONS - catch (...) + + // The creator can close before another client using its manager. + status_t status = STATUS_EFAIL; + auto manager = LogManagerFactory::GetOwned(std::shared_ptr(client, &client->config), status); + if (manager) { - // Roll back the partially-populated client so a later open with the - // same config does not find stale half-initialized state. - remove_client(code); - ctx->result = static_cast(EFAULT); - ctx->handle = 0; - return EFAULT; + LOCKGUARD(mtx); + client->logmanager = manager; + ctx->result = static_cast(status); + ctx->handle = code; + return ctx->result; } -#endif } - - status_t status = static_cast(EFAULT); - clients[code].logmanager = LogManagerProvider::CreateLogManager(clients[code].config, status); - - // Verify that the instance pointer is valid - if (clients[code].logmanager == nullptr) + MATSDK_CATCH(...) { - status = static_cast(EFAULT); } - ctx->result = static_cast(status); - ctx->handle = code; - return ctx->result; + if (reserved) + { + remove_client(code); + } + ctx->result = static_cast(EFAULT); + ctx->handle = 0; + return EFAULT; } static evt_status_t mat_open(evt_context_t *ctx) @@ -315,7 +316,12 @@ static evt_status_t mat_log(evt_context_t *ctx) static evt_status_t mat_close(evt_context_t *ctx) { VERIFY_CLIENT_HANDLE(client, ctx); - const auto result = static_cast(LogManagerProvider::Release(client->logmanager->GetLogConfiguration())); + const auto result = static_cast(LogManagerProvider::Release(client->config)); + if (result != STATUS_SUCCESS) + { + ctx->result = result; + return result; + } if (client->http != nullptr) { @@ -359,9 +365,16 @@ static evt_status_t mat_upload(evt_context_t *ctx) static evt_status_t mat_flushAndTeardown(evt_context_t *ctx) { VERIFY_CLIENT_HANDLE(client, ctx); - client->logmanager->FlushAndTeardown(); - ctx->result = STATUS_SUCCESS; - return STATUS_SUCCESS; + auto manager = static_cast(client->logmanager); + MATSDK_TRY + { + ctx->result = manager->FlushAndTeardownWithStatus() ? STATUS_SUCCESS : STATUS_EFAIL; + } + MATSDK_CATCH(...) + { + ctx->result = STATUS_EFAIL; + } + return ctx->result; } static evt_status_t mat_flush(evt_context_t *ctx) diff --git a/lib/decoder/PayloadDecoder.cpp b/lib/decoder/PayloadDecoder.cpp index 25a0231ce..2c67dade0 100644 --- a/lib/decoder/PayloadDecoder.cpp +++ b/lib/decoder/PayloadDecoder.cpp @@ -33,6 +33,8 @@ MAT_NS_END #else #include #include +#include +#include #include #include #include @@ -391,7 +393,9 @@ namespace clienttelemetry { /// /// /// - bool Compress(const char* source, size_t sourceLen, char** dest, size_t& destLen, bool prependSize) + // Successful custom allocations must be compatible with delete[]. + bool Compress(const char* source, size_t sourceLen, char** dest, size_t& destLen, bool prependSize, + char* (*allocate)(size_t)) { if ((!source) || (!sourceLen)) { @@ -401,38 +405,48 @@ namespace clienttelemetry { *dest = NULL; destLen = 0; - // Compressing variables - uLong compSize = compressBound((uLong)sourceLen); + const auto inputSize = static_cast(sourceLen); + if (inputSize > static_cast(std::numeric_limits::max()) || + (prependSize && inputSize > static_cast(std::numeric_limits::max()))) + { + return false; + } - // Allocate memory for the new compressed buffer - size_t reserved = ((unsigned)prependSize * sizeof(uint32_t)); - char* compBody = new char[std::max(compSize, ((uLong)sourceLen)) + reserved]; - if (compBody != NULL) + uLong compSize = compressBound(static_cast(sourceLen)); + const size_t reserved = prependSize ? sizeof(uint32_t) : 0; + const size_t maxAllocation = static_cast(std::numeric_limits::max()); + if (compSize == std::numeric_limits::max() || compSize < sourceLen || + sourceLen > maxAllocation - reserved || compSize > maxAllocation - reserved) { - if (prependSize) - { - // Remember source uncompressed size if requested - uint32_t *s = (uint32_t*)(compBody); - (*s) = (uint32_t)sourceLen; // truncate this to 32-bit, we do not support 3+ TB blobs - } - // Deflate - int res = compress2((Bytef *)(compBody + reserved), &compSize, (Bytef *)source, (uLong)sourceLen, Z_BEST_SPEED); - if (res != Z_OK) - { - TEST_LOG_ERROR("Compression failed, error=%u", res); - delete[] compBody; - compBody = NULL; - return false; - } - else - { - *dest = compBody; - destLen = compSize + reserved; - return true; - } + return false; } - // OOM - return false; + + char* compBody = allocate(std::max(static_cast(compSize), sourceLen) + reserved); + if (compBody == nullptr) + { + return false; + } + if (prependSize) + { + const uint32_t originalSize = static_cast(sourceLen); + std::memcpy(compBody, &originalSize, sizeof(originalSize)); + } + int res = compress2((Bytef *)(compBody + reserved), &compSize, (Bytef *)source, (uLong)sourceLen, Z_BEST_SPEED); + if (res != Z_OK) + { + TEST_LOG_ERROR("Compression failed, error=%u", res); + delete[] compBody; + return false; + } + *dest = compBody; + destLen = compSize + reserved; + return true; + } + + bool Compress(const char* source, size_t sourceLen, char** dest, size_t& destLen, bool prependSize) + { + return Compress(source, sourceLen, dest, destLen, prependSize, + [](size_t size) { return new (std::nothrow) char[size]; }); } /// @@ -460,13 +474,23 @@ namespace clienttelemetry { // Get uncompressed size at zero offset. if (sizeAtZeroIndex) { - uint32_t s32 = *((uint32_t*)(source)); - uint64_t s64 = (sourceLen >= sizeof(uint64_t)) ? *((uint64_t*)(source)) : 0; + if (sourceLen < sizeof(uint32_t)) + { + destLen = 0; + return false; + } + uint32_t s32 = 0; + std::memcpy(&s32, source, sizeof(s32)); // If we are reading 64-bit generated legacy DB, step 32-bit forward to // skip zero-padding in most-significant DWORD on Intel architecture - if ((s64 - s32) == 0) + if (sourceLen >= sizeof(uint64_t)) { - reserved += sizeof(uint32_t); + uint64_t s64 = 0; + std::memcpy(&s64, source, sizeof(s64)); + if (s64 == s32) + { + reserved += sizeof(uint32_t); + } } destLen = s32; } diff --git a/lib/include/public/ICdsFactory.hpp b/lib/include/public/ICdsFactory.hpp index 312c3b210..f5906969e 100644 --- a/lib/include/public/ICdsFactory.hpp +++ b/lib/include/public/ICdsFactory.hpp @@ -10,6 +10,7 @@ #include #include #include +#include #include #include diff --git a/lib/include/public/LogManagerBase.hpp b/lib/include/public/LogManagerBase.hpp index b9ffdefca..6fbdbf198 100644 --- a/lib/include/public/LogManagerBase.hpp +++ b/lib/include/public/LogManagerBase.hpp @@ -252,6 +252,10 @@ namespace MAT_NS_BEGIN status_t status = STATUS_SUCCESS; instance = LogManagerProvider::CreateLogManager(currentConfig, status); + if (!instance) + { + return nullptr; + } instance->AttachEventSource(GetDebugEventSource()); return instance->GetLogger(currentConfig[CFG_STR_PRIMARY_TOKEN]); } @@ -291,7 +295,10 @@ namespace MAT_NS_BEGIN } ILogConfiguration& currentConfig = GetLogConfiguration(); auto result = LogManagerProvider::Release(currentConfig); - instance = nullptr; + if (result == STATUS_SUCCESS) + { + instance = nullptr; + } return result; } // already gone diff --git a/lib/jni/LogManager_jni.cpp b/lib/jni/LogManager_jni.cpp index cab9d7535..245ec0e5f 100644 --- a/lib/jni/LogManager_jni.cpp +++ b/lib/jni/LogManager_jni.cpp @@ -30,6 +30,7 @@ #include "JavaDataViewerProxy.hpp" #include "JniConvertors.hpp" #include "LogManagerBase.hpp" +#include "api/LogManagerImpl.hpp" #include "WrapperLogManager.hpp" #ifdef HAVE_MAT_LOGGING #include "android/log.h" @@ -71,7 +72,14 @@ extern "C" JNIEnv* /* env */, jclass /* LogManager.class */) { - return static_cast(WrapperLogManager::FlushAndTeardown()); + MATSDK_TRY + { + return static_cast(WrapperLogManager::FlushAndTeardown()); + } + MATSDK_CATCH(...) + { + return static_cast(STATUS_EFAIL); + } } JNIEXPORT jint JNICALL @@ -1167,7 +1175,24 @@ Java_com_microsoft_applications_events_LogManagerProvider_00024LogManagerImpl_na { return; } - logManager->FlushAndTeardown(); + bool stopped = false; + MATSDK_TRY + { + stopped = static_cast(logManager)->FlushAndTeardownWithStatus(); + } + MATSDK_CATCH(...) + { + stopped = false; + } + if (!stopped) + { + if (auto errorClass = env->FindClass("java/lang/IllegalStateException")) + { + env->ThrowNew(errorClass, "Telemetry shutdown did not complete"); + env->DeleteLocalRef(errorClass); + } + return; + } // FlushAndTeardown is terminal: LogManagerImpl sets m_alive to false and GetLogger() returns // nullptr from then on, and nothing sets it back, so no further viewer callback can occur. diff --git a/lib/offline/OfflineStorageHandler.cpp b/lib/offline/OfflineStorageHandler.cpp index 60f67fb64..7c18fc593 100644 --- a/lib/offline/OfflineStorageHandler.cpp +++ b/lib/offline/OfflineStorageHandler.cpp @@ -12,6 +12,7 @@ #include "ILogManager.hpp" #include "utils/Utils.hpp" #include +#include #include #include #include @@ -32,6 +33,152 @@ namespace MAT_NS_BEGIN { MATSDK_LOG_INST_COMPONENT_CLASS(OfflineStorageHandler, "EventsSDK.StorageHandler", "Events telemetry client - OfflineStorageHandler class") + // Queued tasks retain this state even after the handler has stopped. + class OfflineStorageHandler::FlushState + { + public: + enum class Phase { Accepting, Draining, Closing, Retryable, Stopped }; + enum class ShutdownStage { Flush, MemoryShutdown, DiskShutdown, Complete }; + + struct PendingTask + { + // Keep the task alive while cancellation looks up its identity. + std::recursive_mutex mutex; + Task* task = nullptr; + }; + + explicit FlushState(OfflineStorageHandler* handler) : owner(handler) {} + + std::mutex mutex; + std::condition_variable cv; + Phase phase = Phase::Accepting; + ShutdownStage shutdownStage = ShutdownStage::Flush; + OfflineStorageHandler* owner; + size_t active = 0; + std::shared_ptr pending; + }; + + class OfflineStorageHandler::OperationGuard + { + public: + explicit OperationGuard(std::shared_ptr state, bool allowDraining = false) : + m_state(std::move(state)) + { + std::lock_guard lock(m_state->mutex); + if (m_state->phase == FlushState::Phase::Accepting || + (allowDraining && m_state->phase == FlushState::Phase::Draining)) + { + m_owner = m_state->owner; + ++m_state->active; + } + } + + OperationGuard(std::shared_ptr state, + std::shared_ptr const& pending) : + m_state(std::move(state)) + { + std::lock_guard lock(m_state->mutex); + if (m_state->pending != pending) + { + return; + } + m_state->pending.reset(); + if (m_state->phase == FlushState::Phase::Accepting) + { + m_owner = m_state->owner; + ++m_state->active; + } + } + + ~OperationGuard() noexcept + { + if (m_owner) + { + { + std::lock_guard lock(m_state->mutex); + --m_state->active; + } + m_state->cv.notify_all(); + } + } + + explicit operator bool() const noexcept { return m_owner != nullptr; } + OfflineStorageHandler* Owner() const noexcept { return m_owner; } + + OperationGuard(OperationGuard const&) = delete; + OperationGuard& operator=(OperationGuard const&) = delete; + + private: + std::shared_ptr m_state; + OfflineStorageHandler* m_owner = nullptr; + }; + + class OfflineStorageHandler::ScheduledFlushTask final : public Task + { + public: + ScheduledFlushTask(std::shared_ptr state, + std::shared_ptr pending) : + m_state(std::move(state)), + m_pending(std::move(pending)) + { + Type = Task::Call; + TargetTime = 0; + TypeName = "OfflineStorageFlushTask"; + std::lock_guard lock(m_pending->mutex); + m_pending->task = this; + } + + ~ScheduledFlushTask() noexcept override + { + { + std::lock_guard lock(m_pending->mutex); + m_pending->task = nullptr; + } + std::lock_guard lock(m_state->mutex); + if (m_state->pending == m_pending) + { + m_state->pending.reset(); + } + } + + void operator()() override + { + OperationGuard operation(m_state, m_pending); + if (operation) + { + operation.Owner()->Flush(); + } + } + + private: + std::shared_ptr m_state; + std::shared_ptr m_pending; + }; + + class OfflineStorageHandler::TeardownGuard + { + public: + explicit TeardownGuard(std::shared_ptr state) : m_state(std::move(state)) {} + + ~TeardownGuard() noexcept + { + { + std::lock_guard lock(m_state->mutex); + m_state->phase = m_completed ? FlushState::Phase::Stopped : FlushState::Phase::Retryable; + } + m_state->cv.notify_all(); + } + + void Complete() noexcept { m_completed = true; } + + TeardownGuard(TeardownGuard const&) = delete; + TeardownGuard& operator=(TeardownGuard const&) = delete; + + private: + std::shared_ptr m_state; + bool m_completed = false; + }; + OfflineStorageHandler::OfflineStorageHandler(ILogManager& logManager, IRuntimeConfig& runtimeConfig, ITaskDispatcher& taskDispatcher) : OfflineStorageHandler(logManager, runtimeConfig, taskDispatcher, OfflineStorageFactory::GetDefaultProvider()) { @@ -45,7 +192,7 @@ namespace MAT_NS_BEGIN { m_storageProvider(std::move(storageProvider)), m_killSwitchManager(), m_clockSkewManager(), - m_flushPending(false), + m_flushState(std::make_shared(this)), m_offlineStorageMemory(nullptr), m_offlineStorageDisk(nullptr), m_readFromMemory(false), @@ -136,33 +283,74 @@ namespace MAT_NS_BEGIN { /* slower */ m_killSwitchManager.isTokenBlocked(record.tenantToken)); } - void OfflineStorageHandler::WaitForFlush() + bool OfflineStorageHandler::BeginTeardown() { + auto state = m_flushState; + std::shared_ptr pending; { - LOCKGUARD(m_flushLock); - if (!m_flushPending) - return; + std::unique_lock lock(state->mutex); + state->cv.wait(lock, [&state] { + return state->phase != FlushState::Phase::Draining && + state->phase != FlushState::Phase::Closing; + }); + if (state->phase == FlushState::Phase::Stopped) + { + return false; + } + if (state->phase == FlushState::Phase::Retryable) + { + state->phase = FlushState::Phase::Closing; + return true; + } + // Drain admitted operations before closing storage or invalidating queued work. + m_shutdownStarted = true; + state->phase = FlushState::Phase::Draining; + state->cv.wait(lock, [&state] { return state->active == 0; }); + state->phase = FlushState::Phase::Closing; + state->owner = nullptr; + pending = std::move(state->pending); + } + + if (pending) + { + MATSDK_TRY + { + std::lock_guard lock(pending->mutex); + if (pending->task) + { + m_taskDispatcher.Cancel(pending->task); + } + } + MATSDK_CATCH(...) + { + std::fputs("Failed to cancel pending offline flush\n", stderr); + } } - LOG_INFO("Waiting for pending Flush (%p) to complete...", - static_cast(m_flushHandle.GetTask())); - m_flushComplete.wait(); + return true; } OfflineStorageHandler::~OfflineStorageHandler() { - WaitForFlush(); - if (nullptr != m_offlineStorageMemory) + if (BeginTeardown()) { + TeardownGuard teardown(m_flushState); m_offlineStorageMemory.reset(); - } - if (nullptr != m_offlineStorageDisk) - { m_offlineStorageDisk.reset(); + teardown.Complete(); } } void OfflineStorageHandler::Initialize(IOfflineStorageObserver& observer) { + if (!TryShutdown()) + { + ReportIncompleteShutdown(); + return; + } + m_offlineStorageMemory.reset(); + m_offlineStorageDisk.reset(); + m_flushState = std::make_shared(this); + m_shutdownStarted = false; m_observer = &observer; m_cacheMemorySizeLimitInBytes = m_config[CFG_INT_RAM_QUEUE_SIZE]; @@ -181,25 +369,73 @@ namespace MAT_NS_BEGIN { m_offlineStorageMemory->Initialize(*this); } - m_shutdownStarted = false; LOG_TRACE("Initializing offline storage handler"); } void OfflineStorageHandler::Shutdown() + { + if (!TryShutdown()) + { + ReportIncompleteShutdown(); + } + } + + void OfflineStorageHandler::ReportIncompleteShutdown() + { + LOG_ERROR("Offline storage shutdown deferred: could not persist all queued records"); +#if HAVE_EXCEPTIONS + throw std::runtime_error("Could not persist all queued records during offline storage shutdown"); +#endif + } + + bool OfflineStorageHandler::IsShutdownPending() const + { + auto state = m_flushState; + std::lock_guard lock(state->mutex); + return state->phase == FlushState::Phase::Retryable; + } + + bool OfflineStorageHandler::TryShutdown() { LOG_TRACE("Shutting down offline storage handler"); - m_shutdownStarted = true; - WaitForFlush(); - if (nullptr != m_offlineStorageMemory) + if (!BeginTeardown()) { - m_offlineStorageMemory->ReleaseAllRecords(); - Flush(); - m_offlineStorageMemory->Shutdown(); + return true; } - if (nullptr != m_offlineStorageDisk) + auto state = m_flushState; + TeardownGuard teardown(state); + // A failed teardown retries only the stage that did not complete. + if (state->shutdownStage == FlushState::ShutdownStage::Flush) + { + if (nullptr != m_offlineStorageMemory) + { + m_offlineStorageMemory->ReleaseAllRecords(); + ActivityGuard activity(m_logManager, true); + if (!FlushImpl()) + { + return false; + } + } + state->shutdownStage = FlushState::ShutdownStage::MemoryShutdown; + } + if (state->shutdownStage == FlushState::ShutdownStage::MemoryShutdown) { - m_offlineStorageDisk->Shutdown(); + if (nullptr != m_offlineStorageMemory) + { + m_offlineStorageMemory->Shutdown(); + } + state->shutdownStage = FlushState::ShutdownStage::DiskShutdown; } + if (state->shutdownStage == FlushState::ShutdownStage::DiskShutdown) + { + if (nullptr != m_offlineStorageDisk) + { + m_offlineStorageDisk->Shutdown(); + } + state->shutdownStage = FlushState::ShutdownStage::Complete; + } + teardown.Complete(); + return true; } /// @@ -243,33 +479,31 @@ namespace MAT_NS_BEGIN { void OfflineStorageHandler::Flush() { - // Shutdown has already paused normal logging, but its synchronous final - // flush must still persist the in-memory records before storage closes. - ActivityGuard activityGuard(m_logManager, m_shutdownStarted); + OperationGuard operation(m_flushState); + if (!operation) + { + return; + } + ActivityGuard activityGuard(m_logManager); if (!activityGuard.IsActive()) { - // The LogManager is shutting down, so the flush cannot run. Still - // signal completion and clear the pending flag so a concurrent - // WaitForFlush() (e.g. during teardown) does not block forever - // waiting for m_flushComplete. - LOCKGUARD(m_flushLock); - m_flushHandle.Cancel(); - m_flushComplete.post(); - m_flushPending = false; return; } + FlushImpl(); + } + + bool OfflineStorageHandler::FlushImpl() + { std::vector recordsToRecover; std::vector memoryOnlyRecords; + size_t savedRecords = 0; + bool notifySaved = false; + bool complete = true; MATSDK_TRY { // Flush could be executed from context of worker thread, as well as from TPM and // after HTTP callback. Make sure it is atomic / thread-safe. LOCKGUARD(m_flushLock); - // If item isn't scheduled yet, it gets canceled, so that we don't do two flushes. - // If we are running that item right now (our thread), then nothing happens other - // than the handle reporting nullptr once that task finishes. - m_flushHandle.Cancel(); - size_t dbSizeBeforeFlush = (m_offlineStorageMemory != nullptr) ? m_offlineStorageMemory->GetSize() : 0; if ((m_offlineStorageMemory) && (dbSizeBeforeFlush > 0) && (m_offlineStorageDisk)) { @@ -316,11 +550,17 @@ namespace MAT_NS_BEGIN { }), recordsToRecover.end()); - const size_t batchSaved = recordsToRecover.empty() - ? 0 - : m_offlineStorageDisk->StoreRecords(recordsToRecover); + size_t batchSaved = 0; + if (!recordsToRecover.empty()) + { + // Storage can consume its input, so retain the original batch for retry. + auto recordsForStorage = recordsToRecover; + batchSaved = m_offlineStorageDisk->StoreRecords(recordsForStorage); + } + totalSaved += std::min(batchSaved, recordsToRecover.size()); if (batchSaved != recordsToRecover.size()) { + complete = false; LOG_WARN("Flush: disk store failed for the batch of %zu records; returning it to the queue for retry", recordsToRecover.size()); ReturnRecordsToMemory(recordsToRecover); @@ -328,7 +568,6 @@ namespace MAT_NS_BEGIN { break; } - totalSaved += batchSaved; recordsToRecover.clear(); } ReturnRecordsToMemory(memoryOnlyRecords); @@ -339,7 +578,7 @@ namespace MAT_NS_BEGIN { // Preserve the legacy per-record path and its unlimited drain. recordsToRecover = m_offlineStorageMemory->GetRecords( false, EventLatency_Unspecified); - totalSaved = StoreRecordsIndividually(recordsToRecover); + totalSaved = StoreRecordsIndividually(recordsToRecover, complete); } // Persistence and retry handling are complete; a later exception @@ -353,7 +592,8 @@ namespace MAT_NS_BEGIN { // obviously because the disk is slower than ram. LOG_WARN("Data is arriving too fast!"); } - OnStorageRecordsSaved(totalSaved); + savedRecords = totalSaved; + notifySaved = true; } // Checkpoint DB @@ -363,8 +603,6 @@ namespace MAT_NS_BEGIN { } m_isStorageFullNotificationSend = false; - m_flushComplete.post(); - m_flushPending = false; } MATSDK_CATCH(...) { @@ -385,16 +623,66 @@ namespace MAT_NS_BEGIN { { std::fputs("Failed to recover records after flush failure\n", stderr); } - LOCKGUARD(m_flushLock); - m_flushComplete.post(); - m_flushPending = false; + if (notifySaved) + { + MATSDK_TRY + { + OnStorageRecordsSaved(savedRecords); + } + MATSDK_CATCH(...) + { + std::fputs("Failed to report saved records after flush failure\n", stderr); + } + } std::rethrow_exception(failure); +#endif + } + if (notifySaved) + { + OnStorageRecordsSaved(savedRecords); + } + return complete; + } + + void OfflineStorageHandler::QueueScheduledFlush() + { + auto state = m_flushState; + std::shared_ptr pending; + { + std::lock_guard lock(state->mutex); + if (state->phase != FlushState::Phase::Accepting || state->pending) + { + return; + } + pending = std::make_shared(); + state->pending = pending; + } + + MATSDK_TRY + { + std::unique_ptr task(new ScheduledFlushTask(state, pending)); + m_taskDispatcher.Queue(task.release()); + } + MATSDK_CATCH(...) + { +#if HAVE_EXCEPTIONS + std::lock_guard lock(state->mutex); + if (state->pending == pending) + { + state->pending.reset(); + } + throw; #endif } } bool OfflineStorageHandler::StoreRecord(StorageRecord const& record) { + OperationGuard operation(m_flushState, true); + if (!operation) + { + return false; + } // Don't discard on shutdown because the kill-switch may be temporary. // Attempt to upload after restart. if ((!m_shutdownStarted) && isKilled(record)) @@ -436,25 +724,7 @@ namespace MAT_NS_BEGIN { // Perform periodic flush to disk if (memDbSize > cacheMemorySizeLimitInBytes) { - if (m_flushLock.try_lock()) - { - if (!m_flushPending) - { - m_flushPending = true; - m_flushComplete.Reset(); - m_flushHandle = PAL::scheduleTask(&m_taskDispatcher, 0, this, &OfflineStorageHandler::Flush); - if (m_flushHandle.GetTask() == nullptr) - { - // The dispatcher may drop a task synchronously during - // shutdown. Do not leave WaitForFlush blocked forever. - m_flushPending = false; - m_flushComplete.post(); - } - LOG_INFO("Requested Flush (%p)", - static_cast(m_flushHandle.GetTask())); - } - m_flushLock.unlock(); - } + QueueScheduledFlush(); } } else @@ -491,7 +761,7 @@ namespace MAT_NS_BEGIN { OnStorageFailed("Invalid parameters"); } - size_t OfflineStorageHandler::StoreRecordsIndividually(std::vector& records) + size_t OfflineStorageHandler::StoreRecordsIndividually(std::vector& records, bool& complete) { size_t totalSaved = 0; std::vector recordsToRetry; @@ -521,6 +791,7 @@ namespace MAT_NS_BEGIN { continue; } + complete = false; for (size_t retryIndex = nextRecord; retryIndex < records.size(); ++retryIndex) { auto const& retryRecord = records[retryIndex]; diff --git a/lib/offline/OfflineStorageHandler.hpp b/lib/offline/OfflineStorageHandler.hpp index 0eae7510b..c016c0093 100644 --- a/lib/offline/OfflineStorageHandler.hpp +++ b/lib/offline/OfflineStorageHandler.hpp @@ -14,9 +14,10 @@ #include "ILogManager.hpp" #include "pal/TaskDispatcher.hpp" -#include #include #include +#include +#include #include #include "KillSwitchManager.hpp" @@ -33,6 +34,7 @@ namespace MAT_NS_BEGIN { virtual ~OfflineStorageHandler() override; virtual void Initialize(IOfflineStorageObserver& observer) override; virtual void Shutdown() override; + bool IsShutdownPending() const; virtual void Flush() override; virtual bool StoreRecord(StorageRecord const& record) override; virtual size_t StoreRecords(std::vector & records) override; @@ -82,9 +84,11 @@ namespace MAT_NS_BEGIN { bool isKilled(StorageRecord const& record); std::mutex m_flushLock; - bool m_flushPending; - PAL::DeferredCallbackHandle m_flushHandle; - PAL::Event m_flushComplete; + class FlushState; + class OperationGuard; + class ScheduledFlushTask; + class TeardownGuard; + std::shared_ptr m_flushState; std::shared_ptr m_offlineStorageMemory; std::shared_ptr m_offlineStorageDisk; @@ -92,7 +96,7 @@ namespace MAT_NS_BEGIN { std::atomic m_readFromMemory; std::atomic m_lastReadCount; - bool m_shutdownStarted; + std::atomic m_shutdownStarted; unsigned m_memoryDbSize; unsigned m_memoryDbSizeNotificationLimit; unsigned m_queryDbSize; @@ -103,10 +107,14 @@ namespace MAT_NS_BEGIN { MATSDK_LOG_DECL_COMPONENT_CLASS(); private: - void WaitForFlush(); + bool BeginTeardown(); + bool TryShutdown(); + void ReportIncompleteShutdown(); + void QueueScheduledFlush(); + bool FlushImpl(); bool IsBatchedStorageFlushEnabled(); void ReportInvalidDiskRecord(StorageRecord const& record); - size_t StoreRecordsIndividually(std::vector& records); + size_t StoreRecordsIndividually(std::vector& records, bool& complete); size_t ReturnRecordsToMemory(std::vector const& records); }; diff --git a/lib/offline/OfflineStorage_SQLite.cpp b/lib/offline/OfflineStorage_SQLite.cpp index 631fd6dd5..c6e3e02f9 100644 --- a/lib/offline/OfflineStorage_SQLite.cpp +++ b/lib/offline/OfflineStorage_SQLite.cpp @@ -255,9 +255,14 @@ namespace MAT_NS_BEGIN { { LOCKGUARD(m_resizeLock); //Serialize resize operations m_resizing = true; - if (m_DbSizeEstimate > m_DbSizeLimit) + // A batch can exceed the limit by more than one 25% trim. + bool madeProgress = false; + while (m_DbSizeEstimate > m_DbSizeLimit) { - ResizeDb(); + if (!ResizeDb(madeProgress) || !madeProgress) + { + break; + } } m_resizing = false; } @@ -1163,6 +1168,12 @@ namespace MAT_NS_BEGIN { } bool OfflineStorage_SQLite::ResizeDb() + { + bool madeProgress = false; + return ResizeDb(madeProgress); + } + + bool OfflineStorage_SQLite::ResizeDb(bool& madeProgress) { LOCKGUARD(m_lock); if (!m_db) { @@ -1172,8 +1183,9 @@ namespace MAT_NS_BEGIN { size_t eventsDropped = 0; bool compactDatabase = false; - m_DbSizeEstimate = GetSize(); - if (m_DbSizeEstimate <= m_DbSizeLimit) + const size_t previousSize = GetSize(); + m_DbSizeEstimate = previousSize; + if (previousSize <= m_DbSizeLimit) return false; { @@ -1186,7 +1198,7 @@ namespace MAT_NS_BEGIN { } #endif auto count = GetRecordCountUnsafe(EventLatency::EventLatency_Unspecified); - if (m_DbSizeEstimate > 2 * m_DbSizeLimit) + if (previousSize > 2 * m_DbSizeLimit) { LOG_TRACE("DB is too big, deleting..."); if (!SqliteStatement(*m_db, "DELETE FROM " TABLE_NAME_EVENTS).execute()) @@ -1236,7 +1248,9 @@ namespace MAT_NS_BEGIN { return false; } - m_DbSizeEstimate = GetSize(); + const size_t newSize = GetSize(); + m_DbSizeEstimate = newSize; + madeProgress = eventsDropped != 0 || (newSize != 0 && newSize < previousSize); DebugEvent evt(DebugEventType::EVT_DROPPED); evt.param1 = eventsDropped; evt.param2 = static_cast(DROPPED_REASON_OFFLINE_STORAGE_OVERFLOW); diff --git a/lib/offline/OfflineStorage_SQLite.hpp b/lib/offline/OfflineStorage_SQLite.hpp index 2053a0246..aa3d4ffaa 100644 --- a/lib/offline/OfflineStorage_SQLite.hpp +++ b/lib/offline/OfflineStorage_SQLite.hpp @@ -122,6 +122,7 @@ namespace MAT_NS_BEGIN { MATSDK_LOG_DECL_COMPONENT_CLASS(); private: + bool ResizeDb(bool& madeProgress); size_t GetRecordCountUnsafe(EventLatency latency) const; // Validate a record's required fields; reports OnStorageFailed on rejection. diff --git a/lib/pal/PAL.cpp b/lib/pal/PAL.cpp index 94a71b4a0..22c2f6be5 100644 --- a/lib/pal/PAL.cpp +++ b/lib/pal/PAL.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include @@ -50,7 +51,6 @@ #pragma comment(lib, "Ole32.Lib") /* CoCreateGuid */ #include #include -#include "utils/WindowsUtils.hpp" #endif #if defined(ANDROID) && defined(HAVE_MAT_LOGGING) @@ -61,40 +61,6 @@ namespace PAL_NS_BEGIN { -#if defined(_WIN32) || defined(_WIN64) - namespace - { - using GetSystemTimeAsFileTimeProc = VOID (WINAPI*)(LPFILETIME); - - GetSystemTimeAsFileTimeProc getPreciseSystemTimeAsFileTime() noexcept - { - static std::once_flag once; - static GetSystemTimeAsFileTimeProc proc = nullptr; - std::call_once(once, [] { - HMODULE kernel32 = ::GetModuleHandleW(L"kernel32.dll"); - if (kernel32 != nullptr) - { - proc = MAT::GetWindowsProcAddress( - kernel32, "GetSystemTimePreciseAsFileTime"); - } - }); - return proc; - } - - void getSystemTimeAsFileTime(FILETIME& fileTime) noexcept - { - if (auto preciseProc = getPreciseSystemTimeAsFileTime()) - { - preciseProc(&fileTime); - } - else - { - ::GetSystemTimeAsFileTime(&fileTime); - } - } - } -#endif - PlatformAbstractionLayer& GetPAL() noexcept { // Deliberately never destroyed. PAL::shutdown() (called from @@ -137,32 +103,23 @@ namespace PAL_NS_BEGIN { #define DBG_BUFFER_LEN 2048 -#ifndef _WIN32 -#define DEBUG_LOG_NULL "/dev/null" -#else -#define DEBUG_LOG_NULL "NUL" -#endif - - bool isLoggingInited = false; - #ifdef HAVE_MAT_LOGGING std::recursive_mutex debugLogMutex; std::string debugLogPath; std::unique_ptr debugLogStream; + bool isLoggingInited = false; + uint64_t debugLogEpoch = 0; - bool log_init(bool isTraceEnabled, const std::string& traceFolderPath) + bool log_init(bool isTraceEnabled, const std::string& traceFolderPath, uint64_t& epoch) { + std::lock_guard lock(debugLogMutex); + epoch = 0; if (!isTraceEnabled) { + isLoggingInited = false; return false; } - bool result = true; - if (debugLogStream != nullptr) - { - return result; - } - // Check if the path exists #if defined(_WIN32) || defined(_WIN64) DWORD fileAttr = GetFileAttributesA(traceFolderPath.c_str()); @@ -175,29 +132,46 @@ namespace PAL_NS_BEGIN { if (!pathExists || containsParentDirectory) { + isLoggingInited = false; return false; } - debugLogMutex.lock(); - debugLogPath = traceFolderPath; - if (debugLogPath.back() != '/' && debugLogPath.back() != '\\') + std::string requestedPath = traceFolderPath; + if (requestedPath.back() != '/' && requestedPath.back() != '\\') + { + requestedPath += "/"; + } + requestedPath += "mat-debug-"; + requestedPath += std::to_string(MAT::GetCurrentProcessId()); + requestedPath += ".log"; + + if (!debugLogStream || debugLogPath != requestedPath) { - debugLogPath += "/"; + isLoggingInited = false; + debugLogStream.reset(); + debugLogPath = std::move(requestedPath); + auto stream = std::unique_ptr(new std::fstream()); + stream->open(debugLogPath, std::fstream::out); + if (!stream->is_open()) + { + return false; + } + debugLogStream = std::move(stream); } - debugLogPath += "mat-debug-"; - debugLogPath += std::to_string(MAT::GetCurrentProcessId()); - debugLogPath += ".log"; - debugLogStream = std::unique_ptr(new std::fstream()); - debugLogStream->open(debugLogPath, std::fstream::out); - if (!debugLogStream->is_open()) + if (++debugLogEpoch == 0) { - // If file cannot be created, log to /dev/null - debugLogStream->open(DEBUG_LOG_NULL); - result = false; + ++debugLogEpoch; } - debugLogMutex.unlock(); - return result; + epoch = debugLogEpoch; + isLoggingInited = true; + return true; + } + + bool log_init(bool isTraceEnabled, const std::string& traceFolderPath) + { + uint64_t epoch; + return log_init(isTraceEnabled, traceFolderPath, epoch); } const std::unique_ptr& getDebugLogStream() noexcept @@ -212,21 +186,28 @@ namespace PAL_NS_BEGIN { void log_done() { - debugLogMutex.lock(); - if (debugLogStream) + std::lock_guard lock(debugLogMutex); + debugLogStream.reset(); + isLoggingInited = false; + } + + void log_done(uint64_t epoch) + { + std::lock_guard lock(debugLogMutex); + if (epoch != 0 && epoch == debugLogEpoch) { - debugLogStream = nullptr; + debugLogStream.reset(); isLoggingInited = false; } - debugLogMutex.unlock(); } #else - bool log_init(bool /*isTraceEnabled*/, const std::string& /*traceFolderPath*/) + bool log_init(bool /*isTraceEnabled*/, const std::string& /*traceFolderPath*/, uint64_t& epoch) { + epoch = 0; return false; } - void log_done() + void log_done(uint64_t /*epoch*/) { } #endif @@ -362,6 +343,7 @@ namespace PAL_NS_BEGIN { std::shared_ptr PlatformAbstractionLayer::getDefaultTaskDispatcher() { + std::lock_guard lock(m_stateLock); if (!m_taskDispatcher) { // Default implementation of task dispatcher is a single-threaded worker thread task queue @@ -451,7 +433,7 @@ namespace PAL_NS_BEGIN { { #ifdef _WIN32 FILETIME fileTime; - getSystemTimeAsFileTime(fileTime); + ::GetSystemTimePreciseAsFileTime(&fileTime); ULARGE_INTEGER now; now.LowPart = fileTime.dwLowDateTime; now.HighPart = fileTime.dwHighDateTime; @@ -470,7 +452,7 @@ namespace PAL_NS_BEGIN { { #ifdef _WIN32 FILETIME tocks; - getSystemTimeAsFileTime(tocks); + ::GetSystemTimePreciseAsFileTime(&tocks); ULONGLONG ticks = (ULONGLONG(tocks.dwHighDateTime) << 32) | tocks.dwLowDateTime; // number of days from beginning to 1601 multiplied by ticks per day return ticks + 0x701ce1722770000ULL; @@ -567,43 +549,53 @@ namespace PAL_NS_BEGIN { void PlatformAbstractionLayer::registerSemanticContext(ISemanticContext* context) { - if (m_DeviceInformation != nullptr) + std::shared_ptr deviceInformation; + std::shared_ptr systemInformation; + std::shared_ptr networkInformation; { - const auto& deviceId = m_DeviceInformation->GetDeviceId(); + std::lock_guard lock(m_stateLock); + deviceInformation = m_DeviceInformation; + systemInformation = m_SystemInformation; + networkInformation = m_NetworkInformation; + } + + if (deviceInformation != nullptr) + { + const auto& deviceId = deviceInformation->GetDeviceId(); #ifdef MATSDK_DISABLE_DEVICE_ID if (!deviceId.empty()) #endif context->SetDeviceId(deviceId); - context->SetDeviceModel(m_DeviceInformation->GetModel()); - context->SetDeviceMake(m_DeviceInformation->GetManufacturer()); + context->SetDeviceModel(deviceInformation->GetModel()); + context->SetDeviceMake(deviceInformation->GetManufacturer()); } - if (m_SystemInformation != nullptr) + if (systemInformation != nullptr) { // Get SystemInfo common fields - context->SetOsVersion(m_SystemInformation->GetOsMajorVersion()); - context->SetOsName(m_SystemInformation->GetOsName()); - context->SetOsBuild(m_SystemInformation->GetOsFullVersion()); - context->SetDeviceClass(m_SystemInformation->GetDeviceClass()); + context->SetOsVersion(systemInformation->GetOsMajorVersion()); + context->SetOsName(systemInformation->GetOsName()); + context->SetOsBuild(systemInformation->GetOsFullVersion()); + context->SetDeviceClass(systemInformation->GetDeviceClass()); // AppInfo fields - context->SetAppId(m_SystemInformation->GetAppId()); - context->SetAppVersion(m_SystemInformation->GetAppVersion()); - context->SetAppLanguage(m_SystemInformation->GetAppLanguage()); + context->SetAppId(systemInformation->GetAppId()); + context->SetAppVersion(systemInformation->GetAppVersion()); + context->SetAppLanguage(systemInformation->GetAppLanguage()); // UserInfo fields. - context->SetUserLanguage(m_SystemInformation->GetUserLanguage()); - context->SetUserTimeZone(m_SystemInformation->GetUserTimeZone()); - //context->SetUserAdvertisingId(m_SystemInformation->GetUserAdvertisingId()); + context->SetUserLanguage(systemInformation->GetUserLanguage()); + context->SetUserTimeZone(systemInformation->GetUserTimeZone()); + //context->SetUserAdvertisingId(systemInformation->GetUserAdvertisingId()); - context->SetCommercialId(m_SystemInformation->GetCommercialId()); + context->SetCommercialId(systemInformation->GetCommercialId()); } - if (m_NetworkInformation != nullptr) + if (networkInformation != nullptr) { // Get NetworkInfo common fields - context->SetNetworkProvider(m_NetworkInformation->GetNetworkProvider()); - context->SetNetworkCost(m_NetworkInformation->GetNetworkCost()); - context->SetNetworkType(m_NetworkInformation->GetNetworkType()); + context->SetNetworkProvider(networkInformation->GetNetworkProvider()); + context->SetNetworkCost(networkInformation->GetNetworkCost()); + context->SetNetworkType(networkInformation->GetNetworkType()); } } @@ -629,61 +621,137 @@ namespace PAL_NS_BEGIN { #define OS_NAME "Unknown" #endif - const std::string& PlatformAbstractionLayer::getSdkVersion() const + const char* PlatformAbstractionLayer::getSdkVersion() const { - static const std::string sdkVersion(EVTSDK_VERSION_PREFIX "-" OS_NAME "-C++-" ECS_SUPP "-" BUILD_VERSION_STR); - return sdkVersion; + // A literal survives late workers without leaking a string buffer on library unload. + return EVTSDK_VERSION_PREFIX "-" OS_NAME "-C++-" ECS_SUPP "-" BUILD_VERSION_STR; } void PlatformAbstractionLayer::initialize(IRuntimeConfig& configuration) { - if (m_palStarted.fetch_add(1) == 0) { + std::unique_lock lock(m_stateLock); + m_stateChanged.wait(lock, [this] { return !m_initializing; }); + if (m_palStarted > 0) + { + const size_t count = ++m_palStarted; + lock.unlock(); + LOG_INFO("Already initialized: %zu", count); + (void)count; + return; + } + m_initializing = true; + } + + // Platform provider factories can invoke callbacks that access PAL. + uint64_t logEpoch = 0; + std::shared_ptr systemInformation; + std::shared_ptr deviceInformation; + std::shared_ptr networkInformation; +#if HAVE_EXCEPTIONS + try + { +#endif std::string traceFolderPath = MAT::GetTempDirectory(); if (configuration.HasConfig(CFG_STR_TRACE_FOLDER_PATH)) { traceFolderPath = static_cast(configuration[CFG_STR_TRACE_FOLDER_PATH]); } - detail::isLoggingInited = detail::log_init(configuration[CFG_BOOL_ENABLE_TRACE], traceFolderPath); + detail::log_init(configuration[CFG_BOOL_ENABLE_TRACE], traceFolderPath, logEpoch); LOG_TRACE("Initializing..."); - m_SystemInformation = SystemInformationImpl::Create(configuration); - m_DeviceInformation = DeviceInformationImpl::Create(configuration); - m_NetworkInformation = NetworkInformationImpl::Create(configuration); - LOG_INFO("Initialized"); + systemInformation = SystemInformationImpl::Create(configuration); + deviceInformation = DeviceInformationImpl::Create(configuration); + networkInformation = NetworkInformationImpl::Create(configuration); +#if HAVE_EXCEPTIONS } - else + catch (...) + { + networkInformation.reset(); + deviceInformation.reset(); + systemInformation.reset(); + detail::log_done(logEpoch); + { + std::lock_guard lock(m_stateLock); + m_initializing = false; + } + m_stateChanged.notify_all(); + throw; + } +#endif + { - LOG_INFO("Already initialized: %d", m_palStarted.load()); + std::lock_guard lock(m_stateLock); + m_SystemInformation = std::move(systemInformation); + m_DeviceInformation = std::move(deviceInformation); + m_NetworkInformation = std::move(networkInformation); + m_logEpoch = logEpoch; + m_palStarted = 1; + m_initializing = false; } + m_stateChanged.notify_all(); + LOG_INFO("Initialized"); } - std::shared_ptr PlatformAbstractionLayer::GetNetworkInformation() const noexcept { return m_NetworkInformation; } - std::shared_ptr PlatformAbstractionLayer::GetDeviceInformation() const noexcept { return m_DeviceInformation; } - std::shared_ptr PlatformAbstractionLayer::GetSystemInformation() const noexcept { return m_SystemInformation; } + std::shared_ptr PlatformAbstractionLayer::GetNetworkInformation() const noexcept + { + std::lock_guard lock(m_stateLock); + return m_NetworkInformation; + } + + std::shared_ptr PlatformAbstractionLayer::GetDeviceInformation() const noexcept + { + std::lock_guard lock(m_stateLock); + return m_DeviceInformation; + } + + std::shared_ptr PlatformAbstractionLayer::GetSystemInformation() const noexcept + { + std::lock_guard lock(m_stateLock); + return m_SystemInformation; + } void PlatformAbstractionLayer::shutdown() { - if (m_palStarted == 0) + std::shared_ptr taskDispatcher; + std::shared_ptr systemInformation; + std::shared_ptr deviceInformation; + std::shared_ptr networkInformation; + uint64_t logEpoch = 0; { - LOG_ERROR("PAL is already shutdown!"); - return; - } + std::unique_lock lock(m_stateLock); + m_stateChanged.wait(lock, [this] { return !m_initializing; }); + if (m_palStarted == 0) + { + lock.unlock(); + LOG_ERROR("PAL is already shutdown!"); + return; + } + if (--m_palStarted > 0) + { + const size_t count = m_palStarted; + lock.unlock(); + LOG_INFO("Shutting down: %zu", count); + (void)count; + return; + } - if (m_palStarted.fetch_sub(1) == 1) - { - LOG_TRACE("Shutting down..."); - if (m_taskDispatcher) { m_taskDispatcher = nullptr; } - if (m_SystemInformation) { m_SystemInformation = nullptr; } - if (m_DeviceInformation) { m_DeviceInformation = nullptr; } - if (m_NetworkInformation) { m_NetworkInformation = nullptr; } - LOG_INFO("Shut down"); - detail::log_done(); - } - else - { - LOG_INFO("Shutting down: %d", m_palStarted.load()); + taskDispatcher = std::move(m_taskDispatcher); + systemInformation = std::move(m_SystemInformation); + deviceInformation = std::move(m_DeviceInformation); + networkInformation = std::move(m_NetworkInformation); + logEpoch = m_logEpoch; + m_logEpoch = 0; } + + LOG_TRACE("Shutting down..."); + // Releasing the last dispatcher reference can join a worker that re-enters PAL. + taskDispatcher.reset(); + systemInformation.reset(); + deviceInformation.reset(); + networkInformation.reset(); + LOG_INFO("Shut down"); + detail::log_done(logEpoch); } #ifndef HAVE_MAT_UTC diff --git a/lib/pal/PAL.hpp b/lib/pal/PAL.hpp index f79cdd080..eca9edf32 100644 --- a/lib/pal/PAL.hpp +++ b/lib/pal/PAL.hpp @@ -78,7 +78,7 @@ namespace PAL_NS_BEGIN public: void sleep(unsigned delayMs) const noexcept; - const std::string& getSdkVersion() const; + const char* getSdkVersion() const; std::string generateUuidString() const; @@ -111,7 +111,11 @@ namespace PAL_NS_BEGIN MATSDK_LOG_DECL_COMPONENT_CLASS(); private: - volatile std::atomic m_palStarted { 0 }; + mutable std::mutex m_stateLock; + std::condition_variable m_stateChanged; + bool m_initializing = false; + size_t m_palStarted = 0; + uint64_t m_logEpoch = 0; std::shared_ptr m_taskDispatcher; std::shared_ptr m_SystemInformation; std::shared_ptr m_NetworkInformation; @@ -136,7 +140,7 @@ namespace PAL_NS_BEGIN /** * Return SDK version in format "----". */ - inline const std::string& getSdkVersion() + inline const char* getSdkVersion() { return GetPAL().getSdkVersion(); } @@ -243,9 +247,11 @@ namespace PAL_NS_BEGIN namespace detail { bool log_init(bool isTraceEnabled, const std::string& traceFolderPath); + bool log_init(bool isTraceEnabled, const std::string& traceFolderPath, uint64_t& epoch); const std::unique_ptr& getDebugLogStream() noexcept; const std::string& getDebugLogPath() noexcept; void log_done(); + void log_done(uint64_t epoch); } #endif diff --git a/lib/pal/WorkerThread.cpp b/lib/pal/WorkerThread.cpp index 03878f298..46da4f62f 100644 --- a/lib/pal/WorkerThread.cpp +++ b/lib/pal/WorkerThread.cpp @@ -295,19 +295,15 @@ namespace PAL_NS_BEGIN { queuedItem = *it; m_timerQueue.erase(it); } - lock.unlock(); - delete queuedItem; -#if 0 - for (;;) { - { - LOCKGUARD(m_lock); - if (item->Type == MAT::Task::Done) { - return; - } + else { + auto immediate = std::find(m_queue.begin(), m_queue.end(), item); + if (immediate != m_queue.end()) { + queuedItem = *immediate; + m_queue.erase(immediate); } - Sleep(10); } -#endif + lock.unlock(); + delete queuedItem; return true; } diff --git a/tests/apple/embedding-options-tests.cmake b/tests/apple/embedding-options-tests.cmake new file mode 100644 index 000000000..68d2b39e0 --- /dev/null +++ b/tests/apple/embedding-options-tests.cmake @@ -0,0 +1,44 @@ +cmake_minimum_required(VERSION 3.15...3.19) +get_filename_component(sdk_root "${CMAKE_CURRENT_LIST_DIR}/../.." ABSOLUTE) +if(NOT DEFINED OUTPUT_DIR) + set(OUTPUT_DIR "${sdk_root}/out/apple-embedding-options") +endif() +set(generator_args) +if(TEST_GENERATOR) + list(APPEND generator_args -G "${TEST_GENERATOR}") +endif() +if(TEST_GENERATOR_PLATFORM) + list(APPEND generator_args -A "${TEST_GENERATOR_PLATFORM}") +endif() + +function(check_options apple vcpkg provided http mobile class) + # Keep MSBuild's nested compiler-probe paths below its legacy path limit. + string(SHA1 name "${apple}-${vcpkg}-${provided}-${http}-${mobile}-${class}") + string(SUBSTRING "${name}" 0 6 name) + execute_process(COMMAND "${CMAKE_COMMAND}" ${generator_args} + -S "${CMAKE_CURRENT_LIST_DIR}/embedding-options" -B "${OUTPUT_DIR}/${name}" + "-DSDK_ROOT=${sdk_root}" "-DTEST_APPLE=${apple}" "-DTEST_VCPKG=${vcpkg}" + "-DTEST_PROVIDED=${provided}" "-DTEST_HTTP=${http}" "-DTEST_MOBILE=${mobile}" + "-DMATSDK_APPLE_HTTP_DELEGATE_CLASS=${class}" + RESULT_VARIABLE result OUTPUT_VARIABLE output ERROR_VARIABLE error) + if(class STREQUAL "invalid-class") + if(result EQUAL 0 OR NOT error MATCHES "must be a C identifier") + message(FATAL_ERROR "Invalid delegate name was not rejected:\n${output}\n${error}") + endif() + elseif(NOT result EQUAL 0) + message(FATAL_ERROR "${apple}/${vcpkg}/${provided}/${http}/${mobile}/${class} failed:\n${output}\n${error}") + endif() +endfunction() + +foreach(apple ON OFF) + foreach(vcpkg ON OFF) + foreach(provided ON OFF) + check_options("${apple}" "${vcpkg}" "${provided}" ON OFF MATStreamingSessionDelegate) + check_options("${apple}" "${vcpkg}" "${provided}" ON OFF ProductMATStreamingSessionDelegate) + endforeach() + endforeach() +endforeach() +check_options(ON ON OFF OFF OFF ProductMATStreamingSessionDelegate) +check_options(ON ON OFF OFF ON ProductMATStreamingSessionDelegate) +check_options(ON ON OFF ON OFF invalid-class) +message(STATUS "19 Apple dependency/delegate configurations passed") diff --git a/tests/apple/embedding-options/CMakeLists.txt b/tests/apple/embedding-options/CMakeLists.txt new file mode 100644 index 000000000..355bd6b26 --- /dev/null +++ b/tests/apple/embedding-options/CMakeLists.txt @@ -0,0 +1,74 @@ +cmake_minimum_required(VERSION 3.15...3.19) +project(apple_embedding_options LANGUAGES C CXX) + +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/platform.cmake" "set(APPLE ${TEST_APPLE})\n") +set(CMAKE_PROJECT_INCLUDE "${CMAKE_CURRENT_BINARY_DIR}/platform.cmake") +set(APPLE "${TEST_APPLE}") +if(TEST_VCPKG) + set(VCPKG_TARGET_TRIPLET test-triplet) +endif() +set(MATSDK_BUILD_HEADERS OFF CACHE BOOL "" FORCE) +set(MATSDK_BUILD_LIBRARY OFF CACHE BOOL "" FORCE) +set(MATSDK_BUILD_TEST_TOOL OFF CACHE BOOL "" FORCE) +set(MATSDK_BUILD_UNIT_TESTS OFF CACHE BOOL "" FORCE) +set(MATSDK_BUILD_FUNC_TESTS OFF CACHE BOOL "" FORCE) +set(MATSDK_BUILD_PACKAGE OFF CACHE BOOL "" FORCE) +set(DEFAULT_PAL_IMPLEMENTATION CPP11) +set(BUILD_IOS "${TEST_MOBILE}" CACHE BOOL "" FORCE) +set(MATSDK_BUILD_APPLE_HTTP "${TEST_HTTP}" CACHE BOOL "" FORCE) +set(MATSDK_SQLITE_PROVIDER SYSTEM CACHE STRING "" FORCE) +set(MATSDK_ZLIB_PROVIDER SYSTEM CACHE STRING "" FORCE) +add_library(CURL::libcurl INTERFACE IMPORTED) +add_library(nlohmann_json::nlohmann_json INTERFACE IMPORTED) +if(TEST_PROVIDED OR NOT TEST_APPLE) + add_library(SQLite3::SQLite3 INTERFACE IMPORTED) + add_library(ZLIB::ZLIB INTERFACE IMPORTED) + set_property(TARGET SQLite3::SQLite3 PROPERTY INTERFACE_LINK_LIBRARIES caller-sqlite) + set_property(TARGET ZLIB::ZLIB PROPERTY INTERFACE_LINK_LIBRARIES caller-zlib) +endif() +foreach(package SQLite3 unofficial-sqlite3 ZLIB nlohmann_json) + set(CMAKE_DISABLE_FIND_PACKAGE_${package} ON) +endforeach() +add_subdirectory("${SDK_ROOT}" sdk) +foreach(pair "SQLite3::SQLite3|sqlite3|caller-sqlite" "ZLIB::ZLIB|z|caller-zlib") + string(REPLACE "|" ";" pair "${pair}") + list(GET pair 0 target) + list(GET pair 1 expected) + if(TEST_PROVIDED OR NOT TEST_APPLE) + list(GET pair 2 expected) + endif() + get_target_property(links "${target}" INTERFACE_LINK_LIBRARIES) + if(NOT links STREQUAL expected) + message(FATAL_ERROR "${target} links ${links}, expected ${expected}") + endif() +endforeach() + +# Evaluate the production target guard without requiring an Apple compiler or SDK. +file(READ "${SDK_ROOT}/lib/CMakeLists.txt" library) +string(FIND "${library}" "if(APPLE AND PAL_IMPLEMENTATION STREQUAL \"CPP11\" AND (MATSDK_BUILD_APPLE_HTTP OR MATSDK_PLATFORM_IOS))" start) +if(start EQUAL -1) + message(FATAL_ERROR "Update Apple delegate target instrumentation") +endif() +string(SUBSTRING "${library}" ${start} -1 definition) +string(FIND "${definition}" "\nendif()" end) +math(EXPR end "${end} + 8") +string(SUBSTRING "${definition}" 0 ${end} definition) +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/delegate.cpp" "") +add_library(mat STATIC "${CMAKE_CURRENT_BINARY_DIR}/delegate.cpp") +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/delegate.cmake" "${definition}") +set(PAL_IMPLEMENTATION "${DEFAULT_PAL_IMPLEMENTATION}") +set(MATSDK_PLATFORM_IOS "${TEST_MOBILE}") +include("${CMAKE_CURRENT_BINARY_DIR}/delegate.cmake") +get_target_property(private mat COMPILE_DEFINITIONS) +get_target_property(public mat INTERFACE_COMPILE_DEFINITIONS) +set(expected "MATStreamingSessionDelegate=${MATSDK_APPLE_HTTP_DELEGATE_CLASS}") +if(TEST_APPLE AND (TEST_HTTP OR TEST_MOBILE)) + if(NOT expected IN_LIST private) + message(FATAL_ERROR "Missing private Apple delegate definition: ${private}") + endif() +elseif(expected IN_LIST private) + message(FATAL_ERROR "Delegate definition leaked into a non-Apple HTTP build") +endif() +if(expected IN_LIST public) + message(FATAL_ERROR "Delegate definition propagated to consumers") +endif() diff --git a/tests/build-runner-tests.py b/tests/build-runner-tests.py index 8360c1142..43aadc28a 100644 --- a/tests/build-runner-tests.py +++ b/tests/build-runner-tests.py @@ -15,7 +15,7 @@ class BuildRunnerTests(unittest.TestCase): def setUp(self): self.temporary = tempfile.TemporaryDirectory() self.addCleanup(self.temporary.cleanup) - self.root = Path(self.temporary.name) + self.root = Path(self.temporary.name).resolve() self.calls = self.root / "calls.txt" shutil.copyfile(REPO_ROOT / "build-tests.sh", self.root / "build-tests.sh") self.write_script( @@ -33,7 +33,8 @@ def setUp(self): self.write_script( "out/tests/functests/FuncTests", 'printf "concurrent %s\\n" "$*" >> "$CALLS"\n' - 'if mkdir "$CASE_ROOT/first-child" 2>/dev/null; then\n' + # Use shell noclobber to claim one role without an external mkdir. + 'if (set -C; : > "$CASE_ROOT/first-child") 2>/dev/null; then\n' ' sleep 0.05\n' ' echo first-finished >> "$CALLS"\n' ' exit "${FIRST_RESULT:-0}"\n' @@ -65,7 +66,7 @@ def run_runner(self, *arguments, **variables): environment.update(variables) result = subprocess.run( ["sh", str(self.root / "build-tests.sh"), *arguments], - cwd=self.temporary.name, + cwd=self.root, env=environment, capture_output=True, text=True, diff --git a/tests/embedding/CMakeLists.txt b/tests/embedding/CMakeLists.txt index fb7a01ffa..792283f2f 100644 --- a/tests/embedding/CMakeLists.txt +++ b/tests/embedding/CMakeLists.txt @@ -5,7 +5,22 @@ set(CMAKE_CXX_STANDARD 11) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_CXX_EXTENSIONS OFF) +option(MATSDK_EMBEDDING_ADDRESS_SANITIZER + "Run embedding regressions with AddressSanitizer and leak detection" OFF) +if(MATSDK_EMBEDDING_ADDRESS_SANITIZER) + if(NOT CMAKE_SYSTEM_NAME STREQUAL "Linux" OR + NOT CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") + message(FATAL_ERROR "Embedding ASan/LSan coverage requires Linux with GCC or Clang") + endif() + add_compile_options(-fsanitize=address -fno-omit-frame-pointer) + add_link_options(-fsanitize=address) +endif() + set(BUILD_SHARED_LIBS OFF CACHE BOOL "") +if(MATSDK_EMBEDDING_ADDRESS_SANITIZER AND BUILD_SHARED_LIBS) + message(FATAL_ERROR "Embedding ASan/LSan coverage requires static SDK embedding") +endif() + set(MATSDK_BUILD_HEADERS ON CACHE BOOL "" FORCE) set(MATSDK_BUILD_LIBRARY ON CACHE BOOL "" FORCE) set(MATSDK_BUILD_TEST_TOOL OFF CACHE BOOL "" FORCE) @@ -114,3 +129,14 @@ endif() enable_testing() add_test(NAME embedding_test COMMAND embedding_test) +include("${CMAKE_CURRENT_LIST_DIR}/lifetime-tests.cmake") +if(MATSDK_EMBEDDING_ADDRESS_SANITIZER) + set_tests_properties(sdk_version_reload PROPERTIES + ENVIRONMENT "ASAN_OPTIONS=detect_leaks=1;LSAN_OPTIONS=exitcode=23") +endif() +add_test(NAME apple_embedding_options + COMMAND "${CMAKE_COMMAND}" + "-DOUTPUT_DIR=${CMAKE_CURRENT_BINARY_DIR}/apple-options" + "-DTEST_GENERATOR=${CMAKE_GENERATOR}" + "-DTEST_GENERATOR_PLATFORM=${CMAKE_GENERATOR_PLATFORM}" + -P "${CMAKE_CURRENT_LIST_DIR}/../apple/embedding-options-tests.cmake") diff --git a/tests/embedding/lifetime-tests.cmake b/tests/embedding/lifetime-tests.cmake new file mode 100644 index 000000000..8de708589 --- /dev/null +++ b/tests/embedding/lifetime-tests.cmake @@ -0,0 +1,85 @@ +# Static embedding lets the instrumented production objects replace their archive counterparts. +if(BUILD_SHARED_LIBS) + return() +endif() + +set(lifetime_dir "${CMAKE_CURRENT_BINARY_DIR}/lifetime-sdk") +file(MAKE_DIRECTORY "${lifetime_dir}") +foreach(source pal/PAL.cpp api/AuthTokensController.cpp) + set(source_path "${sdk_source}/lib/${source}") + set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS "${source_path}") + file(READ "${source_path}" instrumented) + if(source STREQUAL "pal/PAL.cpp") + string(REPLACE "static const std::string sdkVersion(" "static const LifetimeString sdkVersion(" + instrumented "${instrumented}") + string(REPLACE "using SdkVersion = std::string;" "using SdkVersion = LifetimeString;" + instrumented "${instrumented}") + # Hook entry, not a local variable: the allocation-free implementation has none. + string(REGEX REPLACE "(PlatformAbstractionLayer::getSdkVersion\\(\\) const[ \r\n]*\\{)" + "\\1\n LifetimeVersionAccessed();" instrumented "${instrumented}") + if(NOT instrumented MATCHES "LifetimeVersionAccessed\\(\\);") + message(FATAL_ERROR "Update version accessor lifetime instrumentation") + endif() + string(PREPEND instrumented + "extern \"C\" void LifetimeVersionAccessed();\n") + set(hook "LifetimeVersionDestroyed") + set(type String) + set(base string) + else() + string(REPLACE "static std::mutex mutex;" "static LifetimeMutex mutex;" + instrumented "${instrumented}") + string(REPLACE "using AuthMutex = std::mutex;" "using AuthMutex = LifetimeMutex;" + instrumented "${instrumented}") + set(hook "LifetimeMutexDestroyed") + set(type Mutex) + set(base mutex) + endif() + if(NOT instrumented MATCHES "(LifetimeVersionAccessed\\(\\);|static LifetimeMutex mutex|using AuthMutex = LifetimeMutex)") + message(FATAL_ERROR "Update lifetime instrumentation for ${source}") + endif() + string(PREPEND instrumented + "#include \n#include \n" + "extern \"C\" void ${hook}();\n" + "struct Lifetime${type} : std::${base} {\n" + " using std::${base}::${base};\n" + " ~Lifetime${type}() { ${hook}(); }\n" + "};\n") + get_filename_component(name "${source}" NAME) + file(WRITE "${lifetime_dir}/${name}" "${instrumented}") +endforeach() + +add_executable(sdk_lifetime_tests "${CMAKE_CURRENT_LIST_DIR}/lifetime-tests.cpp" + "${lifetime_dir}/PAL.cpp" "${lifetime_dir}/AuthTokensController.cpp") +target_link_libraries(sdk_lifetime_tests PRIVATE MSTelemetry::mat matsdk_internal_config matsdk_build_options) +target_compile_features(sdk_lifetime_tests PRIVATE cxx_std_17) +target_include_directories(sdk_lifetime_tests PRIVATE "$" + "${sdk_source}/lib/api") +add_dependencies(embedding_test sdk_lifetime_tests) +foreach(mode version mutex both) + add_test(NAME sdk_lifetime_${mode} COMMAND sdk_lifetime_tests "${mode}") + set_tests_properties(sdk_lifetime_${mode} PROPERTIES TIMEOUT 30) +endforeach() + +# Embed the actual archive, not the instrumented copies, to catch unload-time leaks. +add_library(sdk_version_reload_fixture SHARED version-reload-fixture.cpp) +target_link_libraries(sdk_version_reload_fixture PRIVATE MSTelemetry::mat + matsdk_internal_config matsdk_build_options) +target_compile_features(sdk_version_reload_fixture PRIVATE cxx_std_17) +target_include_directories(sdk_version_reload_fixture PRIVATE + "$") +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + # GNU-unique symbols pin DSOs; symbol interposition can bind to another SDK copy. + target_compile_options(mat PRIVATE $<$:-fno-gnu-unique>) + target_link_options(sdk_version_reload_fixture PRIVATE + "-Wl,--exclude-libs,ALL" "-Wl,-Bsymbolic") +endif() + +add_executable(sdk_version_reload_test version-reload-test.cpp) +target_link_libraries(sdk_version_reload_test PRIVATE ${CMAKE_DL_LIBS} + matsdk_internal_config matsdk_build_options) +target_include_directories(sdk_version_reload_test PRIVATE + "$") +add_dependencies(embedding_test sdk_version_reload_fixture sdk_version_reload_test) +add_test(NAME sdk_version_reload + COMMAND sdk_version_reload_test "$") +set_tests_properties(sdk_version_reload PROPERTIES TIMEOUT 30) diff --git a/tests/embedding/lifetime-tests.cpp b/tests/embedding/lifetime-tests.cpp new file mode 100644 index 000000000..be59e18c8 --- /dev/null +++ b/tests/embedding/lifetime-tests.cpp @@ -0,0 +1,120 @@ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +#include "Version.hpp" +#include "api/AuthTokensController.hpp" +#include "pal/PAL.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace +{ + std::atomic versionDestroyed{false}; + std::atomic mutexDestroyed{false}; + bool checkVersion = false; + bool checkMutex = false; + const char* versionAddress = nullptr; + std::mutex* mutexAddress = nullptr; + + void Fail(const char* message) + { + std::fprintf(stderr, "%s\n", message); +#ifdef _WIN32 + // The exit owner holds the CRT exit lock while waiting for this worker. + ::TerminateProcess(::GetCurrentProcess(), 1); +#endif + std::_Exit(1); + } + + void ReadState() + { + if (checkVersion) + { + if (versionDestroyed.load()) + { + Fail("SDK version was destroyed before its exit owner"); + } + + const std::string_view version = PAL::GetPAL().getSdkVersion(); + const std::string_view prefix = EVTSDK_VERSION_PREFIX "-"; + const std::string_view suffix = "-C++-" ECS_SUPP "-" BUILD_VERSION_STR; + if (version.substr(0, prefix.size()) != prefix || + version.size() < suffix.size() || + version.substr(version.size() - suffix.size()) != suffix || + (versionAddress && versionAddress != version.data())) + { + Fail("SDK version did not retain its value and identity"); + } + + versionAddress = version.data(); + } + + if (checkMutex) + { + if (mutexDestroyed.load()) + { + Fail("Auth mutex was destroyed before its exit owner"); + } + + auto& mutex = MAT::AuthTokensController::GetMutex(); + if (mutexAddress && mutexAddress != &mutex) + { + Fail("Auth mutex did not retain its identity"); + } + + std::lock_guard lock(mutex); + mutexAddress = &mutex; + } + } + + void ExitOwner() + { + // Model an owner registered before its first upload initializes SDK state. + std::thread lateWorker(ReadState); + lateWorker.join(); + } +} + +extern "C" void LifetimeVersionDestroyed() +{ + versionDestroyed.store(true); +} + +extern "C" void LifetimeVersionAccessed() +{ + if (versionDestroyed.load()) + { + Fail("SDK version accessed after destruction"); + } +} + +extern "C" void LifetimeMutexDestroyed() +{ + mutexDestroyed.store(true); +} + +int main(int argc, char** argv) +{ + if (argc != 2) + { + return 2; + } + + checkVersion = std::strcmp(argv[1], "version") == 0 || std::strcmp(argv[1], "both") == 0; + checkMutex = std::strcmp(argv[1], "mutex") == 0 || std::strcmp(argv[1], "both") == 0; + if ((!checkVersion && !checkMutex) || std::atexit(ExitOwner) != 0) + { + return 2; + } + + ReadState(); + ReadState(); + return 0; +} diff --git a/tests/embedding/version-reload-fixture.cpp b/tests/embedding/version-reload-fixture.cpp new file mode 100644 index 000000000..8f63cd91c --- /dev/null +++ b/tests/embedding/version-reload-fixture.cpp @@ -0,0 +1,18 @@ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +#include "pal/PAL.hpp" + +#include + +#ifdef _WIN32 +#define EXPORTED __declspec(dllexport) +#else +#define EXPORTED __attribute__((visibility("default"))) +#endif + +extern "C" EXPORTED const char* GetSdkVersionForReload() +{ + return std::string_view(PAL::getSdkVersion()).data(); +} diff --git a/tests/embedding/version-reload-test.cpp b/tests/embedding/version-reload-test.cpp new file mode 100644 index 000000000..d07fc5785 --- /dev/null +++ b/tests/embedding/version-reload-test.cpp @@ -0,0 +1,96 @@ +// +// Copyright (c) Microsoft Corporation. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 +// +#include "Version.hpp" +#include "mat/config.h" + +#include +#include + +#ifdef _WIN32 +#include +#else +#include +#endif + +namespace +{ + bool CheckVersion(const char* version) + { + const char prefix[] = EVTSDK_VERSION_PREFIX "-"; +#ifdef HAVE_MAT_EXP + const char suffix[] = "-C++-ECS-" BUILD_VERSION_STR; +#else + const char suffix[] = "-C++-No-" BUILD_VERSION_STR; +#endif + if (!version) + { + return false; + } + + const auto size = std::strlen(version); + return size >= sizeof(suffix) - 1 && + std::strncmp(version, prefix, sizeof(prefix) - 1) == 0 && + std::strcmp(version + size - (sizeof(suffix) - 1), suffix) == 0; + } + + bool Reload(const char* path) + { +#ifdef _WIN32 + const auto library = ::LoadLibraryA(path); + const auto version = library + ? reinterpret_cast(::GetProcAddress(library, "GetSdkVersionForReload")) + : nullptr; +#else + auto* library = dlopen(path, RTLD_NOW | RTLD_LOCAL); + const auto version = library + ? reinterpret_cast(dlsym(library, "GetSdkVersionForReload")) + : nullptr; +#endif + if (!library) + { + std::fprintf(stderr, "Unable to load SDK fixture: %s\n", path); + return false; + } + + // Do not keep a pointer into an unloaded DSO or heap buffer on the stack. + const bool valid = version && CheckVersion(version()) && CheckVersion(version()); +#ifdef _WIN32 + const bool unloaded = ::FreeLibrary(library) && !::GetModuleHandleA(path); +#else + const bool closed = dlclose(library) == 0; + auto* remaining = dlopen(path, RTLD_NOW | RTLD_NOLOAD); + const bool unloaded = closed && !remaining; + if (remaining) + { + dlclose(remaining); + } +#endif + if (!valid || !unloaded) + { + std::fprintf(stderr, "SDK version validation or actual library unload failed\n"); + } + + return valid && unloaded; + } +} + +int main(int argc, char** argv) +{ + if (argc != 2) + { + return 2; + } + + for (int cycle = 0; cycle != 2; ++cycle) + { + if (!Reload(argv[1])) + { + return 1; + } + } + + std::puts("PASS two SDK version unload/reload cycles"); + return 0; +} diff --git a/tests/functests/APITest.cpp b/tests/functests/APITest.cpp index 1500ec30e..8b910994e 100644 --- a/tests/functests/APITest.cpp +++ b/tests/functests/APITest.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include @@ -891,6 +892,104 @@ TEST(APITest, C_API_Test) } #ifdef HAVE_MAT_JSONHPP +TEST(APITest, C_API_SharedClientsReleaseTheirOwnLeases) +{ + const char* hostConfig = JSON_CONFIG({ + "name": "shared-capi-host", + "config": { "host": "shared-capi-host" }, + "maxTeardownUploadTimeInSec": 0 + }); + const char* guestConfig = JSON_CONFIG({ + "name": "shared-capi-guest", + "config": { "host": "shared-capi-host" } + }); + const char* wildcardConfig = JSON_CONFIG({ + "name": "shared-capi-guest", + "config": { "host": "*" }, + "maxTeardownUploadTimeInSec": 0 + }); + const char* conflictingConfig = JSON_CONFIG({ + "name": "shared-capi-host", + "config": { "host": "shared-capi-host" }, + "version": "2.0.0" + }); + + for (bool wildcardFirst : {false, true}) + { + for (bool closeCreatorFirst : {false, true}) + { + SCOPED_TRACE(wildcardFirst); + SCOPED_TRACE(closeCreatorFirst); + auto creator = evt_open(wildcardFirst ? wildcardConfig : hostConfig); + auto guest = evt_open(wildcardFirst ? hostConfig : guestConfig); + ASSERT_NE(creator, 0); + ASSERT_NE(guest, 0); + ASSERT_NE(creator, guest); + auto manager = capi_get_client(creator)->logmanager; + ASSERT_EQ(capi_get_client(guest)->logmanager, manager); + EXPECT_EQ(evt_open(hostConfig), wildcardFirst ? guest : creator); + EXPECT_EQ(evt_open(conflictingConfig), 0); + EXPECT_EQ(evt_open(conflictingConfig), 0); + EXPECT_EQ(evt_pause(creator), STATUS_SUCCESS); + + const auto first = closeCreatorFirst ? creator : guest; + const auto survivor = closeCreatorFirst ? guest : creator; + ASSERT_EQ(evt_close(first), STATUS_SUCCESS); + EXPECT_EQ(capi_get_client(first), nullptr); + ASSERT_EQ(capi_get_client(survivor)->logmanager, manager); + EXPECT_STREQ(manager->GetLogConfiguration()[CFG_STR_FACTORY_NAME], + wildcardFirst ? "shared-capi-guest" : "shared-capi-host"); + + TestDebugEventListener listener; + int accepted = 0; + listener.OnLogX = [&](::CsProtocol::Record&) { ++accepted; }; + manager->AddEventListener(EVT_LOG_EVENT, listener); + evt_prop event[] = TELEMETRY_EVENT( + _STR(COMMONFIELDS_EVENT_NAME, EVENT_NAME_PURE_C), + _STR(COMMONFIELDS_IKEY, TEST_TOKEN) + ); + EXPECT_EQ(evt_log(survivor, event), STATUS_SUCCESS); + manager->RemoveEventListener(EVT_LOG_EVENT, listener); + EXPECT_EQ(accepted, 1); + ASSERT_EQ(evt_close(survivor), STATUS_SUCCESS); + EXPECT_EQ(capi_get_client(survivor), nullptr); + } + } +} + +TEST(APITest, C_API_DuplicateOpenRejectsRetiringManagerAfterFailedClose) +{ + const auto directory = "missing-capi-" + PAL::generateUuidString(); +#ifdef _WIN32 + const auto path = directory + "\\\\cache.db"; +#else + const auto path = directory + "/cache.db"; +#endif + const auto config = "{\"name\":\"capi-failed-close\",\"maxTeardownUploadTimeInSec\":0,\"cacheFilePath\":\"" + path + "\"}"; + const auto handle = evt_open(config.c_str()); + ASSERT_NE(handle, 0); + ASSERT_EQ(evt_pause(handle), STATUS_SUCCESS); + EXPECT_EQ(evt_open(config.c_str()), handle); + evt_prop event[] = TELEMETRY_EVENT( + _STR(COMMONFIELDS_EVENT_NAME, EVENT_NAME_PURE_C), + _STR(COMMONFIELDS_IKEY, TEST_TOKEN) + ); + ASSERT_EQ(evt_log(handle, event), STATUS_SUCCESS); + + ASSERT_EQ(evt_close(handle), STATUS_EFAIL); + auto client = capi_get_client(handle); + ASSERT_NE(client, nullptr); + EXPECT_EQ(evt_open(config.c_str()), 0); + EXPECT_NE(evt_log(handle, event), STATUS_SUCCESS); + EXPECT_EQ(client->logmanager->DeleteData(), STATUS_SUCCESS); + ASSERT_EQ(evt_close(handle), STATUS_SUCCESS); + EXPECT_EQ(capi_get_client(handle), nullptr); + + const auto reopened = evt_open(config.c_str()); + ASSERT_NE(reopened, 0); + EXPECT_EQ(evt_close(reopened), STATUS_SUCCESS); +} + #if defined(_WIN32) TEST(APITest, UTC_Callback_Test) { @@ -1254,18 +1353,17 @@ TEST(APITest, LogManager_BadStoragePath_Test) auto& config = LogManager::GetLogConfiguration(); config[CFG_INT_TRACE_LEVEL_MASK] = 0xFFFFFFFF; // API calls + Global mask for general messages - less SQL config[CFG_INT_TRACE_LEVEL_MIN] = ACTTraceLevel_Trace; - config[CFG_INT_MAX_TEARDOWN_TIME] = 16; + config[CFG_INT_MAX_TEARDOWN_TIME] = 0; + const std::string missingDirectory = GetTempDirectory() + "invalid-storage-" + PAL::generateUuidString(); std::vector paths = { #ifdef _WIN32 - "T:\\invalid\\file\\path", // This fails - no offline storage - u8"C:\\неправильный\\каталог\\utf-8", // This fails - no offline storage - u8"C:\\Проверка-проверка 1 2 3\\файл.db" // This should pass if dir exists + missingDirectory + "\\file.db", + missingDirectory + u8"\\каталог\\файл.db" #else - "/invalid/file/path", - u8"/неправильный/каталог/utf-8", // This fails - no offline storage - u8"/Проверка-проверка 1 2 3/файл.db" // This should pass if dir exists + missingDirectory + "/file.db", + missingDirectory + u8"/каталог/файл.db" #endif }; @@ -1274,13 +1372,22 @@ TEST(APITest, LogManager_BadStoragePath_Test) debugListener.storageFailed = false; config[CFG_STR_CACHE_FILE_PATH] = path.c_str(); ILogger *result = LogManager::Initialize(TEST_TOKEN, config); + ASSERT_NE(result, nullptr); LogManager::AddEventListener(DebugEventType::EVT_STORAGE_FAILED, debugListener); - EXPECT_EQ(true, (result != NULL)); + LogManager::PauseTransmission(); result->LogEvent("test"); LogManager::Flush(); - LogManager::FlushAndTeardown(); +#if HAVE_EXCEPTIONS + EXPECT_THROW(LogManager::FlushAndTeardown(), std::runtime_error); +#else + EXPECT_EQ(LogManager::FlushAndTeardown(), STATUS_EFAIL); +#endif + EXPECT_EQ(LogManager::GetLogger(), nullptr); + EXPECT_EQ(LogManager::Initialize(TEST_TOKEN, config), nullptr); LogManager::RemoveEventListener(DebugEventType::EVT_STORAGE_FAILED, debugListener); EXPECT_EQ(true, debugListener.storageFailed); + EXPECT_EQ(LogManager::DeleteData(), STATUS_SUCCESS); + ASSERT_EQ(LogManager::FlushAndTeardown(), STATUS_SUCCESS); } } diff --git a/tests/functests/BasicFuncTests.cpp b/tests/functests/BasicFuncTests.cpp index 7f231b07b..a66d03c28 100644 --- a/tests/functests/BasicFuncTests.cpp +++ b/tests/functests/BasicFuncTests.cpp @@ -44,27 +44,31 @@ namespace PAL_NS_BEGIN static long GetPalRefCount() { - return PAL::GetPAL().m_palStarted.load(); + auto& pal = PAL::GetPAL(); + std::lock_guard lock(pal.m_stateLock); + return static_cast(pal.m_palStarted); }; static std::shared_ptr GetTaskDispatcher() { - return PAL::GetPAL().m_taskDispatcher; + auto& pal = PAL::GetPAL(); + std::lock_guard lock(pal.m_stateLock); + return pal.m_taskDispatcher; }; static std::shared_ptr GetSystemInformation() { - return PAL::GetPAL().m_SystemInformation; + return PAL::GetPAL().GetSystemInformation(); } static std::shared_ptr GetNetworkInformation() { - return PAL::GetPAL().m_NetworkInformation; + return PAL::GetPAL().GetNetworkInformation(); } static std::shared_ptr GetDeviceInformation() { - return PAL::GetPAL().m_DeviceInformation; + return PAL::GetPAL().GetDeviceInformation(); } }; } diff --git a/tests/functests/MultipleLogManagersTests.cpp b/tests/functests/MultipleLogManagersTests.cpp index 420377442..024618621 100644 --- a/tests/functests/MultipleLogManagersTests.cpp +++ b/tests/functests/MultipleLogManagersTests.cpp @@ -13,6 +13,7 @@ #include "api/LogManagerFactory.hpp" #include "api/LogManagerImpl.hpp" +#include "utils/ZlibUtils.hpp" #include "CsProtocol_types.hpp" #include "bond/All.hpp" @@ -49,6 +50,8 @@ using namespace MAT; // iOS xctest gtest wrapper, so the exclusion must be at compile time.) #if !defined(TARGET_OS_IPHONE) || !TARGET_OS_IPHONE +constexpr static char final_event_name[] = "multi_manager_final_event"; + class RequestHandler : public HttpServer::Callback { public: @@ -58,6 +61,25 @@ class RequestHandler : public HttpServer::Callback { std::string expected_url = "/" + std::to_string(m_id) + "/"; EXPECT_EQ(request.uri, expected_url); + std::string body = request.content; + auto encoding = request.headers.find("Content-Encoding"); + if (encoding != request.headers.end()) + { + std::vector compressed(body.begin(), body.end()); + std::vector inflated; + if (ZlibUtils::InflateVector(compressed, inflated, encoding->second == "gzip")) + { + body.assign(inflated.begin(), inflated.end()); + } + else + { + body.clear(); + } + } + if (body.find(final_event_name) != std::string::npos) + { + m_receivedFinalEvent = true; + } m_count++; return 200; } @@ -66,8 +88,13 @@ class RequestHandler : public HttpServer::Callback return m_count; } + bool HasFinalEvent() const noexcept { + return m_receivedFinalEvent; + } + private: std::atomic m_count {}; + std::atomic m_receivedFinalEvent {}; int m_id ; }; @@ -147,18 +174,26 @@ class MultipleLogManagersTests : public ::testing::Test } } - void waitForRequestsSingleLogManager(unsigned timeout, unsigned expectedCount = 1) + bool waitForRequestsAndFinalEvent(unsigned timeout, size_t expectedCount) { - auto sz = callback1.GetRequestCount(); auto start = PAL::getUtcSystemTimeMs(); - while (callback1.GetRequestCount() - sz < expectedCount) + while (callback1.GetRequestCount() < expectedCount || !callback1.HasFinalEvent()) { if (PAL::getUtcSystemTimeMs() - start >= timeout) { - GTEST_FATAL_FAILURE_("Didn't receive request within given timeout"); + return false; } PAL::sleep(100); } + return true; + } + + template + bool startAndWaitForRequests(unsigned timeout, Action action) + { + auto expectedCount = callback1.GetRequestCount() + 2; + action(); + return waitForRequestsAndFinalEvent(timeout, expectedCount); } /* CsProtocol::ClientToCollectorRequest decodeRequest(HttpServer::Request const& request) @@ -212,6 +247,42 @@ TEST_F(MultipleLogManagersTests, ThreeInstancesCoexist) constexpr static unsigned max_iterations = 2000; +TEST_F(MultipleLogManagersTests, WaitIncludesRequestsReceivedBeforeWaiting) +{ + HttpServer::Request request {}; + HttpServer::Response response {}; + request.uri = "/1/"; + EXPECT_TRUE(startAndWaitForRequests(0, [&] { + request.content = final_event_name; + callback1.onHttpRequest(request, response); + request.content.clear(); + callback1.onHttpRequest(request, response); + })); +} + +TEST_F(MultipleLogManagersTests, WaitIgnoresRequestsBeforeStarting) +{ + HttpServer::Request request {}; + HttpServer::Response response {}; + request.uri = "/1/"; + callback1.onHttpRequest(request, response); + EXPECT_FALSE(startAndWaitForRequests(0, [&] { + request.content = final_event_name; + callback1.onHttpRequest(request, response); + })); +} + +TEST_F(MultipleLogManagersTests, WaitRequiresFinalEvent) +{ + HttpServer::Request request {}; + HttpServer::Response response {}; + request.uri = "/1/"; + EXPECT_FALSE(startAndWaitForRequests(0, [&] { + callback1.onHttpRequest(request, response); + callback1.onHttpRequest(request, response); + })); +} + TEST_F(MultipleLogManagersTests, MultiProcessesLogManager) { CAPTURE_PERF_STATS("start"); @@ -222,16 +293,17 @@ TEST_F(MultipleLogManagersTests, MultiProcessesLogManager) CAPTURE_PERF_STATS("LogManager created"); ILogger* logger = lm->GetLogger("aaa"); CAPTURE_PERF_STATS("Logger created"); - size_t numIterations = max_iterations; - while (numIterations--) - { - EventProperties props = CreateSampleEvent("event_name", EventPriority_Normal); - logger->LogEvent(props); - } - CAPTURE_PERF_STATS("Events Sent"); - lm->GetLogController()->UploadNow(); - CAPTURE_PERF_STATS("Events Uploaded"); - waitForRequestsSingleLogManager(20000, 2); + ASSERT_TRUE(startAndWaitForRequests(20000, [&] { + size_t numIterations = max_iterations; + while (numIterations--) + { + EventProperties props = CreateSampleEvent(numIterations == 0 ? final_event_name : "event_name", EventPriority_Normal); + logger->LogEvent(props); + } + CAPTURE_PERF_STATS("Events Sent"); + lm->GetLogController()->UploadNow(); + CAPTURE_PERF_STATS("Events Uploaded"); + })) << "Didn't receive two requests and the final event within the given timeout"; lm.reset(); CAPTURE_PERF_STATS("Log Manager deleted"); } diff --git a/tests/no-exceptions/no-exceptions-smoke.cpp b/tests/no-exceptions/no-exceptions-smoke.cpp index d85307af3..2e5e7fb9f 100644 --- a/tests/no-exceptions/no-exceptions-smoke.cpp +++ b/tests/no-exceptions/no-exceptions-smoke.cpp @@ -5,12 +5,16 @@ #include "LogConfiguration.hpp" #include "CorrelationVector.hpp" #include "TransmitProfiles.hpp" +#include "config/RuntimeConfig_Default.hpp" #include "http/HttpResponseDecoder.hpp" +#include "pal/PAL.hpp" #include "utils/ZlibUtils.hpp" +#include #include #include #include +#include #if HAVE_EXCEPTIONS #error This regression executable must be compiled without C++ exceptions. @@ -19,9 +23,25 @@ #error This regression executable requires JSON and zlib support. #endif +namespace +{ + std::atomic failNextNothrowArrayAllocation {false}; +} + +void* operator new[](std::size_t size, const std::nothrow_t&) noexcept +{ + if (failNextNothrowArrayAllocation.exchange(false)) + { + return nullptr; + } + return ::operator new[](size); +} + namespace clienttelemetry { namespace data { namespace v3 { + bool Compress(const char*, size_t, char**, size_t&, bool); + bool Compress(const char*, size_t, char**, size_t&, bool, char* (*)(size_t)); bool Expand(const char*, size_t, char**, size_t&, bool); bool Expand(const char*, size_t, char**, size_t&, bool, char* (*)(size_t)); } @@ -91,6 +111,22 @@ namespace int main() { + ILogConfiguration logConfiguration; + RuntimeConfig_Default runtimeConfiguration(logConfiguration); + PAL::PlatformAbstractionLayer pal; + pal.initialize(runtimeConfiguration); + pal.initialize(runtimeConfiguration); + check(pal.GetSystemInformation() && pal.GetDeviceInformation() && pal.GetNetworkInformation(), + "PAL initialization must publish all providers"); +#ifdef MATSDK_DISABLE_DEVICE_ID + check(pal.GetDeviceInformation()->GetDeviceId().empty(), "native device ID must remain disabled"); +#endif + pal.shutdown(); + check(pal.GetSystemInformation() != nullptr, "PAL must retain providers until its final shutdown"); + pal.shutdown(); + check(!pal.GetSystemInformation() && !pal.GetDeviceInformation() && !pal.GetNetworkInformation(), + "PAL final shutdown must release its providers"); + const char* invalidConfigurations[] = {nullptr, "", "[", "not-json", "null", "1", "\"text\"", "[]", "[{}]"}; for (const char* input : invalidConfigurations) { @@ -151,6 +187,14 @@ int main() "oversized expansion must fail"); check(output == nullptr && outputSize == 0, "failed expansion must clear outputs"); char previousOutput = 0; + for (size_t length = 1; length < sizeof(uint32_t); ++length) + { + output = &previousOutput; + outputSize = 32; + check(!clienttelemetry::data::v3::Expand(invalidCompressed, length, &output, outputSize, true), + "short size prefix must fail"); + check(output == nullptr && outputSize == 0, "short size prefix must clear outputs"); + } output = &previousOutput; outputSize = 32; static size_t requestedSize = 0; @@ -161,6 +205,30 @@ int main() }), "representable allocation failure must return false"); check(requestedSize == 32, "failure injection must reach the allocator"); check(output == nullptr && outputSize == 0, "allocation failure must clear an existing output and its length"); - std::puts("Passed no-exceptions configuration, response, profile, numeric-limit, and expansion smoke checks."); + output = &previousOutput; + outputSize = 32; + requestedSize = 0; + check(!clienttelemetry::data::v3::Compress(invalidCompressed, sizeof(invalidCompressed), &output, outputSize, false, + [](size_t size) -> char* { + requestedSize = size; + return nullptr; + }), "compression allocation failure must return false"); + check(requestedSize > sizeof(invalidCompressed), "compression failure injection must reach the allocator"); + check(output == nullptr && outputSize == 0, "failed compression must clear output and its length"); + output = &previousOutput; + outputSize = 32; + failNextNothrowArrayAllocation = true; + const bool compressed = clienttelemetry::data::v3::Compress( + invalidCompressed, sizeof(invalidCompressed), &output, outputSize, false); + check(!failNextNothrowArrayAllocation, "default compression must use the nothrow array allocator"); + check(!compressed && output == nullptr && outputSize == 0, + "default compression must report allocation failure without exceptions"); + output = &previousOutput; + outputSize = 32; + check(!clienttelemetry::data::v3::Compress(invalidCompressed, std::numeric_limits::max(), + &output, outputSize, true), + "unrepresentable compression size must fail"); + check(output == nullptr && outputSize == 0, "oversized compression must clear output and its length"); + std::puts("Passed no-exceptions configuration, response, profile, numeric-limit, and compression smoke checks."); return EXIT_SUCCESS; } diff --git a/tests/unittests/CMakeLists.txt b/tests/unittests/CMakeLists.txt index ff682427b..51186817d 100644 --- a/tests/unittests/CMakeLists.txt +++ b/tests/unittests/CMakeLists.txt @@ -68,6 +68,9 @@ set(MATSDK_UNIT_TEST_DEFINITIONS) if(NOT MSVC) set_source_files_properties(${SRCS} PROPERTIES COMPILE_FLAGS -Wno-deprecated-declarations) +else() + # The storage regression tests exceed the default COFF section limit. + set_source_files_properties(OfflineStorageTests.cpp PROPERTIES COMPILE_OPTIONS /bigobj) endif() # Enable Azure Monitor unit tests when the module is present. @@ -159,3 +162,8 @@ endif() add_test(NAME UnitTests COMMAND UnitTests "--gtest_output=xml:${PROJECT_BINARY_DIR}/test-reports/UnitTests.xml") set_tests_properties(UnitTests PROPERTIES WORKING_DIRECTORY "${PROJECT_BINARY_DIR}") + +if(NOT MATSDK_PLATFORM_IOS) + add_executable(zlib-allocation-test ../zlib-allocation-test.c) + add_test(NAME zlib-allocation-test COMMAND zlib-allocation-test) +endif() diff --git a/tests/unittests/LogManagerImplTests.cpp b/tests/unittests/LogManagerImplTests.cpp index 289bcc5a1..a74c8601c 100644 --- a/tests/unittests/LogManagerImplTests.cpp +++ b/tests/unittests/LogManagerImplTests.cpp @@ -4,7 +4,10 @@ // #include "api/LogManagerImpl.hpp" #include "common/Common.hpp" +#include "common/MockIOfflineStorage.hpp" +#include "LogManagerProvider.hpp" #include +#include using namespace testing; using namespace MAT; @@ -82,6 +85,119 @@ TEST(LogManagerImplTests, DeadLoggersAreDead) logger->LogEvent("DeadLoggerEvent"); } +#ifdef HAVE_MAT_STORAGE +TEST(LogManagerImplTests, FailedPerRecordShutdownCanBeRetriedBeforeRelease) +{ + ILogConfiguration configuration; + configuration[CFG_STR_FACTORY_NAME] = "storage-shutdown-retry"; + configuration[CFG_INT_MAX_TEARDOWN_TIME] = 0; + configuration[CFG_INT_RAM_QUEUE_SIZE] = 1024 * 1024; + configuration.AddModule(CFG_MODULE_HTTP_CLIENT, std::make_shared()); + auto disk = std::make_shared>(); + configuration.AddModule(CFG_MODULE_OFFLINE_STORAGE, disk); + + status_t status; + auto manager = LogManagerProvider::CreateLogManager(configuration, status); + ASSERT_EQ(status, STATUS_SUCCESS); + ASSERT_NE(manager, nullptr); + ASSERT_EQ(manager->PauseTransmission(), STATUS_SUCCESS); + auto logger = manager->GetLogger("test-tenant"); + ASSERT_NE(logger, nullptr); + logger->LogEvent("StorageShutdownRetry"); + + std::string failedRecord; + EXPECT_CALL(*disk, StoreRecord(_)).WillOnce(Invoke([&](StorageRecord const& record) { + failedRecord = record.id; + return false; + })); + EXPECT_CALL(*disk, Shutdown()).Times(0); +#if HAVE_EXCEPTIONS + EXPECT_THROW(manager->FlushAndTeardown(), std::runtime_error); +#else + manager->FlushAndTeardown(); +#endif + ASSERT_FALSE(failedRecord.empty()); + ASSERT_TRUE(Mock::VerifyAndClearExpectations(disk.get())); + + EXPECT_CALL(*disk, StoreRecord(Field(&StorageRecord::id, failedRecord))) + .WillOnce(Return(true)); + EXPECT_CALL(*disk, Shutdown()); + EXPECT_EQ(LogManagerProvider::Release(configuration), STATUS_SUCCESS); +} + +enum class ReleaseRoute { Exclusive, SharedByConfig, SharedByName }; + +class LogManagerFinalReleaseTests : public TestWithParam +{ +}; + +TEST_P(LogManagerFinalReleaseTests, FailedFinalFlushPreservesLeaseAndRetriesTheRecord) +{ + const auto route = GetParam(); + const bool shared = route != ReleaseRoute::Exclusive; + const std::string name = "final-release-" + std::to_string(static_cast(route)); + ILogConfiguration configuration; + configuration[CFG_STR_FACTORY_NAME] = name.c_str(); + if (shared) + { + configuration[CFG_MAP_FACTORY_CONFIG][CFG_STR_FACTORY_HOST] = name.c_str(); + } + configuration[CFG_INT_MAX_TEARDOWN_TIME] = 0; + configuration[CFG_INT_RAM_QUEUE_SIZE] = 1024 * 1024; + configuration.AddModule(CFG_MODULE_HTTP_CLIENT, std::make_shared()); + auto disk = std::make_shared>(); + configuration.AddModule(CFG_MODULE_OFFLINE_STORAGE, disk); + + status_t status; + auto manager = LogManagerProvider::CreateLogManager(configuration, status); + ASSERT_EQ(status, STATUS_SUCCESS); + ASSERT_NE(manager, nullptr); + ASSERT_EQ(manager->PauseTransmission(), STATUS_SUCCESS); + auto logger = manager->GetLogger("test-tenant"); + ASSERT_NE(logger, nullptr); + logger->LogEvent("FinalReleaseRetry"); + + ILogConfiguration guest; + guest[CFG_STR_FACTORY_NAME] = "final-release-guest"; + guest[CFG_MAP_FACTORY_CONFIG][CFG_STR_FACTORY_HOST] = name.c_str(); + EXPECT_CALL(*disk, Shutdown()).Times(0); + if (shared) + { + EXPECT_CALL(*disk, StoreRecord(_)).Times(0); + ASSERT_EQ(LogManagerProvider::CreateLogManager(guest, status), manager); + ASSERT_EQ(LogManagerProvider::Release(guest), STATUS_SUCCESS); + ASSERT_TRUE(Mock::VerifyAndClearExpectations(disk.get())); + EXPECT_CALL(*disk, Shutdown()).Times(0); + } + + const auto release = [&] { + return route == ReleaseRoute::SharedByName ? LogManagerProvider::Release(name.c_str()) + : LogManagerProvider::Release(configuration); + }; + std::string failedRecord; + EXPECT_CALL(*disk, StoreRecord(_)).WillOnce(Invoke([&](const StorageRecord& record) { + failedRecord = record.id; + EXPECT_EQ(release(), STATUS_EFAIL); + EXPECT_EQ(LogManagerProvider::CreateLogManager(shared ? guest : configuration, status), nullptr); + EXPECT_EQ(status, STATUS_EFAIL); + return false; + })); + ASSERT_EQ(release(), STATUS_EFAIL); + ASSERT_FALSE(failedRecord.empty()); + EXPECT_EQ(LogManagerProvider::CreateLogManager(shared ? guest : configuration, status), nullptr); + EXPECT_EQ(status, STATUS_EFAIL); + ASSERT_TRUE(Mock::VerifyAndClearExpectations(disk.get())); + + EXPECT_CALL(*disk, StoreRecord(Field(&StorageRecord::id, failedRecord))).WillOnce(Return(true)); + EXPECT_CALL(*disk, Shutdown()); + EXPECT_EQ(release(), STATUS_SUCCESS); + EXPECT_EQ(release(), STATUS_EFAIL); +} + +INSTANTIATE_TEST_SUITE_P(FactoryRoutes, LogManagerFinalReleaseTests, + Values(ReleaseRoute::Exclusive, ReleaseRoute::SharedByConfig, ReleaseRoute::SharedByName)); +#endif + TEST(LogManagerImplTests, NotPausedInitially) { ILogConfiguration configuration; diff --git a/tests/unittests/OfflineStorageTests.cpp b/tests/unittests/OfflineStorageTests.cpp index 9f3f5fc35..38b1d27c2 100644 --- a/tests/unittests/OfflineStorageTests.cpp +++ b/tests/unittests/OfflineStorageTests.cpp @@ -8,13 +8,20 @@ #include "offline/IOfflineStorageProvider.hpp" #include "offline/StorageObserver.hpp" #include "offline/MemoryStorage.hpp" +#include "pal/TaskDispatcher_CAPI.hpp" #include "NullObjects.hpp" #include +#include +#include #include +#include +#include #include +#include #include #include +#include #include #include @@ -186,6 +193,28 @@ namespace ILogConfiguration& GetLogConfiguration() override { return config; } }; + class CountingLogManager : public ConfigurableLogManager + { + public: + bool StartActivity() override + { + ++activityCount; + ++activeActivities; + return true; + } + + void EndActivity() override { --activeActivities; } + + std::atomic activityCount{0}; + std::atomic activeActivities{0}; + }; + + class PausedLogManager : public ConfigurableLogManager + { + public: + bool StartActivity() override { return false; } + }; + // Remove a SQLite db file along with its WAL-mode companion files // (-wal/-shm/-journal), which would otherwise accumulate in the temp dir. void RemoveDbFiles(const std::string& path) @@ -226,6 +255,89 @@ namespace } std::vector m_tasks; }; + + class ManualTaskDispatcher : public ITaskDispatcher + { + public: + enum class Behavior { Hold, Inline, Drop, ThrowOnce }; + + void Join() override + { + Take(); + } + + void Queue(Task* task) override + { + std::unique_ptr owned(task); + EXPECT_EQ(static_cast(task->Type), static_cast(Task::Call)); + const unsigned call = ++queueCalls; + if (beforeQueue) + { + beforeQueue(); + } + if (behavior == Behavior::Inline) + { + (*owned)(); + return; + } + if (behavior == Behavior::Drop) + { + return; + } +#if HAVE_EXCEPTIONS + if (behavior == Behavior::ThrowOnce && call == 1) + { + throw std::runtime_error("queue failed"); + } +#else + UNREFERENCED_PARAMETER(call); +#endif + std::lock_guard lock(m_mutex); + EXPECT_EQ(m_task, nullptr); + m_task = std::move(owned); + } + + bool Cancel(Task* task, uint64_t = 0) override + { + std::unique_ptr cancelled; + { + std::lock_guard lock(m_mutex); + if (m_task.get() != task) + { + return false; + } + cancelled = std::move(m_task); + } + return true; + } + + std::unique_ptr Take() + { + std::lock_guard lock(m_mutex); + return std::move(m_task); + } + + Behavior behavior = Behavior::Hold; + std::atomic queueCalls{0}; + std::function beforeQueue; + + private: + std::mutex m_mutex; + std::unique_ptr m_task; + }; + + void EVTSDK_LIBABI_CDECL QueueInlineCapiTask(evt_task_t* task, task_callback_fn_t callback) + { + EXPECT_EQ(task->delayMs, 0u); + callback(task->id); + } + + bool EVTSDK_LIBABI_CDECL CancelCapiTask(const char*) + { + return true; + } + + void EVTSDK_LIBABI_CDECL JoinCapiTasks() {} } namespace MAT_NS_BEGIN { @@ -391,6 +503,697 @@ TEST_P(OfflineStorageRetrievalExceptionTests, PartialRetrievalReleasesRecordsToT INSTANTIATE_TEST_SUITE_P(MemoryAndDisk, OfflineStorageRetrievalExceptionTests, Combine(Bool(), Bool())); #endif +class OfflineStorageLifecycleTests : public Test +{ +protected: + void SetUp() override + { + config[CFG_INT_RAM_QUEUE_SIZE] = 1; + config[CFG_BOOL_ENABLE_BATCHED_STORAGE_FLUSH] = true; + memory = std::make_shared(logManager, config); + disk = std::make_shared>(); + auto provider = std::make_shared(memory, disk); + handler.reset(new OfflineStorageHandler(logManager, config, dispatcher, provider)); + EXPECT_CALL(*disk, Initialize(Ref(*handler))); + handler->Initialize(observer); + } + + StorageRecord Record(const char* id) + { + return StorageRecord(id, "tenant-token", EventLatency_Normal, + EventPersistence_Normal, 1, std::vector{'x'}); + } + + bool StoreTwo() + { + return handler->StoreRecord(Record("first")) && handler->StoreRecord(Record("second")); + } + + void ExpectSaved(size_t count) + { + EXPECT_CALL(*disk, StoreRecords(_)) + .WillOnce(Invoke([count](std::vector& records) + { + EXPECT_EQ(records.size(), count); + return records.size(); + })); + EXPECT_CALL(observer, OnStorageRecordsSaved(count)); + } + + CountingLogManager logManager; + NiceMock config; + ManualTaskDispatcher dispatcher; + StrictMock observer; + std::shared_ptr memory; + std::shared_ptr> disk; + std::unique_ptr handler; +}; + +TEST_F(OfflineStorageLifecycleTests, ShutdownCancelsQueuedFlushAndPersistsRecords) +{ + ASSERT_TRUE(StoreTwo()); + ExpectSaved(2); + EXPECT_CALL(*disk, Shutdown()); + + std::promise finished; + auto done = finished.get_future(); + std::thread shutdown([&] { + handler->Shutdown(); + finished.set_value(); + }); + const auto status = done.wait_for(std::chrono::seconds(5)); + if (status != std::future_status::ready) + { + auto task = dispatcher.Take(); + if (task) + { + (*task)(); + } + } + shutdown.join(); + EXPECT_EQ(status, std::future_status::ready); + EXPECT_EQ(dispatcher.Take(), nullptr); + EXPECT_FALSE(handler->StoreRecord(Record("after-shutdown"))); + const unsigned activitiesAfterShutdown = logManager.activityCount.load(); + handler->Flush(); + EXPECT_EQ(logManager.activityCount.load(), activitiesAfterShutdown); +} + +TEST_F(OfflineStorageLifecycleTests, ShutdownWaitsForDirectFlushObserver) +{ + ASSERT_TRUE(StoreTwo()); + auto task = dispatcher.Take(); + ASSERT_NE(task, nullptr); + std::promise entered; + auto enteredFuture = entered.get_future(); + std::promise release; + auto releaseFuture = release.get_future().share(); + std::atomic shutdownCalls{0}; + EXPECT_CALL(*disk, StoreRecords(_)) + .WillOnce(Invoke([](std::vector& records) { return records.size(); })); + EXPECT_CALL(observer, OnStorageRecordsSaved(2)) + .WillOnce(Invoke([&](size_t) { + entered.set_value(); + releaseFuture.wait(); + })); + EXPECT_CALL(*disk, Shutdown()).WillOnce(Invoke([&] { ++shutdownCalls; })); + + std::thread flush([&] { handler->Flush(); }); + if (enteredFuture.wait_for(std::chrono::seconds(5)) != std::future_status::ready) + { + release.set_value(); + flush.join(); + FAIL() << "Direct flush did not notify its observer"; + } + std::promise started; + auto startedFuture = started.get_future(); + std::promise finished; + auto done = finished.get_future(); + std::thread shutdown([&] { + started.set_value(); + handler->Shutdown(); + finished.set_value(); + }); + startedFuture.wait(); + EXPECT_EQ(done.wait_for(std::chrono::milliseconds(200)), std::future_status::timeout); + EXPECT_EQ(shutdownCalls.load(), 0u); + release.set_value(); + flush.join(); + shutdown.join(); + EXPECT_EQ(done.wait_for(std::chrono::seconds(0)), std::future_status::ready); + const unsigned activitiesAfterShutdown = logManager.activityCount.load(); + (*task)(); + EXPECT_EQ(logManager.activityCount.load(), activitiesAfterShutdown); +} + +TEST_F(OfflineStorageLifecycleTests, ConcurrentShutdownRunsStorageShutdownOnce) +{ + std::promise entered; + auto enteredFuture = entered.get_future(); + std::promise release; + auto releaseFuture = release.get_future().share(); + EXPECT_CALL(*disk, Shutdown()).WillOnce(Invoke([&] { + entered.set_value(); + releaseFuture.wait(); + })); + + std::thread first([&] { handler->Shutdown(); }); + if (enteredFuture.wait_for(std::chrono::seconds(5)) != std::future_status::ready) + { + release.set_value(); + first.join(); + FAIL() << "First shutdown did not reach storage"; + } + std::promise started; + auto startedFuture = started.get_future(); + std::promise finished; + auto done = finished.get_future(); + std::thread second([&] { + started.set_value(); + handler->Shutdown(); + finished.set_value(); + }); + startedFuture.wait(); + EXPECT_EQ(done.wait_for(std::chrono::milliseconds(200)), std::future_status::timeout); + release.set_value(); + first.join(); + second.join(); + EXPECT_EQ(done.wait_for(std::chrono::seconds(0)), std::future_status::ready); + handler->Shutdown(); +} + +TEST_F(OfflineStorageLifecycleTests, ShutdownWaitsForRunningFlush) +{ + ASSERT_TRUE(StoreTwo()); + auto task = dispatcher.Take(); + ASSERT_NE(task, nullptr); + std::promise entered; + auto enteredFuture = entered.get_future(); + std::promise release; + auto releaseFuture = release.get_future().share(); + std::atomic batchCalls{0}; + std::atomic directlyStored{0}; + EXPECT_CALL(*disk, StoreRecords(_)) + .WillRepeatedly(Invoke([&](std::vector& records) { + if (++batchCalls == 1) + { + entered.set_value(); + releaseFuture.wait(); + } + return records.size(); + })); + EXPECT_CALL(*disk, StoreRecord(_)) + .WillRepeatedly(Invoke([&](StorageRecord const&) { + ++directlyStored; + return true; + })); + EXPECT_CALL(observer, OnStorageRecordsSaved(_)).Times(AtLeast(1)); + EXPECT_CALL(*disk, Shutdown()); + + std::thread worker([task = std::move(task)] { (*task)(); }); + if (enteredFuture.wait_for(std::chrono::seconds(5)) != std::future_status::ready) + { + release.set_value(); + worker.join(); + FAIL() << "Scheduled flush did not enter storage"; + } + std::promise started; + auto startedFuture = started.get_future(); + std::promise finished; + auto done = finished.get_future(); + std::thread shutdown([&] { + started.set_value(); + handler->Shutdown(); + finished.set_value(); + }); + startedFuture.wait(); + for (unsigned i = 0; i < 500 && directlyStored.load() == 0; ++i) + { + auto id = "probe-" + std::to_string(i); + handler->StoreRecord(Record(id.c_str())); + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + EXPECT_EQ(directlyStored.load(), 1u); + EXPECT_EQ(done.wait_for(std::chrono::seconds(0)), std::future_status::timeout); + release.set_value(); + worker.join(); + shutdown.join(); + EXPECT_EQ(done.wait_for(std::chrono::seconds(0)), std::future_status::ready); +} + +TEST_F(OfflineStorageLifecycleTests, StoresDuringDrainReachDiskBeforeShutdown) +{ + ASSERT_TRUE(handler->StoreRecord(Record("first"))); + std::promise entered; + auto enteredFuture = entered.get_future(); + std::promise release; + auto releaseFuture = release.get_future().share(); + dispatcher.beforeQueue = [&] { + entered.set_value(); + releaseFuture.wait(); + }; + std::atomic directlyStored{0}; + size_t batched = 0; + EXPECT_CALL(*disk, StoreRecord(_)) + .WillRepeatedly(Invoke([&](StorageRecord const&) { + ++directlyStored; + return true; + })); + EXPECT_CALL(*disk, StoreRecords(_)) + .WillOnce(Invoke([&](std::vector& records) { + batched = records.size(); + return records.size(); + })); + EXPECT_CALL(observer, OnStorageRecordsSaved(_)); + EXPECT_CALL(*disk, Shutdown()); + + std::thread producer([&] { EXPECT_TRUE(handler->StoreRecord(Record("second"))); }); + if (enteredFuture.wait_for(std::chrono::seconds(5)) != std::future_status::ready) + { + release.set_value(); + producer.join(); + FAIL() << "Store did not reach task submission"; + } + std::promise started; + auto startedFuture = started.get_future(); + std::promise finished; + auto done = finished.get_future(); + std::thread shutdown([&] { + started.set_value(); + handler->Shutdown(); + finished.set_value(); + }); + startedFuture.wait(); + size_t accepted = 2; + for (unsigned i = 0; i < 500 && directlyStored.load() == 0; ++i) + { + auto id = "during-drain-" + std::to_string(i); + if (handler->StoreRecord(Record(id.c_str()))) + { + ++accepted; + } + std::this_thread::sleep_for(std::chrono::milliseconds(10)); + } + EXPECT_EQ(directlyStored.load(), 1u); + EXPECT_EQ(done.wait_for(std::chrono::seconds(0)), std::future_status::timeout); + release.set_value(); + producer.join(); + shutdown.join(); + EXPECT_EQ(batched + directlyStored.load(), accepted); + EXPECT_EQ(dispatcher.Take(), nullptr); +} + +TEST_F(OfflineStorageLifecycleTests, DroppedTaskAllowsAnotherFlushToBeScheduled) +{ + dispatcher.behavior = ManualTaskDispatcher::Behavior::Drop; + ASSERT_TRUE(StoreTwo()); + ASSERT_TRUE(handler->StoreRecord(Record("third"))); + EXPECT_EQ(dispatcher.queueCalls.load(), 2u); + ExpectSaved(3); + EXPECT_CALL(*disk, Shutdown()); + handler->Shutdown(); +} + +TEST_F(OfflineStorageLifecycleTests, InlineDispatcherRunsFlushWithoutDeadlock) +{ + dispatcher.behavior = ManualTaskDispatcher::Behavior::Inline; + ExpectSaved(2); + ASSERT_TRUE(StoreTwo()); + EXPECT_EQ(dispatcher.queueCalls.load(), 1u); + EXPECT_CALL(*disk, Shutdown()); + handler->Shutdown(); +} + +#if HAVE_EXCEPTIONS +TEST_F(OfflineStorageLifecycleTests, FailedQueueDoesNotBlockLaterScheduling) +{ + dispatcher.behavior = ManualTaskDispatcher::Behavior::ThrowOnce; + ASSERT_TRUE(handler->StoreRecord(Record("first"))); + EXPECT_THROW(handler->StoreRecord(Record("second")), std::runtime_error); + ASSERT_TRUE(handler->StoreRecord(Record("third"))); + EXPECT_EQ(dispatcher.queueCalls.load(), 2u); + ExpectSaved(3); + EXPECT_CALL(*disk, Shutdown()); + handler->Shutdown(); +} + +TEST_F(OfflineStorageLifecycleTests, FailedDirectFlushReleasesActivityAndCanBeRetried) +{ + ASSERT_TRUE(StoreTwo()); + EXPECT_CALL(*disk, StoreRecords(_)) + .WillOnce(Invoke([](std::vector& records) -> size_t { + records.clear(); + throw std::runtime_error("disk write failed"); + })) + .WillOnce(Invoke([](std::vector& records) { return records.size(); })); + EXPECT_CALL(observer, OnStorageRecordsSaved(2)); + EXPECT_THROW(handler->Flush(), std::runtime_error); + EXPECT_EQ(logManager.activeActivities.load(), 0); + EXPECT_EQ(memory->GetRecordCount(), 2u); + handler->Flush(); + EXPECT_EQ(logManager.activeActivities.load(), 0); + EXPECT_EQ(memory->GetRecordCount(), 0u); + EXPECT_CALL(*disk, Shutdown()); + handler->Shutdown(); +} + +TEST_F(OfflineStorageLifecycleTests, ConcurrentShutdownRetriesFailedAttempt) +{ + std::promise entered; + auto enteredFuture = entered.get_future(); + std::promise release; + auto releaseFuture = release.get_future().share(); + EXPECT_CALL(*disk, Shutdown()) + .WillOnce(Invoke([&] { + entered.set_value(); + releaseFuture.wait(); + throw std::runtime_error("shutdown failed"); + })) + .WillOnce(Return()); + + std::thread first([&] { EXPECT_THROW(handler->Shutdown(), std::runtime_error); }); + if (enteredFuture.wait_for(std::chrono::seconds(5)) != std::future_status::ready) + { + release.set_value(); + first.join(); + FAIL() << "First shutdown did not reach storage"; + } + std::promise started; + auto startedFuture = started.get_future(); + std::promise finished; + auto done = finished.get_future(); + std::thread second([&] { + started.set_value(); + EXPECT_NO_THROW(handler->Shutdown()); + finished.set_value(); + }); + startedFuture.wait(); + EXPECT_EQ(done.wait_for(std::chrono::milliseconds(200)), std::future_status::timeout); + release.set_value(); + first.join(); + second.join(); + EXPECT_EQ(done.wait_for(std::chrono::seconds(0)), std::future_status::ready); + handler->Shutdown(); +} + +TEST_F(OfflineStorageLifecycleTests, FailedShutdownFlushCanBeRetried) +{ + ASSERT_TRUE(StoreTwo()); + EXPECT_CALL(*disk, StoreRecords(_)) + .WillOnce(Throw(std::runtime_error("disk write failed"))) + .WillOnce(Invoke([](std::vector& records) { return records.size(); })); + EXPECT_CALL(observer, OnStorageRecordsSaved(2)); + EXPECT_CALL(*disk, Shutdown()); + EXPECT_THROW(handler->Shutdown(), std::runtime_error); + EXPECT_EQ(memory->GetRecordCount(), 2u); + handler->Shutdown(); + EXPECT_EQ(memory->GetRecordCount(), 0u); +} + +TEST_F(OfflineStorageLifecycleTests, ReinitializeRetriesFailedShutdownBeforeReplacingStorage) +{ + ASSERT_TRUE(StoreTwo()); + EXPECT_CALL(*disk, StoreRecords(_)) + .WillOnce(Throw(std::runtime_error("disk write failed"))) + .WillOnce(Invoke([](std::vector& records) { return records.size(); })); + EXPECT_CALL(observer, OnStorageRecordsSaved(2)); + EXPECT_CALL(*disk, Shutdown()).Times(2); + EXPECT_THROW(handler->Shutdown(), std::runtime_error); + EXPECT_CALL(*disk, Initialize(Ref(*handler))); + handler->Initialize(observer); + EXPECT_EQ(memory->GetRecordCount(), 0u); + handler->Shutdown(); +} + +TEST(OfflineStorageHandlerFlushTests, RetryingDiskShutdownDoesNotRepeatMemoryShutdown) +{ + ConfigurableLogManager logManager; + NiceMock config; + ManualTaskDispatcher dispatcher; + StrictMock observer; + config[CFG_INT_RAM_QUEUE_SIZE] = 1024 * 1024; + config[CFG_BOOL_ENABLE_BATCHED_STORAGE_FLUSH] = true; + auto memory = std::make_shared>(); + auto disk = std::make_shared>(); + auto provider = std::make_shared(memory, disk); + OfflineStorageHandler handler(logManager, config, dispatcher, provider); + EXPECT_CALL(*disk, Initialize(Ref(handler))); + EXPECT_CALL(*memory, Initialize(Ref(handler))); + handler.Initialize(observer); + EXPECT_CALL(*memory, GetSize()).WillOnce(Return(0)); + EXPECT_CALL(*memory, Shutdown()).Times(1); + EXPECT_CALL(*disk, Shutdown()) + .WillOnce(Throw(std::runtime_error("shutdown failed"))) + .WillOnce(Return()); + EXPECT_THROW(handler.Shutdown(), std::runtime_error); + handler.Shutdown(); +} +#endif + +TEST_F(OfflineStorageLifecycleTests, PartialBatchMutationRetainsRecordsForRetry) +{ + ASSERT_TRUE(StoreTwo()); + EXPECT_CALL(*disk, StoreRecords(_)) + .WillOnce(Invoke([](std::vector& records) -> size_t { + records.clear(); + return 1; + })) + .WillOnce(Invoke([](std::vector& records) { + EXPECT_EQ(records.size(), 2u); + return records.size(); + })); + EXPECT_CALL(observer, OnStorageRecordsSaved(1)); + EXPECT_CALL(observer, OnStorageRecordsSaved(2)); + handler->Flush(); + EXPECT_EQ(memory->GetRecordCount(), 2u); + handler->Flush(); + EXPECT_EQ(memory->GetRecordCount(), 0u); + EXPECT_CALL(*disk, Shutdown()); + handler->Shutdown(); +} + +TEST_F(OfflineStorageLifecycleTests, ShortShutdownWritesRetainStorageUntilReinitializeCanFlush) +{ + ASSERT_TRUE(StoreTwo()); + EXPECT_CALL(*disk, StoreRecords(_)) + .WillOnce(Return(0)) + .WillOnce(Return(1)); + EXPECT_CALL(observer, OnStorageRecordsSaved(0)); + EXPECT_CALL(observer, OnStorageRecordsSaved(1)); + +#if HAVE_EXCEPTIONS + EXPECT_THROW(handler->Shutdown(), std::runtime_error); +#else + handler->Shutdown(); +#endif + EXPECT_EQ(memory->GetRecordCount(), 2u); +#if HAVE_EXCEPTIONS + EXPECT_THROW(handler->Initialize(observer), std::runtime_error); +#else + handler->Initialize(observer); +#endif + EXPECT_EQ(memory->GetRecordCount(), 2u); + + ExpectSaved(2); + EXPECT_CALL(*disk, Shutdown()).Times(2); + EXPECT_CALL(*disk, Initialize(Ref(*handler))); + handler->Initialize(observer); + EXPECT_EQ(memory->GetRecordCount(), 0u); + handler->Shutdown(); +} + +TEST_F(OfflineStorageLifecycleTests, SavedObserverCanWaitForAnotherFlush) +{ + ASSERT_TRUE(StoreTwo()); + EXPECT_CALL(*disk, StoreRecords(_)) + .WillOnce(Invoke([](std::vector& records) { return records.size(); })); + std::promise finished; + auto done = finished.get_future(); + std::thread nested; + EXPECT_CALL(observer, OnStorageRecordsSaved(2)) + .WillOnce(Invoke([&](size_t) { + nested = std::thread([&] { + handler->Flush(); + finished.set_value(); + }); + EXPECT_EQ(done.wait_for(std::chrono::seconds(5)), std::future_status::ready); + })); + handler->Flush(); + if (nested.joinable()) + { + nested.join(); + } + EXPECT_CALL(*disk, Shutdown()); + handler->Shutdown(); +} + +TEST_F(OfflineStorageLifecycleTests, ReinitializeWithoutMemoryCacheStoresDirectlyToDisk) +{ + config[CFG_INT_RAM_QUEUE_SIZE] = 0; + EXPECT_CALL(*disk, Shutdown()); + EXPECT_CALL(*disk, Initialize(Ref(*handler))); + handler->Initialize(observer); + + EXPECT_CALL(*disk, StoreRecord(_)).WillOnce(Return(true)); + EXPECT_TRUE(handler->StoreRecord(Record("direct"))); + EXPECT_EQ(memory->GetRecordCount(), 0u); + + EXPECT_CALL(*disk, Shutdown()); + handler->Shutdown(); +} + +TEST_F(OfflineStorageLifecycleTests, OldDequeuedTaskStaysInertAfterReinitialize) +{ + ASSERT_TRUE(StoreTwo()); + auto oldTask = dispatcher.Take(); + ASSERT_NE(oldTask, nullptr); + ExpectSaved(2); + EXPECT_CALL(*disk, Shutdown()); + handler->Shutdown(); + + EXPECT_CALL(*disk, Initialize(Ref(*handler))); + handler->Initialize(observer); + ASSERT_TRUE(StoreTwo()); + const unsigned activitiesBeforeTask = logManager.activityCount.load(); + (*oldTask)(); + oldTask.reset(); + EXPECT_EQ(logManager.activityCount.load(), activitiesBeforeTask); + auto currentTask = dispatcher.Take(); + ASSERT_NE(currentTask, nullptr); + ExpectSaved(2); + (*currentTask)(); + EXPECT_GT(logManager.activityCount.load(), activitiesBeforeTask); + EXPECT_EQ(memory->GetRecordCount(), 0u); + EXPECT_CALL(*disk, Shutdown()); + handler->Shutdown(); +} + +TEST_F(OfflineStorageLifecycleTests, ReinitializeWhileAcceptingClosesOldGeneration) +{ + ASSERT_TRUE(StoreTwo()); + auto oldTask = dispatcher.Take(); + ASSERT_NE(oldTask, nullptr); + ExpectSaved(2); + EXPECT_CALL(*disk, Shutdown()); + EXPECT_CALL(*disk, Initialize(Ref(*handler))); + handler->Initialize(observer); + + ASSERT_TRUE(StoreTwo()); + const unsigned activitiesBeforeTask = logManager.activityCount.load(); + (*oldTask)(); + oldTask.reset(); + EXPECT_EQ(logManager.activityCount.load(), activitiesBeforeTask); + auto currentTask = dispatcher.Take(); + ASSERT_NE(currentTask, nullptr); + ExpectSaved(2); + (*currentTask)(); + EXPECT_EQ(memory->GetRecordCount(), 0u); + EXPECT_CALL(*disk, Shutdown()); + handler->Shutdown(); +} + +TEST_F(OfflineStorageLifecycleTests, OldCompletionDoesNotClearNewerQueuedFlush) +{ + ASSERT_TRUE(StoreTwo()); + auto oldTask = dispatcher.Take(); + ASSERT_NE(oldTask, nullptr); + std::promise entered; + auto enteredFuture = entered.get_future(); + std::promise release; + auto releaseFuture = release.get_future().share(); + EXPECT_CALL(*disk, StoreRecords(_)) + .WillOnce(Invoke([&](std::vector& records) { + entered.set_value(); + releaseFuture.wait(); + return records.size(); + })) + .WillOnce(Invoke([](std::vector& records) { return records.size(); })); + EXPECT_CALL(observer, OnStorageRecordsSaved(2)).Times(2); + std::thread worker([task = std::move(oldTask)] { (*task)(); }); + if (enteredFuture.wait_for(std::chrono::seconds(5)) != std::future_status::ready) + { + release.set_value(); + worker.join(); + FAIL() << "Scheduled flush did not enter storage"; + } + EXPECT_TRUE(handler->StoreRecord(Record("third"))); + EXPECT_TRUE(handler->StoreRecord(Record("fourth"))); + release.set_value(); + worker.join(); + auto newTask = dispatcher.Take(); + ASSERT_NE(newTask, nullptr); + (*newTask)(); + EXPECT_EQ(memory->GetRecordCount(), 0u); + EXPECT_CALL(*disk, Shutdown()); + handler->Shutdown(); +} + +TEST(OfflineStorageHandlerFlushTests, ShutdownFlushesWhenActivitiesArePaused) +{ + PausedLogManager logManager; + NiceMock config; + ManualTaskDispatcher dispatcher; + StrictMock observer; + config[CFG_INT_RAM_QUEUE_SIZE] = 1024 * 1024; + config[CFG_BOOL_ENABLE_BATCHED_STORAGE_FLUSH] = true; + auto memory = std::make_shared(logManager, config); + auto disk = std::make_shared>(); + auto provider = std::make_shared(memory, disk); + OfflineStorageHandler handler(logManager, config, dispatcher, provider); + EXPECT_CALL(*disk, Initialize(Ref(handler))); + handler.Initialize(observer); + StorageRecord record("event", "tenant-token", EventLatency_Normal, + EventPersistence_Normal, 1, std::vector{'x'}); + ASSERT_TRUE(handler.StoreRecord(record)); + handler.Flush(); + EXPECT_CALL(*disk, StoreRecords(_)).WillOnce(Return(1)); + EXPECT_CALL(observer, OnStorageRecordsSaved(1)); + EXPECT_CALL(*disk, Shutdown()); + handler.Shutdown(); +} + +TEST(OfflineStorageHandlerFlushTests, CapiDispatcherReceivesImmediateFlush) +{ + ConfigurableLogManager logManager; + NiceMock config; + PAL::TaskDispatcher_CAPI dispatcher(&QueueInlineCapiTask, &CancelCapiTask, &JoinCapiTasks); + StrictMock observer; + config[CFG_INT_RAM_QUEUE_SIZE] = 1; + config[CFG_BOOL_ENABLE_BATCHED_STORAGE_FLUSH] = true; + auto memory = std::make_shared(logManager, config); + auto disk = std::make_shared>(); + auto provider = std::make_shared(memory, disk); + OfflineStorageHandler handler(logManager, config, dispatcher, provider); + EXPECT_CALL(*disk, Initialize(Ref(handler))); + handler.Initialize(observer); + EXPECT_CALL(*disk, StoreRecords(_)).WillOnce(Return(2)); + EXPECT_CALL(observer, OnStorageRecordsSaved(2)); + StorageRecord first("first", "tenant-token", EventLatency_Normal, + EventPersistence_Normal, 1, std::vector{'x'}); + StorageRecord second("second", "tenant-token", EventLatency_Normal, + EventPersistence_Normal, 1, std::vector{'y'}); + ASSERT_TRUE(handler.StoreRecord(first)); + ASSERT_TRUE(handler.StoreRecord(second)); + EXPECT_CALL(*disk, Shutdown()); + handler.Shutdown(); +} + +TEST(OfflineStorageHandlerFlushTests, DequeuedFlushCannotRunAfterShutdown) +{ + CountingLogManager logManager; + NiceMock config; + ManualTaskDispatcher dispatcher; + StrictMock observer; + config[CFG_INT_RAM_QUEUE_SIZE] = 1; + config[CFG_BOOL_ENABLE_BATCHED_STORAGE_FLUSH] = true; + auto memory = std::make_shared(logManager, config); + auto disk = std::make_shared>(); + auto provider = std::make_shared(memory, disk); + OfflineStorageHandler handler(logManager, config, dispatcher, provider); + EXPECT_CALL(*disk, Initialize(Ref(handler))); + handler.Initialize(observer); + + StorageRecord first("first", "tenant-token", EventLatency_Normal, + EventPersistence_Normal, 1, std::vector{'x'}); + StorageRecord second("second", "tenant-token", EventLatency_Normal, + EventPersistence_Normal, 1, std::vector{'y'}); + ASSERT_TRUE(handler.StoreRecord(first)); + ASSERT_TRUE(handler.StoreRecord(second)); + auto task = dispatcher.Take(); + ASSERT_NE(task, nullptr); + + EXPECT_CALL(*disk, StoreRecords(_)) + .WillOnce(Invoke([](std::vector& records) { return records.size(); })); + EXPECT_CALL(observer, OnStorageRecordsSaved(2)); + handler.Flush(); + + EXPECT_CALL(*disk, Shutdown()); + handler.Shutdown(); + const unsigned activitiesBeforeTask = logManager.activityCount.load(); + (*task)(); + EXPECT_EQ(logManager.activityCount.load(), activitiesBeforeTask); +} + TEST(OfflineStorageHandlerFlushTests, FailedMemoryRequeueIsReportedAndDropped) { NullLogManager logManager; @@ -512,7 +1315,12 @@ TEST(OfflineStorageHandlerFlushTests, BatchedFlushKeepsMemoryOnlyRecordsOffDisk) EXPECT_CALL(*memory, StoreRecord(Field(&StorageRecord::id, "memory-only"))) .WillOnce(Return(true)); EXPECT_CALL(*disk, StoreRecord(_)).Times(0); - EXPECT_CALL(*disk, StoreRecords(_)).WillOnce(Return(1)); + EXPECT_CALL(*disk, StoreRecords(_)) + .WillOnce(Invoke([](std::vector& batch) -> size_t { + EXPECT_THAT(batch, ElementsAre(Field(&StorageRecord::id, "persisted"))); + batch.clear(); + return 1; + })); EXPECT_CALL(observer, OnStorageRecordsSaved(1)); handler.Flush(); @@ -854,7 +1662,12 @@ TEST(OfflineStorageHandlerFlushTests, FailedDiskStoreDuringFlushReturnsRecordsTo // returned to the in-memory queue rather than silently dropped. EXPECT_EQ(handler.GetRecordCount(), kCount); +#if HAVE_EXCEPTIONS + EXPECT_THROW(handler.Shutdown(), std::runtime_error); +#else handler.Shutdown(); +#endif + EXPECT_EQ(handler.GetRecordCount(), kCount); } TEST(OfflineStorageHandlerFlushTests, EventLatencyOffIsDroppedWithoutReportingStoreFailure) diff --git a/tests/unittests/OfflineStorageTests_SQLite.cpp b/tests/unittests/OfflineStorageTests_SQLite.cpp index 79f631c83..38cf8082d 100644 --- a/tests/unittests/OfflineStorageTests_SQLite.cpp +++ b/tests/unittests/OfflineStorageTests_SQLite.cpp @@ -1135,6 +1135,69 @@ TEST_F(OfflineStorageTests_SQLite, ResizeDbCompactsThePhysicalDatabase) EXPECT_LE(offlineStorage->GetSize(), maximumSize); } +TEST_F(OfflineStorageTests_SQLite, BatchStorageLimitRequiresMultipleTrims) +{ + constexpr size_t maximumSize = 5 * 1024 * 1024; + EXPECT_CALL(configMock, GetOfflineStorageMaximumSizeBytes()) + .WillRepeatedly(Return(maximumSize)); + configMock[CFG_BOOL_ENABLE_DB_DROP_IF_FULL] = true; + initializeStorage(false); + + std::vector records; + for (int i = 0; i < 15; ++i) + { + records.push_back({ + "record-" + std::to_string(i), + "token", + EventLatency_Normal, + EventPersistence_Normal, + i + 1, + StorageBlob(512 * 1024) }); + } + + ASSERT_THAT(offlineStorage->StoreRecords(records), records.size()); + EXPECT_LE(offlineStorage->GetSize(), maximumSize); + EXPECT_GT(offlineStorage->GetRecordCount(EventLatency_Unspecified), size_t { 0 }); +} + +TEST_F(OfflineStorageTests_SQLite, BatchStorageLimitKeepsTrimmingWhenOnlyRecordCountDrops) +{ + sqlite3* db = nullptr; + ASSERT_EQ(sqlite3_open(storageFilename.c_str(), &db), SQLITE_OK); + const int result = sqlite3_exec(db, "PRAGMA page_size=65536; PRAGMA auto_vacuum=FULL; VACUUM;", nullptr, nullptr, nullptr); + const int closeResult = sqlite3_close(db); + ASSERT_EQ(result, SQLITE_OK); + ASSERT_EQ(closeResult, SQLITE_OK); + + constexpr size_t maximumSize = 512 * 1024; + EXPECT_CALL(configMock, GetOfflineStorageMaximumSizeBytes()).WillRepeatedly(Return(maximumSize)); + configMock[CFG_BOOL_ENABLE_DB_DROP_IF_FULL] = false; + initializeStorage(false); + + std::vector records; + for (int i = 0; i < 40; ++i) + { + records.emplace_back("small-" + std::to_string(i), "token", EventLatency_Normal, + EventPersistence_Normal, i + 1, StorageBlob(1)); + } + records.emplace_back("large", "token", EventLatency_Normal, + EventPersistence_Normal, 41, StorageBlob(4 * 65536)); + ASSERT_EQ(offlineStorage->StoreRecords(records), records.size()); + + const size_t oversized = offlineStorage->GetSize(); + ASSERT_GT(oversized, maximumSize); + ASSERT_LE(oversized, 2 * maximumSize); + ASSERT_TRUE(offlineStorage->ResizeDb()); + ASSERT_LT(offlineStorage->GetRecordCount(EventLatency_Unspecified), records.size()); + ASSERT_EQ(offlineStorage->GetSize(), oversized); + + configMock[CFG_BOOL_ENABLE_DB_DROP_IF_FULL] = true; + std::vector next{{"next", "token", EventLatency_Normal, + EventPersistence_Normal, 42, StorageBlob(1)}}; + ASSERT_EQ(offlineStorage->StoreRecords(next), 1u); + EXPECT_LE(offlineStorage->GetSize(), maximumSize); +} + TEST_F(OfflineStorageTests_SQLite, StorageLimitIncludesLargePageOverhead) { sqlite3* db = nullptr; diff --git a/tests/unittests/PalTests.cpp b/tests/unittests/PalTests.cpp index 9d4ba3891..86fae96aa 100644 --- a/tests/unittests/PalTests.cpp +++ b/tests/unittests/PalTests.cpp @@ -4,12 +4,16 @@ // #include "common/Common.hpp" +#include "config/RuntimeConfig_Default.hpp" +#include "pal/PAL.hpp" #include "pal/PseudoRandomGenerator.hpp" #include "pal/TaskDispatcher.hpp" #include "pal/WorkerThread.hpp" +#include "NullObjects.hpp" #include "Version.hpp" #include +#include #include #include #include @@ -22,13 +26,12 @@ #include #include #include +#include +#include #ifdef HAVE_MAT_LOGGING -#include "pal/PAL.hpp" #include #include -#include -#include #include #if defined(_WIN32) || defined(_WIN64) #include @@ -40,6 +43,35 @@ using namespace PAL::detail; using namespace testing; +namespace PAL_NS_BEGIN { +#ifdef HAVE_MAT_LOGGING + namespace detail + { + extern std::recursive_mutex debugLogMutex; + extern std::string debugLogPath; + extern std::unique_ptr debugLogStream; + extern bool isLoggingInited; + extern uint64_t debugLogEpoch; + } +#endif + + class PALTest + { + public: + static bool HasDispatcher(const PlatformAbstractionLayer& pal) + { + std::lock_guard lock(pal.m_stateLock); + return static_cast(pal.m_taskDispatcher); + } + + static bool IsInitializing(const PlatformAbstractionLayer& pal) + { + std::lock_guard lock(pal.m_stateLock); + return pal.m_initializing; + } + }; +} PAL_NS_END + #if defined(_WIN32) || defined(_WIN64) namespace PAL_NS_BEGIN { std::string formatWindowsOsFullVersion( @@ -51,7 +83,384 @@ namespace PAL_NS_BEGIN { } PAL_NS_END #endif -class PalTests : public Test {}; +namespace +{ +#ifdef HAVE_MAT_LOGGING + class ScopedLogState + { + public: + ScopedLogState() + { + std::lock_guard lock(PAL::detail::debugLogMutex); + m_path = std::move(PAL::detail::debugLogPath); + m_stream = std::move(PAL::detail::debugLogStream); + m_enabled = PAL::detail::isLoggingInited; + m_epoch = PAL::detail::debugLogEpoch; + PAL::detail::isLoggingInited = false; + } + + ~ScopedLogState() + { + std::lock_guard lock(PAL::detail::debugLogMutex); + PAL::detail::debugLogStream = std::move(m_stream); + PAL::detail::debugLogPath = std::move(m_path); + PAL::detail::debugLogEpoch = m_epoch; + PAL::detail::isLoggingInited = m_enabled; + } + + private: + std::string m_path; + std::unique_ptr m_stream; + uint64_t m_epoch = 0; + bool m_enabled = false; + }; +#endif + + class BlockingRuntimeConfig : public MAT::RuntimeConfig_Default + { + public: + BlockingRuntimeConfig( + MAT::ILogConfiguration& configuration, + std::promise& entered, + std::shared_future release) + : RuntimeConfig_Default(configuration), m_entered(entered), m_release(std::move(release)) + { + } + + bool HasConfig(const char* key) override + { + if (!m_blocked.exchange(true)) + { + m_entered.set_value(); + m_release.wait(); + } + return RuntimeConfig_Default::HasConfig(key); + } + + private: + std::promise& m_entered; + std::shared_future m_release; + std::atomic m_blocked { false }; + }; + +#if HAVE_EXCEPTIONS + class ThrowOnceRuntimeConfig : public MAT::RuntimeConfig_Default + { + public: + explicit ThrowOnceRuntimeConfig(MAT::ILogConfiguration& configuration) + : RuntimeConfig_Default(configuration) + { + } + + MAT::Variant& operator[](const char* key) override + { + if (m_throw && std::string(key) == CFG_BOOL_ENABLE_NET_DETECT) + { + m_throw = false; + throw std::runtime_error("PAL initialization failed"); + } + return RuntimeConfig_Default::operator[](key); + } + + private: + bool m_throw = true; + }; +#endif + + class ReinitializePalTask + { + public: + ReinitializePalTask( + PAL::PlatformAbstractionLayer& pal, + MAT::IRuntimeConfig& configuration, + std::shared_future release, + std::atomic& shouldInitialize, + std::promise& started, + std::promise& finished, + std::shared_ptr& replacement) + : m_pal(pal), + m_configuration(configuration), + m_release(std::move(release)), + m_shouldInitialize(shouldInitialize), + m_started(started), + m_finished(finished), + m_replacement(replacement) + { + } + + void Run() + { + m_started.set_value(); + m_release.wait(); + if (m_shouldInitialize.load()) + { + m_pal.initialize(m_configuration); + m_replacement = m_pal.getDefaultTaskDispatcher(); + m_pal.shutdown(); + } + m_finished.set_value(); + } + + private: + PAL::PlatformAbstractionLayer& m_pal; + MAT::IRuntimeConfig& m_configuration; + std::shared_future m_release; + std::atomic& m_shouldInitialize; + std::promise& m_started; + std::promise& m_finished; + std::shared_ptr& m_replacement; + }; + + class SignalTask + { + public: + explicit SignalTask(std::promise& signal) : m_signal(signal) {} + void Run() { m_signal.set_value(); } + + private: + std::promise& m_signal; + }; + + class BlockingTask + { + public: + BlockingTask(std::promise& started, std::shared_future release) + : m_started(started), m_release(std::move(release)) + { + } + + void Run() + { + m_started.set_value(); + m_release.wait(); + } + + private: + std::promise& m_started; + std::shared_future m_release; + }; + + class BlockingSemanticContext : public MAT::NullContext + { + public: + BlockingSemanticContext(std::promise& entered, std::shared_future release) + : m_entered(entered), m_release(std::move(release)) + { + } + + void SetDeviceId(const std::string& value) override + { + deviceId = value; + sawDeviceId = true; + } + + void SetDeviceModel(const std::string& value) override + { + m_entered.set_value(); + m_release.wait(); + deviceModel = value; + sawDeviceModel = true; + } + + void SetOsName(const std::string& value) override + { + osName = value; + sawOsName = true; + } + + void SetNetworkProvider(const std::string&) override + { + sawNetworkProvider = true; + } + + std::string deviceId; + std::string deviceModel; + std::string osName; + bool sawDeviceId = false; + bool sawDeviceModel = false; + bool sawOsName = false; + bool sawNetworkProvider = false; + + private: + std::promise& m_entered; + std::shared_future m_release; + }; +} + +class PalTests : public Test +{ +#ifdef HAVE_MAT_LOGGING + ScopedLogState m_logState; +#endif +}; + +TEST_F(PalTests, ConcurrentInitializationPublishesCompleteState) +{ + MAT::ILogConfiguration logConfiguration; + logConfiguration[CFG_BOOL_ENABLE_TRACE] = false; + std::promise firstEntered; + std::promise releaseFirst; + auto firstEnteredFuture = firstEntered.get_future(); + BlockingRuntimeConfig configuration(logConfiguration, firstEntered, releaseFirst.get_future().share()); + PAL::PlatformAbstractionLayer pal; + + struct Observation + { + std::shared_ptr system; + std::shared_ptr device; + std::shared_ptr network; + std::shared_ptr dispatcher; + }; + std::array observations; + auto initialize = [&](size_t index) { + pal.initialize(configuration); + observations[index].system = pal.GetSystemInformation(); + observations[index].device = pal.GetDeviceInformation(); + observations[index].network = pal.GetNetworkInformation(); + observations[index].dispatcher = pal.getDefaultTaskDispatcher(); + }; + + std::thread first([&] { initialize(0); }); + if (firstEnteredFuture.wait_for(std::chrono::seconds(5)) != std::future_status::ready) + { + releaseFirst.set_value(); + first.join(); + pal.shutdown(); + FAIL() << "The first initializer did not enter the configuration"; + } + + std::promise secondStarted; + std::promise secondFinished; + auto secondStartedFuture = secondStarted.get_future(); + auto secondFinishedFuture = secondFinished.get_future(); + std::thread second([&] { + secondStarted.set_value(); + initialize(1); + secondFinished.set_value(); + }); + secondStartedFuture.wait(); + + auto getter = std::async(std::launch::async, [&] { return pal.GetSystemInformation(); }); + const auto getterStatus = getter.wait_for(std::chrono::seconds(2)); + const auto secondStatus = secondFinishedFuture.wait_for(std::chrono::milliseconds(250)); + releaseFirst.set_value(); + first.join(); + second.join(); + + EXPECT_EQ(getterStatus, std::future_status::ready); + EXPECT_EQ(getter.get(), nullptr); + EXPECT_EQ(secondStatus, std::future_status::timeout); + EXPECT_THAT(observations[0].system, NotNull()); + EXPECT_THAT(observations[0].device, NotNull()); + EXPECT_THAT(observations[0].network, NotNull()); + EXPECT_THAT(observations[0].dispatcher, NotNull()); + EXPECT_EQ(observations[0].system, observations[1].system); + EXPECT_EQ(observations[0].device, observations[1].device); + EXPECT_EQ(observations[0].network, observations[1].network); + EXPECT_EQ(observations[0].dispatcher, observations[1].dispatcher); + + std::promise releaseShutdown; + auto shutdownGate = releaseShutdown.get_future().share(); + std::thread shutdown1([&] { shutdownGate.wait(); pal.shutdown(); }); + std::thread shutdown2([&] { shutdownGate.wait(); pal.shutdown(); }); + releaseShutdown.set_value(); + shutdown1.join(); + shutdown2.join(); + EXPECT_EQ(pal.GetSystemInformation(), nullptr); + EXPECT_EQ(pal.GetDeviceInformation(), nullptr); + EXPECT_EQ(pal.GetNetworkInformation(), nullptr); + EXPECT_FALSE(PAL::PALTest::HasDispatcher(pal)); +} + +#if HAVE_EXCEPTIONS +TEST_F(PalTests, FailedInitializationCanBeRetried) +{ + MAT::ILogConfiguration logConfiguration; + logConfiguration[CFG_BOOL_ENABLE_TRACE] = false; + ThrowOnceRuntimeConfig configuration(logConfiguration); + PAL::PlatformAbstractionLayer pal; + + EXPECT_THROW(pal.initialize(configuration), std::runtime_error); + ASSERT_FALSE(PAL::PALTest::IsInitializing(pal)); + EXPECT_FALSE(pal.GetSystemInformation()); + EXPECT_FALSE(pal.GetDeviceInformation()); + EXPECT_FALSE(pal.GetNetworkInformation()); + pal.initialize(configuration); + EXPECT_THAT(pal.GetSystemInformation(), NotNull()); + pal.shutdown(); +} +#endif + +TEST_F(PalTests, RetainedDispatcherSurvivesFinalShutdown) +{ + MAT::ILogConfiguration logConfiguration; + logConfiguration[CFG_BOOL_ENABLE_TRACE] = false; + MAT::RuntimeConfig_Default configuration(logConfiguration); + PAL::PlatformAbstractionLayer pal; + pal.initialize(configuration); + auto dispatcher = pal.getDefaultTaskDispatcher(); + pal.shutdown(); + + std::promise ran; + auto ranFuture = ran.get_future(); + SignalTask task(ran); + PAL::dispatchTask(dispatcher.get(), &task, &SignalTask::Run); + EXPECT_EQ(ranFuture.wait_for(std::chrono::seconds(5)), std::future_status::ready); + dispatcher.reset(); +} + +TEST_F(PalTests, WorkerCanReinitializeWhileFinalShutdownReleasesDispatcher) +{ + MAT::ILogConfiguration logConfiguration; + logConfiguration[CFG_BOOL_ENABLE_TRACE] = false; + MAT::RuntimeConfig_Default configuration(logConfiguration); + PAL::PlatformAbstractionLayer pal; + pal.initialize(configuration); + auto dispatcher = pal.getDefaultTaskDispatcher(); + + std::promise workerStarted; + std::promise releaseWorker; + std::promise workerFinished; + auto startedFuture = workerStarted.get_future(); + auto finishedFuture = workerFinished.get_future(); + std::atomic shouldInitialize { false }; + std::shared_ptr replacement; + ReinitializePalTask task( + pal, configuration, releaseWorker.get_future().share(), shouldInitialize, + workerStarted, workerFinished, replacement); + PAL::dispatchTask(dispatcher.get(), &task, &ReinitializePalTask::Run); + if (startedFuture.wait_for(std::chrono::seconds(5)) != std::future_status::ready) + { + releaseWorker.set_value(); + dispatcher.reset(); + pal.shutdown(); + FAIL() << "The worker did not start"; + } + dispatcher.reset(); + + std::thread shutdown([&] { pal.shutdown(); }); + std::promise dispatcherRetired; + auto retiredFuture = dispatcherRetired.get_future(); + std::thread observer([&] { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); + while (PAL::PALTest::HasDispatcher(pal) && std::chrono::steady_clock::now() < deadline) + { + std::this_thread::yield(); + } + dispatcherRetired.set_value(!PAL::PALTest::HasDispatcher(pal)); + }); + const bool retired = + retiredFuture.wait_for(std::chrono::seconds(5)) == std::future_status::ready && retiredFuture.get(); + shouldInitialize.store(retired); + releaseWorker.set_value(); + observer.join(); + const auto finished = finishedFuture.wait_for(std::chrono::seconds(5)); + shutdown.join(); + + EXPECT_TRUE(retired); + EXPECT_EQ(finished, std::future_status::ready); + EXPECT_THAT(replacement, NotNull()); +} TEST_F(PalTests, UuidGeneration) { @@ -189,24 +598,50 @@ TEST_F(PalTests, MonotonicTime) TEST_F(PalTests, SemanticContextPopulation) { - /* MockISemanticContext context; - - - EXPECT_CALL(context, SetAppId(Not(IsEmpty()))).WillOnce(DoDefault()); - EXPECT_CALL(context, SetAppVersion(_)).WillOnce(DoDefault()); - EXPECT_CALL(context, SetAppLanguage(_)).WillOnce(DoDefault()); - - EXPECT_CALL(context, SetUserLanguage(_)).WillOnce(DoDefault()); - EXPECT_CALL(context, SetUserTimeZone(Not(IsEmpty()))).WillOnce(DoDefault()); - //EXPECT_CALL(context, SetUserAdvertisingId(_)).WillOnce(DoDefault()); - - - PAL::registerSemanticContext(&context); + MAT::ILogConfiguration logConfiguration; + logConfiguration[CFG_BOOL_ENABLE_TRACE] = false; + MAT::RuntimeConfig_Default configuration(logConfiguration); + PAL::PlatformAbstractionLayer pal; + pal.initialize(configuration); + + ASSERT_TRUE(pal.GetDeviceInformation()); + ASSERT_TRUE(pal.GetSystemInformation()); + ASSERT_TRUE(pal.GetNetworkInformation()); + const auto expectedDeviceId = pal.GetDeviceInformation()->GetDeviceId(); + const auto expectedDeviceModel = pal.GetDeviceInformation()->GetModel(); + const auto expectedOsName = pal.GetSystemInformation()->GetOsName(); + + std::promise entered; + std::promise release; + auto enteredFuture = entered.get_future(); + BlockingSemanticContext context(entered, release.get_future().share()); + std::thread populate([&] { pal.registerSemanticContext(&context); }); + if (enteredFuture.wait_for(std::chrono::seconds(5)) != std::future_status::ready) + { + release.set_value(); + populate.join(); + pal.shutdown(); + FAIL() << "Semantic-context population did not reach the device callback"; + } - PAL::sleep(500); + auto shutdown = std::async(std::launch::async, [&] { pal.shutdown(); }); + const auto shutdownStatus = shutdown.wait_for(std::chrono::seconds(2)); + release.set_value(); + populate.join(); + shutdown.get(); - PAL::unregisterSemanticContext(&context); - */ + EXPECT_EQ(shutdownStatus, std::future_status::ready); +#ifdef MATSDK_DISABLE_DEVICE_ID + EXPECT_EQ(context.sawDeviceId, !expectedDeviceId.empty()); +#else + EXPECT_TRUE(context.sawDeviceId); +#endif + EXPECT_EQ(context.deviceId, expectedDeviceId); + EXPECT_TRUE(context.sawDeviceModel); + EXPECT_EQ(context.deviceModel, expectedDeviceModel); + EXPECT_TRUE(context.sawOsName); + EXPECT_EQ(context.osName, expectedOsName); + EXPECT_TRUE(context.sawNetworkProvider); } TEST_F(PalTests, SdkVersion) @@ -592,6 +1027,25 @@ namespace bool m_successorRan = false; }; + class TrackedImmediateTask final : public MAT::Task + { + public: + TrackedImmediateTask(std::atomic& ran, std::atomic& destroyed) : + m_ran(ran), m_destroyed(destroyed) + { + Type = MAT::Task::Call; + TargetTime = 0; + TypeName = "TrackedImmediateTask"; + } + + ~TrackedImmediateTask() noexcept override { m_destroyed.store(true); } + void operator()() override { m_ran.store(true); } + + private: + std::atomic& m_ran; + std::atomic& m_destroyed; + }; + class SelfDisposeHelper { public: @@ -682,6 +1136,33 @@ TEST_F(PalTests, ScheduleTaskAfterWorkerThreadJoinReturnsNoOpHandle) EXPECT_TRUE(handle.Cancel()); } +TEST_F(PalTests, CancelRemovesQueuedImmediateTask) +{ + auto dispatcher = PAL::WorkerThreadFactory::Create(); + BlockingCancellationTarget blocker; + auto running = PAL::scheduleTask( + dispatcher.get(), 0, &blocker, &BlockingCancellationTarget::Block); + (void)running; + if (!blocker.WaitUntilEntered()) + { + blocker.Release(); + dispatcher->Join(); + FAIL() << "Worker did not start the blocking task"; + } + + std::atomic ran{false}; + std::atomic destroyed{false}; + auto task = std::make_unique(ran, destroyed); + auto* identity = task.get(); + dispatcher->Queue(task.release()); + EXPECT_TRUE(dispatcher->Cancel(identity)); + EXPECT_TRUE(destroyed.load()); + blocker.Release(); + dispatcher->Join(); + EXPECT_FALSE(ran.load()); + EXPECT_TRUE(destroyed.load()); +} + TEST_F(PalTests, ScheduleTaskHandleClearsAfterWorkerThreadCallbackCompletes) { auto dispatcher = PAL::WorkerThreadFactory::Create(); @@ -840,6 +1321,7 @@ TEST_F(PalTests, WorkerThreadSelfJoinSurvivesConcurrentFinalRelease) class LogInitTest : public Test { protected: + ScopedLogState m_logState; std::string validPath = "valid/path/"; void SetUp() override @@ -937,4 +1419,125 @@ TEST_F(LogInitTest, LogInitPathWithoutTrailingBackslash) EXPECT_TRUE(PAL::detail::getDebugLogStream()->is_open()); } +TEST_F(LogInitTest, OlderEpochCannotCloseCurrentLog) +{ + uint64_t oldEpoch = 0; + uint64_t currentEpoch = 0; + ASSERT_TRUE(log_init(true, validPath, oldEpoch)); + ASSERT_TRUE(log_init(true, validPath, currentEpoch)); + EXPECT_NE(oldEpoch, currentEpoch); + + log_done(oldEpoch); + ASSERT_TRUE(getDebugLogStream()); + EXPECT_TRUE(getDebugLogStream()->is_open()); + log_done(currentEpoch); + EXPECT_FALSE(getDebugLogStream()); +} + +TEST_F(LogInitTest, PalGenerationSurvivesOlderShutdown) +{ + MAT::ILogConfiguration firstLogConfiguration; + firstLogConfiguration[CFG_BOOL_ENABLE_TRACE] = true; + firstLogConfiguration[CFG_STR_TRACE_FOLDER_PATH] = validPath; + MAT::RuntimeConfig_Default firstConfiguration(firstLogConfiguration); + PAL::PlatformAbstractionLayer pal; + pal.initialize(firstConfiguration); + ASSERT_TRUE(getDebugLogStream()); + const std::string oldPath = getDebugLogPath(); + + auto dispatcher = pal.getDefaultTaskDispatcher(); + std::promise started; + std::promise release; + auto startedFuture = started.get_future(); + BlockingTask task(started, release.get_future().share()); + PAL::dispatchTask(dispatcher.get(), &task, &BlockingTask::Run); + if (startedFuture.wait_for(std::chrono::seconds(5)) != std::future_status::ready) + { + release.set_value(); + dispatcher.reset(); + pal.shutdown(); + FAIL() << "The worker did not start"; + } + dispatcher.reset(); + + std::thread shutdown([&] { pal.shutdown(); }); + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5); + while (PAL::PALTest::HasDispatcher(pal) && std::chrono::steady_clock::now() < deadline) + { + std::this_thread::yield(); + } + if (PAL::PALTest::HasDispatcher(pal)) + { + release.set_value(); + shutdown.join(); + FAIL() << "The old dispatcher was not retired"; + } + + const auto separator = validPath.find_last_of("/\\", validPath.size() - 2); + const std::string otherDirectory = validPath.substr(0, separator + 1); + MAT::ILogConfiguration secondLogConfiguration; + secondLogConfiguration[CFG_BOOL_ENABLE_TRACE] = true; + secondLogConfiguration[CFG_STR_TRACE_FOLDER_PATH] = otherDirectory; + MAT::RuntimeConfig_Default secondConfiguration(secondLogConfiguration); + pal.initialize(secondConfiguration); + const std::string newPath = getDebugLogPath(); + release.set_value(); + shutdown.join(); + + EXPECT_NE(newPath, oldPath); + ASSERT_TRUE(getDebugLogStream()); + EXPECT_TRUE(getDebugLogStream()->is_open()); + EXPECT_EQ(getDebugLogPath(), newPath); + pal.shutdown(); + std::remove(oldPath.c_str()); +} + +TEST_F(LogInitTest, NewEpochUsesItsConfiguredPath) +{ + uint64_t oldEpoch = 0; + uint64_t currentEpoch = 0; + ASSERT_TRUE(log_init(true, validPath, oldEpoch)); + const std::string oldPath = getDebugLogPath(); + const auto separator = validPath.find_last_of("/\\", validPath.size() - 2); + ASSERT_NE(separator, std::string::npos); + const std::string otherDirectory = validPath.substr(0, separator + 1); + + const bool opened = log_init(true, otherDirectory, currentEpoch); + EXPECT_TRUE(opened); + if (opened) + { + EXPECT_NE(getDebugLogPath(), oldPath); + log_done(oldEpoch); + EXPECT_TRUE(getDebugLogStream()); + } + std::remove(oldPath.c_str()); +} + +TEST_F(LogInitTest, FailedOpenIsNotReusedAsSuccessfulLogging) +{ + uint64_t epoch = 0; + ASSERT_TRUE(log_init(true, validPath, epoch)); + const std::string blockedPath = getDebugLogPath(); + log_done(epoch); + ASSERT_EQ(std::remove(blockedPath.c_str()), 0); +#if defined(_WIN32) || defined(_WIN64) + ASSERT_TRUE(CreateDirectoryA(blockedPath.c_str(), nullptr)); +#else + ASSERT_EQ(mkdir(blockedPath.c_str(), 0777), 0); +#endif + + uint64_t firstEpoch = 0; + uint64_t secondEpoch = 0; + EXPECT_FALSE(log_init(true, validPath, firstEpoch)); + EXPECT_FALSE(log_init(true, validPath, secondEpoch)); + EXPECT_EQ(firstEpoch, 0u); + EXPECT_EQ(secondEpoch, 0u); + log_done(); +#if defined(_WIN32) || defined(_WIN64) + EXPECT_TRUE(RemoveDirectoryA(blockedPath.c_str())); +#else + EXPECT_EQ(rmdir(blockedPath.c_str()), 0); +#endif +} + #endif diff --git a/tests/unittests/PayloadDecoderTests.cpp b/tests/unittests/PayloadDecoderTests.cpp index 6a3d8f6a2..5be428b5f 100644 --- a/tests/unittests/PayloadDecoderTests.cpp +++ b/tests/unittests/PayloadDecoderTests.cpp @@ -5,16 +5,23 @@ #include "common/Common.hpp" #include "PayloadDecoder.hpp" #include "utils/ZlibUtils.hpp" +#include +#include #include +#include #if defined(HAVE_MAT_ZLIB) && defined(HAVE_MAT_JSONHPP) #include "bond/All.hpp" #include "bond/generated/CsProtocol_writers.hpp" #include +#include namespace clienttelemetry { namespace data { namespace v3 { + bool Compress(const char* source, size_t sourceLen, char** dest, size_t& destLen, bool prependSize); + bool Compress(const char* source, size_t sourceLen, char** dest, size_t& destLen, bool prependSize, + char* (*allocate)(size_t)); bool Expand(const char* source, size_t sourceLen, char** dest, size_t& destLen, bool sizeAtZeroIndex); bool Expand(const char* source, size_t sourceLen, char** dest, size_t& destLen, bool sizeAtZeroIndex, char* (*allocate)(size_t)); @@ -147,6 +154,224 @@ TEST(PayloadDecoderTests, DecodeRecord_ValidUtf8_IsPreserved) } #if defined(HAVE_MAT_ZLIB) && defined(HAVE_MAT_JSONHPP) +TEST(PayloadDecoderTests, Compress_InvalidInputLeavesOutputUnchanged) +{ + const char source[] = "sample"; + char previousOutput = 0; + char* output = &previousOutput; + size_t outputSize = 32; + EXPECT_FALSE(clienttelemetry::data::v3::Compress(nullptr, sizeof(source), &output, outputSize, false)); + EXPECT_FALSE(clienttelemetry::data::v3::Compress(source, 0, &output, outputSize, false)); + EXPECT_EQ(output, &previousOutput); + EXPECT_EQ(outputSize, 32u); +} + +TEST(PayloadDecoderTests, Compress_AllocationFailureClearsExistingOutput) +{ + const char source[] = "sample"; + for (bool prependSize : {false, true}) + { + char previousOutput = 0; + char* output = &previousOutput; + size_t outputSize = 32; + static size_t requestedSize = 0; + requestedSize = 0; + EXPECT_FALSE(clienttelemetry::data::v3::Compress(source, sizeof(source), &output, outputSize, prependSize, + [](size_t size) -> char* { + requestedSize = size; + return nullptr; + })); + EXPECT_GT(requestedSize, sizeof(source)); + EXPECT_EQ(output, nullptr); + EXPECT_EQ(outputSize, 0u); + } +} + +TEST(PayloadDecoderTests, Compress_RejectsUnrepresentableSizeBeforeAllocation) +{ + const char source[] = "sample"; + for (bool prependSize : {false, true}) + { + char previousOutput = 0; + char* output = &previousOutput; + size_t outputSize = 32; + static bool allocated = false; + allocated = false; + EXPECT_FALSE(clienttelemetry::data::v3::Compress(source, std::numeric_limits::max(), + &output, outputSize, prependSize, [](size_t) -> char* { + allocated = true; + return nullptr; + })); + EXPECT_FALSE(allocated); + EXPECT_EQ(output, nullptr); + EXPECT_EQ(outputSize, 0u); + } +} + +TEST(PayloadDecoderTests, Compress_RejectsSaturatedZlibBound) +{ + const auto maxZlibSize = static_cast(std::numeric_limits::max()); + if (maxZlibSize <= std::numeric_limits::max()) + { + const char source[] = "sample"; + char* output = nullptr; + size_t outputSize = 0; + static bool allocated = false; + allocated = false; + EXPECT_FALSE(clienttelemetry::data::v3::Compress(source, static_cast(maxZlibSize), + &output, outputSize, false, [](size_t) -> char* { + allocated = true; + return nullptr; + })); + EXPECT_FALSE(allocated); + EXPECT_EQ(output, nullptr); + EXPECT_EQ(outputSize, 0u); + } +} + +TEST(PayloadDecoderTests, Compress_RejectsUnrepresentableAllocationBound) +{ + const auto maxAllocation = static_cast(std::numeric_limits::max()); + if (maxAllocation <= static_cast(std::numeric_limits::max())) + { + const char source[] = "sample"; + char* output = nullptr; + size_t outputSize = 0; + static bool allocated = false; + allocated = false; + EXPECT_FALSE(clienttelemetry::data::v3::Compress(source, static_cast(maxAllocation), + &output, outputSize, false, [](size_t) -> char* { + allocated = true; + return nullptr; + })); + EXPECT_FALSE(allocated); + EXPECT_EQ(output, nullptr); + EXPECT_EQ(outputSize, 0u); + } +} + +TEST(PayloadDecoderTests, Compress_RejectsSizeThatCannotFitPrefix) +{ + const auto oversized = static_cast(std::numeric_limits::max()) + 1; + if (oversized <= std::numeric_limits::max()) + { + const char source[] = "sample"; + char* output = nullptr; + size_t outputSize = 0; + static bool allocated = false; + allocated = false; + EXPECT_FALSE(clienttelemetry::data::v3::Compress(source, static_cast(oversized), + &output, outputSize, true, [](size_t) -> char* { + allocated = true; + return nullptr; + })); + EXPECT_FALSE(allocated); + EXPECT_EQ(output, nullptr); + EXPECT_EQ(outputSize, 0u); + + if (oversized <= static_cast(std::numeric_limits::max()) && + oversized < static_cast(std::numeric_limits::max())) + { + EXPECT_FALSE(clienttelemetry::data::v3::Compress(source, static_cast(oversized), + &output, outputSize, false, [](size_t) -> char* { + allocated = true; + return nullptr; + })); + EXPECT_TRUE(allocated); + } + } +} + +TEST(PayloadDecoderTests, Compress_PreservesZlibOutputWithAndWithoutSizePrefix) +{ + const char source[] = "sample compression payload"; + std::vector expected(compressBound(sizeof(source))); + uLongf expectedSize = static_cast(expected.size()); + ASSERT_EQ(compress2(expected.data(), &expectedSize, reinterpret_cast(source), + sizeof(source), Z_BEST_SPEED), Z_OK); + + for (bool prependSize : {false, true}) + { + char* output = nullptr; + size_t outputSize = 0; + ASSERT_TRUE(clienttelemetry::data::v3::Compress(source, sizeof(source), &output, outputSize, prependSize)); + std::unique_ptr owned(output); + const size_t reserved = prependSize ? sizeof(uint32_t) : 0; + ASSERT_EQ(outputSize, expectedSize + reserved); + EXPECT_EQ(std::memcmp(output + reserved, expected.data(), expectedSize), 0); + if (prependSize) + { + uint32_t originalSize = 0; + std::memcpy(&originalSize, output, sizeof(originalSize)); + EXPECT_EQ(originalSize, sizeof(source)); + + std::vector unaligned(outputSize + 1); + std::memcpy(unaligned.data() + 1, output, outputSize); + char* expanded = nullptr; + size_t expandedSize = 0; + ASSERT_TRUE(clienttelemetry::data::v3::Expand( + unaligned.data() + 1, outputSize, &expanded, expandedSize, true)); + std::unique_ptr expandedOwner(expanded); + ASSERT_EQ(expandedSize, sizeof(source)); + EXPECT_EQ(std::memcmp(expanded, source, sizeof(source)), 0); + + const uint16_t endianMarker = 1; + if (*reinterpret_cast(&endianMarker) == 1) + { + std::vector legacy(outputSize + sizeof(uint32_t) + 1, 0); + std::memcpy(legacy.data() + 1, output, sizeof(uint32_t)); + std::memcpy(legacy.data() + 1 + sizeof(uint64_t), output + sizeof(uint32_t), + outputSize - sizeof(uint32_t)); + expanded = nullptr; + expandedSize = 0; + ASSERT_TRUE(clienttelemetry::data::v3::Expand(legacy.data() + 1, + outputSize + sizeof(uint32_t), &expanded, expandedSize, true)); + std::unique_ptr legacyOwner(expanded); + ASSERT_EQ(expandedSize, sizeof(source)); + EXPECT_EQ(std::memcmp(expanded, source, sizeof(source)), 0); + } + } + char restored[sizeof(source)] {}; + uLongf restoredSize = sizeof(restored); + ASSERT_EQ(uncompress(reinterpret_cast(restored), &restoredSize, + reinterpret_cast(output + reserved), + static_cast(outputSize - reserved)), Z_OK); + ASSERT_EQ(restoredSize, sizeof(source)); + EXPECT_EQ(std::memcmp(restored, source, sizeof(source)), 0); + } +} + +TEST(PayloadDecoderTests, Expand_RejectsShortOrIncompleteSizePrefixes) +{ + char previousOutput = 0; + char* output = &previousOutput; + size_t outputSize = 32; + const char source = 0; + EXPECT_FALSE(clienttelemetry::data::v3::Expand(&source, 0, &output, outputSize, true)); + EXPECT_EQ(output, &previousOutput); + EXPECT_EQ(outputSize, 32u); + + for (size_t length = 1; length <= sizeof(uint64_t); ++length) + { + std::vector prefix(length, 0); + output = &previousOutput; + outputSize = 32; + EXPECT_FALSE(clienttelemetry::data::v3::Expand(prefix.data(), prefix.size(), &output, outputSize, true)); + EXPECT_EQ(output, nullptr); + EXPECT_EQ(outputSize, 0u); + + if (length >= sizeof(uint32_t)) + { + const uint32_t declaredSize = 1; + std::memcpy(prefix.data(), &declaredSize, sizeof(declaredSize)); + output = &previousOutput; + outputSize = 32; + EXPECT_FALSE(clienttelemetry::data::v3::Expand(prefix.data(), prefix.size(), &output, outputSize, true)); + EXPECT_EQ(output, nullptr); + } + } +} + TEST(PayloadDecoderTests, Expand_UnrepresentableSizeClearsOutput) { const char source[] = "invalid"; diff --git a/tests/unittests/UnitTests.vcxproj b/tests/unittests/UnitTests.vcxproj index ce61469ff..298c18d9a 100644 --- a/tests/unittests/UnitTests.vcxproj +++ b/tests/unittests/UnitTests.vcxproj @@ -464,7 +464,9 @@ - + + /bigobj %(AdditionalOptions) + diff --git a/tests/zlib-allocation-test.c b/tests/zlib-allocation-test.c new file mode 100644 index 000000000..88b6b520b --- /dev/null +++ b/tests/zlib-allocation-test.c @@ -0,0 +1,87 @@ +#include +#include +#include +#include + +static size_t allocated_size; +static unsigned allocation_calls; +static int allocation_succeeds = 1; +static char allocation; + +static void *test_malloc(size_t size) { + allocated_size = size; + allocation_calls++; + return allocation_succeeds ? &allocation : NULL; +} + +static void *test_calloc(size_t items, size_t size) { + allocation_calls++; + if (size != 0 && items > (size_t)-1 / size) + return NULL; + allocated_size = items * size; + return allocation_succeeds ? &allocation : NULL; +} + +static void test_free(void *ptr) { + (void)ptr; +} + +#define malloc test_malloc +#define calloc test_calloc +#define free test_free +#include "../zlib/zutil.c" +#undef malloc +#undef calloc +#undef free + +#define CHECK(condition) do { \ + if (!(condition)) { \ + fprintf(stderr, "Allocation check failed at line %d\n", __LINE__); \ + return 1; \ + } \ +} while (0) + +int main(void) { + voidpf result; + size_t size_t_width = sizeof(size_t); + size_t uint_width = sizeof(uInt); + size_t max_size = (size_t)-1; + +#ifdef ZLIB_TEST_REQUIRE_32_BIT + CHECK(size_t_width == 4 && uint_width == 4); +#endif + + allocation_calls = 0; + result = zcalloc(NULL, 3, 7); + CHECK(result == &allocation && allocation_calls == 1 && allocated_size == 21); + + result = zcalloc(NULL, 0, 7); + CHECK(result == &allocation && allocated_size == 0); + result = zcalloc(NULL, 7, 0); + CHECK(result == &allocation && allocated_size == 0); + + allocation_succeeds = 0; + result = zcalloc(NULL, 3, 7); + CHECK(result == NULL); + allocation_succeeds = 1; + + if (size_t_width > sizeof(unsigned)) { + result = zcalloc(NULL, UINT_MAX, 2); + CHECK(result == &allocation && allocated_size == (size_t)UINT_MAX * 2); + if (UINT_MAX <= max_size / UINT_MAX) { + result = zcalloc(NULL, UINT_MAX, UINT_MAX); + CHECK(result == &allocation && + allocated_size == (size_t)UINT_MAX * UINT_MAX); + } + } else { + result = zcalloc(NULL, UINT_MAX, 1); + CHECK(result == &allocation && allocated_size == (size_t)UINT_MAX); + allocation_calls = 0; + result = zcalloc(NULL, UINT_MAX, 2); + CHECK(result == NULL); + if (uint_width > 2) + CHECK(allocation_calls == 0); + } + + return 0; +} diff --git a/zlib/zutil.c b/zlib/zutil.c index 6c01021df..6a43b038b 100644 --- a/zlib/zutil.c +++ b/zlib/zutil.c @@ -301,8 +301,16 @@ extern void free(voidpf ptr); #endif voidpf ZLIB_INTERNAL zcalloc(voidpf opaque, unsigned items, unsigned size) { +#ifdef STDC + typedef size_t alloc_size_t; +#else + typedef uInt alloc_size_t; +#endif (void)opaque; - return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) : + /* Modified for the SDK: reject sizes that malloc cannot represent. */ + if (size != 0 && sizeof(uInt) > 2 && items > (alloc_size_t)-1 / size) + return Z_NULL; + return sizeof(uInt) > 2 ? (voidpf)malloc((alloc_size_t)items * size) : (voidpf)calloc(items, size); }