This repository has been archived by the owner on Apr 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 28
/
webhandler.go
306 lines (265 loc) · 9.32 KB
/
webhandler.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
package handlers
import (
"context"
"strings"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/integr8ly/tutorial-web-app-operator/pkg/apis/integreatly/v1alpha1"
"errors"
"fmt"
"github.com/integr8ly/tutorial-web-app-operator/pkg/apis/integreatly/openshift"
"github.com/integr8ly/tutorial-web-app-operator/pkg/metrics"
routev1 "github.com/openshift/api/route/v1"
v1 "github.com/openshift/api/template/v1"
"github.com/operator-framework/operator-sdk/pkg/sdk"
"github.com/operator-framework/operator-sdk/pkg/util/k8sutil"
"github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
errors2 "k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/runtime"
)
const (
WTLocations = "WALKTHROUGH_LOCATIONS"
IntegreatlyVersion = "INTEGREATLY_VERSION"
ClusterType = "CLUSTER_TYPE"
OpenShiftVersion = "OPENSHIFT_VERSION"
OpenShiftAPIHost = "OPENSHIFT_API"
InstalledServices = "INSTALLED_SERVICES"
InstallationType = "INSTALLATION_TYPE"
WTLocationsDefault = "https://github.com/integr8ly/tutorial-web-app-walkthroughs#v1.12.3"
IntegreatlyVersionDefault = "not set"
ClusterTypeDefault = "not set"
OpenShiftVersionDefault = "3"
OpenShiftAPIHostDefault = "openshift.default.svc"
WebAppImage = "quay.io/integreatly/tutorial-web-app:2.28.1"
serviceName = "tutorial-web-app"
routeName = "tutorial-web-app"
upgradeData = "UPGRADE_DATA"
)
var webappParams = [...]string{"OPENSHIFT_OAUTHCLIENT_ID", "OPENSHIFT_HOST", "OPENSHIFT_OAUTH_HOST", "SSO_ROUTE", OpenShiftAPIHost, OpenShiftVersion, IntegreatlyVersion, WTLocations, ClusterType, InstalledServices, InstallationType, upgradeData}
func NewWebHandler(m *metrics.Metrics, osClient openshift.OSClientInterface, factory ClientFactory, cruder SdkCruder) AppHandler {
return AppHandler{
metrics: m,
osClient: osClient,
dynamicResourceClientFactory: factory,
sdkCruder: cruder,
}
}
func (h *AppHandler) Handle(ctx context.Context, event sdk.Event) error {
switch o := event.Object.(type) {
case *v1alpha1.WebApp:
if o.GetDeletionTimestamp() != nil {
err := h.Delete(o)
if err != nil {
logrus.Errorf("Error deleting all operator related resources: %v", err)
h.SetStatus(err.Error(), o)
return err
}
return nil
}
if o.Status.Message == "OK" {
//finished provision, move to reconcile
err := h.reconcile(o)
if err != nil {
h.SetStatus("Error: "+err.Error(), o)
return err
}
h.SetStatus("OK", o)
return nil
}
exts, err := h.ProcessTemplate(o)
if err != nil {
logrus.Errorf("Error while processing the template: %v", err)
h.SetStatus(err.Error(), o)
return err
}
runtimeObjs, err := h.GetRuntimeObjs(exts)
if err != nil {
logrus.Errorf("Error parsing the runtime objects from the template: %v", err)
h.SetStatus(err.Error(), o)
return err
}
// append route onto runtime objs list
route := h.CreateRoute(o)
runtimeObjs = append(runtimeObjs, route)
err = h.ProvisionObjects(runtimeObjs, o)
if err != nil {
logrus.Errorf("Error provisioning the runtime objects: %v", err)
h.SetStatus(err.Error(), o)
return err
}
if h.IsAppReady(o) {
h.SetStatus("OK", o)
} else {
h.SetStatus("", o)
}
return nil
}
return nil
}
func (h *AppHandler) reconcile(cr *v1alpha1.WebApp) error {
//reconcile template params into deployment config
dc, err := h.osClient.GetDC(cr.Namespace, "tutorial-web-app")
if err != nil {
return err
}
dcUpdated := false
dcUpdated, dc.Spec.Template.Spec.Containers[0] = migrateImage(dc.Spec.Template.Spec.Containers[0])
for _, param := range webappParams {
updated := false
if val, ok := cr.Spec.Template.Parameters[param]; ok {
updated, dc.Spec.Template.Spec.Containers[0] = updateOrCreateEnvVar(dc.Spec.Template.Spec.Containers[0], param, val)
} else {
// if WALKTHROUGH_LOCATIONS is not defined then use the default value
if param == WTLocations {
updated, dc.Spec.Template.Spec.Containers[0] = updateOrCreateEnvVar(dc.Spec.Template.Spec.Containers[0], param, WTLocationsDefault)
} else if param == IntegreatlyVersion {
updated, dc.Spec.Template.Spec.Containers[0] = updateOrCreateEnvVar(dc.Spec.Template.Spec.Containers[0], param, IntegreatlyVersionDefault)
} else if param == ClusterType {
updated, dc.Spec.Template.Spec.Containers[0] = updateOrCreateEnvVar(dc.Spec.Template.Spec.Containers[0], param, ClusterTypeDefault)
} else if param == OpenShiftVersion {
updated, dc.Spec.Template.Spec.Containers[0] = updateOrCreateEnvVar(dc.Spec.Template.Spec.Containers[0], param, OpenShiftVersionDefault)
} else if param == OpenShiftAPIHost {
updated, dc.Spec.Template.Spec.Containers[0] = updateOrCreateEnvVar(dc.Spec.Template.Spec.Containers[0], param, OpenShiftAPIHostDefault)
} else {
//key does not exist in CR, ensure it is not present in the DC
updated, dc.Spec.Template.Spec.Containers[0] = deleteEnvVar(dc.Spec.Template.Spec.Containers[0], param)
}
}
if updated && !dcUpdated {
dcUpdated = true
}
}
//update the DC
if dcUpdated {
logrus.Info("Updating DC")
return h.osClient.UpdateDC(cr.Namespace, &dc)
}
return nil
}
func migrateImage(container corev1.Container) (bool, corev1.Container) {
if container.Image == WebAppImage {
return false, container
}
logrus.Infof("Migrating image from %v to %v", container.Image, WebAppImage)
container.Image = WebAppImage
return true, container
}
func deleteEnvVar(container corev1.Container, envName string) (bool, corev1.Container) {
for k, envVar := range container.Env {
if envVar.Name == envName {
container.Env = append(container.Env[:k], container.Env[k+1:]...)
return true, container
}
}
return false, container
}
func updateOrCreateEnvVar(container corev1.Container, envName, envVal string) (bool, corev1.Container) {
for envIndex, envVar := range container.Env {
if envVar.Name == envName {
if envVar.Value != envVal {
// update env var with correct value
container.Env[envIndex].Value = envVal
return true, container
}
return false, container
}
}
//create new env var with correct value
container.Env = append(container.Env, corev1.EnvVar{Name: envName, Value: envVal})
return true, container
}
func (h *AppHandler) Delete(cr *v1alpha1.WebApp) error {
return h.osClient.Delete(cr.Namespace, cr.Spec.AppLabel)
}
func (h *AppHandler) SetStatus(msg string, cr *v1alpha1.WebApp) {
cr.Status.Message = msg
imgParts := strings.Split(WebAppImage, ":")
cr.Status.Version = imgParts[len(imgParts)-1]
h.sdkCruder.Update(cr)
}
func (h *AppHandler) ProcessTemplate(cr *v1alpha1.WebApp) ([]runtime.RawExtension, error) {
tmplPath := cr.Spec.Template.Path
res, err := openshift.LoadKubernetesResourceFromFile(tmplPath)
if err != nil {
return nil, err
}
params := make(map[string]string)
for k, v := range cr.Spec.Template.Parameters {
params[k] = v
}
tmpl := res.(*v1.Template)
return h.osClient.ProcessTemplate(tmpl, params, openshift.TemplateDefaultOpts)
}
func (h *AppHandler) GetRuntimeObjs(exts []runtime.RawExtension) ([]runtime.Object, error) {
objects := make([]runtime.Object, 0)
for _, ext := range exts {
res, err := openshift.LoadKubernetesResource(ext.Raw)
if err != nil {
return nil, err
}
objects = append(objects, res)
}
return objects, nil
}
func (h *AppHandler) CreateRoute(cr *v1alpha1.WebApp) *routev1.Route {
route := &routev1.Route{
TypeMeta: metav1.TypeMeta{
Kind: "Route",
APIVersion: "route.openshift.io/v1",
},
ObjectMeta: metav1.ObjectMeta{
Name: routeName,
Namespace: cr.Namespace,
Labels: cr.GetLabels(),
},
Spec: routev1.RouteSpec{
TLS: &routev1.TLSConfig{
Termination: routev1.TLSTerminationEdge,
},
To: routev1.RouteTargetReference{
Kind: "Service",
Name: serviceName,
},
},
}
subdomain := cr.Spec.Template.Parameters["ROUTING_SUBDOMAIN"]
// Only set the host when the routing subdomain is set (RHMI 2.x). In 1.x we want to
// make sure to not change the existing route hosts because the cluster CORS settings
// depend on it
if subdomain != "" {
routeName := "solution-explorer"
route.Name = routeName
route.Spec.Host = fmt.Sprintf("%s.%s", routeName, subdomain)
}
return route
}
func (h *AppHandler) ProvisionObjects(objects []runtime.Object, cr *v1alpha1.WebApp) error {
for _, o := range objects {
gvk := o.GetObjectKind().GroupVersionKind()
apiVersion, kind := gvk.ToAPIVersionAndKind()
gvkStr := gvk.String()
resourceClient, _, err := h.dynamicResourceClientFactory(apiVersion, kind, cr.Namespace)
if err != nil {
return errors.New(fmt.Sprintf("failed to get resource client: %v", err))
}
unstructObj, err := k8sutil.UnstructuredFromRuntimeObject(o)
if err != nil {
return fmt.Errorf("%v failed to turn runtime object %s into unstructured object during provision", err, gvkStr)
}
unstructObj, err = resourceClient.Create(unstructObj)
if err != nil && !errors2.IsAlreadyExists(err) {
return fmt.Errorf("%v failed to create object during provision with kind ", err)
}
}
return nil
}
func (h *AppHandler) IsAppReady(cr *v1alpha1.WebApp) bool {
pod, err := h.osClient.GetPod(cr.Namespace, cr.Spec.AppLabel)
if err != nil {
return false
}
if pod.Status.Phase == corev1.PodRunning {
return true
}
return false
}