aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/messagebus/actor/executor.cpp
blob: 70233799e3ca767031b606a44cac04f17f93f7cc (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
#include "executor.h"

#include "thread_extra.h"
#include "what_thread_does.h"
#include "what_thread_does_guard.h"

#include <util/generic/utility.h>
#include <util/random/random.h>
#include <util/stream/str.h>
#include <util/system/tls.h>
#include <util/system/yassert.h>

#include <array>

using namespace NActor;
using namespace NActor::NPrivate;

namespace {
    struct THistoryInternal {
        struct TRecord {
            TAtomic MaxQueueSize;

            TRecord()
                : MaxQueueSize()
            {
            }

            TExecutorHistory::THistoryRecord Capture() {
                TExecutorHistory::THistoryRecord r;
                r.MaxQueueSize = AtomicGet(MaxQueueSize);
                return r;
            }
        };

        ui64 Start;
        ui64 LastTime;

        std::array<TRecord, 3600> Records;

        THistoryInternal() {
            Start = TInstant::Now().Seconds();
            LastTime = Start - 1;
        }

        TRecord& GetRecordForTime(ui64 time) {
            return Records[time % Records.size()];
        }

        TRecord& GetNowRecord(ui64 now) {
            for (ui64 t = LastTime + 1; t <= now; ++t) {
                GetRecordForTime(t) = TRecord();
            }
            LastTime = now;
            return GetRecordForTime(now);
        }

        TExecutorHistory Capture() {
            TExecutorHistory history;
            ui64 now = TInstant::Now().Seconds();
            ui64 lastHistoryRecord = now - 1;
            ui32 historySize = Min<ui32>(lastHistoryRecord - Start, Records.size() - 1);
            history.HistoryRecords.resize(historySize);
            for (ui32 i = 0; i < historySize; ++i) {
                history.HistoryRecords[i] = GetRecordForTime(lastHistoryRecord - historySize + i).Capture();
            }
            history.LastHistoryRecordSecond = lastHistoryRecord;
            return history;
        }
    };

}

Y_POD_STATIC_THREAD(TExecutor*)
ThreadCurrentExecutor;

static const char* NoLocation = "nowhere";

struct TExecutorWorkerThreadLocalData {
    ui32 MaxQueueSize;
};

static TExecutorWorkerThreadLocalData WorkerNoThreadLocalData;
Y_POD_STATIC_THREAD(TExecutorWorkerThreadLocalData)
WorkerThreadLocalData;

namespace NActor {
    struct TExecutorWorker {
        TExecutor* const Executor;
        TThread Thread;
        const char** WhatThreadDoesLocation;
        TExecutorWorkerThreadLocalData* ThreadLocalData;

        TExecutorWorker(TExecutor* executor)
            : Executor(executor)
            , Thread(RunThreadProc, this)
            , WhatThreadDoesLocation(&NoLocation)
            , ThreadLocalData(&::WorkerNoThreadLocalData)
        {
            Thread.Start();
        }

        void Run() {
            WhatThreadDoesLocation = ::WhatThreadDoesLocation();
            AtomicSet(ThreadLocalData, &::WorkerThreadLocalData);
            WHAT_THREAD_DOES_PUSH_POP_CURRENT_FUNC();
            Executor->RunWorker();
        }

        static void* RunThreadProc(void* thiz0) {
            TExecutorWorker* thiz = (TExecutorWorker*)thiz0;
            thiz->Run();
            return nullptr;
        }
    };

    struct TExecutor::TImpl {
        TExecutor* const Executor;
        THistoryInternal History;

        TSystemEvent HelperStopSignal;
        TThread HelperThread;

        TImpl(TExecutor* executor)
            : Executor(executor)
            , HelperThread(HelperThreadProc, this)
        {
        }

        void RunHelper() {
            ui64 nowSeconds = TInstant::Now().Seconds();
            for (;;) {
                TInstant nextStop = TInstant::Seconds(nowSeconds + 1) + TDuration::MilliSeconds(RandomNumber<ui32>(1000));

                if (HelperStopSignal.WaitD(nextStop)) {
                    return;
                }

                nowSeconds = nextStop.Seconds();

                THistoryInternal::TRecord& record = History.GetNowRecord(nowSeconds);

                ui32 maxQueueSize = Executor->GetMaxQueueSizeAndClear();
                if (maxQueueSize > record.MaxQueueSize) {
                    AtomicSet(record.MaxQueueSize, maxQueueSize);
                }
            }
        }

        static void* HelperThreadProc(void* impl0) {
            TImpl* impl = (TImpl*)impl0;
            impl->RunHelper();
            return nullptr;
        }
    };

}

static TExecutor::TConfig MakeConfig(unsigned workerCount) {
    TExecutor::TConfig config;
    config.WorkerCount = workerCount;
    return config;
}

TExecutor::TExecutor(size_t workerCount)
    : Config(MakeConfig(workerCount))
{
    Init();
}

TExecutor::TExecutor(const TExecutor::TConfig& config)
    : Config(config)
{
    Init();
}

void TExecutor::Init() {
    Impl.Reset(new TImpl(this));

    AtomicSet(ExitWorkers, 0);

    Y_ABORT_UNLESS(Config.WorkerCount > 0);

    for (size_t i = 0; i < Config.WorkerCount; i++) {
        WorkerThreads.push_back(new TExecutorWorker(this));
    }

    Impl->HelperThread.Start();
}

TExecutor::~TExecutor() {
    Stop();
}

void TExecutor::Stop() {
    AtomicSet(ExitWorkers, 1);

    Impl->HelperStopSignal.Signal();
    Impl->HelperThread.Join();

    {
        TWhatThreadDoesAcquireGuard<TMutex> guard(WorkMutex, "executor: acquiring lock for Stop");
        WorkAvailable.BroadCast();
    }

    for (size_t i = 0; i < WorkerThreads.size(); i++) {
        WorkerThreads[i]->Thread.Join();
    }

    // TODO: make queue empty at this point
    ProcessWorkQueueHere();
}

void TExecutor::EnqueueWork(TArrayRef<IWorkItem* const> wis) {
    if (wis.empty())
        return;

    if (Y_UNLIKELY(AtomicGet(ExitWorkers) != 0)) {
        Y_ABORT_UNLESS(WorkItems.Empty(), "executor %s: cannot add tasks after queue shutdown", Config.Name);
    }

    TWhatThreadDoesPushPop pp("executor: EnqueueWork");

    WorkItems.PushAll(wis);

    {
        if (wis.size() == 1) {
            TWhatThreadDoesAcquireGuard<TMutex> g(WorkMutex, "executor: acquiring lock for EnqueueWork");
            WorkAvailable.Signal();
        } else {
            TWhatThreadDoesAcquireGuard<TMutex> g(WorkMutex, "executor: acquiring lock for EnqueueWork");
            WorkAvailable.BroadCast();
        }
    }
}

size_t TExecutor::GetWorkQueueSize() const {
    return WorkItems.Size();
}

using namespace NTSAN;

ui32 TExecutor::GetMaxQueueSizeAndClear() const {
    ui32 max = 0;
    for (unsigned i = 0; i < WorkerThreads.size(); ++i) {
        TExecutorWorkerThreadLocalData* wtls = AtomicGet(WorkerThreads[i]->ThreadLocalData);
        max = Max<ui32>(max, RelaxedLoad(&wtls->MaxQueueSize));
        RelaxedStore<ui32>(&wtls->MaxQueueSize, 0);
    }
    return max;
}

TString TExecutor::GetStatus() const {
    return GetStatusRecordInternal().Status;
}

TString TExecutor::GetStatusSingleLine() const {
    TStringStream ss;
    ss << "work items: " << GetWorkQueueSize();
    return ss.Str();
}

TExecutorStatus TExecutor::GetStatusRecordInternal() const {
    TExecutorStatus r;

    r.WorkQueueSize = GetWorkQueueSize();

    {
        TStringStream ss;
        ss << "work items:     " << GetWorkQueueSize() << "\n";
        ss << "workers:\n";
        for (unsigned i = 0; i < WorkerThreads.size(); ++i) {
            ss << "-- " << AtomicGet(*AtomicGet(WorkerThreads[i]->WhatThreadDoesLocation)) << "\n";
        }
        r.Status = ss.Str();
    }

    r.History = Impl->History.Capture();

    return r;
}

bool TExecutor::IsInExecutorThread() const {
    return ThreadCurrentExecutor == this;
}

TAutoPtr<IWorkItem> TExecutor::DequeueWork() {
    IWorkItem* wi = reinterpret_cast<IWorkItem*>(1);
    size_t queueSize = Max<size_t>();
    if (!WorkItems.TryPop(&wi, &queueSize)) {
        TWhatThreadDoesAcquireGuard<TMutex> g(WorkMutex, "executor: acquiring lock for DequeueWork");
        while (!WorkItems.TryPop(&wi, &queueSize)) {
            if (AtomicGet(ExitWorkers) != 0)
                return nullptr;

            TWhatThreadDoesPushPop pp("waiting for work on condvar");
            WorkAvailable.Wait(WorkMutex);
        }
    }

    auto& wtls = TlsRef(WorkerThreadLocalData);

    if (queueSize > RelaxedLoad(&wtls.MaxQueueSize)) {
        RelaxedStore<ui32>(&wtls.MaxQueueSize, queueSize);
    }

    return wi;
}

void TExecutor::RunWorkItem(TAutoPtr<IWorkItem> wi) {
    WHAT_THREAD_DOES_PUSH_POP_CURRENT_FUNC();
    wi.Release()->DoWork();
}

void TExecutor::ProcessWorkQueueHere() {
    IWorkItem* wi;
    while (WorkItems.TryPop(&wi)) {
        RunWorkItem(wi);
    }
}

void TExecutor::RunWorker() {
    Y_ABORT_UNLESS(!ThreadCurrentExecutor, "state check");
    ThreadCurrentExecutor = this;

    SetCurrentThreadName("wrkr");

    for (;;) {
        TAutoPtr<IWorkItem> wi = DequeueWork();
        if (!wi) {
            break;
        }
        // Note for messagebus users: make sure program crashes
        // on uncaught exception in thread, otherewise messagebus may just hang on error.
        RunWorkItem(wi);
    }

    ThreadCurrentExecutor = (TExecutor*)nullptr;
}