// ProcUsage returns CPU usage
197933
func ProcUsage(pcpu *float64, rss, vss *int64) error {
	pidStr := fmt.Sprintf("%d", os.Getpid())
	out, err := exec.Command("ps", "o", "pcpu=,rss=,vsz=", "-p", pidStr).Output()
	if err != nil {
		*rss, *vss = -1, -1
		return fmt.Errorf("ps call failed:%v", err)
	}
	fmt.Sscanf(string(out), "%f %d %d", pcpu, rss, vss)
	*rss *= 1024 // 1k blocks, want bytes.
	*vss *= 1024 // 1k blocks, want bytes.
	return nil
}
1015211
func (mgr *Manager) ShouldProcess(request protocol.Request, knownAgents []string) bool {
	filter, _ := request.Filter()
	passed := 0

	if filter.Empty() {
		mgr.log.Debugf("Matching request %s with empty filter", request.RequestID())
		passed++
	}

	if len(filter.ClassFilters()) > 0 {
		if classes.Match(filter.ClassFilters(), mgr.cfg.ClassesFile, mgr.log) {
			mgr.log.Debugf("Matching request %s with class filters '%#v'", request.RequestID(), filter.ClassFilters())
			passed++
		} else {
			mgr.log.Debugf("Not matching request %s with class filters '%#v'", request.RequestID(), filter.ClassFilters())
			return false
		}
	}

	if len(filter.AgentFilters()) > 0 {
		if agents.Match(filter.AgentFilters(), knownAgents) {
			mgr.log.Debugf("Matching request %s with agent filters '%#v'", request.RequestID(), filter.AgentFilters())
			passed++
		} else {
			mgr.log.Debugf("Not matching request %s with agent filters '%#v'", request.RequestID(), filter.AgentFilters())
			return false
		}
	}

	if len(filter.IdentityFilters()) > 0 {
		if identity.Match(filter.IdentityFilters(), mgr.cfg.Identity) {
			mgr.log.Debugf("Matching request %s with identity filters '%#v'", request.RequestID(), filter.IdentityFilters())
			passed++
		} else {
			mgr.log.Debugf("Not matching request %s with identity filters '%#v'", request.RequestID(), filter.IdentityFilters())
			return false
		}
	}

	if len(filter.FactFilters()) > 0 {
		if facts.Match(filter.FactFilters(), mgr.fw, mgr.log) {
			mgr.log.Debugf("Matching request %s based on fact filters '%#v'", request.RequestID(), filter.FactFilters())
			passed++
		} else {
			mgr.log.Debugf("Not matching request %s based on fact filters '%#v'", request.RequestID(), filter.FactFilters())
			return false
		}
	}

	if len(filter.CompoundFilters()) > 0 {
		mgr.log.Warnf("Compound filters are not supported, not matching request %s with filter '%#v'", request.RequestID(), filter.CompoundFilters())
		return false
	}

	return passed > 0
}
595997
func (c *client) pruneDenyCache() {
	r := 0
	for subject := range c.mperms.dcache {
		delete(c.mperms.dcache, subject)
		if r++; r > pruneSize {
			break
		}
	}
}
133661
func (c *imageProber) Probe(parentID string, runConfig *container.Config) (string, error) {
	if c.cacheBusted {
		return "", nil
	}
	cacheID, err := c.cache.GetCache(parentID, runConfig)
	if err != nil {
		return "", err
	}
	if len(cacheID) == 0 {
		logrus.Debugf("[BUILDER] Cache miss: %s", runConfig.Cmd)
		c.cacheBusted = true
		return "", nil
	}
	logrus.Debugf("[BUILDER] Use cached version: %s", runConfig.Cmd)
	return cacheID, nil
}
613301
func (c *helpCacher) rpcUsage(includeWebsockets bool) (string, error) {
	c.Lock()
	defer c.Unlock()

	// Return the cached usage if it is available.
	if c.usage != "" {
		return c.usage, nil
	}

	// Generate a list of one-line usage for every command.
	usageTexts := make([]string, 0, len(rpcHandlers))
	for k := range rpcHandlers {
		usage, err := btcjson.MethodUsageText(k)
		if err != nil {
			return "", err
		}
		usageTexts = append(usageTexts, usage)
	}

	// Include websockets commands if requested.
	if includeWebsockets {
		for k := range wsHandlers {
			usage, err := btcjson.MethodUsageText(k)
			if err != nil {
				return "", err
			}
			usageTexts = append(usageTexts, usage)
		}
	}

	sort.Sort(sort.StringSlice(usageTexts))
	c.usage = strings.Join(usageTexts, "\n")
	return c.usage, nil
}
349237
func (c *client) prunePerAccountCache() {
	n := 0
	for cacheKey := range c.in.pacache {
		delete(c.in.pacache, cacheKey)
		if n++; n > prunePerAccountCacheSize {
			break
		}
	}
}
974734
func (tr *TaskRunner) setGaugeForCPU(ru *cstructs.TaskResourceUsage) {
	if !tr.clientConfig.DisableTaggedMetrics {
		metrics.SetGaugeWithLabels([]string{"client", "allocs", "cpu", "total_percent"},
			float32(ru.ResourceUsage.CpuStats.Percent), tr.baseLabels)
		metrics.SetGaugeWithLabels([]string{"client", "allocs", "cpu", "system"},
			float32(ru.ResourceUsage.CpuStats.SystemMode), tr.baseLabels)
		metrics.SetGaugeWithLabels([]string{"client", "allocs", "cpu", "user"},
			float32(ru.ResourceUsage.CpuStats.UserMode), tr.baseLabels)
		metrics.SetGaugeWithLabels([]string{"client", "allocs", "cpu", "throttled_time"},
			float32(ru.ResourceUsage.CpuStats.ThrottledTime), tr.baseLabels)
		metrics.SetGaugeWithLabels([]string{"client", "allocs", "cpu", "throttled_periods"},
			float32(ru.ResourceUsage.CpuStats.ThrottledPeriods), tr.baseLabels)
		metrics.SetGaugeWithLabels([]string{"client", "allocs", "cpu", "total_ticks"},
			float32(ru.ResourceUsage.CpuStats.TotalTicks), tr.baseLabels)
	}

	if tr.clientConfig.BackwardsCompatibleMetrics {
		metrics.SetGauge([]string{"client", "allocs", tr.alloc.Job.Name, tr.alloc.TaskGroup, tr.allocID, tr.taskName, "cpu", "total_percent"}, float32(ru.ResourceUsage.CpuStats.Percent))
		metrics.SetGauge([]string{"client", "allocs", tr.alloc.Job.Name, tr.alloc.TaskGroup, tr.allocID, tr.taskName, "cpu", "system"}, float32(ru.ResourceUsage.CpuStats.SystemMode))
		metrics.SetGauge([]string{"client", "allocs", tr.alloc.Job.Name, tr.alloc.TaskGroup, tr.allocID, tr.taskName, "cpu", "user"}, float32(ru.ResourceUsage.CpuStats.UserMode))
		metrics.SetGauge([]string{"client", "allocs", tr.alloc.Job.Name, tr.alloc.TaskGroup, tr.allocID, tr.taskName, "cpu", "throttled_time"}, float32(ru.ResourceUsage.CpuStats.ThrottledTime))
		metrics.SetGauge([]string{"client", "allocs", tr.alloc.Job.Name, tr.alloc.TaskGroup, tr.allocID, tr.taskName, "cpu", "throttled_periods"}, float32(ru.ResourceUsage.CpuStats.ThrottledPeriods))
		metrics.SetGauge([]string{"client", "allocs", tr.alloc.Job.Name, tr.alloc.TaskGroup, tr.allocID, tr.taskName, "cpu", "total_ticks"}, float32(ru.ResourceUsage.CpuStats.TotalTicks))
	}
}
1308066
func updateUsage(v *Varz) {
	var rss, vss int64
	var pcpu float64

	pse.ProcUsage(&pcpu, &rss, &vss)

	v.Mem = rss
	v.CPU = pcpu
	v.Cores = numCores
}
383057
func (self *ResourceList) Cpu() *resource.Quantity {
	if val, ok := (*self)[ResourceCPU]; ok {
		return &val
	}
	return &resource.Quantity{Format: resource.DecimalSI}
}
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)
	}
}
1297203
func startProfile(cpuprofile, memprofile string) {
	if cpuprofile != "" {
		f, err := os.Create(cpuprofile)
		if err != nil {
			log.Fatalf("failed to create CPU profile file at %s: %s", cpuprofile, err.Error())
		}
		log.Printf("writing CPU profile to: %s\n", cpuprofile)
		prof.cpu = f
		pprof.StartCPUProfile(prof.cpu)
	}

	if memprofile != "" {
		f, err := os.Create(memprofile)
		if err != nil {
			log.Fatalf("failed to create memory profile file at %s: %s", cpuprofile, err.Error())
		}
		log.Printf("writing memory profile to: %s\n", memprofile)
		prof.mem = f
		runtime.MemProfileRate = 4096
	}
}
1262244
func ComputeTaintTolerationPriorityMap(pod *v1.Pod, meta interface{}, nodeInfo *schedulernodeinfo.NodeInfo) (schedulerapi.HostPriority, error) {
	node := nodeInfo.Node()
	if node == nil {
		return schedulerapi.HostPriority{}, fmt.Errorf("node not found")
	}
	// To hold all the tolerations with Effect PreferNoSchedule
	var tolerationsPreferNoSchedule []v1.Toleration
	if priorityMeta, ok := meta.(*priorityMetadata); ok {
		tolerationsPreferNoSchedule = priorityMeta.podTolerations

	} else {
		tolerationsPreferNoSchedule = getAllTolerationPreferNoSchedule(pod.Spec.Tolerations)
	}

	return schedulerapi.HostPriority{
		Host:  node.Name,
		Score: countIntolerableTaintsPreferNoSchedule(node.Spec.Taints, tolerationsPreferNoSchedule),
	}, nil
}
774840
func (d *Daemon) waitForCacheSync(resourceNames ...string) {
	for _, resourceName := range resourceNames {
		d.k8sResourceSyncedMu.RLock()
		c, ok := d.k8sResourceSynced[resourceName]
		d.k8sResourceSyncedMu.RUnlock()
		if !ok {
			continue
		}
		<-c
	}
}
703708
func (prof *Profiler) cache(x int, cpu *CPU) error {
	cpu.Cache = map[string]string{}
	//go through all the entries in cpuX/cache
	p := prof.cachePath(x)
	dirs, err := ioutil.ReadDir(p)
	if err != nil {
		return err
	}
	var cacheID string
	// all the entries should be dirs with their contents holding the cache info
	for _, d := range dirs {
		if !d.IsDir() {
			continue // this shouldn't happen but if it does we just skip the entry
		}
		// cache level
		l, err := ioutil.ReadFile(filepath.Join(p, d.Name(), "level"))
		if err != nil {
			return err
		}

		t, err := ioutil.ReadFile(filepath.Join(p, d.Name(), "type"))
		if err != nil {
			return err
		}

		// cache type: unified entries aren't decorated, otherwise the first letter is used
		// like what lscpu does.
		if t[0] != 'U' && t[0] != 'u' {
			cacheID = fmt.Sprintf("L%s%s cache", string(l[:len(l)-1]), strings.ToLower(string(t[0])))
		} else {
			cacheID = fmt.Sprintf("L%s cache", string(l[:len(l)-1]))
		}

		// cache size
		s, err := ioutil.ReadFile(filepath.Join(p, d.Name(), "size"))
		if err != nil {
			return err
		}

		// add the info
		cpu.Cache[cacheID] = string(s[:len(s)-1])
		cpu.CacheIDs = append(cpu.CacheIDs, cacheID)
	}
	// sort the cache names
	sort.Strings(cpu.CacheIDs)

	return nil
}
1202545
func (c *Chunk) MemoryUsage() (sum int64) {
	for _, col := range c.columns {
		curColMemUsage := int64(unsafe.Sizeof(*col)) + int64(cap(col.nullBitmap)) + int64(cap(col.offsets)*4) + int64(cap(col.data)) + int64(cap(col.elemBuf))
		sum += curColMemUsage
	}
	return
}
898298
func (c *BitcoindClient) onRescanProgress(hash *chainhash.Hash, height int32,
	timestamp time.Time) {

	select {
	case c.notificationQueue.ChanIn() <- &RescanProgress{
		Hash:   hash,
		Height: height,
		Time:   timestamp,
	}:
	case <-c.quit:
	}
}
1105532
func probFalsePositive(l, k int, t, precision float64) float64 {
	return integral(falsePositive(l, k), 0, t, precision)
}