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) {
38 reader := bufio.NewReader(in)
40 line, err := reader.ReadBytes('\n')
43 // err == nil IFF line ends in \n
44 line = line[:len(line)-1]
50 out <- fmt.Sprintf("crunchstat: line buffering error: %s", err)
59 func CopyChanToPipe(in <-chan string, out io.Writer) {
65 var logChan chan string
67 func LogPrintf(format string, args ...interface{}) {
71 logChan <- fmt.Sprintf("crunchstat: "+format, args...)
74 func ReadAllOrWarn(in *os.File) ([]byte, error) {
75 content, err := ioutil.ReadAll(in)
77 LogPrintf("read %s: %s", in.Name(), err)
82 var reportedStatFile = map[string]string{}
84 // Open the cgroup stats file in /sys/fs corresponding to the target
85 // cgroup, and return an *os.File. If no stats file is available,
88 // TODO: Instead of trying all options, choose a process in the
89 // container, and read /proc/PID/cgroup to determine the appropriate
90 // cgroup root for the given statgroup. (This will avoid falling back
91 // to host-level stats during container setup and teardown.)
92 func OpenStatFile(cgroup Cgroup, statgroup string, stat string) (*os.File, error) {
94 fmt.Sprintf("%s/%s/%s/%s/%s", cgroup.root, statgroup, cgroup.parent, cgroup.cid, stat),
95 fmt.Sprintf("%s/%s/%s/%s", cgroup.root, cgroup.parent, cgroup.cid, stat),
96 fmt.Sprintf("%s/%s/%s", cgroup.root, statgroup, stat),
97 fmt.Sprintf("%s/%s", cgroup.root, stat),
102 for _, path = range paths {
103 file, err = os.Open(path)
110 if pathWas, ok := reportedStatFile[stat]; !ok || pathWas != path {
111 // Log whenever we start using a new/different cgroup
112 // stat file for a given statistic. This typically
113 // happens 1 to 3 times per statistic, depending on
114 // whether we happen to collect stats [a] before any
115 // processes have been created in the container and
116 // [b] after all contained processes have exited.
117 reportedStatFile[stat] = path
119 LogPrintf("did not find stats file: stat %s, statgroup %s, cid %s, parent %s, root %s", stat, statgroup, cgroup.cid, cgroup.parent, cgroup.root)
121 LogPrintf("reading stats from %s", path)
127 func GetContainerNetStats(cgroup Cgroup) (io.Reader, error) {
128 procsFile, err := OpenStatFile(cgroup, "cpuacct", "cgroup.procs")
132 defer procsFile.Close()
133 reader := bufio.NewScanner(procsFile)
135 taskPid := reader.Text()
136 statsFilename := fmt.Sprintf("/proc/%s/net/dev", taskPid)
137 stats, err := ioutil.ReadFile(statsFilename)
139 LogPrintf("read %s: %s", statsFilename, err)
142 return strings.NewReader(string(stats)), nil
144 return nil, errors.New("Could not read stats for any proc in container")
147 type IoSample struct {
153 func DoBlkIoStats(cgroup Cgroup, lastSample map[string]IoSample) {
154 c, err := OpenStatFile(cgroup, "blkio", "blkio.io_service_bytes")
159 b := bufio.NewScanner(c)
160 var sampleTime = time.Now()
161 newSamples := make(map[string]IoSample)
163 var device, op string
165 if _, err := fmt.Sscanf(string(b.Text()), "%s %s %d", &device, &op, &val); err != nil {
168 var thisSample IoSample
170 if thisSample, ok = newSamples[device]; !ok {
171 thisSample = IoSample{sampleTime, -1, -1}
175 thisSample.rxBytes = val
177 thisSample.txBytes = val
179 newSamples[device] = thisSample
181 for dev, sample := range newSamples {
182 if sample.txBytes < 0 || sample.rxBytes < 0 {
186 if prev, ok := lastSample[dev]; ok {
187 delta = fmt.Sprintf(" -- interval %.4f seconds %d write %d read",
188 sample.sampleTime.Sub(prev.sampleTime).Seconds(),
189 sample.txBytes-prev.txBytes,
190 sample.rxBytes-prev.rxBytes)
192 LogPrintf("blkio:%s %d write %d read%s", dev, sample.txBytes, sample.rxBytes, delta)
193 lastSample[dev] = sample
197 type MemSample struct {
199 memStat map[string]int64
202 func DoMemoryStats(cgroup Cgroup) {
203 c, err := OpenStatFile(cgroup, "memory", "memory.stat")
208 b := bufio.NewScanner(c)
209 thisSample := MemSample{time.Now(), make(map[string]int64)}
210 wantStats := [...]string{"cache", "swap", "pgmajfault", "rss"}
214 if _, err := fmt.Sscanf(string(b.Text()), "%s %d", &stat, &val); err != nil {
217 thisSample.memStat[stat] = val
219 var outstat bytes.Buffer
220 for _, key := range wantStats {
221 if val, ok := thisSample.memStat[key]; ok {
222 outstat.WriteString(fmt.Sprintf(" %d %s", val, key))
225 LogPrintf("mem%s", outstat.String())
228 func DoNetworkStats(cgroup Cgroup, lastSample map[string]IoSample) {
229 sampleTime := time.Now()
230 stats, err := GetContainerNetStats(cgroup)
235 scanner := bufio.NewScanner(stats)
239 words := strings.Fields(scanner.Text())
240 if len(words) != 17 {
241 // Skip lines with wrong format
244 ifName = strings.TrimRight(words[0], ":")
245 if ifName == "lo" || ifName == "" {
246 // Skip loopback interface and lines with wrong format
249 if tx, err = strconv.ParseInt(words[9], 10, 64); err != nil {
252 if rx, err = strconv.ParseInt(words[1], 10, 64); err != nil {
255 nextSample := IoSample{}
256 nextSample.sampleTime = sampleTime
257 nextSample.txBytes = tx
258 nextSample.rxBytes = rx
260 if prev, ok := lastSample[ifName]; ok {
261 interval := nextSample.sampleTime.Sub(prev.sampleTime).Seconds()
262 delta = fmt.Sprintf(" -- interval %.4f seconds %d tx %d rx",
267 LogPrintf("net:%s %d tx %d rx%s", ifName, tx, rx, delta)
268 lastSample[ifName] = nextSample
272 type CpuSample struct {
273 hasData bool // to distinguish the zero value from real data
280 // Return the number of CPUs available in the container. Return 0 if
281 // we can't figure out the real number of CPUs.
282 func GetCpuCount(cgroup Cgroup) int64 {
283 cpusetFile, err := OpenStatFile(cgroup, "cpuset", "cpuset.cpus")
287 defer cpusetFile.Close()
288 b, err := ReadAllOrWarn(cpusetFile)
289 sp := strings.Split(string(b), ",")
291 for _, v := range sp {
293 n, _ := fmt.Sscanf(v, "%d-%d", &min, &max)
295 cpus += (max - min) + 1
303 func DoCpuStats(cgroup Cgroup, lastSample *CpuSample) {
304 statFile, err := OpenStatFile(cgroup, "cpuacct", "cpuacct.stat")
308 defer statFile.Close()
309 b, err := ReadAllOrWarn(statFile)
314 nextSample := CpuSample{true, time.Now(), 0, 0, GetCpuCount(cgroup)}
315 var userTicks, sysTicks int64
316 fmt.Sscanf(string(b), "user %d\nsystem %d", &userTicks, &sysTicks)
317 user_hz := float64(C.sysconf(C._SC_CLK_TCK))
318 nextSample.user = float64(userTicks) / user_hz
319 nextSample.sys = float64(sysTicks) / user_hz
322 if lastSample.hasData {
323 delta = fmt.Sprintf(" -- interval %.4f seconds %.4f user %.4f sys",
324 nextSample.sampleTime.Sub(lastSample.sampleTime).Seconds(),
325 nextSample.user-lastSample.user,
326 nextSample.sys-lastSample.sys)
328 LogPrintf("cpu %.4f user %.4f sys %d cpus%s",
329 nextSample.user, nextSample.sys, nextSample.cpus, delta)
330 *lastSample = nextSample
333 func PollCgroupStats(cgroup Cgroup, poll int64, stop_poll_chan <-chan bool) {
334 var lastNetSample = map[string]IoSample{}
335 var lastDiskSample = map[string]IoSample{}
336 var lastCpuSample = CpuSample{}
338 poll_chan := make(chan bool, 1)
340 // Send periodic poll events.
343 time.Sleep(time.Duration(poll) * time.Millisecond)
349 case <-stop_poll_chan:
352 // Emit stats, then select again.
354 DoMemoryStats(cgroup)
355 DoCpuStats(cgroup, &lastCpuSample)
356 DoBlkIoStats(cgroup, lastDiskSample)
357 DoNetworkStats(cgroup, lastNetSample)
361 func run(logger *log.Logger) error {
366 cgroup_cidfile string
371 flag.StringVar(&cgroup_root, "cgroup-root", "", "Root of cgroup tree")
372 flag.StringVar(&cgroup_parent, "cgroup-parent", "", "Name of container parent under cgroup")
373 flag.StringVar(&cgroup_cidfile, "cgroup-cid", "", "Path to container id file")
374 flag.Int64Var(&wait, "wait", 5, "Maximum time (in seconds) to wait for cid file to show up")
375 flag.Int64Var(&poll, "poll", 1000, "Polling frequency, in milliseconds")
379 if cgroup_root == "" {
380 logger.Fatal("Must provide -cgroup-root")
383 logChan = make(chan string, 1)
385 finish_chan := make(chan bool)
386 defer close(finish_chan)
388 go CopyChanToPipe(logChan, os.Stderr)
392 if len(flag.Args()) > 0 {
394 cmd = exec.Command(flag.Args()[0], flag.Args()[1:]...)
396 logger.Print("Running ", flag.Args())
398 // Child process will use our stdin and stdout pipes
399 // (we close our copies below)
401 cmd.Stdout = os.Stdout
403 // Forward SIGINT and SIGTERM to inner process
404 term := make(chan os.Signal, 1)
405 go func(sig <-chan os.Signal) {
407 if cmd.Process != nil {
408 cmd.Process.Signal(catch)
410 logger.Print("caught signal: ", catch)
412 signal.Notify(term, syscall.SIGTERM)
413 signal.Notify(term, syscall.SIGINT)
415 // Funnel stderr through our channel
416 stderr_pipe, err := cmd.StderrPipe()
420 go CopyPipeToChan(stderr_pipe, logChan, finish_chan)
423 if err := cmd.Start(); err != nil {
427 // Close stdin/stdout in this (parent) process
433 var container_id string
434 if cgroup_cidfile != "" {
435 // wait up to 'wait' seconds for the cid file to appear
438 for i = 0; i < time.Duration(wait)*time.Second; i += (100 * time.Millisecond) {
439 cid, err := ioutil.ReadFile(cgroup_cidfile)
440 if err == nil && len(cid) > 0 {
442 container_id = string(cid)
445 time.Sleep(100 * time.Millisecond)
448 logger.Printf("Could not read cid file %s", cgroup_cidfile)
452 stop_poll_chan := make(chan bool, 1)
453 cgroup := Cgroup{cgroup_root, cgroup_parent, container_id}
454 go PollCgroupStats(cgroup, poll, stop_poll_chan)
456 // When the child exits, tell the polling goroutine to stop.
457 defer func() { stop_poll_chan <- true }()
459 // Wait for CopyPipeToChan to consume child's stderr pipe
466 logger := log.New(os.Stderr, "crunchstat: ", 0)
467 if err := run(logger); err != nil {
468 if exiterr, ok := err.(*exec.ExitError); ok {
469 // The program has exited with an exit code != 0
471 // This works on both Unix and
472 // Windows. Although package syscall is
473 // generally platform dependent, WaitStatus is
474 // defined for both Unix and Windows and in
475 // both cases has an ExitStatus() method with
476 // the same signature.
477 if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
478 os.Exit(status.ExitStatus())
481 logger.Fatalf("cmd.Wait: %v", err)