1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
7 // Dispatcher service for Crunch that runs containers locally.
20 "git.arvados.org/arvados.git/lib/config"
21 "git.arvados.org/arvados.git/sdk/go/arvados"
22 "git.arvados.org/arvados.git/sdk/go/arvadosclient"
23 "git.arvados.org/arvados.git/sdk/go/dispatch"
24 "github.com/sirupsen/logrus"
32 logrus.Fatalf("%q", err)
37 runningCmds map[string]*exec.Cmd
38 runningCmdsMutex sync.Mutex
39 waitGroup sync.WaitGroup
40 crunchRunCommand *string
44 logger := logrus.StandardLogger()
45 if os.Getenv("DEBUG") != "" {
46 logger.SetLevel(logrus.DebugLevel)
48 logger.Formatter = &logrus.JSONFormatter{
49 TimestampFormat: "2006-01-02T15:04:05.000000000Z07:00",
52 flags := flag.NewFlagSet("crunch-dispatch-local", flag.ExitOnError)
54 pollInterval := flags.Int(
57 "Interval in seconds to poll for queued containers")
59 crunchRunCommand = flags.String(
61 "/usr/bin/crunch-run",
62 "Crunch command to run container")
64 getVersion := flags.Bool(
67 "Print version information and exit.")
69 // Parse args; omit the first arg which is the command name
70 flags.Parse(os.Args[1:])
72 // Print version information if requested
74 fmt.Printf("crunch-dispatch-local %s\n", version)
78 loader := config.NewLoader(nil, logger)
79 cfg, err := loader.Load()
80 cluster, err := cfg.GetCluster("")
82 return fmt.Errorf("config error: %s", err)
85 logger.Printf("crunch-dispatch-local %s started", version)
87 runningCmds = make(map[string]*exec.Cmd)
89 var client arvados.Client
90 client.APIHost = cluster.Services.Controller.ExternalURL.Host
91 client.AuthToken = cluster.SystemRootToken
92 client.Insecure = cluster.TLS.Insecure
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", "")
102 os.Setenv("ARVADOS_API_HOST_INSECURE", "1")
104 os.Setenv("ARVADOS_EXTERNAL_CLIENT", "")
106 logger.Warnf("Client credentials missing from config, so falling back on environment variables (deprecated).")
109 arv, err := arvadosclient.MakeArvadosClient()
111 logger.Errorf("error making Arvados client: %v", err)
116 ctx, cancel := context.WithCancel(context.Background())
118 dispatcher := dispatch.Dispatcher{
121 RunContainer: (&LocalRun{startFunc, make(chan bool, 8), ctx, cluster}).run,
122 PollPeriod: time.Duration(*pollInterval) * time.Second,
125 err = dispatcher.Run(ctx)
130 c := make(chan os.Signal, 1)
131 signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)
133 logger.Printf("Received %s, shutting down", sig)
138 runningCmdsMutex.Lock()
139 // Finished dispatching; interrupt any crunch jobs that are still running
140 for _, cmd := range runningCmds {
141 cmd.Process.Signal(os.Interrupt)
143 runningCmdsMutex.Unlock()
145 // Wait for all running crunch jobs to complete / terminate
151 func startFunc(container arvados.Container, cmd *exec.Cmd) error {
155 type LocalRun struct {
156 startCmd func(container arvados.Container, cmd *exec.Cmd) error
157 concurrencyLimit chan bool
159 cluster *arvados.Cluster
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.
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 {
174 uuid := container.UUID
176 if container.State == dispatch.Locked {
179 case lr.concurrencyLimit <- true:
181 case <-lr.ctx.Done():
185 defer func() { <-lr.concurrencyLimit }()
189 // Check for state updates after possibly
190 // waiting to be ready-to-run
199 defer waitGroup.Done()
201 cmd := exec.Command(*crunchRunCommand, "--runtime-engine="+lr.cluster.Containers.RuntimeEngine, uuid)
203 cmd.Stderr = os.Stderr
204 cmd.Stdout = os.Stderr
206 dispatcher.Logger.Printf("starting container %v", uuid)
208 // Add this crunch job to the list of runningCmds only if we
209 // succeed in starting crunch-run.
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)
217 runningCmds[uuid] = cmd
218 runningCmdsMutex.Unlock()
220 // Need to wait for crunch-run to exit
221 done := make(chan struct{})
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)
227 dispatcher.Logger.Debugf("sending done")
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)
246 dispatcher.Logger.Printf("finished container run for %v", uuid)
248 // Remove the crunch job from runningCmds
249 runningCmdsMutex.Lock()
250 delete(runningCmds, uuid)
251 runningCmdsMutex.Unlock()
257 // If the container is not finalized, then change it to "Cancelled".
258 err := dispatcher.Arv.Get("containers", uuid, nil, &container)
260 dispatcher.Logger.Warnf("error getting final container state: %v", err)
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)
268 // drain any subsequent status changes
272 dispatcher.Logger.Printf("finalized container %v", uuid)