当前位置: 首页>>代码示例>>Golang>>正文


Golang disk.DiskUsage函数代码示例

本文整理汇总了Golang中github.com/shirou/gopsutil/disk.DiskUsage函数的典型用法代码示例。如果您正苦于以下问题:Golang DiskUsage函数的具体用法?Golang DiskUsage怎么用?Golang DiskUsage使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了DiskUsage函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。

示例1: jsonDiskInfo

func jsonDiskInfo() []byte {

	type DiskStat struct {
		Partition disk.DiskPartitionStat
		Usage     disk.DiskUsageStat
		Counters  disk.DiskIOCountersStat
	}

	var disks []DiskStat
	partitions, _ := disk.DiskPartitions(false)
	c := &DiskStat{}
	IOCounters, _ := disk.DiskIOCounters()

	for _, singleDisk := range partitions {
		if !strings.HasPrefix(singleDisk.Device, "/") {
			continue
		}
		usage, _ := disk.DiskUsage(singleDisk.Mountpoint)
		c.Partition = singleDisk
		c.Usage = *usage
		c.Counters = IOCounters[strings.Split(singleDisk.Device, "/")[2]]
		disks = append(disks, *c)
	}
	jsonPartitions, _ := json.Marshal(disks)
	return jsonPartitions
}
开发者ID:daniellawrence,项目名称:go-go-serverinfo,代码行数:26,代码来源:gather.go

示例2: buildData

func (d *Du) buildData(path string) error {
	path = strings.TrimSpace(path)

	pathStat, err := os.Stat(path)
	if err != nil {
		return err
	}

	if !pathStat.IsDir() {
		return errors.New(fmt.Sprintf("%v is not a directory.", path))
	}

	duStat, err := gopsutil_disk.DiskUsage(path)
	if err == nil {
		d.Data[path] = make(map[string]interface{})
		d.Data[path]["Path"] = duStat.Path
		d.Data[path]["Total"] = duStat.Total
		d.Data[path]["Free"] = duStat.Free
		d.Data[path]["InodesTotal"] = duStat.InodesTotal
		d.Data[path]["InodesFree"] = duStat.InodesFree
		d.Data[path]["InodesUsed"] = duStat.InodesUsed
		d.Data[path]["Used"] = duStat.Used

		if duStat.InodesTotal != 0 {
			d.Data[path]["InodesUsedPercent"] = duStat.InodesUsedPercent
		}

		if duStat.Total != 0 {
			d.Data[path]["UsedPercent"] = duStat.UsedPercent
		}
	}
	return err
}
开发者ID:simudream,项目名称:resourced,代码行数:33,代码来源:du.go

示例3: GetNodeResource

/**
	read node resource usage
**/
func GetNodeResource(w http.ResponseWriter, r *http.Request) {
	// get this node memory
	memory, _ := mem.VirtualMemory()
	// get this node cpu percent usage
	cpu_percent, _ := cpu.CPUPercent(time.Duration(1)*time.Second, false)
	// Disk mount Point
	disk_partitions, _ := disk.DiskPartitions(true)
	// Disk usage
	var disk_usages []*disk.DiskUsageStat
	for _, disk_partition := range disk_partitions {
		if disk_partition.Mountpoint == "/" || disk_partition.Mountpoint == "/home" {
			disk_stat, _ := disk.DiskUsage(disk_partition.Device)
			disk_usages = append(disk_usages, disk_stat)
		}
	}
	// Network
	network, _ := net.NetIOCounters(false)

	// create new node obj with resource usage information
	node_metric := thoth.NodeMetric{
		Cpu:       cpu_percent,
		Memory:    memory,
		DiskUsage: disk_usages,
		Network:   network,
	}

	node_json, err := json.MarshalIndent(node_metric, "", "\t")
	if err != nil {
		fmt.Println("error:", err)
	}
	fmt.Fprint(w, string(node_json))
}
开发者ID:SOUP-CE-KMITL,项目名称:Thoth,代码行数:35,代码来源:handler.go

示例4: RecordDiskUsage

func RecordDiskUsage(path string) {
	c := time.Tick(30 * time.Second)
	for now := range c {
		usage, err := disk.DiskUsage(path)
		if err != nil {
			log.Println(err)
		}
		fmt.Printf("disk size %d bytes at %d seconds\n", usage.Used, now.Unix())
	}
}
开发者ID:sheki,项目名称:rocksiterbench,代码行数:10,代码来源:disk_stats.go

示例5: updateDisk

