From c1f4faaab375743f94ccc2ff416ed0df46265943 Mon Sep 17 00:00:00 2001 From: Ryan Uber Date: Tue, 8 Sep 2015 11:51:20 -0700 Subject: [PATCH] api: allow querying node name from agent --- api/agent.go | 22 +++++++++++++++++++++- api/agent_test.go | 22 ++++++++++++++++++++++ 2 files changed, 43 insertions(+), 1 deletion(-) diff --git a/api/agent.go b/api/agent.go index aeec83e21..e80523c42 100644 --- a/api/agent.go +++ b/api/agent.go @@ -8,7 +8,9 @@ import ( // agent endpoints for a specific node. type Agent struct { client *Client - node string + + // Cache static agent info + nodeName string } // Agent returns a new agent which can be used to query @@ -30,3 +32,21 @@ func (a *Agent) Self() (map[string]map[string]interface{}, error) { return out, nil } + +// NodeName is used to query the Nomad agent for its node name. +func (a *Agent) NodeName() (string, error) { + // Return from cache if we have it + if a.nodeName != "" { + return a.nodeName, nil + } + + // Query the node name + info, err := a.Self() + if err != nil { + return "", err + } + if name, ok := info["member"]["Name"]; ok { + a.nodeName = name.(string) + } + return a.nodeName, nil +} diff --git a/api/agent_test.go b/api/agent_test.go index fd038970d..177db0e87 100644 --- a/api/agent_test.go +++ b/api/agent_test.go @@ -22,3 +22,25 @@ func TestAgent_Self(t *testing.T) { t.Fatalf("bad member name in response: %#v", res) } } + +func TestAgent_NodeName(t *testing.T) { + c, s := makeClient(t, nil, nil) + defer s.Stop() + a := c.Agent() + + // Query the agent for the node name + res, err := a.NodeName() + if err != nil { + t.Fatalf("err: %s", err) + } + + // Ensure we got a node name back + if res == "" { + t.Fatalf("expected node name, got nothing") + } + + // Check that we cached the node name + if a.nodeName == "" { + t.Fatalf("should have cached node name") + } +}