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.Reader, out chan string, done chan<- bool) {
38 s := bufio.NewScanner(in)
45 func CopyChanToPipe(in <-chan string, out io.Writer) {
51 var logChan chan string
52 func LogPrintf(format string, args ...interface{}) {
56 logChan <- fmt.Sprintf("crunchstat: " + format, args...)
59 func ReadAllOrWarn(in *os.File) ([]byte, error) {
60 content, err := ioutil.ReadAll(in)
62 LogPrintf("read %s: %s", in.Name(), err)
67 var reportedStatFile = map[string]string{}
69 // Open the cgroup stats file in /sys/fs corresponding to the target
70 // cgroup, and return an *os.File. If no stats file is available,
73 // TODO: Instead of trying all options, choose a process in the
74 // container, and read /proc/PID/cgroup to determine the appropriate
75 // cgroup root for the given statgroup. (This will avoid falling back
76 // to host-level stats during container setup and teardown.)
77 func OpenStatFile(cgroup Cgroup, statgroup string, stat string) (*os.File, error) {
79 fmt.Sprintf("%s/%s/%s/%s/%s", cgroup.root, statgroup, cgroup.parent, cgroup.cid, stat),
80 fmt.Sprintf("%s/%s/%s/%s", cgroup.root, cgroup.parent, cgroup.cid, stat),
81 fmt.Sprintf("%s/%s/%s", cgroup.root, statgroup, stat),
82 fmt.Sprintf("%s/%s", cgroup.root, stat),
87 for _, path = range paths {
88 file, err = os.Open(path)
95 if pathWas, ok := reportedStatFile[stat]; !ok || pathWas != path {
96 // Log whenever we start using a new/different cgroup
97 // stat file for a given statistic. This typically
98 // happens 1 to 3 times per statistic, depending on
99 // whether we happen to collect stats [a] before any
100 // processes have been created in the container and
101 // [b] after all contained processes have exited.
102 reportedStatFile[stat] = path
104 LogPrintf("did not find stats file: stat %s, statgroup %s, cid %s, parent %s, root %s", stat, statgroup, cgroup.cid, cgroup.parent, cgroup.root)
106 LogPrintf("reading stats from %s", path)
112 func GetContainerNetStats(cgroup Cgroup) (io.Reader, error) {
113 procsFile, err := OpenStatFile(cgroup, "cpuacct", "cgroup.procs")
117 defer procsFile.Close()
118 reader := bufio.NewScanner(procsFile)
120 taskPid := reader.Text()
121 statsFilename := fmt.Sprintf("/proc/%s/net/dev", taskPid)
122 stats, err := ioutil.ReadFile(statsFilename)
124 LogPrintf("read %s: %s", statsFilename, err)
127 return strings.NewReader(string(stats)), nil
129 return nil, errors.New("Could not read stats for any proc in container")
132 type IoSample struct {
138 func DoBlkIoStats(cgroup Cgroup, lastSample map[string]IoSample) {
139 c, err := OpenStatFile(cgroup, "blkio", "blkio.io_service_bytes")
144 b := bufio.NewScanner(c)
145 var sampleTime = time.Now()
146 newSamples := make(map[string]IoSample)
148 var device, op string
150 if _, err := fmt.Sscanf(string(b.Text()), "%s %s %d", &device, &op, &val); err != nil {
153 var thisSample IoSample
155 if thisSample, ok = newSamples[device]; !ok {
156 thisSample = IoSample{sampleTime, -1, -1}
160 thisSample.rxBytes = val
162 thisSample.txBytes = val
164 newSamples[device] = thisSample
166 for dev, sample := range newSamples {
167 if sample.txBytes < 0 || sample.rxBytes < 0 {
171 if prev, ok := lastSample[dev]; ok {
172 delta = fmt.Sprintf(" -- interval %.4f seconds %d write %d read",
173 sample.sampleTime.Sub(prev.sampleTime).Seconds(),
174 sample.txBytes-prev.txBytes,
175 sample.rxBytes-prev.rxBytes)
177 LogPrintf("blkio:%s %d write %d read%s", dev, sample.txBytes, sample.rxBytes, delta)
178 lastSample[dev] = sample
182 type MemSample struct {
184 memStat map[string]int64
187 func DoMemoryStats(cgroup Cgroup) {
188 c, err := OpenStatFile(cgroup, "memory", "memory.stat")
193 b := bufio.NewScanner(c)
194 thisSample := MemSample{time.Now(), make(map[string]int64)}
195 wantStats := [...]string{"cache", "pgmajfault", "rss"}
199 if _, err := fmt.Sscanf(string(b.Text()), "%s %d", &stat, &val); err != nil {
202 thisSample.memStat[stat] = val
204 var outstat bytes.Buffer
205 for _, key := range wantStats {
206 if val, ok := thisSample.memStat[key]; ok {
207 outstat.WriteString(fmt.Sprintf(" %d %s", val, key))
210 LogPrintf("mem%s", outstat.String())
213 func DoNetworkStats(cgroup Cgroup, lastSample map[string]IoSample) {
214 sampleTime := time.Now()
215 stats, err := GetContainerNetStats(cgroup)
220 scanner := bufio.NewScanner(stats)
224 words := strings.Fields(scanner.Text())
225 if len(words) != 17 {
226 // Skip lines with wrong format
229 ifName = strings.TrimRight(words[0], ":")
230 if ifName == "lo" || ifName == "" {
231 // Skip loopback interface and lines with wrong format
234 if tx, err = strconv.ParseInt(words[9], 10, 64); err != nil {
237 if rx, err = strconv.ParseInt(words[1], 10, 64); err != nil {
240 nextSample := IoSample{}
241 nextSample.sampleTime = sampleTime
242 nextSample.txBytes = tx
243 nextSample.rxBytes = rx
245 if prev, ok := lastSample[ifName]; ok {
246 interval := nextSample.sampleTime.Sub(prev.sampleTime).Seconds()
247 delta = fmt.Sprintf(" -- interval %.4f seconds %d tx %d rx",
252 LogPrintf("net:%s %d tx %d rx%s", ifName, tx, rx, delta)
253 lastSample[ifName] = nextSample
257 type CpuSample struct {
258 hasData bool // to distinguish the zero value from real data
265 // Return the number of CPUs available in the container. Return 0 if
266 // we can't figure out the real number of CPUs.
267 func GetCpuCount(cgroup Cgroup) int64 {
268 cpusetFile, err := OpenStatFile(cgroup, "cpuset", "cpuset.cpus")
272 defer cpusetFile.Close()
273 b, err := ReadAllOrWarn(cpusetFile)
274 sp := strings.Split(string(b), ",")
276 for _, v := range sp {
278 n, _ := fmt.Sscanf(v, "%d-%d", &min, &max)
280 cpus += (max - min) + 1
288 func DoCpuStats(cgroup Cgroup, lastSample *CpuSample) {
289 statFile, err := OpenStatFile(cgroup, "cpuacct", "cpuacct.stat")
293 defer statFile.Close()
294 b, err := ReadAllOrWarn(statFile)
299 nextSample := CpuSample{true, time.Now(), 0, 0, GetCpuCount(cgroup)}
300 var userTicks, sysTicks int64
301 fmt.Sscanf(string(b), "user %d\nsystem %d", &userTicks, &sysTicks)
302 user_hz := float64(C.sysconf(C._SC_CLK_TCK))
303 nextSample.user = float64(userTicks) / user_hz
304 nextSample.sys = float64(sysTicks) / user_hz
307 if lastSample.hasData {
308 delta = fmt.Sprintf(" -- interval %.4f seconds %.4f user %.4f sys",
309 nextSample.sampleTime.Sub(lastSample.sampleTime).Seconds(),
310 nextSample.user-lastSample.user,
311 nextSample.sys-lastSample.sys)
313 LogPrintf("cpu %.4f user %.4f sys %d cpus%s",
314 nextSample.user, nextSample.sys, nextSample.cpus, delta)
315 *lastSample = nextSample
318 func PollCgroupStats(cgroup Cgroup, poll int64, stop_poll_chan <-chan bool) {
319 var lastNetSample = map[string]IoSample{}
320 var lastDiskSample = map[string]IoSample{}
321 var lastCpuSample = CpuSample{}
323 poll_chan := make(chan bool, 1)
325 // Send periodic poll events.
328 time.Sleep(time.Duration(poll) * time.Millisecond)
334 case <-stop_poll_chan:
337 // Emit stats, then select again.
339 DoMemoryStats(cgroup)
340 DoCpuStats(cgroup, &lastCpuSample)
341 DoBlkIoStats(cgroup, lastDiskSample)
342 DoNetworkStats(cgroup, lastNetSample)
346 func run(logger *log.Logger) error {
351 cgroup_cidfile string
356 flag.StringVar(&cgroup_root, "cgroup-root", "", "Root of cgroup tree")
357 flag.StringVar(&cgroup_parent, "cgroup-parent", "", "Name of container parent under cgroup")
358 flag.StringVar(&cgroup_cidfile, "cgroup-cid", "", "Path to container id file")
359 flag.Int64Var(&wait, "wait", 5, "Maximum time (in seconds) to wait for cid file to show up")
360 flag.Int64Var(&poll, "poll", 1000, "Polling frequency, in milliseconds")
364 if cgroup_root == "" {
365 logger.Fatal("Must provide -cgroup-root")
368 logChan = make(chan string, 1)
370 finish_chan := make(chan bool)
371 defer close(finish_chan)
373 go CopyChanToPipe(logChan, os.Stderr)
377 if len(flag.Args()) > 0 {
379 cmd = exec.Command(flag.Args()[0], flag.Args()[1:]...)
381 logger.Print("Running ", flag.Args())
383 // Child process will use our stdin and stdout pipes
384 // (we close our copies below)
386 cmd.Stdout = os.Stdout
388 // Forward SIGINT and SIGTERM to inner process
389 term := make(chan os.Signal, 1)
390 go func(sig <-chan os.Signal) {
392 if cmd.Process != nil {
393 cmd.Process.Signal(catch)
395 logger.Print("caught signal: ", catch)
397 signal.Notify(term, syscall.SIGTERM)
398 signal.Notify(term, syscall.SIGINT)
400 // Funnel stderr through our channel
401 stderr_pipe, err := cmd.StderrPipe()
405 go CopyPipeToChan(stderr_pipe, logChan, finish_chan)
408 if err := cmd.Start(); err != nil {
412 // Close stdin/stdout in this (parent) process
418 var container_id string
419 if cgroup_cidfile != "" {
420 // wait up to 'wait' seconds for the cid file to appear
423 for i = 0; i < time.Duration(wait)*time.Second; i += (100 * time.Millisecond) {
424 cid, err := ioutil.ReadFile(cgroup_cidfile)
425 if err == nil && len(cid) > 0 {
427 container_id = string(cid)
430 time.Sleep(100 * time.Millisecond)
433 logger.Printf("Could not read cid file %s", cgroup_cidfile)
437 stop_poll_chan := make(chan bool, 1)
438 cgroup := Cgroup{cgroup_root, cgroup_parent, container_id}
439 go PollCgroupStats(cgroup, poll, stop_poll_chan)
441 // When the child exits, tell the polling goroutine to stop.
442 defer func() { stop_poll_chan <- true }()
444 // Wait for CopyPipeToChan to consume child's stderr pipe
451 logger := log.New(os.Stderr, "crunchstat: ", 0)
452 if err := run(logger); err != nil {
453 if exiterr, ok := err.(*exec.ExitError); ok {
454 // The program has exited with an exit code != 0
456 // This works on both Unix and
457 // Windows. Although package syscall is
458 // generally platform dependent, WaitStatus is
459 // defined for both Unix and Windows and in
460 // both cases has an ExitStatus() method with
461 // the same signature.
462 if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
463 os.Exit(status.ExitStatus())
466 logger.Fatalf("cmd.Wait: %v", err)