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