Skip to content

Commit

Permalink
improve codes
Browse files Browse the repository at this point in the history
Signed-off-by: Poor12 <shentiecheng@huawei.com>
  • Loading branch information
Poor12 committed May 26, 2022
1 parent 49de40a commit 7a8f82d
Show file tree
Hide file tree
Showing 16 changed files with 126 additions and 153 deletions.
8 changes: 4 additions & 4 deletions cmd/controller-manager/app/controllermanager.go
Original file line number Diff line number Diff line change
Expand Up @@ -427,15 +427,15 @@ func startFederatedResourceQuotaStatusController(ctx controllerscontext.Context)

func startHelmController(ctx controllerscontext.Context) (enabled bool, err error) {
helmReleaseWatcher := objectwatcher.NewHelmReleaseWatcher(ctx.Mgr.GetClient(), util.BuildClusterConfig)
helmController := &helm.HelmController{
helmController := &helm.Controller{
Client: ctx.Mgr.GetClient(),
EventRecorder: ctx.Mgr.GetEventRecorderFor(helm.HelmControllerName),
EventRecorder: ctx.Mgr.GetEventRecorderFor(helm.ControllerName),
HelmReleaseWatcher: helmReleaseWatcher,
PredicateFunc: helper.NewHelmReleasePredicate(ctx.Mgr),
RatelimiterOptions: ctx.Opts.RateLimiterOptions,
RequeueDependency: ctx.Opts.HelmControllerRequeueDependency,
NoCrossNamespaceRef: ctx.Opts.HelmControllerNoCrossNamespaceRefs,
HTTPRetry: ctx.Opts.HelmControllerHttpRetry,
HTTPRetry: ctx.Opts.HelmControllerHTTPRetry,
}
if err = helmController.SetupWithManager(ctx.Mgr); err != nil {
return false, err
Expand Down Expand Up @@ -522,7 +522,7 @@ func setupControllers(mgr controllerruntime.Manager, opts *options.Options, stop
ConcurrentWorkSyncs: opts.ConcurrentWorkSyncs,
RateLimiterOptions: opts.RateLimiterOpts,
HelmControllerRequeueDependency: opts.HelmControllerRequeueDependency,
HelmControllerHttpRetry: opts.HelmControllerHttpRetry,
HelmControllerHTTPRetry: opts.HelmControllerHTTPRetry,
HelmControllerNoCrossNamespaceRefs: opts.HelmControllerNoCrossNamespaceRefs,
},
StopChan: stopChan,
Expand Down
6 changes: 3 additions & 3 deletions cmd/controller-manager/app/options/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,8 +104,8 @@ type Options struct {
ConcurrentResourceTemplateSyncs int
// HelmControllerRequeueDependency is the interval at which failing dependencies are reevaluated for helm-controller.
HelmControllerRequeueDependency time.Duration
// HelmControllerHttpRetry is the maximum number of retries when failing to fetch artifacts over HTTP.
HelmControllerHttpRetry int
// HelmControllerHTTPRetry is the maximum number of retries when failing to fetch artifacts over HTTP.
HelmControllerHTTPRetry int
// HelmControllerNoCrossNamespaceRefs is the flag whether references between custom resources are allowed.
HelmControllerNoCrossNamespaceRefs bool
RateLimiterOpts ratelimiterflag.Options
Expand Down Expand Up @@ -173,7 +173,7 @@ func (o *Options) AddFlags(flags *pflag.FlagSet, allControllers, disabledByDefau
flags.IntVar(&o.ConcurrentResourceTemplateSyncs, "concurrent-resource-template-syncs", 5, "The number of resource templates that are allowed to sync concurrently.")

flags.DurationVar(&o.HelmControllerRequeueDependency, "helm-controller-requeue-dependency", 30*time.Second, "The interval at which failing dependencies are reevaluated.")
flags.IntVar(&o.HelmControllerHttpRetry, "helm-controller-http-retry", 9, "The maximum number of retries when failing to fetch artifacts over HTTP.")
flags.IntVar(&o.HelmControllerHTTPRetry, "helm-controller-http-retry", 9, "The maximum number of retries when failing to fetch artifacts over HTTP.")
flags.BoolVar(&o.HelmControllerNoCrossNamespaceRefs, "helm-controller-no-cross-namespace-refs", false, "When set to true, references between custom resources are allowed "+"only if the reference and the referee are in the same namespace.")
o.RateLimiterOpts.AddFlags(flags)
features.FeatureGate.AddFlag(flags)
Expand Down
1 change: 1 addition & 0 deletions hack/tools/swagger/lib/render.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ func RenderOpenAPISpec(cfg Config) (string, error) {
}

// Create Swagger Spec.
//nolint:staticcheck
spec, err := builder.BuildOpenAPISpec(genericServer.Handler.GoRestfulContainer.RegisteredWebServices(), serverConfig.OpenAPIConfig)
if err != nil {
klog.Fatal(err)
Expand Down
1 change: 1 addition & 0 deletions pkg/controllers/binding/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ var workPredicateFn = builder.WithPredicates(predicate.Funcs{
})

// ensureWork ensure Work to be created or updated.
//nolint:gocyclo
func ensureWork(
c client.Client, resourceInterpreter resourceinterpreter.ResourceInterpreter, workload *unstructured.Unstructured,
overrideManager overridemanager.OverrideManager, binding metav1.Object, scope apiextensionsv1.ResourceScope,
Expand Down
4 changes: 2 additions & 2 deletions pkg/controllers/context/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ type Options struct {
ConcurrentWorkSyncs int
// HelmControllerRequeueDependency is the interval at which failing dependencies are reevaluated for helm-controller.
HelmControllerRequeueDependency time.Duration
// HelmControllerHttpRetry is the maximum number of retries when failing to fetch artifacts over HTTP.
HelmControllerHttpRetry int
// HelmControllerHTTPRetry is the maximum number of retries when failing to fetch artifacts over HTTP.
HelmControllerHTTPRetry int
// HelmControllerNoCrossNamespaceRefs is the flag whether references between custom resources are allowed.
HelmControllerNoCrossNamespaceRefs bool
// RateLimiterOptions contains the options for rate limiter.
Expand Down
33 changes: 17 additions & 16 deletions pkg/controllers/helm/helm_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,14 +42,14 @@ import (
)

const (
// HelmControllerName and SourceControllerName is the controller name that will be used when reporting events.
HelmControllerName = "helm-controller"
// ControllerName is the controller name that will be used when reporting events.
ControllerName = "helm-controller"

Ready = "Ready"
ready = "ready"
)

// HelmController is to sync Work with helm release.
type HelmController struct {
// Controller is to sync Work with helm release.
type Controller struct {
client.Client
EventRecorder record.EventRecorder
HelmReleaseWatcher objectwatcher.HelmReleaseWatcher
Expand All @@ -66,7 +66,7 @@ type HelmController struct {
// Reconcile performs a full reconciliation for the object referred to by the Request.
// The Controller will requeue the Request to be processed again if an error is non-nil or
// Result.Requeue is true, otherwise upon completion it will remove the work from the queue.
func (h *HelmController) Reconcile(ctx context.Context, req controllerruntime.Request) (controllerruntime.Result, error) {
func (h *Controller) Reconcile(ctx context.Context, req controllerruntime.Request) (controllerruntime.Result, error) {
klog.V(4).Infof("Reconciling Work %s", req.NamespacedName.String())

work := &workv1alpha1.Work{}
Expand Down Expand Up @@ -115,7 +115,7 @@ func (h *HelmController) Reconcile(ctx context.Context, req controllerruntime.Re
}

// SetupWithManager creates a controller and register to controller manager.
func (h *HelmController) SetupWithManager(mgr controllerruntime.Manager) error {
func (h *Controller) SetupWithManager(mgr controllerruntime.Manager) error {
// Index the work by the HelmChart references they point at
if err := mgr.GetFieldIndexer().IndexField(context.TODO(), &workv1alpha1.Work{}, v2.SourceIndexKey,
func(o client.Object) []string {
Expand Down Expand Up @@ -165,7 +165,8 @@ func (h *HelmController) SetupWithManager(mgr controllerruntime.Manager) error {
Complete(h)
}

func (h *HelmController) requestsForHelmChartChange(o client.Object) []reconcile.Request {
//nolint:gosec
func (h *Controller) requestsForHelmChartChange(o client.Object) []reconcile.Request {
hc, ok := o.(*sourcev1.HelmChart)
if !ok {
panic(fmt.Sprintf("Expected a HelmChart, got %T", o))
Expand Down Expand Up @@ -205,7 +206,7 @@ func (h *HelmController) requestsForHelmChartChange(o client.Object) []reconcile
return reqs
}

func (h *HelmController) syncWork(ctx context.Context, clusterName string, work *workv1alpha1.Work) (controllerruntime.Result, error) {
func (h *Controller) syncWork(ctx context.Context, clusterName string, work *workv1alpha1.Work) (controllerruntime.Result, error) {
result, err := h.syncToClusters(ctx, clusterName, work)
if err != nil {
msg := fmt.Sprintf("Failed to sync work(%s) to cluster(%s): %v", work.Name, clusterName, err)
Expand All @@ -220,7 +221,7 @@ func (h *HelmController) syncWork(ctx context.Context, clusterName string, work
}

// syncToClusters ensures that the state of the given object is synchronized to member clusters.
func (h *HelmController) syncToClusters(ctx context.Context, clusterName string, work *workv1alpha1.Work) (controllerruntime.Result, error) {
func (h *Controller) syncToClusters(ctx context.Context, clusterName string, work *workv1alpha1.Work) (controllerruntime.Result, error) {
var errs []error
var msg string
isReady := false
Expand Down Expand Up @@ -271,7 +272,7 @@ func (h *HelmController) syncToClusters(ctx context.Context, clusterName string,
continue
}

if meta.IsStatusConditionTrue(hr.Status.Conditions, Ready) {
if meta.IsStatusConditionTrue(hr.Status.Conditions, ready) {
isReady = true
msg = fmt.Sprintf("Successfully synced helmrelease(%v/%v) to cluster %s", hr.GetNamespace(), hr.GetName(), clusterName)
klog.V(4).Info(msg)
Expand Down Expand Up @@ -301,7 +302,7 @@ func (h *HelmController) syncToClusters(ctx context.Context, clusterName string,
}

// removeFinalizer remove finalizer from the given Work
func (h *HelmController) removeFinalizer(work *workv1alpha1.Work) (controllerruntime.Result, error) {
func (h *Controller) removeFinalizer(work *workv1alpha1.Work) (controllerruntime.Result, error) {
if !controllerutil.ContainsFinalizer(work, util.HelmControllerFinalizer) {
return controllerruntime.Result{}, nil
}
Expand All @@ -315,7 +316,7 @@ func (h *HelmController) removeFinalizer(work *workv1alpha1.Work) (controllerrun
}

// updateAppliedCondition update the Applied condition for the given Work
func (h *HelmController) updateAppliedCondition(work *workv1alpha1.Work, status metav1.ConditionStatus, reason, message string) error {
func (h *Controller) updateAppliedCondition(work *workv1alpha1.Work, status metav1.ConditionStatus, reason, message string) error {
newWorkAppliedCondition := metav1.Condition{
Type: workv1alpha1.WorkApplied,
Status: status,
Expand All @@ -341,7 +342,7 @@ func (h *HelmController) updateAppliedCondition(work *workv1alpha1.Work, status
})
}

func (h *HelmController) patchManifestStatus(work *workv1alpha1.Work, hr v2.HelmRelease) error {
func (h *Controller) patchManifestStatus(work *workv1alpha1.Work, hr v2.HelmRelease) error {
status, err := helper.BuildStatusRawExtension(hr.Status)
if err != nil {
klog.Errorf("Failed to convert status from helmrelease, err is: %v", err)
Expand Down Expand Up @@ -382,7 +383,7 @@ func (h *HelmController) patchManifestStatus(work *workv1alpha1.Work, hr v2.Helm
})
}

func (h *HelmController) tryDeleteWorkload(ctx context.Context, clusterName string, work *workv1alpha1.Work) error {
func (h *Controller) tryDeleteWorkload(ctx context.Context, clusterName string, work *workv1alpha1.Work) error {
for i, manifest := range work.Spec.Workload.Manifests {
workload := &unstructured.Unstructured{}
err := workload.UnmarshalJSON(manifest.Raw)
Expand Down Expand Up @@ -421,7 +422,7 @@ func (h *HelmController) tryDeleteWorkload(ctx context.Context, clusterName stri
return nil
}

func (h *HelmController) mergeStatus(statuses []workv1alpha1.ManifestStatus, newStatus workv1alpha1.ManifestStatus) []workv1alpha1.ManifestStatus {
func (h *Controller) mergeStatus(statuses []workv1alpha1.ManifestStatus, newStatus workv1alpha1.ManifestStatus) []workv1alpha1.ManifestStatus {
// For now, we only have at most one manifest in Work, so just override current 'statuses'.
return []workv1alpha1.ManifestStatus{newStatus}
}
41 changes: 12 additions & 29 deletions pkg/controllers/helm/helm_controller_chart.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ package helm

import (
"context"
"crypto/sha1"
"crypto/sha256"
"fmt"
"io"
Expand Down Expand Up @@ -47,7 +46,7 @@ import (
v2 "github.com/fluxcd/helm-controller/api/v2beta1"
)

func (h *HelmController) reconcileChart(ctx context.Context, hr *v2.HelmRelease) (*sourcev1.HelmChart, error) {
func (h *Controller) reconcileChart(ctx context.Context, hr *v2.HelmRelease) (*sourcev1.HelmChart, error) {
chartName := types.NamespacedName{
Namespace: hr.Spec.Chart.GetNamespace(hr.Namespace),
Name: hr.GetHelmChartName(),
Expand Down Expand Up @@ -93,22 +92,10 @@ func (h *HelmController) reconcileChart(ctx context.Context, hr *v2.HelmRelease)
return &helmChart, nil
}

// getHelmChart retrieves the v1beta2.HelmChart for the given
// v2beta1.HelmRelease using the name that is advertised in the status
// object. It returns the v1beta2.HelmChart, or an error.
func (h *HelmController) getHelmChart(ctx context.Context, hr *v2.HelmRelease) (*sourcev1.HelmChart, error) {
namespace, name := hr.Status.GetHelmChart()
hc := &sourcev1.HelmChart{}
if err := h.Client.Get(ctx, types.NamespacedName{Namespace: namespace, Name: name}, hc); err != nil {
return nil, err
}
return hc, nil
}

// loadHelmChart attempts to download the artifact from the provided source,
// loads it into a chart.Chart, and removes the downloaded artifact.
// It returns the loaded chart.Chart on success, or an error.
func (h *HelmController) loadHelmChart(source *sourcev1.HelmChart) (*chart.Chart, error) {
func (h *Controller) loadHelmChart(source *sourcev1.HelmChart) (*chart.Chart, error) {
f, err := os.CreateTemp("", fmt.Sprintf("%s-%s-*.tgz", source.GetNamespace(), source.GetName()))
if err != nil {
return nil, err
Expand Down Expand Up @@ -149,14 +136,9 @@ func (h *HelmController) loadHelmChart(source *sourcev1.HelmChart) (*chart.Chart
return loader.Load(f.Name())
}

func (h *HelmController) copyAndVerifyArtifact(artifact *sourcev1.Artifact, reader io.Reader, writer io.Writer) error {
func (h *Controller) copyAndVerifyArtifact(artifact *sourcev1.Artifact, reader io.Reader, writer io.Writer) error {
hasher := sha256.New()

// for backwards compatibility with source-controller v0.17.2 and older
if len(artifact.Checksum) == 40 {
hasher = sha1.New()
}

// compute checksum
mw := io.MultiWriter(hasher, writer)
if _, err := io.Copy(mw, reader); err != nil {
Expand All @@ -173,7 +155,7 @@ func (h *HelmController) copyAndVerifyArtifact(artifact *sourcev1.Artifact, read

// deleteHelmChart deletes the v1beta2.HelmChart of the v2beta1.HelmRelease.
// input is a helmRelease instance, not a template
func (h *HelmController) deleteHelmChart(ctx context.Context, hr *v2.HelmRelease) error {
func (h *Controller) deleteHelmChart(ctx context.Context, hr *v2.HelmRelease) error {
if hr.Status.HelmChart == "" {
return nil
}
Expand Down Expand Up @@ -261,7 +243,8 @@ func helmChartRequiresUpdate(hr *v2.HelmRelease, chart *sourcev1.HelmChart) bool
// composeValues attempts to resolve all v2beta1.ValuesReference resources
// and merges them as defined. Referenced resources are only retrieved once
// to ensure a single version is taken into account during the merge.
func (h *HelmController) composeValues(ctx context.Context, hr v2.HelmRelease) (chartutil.Values, error) {
//nolint:gocyclo
func (h *Controller) composeValues(ctx context.Context, hr v2.HelmRelease) (chartutil.Values, error) {
result := chartutil.Values{}

configMaps := make(map[string]*corev1.ConfigMap)
Expand Down Expand Up @@ -300,11 +283,11 @@ func (h *HelmController) composeValues(ctx context.Context, hr v2.HelmRelease) (
}
return nil, fmt.Errorf("could not find %s '%s'", v.Kind, namespacedName)
}
if data, ok := resource.Data[v.GetValuesKey()]; !ok {
var data string
if data, ok = resource.Data[v.GetValuesKey()]; !ok {
return nil, fmt.Errorf("missing key '%s' in %s '%s'", v.GetValuesKey(), v.Kind, namespacedName)
} else {
valuesData = []byte(data)
}
valuesData = []byte(data)
case "Secret":
resource, ok := secrets[namespacedName.String()]
if !ok {
Expand Down Expand Up @@ -333,11 +316,11 @@ func (h *HelmController) composeValues(ctx context.Context, hr v2.HelmRelease) (
}
return nil, fmt.Errorf("could not find %s '%s'", v.Kind, namespacedName)
}
if data, ok := resource.Data[v.GetValuesKey()]; !ok {
var data []byte
if data, ok = resource.Data[v.GetValuesKey()]; !ok {
return nil, fmt.Errorf("missing key '%s' in %s '%s'", v.GetValuesKey(), v.Kind, namespacedName)
} else {
valuesData = data
}
valuesData = data
default:
return nil, fmt.Errorf("unsupported ValuesReference kind '%s'", v.Kind)
}
Expand Down

0 comments on commit 7a8f82d

Please sign in to comment.