Files
zitadel-k8s-operator/src/internal/controller/organization_controller.go
Haim Kortovich 686d4e5e11 catch error
[ZITADOPER-5]
2024-10-29 17:59:33 -05:00

264 lines
9.0 KiB
Go

/*
Copyright 2024.
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 controller
import (
"context"
"fmt"
"strings"
"time"
zitadelv1alpha1 "bitbucket.org/topmanage-software-engineering/zitadel-k8s-operator/src/api/v1alpha1"
condition "bitbucket.org/topmanage-software-engineering/zitadel-k8s-operator/src/pkg/condition"
"bitbucket.org/topmanage-software-engineering/zitadel-k8s-operator/src/pkg/controller/zitadel"
zitadelClient "bitbucket.org/topmanage-software-engineering/zitadel-k8s-operator/src/pkg/zitadel"
"github.com/zitadel/zitadel-go/v2/pkg/client/management"
"github.com/zitadel/zitadel-go/v2/pkg/client/middleware"
adm "github.com/zitadel/zitadel-go/v2/pkg/client/zitadel/admin"
pb "github.com/zitadel/zitadel-go/v2/pkg/client/zitadel/management"
"k8s.io/client-go/util/workqueue"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
ctrlClient "sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/controller"
)
// OrganizationReconciler reconciles a Organization object
type OrganizationReconciler struct {
client.Client
RefResolver *zitadelv1alpha1.RefResolver
ConditionReady *condition.Ready
RequeueInterval time.Duration
}
func NewOrganizationReconciler(client client.Client, refResolver *zitadelv1alpha1.RefResolver, conditionReady *condition.Ready,
requeueInterval time.Duration) *OrganizationReconciler {
return &OrganizationReconciler{
Client: client,
RefResolver: refResolver,
ConditionReady: conditionReady,
RequeueInterval: requeueInterval,
}
}
//+kubebuilder:rbac:groups=zitadel.topmanage.com,resources=organizations,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=zitadel.topmanage.com,resources=organizations/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=zitadel.topmanage.com,resources=organizations/finalizers,verbs=update
// Reconcile is part of the main kubernetes reconciliation loop which aims to
// move the current state of the cluster closer to the desired state.
func (r *OrganizationReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
var organization zitadelv1alpha1.Organization
if err := r.Get(ctx, req.NamespacedName, &organization); err != nil {
return ctrl.Result{}, client.IgnoreNotFound(err)
}
wr := newWrappedOrganizationReconciler(r.Client, r.RefResolver, &organization)
wf := newWrappedOrganizationFinalizer(r.Client, &organization)
tf := zitadel.NewZitadelFinalizer(r.Client, wf)
tr := zitadel.NewZitadelReconciler(r.Client, r.ConditionReady, wr, tf, r.RequeueInterval)
result, err := tr.Reconcile(ctx, &organization)
if err != nil {
return result, fmt.Errorf("error reconciling in OrganizationReconciler: %v", err)
}
return result, nil
}
type wrappedOrganizationReconciler struct {
client.Client
refResolver *zitadelv1alpha1.RefResolver
organization *zitadelv1alpha1.Organization
}
func newWrappedOrganizationReconciler(client client.Client, refResolver *zitadelv1alpha1.RefResolver,
organization *zitadelv1alpha1.Organization) zitadel.WrappedReconciler {
return &wrappedOrganizationReconciler{
Client: client,
refResolver: refResolver,
organization: organization,
}
}
type orgReconcilePhase struct {
Name string
Reconcile func(context.Context, *management.Client) error
}
func (wr *wrappedOrganizationReconciler) Reconcile(ctx context.Context, ztdClient *management.Client) error {
phases := []orgReconcilePhase{
{
Name: "organization",
Reconcile: wr.reconcileOrg,
},
{
Name: "admin",
Reconcile: wr.reconcileInitialAdmin,
},
}
for _, p := range phases {
err := p.Reconcile(ctx, ztdClient)
if err != nil {
return err
}
}
return nil
}
func (wr *wrappedOrganizationReconciler) reconcileOrg(ctx context.Context, ztdClient *management.Client) error {
zitadelCluster, err := wr.refResolver.ZitadelCluster(ctx, &wr.organization.Spec.ZitadelClusterRef, wr.organization.Namespace)
if err != nil {
return err
}
orgRes, err := ztdClient.GetOrgByDomainGlobal(ctx, &pb.GetOrgByDomainGlobalRequest{
Domain: strings.ToLower(fmt.Sprintf("%s.%s", wr.organization.Name, zitadelCluster.Spec.Host)),
})
if err != nil {
if !strings.Contains(err.Error(), "not found") {
return fmt.Errorf("Error getting org: %v", err)
}
}
if orgRes == nil {
resp, err := ztdClient.AddOrg(ctx, &pb.AddOrgRequest{
Name: strings.ToLower(wr.organization.Name),
})
if err != nil {
return fmt.Errorf("error creating organization in Zitadel: %v", err)
}
patch := ctrlClient.MergeFrom(wr.organization.DeepCopy())
wr.organization.Status.OrgId = resp.Id
return wr.Client.Status().Patch(ctx, wr.organization, patch)
}
patch := ctrlClient.MergeFrom(wr.organization.DeepCopy())
wr.organization.Status.OrgId = orgRes.Org.Id
return wr.Client.Status().Patch(ctx, wr.organization, patch)
}
func (wr *wrappedOrganizationReconciler) reconcileInitialAdmin(ctx context.Context, ztdClient *management.Client) error {
zitadelCluster, err := wr.refResolver.ZitadelCluster(ctx, &wr.organization.Spec.ZitadelClusterRef, wr.organization.Namespace)
if err != nil {
return err
}
adminUser, err := ztdClient.GetUserByLoginNameGlobal(ctx, &pb.GetUserByLoginNameGlobalRequest{
LoginName: strings.ToLower(fmt.Sprintf("%s@%s.%s", wr.organization.Spec.OrganizationAdmin.UserName, wr.organization.Name, zitadelCluster.Spec.Host)),
})
if err != nil {
if !strings.Contains(err.Error(), "could not be found") {
return fmt.Errorf("Error getting admin user: %v", err)
}
}
ctx = middleware.SetOrgID(ctx, wr.organization.Status.OrgId)
var userid string
if adminUser == nil {
resp, err := ztdClient.AddHumanUser(ctx, &pb.AddHumanUserRequest{
UserName: wr.organization.Spec.OrganizationAdmin.UserName,
Profile: &pb.AddHumanUserRequest_Profile{
FirstName: wr.organization.Spec.OrganizationAdmin.FirstName,
LastName: wr.organization.Spec.OrganizationAdmin.LastName,
},
Email: &pb.AddHumanUserRequest_Email{
Email: wr.organization.Spec.OrganizationAdmin.Email,
IsEmailVerified: false,
},
})
userid = resp.UserId
if err != nil {
return fmt.Errorf("Error adding human user: %v", err)
}
{
if _, err := ztdClient.AddOrgMember(ctx, &pb.AddOrgMemberRequest{
UserId: userid,
Roles: []string{
"ORG_OWNER",
},
}); err != nil {
if !strings.Contains(err.Error(), "Errors.Org.Member.RolesNotChanged") {
return fmt.Errorf("Error adding org member: %v", err)
}
}
}
} else {
userid = adminUser.User.Id
}
{
if _, err := ztdClient.UpdateOrgMember(ctx, &pb.UpdateOrgMemberRequest{
UserId: userid,
Roles: []string{
"ORG_OWNER",
},
}); err != nil {
if !strings.Contains(err.Error(), "Errors.Org.Member.RolesNotChanged") {
return fmt.Errorf("Error updating org member: %v", err)
}
}
if zitadelCluster.Spec.FirstOrgName == wr.organization.Name {
adminClient, err := zitadelClient.NewAdminClient(ctx, zitadelCluster, *wr.refResolver)
if err != nil {
return err
}
{
if _, err := adminClient.AddIAMMember(ctx, &adm.AddIAMMemberRequest{
UserId: userid,
Roles: []string{
"IAM_OWNER",
},
}); err != nil {
if !strings.Contains(err.Error(), "Roles have not been changed") && !strings.Contains(err.Error(), "AlreadyExists") {
return fmt.Errorf("Error adding iam member: %v", err)
}
}
}
{
if _, err := adminClient.UpdateIAMMember(ctx, &adm.UpdateIAMMemberRequest{
UserId: userid,
Roles: []string{
"IAM_OWNER",
},
}); err != nil {
if !strings.Contains(err.Error(), "Roles have not been changed") {
return fmt.Errorf("Error updating iam member: %v", err)
}
}
}
}
}
patch := client.MergeFrom(wr.organization.DeepCopy())
wr.organization.Status.AdminId = userid
return wr.Status().Patch(ctx, wr.organization, patch)
}
func (wr *wrappedOrganizationReconciler) PatchStatus(ctx context.Context, patcher condition.Patcher) error {
patch := client.MergeFrom(wr.organization.DeepCopy())
patcher(&wr.organization.Status)
if err := wr.Client.Status().Patch(ctx, wr.organization, patch); err != nil {
return fmt.Errorf("error patching Organization status: %v", err)
}
return nil
}
// SetupWithManager sets up the controller with the Manager.
func (r *OrganizationReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&zitadelv1alpha1.Organization{}).
WithOptions(controller.Options{RateLimiter: workqueue.NewItemExponentialFailureRateLimiter(time.Millisecond*500, time.Minute*3)}).
Complete(r)
}