-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
113 lines (92 loc) · 1.87 KB
/
main.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package main
import (
"log"
"os"
"os/signal"
"strings"
"time"
"github.com/kelseyhightower/envconfig"
)
func main() {
ecfg := new(Config)
if err := envconfig.Process("app_config", ecfg); err != nil {
log.Fatal(err)
}
egw := new(Gateway)
if err := envconfig.Process("app_gateway", egw); err != nil {
log.Fatal(err)
}
emetric := new(Metric)
if err := envconfig.Process("app_metric", emetric); err != nil {
log.Fatal(err)
}
gwUsername, err := readSecret(egw.UsernameFile)
if err != nil {
log.Fatal(err)
}
gwPassword, err := readSecret(egw.PasswordFile)
if err != nil {
log.Fatal(err)
}
fc, err := NewFunction(egw.URL, gwUsername, gwPassword)
if err != nil {
log.Fatal(err)
}
mc, err := NewMetric(emetric.Host, emetric.Port, emetric.InactivityDuration)
if err != nil {
log.Fatal(err)
}
ticker := time.NewTicker(time.Second * time.Duration(ecfg.Interval))
done := make(chan bool)
go func() {
for {
select {
case <-done:
return
case <-ticker.C:
if err := reconcile(fc, mc); err != nil {
log.Println(err)
}
}
}
}()
quit := make(chan os.Signal, 1)
signal.Notify(quit, os.Interrupt)
<-quit
ticker.Stop()
done <- true
}
func readSecret(filename string) (string, error) {
b, err := os.ReadFile(filename)
if err != nil {
return "", err
}
result := strings.TrimSpace(string(b))
return result, nil
}
func reconcile(fc *FunctionConfig, mc *MetricConfig) error {
// Get functions
functions, err := fc.ListScalableFunctions()
if err != nil {
return err
}
// Get metrics
functionMetrics := make(map[string]float64)
for _, f := range functions {
metric, err := mc.Get(f)
if err != nil {
log.Println(err)
continue
}
functionMetrics[f] = metric
}
for f, m := range functionMetrics {
if m == 0 {
if err := fc.ScaleToZero(f); err != nil {
log.Println(err)
continue
}
}
}
return nil
}