// ImageFsStats returns the stats of the image filesystem.
493233
func (p *criStatsProvider) ImageFsStats() (*statsapi.FsStats, error) {
	resp, err := p.imageService.ImageFsInfo()
	if err != nil {
		return nil, err
	}

	// CRI may return the stats of multiple image filesystems but we only
	// return the first one.
	//
	// TODO(yguo0905): Support returning stats of multiple image filesystems.
	for _, fs := range resp {
		s := &statsapi.FsStats{
			Time:      metav1.NewTime(time.Unix(0, fs.Timestamp)),
			UsedBytes: &fs.UsedBytes.Value,
		}
		if fs.InodesUsed != nil {
			s.InodesUsed = &fs.InodesUsed.Value
		}
		imageFsInfo := p.getFsInfo(fs.GetFsId())
		if imageFsInfo != nil {
			// The image filesystem id is unknown to the local node or there's
			// an error on retrieving the stats. In these cases, we omit those
			// stats and return the best-effort partial result. See
			// https://github.com/kubernetes/heapster/issues/1793.
			s.AvailableBytes = &imageFsInfo.Available
			s.CapacityBytes = &imageFsInfo.Capacity
			s.InodesFree = imageFsInfo.InodesFree
			s.Inodes = imageFsInfo.Inodes
		}
		return s, nil
	}

	return nil, fmt.Errorf("imageFs information is unavailable")
}
1330159
func (r *Runtime) ContainerStats(c *Container) (*ContainerStats, error) {
	impl, err := r.RuntimeImpl(c)
	if err != nil {
		return nil, err
	}

	return impl.ContainerStats(c)
}
284050
func (p *Partition) computeStats() {
	// Shallow copy the fileset and trim initial active log file.
	fs := *p.fileSet
	fs.files = fs.files[1:]

	// Compute stats on the remaining files.
	p.stats = fs.Stats()
}
160696
func (s *Store) Stats() (map[string]interface{}, error) {
	finfos, err := ioutil.ReadDir(s.dir)
	if err != nil {
		return nil, err
	}

	var numBytesUsedDisk uint64
	for _, finfo := range finfos {
		if !finfo.IsDir() {
			numBytesUsedDisk += uint64(finfo.Size())
		}
	}

	s.m.Lock()
	totPersists := s.totPersists
	totCompactions := s.totCompactions
	totCompactionsPartial := s.totCompactionsPartial
	numLastCompactionBeforeBytes := s.numLastCompactionBeforeBytes
	numLastCompactionAfterBytes := s.numLastCompactionAfterBytes
	totCompactionDecreaseBytes := s.totCompactionDecreaseBytes
	totCompactionIncreaseBytes := s.totCompactionIncreaseBytes
	maxCompactionDecreaseBytes := s.maxCompactionDecreaseBytes
	maxCompactionIncreaseBytes := s.maxCompactionIncreaseBytes
	totCompactionBeforeBytes := s.totCompactionBeforeBytes
	totCompactionWrittenBytes := s.totCompactionWrittenBytes
	s.m.Unlock()

	footer, err := s.snapshot()
	if err != nil {
		return nil, err
	}

	var numSegments uint64
	if footer != nil {
		footer.m.Lock()
		if footer.ss != nil {
			numSegments = uint64(len(footer.ss.a))
		}
		footer.m.Unlock()
	}

	footer.Close()

	files, numFilesOpen := s.allFiles()

	return map[string]interface{}{
		"num_bytes_used_disk":              numBytesUsedDisk,
		"total_persists":                   totPersists,
		"total_compactions":                totCompactions,
		"total_compactions_partial":        totCompactionsPartial,
		"total_compaction_before_bytes":    totCompactionBeforeBytes,
		"total_compaction_written_bytes":   totCompactionWrittenBytes,
		"num_segments":                     numSegments,
		"num_last_compaction_before_bytes": numLastCompactionBeforeBytes,
		"num_last_compaction_after_bytes":  numLastCompactionAfterBytes,
		"total_compaction_decrease_bytes":  totCompactionDecreaseBytes,
		"total_compaction_increase_bytes":  totCompactionIncreaseBytes,
		"max_compaction_decrease_bytes":    maxCompactionDecreaseBytes,
		"max_compaction_increase_bytes":    maxCompactionIncreaseBytes,
		"num_files":                        len(files),
		"num_files_open":                   numFilesOpen,
		"files":                            files,
	}, nil
}
1296580
func (sf64 *SliceFloat64) BuildStats() (SliceFloat64Stats, error) {
	stats := NewSliceFloat64Stats()
	stats.Len = sf64.Len()
	max, err := sf64.Max()
	if err != nil {
		return stats, err
	}
	stats.Max = max
	min, err := sf64.Min()
	if err != nil {
		return stats, err
	}
	stats.Min = min
	mean, err := sf64.Mean()
	if err != nil {
		return stats, err
	}
	stats.Mean = mean
	median, err := sf64.Median()
	if err != nil {
		return stats, err
	}
	stats.Median = median
	sum, err := sf64.Sum()
	if err != nil {
		return stats, err
	}
	stats.Sum = sum
	sf64.Stats = stats
	return stats, nil
}
770359
func (t *Torrent) allStats(f func(*ConnStats)) {
	f(&t.stats)
	f(&t.cl.stats)
}
1280841
func (fs MapFS) Lstat(p string) (os.FileInfo, error) {
	e, ok := fs[fixpath(p)]
	if ok {
		return e, nil
	}
	return nil, os.ErrNotExist
}
210340
func parseNFSEventsStats(ss []string) (*NFSEventsStats, error) {
	if len(ss) != fieldEventsLen {
		return nil, fmt.Errorf("invalid NFS events stats: %v", ss)
	}

	ns := make([]uint64, 0, fieldEventsLen)
	for _, s := range ss {
		n, err := strconv.ParseUint(s, 10, 64)
		if err != nil {
			return nil, err
		}

		ns = append(ns, n)
	}

	return &NFSEventsStats{
		InodeRevalidate:     ns[0],
		DnodeRevalidate:     ns[1],
		DataInvalidate:      ns[2],
		AttributeInvalidate: ns[3],
		VFSOpen:             ns[4],
		VFSLookup:           ns[5],
		VFSAccess:           ns[6],
		VFSUpdatePage:       ns[7],
		VFSReadPage:         ns[8],
		VFSReadPages:        ns[9],
		VFSWritePage:        ns[10],
		VFSWritePages:       ns[11],
		VFSGetdents:         ns[12],
		VFSSetattr:          ns[13],
		VFSFlush:            ns[14],
		VFSFsync:            ns[15],
		VFSLock:             ns[16],
		VFSFileRelease:      ns[17],
		CongestionWait:      ns[18],
		Truncation:          ns[19],
		WriteExtension:      ns[20],
		SillyRename:         ns[21],
		ShortRead:           ns[22],
		ShortWrite:          ns[23],
		JukeboxDelay:        ns[24],
		PNFSRead:            ns[25],
		PNFSWrite:           ns[26],
	}, nil
}
1011182
func ReadDiskStats(stats *DiskStats) error {
	// Open the process disk IO counter file
	inf, err := os.Open(fmt.Sprintf("/proc/%d/io", os.Getpid()))
	if err != nil {
		return err
	}
	defer inf.Close()
	in := bufio.NewReader(inf)

	// Iterate over the IO counter, and extract what we need
	for {
		// Read the next line and split to key and value
		line, err := in.ReadString('\n')
		if err != nil {
			if err == io.EOF {
				return nil
			}
			return err
		}
		parts := strings.Split(line, ":")
		if len(parts) != 2 {
			continue
		}
		key := strings.TrimSpace(parts[0])
		value, err := strconv.ParseInt(strings.TrimSpace(parts[1]), 10, 64)
		if err != nil {
			return err
		}

		// Update the counter based on the key
		switch key {
		case "syscr":
			stats.ReadCount = value
		case "syscw":
			stats.WriteCount = value
		case "rchar":
			stats.ReadBytes = value
		case "wchar":
			stats.WriteBytes = value
		}
	}
}
770982
func (r *RemoteImageService) ImageFsInfo() ([]*runtimeapi.FilesystemUsage, error) {
	// Do not set timeout, because `ImageFsInfo` takes time.
	// TODO(random-liu): Should we assume runtime should cache the result, and set timeout here?
	ctx, cancel := getContextWithCancel()
	defer cancel()

	resp, err := r.imageClient.ImageFsInfo(ctx, &runtimeapi.ImageFsInfoRequest{})
	if err != nil {
		klog.Errorf("ImageFsInfo from image service failed: %v", err)
		return nil, err
	}
	return resp.GetImageFilesystems(), nil
}
475280
func (rfs *RootFS) Lstat(filename string) (fi os.FileInfo, err error) {
	if filename == "" {
		filename = "."
	}
	if filename == "." {
		return &wrappedReadFileInfo{
			"keybase", 0, rfs.config.Clock().Now(), true}, nil
	}
	if !rootWrappedNodeNames[filename] {
		return nil, os.ErrNotExist
	}

	switch filename {
	case StatusFileName:
		wrf := &wrappedReadFile{
			name: StatusFileName,
			reader: func(ctx context.Context) ([]byte, time.Time, error) {
				return GetEncodedStatus(ctx, rfs.config)
			},
			log: rfs.log,
		}
		return wrf.GetInfo(), nil
	default:
		panic(fmt.Sprintf("Name %s was in map, but not in switch", filename))
	}
}
494274
func (ds *dockerService) ImageFsInfo(_ context.Context, _ *runtimeapi.ImageFsInfoRequest) (*runtimeapi.ImageFsInfoResponse, error) {
	info, err := ds.client.Info()
	if err != nil {
		klog.Errorf("Failed to get docker info: %v", err)
		return nil, err
	}

	statsClient := &winstats.StatsClient{}
	fsinfo, err := statsClient.GetDirFsInfo(info.DockerRootDir)
	if err != nil {
		klog.Errorf("Failed to get dir fsInfo for %q: %v", info.DockerRootDir, err)
		return nil, err
	}

	filesystems := []*runtimeapi.FilesystemUsage{
		{
			Timestamp: time.Now().UnixNano(),
			UsedBytes: &runtimeapi.UInt64Value{Value: fsinfo.Usage},
			FsId: &runtimeapi.FilesystemIdentifier{
				Mountpoint: info.DockerRootDir,
			},
		},
	}

	return &runtimeapi.ImageFsInfoResponse{ImageFilesystems: filesystems}, nil
}
837957
func inodeClusteringStats(us []uint32) (InodeClusteringStats, error) {
	if l := len(us); l != 3 {
		return InodeClusteringStats{}, fmt.Errorf("incorrect number of values for XFS inode clustering stats: %d", l)
	}

	return InodeClusteringStats{
		Iflush:     us[0],
		Flush:      us[1],
		FlushInode: us[2],
	}, nil
}
923694
func (f *File) Stat() (os.FileInfo, error) {
	fs, err := f.c.fstat(f.handle)
	if err != nil {
		return nil, err
	}
	return fileInfoFromStat(fs, path.Base(f.path)), nil
}
654271
func (fs *RootMappingFs) Stat(name string) (os.FileInfo, error) {
	if fs.isRoot(name) {
		return newRootMappingDirFileInfo(name), nil
	}
	realName := fs.realName(name)

	fi, err := fs.Fs.Stat(realName)
	if rfi, ok := fi.(RealFilenameInfo); ok {
		return rfi, err
	}

	return &realFilenameInfo{FileInfo: fi, realFilename: realName}, err

}
620760
func (s *SimpleFSHandler) SimpleFSSetStat(ctx context.Context, arg keybase1.SimpleFSSetStatArg) error {
	ctx, cancel := s.wrapContextWithTimeout(ctx)
	defer cancel()
	cli, err := s.client()
	if err != nil {
		return err
	}
	return cli.SimpleFSSetStat(ctx, arg)
}
791263
func (p *cadvisorStatsProvider) ImageFsDevice() (string, error) {
	imageFsInfo, err := p.cadvisor.ImagesFsInfo()
	if err != nil {
		return "", err
	}
	return imageFsInfo.Device, nil
}