18 func ReadLineByLine(inp io.ReadCloser, out chan string, finish chan bool) {
19 s := bufio.NewScanner(inp)
26 func OutputChannel(stdout chan string, stderr chan string) {
29 case s, ok := <-stdout:
31 fmt.Fprintln(os.Stdout, s)
35 case s, ok := <-stderr:
37 fmt.Fprintln(os.Stderr, s)
45 func FindStat(cgroup_root string, cgroup_parent string, container_id string, statgroup string, stat string) string {
47 path = fmt.Sprintf("%s/%s/%s/%s/%s.%s", cgroup_root, statgroup, cgroup_parent, container_id, statgroup, stat)
48 if _, err := os.Stat(path); err == nil {
51 path = fmt.Sprintf("%s/%s/%s/%s.%s", cgroup_root, cgroup_parent, container_id, statgroup, stat)
52 if _, err := os.Stat(path); err == nil {
55 path = fmt.Sprintf("%s/%s/%s.%s", cgroup_root, statgroup, statgroup, stat)
56 if _, err := os.Stat(path); err == nil {
59 path = fmt.Sprintf("%s/%s.%s", cgroup_root, statgroup, stat)
60 if _, err := os.Stat(path); err == nil {
66 func PollCgroupStats(cgroup_root string, cgroup_parent string, container_id string, stderr chan string, poll int64) {
67 //var last_usage int64 = 0
68 var last_user int64 = 0
69 var last_sys int64 = 0
70 var last_cpucount int64 = 0
79 disk := make(map[string]*Disk)
81 //cpuacct_usage := FindStat(cgroup_path, "cpuacct", "usage")
82 cpuacct_stat := FindStat(cgroup_root, cgroup_parent, container_id, "cpuacct", "stat")
83 blkio_io_service_bytes := FindStat(cgroup_root, cgroup_parent, container_id, "blkio", "io_service_bytes")
84 cpuset_cpus := FindStat(cgroup_root, cgroup_parent, container_id, "cpuset", "cpus")
85 memory_stat := FindStat(cgroup_root, cgroup_parent, container_id, "memory", "stat")
87 if cpuacct_stat != "" {
88 stderr <- fmt.Sprintf("crunchstat: reading stats from %s", cpuacct_stat)
90 if blkio_io_service_bytes != "" {
91 stderr <- fmt.Sprintf("crunchstat: reading stats from %s", blkio_io_service_bytes)
93 if cpuset_cpus != "" {
94 stderr <- fmt.Sprintf("crunchstat: reading stats from %s", cpuset_cpus)
96 if memory_stat != "" {
97 stderr <- fmt.Sprintf("crunchstat: reading stats from %s", memory_stat)
100 var elapsed int64 = poll
104 c, _ := os.Open(cpuacct_usage)
105 b, _ := ioutil.ReadAll(c)
107 fmt.Sscanf(string(b), "%d", &next)
109 stderr <- fmt.Sprintf("crunchstat: cpuacct.usage %v", (next-last_usage)/10000000)
111 //fmt.Printf("usage %d %d %d %d%%\n", last_usage, next, next-last_usage, (next-last_usage)/10000000)
116 if cpuset_cpus != "" {
117 c, _ := os.Open(cpuset_cpus)
118 b, _ := ioutil.ReadAll(c)
119 sp := strings.Split(string(b), ",")
120 for _, v := range sp {
122 n, _ := fmt.Sscanf(v, "%d-%d", &min, &max)
124 cpus += (max - min) + 1
130 if cpus != last_cpucount {
131 stderr <- fmt.Sprintf("crunchstat: cpuset.cpus %v", cpus)
140 if cpuacct_stat != "" {
141 c, _ := os.Open(cpuacct_stat)
142 b, _ := ioutil.ReadAll(c)
145 fmt.Sscanf(string(b), "user %d\nsystem %d", &next_user, &next_sys)
149 user_diff := next_user - last_user
150 sys_diff := next_sys - last_sys
151 // Assume we're reading stats based on 100
152 // jiffies per second. Because the ellaspsed
153 // time is in milliseconds, we need to boost
154 // that to 1000 jiffies per second, then boost
155 // it by another 100x to get a percentage, then
156 // finally divide by the actual elapsed time
157 // and the number of cpus to get average load
158 // over the polling period.
159 user_pct := (user_diff * 10 * 100) / (elapsed * cpus)
160 sys_pct := (sys_diff * 10 * 100) / (elapsed * cpus)
162 stderr <- fmt.Sprintf("crunchstat: cpuacct.stat user %v", user_pct)
163 stderr <- fmt.Sprintf("crunchstat: cpuacct.stat sys %v", sys_pct)
166 /*fmt.Printf("user %d %d %d%%\n", last_user, next_user, next_user-last_user)
167 fmt.Printf("sys %d %d %d%%\n", last_sys, next_sys, next_sys-last_sys)
168 fmt.Printf("sum %d%%\n", (next_user-last_user)+(next_sys-last_sys))*/
169 last_user = next_user
172 if blkio_io_service_bytes != "" {
173 c, _ := os.Open(blkio_io_service_bytes)
174 b := bufio.NewScanner(c)
175 var device, op string
178 if _, err := fmt.Sscanf(string(b.Text()), "%s %s %d", &device, &op, &next); err == nil {
179 if disk[device] == nil {
180 disk[device] = new(Disk)
183 disk[device].last_read = disk[device].next_read
184 disk[device].next_read = next
185 if disk[device].last_read > 0 && (disk[device].next_read != disk[device].last_read) {
186 stderr <- fmt.Sprintf("crunchstat: blkio.io_service_bytes %s read %v", device, disk[device].next_read-disk[device].last_read)
190 disk[device].last_write = disk[device].next_write
191 disk[device].next_write = next
192 if disk[device].last_write > 0 && (disk[device].next_write != disk[device].last_write) {
193 stderr <- fmt.Sprintf("crunchstat: blkio.io_service_bytes %s write %v", device, disk[device].next_write-disk[device].last_write)
201 if memory_stat != "" {
202 c, _ := os.Open(memory_stat)
203 b := bufio.NewScanner(c)
207 if _, err := fmt.Sscanf(string(b.Text()), "%s %d", &stat, &val); err == nil {
209 stderr <- fmt.Sprintf("crunchstat: memory.stat rss %v", val)
216 bedtime := time.Now()
217 time.Sleep(time.Duration(poll) * time.Millisecond)
218 morning := time.Now()
219 elapsed = morning.Sub(bedtime).Nanoseconds() / int64(time.Millisecond)
228 cgroup_cidfile string
233 flag.StringVar(&cgroup_root, "cgroup-root", "", "Root of cgroup tree")
234 flag.StringVar(&cgroup_parent, "cgroup-parent", "", "Name of container parent under cgroup")
235 flag.StringVar(&cgroup_cidfile, "cgroup-cid", "", "Path to container id file")
236 flag.Int64Var(&wait, "wait", 5, "Maximum time (in seconds) to wait for cid file to show up")
237 flag.Int64Var(&poll, "poll", 1000, "Polling frequency, in milliseconds")
241 logger := log.New(os.Stderr, "crunchstat: ", 0)
243 if cgroup_root == "" {
244 logger.Fatal("Must provide either -cgroup-root")
247 // Make output channel
248 stdout_chan := make(chan string)
249 stderr_chan := make(chan string)
250 finish_chan := make(chan bool)
251 defer close(stdout_chan)
252 defer close(stderr_chan)
253 defer close(finish_chan)
255 go OutputChannel(stdout_chan, stderr_chan)
259 if len(flag.Args()) > 0 {
261 cmd = exec.Command(flag.Args()[0], flag.Args()[1:]...)
263 logger.Print("Running ", flag.Args())
265 // Forward SIGINT and SIGTERM to inner process
266 term := make(chan os.Signal, 1)
267 go func(sig <-chan os.Signal) {
269 if cmd.Process != nil {
270 cmd.Process.Signal(catch)
272 logger.Print("caught signal:", catch)
274 signal.Notify(term, syscall.SIGTERM)
275 signal.Notify(term, syscall.SIGINT)
277 // Funnel stdout and stderr from subprocess to output channels
278 stdout_pipe, err := cmd.StdoutPipe()
282 go ReadLineByLine(stdout_pipe, stdout_chan, finish_chan)
284 stderr_pipe, err := cmd.StderrPipe()
288 go ReadLineByLine(stderr_pipe, stderr_chan, finish_chan)
291 if err := cmd.Start(); err != nil {
297 var container_id string
298 if cgroup_cidfile != "" {
299 // wait up to 'wait' seconds for the cid file to appear
301 for i = 0; i < time.Duration(wait)*time.Second; i += (100 * time.Millisecond) {
302 f, err := os.Open(cgroup_cidfile)
304 cid, err2 := ioutil.ReadAll(f)
305 if err2 == nil && len(cid) > 0 {
306 container_id = string(cid)
311 time.Sleep(100 * time.Millisecond)
313 if cgroup_root == "" {
314 logger.Printf("Could not read cid file %s", cgroup_cidfile)
318 go PollCgroupStats(cgroup_root, cgroup_parent, container_id, stderr_chan, poll)
320 // Wait for each of stdout and stderr to drain
324 if err := cmd.Wait(); err != nil {
325 if exiterr, ok := err.(*exec.ExitError); ok {
326 // The program has exited with an exit code != 0
328 // This works on both Unix and Windows. Although package
329 // syscall is generally platform dependent, WaitStatus is
330 // defined for both Unix and Windows and in both cases has
331 // an ExitStatus() method with the same signature.
332 if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
333 os.Exit(status.ExitStatus())
336 logger.Fatalf("cmd.Wait: %v", err)