chore(lint): enable wsl

This commit is contained in:
Luca Burgazzoli 2024-05-16 15:33:39 +02:00
parent 0e977d1edc
commit ce44e487c9
No known key found for this signature in database
GPG Key ID: 238C46A40510C1A9
34 changed files with 66 additions and 36 deletions

View File

@ -35,6 +35,9 @@ linters-settings:
- '^len\.'
- '^strings\.SplitN$'
- '^make$'
wsl:
allow-cuddle-declarations: true
allow-separated-leading-comment: true
linters:
enable-all: true
disable:
@ -78,5 +81,4 @@ linters:
- wastedassign
- whitespace
- wrapcheck
- wsl
- depguard

View File

@ -40,6 +40,7 @@ func (m RawMessage) MarshalJSON() ([]byte, error) {
if m == nil {
return []byte("null"), nil
}
return m, nil
}
@ -48,7 +49,9 @@ func (m *RawMessage) UnmarshalJSON(data []byte) error {
if m == nil {
return errors.New("json.RawMessage: UnmarshalJSON on nil pointer")
}
*m = append((*m)[0:0], data...)
return nil
}
@ -57,10 +60,12 @@ func (m *RawMessage) String() string {
if m == nil {
return ""
}
b, err := m.MarshalJSON()
if err != nil {
return ""
}
return string(b)
}

View File

