1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
15 "git.arvados.org/arvados.git/lib/cloud"
16 "git.arvados.org/arvados.git/sdk/go/arvados"
17 "git.arvados.org/arvados.git/sdk/go/stats"
18 "github.com/sirupsen/logrus"
23 maxPingFailTime = 10 * time.Minute
26 // State indicates whether a worker is available to do work, and (if
27 // not) whether/when it is expected to become ready.
31 StateUnknown State = iota // might be running a container already
32 StateBooting // instance is booting
33 StateIdle // instance booted, no containers are running
34 StateRunning // instance is running one or more containers
35 StateShutdown // worker has stopped monitoring the instance
38 var stateString = map[State]string{
39 StateUnknown: "unknown",
40 StateBooting: "booting",
42 StateRunning: "running",
43 StateShutdown: "shutdown",
46 // String implements fmt.Stringer.
47 func (s State) String() string {
51 // MarshalText implements encoding.TextMarshaler so a JSON encoding of
52 // map[State]anything uses the state's string representation.
53 func (s State) MarshalText() ([]byte, error) {
54 return []byte(stateString[s]), nil
57 // BootOutcome is the result of a worker boot. It is used as a label in a metric.
58 type BootOutcome string
61 BootOutcomeFailed BootOutcome = "failure"
62 BootOutcomeSucceeded BootOutcome = "success"
63 BootOutcomeAborted BootOutcome = "aborted"
64 BootOutcomeDisappeared BootOutcome = "disappeared"
67 var validBootOutcomes = map[BootOutcome]bool{
68 BootOutcomeFailed: true,
69 BootOutcomeSucceeded: true,
70 BootOutcomeAborted: true,
71 BootOutcomeDisappeared: true,
74 // IdleBehavior indicates the behavior desired when a node becomes idle.
75 type IdleBehavior string
78 IdleBehaviorRun IdleBehavior = "run" // run containers, or shutdown on idle timeout
79 IdleBehaviorHold IdleBehavior = "hold" // don't shutdown or run more containers
80 IdleBehaviorDrain IdleBehavior = "drain" // shutdown immediately when idle
83 var validIdleBehavior = map[IdleBehavior]bool{
84 IdleBehaviorRun: true,
85 IdleBehaviorHold: true,
86 IdleBehaviorDrain: true,
90 logger logrus.FieldLogger
94 mtx sync.Locker // must be wp's Locker.
96 idleBehavior IdleBehavior
97 instance cloud.Instance
98 instType arvados.InstanceType
107 running map[string]*remoteRunner // remember to update state idle<->running when this changes
108 starting map[string]*remoteRunner // remember to update state idle<->running when this changes
109 probing chan struct{}
110 bootOutcomeReported bool
113 func (wkr *worker) onUnkillable(uuid string) {
115 defer wkr.mtx.Unlock()
116 logger := wkr.logger.WithField("ContainerUUID", uuid)
117 if wkr.idleBehavior == IdleBehaviorHold {
118 logger.Warn("unkillable container, but worker has IdleBehavior=Hold")
121 logger.Warn("unkillable container, draining worker")
122 wkr.setIdleBehavior(IdleBehaviorDrain)
125 func (wkr *worker) onKilled(uuid string) {
127 defer wkr.mtx.Unlock()
128 wkr.closeRunner(uuid)
132 // caller must have lock.
133 func (wkr *worker) reportBootOutcome(outcome BootOutcome) {
134 if wkr.bootOutcomeReported {
137 if wkr.wp.mBootOutcomes != nil {
138 wkr.wp.mBootOutcomes.WithLabelValues(string(outcome)).Inc()
140 wkr.bootOutcomeReported = true
143 // caller must have lock.
144 func (wkr *worker) setIdleBehavior(idleBehavior IdleBehavior) {
145 wkr.logger.WithField("IdleBehavior", idleBehavior).Info("set idle behavior")
146 wkr.idleBehavior = idleBehavior
151 // caller must have lock.
152 func (wkr *worker) startContainer(ctr arvados.Container) {
153 logger := wkr.logger.WithFields(logrus.Fields{
154 "ContainerUUID": ctr.UUID,
155 "Priority": ctr.Priority,
157 logger.Debug("starting container")
158 rr := newRemoteRunner(ctr.UUID, wkr)
159 wkr.starting[ctr.UUID] = rr
160 if wkr.state != StateRunning {
161 wkr.state = StateRunning
167 defer wkr.mtx.Unlock()
171 delete(wkr.starting, ctr.UUID)
172 wkr.running[ctr.UUID] = rr
173 wkr.lastUUID = ctr.UUID
177 // ProbeAndUpdate conducts appropriate boot/running probes (if any)
178 // for the worker's curent state. If a previous probe is still
179 // running, it does nothing.
181 // It should be called in a new goroutine.
182 func (wkr *worker) ProbeAndUpdate() {
184 case wkr.probing <- struct{}{}:
188 wkr.logger.Debug("still waiting for last probe to finish")
192 // probeAndUpdate calls probeBooted and/or probeRunning if needed, and
193 // updates state accordingly.
195 // In StateUnknown: Call both probeBooted and probeRunning.
196 // In StateBooting: Call probeBooted; if successful, call probeRunning.
197 // In StateRunning: Call probeRunning.
198 // In StateIdle: Call probeRunning.
199 // In StateShutdown: Do nothing.
201 // If both probes succeed, wkr.state changes to
202 // StateIdle/StateRunning.
204 // If probeRunning succeeds, wkr.running is updated. (This means
205 // wkr.running might be non-empty even in StateUnknown, if the boot
208 // probeAndUpdate should be called in a new goroutine.
209 func (wkr *worker) probeAndUpdate() {
211 updated := wkr.updated
212 initialState := wkr.state
219 stderr []byte // from probeBooted
222 switch initialState {
225 case StateIdle, StateRunning:
227 case StateUnknown, StateBooting:
229 panic(fmt.Sprintf("unknown state %s", initialState))
232 probeStart := time.Now()
233 logger := wkr.logger.WithField("ProbeStart", probeStart)
236 booted, stderr = wkr.probeBooted()
238 // Pretend this probe succeeded if another
239 // concurrent attempt succeeded.
241 booted = wkr.state == StateRunning || wkr.state == StateIdle
245 logger.Info("instance booted; will try probeRunning")
248 reportedBroken := false
249 if booted || wkr.state == StateUnknown {
250 ctrUUIDs, reportedBroken, ok = wkr.probeRunning()
253 defer wkr.mtx.Unlock()
254 if reportedBroken && wkr.idleBehavior == IdleBehaviorRun {
255 logger.Info("probe reported broken instance")
256 wkr.reportBootOutcome(BootOutcomeFailed)
257 wkr.setIdleBehavior(IdleBehaviorDrain)
259 if !ok || (!booted && len(ctrUUIDs) == 0 && len(wkr.running) == 0) {
260 if wkr.state == StateShutdown && wkr.updated.After(updated) {
261 // Skip the logging noise if shutdown was
262 // initiated during probe.
265 // Using the start time of the probe as the timeout
266 // threshold ensures we always initiate at least one
267 // probe attempt after the boot/probe timeout expires
268 // (otherwise, a slow probe failure could cause us to
269 // shutdown an instance even though it did in fact
270 // boot/recover before the timeout expired).
271 dur := probeStart.Sub(wkr.probed)
272 if wkr.shutdownIfBroken(dur) {
273 // stderr from failed run-probes will have
274 // been logged already, but boot-probe
275 // failures are normal so they are logged only
276 // at Debug level. This is our chance to log
277 // some evidence about why the node never
278 // booted, even in non-debug mode.
280 wkr.reportBootOutcome(BootOutcomeFailed)
281 logger.WithFields(logrus.Fields{
283 "stderr": string(stderr),
284 }).Info("boot failed")
290 updateTime := time.Now()
291 wkr.probed = updateTime
293 if updated != wkr.updated {
294 // Worker was updated after the probe began, so
295 // wkr.running might have a container UUID that was
296 // not yet running when ctrUUIDs was generated. Leave
297 // wkr.running alone and wait for the next probe to
298 // catch up on any changes.
302 if len(ctrUUIDs) > 0 {
303 wkr.busy = updateTime
304 wkr.lastUUID = ctrUUIDs[0]
305 } else if len(wkr.running) > 0 {
306 // Actual last-busy time was sometime between wkr.busy
307 // and now. Now is the earliest opportunity to take
308 // advantage of the non-busy state, though.
309 wkr.busy = updateTime
312 changed := wkr.updateRunning(ctrUUIDs)
314 // Update state if this was the first successful boot-probe.
315 if booted && (wkr.state == StateUnknown || wkr.state == StateBooting) {
316 // Note: this will change again below if
317 // len(wkr.starting)+len(wkr.running) > 0.
318 wkr.state = StateIdle
322 // If wkr.state and wkr.running aren't changing then there's
323 // no need to log anything, notify the scheduler, move state
324 // back and forth between idle/running, etc.
329 // Log whenever a run-probe reveals crunch-run processes
330 // appearing/disappearing before boot-probe succeeds.
331 if wkr.state == StateUnknown && changed {
332 logger.WithFields(logrus.Fields{
333 "RunningContainers": len(wkr.running),
335 }).Info("crunch-run probe succeeded, but boot probe is still failing")
338 if wkr.state == StateIdle && len(wkr.starting)+len(wkr.running) > 0 {
339 wkr.state = StateRunning
340 } else if wkr.state == StateRunning && len(wkr.starting)+len(wkr.running) == 0 {
341 wkr.state = StateIdle
343 wkr.updated = updateTime
344 if booted && (initialState == StateUnknown || initialState == StateBooting) {
345 wkr.reportBootOutcome(BootOutcomeSucceeded)
346 logger.WithFields(logrus.Fields{
347 "RunningContainers": len(wkr.running),
349 }).Info("probes succeeded, instance is in service")
354 func (wkr *worker) probeRunning() (running []string, reportsBroken, ok bool) {
355 cmd := wkr.wp.runnerCmd + " --list"
356 if u := wkr.instance.RemoteUser(); u != "root" {
359 stdout, stderr, err := wkr.executor.Execute(nil, cmd, nil)
361 wkr.logger.WithFields(logrus.Fields{
363 "stdout": string(stdout),
364 "stderr": string(stderr),
365 }).WithError(err).Warn("probe failed")
369 for _, s := range strings.Split(string(stdout), "\n") {
373 running = append(running, s)
379 func (wkr *worker) probeBooted() (ok bool, stderr []byte) {
380 cmd := wkr.wp.bootProbeCommand
384 stdout, stderr, err := wkr.executor.Execute(nil, cmd, nil)
385 logger := wkr.logger.WithFields(logrus.Fields{
387 "stdout": string(stdout),
388 "stderr": string(stderr),
391 logger.WithError(err).Debug("boot probe failed")
394 logger.Info("boot probe succeeded")
395 if err = wkr.wp.loadRunnerData(); err != nil {
396 wkr.logger.WithError(err).Warn("cannot boot worker: error loading runner binary")
398 } else if len(wkr.wp.runnerData) == 0 {
399 // Assume crunch-run is already installed
400 } else if _, stderr2, err := wkr.copyRunnerData(); err != nil {
401 wkr.logger.WithError(err).WithField("stderr", string(stderr2)).Warn("error copying runner binary")
402 return false, stderr2
404 stderr = append(stderr, stderr2...)
409 func (wkr *worker) copyRunnerData() (stdout, stderr []byte, err error) {
410 hash := fmt.Sprintf("%x", wkr.wp.runnerMD5)
411 dstdir, _ := filepath.Split(wkr.wp.runnerCmd)
412 logger := wkr.logger.WithFields(logrus.Fields{
414 "path": wkr.wp.runnerCmd,
417 stdout, stderr, err = wkr.executor.Execute(nil, `md5sum `+wkr.wp.runnerCmd, nil)
418 if err == nil && len(stderr) == 0 && bytes.Equal(stdout, []byte(hash+" "+wkr.wp.runnerCmd+"\n")) {
419 logger.Info("runner binary already exists on worker, with correct hash")
423 // Note touch+chmod come before writing data, to avoid the
424 // possibility of md5 being correct while file mode is
426 cmd := `set -e; dstdir="` + dstdir + `"; dstfile="` + wkr.wp.runnerCmd + `"; mkdir -p "$dstdir"; touch "$dstfile"; chmod 0755 "$dstdir" "$dstfile"; cat >"$dstfile"`
427 if wkr.instance.RemoteUser() != "root" {
428 cmd = `sudo sh -c '` + strings.Replace(cmd, "'", "'\\''", -1) + `'`
430 logger.WithField("cmd", cmd).Info("installing runner binary on worker")
431 stdout, stderr, err = wkr.executor.Execute(nil, cmd, bytes.NewReader(wkr.wp.runnerData))
435 // caller must have lock.
436 func (wkr *worker) shutdownIfBroken(dur time.Duration) bool {
437 if wkr.idleBehavior == IdleBehaviorHold {
441 label, threshold := "", wkr.wp.timeoutProbe
442 if wkr.state == StateUnknown || wkr.state == StateBooting {
443 label, threshold = "new ", wkr.wp.timeoutBooting
448 wkr.logger.WithFields(logrus.Fields{
452 }).Warnf("%sinstance unresponsive, shutting down", label)
457 // Returns true if the instance is eligible for shutdown: either it's
458 // been idle too long, or idleBehavior=Drain and nothing is running.
460 // caller must have lock.
461 func (wkr *worker) eligibleForShutdown() bool {
462 if wkr.idleBehavior == IdleBehaviorHold {
465 draining := wkr.idleBehavior == IdleBehaviorDrain
470 return draining || time.Since(wkr.busy) >= wkr.wp.timeoutIdle
475 for _, rr := range wkr.running {
480 for _, rr := range wkr.starting {
485 // draining, and all remaining runners are just trying
486 // to force-kill their crunch-run procs
493 // caller must have lock.
494 func (wkr *worker) shutdownIfIdle() bool {
495 if !wkr.eligibleForShutdown() {
498 wkr.logger.WithFields(logrus.Fields{
500 "IdleDuration": stats.Duration(time.Since(wkr.busy)),
501 "IdleBehavior": wkr.idleBehavior,
502 }).Info("shutdown worker")
503 wkr.reportBootOutcome(BootOutcomeAborted)
508 // caller must have lock.
509 func (wkr *worker) shutdown() {
513 wkr.state = StateShutdown
516 err := wkr.instance.Destroy()
518 wkr.logger.WithError(err).Warn("shutdown failed")
524 // Save worker tags to cloud provider metadata, if they don't already
525 // match. Caller must have lock.
526 func (wkr *worker) saveTags() {
527 instance := wkr.instance
528 tags := instance.Tags()
529 update := cloud.InstanceTags{
530 wkr.wp.tagKeyPrefix + tagKeyInstanceType: wkr.instType.Name,
531 wkr.wp.tagKeyPrefix + tagKeyIdleBehavior: string(wkr.idleBehavior),
534 for k, v := range update {
542 err := instance.SetTags(tags)
544 wkr.wp.logger.WithField("Instance", instance.ID()).WithError(err).Warnf("error updating tags")
550 func (wkr *worker) Close() {
551 // This might take time, so do it after unlocking mtx.
552 defer wkr.executor.Close()
555 defer wkr.mtx.Unlock()
556 for uuid, rr := range wkr.running {
557 wkr.logger.WithField("ContainerUUID", uuid).Info("crunch-run process abandoned")
560 for uuid, rr := range wkr.starting {
561 wkr.logger.WithField("ContainerUUID", uuid).Info("crunch-run process abandoned")
566 // Add/remove entries in wkr.running to match ctrUUIDs returned by a
567 // probe. Returns true if anything was added or removed.
569 // Caller must have lock.
570 func (wkr *worker) updateRunning(ctrUUIDs []string) (changed bool) {
571 alive := map[string]bool{}
572 for _, uuid := range ctrUUIDs {
574 if _, ok := wkr.running[uuid]; ok {
576 } else if rr, ok := wkr.starting[uuid]; ok {
577 wkr.running[uuid] = rr
578 delete(wkr.starting, uuid)
581 // We didn't start it -- it must have been
582 // started by a previous dispatcher process.
583 wkr.logger.WithField("ContainerUUID", uuid).Info("crunch-run process detected")
584 wkr.running[uuid] = newRemoteRunner(uuid, wkr)
588 for uuid := range wkr.running {
590 wkr.closeRunner(uuid)
597 // caller must have lock.
598 func (wkr *worker) closeRunner(uuid string) {
599 rr := wkr.running[uuid]
603 wkr.logger.WithField("ContainerUUID", uuid).Info("crunch-run process ended")
604 delete(wkr.running, uuid)
609 wkr.wp.exited[uuid] = now
610 if wkr.state == StateRunning && len(wkr.running)+len(wkr.starting) == 0 {
611 wkr.state = StateIdle