forked from docker-archive/classicswarm
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathconstraint.go
67 lines (61 loc) · 1.79 KB
/
constraint.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
package filter
import (
"fmt"
"regexp"
"strings"
log "github.com/Sirupsen/logrus"
"github.com/docker/swarm/cluster"
"github.com/samalba/dockerclient"
)
// ConstraintFilter selects only nodes that match certain labels.
type ConstraintFilter struct {
}
func (f *ConstraintFilter) extractConstraints(env []string) map[string]string {
constraints := make(map[string]string)
for _, e := range env {
if strings.HasPrefix(e, "constraint:") {
constraint := strings.TrimPrefix(e, "constraint:")
parts := strings.SplitN(constraint, "=", 2)
constraints[strings.ToLower(parts[0])] = strings.ToLower(parts[1])
}
}
return constraints
}
// Create the regex for globbing (ex: ub*t* -> ^ub.*t.*$)
// and match.
func (f *ConstraintFilter) match(pattern, s string) bool {
regex := "^" + strings.Replace(pattern, "*", ".*", -1) + "$"
matched, err := regexp.MatchString(regex, strings.ToLower(s))
if err != nil {
log.Error(err)
}
return matched
}
func (f *ConstraintFilter) Filter(config *dockerclient.ContainerConfig, nodes []*cluster.Node) ([]*cluster.Node, error) {
constraints := f.extractConstraints(config.Env)
for k, v := range constraints {
log.Debugf("matching constraint: %s=%s", k, v)
candidates := []*cluster.Node{}
for _, node := range nodes {
switch k {
case "node":
// "node" label is a special case pinning a container to a specific node.
if f.match(v, node.ID) || f.match(v, node.Name) {
candidates = append(candidates, node)
}
default:
// By default match the node labels.
if label, ok := node.Labels[k]; ok {
if f.match(v, label) {
candidates = append(candidates, node)
}
}
}
}
if len(candidates) == 0 {
return nil, fmt.Errorf("unable to find a node that satisfies %s == %s", k, v)
}
nodes = candidates
}
return nodes, nil
}