-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.go
373 lines (310 loc) · 9.57 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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"log"
"net/http"
"net/url"
"os"
"strings"
"sync"
"time"
"github.com/jessevdk/go-flags"
providerTypes "github.com/openfaas/faas-provider/types"
"github.com/openfaas/faas/gateway/metrics"
)
var opts struct {
Verbose []bool `short:"v" long:"verbose" description:"Show verbose debug information"`
DryRun bool `short:"d" long:"dry_run" description:"Should scaling be run in dry run mode, scaling events will be shown, but not committed"`
GatewayURI string `short:"g" long:"gateway_uri" description:"Full URI to the openfaas gateway" default:"http://gateway:8080"`
GatewayHeaders []string `short:"a" long:"gateway_header" description:"Additional headers to use when calling the gateway, eg. authentication"`
PrometheusHost string `short:"p" long:"prometheus_host" description:"Full URI to the openfaas gateway" default:"prometheus"`
PrometheusPort int `short:"o" long:"prometheus_port" description:"Full URI to the openfaas gateway" default:"9090"`
PollingFrequency string `short:"f" long:"polling_frequency" description:"Polling frequency against scaling" default:"30s"`
DefaultScaleInterval string `short:"i" long:"default_scale_interval" description:"Default interval period between scaling events" default:"320s"`
IgnoreLabels bool `short:"n" long:"ignore_labels" description:"Ignore scaling labels and run for every function found"`
}
var appLogger logger
var client = http.DefaultClient
func main() {
parseArgs()
appLogger = defaultLogger{
level: len(opts.Verbose),
}
appLogger.debug(opts)
appLogger.info("Running first polling")
pollFunctions()
appLogger.info(fmt.Sprintf("Starting polling loop, running every %s", opts.PollingFrequency))
pollingFrequencyDuration, err := time.ParseDuration(opts.PollingFrequency)
if err != nil {
appLogger.info(fmt.Sprintf("the provided polling frequency: %s was invalid", opts.PollingFrequency))
panic(err.Error())
}
ticker := time.NewTicker(pollingFrequencyDuration)
for range ticker.C {
ticker.Stop()
pollFunctions()
ticker.Reset(pollingFrequencyDuration)
}
}
func parseArgs() {
_, err := flags.ParseArgs(&opts, os.Args)
if err != nil {
usedHelp := func() bool {
for _, arg := range os.Args {
if arg == "-h" || arg == "--help" || arg == "help" {
return true
}
}
return false
}
if usedHelp() {
os.Exit(0)
}
log.Fatalln(err.Error())
}
}
func pollFunctions() {
appLogger.info("Polling functions")
functions := []providerTypes.FunctionStatus{}
if err := callGateway(http.MethodGet, "system/functions", &functions, nil, 200); err != nil {
log.Println(err.Error())
}
idleFunctions := listIdleFunctions(functions)
if len(idleFunctions) == 0 {
appLogger.info("No idle functions found, stopping!")
return
}
for _, idleFunction := range idleFunctions {
if idleFunction.Replicas > 0 {
err := scaleFunction(idleFunction.Name, 0)
if err != nil {
log.Println(err.Error())
}
}
}
appLogger.info("Finished polling functions")
}
func scaleFunction(fnName string, replicas uint64) error {
req := providerTypes.ScaleServiceRequest{
ServiceName: fnName,
Replicas: replicas,
}
if opts.DryRun {
appLogger.info("*DRY RUN*")
appLogger.info(fmt.Sprintf("Would be scaling %s replicas to %d", fnName, replicas))
return nil
}
appLogger.info(fmt.Sprintf("Scaling %s replicas to %d", fnName, replicas))
if err := callGateway(http.MethodPost, fmt.Sprintf("system/scale-function/%s", fnName), nil, req, 202); err != nil {
return err
}
return nil
}
func listIdleFunctions(functions []providerTypes.FunctionStatus) (idleFunctions []providerTypes.FunctionStatus) {
query := metrics.NewPrometheusQuery(opts.PrometheusHost, opts.PrometheusPort, client)
appLogger.debug(fmt.Sprintf("creating prometheus client with host: %s and port: %d", opts.PrometheusHost, opts.PrometheusPort))
duration := opts.DefaultScaleInterval
appLogger.debug(fmt.Sprintf("default idle duration set to %s", duration))
c := make(chan providerTypes.FunctionStatus)
wg := sync.WaitGroup{}
for _, function := range functions {
wg.Add(1)
go func(function providerTypes.FunctionStatus) {
defer wg.Done()
fnName := fmt.Sprintf("%s.%s", function.Name, function.Namespace)
if !canZero(fnName, *function.Labels) {
return
}
if function.AvailableReplicas < function.Replicas {
return
}
if customIntervalValue := customInterval(fnName, *function.Labels); customIntervalValue != nil {
duration = *customIntervalValue
}
parsedDuration, err := time.ParseDuration(duration)
if err != nil {
appLogger.info(fmt.Sprintf("the scaling value %s given for the function %s was not parsable", duration, fnName))
appLogger.info(err.Error())
}
if function.CreatedAt.Add(parsedDuration).After(time.Now()) {
return
}
queryReq := url.QueryEscape(fmt.Sprintf(`sum(rate(gateway_function_invocation_total{function_name="%s", code=~".*"}[%s])) by (code, function_name)`, fnName, duration))
appLogger.trace("calling prometheus with query:")
appLogger.trace(queryReq)
resp, err := query.Fetch(queryReq)
if err != nil {
appLogger.debug("failed to query prometheus")
appLogger.debug(err.Error())
}
appLogger.trace("prometheus query response:")
appLogger.trace(resp)
if len(resp.Data.Result) <= 0 {
c <- function
return
}
if !hasActiveResult(resp) {
c <- function
}
}(function)
}
go func() {
defer close(c)
wg.Wait()
}()
for function := range c {
idleFunctions = append(idleFunctions, function)
}
return
}
func callGateway(method, path string, result interface{}, data interface{}, statusCodes ...int) error {
appLogger.trace("http client settings:")
appLogger.trace(client.Transport)
appLogger.debug("using data:")
appLogger.debug(data)
var body io.Reader
body = nil
if data != nil {
dataBody, err := json.Marshal(data)
if err != nil {
return err
}
appLogger.trace("encoded data payload:")
appLogger.trace(dataBody)
body = bytes.NewBuffer(dataBody)
}
req, err := http.NewRequest(method, fmt.Sprintf("%s/%s", opts.GatewayURI, path), body)
if err != nil {
return err
}
appLogger.trace("request object:")
appLogger.trace(req)
if err := setHeaders(req); err != nil {
return err
}
basicAuthUser := os.Getenv("BASIC_AUTH_USER")
basicAuthPassword := os.Getenv("BASIC_AUTH_PASSWORD")
if basicAuthUser != "" && basicAuthPassword != "" {
appLogger.debug("setting basic auth header via environment variables")
req.SetBasicAuth(basicAuthUser, basicAuthPassword)
}
resp, err := client.Do(req)
if resp != nil && resp.Body != nil {
defer resp.Body.Close()
}
if err != nil {
return err
}
appLogger.trace("api response:")
appLogger.trace(resp)
if !validStatus(resp.StatusCode, statusCodes...) {
bodyBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
appLogger.debug("failed to read body response from gateway")
return err
}
appLogger.debug("bad gateway response, body returned:")
appLogger.debug(string(bodyBytes))
return fmt.Errorf("invalid response from gateway, with status %d", resp.StatusCode)
}
if resp.Body != nil && result != nil {
if err := json.NewDecoder(resp.Body).Decode(result); err != nil {
return err
}
appLogger.debug("parsed gateway response:")
appLogger.debug(result)
}
return nil
}
func setHeaders(req *http.Request) error {
for _, header := range opts.GatewayHeaders {
headerKV := strings.SplitN(header, ":", 2)
if len(headerKV) != 2 {
return fmt.Errorf("invalid header '%s' provided", header)
}
headerKey := strings.TrimSpace(headerKV[0])
headerValue := strings.TrimSpace(headerKV[1])
appLogger.debug("adding header to request:")
appLogger.debug(header)
req.Header.Add(headerKey, headerValue)
}
return nil
}
func canZero(fnName string, labels map[string]string) bool {
if opts.IgnoreLabels {
return true
}
for key, value := range labels {
if key == "com.openfaas.scale.zero" && value == "true" {
appLogger.debug(fmt.Sprintf("found scale to zero label for function %s", fnName))
return true
}
}
appLogger.debug(fmt.Sprintf("no scale to zero label found for function %s", fnName))
return false
}
func customInterval(fnName string, labels map[string]string) *string {
if opts.IgnoreLabels {
return nil
}
for key, value := range labels {
if key == "com.openfaas.scale.custom.interval" {
appLogger.debug(fmt.Sprintf("found custom scaling interval label for function %s", fnName))
return &value
}
}
appLogger.debug(fmt.Sprintf("no custom scaling interval label found for function %s", fnName))
return nil
}
func hasActiveResult(resp *metrics.VectorQueryResponse) bool {
for _, result := range resp.Data.Result {
if len(result.Value) < 2 {
continue
}
resultValue, ok := result.Value[1].(string)
if !ok {
continue
}
if resultValue != "0" && resultValue != "0.0" {
return true
}
}
return false
}
func validStatus(statusCode int, validStatusCodes ...int) bool {
for _, validStatusCode := range validStatusCodes {
if statusCode == validStatusCode {
return true
}
}
return false
}
type logger interface {
getLevel() int
info(message interface{})
debug(message interface{})
trace(message interface{})
}
type defaultLogger struct {
level int
}
func (l defaultLogger) getLevel() int {
return l.level
}
func (l defaultLogger) info(message interface{}) {
log.Println(message)
}
func (l defaultLogger) debug(message interface{}) {
if l.level > 0 {
log.Println(message)
}
}
func (l defaultLogger) trace(message interface{}) {
if l.level > 1 {
log.Println(message)
}
}