// validateProcessInfo checks for a complete process info
428455
func validateProcessInfo(p *ProcessInfo) error {
	if p == nil {
		return fmt.Errorf("ProcessInfo must be set")
	} else if p.Name == "" {
		return fmt.Errorf("ProcessInfo name must be set")
	} else if p.Namespace == "" {
		return fmt.Errorf("ProcessInfo namespace must be set")
	}
	return nil
}
677673
func validateClusterInfo(clusterName string, clusterInfo clientcmdapi.Cluster) []error {
	validationErrors := make([]error, 0)

	emptyCluster := clientcmdapi.NewCluster()
	if reflect.DeepEqual(*emptyCluster, clusterInfo) {
		return []error{ErrEmptyCluster}
	}

	if len(clusterInfo.Server) == 0 {
		if len(clusterName) == 0 {
			validationErrors = append(validationErrors, fmt.Errorf("default cluster has no server defined"))
		} else {
			validationErrors = append(validationErrors, fmt.Errorf("no server found for cluster %q", clusterName))
		}
	}
	// Make sure CA data and CA file aren't both specified
	if len(clusterInfo.CertificateAuthority) != 0 && len(clusterInfo.CertificateAuthorityData) != 0 {
		validationErrors = append(validationErrors, fmt.Errorf("certificate-authority-data and certificate-authority are both specified for %v. certificate-authority-data will override.", clusterName))
	}
	if len(clusterInfo.CertificateAuthority) != 0 {
		clientCertCA, err := os.Open(clusterInfo.CertificateAuthority)
		defer clientCertCA.Close()
		if err != nil {
			validationErrors = append(validationErrors, fmt.Errorf("unable to read certificate-authority %v for %v due to %v", clusterInfo.CertificateAuthority, clusterName, err))
		}
	}

	return validationErrors
}
1273285
func (v *Validator) CheckProcess() (errs error) {
	logrus.Debugf("check process")

	if v.spec.Process == nil {
		return
	}

	process := v.spec.Process
	if !osFilepath.IsAbs(v.platform, process.Cwd) {
		errs = multierror.Append(errs,
			specerror.NewError(
				specerror.ProcCwdAbs,
				fmt.Errorf("cwd %q is not an absolute path", process.Cwd),
				rspec.Version))
	}

	for _, env := range process.Env {
		if !envValid(env) {
			errs = multierror.Append(errs, fmt.Errorf("env %q should be in the form of 'key=value'. The left hand side must consist solely of letters, digits, and underscores '_'", env))
		}
	}

	if len(process.Args) == 0 {
		errs = multierror.Append(errs,
			specerror.NewError(
				specerror.ProcArgsOneEntryRequired,
				fmt.Errorf("args must not be empty"),
				rspec.Version))
	} else {
		if filepath.IsAbs(process.Args[0]) && v.spec.Root != nil {
			var rootfsPath string
			if filepath.IsAbs(v.spec.Root.Path) {
				rootfsPath = v.spec.Root.Path
			} else {
				rootfsPath = filepath.Join(v.bundlePath, v.spec.Root.Path)
			}
			absPath := filepath.Join(rootfsPath, process.Args[0])
			fileinfo, err := os.Stat(absPath)
			if os.IsNotExist(err) {
				logrus.Warnf("executable %q is not available in rootfs currently", process.Args[0])
			} else if err != nil {
				errs = multierror.Append(errs, err)
			} else {
				m := fileinfo.Mode()
				if m.IsDir() || m&0111 == 0 {
					errs = multierror.Append(errs, fmt.Errorf("arg %q is not executable", process.Args[0]))
				}
			}
		}
	}

	if v.platform == "linux" || v.platform == "solaris" {
		errs = multierror.Append(errs, v.CheckRlimits())
	}

	if v.platform == "linux" {
		if v.spec.Process.Capabilities != nil {
			errs = multierror.Append(errs, v.CheckCapabilities())
		}

		if len(process.ApparmorProfile) > 0 {
			profilePath := filepath.Join(v.bundlePath, v.spec.Root.Path, "/etc/apparmor.d", process.ApparmorProfile)
			_, err := os.Stat(profilePath)
			if err != nil {
				errs = multierror.Append(errs, err)
			}
		}
	}

	return
}
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
}
980606
func GetProcessStartTime(pid int) (string, error) {
	stat, err := Stat(pid)
	if err != nil {
		return "", err
	}
	return fmt.Sprintf("%d", stat.StartTime), nil
}
106713
func (client *Client) GetApplicationProcesses(appGUID string) ([]Process, Warnings, error) {
	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.GetApplicationProcessesRequest,
		URIParams:   map[string]string{"app_guid": appGUID},
	})
	if err != nil {
		return nil, nil, err
	}

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

	return fullProcessesList, warnings, err
}
260539
func ValidateOriginProcess(pid string) (string, error) {

	pidNumber, err := strconv.Atoi(pid)
	if err != nil {
		return "", fmt.Errorf("Invalid PID %s", pid)
	}
	process, err := process.NewProcess(int32(pidNumber))
	if err != nil {
		return "", fmt.Errorf("Process not found: %s", err)
	}
	ppid, err := process.Ppid()
	if err != nil {
		return "", fmt.Errorf("Parent process not found: %s", err)
	}
	parentPidCgroup, err := processCgroups(strconv.Itoa(int(ppid)), "net_cls,net_prio")
	if err != nil {
		return "", fmt.Errorf("Parent cgroup not found: %s", err)
	}
	if parentPidCgroup != "/" {
		return "", fmt.Errorf("Parent is not root cgroup - authorization fail")
	}
	return findParentCgroup(pid)
}
151355
func (tc *TiDBContext) SetProcessInfo(sql string, t time.Time, command byte) {
	tc.session.SetProcessInfo(sql, t, command)
}
1071937
func (p *PUContext) GetProcessKeys() (string, []string, []string) {
	return p.mark, p.tcpPorts, p.udpPorts
}
1152820
func (nc *Conn) processInfo(info string) error {
	if info == _EMPTY_ {
		return nil
	}
	ncInfo := serverInfo{}
	if err := json.Unmarshal([]byte(info), &ncInfo); err != nil {
		return err
	}

	// Copy content into connection's info structure.
	nc.info = ncInfo
	// The array could be empty/not present on initial connect,
	// if advertise is disabled on that server, or servers that
	// did not include themselves in the async INFO protocol.
	// If empty, do not remove the implicit servers from the pool.
	if len(ncInfo.ConnectURLs) == 0 {
		return nil
	}
	// Note about pool randomization: when the pool was first created,
	// it was randomized (if allowed). We keep the order the same (removing
	// implicit servers that are no longer sent to us). New URLs are sent
	// to us in no specific order so don't need extra randomization.
	hasNew := false
	// This is what we got from the server we are connected to.
	urls := nc.info.ConnectURLs
	// Transform that to a map for easy lookups
	tmp := make(map[string]struct{}, len(urls))
	for _, curl := range urls {
		tmp[curl] = struct{}{}
	}
	// Walk the pool and removed the implicit servers that are no longer in the
	// given array/map
	sp := nc.srvPool
	for i := 0; i < len(sp); i++ {
		srv := sp[i]
		curl := srv.url.Host
		// Check if this URL is in the INFO protocol
		_, inInfo := tmp[curl]
		// Remove from the temp map so that at the end we are left with only
		// new (or restarted) servers that need to be added to the pool.
		delete(tmp, curl)
		// Keep servers that were set through Options, but also the one that
		// we are currently connected to (even if it is a discovered server).
		if !srv.isImplicit || srv.url == nc.current.url {
			continue
		}
		if !inInfo {
			// Remove from server pool. Keep current order.
			copy(sp[i:], sp[i+1:])
			nc.srvPool = sp[:len(sp)-1]
			sp = nc.srvPool
			i--
		}
	}
	// Figure out if we should save off the current non-IP hostname if we encounter a bare IP.
	saveTLS := nc.current != nil && !hostIsIP(nc.current.url)

	// If there are any left in the tmp map, these are new (or restarted) servers
	// and need to be added to the pool.
	for curl := range tmp {
		// Before adding, check if this is a new (as in never seen) URL.
		// This is used to figure out if we invoke the DiscoveredServersCB
		if _, present := nc.urls[curl]; !present {
			hasNew = true
		}
		nc.addURLToPool(fmt.Sprintf("%s://%s", nc.connScheme(), curl), true, saveTLS)
	}
	if hasNew && !nc.initc && nc.Opts.DiscoveredServersCB != nil {
		nc.ach.push(func() { nc.Opts.DiscoveredServersCB(nc) })
	}

	return nil
}
583188
func findProcessesWithFn(fn processesFn, matchFn MatchFn, max int) ([]ps.Process, error) {
	processes, err := fn()
	if err != nil {
		return nil, fmt.Errorf("Error listing processes: %s", err)
	}
	if processes == nil {
		return nil, nil
	}
	procs := []ps.Process{}
	for _, p := range processes {
		if matchFn(p) {
			procs = append(procs, p)
		}
		if max != 0 && len(procs) >= max {
			break
		}
	}
	return procs, nil
}
486781
func (actor Actor) GetProcessByTypeAndApplication(processType string, appGUID string) (Process, Warnings, error) {
	process, warnings, err := actor.CloudControllerClient.GetApplicationProcessByType(appGUID, processType)
	if _, ok := err.(ccerror.ProcessNotFoundError); ok {
		return Process{}, Warnings(warnings), actionerror.ProcessNotFoundError{ProcessType: processType}
	}
	return Process(process), Warnings(warnings), err
}
1271604
func (nc *Conn) processAsyncInfo(info []byte) {
	nc.mu.Lock()
	// Ignore errors, we will simply not update the server pool...
	nc.processInfo(string(info))
	nc.mu.Unlock()
}
588223
func (g *Generator) ClearProcessEnv() {
	if g.Config == nil || g.Config.Process == nil {
		return
	}
	g.Config.Process.Env = []string{}
	// Clear out the env cache map as well
	g.envMap = map[string]int{}
}
678737
func (p *Procstat) updateProcesses(pids []PID, tags map[string]string, prevInfo map[PID]Process) (map[PID]Process, error) {
	procs := make(map[PID]Process, len(prevInfo))

	for _, pid := range pids {
		info, ok := prevInfo[pid]
		if ok {
			// Assumption: if a process has no name, it probably does not exist
			if name, _ := info.Name(); name == "" {
				continue
			}
			procs[pid] = info
		} else {
			proc, err := p.createProcess(pid)
			if err != nil {
				// No problem; process may have ended after we found it
				continue
			}
			// Assumption: if a process has no name, it probably does not exist
			if name, _ := proc.Name(); name == "" {
				continue
			}
			procs[pid] = proc

			// Add initial tags
			for k, v := range tags {
				proc.Tags()[k] = v
			}

			// Add pid tag if needed
			if p.PidTag {
				proc.Tags()["pid"] = strconv.Itoa(int(pid))
			}
			if p.ProcessName != "" {
				proc.Tags()["process_name"] = p.ProcessName
			}
		}
	}
	return procs, nil
}
761527
func NewProcessInfo(name, namespace string) *ProcessInfo {
	// try to concat the hostname if available
	host, _ := os.Hostname()
	if host != "" {
		name = fmt.Sprintf("%s-%s", name, host)
	}
	return &ProcessInfo{
		Name:      name,
		Namespace: namespace,
	}
}
458460
func (client *Client) DeleteApplicationProcessInstance(appGUID string, processType string, instanceIndex int) (Warnings, error) {
	request, err := client.newHTTPRequest(requestOptions{
		RequestName: internal.DeleteApplicationProcessInstanceRequest,
		URIParams: map[string]string{
			"app_guid": appGUID,
			"type":     processType,
			"index":    strconv.Itoa(instanceIndex),
		},
	})
	if err != nil {
		return nil, err
	}

	var response cloudcontroller.Response
	err = client.connection.Make(request, &response)

	return response.Warnings, err
}