Refactor Disk and Memory Size Formatting with Centralized Utility Function

- Extracted common size formatting logic to a new utility function `HumanSize` in utils package
- Removed duplicate size formatting code from Disk and Memory configurations
- Updated Disk and Memory modules to use the centralized size formatting utility
- Uncommented and implemented disk usage calculation in Disk configuration
- Improved code readability and maintainability by centralizing size conversion logic
This commit is contained in:
zeaslity
2025-02-27 15:15:55 +08:00
parent 8fc55e2e28
commit b6cc5abc63
4 changed files with 70 additions and 57 deletions

View File

@@ -2,10 +2,11 @@ package config
import (
"agent-wdd/log"
"agent-wdd/utils"
"bufio"
"fmt"
"os"
"path/filepath"
"strconv"
"strings"
)
@@ -80,47 +81,31 @@ func DiskListGather() {
}
func (disk *Disk) calculateDiskUsage() {
// var stat unix.Statfs_t
// err := unix.Statfs(disk.Path, &stat)
// if err != nil {
// log.Error("disk syscall error: %v", err)
// disk.Size = "0B"
// disk.Usage = "0B"
// disk.Percent = "0.00%"
// return
// }
// // 计算存储空间大小
// totalBytes := stat.Blocks * uint64(stat.Bsize)
// availBytes := stat.Bavail * uint64(stat.Bsize)
// usedBytes := totalBytes - availBytes
// // 格式化输出
// disk.Size = formatDiskSize(totalBytes)
// disk.Usage = formatDiskSize(usedBytes)
// if totalBytes == 0 {
// disk.Percent = "0.00%"
// } else {
// percent := float64(usedBytes) / float64(totalBytes) * 100
// disk.Percent = fmt.Sprintf("%.2f%%", percent)
// }
}
func formatDiskSize(bytes uint64) string {
units := []string{"B", "KB", "MB", "GB", "TB", "PB"}
var unitIndex int
size := float64(bytes)
for size >= 1000 && unitIndex < len(units)-1 {
size /= 1000
unitIndex++
var stat unix.Statfs_t
err := unix.Statfs(disk.Path, &stat)
if err != nil {
log.Error("disk syscall error: %v", err)
disk.Size = "0B"
disk.Usage = "0B"
disk.Percent = "0.00%"
return
}
if unitIndex == 0 {
return strconv.FormatUint(bytes, 10) + units[unitIndex]
// 计算存储空间大小
totalBytes := stat.Blocks * uint64(stat.Bsize)
availBytes := stat.Bavail * uint64(stat.Bsize)
usedBytes := totalBytes - availBytes
// 格式化输出
disk.Size = utils.HumanDiskSize(totalBytes)
disk.Usage = utils.HumanDiskSize(usedBytes)
if totalBytes == 0 {
disk.Percent = "0.00%"
} else {
percent := float64(usedBytes) / float64(totalBytes) * 100
disk.Percent = fmt.Sprintf("%.2f%%", percent)
}
return strconv.FormatFloat(size, 'f', 1, 64) + units[unitIndex]
}
func DiskListSaveConfig() {