On cli node status list print the short Node ID when possible

This commit is contained in:
Armin
2015-12-20 17:33:27 +01:00
parent bdf4347bc8
commit 5d3bd1b6f0
2 changed files with 74 additions and 1 deletions

View File

@@ -4,6 +4,8 @@ import (
"fmt"
"sort"
"strings"
"github.com/hashicorp/nomad/api"
)
type NodeStatusCommand struct {
@@ -78,12 +80,14 @@ func (c *NodeStatusCommand) Run(args []string) int {
return 0
}
shortenNodeId := shouldShortenNodeIds(nodes)
// Format the nodes list
out := make([]string, len(nodes)+1)
out[0] = "ID|DC|Name|Class|Drain|Status"
for i, node := range nodes {
out[i+1] = fmt.Sprintf("%s|%s|%s|%s|%v|%s",
node.ID,
shortenId(node.ID, shortenNodeId),
node.Datacenter,
node.Name,
node.NodeClass,
@@ -160,3 +164,27 @@ func (c *NodeStatusCommand) Run(args []string) int {
}
return 0
}
// check if there is a collision if we shorten the Node ids
func shouldShortenNodeIds(nodes []*api.NodeListStub) bool {
ids := map[string]bool{}
for _, node := range nodes {
if len(node.ID) != 36 {
return false //We have a custom ID, don't shorten anything
} else if ids[node.ID[:8]] == true {
return false //There is a collision
} else {
ids[node.ID[:8]] = true
}
}
return true
}
// shorten an UUID syntax XXXXXXXX-XX... to 8 chars XXXXXXXX
func shortenId(id string, shouldShortenId bool) string {
if shouldShortenId == true {
return id[:8]
}
return id
}

View File

@@ -5,6 +5,7 @@ import (
"strings"
"testing"
"github.com/hashicorp/nomad/api"
"github.com/hashicorp/nomad/testutil"
"github.com/mitchellh/cli"
)
@@ -108,3 +109,47 @@ func TestNodeStatusCommand_Fails(t *testing.T) {
t.Fatalf("expected not found error, got: %s", out)
}
}
func Test_ShortenId(t *testing.T) {
id := "1234567890"
shortID := "12345678"
dontShorten := shortenId(id, false)
if dontShorten != id {
t.Fatalf("Shorten ID should not short id on false, expected %s, got: %s", id, dontShorten)
}
shorten := shortenId(id, true)
if shorten != shortID {
t.Fatalf("Shorten ID should short id on true, expected %s, got: %s", shortID, shorten)
}
}
func Test_ShouldShortenNodeIds(t *testing.T) {
var list []*api.NodeListStub
nodeCustomId := &api.NodeListStub{
ID: "my_own_id",
}
nodeOne := &api.NodeListStub{
ID: "11111111-1111-1111-1111-111111111111",
}
nodeTwo := &api.NodeListStub{
ID: "11111111-2222-2222-2222-222222222222",
}
list = append(list, nodeCustomId)
if shouldShortenNodeIds(list) != false {
t.Fatalf("ShouldShortenNodeIds should return false when using custom id")
}
list = nil
list = append(list, nodeOne)
if shouldShortenNodeIds(list) != true {
t.Fatalf("ShouldShortenNodeIds should return true when no collisions")
}
list = append(list, nodeTwo)
if shouldShortenNodeIds(list) != false {
t.Fatalf("ShouldShortenNodeIds should return false when collision detected")
}
}