Skip to content

Commit

Permalink
Replace agent's logger with logr.Logger
Browse files Browse the repository at this point in the history
  • Loading branch information
Mario Manno committed Oct 23, 2023
1 parent 2a5ab4d commit 2a60f2a
Show file tree
Hide file tree
Showing 8 changed files with 84 additions and 46 deletions.
9 changes: 7 additions & 2 deletions internal/cmd/agent/controller/bundledeployment_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,8 @@ type BundleDeploymentReconciler struct {
// For more details, check Reconcile and its Result here:
// - https://pkg.go.dev/sigs.k8s.io/[email protected]/pkg/reconcile
func (r *BundleDeploymentReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Result, error) {
_ = log.FromContext(ctx).WithName("bundledeployment")
logger := log.FromContext(ctx).WithName("bundledeployment")
ctx = log.IntoContext(ctx, logger)

// get latest BundleDeployment from cluster
bd := &fleetv1.BundleDeployment{}
Expand All @@ -73,13 +74,15 @@ func (r *BundleDeploymentReconciler) Reconcile(ctx context.Context, req ctrl.Req
var updateErr error
bd, updateErr = updateCondition(ctx, r.Client, bd, &status, err, condition.Cond(fleetv1.BundleDeploymentConditionDeployed))
if err != nil {
logger.V(1).Error(err, "Failed to deploy bundle", "status", status)
return ctrl.Result{
// Defaults
Requeue: false,
RequeueAfter: 0,
}, err
}
if updateErr != nil {
logger.V(1).Error(updateErr, "Failed to update bundledeployment status", "step", "deploy", "status", status)
return ctrl.Result{}, updateErr
}

Expand All @@ -95,11 +98,13 @@ func (r *BundleDeploymentReconciler) Reconcile(ctx context.Context, req ctrl.Req
return ctrl.Result{}, err
}
if updateErr != nil {
logger.V(1).Error(updateErr, "Failed to update bundledeployment status", "step", "monitor", "status", status)
return ctrl.Result{}, updateErr
}

_, err = r.DriftDetect.Refresh(req.String(), bd)
_, err = r.DriftDetect.Refresh(logger, req.String(), bd)
if err != nil {
logger.V(1).Error(err, "Failed to refresh drift detection", "step", "drift")
return ctrl.Result{}, err
}

Expand Down
14 changes: 8 additions & 6 deletions internal/cmd/agent/deployer/cleanup/cleanup.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"sync"
"time"

"github.com/sirupsen/logrus"
"github.com/go-logr/logr"

"github.com/rancher/fleet/internal/helmdeployer"
fleet "github.com/rancher/fleet/pkg/apis/fleet.cattle.io/v1alpha1"
Expand All @@ -17,6 +17,7 @@ import (
"k8s.io/apimachinery/pkg/types"
"k8s.io/apimachinery/pkg/util/wait"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
)

type Cleanup struct {
Expand Down Expand Up @@ -48,9 +49,10 @@ func (c *Cleanup) CleanupReleases(ctx context.Context, key string, bd *fleet.Bun
}

func (c *Cleanup) garbageCollect(ctx context.Context) {
logger := log.FromContext(ctx).WithName("garbageCollect")
for {
if err := c.cleanup(ctx); err != nil {
logrus.Errorf("failed to cleanup orphaned releases: %v", err)
if err := c.cleanup(ctx, logger); err != nil {
logger.Error(err, "failed to cleanup orphaned releases")
}
select {
case <-ctx.Done():
Expand All @@ -60,7 +62,7 @@ func (c *Cleanup) garbageCollect(ctx context.Context) {
}
}

func (c *Cleanup) cleanup(ctx context.Context) error {
func (c *Cleanup) cleanup(ctx context.Context, logger logr.Logger) error {
deployed, err := c.helmDeployer.ListDeployments()
if err != nil {
return err
Expand All @@ -71,7 +73,7 @@ func (c *Cleanup) cleanup(ctx context.Context) error {
err := c.client.Get(ctx, types.NamespacedName{Namespace: c.fleetNamespace, Name: deployed.BundleID}, bundleDeployment)
if apierror.IsNotFound(err) {
// found a helm secret, but no bundle deployment, so uninstall the release
logrus.Infof("Deleting orphan bundle ID %s, release %s", deployed.BundleID, deployed.ReleaseName)
logger.Info("Deleting orphan bundle ID, helm uninstall", "bundleID", deployed.BundleID, "release", deployed.ReleaseName)
if err := c.helmDeployer.Delete(ctx, deployed.BundleID, deployed.ReleaseName); err != nil {
return err
}
Expand All @@ -84,7 +86,7 @@ func (c *Cleanup) cleanup(ctx context.Context) error {
key := releaseKey(c.defaultNamespace, bundleDeployment)
if key != deployed.ReleaseName {
// found helm secret and bundle deployment for BundleID, but release name doesn't match, so delete the release
logrus.Infof("Deleting unknown bundle ID %s, release %s, expecting release %s", deployed.BundleID, deployed.ReleaseName, key)
logger.Info("Deleting unknown bundle ID, helm uninstall", "bundleID", deployed.BundleID, "release", deployed.ReleaseName, "expectedRelease", key)
if err := c.helmDeployer.Delete(ctx, deployed.BundleID, deployed.ReleaseName); err != nil {
return err
}
Expand Down
19 changes: 10 additions & 9 deletions internal/cmd/agent/deployer/deployer.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@ import (
"regexp"
"strings"

"github.com/sirupsen/logrus"

"github.com/rancher/fleet/internal/helmdeployer"
"github.com/rancher/fleet/internal/manifest"
fleet "github.com/rancher/fleet/pkg/apis/fleet.cattle.io/v1alpha1"
Expand All @@ -19,38 +17,41 @@ import (
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
)

type Deployer struct {
client client.Client
upstreamClient client.Reader
lookup *manifest.Lookup
deployer *helmdeployer.Helm
helm *helmdeployer.Helm
}

func NewDeployer(localClient client.Client, upstreamClient client.Reader, lookup *manifest.Lookup, deployer *helmdeployer.Helm) *Deployer {
return &Deployer{
client: localClient,
upstreamClient: upstreamClient,
lookup: lookup,
deployer: deployer,
helm: deployer,
}
}

func (d *Deployer) DeployBundle(ctx context.Context, bd *fleet.BundleDeployment) (fleet.BundleDeploymentStatus, error) {
logger := log.FromContext(ctx).WithName("DeployBundle").WithValues("deploymentID", bd.Spec.DeploymentID, "appliedDeploymentID", bd.Status.AppliedDeploymentID)

status := *bd.Status.DeepCopy()
if bd.Spec.Paused {
// nothing to do
logrus.Debugf("Bundle %s/%s is paused", bd.Namespace, bd.Name)
logger.V(1).Info("Bundle paused")
return status, nil
}

if err := d.checkDependency(ctx, bd); err != nil {
logrus.Debugf("Bundle %s/%s has a dependency that is not ready: %v", bd.Namespace, bd.Name, err)
logger.V(1).Info("Bundle has a dependency that is not ready: %v", err)
return status, err
}

logrus.Infof("Deploying bundle %s/%s", bd.Namespace, bd.Name)
logger.Info("Deploying bundle")
release, err := d.helmdeploy(ctx, bd)
if err != nil {
// When an error from DeployBundle is returned it causes DeployBundle
Expand Down Expand Up @@ -88,7 +89,7 @@ func (d *Deployer) DeployBundle(ctx context.Context, bd *fleet.BundleDeployment)
// This loads the manifest and the contents from the upstream cluster.
func (d *Deployer) helmdeploy(ctx context.Context, bd *fleet.BundleDeployment) (string, error) {
if bd.Spec.DeploymentID == bd.Status.AppliedDeploymentID {
if ok, err := d.deployer.EnsureInstalled(bd.Name, bd.Status.Release); err != nil {
if ok, err := d.helm.EnsureInstalled(bd.Name, bd.Status.Release); err != nil {
return "", err
} else if ok {
return bd.Status.Release, nil
Expand All @@ -101,7 +102,7 @@ func (d *Deployer) helmdeploy(ctx context.Context, bd *fleet.BundleDeployment) (
}

manifest.Commit = bd.Labels["fleet.cattle.io/commit"]
resource, err := d.deployer.Deploy(ctx, bd.Name, manifest, bd.Spec.Options)
resource, err := d.helm.Deploy(ctx, bd.Name, manifest, bd.Spec.Options)
if err != nil {
return "", err
}
Expand Down
13 changes: 9 additions & 4 deletions internal/cmd/agent/deployer/driftdetect/driftdetect.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
package driftdetect

import (
"github.com/go-logr/logr"
"github.com/rancher/fleet/internal/cmd/agent/deployer/plan"
"github.com/rancher/fleet/internal/cmd/agent/trigger"
"github.com/rancher/fleet/internal/helmdeployer"
fleet "github.com/rancher/fleet/pkg/apis/fleet.cattle.io/v1alpha1"
"github.com/sirupsen/logrus"

"github.com/rancher/wrangler/v2/pkg/apply"

Expand Down Expand Up @@ -42,12 +42,13 @@ func New(
}
}

func (m *DriftDetect) Refresh(key string, bd *fleet.BundleDeployment) (*fleet.BundleDeployment, error) {
func (m *DriftDetect) Refresh(logger logr.Logger, key string, bd *fleet.BundleDeployment) (*fleet.BundleDeployment, error) {
logger = logger.WithName("DriftDetect")
if bd == nil || bd.Spec.Paused {
return bd, m.trigger.Clear(key)
}

logrus.Debugf("Triggering for bundledeployment '%s'", key)
logger.V(1).Info("Refreshing drift detection")

resources, err := m.allResources(bd)
if err != nil {
Expand All @@ -58,11 +59,15 @@ func (m *DriftDetect) Refresh(key string, bd *fleet.BundleDeployment) (*fleet.Bu
return bd, nil
}

logrus.Debugf("Adding OnChange for bundledeployment's '%s' resource list", key)
logger.V(1).Info("Adding OnChange for bundledeployment's resource list")
return bd, m.trigger.OnChange(key, resources.DefaultNamespace, func() {
// enqueue bundledeployment if any resource changes
//h.bdController.EnqueueAfter(bd.Namespace, bd.Name, 0)
// TODO(manno): we can't enqueue directly, update status instead
// TODO
// TODO
// TODO
// TODO
}, resources.Objects...)
}

Expand Down
11 changes: 6 additions & 5 deletions internal/cmd/agent/deployer/monitor/monitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,6 @@ import (
"fmt"
"strings"

"github.com/sirupsen/logrus"

"github.com/rancher/fleet/internal/helmdeployer"
fleet "github.com/rancher/fleet/pkg/apis/fleet.cattle.io/v1alpha1"

Expand All @@ -20,6 +18,7 @@ import (
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/client-go/dynamic"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/log"
)

type Monitor struct {
Expand All @@ -39,6 +38,7 @@ type Monitor struct {
}

func (ma *Monitor) MonitorBundle(ctx context.Context, bd *fleet.BundleDeployment) (fleet.BundleDeploymentStatus, error) {
logger := log.FromContext(ctx).WithName("MonitorBundle")
status := *bd.Status.DeepCopy()
if bd.Spec.DeploymentID != status.AppliedDeploymentID {
return status, nil
Expand Down Expand Up @@ -77,7 +77,7 @@ func (ma *Monitor) MonitorBundle(ctx context.Context, bd *fleet.BundleDeployment
// TODO(manno): this should be a return value or a status update ...but how to delay?
//h.bdController.EnqueueAfter(bd.Namespace, bd.Name, durations.MonitorBundleDelay)
if shouldRedeploy(bd) {
logrus.Infof("Redeploying %s", bd.Name)
logger.Info("Redeploying")
status.AppliedDeploymentID = ""
if isAgent(bd) {
if err := ma.cleanupOldAgent(ctx, status.ModifiedStatus); err != nil {
Expand All @@ -89,7 +89,7 @@ func (ma *Monitor) MonitorBundle(ctx context.Context, bd *fleet.BundleDeployment

status.SyncGeneration = &bd.Spec.Options.ForceSyncGeneration
if readyError != nil {
logrus.Errorf("bundle %s: %v", bd.Name, readyError)
logger.Error(readyError, "Status not ready")
}

removePrivateFields(&status)
Expand Down Expand Up @@ -123,6 +123,7 @@ func isAgent(bd *fleet.BundleDeployment) bool {
}

func (ma *Monitor) cleanupOldAgent(ctx context.Context, modifiedStatuses []fleet.ModifiedStatus) error {
logger := log.FromContext(ctx).WithName("cleanupOldAgent")
var errs []error
for _, modified := range modifiedStatuses {
if modified.Delete {
Expand All @@ -133,7 +134,7 @@ func (ma *Monitor) cleanupOldAgent(ctx context.Context, modifiedStatuses []fleet
continue
}

logrus.Infof("Removing old agent resource %s/%s, %s", modified.Namespace, modified.Name, gvk)
logger.Info("Removing old agent resource", "namespace", modified.Namespace, "name", modified.Name, "gvk", gvk)
err = ma.LocalDynamicClient.Resource(mapping.Resource).Namespace(modified.Namespace).Delete(ctx, modified.Name, metav1.DeleteOptions{})
if err != nil {
errs = append(errs, fmt.Errorf("deleting %s/%s for %s for agent cleanup: %w", modified.Namespace, modified.Name, gvk, err))
Expand Down
10 changes: 6 additions & 4 deletions internal/cmd/agent/deployer/monitor/updatestatus.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ import (
"fmt"
"sort"

"github.com/go-logr/logr"
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"sigs.k8s.io/controller-runtime/pkg/log"

"github.com/rancher/fleet/internal/cmd/agent/deployer/plan"
"github.com/rancher/fleet/internal/helmdeployer"
Expand All @@ -25,6 +26,7 @@ import (
// updateBundleDeploymentStatus updates the status with information from the
// helm release history and an apply dry run.
func (m *Monitor) updateBundleDeploymentStatus(ctx context.Context, bd *fleet.BundleDeployment) error {
logger := log.FromContext(ctx).WithName("updateBundleDeploymentStatus")
resources, err := m.Deployer.Resources(bd.Name, bd.Status.Release)
if err != nil {
return err
Expand All @@ -49,7 +51,7 @@ func (m *Monitor) updateBundleDeploymentStatus(ctx context.Context, bd *fleet.Bu
return err
}

bd.Status.NonReadyStatus = nonReady(plan, bd.Spec.Options.IgnoreOptions)
bd.Status.NonReadyStatus = nonReady(logger, plan, bd.Spec.Options.IgnoreOptions)
bd.Status.ModifiedStatus = modified(plan, resourcesPreviousRelease)
bd.Status.Ready = false
bd.Status.NonModified = false
Expand Down Expand Up @@ -97,7 +99,7 @@ func (m *Monitor) updateBundleDeploymentStatus(ctx context.Context, bd *fleet.Bu
return nil
}

func nonReady(plan apply.Plan, ignoreOptions fleet.IgnoreOptions) (result []fleet.NonReadyStatus) {
func nonReady(logger logr.Logger, plan apply.Plan, ignoreOptions fleet.IgnoreOptions) (result []fleet.NonReadyStatus) {
defer func() {
sort.Slice(result, func(i, j int) bool {
return result[i].UID < result[j].UID
Expand All @@ -111,7 +113,7 @@ func nonReady(plan apply.Plan, ignoreOptions fleet.IgnoreOptions) (result []flee
if u, ok := obj.(*unstructured.Unstructured); ok {
if ignoreOptions.Conditions != nil {
if err := excludeIgnoredConditions(u, ignoreOptions); err != nil {
logrus.Errorf("failed to ignore conditions: %v", err)
logger.Error(err, "failed to ignore conditions")
}
}

Expand Down
11 changes: 11 additions & 0 deletions internal/cmd/controller/start.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,20 @@ import (

"github.com/rancher/wrangler/v2/pkg/kubeconfig"
"github.com/rancher/wrangler/v2/pkg/ratelimit"

ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/log"
"sigs.k8s.io/controller-runtime/pkg/log/zap"
)

func start(ctx context.Context, systemNamespace string, kubeconfigFile string, disableGitops bool, disableBootstrap bool) error {
// provide a logger in the context to be compatible with controller-runtime
zopts := zap.Options{
Development: true,
}
ctrl.SetLogger(zap.New(zap.UseFlagOptions(&zopts)))
ctx = log.IntoContext(ctx, ctrl.Log)

cfg := kubeconfig.GetNonInteractiveClientConfig(kubeconfigFile)
clientConfig, err := cfg.ClientConfig()
if err != nil {
Expand Down
Loading

0 comments on commit 2a60f2a

Please sign in to comment.