@ -29,7 +29,6 @@ func init() {
}
func NewRunCmd() *cobra.Command {
co := controller.Options{
MetricsAddr: ":8080",
ProbeAddr: ":8081",

View File

@ -56,6 +56,7 @@ func NewReconciler(ctx context.Context, manager ctrlRt.Manager, o helm.Options)
if err != nil {
return nil, err
}
if isOpenshift {
rec.ClusterType = controller.ClusterTypeOpenShift
}

View File

@ -94,11 +94,9 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu
//nolint:nestif
if rr.Resource.ObjectMeta.DeletionTimestamp.IsZero() {
//
// Add finalizer
//
if ctrlutil.AddFinalizer(rr.Resource, DaprControlPlaneFinalizerName) {
if err := r.Update(ctx, rr.Resource); err != nil {
if k8serrors.IsConflict(err) {
@ -109,11 +107,9 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu
}
}
} else {
//
// Cleanup leftovers if needed
//
for i := len(r.actions) - 1; i >= 0; i-- {
if err := r.actions[i].Cleanup(ctx, &rr); err != nil {
return ctrl.Result{}, err
@ -123,7 +119,6 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu
//
// Handle finalizer
//
if ctrlutil.RemoveFinalizer(rr.Resource, DaprControlPlaneFinalizerName) {
if err := r.Update(ctx, rr.Resource); err != nil {
if k8serrors.IsConflict(err) {
@ -150,6 +145,7 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu
}
errs := make([]error, 0, len(r.actions)+1)
for i := range r.actions {
if err := r.actions[i].Run(ctx, &rr); err != nil {
errs = append(errs, err)

View File

@ -62,6 +62,7 @@ func NewReconciler(ctx context.Context, manager ctrlRt.Manager, o helm.Options)
if err != nil {
return nil, err
}
if isOpenshift {
rec.ClusterType = controller.ClusterTypeOpenShift
}

View File

@ -72,11 +72,12 @@ func (a *ApplyCRDsAction) Run(ctx context.Context, rc *ReconciliationRequest) er
})
apply := rc.Resource.Generation != rc.Resource.Status.ObservedGeneration
_, err = dc.Get(ctx, obj.GetName(), metav1.GetOptions{})
_, err = dc.Get(ctx, obj.GetName(), metav1.GetOptions{})
if err != nil && !k8serrors.IsNotFound(err) {
return fmt.Errorf("cannot determine if CRD %s exists: %w", resources.Ref(&obj), err)
}
if err != nil && k8serrors.IsNotFound(err) {
apply = true
}
@ -105,7 +106,6 @@ func (a *ApplyCRDsAction) Run(ctx context.Context, rc *ReconciliationRequest) er
"apply", "true",
"gen", rc.Resource.Generation,
"ref", resources.Ref(&obj))
}
}

View File

@ -107,7 +107,6 @@ func (a *ApplyResourcesAction) Run(ctx context.Context, rc *ReconciliationReques
})
switch dc.(type) {
//
// NamespacedResource: in this case, filtering with ownership can be implemented
// as all the namespaced resources created by this controller have the Dapr CR as
@ -120,7 +119,6 @@ func (a *ApplyResourcesAction) Run(ctx context.Context, rc *ReconciliationReques
r := gvk.GroupVersion().String() + ":" + gvk.Kind
if _, ok := a.subscriptions[r]; !ok {
a.l.Info("watch", "ref", r)
err = rc.Reconciler.Watch(
@ -152,7 +150,6 @@ func (a *ApplyResourcesAction) Run(ctx context.Context, rc *ReconciliationReques
r := gvk.GroupVersion().String() + ":" + gvk.Kind
if _, ok := a.subscriptions[r]; !ok {
a.l.Info("watch", "ref", r)
err = rc.Reconciler.Watch(
@ -196,7 +193,6 @@ func (a *ApplyResourcesAction) Run(ctx context.Context, rc *ReconciliationReques
// - https://github.com/dapr/dapr/issues/3968
// - https://github.com/dapr/dapr/issues/6500
//
a.l.Info("run",
"apply", "false",
"ref", resources.Ref(&obj),
@ -284,9 +280,11 @@ func (a *ApplyResourcesAction) watchForUpdates(gvk schema.GroupVersionKind) bool
if gvk.Group == "" && gvk.Version == "v1" && gvk.Kind == "Secret" {
return false
}
if gvk.Group == "admissionregistration.k8s.io" && gvk.Version == "v1" && gvk.Kind == "MutatingWebhookConfiguration" {
return false
}
if gvk.Group == "apiextensions.k8s.io" && gvk.Version == "v1" && gvk.Kind == "CustomResourceDefinition" {
return false
}
@ -306,9 +304,11 @@ func (a *ApplyResourcesAction) installOnly(gvk schema.GroupVersionKind) bool {
if gvk.Group == "" && gvk.Version == "v1" && gvk.Kind == "Secret" {
return true
}
if gvk.Group == "admissionregistration.k8s.io" && gvk.Version == "v1" && gvk.Kind == "MutatingWebhookConfiguration" {
return true
}
if gvk.Group == "apiextensions.k8s.io" && gvk.Version == "v1" && gvk.Kind == "CustomResourceDefinition" {
return true
}

View File

@ -86,6 +86,7 @@ func (a *ChartAction) loadChart(ctx context.Context, rc *ReconciliationRequest)
if v, ok := s.Data[ChartRepoUsernameKey]; ok {
opts.Username = string(v)
}
if v, ok := s.Data[ChartRepoPasswordKey]; ok {
opts.Password = string(v)
}

View File

@ -52,6 +52,7 @@ func (a *ConditionsAction) Run(ctx context.Context, rc *ReconciliationRequest) e
}
ready := 0
for i := range deployments.Items {
if conditions.ConditionStatus(deployments.Items[i], appsv1.DeploymentAvailable) == corev1.ConditionTrue {
ready++

View File

@ -101,11 +101,9 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu
//nolint:nestif
if rr.Resource.ObjectMeta.DeletionTimestamp.IsZero() {
//
// Add finalizer
//
if ctrlutil.AddFinalizer(rr.Resource, DaprInstanceFinalizerName) {
if err := r.Update(ctx, rr.Resource); err != nil {
if k8serrors.IsConflict(err) {
@ -116,11 +114,9 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu
}
}
} else {
//
// Cleanup leftovers if needed
//
for i := len(r.actions) - 1; i >= 0; i-- {
if err := r.actions[i].Cleanup(ctx, &rr); err != nil {
return ctrl.Result{}, err
@ -130,7 +126,6 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu
//
// Handle finalizer
//
if ctrlutil.RemoveFinalizer(rr.Resource, DaprInstanceFinalizerName) {
if err := r.Update(ctx, rr.Resource); err != nil {
if k8serrors.IsConflict(err) {
@ -157,6 +152,7 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu
}
errs := make([]error, 0, len(r.actions)+1)
for i := range r.actions {
if err := r.actions[i].Run(ctx, &rr); err != nil {
errs = append(errs, err)
@ -185,6 +181,7 @@ func (r *Reconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.Resu
//
err = r.Status().Update(ctx, rr.Resource)
if err != nil && k8serrors.IsConflict(err) {
l.Info(err.Error())
return ctrl.Result{Requeue: true}, nil

View File

@ -18,7 +18,6 @@ import (
)
func gcSelector(rc *ReconciliationRequest) (labels.Selector, error) {
namespace, err := labels.NewRequirement(
helm.ReleaseNamespace,
selection.Equals,
@ -59,10 +58,12 @@ func labelsToRequest(_ context.Context, object ctrlCli.Object) []reconcile.Reque
if allLabels == nil {
return nil
}
name := allLabels[helm.ReleaseName]
if name == "" {
return nil
}
namespace := allLabels[helm.ReleaseNamespace]
if namespace == "" {
return nil

View File

@ -35,6 +35,7 @@ func Get(from Getter, t ConditionType) *metav1.Condition {
return &condition
}
}
return nil
}

View File

@ -48,27 +48,31 @@ type Client struct {
}
func NewClient(cfg *rest.Config, scheme *runtime.Scheme, cc ctrl.Client) (*Client, error) {
discoveryCl, err := discovery.NewDiscoveryClientForConfig(cfg)
if err != nil {
return nil, err
}
kubeCl, err := kubernetes.NewForConfig(cfg)
if err != nil {
return nil, err
}
restCl, err := newRESTClientForConfig(cfg)
if err != nil {
return nil, err
}
dynCl, err := dynamic.NewForConfig(cfg)
if err != nil {
return nil, err
}
daprCl, err := daprClient.NewForConfig(cfg)
if err != nil {
return nil, err
}
apiextCl, err := apiextv1.NewForConfig(cfg)
if err != nil {
return nil, err
@ -98,6 +102,7 @@ func newRESTClientForConfig(config *rest.Config) (*rest.RESTClient, error) {
// so that the RESTClientFor doesn't complain
cfg.GroupVersion = &schema.GroupVersion{}
cfg.NegotiatedSerializer = codecs.WithoutConversion()
if len(cfg.UserAgent) == 0 {
cfg.UserAgent = rest.DefaultKubernetesUserAgent()
}

View File

@ -69,6 +69,7 @@ func Start(options Options, setup func(manager.Manager, Options) error) error {
if err := mgr.AddHealthzCheck("healthz", healthz.Ping); err != nil {
return fmt.Errorf("unable to set up health check: %w", err)
}
if err := mgr.AddReadyzCheck("readyz", healthz.Ping); err != nil {
return fmt.Errorf("unable to set up readiness check: %w", err)
}

View File

@ -51,7 +51,6 @@ func (gc *GC) Run(ctx context.Context, ns string, c *client.Client, selector lab
}
func (gc *GC) deleteEachOf(ctx context.Context, c *client.Client, selector labels.Selector) (int, error) {
deleted := 0
for GVK := range gc.collectableGVKs {
@ -70,9 +69,11 @@ func (gc *GC) deleteEachOf(ctx context.Context, c *client.Client, selector label
gc.l.Info("cannot gc, forbidden", "gvk", GVK.String())
continue
}
if !k8serrors.IsNotFound(err) {
return 0, fmt.Errorf("cannot list child resources %s: %w", GVK.String(), err)
}
continue
}
@ -154,9 +155,11 @@ func (gc *GC) computeDeletableTypes(ctx context.Context, ns string, c *client.Cl
}
GVKs := make(map[schema.GroupVersionKind]struct{})
for _, res := range apiResourceLists {
for i := range res.APIResources {
resourceGroup := res.APIResources[i].Group
if resourceGroup == "" {
// Empty implies the group of the containing resource list should be used
gv, err := schema.ParseGroupVersion(res.GroupVersion)
@ -166,6 +169,7 @@ func (gc *GC) computeDeletableTypes(ctx context.Context, ns string, c *client.Cl
resourceGroup = gv.Group
}
rule:
for _, rule := range ssrr.Status.ResourceRules {
if !slices.Contains(rule.Verbs, "delete") && !slices.Contains(rule.Verbs, "*") {
@ -179,6 +183,7 @@ func (gc *GC) computeDeletableTypes(ctx context.Context, ns string, c *client.Cl
if gc.canBeDeleted(ctx, GVK) {
GVKs[GVK] = struct{}{}
}
break rule
}
}

View File

@ -30,6 +30,7 @@ func (p AnnotationChanged) Update(e event.UpdateEvent) bool {
log.Error(nil, "Update event has no old object to update", "event", e)
return false
}
if e.ObjectOld.GetAnnotations() == nil {
log.Error(nil, "Update event has no old object annotations to update", "event", e)
return false

View File

@ -33,6 +33,7 @@ func (p HasLabel) test(obj client.Object) bool {
if obj == nil {
return false
}
if obj.GetLabels() == nil {
return false
}

View File

@ -33,6 +33,7 @@ func (p StatusChanged) Update(e event.UpdateEvent) bool {
log.Error(nil, "Update event has no old object to update", "event", e)
return false
}
if e.ObjectNew == nil {
log.Error(nil, "Update event has no new object to update", "event", e)
return false

View File

@ -78,6 +78,7 @@ func (e *Engine) Render(c *chart.Chart, dapr *daprApi.DaprInstance, overrides ma
}
keys := make([]string, 0, len(files))
for k := range files {
if !strings.HasSuffix(k, ".yaml") && !strings.HasSuffix(k, ".yml") {
continue
@ -92,10 +93,12 @@ func (e *Engine) Render(c *chart.Chart, dapr *daprApi.DaprInstance, overrides ma
for _, k := range keys {
v := files[k]
ul, err := resources.Decode(e.decoder, []byte(v))
if err != nil {
return nil, fmt.Errorf("cannot decode %s: %w", k, err)
}
if ul == nil {
continue
}
@ -152,5 +155,4 @@ func (e *Engine) renderValues(
}
return rv, nil
}

View File

@ -108,6 +108,7 @@ func ToUnstructured(s *runtime.Scheme, obj runtime.Object) (*unstructured.Unstru
if err != nil {
return nil, fmt.Errorf("failed to convert to unstructured - unable to get GVK %w", err)
}
apiv, k := gvks[0].ToAPIVersionAndKind()
u.SetAPIVersion(apiv)
@ -139,6 +140,7 @@ func Decode(decoder runtime.Decoder, content []byte) ([]unstructured.Unstructure
if len(out) == 0 {
continue
}
if out["Kind"] == "" {
continue
}
@ -159,7 +161,6 @@ func Decode(decoder runtime.Decoder, content []byte) ([]unstructured.Unstructure
}
results = append(results, obj)
}
return results, nil

View File

@ -18,6 +18,7 @@ func Merge(dst map[string]interface{}, source map[string]interface{}) map[string
}
}
}
out[k] = v
}
@ -28,6 +29,7 @@ func Lookup(m map[string]interface{}, ks ...string) (interface{}, error) {
if len(ks) == 0 { // degenerate input
return nil, errors.New("lookup needs at least one key")
}
if rval, ok := m[ks[0]]; !ok {
return nil, fmt.Errorf("key not found; remaining keys: %v", ks)
} else if len(ks) == 1 { // we've reached the final key

View File

@ -21,7 +21,6 @@ import (
)
func TestDaprDeploy(t *testing.T) {
t.Run("With ControlPlane", func(t *testing.T) {
testDaprDeploy(
With(t),
@ -65,7 +64,6 @@ func TestDaprDeploy(t *testing.T) {
},
)
})
}
func testDaprDeploy(test Test, f func(t Test, ns *corev1.Namespace) client.Object) {
@ -108,5 +106,4 @@ func testDaprDeploy(test Test, f func(t Test, ns *corev1.Namespace) client.Objec
//
daprTC.ValidateDaprApp(test, res.GetNamespace())
}

View File

@ -69,5 +69,4 @@ func TestDaprControlPlaneDeployWrongCR(t *testing.T) {
WithTransform(ConditionStatus(conditions.TypeReconciled), Equal(corev1.ConditionFalse)))
test.Eventually(dapr.ControlPlane(test, instance), TestTimeoutLong).Should(
WithTransform(ConditionReason(conditions.TypeReconciled), Equal(conditions.ReasonUnsupportedConfiguration)))
}

View File

@ -128,7 +128,6 @@ func TestDaprInstanceDeployWithCustomSidecarImage(t *testing.T) {
jq.Match(`.items[0].spec.containers[0].env[] | select(.name == "SIDECAR_IMAGE_PULL_POLICY") | .value == "%s"`, corev1.PullAlways),
)),
)
}
func TestDaprInstanceDeployWithApp(t *testing.T) {

View File

@ -46,14 +46,17 @@ func New(t *testing.T) (*Client, error) {
if err != nil {
return nil, err
}
dynamicClient, err := dynamic.NewForConfig(cfg)
if err != nil {
return nil, err
}
kubeClient, err := kubernetes.NewForConfig(cfg)
if err != nil {
return nil, err
}
extClient, err := apiextClient.NewForConfig(cfg)
if err != nil {
return nil, err
@ -106,8 +109,8 @@ func (c *Client) RESTMapper() (meta.RESTMapper, error) {
}
return restmapper.NewDiscoveryRESTMapper(gr), nil
}
func (c *Client) ForResource(in *unstructured.Unstructured) (dynamic.ResourceInterface, error) {
gvk := in.GetObjectKind().GroupVersionKind()
gk := schema.GroupKind{Group: gvk.Group, Kind: gvk.Kind}

View File

@ -183,6 +183,7 @@ func DeployTestApp(t support.Test, name string, namespace string) {
if !strings.HasPrefix(path, "/") {
path = "/" + path
}
if !strings.HasSuffix(path, "(/|$)(.*)") {
path += "(/|$)(.*)"
}
@ -226,7 +227,6 @@ func DeployTestApp(t support.Test, name string, namespace string) {
t.Cleanup(func() []runtime.Object {
return []runtime.Object{ing}
})
}
func Values(t support.Test, in map[string]any) *daprAc.JSONApplyConfiguration {
@ -245,5 +245,4 @@ func Values(t support.Test, in map[string]any) *daprAc.JSONApplyConfiguration {
cfg.RawMessage = data
return cfg
}

View File

@ -20,7 +20,6 @@ func GET(t support.Test, url string) func(g gomega.Gomega) (*http.Response, erro
}
func POST(t support.Test, url string, contentType string, content []byte) func(g gomega.Gomega) (*http.Response, error) {
return func(g gomega.Gomega) (*http.Response, error) {
data := content
if data == nil {

View File

@ -22,7 +22,6 @@ func WithLog(value func(string, ...interface{})) ConfigurationOption {
}
func New(options ...ConfigurationOption) (*Helm, error) {
settings := cli.New()
config := action.Configuration{}

View File

@ -25,7 +25,6 @@ func DeployOperator(test support.Test, ns *corev1.Namespace, image string) {
//
// Install OperatorGroups
//
og, err := test.Client().OLM().OperatorsV1().OperatorGroups(ns.Name).Create(
test.Ctx(),
&olmV1.OperatorGroup{
@ -176,9 +175,11 @@ func OperatorGroup(t support.Test, name string, namespace string) func(g gomega.
name,
metav1.GetOptions{},
)
if err != nil && !k8serrors.IsNotFound(err) {
return nil, err
}
if err != nil && k8serrors.IsNotFound(err) {
return nil, nil
}

View File

@ -29,6 +29,7 @@ func runCleanup(t Test, in runtime.Object) error {
if err != nil && !k8serrors.IsNotFound(err) {
return fmt.Errorf("failed to get current object, %w", err)
}
if err != nil && k8serrors.IsNotFound(err) {
return nil
}

View File

@ -127,6 +127,7 @@ func Resource(t Test, ri dynamic.ResourceInterface, un *unstructured.Unstructure
if err != nil && !k8serrors.IsNotFound(err) {
return nil, err
}
if err != nil && k8serrors.IsNotFound(err) {
return nil, nil
}

View File

@ -1,6 +1,7 @@
package support
import (
"github.com/dapr-sandbox/dapr-kubernetes-operator/pkg/pointer"
"github.com/onsi/gomega"
"github.com/rs/xid"
corev1 "k8s.io/api/core/v1"
@ -29,9 +30,10 @@ func createTestNamespace(t Test, options ...Option[*corev1.Namespace]) *corev1.N
func deleteTestNamespace(t Test, namespace *corev1.Namespace) {
t.T().Helper()
propagationPolicy := metav1.DeletePropagationBackground
err := t.Client().CoreV1().Namespaces().Delete(t.Ctx(), namespace.Name, metav1.DeleteOptions{
PropagationPolicy: &propagationPolicy,
PropagationPolicy: pointer.Any(metav1.DeletePropagationBackground),
})
t.Expect(err).NotTo(gomega.HaveOccurred())
}

View File

@ -44,9 +44,11 @@ func init() {
if err := daprApi.AddToScheme(scheme.Scheme); err != nil {
panic(err)
}
if err := olmV1.AddToScheme(scheme.Scheme); err != nil {
panic(err)
}
if err := olmV1Alpha1.AddToScheme(scheme.Scheme); err != nil {
panic(err)
}
@ -82,8 +84,10 @@ func With(t *testing.T) Test {
if deadline, ok := t.Deadline(); ok {
withDeadline, cancel := context.WithDeadline(ctx, deadline)
t.Cleanup(cancel)
ctx = withDeadline
}
answer := &T{
WithT: gomega.NewWithT(t),
id: xid.New().String(),
@ -158,8 +162,10 @@ func (t *T) Client() *supportclient.Client {
if err != nil {
t.T().Fatalf("Error creating client: %v", err)
}
t.client = c
})
return t.client
}