// GetDiskUsageStats accepts a path to a directory or file
// and returns the number of bytes and inodes used by the path
174555
func GetDiskUsageStats(path string) (dirSize, inodeCount uint64, err error) {
	err = filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
		// Walk does not follow symbolic links
		if err != nil {
			return err
		}

		dirSize += uint64(info.Size())
		inodeCount++

		return nil
	})

	if err != nil {
		return 0, 0, err
	}

	return dirSize, inodeCount, err
}
1287934
func readInt64Stats(dir string) (results map[string]int64, err error) {
	finfos, err := ioutil.ReadDir(dir)
	if err != nil {
		return nil, err
	}

	results = make(map[string]int64)
	for _, finfo := range finfos {
		if finfo.IsDir() {
			continue
		}
		fname := path.Join(dir, finfo.Name())
		data, err := ioutil.ReadFile(fname)
		if err != nil {
			return nil, err
		}
		i, err := strconv.ParseInt(strings.TrimSpace(string(data)), 10, 64)
		if err != nil {
			return nil, err
		}
		results[finfo.Name()] = i
	}
	return results, nil
}
853229
func (e *RuntimeStatsColl) GetRootStats(planID string) *RuntimeStats {
	e.mu.Lock()
	defer e.mu.Unlock()
	runtimeStats, exists := e.rootStats[planID]
	if !exists {
		runtimeStats = &RuntimeStats{}
		e.rootStats[planID] = runtimeStats
	}
	return runtimeStats
}
1126180
func (c *sioClient) getSioDiskPaths() ([]os.FileInfo, error) {
	files, err := ioutil.ReadDir(sioDiskIDPath)
	if err != nil {
		if os.IsNotExist(err) {
			// sioDiskIDPath may not exist yet which is fine
			return []os.FileInfo{}, nil
		}
		klog.Error(log("failed to ReadDir %s: %v", sioDiskIDPath, err))
		return nil, err

	}
	result := []os.FileInfo{}
	for _, file := range files {
		if c.diskRegex.MatchString(file.Name()) {
			result = append(result, file)
		}
	}

	return result, nil

}
1052926
func getDeviceResources(deviceGroupStats []*api.DeviceGroupStats) []string {
	statsSummaryMap := buildDeviceStatsSummaryMap(deviceGroupStats)

	result := make([]string, 0, len(statsSummaryMap))
	for id, stats := range statsSummaryMap {
		result = append(result, id+"|"+stats.String())
	}

	sort.Strings(result)

	return result
}
834618
func GetDisks(ctx types.Context) (map[string]string, error) {
	disksJSON, err := getMetadata(ctx, diskURL)
	if err != nil {
		return nil, err
	}

	disks := make(map[string]string)
	diskList := make([]*Disk, 1, 1)

	// TODO: fix taking the bytes from original request being returned
	// as a string, only to be cast back to byte here
	err = json.Unmarshal([]byte(disksJSON), &diskList)
	if err != nil {
		return nil, err
	}

	for _, disk := range diskList {
		disks[disk.DeviceName] = disk.DeviceName
	}

	return disks, nil
}
98521
func getFileOwnerAndMode(path string) (int, int, os.FileMode) {
	finfo, err := os.Stat(path)
	if err != nil {
		return 0, 0, 0
	}
	return int(finfo.Sys().(*syscall.Stat_t).Uid), int(finfo.Sys().(*syscall.Stat_t).Gid), finfo.Mode()
}
1001999
func (cs *Stats) GetStatistics() StatsEntry {
	cs.mutex.Lock()
	defer cs.mutex.Unlock()
	return cs.StatsEntry
}
944767
func (h *HostStatsCollector) toDiskStats(usage *disk.UsageStat, partitionStat *disk.PartitionStat) *DiskStats {
	ds := DiskStats{
		Size:              usage.Total,
		Used:              usage.Used,
		Available:         usage.Free,
		UsedPercent:       usage.UsedPercent,
		InodesUsedPercent: usage.InodesUsedPercent,
	}
	if math.IsNaN(ds.UsedPercent) {
		ds.UsedPercent = 0.0
	}
	if math.IsNaN(ds.InodesUsedPercent) {
		ds.InodesUsedPercent = 0.0
	}

	if partitionStat != nil {
		ds.Device = partitionStat.Device
		ds.Mountpoint = partitionStat.Mountpoint
	}

	return &ds
}
698417
func inodeOperationStats(us []uint32) (InodeOperationStats, error) {
	if l := len(us); l != 7 {
		return InodeOperationStats{}, fmt.Errorf("incorrect number of values for XFS inode operation stats: %d", l)
	}

	return InodeOperationStats{
		Attempts:        us[0],
		Found:           us[1],
		Recycle:         us[2],
		Missed:          us[3],
		Duplicate:       us[4],
		Reclaims:        us[5],
		AttributeChange: us[6],
	}, nil
}
1069474
func ReadDiskstat() ([]*DiskStatsProxy, error) {

	diskstatsproxies := []*DiskStatsProxy{}
	file, err := os.Open(diskStatFile)
	if err != nil {
		return nil, err
	}
	defer file.Close()
	scanner := bufio.NewScanner(file)

	for scanner.Scan() {
		line := strings.Fields(scanner.Text())
		if len(line) != 14 {
			err = fmt.Errorf("malformed diskstat line: %s", scanner.Text())
			return nil, err
		}

		// Each disk should only exist once in /proc/diskstat, error out if we find a dupe
		for _, proxy := range diskstatsproxies {
			if line[2] == proxy.Disk {
				return nil, fmt.Errorf("duplicate entry for disk %s found", line[2])
			}
		}

		major, err := strconv.ParseUint(line[0], 10, 8)
		if err != nil {
			return nil, fmt.Errorf("unable to convert major device number: %s", err)
		}
		minor, err := strconv.ParseUint(line[1], 10, 8)
		if err != nil {
			return nil, fmt.Errorf("unable to convert minor device number: %s", err)
		}
		stat := Diskstat{}
		for i := 3; i < len(line); i++ {
			switch i {
			case 3:
				err = parseInt64Line(line[i], &stat.NReads)
			case 4:
				err = parseInt64Line(line[i], &stat.NReadsMerged)
			case 5:
				err = parseInt64Line(line[i], &stat.NSectorsRead)
			case 6:
				err = parseInt64Line(line[i], &stat.NMsReading)
			case 7:
				err = parseInt64Line(line[i], &stat.NWrites)
			case 8:
				err = parseInt64Line(line[i], &stat.NWritesMerged)
			case 9:
				err = parseInt64Line(line[i], &stat.NSectorsWritten)
			case 10:
				err = parseInt64Line(line[i], &stat.NMsWriting)
			case 11:
				err = parseInt64Line(line[i], &stat.NIoInProgress)
			case 12:
				err = parseInt64Line(line[i], &stat.NMsIo)
			case 13:
				err = parseInt64Line(line[i], &stat.NMsIoWeighted)
			}

			if err != nil {
				return nil, err
			}
		}
		diskstatsproxies = append(diskstatsproxies, &DiskStatsProxy{Disk: line[2], Major: uint8(major), Minor: uint8(minor), Stats: &stat})
	}

	return diskstatsproxies, nil
}
153485
func (md *metricsStatFS) getFsInfo(metrics *Metrics) error {
	available, capacity, usage, inodes, inodesFree, inodesUsed, err := fs.FsInfo(md.path)
	if err != nil {
		return NewFsInfoFailedError(err)
	}
	metrics.Available = resource.NewQuantity(available, resource.BinarySI)
	metrics.Capacity = resource.NewQuantity(capacity, resource.BinarySI)
	metrics.Used = resource.NewQuantity(usage, resource.BinarySI)
	metrics.Inodes = resource.NewQuantity(inodes, resource.BinarySI)
	metrics.InodesFree = resource.NewQuantity(inodesFree, resource.BinarySI)
	metrics.InodesUsed = resource.NewQuantity(inodesUsed, resource.BinarySI)
	return nil
}
911952
func (fs *Datastore) readDiskUsageFile() int64 {
	fpath := filepath.Join(fs.path, DiskUsageFile)
	duB, err := ioutil.ReadFile(fpath)
	if err != nil {
		return 0
	}
	err = json.Unmarshal(duB, &fs.storedValue)
	if err != nil {
		return 0
	}
	return fs.storedValue.DiskUsage
}
716852
func getDiskUsage(ctx context.Context, root string, usageFn usageFunc) error {
	return walk(ctx, root+slashSeparator, usageFn)
}
844713
func (c *filesystemCollector) GetStats() ([]filesystemStats, error) {
	mps, err := mountPointDetails()
	if err != nil {
		return nil, err
	}
	stats := []filesystemStats{}
	for _, labels := range mps {
		if c.ignoredMountPointsPattern.MatchString(labels.mountPoint) {
			log.Debugf("Ignoring mount point: %s", labels.mountPoint)
			continue
		}
		if c.ignoredFSTypesPattern.MatchString(labels.fsType) {
			log.Debugf("Ignoring fs type: %s", labels.fsType)
			continue
		}
		stuckMountsMtx.Lock()
		if _, ok := stuckMounts[labels.mountPoint]; ok {
			stats = append(stats, filesystemStats{
				labels:      labels,
				deviceError: 1,
			})
			log.Debugf("Mount point %q is in an unresponsive state", labels.mountPoint)
			stuckMountsMtx.Unlock()
			continue
		}
		stuckMountsMtx.Unlock()

		// The success channel is used do tell the "watcher" that the stat
		// finished successfully. The channel is closed on success.
		success := make(chan struct{})
		go stuckMountWatcher(labels.mountPoint, success)

		buf := new(syscall.Statfs_t)
		err = syscall.Statfs(rootfsFilePath(labels.mountPoint), buf)

		stuckMountsMtx.Lock()
		close(success)
		// If the mount has been marked as stuck, unmark it and log it's recovery.
		if _, ok := stuckMounts[labels.mountPoint]; ok {
			log.Debugf("Mount point %q has recovered, monitoring will resume", labels.mountPoint)
			delete(stuckMounts, labels.mountPoint)
		}
		stuckMountsMtx.Unlock()

		if err != nil {
			stats = append(stats, filesystemStats{
				labels:      labels,
				deviceError: 1,
			})
			log.Debugf("Error on statfs() system call for %q: %s", rootfsFilePath(labels.mountPoint), err)
			continue
		}

		var ro float64
		for _, option := range strings.Split(labels.options, ",") {
			if option == "ro" {
				ro = 1
				break
			}
		}

		stats = append(stats, filesystemStats{
			labels:    labels,
			size:      float64(buf.Blocks) * float64(buf.Bsize),
			free:      float64(buf.Bfree) * float64(buf.Bsize),
			avail:     float64(buf.Bavail) * float64(buf.Bsize),
			files:     float64(buf.Files),
			filesFree: float64(buf.Ffree),
			ro:        ro,
		})
	}
	return stats, nil
}
582084
func (c *Client) GetStats(i *GetStatsInput) (*StatsResponse, error) {

	p := "/stats"

	if i.Service != "" {
		p = fmt.Sprintf("%s/service/%s", p, i.Service)
	}

	if i.Field != "" {
		p = fmt.Sprintf("%s/field/%s", p, i.Field)
	}

	r, err := c.Get(p, &RequestOptions{
		Params: map[string]string{
			"from":   i.From,
			"to":     i.To,
			"by":     i.By,
			"region": i.Region,
		},
	})
	if err != nil {
		return nil, err
	}

	var sr *StatsResponse
	if err := decodeJSON(&sr, r.Body); err != nil {
		return nil, err
	}

	return sr, nil
}
1116496
func getFilesystemStats(dev string) (uint64, uint64, uint64, error) {
	totalBlocks, usedBlocks, freeBlocks, err := getMountedFilesystemStats(dev)
	// Catch the errFilesystemNotMounted and try getUnmountedFilesystemStats
	if err == errFilesystemNotMounted {
		totalBlocks, usedBlocks, freeBlocks, err = getUnmountedFilesystemStats(dev)
		if err != nil {
			return 0, 0, 0, err
		}
	} else if err != nil {
		return 0, 0, 0, err
	}
	return totalBlocks, usedBlocks, freeBlocks, err
}