1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 // Package crunchstat reports resource usage (CPU, memory, disk,
6 // network) for a cgroup.
24 // This magically allows us to look up userHz via _SC_CLK_TCK:
28 #include <sys/types.h>
34 // A Reporter gathers statistics for a cgroup and writes them to a
36 type Reporter struct {
37 // CID of the container to monitor. If empty, read the CID
38 // from CIDFile (first waiting until a non-empty file appears
39 // at CIDFile). If CIDFile is also empty, report host
43 // Path to a file we can read CID from.
46 // Where cgroup accounting files live on this system, e.g.,
50 // Parent cgroup, e.g., "docker".
53 // Interval between samples. Must be positive.
54 PollPeriod time.Duration
56 // Where to write statistics. Must not be nil.
59 reportedStatFile map[string]string
60 lastNetSample map[string]ioSample
61 lastDiskIOSample map[string]ioSample
62 lastCPUSample cpuSample
63 lastDiskSpaceSample diskSpaceSample
65 done chan struct{} // closed when we should stop reporting
66 flushed chan struct{} // closed when we have made our last report
69 // Start starts monitoring in a new goroutine, and returns
72 // The monitoring goroutine waits for a non-empty CIDFile to appear
73 // (unless CID is non-empty). Then it waits for the accounting files
74 // to appear for the monitored container. Then it collects and reports
75 // statistics until Stop is called.
77 // Callers should not call Start more than once.
79 // Callers should not modify public data fields after calling Start.
80 func (r *Reporter) Start() {
81 r.done = make(chan struct{})
82 r.flushed = make(chan struct{})
86 // Stop reporting. Do not call more than once, or before calling
89 // Nothing will be logged after Stop returns.
90 func (r *Reporter) Stop() {
95 func (r *Reporter) readAllOrWarn(in io.Reader) ([]byte, error) {
96 content, err := ioutil.ReadAll(in)
98 r.Logger.Printf("warning: %v", err)
103 // Open the cgroup stats file in /sys/fs corresponding to the target
104 // cgroup, and return an io.ReadCloser. If no stats file is available,
107 // Log the file that was opened, if it isn't the same file opened on
108 // the last openStatFile for this stat.
110 // Log "not available" if no file is found and either this stat has
111 // been available in the past, or verbose==true.
113 // TODO: Instead of trying all options, choose a process in the
114 // container, and read /proc/PID/cgroup to determine the appropriate
115 // cgroup root for the given statgroup. (This will avoid falling back
116 // to host-level stats during container setup and teardown.)
117 func (r *Reporter) openStatFile(statgroup, stat string, verbose bool) (io.ReadCloser, error) {
120 // Collect container's stats
122 fmt.Sprintf("%s/%s/%s/%s/%s", r.CgroupRoot, statgroup, r.CgroupParent, r.CID, stat),
123 fmt.Sprintf("%s/%s/%s/%s", r.CgroupRoot, r.CgroupParent, r.CID, stat),
126 // Collect this host's stats
128 fmt.Sprintf("%s/%s/%s", r.CgroupRoot, statgroup, stat),
129 fmt.Sprintf("%s/%s", r.CgroupRoot, stat),
135 for _, path = range paths {
136 file, err = os.Open(path)
143 if pathWas := r.reportedStatFile[stat]; pathWas != path {
144 // Log whenever we start using a new/different cgroup
145 // stat file for a given statistic. This typically
146 // happens 1 to 3 times per statistic, depending on
147 // whether we happen to collect stats [a] before any
148 // processes have been created in the container and
149 // [b] after all contained processes have exited.
150 if path == "" && verbose {
151 r.Logger.Printf("notice: stats not available: stat %s, statgroup %s, cid %s, parent %s, root %s\n", stat, statgroup, r.CID, r.CgroupParent, r.CgroupRoot)
152 } else if pathWas != "" {
153 r.Logger.Printf("notice: stats moved from %s to %s\n", r.reportedStatFile[stat], path)
155 r.Logger.Printf("notice: reading stats from %s\n", path)
157 r.reportedStatFile[stat] = path
162 func (r *Reporter) getContainerNetStats() (io.Reader, error) {
163 procsFile, err := r.openStatFile("cpuacct", "cgroup.procs", true)
167 defer procsFile.Close()
168 reader := bufio.NewScanner(procsFile)
170 taskPid := reader.Text()
171 statsFilename := fmt.Sprintf("/proc/%s/net/dev", taskPid)
172 stats, err := ioutil.ReadFile(statsFilename)
174 r.Logger.Printf("notice: %v", err)
177 return strings.NewReader(string(stats)), nil
179 return nil, errors.New("Could not read stats for any proc in container")
182 type ioSample struct {
188 func (r *Reporter) doBlkIOStats() {
189 c, err := r.openStatFile("blkio", "blkio.io_service_bytes", true)
194 b := bufio.NewScanner(c)
195 var sampleTime = time.Now()
196 newSamples := make(map[string]ioSample)
198 var device, op string
200 if _, err := fmt.Sscanf(string(b.Text()), "%s %s %d", &device, &op, &val); err != nil {
203 var thisSample ioSample
205 if thisSample, ok = newSamples[device]; !ok {
206 thisSample = ioSample{sampleTime, -1, -1}
210 thisSample.rxBytes = val
212 thisSample.txBytes = val
214 newSamples[device] = thisSample
216 for dev, sample := range newSamples {
217 if sample.txBytes < 0 || sample.rxBytes < 0 {
221 if prev, ok := r.lastDiskIOSample[dev]; ok {
222 delta = fmt.Sprintf(" -- interval %.4f seconds %d write %d read",
223 sample.sampleTime.Sub(prev.sampleTime).Seconds(),
224 sample.txBytes-prev.txBytes,
225 sample.rxBytes-prev.rxBytes)
227 r.Logger.Printf("blkio:%s %d write %d read%s\n", dev, sample.txBytes, sample.rxBytes, delta)
228 r.lastDiskIOSample[dev] = sample
232 type memSample struct {
234 memStat map[string]int64
237 func (r *Reporter) doMemoryStats() {
238 c, err := r.openStatFile("memory", "memory.stat", true)
243 b := bufio.NewScanner(c)
244 thisSample := memSample{time.Now(), make(map[string]int64)}
245 wantStats := [...]string{"cache", "swap", "pgmajfault", "rss"}
249 if _, err := fmt.Sscanf(string(b.Text()), "%s %d", &stat, &val); err != nil {
252 thisSample.memStat[stat] = val
254 var outstat bytes.Buffer
255 for _, key := range wantStats {
256 if val, ok := thisSample.memStat[key]; ok {
257 outstat.WriteString(fmt.Sprintf(" %d %s", val, key))
260 r.Logger.Printf("mem%s\n", outstat.String())
263 func (r *Reporter) doNetworkStats() {
264 sampleTime := time.Now()
265 stats, err := r.getContainerNetStats()
270 scanner := bufio.NewScanner(stats)
274 words := strings.Fields(scanner.Text())
275 if len(words) != 17 {
276 // Skip lines with wrong format
279 ifName = strings.TrimRight(words[0], ":")
280 if ifName == "lo" || ifName == "" {
281 // Skip loopback interface and lines with wrong format
284 if tx, err = strconv.ParseInt(words[9], 10, 64); err != nil {
287 if rx, err = strconv.ParseInt(words[1], 10, 64); err != nil {
290 nextSample := ioSample{}
291 nextSample.sampleTime = sampleTime
292 nextSample.txBytes = tx
293 nextSample.rxBytes = rx
295 if prev, ok := r.lastNetSample[ifName]; ok {
296 interval := nextSample.sampleTime.Sub(prev.sampleTime).Seconds()
297 delta = fmt.Sprintf(" -- interval %.4f seconds %d tx %d rx",
302 r.Logger.Printf("net:%s %d tx %d rx%s\n", ifName, tx, rx, delta)
303 r.lastNetSample[ifName] = nextSample
307 type diskSpaceSample struct {
315 func (r *Reporter) doDiskSpaceStats() {
316 s := syscall.Statfs_t{}
317 err := syscall.Statfs("/tmp", &s)
321 bs := uint64(s.Bsize)
322 nextSample := diskSpaceSample{
324 sampleTime: time.Now(),
325 total: s.Blocks * bs,
326 used: (s.Blocks - s.Bavail) * bs,
327 available: s.Bavail * bs,
331 if r.lastDiskSpaceSample.hasData {
332 prev := r.lastDiskSpaceSample
333 interval := nextSample.sampleTime.Sub(prev.sampleTime).Seconds()
334 delta = fmt.Sprintf(" -- interval %.4f seconds %d used",
336 int64(nextSample.used-prev.used))
338 r.Logger.Printf("tmpdir available:%d used:%d total:%d%s\n",
339 nextSample.available, nextSample.used, nextSample.total, delta)
340 r.lastDiskSpaceSample = nextSample
343 type cpuSample struct {
344 hasData bool // to distinguish the zero value from real data
351 // Return the number of CPUs available in the container. Return 0 if
352 // we can't figure out the real number of CPUs.
353 func (r *Reporter) getCPUCount() int64 {
354 cpusetFile, err := r.openStatFile("cpuset", "cpuset.cpus", true)
358 defer cpusetFile.Close()
359 b, err := r.readAllOrWarn(cpusetFile)
363 sp := strings.Split(string(b), ",")
365 for _, v := range sp {
367 n, _ := fmt.Sscanf(v, "%d-%d", &min, &max)
369 cpus += (max - min) + 1
377 func (r *Reporter) doCPUStats() {
378 statFile, err := r.openStatFile("cpuacct", "cpuacct.stat", true)
382 defer statFile.Close()
383 b, err := r.readAllOrWarn(statFile)
388 var userTicks, sysTicks int64
389 fmt.Sscanf(string(b), "user %d\nsystem %d", &userTicks, &sysTicks)
390 userHz := float64(C.sysconf(C._SC_CLK_TCK))
391 nextSample := cpuSample{
393 sampleTime: time.Now(),
394 user: float64(userTicks) / userHz,
395 sys: float64(sysTicks) / userHz,
396 cpus: r.getCPUCount(),
400 if r.lastCPUSample.hasData {
401 delta = fmt.Sprintf(" -- interval %.4f seconds %.4f user %.4f sys",
402 nextSample.sampleTime.Sub(r.lastCPUSample.sampleTime).Seconds(),
403 nextSample.user-r.lastCPUSample.user,
404 nextSample.sys-r.lastCPUSample.sys)
406 r.Logger.Printf("cpu %.4f user %.4f sys %d cpus%s\n",
407 nextSample.user, nextSample.sys, nextSample.cpus, delta)
408 r.lastCPUSample = nextSample
411 // Report stats periodically until we learn (via r.done) that someone
413 func (r *Reporter) run() {
414 defer close(r.flushed)
416 r.reportedStatFile = make(map[string]string)
418 if !r.waitForCIDFile() || !r.waitForCgroup() {
422 r.lastNetSample = make(map[string]ioSample)
423 r.lastDiskIOSample = make(map[string]ioSample)
425 ticker := time.NewTicker(r.PollPeriod)
440 // If CID is empty, wait for it to appear in CIDFile. Return true if
441 // we get it before we learn (via r.done) that someone called Stop.
442 func (r *Reporter) waitForCIDFile() bool {
443 if r.CID != "" || r.CIDFile == "" {
447 ticker := time.NewTicker(100 * time.Millisecond)
450 cid, err := ioutil.ReadFile(r.CIDFile)
451 if err == nil && len(cid) > 0 {
458 r.Logger.Printf("warning: CID never appeared in %+q: %v", r.CIDFile, err)
464 // Wait for the cgroup stats files to appear in cgroup_root. Return
465 // true if they appear before r.done indicates someone called Stop. If
466 // they don't appear within one poll interval, log a warning and keep
468 func (r *Reporter) waitForCgroup() bool {
469 ticker := time.NewTicker(100 * time.Millisecond)
471 warningTimer := time.After(r.PollPeriod)
473 c, err := r.openStatFile("cpuacct", "cgroup.procs", false)
481 r.Logger.Printf("warning: cgroup stats files have not appeared after %v (config error?) -- still waiting...", r.PollPeriod)
483 r.Logger.Printf("warning: cgroup stats files never appeared for %v", r.CID)