zelda/backend/internal/controller/zuser_controller.go

173 lines
6.1 KiB
Go
Raw Normal View History

2024-11-19 16:57:27 +08:00
/*
Copyright 2023 ycyxuehan.
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"
corev1 "k8s.io/api/core/v1"
rbacv1 "k8s.io/api/rbac/v1"
"k8s.io/apimachinery/pkg/runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
zeldaiov1alpha1 "github.com/ycyxuehan/zelda/api/v1alpha1"
watchers "github.com/ycyxuehan/zelda/watcher"
)
// ZUserReconciler reconciles a ZUser object
type ZUserReconciler struct {
client.Client
Scheme *runtime.Scheme
}
//+kubebuilder:rbac:groups=zelda.io,resources=zusers,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=zelda.io,resources=zusers/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=zelda.io,resources=zusers/finalizers,verbs=update
//+kubebuilder:rbac:groups=rbac.authorization.k8s.io/v1,resources=rolebindings,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=rbac.authorization.k8s.io/v1,resources=rolebindings/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=rbac.authorization.k8s.io/v1,resources=rolebindings/finalizers,verbs=update
//+kubebuilder:rbac:groups=rbac.authorization.k8s.io/v1,resources=clusterrolebindings,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=rbac.authorization.k8s.io/v1,resources=clusterrolebindings/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=rbac.authorization.k8s.io/v1,resources=clusterrolebindings/finalizers,verbs=update
//+kubebuilder:rbac:groups=*,resources=serviceaccounts,verbs=get;list;watch;create;update;patch;delete
//+kubebuilder:rbac:groups=*,resources=serviceaccounts/status,verbs=get;update;patch
//+kubebuilder:rbac:groups=*,resources=serviceaccounts/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.
// TODO(user): Modify the Reconcile function to compare the state specified by
// the ZUser object against the actual cluster state, and then
// perform operations to make the cluster state reflect the state specified by
// the user.
//
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/controller-runtime@v0.10.0/pkg/reconcile
func (r *ZUserReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
_ = log.FromContext(ctx)
// TODO(user): your logic here
zuser := zeldaiov1alpha1.ZUser{}
err := r.Get(ctx, req.NamespacedName, &zuser)
if err != nil {
return ctrl.Result{}, err
}
if zuser.DeletionTimestamp == nil || zuser.DeletionTimestamp.IsZero() {
err = r.Process(ctx, &zuser)
return ctrl.Result{}, err
}
return ctrl.Result{}, nil
}
// SetupWithManager sets up the controller with the Manager.
func (r *ZUserReconciler) SetupWithManager(mgr ctrl.Manager) error {
return ctrl.NewControllerManagedBy(mgr).
For(&zeldaiov1alpha1.ZUser{}).
Watches(&corev1.ServiceAccount{},
&watchers.ZUserWatcher{
Client: mgr.GetClient(),
}).
Complete(r)
}
// 处理user变更。
// user会保持对应的service accountrole binding cluster role binding 与其一致
// user会定期清理token
func (r *ZUserReconciler) Process(ctx context.Context, zuser *zeldaiov1alpha1.ZUser) error {
zgroup := zeldaiov1alpha1.ZGroup{}
err := r.Get(ctx, zuser.NamespacedNameGroup(), &zgroup) //获取不到组则无法为账号绑定role
if err != nil {
return err
}
changed, _ := zuser.IsSpecChanged()
err = r.ProcessServiceAccount(ctx, &zgroup, zuser, changed)
if err != nil { //sa处理失败则不用处理角色绑定
return err
}
err = r.ProcessRoleBinding(ctx, zuser, changed)
if err != nil {
//打印日志
}
err = r.ProcessClusterRoleBinding(ctx, zuser, changed)
return err
}
// 处理service account
func (r *ZUserReconciler) ProcessServiceAccount(ctx context.Context, zgroup *zeldaiov1alpha1.ZGroup, zuser *zeldaiov1alpha1.ZUser, changed bool) error {
sa := &corev1.ServiceAccount{}
err := r.Get(ctx, zuser.NamespacedNameServiceAccount(), sa)
if err != nil || changed {
sa = zuser.ServiceAccount(zgroup.Spec.Secrets)
}
if err != nil { //没有获取到,需要创建
err = r.Create(ctx, sa, &client.CreateOptions{})
return err
}
if changed {
err = r.Update(ctx, sa, &client.UpdateOptions{})
return err
}
//zuser 无变化,这里更新状态
for _, secret := range sa.Secrets {
if strings.Contains(secret.Name, fmt.Sprintf("%s-%s", sa.Name, "token")) {
zuser.Status.Token = secret.Name
err = r.Status().Update(ctx, zuser)
return err
}
}
return nil
}
// 处理rolebinding
func (r *ZUserReconciler) ProcessRoleBinding(ctx context.Context, zuser *zeldaiov1alpha1.ZUser, changed bool) error {
roleBinding := &rbacv1.RoleBinding{}
err := r.Get(ctx, zuser.NamespacedNameRoleBinding(), roleBinding)
if err != nil || changed {
roleBinding = zuser.RoleBinding()
}
if err != nil { //没有获取到,需要创建
err = r.Create(ctx, roleBinding, &client.CreateOptions{})
return err
}
if changed {
err = r.Update(ctx, roleBinding, &client.UpdateOptions{})
return err
}
return nil
}
// 处理cluster rolebinding
func (r *ZUserReconciler) ProcessClusterRoleBinding(ctx context.Context, zuser *zeldaiov1alpha1.ZUser, changed bool) error {
roleBinding := &rbacv1.ClusterRoleBinding{}
err := r.Get(ctx, zuser.NamespacedNameClusterRoleBinding(), roleBinding)
if err != nil || changed {
roleBinding = zuser.ClusterRoleBinding()
}
if err != nil { //没有获取到,需要创建
err = r.Create(ctx, roleBinding, &client.CreateOptions{})
return err
}
if changed {
err = r.Update(ctx, roleBinding, &client.UpdateOptions{})
return err
}
return nil
}