23 #include <sys/types.h>
29 // The above block of magic allows us to look up user_hz via _SC_CLK_TCK.
37 func CopyPipeToChan(in io.ReadCloser, out chan string, done chan<- bool) {
40 // TODO(twp): handle long input records gracefully, if possible
41 // without killing the child task (#4889)
43 s := bufio.NewScanner(in)
48 out <- fmt.Sprintf("crunchstat: line buffering error: %s", s.Err())
53 func CopyChanToPipe(in <-chan string, out io.Writer) {
59 var logChan chan string
61 func LogPrintf(format string, args ...interface{}) {
65 logChan <- fmt.Sprintf("crunchstat: "+format, args...)
68 func ReadAllOrWarn(in *os.File) ([]byte, error) {
69 content, err := ioutil.ReadAll(in)
71 LogPrintf("read %s: %s", in.Name(), err)
76 var reportedStatFile = map[string]string{}
78 // Open the cgroup stats file in /sys/fs corresponding to the target
79 // cgroup, and return an *os.File. If no stats file is available,
82 // TODO: Instead of trying all options, choose a process in the
83 // container, and read /proc/PID/cgroup to determine the appropriate
84 // cgroup root for the given statgroup. (This will avoid falling back
85 // to host-level stats during container setup and teardown.)
86 func OpenStatFile(cgroup Cgroup, statgroup string, stat string) (*os.File, error) {
88 fmt.Sprintf("%s/%s/%s/%s/%s", cgroup.root, statgroup, cgroup.parent, cgroup.cid, stat),
89 fmt.Sprintf("%s/%s/%s/%s", cgroup.root, cgroup.parent, cgroup.cid, stat),
90 fmt.Sprintf("%s/%s/%s", cgroup.root, statgroup, stat),
91 fmt.Sprintf("%s/%s", cgroup.root, stat),
96 for _, path = range paths {
97 file, err = os.Open(path)
104 if pathWas, ok := reportedStatFile[stat]; !ok || pathWas != path {
105 // Log whenever we start using a new/different cgroup
106 // stat file for a given statistic. This typically
107 // happens 1 to 3 times per statistic, depending on
108 // whether we happen to collect stats [a] before any
109 // processes have been created in the container and
110 // [b] after all contained processes have exited.
111 reportedStatFile[stat] = path
113 LogPrintf("did not find stats file: stat %s, statgroup %s, cid %s, parent %s, root %s", stat, statgroup, cgroup.cid, cgroup.parent, cgroup.root)
115 LogPrintf("reading stats from %s", path)
121 func GetContainerNetStats(cgroup Cgroup) (io.Reader, error) {
122 procsFile, err := OpenStatFile(cgroup, "cpuacct", "cgroup.procs")
126 defer procsFile.Close()
127 reader := bufio.NewScanner(procsFile)
129 taskPid := reader.Text()
130 statsFilename := fmt.Sprintf("/proc/%s/net/dev", taskPid)
131 stats, err := ioutil.ReadFile(statsFilename)
133 LogPrintf("read %s: %s", statsFilename, err)
136 return strings.NewReader(string(stats)), nil
138 return nil, errors.New("Could not read stats for any proc in container")
141 type IoSample struct {
147 func DoBlkIoStats(cgroup Cgroup, lastSample map[string]IoSample) {
148 c, err := OpenStatFile(cgroup, "blkio", "blkio.io_service_bytes")
153 b := bufio.NewScanner(c)
154 var sampleTime = time.Now()
155 newSamples := make(map[string]IoSample)
157 var device, op string
159 if _, err := fmt.Sscanf(string(b.Text()), "%s %s %d", &device, &op, &val); err != nil {
162 var thisSample IoSample
164 if thisSample, ok = newSamples[device]; !ok {
165 thisSample = IoSample{sampleTime, -1, -1}
169 thisSample.rxBytes = val
171 thisSample.txBytes = val
173 newSamples[device] = thisSample
175 for dev, sample := range newSamples {
176 if sample.txBytes < 0 || sample.rxBytes < 0 {
180 if prev, ok := lastSample[dev]; ok {
181 delta = fmt.Sprintf(" -- interval %.4f seconds %d write %d read",
182 sample.sampleTime.Sub(prev.sampleTime).Seconds(),
183 sample.txBytes-prev.txBytes,
184 sample.rxBytes-prev.rxBytes)
186 LogPrintf("blkio:%s %d write %d read%s", dev, sample.txBytes, sample.rxBytes, delta)
187 lastSample[dev] = sample
191 type MemSample struct {
193 memStat map[string]int64
196 func DoMemoryStats(cgroup Cgroup) {
197 c, err := OpenStatFile(cgroup, "memory", "memory.stat")
202 b := bufio.NewScanner(c)
203 thisSample := MemSample{time.Now(), make(map[string]int64)}
204 wantStats := [...]string{"cache", "swap", "pgmajfault", "rss"}
208 if _, err := fmt.Sscanf(string(b.Text()), "%s %d", &stat, &val); err != nil {
211 thisSample.memStat[stat] = val
213 var outstat bytes.Buffer
214 for _, key := range wantStats {
215 if val, ok := thisSample.memStat[key]; ok {
216 outstat.WriteString(fmt.Sprintf(" %d %s", val, key))
219 LogPrintf("mem%s", outstat.String())
222 func DoNetworkStats(cgroup Cgroup, lastSample map[string]IoSample) {
223 sampleTime := time.Now()
224 stats, err := GetContainerNetStats(cgroup)
229 scanner := bufio.NewScanner(stats)
233 words := strings.Fields(scanner.Text())
234 if len(words) != 17 {
235 // Skip lines with wrong format
238 ifName = strings.TrimRight(words[0], ":")
239 if ifName == "lo" || ifName == "" {
240 // Skip loopback interface and lines with wrong format
243 if tx, err = strconv.ParseInt(words[9], 10, 64); err != nil {
246 if rx, err = strconv.ParseInt(words[1], 10, 64); err != nil {
249 nextSample := IoSample{}
250 nextSample.sampleTime = sampleTime
251 nextSample.txBytes = tx
252 nextSample.rxBytes = rx
254 if prev, ok := lastSample[ifName]; ok {
255 interval := nextSample.sampleTime.Sub(prev.sampleTime).Seconds()
256 delta = fmt.Sprintf(" -- interval %.4f seconds %d tx %d rx",
261 LogPrintf("net:%s %d tx %d rx%s", ifName, tx, rx, delta)
262 lastSample[ifName] = nextSample
266 type CpuSample struct {
267 hasData bool // to distinguish the zero value from real data
274 // Return the number of CPUs available in the container. Return 0 if
275 // we can't figure out the real number of CPUs.
276 func GetCpuCount(cgroup Cgroup) int64 {
277 cpusetFile, err := OpenStatFile(cgroup, "cpuset", "cpuset.cpus")
281 defer cpusetFile.Close()
282 b, err := ReadAllOrWarn(cpusetFile)
283 sp := strings.Split(string(b), ",")
285 for _, v := range sp {
287 n, _ := fmt.Sscanf(v, "%d-%d", &min, &max)
289 cpus += (max - min) + 1
297 func DoCpuStats(cgroup Cgroup, lastSample *CpuSample) {
298 statFile, err := OpenStatFile(cgroup, "cpuacct", "cpuacct.stat")
302 defer statFile.Close()
303 b, err := ReadAllOrWarn(statFile)
308 nextSample := CpuSample{true, time.Now(), 0, 0, GetCpuCount(cgroup)}
309 var userTicks, sysTicks int64
310 fmt.Sscanf(string(b), "user %d\nsystem %d", &userTicks, &sysTicks)
311 user_hz := float64(C.sysconf(C._SC_CLK_TCK))
312 nextSample.user = float64(userTicks) / user_hz
313 nextSample.sys = float64(sysTicks) / user_hz
316 if lastSample.hasData {
317 delta = fmt.Sprintf(" -- interval %.4f seconds %.4f user %.4f sys",
318 nextSample.sampleTime.Sub(lastSample.sampleTime).Seconds(),
319 nextSample.user-lastSample.user,
320 nextSample.sys-lastSample.sys)
322 LogPrintf("cpu %.4f user %.4f sys %d cpus%s",
323 nextSample.user, nextSample.sys, nextSample.cpus, delta)
324 *lastSample = nextSample
327 func PollCgroupStats(cgroup Cgroup, poll int64, stop_poll_chan <-chan bool) {
328 var lastNetSample = map[string]IoSample{}
329 var lastDiskSample = map[string]IoSample{}
330 var lastCpuSample = CpuSample{}
332 poll_chan := make(chan bool, 1)
334 // Send periodic poll events.
337 time.Sleep(time.Duration(poll) * time.Millisecond)
343 case <-stop_poll_chan:
346 // Emit stats, then select again.
348 DoMemoryStats(cgroup)
349 DoCpuStats(cgroup, &lastCpuSample)
350 DoBlkIoStats(cgroup, lastDiskSample)
351 DoNetworkStats(cgroup, lastNetSample)
355 func run(logger *log.Logger) error {
360 cgroup_cidfile string
365 flag.StringVar(&cgroup_root, "cgroup-root", "", "Root of cgroup tree")
366 flag.StringVar(&cgroup_parent, "cgroup-parent", "", "Name of container parent under cgroup")
367 flag.StringVar(&cgroup_cidfile, "cgroup-cid", "", "Path to container id file")
368 flag.Int64Var(&wait, "wait", 5, "Maximum time (in seconds) to wait for cid file to show up")
369 flag.Int64Var(&poll, "poll", 1000, "Polling frequency, in milliseconds")
373 if cgroup_root == "" {
374 logger.Fatal("Must provide -cgroup-root")
377 logChan = make(chan string, 1)
379 finish_chan := make(chan bool)
380 defer close(finish_chan)
382 go CopyChanToPipe(logChan, os.Stderr)
386 if len(flag.Args()) > 0 {
388 cmd = exec.Command(flag.Args()[0], flag.Args()[1:]...)
390 logger.Print("Running ", flag.Args())
392 // Child process will use our stdin and stdout pipes
393 // (we close our copies below)
395 cmd.Stdout = os.Stdout
397 // Forward SIGINT and SIGTERM to inner process
398 term := make(chan os.Signal, 1)
399 go func(sig <-chan os.Signal) {
401 if cmd.Process != nil {
402 cmd.Process.Signal(catch)
404 logger.Print("caught signal: ", catch)
406 signal.Notify(term, syscall.SIGTERM)
407 signal.Notify(term, syscall.SIGINT)
409 // Funnel stderr through our channel
410 stderr_pipe, err := cmd.StderrPipe()
414 go CopyPipeToChan(stderr_pipe, logChan, finish_chan)
417 if err := cmd.Start(); err != nil {
421 // Close stdin/stdout in this (parent) process
427 var container_id string
428 if cgroup_cidfile != "" {
429 // wait up to 'wait' seconds for the cid file to appear
432 for i = 0; i < time.Duration(wait)*time.Second; i += (100 * time.Millisecond) {
433 cid, err := ioutil.ReadFile(cgroup_cidfile)
434 if err == nil && len(cid) > 0 {
436 container_id = string(cid)
439 time.Sleep(100 * time.Millisecond)
442 logger.Printf("Could not read cid file %s", cgroup_cidfile)
446 stop_poll_chan := make(chan bool, 1)
447 cgroup := Cgroup{cgroup_root, cgroup_parent, container_id}
448 go PollCgroupStats(cgroup, poll, stop_poll_chan)
450 // When the child exits, tell the polling goroutine to stop.
451 defer func() { stop_poll_chan <- true }()
453 // Wait for CopyPipeToChan to consume child's stderr pipe
460 logger := log.New(os.Stderr, "crunchstat: ", 0)
461 if err := run(logger); err != nil {
462 if exiterr, ok := err.(*exec.ExitError); ok {
463 // The program has exited with an exit code != 0
465 // This works on both Unix and
466 // Windows. Although package syscall is
467 // generally platform dependent, WaitStatus is
468 // defined for both Unix and Windows and in
469 // both cases has an ExitStatus() method with
470 // the same signature.
471 if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
472 os.Exit(status.ExitStatus())
475 logger.Fatalf("cmd.Wait: %v", err)