X-Git-Url: https://git.arvados.org/arvados.git/blobdiff_plain/8e5206a5b1910ee7bc1d0a45af754ce507a7f237..8734a7391a5672eebcdf572d93bae1b3ed1179c9:/services/crunch-dispatch-local/crunch-dispatch-local.go diff --git a/services/crunch-dispatch-local/crunch-dispatch-local.go b/services/crunch-dispatch-local/crunch-dispatch-local.go index 848d723380..bb3c05c7eb 100644 --- a/services/crunch-dispatch-local/crunch-dispatch-local.go +++ b/services/crunch-dispatch-local/crunch-dispatch-local.go @@ -1,8 +1,12 @@ package main +// Dispatcher service for Crunch that runs containers locally. + import ( "flag" + "git.curoverse.com/arvados.git/sdk/go/arvados" "git.curoverse.com/arvados.git/sdk/go/arvadosclient" + "git.curoverse.com/arvados.git/sdk/go/dispatch" "log" "os" "os/exec" @@ -20,12 +24,10 @@ func main() { } var ( - arv arvadosclient.ArvadosClient runningCmds map[string]*exec.Cmd runningCmdsMutex sync.Mutex waitGroup sync.WaitGroup - doneProcessing chan bool - sigChan chan os.Signal + crunchRunCommand *string ) func doMain() error { @@ -36,12 +38,7 @@ 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") @@ -49,35 +46,40 @@ func doMain() error { // Parse args; omit the first arg which is the command name flags.Parse(os.Args[1:]) - var err error - arv, err = arvadosclient.MakeArvadosClient() + runningCmds = make(map[string]*exec.Cmd) + + arv, err := arvadosclient.MakeArvadosClient() if err != nil { + log.Printf("Error making Arvados client: %v", err) return err } + arv.Retries = 25 - // Channel to terminate - doneProcessing = make(chan bool) + dispatcher := dispatch.Dispatcher{ + Arv: arv, + RunContainer: run, + PollPeriod: time.Duration(*pollInterval) * time.Second, + } - // Map of running crunch jobs - runningCmds = make(map[string]*exec.Cmd) + err = dispatcher.Run() + if err != nil { + return err + } - // Graceful shutdown - sigChan = make(chan os.Signal, 1) - signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGQUIT) - go func(sig <-chan os.Signal) { - for sig := range sig { - log.Printf("Caught signal: %v", sig) - doneProcessing <- true - } - }(sigChan) + c := make(chan os.Signal, 1) + signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGQUIT) + sig := <-c + log.Printf("Received %s, shutting down", sig) + signal.Stop(c) - // Run all queued containers - runQueuedContainers(time.Duration(*pollInterval)*time.Second, time.Duration(*priorityPollInterval)*time.Second, *crunchRunCommand) + dispatcher.Stop() + runningCmdsMutex.Lock() // Finished dispatching; interrupt any crunch jobs that are still running for _, cmd := range runningCmds { cmd.Process.Signal(os.Interrupt) } + runningCmdsMutex.Unlock() // Wait for all running crunch jobs to complete / terminate waitGroup.Wait() @@ -85,166 +87,99 @@ func doMain() error { return nil } -// 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 crunch jobs are running, -// we would need to wait for them complete. -func runQueuedContainers(pollInterval, priorityPollInterval time.Duration, crunchRunCommand string) { - ticker := time.NewTicker(pollInterval) - - for { - select { - case <-ticker.C: - dispatchLocal(priorityPollInterval, crunchRunCommand) - case <-doneProcessing: - ticker.Stop() - return - } - } +func startFunc(container arvados.Container, cmd *exec.Cmd) error { + return cmd.Start() } -// Container data -type Container struct { - UUID string `json:"uuid"` - State string `json:"state"` - Priority int `json:"priority"` - LockedByUUID string `json:"locked_by_uuid"` -} - -// 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(pollInterval time.Duration, crunchRunCommand string) { - params := arvadosclient.Dict{ - "filters": [][]string{[]string{"state", "=", "Queued"}}, - } - - var containers ContainerList - err := arv.List("containers", params, &containers) - if err != nil { - log.Printf("Error getting list of queued containers: %q", err) - return - } +var startCmd = startFunc - for i := 0; i < len(containers.Items); i++ { - log.Printf("About to run queued container %v", containers.Items[i].UUID) - // Run the container - go run(containers.Items[i].UUID, crunchRunCommand, pollInterval) - } -} +// 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) { -func updateState(uuid, newState string) error { - err := arv.Update("containers", uuid, - arvadosclient.Dict{ - "container": arvadosclient.Dict{"state": newState}}, - nil) - if err != nil { - log.Printf("Error updating container %s to '%s' state: %q", uuid, newState, err) - } - return err -} + uuid := container.UUID -// Run queued container: -// Set container state to Locked -// 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, pollInterval time.Duration) { - if err := updateState(uuid, "Locked"); err != nil { - return - } + if container.State == dispatch.Locked { + waitGroup.Add(1) - cmd := exec.Command(crunchRunCommand, uuid) - cmd.Stdin = nil - cmd.Stderr = os.Stderr - cmd.Stdout = os.Stderr + cmd := exec.Command(*crunchRunCommand, uuid) + cmd.Stdin = nil + cmd.Stderr = os.Stderr + cmd.Stdout = os.Stderr - // Add this crunch job to the list of runningCmds only if we - // succeed in starting crunch-run. - runningCmdsMutex.Lock() - if err := cmd.Start(); err != nil { - log.Printf("Error starting crunch-run for %v: %q", uuid, err) - runningCmdsMutex.Unlock() - updateState(uuid, "Queued") - return - } - runningCmds[uuid] = cmd - runningCmdsMutex.Unlock() + log.Printf("Starting container %v", uuid) - defer func() { - setFinalState(uuid) + // Add this crunch job to the list of runningCmds only if we + // succeed in starting crunch-run. - // Remove the crunch job from runningCmds runningCmdsMutex.Lock() - delete(runningCmds, uuid) - runningCmdsMutex.Unlock() - }() - - log.Printf("Starting container %v", uuid) - - // Add this crunch job to waitGroup - waitGroup.Add(1) - defer waitGroup.Done() - - updateState(uuid, "Running") + if err := startCmd(container, cmd); err != nil { + runningCmdsMutex.Unlock() + log.Printf("Error starting %v for %v: %q", *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 { + log.Printf("Error while waiting for crunch job to finish for %v: %q", uuid, err) + } + log.Printf("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 { + log.Printf("Sending SIGINT to pid %d to cancel container %v", cmd.Process.Pid, uuid) + cmd.Process.Signal(os.Interrupt) + } + } + } + close(done) - cmdExited := make(chan struct{}) + log.Printf("Finished container run for %v", uuid) - // Kill the child process if container priority changes to zero - go func() { - ticker := time.NewTicker(pollInterval) - defer ticker.Stop() - for { - select { - case <-cmdExited: - return - case <-ticker.C: - } - var container Container - err := arv.Get("containers", uuid, nil, &container) - if err != nil { - log.Printf("Error getting container %v: %q", uuid, err) - continue - } - if container.Priority == 0 { - log.Printf("Sending SIGINT to pid %d to cancel container %v", cmd.Process.Pid, uuid) - cmd.Process.Signal(os.Interrupt) - } + // Remove the crunch job from runningCmds + runningCmdsMutex.Lock() + delete(runningCmds, uuid) + runningCmdsMutex.Unlock() } - }() - - // Wait for crunch-run to exit - if _, err := cmd.Process.Wait(); err != nil { - log.Printf("Error while waiting for crunch job to finish for %v: %q", uuid, err) + waitGroup.Done() } - close(cmdExited) - - log.Printf("Finished container run for %v", uuid) -} -func setFinalState(uuid string) { - // The container state should now be 'Complete' if everything - // went well. If it started but crunch-run didn't change its - // final state to 'Running', fix that now. If it never even - // started, cancel it as unrunnable. (TODO: Requeue instead, - // and fix tests so they can tell something happened even if - // the final state is Queued.) - var container Container - err := arv.Get("containers", uuid, nil, &container) + // If the container is not finalized, then change it to "Cancelled". + err := dispatcher.Arv.Get("containers", uuid, nil, &container) if err != nil { log.Printf("Error getting final container state: %v", err) } - fixState := map[string]string{ - "Running": "Complete", - "Locked": "Cancelled", + if container.LockedByUUID == dispatcher.Auth.UUID && + (container.State == dispatch.Locked || container.State == dispatch.Running) { + log.Printf("After %s process termination, container state for %v is %q. Updating it to %q", + *crunchRunCommand, container.State, uuid, dispatch.Cancelled) + dispatcher.UpdateState(uuid, dispatch.Cancelled) } - if newState, ok := fixState[container.State]; ok { - log.Printf("After crunch-run process termination, the state is still '%s' for %v. Updating it to '%s'", container.State, uuid, newState) - updateState(uuid, newState) + + // drain any subsequent status changes + for range status { } + + log.Printf("Finalized container %v", uuid) }