Пример #1
0
/**
	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))
}
Пример #2
0
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
}
Пример #3
0
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)
	}
}
Пример #4
0
// 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
}
Пример #5
0
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
}
Пример #6
0
// Run gathers partition information from gopsutil.
func (d *DiskPartitions) Run() error {
	dataSlice, err := gopsutil_disk.DiskPartitions(true)
	if err != nil {
		return err
	}

	d.Data["PartitionsByDevice"] = make(map[string]gopsutil_disk.DiskPartitionStat)
	d.Data["PartitionsByMount"] = make(map[string]gopsutil_disk.DiskPartitionStat)

	for _, data := range dataSlice {
		d.Data["PartitionsByDevice"][data.Device] = data
		d.Data["PartitionsByMount"][data.Mountpoint] = data
	}

	return nil
}
Пример #7
0
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
}
Пример #8
0
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
}
Пример #9
0
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
}
Пример #10
0
func main() {

	// DISK INFO

	fmt.Print("\n----Disk Info ----\n\n")
	diskInfo, err := disk.DiskPartitions(true)
	if err != nil {
		panic(err)
	}
	log.Printf("[DEBUG] %#v\n\n", diskInfo)

	for _, diskn := range diskInfo {
		fmt.Printf("%s %s\n", diskn.Device, diskn.Mountpoint)
	}

	// CPU INFO

	fmt.Print("\n----CPU Info ----\n\n")
	cpuInfo, err := cpu.CPUInfo()
	if err != nil {
		panic(err)
	}
	log.Printf("[DEBUG] %#v\n\n", cpuInfo)

	var totalCores int32
	var frequency float64
	var totalCompute float64
	var flags string

	for _, cpu := range cpuInfo {
		totalCores += cpu.Cores
		if frequency == 0 {
			frequency = cpu.Mhz
		} else {
			if frequency != cpu.Mhz {
				log.Printf("A CPU shows inconsistent frequency with other CPUs: baseline %f, abberant %f", frequency, frequency)
			}
		}
		flags = strings.Join(cpu.Flags, " ")
	}
	totalCompute = frequency * float64(totalCores)
	fmt.Printf("%s %d\n", "cpu.totalcores", totalCores)
	fmt.Printf("%s %d\n", "cpu.numcpus", len(cpuInfo))
	fmt.Printf("%s %f\n", "cpu.frequency", frequency)
	fmt.Printf("%s %f\n", "cpu.totalcompute", totalCompute)
	fmt.Printf("%s %s\n", "cpu.flags", flags)

	// MEMORY INFO

	fmt.Print("\n----Memory Info ----\n\n")
	memInfo, err := mem.VirtualMemory()
	if err != nil {
		panic(err)
	}
	log.Printf("[DEBUG] %#v\n\n", memInfo)

	fmt.Printf("%s %d\n", "memory.totalbytes", memInfo.Total)

	// HOST INFO

	fmt.Print("\n----Host Info ----\n\n")
	hostInfo, err := host.HostInfo()
	if err != nil {
		panic(err)
	}

	log.Printf("[DEBUG] %#v\n\n", hostInfo)

	fmt.Printf("%s %s\n", "hostInfo.Hostname       ", hostInfo.Hostname)
	fmt.Printf("%s %s\n", "hostInfo.OS             ", hostInfo.OS)
	fmt.Printf("%s %s\n", "hostInfo.Platform       ", hostInfo.Platform)
	fmt.Printf("%s %s\n", "hostInfo.PlatformVersion", hostInfo.PlatformVersion)
	fmt.Printf("%s %s\n", "hostInfo.PlatformFamily ", hostInfo.PlatformFamily)
}
Пример #11
0
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 "欢迎来到未知领域(ゝ∀・)"
	}
}
Пример #12
0
func json_diskpartitions(w http.ResponseWriter, r *http.Request) {
	diskinfo, _ := disk.DiskPartitions(true)
	b, _ := json.Marshal(diskinfo)
	w.Header().Set("Content-Type", "application/json")
	fmt.Fprintf(w, string(b))
}