19166: Pass GatewayAuthSecret to crunch-run through lsf/slurm.
[arvados.git] / services / crunch-dispatch-slurm / crunch-dispatch-slurm.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 // Dispatcher service for Crunch that submits containers to the slurm queue.
6 package dispatchslurm
7
8 import (
9         "context"
10         "crypto/hmac"
11         "crypto/sha256"
12         "fmt"
13         "log"
14         "math"
15         "net/http"
16         "os"
17         "regexp"
18         "strings"
19         "time"
20
21         "git.arvados.org/arvados.git/lib/cmd"
22         "git.arvados.org/arvados.git/lib/dispatchcloud"
23         "git.arvados.org/arvados.git/lib/service"
24         "git.arvados.org/arvados.git/sdk/go/arvados"
25         "git.arvados.org/arvados.git/sdk/go/arvadosclient"
26         "git.arvados.org/arvados.git/sdk/go/ctxlog"
27         "git.arvados.org/arvados.git/sdk/go/dispatch"
28         "github.com/coreos/go-systemd/daemon"
29         "github.com/prometheus/client_golang/prometheus"
30         "github.com/sirupsen/logrus"
31 )
32
33 var Command cmd.Handler = service.Command(arvados.ServiceNameDispatchSLURM, newHandler)
34
35 func newHandler(ctx context.Context, cluster *arvados.Cluster, _ string, _ *prometheus.Registry) service.Handler {
36         logger := ctxlog.FromContext(ctx)
37         disp := &Dispatcher{logger: logger, cluster: cluster}
38         if err := disp.configure(); err != nil {
39                 return service.ErrorHandler(ctx, cluster, err)
40         }
41         disp.setup()
42         go func() {
43                 disp.err = disp.run()
44                 close(disp.done)
45         }()
46         return disp
47 }
48
49 type logger interface {
50         dispatch.Logger
51         Fatalf(string, ...interface{})
52 }
53
54 const initialNiceValue int64 = 10000
55
56 type Dispatcher struct {
57         *dispatch.Dispatcher
58         logger  logrus.FieldLogger
59         cluster *arvados.Cluster
60         sqCheck *SqueueChecker
61         slurm   Slurm
62
63         done chan struct{}
64         err  error
65
66         Client arvados.Client
67 }
68
69 func (disp *Dispatcher) CheckHealth() error {
70         return disp.err
71 }
72
73 func (disp *Dispatcher) Done() <-chan struct{} {
74         return disp.done
75 }
76
77 func (disp *Dispatcher) ServeHTTP(w http.ResponseWriter, r *http.Request) {
78         http.NotFound(w, r)
79 }
80
81 // configure() loads config files. Some tests skip this (see
82 // StubbedSuite).
83 func (disp *Dispatcher) configure() error {
84         if disp.logger == nil {
85                 disp.logger = logrus.StandardLogger()
86         }
87         disp.logger = disp.logger.WithField("ClusterID", disp.cluster.ClusterID)
88         disp.logger.Printf("crunch-dispatch-slurm %s started", cmd.Version.String())
89
90         disp.Client.APIHost = disp.cluster.Services.Controller.ExternalURL.Host
91         disp.Client.AuthToken = disp.cluster.SystemRootToken
92         disp.Client.Insecure = disp.cluster.TLS.Insecure
93
94         if disp.Client.APIHost != "" || disp.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", disp.Client.APIHost)
99                 os.Setenv("ARVADOS_API_TOKEN", disp.Client.AuthToken)
100                 os.Setenv("ARVADOS_API_HOST_INSECURE", "")
101                 if disp.Client.Insecure {
102                         os.Setenv("ARVADOS_API_HOST_INSECURE", "1")
103                 }
104                 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
105                 for k, v := range disp.cluster.Containers.SLURM.SbatchEnvironmentVariables {
106                         os.Setenv(k, v)
107                 }
108         } else {
109                 disp.logger.Warnf("Client credentials missing from config, so falling back on environment variables (deprecated).")
110         }
111         return nil
112 }
113
114 // setup() initializes private fields after configure().
115 func (disp *Dispatcher) setup() {
116         disp.done = make(chan struct{})
117         arv, err := arvadosclient.MakeArvadosClient()
118         if err != nil {
119                 disp.logger.Fatalf("Error making Arvados client: %v", err)
120         }
121         arv.Retries = 25
122
123         disp.slurm = NewSlurmCLI()
124         disp.sqCheck = &SqueueChecker{
125                 Logger:         disp.logger,
126                 Period:         time.Duration(disp.cluster.Containers.CloudVMs.PollInterval),
127                 PrioritySpread: disp.cluster.Containers.SLURM.PrioritySpread,
128                 Slurm:          disp.slurm,
129         }
130         disp.Dispatcher = &dispatch.Dispatcher{
131                 Arv:            arv,
132                 Logger:         disp.logger,
133                 BatchSize:      disp.cluster.API.MaxItemsPerResponse,
134                 RunContainer:   disp.runContainer,
135                 PollPeriod:     time.Duration(disp.cluster.Containers.CloudVMs.PollInterval),
136                 MinRetryPeriod: time.Duration(disp.cluster.Containers.MinRetryPeriod),
137         }
138 }
139
140 func (disp *Dispatcher) run() error {
141         defer disp.sqCheck.Stop()
142
143         if disp.cluster != nil && len(disp.cluster.InstanceTypes) > 0 {
144                 go SlurmNodeTypeFeatureKludge(disp.cluster)
145         }
146
147         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
148                 log.Printf("Error notifying init daemon: %v", err)
149         }
150         go disp.checkSqueueForOrphans()
151         return disp.Dispatcher.Run(context.Background())
152 }
153
154 var containerUuidPattern = regexp.MustCompile(`^[a-z0-9]{5}-dz642-[a-z0-9]{15}$`)
155
156 // Check the next squeue report, and invoke TrackContainer for all the
157 // containers in the report. This gives us a chance to cancel slurm
158 // jobs started by a previous dispatch process that never released
159 // their slurm allocations even though their container states are
160 // Cancelled or Complete. See https://dev.arvados.org/issues/10979
161 func (disp *Dispatcher) checkSqueueForOrphans() {
162         for _, uuid := range disp.sqCheck.All() {
163                 if !containerUuidPattern.MatchString(uuid) || !strings.HasPrefix(uuid, disp.cluster.ClusterID) {
164                         continue
165                 }
166                 err := disp.TrackContainer(uuid)
167                 if err != nil {
168                         log.Printf("checkSqueueForOrphans: TrackContainer(%s): %s", uuid, err)
169                 }
170         }
171 }
172
173 func (disp *Dispatcher) slurmConstraintArgs(container arvados.Container) []string {
174         mem := int64(math.Ceil(float64(container.RuntimeConstraints.RAM+
175                 container.RuntimeConstraints.KeepCacheRAM+
176                 int64(disp.cluster.Containers.ReserveExtraRAM)) / float64(1048576)))
177
178         disk := dispatchcloud.EstimateScratchSpace(&container)
179         disk = int64(math.Ceil(float64(disk) / float64(1048576)))
180         return []string{
181                 fmt.Sprintf("--mem=%d", mem),
182                 fmt.Sprintf("--cpus-per-task=%d", container.RuntimeConstraints.VCPUs),
183                 fmt.Sprintf("--tmp=%d", disk),
184         }
185 }
186
187 func (disp *Dispatcher) sbatchArgs(container arvados.Container) ([]string, error) {
188         var args []string
189         args = append(args, disp.cluster.Containers.SLURM.SbatchArgumentsList...)
190         args = append(args, "--job-name="+container.UUID, fmt.Sprintf("--nice=%d", initialNiceValue), "--no-requeue")
191
192         if disp.cluster == nil {
193                 // no instance types configured
194                 args = append(args, disp.slurmConstraintArgs(container)...)
195         } else if it, err := dispatchcloud.ChooseInstanceType(disp.cluster, &container); err == dispatchcloud.ErrInstanceTypesNotConfigured {
196                 // ditto
197                 args = append(args, disp.slurmConstraintArgs(container)...)
198         } else if err != nil {
199                 return nil, err
200         } else {
201                 // use instancetype constraint instead of slurm mem/cpu/tmp specs
202                 args = append(args, "--constraint=instancetype="+it.Name)
203         }
204
205         if len(container.SchedulingParameters.Partitions) > 0 {
206                 args = append(args, "--partition="+strings.Join(container.SchedulingParameters.Partitions, ","))
207         }
208
209         return args, nil
210 }
211
212 func (disp *Dispatcher) submit(container arvados.Container, crunchRunCommand []string) error {
213         // append() here avoids modifying crunchRunCommand's
214         // underlying array, which is shared with other goroutines.
215         crArgs := append([]string(nil), crunchRunCommand...)
216         crArgs = append(crArgs, "--runtime-engine="+disp.cluster.Containers.RuntimeEngine)
217         crArgs = append(crArgs, container.UUID)
218
219         h := hmac.New(sha256.New, []byte(disp.cluster.SystemRootToken))
220         fmt.Fprint(h, container.UUID)
221         authsecret := fmt.Sprintf("%x", h.Sum(nil))
222
223         crScript := strings.NewReader(execScript(crArgs, map[string]string{"GatewayAuthSecret": authsecret}))
224
225         sbArgs, err := disp.sbatchArgs(container)
226         if err != nil {
227                 return err
228         }
229         log.Printf("running sbatch %+q", sbArgs)
230         return disp.slurm.Batch(crScript, sbArgs)
231 }
232
233 // Submit a container to the slurm queue (or resume monitoring if it's
234 // already in the queue).  Cancel the slurm job if the container's
235 // priority changes to zero or its state indicates it's no longer
236 // running.
237 func (disp *Dispatcher) runContainer(_ *dispatch.Dispatcher, ctr arvados.Container, status <-chan arvados.Container) error {
238         ctx, cancel := context.WithCancel(context.Background())
239         defer cancel()
240
241         if ctr.State == dispatch.Locked && !disp.sqCheck.HasUUID(ctr.UUID) {
242                 log.Printf("Submitting container %s to slurm", ctr.UUID)
243                 cmd := []string{disp.cluster.Containers.CrunchRunCommand}
244                 cmd = append(cmd, disp.cluster.Containers.CrunchRunArgumentsList...)
245                 err := disp.submit(ctr, cmd)
246                 if err != nil {
247                         return err
248                 }
249         }
250
251         log.Printf("Start monitoring container %v in state %q", ctr.UUID, ctr.State)
252         defer log.Printf("Done monitoring container %s", ctr.UUID)
253
254         // If the container disappears from the slurm queue, there is
255         // no point in waiting for further dispatch updates: just
256         // clean up and return.
257         go func(uuid string) {
258                 for ctx.Err() == nil && disp.sqCheck.HasUUID(uuid) {
259                 }
260                 cancel()
261         }(ctr.UUID)
262
263         for {
264                 select {
265                 case <-ctx.Done():
266                         // Disappeared from squeue
267                         if err := disp.Arv.Get("containers", ctr.UUID, nil, &ctr); err != nil {
268                                 log.Printf("error getting final container state for %s: %s", ctr.UUID, err)
269                         }
270                         switch ctr.State {
271                         case dispatch.Running:
272                                 disp.UpdateState(ctr.UUID, dispatch.Cancelled)
273                         case dispatch.Locked:
274                                 disp.Unlock(ctr.UUID)
275                         }
276                         return nil
277                 case updated, ok := <-status:
278                         if !ok {
279                                 log.Printf("container %s is done: cancel slurm job", ctr.UUID)
280                                 disp.scancel(ctr)
281                         } else if updated.Priority == 0 {
282                                 log.Printf("container %s has state %q, priority %d: cancel slurm job", ctr.UUID, updated.State, updated.Priority)
283                                 disp.scancel(ctr)
284                         } else {
285                                 p := int64(updated.Priority)
286                                 if p <= 1000 {
287                                         // API is providing
288                                         // user-assigned priority. If
289                                         // ctrs have equal priority,
290                                         // run the older one first.
291                                         p = int64(p)<<50 - (updated.CreatedAt.UnixNano() >> 14)
292                                 }
293                                 disp.sqCheck.SetPriority(ctr.UUID, p)
294                         }
295                 }
296         }
297 }
298 func (disp *Dispatcher) scancel(ctr arvados.Container) {
299         err := disp.slurm.Cancel(ctr.UUID)
300         if err != nil {
301                 log.Printf("scancel: %s", err)
302                 time.Sleep(time.Second)
303         } else if disp.sqCheck.HasUUID(ctr.UUID) {
304                 log.Printf("container %s is still in squeue after scancel", ctr.UUID)
305                 time.Sleep(time.Second)
306         }
307 }