17840: Merge branch 'main'
[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.arvados.org/arvados.git/lib/cmd"
21         "git.arvados.org/arvados.git/lib/config"
22         "git.arvados.org/arvados.git/sdk/go/arvados"
23         "git.arvados.org/arvados.git/sdk/go/arvadosclient"
24         "git.arvados.org/arvados.git/sdk/go/dispatch"
25         "github.com/sirupsen/logrus"
26 )
27
28 var version = "dev"
29
30 var (
31         runningCmds      map[string]*exec.Cmd
32         runningCmdsMutex sync.Mutex
33         waitGroup        sync.WaitGroup
34         crunchRunCommand *string
35 )
36
37 func main() {
38         logger := logrus.StandardLogger()
39         if os.Getenv("DEBUG") != "" {
40                 logger.SetLevel(logrus.DebugLevel)
41         }
42         logger.Formatter = &logrus.JSONFormatter{
43                 TimestampFormat: "2006-01-02T15:04:05.000000000Z07:00",
44         }
45
46         flags := flag.NewFlagSet("crunch-dispatch-local", flag.ExitOnError)
47
48         pollInterval := flags.Int(
49                 "poll-interval",
50                 10,
51                 "Interval in seconds to poll for queued containers")
52
53         crunchRunCommand = flags.String(
54                 "crunch-run-command",
55                 "/usr/bin/crunch-run",
56                 "Crunch command to run container")
57
58         getVersion := flags.Bool(
59                 "version",
60                 false,
61                 "Print version information and exit.")
62
63         if ok, code := cmd.ParseFlags(flags, os.Args[0], os.Args[1:], "", os.Stderr); !ok {
64                 os.Exit(code)
65         }
66
67         // Print version information if requested
68         if *getVersion {
69                 fmt.Printf("crunch-dispatch-local %s\n", version)
70                 return
71         }
72
73         loader := config.NewLoader(nil, logger)
74         cfg, err := loader.Load()
75         if err != nil {
76                 fmt.Fprintf(os.Stderr, "error loading config: %s\n", err)
77                 os.Exit(1)
78         }
79         cluster, err := cfg.GetCluster("")
80         if err != nil {
81                 fmt.Fprintf(os.Stderr, "config error: %s\n", err)
82                 os.Exit(1)
83         }
84
85         logger.Printf("crunch-dispatch-local %s started", version)
86
87         runningCmds = make(map[string]*exec.Cmd)
88
89         var client arvados.Client
90         client.APIHost = cluster.Services.Controller.ExternalURL.Host
91         client.AuthToken = cluster.SystemRootToken
92         client.Insecure = cluster.TLS.Insecure
93
94         if client.APIHost != "" || client.AuthToken != "" {
95                 // Copy real configs into env vars so [a]
96                 // MakeArvadosClient() uses them, and [b] they get
97                 // propagated to crunch-run via SLURM.
98                 os.Setenv("ARVADOS_API_HOST", client.APIHost)
99                 os.Setenv("ARVADOS_API_TOKEN", client.AuthToken)
100                 os.Setenv("ARVADOS_API_HOST_INSECURE", "")
101                 if client.Insecure {
102                         os.Setenv("ARVADOS_API_HOST_INSECURE", "1")
103                 }
104                 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
105         } else {
106                 logger.Warnf("Client credentials missing from config, so falling back on environment variables (deprecated).")
107         }
108
109         arv, err := arvadosclient.MakeArvadosClient()
110         if err != nil {
111                 logger.Errorf("error making Arvados client: %v", err)
112                 os.Exit(1)
113         }
114         arv.Retries = 25
115
116         ctx, cancel := context.WithCancel(context.Background())
117
118         dispatcher := dispatch.Dispatcher{
119                 Logger:       logger,
120                 Arv:          arv,
121                 RunContainer: (&LocalRun{startFunc, make(chan bool, 8), ctx, cluster}).run,
122                 PollPeriod:   time.Duration(*pollInterval) * time.Second,
123         }
124
125         err = dispatcher.Run(ctx)
126         if err != nil {
127                 logger.Error(err)
128                 return
129         }
130
131         c := make(chan os.Signal, 1)
132         signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)
133         sig := <-c
134         logger.Printf("Received %s, shutting down", sig)
135         signal.Stop(c)
136
137         cancel()
138
139         runningCmdsMutex.Lock()
140         // Finished dispatching; interrupt any crunch jobs that are still running
141         for _, cmd := range runningCmds {
142                 cmd.Process.Signal(os.Interrupt)
143         }
144         runningCmdsMutex.Unlock()
145
146         // Wait for all running crunch jobs to complete / terminate
147         waitGroup.Wait()
148 }
149
150 func startFunc(container arvados.Container, cmd *exec.Cmd) error {
151         return cmd.Start()
152 }
153
154 type LocalRun struct {
155         startCmd         func(container arvados.Container, cmd *exec.Cmd) error
156         concurrencyLimit chan bool
157         ctx              context.Context
158         cluster          *arvados.Cluster
159 }
160
161 // Run a container.
162 //
163 // If the container is Locked, start a new crunch-run process and wait until
164 // crunch-run completes.  If the priority is set to zero, set an interrupt
165 // signal to the crunch-run process.
166 //
167 // If the container is in any other state, or is not Complete/Cancelled after
168 // crunch-run terminates, mark the container as Cancelled.
169 func (lr *LocalRun) run(dispatcher *dispatch.Dispatcher,
170         container arvados.Container,
171         status <-chan arvados.Container) error {
172
173         uuid := container.UUID
174
175         if container.State == dispatch.Locked {
176
177                 select {
178                 case lr.concurrencyLimit <- true:
179                         break
180                 case <-lr.ctx.Done():
181                         return lr.ctx.Err()
182                 }
183
184                 defer func() { <-lr.concurrencyLimit }()
185
186                 select {
187                 case c := <-status:
188                         // Check for state updates after possibly
189                         // waiting to be ready-to-run
190                         if c.Priority == 0 {
191                                 goto Finish
192                         }
193                 default:
194                         break
195                 }
196
197                 waitGroup.Add(1)
198                 defer waitGroup.Done()
199
200                 cmd := exec.Command(*crunchRunCommand, "--runtime-engine="+lr.cluster.Containers.RuntimeEngine, uuid)
201                 cmd.Stdin = nil
202                 cmd.Stderr = os.Stderr
203                 cmd.Stdout = os.Stderr
204
205                 dispatcher.Logger.Printf("starting container %v", uuid)
206
207                 // Add this crunch job to the list of runningCmds only if we
208                 // succeed in starting crunch-run.
209
210                 runningCmdsMutex.Lock()
211                 if err := lr.startCmd(container, cmd); err != nil {
212                         runningCmdsMutex.Unlock()
213                         dispatcher.Logger.Warnf("error starting %q for %s: %s", *crunchRunCommand, uuid, err)
214                         dispatcher.UpdateState(uuid, dispatch.Cancelled)
215                 } else {
216                         runningCmds[uuid] = cmd
217                         runningCmdsMutex.Unlock()
218
219                         // Need to wait for crunch-run to exit
220                         done := make(chan struct{})
221
222                         go func() {
223                                 if _, err := cmd.Process.Wait(); err != nil {
224                                         dispatcher.Logger.Warnf("error while waiting for crunch job to finish for %v: %q", uuid, err)
225                                 }
226                                 dispatcher.Logger.Debugf("sending done")
227                                 done <- struct{}{}
228                         }()
229
230                 Loop:
231                         for {
232                                 select {
233                                 case <-done:
234                                         break Loop
235                                 case c := <-status:
236                                         // Interrupt the child process if priority changes to 0
237                                         if (c.State == dispatch.Locked || c.State == dispatch.Running) && c.Priority == 0 {
238                                                 dispatcher.Logger.Printf("sending SIGINT to pid %d to cancel container %v", cmd.Process.Pid, uuid)
239                                                 cmd.Process.Signal(os.Interrupt)
240                                         }
241                                 }
242                         }
243                         close(done)
244
245                         dispatcher.Logger.Printf("finished container run for %v", uuid)
246
247                         // Remove the crunch job from runningCmds
248                         runningCmdsMutex.Lock()
249                         delete(runningCmds, uuid)
250                         runningCmdsMutex.Unlock()
251                 }
252         }
253
254 Finish:
255
256         // If the container is not finalized, then change it to "Cancelled".
257         err := dispatcher.Arv.Get("containers", uuid, nil, &container)
258         if err != nil {
259                 dispatcher.Logger.Warnf("error getting final container state: %v", err)
260         }
261         if container.State == dispatch.Locked || container.State == dispatch.Running {
262                 dispatcher.Logger.Warnf("after %q process termination, container state for %v is %q; updating it to %q",
263                         *crunchRunCommand, uuid, container.State, dispatch.Cancelled)
264                 dispatcher.UpdateState(uuid, dispatch.Cancelled)
265         }
266
267         // drain any subsequent status changes
268         for range status {
269         }
270
271         dispatcher.Logger.Printf("finalized container %v", uuid)
272         return nil
273 }