Skip to content

Commit

Permalink
Cluster reconciler
Browse files Browse the repository at this point in the history
Signed-off-by: PrimalPimmy <[email protected]>
  • Loading branch information
PrimalPimmy committed Jun 20, 2024
1 parent efe3e1c commit a1054da
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 143 deletions.
178 changes: 35 additions & 143 deletions controllers/pkg/reconcilers/spire-bootstrap/reconciler.go
Original file line number Diff line number Diff line change
@@ -1,24 +1,29 @@
/*
Copyright 2023 The Nephio Authors.
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 bootstrapsecret

import (
"context"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"math/big"
"time"

"github.com/nephio-project/nephio/controllers/pkg/cluster"

reconcilerinterface "github.com/nephio-project/nephio/controllers/pkg/reconcilers/reconciler-interface"
"github.com/nephio-project/nephio/controllers/pkg/resource"
"github.com/pkg/errors"
corev1 "k8s.io/api/core/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"

"sigs.k8s.io/cluster-api/api/v1beta1"
capiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/event"
Expand All @@ -27,17 +32,9 @@ import (
)

func init() {
reconcilerinterface.Register("spire-bootstrapsecrets", &reconciler{})
reconcilerinterface.Register("bootstrap-spire", &reconciler{})
}

const (
clusterNameKey = "nephio.org/cluster-name"
remoteNamespaceKey = "nephio.org/remote-namespace"
syncApp = "tobeinstalledonremotecluster"
bootstrapApp = "bootstrap"
)

//+kubebuilder:rbac:groups="*",resources=secrets,verbs=get;list;watch
//+kubebuilder:rbac:groups=cluster.x-k8s.io,resources=clusters,verbs=get;list;watch
//+kubebuilder:rbac:groups=cluster.x-k8s.io,resources=clusters/status,verbs=get

Expand All @@ -46,139 +43,34 @@ func (r *reconciler) SetupWithManager(ctx context.Context, mgr ctrl.Manager, c a
r.Client = mgr.GetClient()

return nil, ctrl.NewControllerManagedBy(mgr).
Named("BootstrapSecretController").
For(&corev1.Secret{}).
Named("BootstrapSpireController").
For(&capiv1beta1.Cluster{}).
Complete(r)
}

type reconciler struct {
client.Client
}

// r.List --> gets us cluster name list

func (r *reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
log := log.FromContext(ctx)

cr := &corev1.Secret{}
if err := r.Get(ctx, req.NamespacedName, cr); err != nil {
if resource.IgnoreNotFound(err) != nil {
msg := "cannot get resource"
log.Error(err, msg)
return ctrl.Result{}, errors.Wrap(resource.IgnoreNotFound(err), msg)
}
return reconcile.Result{}, nil
}

if resource.WasDeleted(cr) {
return reconcile.Result{}, nil
}

if cr.GetAnnotations()[nephioAppKey] == syncApp &&
cr.GetAnnotations()[clusterNameKey] != "" &&
cr.GetAnnotations()[clusterNameKey] != "mgmt" {
log.Info("reconcile secret")

clusterName := cr.GetAnnotations()[clusterNameKey]
clusterNames := strings.Split(clusterName, ",")

for _, clusterName := range clusterNames {
secrets := &corev1.SecretList{}
if err := r.List(ctx, secrets); err != nil {
msg := "cannot list secrets"
log.Error(err, msg)
return ctrl.Result{}, errors.Wrap(err, msg)
}
found := false
for _, secret := range secrets.Items {
if strings.Contains(secret.GetName(), clusterName) {
secret := secret
clusterClient, ok := cluster.Cluster{Client: r.Client}.GetClusterClient(&secret)
if ok {
found = true
clusterClient, ready, err := clusterClient.GetClusterClient(ctx)
if err != nil {
msg := "cannot get clusterClient"
log.Error(err, msg)
return ctrl.Result{RequeueAfter: 30 * time.Second}, errors.Wrap(err, msg)
}
if !ready {
log.Info("cluster not ready")
return ctrl.Result{RequeueAfter: 10 * time.Second}, nil
}

remoteNamespace := cr.Namespace
if rns, ok := cr.GetAnnotations()[remoteNamespaceKey]; ok {
remoteNamespace = rns
}
ns := &corev1.Namespace{}
if err = clusterClient.Get(ctx, types.NamespacedName{Name: remoteNamespace}, ns); err != nil {
if resource.IgnoreNotFound(err) != nil {
msg := fmt.Sprintf("cannot get namespace: %s", remoteNamespace)
log.Error(err, msg)
return ctrl.Result{RequeueAfter: 30 * time.Second}, errors.Wrap(err, msg)
}
msg := fmt.Sprintf("namespace: %s, does not exist, retry...", remoteNamespace)
log.Info(msg)
return ctrl.Result{RequeueAfter: 10 * time.Second}, nil
}

bootstrapCrt, err := generateBootstrapCrt()
if err != nil {
msg := "cannot generate bootstrap.crt"
log.Error(err, msg)
return ctrl.Result{}, errors.Wrap(err, msg)
}

newSecret := &corev1.Secret{
ObjectMeta: cr.ObjectMeta,
Data: map[string][]byte{
"bootstrap.crt": bootstrapCrt,
},
}
newSecret.Namespace = remoteNamespace
newSecret.ResourceVersion = ""
newSecret.UID = ""

if err := clusterClient.Apply(ctx, newSecret); err != nil {
msg := fmt.Sprintf("cannot apply secret to cluster %s", clusterName)
log.Error(err, msg)
return ctrl.Result{}, errors.Wrap(err, msg)
}
}
}
if found {
break
}
}
if !found {
log.Info("cluster client not found, retry...")
return ctrl.Result{RequeueAfter: 10 * time.Second}, nil
}
}
}
return ctrl.Result{}, nil
}

func generateBootstrapCrt() ([]byte, error) {
priv, err := rsa.GenerateKey(rand.Reader, 2048)
// Fetch the Cluster instance
cluster := &v1beta1.ClusterClass{}
err := r.Get(ctx, req.NamespacedName, cluster)
if err != nil {
return nil, err
if client.IgnoreNotFound(err) != nil {
log.Error(err, "unable to fetch Cluster")
}
return reconcile.Result{}, client.IgnoreNotFound(err)
}

template := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{
Organization: []string{"Nephio"},
},
NotBefore: time.Now(),
NotAfter: time.Now().Add(365 * 24 * time.Hour),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
}
// Add your reconciliation logic here
log.Info("Reconciling Cluster", "cluster", cluster.Name)

derBytes, err := x509.CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv)
if err != nil {
return nil, err
}
// Example: Update the status if necessary

certOut := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: derBytes})
return certOut, nil
return reconcile.Result{}, nil
}
9 changes: 9 additions & 0 deletions operators/nephio-controller-manager/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import (

"k8s.io/apimachinery/pkg/runtime"
clientgoscheme "k8s.io/client-go/kubernetes/scheme"
capiv1beta1 "sigs.k8s.io/cluster-api/api/v1beta1"
ctrl "sigs.k8s.io/controller-runtime"

//+kubebuilder:scaffold:imports
Expand All @@ -56,6 +57,7 @@ import (

//_ "github.com/nephio-project/nephio/controllers/pkg/reconcilers/ipam-specializer"
_ "github.com/nephio-project/nephio/controllers/pkg/reconcilers/repository"
_ "github.com/nephio-project/nephio/controllers/pkg/reconcilers/spire-bootstrap"
_ "github.com/nephio-project/nephio/controllers/pkg/reconcilers/token"
//_ "github.com/nephio-project/nephio/controllers/pkg/reconcilers/vlan-specializer"
)
Expand Down Expand Up @@ -108,6 +110,13 @@ func main() {
os.Exit(1)
}

err = capiv1beta1.AddToScheme(scheme)
if err != nil {
setupLog.Error(err, "cannot initializer schema with Cluster API(s)")
// klog.Errorf("error initializing scheme with Porch APIs: %s", err.Error())
os.Exit(1)
}

managerOptions := ctrl.Options{
Scheme: scheme,
MetricsBindAddress: metricsAddr,
Expand Down

0 comments on commit a1054da

Please sign in to comment.