-
Notifications
You must be signed in to change notification settings - Fork 10
/
main.go
214 lines (176 loc) · 6.09 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
// Copyright (c) OpenFaaS Author(s) 2021. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/openfaas/connector-sdk/types"
crontypes "github.com/openfaas/cron-connector/types"
"github.com/openfaas/cron-connector/version"
sdk "github.com/openfaas/faas-cli/proxy"
ptypes "github.com/openfaas/faas-provider/types"
)
// topic is the value of the "topic" annotation to look for
// on functions, to decide to include them for invocation
const topic = "cron-function"
func main() {
config, err := getControllerConfig()
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %s\n", err.Error())
os.Exit(1)
}
rebuildTimeout := time.Second * 5
if val, exists := os.LookupEnv("rebuild_timeout"); exists {
rebuildTimeout, err = time.ParseDuration(val)
if err != nil {
log.Printf("Error: %s\n", err.Error())
os.Exit(1)
}
}
sha, ver := version.GetReleaseInfo()
log.Printf("Version: %s\tCommit: %s\n", sha, ver)
log.Printf("Gateway URL: %s", config.GatewayURL)
log.Printf("Async Invocation: %v", config.AsyncFunctionInvocation)
log.Printf("Rebuild interval: %s\tRebuild timeout: %s", config.RebuildInterval, rebuildTimeout)
httpClient := types.MakeClient(config.UpstreamTimeout)
invoker := types.NewInvoker(
gatewayRoute(config),
httpClient,
config.ContentType,
config.PrintResponse,
config.PrintRequestBody)
go func() {
for {
r := <-invoker.Responses
if r.Error != nil {
log.Printf("Error with: %s, %s", r.Function, err.Error())
} else {
duration := fmt.Sprintf("%.2fs", r.Duration.Seconds())
if r.Duration < time.Second*1 {
duration = fmt.Sprintf("%dms", r.Duration.Milliseconds())
}
log.Printf("Response: %s [%d] (%s)",
r.Function,
r.Status,
duration)
}
}
}()
cronScheduler := crontypes.NewScheduler()
cronScheduler.Start()
if err := startFunctionProbe(config.RebuildInterval, rebuildTimeout, topic, config, cronScheduler, invoker); err != nil {
fmt.Fprintf(os.Stderr, "Error: %s\n", err.Error())
os.Exit(1)
}
}
func gatewayRoute(config *types.ControllerConfig) string {
if config.AsyncFunctionInvocation {
return fmt.Sprintf("%s/%s", config.GatewayURL, "async-function")
}
return fmt.Sprintf("%s/%s", config.GatewayURL, "function")
}
// BasicAuth basic authentication for the the gateway
type BasicAuth struct {
Username string
Password string
}
// Set set Authorization header on request
func (auth *BasicAuth) Set(req *http.Request) error {
req.SetBasicAuth(auth.Username, auth.Password)
return nil
}
func startFunctionProbe(interval time.Duration, probeTimeout time.Duration, topic string, c *types.ControllerConfig, cronScheduler *crontypes.Scheduler, invoker *types.Invoker) error {
runningFuncs := make(crontypes.ScheduledFunctions, 0)
creds := types.GetCredentials()
auth := &BasicAuth{
Username: creds.User,
Password: creds.Password,
}
sdkClient, err := sdk.NewClient(auth, c.GatewayURL, nil, &probeTimeout)
if err != nil {
return err
}
ctx := context.Background()
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
<-ticker.C
namespaces, err := sdkClient.ListNamespaces(ctx)
if err != nil {
log.Printf("error listing namespaces: %s", err)
continue
}
for _, namespace := range namespaces {
functions, err := sdkClient.ListFunctions(ctx, namespace)
if err != nil {
log.Printf("error listing functions in %s: %s", namespace, err)
continue
}
newCronFunctions := requestsToCronFunctions(functions, namespace, topic)
addFuncs, deleteFuncs := getNewAndDeleteFuncs(newCronFunctions, runningFuncs, namespace)
for _, function := range deleteFuncs {
log.Printf("Removed: %s [%s]",
function.Function.String(),
function.Function.Schedule)
cronScheduler.Remove(function)
}
newScheduledFuncs := make(crontypes.ScheduledFunctions, 0)
for _, function := range addFuncs {
f, err := cronScheduler.AddCronFunction(function, invoker)
if err != nil {
log.Printf("can't add function: %s, %s", function.String(), err)
continue
}
newScheduledFuncs = append(newScheduledFuncs, f)
log.Printf("Added: %s [%s]", function.String(), function.Schedule)
}
runningFuncs = updateScheduledFunctions(runningFuncs, newScheduledFuncs, deleteFuncs)
}
}
}
// requestsToCronFunctions converts an array of types.FunctionStatus object
// to CronFunction, ignoring those that cannot be converted
func requestsToCronFunctions(functions []ptypes.FunctionStatus, namespace string, topic string) crontypes.CronFunctions {
newCronFuncs := make(crontypes.CronFunctions, 0)
for _, function := range functions {
cF, err := crontypes.ToCronFunction(function, namespace, topic)
if err != nil {
continue
}
newCronFuncs = append(newCronFuncs, cF)
}
return newCronFuncs
}
// getNewAndDeleteFuncs takes new functions and running cron functions and returns
// functions that need to be added and that need to be deleted
func getNewAndDeleteFuncs(newFuncs crontypes.CronFunctions, oldFuncs crontypes.ScheduledFunctions, namespace string) (crontypes.CronFunctions, crontypes.ScheduledFunctions) {
addFuncs := make(crontypes.CronFunctions, 0)
deleteFuncs := make(crontypes.ScheduledFunctions, 0)
for _, function := range newFuncs {
if !oldFuncs.Contains(&function) {
addFuncs = append(addFuncs, function)
}
}
for _, function := range oldFuncs {
if !newFuncs.Contains(&function.Function) && function.Function.Namespace == namespace {
deleteFuncs = append(deleteFuncs, function)
}
}
return addFuncs, deleteFuncs
}
// updateScheduledFunctions updates the scheduled function with
// added functions and removes deleted functions
func updateScheduledFunctions(running, added, deleted crontypes.ScheduledFunctions) crontypes.ScheduledFunctions {
updatedSchedule := make(crontypes.ScheduledFunctions, 0)
for _, function := range running {
if !deleted.Contains(&function.Function) {
updatedSchedule = append(updatedSchedule, function)
}
}
updatedSchedule = append(updatedSchedule, added...)
return updatedSchedule
}