基于node_exporter增加
cmd/collector/rds_files_linux.go
package collector
import (
"github.com/go-kit/log"
"github.com/prometheus/client_golang/prometheus"
)
func init() {
registerCollector("system", defaultEnabled, NewSystemCollector)
}
type SystemCollector struct {
log log.Logger
}
func NewSystemCollector(logger log.Logger) (Collector, error) {
return &SystemCollector{log: logger}, nil
}
var sysInfo = map[string]*prometheus.Desc{
"dir_size": prometheus.NewDesc(
"rds_dir_size",
"自定义指定文件夹的大小",
[]string{}, prometheus.Labels{},
),
"file_size": prometheus.NewDesc(
"rds_file_size",
"自定义指定文件的大小",
[]string{}, prometheus.Labels{},
),
}
func (SystemCollector) Update(ch chan<- prometheus.Metric) error {
var dirSize = DirSize("/root/go/src/node_mysqld_exporter/cmd/collector")
ch <- prometheus.MustNewConstMetric(
sysInfo["dir_size"],
prometheus.GaugeValue, float64(dirSize),
)
var fileSize = DirSize("/root/go/src/node_mysqld_exporter/cmd/collector/cpu_linux.go")
ch <- prometheus.MustNewConstMetric(
sysInfo["file_size"],
prometheus.GaugeValue, float64(fileSize),
)
return nil
}
cmd/collector/utils.go
package collector
import (
"io/ioutil"
"log"
"os"
"path/filepath"
"sync"
"time"
)
var syncM sync.Map
var wait sync.WaitGroup
func DirSize(path string) int64 {
var size int64
filepath.Walk(path, func(_ string, info os.FileInfo, err error) error {
if err != nil {
log.Println(err.Error())
return err
}
if !info.IsDir() {
size += info.Size()
}
return err
})
return size
}
func getFileSize(path string) int64 {
if !exists(path) {
return 0
}
fileInfo, err := os.Stat(path)
log.Println(fileInfo)
if err != nil {
return 0
}
return fileInfo.Size()
}
func exists(path string) bool {
_, err := os.Stat(path)
return err == nil || os.IsExist(err)
}
func SizeOfDirPath(dirPath string) float64 {
log.Println("扫描文件夹:" + dirPath)
t := time.Now()
wait.Add(1)
go scanDir(dirPath, &syncM)
wait.Wait()
var fileCount int
var dirSize float64
syncM.Range(func(key, value interface{}) bool {
fileCount++
v := value.(float64)
dirSize += v
return true
})
log.Println("花费的时间:" + time.Since(t).String())
log.Println("文件的数量:", fileCount)
log.Println("文件夹大小:", dirSize)
return dirSize
}
func scanDir(path string, syncM *sync.Map) {
defer wait.Done()
dirAry, err := ioutil.ReadDir(path)
if err != nil {
panic(err)
}
for _, e := range dirAry {
if e.IsDir() {
wait.Add(1)
go scanDir(filepath.Join(path, e.Name()), syncM)
} else {
syncM.Store(filepath.Join(path, e.Name()), (float64(e.Size()) / 1024))
}
}
}
验证
# HELP rds_dir_size 自定义指定文件夹的大小
# TYPE rds_dir_size gauge
rds_dir_size 1.591099e+06
# HELP rds_file_size 自定义指定文件的大小
# TYPE rds_file_size gauge
rds_file_size 15226