Merge branch '13973-child-priority' refs #13973
[arvados.git] / services / crunch-dispatch-local / crunch-dispatch-local.go
index eb8550eceb8ebcaca25ace2ad2771a4bd587a227..fc10393626be103c17b01b5b1bfde615ed470bc9 100644 (file)
@@ -1,28 +1,53 @@
+// Copyright (C) The Arvados Authors. All rights reserved.
+//
+// SPDX-License-Identifier: AGPL-3.0
+
 package main
 
+// Dispatcher service for Crunch that runs containers locally.
+
 import (
+       "context"
        "flag"
-       "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
-       "log"
+       "fmt"
        "os"
        "os/exec"
        "os/signal"
        "sync"
        "syscall"
        "time"
+
+       "git.curoverse.com/arvados.git/sdk/go/arvados"
+       "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
+       "git.curoverse.com/arvados.git/sdk/go/dispatch"
+       "github.com/Sirupsen/logrus"
 )
 
+var version = "dev"
+
 func main() {
        err := doMain()
        if err != nil {
-               log.Fatalf("%q", err)
+               logrus.Fatalf("%q", err)
        }
 }
 
-var arv arvadosclient.ArvadosClient
-var runningCmds map[string]*exec.Cmd
+var (
+       runningCmds      map[string]*exec.Cmd
+       runningCmdsMutex sync.Mutex
+       waitGroup        sync.WaitGroup
+       crunchRunCommand *string
+)
 
 func doMain() error {
+       logger := logrus.StandardLogger()
+       if os.Getenv("DEBUG") != "" {
+               logger.SetLevel(logrus.DebugLevel)
+       }
+       logger.Formatter = &logrus.JSONFormatter{
+               TimestampFormat: "2006-01-02T15:04:05.000000000Z07:00",
+       }
+
        flags := flag.NewFlagSet("crunch-dispatch-local", flag.ExitOnError)
 
        pollInterval := flags.Int(
@@ -30,177 +55,162 @@ func doMain() error {
                10,
                "Interval in seconds to poll for queued containers")
 
-       priorityPollInterval := flags.Int(
-               "container-priority-poll-interval",
-               60,
-               "Interval in seconds to check priority of a dispatched container")
-
-       crunchRunCommand := flags.String(
+       crunchRunCommand = flags.String(
                "crunch-run-command",
                "/usr/bin/crunch-run",
                "Crunch command to run container")
 
+       getVersion := flags.Bool(
+               "version",
+               false,
+               "Print version information and exit.")
+
        // Parse args; omit the first arg which is the command name
        flags.Parse(os.Args[1:])
 
-       var err error
-       arv, err = arvadosclient.MakeArvadosClient()
-       if err != nil {
-               return err
+       // Print version information if requested
+       if *getVersion {
+               fmt.Printf("crunch-dispatch-local %s\n", version)
+               return nil
        }
 
-       runningCmds = make(map[string]*exec.Cmd)
-       sigChan = make(chan os.Signal, 1)
-       signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT)
-       go func(sig <-chan os.Signal) {
-               var wg sync.WaitGroup
-               for sig := range sig {
-                       doneProcessing <- true
-                       caught := sig
-                       for uuid, cmd := range runningCmds {
-                               go func(uuid string) {
-                                       wg.Add(1)
-                                       defer wg.Done()
-                                       cmd.Process.Signal(caught)
-                                       if _, err := cmd.Process.Wait(); err != nil {
-                                               log.Printf("Error while waiting for process to finish for %v: %q", uuid, err)
-                                       }
-                               }(uuid)
-                       }
-               }
-               wg.Wait()
-       }(sigChan)
-
-       // channel to terminate
-       doneProcessing = make(chan bool)
+       logger.Printf("crunch-dispatch-local %s started", version)
 
-       // run all queued containers
-       runQueuedContainers(*pollInterval, *priorityPollInterval, *crunchRunCommand)
-       return nil
-}
-
-var doneProcessing chan bool
-var sigChan chan os.Signal
+       runningCmds = make(map[string]*exec.Cmd)
 
-// Poll for queued containers using pollInterval.
-// Invoke dispatchLocal for each ticker cycle, which will run all the queued containers.
-//
-// Any errors encountered are logged but the program would continue to run (not exit).
-// This is because, once one or more child processes are running,
-// we would need to wait for them complete.
-func runQueuedContainers(pollInterval, priorityPollInterval int, crunchRunCommand string) {
-       ticker := time.NewTicker(time.Duration(pollInterval) * time.Second)
-
-       for {
-               select {
-               case <-ticker.C:
-                       dispatchLocal(priorityPollInterval, crunchRunCommand)
-               case <-doneProcessing:
-                       ticker.Stop()
-                       return
-               }
+       arv, err := arvadosclient.MakeArvadosClient()
+       if err != nil {
+               logger.Errorf("error making Arvados client: %v", err)
+               return err
        }
-}
-
-// Container data
-type Container struct {
-       UUID     string `json:"uuid"`
-       State    string `json:"state"`
-       Priority int    `json:"priority"`
-}
+       arv.Retries = 25
 
-// ContainerList is a list of the containers from api
-type ContainerList struct {
-       Items []Container `json:"items"`
-}
-
-// Get the list of queued containers from API server and invoke run for each container.
-func dispatchLocal(priorityPollInterval int, crunchRunCommand string) {
-       params := arvadosclient.Dict{
-               "filters": [][]string{[]string{"state", "=", "Queued"}},
+       dispatcher := dispatch.Dispatcher{
+               Logger:       logger,
+               Arv:          arv,
+               RunContainer: run,
+               PollPeriod:   time.Duration(*pollInterval) * time.Second,
        }
 
-       var containers ContainerList
-       err := arv.List("containers", params, &containers)
+       ctx, cancel := context.WithCancel(context.Background())
+       err = dispatcher.Run(ctx)
        if err != nil {
-               log.Printf("Error getting list of queued containers: %q", err)
-               return
+               return err
        }
 
-       for i := 0; i < len(containers.Items); i++ {
-               log.Printf("About to run queued container %v", containers.Items[i].UUID)
-               go run(containers.Items[i].UUID, crunchRunCommand, priorityPollInterval)
-       }
-}
+       c := make(chan os.Signal, 1)
+       signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT)
+       sig := <-c
+       logger.Printf("Received %s, shutting down", sig)
+       signal.Stop(c)
 
-// Run queued container:
-// Set container state to locked (TBD)
-// Run container using the given crunch-run command
-// Set the container state to Running
-// If the container priority becomes zero while crunch job is still running, terminate it.
-func run(uuid string, crunchRunCommand string, priorityPollInterval int) {
-       cmd := exec.Command(crunchRunCommand, uuid)
-
-       cmd.Stdin = nil
-       cmd.Stderr = os.Stderr
-       cmd.Stdout = os.Stderr
-       if err := cmd.Start(); err != nil {
-               log.Printf("Error running container for %v: %q", uuid, err)
-               return
+       cancel()
+
+       runningCmdsMutex.Lock()
+       // Finished dispatching; interrupt any crunch jobs that are still running
+       for _, cmd := range runningCmds {
+               cmd.Process.Signal(os.Interrupt)
        }
+       runningCmdsMutex.Unlock()
 
-       runningCmds[uuid] = cmd
+       // Wait for all running crunch jobs to complete / terminate
+       waitGroup.Wait()
 
-       log.Printf("Started container run for %v", uuid)
+       return nil
+}
 
-       err := arv.Update("containers", uuid,
-               arvadosclient.Dict{
-                       "container": arvadosclient.Dict{"state": "Running"}},
-               nil)
-       if err != nil {
-               log.Printf("Error updating container state to 'Running' for %v: %q", uuid, err)
-       }
+func startFunc(container arvados.Container, cmd *exec.Cmd) error {
+       return cmd.Start()
+}
+
+var startCmd = startFunc
 
-       // Terminate the runner if container priority becomes zero
-       priorityTicker := time.NewTicker(time.Duration(priorityPollInterval) * time.Second)
-       go func() {
-               for {
-                       select {
-                       case <-priorityTicker.C:
-                               var container Container
-                               err := arv.Get("containers", uuid, nil, &container)
-                               if err != nil {
-                                       log.Printf("Error getting container info for %v: %q", uuid, err)
-                               } else {
-                                       if container.Priority == 0 {
-                                               priorityTicker.Stop()
+// Run a container.
+//
+// If the container is Locked, start a new crunch-run process and wait until
+// crunch-run completes.  If the priority is set to zero, set an interrupt
+// signal to the crunch-run process.
+//
+// If the container is in any other state, or is not Complete/Cancelled after
+// crunch-run terminates, mark the container as Cancelled.
+func run(dispatcher *dispatch.Dispatcher,
+       container arvados.Container,
+       status <-chan arvados.Container) {
+
+       uuid := container.UUID
+
+       if container.State == dispatch.Locked {
+               waitGroup.Add(1)
+
+               cmd := exec.Command(*crunchRunCommand, uuid)
+               cmd.Stdin = nil
+               cmd.Stderr = os.Stderr
+               cmd.Stdout = os.Stderr
+
+               dispatcher.Logger.Printf("starting container %v", uuid)
+
+               // Add this crunch job to the list of runningCmds only if we
+               // succeed in starting crunch-run.
+
+               runningCmdsMutex.Lock()
+               if err := startCmd(container, cmd); err != nil {
+                       runningCmdsMutex.Unlock()
+                       dispatcher.Logger.Warnf("error starting %q for %s: %s", *crunchRunCommand, uuid, err)
+                       dispatcher.UpdateState(uuid, dispatch.Cancelled)
+               } else {
+                       runningCmds[uuid] = cmd
+                       runningCmdsMutex.Unlock()
+
+                       // Need to wait for crunch-run to exit
+                       done := make(chan struct{})
+
+                       go func() {
+                               if _, err := cmd.Process.Wait(); err != nil {
+                                       dispatcher.Logger.Warnf("error while waiting for crunch job to finish for %v: %q", uuid, err)
+                               }
+                               dispatcher.Logger.Debugf("sending done")
+                               done <- struct{}{}
+                       }()
+
+               Loop:
+                       for {
+                               select {
+                               case <-done:
+                                       break Loop
+                               case c := <-status:
+                                       // Interrupt the child process if priority changes to 0
+                                       if (c.State == dispatch.Locked || c.State == dispatch.Running) && c.Priority == 0 {
+                                               dispatcher.Logger.Printf("sending SIGINT to pid %d to cancel container %v", cmd.Process.Pid, uuid)
                                                cmd.Process.Signal(os.Interrupt)
-                                               delete(runningCmds, uuid)
-                                               return
                                        }
                                }
                        }
+                       close(done)
+
+                       dispatcher.Logger.Printf("finished container run for %v", uuid)
+
+                       // Remove the crunch job from runningCmds
+                       runningCmdsMutex.Lock()
+                       delete(runningCmds, uuid)
+                       runningCmdsMutex.Unlock()
                }
-       }()
+               waitGroup.Done()
+       }
 
-       // Wait for the process to exit
-       if _, err := cmd.Process.Wait(); err != nil {
-               log.Printf("Error while waiting for process to finish for %v: %q", uuid, err)
+       // If the container is not finalized, then change it to "Cancelled".
+       err := dispatcher.Arv.Get("containers", uuid, nil, &container)
+       if err != nil {
+               dispatcher.Logger.Warnf("error getting final container state: %v", err)
        }
-       delete(runningCmds, uuid)
-
-       priorityTicker.Stop()
-
-       var container Container
-       err = arv.Get("containers", uuid, nil, &container)
-       if container.State == "Running" {
-               log.Printf("After crunch-run process termination, the state is still 'Running' for %v. Updating it to 'Complete'", uuid)
-               err = arv.Update("containers", uuid,
-                       arvadosclient.Dict{
-                               "container": arvadosclient.Dict{"state": "Complete"}},
-                       nil)
-               if err != nil {
-                       log.Printf("Error updating container state to Complete for %v: %q", uuid, err)
-               }
+       if container.State == dispatch.Locked || container.State == dispatch.Running {
+               dispatcher.Logger.Warnf("after %q process termination, container state for %v is %q; updating it to %q",
+                       *crunchRunCommand, uuid, container.State, dispatch.Cancelled)
+               dispatcher.UpdateState(uuid, dispatch.Cancelled)
        }
+
+       // drain any subsequent status changes
+       for range status {
+       }
+
+       dispatcher.Logger.Printf("finalized container %v", uuid)
 }