func updateDisk() {
	disks, err = disk.DiskPartitions(true)
	log.Printf("updateDisk(): %v", spew.Sdump(disks))
	if err != nil {
		log.Fatal(err)
	}

	disksUsage, err = disk.DiskUsage("/")
	log.Printf("updateDisk(): %v", spew.Sdump(disksUsage))
	if err != nil {
		log.Fatal(err)
	}
}
开发者ID:ashmckenzie,项目名称:sysdeets,代码行数:13,代码来源:main.go

示例6: DiskUsage

// DiskUsage - return a list with disk usage structs
func DiskUsage() (DiskUsageList, error) {
	parts, err := disk.DiskPartitions(false)
	if err != nil {
		diskLogger.Errorf("Error getting disk usage info: %v", err)
	}

	var usage DiskUsageList

	for _, p := range parts {
		if _, err := os.Stat(p.Mountpoint); err == nil {
			du, err := disk.DiskUsage(p.Mountpoint)
			if err != nil {
				diskLogger.Errorf("Error getting disk usage for Mount: %v", err)
			}

			if !isPseudoFS(du.Fstype) && !removableFs(du.Path) {

				TotalMB, _ := util.ConvertBytesTo(du.Total, "mb", 0)
				FreeMB, _ := util.ConvertBytesTo(du.Free, "mb", 0)
				UsedMB, _ := util.ConvertBytesTo(du.Used, "mb", 0)

				UsedPercent := 0.0
				if TotalMB > 0 && UsedMB > 0 {
					UsedPercent = (float64(du.Used) / float64(du.Total)) * 100.0
					UsedPercent, _ = util.FloatDecimalPoint(UsedPercent, 2)
					DeviceName := strings.Replace(p.Device, "/dev/", "", -1)

					TotalMBFormatted, _ := util.FloatToString(TotalMB)
					FreeMBFormatted, _ := util.FloatToString(FreeMB)
					UsedMBFormatted, _ := util.FloatToString(UsedMB)

					d := DiskUsageStruct{
						Name:        DeviceName,
						Path:        du.Path,
						Fstype:      du.Fstype,
						Total:       TotalMBFormatted,
						Free:        FreeMBFormatted,
						Used:        UsedMBFormatted,
						UsedPercent: UsedPercent,
					}

					usage = append(usage, d)

				}

			}
		}
	}

	return usage, err
}
开发者ID:0-T-0,项目名称:amonagent,代码行数:52,代码来源:disk.go

示例7: DiskUsage

func (s *systemPS) DiskUsage(
	mountPointFilter []string,
	fstypeExclude []string,
) ([]*disk.DiskUsageStat, error) {
	parts, err := disk.DiskPartitions(true)
	if err != nil {
		return nil, err
	}

	// Make a "set" out of the filter slice
	mountPointFilterSet := make(map[string]bool)
	for _, filter := range mountPointFilter {
		mountPointFilterSet[filter] = true
	}
	fstypeExcludeSet := make(map[string]bool)
	for _, filter := range fstypeExclude {
		fstypeExcludeSet[filter] = true
	}

	var usage []*disk.DiskUsageStat

	for _, p := range parts {
		if len(mountPointFilter) > 0 {
			// If the mount point is not a member of the filter set,
			// don't gather info on it.
			_, ok := mountPointFilterSet[p.Mountpoint]
			if !ok {
				continue
			}
		}
		if _, err := os.Stat(p.Mountpoint); err == nil {
			du, err := disk.DiskUsage(p.Mountpoint)
			if err != nil {
				return nil, err
			}
			// If the mount point is a member of the exclude set,
			// don't gather info on it.
			_, ok := fstypeExcludeSet[p.Fstype]
			if ok {
				continue
			}
			du.Fstype = p.Fstype
			usage = append(usage, du)
		}
	}

	return usage, nil
}
开发者ID:cwegener,项目名称:telegraf,代码行数:48,代码来源:ps.go

示例8: initDiskInfo

func initDiskInfo(monitorData *monitoringData) error {
	partitions, err := disk.DiskPartitions(true)
	monitorData.DiskStats = make(map[string]disk.DiskUsageStat)

	if err == nil {
		for d := range partitions {
			if partitions[d].Device != "none" {
				usage, _ := disk.DiskUsage(partitions[d].Mountpoint)

				if usage != nil {
					if !math.IsNaN(usage.UsedPercent) {
						monitorData.DiskStats[partitions[d].Device] = *usage
					}
				}
			}
		}
	}

	return err
}
开发者ID:VALERE91,项目名称:monitoring,代码行数:20,代码来源:systemMonitoring.go

