// cleanup() has a windows-specific implementation which finds the job object associated with the // given task key, and if it exists, terminates it. This will guarantee that any shell processes // started throughout the task run are destroyed, as long as they were captured in trackProcess. func cleanup(key string, log plugin.Logger) error { jobsMutex.Lock() defer jobsMutex.Unlock() job, hasKey := jobsMapping[key] if !hasKey { return nil } err := job.Terminate(0) if err != nil { log.LogSystem(slogger.ERROR, "terminating job object failed: %v", err) return err } delete(jobsMapping, key) defer job.Close() return nil }
func cleanup(key string, log plugin.Logger) error { pids, err := listProc() if err != nil { return err } pidMarker := fmt.Sprintf("EVR_AGENT_PID=%v", os.Getpid()) taskMarker := fmt.Sprintf("EVR_TASK_ID=%v", key) for _, pid := range pids { env, err := getEnv(pid) if err != nil { continue } if envHasMarkers(env, pidMarker, taskMarker) { p := os.Process{} p.Pid = pid if err := p.Kill(); err != nil { log.LogSystem(slogger.INFO, "Cleanup killing %v failed: %v", pid, err) } else { log.LogTask(slogger.INFO, "Cleanup killed process %v", pid) } } } return nil }
// This windows-specific specific implementation of trackProcess associates the given pid with a // job object, which can later be used by "cleanup" to terminate all members of the job object at // once. If a job object doesn't already exist, it will create one automatically, scoped by the // task ID for which the shell process was started. func trackProcess(taskId string, pid int, log plugin.Logger) error { jobsMutex.Lock() defer jobsMutex.Unlock() var job *Job var err error // If we have already created an existing job object for this task, find it if jobObj, hasKey := jobsMapping[taskId]; hasKey { job = jobObj } else { log.LogSystem(slogger.INFO, "tracking process with pid %v", pid) // Job object does not exist yet for this task, so we must create one job, err = NewJob(taskId) if err != nil { log.LogSystem(slogger.ERROR, "failed creating job object: %v", err) return err } jobsMapping[taskId] = job } err = job.AssignProcess(uint(pid)) if err != nil { log.LogSystem(slogger.ERROR, "failed assigning process %v to job object: %v", pid, err) } return err }
func cleanup(key string, log plugin.Logger) error { /* Usage of ps on OSX for extracting environment variables: -E: print the environment of the process (VAR1=FOO VAR2=BAR ...) -e: list *all* processes, not just ones that we own -o: print output according to the given format. We supply 'pid,command' so that only those two columns are printed, and then we extract their values using the regexes. Each line of output has a format with the pid, command, and environment, e.g.: 1084 foo.sh PATH=/usr/bin/sbin TMPDIR=/tmp LOGNAME=xxx */ out, err := exec.Command("ps", "-E", "-e", "-o", "pid,command").CombinedOutput() if err != nil { log.LogSystem(slogger.ERROR, "cleanup failed to get output of 'ps': %v", err) return err } myPid := fmt.Sprintf("%v", os.Getpid()) pidsToKill := []int{} lines := strings.Split(string(out), "\n") // Look through the output of the "ps" command and find the processes we need to kill. for _, line := range lines { // Use the regexes to extract the fields look for our 'tracer' variables matchTask := taskEnvRegex.FindStringSubmatch(line) matchAgent := agentPidRegex.FindStringSubmatch(line) if matchTask == nil || matchAgent == nil { continue } pidStr := matchTask[1] taskId := matchTask[2] agentPid := matchAgent[2] // If the process is from a different task, agent process, // or is the agent itself, leave it alone. if pidStr == myPid || taskId != key || agentPid != myPid { continue } // Otherwise add it to the list of processes to clean up pidAsInt, err := strconv.Atoi(pidStr) if err != nil { continue } pidsToKill = append(pidsToKill, pidAsInt) } // Iterate through the list of processes to kill that we just built, and actually kill them. for _, pid := range pidsToKill { p := os.Process{} p.Pid = pid err := p.Kill() if err != nil { log.LogSystem(slogger.ERROR, "Cleanup got error killing pid %v: %v", pid, err) } else { log.LogSystem(slogger.INFO, "Cleanup killed pid %v", pid) } } return nil }
// Execute starts the shell with its given parameters. func (self *ShellExecCommand) Execute(pluginLogger plugin.Logger, pluginCom plugin.PluginCommunicator, conf *model.TaskConfig, stop chan bool) error { pluginLogger.LogExecution(slogger.DEBUG, "Preparing script...") logWriterInfo := pluginLogger.GetTaskLogWriter(slogger.INFO) logWriterErr := pluginLogger.GetTaskLogWriter(slogger.ERROR) outBufferWriter := util.NewLineBufferingWriter(logWriterInfo) errorBufferWriter := util.NewLineBufferingWriter(logWriterErr) defer outBufferWriter.Flush() defer errorBufferWriter.Flush() localCmd := &command.LocalCommand{ CmdString: self.Script, Stdout: outBufferWriter, Stderr: errorBufferWriter, ScriptMode: true, } if self.WorkingDir != "" { localCmd.WorkingDirectory = filepath.Join(conf.WorkDir, self.WorkingDir) } else { localCmd.WorkingDirectory = conf.WorkDir } err := localCmd.PrepToRun(conf.Expansions) if err != nil { return fmt.Errorf("Failed to apply expansions: %v", err) } if self.Silent { pluginLogger.LogExecution(slogger.INFO, "Executing script (source hidden)...") } else { pluginLogger.LogExecution(slogger.INFO, "Executing script: %v", localCmd.CmdString) } doneStatus := make(chan error) go func() { var err error env := os.Environ() env = append(env, fmt.Sprintf("EVR_TASK_ID=%v", conf.Task.Id)) env = append(env, fmt.Sprintf("EVR_AGENT_PID=%v", os.Getpid())) localCmd.Environment = env err = localCmd.Start() if err == nil { pluginLogger.LogSystem(slogger.DEBUG, "spawned shell process with pid %v", localCmd.Cmd.Process.Pid) // Call the platform's process-tracking function. On some OSes this will be a noop, // on others this may need to do some additional work to track the process so that // it can be cleaned up later. if trackedTask != "" && trackedTask == conf.Task.Id { trackProcess(conf.Task.Id, localCmd.Cmd.Process.Pid, pluginLogger) } if !self.Background { err = localCmd.Cmd.Wait() } } else { pluginLogger.LogSystem(slogger.DEBUG, "error spawning shell process: %v", err) } doneStatus <- err }() defer pluginLogger.Flush() select { case err = <-doneStatus: if err != nil { if self.ContinueOnError { pluginLogger.LogExecution(slogger.INFO, "(ignoring) Script finished with error: %v", err) return nil } else { pluginLogger.LogExecution(slogger.INFO, "Script finished with error: %v", err) return err } } else { pluginLogger.LogExecution(slogger.INFO, "Script execution complete.") } case <-stop: pluginLogger.LogExecution(slogger.INFO, "Got kill signal") // need to check command has started if localCmd.Cmd != nil { pluginLogger.LogExecution(slogger.INFO, "Stopping process: %v", localCmd.Cmd.Process.Pid) // try and stop the process if err := localCmd.Stop(); err != nil { pluginLogger.LogExecution(slogger.ERROR, "Error occurred stopping process: %v", err) } } return fmt.Errorf("Shell command interrupted.") } return nil }