aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/lwtrace/shuttle.h
blob: 24c38e4c47a591b5d1c9350b4aceadeb3b115d29 (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
#pragma once 
 
#include "event.h"

#include <library/cpp/containers/stack_vector/stack_vec.h>

#include <util/generic/ptr.h> 
#include <util/system/spinlock.h> 
 
#include <algorithm>
#include <type_traits> 

namespace NLWTrace { 
    struct TProbe; 
 
    class IShuttle; 
    using TShuttlePtr = TIntrusivePtr<IShuttle>; 
 
    // Represents interface of tracing context passing by application between probes 
    class alignas(8) IShuttle: public TThrRefBase { 
    private: 
        ui64 TraceIdx; 
        ui64 SpanId;
        ui64 ParentSpanId = 0;
        TAtomic Status = 0; 
        static constexpr ui64 DeadFlag = 0x1ull; 
        TShuttlePtr Next; 
 
    public: 
        explicit IShuttle(ui64 traceIdx, ui64 spanId)
            : TraceIdx(traceIdx) 
            , SpanId(spanId)
        { 
        } 
 
        virtual ~IShuttle() { 
        } 
 
        ui64 GetTraceIdx() const { 
            return TraceIdx; 
        } 
 
        ui64 GetSpanId() const {
            return SpanId;
        }

        ui64 GetParentSpanId() const {
            return ParentSpanId;
        }

        void SetParentSpanId(ui64 parentSpanId) {
            ParentSpanId = parentSpanId;
        }

        template <class F, class R> 
        R UnlessDead(F func, R dead) { 
            while (true) { 
                ui64 status = AtomicGet(Status); 
                if (status & DeadFlag) { 
                    return dead; 
                } 
                if (AtomicCas(&Status, status + 2, status)) { 
                    R result = func(); 
                    ATOMIC_COMPILER_BARRIER(); 
                    AtomicSub(Status, 2); 
                    return result; 
                } 
            }
        }

        template <class F> 
        void UnlessDead(F func) { 
            while (true) { 
                ui64 status = AtomicGet(Status); 
                if (status & DeadFlag) { 
                    return; 
                } 
                if (AtomicCas(&Status, status + 2, status)) { 
                    func(); 
                    ATOMIC_COMPILER_BARRIER(); 
                    AtomicSub(Status, 2); 
                    return; 
                } 
            } 
        } 
 
        void Serialize(TShuttleTrace& msg) { 
            UnlessDead([&] { 
                DoSerialize(msg); 
            }); 
        } 
 
        // Returns false iff shuttle should be destroyed 
        bool AddProbe(TProbe* probe, const TParams& params, ui64 timestamp = 0) {
            return UnlessDead([&] { 
                return DoAddProbe(probe, params, timestamp); 
            }, false); 
        } 
 
        // Track object was destroyed 
        void EndOfTrack() { 
            if (Next) { 
                Next->EndOfTrack(); 
                Next.Reset(); 
            } 
            UnlessDead([&] { 
                DoEndOfTrack(); 
            }); 
        } 
 
        // Shuttle was dropped from orbit 
        TShuttlePtr Drop() { 
            UnlessDead([&] { 
                DoDrop(); 
            }); 
            return Detach(); // Detached from orbit on Drop
        }

        TShuttlePtr Detach() {
            TShuttlePtr result; 
            result.Swap(Next);
            return result; 
        } 
 
        // Trace session was destroyed 
        void Kill() { 
            AtomicAdd(Status, 1); // Sets DeadFlag 
            while (AtomicGet(Status) != 1) { // Wait until any vcall is over 
                SpinLockPause(); 
            } 
            // After this point all virtual calls on shuttle are disallowed 
            ATOMIC_COMPILER_BARRIER(); 
        } 
 
        const TShuttlePtr& GetNext() const { 
            return Next; 
        } 
 
        TShuttlePtr& GetNext() { 
            return Next; 
        } 
 
        void SetNext(const TShuttlePtr& next) { 
            Next = next; 
        } 
 
        bool Fork(TShuttlePtr& child) { 
            return UnlessDead([&] { 
                return DoFork(child); 
            }, true); 
        }

        bool Join(TShuttlePtr& child) {
            return UnlessDead([&] { 
                return DoJoin(child); 
            }, false); 
        }

        bool IsDead() {
            return AtomicGet(Status) & DeadFlag;
        }

    protected: 
        virtual bool DoAddProbe(TProbe* probe, const TParams& params, ui64 timestamp) = 0;
        virtual void DoEndOfTrack() = 0; 
        virtual void DoDrop() = 0; 
        virtual void DoSerialize(TShuttleTrace& msg) = 0;
        virtual bool DoFork(TShuttlePtr& child) = 0; 
        virtual bool DoJoin(const TShuttlePtr& child) = 0;
    }; 
 
    // Not thread-safe orbit 
    // Orbit should not be used concurrenty, lock is used 
    // to ensure this is the case and avoid race condition if not. 
    class TOrbit { 
    private: 
        TShuttlePtr HeadNoLock; 
    public: 
        TOrbit() = default;
        TOrbit(const TOrbit&) = delete;
        TOrbit(TOrbit&&) = default;

        TOrbit& operator=(const TOrbit&) = delete;
        TOrbit& operator=(TOrbit&&) = default;

        ~TOrbit() { 
            Reset(); 
        } 
 
        void Reset() { 
            NotConcurrent([] (TShuttlePtr& head) { 
                if (head) { 
                    head->EndOfTrack(); 
                    head.Reset(); 
                } 
            }); 
        } 
 
        // Checks if there is at least one shuttle in orbit 
        // NOTE: used by every LWTRACK macro check, so keep it optimized - do not lock 
        bool HasShuttles() const { 
            return HeadNoLock.Get(); 
        } 
 
        void AddShuttle(const TShuttlePtr& shuttle) { 
            NotConcurrent([&] (TShuttlePtr& head) { 
                Y_VERIFY(!shuttle->GetNext()); 
                shuttle->SetNext(head); 
                head = shuttle; 
            }); 
        } 
 
        // Moves every shuttle from `orbit' into this 
        void Take(TOrbit& orbit) { 
            NotConcurrent([&] (TShuttlePtr& head) { 
                orbit.NotConcurrent([&] (TShuttlePtr& oHead) { 
                    TShuttlePtr* ref = &oHead; 
                    if (ref->Get()) { 
                        while (TShuttlePtr& next = (*ref)->GetNext()) { 
                            ref = &next; 
                        } 
                        (*ref)->SetNext(head); 
                        head.Swap(oHead); 
                        oHead.Reset(); 
                    } 
                }); 
            }); 
        } 
 
        void AddProbe(TProbe* probe, const TParams& params, ui64 timestamp = 0) {
            NotConcurrent([&] (TShuttlePtr& head) { 
                TShuttlePtr* ref = &head; 
                while (IShuttle* s = ref->Get()) { 
                    if (!s->AddProbe(probe, params, timestamp)) { // Shuttle self-destructed 
                        *ref = s->Drop(); // May destroy shuttle 
                    } else { 
                        ref = &s->GetNext(); // Keep shuttle 
                    } 
                } 
            }); 
        } 
 
        template <class TFunc> 
        void ForEachShuttle(ui64 traceIdx, TFunc&& func) { 
            NotConcurrent([&] (TShuttlePtr& head) { 
                TShuttlePtr* ref = &head; 
                while (IShuttle* s = ref->Get()) { 
                    if (s->GetTraceIdx() == traceIdx && !func(s)) { // Shuttle self-destructed 
                        *ref = s->Drop(); // May destroy shuttle 
                    } else { 
                        ref = &s->GetNext(); // Keep shuttle 
                    } 
                } 
            }); 
        } 

        void Serialize(ui64 traceIdx, TShuttleTrace& msg) { 
            ForEachShuttle(traceIdx, [&] (NLWTrace::IShuttle* shuttle) { 
                shuttle->Serialize(msg);
                return false;
            });
        }

        bool HasShuttle(ui64 traceIdx) { 
            return NotConcurrent([=] (TShuttlePtr& head) { 
                TShuttlePtr ref = head; 
                while (IShuttle* s = ref.Get()) { 
                    if (s->GetTraceIdx() == traceIdx) { 
                        return true; 
                    } else { 
                        ref = s->GetNext(); 
                    } 
                }
                return false; 
            }); 
        }

        bool Fork(TOrbit& child) {
            return NotConcurrent([&] (TShuttlePtr& head) { 
                return child.NotConcurrent([&] (TShuttlePtr& cHead) { 
                    bool result = true; 
                    TShuttlePtr* ref = &head; 
                    while (IShuttle* shuttle = ref->Get()) { 
                        if (shuttle->IsDead()) { 
                            *ref = shuttle->Drop(); 
                        } else { 
                            result = result && shuttle->Fork(cHead); 
                            ref = &shuttle->GetNext(); 
                        } 
                    } 
                    return result; 
                }); 
            }); 
        }

        void Join(TOrbit& child) {
            NotConcurrent([&] (TShuttlePtr& head) { 
                child.NotConcurrent([&] (TShuttlePtr& cHead) { 
                    TShuttlePtr* ref = &head; 
                    while (IShuttle* shuttle = ref->Get()) { 
                        if (shuttle->IsDead()) { 
                            *ref = shuttle->Drop(); 
                        } else { 
                            child.Join(cHead, shuttle); 
                            ref = &shuttle->GetNext(); 
                        } 
                    } 
                }); 
            }); 
        }

    private: 
        static void Join(TShuttlePtr& head, IShuttle* parent) { 
            TShuttlePtr* ref = &head; 
            while (IShuttle* child = ref->Get()) {
                if (parent->GetTraceIdx() == child->GetTraceIdx() && parent->GetSpanId() == child->GetParentSpanId()) {
                    TShuttlePtr next = child->Detach();
                    parent->Join(*ref);
                    *ref = next;
                } else {
                    ref = &child->GetNext();
                }
            }
        }
 
        template <class TFunc> 
        typename std::invoke_result<TFunc, TShuttlePtr&>::type NotConcurrent(TFunc func) { 
            // `HeadNoLock` is binary-copied into local `headCopy` and written with special `locked` value 
            // during not concurrent operations. Not concurrent operations should not work 
            // with `HeadNoLock` directly. Instead `headCopy` is passed into `func` by reference and 
            // after `func()` it is binary-copied back into `HeadNoLock`. 
            static_assert(sizeof(HeadNoLock) == sizeof(TAtomic)); 
            TAtomic* headPtr = reinterpret_cast<TAtomic*>(&HeadNoLock); 
            TAtomicBase headCopy = AtomicGet(*headPtr); 
            static constexpr TAtomicBase locked = 0x1ull; 
            if (headCopy != locked && AtomicCas(headPtr, locked, headCopy)) { 
                struct TUnlocker { // to avoid specialization for R=void 
                    TAtomic* HeadPtr; 
                    TAtomicBase* HeadCopy; 
                    ~TUnlocker() { 
                        ATOMIC_COMPILER_BARRIER(); 
                        AtomicSet(*HeadPtr, *HeadCopy); 
                    } 
                } scoped{headPtr, &headCopy}; 
                return func(*reinterpret_cast<TShuttlePtr*>(&headCopy)); 
            } else { 
                LockFailed(); 
                return typename std::invoke_result<TFunc, TShuttlePtr&>::type(); 
            } 
        } 
 
        void LockFailed(); 
    }; 
 
    inline size_t HasShuttles(const TOrbit& orbit) { 
        return orbit.HasShuttles(); 
    } 
}