Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

merge to stable-23-3 #851

Merged
merged 2 commits into from
Mar 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

#include <cloud/blockstore/libs/diagnostics/critical_events.h>
#include <cloud/blockstore/libs/kikimr/components.h>

#include <cloud/blockstore/libs/storage/disk_agent/disk_agent_private.h>
#include <cloud/storage/core/libs/actors/helpers.h>
#include <cloud/storage/core/libs/common/error.h>

Expand All @@ -21,87 +21,131 @@ namespace {

////////////////////////////////////////////////////////////////////////////////

class TSessionCacheActor
: public TActorBootstrapped<TSessionCacheActor>
NProto::TError SaveSessionCache(
const TString& path,
const TVector<NProto::TDiskAgentDeviceSession>& sessions,
TInstant deadline)
{
try {
NProto::TDiskAgentDeviceSessionCache proto;
proto.MutableSessions()->Reserve(static_cast<int>(sessions.size()));

// saving only active sessions
for (const auto& session: sessions) {
if (session.GetLastActivityTs() > deadline.MicroSeconds()) {
*proto.MutableSessions()->Add() = session;
}
}

const TString tmpPath{path + ".tmp"};

SerializeToTextFormat(proto, tmpPath);

if (!NFs::Rename(tmpPath, path)) {
char buf[64] = {};
const auto ec = errno;

return MakeError(
MAKE_SYSTEM_ERROR(ec),
strerror_r(ec, buf, sizeof(buf)));
}
} catch (...) {
return MakeError(E_FAIL, CurrentExceptionMessage());
}

return {};
}

////////////////////////////////////////////////////////////////////////////////

class TSessionCacheActor: public TActorBootstrapped<TSessionCacheActor>
{
private:
const TString CachePath;

TVector<NProto::TDiskAgentDeviceSession> Sessions;
TRequestInfoPtr RequestInfo;
NActors::IEventBasePtr Response;
const TDuration ReleaseInactiveSessionsTimeout;

public:
TSessionCacheActor(
TVector<NProto::TDiskAgentDeviceSession> sessions,
TString cachePath,
TRequestInfoPtr requestInfo,
NActors::IEventBasePtr response)
: CachePath {std::move(cachePath)}
, Sessions {std::move(sessions)}
, RequestInfo {std::move(requestInfo)}
, Response {std::move(response)}
TString cachePath,
TDuration releaseInactiveSessionsTimeout)
: CachePath{std::move(cachePath)}
, ReleaseInactiveSessionsTimeout{releaseInactiveSessionsTimeout}
{
ActivityType = TBlockStoreComponents::DISK_AGENT_WORKER;
}

void Bootstrap(const TActorContext& ctx);
};

////////////////////////////////////////////////////////////////////////////////
void Bootstrap(const TActorContext& ctx)
{
Become(&TThis::StateWork);

void TSessionCacheActor::Bootstrap(const TActorContext& ctx)
{
try {
NProto::TDiskAgentDeviceSessionCache proto;
proto.MutableSessions()->Assign(
std::make_move_iterator(Sessions.begin()),
std::make_move_iterator(Sessions.end())
);
LOG_INFO(
ctx,
TBlockStoreComponents::DISK_AGENT_WORKER,
"Session Cache Actor started");
}

const TString tmpPath {CachePath + ".tmp"};
private:
STFUNC(StateWork)
{
switch (ev->GetTypeRewrite()) {
HFunc(NActors::TEvents::TEvPoisonPill, HandlePoisonPill);

HFunc(
TEvDiskAgentPrivate::TEvUpdateSessionCacheRequest,
HandleUpdateSessionCache);

default:
HandleUnexpectedEvent(
ev,
TBlockStoreComponents::DISK_AGENT_WORKER);
break;
}
}

SerializeToTextFormat(proto, tmpPath);
void HandlePoisonPill(
const TEvents::TEvPoisonPill::TPtr& ev,
const TActorContext& ctx)
{
Y_UNUSED(ev);

if (!NFs::Rename(tmpPath, CachePath)) {
char buf[64] = {};
Die(ctx);
}

const auto ec = errno;
ythrow TServiceError {MAKE_SYSTEM_ERROR(ec)}
<< strerror_r(ec, buf, sizeof(buf));
}
} catch (...) {
LOG_ERROR_S(
void HandleUpdateSessionCache(
const TEvDiskAgentPrivate::TEvUpdateSessionCacheRequest::TPtr& ev,
const TActorContext& ctx)
{
LOG_INFO(
ctx,
ActivityType,
"Can't update session cache: " << CurrentExceptionMessage());
TBlockStoreComponents::DISK_AGENT_WORKER,
"Update the session cache");

ReportDiskAgentSessionCacheUpdateError();
}
auto* msg = ev->Get();

NCloud::Reply(
ctx,
*RequestInfo,
std::move(Response));
const auto deadline = ctx.Now() - ReleaseInactiveSessionsTimeout;
Y_DEBUG_ABORT_UNLESS(deadline);

Die(ctx);
}
SaveSessionCache(CachePath, msg->Sessions, deadline);

NCloud::Reply(
ctx,
*ev,
std::make_unique<
TEvDiskAgentPrivate::TEvUpdateSessionCacheResponse>());
}
};

} // namespace

