From 33e7d0cd2d5c8bd1ffe3f08765f223da95120e2d Mon Sep 17 00:00:00 2001 From: Ryan Uber Date: Tue, 8 Sep 2015 19:27:04 -0700 Subject: [PATCH] api: add constraints generators --- api/jobs.go | 33 +++++++++++++++++++++++++++++++++ api/jobs_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) diff --git a/api/jobs.go b/api/jobs.go index 66080381e..6b457ada9 100644 --- a/api/jobs.go +++ b/api/jobs.go @@ -82,6 +82,7 @@ type Job struct { Priority int AllAtOnce bool Datacenters []string + Constraints []*Constraint Meta map[string]string Status string StatusDescription string @@ -96,3 +97,35 @@ type registerJobRequest struct { type registerJobResponse struct { EvalID string } + +// Constraint is used to serialize a job placement constraint. +type Constraint struct { + Hard bool + LTarget string + RTarget string + Operand string + Weight int +} + +// HardConstraint is used to create a new hard constraint. +func HardConstraint(left, operand, right string) *Constraint { + return constraint(left, operand, right, true, 0) +} + +// SoftConstraint is used to create a new soft constraint. It +// takes an additional weight parameter to allow balancing +// multiple soft constraints amongst eachother. +func SoftConstraint(left, operand, right string, weight int) *Constraint { + return constraint(left, operand, right, false, weight) +} + +// constraint generates a new job placement constraint. +func constraint(left, operand, right string, hard bool, weight int) *Constraint { + return &Constraint{ + Hard: hard, + LTarget: left, + RTarget: right, + Operand: operand, + Weight: weight, + } +} diff --git a/api/jobs_test.go b/api/jobs_test.go index 99d5a009a..db844d45d 100644 --- a/api/jobs_test.go +++ b/api/jobs_test.go @@ -178,3 +178,33 @@ func TestJobs_Delete(t *testing.T) { t.Fatalf("expected 0 jobs, got: %d", n) } } + +func TestJobs_Constraints(t *testing.T) { + { + c := HardConstraint("kernel.name", "=", "darwin") + expect := &Constraint{ + Hard: true, + LTarget: "kernel.name", + RTarget: "darwin", + Operand: "=", + Weight: 0, + } + if !reflect.DeepEqual(c, expect) { + t.Fatalf("expect: %#v, got: %#v", expect, c) + } + } + + { + c := SoftConstraint("memory.totalbytes", ">=", "250000000", 5) + expect := &Constraint{ + Hard: false, + LTarget: "memory.totalbytes", + RTarget: "250000000", + Operand: ">=", + Weight: 5, + } + if !reflect.DeepEqual(c, expect) { + t.Fatalf("expect: %#v, got: %#v", expect, c) + } + } +}