// GetProcStat gets the /proc/pid/stat info for the given pid.
339650
func GetProcStat(pid int) (*ProcStat, error) {
	stat := ProcStat{}

	// read in the stat
	data, err := ioutil.ReadFile(fmt.Sprintf(procDir+"%d/stat", pid))
	if err != nil {
		return nil, err
	}
	fields := strings.Fields(string(data))

	// the first field contains the PID
	if len(fields) < 1 {
		return nil, fmt.Errorf("less than 1 field")
	}
	if err := parseInt(fields[0], &stat.Pid); err != nil {
		return nil, err
	}

	// The next couple of fields will contain the process file name enclosed by ()
	// so look for the last ) starting at the end
	i := 0
	for j := len(fields) - 1; j >= 0; j-- {
		if strings.HasSuffix(fields[j], ")") {
			i = j
			break
		}
	}
	if i < 1 {
		return nil, fmt.Errorf("could not find process name")
	}
	stat.Filename = fields[1]
	for j := 2; j <= i; j++ {
		stat.Filename = stat.Filename + " " + fields[j]
	}

	if (len(fields) - i) < 5 {
		return nil, MalformedStatErr
	}

	// the next field is the process state flag
	i++
	stat.State = fields[i]

	// the remaining fields are integers
	i++
	if err := parseInt(fields[i], &stat.Ppid); err != nil {
		return nil, MalformedStatErr
	}
	i++
	if err := parseInt(fields[i], &stat.Pgrp); err != nil {
		return nil, MalformedStatErr
	}
	i++
	if err := parseInt(fields[i], &stat.Session); err != nil {
		return nil, MalformedStatErr
	}
	return &stat, nil
}
995122
func (p *ProcMetrics) Collect() {
	if m, err := CollectProcInfo(p.pid); err == nil {
		now := time.Now()

		if !p.lastTime.IsZero() {
			ratio := 1.0
			switch {
			case m.CPU.Period > 0 && m.CPU.Quota > 0:
				ratio = float64(m.CPU.Quota) / float64(m.CPU.Period)
			case m.CPU.Shares > 0:
				ratio = float64(m.CPU.Shares) / 1024
			default:
				ratio = 1 / float64(runtime.NumCPU())
			}

			interval := ratio * float64(now.Sub(p.lastTime))

			p.cpu.user.time = m.CPU.User - p.last.CPU.User
			p.cpu.user.percent = 100 * float64(p.cpu.user.time) / interval

			p.cpu.system.time = m.CPU.Sys - p.last.CPU.Sys
			p.cpu.system.percent = 100 * float64(p.cpu.system.time) / interval

			p.cpu.total.time = (m.CPU.User + m.CPU.Sys) - (p.last.CPU.User + p.last.CPU.Sys)
			p.cpu.total.percent = 100 * float64(p.cpu.total.time) / interval

		}

		p.memory.available = m.Memory.Available
		p.memory.size = m.Memory.Size
		p.memory.resident.usage = m.Memory.Resident
		p.memory.resident.percent = 100 * float64(p.memory.resident.usage) / float64(p.memory.available)
		p.memory.shared.usage = m.Memory.Shared
		p.memory.text.usage = m.Memory.Text
		p.memory.data.usage = m.Memory.Data
		p.memory.pagefault.major.count = m.Memory.MajorPageFaults - p.last.Memory.MajorPageFaults
		p.memory.pagefault.minor.count = m.Memory.MinorPageFaults - p.last.Memory.MinorPageFaults

		p.files.open = m.Files.Open
		p.files.max = m.Files.Max

		p.threads.num = m.Threads.Num
		p.threads.switches.voluntary.count = m.Threads.VoluntaryContextSwitches - p.last.Threads.VoluntaryContextSwitches
		p.threads.switches.involuntary.count = m.Threads.InvoluntaryContextSwitches - p.last.Threads.InvoluntaryContextSwitches

		p.last = m
		p.lastTime = now
		p.engine.Report(p)
	}
}
144490
func GetStats() (stats Stats, err error) {
	var limit uint64
	limit, err = getMemoryLimit()
	if err != nil {
		return Stats{}, err
	}

	stats.TotalRAM = limit
	return stats, nil
}
307077
func GetStats() (stats Stats, err error) {
	var memInfo memoryStatusEx
	memInfo.cbSize = uint32(unsafe.Sizeof(memInfo))
	if mem, _, _ := procGlobalMemoryStatusEx.Call(uintptr(unsafe.Pointer(&memInfo))); mem == 0 {
		err = syscall.GetLastError()
	} else {
		stats.TotalRAM = memInfo.ullTotalPhys
	}

	return stats, err
}
1126300
func getCoresFromStatus(adminCoresStatus *AdminCoresStatus) []string {
	serverCores := []string{}
	for coreName := range adminCoresStatus.Status {
		serverCores = append(serverCores, coreName)
	}
	return serverCores
}
1356231
func (c *filesystemCollector) GetStats() (stats []filesystemStats, err error) {
	var mntbuf *C.struct_statfs
	count := C.getmntinfo(&mntbuf, C.MNT_NOWAIT)
	if count == 0 {
		return nil, errors.New("getmntinfo() failed")
	}

	mnt := (*[1 << 20]C.struct_statfs)(unsafe.Pointer(mntbuf))
	stats = []filesystemStats{}
	for i := 0; i < int(count); i++ {
		mountpoint := C.GoString(&mnt[i].f_mntonname[0])
		if c.ignoredMountPointsPattern.MatchString(mountpoint) {
			log.Debugf("Ignoring mount point: %s", mountpoint)
			continue
		}

		device := C.GoString(&mnt[i].f_mntfromname[0])
		fstype := C.GoString(&mnt[i].f_fstypename[0])
		if c.ignoredFSTypesPattern.MatchString(fstype) {
			log.Debugf("Ignoring fs type: %s", fstype)
			continue
		}

		var ro float64
		if (mnt[i].f_flags & readOnly) != 0 {
			ro = 1
		}

		stats = append(stats, filesystemStats{
			labels: filesystemLabels{
				device:     device,
				mountPoint: mountpoint,
				fsType:     fstype,
			},
			size:      float64(mnt[i].f_blocks) * float64(mnt[i].f_bsize),
			free:      float64(mnt[i].f_bfree) * float64(mnt[i].f_bsize),
			avail:     float64(mnt[i].f_bavail) * float64(mnt[i].f_bsize),
			files:     float64(mnt[i].f_files),
			filesFree: float64(mnt[i].f_ffree),
			ro:        ro,
		})
	}
	return stats, nil
}
138733
func (crl *CRL) GetStatusProto() *admin.CRLStatus {
	return &admin.CRLStatus{
		LastUpdateTime:    google.NewTimestamp(crl.LastUpdateTime),
		LastFetchTime:     google.NewTimestamp(crl.LastFetchTime),
		LastFetchEtag:     crl.LastFetchETag,
		RevokedCertsCount: int64(crl.RevokedCertsCount),
	}
}
1172429
func ReadClientRPCStats(procfs string) (*ClientRPCStats, error) {
	f, err := os.Open(path.Join(procfs, "net/rpc/nfs"))
	if err != nil {
		return nil, err
	}
	defer f.Close()

	return ParseClientRPCStats(f)
}
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
}
439013
func GetCPU() (info *CPU, err error) {
	info = &CPU{}

	// get physical cpu stats
	var cpus []cpu.InfoStat
	if cpus, err = cpuInfo(); err != nil {
		return info, err
	}

	info.HostPhysicalCPUs = len(cpus)

	// get logical cpu stats
	if info.HostLogicalCPUs, err = cpuCounts(true); err != nil {
		return info, err
	}

	// total number of cpu cores
	for _, cpu := range cpus {
		info.HostCPUCores += int64(cpu.Cores)
		// TODO: This is not ideal... if there are different processors
		// we will only report one of the models... This is unlikely to happen,
		// but it could
		info.HostCPUModel = cpu.ModelName
	}

	err = fillPlatformSpecificCPUData(info)
	return info, err
}
1139167
func (n *Graph) getProcPort(procName, portName string, dir reflect.ChanDir) (reflect.Value, error) {
	nilValue := reflect.ValueOf(nil)
	// Ensure process exists
	proc, ok := n.procs[procName]
	if !ok {
		return nilValue, fmt.Errorf("Connect error: process '%s' not found", procName)
	}

	// Ensure sender is settable
	val := reflect.ValueOf(proc)
	if val.Kind() == reflect.Ptr && val.IsValid() {
		val = val.Elem()
	}
	if !val.CanSet() {
		return nilValue, fmt.Errorf("Connect error: process '%s' is not settable", procName)
	}

	// Get the port value
	var portVal reflect.Value
	var err error
	// Check if sender is a net
	net, ok := val.Interface().(Graph)
	if ok {
		// Sender is a net
		if dir == reflect.SendDir {
			portVal, err = net.getOutPort(portName)
		} else {
			portVal, err = net.getInPort(portName)
		}

	} else {
		// Sender is a proc
		portVal = val.FieldByName(portName)
		if !portVal.IsValid() {
			err = errors.New("")
		}
	}
	if err != nil {
		return nilValue, fmt.Errorf("Connect error: process '%s' does not have port '%s'", procName, portName)
	}

	// Validate port type
	portType := portVal.Type()

	// Sender port can be an array port
	if dir == reflect.SendDir && portType.Kind() == reflect.Slice {
		portType = portType.Elem()
	}

	// Validate
	if portType.Kind() != reflect.Chan || portType.ChanDir()&dir == 0 {
		return nilValue, fmt.Errorf("Connect error: '%s.%s' is not of the correct chan type", procName, portName)
	}

	// Check assignability
	if !portVal.CanSet() {
		return nilValue, fmt.Errorf("'%s.%s' is not assignable", procName, portName)
	}

	return portVal, nil
}
675590
func getProfilesDirectory() (string, error) {
	if err := procGetProfilesDirectory.Find(); err != nil {
		return "", err
	}
	var buf [syscall.MAX_PATH]uint16
	n := uint32(len(buf))
	r1, _, e1 := syscall.Syscall(procGetProfilesDirectory.Addr(), 2,
		uintptr(unsafe.Pointer(&buf[0])), // _Out_   LPTSTR  lpProfilesDir,
		uintptr(unsafe.Pointer(&n)),      // _Inout_ LPDWORD lpcchSize
		0,
	)
	if r1 == 0 {
		if e1 == 0 {
			return "", os.NewSyscallError("GetProfilesDirectory", syscall.EINVAL)
		}
		return "", os.NewSyscallError("GetProfilesDirectory", e1)
	}
	s := syscall.UTF16ToString(buf[0:])
	return s, nil
}
17828
func (ioctx *IOContext) Stat(object string) (stat ObjectStat, err error) {
	var c_psize C.uint64_t
	var c_pmtime C.time_t
	c_object := C.CString(object)
	defer C.free(unsafe.Pointer(c_object))

	ret := C.rados_stat(
		ioctx.ioctx,
		c_object,
		&c_psize,
		&c_pmtime)

	if ret < 0 {
		return ObjectStat{}, GetRadosError(int(ret))
	} else {
		return ObjectStat{
			Size:    uint64(c_psize),
			ModTime: time.Unix(int64(c_pmtime), 0),
		}, nil
	}
}
27373
func (c *pidCollector) pidStats() (map[string]*drivers.ResourceUsage, error) {
	stats := make(map[string]*drivers.ResourceUsage)
	c.pidLock.RLock()
	pids := make(map[int]*nomadPid, len(c.pids))
	for k, v := range c.pids {
		pids[k] = v
	}
	c.pidLock.RUnlock()
	for pid, np := range pids {
		p, err := process.NewProcess(int32(pid))
		if err != nil {
			c.logger.Trace("unable to create new process", "pid", pid, "error", err)
			continue
		}
		ms := &drivers.MemoryStats{}
		if memInfo, err := p.MemoryInfo(); err == nil {
			ms.RSS = memInfo.RSS
			ms.Swap = memInfo.Swap
			ms.Measured = ExecutorBasicMeasuredMemStats
		}

		cs := &drivers.CpuStats{}
		if cpuStats, err := p.Times(); err == nil {
			cs.SystemMode = np.cpuStatsSys.Percent(cpuStats.System * float64(time.Second))
			cs.UserMode = np.cpuStatsUser.Percent(cpuStats.User * float64(time.Second))
			cs.Measured = ExecutorBasicMeasuredCpuStats

			// calculate cpu usage percent
			cs.Percent = np.cpuStatsTotal.Percent(cpuStats.Total() * float64(time.Second))
		}
		stats[strconv.Itoa(pid)] = &drivers.ResourceUsage{MemoryStats: ms, CpuStats: cs}
	}

	return stats, nil
}
1264986
func (s *service) getProcess(id, execID string) (*process, error) {
	s.mu.Lock()
	defer s.mu.Unlock()

	return s.getProcessLocked(id, execID)
}
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
}
1294377
func GetProgNextID(current uint32) (uint32, error) {
	attr := attrProg{
		progID: current,
	}

	duration := spanstat.Start()
	ret, _, err := unix.Syscall(unix.SYS_BPF, BPF_PROG_GET_NEXT_ID, uintptr(unsafe.Pointer(&attr)), unsafe.Sizeof(attr))
	metricSyscallDuration.WithLabelValues(metricOpProgGetNextID, metrics.Errno2Outcome(err)).Observe(duration.End(err == 0).Total().Seconds())
	if ret != 0 || err != 0 {
		return 0, fmt.Errorf("Unable to get next id: %v", err)
	}

	return attr.nextID, nil
}