////////////////////////////////////////////////////////////////////////////////

std::unique_ptr<IActor> CreateSessionCacheActor(
TVector<NProto::TDiskAgentDeviceSession> sessions,
TString cachePath,
TRequestInfoPtr requestInfo,
NActors::IEventBasePtr response)
TDuration releaseInactiveSessionsTimeout)
{
return std::make_unique<TSessionCacheActor>(
std::move(sessions),
std::move(cachePath),
std::move(requestInfo),
std::move(response));
releaseInactiveSessionsTimeout);
}

} // namespace NCloud::NBlockStore::NStorage::NDiskAgent
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
#pragma once

#include <cloud/blockstore/config/disk.pb.h>

#include <cloud/blockstore/libs/storage/core/request_info.h>

#include <library/cpp/actors/core/actor.h>
Expand All @@ -13,9 +12,7 @@ namespace NCloud::NBlockStore::NStorage::NDiskAgent {
////////////////////////////////////////////////////////////////////////////////

std::unique_ptr<NActors::IActor> CreateSessionCacheActor(
TVector<NProto::TDiskAgentDeviceSession> sessions,
TString cachePath,
TRequestInfoPtr requestInfo,
NActors::IEventBasePtr response);
TDuration releaseInactiveSessionsTimeout);

} // namespace NCloud::NBlockStore::NStorage::NDiskAgent
Original file line number Diff line number Diff line change
@@ -0,0 +1,185 @@
#include "session_cache_actor.h"

#include <cloud/blockstore/libs/storage/disk_agent/disk_agent_private.h>
#include <cloud/storage/core/libs/common/proto_helpers.h>

#include <library/cpp/testing/unittest/registar.h>

#include <util/folder/tempdir.h>
#include <util/system/fs.h>

#include <contrib/ydb/library/actors/testlib/test_runtime.h>

#include <chrono>

