|
| 1 | +package subroutine |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "context" |
| 6 | + _ "embed" |
| 7 | + "encoding/json" |
| 8 | + "fmt" |
| 9 | + "strings" |
| 10 | + "text/template" |
| 11 | + |
| 12 | + kcpv1alpha1 "github.com/kcp-dev/kcp/sdk/apis/core/v1alpha1" |
| 13 | + lifecycleruntimeobject "github.com/platform-mesh/golang-commons/controller/lifecycle/runtimeobject" |
| 14 | + lifecyclesubroutine "github.com/platform-mesh/golang-commons/controller/lifecycle/subroutine" |
| 15 | + "github.com/platform-mesh/golang-commons/errors" |
| 16 | + "github.com/platform-mesh/golang-commons/logger" |
| 17 | + apiextensionsv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" |
| 18 | + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" |
| 19 | + ctrl "sigs.k8s.io/controller-runtime" |
| 20 | + "sigs.k8s.io/controller-runtime/pkg/client" |
| 21 | + "sigs.k8s.io/controller-runtime/pkg/reconcile" |
| 22 | + "sigs.k8s.io/yaml" |
| 23 | +) |
| 24 | + |
| 25 | +var ( |
| 26 | + //go:embed manifests/organizationIdp/repository.yaml |
| 27 | + repository string |
| 28 | + |
| 29 | + //go:embed manifests/organizationIdp/helmrelease.yaml |
| 30 | + helmRelease string |
| 31 | +) |
| 32 | + |
| 33 | +type realmSubroutine struct { |
| 34 | + k8s client.Client |
| 35 | +} |
| 36 | + |
| 37 | +func NewRealmSubroutine(k8s client.Client) *realmSubroutine { |
| 38 | + return &realmSubroutine{ |
| 39 | + k8s: k8s, |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +var _ lifecyclesubroutine.Subroutine = &realmSubroutine{} |
| 44 | + |
| 45 | +func (r *realmSubroutine) GetName() string { return "Realm" } |
| 46 | + |
| 47 | +func (r *realmSubroutine) Finalizers() []string { return []string{} } |
| 48 | + |
| 49 | +func (r *realmSubroutine) Finalize(ctx context.Context, instance lifecycleruntimeobject.RuntimeObject) (reconcile.Result, errors.OperatorError) { |
| 50 | + log := logger.LoadLoggerFromContext(ctx) |
| 51 | + |
| 52 | + lc := instance.(*kcpv1alpha1.LogicalCluster) |
| 53 | + workspaceName := getWorkspaceName(lc) |
| 54 | + if workspaceName == "" { |
| 55 | + return ctrl.Result{}, errors.NewOperatorError(fmt.Errorf("failed to get workspace path"), true, false) |
| 56 | + } |
| 57 | + |
| 58 | + ociObj, err := unstructuredFromString(repository, nil, log) |
| 59 | + if err != nil { |
| 60 | + return ctrl.Result{}, errors.NewOperatorError(fmt.Errorf("failed to load OCI repository manifest: %w", err), true, true) |
| 61 | + } |
| 62 | + if err := r.k8s.Delete(ctx, &ociObj); err != nil { |
| 63 | + return ctrl.Result{}, errors.NewOperatorError(fmt.Errorf("failed to delete OCI repository: %w", err), true, true) |
| 64 | + } |
| 65 | + |
| 66 | + helmObj, err := unstructuredFromString(helmRelease, nil, log) |
| 67 | + if err != nil { |
| 68 | + return ctrl.Result{}, errors.NewOperatorError(fmt.Errorf("failed to load HelmRelease manifest: %w", err), true, true) |
| 69 | + } |
| 70 | + helmObj.SetName(workspaceName) |
| 71 | + if err := r.k8s.Delete(ctx, &helmObj); err != nil { |
| 72 | + return ctrl.Result{}, errors.NewOperatorError(fmt.Errorf("failed to delete HelmRelease: %w", err), true, true) |
| 73 | + } |
| 74 | + |
| 75 | + log.Info().Str("realm", workspaceName).Msg("Successfully finalized resources") |
| 76 | + return ctrl.Result{}, nil |
| 77 | +} |
| 78 | + |
| 79 | +func (r *realmSubroutine) Process(ctx context.Context, instance lifecycleruntimeobject.RuntimeObject) (reconcile.Result, errors.OperatorError) { |
| 80 | + lc := instance.(*kcpv1alpha1.LogicalCluster) |
| 81 | + |
| 82 | + workspaceName := getWorkspaceName(lc) |
| 83 | + if workspaceName == "" { |
| 84 | + return ctrl.Result{}, errors.NewOperatorError(fmt.Errorf("failed to get workspace path"), true, false) |
| 85 | + } |
| 86 | + |
| 87 | + patch := map[string]interface{}{ |
| 88 | + "crossplane": map[string]interface{}{ |
| 89 | + "realm": map[string]interface{}{ |
| 90 | + "name": workspaceName, |
| 91 | + "displayName": workspaceName, |
| 92 | + }, |
| 93 | + "client": map[string]interface{}{ |
| 94 | + "name": workspaceName, |
| 95 | + "displayName": workspaceName, |
| 96 | + }, |
| 97 | + }, |
| 98 | + "keycloakConfig": map[string]interface{}{ |
| 99 | + "client": map[string]interface{}{ |
| 100 | + "name": workspaceName, |
| 101 | + "targetSecret": map[string]interface{}{ |
| 102 | + "name": fmt.Sprintf("portal-client-secret-%s", workspaceName), |
| 103 | + }, |
| 104 | + }, |
| 105 | + }, |
| 106 | + } |
| 107 | + |
| 108 | + marshalledPatch, err := json.Marshal(patch) |
| 109 | + if err != nil { |
| 110 | + return ctrl.Result{}, errors.NewOperatorError(fmt.Errorf("failed to marshall patch map: %w", err), true, true) |
| 111 | + } |
| 112 | + |
| 113 | + values := apiextensionsv1.JSON{Raw: marshalledPatch} |
| 114 | + releaseName := fmt.Sprintf("%s-idp", workspaceName) |
| 115 | + |
| 116 | + err = applyManifestWithMergedValues(ctx, repository, r.k8s, nil) |
| 117 | + if err != nil { |
| 118 | + return ctrl.Result{}, errors.NewOperatorError(fmt.Errorf("failed to create OCI repository: %w", err), true, true) |
| 119 | + } |
| 120 | + |
| 121 | + err = applyReleaseWithValues(ctx, helmRelease, r.k8s, values, releaseName) |
| 122 | + if err != nil { |
| 123 | + return ctrl.Result{}, errors.NewOperatorError(fmt.Errorf("failed to create HelmRelease: %w", err), true, true) |
| 124 | + } |
| 125 | + |
| 126 | + return ctrl.Result{}, nil |
| 127 | +} |
| 128 | + |
| 129 | +func getWorkspaceName(lc *kcpv1alpha1.LogicalCluster) string { |
| 130 | + if path, ok := lc.Annotations["kcp.io/path"]; ok { |
| 131 | + pathElements := strings.Split(path, ":") |
| 132 | + return pathElements[len(pathElements)-1] |
| 133 | + } |
| 134 | + return "" |
| 135 | +} |
| 136 | + |
| 137 | +func applyReleaseWithValues(ctx context.Context, release string, k8sClient client.Client, values apiextensionsv1.JSON, releaseName string) error { |
| 138 | + log := logger.LoadLoggerFromContext(ctx) |
| 139 | + |
| 140 | + obj, err := unstructuredFromString(release, map[string]string{}, log) |
| 141 | + if err != nil { |
| 142 | + return errors.Wrap(err, "Failed to get unstructuredFromFile") |
| 143 | + } |
| 144 | + obj.SetName(releaseName) |
| 145 | + |
| 146 | + if err := unstructured.SetNestedField(obj.Object, releaseName, "spec", "releaseName"); err != nil { |
| 147 | + return errors.Wrap(err, "failed to set spec.releaseName") |
| 148 | + } |
| 149 | + |
| 150 | + obj.Object["spec"].(map[string]interface{})["values"] = values |
| 151 | + |
| 152 | + err = k8sClient.Patch(ctx, &obj, client.Apply, client.FieldOwner("security-operator")) |
| 153 | + if err != nil { |
| 154 | + return errors.Wrap(err, "Failed to apply manifest: (%s/%s)", obj.GetKind(), obj.GetName()) |
| 155 | + } |
| 156 | + return nil |
| 157 | +} |
| 158 | + |
| 159 | +func unstructuredFromString(manifest string, templateData map[string]string, log *logger.Logger) (unstructured.Unstructured, error) { |
| 160 | + manifestBytes := []byte(manifest) |
| 161 | + |
| 162 | + res, err := ReplaceTemplate(templateData, manifestBytes) |
| 163 | + if err != nil { |
| 164 | + return unstructured.Unstructured{}, errors.Wrap(err, "Failed to replace template") |
| 165 | + } |
| 166 | + |
| 167 | + var objMap map[string]interface{} |
| 168 | + if err := yaml.Unmarshal(res, &objMap); err != nil { |
| 169 | + return unstructured.Unstructured{}, errors.Wrap(err, "Failed to unmarshal YAML from template. Output:\n%s", string(res)) |
| 170 | + } |
| 171 | + |
| 172 | + log.Debug().Str("obj", fmt.Sprintf("%+v", objMap)).Msg("Unmarshalled object") |
| 173 | + |
| 174 | + obj := unstructured.Unstructured{Object: objMap} |
| 175 | + |
| 176 | + log.Debug().Str("kind", obj.GetKind()).Str("name", obj.GetName()).Str("namespace", obj.GetNamespace()).Msg("Applying manifest") |
| 177 | + return obj, err |
| 178 | +} |
| 179 | + |
| 180 | +func ReplaceTemplate(templateData map[string]string, templateBytes []byte) ([]byte, error) { |
| 181 | + tmpl, err := template.New("manifest").Parse(string(templateBytes)) |
| 182 | + if err != nil { |
| 183 | + return []byte{}, errors.Wrap(err, "Failed to parse template") |
| 184 | + } |
| 185 | + var result bytes.Buffer |
| 186 | + err = tmpl.Execute(&result, templateData) |
| 187 | + if err != nil { |
| 188 | + keys := make([]string, 0, len(templateData)) |
| 189 | + for k := range templateData { |
| 190 | + keys = append(keys, k) |
| 191 | + } |
| 192 | + return []byte{}, errors.Wrap(err, "Failed to execute template with keys %v", keys) |
| 193 | + } |
| 194 | + if result.Len() == 0 { |
| 195 | + return []byte{}, nil |
| 196 | + } |
| 197 | + return result.Bytes(), nil |
| 198 | +} |
| 199 | + |
| 200 | +func applyManifestWithMergedValues(ctx context.Context, manifest string, k8sClient client.Client, templateData map[string]string) error { |
| 201 | + log := logger.LoadLoggerFromContext(ctx) |
| 202 | + |
| 203 | + obj, err := unstructuredFromString(manifest, templateData, log) |
| 204 | + if err != nil { |
| 205 | + return err |
| 206 | + } |
| 207 | + |
| 208 | + err = k8sClient.Patch(ctx, &obj, client.Apply, client.FieldOwner("security-operator")) |
| 209 | + if err != nil { |
| 210 | + return errors.Wrap(err, "Failed to apply manifest (%s/%s)", obj.GetKind(), obj.GetName()) |
| 211 | + } |
| 212 | + return nil |
| 213 | +} |
0 commit comments