Merge branch '13973-child-priority' refs #13973
[arvados.git] / services / crunch-dispatch-local / crunch-dispatch-local.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package main
6
7 // Dispatcher service for Crunch that runs containers locally.
8
9 import (
10         "context"
11         "flag"
12         "fmt"
13         "os"
14         "os/exec"
15         "os/signal"
16         "sync"
17         "syscall"
18         "time"
19
20         "git.curoverse.com/arvados.git/sdk/go/arvados"
21         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
22         "git.curoverse.com/arvados.git/sdk/go/dispatch"
23         "github.com/Sirupsen/logrus"
24 )
25
26 var version = "dev"
27
28 func main() {
29         err := doMain()
30         if err != nil {
31                 logrus.Fatalf("%q", err)
32         }
33 }
34
35 var (
36         runningCmds      map[string]*exec.Cmd
37         runningCmdsMutex sync.Mutex
38         waitGroup        sync.WaitGroup
39         crunchRunCommand *string
40 )
41
42 func doMain() error {
43         logger := logrus.StandardLogger()
44         if os.Getenv("DEBUG") != "" {
45                 logger.SetLevel(logrus.DebugLevel)
46         }
47         logger.Formatter = &logrus.JSONFormatter{
48                 TimestampFormat: "2006-01-02T15:04:05.000000000Z07:00",
49         }
50
51         flags := flag.NewFlagSet("crunch-dispatch-local", flag.ExitOnError)
52
53         pollInterval := flags.Int(
54                 "poll-interval",
55                 10,
56                 "Interval in seconds to poll for queued containers")
57
58         crunchRunCommand = flags.String(
59                 "crunch-run-command",
60                 "/usr/bin/crunch-run",
61                 "Crunch command to run container")
62
63         getVersion := flags.Bool(
64                 "version",
65                 false,
66                 "Print version information and exit.")
67
68         // Parse args; omit the first arg which is the command name
69         flags.Parse(os.Args[1:])
70
71         // Print version information if requested
72         if *getVersion {
73                 fmt.Printf("crunch-dispatch-local %s\n", version)
74                 return nil
75         }
76
77         logger.Printf("crunch-dispatch-local %s started", version)
78
79         runningCmds = make(map[string]*exec.Cmd)
80
81         arv, err := arvadosclient.MakeArvadosClient()
82         if err != nil {
83                 logger.Errorf("error making Arvados client: %v", err)
84                 return err
85         }
86         arv.Retries = 25
87
88         dispatcher := dispatch.Dispatcher{
89                 Logger:       logger,
90                 Arv:          arv,
91                 RunContainer: run,
92                 PollPeriod:   time.Duration(*pollInterval) * time.Second,
93         }
94
95         ctx, cancel := context.WithCancel(context.Background())
96         err = dispatcher.Run(ctx)
97         if err != nil {
98                 return err
99         }
100
101         c := make(chan os.Signal, 1)
102         signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)
103         sig := <-c
104         logger.Printf("Received %s, shutting down", sig)
105         signal.Stop(c)
106
107         cancel()
108
109         runningCmdsMutex.Lock()
110         // Finished dispatching; interrupt any crunch jobs that are still running
111         for _, cmd := range runningCmds {
112                 cmd.Process.Signal(os.Interrupt)
113         }
114         runningCmdsMutex.Unlock()
115
116         // Wait for all running crunch jobs to complete / terminate
117         waitGroup.Wait()
118
119         return nil
120 }
121
122 func startFunc(container arvados.Container, cmd *exec.Cmd) error {
123         return cmd.Start()
124 }
125
126 var startCmd = startFunc
127
128 // Run a container.
129 //
130 // If the container is Locked, start a new crunch-run process and wait until
131 // crunch-run completes.  If the priority is set to zero, set an interrupt
132 // signal to the crunch-run process.
133 //
134 // If the container is in any other state, or is not Complete/Cancelled after
135 // crunch-run terminates, mark the container as Cancelled.
136 func run(dispatcher *dispatch.Dispatcher,
137         container arvados.Container,
138         status <-chan arvados.Container) {
139
140         uuid := container.UUID
141
142         if container.State == dispatch.Locked {
143                 waitGroup.Add(1)
144
145                 cmd := exec.Command(*crunchRunCommand, uuid)
146                 cmd.Stdin = nil
147                 cmd.Stderr = os.Stderr
148                 cmd.Stdout = os.Stderr
149
150                 dispatcher.Logger.Printf("starting container %v", uuid)
151
152                 // Add this crunch job to the list of runningCmds only if we
153                 // succeed in starting crunch-run.
154
155                 runningCmdsMutex.Lock()
156                 if err := startCmd(container, cmd); err != nil {
157                         runningCmdsMutex.Unlock()
158                         dispatcher.Logger.Warnf("error starting %q for %s: %s", *crunchRunCommand, uuid, err)
159                         dispatcher.UpdateState(uuid, dispatch.Cancelled)
160                 } else {
161                         runningCmds[uuid] = cmd
162                         runningCmdsMutex.Unlock()
163
164                         // Need to wait for crunch-run to exit
165                         done := make(chan struct{})
166
167                         go func() {
168                                 if _, err := cmd.Process.Wait(); err != nil {
169                                         dispatcher.Logger.Warnf("error while waiting for crunch job to finish for %v: %q", uuid, err)
170                                 }
171                                 dispatcher.Logger.Debugf("sending done")
172                                 done <- struct{}{}
173                         }()
174
175                 Loop:
176                         for {
177                                 select {
178                                 case <-done:
179                                         break Loop
180                                 case c := <-status:
181                                         // Interrupt the child process if priority changes to 0
182                                         if (c.State == dispatch.Locked || c.State == dispatch.Running) && c.Priority == 0 {
183                                                 dispatcher.Logger.Printf("sending SIGINT to pid %d to cancel container %v", cmd.Process.Pid, uuid)
184                                                 cmd.Process.Signal(os.Interrupt)
185                                         }
186                                 }
187                         }
188                         close(done)
189
190                         dispatcher.Logger.Printf("finished container run for %v", uuid)
191
192                         // Remove the crunch job from runningCmds
193                         runningCmdsMutex.Lock()
194                         delete(runningCmds, uuid)
195                         runningCmdsMutex.Unlock()
196                 }
197                 waitGroup.Done()
198         }
199
200         // If the container is not finalized, then change it to "Cancelled".
201         err := dispatcher.Arv.Get("containers", uuid, nil, &container)
202         if err != nil {
203                 dispatcher.Logger.Warnf("error getting final container state: %v", err)
204         }
205         if container.State == dispatch.Locked || container.State == dispatch.Running {
206                 dispatcher.Logger.Warnf("after %q process termination, container state for %v is %q; updating it to %q",
207                         *crunchRunCommand, uuid, container.State, dispatch.Cancelled)
208                 dispatcher.UpdateState(uuid, dispatch.Cancelled)
209         }
210
211         // drain any subsequent status changes
212         for range status {
213         }
214
215         dispatcher.Logger.Printf("finalized container %v", uuid)
216 }