/
autodetect.go
82 lines (76 loc) · 2.32 KB
/
autodetect.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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package core
import (
"context"
"errors"
"fmt"
"strconv"
"github.com/Sirupsen/logrus"
"github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/client"
"github.com/gianarb/orbiter/autoscaler"
"github.com/gianarb/orbiter/provider"
)
// This function use diferent strategies to get information from
// the system itself to configure the autoloader.
// They can be environment variables for example or other systems.
func Autodetect(core *Core) error {
autoDetectSwarmMode(core)
if len(core.Autoscalers) == 0 {
logrus.Info("no autoscaling group detected for now")
}
return nil
}
func autoDetectSwarmMode(c *Core) {
ctx := context.Background()
dockerClient, err := client.NewEnvClient()
if err != nil {
logrus.WithField("error", err).Debug("Problem communication with Docker")
return
}
info, err := dockerClient.Info(ctx)
if err != nil {
logrus.WithField("error", err).Debug("We didn't detect any Docker Swarm running")
return
}
if info.Swarm.NodeID == "" {
logrus.Debug("We didn't detect any Docker Swarm running")
return
}
services, err := dockerClient.ServiceList(ctx, types.ServiceListOptions{})
if err != nil {
logrus.WithField("error", err).Debug("Bad comunication with Docker.")
return
}
prov, _ := provider.NewSwarmProvider(map[string]string{})
for _, service := range services {
s, err := getAutoscalerByService(prov, service.Spec.Annotations)
if err != nil {
continue
}
c.Autoscalers[fmt.Sprintf("autoswarm/%s", service.Spec.Annotations.Name)] = s
}
}
func getAutoscalerByService(p autoscaler.Provider, an swarm.Annotations) (autoscaler.Autoscaler, error) {
_, e := an.Labels["orbiter"]
if e == false {
return autoscaler.Autoscaler{}, errors.New("")
}
up := convertStringLabelToInt("orbiter.up", an.Labels)
down := convertStringLabelToInt("orbiter.down", an.Labels)
cool := convertStringLabelToInt("orbiter.cooldown", an.Labels)
as := autoscaler.NewAutoscaler(p, an.Name, up, down, cool)
logrus.Infof("Registering /handle/autoswarm/%s to orbiter. (UP %d, DOWN %d, COOL %d)", an.Name, up, down, cool)
return as, nil
}
func convertStringLabelToInt(labelName string, labels map[string]string) int {
row, e := labels[labelName]
if e == true {
i, err := strconv.ParseInt(row, 10, 64)
if err != nil {
return 1
}
return int(i)
}
return 1
}