856eaafd88ca02c7e6e9910e72c88993ad92f441
[arvados.git] / services / crunchstat / crunchstat.go
1 package main
2
3 import (
4         "bufio"
5         "flag"
6         "fmt"
7         "io"
8         "io/ioutil"
9         "log"
10         "os"
11         "os/exec"
12         "os/signal"
13         "strings"
14         "syscall"
15         "time"
16 )
17
18 func CopyPipeToChan(in io.Reader, out chan string, done chan<- bool) {
19         s := bufio.NewScanner(in)
20         for s.Scan() {
21                 out <- s.Text()
22         }
23         done <- true
24 }
25
26 func CopyChanToPipe(in <-chan string, out io.Writer) {
27         for s := range in {
28                 fmt.Fprintln(out, s)
29         }
30 }
31
32 func OpenAndReadAll(filename string, log_chan chan<- string) ([]byte, error) {
33         in, err := os.Open(filename)
34         if err != nil {
35                 if log_chan != nil {
36                         log_chan <- fmt.Sprintf("open %s: %s", filename, err)
37                 }
38                 return nil, err
39         }
40         defer in.Close()
41         {
42                 content, err := ioutil.ReadAll(in)
43                 if err != nil && log_chan != nil {
44                         log_chan <- fmt.Sprintf("read %s: %s", filename, err)
45                 }
46                 return content, err
47         }
48 }
49
50 func FindStat(cgroup_root string, cgroup_parent string, container_id string, statgroup string, stat string) string {
51         var path 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 {
54                 return path
55         }
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 {
58                 return path
59         }
60         path = fmt.Sprintf("%s/%s/%s.%s", cgroup_root, statgroup, statgroup, stat)
61         if _, err := os.Stat(path); err == nil {
62                 return path
63         }
64         path = fmt.Sprintf("%s/%s.%s", cgroup_root, statgroup, stat)
65         if _, err := os.Stat(path); err == nil {
66                 return path
67         }
68         return ""
69 }
70
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
75
76         type Disk struct {
77                 last_read  int64
78                 next_read  int64
79                 last_write int64
80                 next_write int64
81         }
82
83         disk := make(map[string]*Disk)
84
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")
89
90         if cpuacct_stat != "" {
91                 stderr <- fmt.Sprintf("crunchstat: reading stats from %s", cpuacct_stat)
92         }
93         if blkio_io_service_bytes != "" {
94                 stderr <- fmt.Sprintf("crunchstat: reading stats from %s", blkio_io_service_bytes)
95         }
96         if cpuset_cpus != "" {
97                 stderr <- fmt.Sprintf("crunchstat: reading stats from %s", cpuset_cpus)
98         }
99         if memory_stat != "" {
100                 stderr <- fmt.Sprintf("crunchstat: reading stats from %s", memory_stat)
101         }
102
103         poll_chan := make(chan bool, 1)
104         go func() {
105                 // Send periodic poll events.
106                 poll_chan <- true
107                 for {
108                         time.Sleep(time.Duration(poll) * time.Millisecond)
109                         poll_chan <- true
110                 }
111         }()
112         for {
113                 bedtime := time.Now()
114                 select {
115                 case <-stop_poll_chan:
116                         return
117                 case <-poll_chan:
118                         // Emit stats, then select again.
119                 }
120                 morning := time.Now()
121                 elapsed := morning.Sub(bedtime).Nanoseconds() / int64(time.Millisecond)
122                 var cpus int64 = 0
123                 if cpuset_cpus != "" {
124                         b, err := OpenAndReadAll(cpuset_cpus, stderr)
125                         if err != nil {
126                                 // cgroup probably gone -- skip other stats too.
127                                 continue
128                         }
129                         sp := strings.Split(string(b), ",")
130                         for _, v := range sp {
131                                 var min, max int64
132                                 n, _ := fmt.Sscanf(v, "%d-%d", &min, &max)
133                                 if n == 2 {
134                                         cpus += (max - min) + 1
135                                 } else {
136                                         cpus += 1
137                                 }
138                         }
139
140                         if cpus != last_cpucount {
141                                 stderr <- fmt.Sprintf("crunchstat: cpuset.cpus %v", cpus)
142                         }
143                         last_cpucount = cpus
144                 }
145                 if cpus == 0 {
146                         cpus = 1
147                 }
148                 if cpuacct_stat != "" {
149                         b, err := OpenAndReadAll(cpuacct_stat, stderr)
150                         if err != nil {
151                                 // Next time around, last_user would
152                                 // be >1 interval old, so stats will
153                                 // be incorrect. Start over instead.
154                                 last_user = -1
155
156                                 // cgroup probably gone -- skip other stats too.
157                                 continue
158                         }
159                         var next_user int64
160                         var next_sys int64
161                         fmt.Sscanf(string(b), "user %d\nsystem %d", &next_user, &next_sys)
162
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)
176
177                                 stderr <- fmt.Sprintf("crunchstat: cpuacct.stat user %v", user_pct)
178                                 stderr <- fmt.Sprintf("crunchstat: cpuacct.stat sys %v", sys_pct)
179                         }
180
181                         last_user = next_user
182                         last_sys = next_sys
183                 }
184                 if blkio_io_service_bytes != "" {
185                         c, err := os.Open(blkio_io_service_bytes)
186                         if err != nil {
187                                 stderr <- fmt.Sprintf("open %s: %s", blkio_io_service_bytes, err)
188                                 // cgroup probably gone -- skip other stats too.
189                                 continue
190                         }
191                         defer c.Close()
192                         b := bufio.NewScanner(c)
193                         var device, op string
194                         var next int64
195                         for b.Scan() {
196                                 if _, err := fmt.Sscanf(string(b.Text()), "%s %s %d", &device, &op, &next); err != nil {
197                                         continue
198                                 }
199                                 if disk[device] == nil {
200                                         disk[device] = new(Disk)
201                                 }
202                                 if op == "Read" {
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)
207                                         }
208                                 }
209                                 if op == "Write" {
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)
214                                         }
215                                 }
216                         }
217                 }
218
219                 if memory_stat != "" {
220                         c, err := os.Open(memory_stat)
221                         if err != nil {
222                                 stderr <- fmt.Sprintf("open %s: %s", memory_stat, err)
223                                 // cgroup probably gone -- skip other stats too.
224                                 continue
225                         }
226                         b := bufio.NewScanner(c)
227                         var stat string
228                         var val int64
229                         for b.Scan() {
230                                 if _, err := fmt.Sscanf(string(b.Text()), "%s %d", &stat, &val); err == nil {
231                                         if stat == "rss" {
232                                                 stderr <- fmt.Sprintf("crunchstat: memory.stat rss %v", val)
233                                         }
234                                 }
235                         }
236                         c.Close()
237                 }
238         }
239 }
240
241 func run(logger *log.Logger) error {
242
243         var (
244                 cgroup_root    string
245                 cgroup_parent  string
246                 cgroup_cidfile string
247                 wait           int64
248                 poll           int64
249         )
250
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")
256
257         flag.Parse()
258
259         if cgroup_root == "" {
260                 logger.Fatal("Must provide -cgroup-root")
261         }
262
263         stderr_chan := make(chan string, 1)
264         defer close(stderr_chan)
265         finish_chan := make(chan bool)
266         defer close(finish_chan)
267
268         go CopyChanToPipe(stderr_chan, os.Stderr)
269
270         var cmd *exec.Cmd
271
272         if len(flag.Args()) > 0 {
273                 // Set up subprocess
274                 cmd = exec.Command(flag.Args()[0], flag.Args()[1:]...)
275
276                 logger.Print("Running ", flag.Args())
277
278                 // Child process will use our stdin and stdout pipes
279                 // (we close our copies below)
280                 cmd.Stdin = os.Stdin
281                 cmd.Stdout = os.Stdout
282
283                 // Forward SIGINT and SIGTERM to inner process
284                 term := make(chan os.Signal, 1)
285                 go func(sig <-chan os.Signal) {
286                         catch := <-sig
287                         if cmd.Process != nil {
288                                 cmd.Process.Signal(catch)
289                         }
290                         logger.Print("caught signal: ", catch)
291                 }(term)
292                 signal.Notify(term, syscall.SIGTERM)
293                 signal.Notify(term, syscall.SIGINT)
294
295                 // Funnel stderr through our channel
296                 stderr_pipe, err := cmd.StderrPipe()
297                 if err != nil {
298                         logger.Fatal(err)
299                 }
300                 go CopyPipeToChan(stderr_pipe, stderr_chan, finish_chan)
301
302                 // Run subprocess
303                 if err := cmd.Start(); err != nil {
304                         logger.Fatal(err)
305                 }
306
307                 // Close stdin/stdout in this (parent) process
308                 os.Stdin.Close()
309                 os.Stdout.Close()
310         }
311
312         // Read the cid file
313         var container_id string
314         if cgroup_cidfile != "" {
315                 // wait up to 'wait' seconds for the cid file to appear
316                 ok := false
317                 var i time.Duration
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 {
321                                 ok = true
322                                 container_id = string(cid)
323                                 break
324                         }
325                         time.Sleep(100 * time.Millisecond)
326                 }
327                 if !ok {
328                         logger.Printf("Could not read cid file %s", cgroup_cidfile)
329                 }
330         }
331
332         stop_poll_chan := make(chan bool, 1)
333         go PollCgroupStats(cgroup_root, cgroup_parent, container_id, stderr_chan, poll, stop_poll_chan)
334
335         // When the child exits, tell the polling goroutine to stop.
336         defer func() { stop_poll_chan <- true }()
337
338         // Wait for CopyPipeToChan to consume child's stderr pipe
339         <-finish_chan
340
341         return cmd.Wait()
342 }
343
344 func main() {
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
349
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())
358                         }
359                 } else {
360                         logger.Fatalf("cmd.Wait: %v", err)
361                 }
362         }
363 }