diff --git a/pkg/metric/statsd.go b/pkg/metric/statsd.go index 969701c..b8316a1 100644 --- a/pkg/metric/statsd.go +++ b/pkg/metric/statsd.go @@ -2,7 +2,7 @@ package metric import ( "fmt" - "os" + "github.com/pantheon-systems/pauditd/pkg/system" "strconv" "strings" @@ -51,7 +51,7 @@ func Configure(config *viper.Viper) error { statsSampleRate = float32(sampleRate) } - hostname, _ := os.Hostname() + hostname := system.GetHostname() simpleHostName := strings.Split(hostname, ".")[0] statsPrefix := fmt.Sprintf("pauditd.%s", simpleHostName) client, err = statsd.New( diff --git a/pkg/output/httptransformer/notification_serivce_transformer.go b/pkg/output/httptransformer/notification_serivce_transformer.go index e896148..374b75a 100644 --- a/pkg/output/httptransformer/notification_serivce_transformer.go +++ b/pkg/output/httptransformer/notification_serivce_transformer.go @@ -3,6 +3,7 @@ package httptransformer import ( "encoding/json" "fmt" + "github.com/pantheon-systems/pauditd/pkg/system" "os" "regexp" "strings" @@ -89,10 +90,7 @@ func (t NotificationServiceTransformer) Transform(traceID uuid.UUID, body []byte } func getHostname() string { - host, err := os.Hostname() - if err != nil { - return "" - } + host := system.GetHostname() // we want to normallize the hostname, // only the first part diff --git a/pkg/system/host_data_provider.go b/pkg/system/host_data_provider.go new file mode 100644 index 0000000..4f841d5 --- /dev/null +++ b/pkg/system/host_data_provider.go @@ -0,0 +1,25 @@ +package system + +import ( + "os" +) + +const ( + hostnameEnv string = "NODENAME" +) + +// GetHostname retrieves the hostname of the system, if no hostname +// is available we return empty string +func GetHostname() string { + var err error + + host, ok := os.LookupEnv(hostnameEnv) + if !ok { + host, err = os.Hostname() + if err != nil { + return "" + } + } + + return host +} diff --git a/pkg/system/host_data_provider_test.go b/pkg/system/host_data_provider_test.go new file mode 100644 index 0000000..ce42d3f --- /dev/null +++ b/pkg/system/host_data_provider_test.go @@ -0,0 +1,19 @@ +package system_test + +import ( + "github.com/pantheon-systems/pauditd/pkg/system" + "os" + "testing" + + "github.com/stretchr/testify/assert" +) + +func Test_GetHostnameWithEnvVar(t *testing.T) { + testName := "test-node-name" + + os.Setenv("NODENAME", testName) + + hostname := system.GetHostname() + + assert.Equal(t, testName, hostname) +}