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 // A Reporter gathers statistics for a cgroup and writes them to a
26 type Reporter struct {
27 // CID of the container to monitor. If empty, read the CID
28 // from CIDFile (first waiting until a non-empty file appears
29 // at CIDFile). If CIDFile is also empty, report host
33 // Path to a file we can read CID from.
36 // Where cgroup accounting files live on this system, e.g.,
40 // Parent cgroup, e.g., "docker".
43 // Interval between samples. Must be positive.
44 PollPeriod time.Duration
46 // Temporary directory, will be monitored for available, used & total space.
49 // Where to write statistics. Must not be nil.
52 reportedStatFile map[string]string
53 lastNetSample map[string]ioSample
54 lastDiskIOSample map[string]ioSample
55 lastCPUSample cpuSample
56 lastDiskSpaceSample diskSpaceSample
58 done chan struct{} // closed when we should stop reporting
59 flushed chan struct{} // closed when we have made our last report
62 // Start starts monitoring in a new goroutine, and returns
65 // The monitoring goroutine waits for a non-empty CIDFile to appear
66 // (unless CID is non-empty). Then it waits for the accounting files
67 // to appear for the monitored container. Then it collects and reports
68 // statistics until Stop is called.
70 // Callers should not call Start more than once.
72 // Callers should not modify public data fields after calling Start.
73 func (r *Reporter) Start() {
74 r.done = make(chan struct{})
75 r.flushed = make(chan struct{})
79 // Stop reporting. Do not call more than once, or before calling
82 // Nothing will be logged after Stop returns.
83 func (r *Reporter) Stop() {
88 func (r *Reporter) readAllOrWarn(in io.Reader) ([]byte, error) {
89 content, err := ioutil.ReadAll(in)
91 r.Logger.Printf("warning: %v", err)
96 // Open the cgroup stats file in /sys/fs corresponding to the target
97 // cgroup, and return an io.ReadCloser. If no stats file is available,
100 // Log the file that was opened, if it isn't the same file opened on
101 // the last openStatFile for this stat.
103 // Log "not available" if no file is found and either this stat has
104 // been available in the past, or verbose==true.
106 // TODO: Instead of trying all options, choose a process in the
107 // container, and read /proc/PID/cgroup to determine the appropriate
108 // cgroup root for the given statgroup. (This will avoid falling back
109 // to host-level stats during container setup and teardown.)
110 func (r *Reporter) openStatFile(statgroup, stat string, verbose bool) (io.ReadCloser, error) {
113 // Collect container's stats
115 fmt.Sprintf("%s/%s/%s/%s/%s", r.CgroupRoot, statgroup, r.CgroupParent, r.CID, stat),
116 fmt.Sprintf("%s/%s/%s/%s", r.CgroupRoot, r.CgroupParent, r.CID, stat),
119 // Collect this host's stats
121 fmt.Sprintf("%s/%s/%s", r.CgroupRoot, statgroup, stat),
122 fmt.Sprintf("%s/%s", r.CgroupRoot, stat),
128 for _, path = range paths {
129 file, err = os.Open(path)
136 if pathWas := r.reportedStatFile[stat]; pathWas != path {
137 // Log whenever we start using a new/different cgroup
138 // stat file for a given statistic. This typically
139 // happens 1 to 3 times per statistic, depending on
140 // whether we happen to collect stats [a] before any
141 // processes have been created in the container and
142 // [b] after all contained processes have exited.
143 if path == "" && verbose {
144 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)
145 } else if pathWas != "" {
146 r.Logger.Printf("notice: stats moved from %s to %s\n", r.reportedStatFile[stat], path)
148 r.Logger.Printf("notice: reading stats from %s\n", path)
150 r.reportedStatFile[stat] = path
155 func (r *Reporter) getContainerNetStats() (io.Reader, error) {
156 procsFile, err := r.openStatFile("cpuacct", "cgroup.procs", true)
160 defer procsFile.Close()
161 reader := bufio.NewScanner(procsFile)
163 taskPid := reader.Text()
164 statsFilename := fmt.Sprintf("/proc/%s/net/dev", taskPid)
165 stats, err := ioutil.ReadFile(statsFilename)
167 r.Logger.Printf("notice: %v", err)
170 return strings.NewReader(string(stats)), nil
172 return nil, errors.New("Could not read stats for any proc in container")
175 type ioSample struct {
181 func (r *Reporter) doBlkIOStats() {
182 c, err := r.openStatFile("blkio", "blkio.io_service_bytes", true)
187 b := bufio.NewScanner(c)
188 var sampleTime = time.Now()
189 newSamples := make(map[string]ioSample)
191 var device, op string
193 if _, err := fmt.Sscanf(string(b.Text()), "%s %s %d", &device, &op, &val); err != nil {
196 var thisSample ioSample
198 if thisSample, ok = newSamples[device]; !ok {
199 thisSample = ioSample{sampleTime, -1, -1}
203 thisSample.rxBytes = val
205 thisSample.txBytes = val
207 newSamples[device] = thisSample
209 for dev, sample := range newSamples {
210 if sample.txBytes < 0 || sample.rxBytes < 0 {
214 if prev, ok := r.lastDiskIOSample[dev]; ok {
215 delta = fmt.Sprintf(" -- interval %.4f seconds %d write %d read",
216 sample.sampleTime.Sub(prev.sampleTime).Seconds(),
217 sample.txBytes-prev.txBytes,
218 sample.rxBytes-prev.rxBytes)
220 r.Logger.Printf("blkio:%s %d write %d read%s\n", dev, sample.txBytes, sample.rxBytes, delta)
221 r.lastDiskIOSample[dev] = sample
225 type memSample struct {
227 memStat map[string]int64
230 func (r *Reporter) doMemoryStats() {
231 c, err := r.openStatFile("memory", "memory.stat", true)
236 b := bufio.NewScanner(c)
237 thisSample := memSample{time.Now(), make(map[string]int64)}
238 wantStats := [...]string{"cache", "swap", "pgmajfault", "rss"}
242 if _, err := fmt.Sscanf(string(b.Text()), "%s %d", &stat, &val); err != nil {
245 thisSample.memStat[stat] = val
247 var outstat bytes.Buffer
248 for _, key := range wantStats {
249 // Use "total_X" stats (entire hierarchy) if enabled,
250 // otherwise just the single cgroup -- see
251 // https://www.kernel.org/doc/Documentation/cgroup-v1/memory.txt
252 if val, ok := thisSample.memStat["total_"+key]; ok {
253 fmt.Fprintf(&outstat, " %d %s", val, key)
254 } else if val, ok := thisSample.memStat[key]; ok {
255 fmt.Fprintf(&outstat, " %d %s", val, key)
258 r.Logger.Printf("mem%s\n", outstat.String())
261 func (r *Reporter) doNetworkStats() {
262 sampleTime := time.Now()
263 stats, err := r.getContainerNetStats()
268 scanner := bufio.NewScanner(stats)
272 words := strings.Fields(scanner.Text())
273 if len(words) != 17 {
274 // Skip lines with wrong format
277 ifName = strings.TrimRight(words[0], ":")
278 if ifName == "lo" || ifName == "" {
279 // Skip loopback interface and lines with wrong format
282 if tx, err = strconv.ParseInt(words[9], 10, 64); err != nil {
285 if rx, err = strconv.ParseInt(words[1], 10, 64); err != nil {
288 nextSample := ioSample{}
289 nextSample.sampleTime = sampleTime
290 nextSample.txBytes = tx
291 nextSample.rxBytes = rx
293 if prev, ok := r.lastNetSample[ifName]; ok {
294 interval := nextSample.sampleTime.Sub(prev.sampleTime).Seconds()
295 delta = fmt.Sprintf(" -- interval %.4f seconds %d tx %d rx",
300 r.Logger.Printf("net:%s %d tx %d rx%s\n", ifName, tx, rx, delta)
301 r.lastNetSample[ifName] = nextSample
305 type diskSpaceSample struct {
313 func (r *Reporter) doDiskSpaceStats() {
314 s := syscall.Statfs_t{}
315 err := syscall.Statfs(r.TempDir, &s)
319 bs := uint64(s.Bsize)
320 nextSample := diskSpaceSample{
322 sampleTime: time.Now(),
323 total: s.Blocks * bs,
324 used: (s.Blocks - s.Bfree) * bs,
325 available: s.Bavail * bs,
329 if r.lastDiskSpaceSample.hasData {
330 prev := r.lastDiskSpaceSample
331 interval := nextSample.sampleTime.Sub(prev.sampleTime).Seconds()
332 delta = fmt.Sprintf(" -- interval %.4f seconds %d used",
334 int64(nextSample.used-prev.used))
336 r.Logger.Printf("statfs %d available %d used %d total%s\n",
337 nextSample.available, nextSample.used, nextSample.total, delta)
338 r.lastDiskSpaceSample = nextSample
341 type cpuSample struct {
342 hasData bool // to distinguish the zero value from real data
349 // Return the number of CPUs available in the container. Return 0 if
350 // we can't figure out the real number of CPUs.
351 func (r *Reporter) getCPUCount() int64 {
352 cpusetFile, err := r.openStatFile("cpuset", "cpuset.cpus", true)
356 defer cpusetFile.Close()
357 b, err := r.readAllOrWarn(cpusetFile)
361 sp := strings.Split(string(b), ",")
363 for _, v := range sp {
365 n, _ := fmt.Sscanf(v, "%d-%d", &min, &max)
367 cpus += (max - min) + 1
375 func (r *Reporter) doCPUStats() {
376 statFile, err := r.openStatFile("cpuacct", "cpuacct.stat", true)
380 defer statFile.Close()
381 b, err := r.readAllOrWarn(statFile)
386 var userTicks, sysTicks int64
387 fmt.Sscanf(string(b), "user %d\nsystem %d", &userTicks, &sysTicks)
388 userHz := float64(100)
389 nextSample := cpuSample{
391 sampleTime: time.Now(),
392 user: float64(userTicks) / userHz,
393 sys: float64(sysTicks) / userHz,
394 cpus: r.getCPUCount(),
398 if r.lastCPUSample.hasData {
399 delta = fmt.Sprintf(" -- interval %.4f seconds %.4f user %.4f sys",
400 nextSample.sampleTime.Sub(r.lastCPUSample.sampleTime).Seconds(),
401 nextSample.user-r.lastCPUSample.user,
402 nextSample.sys-r.lastCPUSample.sys)
404 r.Logger.Printf("cpu %.4f user %.4f sys %d cpus%s\n",
405 nextSample.user, nextSample.sys, nextSample.cpus, delta)
406 r.lastCPUSample = nextSample
409 // Report stats periodically until we learn (via r.done) that someone
411 func (r *Reporter) run() {
412 defer close(r.flushed)
414 r.reportedStatFile = make(map[string]string)
416 if !r.waitForCIDFile() || !r.waitForCgroup() {
420 r.lastNetSample = make(map[string]ioSample)
421 r.lastDiskIOSample = make(map[string]ioSample)
423 if len(r.TempDir) == 0 {
424 // Temporary dir not provided, try to get it from the environment.
425 r.TempDir = os.Getenv("TMPDIR")
427 if len(r.TempDir) > 0 {
428 r.Logger.Printf("notice: monitoring temp dir %s\n", r.TempDir)
431 ticker := time.NewTicker(r.PollPeriod)
446 // If CID is empty, wait for it to appear in CIDFile. Return true if
447 // we get it before we learn (via r.done) that someone called Stop.
448 func (r *Reporter) waitForCIDFile() bool {
449 if r.CID != "" || r.CIDFile == "" {
453 ticker := time.NewTicker(100 * time.Millisecond)
456 cid, err := ioutil.ReadFile(r.CIDFile)
457 if err == nil && len(cid) > 0 {
464 r.Logger.Printf("warning: CID never appeared in %+q: %v", r.CIDFile, err)
470 // Wait for the cgroup stats files to appear in cgroup_root. Return
471 // true if they appear before r.done indicates someone called Stop. If
472 // they don't appear within one poll interval, log a warning and keep
474 func (r *Reporter) waitForCgroup() bool {
475 ticker := time.NewTicker(100 * time.Millisecond)
477 warningTimer := time.After(r.PollPeriod)
479 c, err := r.openStatFile("cpuacct", "cgroup.procs", false)
487 r.Logger.Printf("warning: cgroup stats files have not appeared after %v (config error?) -- still waiting...", r.PollPeriod)
489 r.Logger.Printf("warning: cgroup stats files never appeared for %v", r.CID)