namespace NCloud::NBlockStore::NStorage::NDiskAgent {

using namespace NActors;
using namespace std::chrono_literals;

namespace {

////////////////////////////////////////////////////////////////////////////////

struct TActorSystem: NActors::TTestActorRuntimeBase
{
void Start()
{
SetDispatchTimeout(5s);
InitNodes();
AppendToLogSettings(
TBlockStoreComponents::START,
TBlockStoreComponents::END,
GetComponentName);
}
};

////////////////////////////////////////////////////////////////////////////////

struct TFixture: public NUnitTest::TBaseFixture
{
const TTempDir TempDir;
const TString CachedSessionsPath =
TempDir.Path() / "nbs-disk-agent-sessions.txt";
const TDuration ReleaseInactiveSessionsTimeout = 10s;

TActorSystem ActorSystem;
TActorId SessionCacheActor;
TActorId EdgeActor;

void SetUp(NUnitTest::TTestContext& /*context*/) override
{
ActorSystem.Start();

EdgeActor = ActorSystem.AllocateEdgeActor();

SessionCacheActor =
ActorSystem.Register(CreateSessionCacheActor(
CachedSessionsPath,
ReleaseInactiveSessionsTimeout)
.release());

ActorSystem.DispatchEvents(
{.FinalEvents = {{TEvents::TSystem::Bootstrap}}},
10ms);
}

void UpdateSessionCache(TVector<NProto::TDiskAgentDeviceSession> sessions)
{
ActorSystem.Send(
SessionCacheActor,
EdgeActor,
std::make_unique<TEvDiskAgentPrivate::TEvUpdateSessionCacheRequest>(
std::move(sessions))
.release());

auto response = ActorSystem.GrabEdgeEvent<
TEvDiskAgentPrivate::TEvUpdateSessionCacheResponse>();

UNIT_ASSERT(response);
UNIT_ASSERT_VALUES_EQUAL_C(
S_OK,
response->GetStatus(),
response->GetError());
}

auto LoadSessionCache()
{
NProto::TDiskAgentDeviceSessionCache proto;

ParseProtoTextFromFileRobust(CachedSessionsPath, proto);

return TVector<NProto::TDiskAgentDeviceSession>(
std::make_move_iterator(proto.MutableSessions()->begin()),
std::make_move_iterator(proto.MutableSessions()->end()));
}
};

} // namespace

////////////////////////////////////////////////////////////////////////////////

Y_UNIT_TEST_SUITE(TSessionCacheActorTest)
{
Y_UNIT_TEST_F(ShouldUpdateSessionCache, TFixture)
{
UNIT_ASSERT(!NFs::Exists(CachedSessionsPath));

ActorSystem.AdvanceCurrentTime(1h);

UpdateSessionCache({});

UNIT_ASSERT(NFs::Exists(CachedSessionsPath));
UNIT_ASSERT(LoadSessionCache().empty());

const auto updateTs1 = ActorSystem.GetCurrentTime();

{
NProto::TDiskAgentDeviceSession writer;
writer.SetClientId("client-1");
writer.SetDiskId("vol0");
writer.SetLastActivityTs(
(updateTs1 - ReleaseInactiveSessionsTimeout).MicroSeconds());

NProto::TDiskAgentDeviceSession reader;
reader.SetClientId("client-2");
reader.SetReadOnly(true);
reader.SetDiskId("vol0");
reader.SetLastActivityTs(updateTs1.MicroSeconds());

UpdateSessionCache({writer, reader});
}

{
auto sessions = LoadSessionCache();

// writer session was dropped because it was stale
UNIT_ASSERT_VALUES_EQUAL(1, sessions.size());
UNIT_ASSERT_VALUES_EQUAL("client-2", sessions[0].GetClientId());
UNIT_ASSERT_VALUES_EQUAL(
updateTs1.MicroSeconds(),
sessions[0].GetLastActivityTs());
}

ActorSystem.AdvanceCurrentTime(3s);

const auto updateTs2 = ActorSystem.GetCurrentTime();

{
NProto::TDiskAgentDeviceSession writer;
writer.SetClientId("client-1");
writer.SetDiskId("vol0");
writer.SetLastActivityTs(updateTs2.MicroSeconds());

NProto::TDiskAgentDeviceSession reader;
reader.SetClientId("client-2");
reader.SetReadOnly(true);
reader.SetDiskId("vol0");
reader.SetLastActivityTs(updateTs2.MicroSeconds());

UpdateSessionCache({writer, reader});
}

{
auto sessions = LoadSessionCache();

UNIT_ASSERT_VALUES_EQUAL(2, sessions.size());
SortBy(sessions, [](auto& s) { return s.GetClientId(); });

UNIT_ASSERT_VALUES_EQUAL("client-1", sessions[0].GetClientId());
UNIT_ASSERT_VALUES_EQUAL(
updateTs2.MicroSeconds(),
sessions[0].GetLastActivityTs());

UNIT_ASSERT_VALUES_EQUAL("client-2", sessions[1].GetClientId());
UNIT_ASSERT_VALUES_EQUAL(
updateTs2.MicroSeconds(),
sessions[1].GetLastActivityTs());
}

UpdateSessionCache({});
UNIT_ASSERT(LoadSessionCache().empty());
}
}

} // namespace NCloud::NBlockStore::NStorage::NDiskAgent
Loading