-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathconsul.go
82 lines (73 loc) · 2.18 KB
/
consul.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 main
import (
"fmt"
"io/ioutil"
"net/http"
"strconv"
"strings"
)
const ConsulScaleKey = "scale"
const ConsulColorKey = "color"
type Consul struct{}
func (c Consul) GetScaleCalc(address, serviceName, scale string) (int, error) {
s := 1
inc := 0
resp, err := http.Get(fmt.Sprintf("%s/v1/kv/docker-flow/%s/scale?raw", address, serviceName))
if err != nil {
return 0, fmt.Errorf("Please make sure that Consul address is correct\n%s", err.Error())
}
defer resp.Body.Close()
data, _ := ioutil.ReadAll(resp.Body)
if len(data) > 0 {
s, _ = strconv.Atoi(string(data))
}
if len(scale) > 0 {
if scale[:1] == "+" || scale[:1] == "-" {
inc, _ = strconv.Atoi(scale)
} else {
s, _ = strconv.Atoi(scale)
}
}
total := s + inc
if total <= 0 {
return 1, nil
}
return total, nil
}
func (c Consul) GetColor(address, serviceName string) (string, error) {
resp, err := http.Get(fmt.Sprintf("%s/v1/kv/docker-flow/%s/color?raw", address, serviceName))
if err != nil {
return "", fmt.Errorf("Could not retrieve the color from Consul. Please make sure that Consul address is correct\n%s", err.Error())
}
defer resp.Body.Close()
data, _ := ioutil.ReadAll(resp.Body)
currColor := GreenColor
if len(data) > 0 {
currColor = string(data)
}
return currColor, nil
}
func (c Consul) GetNextColor(currentColor string) string {
if currentColor == BlueColor {
return GreenColor
}
return BlueColor
}
func (c Consul) PutScale(address, serviceName string, value int) (string, error) {
return c.putValue(address, serviceName, ConsulScaleKey, strconv.Itoa(value))
}
func (c Consul) PutColor(address, serviceName string, value string) (string, error) {
return c.putValue(address, serviceName, ConsulColorKey, value)
}
func (c Consul) putValue(address, serviceName, key, value string) (string, error) {
url := fmt.Sprintf("%s/v1/kv/docker-flow/%s/%s", address, serviceName, key)
client := &http.Client{}
request, _ := http.NewRequest("PUT", url, strings.NewReader(value))
resp, err := client.Do(request)
if err != nil {
return "", fmt.Errorf("Could not store store information in Consul\n%s", err.Error())
}
defer resp.Body.Close()
data, _ := ioutil.ReadAll(resp.Body)
return string(data), nil
}