23 #include <sys/types.h>
29 // The above block of magic allows us to look up user_hz via _SC_CLK_TCK.
37 var childLog = log.New(os.Stderr, "", 0)
38 var statLog = log.New(os.Stderr, "crunchstat: ", 0)
41 MaxLogLine = 1 << 14 // Child stderr lines >16KiB will be split
44 func CopyPipeToChildLog(in io.ReadCloser, done chan<- bool) {
45 reader := bufio.NewReaderSize(in, MaxLogLine)
48 line, isPrefix, err := reader.ReadLine()
51 } else if err != nil {
52 statLog.Fatal("error reading child stderr:", err)
58 childLog.Print(prefix, string(line), suffix)
59 // Set up prefix for following line
70 func ReadAllOrWarn(in *os.File) ([]byte, error) {
71 content, err := ioutil.ReadAll(in)
73 statLog.Printf("error reading %s: %s\n", in.Name(), err)
78 var reportedStatFile = map[string]string{}
80 // Open the cgroup stats file in /sys/fs corresponding to the target
81 // cgroup, and return an *os.File. If no stats file is available,
84 // TODO: Instead of trying all options, choose a process in the
85 // container, and read /proc/PID/cgroup to determine the appropriate
86 // cgroup root for the given statgroup. (This will avoid falling back
87 // to host-level stats during container setup and teardown.)
88 func OpenStatFile(cgroup Cgroup, statgroup string, stat string) (*os.File, error) {
91 // Collect container's stats
93 fmt.Sprintf("%s/%s/%s/%s/%s", cgroup.root, statgroup, cgroup.parent, cgroup.cid, stat),
94 fmt.Sprintf("%s/%s/%s/%s", cgroup.root, cgroup.parent, cgroup.cid, stat),
97 // Collect this host's stats
99 fmt.Sprintf("%s/%s/%s", cgroup.root, statgroup, stat),
100 fmt.Sprintf("%s/%s", cgroup.root, stat),
106 for _, path = range paths {
107 file, err = os.Open(path)
114 if pathWas, ok := reportedStatFile[stat]; !ok || pathWas != path {
115 // Log whenever we start using a new/different cgroup
116 // stat file for a given statistic. This typically
117 // happens 1 to 3 times per statistic, depending on
118 // whether we happen to collect stats [a] before any
119 // processes have been created in the container and
120 // [b] after all contained processes have exited.
122 statLog.Printf("notice: stats not available: stat %s, statgroup %s, cid %s, parent %s, root %s\n", stat, statgroup, cgroup.cid, cgroup.parent, cgroup.root)
124 statLog.Printf("notice: stats moved from %s to %s\n", reportedStatFile[stat], path)
126 statLog.Printf("notice: reading stats from %s\n", path)
128 reportedStatFile[stat] = path
133 func GetContainerNetStats(cgroup Cgroup) (io.Reader, error) {
134 procsFile, err := OpenStatFile(cgroup, "cpuacct", "cgroup.procs")
138 defer procsFile.Close()
139 reader := bufio.NewScanner(procsFile)
141 taskPid := reader.Text()
142 statsFilename := fmt.Sprintf("/proc/%s/net/dev", taskPid)
143 stats, err := ioutil.ReadFile(statsFilename)
145 statLog.Printf("error reading %s: %s\n", statsFilename, err)
148 return strings.NewReader(string(stats)), nil
150 return nil, errors.New("Could not read stats for any proc in container")
153 type IoSample struct {
159 func DoBlkIoStats(cgroup Cgroup, lastSample map[string]IoSample) {
160 c, err := OpenStatFile(cgroup, "blkio", "blkio.io_service_bytes")
165 b := bufio.NewScanner(c)
166 var sampleTime = time.Now()
167 newSamples := make(map[string]IoSample)
169 var device, op string
171 if _, err := fmt.Sscanf(string(b.Text()), "%s %s %d", &device, &op, &val); err != nil {
174 var thisSample IoSample
176 if thisSample, ok = newSamples[device]; !ok {
177 thisSample = IoSample{sampleTime, -1, -1}
181 thisSample.rxBytes = val
183 thisSample.txBytes = val
185 newSamples[device] = thisSample
187 for dev, sample := range newSamples {
188 if sample.txBytes < 0 || sample.rxBytes < 0 {
192 if prev, ok := lastSample[dev]; ok {
193 delta = fmt.Sprintf(" -- interval %.4f seconds %d write %d read",
194 sample.sampleTime.Sub(prev.sampleTime).Seconds(),
195 sample.txBytes-prev.txBytes,
196 sample.rxBytes-prev.rxBytes)
198 statLog.Printf("blkio:%s %d write %d read%s\n", dev, sample.txBytes, sample.rxBytes, delta)
199 lastSample[dev] = sample
203 type MemSample struct {
205 memStat map[string]int64
208 func DoMemoryStats(cgroup Cgroup) {
209 c, err := OpenStatFile(cgroup, "memory", "memory.stat")
214 b := bufio.NewScanner(c)
215 thisSample := MemSample{time.Now(), make(map[string]int64)}
216 wantStats := [...]string{"cache", "swap", "pgmajfault", "rss"}
220 if _, err := fmt.Sscanf(string(b.Text()), "%s %d", &stat, &val); err != nil {
223 thisSample.memStat[stat] = val
225 var outstat bytes.Buffer
226 for _, key := range wantStats {
227 if val, ok := thisSample.memStat[key]; ok {
228 outstat.WriteString(fmt.Sprintf(" %d %s", val, key))
231 statLog.Printf("mem%s\n", outstat.String())
234 func DoNetworkStats(cgroup Cgroup, lastSample map[string]IoSample) {
235 sampleTime := time.Now()
236 stats, err := GetContainerNetStats(cgroup)
241 scanner := bufio.NewScanner(stats)
245 words := strings.Fields(scanner.Text())
246 if len(words) != 17 {
247 // Skip lines with wrong format
250 ifName = strings.TrimRight(words[0], ":")
251 if ifName == "lo" || ifName == "" {
252 // Skip loopback interface and lines with wrong format
255 if tx, err = strconv.ParseInt(words[9], 10, 64); err != nil {
258 if rx, err = strconv.ParseInt(words[1], 10, 64); err != nil {
261 nextSample := IoSample{}
262 nextSample.sampleTime = sampleTime
263 nextSample.txBytes = tx
264 nextSample.rxBytes = rx
266 if prev, ok := lastSample[ifName]; ok {
267 interval := nextSample.sampleTime.Sub(prev.sampleTime).Seconds()
268 delta = fmt.Sprintf(" -- interval %.4f seconds %d tx %d rx",
273 statLog.Printf("net:%s %d tx %d rx%s\n", ifName, tx, rx, delta)
274 lastSample[ifName] = nextSample
278 type CpuSample struct {
279 hasData bool // to distinguish the zero value from real data
286 // Return the number of CPUs available in the container. Return 0 if
287 // we can't figure out the real number of CPUs.
288 func GetCpuCount(cgroup Cgroup) int64 {
289 cpusetFile, err := OpenStatFile(cgroup, "cpuset", "cpuset.cpus")
293 defer cpusetFile.Close()
294 b, err := ReadAllOrWarn(cpusetFile)
295 sp := strings.Split(string(b), ",")
297 for _, v := range sp {
299 n, _ := fmt.Sscanf(v, "%d-%d", &min, &max)
301 cpus += (max - min) + 1
309 func DoCpuStats(cgroup Cgroup, lastSample *CpuSample) {
310 statFile, err := OpenStatFile(cgroup, "cpuacct", "cpuacct.stat")
314 defer statFile.Close()
315 b, err := ReadAllOrWarn(statFile)
320 nextSample := CpuSample{true, time.Now(), 0, 0, GetCpuCount(cgroup)}
321 var userTicks, sysTicks int64
322 fmt.Sscanf(string(b), "user %d\nsystem %d", &userTicks, &sysTicks)
323 user_hz := float64(C.sysconf(C._SC_CLK_TCK))
324 nextSample.user = float64(userTicks) / user_hz
325 nextSample.sys = float64(sysTicks) / user_hz
328 if lastSample.hasData {
329 delta = fmt.Sprintf(" -- interval %.4f seconds %.4f user %.4f sys",
330 nextSample.sampleTime.Sub(lastSample.sampleTime).Seconds(),
331 nextSample.user-lastSample.user,
332 nextSample.sys-lastSample.sys)
334 statLog.Printf("cpu %.4f user %.4f sys %d cpus%s\n",
335 nextSample.user, nextSample.sys, nextSample.cpus, delta)
336 *lastSample = nextSample
339 func PollCgroupStats(cgroup Cgroup, poll int64, stop_poll_chan <-chan bool) {
340 var lastNetSample = map[string]IoSample{}
341 var lastDiskSample = map[string]IoSample{}
342 var lastCpuSample = CpuSample{}
344 poll_chan := make(chan bool, 1)
346 // Send periodic poll events.
349 time.Sleep(time.Duration(poll) * time.Millisecond)
355 case <-stop_poll_chan:
358 // Emit stats, then select again.
360 DoMemoryStats(cgroup)
361 DoCpuStats(cgroup, &lastCpuSample)
362 DoBlkIoStats(cgroup, lastDiskSample)
363 DoNetworkStats(cgroup, lastNetSample)
367 func run(logger *log.Logger) error {
372 cgroup_cidfile string
377 flag.StringVar(&cgroup_root, "cgroup-root", "", "Root of cgroup tree")
378 flag.StringVar(&cgroup_parent, "cgroup-parent", "", "Name of container parent under cgroup")
379 flag.StringVar(&cgroup_cidfile, "cgroup-cid", "", "Path to container id file")
380 flag.Int64Var(&wait, "wait", 5, "Maximum time (in seconds) to wait for cid file to show up")
381 flag.Int64Var(&poll, "poll", 1000, "Polling frequency, in milliseconds")
385 if cgroup_root == "" {
386 statLog.Fatal("error: must provide -cgroup-root")
389 finish_chan := make(chan bool)
390 defer close(finish_chan)
394 if len(flag.Args()) > 0 {
396 cmd = exec.Command(flag.Args()[0], flag.Args()[1:]...)
398 childLog.Println("Running", flag.Args())
400 // Child process will use our stdin and stdout pipes
401 // (we close our copies below)
403 cmd.Stdout = os.Stdout
405 // Forward SIGINT and SIGTERM to inner process
406 sigChan := make(chan os.Signal, 1)
407 go func(sig <-chan os.Signal) {
409 if cmd.Process != nil {
410 cmd.Process.Signal(catch)
412 statLog.Println("notice: caught signal:", catch)
414 signal.Notify(sigChan, syscall.SIGTERM)
415 signal.Notify(sigChan, syscall.SIGINT)
417 // Funnel stderr through our channel
418 stderr_pipe, err := cmd.StderrPipe()
420 statLog.Fatalln("error in StderrPipe:", err)
422 go CopyPipeToChildLog(stderr_pipe, finish_chan)
425 if err := cmd.Start(); err != nil {
426 statLog.Fatalln("error in cmd.Start:", err)
429 // Close stdin/stdout in this (parent) process
435 var container_id string
436 if cgroup_cidfile != "" {
437 // wait up to 'wait' seconds for the cid file to appear
440 for i = 0; i < time.Duration(wait)*time.Second; i += (100 * time.Millisecond) {
441 cid, err := ioutil.ReadFile(cgroup_cidfile)
442 if err == nil && len(cid) > 0 {
444 container_id = string(cid)
447 time.Sleep(100 * time.Millisecond)
450 statLog.Println("error reading cid file:", cgroup_cidfile)
454 stop_poll_chan := make(chan bool, 1)
455 cgroup := Cgroup{cgroup_root, cgroup_parent, container_id}
456 go PollCgroupStats(cgroup, poll, stop_poll_chan)
458 // When the child exits, tell the polling goroutine to stop.
459 defer func() { stop_poll_chan <- true }()
461 // Wait for CopyPipeToChan to consume child's stderr pipe
468 logger := log.New(os.Stderr, "crunchstat: ", 0)
469 if err := run(logger); err != nil {
470 if exiterr, ok := err.(*exec.ExitError); ok {
471 // The program has exited with an exit code != 0
473 // This works on both Unix and
474 // Windows. Although package syscall is
475 // generally platform dependent, WaitStatus is
476 // defined for both Unix and Windows and in
477 // both cases has an ExitStatus() method with
478 // the same signature.
479 if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
480 os.Exit(status.ExitStatus())
483 statLog.Fatalln("error in cmd.Wait:", err)