Merge branch '18947-githttpd'
[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         baseLogger := logrus.StandardLogger()
39         if os.Getenv("DEBUG") != "" {
40                 baseLogger.SetLevel(logrus.DebugLevel)
41         }
42         baseLogger.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         flags.StringVar(&crunchRunCommand,
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, baseLogger)
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 := baseLogger.WithField("ClusterID", cluster.ClusterID)
86         logger.Printf("crunch-dispatch-local %s started", version)
87
88         runningCmds = make(map[string]*exec.Cmd)
89
90         var client arvados.Client
91         client.APIHost = cluster.Services.Controller.ExternalURL.Host
92         client.AuthToken = cluster.SystemRootToken
93         client.Insecure = cluster.TLS.Insecure
94
95         if client.APIHost != "" || client.AuthToken != "" {
96                 // Copy real configs into env vars so [a]
97                 // MakeArvadosClient() uses them, and [b] they get
98                 // propagated to crunch-run via SLURM.
99                 os.Setenv("ARVADOS_API_HOST", client.APIHost)
100                 os.Setenv("ARVADOS_API_TOKEN", client.AuthToken)
101                 os.Setenv("ARVADOS_API_HOST_INSECURE", "")
102                 if client.Insecure {
103                         os.Setenv("ARVADOS_API_HOST_INSECURE", "1")
104                 }
105                 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
106         } else {
107                 logger.Warnf("Client credentials missing from config, so falling back on environment variables (deprecated).")
108         }
109
110         arv, err := arvadosclient.MakeArvadosClient()
111         if err != nil {
112                 logger.Errorf("error making Arvados client: %v", err)
113                 os.Exit(1)
114         }
115         arv.Retries = 25
116
117         ctx, cancel := context.WithCancel(context.Background())
118
119         dispatcher := dispatch.Dispatcher{
120                 Logger:       logger,
121                 Arv:          arv,
122                 RunContainer: (&LocalRun{startFunc, make(chan bool, 8), ctx, cluster}).run,
123                 PollPeriod:   time.Duration(*pollInterval) * time.Second,
124         }
125
126         err = dispatcher.Run(ctx)
127         if err != nil {
128                 logger.Error(err)
129                 return
130         }
131
132         c := make(chan os.Signal, 1)
133         signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)
134         sig := <-c
135         logger.Printf("Received %s, shutting down", sig)
136         signal.Stop(c)
137
138         cancel()
139
140         runningCmdsMutex.Lock()
141         // Finished dispatching; interrupt any crunch jobs that are still running
142         for _, cmd := range runningCmds {
143                 cmd.Process.Signal(os.Interrupt)
144         }
145         runningCmdsMutex.Unlock()
146
147         // Wait for all running crunch jobs to complete / terminate
148         waitGroup.Wait()
149 }
150
151 func startFunc(container arvados.Container, cmd *exec.Cmd) error {
152         return cmd.Start()
153 }
154
155 type LocalRun struct {
156         startCmd         func(container arvados.Container, cmd *exec.Cmd) error
157         concurrencyLimit chan bool
158         ctx              context.Context
159         cluster          *arvados.Cluster
160 }
161
162 // Run a container.
163 //
164 // If the container is Locked, start a new crunch-run process and wait until
165 // crunch-run completes.  If the priority is set to zero, set an interrupt
166 // signal to the crunch-run process.
167 //
168 // If the container is in any other state, or is not Complete/Cancelled after
169 // crunch-run terminates, mark the container as Cancelled.
170 func (lr *LocalRun) run(dispatcher *dispatch.Dispatcher,
171         container arvados.Container,
172         status <-chan arvados.Container) error {
173
174         uuid := container.UUID
175
176         if container.State == dispatch.Locked {
177
178                 select {
179                 case lr.concurrencyLimit <- true:
180                         break
181                 case <-lr.ctx.Done():
182                         return lr.ctx.Err()
183                 }
184
185                 defer func() { <-lr.concurrencyLimit }()
186
187                 select {
188                 case c := <-status:
189                         // Check for state updates after possibly
190                         // waiting to be ready-to-run
191                         if c.Priority == 0 {
192                                 goto Finish
193                         }
194                 default:
195                         break
196                 }
197
198                 waitGroup.Add(1)
199                 defer waitGroup.Done()
200
201                 cmd := exec.Command(crunchRunCommand, "--runtime-engine="+lr.cluster.Containers.RuntimeEngine, uuid)
202                 cmd.Stdin = nil
203                 cmd.Stderr = os.Stderr
204                 cmd.Stdout = os.Stderr
205
206                 dispatcher.Logger.Printf("starting container %v", uuid)
207
208                 // Add this crunch job to the list of runningCmds only if we
209                 // succeed in starting crunch-run.
210
211                 runningCmdsMutex.Lock()
212                 if err := lr.startCmd(container, cmd); err != nil {
213                         runningCmdsMutex.Unlock()
214                         dispatcher.Logger.Warnf("error starting %q for %s: %s", crunchRunCommand, uuid, err)
215                         dispatcher.UpdateState(uuid, dispatch.Cancelled)
216                 } else {
217                         runningCmds[uuid] = cmd
218                         runningCmdsMutex.Unlock()
219
220                         // Need to wait for crunch-run to exit
221                         done := make(chan struct{})
222
223                         go func() {
224                                 if _, err := cmd.Process.Wait(); err != nil {
225                                         dispatcher.Logger.Warnf("error while waiting for crunch job to finish for %v: %q", uuid, err)
226                                 }
227                                 dispatcher.Logger.Debugf("sending done")
228                                 done <- struct{}{}
229                         }()
230
231                 Loop:
232                         for {
233                                 select {
234                                 case <-done:
235                                         break Loop
236                                 case c := <-status:
237                                         // Interrupt the child process if priority changes to 0
238                                         if (c.State == dispatch.Locked || c.State == dispatch.Running) && c.Priority == 0 {
239                                                 dispatcher.Logger.Printf("sending SIGINT to pid %d to cancel container %v", cmd.Process.Pid, uuid)
240                                                 cmd.Process.Signal(os.Interrupt)
241                                         }
242                                 }
243                         }
244                         close(done)
245
246                         dispatcher.Logger.Printf("finished container run for %v", uuid)
247
248                         // Remove the crunch job from runningCmds
249                         runningCmdsMutex.Lock()
250                         delete(runningCmds, uuid)
251                         runningCmdsMutex.Unlock()
252                 }
253         }
254
255 Finish:
256
257         // If the container is not finalized, then change it to "Cancelled".
258         err := dispatcher.Arv.Get("containers", uuid, nil, &container)
259         if err != nil {
260                 dispatcher.Logger.Warnf("error getting final container state: %v", err)
261         }
262         if container.State == dispatch.Locked || container.State == dispatch.Running {
263                 dispatcher.Logger.Warnf("after %q process termination, container state for %v is %q; updating it to %q",
264                         crunchRunCommand, uuid, container.State, dispatch.Cancelled)
265                 dispatcher.UpdateState(uuid, dispatch.Cancelled)
266         }
267
268         // drain any subsequent status changes
269         for range status {
270         }
271
272         dispatcher.Logger.Printf("finalized container %v", uuid)
273         return nil
274 }