123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990 |
- /*
- Copyright 2023.
- 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"
- "github.com/iwanhae/nodb/internal/templates"
- "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"
- databasev1 "github.com/iwanhae/nodb/api/v1"
- corev1 "k8s.io/api/core/v1"
- )
- // PostgreSQLReconciler reconciles a PostgreSQL object
- type PostgreSQLServiceReconciler struct {
- client.Client
- Scheme *runtime.Scheme
- }
- //+kubebuilder:rbac:groups="",resources=services,verbs=watch;get
- //+kubebuilder:rbac:groups=database.iwanhae.kr,resources=postgresqls/status,verbs=get;update;patch
- func (r *PostgreSQLServiceReconciler) Reconcile(ctx context.Context, req ctrl.Request) (result ctrl.Result, err error) {
- logger := log.FromContext(ctx)
- // Find PostgreSQL
- obj := databasev1.PostgreSQL{}
- if err := r.Get(ctx, req.NamespacedName, &obj); err != nil {
- if client.IgnoreNotFound(err) == nil {
- return ctrl.Result{}, nil
- }
- logger.Error(err, "resource not found")
- return ctrl.Result{}, err
- }
- original := obj.DeepCopy()
- // will update Status anyway
- defer func() {
- err = r.Status().Patch(ctx, &obj, client.MergeFrom(original))
- if err != nil {
- logger.Error(err, "failed to update status")
- }
- }()
- // Find Svc
- svc := corev1.Service{}
- if err := r.Get(ctx, req.NamespacedName, &svc); err != nil {
- if client.IgnoreNotFound(err) == nil {
- // Have PostgreSQL, but no pod
- obj.Status.Status = databasev1.Status_Error
- return ctrl.Result{}, nil
- }
- logger.Error(err, "resource not found")
- return ctrl.Result{}, err
- }
- if svc.Labels[templates.LabelKeyType] != templates.LabelValuePostgreSQL {
- // This svc is not for PostgreSQL
- return ctrl.Result{}, nil
- }
- logger.Info("reconcile", "namespace", svc.Namespace, "name", svc.Name)
- obj.Status.ListenOn.Port = svc.Spec.Ports[0].NodePort
- return ctrl.Result{}, nil
- }
- // SetupWithManager sets up the controller with the Manager.
- func (r *PostgreSQLServiceReconciler) SetupWithManager(mgr ctrl.Manager) error {
- return ctrl.NewControllerManagedBy(mgr).
- For(&corev1.Service{}).
- Complete(r)
- }
|