forked from kyma-project/kyma
-
Notifications
You must be signed in to change notification settings - Fork 0
/
base_flow.go
353 lines (316 loc) · 11.6 KB
/
base_flow.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
package servicecatalog
import (
"fmt"
"io/ioutil"
"strings"
"time"
"github.com/kubernetes-incubator/service-catalog/pkg/apis/servicecatalog/v1beta1"
"github.com/kubernetes-incubator/service-catalog/pkg/client/clientset_generated/clientset"
"github.com/kyma-project/kyma/components/service-binding-usage-controller/pkg/apis/servicecatalog/v1alpha1"
bu "github.com/kyma-project/kyma/components/service-binding-usage-controller/pkg/client/clientset/versioned"
"github.com/sirupsen/logrus"
appsTypes "k8s.io/api/apps/v1"
k8sCoreTypes "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes"
)
type baseFlow struct {
namespace string
log logrus.FieldLogger
stop <-chan struct{}
k8sInterface kubernetes.Interface
scInterface clientset.Interface
buInterface bu.Interface
}
func (f *baseFlow) createEnvTester(name, testedEnv string) error {
f.log.Infof("Creating environment variable tester")
labels := map[string]string{
"app": name,
}
_, err := f.k8sInterface.AppsV1().Deployments(f.namespace).Create(f.envTesterDeployment(name, labels, testedEnv))
return err
}
func (f *baseFlow) deleteDeployment(name string) error {
return f.k8sInterface.AppsV1().Deployments(f.namespace).Delete(name, &metav1.DeleteOptions{})
}
// envTesterDeployment creates a deployment which starts Alpine Pod, which prints value of the environment variable testedEnv
func (f *baseFlow) envTesterDeployment(name string, labels map[string]string, testedEnv string) *appsTypes.Deployment {
var replicas int32 = 1
return &appsTypes.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: f.namespace,
},
Spec: appsTypes.DeploymentSpec{
Selector: &metav1.LabelSelector{
MatchLabels: labels,
},
Replicas: &replicas,
Template: k8sCoreTypes.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: labels,
},
Spec: k8sCoreTypes.PodSpec{
Containers: []k8sCoreTypes.Container{
{
Name: "app",
Image: "alpine:3.12",
Command: []string{"/bin/sh", "-c", "--"},
Args: []string{fmt.Sprintf("echo \"value=$%s\"; echo \"done\"; while true; do sleep 30; done;", testedEnv)},
},
},
},
},
},
}
}
func (f *baseFlow) createBindingAndWaitForReadiness(bindingName, instanceName string) error {
f.log.Infof("Creating binding %s for service instance %s", bindingName, instanceName)
_, err := f.scInterface.ServicecatalogV1beta1().ServiceBindings(f.namespace).Create(&v1beta1.ServiceBinding{
TypeMeta: metav1.TypeMeta{
Kind: "ServiceBinding",
APIVersion: "servicecatalog.k8s.io/v1beta1",
},
ObjectMeta: metav1.ObjectMeta{
Name: bindingName,
},
Spec: v1beta1.ServiceBindingSpec{
InstanceRef: v1beta1.LocalObjectReference{
Name: instanceName,
},
},
})
if err != nil {
return err
}
f.log.Infof("Waiting for binding %s to be ready", bindingName)
return f.wait(45*time.Second, func() (done bool, err error) {
sb, err := f.scInterface.ServicecatalogV1beta1().ServiceBindings(f.namespace).Get(bindingName, metav1.GetOptions{})
if err != nil {
f.log.Error(err.Error())
return false, err
}
for _, cnd := range sb.Status.Conditions {
if cnd.Type == v1beta1.ServiceBindingConditionReady && cnd.Status == v1beta1.ConditionTrue {
return true, nil
}
}
return false, nil
})
}
func (f *baseFlow) createBindingUsageAndWaitForReadiness(usageName, bindingName, deploymentName string) error {
f.log.Infof("Creating %s binding usage", usageName)
_, err := f.buInterface.ServicecatalogV1alpha1().ServiceBindingUsages(f.namespace).Create(&v1alpha1.ServiceBindingUsage{
TypeMeta: metav1.TypeMeta{
Kind: "ServiceBindingUsage",
APIVersion: "servicecatalog.kyma-project.io/v1alpha1",
},
ObjectMeta: metav1.ObjectMeta{
Name: usageName,
},
Spec: v1alpha1.ServiceBindingUsageSpec{
ServiceBindingRef: v1alpha1.LocalReferenceByName{
Name: bindingName,
},
UsedBy: v1alpha1.LocalReferenceByKindAndName{
Kind: "deployment",
Name: deploymentName,
},
},
})
if err != nil {
return err
}
f.log.Infof("Waiting for binding usage %s to be ready", usageName)
return f.wait(10*time.Second, func() (done bool, err error) {
si, err := f.buInterface.ServicecatalogV1alpha1().ServiceBindingUsages(f.namespace).Get(usageName, metav1.GetOptions{})
if err != nil {
return false, err
}
for _, cnd := range si.Status.Conditions {
if cnd.Type == v1alpha1.ServiceBindingUsageReady && cnd.Status == v1alpha1.ConditionTrue {
return true, nil
}
}
return false, nil
})
}
func (f *baseFlow) deleteServiceBinding(name string) error {
f.log.Infof("Removing Service Binding %s", name)
return f.scInterface.ServicecatalogV1beta1().ServiceBindings(f.namespace).Delete(name, &metav1.DeleteOptions{})
}
func (f *baseFlow) deleteServiceInstance(name string) error {
f.log.Infof("Removing Service Instance %s", name)
return f.scInterface.ServicecatalogV1beta1().ServiceInstances(f.namespace).Delete(name, &metav1.DeleteOptions{})
}
func (f *baseFlow) deleteBindingUsage(name string) error {
f.log.Infof("Removing Service Binding Usage %s", name)
return f.buInterface.ServicecatalogV1alpha1().ServiceBindingUsages(f.namespace).Delete(name, &metav1.DeleteOptions{})
}
func (f *baseFlow) wait(timeout time.Duration, conditionFunc wait.ConditionFunc) error {
timeoutCh := time.After(timeout)
stopCh := make(chan struct{})
go func() {
select {
case <-timeoutCh:
close(stopCh)
case <-f.stop:
close(stopCh)
}
}()
return wait.PollUntil(time.Second, conditionFunc, stopCh)
}
func (f *baseFlow) waitForEnvInjected(svc, expectedEnvValue string) error {
return f.waitForEnvTesterValue(svc, expectedEnvValue)
}
func (f *baseFlow) waitForEnvNotInjected(svc string) error {
return f.waitForEnvTesterValue(svc, "")
}
func (f *baseFlow) waitForEnvTesterValue(svc, expectedEnvValue string) error {
return f.wait(time.Minute, func() (bool, error) {
var podName string
// wait for running single env tester pod
err := f.wait(25*time.Second, func() (bool, error) {
pods, err := f.k8sInterface.CoreV1().Pods(f.namespace).List(metav1.ListOptions{
LabelSelector: fmt.Sprintf("app=%s", svc),
})
if err != nil {
return false, err
}
//extract running pods
var runningPods []*k8sCoreTypes.Pod
for _, p := range pods.Items {
var containerRunning bool
for _, c := range p.Status.ContainerStatuses {
if c.Name == "app" && c.State.Running != nil {
containerRunning = true
}
}
if p.Status.Phase == k8sCoreTypes.PodRunning && containerRunning {
runningPods = append(runningPods, &p)
}
}
// expect only one running env-tester pod
if len(runningPods) == 1 {
podName = runningPods[0].Name
return true, nil
}
return false, nil
})
if err != nil {
return false, nil
}
req := f.k8sInterface.CoreV1().Pods(f.namespace).GetLogs(podName, &k8sCoreTypes.PodLogOptions{Container: "app"})
readCloser, err := req.Stream()
if err != nil {
// it can happen, when pod is initializing
return false, nil
}
defer readCloser.Close()
logs, err := ioutil.ReadAll(readCloser)
if err != nil {
f.log.Warnf("error while reading logs: %s", err.Error())
return false, nil
}
if strings.Contains(string(logs), fmt.Sprintf("value=%s", expectedEnvValue)) {
return true, nil
}
// the "done" string is sent just after the value, it means the value was printed
if strings.Contains(string(logs), "done") {
return false, fmt.Errorf("unexpected environment variable value: %s", string(logs))
}
return false, nil
})
}
func (f *baseFlow) waitForInstance(name string) error {
return f.wait(5*time.Minute, func() (done bool, err error) {
si, err := f.scInterface.ServicecatalogV1beta1().ServiceInstances(f.namespace).Get(name, metav1.GetOptions{})
if err != nil {
return false, err
}
if si.Status.ProvisionStatus == v1beta1.ServiceInstanceProvisionStatusProvisioned {
return true, nil
}
return false, nil
})
}
func (f *baseFlow) waitForInstanceFail(name string) error {
return f.wait(3*time.Minute, func() (done bool, err error) {
si, err := f.scInterface.ServicecatalogV1beta1().ServiceInstances(f.namespace).Get(name, metav1.GetOptions{})
if err != nil {
return false, err
}
for _, cond := range si.Status.Conditions {
if cond.Status == v1beta1.ConditionFalse && cond.Type == v1beta1.ServiceInstanceConditionReady && cond.Reason == "ProvisionCallFailed" {
return true, nil
}
}
return false, nil
})
}
func (f *baseFlow) waitForInstanceRemoved(name string) error {
f.log.Infof("Waiting for %s instance to be removed", name)
var lastInstance *v1beta1.ServiceInstance
err := f.wait(3*time.Minute, func() (bool, error) {
instance, err := f.scInterface.ServicecatalogV1beta1().ServiceInstances(f.namespace).Get(name, metav1.GetOptions{})
if err != nil {
if errors.IsNotFound(err) {
f.log.Infof("Service instances in namespace %s not found - all deleted", f.namespace)
return true, nil
}
f.log.Warnf(err.Error())
}
lastInstance = instance
return false, nil
})
if err == nil {
return nil
}
conditionMessages := make([]string, 0)
for _, condition := range lastInstance.Status.Conditions {
if condition.Reason == "Deprovisioning" && condition.Status == v1beta1.ConditionFalse {
f.log.Warnf("ServiceInstance %s is still in a deprovisioning state. Skip waiting for removing.", lastInstance.Name)
return nil
}
conditionMessages = append(conditionMessages, condition.Message)
}
return fmt.Errorf("timeout for the removal of the instance %s, last conditions: %s", lastInstance.Name, strings.Join(conditionMessages, " | "))
}
func (f *baseFlow) waitForDeployment(name string) error {
return f.wait(time.Minute, func() (done bool, err error) {
deploy, err := f.k8sInterface.AppsV1().Deployments(f.namespace).Get(name, metav1.GetOptions{})
if err != nil {
return false, err
}
if deploy.Status.ReadyReplicas > 0 {
return true, nil
}
return false, nil
})
}
func (f *baseFlow) logK8SReport(report *Report) {
deployments, err := f.k8sInterface.AppsV1().Deployments(f.namespace).List(metav1.ListOptions{})
report.AddDeployments(deployments, err)
pods, err := f.k8sInterface.CoreV1().Pods(f.namespace).List(metav1.ListOptions{})
report.AddPods(pods, err)
secrets, err := f.k8sInterface.CoreV1().Secrets(f.namespace).List(metav1.ListOptions{})
report.AddSecrets(secrets, err)
}
func (f *baseFlow) logServiceCatalogAndBindingUsageReport(report *Report) {
clusterServiceBrokers, err := f.scInterface.ServicecatalogV1beta1().ClusterServiceBrokers().List(metav1.ListOptions{})
report.AddClusterServiceBrokers(clusterServiceBrokers, err)
serviceBrokers, err := f.scInterface.ServicecatalogV1beta1().ServiceBrokers(f.namespace).List(metav1.ListOptions{})
report.AddServiceBrokers(serviceBrokers, err)
clusterServiceClass, err := f.scInterface.ServicecatalogV1beta1().ClusterServiceClasses().List(metav1.ListOptions{})
report.AddClusterServiceClasses(clusterServiceClass, err)
serviceClass, err := f.scInterface.ServicecatalogV1beta1().ServiceClasses(f.namespace).List(metav1.ListOptions{})
report.AddServiceClasses(serviceClass, err)
serviceInstances, err := f.scInterface.ServicecatalogV1beta1().ServiceInstances(f.namespace).List(metav1.ListOptions{})
report.AddServiceInstances(serviceInstances, err)
serviceBindings, err := f.scInterface.ServicecatalogV1beta1().ServiceBindings(f.namespace).List(metav1.ListOptions{})
report.AddServiceBindings(serviceBindings, err)
serviceBindingUsages, err := f.buInterface.ServicecatalogV1alpha1().ServiceBindingUsages(f.namespace).List(metav1.ListOptions{})
report.AddServiceBindingUsages(serviceBindingUsages, err)
}