// Returns an initialized Profiler; ready to use. Upon creation, a
// /proc/diskstats snapshot is taken so that any Get() will return valid
// information.
761315
func NewProfiler() (prof *Profiler, err error) {
	p, err := usage.NewProfiler()
	if err != nil {
		return nil, err
	}
	return &Profiler{Profiler: p}, nil
}
1143807
func (remote *RemoteDebugger) StartProfiler() error {
	_, err := remote.SendRequest("Profiler.start", nil)
	return err
}
1128975
func diskStats() (*disk, error) {
	var (
		freeBytes  uint64 = 0
		totalBytes uint64 = 0
	)

	// windows sets return value to 0 when function fails.
	ret, _, err := procGetDiskFreeSpaceExW.Call(
		0,
		uintptr(unsafe.Pointer(&freeBytes)),
		uintptr(unsafe.Pointer(&totalBytes)),
		0,
	)
	if ret == 0 {
		return nil, err
	}

	// diskStats functions from other platforms return disk usage in kiB.
	return &disk{
		Usage: (totalBytes - freeBytes) / 1024,
		Total: totalBytes / 1024,
	}, nil
}
1236776
func GetDeviceProfileCache(p *redis.Pool, id uuid.UUID) (DeviceProfile, error) {
	var dp DeviceProfile
	key := fmt.Sprintf(DeviceProfileKeyTempl, id)

	c := p.Get()
	defer c.Close()

	val, err := redis.Bytes(c.Do("GET", key))
	if err != nil {
		if err == redis.ErrNil {
			return dp, ErrDoesNotExist
		}
		return dp, errors.Wrap(err, "get error")
	}

	err = gob.NewDecoder(bytes.NewReader(val)).Decode(&dp)
	if err != nil {
		return dp, errors.Wrap(err, "gob decode error")
	}

	return dp, nil
}
41977
func (p *Profiler) Start() error {
	if p.Dir == "" {
		if p.ProfileCPU {
			return errors.New("-profile-cpu requires -profile-output-dir to be set")
		}
		if p.ProfileHeap {
			return errors.New("-profile-heap requires -profile-output-dir to be set")
		}
	}

	if p.ProfileCPU {
		out, err := os.Create(p.generateOutPath("cpu"))
		if err != nil {
			return errors.Annotate(err, "failed to create CPU profile output file").Err()
		}
		pprof.StartCPUProfile(out)
		p.profilingCPU = true
	}

	if p.BindHTTP != "" {
		if err := p.startHTTP(); err != nil {
			return errors.Annotate(err, "failed to start HTTP server").Err()
		}
	}

	return nil
}
544615
func NewProfiler() *Profiler {
	prof := cpux.NewProfiler()
	return &Profiler{Profiler: prof, Builder: fb.NewBuilder(0)}
}
528028
func NewDiskstatsCollector() (Collector, error) {
	var diskLabelNames = []string{"device"}

	return &diskstatsCollector{
		ignoredDevicesPattern: regexp.MustCompile(*ignoredDevices),
		descs: []typedFactorDesc{
			{
				desc: readsCompletedDesc, valueType: prometheus.CounterValue,
			},
			{
				desc: prometheus.NewDesc(
					prometheus.BuildFQName(namespace, diskSubsystem, "reads_merged_total"),
					"The total number of reads merged.",
					diskLabelNames,
					nil,
				), valueType: prometheus.CounterValue,
			},
			{
				desc: readBytesDesc, valueType: prometheus.CounterValue,
				factor: diskSectorSize,
			},
			{
				desc: readTimeSecondsDesc, valueType: prometheus.CounterValue,
				factor: .001,
			},
			{
				desc: writesCompletedDesc, valueType: prometheus.CounterValue,
			},
			{
				desc: prometheus.NewDesc(
					prometheus.BuildFQName(namespace, diskSubsystem, "writes_merged_total"),
					"The number of writes merged.",
					diskLabelNames,
					nil,
				), valueType: prometheus.CounterValue,
			},
			{
				desc: writtenBytesDesc, valueType: prometheus.CounterValue,
				factor: diskSectorSize,
			},
			{
				desc: writeTimeSecondsDesc, valueType: prometheus.CounterValue,
				factor: .001,
			},
			{
				desc: prometheus.NewDesc(
					prometheus.BuildFQName(namespace, diskSubsystem, "io_now"),
					"The number of I/Os currently in progress.",
					diskLabelNames,
					nil,
				), valueType: prometheus.GaugeValue,
			},
			{
				desc: ioTimeSecondsDesc, valueType: prometheus.CounterValue,
				factor: .001,
			},
			{
				desc: prometheus.NewDesc(
					prometheus.BuildFQName(namespace, diskSubsystem, "io_time_weighted_seconds_total"),
					"The weighted # of seconds spent doing I/Os.",
					diskLabelNames,
					nil,
				), valueType: prometheus.CounterValue,
				factor: .001,
			},
			{
				desc: prometheus.NewDesc(
					prometheus.BuildFQName(namespace, diskSubsystem, "discards_completed_total"),
					"The total number of discards completed successfully.",
					diskLabelNames,
					nil,
				), valueType: prometheus.CounterValue,
			},
			{
				desc: prometheus.NewDesc(
					prometheus.BuildFQName(namespace, diskSubsystem, "discards_merged_total"),
					"The total number of discards merged.",
					diskLabelNames,
					nil,
				), valueType: prometheus.CounterValue,
			},
			{
				desc: prometheus.NewDesc(
					prometheus.BuildFQName(namespace, diskSubsystem, "discarded_sectors_total"),
					"The total number of sectors discarded successfully.",
					diskLabelNames,
					nil,
				), valueType: prometheus.CounterValue,
			},
			{
				desc: prometheus.NewDesc(
					prometheus.BuildFQName(namespace, diskSubsystem, "discard_time_seconds_total"),
					"This is the total number of seconds spent by all discards.",
					diskLabelNames,
					nil,
				), valueType: prometheus.CounterValue,
				factor: .001,
			},
		},
	}, nil
}
293527
func Get() (stat *CPUStats, err error) {
	stdMu.Lock()
	defer stdMu.Unlock()
	if std == nil {
		std, err = NewProfiler()
		if err != nil {
			return nil, err
		}
	}
	return std.Get()
}
881360
func (s *Server) GetNICsFromProfile(profName string) (map[string]device, error) {
	profile, _, err := s.GetProfile(lxdDefaultProfileName)
	if err != nil {
		return nil, errors.Trace(err)
	}

	nics := getProfileNICs(profile)
	for name := range nics {
		if nics[name]["hwaddr"] == "" {
			nics[name]["hwaddr"] = network.GenerateVirtualMACAddress()
		}
	}
	return nics, nil
}
1228998
func (c *Client) GetAccountProfile(ctx context.Context) (*Profile, error) {
	var profile Profile

	req, err := c.NewRequest("GET", profilePath, nil, nil)
	if err != nil {
		return nil, err
	}

	if err := c.Do(ctx, req, &profile); err != nil {
		return nil, err
	}

	return &profile, err
}
117769
func (prof *Profiler) Get() (nodes *Nodes, err error) {
	nodes = &Nodes{}
	var x int32 // index of nodeX currently being processed.

	// First see if the node dir exists, return any error.
	_, err = os.Stat(prof.nodePath)
	if err != nil {
		return nil, err
	}
	// Loop and increment x after each dir read; stop when the nodeX dir to be
	// processed doesn't exist.
	for {
		var n Node
		p := prof.nodeXPath(x)
		// get the cpulist
		n.ID = x
		n.CPUList, err = prof.CPUList(p)
		if err != nil {
			// if the dir didn't exist; there are no more nodes to process
			if os.IsNotExist(err) {
				return nodes, nil
			}
			// any other error will be passed back
			return nil, err
		}
		nodes.Node = append(nodes.Node, n)
		x++
	}
}
827512
func (cache *diskBlockCacheWrapped) GetPrefetchStatus(
	ctx context.Context, tlfID tlf.ID, blockID kbfsblock.ID,
	cacheType DiskBlockCacheType) (prefetchStatus PrefetchStatus, err error) {
	cache.mtx.RLock()
	defer cache.mtx.RUnlock()

	// Try the sync cache first unless working set cache is required.
	if cacheType != DiskBlockWorkingSetCache {
		md, err := cache.syncCache.GetMetadata(ctx, blockID)
		switch errors.Cause(err) {
		case nil:
			return md.PrefetchStatus(), nil
		case ldberrors.ErrNotFound:
			if cacheType == DiskBlockSyncCache {
				// Try moving the block and getting it again.
				moved := cache.moveBetweenCachesLocked(
					ctx, tlfID, blockID, cacheType)
				if moved {
					md, err := cache.syncCache.GetMetadata(ctx, blockID)
					if err != nil {
						return NoPrefetch, err
					}
					return md.PrefetchStatus(), nil
				}
				return NoPrefetch, err
			}
			// Otherwise try the working set cache below.
		default:
			return NoPrefetch, err
		}
	}

	md, err := cache.workingSetCache.GetMetadata(ctx, blockID)
	if err != nil {
		return NoPrefetch, err
	}
	return md.PrefetchStatus(), nil
}
93152
func GetDefaultProfile(rs *specs.Spec) (*specs.LinuxSeccomp, error) {
	return setupSeccomp(DefaultProfile(), rs)
}
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
}
203262
func (prof *Profiler) Get() (*structs.DevInfo, error) {
	var (
		i, pos, line, fieldNum int
		n                      uint64
		v                      byte
		dev                  structs.Device
	)
	err := prof.Reset()
	if err != nil {
		return nil, err
	}
	// there's, usually, at least 2 devices
	nDev := &structs.DevInfo{Timestamp: time.Now().UTC().UnixNano(), Device: make([]structs.Device, 0, 2)}
	for {
		prof.Line, err = prof.ReadSlice('\n')
		if err != nil {
			if err == io.EOF {
				break
			}
			return nil, &joe.ReadError{Err: err}
		}
		line++
		if line < 3 {
			continue
		}
		prof.Val = prof.Val[:0]
		// first grab the interface name (everything up to the ':')
		for i, v = range prof.Line {
			if v == 0x3A {
				pos = i + 1
				break
			}
			// skip spaces
			if v == 0x20 {
				continue
			}
			prof.Val = append(prof.Val, v)
		}
		dev.Name = string(prof.Val[:])
		fieldNum = 0
		// process the rest of the line
		for {
			fieldNum++
			// skip all spaces
			for i, v = range prof.Line[pos:] {
				if v != 0x20 {
					pos += i
					break
				}
			}

			// grab the numbers
			for i, v = range prof.Line[pos:] {
				if v == 0x20 || v == '\n' {
					break
				}
			}
			// any conversion error results in 0
			n, err = helpers.ParseUint(prof.Line[pos : pos+i])
			pos += i
			if err != nil {
				return nil, &joe.ParseError{Info: fmt.Sprintf("line %d: field %d", line, fieldNum), Err: err}
			}
			if fieldNum < 9 {
				if fieldNum < 5 {
					if fieldNum < 3 {
						if fieldNum == 1 {
							dev.RBytes = int64(n)
							continue
						}
						dev.RPackets = int64(n) // must be 2
						continue
					}
					if fieldNum == 3 {
						dev.RErrs = int64(n)
						continue
					}
					dev.RDrop = int64(n) // must be 4
					continue
				}
				if fieldNum < 7 {
					if fieldNum == 5 {
						dev.RFIFO = int64(n)
						continue
					}
					dev.RFrame = int64(n) // must be 6
					continue
				}
				if fieldNum == 7 {
					dev.RCompressed = int64(n)
					continue
				}
				dev.RMulticast = int64(n) // must be 8
				continue
			}
			if fieldNum < 13 {
				if fieldNum < 11 {
					if fieldNum == 9 {
						dev.TBytes = int64(n)
						continue
					}
					dev.TPackets = int64(n) // must be 10
					continue
				}
				if fieldNum == 11 {
					dev.TErrs = int64(n)
					continue
				}
				dev.TDrop = int64(n) // must be 12
				continue
			}
			if fieldNum < 15 {
				if fieldNum == 13 {
					dev.TFIFO = int64(n)
					continue
				}
				dev.TColls = int64(n) // must be 14
				continue
			}
			if fieldNum == 15 {
				dev.TCarrier = int64(n)
				continue
			}
			dev.TCompressed = int64(n)
			break
		}
		nDev.Device = append(nDev.Device, dev)
	}
	return nDev, nil
}
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
}
983080
func getHeapProfile(w http.ResponseWriter, r *http.Request) {
	// Ensure up-to-date data.
	runtime.GC()
	w.Header().Set("Content-Type", "application/octet-stream")
	if err := pprof.Lookup("heap").WriteTo(w, 0); err != nil {
		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
		w.WriteHeader(http.StatusInternalServerError)
		fmt.Fprintf(w, "Could not get heap profile: %s\n", err)
	}
}