-
Notifications
You must be signed in to change notification settings - Fork 1
/
reconciler.go
276 lines (238 loc) · 7.83 KB
/
reconciler.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
/*
Copyright 2020 The Knative Authors
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package streamprocessor
import (
context "context"
"fmt"
"strings"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/api/equality"
apierrs "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
appsv1informers "k8s.io/client-go/informers/apps/v1"
corev1informers "k8s.io/client-go/informers/core/v1"
"k8s.io/client-go/kubernetes"
"knative.dev/pkg/kmeta"
"knative.dev/pkg/logging"
reconciler "knative.dev/pkg/reconciler"
v1alpha1 "knative.dev/streaming/pkg/apis/streaming/v1alpha1"
streamingv1alpha1informers "knative.dev/streaming/pkg/client/informers/externalversions/streaming/v1alpha1"
streamprocessor "knative.dev/streaming/pkg/client/injection/reconciler/streaming/v1alpha1/streamprocessor"
"knative.dev/streaming/pkg/kafka"
)
const (
STREAM_PROCESSOR_IMAGE = "docker.io/slinkydeveloper/engine-kafka"
)
// newReconciledNormal makes a new reconciler event with event type Normal, and
// reason StreamProcessorReconciled.
func newReconciledNormal(namespace, name string) reconciler.Event {
return reconciler.NewEvent(corev1.EventTypeNormal, "StreamProcessorReconciled", "StreamProcessor reconciled: \"%s/%s\"", namespace, name)
}
// Reconciler implements controller.Reconciler for StreamProcessor resources.
type Reconciler struct {
svcInformer corev1informers.ServiceInformer
deploymentInformer appsv1informers.DeploymentInformer
streamsInformer streamingv1alpha1informers.StreamInformer
kubeClient kubernetes.Interface
}
// Check that our Reconciler implements Interface
var _ streamprocessor.Interface = (*Reconciler)(nil)
// ReconcileKind implements Interface.ReconcileKind.
func (r *Reconciler) ReconcileKind(ctx context.Context, sp *v1alpha1.StreamProcessor) reconciler.Event {
logger := logging.FromContext(ctx)
sp.Status.InitializeConditions()
// Check if all streams exists
for _, s := range sp.Spec.Input {
_, err := r.streamsInformer.Lister().Streams(sp.Namespace).Get(s.Name)
if err != nil && apierrs.IsNotFound(err) {
logger.Errorf("Stream %s not found", s.Name)
sp.Status.MarkStreamNotFound(s.Name)
return err
}
}
if sp.Spec.Output != nil {
for _, s := range sp.Spec.Output {
_, err := r.streamsInformer.Lister().Streams(sp.Namespace).Get(s.Name)
if err != nil && apierrs.IsNotFound(err) {
logger.Errorf("Stream %s not found", s.Name)
sp.Status.MarkStreamNotFound(s.Name)
return err
}
}
}
if sp.Spec.State != nil {
_, err := r.streamsInformer.Lister().Streams(sp.Namespace).Get(sp.Spec.State.Name)
if err != nil && apierrs.IsNotFound(err) {
logger.Errorf("Stream %s not found", sp.Spec.State.Name)
sp.Status.MarkStreamNotFound(sp.Spec.State.Name)
return err
}
}
sp.Status.MarkStreamsReady()
patchStreamProcessor(sp)
_, err := r.reconcileDeployment(ctx, createDeployment(sp))
if err != nil {
sp.Status.MarkDeploymentFailed(deploymentName(sp), err)
return err
}
sp.Status.MarkReady()
sp.Status.ObservedGeneration = sp.Generation
return newReconciledNormal(sp.Namespace, sp.Name)
}
func (r *Reconciler) reconcileDeployment(ctx context.Context, expected *appsv1.Deployment) (*appsv1.Deployment, error) {
current, err := r.deploymentInformer.Lister().Deployments(expected.Namespace).Get(expected.Name)
if apierrs.IsNotFound(err) {
current, err = r.kubeClient.AppsV1().Deployments(expected.Namespace).Create(expected)
if err != nil {
return nil, err
}
return current, nil
} else if err != nil {
return nil, err
}
if !equality.Semantic.DeepDerivative(expected.Spec, current.Spec) {
// Don't modify the informers copy.
desired := current.DeepCopy()
desired.Spec = expected.Spec
current, err = r.kubeClient.AppsV1().Deployments(current.Namespace).Update(desired)
if err != nil {
return nil, err
}
}
return current, nil
}
func patchStreamProcessor(streamProcessor *v1alpha1.StreamProcessor) {
container := &streamProcessor.Spec.Container
found := false
for _, env := range container.Env {
if env.Name == "UNIX_DOMAIN_SOCKET" {
env.Value = "/data/function"
found = true
break
}
}
if found == false {
container.Env = append(container.Env, corev1.EnvVar{
Name: "UNIX_DOMAIN_SOCKET",
Value: "/data/function",
})
}
found = false
for _, vm := range container.VolumeMounts {
if vm.Name == "uds-data" {
vm.MountPath = "/data"
found = true
break
}
}
if found == false {
container.VolumeMounts = append(container.VolumeMounts, corev1.VolumeMount{
Name: "uds-data",
MountPath: "/data",
})
}
}
func deploymentName(streamProcessor *v1alpha1.StreamProcessor) string {
return fmt.Sprintf("streaming-node-deployment-%s", streamProcessor.Name)
}
func appId(streamProcessor *v1alpha1.StreamProcessor) string {
return fmt.Sprintf("stream-processor-%s", streamProcessor.Name)
}
func generateStreamBindingEnvValue(streamBindings []v1alpha1.StreamBindingSpec) string {
res := []string{}
for _, sb := range streamBindings {
if sb.ParameterName != "" && sb.Key != "" {
res = append(res, fmt.Sprintf("%s:%s:%s", sb.Name, sb.ParameterName, sb.Key))
} else if sb.ParameterName != "" {
res = append(res, fmt.Sprintf("%s:%s", sb.Name, sb.ParameterName))
} else {
res = append(res, sb.Name)
}
}
return strings.Join(res, ",")
}
func generateEnvs(streamProcessor *v1alpha1.StreamProcessor) []corev1.EnvVar {
envs := []corev1.EnvVar{}
envs = append(envs, corev1.EnvVar{
Name: "KAFKA_BROKERS",
Value: kafka.HARDCODED_BOOTSTRAP_SERVER,
})
envs = append(envs, corev1.EnvVar{
Name: "APP_ID",
Value: appId(streamProcessor),
})
envs = append(envs, corev1.EnvVar{
Name: "INPUT_STREAMS",
Value: generateStreamBindingEnvValue(streamProcessor.Spec.Input),
})
if streamProcessor.Spec.Output != nil && len(streamProcessor.Spec.Output) > 0 {
envs = append(envs, corev1.EnvVar{
Name: "OUTPUT_STREAMS",
Value: generateStreamBindingEnvValue(streamProcessor.Spec.Output),
})
}
if streamProcessor.Spec.State != nil {
envs = append(envs, corev1.EnvVar{
Name: "STATE_STREAM",
Value: generateStreamBindingEnvValue([]v1alpha1.StreamBindingSpec{*streamProcessor.Spec.State}),
})
}
return envs
}
func createDeployment(streamProcessor *v1alpha1.StreamProcessor) *appsv1.Deployment {
name := deploymentName(streamProcessor)
labels := map[string]string{
"stream-processor": streamProcessor.Name,
}
replicas := int32(1)
return &appsv1.Deployment{
ObjectMeta: metav1.ObjectMeta{
Name: name,
Namespace: streamProcessor.Namespace,
Labels: labels,
OwnerReferences: []metav1.OwnerReference{
*kmeta.NewControllerRef(streamProcessor),
},
},
Spec: appsv1.DeploymentSpec{
Replicas: &replicas,
Selector: &metav1.LabelSelector{MatchLabels: labels},
Template: corev1.PodTemplateSpec{
ObjectMeta: metav1.ObjectMeta{
Labels: labels,
},
Spec: corev1.PodSpec{
Containers: []corev1.Container{
{
Name: "stream-processor",
Image: STREAM_PROCESSOR_IMAGE,
Env: generateEnvs(streamProcessor),
VolumeMounts: []corev1.VolumeMount{{
Name: "uds-data",
MountPath: "/data",
}},
},
streamProcessor.Spec.Container,
},
Volumes: []corev1.Volume{{
Name: "uds-data",
VolumeSource: corev1.VolumeSource{
EmptyDir: &corev1.EmptyDirVolumeSource{},
},
}},
},
},
},
}
}