示例9: DiskUsage

func (s *systemPS) DiskUsage() ([]*disk.DiskUsageStat, error) {
	parts, err := disk.DiskPartitions(true)
	if err != nil {
		return nil, err
	}

	var usage []*disk.DiskUsageStat

	for _, p := range parts {
		if _, err := os.Stat(p.Mountpoint); err == nil {
			du, err := disk.DiskUsage(p.Mountpoint)
			if err != nil {
				return nil, err
			}
			du.Fstype = p.Fstype
			usage = append(usage, du)
		}
	}

	return usage, nil
}
开发者ID:neezgee,项目名称:telegraf,代码行数:21,代码来源:ps.go

示例10: getDiskUsage

func getDiskUsage() (total uint64, used uint64, usedPercent float64, err error) {
	if partitions, pErr := disk.DiskPartitions(true); pErr == nil {
		for _, partition := range partitions {
			if diskStat, statErr := disk.DiskUsage(partition.Mountpoint); statErr == nil {
				total += diskStat.Total
				used += diskStat.Used
			} else {
				log.Error("Failed to get diskStat:", statErr)
				err = statErr
			}
		}

		if total > 0 {
			usedPercent = float64(used) / float64(total) * 100
		}
	} else {
		log.Error("Failed to get partitions:", pErr)
		err = pErr
	}

	return
}
开发者ID:mohabusama,项目名称:nodnod,代码行数:22,代码来源:stats.go

示例11: DiskCheck

func (c *Config) DiskCheck() error {
	du, err := disk.DiskUsage(c.Disk.Path)

	if err != nil {
		return err
	}

	if du.UsedPercent > c.Disk.UsedPercent {
		td, err := NewTextDetail("disk used " + strconv.Itoa(int(du.UsedPercent)) + "%")

		if err != nil {
			return err
		}
		if err := c.SetText(td); err != nil {
			return err
		}
		if err := c.SlackRequest(); err != nil {
			return err
		}
	}

	if du.InodesUsedPercent > c.Disk.InodesUsedPercent {
		td, err := NewTextDetail("disk inode used " + strconv.Itoa(int(du.InodesUsedPercent)) + "%")

		if err != nil {
			return err
		}
		if err := c.SetText(td); err != nil {
			return err
		}
		if err := c.SlackRequest(); err != nil {
			return err
		}
	}

	return nil
}
开发者ID:ngc224,项目名称:loose-watcher,代码行数:37,代码来源:main.go

示例12: main

