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.curoverse.com/arvados.git/sdk/go/arvados"
21 "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
22 "git.curoverse.com/arvados.git/sdk/go/dispatch"
23 "github.com/sirupsen/logrus"
31 logrus.Fatalf("%q", err)
36 runningCmds map[string]*exec.Cmd
37 runningCmdsMutex sync.Mutex
38 waitGroup sync.WaitGroup
39 crunchRunCommand *string
43 logger := logrus.StandardLogger()
44 if os.Getenv("DEBUG") != "" {
45 logger.SetLevel(logrus.DebugLevel)
47 logger.Formatter = &logrus.JSONFormatter{
48 TimestampFormat: "2006-01-02T15:04:05.000000000Z07:00",
51 flags := flag.NewFlagSet("crunch-dispatch-local", flag.ExitOnError)
53 pollInterval := flags.Int(
56 "Interval in seconds to poll for queued containers")
58 crunchRunCommand = flags.String(
60 "/usr/bin/crunch-run",
61 "Crunch command to run container")
63 getVersion := flags.Bool(
66 "Print version information and exit.")
68 // Parse args; omit the first arg which is the command name
69 flags.Parse(os.Args[1:])
71 // Print version information if requested
73 fmt.Printf("crunch-dispatch-local %s\n", version)
77 logger.Printf("crunch-dispatch-local %s started", version)
79 runningCmds = make(map[string]*exec.Cmd)
81 arv, err := arvadosclient.MakeArvadosClient()
83 logger.Errorf("error making Arvados client: %v", err)
88 ctx, cancel := context.WithCancel(context.Background())
90 dispatcher := dispatch.Dispatcher{
93 RunContainer: (&LocalRun{startFunc, make(chan bool, 8), ctx}).run,
94 PollPeriod: time.Duration(*pollInterval) * time.Second,
97 err = dispatcher.Run(ctx)
102 c := make(chan os.Signal, 1)
103 signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)
105 logger.Printf("Received %s, shutting down", sig)
110 runningCmdsMutex.Lock()
111 // Finished dispatching; interrupt any crunch jobs that are still running
112 for _, cmd := range runningCmds {
113 cmd.Process.Signal(os.Interrupt)
115 runningCmdsMutex.Unlock()
117 // Wait for all running crunch jobs to complete / terminate
123 func startFunc(container arvados.Container, cmd *exec.Cmd) error {
127 type LocalRun struct {
128 startCmd func(container arvados.Container, cmd *exec.Cmd) error
129 concurrencyLimit chan bool
135 // If the container is Locked, start a new crunch-run process and wait until
136 // crunch-run completes. If the priority is set to zero, set an interrupt
137 // signal to the crunch-run process.
139 // If the container is in any other state, or is not Complete/Cancelled after
140 // crunch-run terminates, mark the container as Cancelled.
141 func (lr *LocalRun) run(dispatcher *dispatch.Dispatcher,
142 container arvados.Container,
143 status <-chan arvados.Container) {
145 uuid := container.UUID
147 if container.State == dispatch.Locked {
150 case lr.concurrencyLimit <- true:
152 case <-lr.ctx.Done():
156 defer func() { <-lr.concurrencyLimit }()
160 // Check for state updates after possibly
161 // waiting to be ready-to-run
170 defer waitGroup.Done()
172 cmd := exec.Command(*crunchRunCommand, uuid)
174 cmd.Stderr = os.Stderr
175 cmd.Stdout = os.Stderr
177 dispatcher.Logger.Printf("starting container %v", uuid)
179 // Add this crunch job to the list of runningCmds only if we
180 // succeed in starting crunch-run.
182 runningCmdsMutex.Lock()
183 if err := lr.startCmd(container, cmd); err != nil {
184 runningCmdsMutex.Unlock()
185 dispatcher.Logger.Warnf("error starting %q for %s: %s", *crunchRunCommand, uuid, err)
186 dispatcher.UpdateState(uuid, dispatch.Cancelled)
188 runningCmds[uuid] = cmd
189 runningCmdsMutex.Unlock()
191 // Need to wait for crunch-run to exit
192 done := make(chan struct{})
195 if _, err := cmd.Process.Wait(); err != nil {
196 dispatcher.Logger.Warnf("error while waiting for crunch job to finish for %v: %q", uuid, err)
198 dispatcher.Logger.Debugf("sending done")
208 // Interrupt the child process if priority changes to 0
209 if (c.State == dispatch.Locked || c.State == dispatch.Running) && c.Priority == 0 {
210 dispatcher.Logger.Printf("sending SIGINT to pid %d to cancel container %v", cmd.Process.Pid, uuid)
211 cmd.Process.Signal(os.Interrupt)
217 dispatcher.Logger.Printf("finished container run for %v", uuid)
219 // Remove the crunch job from runningCmds
220 runningCmdsMutex.Lock()
221 delete(runningCmds, uuid)
222 runningCmdsMutex.Unlock()
228 // If the container is not finalized, then change it to "Cancelled".
229 err := dispatcher.Arv.Get("containers", uuid, nil, &container)
231 dispatcher.Logger.Warnf("error getting final container state: %v", err)
233 if container.State == dispatch.Locked || container.State == dispatch.Running {
234 dispatcher.Logger.Warnf("after %q process termination, container state for %v is %q; updating it to %q",
235 *crunchRunCommand, uuid, container.State, dispatch.Cancelled)
236 dispatcher.UpdateState(uuid, dispatch.Cancelled)
239 // drain any subsequent status changes
243 dispatcher.Logger.Printf("finalized container %v", uuid)