// GetProcessList executes "SHOW PROCESSLIST" and returns the resultset.
9676
func GetProcessList(endpoint string) ([]Process, error) {
	var dataSet []map[string]string
	var err error
	if dataSet, err = readDataSet(endpoint, "SHOW PROCESSLIST"); err != nil {
		return nil, err
	}
	processes := make([]Process, 0, len(dataSet))
	for _, row := range dataSet {
		processes = append(processes,
			Process{
				ID:      getInt(row["Id"]),
				User:    row["User"],
				Host:    row["Host"],
				DB:      row["db"],
				Command: row["Command"],
				Time:    getInt(row["Time"]),
				State:   row["State"],
				Info:    row["Info"],
			},
		)
	}
	return processes, nil
}
980606
func GetProcessStartTime(pid int) (string, error) {
	stat, err := Stat(pid)
	if err != nil {
		return "", err
	}
	return fmt.Sprintf("%d", stat.StartTime), nil
}
1001272
func getCgroupProcs(dir string) ([]int, error) {
	procsFile := filepath.Join(dir, "cgroup.procs")
	f, err := os.Open(procsFile)
	if err != nil {
		if os.IsNotExist(err) {
			// The procsFile does not exist, So no pids attached to this directory
			return []int{}, nil
		}
		return nil, err
	}
	defer f.Close()

	s := bufio.NewScanner(f)
	out := []int{}
	for s.Scan() {
		if t := s.Text(); t != "" {
			pid, err := strconv.Atoi(t)
			if err != nil {
				return nil, fmt.Errorf("unexpected line in %v; could not convert to pid: %v", procsFile, err)
			}
			out = append(out, pid)
		}
	}
	return out, nil
}
680174
func (impl *repoImpl) runProcessorsTask(c context.Context, t *tasks.RunProcessors) error {
	// Fetch the instance to see what processors are still pending.
	inst := (&model.Instance{}).FromProto(c, t.Instance)
	switch err := datastore.Get(c, inst); {
	case err == datastore.ErrNoSuchEntity:
		return fmt.Errorf("instance %q is unexpectedly gone from the datastore", inst.InstanceID)
	case err != nil:
		return transient.Tag.Apply(err)
	}

	results := map[string]processing.Result{}

	// Grab processors we haven't ran yet.
	var run []processing.Processor
	for _, id := range inst.ProcessorsPending {
		if proc := impl.procsMap[id]; proc != nil {
			run = append(run, proc)
		} else {
			logging.Errorf(c, "Skipping unknown processor %q", id)
			results[id] = processing.Result{Err: fmt.Errorf("unknown processor %q", id)}
		}
	}

	// Exit early if there's nothing to run.
	if len(run) == 0 {
		return impl.updateProcessors(c, t.Instance, results)
	}

	// Open the package for reading.
	pkg, err := impl.packageReader(c, t.Instance.Instance)
	switch {
	case transient.Tag.In(err):
		return err // retry the whole thing
	case err != nil:
		// The package is fatally broken, give up.
		logging.WithError(err).Errorf(c, "The package can't be opened, failing all processors")
		for _, proc := range run {
			results[proc.ID()] = processing.Result{Err: err}
		}
		return impl.updateProcessors(c, t.Instance, results)
	}

	// Run the processors sequentially, since PackageReader is not very friendly
	// to concurrent access.
	var transientErrs errors.MultiError
	for _, proc := range run {
		logging.Infof(c, "Running processor %q", proc.ID())
		res, err := proc.Run(c, inst, pkg)
		if err != nil {
			logging.WithError(err).Errorf(c, "Processor %q failed transiently", proc.ID())
			transientErrs = append(transientErrs, err)
		} else {
			if res.Err != nil {
				logging.WithError(res.Err).Errorf(c, "Processor %q failed fatally", proc.ID())
			}
			results[proc.ID()] = res
		}
	}

	// Store what we've got, even if some processor may have failed to run.
	updErr := impl.updateProcessors(c, t.Instance, results)

	// Prefer errors from processors over 'updErr' if both happen. Processor
	// errors are more interesting.
	switch {
	case len(transientErrs) != 0:
		return transient.Tag.Apply(transientErrs)
	case updErr != nil:
		return updErr
	}
	return nil
}
1299433
func (p *Plugin) getPMConfig() (path string, err error) {
	var pmConfig Config
	found, err := p.Cfg.LoadValue(&pmConfig)
	if err != nil {
		return path, errors.Errorf("failed to read process manager config file: %v", err)
	}
	if found {
		return pmConfig.TemplatePath, nil
	}
	return path, nil
}
1361673
func (p *RemoteMonitor) getLaunchProcessCmd(remoteEnforcerBuildPath, remoteEnforcerName, arg string) *exec.Cmd {

	cmdName := filepath.Join(remoteEnforcerBuildPath, remoteEnforcerName)

	cmdArgs := []string{arg}
	zap.L().Debug("Enforcer executed",
		zap.String("command", cmdName),
		zap.Strings("args", cmdArgs),
	)

	return execCommand(cmdName, cmdArgs...)
}
271893
func (c *Container) ExecdProcesses() (o []rproc.Process) {
	c.mu.Lock()
	defer c.mu.Unlock()
	for _, p := range c.processes {
		o = append(o, p)
	}
	return o
}
518763
func (p *Plugin) GetAllProcesses() []ProcessInstance {
	var processes []ProcessInstance
	for _, pr := range p.processes {
		processes = append(processes, pr)
	}
	return processes
}
1279153
func getResourceIter(context structs.Context, aclObj *acl.ACL, namespace, prefix string, ws memdb.WatchSet, state *state.StateStore) (memdb.ResultIterator, error) {
	switch context {
	case structs.Jobs:
		return state.JobsByIDPrefix(ws, namespace, prefix)
	case structs.Evals:
		return state.EvalsByIDPrefix(ws, namespace, prefix)
	case structs.Allocs:
		return state.AllocsByIDPrefix(ws, namespace, prefix)
	case structs.Nodes:
		return state.NodesByIDPrefix(ws, prefix)
	case structs.Deployments:
		return state.DeploymentsByIDPrefix(ws, namespace, prefix)
	default:
		return getEnterpriseResourceIter(context, aclObj, namespace, prefix, ws, state)
	}
}
766439
func (client *Client) GetApplicationProcessByType(appGUID string, processType string) (Process, Warnings, error) {
	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.GetApplicationProcessRequest,
		URIParams: map[string]string{
			"app_guid": appGUID,
			"type":     processType,
		},
	})
	if err != nil {
		return Process{}, nil, err
	}
	var process Process
	response := cloudcontroller.Response{
		DecodeJSONResponseInto: &process,
	}

	err = client.connection.Make(request, &response)
	return process, response.Warnings, err
}
107119
func (p procfsprocs) get(i int) Proc {
	return &proc{proccache{Proc: p.Procs[i], fs: p.fs}}
}
335633
func (client *Client) GetProcessInstances(processGUID string) ([]ProcessInstance, Warnings, error) {
	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.GetProcessStatsRequest,
		URIParams:   map[string]string{"process_guid": processGUID},
	})
	if err != nil {
		return nil, nil, err
	}

	var fullInstancesList []ProcessInstance
	warnings, err := client.paginate(request, ProcessInstance{}, func(item interface{}) error {
		if instance, ok := item.(ProcessInstance); ok {
			fullInstancesList = append(fullInstancesList, instance)
		} else {
			return ccerror.UnknownObjectInListError{
				Expected:   ProcessInstance{},
				Unexpected: item,
			}
		}
		return nil
	})

	return fullInstancesList, warnings, err
}
518360
func (p *initProcess) getChildPid() (int, error) {
	var pid pid
	if err := json.NewDecoder(p.parentPipe).Decode(&pid); err != nil {
		p.cmd.Wait()
		return -1, err
	}

	// Clean up the zombie parent process
	// On Unix systems FindProcess always succeeds.
	firstChildProcess, _ := os.FindProcess(pid.PidFirstChild)

	// Ignore the error in case the child has already been reaped for any reason
	_, _ = firstChildProcess.Wait()

	return pid.Pid, nil
}
996817
func (c *Client) GetProjectList(page string, pageSize string, projectOwner string) (result ProjectListResultModel, err error) {

	params := url.Values{}
	params.Add("Page", page)
	params.Add("PageSize", pageSize)

	if projectOwner != "" {
		params.Add("ProjectOwner", projectOwner)
	}

	paramsString := params.Encode()

	requestUrl := c.GetUrl("projects", "", "")
	requestPath := GetRequestPath("projects", "", "")

	responseResult, _ := c.GetResponseJson("GET", requestUrl+"?"+paramsString+"&resource", requestPath+"?"+paramsString+"&resource", "")

	err = json.Unmarshal([]byte(responseResult), &result)

	return result, err
}
1351130
func FetchProcessors(c context.Context, inst *Instance) ([]*api.Processor, error) {
	count := len(inst.ProcessorsPending) +
		len(inst.ProcessorsSuccess) +
		len(inst.ProcessorsFailure)
	if count == 0 {
		return nil, nil
	}

	key := datastore.KeyForObj(c, inst)

	// Fetch results of all finished processors. All entities should exist, since
	// ProcessorsSuccess/ProcessorsFailure is updated transactionally when
	// entities are created.
	finished := make([]*ProcessingResult, 0, len(inst.ProcessorsSuccess)+len(inst.ProcessorsFailure))
	for _, p := range inst.ProcessorsSuccess {
		finished = append(finished, &ProcessingResult{ProcID: p, Instance: key})
	}
	for _, p := range inst.ProcessorsFailure {
		finished = append(finished, &ProcessingResult{ProcID: p, Instance: key})
	}
	if err := datastore.Get(c, finished); err != nil {
		return nil, errors.Annotate(err, "failed to fetch finished processors").Tag(transient.Tag).Err()
	}

	// Convert all them to proto.
	out := make([]*api.Processor, 0, count)
	for _, p := range finished {
		proc, err := p.Proto()
		if err != nil {
			return nil, errors.Annotate(err, "failed to read results of processor %q", p.ProcID).Err()
		}
		out = append(out, proc)
	}

	// Add pending processors to the output too. They don't have entities in the
	// datastore, so we haven't fetched anything for them.
	for _, p := range inst.ProcessorsPending {
		proc, err := (&ProcessingResult{ProcID: p, Instance: key}).Proto()
		if err != nil {
			panic(err) // impossible for empty ProcessingResult{}
		}
		out = append(out, proc)
	}

	// Sort by processor ID, as promised by the API.
	sort.Slice(out, func(i, j int) bool { return out[i].Id < out[j].Id })
	return out, nil
}
84236
func (container *container) ProcessList() ([]ProcessListItem, error) {
	properties, err := container.system.Properties(schema1.PropertyTypeProcessList)
	if err != nil {
		return nil, convertSystemError(err, container)
	}

	return properties.ProcessList, nil
}
1067264
func displayProcessTree() {
	ps := goprocess.FindAll()
	pstree = make(map[int][]goprocess.P)
	for _, p := range ps {
		pstree[p.PPID] = append(pstree[p.PPID], p)
	}
	tree := treeprint.New()
	tree.SetValue("...")
	seen := map[int]bool{}
	for _, p := range ps {
		constructProcessTree(p.PPID, p, seen, tree)
	}
	fmt.Println(tree.String())
}