aboutsummaryrefslogtreecommitdiffstats
path: root/kikimr/yndx/grpc_services/persqueue/grpc_pq_write.cpp
blob: 36ba3fa8f6fd93518a3925233030f75ce7d4c358 (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
#include "grpc_pq_write.h"
#include "grpc_pq_actor.h"
#include "grpc_pq_session.h"
#include "ydb/core/client/server/grpc_proxy_status.h"

#include <ydb/core/base/appdata.h>
#include <util/generic/queue.h>

using namespace NActors;
using namespace NKikimrClient;

using grpc::Status;

namespace NKikimr {
namespace NGRpcProxy {

using namespace NPersQueue;

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


void TPQWriteServiceImpl::TSession::OnCreated() {            // Start waiting for new session.
    Proxy->WaitWriteSession();
    if (Proxy->TooMuchSessions()) {
        ReplyWithError("proxy overloaded", NPersQueue::NErrorCode::OVERLOAD);
        return;
    }
    TMaybe<TString> localCluster = Proxy->AvailableLocalCluster();
    if (NeedDiscoverClusters) {
        if (!localCluster.Defined()) {
            ReplyWithError("initializing", NPersQueue::NErrorCode::INITIALIZING);
            return;
        } else if (localCluster->empty()) {
            ReplyWithError("cluster disabled", NPersQueue::NErrorCode::CLUSTER_DISABLED);
            return;
        } else {
            CreateActor(*localCluster);
        }
    } else {
        CreateActor(TString());
    }
    ReadyForNextRead();
}

void TPQWriteServiceImpl::TSession::OnRead(const TWriteRequest& request) {

    switch (request.GetRequestCase()) {
        case TWriteRequest::kInit: {
            SendEvent(new TEvPQProxy::TEvWriteInit(request, GetPeerName(), GetDatabase()));
            break;
        }
        case TWriteRequest::kDataBatch:
        case TWriteRequest::kData: {
            SendEvent(new TEvPQProxy::TEvWrite(request));
            break;
        }
        default: {
            ReplyWithError("unsupported request", NPersQueue::NErrorCode::BAD_REQUEST);
        }
    }
}

void TPQWriteServiceImpl::TSession::OnDone() {
    SendEvent(new TEvPQProxy::TEvDone());
}

TPQWriteServiceImpl::TSession::TSession(std::shared_ptr<TPQWriteServiceImpl> proxy,
             grpc::ServerCompletionQueue* cq, ui64 cookie, const TActorId& schemeCache,
             TIntrusivePtr<NMonitoring::TDynamicCounters> counters, bool needDiscoverClusters)
    : ISession(cq)
    , Proxy(proxy)
    , Cookie(cookie)
    , SchemeCache(schemeCache)
    , Counters(counters)
    , NeedDiscoverClusters(needDiscoverClusters)
{
}

void TPQWriteServiceImpl::TSession::Start() {
    if (!Proxy->IsShuttingDown()) {
        Proxy->RequestSession(&Context, &Stream, CQ, CQ, new TRequestCreated(this));
    }
}

ui64 TPQWriteServiceImpl::TSession::GetCookie() const {
    return Cookie;
}

void TPQWriteServiceImpl::TSession::DestroyStream(const TString& reason, const NPersQueue::NErrorCode::EErrorCode errorCode) {
    // Send poison pill to the actor(if it is alive)
    SendEvent(new TEvPQProxy::TEvDieCommand("write-session " + ToString<ui64>(Cookie) + ": " + reason, errorCode));
    // Remove reference to session from "cookie -> session" map.
    Proxy->ReleaseSession(this);
}

bool TPQWriteServiceImpl::TSession::IsShuttingDown() const {
    return Proxy->IsShuttingDown();
}

void TPQWriteServiceImpl::TSession::CreateActor(const TString &localCluster) {

    auto classifier = Proxy->GetClassifier();
    ActorId = Proxy->ActorSystem->Register(
        new TWriteSessionActor(this, Cookie, SchemeCache, Counters, localCluster,
                                        classifier ? classifier->ClassifyAddress(GetPeerName())
                                                   : "unknown"), TMailboxType::Simple, 0
    );
}

void TPQWriteServiceImpl::TSession::SendEvent(IEventBase* ev) {
    Proxy->ActorSystem->Send(ActorId, ev);
}

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


TPQWriteServiceImpl::TPQWriteServiceImpl(grpc::ServerCompletionQueue* cq,
                             NActors::TActorSystem* as, const TActorId& schemeCache,
                             TIntrusivePtr<NMonitoring::TDynamicCounters> counters, const ui32 maxSessions)
    : CQ(cq)
    , ActorSystem(as)
    , SchemeCache(schemeCache)
    , Counters(counters)
    , MaxSessions(maxSessions)
    , NeedDiscoverClusters(false)
{
}

void TPQWriteServiceImpl::InitClustersUpdater()
{
    TAppData* appData = ActorSystem->AppData<TAppData>();
    NeedDiscoverClusters = !appData->PQConfig.GetTopicsAreFirstClassCitizen();
    if (NeedDiscoverClusters) {
        ActorSystem->Register(new TClustersUpdater(this));
    }
}


ui64 TPQWriteServiceImpl::NextCookie() {
    return AtomicIncrement(LastCookie);
}


void TPQWriteServiceImpl::ReleaseSession(TSessionRef session) {
    with_lock (Lock) {
        bool erased = Sessions.erase(session->GetCookie());
        if (erased) {
            ActorSystem->Send(MakeGRpcProxyStatusID(ActorSystem->NodeId), new TEvGRpcProxyStatus::TEvUpdateStatus(0, 0, -1, 0));
        }
    }
}


void TPQWriteServiceImpl::SetupIncomingRequests() {
    WaitWriteSession();
}


void TPQWriteServiceImpl::WaitWriteSession() {

    const ui64 cookie = NextCookie();

    ActorSystem->Send(MakeGRpcProxyStatusID(ActorSystem->NodeId), new TEvGRpcProxyStatus::TEvUpdateStatus(0,0,1,0));

    TSessionRef session(new TSession(shared_from_this(), CQ, cookie, SchemeCache, Counters, NeedDiscoverClusters));
    {
        with_lock (Lock) {
            Sessions[cookie] = session;
        }
    }

    session->Start();
}


bool TPQWriteServiceImpl::TooMuchSessions() {
    with_lock (Lock) {
        return Sessions.size() >= MaxSessions;
    }
}


TMaybe<TString> TPQWriteServiceImpl::AvailableLocalCluster() {
    with_lock (Lock) {
        return AvailableLocalClusterName;
    }
}


void TPQWriteServiceImpl::NetClassifierUpdated(NAddressClassifier::TLabeledAddressClassifier::TConstPtr classifier) {
    auto g(Guard(Lock));
    if (!DatacenterClassifier) {
        for (auto it = Sessions.begin(); it != Sessions.end();) {
            auto jt = it++;
            jt->second->DestroyStream("datacenter classifier initialized, restart session please", NPersQueue::NErrorCode::INITIALIZING);
        }
    }

    DatacenterClassifier = classifier;
}



void TPQWriteServiceImpl::CheckClusterChange(const TString &localCluster, const bool enabled) {
    with_lock (Lock) {
        AvailableLocalClusterName = enabled ? localCluster : TString();

        if (!enabled) {
            for (auto it = Sessions.begin(); it != Sessions.end();) {
                auto jt = it++;
                jt->second->DestroyStream("cluster disabled", NPersQueue::NErrorCode::CLUSTER_DISABLED);
            }
        }
    }
}


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

}
}