1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
19 "git.arvados.org/arvados.git/lib/cmd"
20 "git.arvados.org/arvados.git/lib/crunchstat"
23 const MaxLogLine = 1 << 14 // Child stderr lines >16KiB will be split
26 signalOnDeadPPID int = 15
27 ppidCheckInterval = time.Second
32 reporter := crunchstat.Reporter{
33 Logger: log.New(os.Stderr, "crunchstat: ", 0),
36 flags := flag.NewFlagSet(os.Args[0], flag.ExitOnError)
37 flags.StringVar(&reporter.CgroupRoot, "cgroup-root", "", "Root of cgroup tree")
38 flags.StringVar(&reporter.CgroupParent, "cgroup-parent", "", "Name of container parent under cgroup")
39 flags.StringVar(&reporter.CIDFile, "cgroup-cid", "", "Path to container id file")
40 flags.IntVar(&signalOnDeadPPID, "signal-on-dead-ppid", signalOnDeadPPID, "Signal to send child if crunchstat's parent process disappears (0 to disable)")
41 flags.DurationVar(&ppidCheckInterval, "ppid-check-interval", ppidCheckInterval, "Time between checks for parent process disappearance")
42 pollMsec := flags.Int64("poll", 1000, "Reporting interval, in milliseconds")
43 getVersion := flags.Bool("version", false, "Print version information and exit.")
45 if ok, code := cmd.ParseFlags(flags, os.Args[0], os.Args[1:], "program [args ...]", os.Stderr); !ok {
47 } else if *getVersion {
48 fmt.Printf("crunchstat %s\n", version)
50 } else if flags.NArg() == 0 {
51 fmt.Fprintf(os.Stderr, "missing required argument: program (try -help)\n")
55 reporter.Logger.Printf("crunchstat %s started", version)
57 if reporter.CgroupRoot == "" {
58 reporter.Logger.Fatal("error: must provide -cgroup-root")
59 } else if signalOnDeadPPID < 0 {
60 reporter.Logger.Fatalf("-signal-on-dead-ppid=%d is invalid (use a positive signal number, or 0 to disable)", signalOnDeadPPID)
62 reporter.PollPeriod = time.Duration(*pollMsec) * time.Millisecond
65 err := runCommand(flags.Args(), reporter.Logger)
68 if err, ok := err.(*exec.ExitError); ok {
69 // The program has exited with an exit code != 0
71 // This works on both Unix and Windows. Although
72 // package syscall is generally platform dependent,
73 // WaitStatus is defined for both Unix and Windows and
74 // in both cases has an ExitStatus() method with the
76 if status, ok := err.Sys().(syscall.WaitStatus); ok {
77 os.Exit(status.ExitStatus())
79 reporter.Logger.Fatalln("ExitError without WaitStatus:", err)
81 } else if err != nil {
82 reporter.Logger.Fatalln("error in cmd.Wait:", err)
86 func runCommand(argv []string, logger *log.Logger) error {
87 cmd := exec.Command(argv[0], argv[1:]...)
89 logger.Println("Running", argv)
91 // Child process will use our stdin and stdout pipes
92 // (we close our copies below)
94 cmd.Stdout = os.Stdout
96 // Forward SIGINT and SIGTERM to child process
97 sigChan := make(chan os.Signal, 1)
98 go func(sig <-chan os.Signal) {
100 if cmd.Process != nil {
101 cmd.Process.Signal(catch)
103 logger.Println("notice: caught signal:", catch)
105 signal.Notify(sigChan, syscall.SIGTERM)
106 signal.Notify(sigChan, syscall.SIGINT)
108 // Kill our child proc if our parent process disappears
109 if signalOnDeadPPID != 0 {
110 go sendSignalOnDeadPPID(ppidCheckInterval, signalOnDeadPPID, os.Getppid(), cmd, logger)
113 // Funnel stderr through our channel
114 stderrPipe, err := cmd.StderrPipe()
116 logger.Fatalln("error in StderrPipe:", err)
120 if err := cmd.Start(); err != nil {
121 logger.Fatalln("error in cmd.Start:", err)
124 // Close stdin/stdout in this (parent) process
128 copyPipeToChildLog(stderrPipe, log.New(os.Stderr, "", 0))
133 func sendSignalOnDeadPPID(intvl time.Duration, signum, ppidOrig int, cmd *exec.Cmd, logger *log.Logger) {
134 ticker := time.NewTicker(intvl)
137 if ppid == ppidOrig {
140 if cmd.Process == nil {
141 // Child process isn't running yet
144 logger.Printf("notice: crunchstat ppid changed from %d to %d -- killing child pid %d with signal %d", ppidOrig, ppid, cmd.Process.Pid, signum)
145 err := cmd.Process.Signal(syscall.Signal(signum))
147 logger.Printf("error: sending signal: %s", err)
155 func copyPipeToChildLog(in io.ReadCloser, logger *log.Logger) {
156 reader := bufio.NewReaderSize(in, MaxLogLine)
159 line, isPrefix, err := reader.ReadLine()
162 } else if err != nil {
163 logger.Fatal("error reading child stderr:", err)
169 logger.Print(prefix, string(line), suffix)
170 // Set up prefix for following line