func main() {

	flag.Usage = func() {
		fmt.Println(usage)
	}

	flag.Parse()

	for {

		// Docker client remote API
		endpoint := "unix:///var/run/docker.sock"
		dockerClient, _ := docker.NewClient(endpoint)

		// Configuration file settings using key-value
		viper.SetConfigName("plural")
		if *configFlag != "" {
			viper.AddConfigPath(*configFlag)
		} else {
			viper.AddConfigPath("/opt/plural/conf")
		}

		viperReadConfig := viper.ReadInConfig()

		// Default settings if no config file is supplied
		viper.SetDefault("elastic_host", "localhost")
		viper.SetDefault("elastic_port", "9200")
		viper.SetDefault("environment", "dev")
		viper.SetDefault("interval", "300")
		viper.SetDefault("username", "undef")
		viper.SetDefault("password", "undef")
		viper.SetDefault("overwrite", "undef")

		elastic_host := viper.GetString("elastic_host")
		elastic_port := viper.GetString("elastic_port")
		environment := viper.GetString("environment")
		interval := viper.GetInt("interval")
		username := viper.GetString("username")
		password := viper.GetString("password")
		overwrite := viper.GetString("overwrite")

		transport := http.Transport{
			Dial: dialTimeout,
		}

		client := http.Client{
			Transport: &transport,
		}

		cpuCounts, _ := cpu.CPUCounts(true)
		v, _ := mem.VirtualMemory()
		k, _ := disk.DiskUsage("/")
		h, _ := host.HostInfo()
		l, _ := load.LoadAvg()
		memusedprctConv := strconv.FormatFloat(v.UsedPercent, 'f', 6, 64)
		memusedprct := strings.Split(memusedprctConv, ".")[0]
		memfree := humanize.Bytes(v.Free)
		memtotal := humanize.Bytes(v.Total)
		diskusedprctConv := strconv.FormatFloat(k.UsedPercent, 'f', 6, 64)
		diskusedprct := strings.Split(diskusedprctConv, ".")[0]
		diskfree := humanize.Bytes(k.Free)
		disktotal := humanize.Bytes(k.Total)
		timeN := time.Now()
		dateStamp := fmt.Sprintf("%d-%02d-%02dT%02d:%02d:%02d", timeN.Year(), timeN.Month(), timeN.Day(), timeN.Hour(), timeN.Minute(), timeN.Second())
		loadoneConv := strconv.FormatFloat(l.Load1, 'f', 6, 64)
		loadone := strings.Split(loadoneConv, ".")[0]
		loadfifteenConv := strconv.FormatFloat(l.Load15, 'f', 6, 64)
		loadfifteen := strings.Split(loadfifteenConv, ".")[0]
		loadfiveConv := strconv.FormatFloat(l.Load5, 'f', 6, 64)
		loadfive := strings.Split(loadfiveConv, ".")[0]

		ipaddress, err := networkip.ExternalIP()
		if err != nil {
			fmt.Println(err.Error())
		}

		// UNIX system commands
		dnsfile := exec.Command("ls", "/etc/resolv.conf")
		dnsfileout, err := dnsfile.Output()
		dnsgrep := exec.Command("grep", "nameserver", "/etc/resolv.conf")
		dnsawk := exec.Command("awk", "{print$2}")
		dnsgrepOut, err := dnsgrep.StdoutPipe()
		dnsgrep.Start()
		dnsawk.Stdin = dnsgrepOut
		dnsOut, err := dnsawk.Output()
		dnsstring := string(dnsOut)
		dnsoutputSlice := strings.Split(dnsstring, "\n")
		dnsjs, _ := json.Marshal(dnsoutputSlice)

		wbin := exec.Command("ls", "/usr/bin/w")
		wbinout, err := wbin.Output()
		wh := exec.Command("w", "-h")
		whawk := exec.Command("awk", "{print$1\"-\"$2}")
		whOut, err := wh.StdoutPipe()
		wh.Start()
		whawk.Stdin = whOut
		wOut, err := whawk.Output()
		whstring := string(wOut)
		whoutputSlice := strings.Split(whstring, "\n")
		whjs, _ := json.Marshal(whoutputSlice)
//.........这里部分代码省略.........
开发者ID:learningobjectsinc,项目名称:plural,代码行数:101,代码来源:main.go

示例13: main

func main() {
	header, _ := json.Marshal(Header{Version: 1})
	fmt.Println(string(header))
	fmt.Println("[")
	go notifyd()
	for {
		if mode == "standard" {
			line := make([]Block, 0)

			// TIME block
			t := time.Now()
			const t_format = "2006-01-02 15:04:05"
			time_block := Block{
				Name:     "time",
				FullText: t.Format(t_format),
				Color:    GRAY,
			}

			// LOAD block
			load, _ := load.LoadAvg()
			load_block := Block{
				Name:     "load",
				FullText: strconv.FormatFloat(load.Load1, 'f', 2, 64),
			}
			if load.Load1 > 2 {
				load_block.Color = BAD
			} else if load.Load1 > 1 {
				load_block.Color = WARN
			} else {
				load_block.Color = OKAY
			}

			// NET block
			net_blocks := make([]Block, 0)
			interfaces, _ := net.NetInterfaces()
			for _, iface := range interfaces {
				if iface.Name == "lo" {
					continue
				}
				text := iface.Addrs[0].Addr
				net_blocks = append(net_blocks, Block{
					Name:     "iface",
					FullText: text,
					Instance: iface.Name,
					Color:    GRAY,
				})
			}

			// HDD block
			root_stat, _ := disk.DiskUsage("/")
			home_stat, _ := disk.DiskUsage("/home")
			data_stat, _ := disk.DiskUsage("/media/me/data")

			root_block := Block{
				Name:     "hdd",
				Instance: "root",
				FullText: FormatGigabytes(root_stat.Free) + "GB",
			}
			if root_stat.Free > 5*1024*1024*1024 {
				root_block.Color = OKAY
			} else if root_stat.Free > 2.5*1024*1024*1024 {
				root_block.Color = WARN
			} else {
				root_block.Color = BAD
			}

			home_block := Block{
				Name:     "hdd",
				Instance: "root",
				FullText: FormatGigabytes(home_stat.Free) + "GB",
			}
			if home_stat.Free > 20*1024*1024*1024 {
				home_block.Color = OKAY
			} else if home_stat.Free > 10*1024*1024*1024 {
				home_block.Color = WARN
			} else {
				home_block.Color = BAD
			}

			data_block := Block{
				Name:     "hdd",
				Instance: "data",
				FullText: FormatGigabytes(data_stat.Free) + "GB",
			}
			if data_stat.Free > 30*1024*1024*1024 {
				data_block.Color = OKAY
			} else if data_stat.Free > 15*1024*1024*1024 {
				data_block.Color = WARN
			} else {
				data_block.Color = BAD
			}

			/* // Headphones block
			headphones := Block {
				Name: "headphones",
				FullText: "Headphones ",
			}
			if exec.Command("sh", "-c", "pacmd list-sinks | grep DR-BTN200").Run() == nil {
				headphones.FullText += "connected";
				headphones.Color = OKAY;
//.........这里部分代码省略.........
开发者ID:irth,项目名称:gostatus,代码行数:101,代码来源:gostatus.go

示例14: Value

func (o *DiskMetric) Value() (float64, error) {
	d, e := disk.DiskUsage(*cliDiskDir)
	return d.UsedPercent, e
}
开发者ID:nickschuch,项目名称:metrics,代码行数:4,代码来源:metrics.go

示例15: stat

func (st *Stat) stat(t string) string {
	checkErr := func(err error) string {
		return "系统酱正在食用作死药丸中..."
	}
	switch t {
	case "free":
		m, err := mem.VirtualMemory()
		checkErr(err)
		s, err := mem.SwapMemory()
		checkErr(err)
		mem := new(runtime.MemStats)
		runtime.ReadMemStats(mem)
		return fmt.Sprintf(
			"全局:\n"+
				"Total: %s Free: %s\nUsed: %s %s%%\nCache: %s\n"+
				"Swap:\nTotal: %s Free: %s\n Used: %s %s%%\n"+
				"群组娘:\n"+
				"Allocated: %s\nTotal Allocated: %s\nSystem: %s\n",
			helper.HumanByte(m.Total, m.Free, m.Used, m.UsedPercent, m.Cached,
				s.Total, s.Free, s.Used, s.UsedPercent,
				mem.Alloc, mem.TotalAlloc, mem.Sys)...,
		)
	case "df":
		fs, err := disk.DiskPartitions(false)
		checkErr(err)
		var buf bytes.Buffer
		for k := range fs {
			du, err := disk.DiskUsage(fs[k].Mountpoint)
			switch {
			case err != nil, du.UsedPercent == 0, du.Free == 0:
				continue
			}
			f := fmt.Sprintf("Mountpoint: %s Type: %s \n"+
				"Total: %s Free: %s \nUsed: %s %s%%\n",
				helper.HumanByte(fs[k].Mountpoint, fs[k].Fstype,
					du.Total, du.Free, du.Used, du.UsedPercent)...,
			)
			buf.WriteString(f)
		}
		return buf.String()
	case "os":
		h, err := host.HostInfo()
		checkErr(err)
		uptime := time.Duration(time.Now().Unix()-int64(h.Uptime)) * time.Second
		l, err := load.LoadAvg()
		checkErr(err)
		c, err := cpu.CPUPercent(time.Second*3, false)
		checkErr(err)
		return fmt.Sprintf(
			"OSRelease: %s\nHostName: %s\nUptime: %s\nLoadAvg: %.2f %.2f %.2f\n"+
				"Goroutine: %d\nCPU: %.2f%%",
			h.Platform, h.Hostname, uptime.String(), l.Load1, l.Load5, l.Load15,
			runtime.NumGoroutine(), c[0],
		)
	case "redis":
		info := conf.Redis.Info().Val()
		if info != "" {
			infos := strings.Split(info, "\r\n")
			infoMap := make(map[string]string)
			for k := range infos {
				line := strings.Split(infos[k], ":")
				if len(line) > 1 {
					infoMap[line[0]] = line[1]
				}
			}
			DBSize := conf.Redis.DbSize().Val()
			return fmt.Sprintf("Redis Version: %s\nOS: %s\nUsed Memory: %s\n"+
				"Used Memory Peak: %s\nDB Size: %d\n",
				infoMap["redis_version"], infoMap["os"], infoMap["used_memory_human"],
				infoMap["used_memory_peak_human"], DBSize)
		}
		return ""
	default:
		return "欢迎来到未知领域(ゝ∀・)"
	}
}
开发者ID:Megadotzip,项目名称:Jqs7Bot,代码行数:76,代码来源:sysStat.go


注:本文中的github.com/shirou/gopsutil/disk.DiskUsage函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。