-
Notifications
You must be signed in to change notification settings - Fork 83
/
on-reconcile-one-time-migration.go
267 lines (230 loc) · 9.22 KB
/
on-reconcile-one-time-migration.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
//
// Copyright (c) 2019-2023 Red Hat, Inc.
// This program and the accompanying materials are made
// available under the terms of the Eclipse Public License 2.0
// which is available at https://www.eclipse.org/legal/epl-2.0/
//
// SPDX-License-Identifier: EPL-2.0
//
// Contributors:
// Red Hat, Inc. - initial API and implementation
//
package migration
import (
"context"
"fmt"
"time"
"github.com/devfile/devworkspace-operator/pkg/infrastructure"
"github.com/eclipse-che/che-operator/pkg/common/chetypes"
"github.com/eclipse-che/che-operator/pkg/common/constants"
defaults "github.com/eclipse-che/che-operator/pkg/common/operator-defaults"
"github.com/eclipse-che/che-operator/pkg/common/utils"
oauthv1 "github.com/openshift/api/oauth/v1"
"github.com/eclipse-che/che-operator/pkg/deploy"
routev1 "github.com/openshift/api/route/v1"
"github.com/sirupsen/logrus"
appsv1 "k8s.io/api/apps/v1"
batchv1 "k8s.io/api/batch/v1"
corev1 "k8s.io/api/core/v1"
networkingv1 "k8s.io/api/networking/v1"
rbacv1 "k8s.io/api/rbac/v1"
"k8s.io/apimachinery/pkg/api/errors"
"k8s.io/apimachinery/pkg/api/meta"
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/selection"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
)
type Migrator struct {
deploy.Reconcilable
migrationDone bool
}
func NewMigrator() *Migrator {
return &Migrator{
migrationDone: false,
}
}
func (m *Migrator) Reconcile(ctx *chetypes.DeployContext) (reconcile.Result, bool, error) {
if m.migrationDone {
return reconcile.Result{}, true, nil
}
done, err := m.migrate(ctx)
if done && err == nil {
m.migrationDone = true
// Give some time for the migration resources to be flushed and rerun reconcile
return reconcile.Result{RequeueAfter: 5 * time.Second}, false, err
}
return reconcile.Result{}, done, err
}
func (m *Migrator) Finalize(ctx *chetypes.DeployContext) bool {
return true
}
func (m *Migrator) migrate(ctx *chetypes.DeployContext) (bool, error) {
if err := addPartOfCheLabeltoUserDefinedObjects(ctx); err != nil {
return false, err
}
cheFlavor := defaults.GetCheFlavor()
if err := addPartOfCheLabelForObjectsWithLabel(ctx, constants.KubernetesInstanceLabelKey, cheFlavor); err != nil {
return false, err
}
if err := addPartOfCheLabelForObjectsWithLabel(ctx, "app", cheFlavor); err != nil {
return false, err
}
return true, nil
}
// addPartOfCheLabeltoUserDefinedObjects processes the following objects to add 'app.kubernetes.io/part-of=che.eclipse.org' label:
// - spec.server.cheClusterRoles
// - spec.server.cheWorkspaceClusterRole
// - spec.server.serverTrustStoreConfigMapName
// - spec.server.proxy.credentialssecretname
// - spec.networking.tlsSecretName
// Note, most of the objects above are autogenerated and do not require any migration,
// but to handle the case when some were created manually or operator updated, the check is done here.
func addPartOfCheLabeltoUserDefinedObjects(ctx *chetypes.DeployContext) error {
if !infrastructure.IsOpenShift() {
// Kubernetes only
tlsSecretName := utils.GetValue(ctx.CheCluster.Spec.Networking.TlsSecretName, constants.DefaultCheTLSSecretName)
if err := addPartOfCheLabelToSecret(ctx, tlsSecretName); err != nil {
return err
}
}
// TLS
if err := addPartOfCheLabelToSecret(ctx, constants.DefaultSelfSignedCertificateSecretName); err != nil {
return err
}
// Proxy credentials
if ctx.CheCluster.Spec.Components.CheServer.Proxy != nil {
proxyCredentialsSecret := utils.GetValue(ctx.CheCluster.Spec.Components.CheServer.Proxy.CredentialsSecretName, constants.DefaultProxyCredentialsSecret)
if err := addPartOfCheLabelToSecret(ctx, proxyCredentialsSecret); err != nil {
return err
}
}
// Legacy config map with additional CA certificates
if err := addPartOfCheLabelToConfigMap(ctx, constants.DefaultServerTrustStoreConfigMapName); err != nil {
return err
}
// Config map with CA certificates for git
if ctx.CheCluster.Spec.DevEnvironments.TrustedCerts != nil {
gitTrustedCertsConfigMapName := utils.GetValue(ctx.CheCluster.Spec.DevEnvironments.TrustedCerts.GitTrustedCertsConfigMapName, constants.DefaultGitSelfSignedCertsConfigMapName)
if err := addPartOfCheLabelToConfigMap(ctx, gitTrustedCertsConfigMapName); err != nil {
return err
}
}
return nil
}
func addPartOfCheLabelToSecret(ctx *chetypes.DeployContext, secretName string) error {
return addPartOfCheLabelToObject(ctx, secretName, &corev1.Secret{})
}
func addPartOfCheLabelToConfigMap(ctx *chetypes.DeployContext, configMapName string) error {
return addPartOfCheLabelToObject(ctx, configMapName, &corev1.ConfigMap{})
}
// addPartOfCheLabelToObject adds 'app.kubernetes.io/part-of=che.eclipse.org' label to the object with given name to be cached by operator's k8s client.
// As the function doesn't know the kind of the object with given name an empty object should be passed,
// for example: addPartOfCheLabelToObject(ctx, "my-secret", &corev1.Secret{})
func addPartOfCheLabelToObject(ctx *chetypes.DeployContext, objectName string, obj client.Object) error {
// Check if the object is already migrated
if exists, _ := deploy.GetNamespacedObject(ctx, objectName, obj); exists {
// Default client sees the object in cache, no need in adding anything
return nil
}
err := ctx.ClusterAPI.NonCachingClient.Get(context.TODO(), types.NamespacedName{Namespace: ctx.CheCluster.Namespace, Name: objectName}, obj)
if err != nil {
if errors.IsNotFound(err) {
// The object doesn't exist in cluster, nothing to do
return nil
}
return err
}
if err := ctx.ClusterAPI.NonCachingClient.Update(context.TODO(), setPartOfLabel(obj)); err != nil {
return err
}
logrus.Info(getObjectMigratedMessage(obj))
return nil
}
func setPartOfLabel(obj client.Object) client.Object {
labels := obj.GetLabels()
if labels == nil {
labels = make(map[string]string)
}
labels[constants.KubernetesPartOfLabelKey] = constants.CheEclipseOrg
obj.SetLabels(labels)
return obj
}
// addPartOfCheLabelForObjectsWithLabel searches for objects in Che installation namespace,
// that have given label and adds 'app.kubernetes.io/part-of=che.eclipse.org'
func addPartOfCheLabelForObjectsWithLabel(ctx *chetypes.DeployContext, labelKey string, labelValue string) error {
// Prepare selector for all instance=che objects in the installation namespace
instanceCheSelectorRequirement, err := labels.NewRequirement(labelKey, selection.Equals, []string{labelValue})
if err != nil {
logrus.Error(getFailedToCreateSelectorErrorMessage())
return err
}
// Do not migrate already migrated objects
notPartOfCheSelectorRequirement, err := labels.NewRequirement(constants.KubernetesPartOfLabelKey, selection.NotEquals, []string{constants.CheEclipseOrg})
if err != nil {
logrus.Error(getFailedToCreateSelectorErrorMessage())
return err
}
objectsToMigrateLabelSelector := labels.NewSelector().
Add(*instanceCheSelectorRequirement).
Add(*notPartOfCheSelectorRequirement)
listOptions := &client.ListOptions{
LabelSelector: objectsToMigrateLabelSelector,
Namespace: ctx.CheCluster.GetNamespace(),
}
// This list should be based on the list from the cache function (see NewCache filed of the managar in main.go)
kindsToMigrate := []client.ObjectList{
&appsv1.DeploymentList{},
&corev1.PodList{},
&batchv1.JobList{},
&corev1.ServiceList{},
&corev1.SecretList{},
&corev1.ConfigMapList{},
&corev1.ServiceAccountList{},
&rbacv1.RoleList{},
&rbacv1.RoleBindingList{},
&rbacv1.ClusterRoleList{},
&rbacv1.ClusterRoleBindingList{},
&corev1.PersistentVolumeClaimList{},
}
if infrastructure.IsOpenShift() {
kindsToMigrate = append(kindsToMigrate, &routev1.RouteList{})
kindsToMigrate = append(kindsToMigrate, &oauthv1.OAuthClientList{})
} else {
kindsToMigrate = append(kindsToMigrate, &networkingv1.IngressList{})
}
for _, listToGet := range kindsToMigrate {
if err := addPartOfCheLabelToObjectsBySelector(ctx, listOptions, listToGet); err != nil {
return err
}
}
return nil
}
// addPartOfCheLabelToObjectsBySelector adds 'app.kubernetes.io/part-of=che.eclipse.org' label to all objects
// of given objectsList kind that match the provided in listOptions selector and namespace.
func addPartOfCheLabelToObjectsBySelector(ctx *chetypes.DeployContext, listOptions *client.ListOptions, objectsList client.ObjectList) error {
if err := ctx.ClusterAPI.NonCachingClient.List(context.TODO(), objectsList, listOptions); err != nil {
logrus.Warnf("Failed to get %s to add %s label", objectsList.GetObjectKind().GroupVersionKind().Kind, constants.KubernetesPartOfLabelKey)
return err
}
objects, err := meta.ExtractList(objectsList)
if err != nil {
return err
}
for _, runtimeObj := range objects {
obj := setPartOfLabel(runtimeObj.(client.Object))
if err := ctx.ClusterAPI.NonCachingClient.Update(context.TODO(), obj); err != nil {
return err
}
logrus.Info(getObjectMigratedMessage(obj))
}
return nil
}
func getFailedToCreateSelectorErrorMessage() string {
return "Failed to create selector for resources migration. Unable to perform resources migration."
}
func getObjectMigratedMessage(obj client.Object) string {
return fmt.Sprintf("Added '%s=%s' label to %s object of %s kind",
constants.KubernetesPartOfLabelKey, constants.CheEclipseOrg, obj.GetName(), deploy.GetObjectType(obj))
}