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 PollCgroupStats(cgroup_path string, stderr chan string, poll int64) {
46 //var last_usage int64 = 0
47 var last_user int64 = 0
48 var last_sys int64 = 0
49 var last_cpucount int64 = 0
58 disk := make(map[string]*Disk)
60 //cpuacct_usage := fmt.Sprintf("%s/cpuacct.usage", cgroup_path)
61 cpuacct_stat := fmt.Sprintf("%s/cpuacct.stat", cgroup_path)
62 blkio_io_service_bytes := fmt.Sprintf("%s/blkio.io_service_bytes", cgroup_path)
63 cpuset_cpus := fmt.Sprintf("%s/cpuset.cpus", cgroup_path)
64 memory_stat := fmt.Sprintf("%s/memory.stat", cgroup_path)
66 var elapsed int64 = poll
70 c, _ := os.Open(cpuacct_usage)
71 b, _ := ioutil.ReadAll(c)
73 fmt.Sscanf(string(b), "%d", &next)
75 stderr <- fmt.Sprintf("crunchstat: cpuacct.usage %v", (next-last_usage)/10000000)
77 //fmt.Printf("usage %d %d %d %d%%\n", last_usage, next, next-last_usage, (next-last_usage)/10000000)
83 c, _ := os.Open(cpuset_cpus)
84 b, _ := ioutil.ReadAll(c)
85 sp := strings.Split(string(b), ",")
86 for _, v := range sp {
88 n, _ := fmt.Sscanf(v, "%d-%d", &min, &max)
90 cpus += (max - min) + 1
96 if cpus != last_cpucount {
97 stderr <- fmt.Sprintf("crunchstat: cpuset.cpus %v", cpus)
107 c, _ := os.Open(cpuacct_stat)
108 b, _ := ioutil.ReadAll(c)
111 fmt.Sscanf(string(b), "user %d\nsystem %d", &next_user, &next_sys)
115 user_diff := next_user - last_user
116 sys_diff := next_sys - last_sys
117 // Assume we're reading stats based on 100
118 // jiffies per second. Because the ellaspsed
119 // time is in milliseconds, we need to boost
120 // that to 1000 jiffies per second, then boost
121 // it by another 100x to get a percentage, then
122 // finally divide by the actual elapsed time
123 // and the number of cpus to get average load
124 // over the polling period.
125 user_pct := (user_diff * 10 * 100) / (elapsed * cpus)
126 sys_pct := (sys_diff * 10 * 100) / (elapsed * cpus)
128 stderr <- fmt.Sprintf("crunchstat: cpuacct.stat user %v", user_pct)
129 stderr <- fmt.Sprintf("crunchstat: cpuacct.stat sys %v", sys_pct)
132 /*fmt.Printf("user %d %d %d%%\n", last_user, next_user, next_user-last_user)
133 fmt.Printf("sys %d %d %d%%\n", last_sys, next_sys, next_sys-last_sys)
134 fmt.Printf("sum %d%%\n", (next_user-last_user)+(next_sys-last_sys))*/
135 last_user = next_user
139 c, _ := os.Open(blkio_io_service_bytes)
140 b := bufio.NewScanner(c)
141 var device, op string
144 if _, err := fmt.Sscanf(string(b.Text()), "%s %s %d", &device, &op, &next); err == nil {
145 if disk[device] == nil {
146 disk[device] = new(Disk)
149 disk[device].last_read = disk[device].next_read
150 disk[device].next_read = next
151 if disk[device].last_read > 0 {
152 stderr <- fmt.Sprintf("crunchstat: blkio.io_service_bytes %s read %v", device, disk[device].next_read-disk[device].last_read)
156 disk[device].last_write = disk[device].next_write
157 disk[device].next_write = next
158 if disk[device].last_write > 0 {
159 stderr <- fmt.Sprintf("crunchstat: blkio.io_service_bytes %s write %v", device, disk[device].next_write-disk[device].last_write)
168 c, _ := os.Open(memory_stat)
169 b := bufio.NewScanner(c)
173 if _, err := fmt.Sscanf(string(b.Text()), "%s %d", &stat, &val); err == nil {
175 stderr <- fmt.Sprintf("crunchstat: memory.stat rss %v", val)
182 bedtime := time.Now()
183 time.Sleep(time.Duration(poll) * time.Millisecond)
184 morning := time.Now()
185 elapsed = morning.Sub(bedtime).Nanoseconds() / int64(time.Millisecond)
194 cgroup_cidfile string
199 flag.StringVar(&cgroup_path, "cgroup-path", "", "Direct path to cgroup")
200 flag.StringVar(&cgroup_parent, "cgroup-parent", "", "Path to parent cgroup")
201 flag.StringVar(&cgroup_cidfile, "cgroup-cid", "", "Path to container id file")
202 flag.Int64Var(&wait, "wait", 5, "Maximum time (in seconds) to wait for cid file to show up")
203 flag.Int64Var(&poll, "poll", 1000, "Polling frequency, in milliseconds")
207 logger := log.New(os.Stderr, "crunchstat: ", 0)
209 if cgroup_path == "" && cgroup_cidfile == "" {
210 logger.Fatal("Must provide either -cgroup-path or -cgroup-cid")
213 // Make output channel
214 stdout_chan := make(chan string)
215 stderr_chan := make(chan string)
216 finish_chan := make(chan bool)
217 defer close(stdout_chan)
218 defer close(stderr_chan)
219 defer close(finish_chan)
221 go OutputChannel(stdout_chan, stderr_chan)
225 if len(flag.Args()) > 0 {
227 cmd = exec.Command(flag.Args()[0], flag.Args()[1:]...)
229 logger.Print("Running ", flag.Args())
231 // Forward SIGINT and SIGTERM to inner process
232 term := make(chan os.Signal, 1)
233 go func(sig <-chan os.Signal) {
235 if cmd.Process != nil {
236 cmd.Process.Signal(catch)
238 logger.Print("caught signal:", catch)
240 signal.Notify(term, syscall.SIGTERM)
241 signal.Notify(term, syscall.SIGINT)
243 // Funnel stdout and stderr from subprocess to output channels
244 stdout_pipe, err := cmd.StdoutPipe()
248 go ReadLineByLine(stdout_pipe, stdout_chan, finish_chan)
250 stderr_pipe, err := cmd.StderrPipe()
254 go ReadLineByLine(stderr_pipe, stderr_chan, finish_chan)
257 if err := cmd.Start(); err != nil {
263 if cgroup_cidfile != "" {
264 // wait up to 'wait' seconds for the cid file to appear
266 for i = 0; i < time.Duration(wait)*time.Second; i += (100 * time.Millisecond) {
267 f, err := os.Open(cgroup_cidfile)
269 cid, err2 := ioutil.ReadAll(f)
270 if err2 == nil && len(cid) > 0 {
271 cgroup_path = string(cid)
276 time.Sleep(100 * time.Millisecond)
278 if cgroup_path == "" {
279 logger.Printf("Could not read cid file %s", cgroup_cidfile)
283 // add the parent prefix
284 if cgroup_parent != "" {
285 cgroup_path = fmt.Sprintf("%s/%s", cgroup_parent, cgroup_path)
288 logger.Print("Using cgroup ", cgroup_path)
290 go PollCgroupStats(cgroup_path, stderr_chan, poll)
292 // Wait for each of stdout and stderr to drain
296 if err := cmd.Wait(); err != nil {
297 if exiterr, ok := err.(*exec.ExitError); ok {
298 // The program has exited with an exit code != 0
300 // This works on both Unix and Windows. Although package
301 // syscall is generally platform dependent, WaitStatus is
302 // defined for both Unix and Windows and in both cases has
303 // an ExitStatus() method with the same signature.
304 if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
305 os.Exit(status.ExitStatus())
308 logger.Fatalf("cmd.Wait: %v", err)