aboutsummaryrefslogtreecommitdiffstats
path: root/ydb/core/cms/cluster_info.cpp
blob: d53613c6a802966b377b8c23a2d77d5799d7a3c0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
#include "cluster_info.h"
#include "cms_state.h"

#include <util/string/builder.h>
#include <util/system/hostname.h>

#if defined BLOG_D || defined BLOG_I || defined BLOG_ERROR
#error log macro definition clash
#endif

#define BLOG_D(stream) LOG_DEBUG_S(*TlsActivationContext, NKikimrServices::CMS, stream)
#define BLOG_ERROR(stream) LOG_ERROR_S(*TlsActivationContext, NKikimrServices::CMS, stream)

namespace NKikimr {
namespace NCms {

using namespace NNodeWhiteboard;
using namespace NKikimrCms;

bool TLockableItem::IsLocked(TErrorInfo &error, TDuration defaultRetryTime,
                             TInstant now, TDuration duration) const
{
    if (State == RESTART) {
        Y_VERIFY(Lock.Defined());
        error.Code = TStatus::DISALLOW_TEMP;
        error.Reason = Sprintf("%s is restarting (permission %s owned by %s)",
                               PrettyItemName().data(), Lock->PermissionId.data(), Lock->Owner.data());
        error.Deadline = Lock->ActionDeadline;
        return true;
    }

    if (Lock.Defined()) {
        error.Code = TStatus::DISALLOW_TEMP;
        error.Reason = Sprintf("%s has planned shutdown (permission %s owned by %s)",
                               PrettyItemName().data(), Lock->PermissionId.data(), Lock->Owner.data());
        error.Deadline = Lock->ActionDeadline;
        return true;
    }

    for (auto &lock : ExternalLocks) {
        // External locks are sorted by start time.
        if (lock.LockStart > now + duration)
            break;

        if (lock.LockDeadline < now)
            continue;

        error.Code = TStatus::DISALLOW_TEMP;
        error.Reason = Sprintf("%s has planned shutdown (notification %s owned by %s)",
                               PrettyItemName().data(), lock.NotificationId.data(), lock.Owner.data());
        error.Deadline = lock.LockDeadline;
        return true;
    }

    if (!ScheduledLocks.empty() && ScheduledLocks.begin()->Order < DeactivatedLocksOrder) {
        error.Code = TStatus::DISALLOW_TEMP;
        error.Reason = Sprintf("%s has scheduled action %s owned by %s (order %" PRIu64 " vs %" PRIu64 ")",
                               PrettyItemName().data(), ScheduledLocks.begin()->RequestId.data(),
                               ScheduledLocks.begin()->Owner.data(), ScheduledLocks.begin()->Order,
                               DeactivatedLocksOrder);
        error.Deadline = now + defaultRetryTime;
        return true;
    }

    if (!TempLocks.empty()) {
        error.Code = TStatus::DISALLOW;
        error.Reason = Sprintf("%s has temporary lock", PrettyItemName().data());
        error.Deadline = now + defaultRetryTime;
        error.RollbackPoint = TempLocks.back().RollbackPoint;
        return true;
    }

    return false;
}

bool TLockableItem::IsDown(TErrorInfo &error, TInstant defaultDeadline) const
{
    if (State == RESTART) {
        Y_VERIFY(Lock.Defined());
        error.Code = TStatus::DISALLOW_TEMP;
        error.Reason = Sprintf("%s is restarting (permission %s owned by %s)",
                               PrettyItemName().data(), Lock->PermissionId.data(), Lock->Owner.data());
        error.Deadline = Lock->ActionDeadline;
        return true;
    }

    if (State != UP) {
        error.Code = TStatus::DISALLOW_TEMP;
        error.Reason = Sprintf("%s is down", PrettyItemName().data());
        error.Deadline = defaultDeadline;
        return true;
    }

    return false;
}

void TLockableItem::RollbackLocks(ui64 point)
{
    for (auto it = TempLocks.begin(); it != TempLocks.end(); ++it)
        if (it->RollbackPoint >= point) {
            TempLocks.erase(it, TempLocks.end());
            break;
        }
}

void TLockableItem::ReactivateScheduledLocks()
{
    DeactivatedLocksOrder = Max<ui64>();
}

void TLockableItem::DeactivateScheduledLocks(ui64 order)
{
    DeactivatedLocksOrder = order;
}

void TLockableItem::RemoveScheduledLocks(const TString &requestId)
{
    ScheduledLocks.remove_if([&requestId](auto &lock) {
            return lock.RequestId == requestId;
        });
}

void TLockableItem::MigrateOldInfo(const TLockableItem &old)
{
    Downtime = old.Downtime;
    if (State != NKikimrCms::UP)
        Downtime.AddDowntime(old.Timestamp, Timestamp, "known downtime");
    Downtime.CleanupOldSegments(Timestamp);
}

void TLockableItem::DebugLocksDump(IOutputStream &ss, const TString &prefix) const
{
    if (Lock.Defined())
        ss << prefix << "Locked by permission " << Lock->PermissionId << Endl;

    for (auto &lock : ExternalLocks)
        ss << prefix << "External lock by notifications " << lock.NotificationId;

    for (auto &lock : ScheduledLocks)
        ss << prefix << "Scheduled lock by request " << lock.RequestId;

    for (auto &lock : TempLocks)
        ss << prefix << "Temporary lock at point " << lock.RollbackPoint;
}

void TNodeInfo::MigrateOldInfo(const TLockableItem &old)
{ 
    TLockableItem::MigrateOldInfo(old);
    if (auto * oldNode = dynamic_cast<const TNodeInfo *>(&old)) { 
        if (oldNode->State == UP) { 
            PreviousTenant = oldNode->Tenant; 
        } else { 
            PreviousTenant = oldNode->PreviousTenant; 
        } 
 
        if (!HasTenantInfo || State != UP) 
            Tenant = PreviousTenant; 
        HasTenantInfo = true; 
    } 
} 
 
TString TPDiskInfo::ItemName() const
{
    return Sprintf("PDisk %s", PDiskId.ToString().data());
}

TString TPDiskInfo::PrettyItemName() const
{
    TStringBuilder name;

    name << ItemName();
    if (Host || Path) {
        name << " (";

        if (Host) {
            name << Host;
        }
        if (Path) {
            name << ":" << Path;
        }

        name << ")";
    }

    return name;
}

TString TPDiskInfo::GetDeviceName() const
{
    return Sprintf("pdisk-%" PRIu32 "-%" PRIu32, PDiskId.NodeId, PDiskId.DiskId);
}

bool TPDiskInfo::NameToId(const TString &name, TPDiskID &id)
{
    int size;

    if (sscanf(name.data(), "pdisk-%" SCNu32 "-%" SCNu32 "%n", &id.NodeId, &id.DiskId, &size) != 2)
        return false;

    if (size != static_cast<int>(name.size()))
        return false;

    return true;
}

bool TPDiskInfo::IsDeviceName(const TString &name)
{
    TPDiskID id;
    return NameToId(name, id);
}

TPDiskID TPDiskInfo::NameToId(const TString &name)
{
    TPDiskID id;
    NameToId(name, id);
    return id;
}

void TPDiskInfo::MigrateOldInfo(const TLockableItem &old)
{
    TLockableItem::MigrateOldInfo(old);
    if (auto *oldPDisk = dynamic_cast<const TPDiskInfo *>(&old)) {
        if (!NodeId)
            NodeId = oldPDisk->NodeId;
    }
}

TString TVDiskInfo::ItemName() const
{
    return Sprintf("VDisk %s", VDiskId.ToString().data());
}

TString TVDiskInfo::PrettyItemName() const
{
    TStringBuilder name;

    name << ItemName();
    if (Host || Path) {
        name << " (";

        if (Host) {
            name << Host;
        }
        if (Path) {
            name << ":" << Path;
        }

        name << ")";
    }

    return name;
}

TString TVDiskInfo::GetDeviceName() const
{
    return Sprintf("vdisk-%u-%u-%u-%u-%u", VDiskId.GroupID, VDiskId.GroupGeneration,
                   VDiskId.FailRealm, VDiskId.FailDomain, VDiskId.VDisk);
}

bool TVDiskInfo::NameToId(const TString &name, TVDiskID &id)
{
    ui32 group, gen, ring, domain, vdisk;
    int size;

    if (sscanf(name.data(), "vdisk-%" SCNu32 "-%" SCNu32 "-%" SCNu32 "-%" SCNu32 "-%" SCNu32 "%n",
               &group, &gen, &ring, &domain, &vdisk, &size) != 5)
        return false;

    if (size != static_cast<int>(name.size()))
        return false;

    id = TVDiskID(group, gen, ring, domain, vdisk);

    return true;
}

bool TVDiskInfo::IsDeviceName(const TString &name)
{
    TVDiskID id;
    return NameToId(name, id);
}

TVDiskID TVDiskInfo::NameToId(const TString &name)
{
    TVDiskID id;
    NameToId(name, id);
    return id;
}

void TVDiskInfo::MigrateOldInfo(const TLockableItem &old)
{
    TLockableItem::MigrateOldInfo(old);
    if (auto *oldVDisk = dynamic_cast<const TVDiskInfo *>(&old)) {
        if (!NodeId)
            NodeId = oldVDisk->NodeId;
        if (!PDiskId)
            PDiskId = oldVDisk->PDiskId;
    }
}

void TClusterInfo::SetTimestamp(TInstant timestamp)
{
    Timestamp = timestamp;
    for (auto &entry : LockableItems)
        entry.second->Timestamp = timestamp;
}

void TClusterInfo::AddNode(const TEvInterconnect::TNodeInfo &info, const TActorContext *ctx)
{
    TNodeInfoPtr &node = Nodes[info.NodeId];
    if (!node)
        node = new TNodeInfo;

    TString oldHost = node->Host;
    node->NodeId = info.NodeId;
    node->Host = info.Host;
    node->Address = info.Address;
    node->IcPort = info.Port;
    node->Location = info.Location;
    node->State = NKikimrCms::UNKNOWN;

    if (ctx) {
        const auto maxStaticNodeId = AppData(*ctx)->DynamicNameserviceConfig->MaxStaticNodeId;
        if (node->NodeId <= maxStaticNodeId) {
            node->Services |= EService::Storage;
        } else {
            node->Services |= EService::DynamicNode;
        }
    }

    auto range = HostNameToNodeId.equal_range(oldHost);
    for (auto it = range.first; it != range.second; ++it) {
        if (it->second == node->NodeId) {
            HostNameToNodeId.erase(it);
            break;
        }
    }

    HostNameToNodeId.emplace(node->Host, node->NodeId);
    LockableItems[node->ItemName()] = node;
}

void TClusterInfo::SetNodeState(ui32 nodeId, NKikimrCms::EState state, const NKikimrWhiteboard::TSystemStateInfo &info)
{
    if (!HasNode(nodeId))
        return;

    auto &node = NodeRef(nodeId);
    node.State = state;
    node.Version = info.GetVersion();

    node.Services = TServices();
    for (const auto& role : info.GetRoles()) {
        EService value;
        if (TryFromWhiteBoardRole(role, value)) {
            node.Services |= value;
        }
    }
}

void TClusterInfo::ClearNode(ui32 nodeId)
{
    if (!HasNode(nodeId))
        return;

    auto &node = NodeRef(nodeId);
    for (auto tablet : node.Tablets)
        Tablets.erase(tablet);
    node.Tablets.clear();
    node.State = NKikimrCms::DOWN;
}

void TClusterInfo::ApplyInitialNodeTenants(const TActorContext& ctx, const THashMap<ui32, TString>& nodeTenants) 
{ 
    for (const auto& pr : nodeTenants) { 
        ui32 nodeId = pr.first; 
        TString tenant = pr.second; 
 
        if (!HasNode(nodeId)) { 
            LOG_ERROR(ctx, NKikimrServices::CMS, 
                      "Forgoten node tenant '%s' at node %" PRIu32 ". Node is unknown.", 
                      tenant.data(), nodeId);
            continue; 
        } 
 
        TNodeInfo& node = NodeRef(nodeId); 
        node.PreviousTenant = tenant; 
 
        LOG_DEBUG(ctx, NKikimrServices::CMS, 
                  "Initial node tenant '%s' at node %" PRIu32, 
                  tenant.data(), nodeId);
    } 
} 
 
void TClusterInfo::AddTablet(ui32 nodeId, const NKikimrWhiteboard::TTabletStateInfo &info)
{
    if (!HasNode(nodeId))
        return;

    TTabletInfo &tablet = Tablets[info.GetTabletId()];
    tablet.TabletId = info.GetTabletId();
    tablet.Type = info.GetType();
    tablet.State = info.GetState();
    tablet.Leader = info.GetLeader();
    tablet.NodeId = nodeId;

    auto &node = NodeRef(nodeId);
    node.Tablets.insert(tablet.TabletId);
}

void TClusterInfo::AddPDisk(const NKikimrBlobStorage::TBaseConfig::TPDisk &info)
{
    ui32 nodeId = info.GetNodeId();
    ui32 pdiskId = info.GetPDiskId();
    auto &path = info.GetPath();

    if (!HasNode(nodeId))
        return;

    TPDiskID id  = {nodeId, pdiskId};
    TPDiskInfoPtr &pdisk = PDisks[id];
    if (!pdisk)
        pdisk = new TPDiskInfo;

    pdisk->PDiskId = id;
    pdisk->NodeId = nodeId;
    pdisk->Path = path;

    auto &node = NodeRef(nodeId);
    pdisk->Host = node.Host;
    node.PDisks.insert(id);

    LockableItems[pdisk->ItemName()] = pdisk;
}

void TClusterInfo::UpdatePDiskState(const TPDiskID &id, const NKikimrWhiteboard::TPDiskStateInfo &info)
{
    if (!HasPDisk(id)) {
        BLOG_ERROR("Cannot update state for unknown PDisk " << id.ToString());
        return;
    }

    auto &pdisk = PDiskRef(id);
    pdisk.State = info.GetState() == NKikimrBlobStorage::TPDiskState::Normal ? UP : DOWN;
}

void TClusterInfo::AddVDisk(const NKikimrBlobStorage::TBaseConfig::TVSlot &info)
{
    ui32 nodeId = info.GetVSlotId().GetNodeId();
    Y_VERIFY_DEBUG(HasNode(nodeId));
    if (!HasNode(nodeId)) {
        BLOG_ERROR("Got VDisk info from BSC base config for unknown node " << nodeId);
        return;
    }

    TVDiskID vdiskId(info.GetGroupId(),
                     info.GetGroupGeneration(),
                     info.GetFailRealmIdx(),
                     info.GetFailDomainIdx(),
                     info.GetVDiskIdx());
    TVDiskInfoPtr &vdisk = VDisks[vdiskId];
    if (!vdisk)
        vdisk = new TVDiskInfo;

    vdisk->VDiskId = vdiskId;
    vdisk->PDiskId = {nodeId, info.GetVSlotId().GetPDiskId()};
    vdisk->NodeId = nodeId;
    vdisk->SlotId = info.GetVSlotId().GetVSlotId();

    Y_VERIFY_DEBUG(HasPDisk(vdisk->PDiskId));
    if (!HasPDisk(vdisk->PDiskId)) {
        BLOG_ERROR("Got VDisk info from BSC base config for unknown PDisk " << vdisk->PDiskId.ToString());
        PDisks.emplace(vdisk->PDiskId, new TPDiskInfo(vdisk->PDiskId));
    }

    auto &pdisk = PDiskRef(vdisk->PDiskId);
    vdisk->Path = pdisk.Path;
    pdisk.VDisks.insert(vdisk->VDiskId);
    pdisk.VSlots[vdisk->SlotId] = vdisk->VDiskId;

    auto &node = NodeRef(nodeId);
    vdisk->Host = node.Host;
    node.VDisks.insert(vdisk->VDiskId);

    LockableItems[vdisk->ItemName()] = vdisk;
}

void TClusterInfo::UpdateVDiskState(const TVDiskID &id, const NKikimrWhiteboard::TVDiskStateInfo &info)
{
    if (!HasVDisk(id)) {
        if (IsStaticGroupVDisk(id)) {
            return;
        }

        BLOG_ERROR("Cannot update state for unknown VDisk " << id.ToString());
        return;
    }

    auto &vdisk = VDiskRef(id);
    if (info.GetVDiskState() == NKikimrWhiteboard::OK && info.GetReplicated())
        vdisk.State = UP;
    else
        vdisk.State = DOWN;
}

void TClusterInfo::AddBSGroup(const NKikimrBlobStorage::TBaseConfig::TGroup &info)
{
    TBSGroupInfo bsgroup;
    bsgroup.GroupId = info.GetGroupId();
    if (info.GetErasureSpecies())
        bsgroup.Erasure = {TErasureType::ErasureSpeciesByName(info.GetErasureSpecies())};
    for (const auto &vdisk : info.GetVSlotId()) {
        TPDiskID pdiskId = {vdisk.GetNodeId(), vdisk.GetPDiskId()};
        Y_VERIFY_DEBUG(HasPDisk(pdiskId));
        if (!HasPDisk(pdiskId)) {
            BLOG_ERROR("Group " << bsgroup.GroupId << " refers unknown pdisk " << pdiskId.ToString());
            return;
        }

        auto &pdisk = PDiskRef(pdiskId);
        Y_VERIFY_DEBUG(pdisk.VSlots.contains(vdisk.GetVSlotId()));
        if (!pdisk.VSlots.contains(vdisk.GetVSlotId())) {
            BLOG_ERROR("Group " << bsgroup.GroupId << " refers unknown slot " <<
                        vdisk.GetVSlotId() << " in disk " << pdiskId.ToString());
            return;
        }

        bsgroup.VDisks.insert(pdisk.VSlots.at(vdisk.GetVSlotId()));
    }

    for (auto &vdisk : bsgroup.VDisks)
        VDiskRef(vdisk).BSGroups.insert(bsgroup.GroupId);
    BSGroups[bsgroup.GroupId] = std::move(bsgroup);
}

void TClusterInfo::AddNodeTenants(ui32 nodeId, const NKikimrTenantPool::TTenantPoolStatus &info) 
{ 
    if (!HasNode(nodeId)) 
        return; 
 
    auto& node = NodeRef(nodeId); 
    TString nodeTenant; 
 
    for (const auto& slot : info.GetSlots()) { 
        TString slotTenant = slot.GetAssignedTenant(); 
        Y_VERIFY(slotTenant.empty() || nodeTenant.empty() || slotTenant == nodeTenant); 
        if (!slotTenant.empty()) 
            nodeTenant = slotTenant; 
    } 
 
    node.Tenant = nodeTenant; 
    node.HasTenantInfo = true; 

    TenantToNodeId.emplace(nodeTenant, nodeId);
} 
 
void TClusterInfo::AddNodeTempLock(ui32 nodeId, const NKikimrCms::TAction &action)
{
    auto &node = NodeRef(nodeId);
    node.TempLocks.push_back({RollbackPoint, action});
}

void TClusterInfo::AddPDiskTempLock(TPDiskID pdiskId, const NKikimrCms::TAction &action)
{
    auto &pdisk = PDiskRef(pdiskId);
    pdisk.TempLocks.push_back({RollbackPoint, action});
}

void TClusterInfo::AddVDiskTempLock(TVDiskID vdiskId, const NKikimrCms::TAction &action)
{
    auto &vdisk = VDiskRef(vdiskId);
    vdisk.TempLocks.push_back({RollbackPoint, action});
}

static TServices MakeServices(const NKikimrCms::TAction &action) {
    TServices services;

    if (action.GetType() != TAction::RESTART_SERVICES) {
        return services;
    }

    for (const auto &service : action.GetServices()) {
        EService value;
        if (TryFromString(service, value)) {
            services |= value;
        }
    }

    return services;
}

TSet<TLockableItem *> TClusterInfo::FindLockedItems(const NKikimrCms::TAction &action,
                                                    const TActorContext *ctx)
{
    TSet<TLockableItem *> res;

    if (ActionRequiresHost(action) && !HasNode(action.GetHost())) {
        if (ctx)
            LOG_ERROR(*ctx, NKikimrServices::CMS, "FindLockedItems: unknown host %s",
                      action.GetHost().data());
        return res;
    }

    switch (action.GetType()) {
    case TAction::RESTART_SERVICES:
    case TAction::SHUTDOWN_HOST:
        if (auto nodes = NodePtrs(action.GetHost(), MakeServices(action))) {
            for (const auto node : nodes) {
                res.insert(node);
            }
        } else if (ctx) {
            LOG_ERROR_S(*ctx, NKikimrServices::CMS,
                        "FindLockedItems: unknown host " << action.GetHost());
        }
        break;

    case TAction::REPLACE_DEVICES:
        for (const auto &device : action.GetDevices()) {
            TLockableItem *item = nullptr;

            if (HasPDisk(device))
                item = &PDiskRef(device);
            else if (HasVDisk(device))
                item = &VDiskRef(device);

            if (item)
                res.insert(item);
            else if (ctx)
                LOG_ERROR(*ctx, NKikimrServices::CMS, "FindLockedItems: unknown device %s", device.data());
        }
        break;

    default:
        if (ctx) {
            LOG_ERROR(*ctx, NKikimrServices::CMS, "FindLockedItems: action %s is not supported",
                      TAction::EType_Name(action.GetType()).data());
        }
        break;
    }

    return res;
}

ui64 TClusterInfo::AddLocks(const TPermissionInfo &permission, const TActorContext *ctx)
{
    TInstant deadline(permission.Deadline);
    TDuration duration = TDuration::MicroSeconds(permission.Action.GetDuration());
    Y_UNUSED(duration);
    auto items = FindLockedItems(permission.Action, ctx);
    ui64 locks = 0;

    for (auto item : items) {
        bool lock = false;

        if (deadline > Timestamp)
            lock = true;

        if (item->State == DOWN
            && (permission.Action.GetType() == TAction::RESTART_SERVICES
                || permission.Action.GetType() == TAction::SHUTDOWN_HOST
                || permission.Action.GetType() == TAction::REPLACE_DEVICES)) {
            item->State = RESTART;
            lock = true;;
        }

        if (lock) {
            if (ctx)
                LOG_INFO(*ctx, NKikimrServices::CMS, "Adding lock for %s (permission %s until %s)",
                          item->PrettyItemName().data(), permission.PermissionId.data(),
                          permission.Deadline.ToStringLocalUpToSeconds().data());
            item->AddLock(permission);
            ++locks;
        }
    }

    return locks;
}

ui64 TClusterInfo::AddExternalLocks(const TNotificationInfo &notification, const TActorContext *ctx)
{
    ui64 locks = 0;
    for (const auto &action : notification.Notification.GetActions()) {
        auto items = FindLockedItems(action, ctx);

        for (auto item : items) {
            if (ctx)
                LOG_INFO(*ctx, NKikimrServices::CMS, "Adding external lock for %s",
                          item->PrettyItemName().data());

            item->AddExternalLock(notification, action);
        }

        locks += items.size();
    }

    return locks;
}

void TClusterInfo::ApplyDowntimes(const TDowntimes &downtimes)
{
    for (auto &pr : downtimes.NodeDowntimes) {
        if (!HasNode(pr.first))
            continue;
        NodeRef(pr.first).Downtime = pr.second;
    }
    for (auto &pr : downtimes.PDiskDowntimes) {
        if (!HasPDisk(pr.first))
            continue;
        PDiskRef(pr.first).Downtime = pr.second;
    }
}

void TClusterInfo::UpdateDowntimes(TDowntimes &downtimes, const TActorContext &ctx)
{
    downtimes.CleanupOld(ctx.Now());

    for (auto &pr : Nodes) {
        if (pr.second->State != NKikimrCms::UP)
            downtimes.NodeDowntimes[pr.first] = pr.second->Downtime;
    }
    for (auto &pr : PDisks) {
        if (pr.second->State != NKikimrCms::UP)
            downtimes.PDiskDowntimes[pr.first] = pr.second->Downtime;
    }
}

ui64 TClusterInfo::AddTempLocks(const NKikimrCms::TAction &action, const TActorContext *ctx)
{
    auto items = FindLockedItems(action, ctx);

    for (auto item : items)
        item->TempLocks.push_back({RollbackPoint, action});

    return items.size();
}

ui64 TClusterInfo::ScheduleActions(const TRequestInfo &request, const TActorContext *ctx)
{
    ui64 locks = 0;
    for (const auto &action : request.Request.GetActions()) {
        auto items = FindLockedItems(action, ctx);

        for (auto item : items)
            item->ScheduleLock({action, request.Owner, request.RequestId, request.Order});

        locks += items.size();
    }

    return locks;
}

void TClusterInfo::UnscheduleActions(const TString &requestId)
{
    for (auto &entry : LockableItems)
        entry.second->RemoveScheduledLocks(requestId);
}

void TClusterInfo::DeactivateScheduledLocks(ui64 order)
{
    for (auto &entry : LockableItems)
        entry.second->DeactivateScheduledLocks(order);
}

void TClusterInfo::ReactivateScheduledLocks()
{
    for (auto &entry : LockableItems)
        entry.second->ReactivateScheduledLocks();
}

void TClusterInfo::RollbackLocks(ui64 point)
{
    if (!point || point > RollbackPoint)
        return;

    for (auto &entry : LockableItems)
        entry.second->RollbackLocks(point);
    RollbackPoint = point - 1;
}

void TClusterInfo::MigrateOldInfo(TClusterInfoPtr old)
{
    for (auto &entry : LockableItems) {
        auto it = old->LockableItems.find(entry.first);
        if (it != old->LockableItems.end())
            entry.second->MigrateOldInfo(*it->second);
    }
}

void TClusterInfo::DebugDump(const TActorContext &ctx) const
{
    LOG_DEBUG_S(ctx, NKikimrServices::CMS,
                "Timestamp: " << Timestamp.ToStringLocalUpToSeconds());
    for (auto &entry: Nodes) {
        TStringStream ss;
        auto &node = *entry.second;
        ss << "Node {" << Endl
           << "  Id: " << (ui32)node.NodeId << Endl
           << "  Host: " << node.Host << Endl
           << "  Address: " << node.Address << Endl
           << "  Version: " << node.Version << Endl
           << "  State: " << EState_Name(node.State) << Endl;
        for (auto pd : node.PDisks)
            ss << "  PDisk: " << pd.NodeId << ":" << pd.DiskId << Endl;
        for (auto &vd : node.VDisks)
            ss << "  VDisk: " << vd.ToString() << Endl;
        node.DebugLocksDump(ss, "  ");
        ss << "}" << Endl;
        LOG_DEBUG(ctx, NKikimrServices::CMS, ss.Str());
    }
    for (auto &entry: PDisks) {
        TStringStream ss;
        auto &pdisk = *entry.second;
        ss << "PDisk {" << Endl
           << "  Id: " << pdisk.PDiskId.NodeId << ":" << pdisk.PDiskId.DiskId << Endl
           << "  NodeId: " << pdisk.NodeId << Endl
           << "  State: " << EState_Name(pdisk.State) << Endl;
        pdisk.DebugLocksDump(ss, "  ");
        ss << "}" << Endl;
        LOG_DEBUG(ctx, NKikimrServices::CMS, ss.Str());
    }
    for (auto &entry: VDisks) {
        TStringStream ss;
        auto &vdisk = *entry.second;
        ss << "VDisk {" << Endl
           << "  Id: " << vdisk.VDiskId.ToString() << Endl
           << "  NodeId: " << vdisk.NodeId << Endl
           << "  State: " << EState_Name(vdisk.State) << Endl
           << "  PDisk: " << vdisk.PDiskId.NodeId << ":" << vdisk.PDiskId.DiskId << Endl;
        for (auto id : vdisk.BSGroups)
            ss << "  BSGroup: " << id << Endl;
        vdisk.DebugLocksDump(ss, "  ");
        ss << "}" << Endl;
        LOG_DEBUG(ctx, NKikimrServices::CMS, ss.Str());
    }
    for (auto &entry: BSGroups) {
        TStringStream ss;
        auto &group = entry.second;
        ss << "BSGroup {" << Endl
           << "  Id: " << (ui32)group.GroupId << Endl;
        if (group.Erasure.GetErasure() == TErasureType::ErasureSpeciesCount)
            ss << "  Erasure: UNKNOWN" << Endl;
        else
            ss << "  Erasure: " << group.Erasure.ToString() << Endl;
        for (auto &vd : group.VDisks)
            ss << "  VDisk: " << vd.ToString() << Endl;
        ss << "}" << Endl;
        LOG_DEBUG(ctx, NKikimrServices::CMS, ss.Str());
    }
}

} // NCms
} // NKikimr