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

config: shell out to dd-agent to retrieve hostname #242

Merged
merged 1 commit into from Mar 9, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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())
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍


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) {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test is very fine but will probably fall back on os.Hostname in most cases. OTOH I can't see any way to really trigger the "real test" without either black-box test the thing (so, non-Go solution, complex...) or changing the func prototype and passing python and command as args (sounds like over engineering for the sake of testability...). So well, good to go, but will keep in mind this is slightly under tested.

h, err := getHostname()
assert.Nil(t, err)
assert.NotEqual(t, "", h)
}