From b140ba5f5162d42909b51095be091f2c0b625e40 Mon Sep 17 00:00:00 2001 From: Armon Dadgar Date: Tue, 4 Aug 2015 17:28:19 -0700 Subject: [PATCH] nomad: share port overcommit check --- nomad/plan_apply.go | 18 ++---------------- nomad/structs/funcs.go | 16 ++++++++++++++++ nomad/structs/funcs_test.go | 22 ++++++++++++++++++++++ 3 files changed, 40 insertions(+), 16 deletions(-) diff --git a/nomad/plan_apply.go b/nomad/plan_apply.go index cb1dcab84..87041841f 100644 --- a/nomad/plan_apply.go +++ b/nomad/plan_apply.go @@ -154,8 +154,8 @@ func AllocationsFit(node *structs.Node, allocs []*structs.Allocation) bool { return false } - // portsOvercommited - if portsOvercommited(resourcesUsed) { + // Ensure ports are not over commited + if structs.PortsOvercommited(resourcesUsed) { return false } @@ -205,17 +205,3 @@ func resourceSubset(super, sub *structs.Resources) bool { } return true } - -// portsOvercommited checks if any of the port resources are over-committed -func portsOvercommited(r *structs.Resources) bool { - for _, net := range r.Networks { - ports := make(map[int]struct{}) - for _, port := range net.ReservedPorts { - if _, ok := ports[port]; ok { - return true - } - ports[port] = struct{}{} - } - } - return false -} diff --git a/nomad/structs/funcs.go b/nomad/structs/funcs.go index cec99b3a5..90343b8ca 100644 --- a/nomad/structs/funcs.go +++ b/nomad/structs/funcs.go @@ -21,3 +21,19 @@ func RemoveAllocs(alloc []*Allocation, remove []string) []*Allocation { alloc = alloc[:n] return alloc } + +// PortsOvercommited checks if any ports are over-committed. +// This does not handle CIDR subsets, and computes for the entire +// CIDR block currently. +func PortsOvercommited(r *Resources) bool { + for _, net := range r.Networks { + ports := make(map[int]struct{}) + for _, port := range net.ReservedPorts { + if _, ok := ports[port]; ok { + return true + } + ports[port] = struct{}{} + } + } + return false +} diff --git a/nomad/structs/funcs_test.go b/nomad/structs/funcs_test.go index c400c811b..c79f4826b 100644 --- a/nomad/structs/funcs_test.go +++ b/nomad/structs/funcs_test.go @@ -18,3 +18,25 @@ func TestRemoveAllocs(t *testing.T) { t.Fatalf("bad: %#v", out) } } + +func TestPortsOvercommitted(t *testing.T) { + r := &Resources{ + Networks: []*NetworkResource{ + &NetworkResource{ + ReservedPorts: []int{22, 80}, + }, + &NetworkResource{ + ReservedPorts: []int{22, 80}, + }, + }, + } + if PortsOvercommited(r) { + t.Fatalf("bad") + } + + // Overcommit 22 + r.Networks[1].ReservedPorts[1] = 22 + if !PortsOvercommited(r) { + t.Fatalf("bad") + } +}