18 func CopyPipeToChan(in io.Reader, out chan string, done chan<- bool) {
19 s := bufio.NewScanner(in)
26 func CopyChanToPipe(in <-chan string, out io.Writer) {
32 func OpenAndReadAll(filename string, log_chan chan<- string) ([]byte, error) {
33 in, err := os.Open(filename)
36 log_chan <- fmt.Sprintf("open %s: %s", filename, err)
42 content, err := ioutil.ReadAll(in)
43 if err != nil && log_chan != nil {
44 log_chan <- fmt.Sprintf("read %s: %s", filename, err)
50 func FindStat(cgroup_root string, cgroup_parent string, container_id string, statgroup string, stat string) string {
52 path = fmt.Sprintf("%s/%s/%s/%s/%s.%s", cgroup_root, statgroup, cgroup_parent, container_id, statgroup, stat)
53 if _, err := os.Stat(path); err == nil {
56 path = fmt.Sprintf("%s/%s/%s/%s.%s", cgroup_root, cgroup_parent, container_id, statgroup, stat)
57 if _, err := os.Stat(path); err == nil {
60 path = fmt.Sprintf("%s/%s/%s.%s", cgroup_root, statgroup, statgroup, stat)
61 if _, err := os.Stat(path); err == nil {
64 path = fmt.Sprintf("%s/%s.%s", cgroup_root, statgroup, stat)
65 if _, err := os.Stat(path); err == nil {
71 func PollCgroupStats(cgroup_root string, cgroup_parent string, container_id string, stderr chan string, poll int64, stop_poll_chan <-chan bool) {
72 var last_user int64 = -1
73 var last_sys int64 = -1
74 var last_cpucount int64 = 0
83 disk := make(map[string]*Disk)
85 cpuacct_stat := FindStat(cgroup_root, cgroup_parent, container_id, "cpuacct", "stat")
86 blkio_io_service_bytes := FindStat(cgroup_root, cgroup_parent, container_id, "blkio", "io_service_bytes")
87 cpuset_cpus := FindStat(cgroup_root, cgroup_parent, container_id, "cpuset", "cpus")
88 memory_stat := FindStat(cgroup_root, cgroup_parent, container_id, "memory", "stat")
90 if cpuacct_stat != "" {
91 stderr <- fmt.Sprintf("crunchstat: reading stats from %s", cpuacct_stat)
93 if blkio_io_service_bytes != "" {
94 stderr <- fmt.Sprintf("crunchstat: reading stats from %s", blkio_io_service_bytes)
96 if cpuset_cpus != "" {
97 stderr <- fmt.Sprintf("crunchstat: reading stats from %s", cpuset_cpus)
99 if memory_stat != "" {
100 stderr <- fmt.Sprintf("crunchstat: reading stats from %s", memory_stat)
103 poll_chan := make(chan bool, 1)
105 // Send periodic poll events.
108 time.Sleep(time.Duration(poll) * time.Millisecond)
113 bedtime := time.Now()
115 case <-stop_poll_chan:
118 // Emit stats, then select again.
120 morning := time.Now()
121 elapsed := morning.Sub(bedtime).Nanoseconds() / int64(time.Millisecond)
123 if cpuset_cpus != "" {
124 b, err := OpenAndReadAll(cpuset_cpus, stderr)
126 // cgroup probably gone -- skip other stats too.
129 sp := strings.Split(string(b), ",")
130 for _, v := range sp {
132 n, _ := fmt.Sscanf(v, "%d-%d", &min, &max)
134 cpus += (max - min) + 1
140 if cpus != last_cpucount {
141 stderr <- fmt.Sprintf("crunchstat: cpuset.cpus %v", cpus)
148 if cpuacct_stat != "" {
149 b, err := OpenAndReadAll(cpuacct_stat, stderr)
151 // Next time around, last_user would
152 // be >1 interval old, so stats will
153 // be incorrect. Start over instead.
156 // cgroup probably gone -- skip other stats too.
161 fmt.Sscanf(string(b), "user %d\nsystem %d", &next_user, &next_sys)
163 if elapsed > 0 && last_user != -1 {
164 user_diff := next_user - last_user
165 sys_diff := next_sys - last_sys
166 // Assume we're reading stats based on 100
167 // jiffies per second. Because the elapsed
168 // time is in milliseconds, we need to boost
169 // that to 1000 jiffies per second, then boost
170 // it by another 100x to get a percentage, then
171 // finally divide by the actual elapsed time
172 // and the number of cpus to get average load
173 // over the polling period.
174 user_pct := (user_diff * 10 * 100) / (elapsed * cpus)
175 sys_pct := (sys_diff * 10 * 100) / (elapsed * cpus)
177 stderr <- fmt.Sprintf("crunchstat: cpuacct.stat user %v", user_pct)
178 stderr <- fmt.Sprintf("crunchstat: cpuacct.stat sys %v", sys_pct)
181 last_user = next_user
184 if blkio_io_service_bytes != "" {
185 c, err := os.Open(blkio_io_service_bytes)
187 stderr <- fmt.Sprintf("open %s: %s", blkio_io_service_bytes, err)
188 // cgroup probably gone -- skip other stats too.
192 b := bufio.NewScanner(c)
193 var device, op string
196 if _, err := fmt.Sscanf(string(b.Text()), "%s %s %d", &device, &op, &next); err != nil {
199 if disk[device] == nil {
200 disk[device] = new(Disk)
203 disk[device].last_read = disk[device].next_read
204 disk[device].next_read = next
205 if disk[device].last_read > 0 && (disk[device].next_read != disk[device].last_read) {
206 stderr <- fmt.Sprintf("crunchstat: blkio.io_service_bytes %s read %v", device, disk[device].next_read-disk[device].last_read)
210 disk[device].last_write = disk[device].next_write
211 disk[device].next_write = next
212 if disk[device].last_write > 0 && (disk[device].next_write != disk[device].last_write) {
213 stderr <- fmt.Sprintf("crunchstat: blkio.io_service_bytes %s write %v", device, disk[device].next_write-disk[device].last_write)
219 if memory_stat != "" {
220 c, err := os.Open(memory_stat)
222 stderr <- fmt.Sprintf("open %s: %s", memory_stat, err)
223 // cgroup probably gone -- skip other stats too.
226 b := bufio.NewScanner(c)
230 if _, err := fmt.Sscanf(string(b.Text()), "%s %d", &stat, &val); err == nil {
232 stderr <- fmt.Sprintf("crunchstat: memory.stat rss %v", val)
241 func run(logger *log.Logger) error {
246 cgroup_cidfile string
251 flag.StringVar(&cgroup_root, "cgroup-root", "", "Root of cgroup tree")
252 flag.StringVar(&cgroup_parent, "cgroup-parent", "", "Name of container parent under cgroup")
253 flag.StringVar(&cgroup_cidfile, "cgroup-cid", "", "Path to container id file")
254 flag.Int64Var(&wait, "wait", 5, "Maximum time (in seconds) to wait for cid file to show up")
255 flag.Int64Var(&poll, "poll", 1000, "Polling frequency, in milliseconds")
259 if cgroup_root == "" {
260 logger.Fatal("Must provide -cgroup-root")
263 stderr_chan := make(chan string, 1)
264 defer close(stderr_chan)
265 finish_chan := make(chan bool)
266 defer close(finish_chan)
268 go CopyChanToPipe(stderr_chan, os.Stderr)
272 if len(flag.Args()) > 0 {
274 cmd = exec.Command(flag.Args()[0], flag.Args()[1:]...)
276 logger.Print("Running ", flag.Args())
278 // Child process will use our stdin and stdout pipes
279 // (we close our copies below)
281 cmd.Stdout = os.Stdout
283 // Forward SIGINT and SIGTERM to inner process
284 term := make(chan os.Signal, 1)
285 go func(sig <-chan os.Signal) {
287 if cmd.Process != nil {
288 cmd.Process.Signal(catch)
290 logger.Print("caught signal: ", catch)
292 signal.Notify(term, syscall.SIGTERM)
293 signal.Notify(term, syscall.SIGINT)
295 // Funnel stderr through our channel
296 stderr_pipe, err := cmd.StderrPipe()
300 go CopyPipeToChan(stderr_pipe, stderr_chan, finish_chan)
303 if err := cmd.Start(); err != nil {
307 // Close stdin/stdout in this (parent) process
313 var container_id string
314 if cgroup_cidfile != "" {
315 // wait up to 'wait' seconds for the cid file to appear
318 for i = 0; i < time.Duration(wait)*time.Second; i += (100 * time.Millisecond) {
319 cid, err := OpenAndReadAll(cgroup_cidfile, nil)
320 if err == nil && len(cid) > 0 {
322 container_id = string(cid)
325 time.Sleep(100 * time.Millisecond)
328 logger.Printf("Could not read cid file %s", cgroup_cidfile)
332 stop_poll_chan := make(chan bool, 1)
333 go PollCgroupStats(cgroup_root, cgroup_parent, container_id, stderr_chan, poll, stop_poll_chan)
335 // When the child exits, tell the polling goroutine to stop.
336 defer func() { stop_poll_chan <- true }()
338 // Wait for CopyPipeToChan to consume child's stderr pipe
345 logger := log.New(os.Stderr, "crunchstat: ", 0)
346 if err := run(logger); err != nil {
347 if exiterr, ok := err.(*exec.ExitError); ok {
348 // The program has exited with an exit code != 0
350 // This works on both Unix and
351 // Windows. Although package syscall is
352 // generally platform dependent, WaitStatus is
353 // defined for both Unix and Windows and in
354 // both cases has an ExitStatus() method with
355 // the same signature.
356 if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
357 os.Exit(status.ExitStatus())
360 logger.Fatalf("cmd.Wait: %v", err)