Skip to content

Commit

Permalink
Merge pull request #227 from inteon/fix_linters
Browse files Browse the repository at this point in the history
Fix linters
  • Loading branch information
SgtCoDFish authored Mar 28, 2024
2 parents 6120c3c + 8203e28 commit 4a22361
Show file tree
Hide file tree
Showing 20 changed files with 114 additions and 174 deletions.
11 changes: 0 additions & 11 deletions .golangci.yaml
Original file line number Diff line number Diff line change
@@ -1,20 +1,9 @@
issues:
exclude-rules:
- linters:
- unused
- errorlint
- staticcheck
- goprintffuncname
- prealloc
- gofmt
- gosec
- ginkgolinter
- ineffassign
- unconvert
- errcheck
- gocritic
- nilerr
- wastedassign
text: ".*"
linters:
# Explicitly define all enabled linters
Expand Down
15 changes: 10 additions & 5 deletions cmd/app/options/options.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ import (
"k8s.io/client-go/rest"
cliflag "k8s.io/component-base/cli/flag"
"k8s.io/klog/v2"
"k8s.io/klog/v2/klogr"

_ "k8s.io/client-go/plugin/pkg/client/auth"
)
Expand Down Expand Up @@ -83,8 +82,10 @@ func (o *Options) Prepare(cmd *cobra.Command) *Options {

func (o *Options) Complete() error {
klog.InitFlags(nil)
log := klogr.New()
flag.Set("v", o.logLevel)
log := klog.TODO()
if err := flag.Set("v", o.logLevel); err != nil {
return fmt.Errorf("failed to set log level: %s", err)
}
o.Logr = log

var err error
Expand All @@ -107,8 +108,6 @@ func (o *Options) addFlags(cmd *cobra.Command) {
o.addAppFlags(nfs.FlagSet("App"))
o.kubeConfigFlags = genericclioptions.NewConfigFlags(true)
o.kubeConfigFlags.AddFlags(nfs.FlagSet("Kubernetes"))
cmd.MarkPersistentFlagRequired("node-id")
cmd.MarkPersistentFlagRequired("endpoint")

usageFmt := "Usage:\n %s\n"
cmd.SetUsageFunc(func(cmd *cobra.Command) error {
Expand All @@ -135,9 +134,15 @@ func (o *Options) addAppFlags(fs *pflag.FlagSet) {

fs.StringVar(&o.NodeID, "node-id", "",
"The name of the node which is hosting this driver instance.")
if err := cobra.MarkFlagRequired(fs, "node-id"); err != nil {
panic(err)
}

fs.StringVar(&o.Endpoint, "endpoint", "",
"The endpoint that the driver will connect to the Kubelet.")
if err := cobra.MarkFlagRequired(fs, "endpoint"); err != nil {
panic(err)
}

fs.StringVar(&o.DriverName, "driver-name", "csi.cert-manager.io",
"The name of this CSI driver which will be shared with the Kubelet.")
Expand Down
4 changes: 2 additions & 2 deletions pkg/apis/defaults/defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,8 @@ func SetDefaultAttributes(attrOriginal map[string]string) (map[string]string, er
}

func setDefaultIfEmpty(attr map[string]string, k, v string) {
if len(attr[string(k)]) == 0 {
attr[string(k)] = v
if len(attr[k]) == 0 {
attr[k] = v
}
}

Expand Down
5 changes: 0 additions & 5 deletions pkg/apis/validation/validation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,6 @@ import (
)

func Test_ValidateAttributes(t *testing.T) {
type vaT struct {
attr map[string]string
expError error
}

tests := map[string]struct {
attr map[string]string
expErr field.ErrorList
Expand Down
3 changes: 1 addition & 2 deletions pkg/keystore/pkcs12/pkcs12.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ package pkcs12

import (
"crypto"
"crypto/rand"
"errors"
"fmt"

Expand Down Expand Up @@ -60,7 +59,7 @@ func create(password string, pk crypto.PrivateKey, chainPEM []byte) ([]byte, err
return nil, errors.New("no certificates decoded in certificate chain")
}

pfx, err := pkcs12.Encode(rand.Reader, pk, chain[0], chain[1:], password)
pfx, err := pkcs12.LegacyRC2.Encode(pk, chain[0], chain[1:], password)
if err != nil {
return nil, fmt.Errorf("failed to encode the PKCS12 certificate chain file: %v", err)
}
Expand Down
9 changes: 7 additions & 2 deletions test/e2e/framework/framework.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ limitations under the License.
package framework

import (
"context"
"time"

cmmeta "github.com/cert-manager/cert-manager/pkg/apis/meta/v1"
Expand Down Expand Up @@ -133,12 +134,16 @@ func (f *Framework) AfterEach() {
return
}

cleanupCtx := context.Background()
cleanupCtx, cancel := context.WithTimeout(cleanupCtx, 5*time.Minute)
defer cancel()

By("Deleting test namespace")
err := f.DeleteKubeNamespace(f.Namespace.Name)
err := f.DeleteKubeNamespace(cleanupCtx, f.Namespace.Name)
Expect(err).NotTo(HaveOccurred())

By("Waiting for test namespace to no longer exist")
err = f.WaitForKubeNamespaceNotExist(f.Namespace.Name)
err = f.WaitForKubeNamespaceNotExist(cleanupCtx, f.Namespace.Name)
Expect(err).NotTo(HaveOccurred())
}

Expand Down
58 changes: 29 additions & 29 deletions test/e2e/framework/helper/certificaterequest.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,37 +36,35 @@ import (

// WaitForCertificateRequestReady waits for the CertificateRequest resources to
// enter a Ready state.
func (h *Helper) WaitForCertificateRequestsReady(pod *corev1.Pod, timeout time.Duration) ([]*cmapi.CertificateRequest, error) {
func (h *Helper) WaitForCertificateRequestsReady(ctx context.Context, pod *corev1.Pod, timeout time.Duration) ([]*cmapi.CertificateRequest, error) {
var crs []*cmapi.CertificateRequest

err := wait.PollImmediate(time.Second/4, timeout,
func() (bool, error) {
crList, err := h.CMClient.CertmanagerV1().CertificateRequests(pod.Namespace).List(context.TODO(), metav1.ListOptions{})
if err != nil {
return false, err
}
err := wait.PollUntilContextTimeout(ctx, time.Second/4, timeout, true, func(ctx context.Context) (bool, error) {
crList, err := h.CMClient.CertmanagerV1().CertificateRequests(pod.Namespace).List(ctx, metav1.ListOptions{})
if err != nil {
return false, err
}

crs, err = h.findCertificateRequests(crList.Items, pod.UID)
if err != nil {
log.Logf("Cannot find CertificateRequests for pod, waiting...")
return false, nil
}
crs, err = h.findCertificateRequests(crList.Items, pod.UID)
if err != nil {
log.Logf("Cannot find CertificateRequests for pod, waiting...")
return false, nil // nolint:nilerr // We want to ignore this error and wait for the CRs to be created
}

for _, cr := range crs {
isReady := apiutil.CertificateRequestHasCondition(cr, cmapi.CertificateRequestCondition{
Type: cmapi.CertificateRequestConditionReady,
Status: cmmeta.ConditionTrue,
})
if !isReady {
log.Logf("Expected CertificateRequest for Pod %s/%s to have Ready condition 'true' but it has: %v",
pod.Namespace, pod.Name, cr.Status.Conditions)
return false, nil
}
for _, cr := range crs {
isReady := apiutil.CertificateRequestHasCondition(cr, cmapi.CertificateRequestCondition{
Type: cmapi.CertificateRequestConditionReady,
Status: cmmeta.ConditionTrue,
})
if !isReady {
log.Logf("Expected CertificateRequest for Pod %s/%s to have Ready condition 'true' but it has: %v",
pod.Namespace, pod.Name, cr.Status.Conditions)
return false, nil
}
}

return true, nil
},
)
return true, nil
})
if err != nil {
return nil, err
}
Expand All @@ -89,10 +87,10 @@ func (h *Helper) FindCertificateRequestsReady(crs []cmapi.CertificateRequest, po
return podCRs, nil
}

func (h *Helper) WaitForCertificateRequestDeletion(namespace, name string, timeout time.Duration) error {
func (h *Helper) WaitForCertificateRequestDeletion(ctx context.Context, namespace, name string, timeout time.Duration) error {
log.Logf("Waiting for CertificateRequest to be deleted %s/%s", namespace, name)
err := wait.PollImmediate(time.Second/2, timeout, func() (bool, error) {
cr, err := h.CMClient.CertmanagerV1().CertificateRequests(namespace).Get(context.TODO(), name, metav1.GetOptions{})
err := wait.PollUntilContextTimeout(ctx, time.Second/2, timeout, true, func(ctx context.Context) (bool, error) {
cr, err := h.CMClient.CertmanagerV1().CertificateRequests(namespace).Get(ctx, name, metav1.GetOptions{})
if k8sErrors.IsNotFound(err) {
return true, nil
}
Expand All @@ -107,7 +105,9 @@ func (h *Helper) WaitForCertificateRequestDeletion(namespace, name string, timeo
return false, nil
})
if err != nil {
h.Kubectl(namespace).DescribeResource("certificaterequest", name)
if err := h.Kubectl(namespace).DescribeResource("certificaterequest", name); err != nil {
log.Logf("helper: failed to describe CertificateRequest %s/%s: %v", namespace, name, err)
}
return err
}

Expand Down
30 changes: 17 additions & 13 deletions test/e2e/framework/helper/pod.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ import (
"github.com/cert-manager/csi-driver/test/e2e/framework/log"
)

func (h *Helper) CertificateKeyInPodPath(namespace, podName, containerName, mountPath string,
func (h *Helper) CertificateKeyInPodPath(ctx context.Context, namespace, podName, containerName, mountPath string,
attr map[string]string) ([]byte, []byte, error) {
certPath, ok := attr[csiapi.CertFileKey]
if !ok {
Expand All @@ -51,12 +51,12 @@ func (h *Helper) CertificateKeyInPodPath(namespace, podName, containerName, moun
}
keyPath = filepath.Join(mountPath, keyPath)

certData, err := h.ReadFilePathFromContainer(namespace, podName, containerName, certPath)
certData, err := h.ReadFilePathFromContainer(ctx, namespace, podName, containerName, certPath)
if err != nil {
return nil, nil, fmt.Errorf("failed to read cert data from pod: %s", err)
}

keyData, err := h.ReadFilePathFromContainer(namespace, podName, containerName, keyPath)
keyData, err := h.ReadFilePathFromContainer(ctx, namespace, podName, containerName, keyPath)
if err != nil {
return nil, nil, fmt.Errorf("failed to read key data from pod: %s", err)
}
Expand Down Expand Up @@ -93,7 +93,7 @@ func (h *Helper) CertificateKeyMatch(cr *cmapi.CertificateRequest, certData, key
return nil
}

func (h *Helper) ReadFilePathFromContainer(namespace, podName, containerName, path string) ([]byte, error) {
func (h *Helper) ReadFilePathFromContainer(ctx context.Context, namespace, podName, containerName, path string) ([]byte, error) {
coreclient, err := corev1client.NewForConfig(h.RestConfig)
if err != nil {
return nil, fmt.Errorf("failed to build core client form rest config: %s", err)
Expand Down Expand Up @@ -124,7 +124,7 @@ func (h *Helper) ReadFilePathFromContainer(namespace, podName, containerName, pa
}

execOut, execErr := new(bytes.Buffer), new(bytes.Buffer)
err = exec.Stream(remotecommand.StreamOptions{
err = exec.StreamWithContext(ctx, remotecommand.StreamOptions{
Stdout: execOut,
Stderr: execErr,
Tty: false,
Expand All @@ -136,11 +136,11 @@ func (h *Helper) ReadFilePathFromContainer(namespace, podName, containerName, pa
return execOut.Bytes(), nil
}

func (h *Helper) WaitForPodReady(namespace, name string, timeout time.Duration) error {
func (h *Helper) WaitForPodReady(ctx context.Context, namespace, name string, timeout time.Duration) error {
log.Logf("Waiting for Pod to become ready %s/%s", namespace, name)

err := wait.PollImmediate(time.Second/2, timeout, func() (bool, error) {
pod, err := h.KubeClient.CoreV1().Pods(namespace).Get(context.TODO(), name, metav1.GetOptions{})
err := wait.PollUntilContextTimeout(ctx, time.Second/2, timeout, true, func(ctx context.Context) (bool, error) {
pod, err := h.KubeClient.CoreV1().Pods(namespace).Get(ctx, name, metav1.GetOptions{})
if err != nil {
return false, err
}
Expand All @@ -163,17 +163,19 @@ func (h *Helper) WaitForPodReady(namespace, name string, timeout time.Duration)
return true, nil
})
if err != nil {
h.Kubectl(namespace).DescribeResource("pod", name)
if err := h.Kubectl(namespace).DescribeResource("pod", name); err != nil {
log.Logf("helper: failed to describe Pod %s/%s: %v", namespace, name, err)
}
return err
}

return nil
}

func (h *Helper) WaitForPodDeletion(namespace, name string, timeout time.Duration) error {
func (h *Helper) WaitForPodDeletion(ctx context.Context, namespace, name string, timeout time.Duration) error {
log.Logf("Waiting for Pod to be deleted %s/%s", namespace, name)
err := wait.PollImmediate(time.Second/2, timeout, func() (bool, error) {
pod, err := h.KubeClient.CoreV1().Pods(namespace).Get(context.TODO(), name, metav1.GetOptions{})
err := wait.PollUntilContextTimeout(ctx, time.Second/2, timeout, true, func(ctx context.Context) (bool, error) {
pod, err := h.KubeClient.CoreV1().Pods(namespace).Get(ctx, name, metav1.GetOptions{})
if k8sErrors.IsNotFound(err) {
return true, nil
}
Expand All @@ -188,7 +190,9 @@ func (h *Helper) WaitForPodDeletion(namespace, name string, timeout time.Duratio
return false, nil
})
if err != nil {
h.Kubectl(namespace).DescribeResource("pod", name)
if err := h.Kubectl(namespace).DescribeResource("pod", name); err != nil {
log.Logf("helper: failed to describe Pod %s/%s: %v", namespace, name, err)
}
return err
}

Expand Down
4 changes: 2 additions & 2 deletions test/e2e/framework/log/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,10 +29,10 @@ func nowStamp() string {
return time.Now().Format(time.StampMilli)
}

func log(level string, format string, args ...interface{}) {
func logf(level string, format string, args ...interface{}) {
fmt.Fprintf(Writer, nowStamp()+": "+level+": "+format+"\n", args...)
}

func Logf(format string, args ...interface{}) {
log("INFO", format, args...)
logf("INFO", format, args...)
}
18 changes: 7 additions & 11 deletions test/e2e/framework/testenv.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ import (
apierrors "k8s.io/apimachinery/pkg/api/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/util/wait"
"k8s.io/client-go/kubernetes"
)

// Defines methods that help provision test environments
Expand Down Expand Up @@ -181,25 +180,22 @@ func (f *Framework) CreateCAClusterIssuer(baseName string) (cmmeta.ObjectReferen
}

// DeleteKubeNamespace will delete a namespace resource
func (f *Framework) DeleteKubeNamespace(namespace string) error {
return f.KubeClientSet.CoreV1().Namespaces().Delete(context.TODO(), namespace, metav1.DeleteOptions{})
func (f *Framework) DeleteKubeNamespace(ctx context.Context, namespace string) error {
return f.KubeClientSet.CoreV1().Namespaces().Delete(ctx, namespace, metav1.DeleteOptions{})
}

// WaitForKubeNamespaceNotExist will wait for the namespace with the given name
// to not exist for up to 2 minutes.
func (f *Framework) WaitForKubeNamespaceNotExist(namespace string) error {
return wait.PollImmediate(Poll, time.Minute*2, namespaceNotExist(f.KubeClientSet, namespace))
}

func namespaceNotExist(c kubernetes.Interface, namespace string) wait.ConditionFunc {
return func() (bool, error) {
_, err := c.CoreV1().Namespaces().Get(context.TODO(), namespace, metav1.GetOptions{})
func (f *Framework) WaitForKubeNamespaceNotExist(ctx context.Context, namespace string) error {
return wait.PollUntilContextTimeout(ctx, time.Second, time.Minute*2, true, func(ctx context.Context) (bool, error) {
_, err := f.KubeClientSet.CoreV1().Namespaces().Get(ctx, namespace, metav1.GetOptions{})
if apierrors.IsNotFound(err) {
return true, nil
}

if err != nil {
return false, err
}
return false, nil
}
})
}
6 changes: 3 additions & 3 deletions test/e2e/suite/cases/annotations.go
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,14 @@ var _ = framework.CasesDescribe("Should set extra attributes as annotations on t
Expect(err).NotTo(HaveOccurred())

By("Waiting for Pod to become ready")
err = f.Helper().WaitForPodReady(f.Namespace.Name, testPod.Name, time.Minute)
err = f.Helper().WaitForPodReady(context.TODO(), f.Namespace.Name, testPod.Name, time.Minute)
Expect(err).NotTo(HaveOccurred())

testPod, err = f.KubeClientSet.CoreV1().Pods(f.Namespace.Name).Get(context.TODO(), testPod.Name, metav1.GetOptions{})
Expect(err).NotTo(HaveOccurred())

By("Ensure the corresponding CertificateRequest should exist with the correct spec")
crs, err := f.Helper().WaitForCertificateRequestsReady(testPod, time.Second)
crs, err := f.Helper().WaitForCertificateRequestsReady(context.TODO(), testPod, time.Second)
Expect(err).NotTo(HaveOccurred())

err = util.CertificateRequestMatchesSpec(crs[0], testVolume.CSI.VolumeAttributes)
Expand All @@ -71,7 +71,7 @@ var _ = framework.CasesDescribe("Should set extra attributes as annotations on t
Expect(crs[0].Annotations["custom.group.io/custom-key"]).Should(Equal("custom-value"))

By("Ensure the certificate key pair exists in the pod and matches that in the CertificateRequest")
certData, keyData, err := f.Helper().CertificateKeyInPodPath(f.Namespace.Name, testPod.Name, "test-container-1", "/tls",
certData, keyData, err := f.Helper().CertificateKeyInPodPath(context.TODO(), f.Namespace.Name, testPod.Name, "test-container-1", "/tls",
testVolume.CSI.VolumeAttributes)
Expect(err).NotTo(HaveOccurred())

Expand Down
Loading

0 comments on commit 4a22361

Please sign in to comment.