forked from servicemeshinterface/smi-controller-sdk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
189 lines (154 loc) · 4.35 KB
/
main.go
File metadata and controls
189 lines (154 loc) · 4.35 KB
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
package main
import (
"context"
"flag"
"fmt"
"net/http"
"os"
"time"
"github.com/cucumber/godog"
"github.com/cucumber/godog/colors"
"github.com/cucumber/messages-go/v10"
"github.com/go-logr/logr"
"github.com/servicemeshinterface/smi-controller-sdk/sdk"
"github.com/servicemeshinterface/smi-controller-sdk/sdk/controller"
"github.com/stretchr/testify/mock"
"k8s.io/apimachinery/pkg/api/resource"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/rest"
"k8s.io/client-go/tools/clientcmd"
ctrl "sigs.k8s.io/controller-runtime"
splitv1alpha1 "github.com/servicemeshinterface/smi-sdk-go/pkg/apis/split/v1alpha1"
splitClientSet "github.com/servicemeshinterface/smi-sdk-go/pkg/gen/client/split/clientset/versioned"
)
var opts = &godog.Options{
Format: "pretty",
Output: colors.Colored(os.Stdout),
}
var mockAPI *MockAPI
var logger logr.Logger
// store a reference to any objects submitted to the controller for later cleanup
var trafficSplits []*splitv1alpha1.TrafficSplit
func main() {
godog.BindFlags("godog.", flag.CommandLine, opts)
flag.Parse()
status := godog.TestSuite{
Name: "SDK Functional Tests",
ScenarioInitializer: initializeSuite,
Options: opts,
}.Run()
os.Exit(status)
}
func initializeSuite(ctx *godog.ScenarioContext) {
trafficSplits = []*splitv1alpha1.TrafficSplit{}
logger = Log()
ctx.Step(`^the server is running$`, theServerIsRunning)
ctx.Step(`^I create a TrafficSplitter$`, iCreateATrafficSplitter)
ctx.Step(`^I expect the controller to have received the details$`, iExpectTheControllerToHaveRecievedTheDetails)
ctx.AfterScenario(func(s *messages.Pickle, err error) {
cleanupTrafficSplit()
if err != nil {
fmt.Println(logger.(*StringLogger).String())
}
})
}
func cleanupTrafficSplit() {
c := getK8sConfig()
sl, err := splitClientSet.NewForConfig(c)
if err != nil {
panic(err.Error())
}
for _, ts := range trafficSplits {
sl.SplitV1alpha1().TrafficSplits("default").Delete(context.Background(), ts.Name, v1.DeleteOptions{})
}
}
func theServerIsRunning() error {
mockAPI = &MockAPI{}
mockAPI.On("UpsertTrafficSplit", mock.Anything,
mock.Anything,
mock.Anything,
mock.Anything).Return(ctrl.Result{}, nil)
sdk.API().RegisterV1Alpha(mockAPI)
// create and start the controller
config := controller.DefaultConfig()
config.WebhooksEnabled = false
config.Logger = logger
go controller.Start(config)
return waitForComplete(
30*time.Second,
func() error {
resp, err := http.Get(fmt.Sprintf("http://%s/readyz", config.HealthProbeBindAddress))
if err == nil {
if resp != nil && resp.StatusCode == http.StatusOK {
return nil
}
}
return fmt.Errorf("Timeout waiting for service to become ready")
},
)
}
func iCreateATrafficSplitter() error {
c := getK8sConfig()
sl, err := splitClientSet.NewForConfig(c)
if err != nil {
return err
}
ts := &splitv1alpha1.TrafficSplit{
ObjectMeta: v1.ObjectMeta{Name: "testing"},
Spec: splitv1alpha1.TrafficSplitSpec{
Service: "myService",
Backends: []splitv1alpha1.TrafficSplitBackend{
splitv1alpha1.TrafficSplitBackend{
Service: "v1",
Weight: resource.NewQuantity(100, resource.BinarySI),
},
},
},
}
// add to our collection so we can cleanup later
trafficSplits = append(trafficSplits, ts)
ts, err = sl.SplitV1alpha1().TrafficSplits("default").Create(context.Background(), ts, v1.CreateOptions{})
return err
}
// The controller is eventually consistent so we need to check this in a loop
func iExpectTheControllerToHaveRecievedTheDetails() error {
return waitForComplete(
30*time.Second,
func() error {
if len(mockAPI.Calls) < 1 {
return fmt.Errorf("Expected UpsertTrafficSplit to have been called")
}
return nil
},
)
}
func getK8sConfig() *rest.Config {
// use the current context in kubeconfig
config, err := clientcmd.BuildConfigFromFlags("", os.Getenv("KUBECONFIG"))
if err != nil {
panic(err.Error())
}
return config
}
// helper function to loop until a condition is met
func waitForComplete(duration time.Duration, f func() error) error {
// wait for the server to mark it is ready
done := make(chan struct{})
timeout := time.After(30 * time.Second)
var err error
go func() {
for {
err = f()
if err == nil {
done <- struct{}{}
}
time.Sleep(2 * time.Second)
}
}()
select {
case <-timeout:
return err
case <-done:
return nil
}
}