Skip to content
This repository has been archived by the owner on Aug 30, 2019. It is now read-only.

Commit

Permalink
Merge pull request #242 from DataDog/talwai/hostname
Browse files Browse the repository at this point in the history
config: shell out to dd-agent to retrieve hostname
  • Loading branch information
talwai committed Mar 9, 2017
2 parents eb7c0d7 + 3f46d34 commit d2e71c5
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 1 deletion.
33 changes: 32 additions & 1 deletion config/agent.go
@@ -1,8 +1,10 @@
package config

import (
"bytes"
"errors"
"os"
"os/exec"
"strconv"
"strings"
"time"
Expand Down Expand Up @@ -104,9 +106,38 @@ func mergeEnv(c *AgentConfig) {
}
}

// getHostname shells out to obtain the hostname used by the infra agent
// falling back to os.Hostname() if it is unavailable
func getHostname() (string, error) {
ddAgentPy := "/opt/datadog-agent/embedded/bin/python"
getHostnameCmd := "from utils.hostname import get_hostname; print get_hostname()"

cmd := exec.Command(ddAgentPy, "-c", getHostnameCmd)
cmd.Env = []string{"PYTHONPATH=/opt/datadog-agent/agent"}

var stdout, stderr bytes.Buffer
cmd.Stdout = &stdout
cmd.Stderr = &stderr

err := cmd.Run()
if err != nil {
log.Infof("error retrieving dd-agent hostname, falling back to os.Hostname(): %s", stderr)
return os.Hostname()
}

hostname := strings.TrimSpace(stdout.String())

if hostname == "" {
log.Infof("error retrieving dd-agent hostname, falling back to os.Hostname(): %s", stderr)
return os.Hostname()
}

return hostname, err
}

// NewDefaultAgentConfig returns a configuration with the default values
func NewDefaultAgentConfig() *AgentConfig {
hostname, err := os.Hostname()
hostname, err := getHostname()
if err != nil {
hostname = ""
}
Expand Down
6 changes: 6 additions & 0 deletions config/config_test.go
Expand Up @@ -149,3 +149,9 @@ func TestConfigNewIfExists(t *testing.T) {
assert.Nil(t, conf)
os.Remove(filename)
}

func TestGetHostname(t *testing.T) {
h, err := getHostname()
assert.Nil(t, err)
assert.NotEqual(t, "", h)
}

0 comments on commit d2e71c5

Please sign in to comment.