aboutsummaryrefslogtreecommitdiffstats
path: root/library/cpp/actors/core/process_stats.cpp
blob: 3edbaded63e80f4a28535b3b2b712e3b6ce7e648 (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
#include "actorsystem.h"
#include "actor_bootstrapped.h"
#include "hfunc.h"
#include "process_stats.h"

#include <library/cpp/monlib/dynamic_counters/counters.h>
#include <library/cpp/monlib/metrics/metric_registry.h>

#include <util/datetime/uptime.h>
#include <util/system/defaults.h>
#include <util/stream/file.h>
#include <util/string/vector.h>
#include <util/string/split.h>

#ifndef _win_
#include <sys/user.h>
#include <sys/sysctl.h>
#endif

namespace NActors {
#ifdef _linux_

    namespace {
        template <typename TVal>
        static bool ExtractVal(const TString& str, const TString& name, TVal& res) {
            if (!str.StartsWith(name))
                return false;
            size_t pos = name.size(); 
            while (pos < str.size() && (str[pos] == ' ' || str[pos] == '\t')) { 
                pos++;
            }
            res = atol(str.data() + pos); 
            return true;
        }

        float TicksPerMillisec() {
#ifdef _SC_CLK_TCK
            return sysconf(_SC_CLK_TCK) / 1000.0;
#else
            return 1.f;
#endif
        }
    }

    bool TProcStat::Fill(pid_t pid) {
        try {
            TString strPid(ToString(pid));
            TFileInput proc("/proc/" + strPid + "/status");
            TString str;
            while (proc.ReadLine(str)) {
                if (ExtractVal(str, "VmRSS:", Rss))
                    continue;
                if (ExtractVal(str, "voluntary_ctxt_switches:", VolCtxSwtch))
                    continue;
                if (ExtractVal(str, "nonvoluntary_ctxt_switches:", NonvolCtxSwtch))
                    continue;
            }
            // Convert from kB to bytes
            Rss *= 1024;

            float tickPerMillisec = TicksPerMillisec();

            TFileInput procStat("/proc/" + strPid + "/stat");
            procStat.ReadLine(str);
            if (!str.empty()) {
                sscanf(str.data(), 
                       "%d %*s %c %d %d %d %d %d %u %lu %lu "
                       "%lu %lu %lu %lu %ld %ld %ld %ld %ld "
                       "%ld %llu %lu %ld %lu",
                       &Pid, &State, &Ppid, &Pgrp, &Session, &TtyNr, &TPgid, &Flags, &MinFlt, &CMinFlt,
                       &MajFlt, &CMajFlt, &Utime, &Stime, &CUtime, &CStime, &Priority, &Nice, &NumThreads,
                       &ItRealValue, &StartTime, &Vsize, &RssPages, &RssLim);
                Utime /= tickPerMillisec;
                Stime /= tickPerMillisec;
                CUtime /= tickPerMillisec;
                CStime /= tickPerMillisec;
                SystemUptime = ::Uptime();
                Uptime = SystemUptime - TDuration::MilliSeconds(StartTime / TicksPerMillisec());
            }

            TFileInput statm("/proc/" + strPid + "/statm");
            statm.ReadLine(str);
            TVector<TString> fields;
            StringSplitter(str).Split(' ').SkipEmpty().Collect(&fields); 
            if (fields.size() >= 7) {
                ui64 resident = FromString<ui64>(fields[1]);
                ui64 shared = FromString<ui64>(fields[2]);
                if (PageSize == 0) {
                    PageSize = ObtainPageSize();
                }
                FileRss = shared * PageSize;
                AnonRss = (resident - shared) * PageSize;
            }

            TFileInput cgroup("/proc/" + strPid + "/cgroup");
            TString line;
            TString memoryCGroup;
            while (cgroup.ReadLine(line) > 0) {
                StringSplitter(line).Split(':').Collect(&fields);
                if (fields.size() > 2 && fields[1] == "memory") {
                    memoryCGroup = fields[2];
                    break;
                }
            }
            if (!memoryCGroup.empty()) {
                TFileInput limit("/sys/fs/cgroup/memory" + memoryCGroup + "/memory.limit_in_bytes");
                if (limit.ReadLine(line) > 0) {
                    CGroupMemLim = FromString<ui64>(line);
                    if (CGroupMemLim > (1ULL << 40)) {
                        CGroupMemLim = 0;
                    }
                }
            }

        } catch (...) {
            return false;
        }
        return true;
    }

    long TProcStat::ObtainPageSize() {
        long sz = sysconf(_SC_PAGESIZE);
        return sz;
    }

#else

    bool TProcStat::Fill(pid_t pid) {
        Y_UNUSED(pid);
        return false;
    }

    long TProcStat::ObtainPageSize() {
        return 0;
    }

#endif

namespace {
    // Periodically collects process stats and exposes them as mon counters
    template <typename TDerived>
    class TProcStatCollectingActor: public TActorBootstrapped<TProcStatCollectingActor<TDerived>> {
    public:
        static constexpr IActor::EActivityType ActorActivityType() {
            return IActor::ACTORLIB_STATS;
        }

        TProcStatCollectingActor(TDuration interval)
            : Interval(interval)
        {
        }

        void Bootstrap(const TActorContext& ctx) {
            ctx.Schedule(Interval, new TEvents::TEvWakeup());
            Self()->Become(&TDerived::StateWork);
        }

        STFUNC(StateWork) {
            switch (ev->GetTypeRewrite()) {
                CFunc(TEvents::TSystem::Wakeup, Wakeup);
            }
        }

    private:
        void Wakeup(const TActorContext& ctx) {
            Self()->UpdateCounters(ProcStat);
            ctx.Schedule(Interval, new TEvents::TEvWakeup());
        }

        TDerived* Self() {
            ProcStat.Fill(getpid());
            return static_cast<TDerived*>(this);
        }

    private:
        const TDuration Interval;
        TProcStat ProcStat;
    };

    // Periodically collects process stats and exposes them as mon counters
    class TDynamicCounterCollector: public TProcStatCollectingActor<TDynamicCounterCollector> {
        using TBase = TProcStatCollectingActor<TDynamicCounterCollector>;
    public:
        TDynamicCounterCollector(
            ui32 intervalSeconds,
            NMonitoring::TDynamicCounterPtr counters)
            : TBase{TDuration::Seconds(intervalSeconds)}
        {
            ProcStatGroup = counters->GetSubgroup("counters", "utils");

            VmSize = ProcStatGroup->GetCounter("Process/VmSize", false);
            AnonRssSize = ProcStatGroup->GetCounter("Process/AnonRssSize", false);
            FileRssSize = ProcStatGroup->GetCounter("Process/FileRssSize", false);
            CGroupMemLimit = ProcStatGroup->GetCounter("Process/CGroupMemLimit", false);
            UserTime = ProcStatGroup->GetCounter("Process/UserTime", true);
            SysTime = ProcStatGroup->GetCounter("Process/SystemTime", true);
            MinorPageFaults = ProcStatGroup->GetCounter("Process/MinorPageFaults", true);
            MajorPageFaults = ProcStatGroup->GetCounter("Process/MajorPageFaults", true);
            UptimeSeconds = ProcStatGroup->GetCounter("Process/UptimeSeconds", false);
            NumThreads = ProcStatGroup->GetCounter("Process/NumThreads", false);
            SystemUptimeSeconds = ProcStatGroup->GetCounter("System/UptimeSeconds", false);
        }

        void UpdateCounters(const TProcStat& procStat) {
            *VmSize = procStat.Vsize;
            *AnonRssSize = procStat.AnonRss;
            *FileRssSize = procStat.FileRss;
            if (procStat.CGroupMemLim) {
                *CGroupMemLimit = procStat.CGroupMemLim;
            }
            *UserTime = procStat.Utime;
            *SysTime = procStat.Stime;
            *MinorPageFaults = procStat.MinFlt;
            *MajorPageFaults = procStat.MajFlt;
            *UptimeSeconds = procStat.Uptime.Seconds();
            *NumThreads = procStat.NumThreads;
            *SystemUptimeSeconds = procStat.Uptime.Seconds();
        }

    private:
        NMonitoring::TDynamicCounterPtr ProcStatGroup;
        NMonitoring::TDynamicCounters::TCounterPtr VmSize;
        NMonitoring::TDynamicCounters::TCounterPtr AnonRssSize;
        NMonitoring::TDynamicCounters::TCounterPtr FileRssSize;
        NMonitoring::TDynamicCounters::TCounterPtr CGroupMemLimit;
        NMonitoring::TDynamicCounters::TCounterPtr UserTime;
        NMonitoring::TDynamicCounters::TCounterPtr SysTime;
        NMonitoring::TDynamicCounters::TCounterPtr MinorPageFaults;
        NMonitoring::TDynamicCounters::TCounterPtr MajorPageFaults;
        NMonitoring::TDynamicCounters::TCounterPtr UptimeSeconds;
        NMonitoring::TDynamicCounters::TCounterPtr NumThreads;
        NMonitoring::TDynamicCounters::TCounterPtr SystemUptimeSeconds;
    };


    class TRegistryCollector: public TProcStatCollectingActor<TRegistryCollector> {
        using TBase = TProcStatCollectingActor<TRegistryCollector>;
    public:
        TRegistryCollector(TDuration interval, NMonitoring::TMetricRegistry& registry)
            : TBase{interval}
        {
            VmSize = registry.IntGauge({{"sensor", "process.VmSize"}});
            AnonRssSize = registry.IntGauge({{"sensor", "process.AnonRssSize"}});
            FileRssSize = registry.IntGauge({{"sensor", "process.FileRssSize"}});
            CGroupMemLimit = registry.IntGauge({{"sensor", "process.CGroupMemLimit"}});
            UptimeSeconds = registry.IntGauge({{"sensor", "process.UptimeSeconds"}});
            NumThreads = registry.IntGauge({{"sensor", "process.NumThreads"}});
            SystemUptimeSeconds = registry.IntGauge({{"sensor", "system.UptimeSeconds"}});

            UserTime = registry.Rate({{"sensor", "process.UserTime"}});
            SysTime = registry.Rate({{"sensor", "process.SystemTime"}});
            MinorPageFaults = registry.Rate({{"sensor", "process.MinorPageFaults"}});
            MajorPageFaults = registry.Rate({{"sensor", "process.MajorPageFaults"}});
        }

        void UpdateCounters(const TProcStat& procStat) {
            VmSize->Set(procStat.Vsize);
            AnonRssSize->Set(procStat.AnonRss);
            FileRssSize->Set(procStat.FileRss);
            CGroupMemLimit->Set(procStat.CGroupMemLim);
            UptimeSeconds->Set(procStat.Uptime.Seconds());
            NumThreads->Set(procStat.NumThreads);
            SystemUptimeSeconds->Set(procStat.SystemUptime.Seconds());

            // it is ok here to reset and add metric value, because mutation
            // is performed in siglethreaded context

            UserTime->Reset();
            UserTime->Add(procStat.Utime);

            SysTime->Reset();
            SysTime->Add(procStat.Stime);

            MinorPageFaults->Reset();
            MinorPageFaults->Add(procStat.MinFlt);

            MajorPageFaults->Reset();
            MajorPageFaults->Add(procStat.MajFlt);
        }

    private:
        NMonitoring::TIntGauge* VmSize;
        NMonitoring::TIntGauge* AnonRssSize;
        NMonitoring::TIntGauge* FileRssSize;
        NMonitoring::TIntGauge* CGroupMemLimit;
        NMonitoring::TRate* UserTime;
        NMonitoring::TRate* SysTime;
        NMonitoring::TRate* MinorPageFaults;
        NMonitoring::TRate* MajorPageFaults;
        NMonitoring::TIntGauge* UptimeSeconds;
        NMonitoring::TIntGauge* NumThreads;
        NMonitoring::TIntGauge* SystemUptimeSeconds;
    };
} // namespace

    IActor* CreateProcStatCollector(ui32 intervalSec, NMonitoring::TDynamicCounterPtr counters) {
        return new TDynamicCounterCollector(intervalSec, counters);
    }

    IActor* CreateProcStatCollector(TDuration interval, NMonitoring::TMetricRegistry& registry) {
        return new TRegistryCollector(interval, registry);
    }
}