X-Git-Url: https://git.arvados.org/arvados.git/blobdiff_plain/4c1281bba5d3e01d677165b6e2fa7d9209e233b5..4e2763883588ac691da65ee316a52a052c002aa7:/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 e575839040..848d723380 100644 --- a/services/crunch-dispatch-local/crunch-dispatch-local.go +++ b/services/crunch-dispatch-local/crunch-dispatch-local.go @@ -7,6 +7,7 @@ import ( "os" "os/exec" "os/signal" + "sync" "syscall" "time" ) @@ -18,8 +19,14 @@ func main() { } } -var arv arvadosclient.ArvadosClient -var runningCmds map[string]*exec.Cmd +var ( + arv arvadosclient.ArvadosClient + runningCmds map[string]*exec.Cmd + runningCmdsMutex sync.Mutex + waitGroup sync.WaitGroup + doneProcessing chan bool + sigChan chan os.Signal +) func doMain() error { flags := flag.NewFlagSet("crunch-dispatch-local", flag.ExitOnError) @@ -48,41 +55,44 @@ func doMain() error { return err } + // Channel to terminate + doneProcessing = make(chan bool) + + // Map of running crunch jobs runningCmds = make(map[string]*exec.Cmd) + + // 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 - caught := sig - for uuid, cmd := range runningCmds { - 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) - } - } } }(sigChan) - // channel to terminate - doneProcessing = make(chan bool) + // Run all queued containers + runQueuedContainers(time.Duration(*pollInterval)*time.Second, time.Duration(*priorityPollInterval)*time.Second, *crunchRunCommand) + + // Finished dispatching; interrupt any crunch jobs that are still running + for _, cmd := range runningCmds { + cmd.Process.Signal(os.Interrupt) + } + + // Wait for all running crunch jobs to complete / terminate + waitGroup.Wait() - // run all queued containers - runQueuedContainers(*pollInterval, *priorityPollInterval, *crunchRunCommand) return nil } -var doneProcessing chan bool -var sigChan chan os.Signal - // 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, +// This is because, once one or more crunch jobs 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) +func runQueuedContainers(pollInterval, priorityPollInterval time.Duration, crunchRunCommand string) { + ticker := time.NewTicker(pollInterval) for { select { @@ -97,9 +107,10 @@ func runQueuedContainers(pollInterval, priorityPollInterval int, crunchRunComman // Container data type Container struct { - UUID string `json:"uuid"` - State string `json:"state"` - Priority int `json:"priority"` + 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 @@ -108,7 +119,7 @@ type ContainerList struct { } // Get the list of queued containers from API server and invoke run for each container. -func dispatchLocal(priorityPollInterval int, crunchRunCommand string) { +func dispatchLocal(pollInterval time.Duration, crunchRunCommand string) { params := arvadosclient.Dict{ "filters": [][]string{[]string{"state", "=", "Queued"}}, } @@ -122,78 +133,118 @@ func dispatchLocal(priorityPollInterval int, crunchRunCommand string) { 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) + // Run the container + go run(containers.Items[i].UUID, crunchRunCommand, pollInterval) } } +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 +} + // Run queued container: -// Set container state to locked (TBD) +// 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, priorityPollInterval int) { - cmd := exec.Command(crunchRunCommand, uuid) +func run(uuid string, crunchRunCommand string, pollInterval time.Duration) { + if err := updateState(uuid, "Locked"); err != nil { + return + } + 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 running container for %v: %q", uuid, err) + log.Printf("Error starting crunch-run for %v: %q", uuid, err) + runningCmdsMutex.Unlock() + updateState(uuid, "Queued") return } - runningCmds[uuid] = cmd + runningCmdsMutex.Unlock() - log.Printf("Started container run for %v", uuid) + defer func() { + setFinalState(uuid) - 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) - } + // Remove the crunch job from runningCmds + runningCmdsMutex.Lock() + delete(runningCmds, uuid) + runningCmdsMutex.Unlock() + }() + + log.Printf("Starting container %v", uuid) - // Terminate the runner if container priority becomes zero - priorityTicker := time.NewTicker(time.Duration(priorityPollInterval) * time.Second) + // Add this crunch job to waitGroup + waitGroup.Add(1) + defer waitGroup.Done() + + updateState(uuid, "Running") + + cmdExited := make(chan struct{}) + + // Kill the child process if container priority changes to zero go func() { + ticker := time.NewTicker(pollInterval) + defer ticker.Stop() 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() - cmd.Process.Signal(os.Interrupt) - delete(runningCmds, uuid) - return - } - } + 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) } } }() - // Wait for the process to exit + // Wait for crunch-run to exit if _, err := cmd.Process.Wait(); err != nil { - log.Printf("Error while waiting for process to finish for %v: %q", uuid, err) + log.Printf("Error while waiting for crunch job to finish for %v: %q", uuid, err) } - delete(runningCmds, uuid) + close(cmdExited) - priorityTicker.Stop() + 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 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) - } + err := 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 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) } }