auto detect hostname and ip
This commit is contained in:
parent
6eb9723753
commit
10573a3b26
|
@ -3,6 +3,11 @@
|
|||
print_configs = false
|
||||
|
||||
# add label(agent_hostname) to series
|
||||
# "" -> auto detect hostname
|
||||
# "xx" -> use specified string xx
|
||||
# "$hostname" -> auto detect hostname
|
||||
# "$ip" -> auto detect ip
|
||||
# "$hostname-$ip" -> auto detect hostname and ip to replace the vars
|
||||
hostname = ""
|
||||
|
||||
# will not add label(agent_hostname) if true
|
||||
|
|
|
@ -3,8 +3,10 @@ package config
|
|||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"path"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"flashcat.cloud/categraf/pkg/cfg"
|
||||
|
@ -72,12 +74,8 @@ func InitConfig(configDir string, debugMode bool, testMode bool) error {
|
|||
return fmt.Errorf("failed to load configs of dir: %s", configDir)
|
||||
}
|
||||
|
||||
if Config.Global.Hostname == "" {
|
||||
name, err := os.Hostname()
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get hostname: %v", err)
|
||||
}
|
||||
Config.Global.Hostname = name
|
||||
if err := Config.fillHostname(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if Config.Global.PrintConfigs {
|
||||
|
@ -88,6 +86,38 @@ func InitConfig(configDir string, debugMode bool, testMode bool) error {
|
|||
return nil
|
||||
}
|
||||
|
||||
func (c *ConfigType) fillHostname() error {
|
||||
if c.Global.Hostname == "" {
|
||||
name, err := GetHostname()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c.Global.Hostname = name
|
||||
return nil
|
||||
}
|
||||
|
||||
if strings.Contains(c.Global.Hostname, "$hostname") {
|
||||
name, err := GetHostname()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c.Global.Hostname = strings.Replace(c.Global.Hostname, "$hostname", name, -1)
|
||||
}
|
||||
|
||||
if strings.Contains(c.Global.Hostname, "$ip") {
|
||||
ip, err := GetOutboundIP()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
c.Global.Hostname = strings.Replace(c.Global.Hostname, "$ip", fmt.Sprint(ip), -1)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func GetInterval() time.Duration {
|
||||
if Config.Global.Interval <= 0 {
|
||||
return time.Second * 15
|
||||
|
@ -95,3 +125,20 @@ func GetInterval() time.Duration {
|
|||
|
||||
return time.Duration(Config.Global.Interval)
|
||||
}
|
||||
|
||||
func GetHostname() (string, error) {
|
||||
return os.Hostname()
|
||||
}
|
||||
|
||||
// Get preferred outbound ip of this machine
|
||||
func GetOutboundIP() (net.IP, error) {
|
||||
conn, err := net.Dial("udp", "8.8.8.8:80")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get outbound ip: %v", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
localAddr := conn.LocalAddr().(*net.UDPAddr)
|
||||
|
||||
return localAddr.IP, nil
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue