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) {
90 fmt.Sprintf("%s/%s/%s/%s/%s", cgroup.root, statgroup, cgroup.parent, cgroup.cid, stat),
91 fmt.Sprintf("%s/%s/%s/%s", cgroup.root, cgroup.parent, cgroup.cid, stat),
92 fmt.Sprintf("%s/%s/%s", cgroup.root, statgroup, stat),
93 fmt.Sprintf("%s/%s", cgroup.root, stat),
98 for _, path = range paths {
99 file, err = os.Open(path)
106 if pathWas, ok := reportedStatFile[stat]; !ok || pathWas != path {
107 // Log whenever we start using a new/different cgroup
108 // stat file for a given statistic. This typically
109 // happens 1 to 3 times per statistic, depending on
110 // whether we happen to collect stats [a] before any
111 // processes have been created in the container and
112 // [b] after all contained processes have exited.
113 reportedStatFile[stat] = path
115 statLog.Printf("error finding stats file: stat %s, statgroup %s, cid %s, parent %s, root %s\n", stat, statgroup, cgroup.cid, cgroup.parent, cgroup.root)
117 statLog.Printf("error reading stats from %s\n", path)
123 func GetContainerNetStats(cgroup Cgroup) (io.Reader, error) {
124 procsFile, err := OpenStatFile(cgroup, "cpuacct", "cgroup.procs")
128 defer procsFile.Close()
129 reader := bufio.NewScanner(procsFile)
131 taskPid := reader.Text()
132 statsFilename := fmt.Sprintf("/proc/%s/net/dev", taskPid)
133 stats, err := ioutil.ReadFile(statsFilename)
135 statLog.Printf("read %s: %s\n", statsFilename, err)
138 return strings.NewReader(string(stats)), nil
140 return nil, errors.New("Could not read stats for any proc in container")
143 type IoSample struct {
149 func DoBlkIoStats(cgroup Cgroup, lastSample map[string]IoSample) {
150 c, err := OpenStatFile(cgroup, "blkio", "blkio.io_service_bytes")
155 b := bufio.NewScanner(c)
156 var sampleTime = time.Now()
157 newSamples := make(map[string]IoSample)
159 var device, op string
161 if _, err := fmt.Sscanf(string(b.Text()), "%s %s %d", &device, &op, &val); err != nil {
164 var thisSample IoSample
166 if thisSample, ok = newSamples[device]; !ok {
167 thisSample = IoSample{sampleTime, -1, -1}
171 thisSample.rxBytes = val
173 thisSample.txBytes = val
175 newSamples[device] = thisSample
177 for dev, sample := range newSamples {
178 if sample.txBytes < 0 || sample.rxBytes < 0 {
182 if prev, ok := lastSample[dev]; ok {
183 delta = fmt.Sprintf(" -- interval %.4f seconds %d write %d read",
184 sample.sampleTime.Sub(prev.sampleTime).Seconds(),
185 sample.txBytes-prev.txBytes,
186 sample.rxBytes-prev.rxBytes)
188 statLog.Printf("blkio:%s %d write %d read%s\n", dev, sample.txBytes, sample.rxBytes, delta)
189 lastSample[dev] = sample
193 type MemSample struct {
195 memStat map[string]int64
198 func DoMemoryStats(cgroup Cgroup) {
199 c, err := OpenStatFile(cgroup, "memory", "memory.stat")
204 b := bufio.NewScanner(c)
205 thisSample := MemSample{time.Now(), make(map[string]int64)}
206 wantStats := [...]string{"cache", "swap", "pgmajfault", "rss"}
210 if _, err := fmt.Sscanf(string(b.Text()), "%s %d", &stat, &val); err != nil {
213 thisSample.memStat[stat] = val
215 var outstat bytes.Buffer
216 for _, key := range wantStats {
217 if val, ok := thisSample.memStat[key]; ok {
218 outstat.WriteString(fmt.Sprintf(" %d %s", val, key))
221 statLog.Printf("mem%s\n", outstat.String())
224 func DoNetworkStats(cgroup Cgroup, lastSample map[string]IoSample) {
225 sampleTime := time.Now()
226 stats, err := GetContainerNetStats(cgroup)
231 scanner := bufio.NewScanner(stats)
235 words := strings.Fields(scanner.Text())
236 if len(words) != 17 {
237 // Skip lines with wrong format
240 ifName = strings.TrimRight(words[0], ":")
241 if ifName == "lo" || ifName == "" {
242 // Skip loopback interface and lines with wrong format
245 if tx, err = strconv.ParseInt(words[9], 10, 64); err != nil {
248 if rx, err = strconv.ParseInt(words[1], 10, 64); err != nil {
251 nextSample := IoSample{}
252 nextSample.sampleTime = sampleTime
253 nextSample.txBytes = tx
254 nextSample.rxBytes = rx
256 if prev, ok := lastSample[ifName]; ok {
257 interval := nextSample.sampleTime.Sub(prev.sampleTime).Seconds()
258 delta = fmt.Sprintf(" -- interval %.4f seconds %d tx %d rx",
263 statLog.Printf("net:%s %d tx %d rx%s\n", ifName, tx, rx, delta)
264 lastSample[ifName] = nextSample
268 type CpuSample struct {
269 hasData bool // to distinguish the zero value from real data
276 // Return the number of CPUs available in the container. Return 0 if
277 // we can't figure out the real number of CPUs.
278 func GetCpuCount(cgroup Cgroup) int64 {
279 cpusetFile, err := OpenStatFile(cgroup, "cpuset", "cpuset.cpus")
283 defer cpusetFile.Close()
284 b, err := ReadAllOrWarn(cpusetFile)
285 sp := strings.Split(string(b), ",")
287 for _, v := range sp {
289 n, _ := fmt.Sscanf(v, "%d-%d", &min, &max)
291 cpus += (max - min) + 1
299 func DoCpuStats(cgroup Cgroup, lastSample *CpuSample) {
300 statFile, err := OpenStatFile(cgroup, "cpuacct", "cpuacct.stat")
304 defer statFile.Close()
305 b, err := ReadAllOrWarn(statFile)
310 nextSample := CpuSample{true, time.Now(), 0, 0, GetCpuCount(cgroup)}
311 var userTicks, sysTicks int64
312 fmt.Sscanf(string(b), "user %d\nsystem %d", &userTicks, &sysTicks)
313 user_hz := float64(C.sysconf(C._SC_CLK_TCK))
314 nextSample.user = float64(userTicks) / user_hz
315 nextSample.sys = float64(sysTicks) / user_hz
318 if lastSample.hasData {
319 delta = fmt.Sprintf(" -- interval %.4f seconds %.4f user %.4f sys",
320 nextSample.sampleTime.Sub(lastSample.sampleTime).Seconds(),
321 nextSample.user-lastSample.user,
322 nextSample.sys-lastSample.sys)
324 statLog.Printf("cpu %.4f user %.4f sys %d cpus%s\n",
325 nextSample.user, nextSample.sys, nextSample.cpus, delta)
326 *lastSample = nextSample
329 func PollCgroupStats(cgroup Cgroup, poll int64, stop_poll_chan <-chan bool) {
330 var lastNetSample = map[string]IoSample{}
331 var lastDiskSample = map[string]IoSample{}
332 var lastCpuSample = CpuSample{}
334 poll_chan := make(chan bool, 1)
336 // Send periodic poll events.
339 time.Sleep(time.Duration(poll) * time.Millisecond)
345 case <-stop_poll_chan:
348 // Emit stats, then select again.
350 DoMemoryStats(cgroup)
351 DoCpuStats(cgroup, &lastCpuSample)
352 DoBlkIoStats(cgroup, lastDiskSample)
353 DoNetworkStats(cgroup, lastNetSample)
357 func run(logger *log.Logger) error {
362 cgroup_cidfile string
367 flag.StringVar(&cgroup_root, "cgroup-root", "", "Root of cgroup tree")
368 flag.StringVar(&cgroup_parent, "cgroup-parent", "", "Name of container parent under cgroup")
369 flag.StringVar(&cgroup_cidfile, "cgroup-cid", "", "Path to container id file")
370 flag.Int64Var(&wait, "wait", 5, "Maximum time (in seconds) to wait for cid file to show up")
371 flag.Int64Var(&poll, "poll", 1000, "Polling frequency, in milliseconds")
375 if cgroup_root == "" {
376 statLog.Fatal("error: must provide -cgroup-root")
379 finish_chan := make(chan bool)
380 defer close(finish_chan)
384 if len(flag.Args()) > 0 {
386 cmd = exec.Command(flag.Args()[0], flag.Args()[1:]...)
388 childLog.Println("Running", flag.Args())
390 // Child process will use our stdin and stdout pipes
391 // (we close our copies below)
393 cmd.Stdout = os.Stdout
395 // Forward SIGINT and SIGTERM to inner process
396 sigChan := make(chan os.Signal, 1)
397 go func(sig <-chan os.Signal) {
399 if cmd.Process != nil {
400 cmd.Process.Signal(catch)
402 statLog.Println("caught signal:", catch)
404 signal.Notify(sigChan, syscall.SIGTERM)
405 signal.Notify(sigChan, syscall.SIGINT)
407 // Funnel stderr through our channel
408 stderr_pipe, err := cmd.StderrPipe()
410 statLog.Fatalln("error in StderrPipe:", err)
412 go CopyPipeToChildLog(stderr_pipe, finish_chan)
415 if err := cmd.Start(); err != nil {
416 statLog.Fatalln("error in cmd.Start:", err)
419 // Close stdin/stdout in this (parent) process
425 var container_id string
426 if cgroup_cidfile != "" {
427 // wait up to 'wait' seconds for the cid file to appear
430 for i = 0; i < time.Duration(wait)*time.Second; i += (100 * time.Millisecond) {
431 cid, err := ioutil.ReadFile(cgroup_cidfile)
432 if err == nil && len(cid) > 0 {
434 container_id = string(cid)
437 time.Sleep(100 * time.Millisecond)
440 statLog.Println("error reading cid file:", cgroup_cidfile)
444 stop_poll_chan := make(chan bool, 1)
445 cgroup := Cgroup{cgroup_root, cgroup_parent, container_id}
446 go PollCgroupStats(cgroup, poll, stop_poll_chan)
448 // When the child exits, tell the polling goroutine to stop.
449 defer func() { stop_poll_chan <- true }()
451 // Wait for CopyPipeToChan to consume child's stderr pipe
458 logger := log.New(os.Stderr, "crunchstat: ", 0)
459 if err := run(logger); err != nil {
460 if exiterr, ok := err.(*exec.ExitError); ok {
461 // The program has exited with an exit code != 0
463 // This works on both Unix and
464 // Windows. Although package syscall is
465 // generally platform dependent, WaitStatus is
466 // defined for both Unix and Windows and in
467 // both cases has an ExitStatus() method with
468 // the same signature.
469 if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
470 os.Exit(status.ExitStatus())
473 statLog.Fatalln("error in cmd.Wait:", err)