diff options
| author | Stefan Boberg <[email protected]> | 2021-09-15 19:49:20 +0200 |
|---|---|---|
| committer | Stefan Boberg <[email protected]> | 2021-09-15 19:49:20 +0200 |
| commit | 83ccd52321a23c8f1c8a3228cbbf34b8f199a22b (patch) | |
| tree | 9cf1fb68651f616aef2fa28000e4f328ef9204d8 /zenserver | |
| parent | Added GetSize/GetData functions to reduce cognitive load and bridge the gap b... (diff) | |
| parent | Tweaked logging to streamline access, and simplified setup code for new loggers (diff) | |
| download | zen-83ccd52321a23c8f1c8a3228cbbf34b8f199a22b.tar.xz zen-83ccd52321a23c8f1c8a3228cbbf34b8f199a22b.zip | |
Merge branch 'main' into cbpackage-update
Diffstat (limited to 'zenserver')
| -rw-r--r-- | zenserver/cache/cachestore.cpp | 18 | ||||
| -rw-r--r-- | zenserver/cache/structuredcache.cpp | 80 | ||||
| -rw-r--r-- | zenserver/cache/structuredcache.h | 7 | ||||
| -rw-r--r-- | zenserver/cache/structuredcachestore.cpp | 8 | ||||
| -rw-r--r-- | zenserver/casstore.cpp | 6 | ||||
| -rw-r--r-- | zenserver/compute/apply.cpp | 188 | ||||
| -rw-r--r-- | zenserver/compute/apply.h | 2 | ||||
| -rw-r--r-- | zenserver/config.cpp | 9 | ||||
| -rw-r--r-- | zenserver/config.h | 15 | ||||
| -rw-r--r-- | zenserver/diag/logging.cpp | 15 | ||||
| -rw-r--r-- | zenserver/experimental/usnjournal.cpp | 17 | ||||
| -rw-r--r-- | zenserver/projectstore.cpp | 118 | ||||
| -rw-r--r-- | zenserver/projectstore.h | 8 | ||||
| -rw-r--r-- | zenserver/sos/sos.cpp | 9 | ||||
| -rw-r--r-- | zenserver/sos/sos.h | 8 | ||||
| -rw-r--r-- | zenserver/testing/httptest.h | 3 | ||||
| -rw-r--r-- | zenserver/testing/launch.cpp | 29 | ||||
| -rw-r--r-- | zenserver/testing/launch.h | 6 | ||||
| -rw-r--r-- | zenserver/upstream/jupiter.cpp | 20 | ||||
| -rw-r--r-- | zenserver/upstream/jupiter.h | 5 | ||||
| -rw-r--r-- | zenserver/upstream/upstreamcache.cpp | 38 | ||||
| -rw-r--r-- | zenserver/upstream/zen.cpp | 22 | ||||
| -rw-r--r-- | zenserver/upstream/zen.h | 2 | ||||
| -rw-r--r-- | zenserver/vfs.cpp | 8 | ||||
| -rw-r--r-- | zenserver/zenserver.cpp | 61 |
25 files changed, 326 insertions, 376 deletions
diff --git a/zenserver/cache/cachestore.cpp b/zenserver/cache/cachestore.cpp index 9180835d9..2fc253a07 100644 --- a/zenserver/cache/cachestore.cpp +++ b/zenserver/cache/cachestore.cpp @@ -4,6 +4,7 @@ #include <zencore/crc32.h> #include <zencore/except.h> +#include <zencore/logging.h> #include <zencore/windows.h> #include <zencore/filesystem.h> @@ -16,7 +17,6 @@ #include <zenstore/caslog.h> #include <fmt/core.h> -#include <spdlog/spdlog.h> #include <concepts> #include <filesystem> #include <gsl/gsl-lite.hpp> @@ -85,7 +85,7 @@ FileCacheStore::FileCacheStore(const char* RootDir, const char* ReadRootDir) { // Ensure root directory exists - create if it doesn't exist already - spdlog::info("Initializing FileCacheStore at '{}'", std::string_view(RootDir)); + ZEN_INFO("Initializing FileCacheStore at '{}'", std::string_view(RootDir)); m_RootDir = RootDir; @@ -98,7 +98,7 @@ FileCacheStore::FileCacheStore(const char* RootDir, const char* ReadRootDir) ExtendableStringBuilder<256> Name; WideToUtf8(m_RootDir.c_str(), Name); - spdlog::error("Could not open file cache directory '{}' for writing ({})", Name.c_str(), ErrorCode.message()); + ZEN_ERROR("Could not open file cache directory '{}' for writing ({})", Name.c_str(), ErrorCode.message()); m_IsOk = false; } @@ -109,7 +109,7 @@ FileCacheStore::FileCacheStore(const char* RootDir, const char* ReadRootDir) if (std::filesystem::exists(m_ReadRootDir, ErrorCode)) { - spdlog::info("FileCacheStore will use additional read tree at '{}'", std::string_view(ReadRootDir)); + ZEN_INFO("FileCacheStore will use additional read tree at '{}'", std::string_view(ReadRootDir)); m_ReadRootIsValid = true; } @@ -145,7 +145,7 @@ FileCacheStore::Get(std::string_view Key, CacheValue& OutValue) if (FAILED(hRes)) { - spdlog::debug("GET MISS {}", Key); + ZEN_DEBUG("GET MISS {}", Key); return false; } @@ -162,7 +162,7 @@ FileCacheStore::Get(std::string_view Key, CacheValue& OutValue) OutValue.Value = IoBuffer(IoBuffer::File, File.Detach(), 0, FileSize); - spdlog::debug("GET HIT {}", Key); + ZEN_DEBUG("GET HIT {}", Key); return true; } @@ -180,7 +180,7 @@ FileCacheStore::Put(std::string_view Key, const CacheValue& Value) CAtlTemporaryFile File; - spdlog::debug("PUT {}", Key); + ZEN_DEBUG("PUT {}", Key); HRESULT hRes = File.Create(m_RootDir.c_str()); @@ -205,11 +205,11 @@ FileCacheStore::Put(std::string_view Key, const CacheValue& Value) if (FAILED(hRes)) { - spdlog::warn("Failed to rename temp file for key '{}' - deleting temporary file", Key); + ZEN_WARN("Failed to rename temp file for key '{}' - deleting temporary file", Key); if (!DeleteFile(File.TempFileName())) { - spdlog::warn("Temp file for key '{}' could not be deleted - no value persisted", Key); + ZEN_WARN("Temp file for key '{}' could not be deleted - no value persisted", Key); } } } diff --git a/zenserver/cache/structuredcache.cpp b/zenserver/cache/structuredcache.cpp index b2f8d191c..9600c5f8a 100644 --- a/zenserver/cache/structuredcache.cpp +++ b/zenserver/cache/structuredcache.cpp @@ -4,6 +4,7 @@ #include <zencore/compactbinaryvalidation.h> #include <zencore/compress.h> #include <zencore/fmtutils.h> +#include <zencore/logging.h> #include <zencore/timer.h> #include <zenhttp/httpserver.h> @@ -14,7 +15,6 @@ #include "upstream/zen.h" #include "zenstore/cidstore.h" -#include <spdlog/spdlog.h> #include <algorithm> #include <atomic> #include <filesystem> @@ -31,18 +31,18 @@ HttpStructuredCacheService::HttpStructuredCacheService(::ZenCacheStore& InC zen::CasStore& InStore, zen::CidStore& InCidStore, std::unique_ptr<UpstreamCache> UpstreamCache) -: m_Log("cache", begin(spdlog::default_logger()->sinks()), end(spdlog::default_logger()->sinks())) +: m_Log(zen::logging::Get("cache")) , m_CacheStore(InCacheStore) , m_CasStore(InStore) , m_CidStore(InCidStore) , m_UpstreamCache(std::move(UpstreamCache)) { - m_Log.set_level(spdlog::level::debug); + // m_Log.set_level(spdlog::level::debug); } HttpStructuredCacheService::~HttpStructuredCacheService() { - spdlog::info("closing structured cache"); + ZEN_INFO("closing structured cache"); } const char* @@ -173,7 +173,7 @@ HttpStructuredCacheService::HandleCacheRecordRequest(zen::HttpServerRequest& Req { Value.Value = IoBuffer(); Success = false; - m_Log.warn("Upstream cache record '{}/{}' failed validation", Ref.BucketSegment, Ref.HashKey); + ZEN_WARN("Upstream cache record '{}/{}' failed validation", Ref.BucketSegment, Ref.HashKey); } } @@ -186,7 +186,7 @@ HttpStructuredCacheService::HandleCacheRecordRequest(zen::HttpServerRequest& Req if (!Success) { - m_Log.debug("MISS - '{}/{}'", Ref.BucketSegment, Ref.HashKey); + ZEN_DEBUG("MISS - '{}/{}'", Ref.BucketSegment, Ref.HashKey); return Request.WriteResponse(zen::HttpResponseCode::NotFound); } @@ -196,12 +196,12 @@ HttpStructuredCacheService::HandleCacheRecordRequest(zen::HttpServerRequest& Req Request.SetSuppressResponseBody(); } - m_Log.debug("HIT - '{}/{}' ({} bytes {}) ({})", - Ref.BucketSegment, - Ref.HashKey, - Value.Value.Size(), - Value.Value.GetContentType(), - InUpstreamCache ? "upstream" : "local"); + ZEN_DEBUG("HIT - '{}/{}' ({} bytes {}) ({})", + Ref.BucketSegment, + Ref.HashKey, + Value.Value.Size(), + Value.Value.GetContentType(), + InUpstreamCache ? "upstream" : "local"); return Request.WriteResponse(zen::HttpResponseCode::OK, Value.Value.GetContentType(), Value.Value); } @@ -239,11 +239,7 @@ HttpStructuredCacheService::HandleCacheRecordRequest(zen::HttpServerRequest& Req { // TODO: create a cache record and put value in CAS? m_CacheStore.Put(Ref.BucketSegment, Ref.HashKey, {.Value = Body}); - m_Log.debug("PUT (binary) - '{}/{}' ({} bytes, {})", - Ref.BucketSegment, - Ref.HashKey, - Body.Size(), - Body.GetContentType()); + ZEN_DEBUG("PUT (binary) - '{}/{}' ({} bytes, {})", Ref.BucketSegment, Ref.HashKey, Body.Size(), Body.GetContentType()); if (m_UpstreamCache) { @@ -260,7 +256,7 @@ HttpStructuredCacheService::HandleCacheRecordRequest(zen::HttpServerRequest& Req if (ValidationResult != CbValidateError::None) { - m_Log.warn("Payload for key '{}/{}' ({} bytes) failed validation", Ref.BucketSegment, Ref.HashKey, Body.Size()); + ZEN_WARN("Payload for key '{}/{}' ({} bytes) failed validation", Ref.BucketSegment, Ref.HashKey, Body.Size()); // TODO: add details in response, kText || kCbObject? return Request.WriteResponse(HttpResponseCode::BadRequest, @@ -299,13 +295,13 @@ HttpStructuredCacheService::HandleCacheRecordRequest(zen::HttpServerRequest& Req m_CacheStore.Put(Ref.BucketSegment, Ref.HashKey, CacheValue); - m_Log.debug("PUT (cache record) - '{}/{}' ({} bytes, {}, ({}/{} refs/missing))", - Ref.BucketSegment, - Ref.HashKey, - CacheValue.Value.Size(), - CacheValue.Value.GetContentType(), - References.size(), - MissingRefs.size()); + ZEN_DEBUG("PUT (cache record) - '{}/{}' ({} bytes, {}, ({}/{} refs/missing))", + Ref.BucketSegment, + Ref.HashKey, + CacheValue.Value.Size(), + CacheValue.Value.GetContentType(), + References.size(), + MissingRefs.size()); if (MissingRefs.empty()) { @@ -327,7 +323,7 @@ HttpStructuredCacheService::HandleCacheRecordRequest(zen::HttpServerRequest& Req for (const IoHash& MissingRef : MissingRefs) { Response.AddHash(MissingRef); - m_Log.debug("cache record '{}/{}' is missing reference '{}'", Ref.BucketSegment, Ref.HashKey, MissingRef); + ZEN_DEBUG("cache record '{}/{}' is missing reference '{}'", Ref.BucketSegment, Ref.HashKey, MissingRef); } Response.EndArray(); @@ -380,24 +376,24 @@ HttpStructuredCacheService::HandleCachePayloadRequest(zen::HttpServerRequest& Re } else { - m_Log.warn("got uncompressed upstream cache payload"); + ZEN_WARN("got uncompressed upstream cache payload"); } } } if (!Payload) { - m_Log.debug("MISS - '{}/{}/{}'", Ref.BucketSegment, Ref.HashKey, Ref.PayloadId); + ZEN_DEBUG("MISS - '{}/{}/{}'", Ref.BucketSegment, Ref.HashKey, Ref.PayloadId); return Request.WriteResponse(zen::HttpResponseCode::NotFound); } - m_Log.debug("HIT - '{}/{}/{}' ({} bytes, {}) ({})", - Ref.BucketSegment, - Ref.HashKey, - Ref.PayloadId, - Payload.Size(), - Payload.GetContentType(), - InUpstreamCache ? "upstream" : "local"); + ZEN_DEBUG("HIT - '{}/{}/{}' ({} bytes, {}) ({})", + Ref.BucketSegment, + Ref.HashKey, + Ref.PayloadId, + Payload.Size(), + Payload.GetContentType(), + InUpstreamCache ? "upstream" : "local"); if (Verb == kHead) { @@ -442,13 +438,13 @@ HttpStructuredCacheService::HandleCachePayloadRequest(zen::HttpServerRequest& Re m_CidStore.AddCompressedCid(Ref.PayloadId, ChunkHash); - m_Log.debug("PUT ({}) - '{}/{}/{}' ({} bytes, {})", - Result.New ? "NEW" : "OLD", - Ref.BucketSegment, - Ref.HashKey, - Ref.PayloadId, - Body.Size(), - Body.GetContentType()); + ZEN_DEBUG("PUT ({}) - '{}/{}/{}' ({} bytes, {})", + Result.New ? "NEW" : "OLD", + Ref.BucketSegment, + Ref.HashKey, + Ref.PayloadId, + Body.Size(), + Body.GetContentType()); if (Result.New) { diff --git a/zenserver/cache/structuredcache.h b/zenserver/cache/structuredcache.h index d4bb94c52..c8c959569 100644 --- a/zenserver/cache/structuredcache.h +++ b/zenserver/cache/structuredcache.h @@ -4,9 +4,12 @@ #include <zenhttp/httpserver.h> -#include <spdlog/spdlog.h> #include <memory> +namespace spdlog { +class logger; +} + class ZenCacheStore; namespace zen { @@ -71,7 +74,7 @@ private: void HandleCachePayloadRequest(zen::HttpServerRequest& Request, CacheRef& Ref); void HandleCacheBucketRequest(zen::HttpServerRequest& Request, std::string_view Bucket); - spdlog::logger m_Log; + spdlog::logger& m_Log; ZenCacheStore& m_CacheStore; zen::CasStore& m_CasStore; zen::CidStore& m_CidStore; diff --git a/zenserver/cache/structuredcachestore.cpp b/zenserver/cache/structuredcachestore.cpp index a07fccf98..018955e65 100644 --- a/zenserver/cache/structuredcachestore.cpp +++ b/zenserver/cache/structuredcachestore.cpp @@ -9,6 +9,7 @@ #include <zencore/filesystem.h> #include <zencore/fmtutils.h> #include <zencore/iobuffer.h> +#include <zencore/logging.h> #include <zencore/string.h> #include <zencore/thread.h> #include <zenstore/basicfile.h> @@ -16,7 +17,6 @@ #include <zenstore/caslog.h> #include <fmt/core.h> -#include <spdlog/spdlog.h> #include <concepts> #include <filesystem> #include <gsl/gsl-lite.hpp> @@ -31,7 +31,7 @@ using namespace fmt::literals; ZenCacheStore::ZenCacheStore(zen::CasStore& Cas, const std::filesystem::path& RootDir) : m_DiskLayer{Cas, RootDir} { - spdlog::info("initializing structured cache at '{}'", RootDir); + ZEN_INFO("initializing structured cache at '{}'", RootDir); zen::CreateDirectories(RootDir); } @@ -85,7 +85,7 @@ ZenCacheStore::Put(std::string_view InBucket, const zen::IoHash& HashKey, const bool ZenCacheStore::DropBucket(std::string_view Bucket) { - spdlog::info("dropping bucket '{}'", Bucket); + ZEN_INFO("dropping bucket '{}'", Bucket); // TODO: should ensure this is done atomically across all layers @@ -93,7 +93,7 @@ ZenCacheStore::DropBucket(std::string_view Bucket) const bool DiskDropped = m_DiskLayer.DropBucket(Bucket); const bool AnyDropped = MemDropped || DiskDropped; - spdlog::info("bucket '{}' was {}", Bucket, AnyDropped ? "dropped" : "not found"); + ZEN_INFO("bucket '{}' was {}", Bucket, AnyDropped ? "dropped" : "not found"); return AnyDropped; } diff --git a/zenserver/casstore.cpp b/zenserver/casstore.cpp index 6f1e4873b..b36dcc09f 100644 --- a/zenserver/casstore.cpp +++ b/zenserver/casstore.cpp @@ -2,9 +2,9 @@ #include "casstore.h" +#include <zencore/logging.h> #include <zencore/streamutil.h> -#include <spdlog/spdlog.h> #include <gsl/gsl-lite.hpp> namespace zen { @@ -63,7 +63,7 @@ HttpCasService::HttpCasService(CasStore& Store) : m_CasStore(Store) "{cas}", [this](HttpRouterRequest& Req) { IoHash Hash = IoHash::FromHexString(Req.GetCapture(1)); - spdlog::debug("CAS request for {}", Hash); + ZEN_DEBUG("CAS request for {}", Hash); HttpServerRequest& ServerRequest = Req.ServerRequest(); @@ -123,7 +123,7 @@ HttpCasService::HandleRequest(zen::HttpServerRequest& Request) IoBuffer Payload = Request.ReadPayload(); IoHash PayloadHash = IoHash::HashBuffer(Payload.Data(), Payload.Size()); - spdlog::debug("CAS POST request for {} ({} bytes)", PayloadHash, Payload.Size()); + ZEN_DEBUG("CAS POST request for {} ({} bytes)", PayloadHash, Payload.Size()); auto InsertResult = m_CasStore.InsertChunk(Payload, PayloadHash); diff --git a/zenserver/compute/apply.cpp b/zenserver/compute/apply.cpp index b46945d88..c3d83b2b5 100644 --- a/zenserver/compute/apply.cpp +++ b/zenserver/compute/apply.cpp @@ -89,7 +89,7 @@ BasicFunctionJob::SpawnJob(std::filesystem::path ExePath, std::wstring CommandLi m_ProcessHandle.Attach(ProcessInfo.hProcess); ::CloseHandle(ProcessInfo.hThread); - spdlog::info("Created process {}", m_ProcessId); + ZEN_INFO("Created process {}", m_ProcessId); return true; } @@ -114,7 +114,7 @@ BasicFunctionJob::Wait(uint32_t TimeoutMs) return true; } - throw std::exception("Failed wait on process handle"); + throw std::runtime_error("Failed wait on process handle"); } int @@ -125,12 +125,12 @@ BasicFunctionJob::ExitCode() if (!Success) { - spdlog::warn("failed getting exit code"); + ZEN_WARN("failed getting exit code"); } if (Ec == STILL_ACTIVE) { - spdlog::warn("getting exit code but process is STILL_ACTIVE"); + ZEN_WARN("getting exit code but process is STILL_ACTIVE"); } return gsl::narrow_cast<int>(Ec); @@ -231,7 +231,7 @@ SandboxedFunctionJob::Initialize(std::string_view AppContainerId) if (FAILED(hRes)) { - spdlog::error("Failed creating app container SID"); + ZEN_ERROR("Failed creating app container SID"); } } @@ -240,12 +240,12 @@ SandboxedFunctionJob::Initialize(std::string_view AppContainerId) PWSTR Str = nullptr; ::ConvertSidToStringSid(m_AppContainerSid, &Str); - spdlog::info("AppContainer SID : '{}'", WideToUtf8(Str)); + ZEN_INFO("AppContainer SID : '{}'", WideToUtf8(Str)); PWSTR Path = nullptr; if (SUCCEEDED(::GetAppContainerFolderPath(Str, &Path))) { - spdlog::info("AppContainer folder: '{}'", WideToUtf8(Path)); + ZEN_INFO("AppContainer folder: '{}'", WideToUtf8(Path)); ::CoTaskMemFree(Path); } @@ -321,13 +321,13 @@ SandboxedFunctionJob::SpawnJob(std::filesystem::path ExePath) return false; } - spdlog::info("Created process {}", ProcessInfo.dwProcessId); + ZEN_INFO("Created process {}", ProcessInfo.dwProcessId); return true; } HttpFunctionService::HttpFunctionService(CasStore& Store, CidStore& InCidStore, const std::filesystem::path& BaseDir) -: m_Log("apply", begin(spdlog::default_logger()->sinks()), end(spdlog::default_logger()->sinks())) +: m_Log(logging::Get("apply")) , m_CasStore(Store) , m_CidStore(InCidStore) , m_SandboxPath(BaseDir / "scratch") @@ -378,6 +378,10 @@ HttpFunctionService::HttpFunctionService(CasStore& Store, CidStore& InCidStore, ChunkSet.AddChunk(Hash); }); + // Note that we store executables uncompressed to make it + // more straightforward and efficient to materialize them, hence + // the CAS lookup here instead of CID for the input payloads + m_CasStore.FilterChunks(ChunkSet); if (ChunkSet.IsEmpty()) @@ -386,7 +390,7 @@ HttpFunctionService::HttpFunctionService(CasStore& Store, CidStore& InCidStore, m_WorkerMap.insert_or_assign(WorkerId, WorkerDesc{FunctionSpec}); - spdlog::debug("worker {}: all attachments already available", WorkerId); + ZEN_DEBUG("worker {}: all attachments already available", WorkerId); return HttpReq.WriteResponse(HttpResponseCode::NoContent); } @@ -397,14 +401,14 @@ HttpFunctionService::HttpFunctionService(CasStore& Store, CidStore& InCidStore, for (const IoHash& Hash : ChunkSet.GetChunkSet()) { - spdlog::debug("worker {}: need chunk {}", WorkerId, Hash); + ZEN_DEBUG("worker {}: need chunk {}", WorkerId, Hash); ResponseWriter.AddHash(Hash); } ResponseWriter.EndArray(); - spdlog::debug("worker {}: need {} attachments", WorkerId, ChunkSet.GetChunkSet().size()); + ZEN_DEBUG("worker {}: need {} attachments", WorkerId, ChunkSet.GetChunkSet().size()); return HttpReq.WriteResponse(HttpResponseCode::NotFound, ResponseWriter.Save()); } @@ -426,31 +430,35 @@ HttpFunctionService::HttpFunctionService(CasStore& Store, CidStore& InCidStore, for (const CbAttachment& Attachment : Attachments) { - ZEN_ASSERT(Attachment.IsBinary()); + ZEN_ASSERT(Attachment.IsCompressedBinary()); - const IoHash DataHash = Attachment.GetHash(); - CompressedBuffer DataView = Attachment.AsCompressedBinary(); + const IoHash DataHash = Attachment.GetHash(); + CompressedBuffer DataView = Attachment.AsCompressedBinary(); + SharedBuffer Decompressed = DataView.Decompress(); + const uint64_t DecompressedSize = DataView.GetRawSize(); - TotalAttachmentBytes += DataView.GetCompressedSize(); + TotalAttachmentBytes += DecompressedSize; ++AttachmentCount; - IoBuffer Payload = DataView.GetCompressed().Flatten().AsIoBuffer(); + // Note that we store executables uncompressed to make it + // more straightforward and efficient to materialize them - CasStore::InsertResult InsertResult = m_CasStore.InsertChunk(Payload, DataHash); + const CasStore::InsertResult InsertResult = + m_CasStore.InsertChunk(Decompressed.AsIoBuffer(), IoHash::FromBLAKE3(DataView.GetRawHash())); if (InsertResult.New) { - TotalNewBytes += Payload.Size(); + TotalNewBytes += DecompressedSize; ++NewAttachmentCount; } } - spdlog::debug("worker {}: {} in {} attachments, {} in {} new attachments", - WorkerId, - zen::NiceBytes(TotalAttachmentBytes), - AttachmentCount, - zen::NiceBytes(TotalNewBytes), - NewAttachmentCount); + ZEN_DEBUG("worker {}: {} in {} attachments, {} in {} new attachments", + WorkerId, + zen::NiceBytes(TotalAttachmentBytes), + AttachmentCount, + zen::NiceBytes(TotalNewBytes), + NewAttachmentCount); RwLock::ExclusiveLockScope _(m_WorkerLock); @@ -526,7 +534,7 @@ HttpFunctionService::HttpFunctionService(CasStore& Store, CidStore& InCidStore, RequestObject.IterateAttachments([&](CbFieldView Field) { const IoHash FileHash = Field.AsHash(); - if (!m_CasStore.FindChunk(FileHash)) + if (!m_CidStore.ContainsChunk(FileHash)) { NeedList.push_back(FileHash); } @@ -570,28 +578,30 @@ HttpFunctionService::HttpFunctionService(CasStore& Store, CidStore& InCidStore, for (const CbAttachment& Attachment : Attachments) { - ZEN_ASSERT(Attachment.IsBinary()); + ZEN_ASSERT(Attachment.IsCompressedBinary()); + + const IoHash DataHash = Attachment.GetHash(); + CompressedBuffer DataView = Attachment.AsCompressedBinary(); - const IoHash DataHash = Attachment.GetHash(); - SharedBuffer DataView = Attachment.AsBinary(); + const uint64_t CompressedSize = DataView.GetCompressedSize(); - TotalAttachmentBytes += DataView.GetSize(); + TotalAttachmentBytes += CompressedSize; ++AttachmentCount; - CasStore::InsertResult InsertResult = m_CasStore.InsertChunk(DataView.AsIoBuffer(), DataHash); + const CasStore::InsertResult InsertResult = m_CidStore.AddChunk(DataView); if (InsertResult.New) { - TotalNewBytes += DataView.GetSize(); + TotalNewBytes += CompressedSize; ++NewAttachmentCount; } } - spdlog::debug("new action: {}B in {} attachments. {}B new ({} attachments)", - zen::NiceBytes(TotalAttachmentBytes), - AttachmentCount, - zen::NiceBytes(TotalNewBytes), - NewAttachmentCount); + ZEN_DEBUG("new action: {} in {} attachments. {} new ({} attachments)", + zen::NiceBytes(TotalAttachmentBytes), + AttachmentCount, + zen::NiceBytes(TotalNewBytes), + NewAttachmentCount); CbPackage Output = ExecAction(Worker, ActionObj); @@ -603,90 +613,6 @@ HttpFunctionService::HttpFunctionService(CasStore& Store, CidStore& InCidStore, } }, HttpVerb::kPost); - - // This is just for reference - m_Router.RegisterRoute( - "jobs/noop", - [this](HttpRouterRequest& Req) { - HttpServerRequest& HttpReq = Req.ServerRequest(); - - switch (HttpReq.RequestVerb()) - { - case HttpVerb::kGet: - break; - - case HttpVerb::kPost: - { - IoBuffer Payload = HttpReq.ReadPayload(); - CbObject RequestObject = LoadCompactBinaryObject(Payload); - - bool AllOk = true; - - std::vector<IoHash> NeedList; - - std::filesystem::path SandboxDir{CreateNewSandbox()}; - - spdlog::debug("setting up job in sandbox '{}'", SandboxDir); - - zen::DeleteDirectories(SandboxDir); - zen::CreateDirectories(SandboxDir); - - for (auto Entry : RequestObject["files"sv]) - { - CbObjectView Ob = Entry.AsObjectView(); - - std::string_view FileName = Ob["file"sv].AsString(); - const IoHash FileHash = Ob["hash"sv].AsHash(); - uint64_t FileSize = Ob["size"sv].AsUInt64(); - - if (IoBuffer Chunk = m_CasStore.FindChunk(FileHash); !Chunk) - { - spdlog::debug("MISSING: {} {} {}", FileHash, FileName, FileSize); - AllOk = false; - - NeedList.push_back(FileHash); - } - else - { - std::filesystem::path FullPath = SandboxDir / FileName; - - const IoBuffer* Chunks[] = {&Chunk}; - - zen::WriteFile(FullPath, Chunks, 1); - } - } - - if (!AllOk) - { - // TODO: Could report all the missing pieces in the response here - return HttpReq.WriteResponse(HttpResponseCode::NotFound); - } - - std::string Executable8{RequestObject["cmd"].AsString()}; - std::string Args8{RequestObject["args"].AsString()}; - - std::wstring Executable = Utf8ToWide(Executable8); - std::wstring Args = Utf8ToWide(Args8); - - spdlog::debug("spawning job in sandbox '{}': '{}' '{}'", SandboxDir, Executable8, Args8); - - std::filesystem::path ExeName = SandboxDir / Executable; - - BasicFunctionJob Job; - Job.SetWorkingDirectory(SandboxDir); - Job.SpawnJob(ExeName, Args); - Job.Wait(); - - CbObjectWriter Response; - - Response << "exitcode" << Job.ExitCode(); - - return HttpReq.WriteResponse(HttpResponseCode::OK, Response.Save()); - } - break; - } - }, - HttpVerb::kGet | HttpVerb::kPost); } HttpFunctionService::~HttpFunctionService() @@ -704,7 +630,7 @@ HttpFunctionService::HandleRequest(HttpServerRequest& Request) { if (m_Router.HandleRequest(Request) == false) { - m_Log.warn("No route found for {0}", Request.RelativeUri()); + ZEN_WARN("No route found for {0}", Request.RelativeUri()); } } @@ -741,7 +667,7 @@ HttpFunctionService::ExecAction(const WorkerDesc& Worker, CbObject Action) if (!DataBuffer) { - throw std::exception("Chunk missing" /* ADD CONTEXT */); + throw std::runtime_error("Chunk missing" /* ADD CONTEXT */); } zen::WriteFile(FilePath, DataBuffer); @@ -767,7 +693,7 @@ HttpFunctionService::ExecAction(const WorkerDesc& Worker, CbObject Action) if (!DataBuffer) { - throw std::exception("Chunk missing" /* ADD CONTEXT */); + throw std::runtime_error("Chunk missing" /* ADD CONTEXT */); } zen::WriteFile(FilePath, DataBuffer); @@ -780,18 +706,16 @@ HttpFunctionService::ExecAction(const WorkerDesc& Worker, CbObject Action) // Manifest inputs in sandbox Action.IterateAttachments([&](CbFieldView Field) { - const IoHash Hash = Field.AsHash(); - std::filesystem::path FilePath{SandboxPath / "Inputs" / Hash.ToHexString()}; - IoBuffer DataBuffer = m_CasStore.FindChunk(Hash); + const IoHash Cid = Field.AsHash(); + std::filesystem::path FilePath{SandboxPath / "Inputs" / Cid.ToHexString()}; + IoBuffer DataBuffer = m_CidStore.FindChunkByCid(Cid); if (!DataBuffer) { - throw std::exception("Chunk missing" /* ADD CONTEXT */); + throw std::runtime_error("Chunk missing" /* ADD CONTEXT */); } - CompressedBuffer Buffer = CompressedBuffer::Compress(SharedBuffer(std::move(DataBuffer))); - - zen::WriteFile(FilePath, Buffer.GetCompressed().Flatten().AsIoBuffer()); + zen::WriteFile(FilePath, DataBuffer); }); // Set up environment variables @@ -884,7 +808,7 @@ HttpFunctionService::ExecAction(const WorkerDesc& Worker, CbObject Action) ZEN_ASSERT(OutputData.Data.size() == 1); - CbAttachment Attachment(SharedBuffer(ChunkData.Data[0]), Hash); + CbAttachment Attachment(CompressedBuffer::FromCompressed(SharedBuffer(ChunkData.Data[0]))); OutputPackage.AddAttachment(Attachment); }); diff --git a/zenserver/compute/apply.h b/zenserver/compute/apply.h index 695dc2e6e..474156a5e 100644 --- a/zenserver/compute/apply.h +++ b/zenserver/compute/apply.h @@ -28,7 +28,7 @@ public: virtual void HandleRequest(HttpServerRequest& Request) override; private: - spdlog::logger m_Log; + spdlog::logger& m_Log; HttpRequestRouter m_Router; CasStore& m_CasStore; CidStore& m_CidStore; diff --git a/zenserver/config.cpp b/zenserver/config.cpp index ddef83c02..578a3a202 100644 --- a/zenserver/config.cpp +++ b/zenserver/config.cpp @@ -14,7 +14,7 @@ #pragma warning(pop) #include <fmt/format.h> -#include <spdlog/spdlog.h> +#include <zencore/logging.h> #include <sol/sol.hpp> #if ZEN_PLATFORM_WINDOWS @@ -59,6 +59,9 @@ void ParseGlobalCliOptions(int argc, char* argv[], ZenServerOptions& GlobalOptions, ZenServiceConfig& ServiceConfig) { cxxopts::Options options("zenserver", "Zen Server"); + options.add_options()("dedicated", + "Enable dedicated server mode", + cxxopts::value<bool>(GlobalOptions.IsDedicated)->default_value("false")); options.add_options()("d, debug", "Enable debugging", cxxopts::value<bool>(GlobalOptions.IsDebug)->default_value("false")); options.add_options()("help", "Show command line help"); options.add_options()("t, test", "Enable test mode", cxxopts::value<bool>(GlobalOptions.IsTest)->default_value("false")); @@ -237,9 +240,9 @@ ParseServiceConfig(const std::filesystem::path& DataRoot, ZenServiceConfig& Serv } catch (std::exception& e) { - spdlog::error("config script failure: {}", e.what()); + ZEN_ERROR("config script failure: {}", e.what()); - throw std::exception("fatal zen global config script ({}) failure: {}"_format(ConfigScript, e.what()).c_str()); + throw std::runtime_error("fatal zen global config script ({}) failure: {}"_format(ConfigScript, e.what()).c_str()); } ServiceConfig.MeshEnabled = lua["mesh"]["enable"].get_or(ServiceConfig.MeshEnabled); diff --git a/zenserver/config.h b/zenserver/config.h index 92b7c9e31..80ec86905 100644 --- a/zenserver/config.h +++ b/zenserver/config.h @@ -7,13 +7,14 @@ struct ZenServerOptions { - bool IsDebug = false; - bool IsTest = false; - int BasePort = 1337; // Service listen port (used for both UDP and TCP) - int OwnerPid = 0; // Parent process id (zero for standalone) - std::string ChildId; // Id assigned by parent process (used for lifetime management) - std::string LogId; // Id for tagging log output - std::filesystem::path DataDir; // Root directory for state (used for testing) + bool IsDebug = false; + bool IsTest = false; + bool IsDedicated = false; // Indicates a dedicated/shared instance, with larger resource requirements + int BasePort = 1337; // Service listen port (used for both UDP and TCP) + int OwnerPid = 0; // Parent process id (zero for standalone) + std::string ChildId; // Id assigned by parent process (used for lifetime management) + std::string LogId; // Id for tagging log output + std::filesystem::path DataDir; // Root directory for state (used for testing) }; struct ZenUpstreamJupiterConfig diff --git a/zenserver/diag/logging.cpp b/zenserver/diag/logging.cpp index 5782ce582..48eda7512 100644 --- a/zenserver/diag/logging.cpp +++ b/zenserver/diag/logging.cpp @@ -211,7 +211,7 @@ InitializeLogging(const ZenServerOptions& GlobalOptions) spdlog::init_thread_pool(QueueSize, ThreadCount); auto AsyncLogger = spdlog::create_async<spdlog::sinks::ansicolor_stdout_sink_mt>("main"); - spdlog::set_default_logger(AsyncLogger); + zen::logging::SetDefault(AsyncLogger); } // Sinks @@ -220,16 +220,16 @@ InitializeLogging(const ZenServerOptions& GlobalOptions) auto FileSink = std::make_shared<spdlog::sinks::basic_file_sink_mt>(zen::WideToUtf8(LogPath.c_str()), /* truncate */ true); // Default - auto DefaultLogger = spdlog::default_logger(); - auto& Sinks = spdlog::default_logger()->sinks(); - Sinks.clear(); + auto& DefaultLogger = zen::logging::Default(); + auto& Sinks = DefaultLogger.sinks(); + + Sinks.clear(); Sinks.push_back(ConsoleSink); Sinks.push_back(FileSink); - DefaultLogger->set_level(LogLevel); - DefaultLogger->flush_on(spdlog::level::err); // Jupiter - only log HTTP traffic to file + auto JupiterLogger = std::make_shared<spdlog::logger>("jupiter", FileSink); spdlog::register_logger(JupiterLogger); JupiterLogger->set_level(LogLevel); @@ -238,7 +238,10 @@ InitializeLogging(const ZenServerOptions& GlobalOptions) spdlog::register_logger(ZenClientLogger); ZenClientLogger->set_level(LogLevel); + // Configure all registered loggers according to settings + spdlog::set_level(LogLevel); + spdlog::flush_on(spdlog::level::err); spdlog::set_formatter(std::make_unique<logging::full_formatter>(GlobalOptions.LogId, std::chrono::system_clock::now())); } diff --git a/zenserver/experimental/usnjournal.cpp b/zenserver/experimental/usnjournal.cpp index 0553945dd..ab83b8a1c 100644 --- a/zenserver/experimental/usnjournal.cpp +++ b/zenserver/experimental/usnjournal.cpp @@ -3,11 +3,10 @@ #include "usnjournal.h" #include <zencore/except.h> +#include <zencore/logging.h> #include <zencore/timer.h> #include <zencore/zencore.h> -#include <spdlog/spdlog.h> - #include <atlfile.h> #include <filesystem> @@ -90,7 +89,7 @@ UsnJournalReader::Initialize(std::filesystem::path VolumePath) ThrowSystemException("Failed to get volume information"); } - spdlog::debug("File system type is {}", WideToUtf8(FileSystemName)); + ZEN_DEBUG("File system type is {}", WideToUtf8(FileSystemName)); if (wcscmp(L"ReFS", FileSystemName) == 0) { @@ -143,7 +142,7 @@ UsnJournalReader::Initialize(std::filesystem::path VolumePath) switch (DWORD Error = GetLastError()) { case ERROR_JOURNAL_NOT_ACTIVE: - spdlog::info("No USN journal active on drive"); + ZEN_INFO("No USN journal active on drive"); // TODO: optionally activate USN journal on drive? @@ -183,7 +182,7 @@ UsnJournalReader::Initialize(std::filesystem::path VolumePath) if (m_FileSystemType == FileSystemType::NTFS) { - spdlog::info("Enumerating MFT for {}", WideToUtf8(VolumePathName)); + ZEN_INFO("Enumerating MFT for {}", WideToUtf8(VolumePathName)); zen::Stopwatch Timer; uint64_t MftBytesProcessed = 0; @@ -262,10 +261,10 @@ UsnJournalReader::Initialize(std::filesystem::path VolumePath) const auto ElapsedMs = Timer.getElapsedTimeMs(); - spdlog::info("MFT enumeration of {} completed after {} ({})", - zen::NiceBytes(MftBytesProcessed), - zen::NiceTimeSpanMs(ElapsedMs), - zen::NiceByteRate(MftBytesProcessed, ElapsedMs)); + ZEN_INFO("MFT enumeration of {} completed after {} ({})", + zen::NiceBytes(MftBytesProcessed), + zen::NiceTimeSpanMs(ElapsedMs), + zen::NiceByteRate(MftBytesProcessed, ElapsedMs)); } // Populate by traversal diff --git a/zenserver/projectstore.cpp b/zenserver/projectstore.cpp index 2bbc1dce3..404484edf 100644 --- a/zenserver/projectstore.cpp +++ b/zenserver/projectstore.cpp @@ -7,6 +7,7 @@ #include <zencore/compactbinaryvalidation.h> #include <zencore/filesystem.h> #include <zencore/fmtutils.h> +#include <zencore/logging.h> #include <zencore/stream.h> #include <zencore/string.h> #include <zencore/timer.h> @@ -22,11 +23,8 @@ # include <rocksdb/db.h> #endif -#include <ppl.h> -#include <spdlog/spdlog.h> #include <xxh3.h> #include <asio.hpp> -#include <future> #include <latch> #include <string> @@ -66,7 +64,7 @@ struct ProjectStore::OplogStorage : public RefCounted ~OplogStorage() { - Log().info("closing oplog storage at {}", m_OplogStoragePath); + ZEN_INFO("closing oplog storage at {}", m_OplogStoragePath); Flush(); #if USE_ROCKSDB @@ -82,7 +80,7 @@ struct ProjectStore::OplogStorage : public RefCounted if (!Status.ok()) { - Log().warn("db close error reported for '{}' : '{}'", m_OplogStoragePath, Status.getState()); + ZEN_WARN("db close error reported for '{}' : '{}'", m_OplogStoragePath, Status.getState()); } } #endif @@ -98,7 +96,7 @@ struct ProjectStore::OplogStorage : public RefCounted void Open(bool IsCreate) { - Log().info("initializing oplog storage at '{}'", m_OplogStoragePath); + ZEN_INFO("initializing oplog storage at '{}'", m_OplogStoragePath); if (IsCreate) { @@ -118,7 +116,7 @@ struct ProjectStore::OplogStorage : public RefCounted { std::string RocksdbPath = WideToUtf8((m_OplogStoragePath / "ops.rdb").native().c_str()); - Log().debug("opening rocksdb db at '{}'", RocksdbPath); + ZEN_DEBUG("opening rocksdb db at '{}'", RocksdbPath); rocksdb::DB* Db; rocksdb::DBOptions Options; @@ -144,14 +142,14 @@ struct ProjectStore::OplogStorage : public RefCounted } else { - throw std::exception("column family iteration failed for '{}': '{}'"_format(RocksdbPath, Status.getState()).c_str()); + throw std::runtime_error("column family iteration failed for '{}': '{}'"_format(RocksdbPath, Status.getState()).c_str()); } Status = rocksdb::DB::Open(Options, RocksdbPath, ColumnDescriptors, &m_RocksDbColumnHandles, &Db); if (!Status.ok()) { - throw std::exception("database open failed for '{}': '{}'"_format(RocksdbPath, Status.getState()).c_str()); + throw std::runtime_error("database open failed for '{}': '{}'"_format(RocksdbPath, Status.getState()).c_str()); } m_RocksDb.reset(Db); @@ -163,7 +161,7 @@ struct ProjectStore::OplogStorage : public RefCounted { // This could use memory mapping or do something clever but for now it just reads the file sequentially - spdlog::info("replaying log for '{}'", m_OplogStoragePath); + ZEN_INFO("replaying log for '{}'", m_OplogStoragePath); Stopwatch Timer; @@ -179,7 +177,7 @@ struct ProjectStore::OplogStorage : public RefCounted if (OpCoreHash != LogEntry.OpCoreHash) { - Log().warn("skipping oplog entry with bad checksum!"); + ZEN_WARN("skipping oplog entry with bad checksum!"); return; } @@ -192,10 +190,10 @@ struct ProjectStore::OplogStorage : public RefCounted Handler(Op, LogEntry); }); - spdlog::info("Oplog replay completed in {} - Max LSN# {}, Next offset: {}", - NiceTimeSpanMs(Timer.getElapsedTimeMs()), - m_MaxLsn, - m_NextOpsOffset); + ZEN_INFO("Oplog replay completed in {} - Max LSN# {}, Next offset: {}", + NiceTimeSpanMs(Timer.getElapsedTimeMs()), + m_MaxLsn, + m_NextOpsOffset); } void ReplayLog(const std::vector<OplogEntryAddress>& Entries, std::function<void(CbObject)>&& Handler) @@ -466,7 +464,7 @@ ProjectStore::Oplog::RegisterOplogEntry(CbObject Core, const OplogEntry& OpEntry AddChunkMapping(PackageId, PackageHash); - Log().debug("package data {} -> {}", PackageId, PackageHash); + ZEN_DEBUG("package data {} -> {}", PackageId, PackageHash); } for (CbFieldView& Entry : Core["bulkdata"sv]) @@ -478,7 +476,7 @@ ProjectStore::Oplog::RegisterOplogEntry(CbObject Core, const OplogEntry& OpEntry AddChunkMapping(BulkDataId, BulkDataHash); - Log().debug("bulkdata {} -> {}", BulkDataId, BulkDataHash); + ZEN_DEBUG("bulkdata {} -> {}", BulkDataId, BulkDataHash); } if (Core["files"sv]) @@ -500,11 +498,11 @@ ProjectStore::Oplog::RegisterOplogEntry(CbObject Core, const OplogEntry& OpEntry } else { - Log().warn("invalid file"); + ZEN_WARN("invalid file"); } } - Log().debug("added {} file(s) in {}", FileCount, NiceTimeSpanMs(Timer.getElapsedTimeMs())); + ZEN_DEBUG("added {} file(s) in {}", FileCount, NiceTimeSpanMs(Timer.getElapsedTimeMs())); } for (CbFieldView& Entry : Core["meta"sv]) @@ -516,7 +514,7 @@ ProjectStore::Oplog::RegisterOplogEntry(CbObject Core, const OplogEntry& OpEntry AddMetaMapping(MetaId, MetaDataHash); - Log().debug("meta data ({}) {} -> {}", NameString, MetaId, MetaDataHash); + ZEN_DEBUG("meta data ({}) {} -> {}", NameString, MetaId, MetaDataHash); } m_OpAddressMap.emplace(OpEntry.OpLsn, OplogEntryAddress{.Offset = OpEntry.OpCoreOffset, .Size = OpEntry.OpCoreSize}); @@ -579,10 +577,10 @@ ProjectStore::Oplog::AppendNewOplogEntry(CbPackage OpPackage) const uint32_t EntryId = RegisterOplogEntry(Core, OpEntry, kUpdateNewEntry); - Log().debug("oplog entry #{} attachments: {}B new, {}B total", - EntryId, - zen::NiceBytes(NewAttachmentBytes), - zen::NiceBytes(AttachmentBytes)); + ZEN_DEBUG("oplog entry #{} attachments: {} new, {} total", + EntryId, + zen::NiceBytes(NewAttachmentBytes), + zen::NiceBytes(AttachmentBytes)); return EntryId; } @@ -611,7 +609,7 @@ ProjectStore::Project::Read() { std::filesystem::path ProjectStateFilePath = m_OplogStoragePath / "Project.zcb"; - spdlog::info("reading config for project '{}' from {}", Identifier, ProjectStateFilePath); + ZEN_INFO("reading config for project '{}' from {}", Identifier, ProjectStateFilePath); BasicFile Blob; Blob.Open(ProjectStateFilePath, false); @@ -630,7 +628,7 @@ ProjectStore::Project::Read() } else { - spdlog::error("validation error {} hit for '{}'", int(ValidationError), ProjectStateFilePath); + ZEN_ERROR("validation error {} hit for '{}'", int(ValidationError), ProjectStateFilePath); } } @@ -652,7 +650,7 @@ ProjectStore::Project::Write() std::filesystem::path ProjectStateFilePath = m_OplogStoragePath / "Project.zcb"; - spdlog::info("persisting config for project '{}' to {}", Identifier, ProjectStateFilePath); + ZEN_INFO("persisting config for project '{}' to {}", Identifier, ProjectStateFilePath); BasicFile Blob; Blob.Open(ProjectStateFilePath, true); @@ -729,7 +727,7 @@ ProjectStore::Project::OpenOplog(std::string_view OplogId) } catch (std::exception& ex) { - spdlog::error("failed to open oplog '{}' @ '{}': {}", OplogId, OplogBasePath, ex.what()); + ZEN_ERROR("failed to open oplog '{}' @ '{}': {}", OplogId, OplogBasePath, ex.what()); m_Oplogs.erase(std::string{OplogId}); } @@ -785,17 +783,17 @@ ProjectStore::Project::Flush() ////////////////////////////////////////////////////////////////////////// ProjectStore::ProjectStore(CasStore& Store, std::filesystem::path BasePath) -: m_Log("project", begin(spdlog::default_logger()->sinks()), end(spdlog::default_logger()->sinks())) +: m_Log(zen::logging::Get("project")) , m_ProjectBasePath(BasePath) , m_CasStore(Store) { - m_Log.info("initializing project store at '{}'", BasePath); - m_Log.set_level(spdlog::level::debug); + ZEN_INFO("initializing project store at '{}'", BasePath); + // m_Log.set_level(spdlog::level::debug); } ProjectStore::~ProjectStore() { - m_Log.info("closing project store ('{}')", m_ProjectBasePath); + ZEN_INFO("closing project store ('{}')", m_ProjectBasePath); } std::filesystem::path @@ -839,7 +837,7 @@ ProjectStore::OpenProject(std::string_view ProjectId) { try { - Log().info("opening project {} @ {}", ProjectId, ProjectBasePath); + ZEN_INFO("opening project {} @ {}", ProjectId, ProjectBasePath); ProjectStore::Project& Prj = m_Projects.try_emplace(std::string{ProjectId}, this, m_CasStore, ProjectBasePath).first->second; Prj.Identifier = ProjectId; @@ -848,7 +846,7 @@ ProjectStore::OpenProject(std::string_view ProjectId) } catch (std::exception& e) { - Log().warn("failed to open {} @ {} ({})", ProjectId, ProjectBasePath, e.what()); + ZEN_WARN("failed to open {} @ {} ({})", ProjectId, ProjectBasePath, e.what()); m_Projects.erase(std::string{ProjectId}); } } @@ -880,7 +878,7 @@ ProjectStore::DeleteProject(std::string_view ProjectId) { std::filesystem::path ProjectBasePath = BasePathForProject(ProjectId); - Log().info("deleting project {} @ {}", ProjectId, ProjectBasePath); + ZEN_INFO("deleting project {} @ {}", ProjectId, ProjectBasePath); m_Projects.erase(std::string{ProjectId}); @@ -908,7 +906,7 @@ ProjectStore::OpenProjectOplog(std::string_view ProjectId, std::string_view Oplo HttpProjectService::HttpProjectService(CasStore& Store, ProjectStore* Projects) : m_CasStore(Store) -, m_Log("project", begin(spdlog::default_logger()->sinks()), end(spdlog::default_logger()->sinks())) +, m_Log(logging::Get("project")) , m_ProjectStore(Projects) { using namespace std::literals; @@ -1163,7 +1161,7 @@ HttpProjectService::HttpProjectService(CasStore& Store, ProjectStore* Projects) } } - m_Log.debug("chunk - {} / {} / {}", ProjectId, OplogId, ChunkId); + ZEN_DEBUG("chunk - {} / {} / {}", ProjectId, OplogId, ChunkId); ProjectStore::Oplog* FoundLog = m_ProjectStore->OpenProjectOplog(ProjectId, OplogId); @@ -1256,7 +1254,7 @@ HttpProjectService::HttpProjectService(CasStore& Store, ProjectStore* Projects) } } - m_Log.debug("oplog hash - {} / {} / {}", ProjectId, OplogId, HashString); + ZEN_DEBUG("oplog hash - {} / {} / {}", ProjectId, OplogId, HashString); IoHash Hash = IoHash::FromHexString(HashString); IoBuffer Value = m_CasStore.FindChunk(Hash); @@ -1317,7 +1315,7 @@ HttpProjectService::HttpProjectService(CasStore& Store, ProjectStore* Projects) if (!m_CasStore.FindChunk(FileHash)) { - spdlog::debug("NEED: {}", FileHash); + ZEN_DEBUG("NEED: {}", FileHash); NeedList.push_back(FileHash); } @@ -1365,7 +1363,7 @@ HttpProjectService::HttpProjectService(CasStore& Store, ProjectStore* Projects) return HttpReq.WriteResponse(HttpResponseCode::NotFound); } - ProjectStore::Oplog& Log = *FoundLog; + ProjectStore::Oplog& Oplog = *FoundLog; IoBuffer Payload = HttpReq.ReadPayload(); @@ -1389,7 +1387,7 @@ HttpProjectService::HttpProjectService(CasStore& Store, ProjectStore* Projects) AttachmentId = Hash; } - std::filesystem::path AttachmentPath = Log.TempPath() / AttachmentId.ToHexString(); + std::filesystem::path AttachmentPath = Oplog.TempPath() / AttachmentId.ToHexString(); if (IoBuffer Data = m_CasStore.FindChunk(Hash)) { @@ -1412,7 +1410,7 @@ HttpProjectService::HttpProjectService(CasStore& Store, ProjectStore* Projects) if (!legacy::TryLoadCbPackage(Package, Payload, &UniqueBuffer::Alloc, &Resolver)) { - m_Log.error("Received malformed package!"); + ZEN_ERROR("Received malformed package!"); return HttpReq.WriteResponse(HttpResponseCode::BadRequest, HttpContentType::kText, "Invalid package"); } @@ -1433,14 +1431,14 @@ HttpProjectService::HttpProjectService(CasStore& Store, ProjectStore* Projects) // Write core to oplog - const uint32_t OpLsn = Log.AppendNewOplogEntry(Package); + const uint32_t OpLsn = Oplog.AppendNewOplogEntry(Package); if (OpLsn == ProjectStore::Oplog::kInvalidOp) { return HttpReq.WriteResponse(HttpResponseCode::BadRequest); } - m_Log.info("new op #{:4} - {}/{} ({:>6}) {}", OpLsn, ProjectId, OplogId, NiceBytes(Payload.Size()), Core["key"sv].AsString()); + ZEN_INFO("new op #{:4} - {}/{} ({:>6}) {}", OpLsn, ProjectId, OplogId, NiceBytes(Payload.Size()), Core["key"sv].AsString()); HttpReq.WriteResponse(HttpResponseCode::Created); }, @@ -1510,7 +1508,7 @@ HttpProjectService::HttpProjectService(CasStore& Store, ProjectStore* Projects) return Req.ServerRequest().WriteResponse(HttpResponseCode::InternalServerError); } - m_Log.info("established oplog {} / {}", ProjectId, OplogId); + ZEN_INFO("established oplog {} / {}", ProjectId, OplogId); return Req.ServerRequest().WriteResponse(HttpResponseCode::Created); } @@ -1524,7 +1522,7 @@ HttpProjectService::HttpProjectService(CasStore& Store, ProjectStore* Projects) case HttpVerb::kDelete: { - spdlog::info("deleting oplog {}/{}", ProjectId, OplogId); + ZEN_INFO("deleting oplog {}/{}", ProjectId, OplogId); ProjectIt->DeleteOplog(OplogId); @@ -1603,12 +1601,12 @@ HttpProjectService::HttpProjectService(CasStore& Store, ProjectStore* Projects) const std::filesystem::path BasePath = m_ProjectStore->BasePath() / ProjectId; m_ProjectStore->NewProject(BasePath, ProjectId, Root, EngineRoot, ProjectRoot); - m_Log.info("established project - {} (id: '{}', roots: '{}', '{}', '{}')", - ProjectId, - Id, - Root, - EngineRoot, - ProjectRoot); + ZEN_INFO("established project - {} (id: '{}', roots: '{}', '{}', '{}')", + ProjectId, + Id, + Root, + EngineRoot, + ProjectRoot); Req.ServerRequest().WriteResponse(HttpResponseCode::Created); } @@ -1672,7 +1670,7 @@ HttpProjectService::HandleRequest(HttpServerRequest& Request) { if (m_Router.HandleRequest(Request) == false) { - m_Log.warn("No route found for {0}", Request.RelativeUri()); + ZEN_WARN("No route found for {0}", Request.RelativeUri()); } } @@ -1738,7 +1736,7 @@ struct LocalProjectService::LocalProjectImpl } catch (std::exception& ex) { - spdlog::error("exception caught in pipe project service loop: {}", ex.what()); + ZEN_ERROR("exception caught in pipe project service loop: {}", ex.what()); } m_ShutdownLatch.count_down(); @@ -1823,7 +1821,7 @@ private: if (hPipe == INVALID_HANDLE_VALUE) { - spdlog::warn("failed while creating named pipe {}", PipeName.c_str()); + ZEN_WARN("failed while creating named pipe {}", PipeName.c_str()); // TODO: error - how to best handle? } @@ -1870,13 +1868,13 @@ private: return; } - spdlog::warn("pipe connection error: {}", Ec.message()); + ZEN_WARN("pipe connection error: {}", Ec.message()); // TODO: should disconnect and issue a new connect return; } - spdlog::debug("pipe connection established"); + ZEN_DEBUG("pipe connection established"); IssueRead(); } @@ -1898,13 +1896,13 @@ private: return; } - spdlog::warn("pipe read error: {}", Ec.message()); + ZEN_WARN("pipe read error: {}", Ec.message()); // TODO: should disconnect and issue a new connect return; } - spdlog::debug("received message: {} bytes", Bytes); + ZEN_DEBUG("received message: {} bytes", Bytes); // TODO: Actually process request @@ -1926,7 +1924,7 @@ private: return; } - spdlog::warn("pipe write error: {}", Ec.message()); + ZEN_WARN("pipe write error: {}", Ec.message()); // TODO: should disconnect and issue a new connect return; diff --git a/zenserver/projectstore.h b/zenserver/projectstore.h index 8fe189ab9..3d2247305 100644 --- a/zenserver/projectstore.h +++ b/zenserver/projectstore.h @@ -8,8 +8,8 @@ #include <zenstore/cas.h> #include <zenstore/caslog.h> -#include <spdlog/spdlog.h> #include <tsl/robin_map.h> +#include <zencore/logging.h> #include <filesystem> #include <map> #include <optional> @@ -182,7 +182,7 @@ public: const std::filesystem::path& BasePath() const { return m_ProjectBasePath; } private: - spdlog::logger m_Log; + spdlog::logger& m_Log; CasStore& m_CasStore; std::filesystem::path m_ProjectBasePath; RwLock m_ProjectsLock; @@ -221,9 +221,11 @@ public: private: CasStore& m_CasStore; - spdlog::logger m_Log; + spdlog::logger& m_Log; HttpRequestRouter m_Router; Ref<ProjectStore> m_ProjectStore; + + inline spdlog::logger& Log() { return m_Log; } }; /** Project store interface for local clients diff --git a/zenserver/sos/sos.cpp b/zenserver/sos/sos.cpp index d52a346ae..5fa6ffaae 100644 --- a/zenserver/sos/sos.cpp +++ b/zenserver/sos/sos.cpp @@ -2,8 +2,11 @@ #include "sos.h" -HttpCommonStructuredObjectStore::HttpCommonStructuredObjectStore() -: m_Log("sos", begin(spdlog::default_logger()->sinks()), end(spdlog::default_logger()->sinks())) +#include <zencore/logging.h> + +namespace zen { + +HttpCommonStructuredObjectStore::HttpCommonStructuredObjectStore() : m_Log(logging::Get("sos")) { m_Router.AddPattern("ns", "([[:alnum:]_-.]+)"); m_Router.AddPattern("bucket", "([[:alnum:]_-.]+)"); @@ -25,3 +28,5 @@ HttpCommonStructuredObjectStore::HandleRequest(zen::HttpServerRequest& HttpServi { ZEN_UNUSED(HttpServiceRequest); } + +} // namespace zen diff --git a/zenserver/sos/sos.h b/zenserver/sos/sos.h index da9064262..e602df8c4 100644 --- a/zenserver/sos/sos.h +++ b/zenserver/sos/sos.h @@ -4,7 +4,9 @@ #include <zenhttp/httpserver.h> -#include <spdlog/spdlog.h> +#include <zencore/logging.h> + +namespace zen { /** Simple Object Store API * @@ -25,6 +27,8 @@ public: virtual void HandleRequest(zen::HttpServerRequest& HttpServiceRequest) override; private: - spdlog::logger m_Log; + spdlog::logger& m_Log; zen::HttpRequestRouter m_Router; }; + +} // namespace zen diff --git a/zenserver/testing/httptest.h b/zenserver/testing/httptest.h index 5809d4e2e..b445fb450 100644 --- a/zenserver/testing/httptest.h +++ b/zenserver/testing/httptest.h @@ -2,10 +2,9 @@ #pragma once +#include <zencore/logging.h> #include <zenhttp/httpserver.h> -#include <spdlog/spdlog.h> - namespace zen { /** diff --git a/zenserver/testing/launch.cpp b/zenserver/testing/launch.cpp index b031193d5..55695ac9c 100644 --- a/zenserver/testing/launch.cpp +++ b/zenserver/testing/launch.cpp @@ -8,6 +8,7 @@ #include <zencore/fmtutils.h> #include <zencore/iobuffer.h> #include <zencore/iohash.h> +#include <zencore/logging.h> #include <zencore/windows.h> #include <zenstore/CAS.h> @@ -79,7 +80,7 @@ BasicJob::SpawnJob(std::filesystem::path ExePath, std::wstring CommandLine) m_ProcessHandle.Attach(ProcessInfo.hProcess); ::CloseHandle(ProcessInfo.hThread); - spdlog::info("Created process {}", m_ProcessId); + ZEN_INFO("Created process {}", m_ProcessId); return true; } @@ -104,7 +105,7 @@ BasicJob::Wait(uint32_t TimeoutMs) return true; } - throw std::exception("Failed wait on process handle"); + throw std::runtime_error("Failed wait on process handle"); } int @@ -115,12 +116,12 @@ BasicJob::ExitCode() if (!Success) { - spdlog::warn("failed getting exit code"); + ZEN_WARN("failed getting exit code"); } if (Ec == STILL_ACTIVE) { - spdlog::warn("getting exit code but process is STILL_ACTIVE"); + ZEN_WARN("getting exit code but process is STILL_ACTIVE"); } return gsl::narrow_cast<int>(Ec); @@ -221,7 +222,7 @@ SandboxedJob::Initialize(std::string_view AppContainerId) if (FAILED(hRes)) { - spdlog::error("Failed creating app container SID"); + ZEN_ERROR("Failed creating app container SID"); } } @@ -230,12 +231,12 @@ SandboxedJob::Initialize(std::string_view AppContainerId) PWSTR Str = nullptr; ::ConvertSidToStringSid(m_AppContainerSid, &Str); - spdlog::info("AppContainer SID : '{}'", WideToUtf8(Str)); + ZEN_INFO("AppContainer SID : '{}'", WideToUtf8(Str)); PWSTR Path = nullptr; if (SUCCEEDED(::GetAppContainerFolderPath(Str, &Path))) { - spdlog::info("AppContainer folder: '{}'", WideToUtf8(Path)); + ZEN_INFO("AppContainer folder: '{}'", WideToUtf8(Path)); ::CoTaskMemFree(Path); } @@ -311,13 +312,13 @@ SandboxedJob::SpawnJob(std::filesystem::path ExePath) return false; } - spdlog::info("Created process {}", ProcessInfo.dwProcessId); + ZEN_INFO("Created process {}", ProcessInfo.dwProcessId); return true; } HttpLaunchService::HttpLaunchService(CasStore& Store, const std::filesystem::path& SandboxBaseDir) -: m_Log("exec", begin(spdlog::default_logger()->sinks()), end(spdlog::default_logger()->sinks())) +: m_Log(logging::Get("exec")) , m_CasStore(Store) , m_SandboxPath(SandboxBaseDir) { @@ -392,7 +393,7 @@ HttpLaunchService::HttpLaunchService(CasStore& Store, const std::filesystem::pat if (!m_CasStore.FindChunk(FileHash)) { - spdlog::debug("NEED: {} {} {}", FileHash, Ob["file"sv].AsString(), Ob["size"sv].AsUInt64()); + ZEN_DEBUG("NEED: {} {} {}", FileHash, Ob["file"sv].AsString(), Ob["size"sv].AsUInt64()); NeedList.push_back(FileHash); } @@ -437,7 +438,7 @@ HttpLaunchService::HttpLaunchService(CasStore& Store, const std::filesystem::pat std::filesystem::path SandboxDir{CreateNewSandbox()}; - spdlog::debug("setting up job in sandbox '{}'", SandboxDir); + ZEN_DEBUG("setting up job in sandbox '{}'", SandboxDir); zen::DeleteDirectories(SandboxDir); zen::CreateDirectories(SandboxDir); @@ -452,7 +453,7 @@ HttpLaunchService::HttpLaunchService(CasStore& Store, const std::filesystem::pat if (IoBuffer Chunk = m_CasStore.FindChunk(FileHash); !Chunk) { - spdlog::debug("MISSING: {} {} {}", FileHash, FileName, FileSize); + ZEN_DEBUG("MISSING: {} {} {}", FileHash, FileName, FileSize); AllOk = false; NeedList.push_back(FileHash); @@ -479,7 +480,7 @@ HttpLaunchService::HttpLaunchService(CasStore& Store, const std::filesystem::pat std::wstring Executable = Utf8ToWide(Executable8); std::wstring Args = Utf8ToWide(Args8); - spdlog::debug("spawning job in sandbox '{}': '{}' '{}'", SandboxDir, Executable8, Args8); + ZEN_DEBUG("spawning job in sandbox '{}': '{}' '{}'", SandboxDir, Executable8, Args8); std::filesystem::path ExeName = SandboxDir / Executable; @@ -515,7 +516,7 @@ HttpLaunchService::HandleRequest(HttpServerRequest& Request) { if (m_Router.HandleRequest(Request) == false) { - m_Log.warn("No route found for {0}", Request.RelativeUri()); + ZEN_WARN("No route found for {0}", Request.RelativeUri()); } } diff --git a/zenserver/testing/launch.h b/zenserver/testing/launch.h index a6eb137d2..49f12e2ec 100644 --- a/zenserver/testing/launch.h +++ b/zenserver/testing/launch.h @@ -2,9 +2,9 @@ #pragma once +#include <zencore/logging.h> #include <zenhttp/httpserver.h> -#include <spdlog/spdlog.h> #include <filesystem> namespace zen { @@ -24,7 +24,9 @@ public: virtual void HandleRequest(HttpServerRequest& Request) override; private: - spdlog::logger m_Log; + inline spdlog::logger& Log() { return m_Log; } + + spdlog::logger& m_Log; HttpRequestRouter m_Router; CasStore& m_CasStore; std::filesystem::path m_SandboxPath; diff --git a/zenserver/upstream/jupiter.cpp b/zenserver/upstream/jupiter.cpp index ba6300c65..0af92da6d 100644 --- a/zenserver/upstream/jupiter.cpp +++ b/zenserver/upstream/jupiter.cpp @@ -80,7 +80,7 @@ CloudCacheSession::GetDerivedData(std::string_view BucketId, std::string_view Ke Session.SetOption(cpr::Header{{"Authorization", Auth}}); cpr::Response Response = Session.Get(); - m_Log.debug("GET {}", Response); + ZEN_DEBUG("GET {}", Response); const bool Success = Response.status_code == 200; const IoBuffer Buffer = Success ? IoBufferBuilder::MakeCloneFromMemory(Response.text.data(), Response.text.size()) : IoBuffer(); @@ -111,7 +111,7 @@ CloudCacheSession::GetRef(std::string_view BucketId, const IoHash& Key, ZenConte Session.SetOption(cpr::Header{{"Authorization", Auth}, {"Accept", ContentType}}); cpr::Response Response = Session.Get(); - m_Log.debug("GET {}", Response); + ZEN_DEBUG("GET {}", Response); const bool Success = Response.status_code == 200; const IoBuffer Buffer = Success ? IoBufferBuilder::MakeCloneFromMemory(Response.text.data(), Response.text.size()) : IoBuffer(); @@ -134,7 +134,7 @@ CloudCacheSession::GetCompressedBlob(const IoHash& Key) Session.SetOption(cpr::Header{{"Authorization", Auth}, {"Accept", "application/x-ue-comp"}}); cpr::Response Response = Session.Get(); - m_Log.debug("GET {}", Response); + ZEN_DEBUG("GET {}", Response); const bool Success = Response.status_code == 200; const IoBuffer Buffer = Success ? IoBufferBuilder::MakeCloneFromMemory(Response.text.data(), Response.text.size()) : IoBuffer(); @@ -161,7 +161,7 @@ CloudCacheSession::PutDerivedData(std::string_view BucketId, std::string_view Ke Session.SetBody(cpr::Body{(const char*)DerivedData.Data(), DerivedData.Size()}); cpr::Response Response = Session.Put(); - m_Log.debug("PUT {}", Response); + ZEN_DEBUG("PUT {}", Response); return {.Bytes = Response.uploaded_bytes, .ElapsedSeconds = Response.elapsed, .Success = Response.status_code == 200}; } @@ -192,7 +192,7 @@ CloudCacheSession::PutRef(std::string_view BucketId, const IoHash& Key, IoBuffer Session.SetBody(cpr::Body{(const char*)Ref.Data(), Ref.Size()}); cpr::Response Response = Session.Put(); - m_Log.debug("PUT {}", Response); + ZEN_DEBUG("PUT {}", Response); return {.Bytes = Response.uploaded_bytes, .ElapsedSeconds = Response.elapsed, .Success = Response.status_code == 200}; } @@ -213,7 +213,7 @@ CloudCacheSession::PutCompressedBlob(const IoHash& Key, IoBuffer Blob) Session.SetBody(cpr::Body{(const char*)Blob.Data(), Blob.Size()}); cpr::Response Response = Session.Put(); - m_Log.debug("PUT {}", Response); + ZEN_DEBUG("PUT {}", Response); return {.Bytes = Response.uploaded_bytes, .ElapsedSeconds = Response.elapsed, .Success = Response.status_code == 200}; } @@ -268,7 +268,7 @@ CloudCacheClient::CloudCacheClient(const CloudCacheClientOptions& Options) { if (!Options.OAuthProvider.starts_with("http://"sv) && !Options.OAuthProvider.starts_with("https://"sv)) { - m_Log.warn("bad provider specification: '{}' - must be fully qualified"_format(Options.OAuthProvider).c_str()); + ZEN_WARN("bad provider specification: '{}' - must be fully qualified", Options.OAuthProvider); m_IsValid = false; return; @@ -280,7 +280,7 @@ CloudCacheClient::CloudCacheClient(const CloudCacheClientOptions& Options) if (SchemePos == std::string::npos) { - m_Log.warn("Bad service URL passed to cloud cache client: '{}'", Options.ServiceUrl); + ZEN_WARN("Bad service URL passed to cloud cache client: '{}'", Options.ServiceUrl); m_IsValid = false; return; @@ -290,7 +290,7 @@ CloudCacheClient::CloudCacheClient(const CloudCacheClientOptions& Options) if (DomainEnd == std::string::npos) { - m_Log.warn("Bad service URL passed to cloud cache client: '{}' no path delimiter found", Options.ServiceUrl); + ZEN_WARN("Bad service URL passed to cloud cache client: '{}' no path delimiter found", Options.ServiceUrl); m_IsValid = false; return; @@ -347,7 +347,7 @@ CloudCacheClient::AcquireAccessToken(std::string& AuthorizationHeaderValue) json11::Json JsonResponse = json11::Json::parse(Body, /* out */ JsonError); if (!JsonError.empty()) { - spdlog::warn("failed to parse OAuth response: '{}'", JsonError); + ZEN_WARN("failed to parse OAuth response: '{}'", JsonError); return false; } diff --git a/zenserver/upstream/jupiter.h b/zenserver/upstream/jupiter.h index 9f36704fa..5535ba000 100644 --- a/zenserver/upstream/jupiter.h +++ b/zenserver/upstream/jupiter.h @@ -2,12 +2,11 @@ #pragma once +#include <zencore/logging.h> #include <zencore/refcount.h> #include <zencore/thread.h> #include <zenhttp/httpserver.h> -#include <spdlog/spdlog.h> - #include <atomic> #include <list> #include <memory> @@ -75,6 +74,8 @@ public: std::vector<IoHash> Filter(std::string_view BucketId, const std::vector<IoHash>& ChunkHashes); private: + inline spdlog::logger& Log() { return m_Log; } + spdlog::logger& m_Log; RefPtr<CloudCacheClient> m_CacheClient; detail::CloudCacheSessionState* m_SessionState; diff --git a/zenserver/upstream/upstreamcache.cpp b/zenserver/upstream/upstreamcache.cpp index aef9c0bb3..97b222a68 100644 --- a/zenserver/upstream/upstreamcache.cpp +++ b/zenserver/upstream/upstreamcache.cpp @@ -419,17 +419,19 @@ private: ZEN_UNUSED(Endpoint); - m_Log.info("{} Endpoint: {}, Bytes: {:.2f} MB, Time: {:.2f} s, Speed: {:.2f} MB/s, Avg: {:.2f} ms/request, Samples: {}", - What, - Kv.first->DisplayName(), - TotalMb, - Counters.Seconds, - TotalMb / Counters.Seconds, - (Counters.Seconds * 1000.0) / double(Counters.Count), - Counters.Count); + ZEN_INFO("{} Endpoint: {}, Bytes: {:.2f} MB, Time: {:.2f} s, Speed: {:.2f} MB/s, Avg: {:.2f} ms/request, Samples: {}", + What, + Kv.first->DisplayName(), + TotalMb, + Counters.Seconds, + TotalMb / Counters.Seconds, + (Counters.Seconds * 1000.0) / double(Counters.Count), + Counters.Count); } } + spdlog::logger& Log() { return m_Log; } + spdlog::logger& m_Log; EndpointStats m_UpStats; EndpointStats m_DownStats; @@ -455,7 +457,7 @@ public: { auto NewEnd = std::remove_if(std::begin(m_Endpoints), std::end(m_Endpoints), [this](auto& Endpoint) { const bool Ok = Endpoint->Initialize(); - m_Log.info("{} [{}]", Endpoint->DisplayName(), Ok ? "OK" : "FAILED"); + ZEN_INFO("{} [{}]", Endpoint->DisplayName(), Ok ? "OK" : "FAILED"); return !Ok; }); @@ -522,9 +524,9 @@ private: if (!m_CacheStore.Get(CacheRecord.CacheKey.Bucket, CacheRecord.CacheKey.Hash, CacheValue)) { - m_Log.warn("process upstream FAILED, '{}/{}', cache record doesn't exist", - CacheRecord.CacheKey.Bucket, - CacheRecord.CacheKey.Hash); + ZEN_WARN("process upstream FAILED, '{}/{}', cache record doesn't exist", + CacheRecord.CacheKey.Bucket, + CacheRecord.CacheKey.Hash); return; } @@ -536,10 +538,10 @@ private: } else { - m_Log.warn("process upstream FAILED, '{}/{}/{}', payload doesn't exist in CAS", - CacheRecord.CacheKey.Bucket, - CacheRecord.CacheKey.Hash, - PayloadId); + ZEN_WARN("process upstream FAILED, '{}/{}/{}', payload doesn't exist in CAS", + CacheRecord.CacheKey.Bucket, + CacheRecord.CacheKey.Hash, + PayloadId); return; } } @@ -567,7 +569,7 @@ private: } catch (std::exception& e) { - m_Log.warn("process upstream ({}/{}) FAILED '{}'", CacheRecord.CacheKey.Bucket, CacheRecord.CacheKey.Hash, e.what()); + ZEN_WARN("process upstream ({}/{}) FAILED '{}'", CacheRecord.CacheKey.Bucket, CacheRecord.CacheKey.Hash, e.what()); } } @@ -597,6 +599,8 @@ private: using UpstreamQueue = detail::BlockingQueue<UpstreamCacheRecord>; + spdlog::logger& Log() { return m_Log; } + spdlog::logger& m_Log; UpstreamCacheOptions m_Options; ::ZenCacheStore& m_CacheStore; diff --git a/zenserver/upstream/zen.cpp b/zenserver/upstream/zen.cpp index 7cdaa0036..eef92bab4 100644 --- a/zenserver/upstream/zen.cpp +++ b/zenserver/upstream/zen.cpp @@ -137,7 +137,7 @@ Mesh::EnqueueTick() { if (m_State != kExiting) { - spdlog::warn("Mesh timer error: {}", Ec.message()); + ZEN_WARN("Mesh timer error: {}", Ec.message()); } } }); @@ -198,12 +198,12 @@ Mesh::BroadcastPacket(CbObjectWriter& Obj) if (ErrorCode) { - spdlog::warn("packet broadcast failed: {}", ErrorCode.message()); + ZEN_WARN("packet broadcast failed: {}", ErrorCode.message()); } } else { - spdlog::warn("failed to open broadcast socket: {}", ErrorCode.message()); + ZEN_WARN("failed to open broadcast socket: {}", ErrorCode.message()); } } @@ -260,7 +260,7 @@ Mesh::IssueReceive() const uint16_t Port = (++It)->AsUInt16(m_SenderEndpoint.port()); const uint32_t Lsn = (++It)->AsUInt32(); - spdlog::info("received hey from {} ({})", SenderIp, SessionId); + ZEN_INFO("received hey from {} ({})", SenderIp, SessionId); RwLock::ExclusiveLockScope _(m_SessionsLock); @@ -279,7 +279,7 @@ Mesh::IssueReceive() { Oid SessionId = Field.AsObjectId(); - spdlog::info("received bye from {} ({})", SenderIp, SessionId); + ZEN_INFO("received bye from {} ({})", SenderIp, SessionId); // We could verify that it's sent from a known IP before erasing the // session, if we want to be paranoid @@ -295,13 +295,13 @@ Mesh::IssueReceive() } else { - spdlog::warn("received malformed message from {}", SenderIp); + ZEN_WARN("received malformed message from {}", SenderIp); } } break; default: - spdlog::warn("received malformed data from {}", SenderIp); + ZEN_WARN("received malformed data from {}", SenderIp); break; } } @@ -392,7 +392,7 @@ ZenStructuredCacheSession::GetCacheRecord(std::string_view BucketId, const IoHas Session.SetHeader(cpr::Header{{"Accept", Type == ZenContentType::kCbObject ? "application/x-ue-cb" : "application/octet-stream"}}); cpr::Response Response = Session.Get(); - m_Log.debug("GET {}", Response); + ZEN_DEBUG("GET {}", Response); const bool Success = Response.status_code == 200; const IoBuffer Buffer = Success ? IoBufferBuilder::MakeCloneFromMemory(Response.text.data(), Response.text.size()) : IoBuffer(); @@ -412,7 +412,7 @@ ZenStructuredCacheSession::GetCachePayload(std::string_view BucketId, const IoHa Session.SetHeader(cpr::Header{{"Accept", "application/x-ue-comp"}}); cpr::Response Response = Session.Get(); - m_Log.debug("GET {}", Response); + ZEN_DEBUG("GET {}", Response); const bool Success = Response.status_code == 200; const IoBuffer Buffer = Success ? IoBufferBuilder::MakeCloneFromMemory(Response.text.data(), Response.text.size()) : IoBuffer(); @@ -434,7 +434,7 @@ ZenStructuredCacheSession::PutCacheRecord(std::string_view BucketId, const IoHas Session.SetBody(cpr::Body{static_cast<const char*>(Value.Data()), Value.Size()}); cpr::Response Response = Session.Put(); - m_Log.debug("PUT {}", Response); + ZEN_DEBUG("PUT {}", Response); return {.Bytes = Response.uploaded_bytes, .ElapsedSeconds = Response.elapsed, .Success = Response.status_code == 200}; } @@ -452,7 +452,7 @@ ZenStructuredCacheSession::PutCachePayload(std::string_view BucketId, const IoHa Session.SetBody(cpr::Body{static_cast<const char*>(Payload.Data()), Payload.Size()}); cpr::Response Response = Session.Put(); - m_Log.debug("PUT {}", Response); + ZEN_DEBUG("PUT {}", Response); return {.Bytes = Response.uploaded_bytes, .ElapsedSeconds = Response.elapsed, .Success = Response.status_code == 200}; } diff --git a/zenserver/upstream/zen.h b/zenserver/upstream/zen.h index c4bff8980..541495818 100644 --- a/zenserver/upstream/zen.h +++ b/zenserver/upstream/zen.h @@ -111,6 +111,8 @@ public: ZenCacheResult PutCachePayload(std::string_view BucketId, const IoHash& Key, const IoHash& PayloadId, IoBuffer Payload); private: + inline spdlog::logger& Log() { return m_Log; } + spdlog::logger& m_Log; ZenStructuredCacheClient& m_Client; detail::ZenCacheSessionState* m_SessionState; diff --git a/zenserver/vfs.cpp b/zenserver/vfs.cpp index 18d8f1842..86e265b20 100644 --- a/zenserver/vfs.cpp +++ b/zenserver/vfs.cpp @@ -8,13 +8,13 @@ # include <zencore/snapshot_manifest.h> # include <zencore/stream.h> # include <zencore/windows.h> +# include <zencore/logging.h> # include <zenstore/CAS.h> # include <map> # include <atlfile.h> # include <projectedfslib.h> -# include <spdlog/spdlog.h> # pragma comment(lib, "projectedfslib.lib") @@ -54,7 +54,7 @@ public: HRESULT hRes = ManifestFile.Create(ManifestSpec.c_str(), GENERIC_READ, FILE_SHARE_READ, OPEN_EXISTING); if (FAILED(hRes)) { - spdlog::error("MANIFEST NOT FOUND!"); // TODO: add context + ZEN_ERROR("MANIFEST NOT FOUND!"); // TODO: add context return hRes; } @@ -588,11 +588,11 @@ retry: if (SUCCEEDED(hRes)) { - spdlog::info("Successfully mounted snapshot at '{}'!", WideToUtf8(RootPath.c_str())); + ZEN_INFO("Successfully mounted snapshot at '{}'!", WideToUtf8(RootPath.c_str())); } else { - spdlog::info("Failed mounting snapshot at '{}'!", WideToUtf8(RootPath.c_str())); + ZEN_INFO("Failed mounting snapshot at '{}'!", WideToUtf8(RootPath.c_str())); } return hRes; diff --git a/zenserver/zenserver.cpp b/zenserver/zenserver.cpp index c9f74daa4..3b56d8683 100644 --- a/zenserver/zenserver.cpp +++ b/zenserver/zenserver.cpp @@ -3,6 +3,7 @@ #include <zencore/filesystem.h> #include <zencore/fmtutils.h> #include <zencore/iobuffer.h> +#include <zencore/logging.h> #include <zencore/refcount.h> #include <zencore/scopeguard.h> #include <zencore/string.h> @@ -17,7 +18,6 @@ #include <fmt/format.h> #include <mimalloc-new-delete.h> #include <mimalloc.h> -#include <spdlog/spdlog.h> #include <asio.hpp> #include <exception> #include <list> @@ -88,7 +88,7 @@ public: void Initialize(ZenServiceConfig& ServiceConfig, int BasePort, int ParentPid) { using namespace fmt::literals; - spdlog::info(ZEN_APP_NAME " initializing"); + ZEN_INFO(ZEN_APP_NAME " initializing"); m_DebugOptionForcedCrash = ServiceConfig.ShouldCrash; @@ -98,11 +98,11 @@ public: if (!m_Process.IsValid()) { - spdlog::warn("Unable to initialize process handle for specified parent pid #{}", ParentPid); + ZEN_WARN("Unable to initialize process handle for specified parent pid #{}", ParentPid); } else { - spdlog::info("Using parent pid #{} to control process lifetime", ParentPid); + ZEN_INFO("Using parent pid #{} to control process lifetime", ParentPid); } } @@ -112,12 +112,12 @@ public: if (zen::NamedMutex::Exists(MutexName) || (m_ServerMutex.Create(MutexName) == false)) { - throw std::exception("Failed to create mutex '{}' - is another instance already running?"_format(MutexName).c_str()); + throw std::runtime_error("Failed to create mutex '{}' - is another instance already running?"_format(MutexName).c_str()); } // Ok so now we're configured, let's kick things off - spdlog::info("initializing storage"); + ZEN_INFO("initializing storage"); zen::CasStoreConfiguration Config; Config.RootDirectory = m_DataRoot / "cas"; @@ -126,13 +126,13 @@ public: m_CidStore = std::make_unique<zen::CidStore>(*m_CasStore, m_DataRoot / "cid"); - spdlog::info("instantiating project service"); + ZEN_INFO("instantiating project service"); m_ProjectStore = new zen::ProjectStore(*m_CasStore, m_DataRoot / "projects"); m_HttpProjectService.reset(new zen::HttpProjectService{*m_CasStore, m_ProjectStore}); m_LocalProjectService = zen::LocalProjectService::New(*m_CasStore, m_ProjectStore); - spdlog::info("instantiating compute services"); + ZEN_INFO("instantiating compute services"); std::filesystem::path SandboxDir = m_DataRoot / "exec" / "sandbox"; zen::CreateDirectories(SandboxDir); @@ -147,7 +147,7 @@ public: using namespace std::literals; auto ValueOrDefault = [](std::string_view Value, std::string_view Default) { return Value.empty() ? Default : Value; }; - spdlog::info("instantiating structured cache service"); + ZEN_INFO("instantiating structured cache service"); m_CacheStore = std::make_unique<ZenCacheStore>(*m_CasStore, m_DataRoot / "cache"); std::unique_ptr<zen::UpstreamCache> UpstreamCache; @@ -201,12 +201,12 @@ public: if (UpstreamCache->Initialize()) { - spdlog::info("upstream cache active"); + ZEN_INFO("upstream cache active"); } else { UpstreamCache.reset(); - spdlog::info("NOT using upstream cache"); + ZEN_INFO("NOT using upstream cache"); } } @@ -215,7 +215,7 @@ public: } else { - spdlog::info("NOT instantiating structured cache service"); + ZEN_INFO("NOT instantiating structured cache service"); } if (ServiceConfig.MeshEnabled) @@ -224,7 +224,7 @@ public: } else { - spdlog::info("NOT starting mesh"); + ZEN_INFO("NOT starting mesh"); } m_Http = zen::CreateHttpServer(); @@ -261,7 +261,7 @@ public: void StartMesh(int BasePort) { - spdlog::info("initializing mesh discovery"); + ZEN_INFO("initializing mesh discovery"); m_ZenMesh.Start(uint16_t(BasePort)); } @@ -274,15 +274,15 @@ public: if (!m_TestMode) { - spdlog::info("__________ _________ __ "); - spdlog::info("\\____ /____ ____ / _____// |_ ___________ ____ "); - spdlog::info(" / // __ \\ / \\ \\_____ \\\\ __\\/ _ \\_ __ \\_/ __ \\ "); - spdlog::info(" / /\\ ___/| | \\ / \\| | ( <_> ) | \\/\\ ___/ "); - spdlog::info("/_______ \\___ >___| / /_______ /|__| \\____/|__| \\___ >"); - spdlog::info(" \\/ \\/ \\/ \\/ \\/ "); + ZEN_INFO("__________ _________ __ "); + ZEN_INFO("\\____ /____ ____ / _____// |_ ___________ ____ "); + ZEN_INFO(" / // __ \\ / \\ \\_____ \\\\ __\\/ _ \\_ __ \\_/ __ \\ "); + ZEN_INFO(" / /\\ ___/| | \\ / \\| | ( <_> ) | \\/\\ ___/ "); + ZEN_INFO("/_______ \\___ >___| / /_______ /|__| \\____/|__| \\___ >"); + ZEN_INFO(" \\/ \\/ \\/ \\/ \\/ "); } - spdlog::info(ZEN_APP_NAME " now running"); + ZEN_INFO(ZEN_APP_NAME " now running"); #if USE_SENTRY sentry_clear_modulecache(); @@ -295,7 +295,7 @@ public: m_Http->Run(m_TestMode); - spdlog::info(ZEN_APP_NAME " exiting"); + ZEN_INFO(ZEN_APP_NAME " exiting"); m_IoContext.stop(); @@ -308,8 +308,9 @@ public: m_Http->RequestExit(); } - void Cleanup() { spdlog::info(ZEN_APP_NAME " cleaning up"); } + void Cleanup() { ZEN_INFO(ZEN_APP_NAME " cleaning up"); } + void SetDedicatedMode(bool State) { m_IsDedicatedMode = State; } void SetTestMode(bool State) { m_TestMode = State; } void SetDataRoot(std::filesystem::path Root) { m_DataRoot = Root; } @@ -337,7 +338,7 @@ public: } else { - spdlog::info(ZEN_APP_NAME " exiting since parent process id {} is gone", m_Process.Pid()); + ZEN_INFO(ZEN_APP_NAME " exiting since parent process id {} is gone", m_Process.Pid()); RequestExit(0); } @@ -359,7 +360,8 @@ public: } private: - bool m_TestMode = false; + bool m_IsDedicatedMode = false; + bool m_TestMode = false; std::filesystem::path m_DataRoot; std::jthread m_IoRunner; asio::io_context m_IoContext; @@ -413,7 +415,7 @@ main(int argc, char* argv[]) ParseServiceConfig(GlobalOptions.DataDir, /* out */ ServiceConfig); - spdlog::info("zen cache server starting on port {}", GlobalOptions.BasePort); + ZEN_INFO("zen cache server starting on port {}", GlobalOptions.BasePort); try { @@ -425,7 +427,7 @@ main(int argc, char* argv[]) { // Instance already running for this port? Should double check pid - spdlog::warn("Looks like there is already a process listening to this port (pid: {})", Entry->Pid); + ZEN_WARN("Looks like there is already a process listening to this port (pid: {})", Entry->Pid); } else { @@ -442,14 +444,15 @@ main(int argc, char* argv[]) ZenServer Server; Server.SetDataRoot(GlobalOptions.DataDir); Server.SetTestMode(GlobalOptions.IsTest); + Server.SetDedicatedMode(GlobalOptions.IsDedicated); Server.Initialize(ServiceConfig, GlobalOptions.BasePort, GlobalOptions.OwnerPid); // Monitor shutdown signals ShutdownThread.reset(new std::thread{[&] { - spdlog::info("shutdown monitor thread waiting for shutdown signal '{}'", ShutdownEventName); + ZEN_INFO("shutdown monitor thread waiting for shutdown signal '{}'", ShutdownEventName); ShutdownEvent->Wait(); - spdlog::info("shutdown signal received"); + ZEN_INFO("shutdown signal received"); Server.RequestExit(0); }}); |