Merge branch '5523-stats-error' closes #5523
[arvados.git] / services / crunchstat / crunchstat.go
1 package main
2
3 import (
4         "bufio"
5         "bytes"
6         "errors"
7         "flag"
8         "fmt"
9         "io"
10         "io/ioutil"
11         "log"
12         "os"
13         "os/exec"
14         "os/signal"
15         "strconv"
16         "strings"
17         "syscall"
18         "time"
19 )
20
21 /*
22 #include <unistd.h>
23 #include <sys/types.h>
24 #include <pwd.h>
25 #include <stdlib.h>
26 */
27 import "C"
28
29 // The above block of magic allows us to look up user_hz via _SC_CLK_TCK.
30
31 type Cgroup struct {
32         root   string
33         parent string
34         cid    string
35 }
36
37 var childLog = log.New(os.Stderr, "", 0)
38 var statLog = log.New(os.Stderr, "crunchstat: ", 0)
39
40 const (
41         MaxLogLine = 1 << 14 // Child stderr lines >16KiB will be split
42 )
43
44 func CopyPipeToChildLog(in io.ReadCloser, done chan<- bool) {
45         reader := bufio.NewReaderSize(in, MaxLogLine)
46         var prefix string
47         for {
48                 line, isPrefix, err := reader.ReadLine()
49                 if err == io.EOF {
50                         break
51                 } else if err != nil {
52                         statLog.Fatal("error reading child stderr:", err)
53                 }
54                 var suffix string
55                 if isPrefix {
56                         suffix = "[...]"
57                 }
58                 childLog.Print(prefix, string(line), suffix)
59                 // Set up prefix for following line
60                 if isPrefix {
61                         prefix = "[...]"
62                 } else {
63                         prefix = ""
64                 }
65         }
66         done <- true
67         in.Close()
68 }
69
70 func ReadAllOrWarn(in *os.File) ([]byte, error) {
71         content, err := ioutil.ReadAll(in)
72         if err != nil {
73                 statLog.Printf("error reading %s: %s\n", in.Name(), err)
74         }
75         return content, err
76 }
77
78 var reportedStatFile = map[string]string{}
79
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,
82 // return nil.
83 //
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) {
89         var paths = []string{
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),
94         }
95         var path string
96         var file *os.File
97         var err error
98         for _, path = range paths {
99                 file, err = os.Open(path)
100                 if err == nil {
101                         break
102                 } else {
103                         path = ""
104                 }
105         }
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                 if path == "" {
114                         statLog.Printf("notice: stats not available: stat %s, statgroup %s, cid %s, parent %s, root %s\n", stat, statgroup, cgroup.cid, cgroup.parent, cgroup.root)
115                 } else if ok {
116                         statLog.Printf("notice: stats moved from %s to %s\n", reportedStatFile[stat], path)
117                 } else {
118                         statLog.Printf("notice: reading stats from %s\n", path)
119                 }
120                 reportedStatFile[stat] = path
121         }
122         return file, err
123 }
124
125 func GetContainerNetStats(cgroup Cgroup) (io.Reader, error) {
126         procsFile, err := OpenStatFile(cgroup, "cpuacct", "cgroup.procs")
127         if err != nil {
128                 return nil, err
129         }
130         defer procsFile.Close()
131         reader := bufio.NewScanner(procsFile)
132         for reader.Scan() {
133                 taskPid := reader.Text()
134                 statsFilename := fmt.Sprintf("/proc/%s/net/dev", taskPid)
135                 stats, err := ioutil.ReadFile(statsFilename)
136                 if err != nil {
137                         statLog.Printf("read %s: %s\n", statsFilename, err)
138                         continue
139                 }
140                 return strings.NewReader(string(stats)), nil
141         }
142         return nil, errors.New("Could not read stats for any proc in container")
143 }
144
145 type IoSample struct {
146         sampleTime time.Time
147         txBytes    int64
148         rxBytes    int64
149 }
150
151 func DoBlkIoStats(cgroup Cgroup, lastSample map[string]IoSample) {
152         c, err := OpenStatFile(cgroup, "blkio", "blkio.io_service_bytes")
153         if err != nil {
154                 return
155         }
156         defer c.Close()
157         b := bufio.NewScanner(c)
158         var sampleTime = time.Now()
159         newSamples := make(map[string]IoSample)
160         for b.Scan() {
161                 var device, op string
162                 var val int64
163                 if _, err := fmt.Sscanf(string(b.Text()), "%s %s %d", &device, &op, &val); err != nil {
164                         continue
165                 }
166                 var thisSample IoSample
167                 var ok bool
168                 if thisSample, ok = newSamples[device]; !ok {
169                         thisSample = IoSample{sampleTime, -1, -1}
170                 }
171                 switch op {
172                 case "Read":
173                         thisSample.rxBytes = val
174                 case "Write":
175                         thisSample.txBytes = val
176                 }
177                 newSamples[device] = thisSample
178         }
179         for dev, sample := range newSamples {
180                 if sample.txBytes < 0 || sample.rxBytes < 0 {
181                         continue
182                 }
183                 delta := ""
184                 if prev, ok := lastSample[dev]; ok {
185                         delta = fmt.Sprintf(" -- interval %.4f seconds %d write %d read",
186                                 sample.sampleTime.Sub(prev.sampleTime).Seconds(),
187                                 sample.txBytes-prev.txBytes,
188                                 sample.rxBytes-prev.rxBytes)
189                 }
190                 statLog.Printf("blkio:%s %d write %d read%s\n", dev, sample.txBytes, sample.rxBytes, delta)
191                 lastSample[dev] = sample
192         }
193 }
194
195 type MemSample struct {
196         sampleTime time.Time
197         memStat    map[string]int64
198 }
199
200 func DoMemoryStats(cgroup Cgroup) {
201         c, err := OpenStatFile(cgroup, "memory", "memory.stat")
202         if err != nil {
203                 return
204         }
205         defer c.Close()
206         b := bufio.NewScanner(c)
207         thisSample := MemSample{time.Now(), make(map[string]int64)}
208         wantStats := [...]string{"cache", "swap", "pgmajfault", "rss"}
209         for b.Scan() {
210                 var stat string
211                 var val int64
212                 if _, err := fmt.Sscanf(string(b.Text()), "%s %d", &stat, &val); err != nil {
213                         continue
214                 }
215                 thisSample.memStat[stat] = val
216         }
217         var outstat bytes.Buffer
218         for _, key := range wantStats {
219                 if val, ok := thisSample.memStat[key]; ok {
220                         outstat.WriteString(fmt.Sprintf(" %d %s", val, key))
221                 }
222         }
223         statLog.Printf("mem%s\n", outstat.String())
224 }
225
226 func DoNetworkStats(cgroup Cgroup, lastSample map[string]IoSample) {
227         sampleTime := time.Now()
228         stats, err := GetContainerNetStats(cgroup)
229         if err != nil {
230                 return
231         }
232
233         scanner := bufio.NewScanner(stats)
234         for scanner.Scan() {
235                 var ifName string
236                 var rx, tx int64
237                 words := strings.Fields(scanner.Text())
238                 if len(words) != 17 {
239                         // Skip lines with wrong format
240                         continue
241                 }
242                 ifName = strings.TrimRight(words[0], ":")
243                 if ifName == "lo" || ifName == "" {
244                         // Skip loopback interface and lines with wrong format
245                         continue
246                 }
247                 if tx, err = strconv.ParseInt(words[9], 10, 64); err != nil {
248                         continue
249                 }
250                 if rx, err = strconv.ParseInt(words[1], 10, 64); err != nil {
251                         continue
252                 }
253                 nextSample := IoSample{}
254                 nextSample.sampleTime = sampleTime
255                 nextSample.txBytes = tx
256                 nextSample.rxBytes = rx
257                 var delta string
258                 if prev, ok := lastSample[ifName]; ok {
259                         interval := nextSample.sampleTime.Sub(prev.sampleTime).Seconds()
260                         delta = fmt.Sprintf(" -- interval %.4f seconds %d tx %d rx",
261                                 interval,
262                                 tx-prev.txBytes,
263                                 rx-prev.rxBytes)
264                 }
265                 statLog.Printf("net:%s %d tx %d rx%s\n", ifName, tx, rx, delta)
266                 lastSample[ifName] = nextSample
267         }
268 }
269
270 type CpuSample struct {
271         hasData    bool // to distinguish the zero value from real data
272         sampleTime time.Time
273         user       float64
274         sys        float64
275         cpus       int64
276 }
277
278 // Return the number of CPUs available in the container. Return 0 if
279 // we can't figure out the real number of CPUs.
280 func GetCpuCount(cgroup Cgroup) int64 {
281         cpusetFile, err := OpenStatFile(cgroup, "cpuset", "cpuset.cpus")
282         if err != nil {
283                 return 0
284         }
285         defer cpusetFile.Close()
286         b, err := ReadAllOrWarn(cpusetFile)
287         sp := strings.Split(string(b), ",")
288         cpus := int64(0)
289         for _, v := range sp {
290                 var min, max int64
291                 n, _ := fmt.Sscanf(v, "%d-%d", &min, &max)
292                 if n == 2 {
293                         cpus += (max - min) + 1
294                 } else {
295                         cpus += 1
296                 }
297         }
298         return cpus
299 }
300
301 func DoCpuStats(cgroup Cgroup, lastSample *CpuSample) {
302         statFile, err := OpenStatFile(cgroup, "cpuacct", "cpuacct.stat")
303         if err != nil {
304                 return
305         }
306         defer statFile.Close()
307         b, err := ReadAllOrWarn(statFile)
308         if err != nil {
309                 return
310         }
311
312         nextSample := CpuSample{true, time.Now(), 0, 0, GetCpuCount(cgroup)}
313         var userTicks, sysTicks int64
314         fmt.Sscanf(string(b), "user %d\nsystem %d", &userTicks, &sysTicks)
315         user_hz := float64(C.sysconf(C._SC_CLK_TCK))
316         nextSample.user = float64(userTicks) / user_hz
317         nextSample.sys = float64(sysTicks) / user_hz
318
319         delta := ""
320         if lastSample.hasData {
321                 delta = fmt.Sprintf(" -- interval %.4f seconds %.4f user %.4f sys",
322                         nextSample.sampleTime.Sub(lastSample.sampleTime).Seconds(),
323                         nextSample.user-lastSample.user,
324                         nextSample.sys-lastSample.sys)
325         }
326         statLog.Printf("cpu %.4f user %.4f sys %d cpus%s\n",
327                 nextSample.user, nextSample.sys, nextSample.cpus, delta)
328         *lastSample = nextSample
329 }
330
331 func PollCgroupStats(cgroup Cgroup, poll int64, stop_poll_chan <-chan bool) {
332         var lastNetSample = map[string]IoSample{}
333         var lastDiskSample = map[string]IoSample{}
334         var lastCpuSample = CpuSample{}
335
336         poll_chan := make(chan bool, 1)
337         go func() {
338                 // Send periodic poll events.
339                 poll_chan <- true
340                 for {
341                         time.Sleep(time.Duration(poll) * time.Millisecond)
342                         poll_chan <- true
343                 }
344         }()
345         for {
346                 select {
347                 case <-stop_poll_chan:
348                         return
349                 case <-poll_chan:
350                         // Emit stats, then select again.
351                 }
352                 DoMemoryStats(cgroup)
353                 DoCpuStats(cgroup, &lastCpuSample)
354                 DoBlkIoStats(cgroup, lastDiskSample)
355                 DoNetworkStats(cgroup, lastNetSample)
356         }
357 }
358
359 func run(logger *log.Logger) error {
360
361         var (
362                 cgroup_root    string
363                 cgroup_parent  string
364                 cgroup_cidfile string
365                 wait           int64
366                 poll           int64
367         )
368
369         flag.StringVar(&cgroup_root, "cgroup-root", "", "Root of cgroup tree")
370         flag.StringVar(&cgroup_parent, "cgroup-parent", "", "Name of container parent under cgroup")
371         flag.StringVar(&cgroup_cidfile, "cgroup-cid", "", "Path to container id file")
372         flag.Int64Var(&wait, "wait", 5, "Maximum time (in seconds) to wait for cid file to show up")
373         flag.Int64Var(&poll, "poll", 1000, "Polling frequency, in milliseconds")
374
375         flag.Parse()
376
377         if cgroup_root == "" {
378                 statLog.Fatal("error: must provide -cgroup-root")
379         }
380
381         finish_chan := make(chan bool)
382         defer close(finish_chan)
383
384         var cmd *exec.Cmd
385
386         if len(flag.Args()) > 0 {
387                 // Set up subprocess
388                 cmd = exec.Command(flag.Args()[0], flag.Args()[1:]...)
389
390                 childLog.Println("Running", flag.Args())
391
392                 // Child process will use our stdin and stdout pipes
393                 // (we close our copies below)
394                 cmd.Stdin = os.Stdin
395                 cmd.Stdout = os.Stdout
396
397                 // Forward SIGINT and SIGTERM to inner process
398                 sigChan := make(chan os.Signal, 1)
399                 go func(sig <-chan os.Signal) {
400                         catch := <-sig
401                         if cmd.Process != nil {
402                                 cmd.Process.Signal(catch)
403                         }
404                         statLog.Println("caught signal:", catch)
405                 }(sigChan)
406                 signal.Notify(sigChan, syscall.SIGTERM)
407                 signal.Notify(sigChan, syscall.SIGINT)
408
409                 // Funnel stderr through our channel
410                 stderr_pipe, err := cmd.StderrPipe()
411                 if err != nil {
412                         statLog.Fatalln("error in StderrPipe:", err)
413                 }
414                 go CopyPipeToChildLog(stderr_pipe, finish_chan)
415
416                 // Run subprocess
417                 if err := cmd.Start(); err != nil {
418                         statLog.Fatalln("error in cmd.Start:", err)
419                 }
420
421                 // Close stdin/stdout in this (parent) process
422                 os.Stdin.Close()
423                 os.Stdout.Close()
424         }
425
426         // Read the cid file
427         var container_id string
428         if cgroup_cidfile != "" {
429                 // wait up to 'wait' seconds for the cid file to appear
430                 ok := false
431                 var i time.Duration
432                 for i = 0; i < time.Duration(wait)*time.Second; i += (100 * time.Millisecond) {
433                         cid, err := ioutil.ReadFile(cgroup_cidfile)
434                         if err == nil && len(cid) > 0 {
435                                 ok = true
436                                 container_id = string(cid)
437                                 break
438                         }
439                         time.Sleep(100 * time.Millisecond)
440                 }
441                 if !ok {
442                         statLog.Println("error reading cid file:", cgroup_cidfile)
443                 }
444         }
445
446         stop_poll_chan := make(chan bool, 1)
447         cgroup := Cgroup{cgroup_root, cgroup_parent, container_id}
448         go PollCgroupStats(cgroup, poll, stop_poll_chan)
449
450         // When the child exits, tell the polling goroutine to stop.
451         defer func() { stop_poll_chan <- true }()
452
453         // Wait for CopyPipeToChan to consume child's stderr pipe
454         <-finish_chan
455
456         return cmd.Wait()
457 }
458
459 func main() {
460         logger := log.New(os.Stderr, "crunchstat: ", 0)
461         if err := run(logger); err != nil {
462                 if exiterr, ok := err.(*exec.ExitError); ok {
463                         // The program has exited with an exit code != 0
464
465                         // This works on both Unix and
466                         // Windows. Although package syscall is
467                         // generally platform dependent, WaitStatus is
468                         // defined for both Unix and Windows and in
469                         // both cases has an ExitStatus() method with
470                         // the same signature.
471                         if status, ok := exiterr.Sys().(syscall.WaitStatus); ok {
472                                 os.Exit(status.ExitStatus())
473                         }
474                 } else {
475                         statLog.Fatalln("error in cmd.Wait:", err)
476                 }
477         }
478 }