-
Notifications
You must be signed in to change notification settings - Fork 0
/
function.go
104 lines (82 loc) · 1.83 KB
/
function.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
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"time"
"github.com/openfaas/faas-provider/types"
)
type FunctionConfig struct {
URL string
Username string
Password string
}
func NewFunction(url, username, password string) (*FunctionConfig, error) {
cfg := FunctionConfig{
URL: url,
Username: username,
Password: password,
}
return &cfg, nil
}
func (c *FunctionConfig) ListScalableFunctions() ([]string, error) {
var result []string
response, err := c.request("GET", "/system/functions", nil)
if err != nil {
return nil, err
}
var functions []types.FunctionStatus
if err := json.Unmarshal(response, &functions); err != nil {
return nil, err
}
for _, f := range functions {
if f.Labels != nil {
v, ok := (*f.Labels)["com.openfaas.scale.zero"]
if ok {
if v == "true" && f.Replicas > 0 {
result = append(result, f.Name)
}
}
}
}
return result, nil
}
func (c *FunctionConfig) ScaleToZero(functionName string) error {
payload := struct {
Replicas int
}{Replicas: 0}
body, err := json.Marshal(payload)
if err != nil {
return err
}
path := fmt.Sprintf("/system/scale-function/%s", functionName)
if _, err = c.request(http.MethodPost, path, body); err != nil {
return err
}
return nil
}
func (c *FunctionConfig) request(method, path string, body []byte) ([]byte, error) {
url := fmt.Sprintf("%s%s", c.URL, path)
client := &http.Client{
Timeout: time.Second * 10,
}
req, err := http.NewRequest(method, url, bytes.NewBuffer(body))
if err != nil {
return nil, err
}
req.SetBasicAuth(c.Username, c.Password)
response, err := client.Do(req)
if err != nil {
return nil, err
}
respBody, err := io.ReadAll(response.Body)
if err != nil {
return nil, err
}
if err := response.Body.Close(); err != nil {
return nil, err
}
return respBody, nil
}