//配置文件
ip=http://10.102.110.93:8086
name=lbw
pwd=123
portOrPid=8080,8086
pidName=java,influx
telNetIp=10.102.110.100:3306,www.baidu.com:80
//读取配置文件
func InitConfig(path string) map[string]string {
config := make(map[string]string)
f, err := os.Open(path)
defer f.Close()
if err != nil {
panic(err)
}
r := bufio.NewReader(f)
for {
b, _, err := r.ReadLine()
if err != nil {
if err == io.EOF {
break
}
panic(err)
}
s := strings.TrimSpace(string(b))
index := strings.Index(s, "=")
if index < 0 {
continue
}
key := strings.TrimSpace(s[:index])
if len(key) == 0 {
continue
}
value := strings.TrimSpace(s[index+1:])
if len(value) == 0 {
continue
}
config[key] = value
}
return config
}
//influxdb初始化
func InitFluxdb() client.Client {
config := InitConfig("./config/test.txt")
ip := config["ip"]
name := config["name"]
pwd := config["pwd"]
conn := ConnInflux(ip,name,pwd)
return conn
}
func ConnInflux(ip string,name string,pwd string) client.Client {
cli, err := client.NewHTTPClient(client.HTTPConfig{
Addr: ip,
Username: name,
Password: pwd,
})
if err != nil {
log.Fatal(err)
}
return cli
}
func InsertDB(cli client.Client,dbName string,tableName string,tags map[string]string,fields map[string]interface{},accuracy string) {
bp, err := client.NewBatchPoints(client.BatchPointsConfig{
Database: dbName,
Precision: accuracy,
})
if err != nil {
log.Fatal(err)
}
pt, err := client.NewPoint(tableName, tags, fields, time.Now())
if err != nil {
log.Fatal(err)
}
bp.AddPoint(pt)
err = cli.Write(bp)
if err != nil {
log.Fatal(err)
}
log.Println("insert success")
}
//调用
func main() {
hostname:=common.GetHostName()
mem:=common.GetMem()
info, _ := disk.Partitions(true)
cpu:=common.GetCpuPercent()
memup:=mem.UsedPercent
tags := map[string]string{"name": hostname}
fields := map[string]interface{}{
"cpu_used_percent": cpu,
"mem_used_percent": memup,
}
for _,info2:=range info{
disks:=info2
info3, _ := disk.Usage(disks.Device)
fields[strings.ToLower( strings.Replace(disks.Device,":","_used_percent",-1))]=info3.UsedPercent
}
common.InsertDB(common.InitFluxdb(),"testdb","host_info",tags,fields,"s")
}