Fix golangci-lint errors (#10196)

* Fix golangci-lint errors

Signed-off-by: z1cheng <imchench@gmail.com>

* Fix dupl errors

Signed-off-by: z1cheng <imchench@gmail.com>

* Fix comments

Signed-off-by: z1cheng <imchench@gmail.com>

* Fix errcheck lint errors

Signed-off-by: z1cheng <imchench@gmail.com>

* Fix assert in e2e test

Signed-off-by: z1cheng <imchench@gmail.com>

* Not interrupt the waitForPodsReady

Signed-off-by: z1cheng <imchench@gmail.com>

* Replace string with constant

Signed-off-by: z1cheng <imchench@gmail.com>

* Fix comments

Signed-off-by: z1cheng <imchench@gmail.com>

* Revert write file permision

Signed-off-by: z1cheng <imchench@gmail.com>

---------

Signed-off-by: z1cheng <imchench@gmail.com>
This commit is contained in:
Chen Chen 2023-08-31 15:36:48 +08:00 committed by GitHub
parent 46d87d3462
commit b3060bfbd0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
253 changed files with 2434 additions and 2113 deletions

View file

@ -50,7 +50,7 @@ var HTTPBunImage = os.Getenv("HTTPBUN_IMAGE")
const EchoImage = "registry.k8s.io/ingress-nginx/e2e-test-echo@sha256:4938d1d91a2b7d19454460a8c1b010b89f6ff92d2987fd889ac3e8fc3b70d91a"
// TODO: change all Deployment functions to use these options
// in order to reduce complexity and have a unified API accross the
// in order to reduce complexity and have a unified API across the
// framework
type deploymentOptions struct {
name string
@ -317,7 +317,7 @@ func (f *Framework) GetNginxBaseImage() string {
// NGINXDeployment creates a new simple NGINX Deployment using NGINX base image
// and passing the desired configuration
func (f *Framework) NGINXDeployment(name string, cfg string, waitendpoint bool) {
func (f *Framework) NGINXDeployment(name, cfg string, waitendpoint bool) {
cfgMap := map[string]string{
"nginx.conf": cfg,
}
@ -389,7 +389,7 @@ func (f *Framework) NGINXDeployment(name string, cfg string, waitendpoint bool)
}
// NGINXWithConfigDeployment creates an NGINX deployment using a configmap containing the nginx.conf configuration
func (f *Framework) NGINXWithConfigDeployment(name string, cfg string) {
func (f *Framework) NGINXWithConfigDeployment(name, cfg string) {
f.NGINXDeployment(name, cfg, true)
}
@ -487,7 +487,8 @@ func (f *Framework) NewGRPCBinDeployment() {
}
func newDeployment(name, namespace, image string, port int32, replicas int32, command []string, args []string, env []corev1.EnvVar,
volumeMounts []corev1.VolumeMount, volumes []corev1.Volume, setProbe bool) *appsv1.Deployment {
volumeMounts []corev1.VolumeMount, volumes []corev1.Volume, setProbe bool,
) *appsv1.Deployment {
probe := &corev1.Probe{
InitialDelaySeconds: 2,
PeriodSeconds: 1,
@ -559,12 +560,12 @@ func newDeployment(name, namespace, image string, port int32, replicas int32, co
return d
}
func (f *Framework) NewDeployment(name, image string, port int32, replicas int32) {
func (f *Framework) NewDeployment(name, image string, port, replicas int32) {
f.NewDeploymentWithOpts(name, image, port, replicas, nil, nil, nil, nil, nil, true)
}
// NewDeployment creates a new deployment in a particular namespace.
func (f *Framework) NewDeploymentWithOpts(name, image string, port int32, replicas int32, command []string, args []string, env []corev1.EnvVar, volumeMounts []corev1.VolumeMount, volumes []corev1.Volume, setProbe bool) {
func (f *Framework) NewDeploymentWithOpts(name, image string, port, replicas int32, command, args []string, env []corev1.EnvVar, volumeMounts []corev1.VolumeMount, volumes []corev1.Volume, setProbe bool) {
deployment := newDeployment(name, f.Namespace, image, port, replicas, command, args, env, volumeMounts, volumes, setProbe)
f.EnsureDeployment(deployment)
@ -606,7 +607,7 @@ func (f *Framework) DeleteDeployment(name string) error {
})
assert.Nil(ginkgo.GinkgoT(), err, "deleting deployment")
return waitForPodsDeleted(f.KubeClientSet, 2*time.Minute, f.Namespace, metav1.ListOptions{
return waitForPodsDeleted(f.KubeClientSet, 2*time.Minute, f.Namespace, &metav1.ListOptions{
LabelSelector: labelSelectorToString(d.Spec.Selector.MatchLabels),
})
}

View file

@ -66,6 +66,7 @@ func (f *Framework) ExecCommand(pod *corev1.Pod, command string) (string, error)
execErr bytes.Buffer
)
//nolint:gosec // Ignore G204 error
cmd := exec.Command("/bin/bash", "-c", fmt.Sprintf("%v exec --namespace %s %s --container controller -- %s", KubectlPath, pod.Namespace, pod.Name, command))
cmd.Stdout = &execOut
cmd.Stderr = &execErr
@ -73,7 +74,6 @@ func (f *Framework) ExecCommand(pod *corev1.Pod, command string) (string, error)
err := cmd.Run()
if err != nil {
return "", fmt.Errorf("could not execute '%s %s': %v", cmd.Path, cmd.Args, err)
}
if execErr.Len() > 0 {
@ -91,6 +91,7 @@ func (f *Framework) NamespaceContent() (string, error) {
execErr bytes.Buffer
)
//nolint:gosec // Ignore G204 error
cmd := exec.Command("/bin/bash", "-c", fmt.Sprintf("%v get pods,services,endpoints,deployments --namespace %s", KubectlPath, f.Namespace))
cmd.Stdout = &execOut
cmd.Stderr = &execErr
@ -98,7 +99,6 @@ func (f *Framework) NamespaceContent() (string, error) {
err := cmd.Run()
if err != nil {
return "", fmt.Errorf("could not execute '%s %s': %v", cmd.Path, cmd.Args, err)
}
eout := strings.TrimSpace(execErr.String())
@ -110,7 +110,7 @@ func (f *Framework) NamespaceContent() (string, error) {
}
// newIngressController deploys a new NGINX Ingress controller in a namespace
func (f *Framework) newIngressController(namespace string, namespaceOverlay string) error {
func (f *Framework) newIngressController(namespace, namespaceOverlay string) error {
// Creates an nginx deployment
isChroot, ok := os.LookupEnv("IS_CHROOT")
if !ok {
@ -130,12 +130,11 @@ func (f *Framework) newIngressController(namespace string, namespaceOverlay stri
return nil
}
var (
proxyRegexp = regexp.MustCompile("Starting to serve on .*:([0-9]+)")
)
var proxyRegexp = regexp.MustCompile(`Starting to serve on .*:(\d+)`)
// KubectlProxy creates a proxy to kubernetes apiserver
func (f *Framework) KubectlProxy(port int) (int, *exec.Cmd, error) {
//nolint:gosec // Ignore G204 error
cmd := exec.Command("/bin/bash", "-c", fmt.Sprintf("%s proxy --accept-hosts=.* --address=0.0.0.0 --port=%d", KubectlPath, port))
stdout, stderr, err := startCmdAndStreamOutput(cmd)
if err != nil {
@ -163,6 +162,7 @@ func (f *Framework) KubectlProxy(port int) (int, *exec.Cmd, error) {
}
func (f *Framework) UninstallChart() error {
//nolint:gosec //Ignore G204 error
cmd := exec.Command("helm", "uninstall", "--namespace", f.Namespace, "nginx-ingress")
_, err := cmd.CombinedOutput()
if err != nil {

View file

@ -14,6 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
//nolint:dupl // Ignore dupl errors for similar test case
package framework
import (
@ -75,7 +76,7 @@ func (f *Framework) NewNewFastCGIHelloServerDeploymentWithReplicas(replicas int3
d := f.EnsureDeployment(deployment)
err := waitForPodsReady(f.KubeClientSet, DefaultTimeout, int(replicas), f.Namespace, metav1.ListOptions{
err := waitForPodsReady(f.KubeClientSet, DefaultTimeout, int(replicas), f.Namespace, &metav1.ListOptions{
LabelSelector: fields.SelectorFromSet(fields.Set(d.Spec.Template.ObjectMeta.Labels)).String(),
})
assert.Nil(ginkgo.GinkgoT(), err, "failed to wait for to become ready")

View file

@ -49,10 +49,8 @@ const (
HTTPS RequestScheme = "https"
)
var (
// KubectlPath defines the full path of the kubectl binary
KubectlPath = "/usr/local/bin/kubectl"
)
// KubectlPath defines the full path of the kubectl binary
var KubectlPath = "/usr/local/bin/kubectl"
// Framework supports common operations used by e2e tests; it will keep a client & a namespace for you.
type Framework struct {
@ -131,7 +129,6 @@ func (f *Framework) CreateEnvironment() {
f.KubeClientSet, err = kubernetes.NewForConfig(f.KubeConfig)
assert.Nil(ginkgo.GinkgoT(), err, "creating a kubernetes client")
}
f.Namespace, err = CreateKubeNamespace(f.BaseName, f.KubeClientSet)
@ -250,9 +247,9 @@ func (f *Framework) GetNginxPodIP() string {
}
// GetURL returns the URL should be used to make a request to NGINX
func (f *Framework) GetURL(scheme RequestScheme) string {
func (f *Framework) GetURL(requestScheme RequestScheme) string {
ip := f.GetNginxIP()
return fmt.Sprintf("%v://%v", scheme, ip)
return fmt.Sprintf("%v://%v", requestScheme, ip)
}
// GetIngressNGINXPod returns the ingress controller running pod
@ -270,6 +267,7 @@ func (f *Framework) updateIngressNGINXPod() error {
// WaitForNginxServer waits until the nginx configuration contains a particular server section.
// `cfg` passed to matcher is normalized by replacing all tabs and spaces with single space.
func (f *Framework) WaitForNginxServer(name string, matcher func(cfg string) bool) {
//nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated
err := wait.Poll(Poll, DefaultTimeout, f.matchNginxConditions(name, matcher))
assert.Nil(ginkgo.GinkgoT(), err, "waiting for nginx server condition/s")
Sleep(1 * time.Second)
@ -278,13 +276,15 @@ func (f *Framework) WaitForNginxServer(name string, matcher func(cfg string) boo
// WaitForNginxConfiguration waits until the nginx configuration contains a particular configuration
// `cfg` passed to matcher is normalized by replacing all tabs and spaces with single space.
func (f *Framework) WaitForNginxConfiguration(matcher func(cfg string) bool) {
//nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated
err := wait.Poll(Poll, DefaultTimeout, f.matchNginxConditions("", matcher))
assert.Nil(ginkgo.GinkgoT(), err, "waiting for nginx server condition/s")
Sleep(1 * time.Second)
}
// WaitForNginxCustomConfiguration waits until the nginx configuration given part (from, to) contains a particular configuration
func (f *Framework) WaitForNginxCustomConfiguration(from string, to string, matcher func(cfg string) bool) {
func (f *Framework) WaitForNginxCustomConfiguration(from, to string, matcher func(cfg string) bool) {
//nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated
err := wait.Poll(Poll, DefaultTimeout, f.matchNginxCustomConditions(from, to, matcher))
assert.Nil(ginkgo.GinkgoT(), err, "waiting for nginx server condition/s")
}
@ -325,7 +325,7 @@ func (f *Framework) matchNginxConditions(name string, matcher func(cfg string) b
}
}
func (f *Framework) matchNginxCustomConditions(from string, to string, matcher func(cfg string) bool) wait.ConditionFunc {
func (f *Framework) matchNginxCustomConditions(from, to string, matcher func(cfg string) bool) wait.ConditionFunc {
return func() (bool, error) {
cmd := fmt.Sprintf("cat /etc/nginx/nginx.conf| awk '/%v/,/%v/'", from, to)
@ -395,7 +395,7 @@ func (f *Framework) CreateConfigMap(name string, data map[string]string) {
}
// UpdateNginxConfigMapData updates single field in ingress-nginx's nginx-ingress-controller map data
func (f *Framework) UpdateNginxConfigMapData(key string, value string) {
func (f *Framework) UpdateNginxConfigMapData(key, value string) {
config, err := f.getConfigMap("nginx-ingress-controller")
assert.Nil(ginkgo.GinkgoT(), err)
assert.NotNil(ginkgo.GinkgoT(), config, "expected a configmap but none returned")
@ -421,6 +421,7 @@ func (f *Framework) WaitForReload(fn func()) {
fn()
count := 0
//nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated
err := wait.Poll(1*time.Second, DefaultTimeout, func() (bool, error) {
reloads := getReloadCount(f.pod, f.Namespace, f.KubeClientSet)
// most of the cases reload the ingress controller
@ -441,8 +442,8 @@ func getReloadCount(pod *v1.Pod, namespace string, client kubernetes.Interface)
assert.Nil(ginkgo.GinkgoT(), err, "obtaining NGINX Pod")
reloadCount := 0
for _, e := range events.Items {
if e.Reason == "RELOAD" && e.Type == v1.EventTypeNormal {
for i := range events.Items {
if events.Items[i].Reason == "RELOAD" && events.Items[i].Type == v1.EventTypeNormal {
reloadCount++
}
}
@ -457,7 +458,7 @@ func (f *Framework) DeleteNGINXPod(grace int64) {
err := f.KubeClientSet.CoreV1().Pods(ns).Delete(context.TODO(), f.pod.GetName(), *metav1.NewDeleteOptions(grace))
assert.Nil(ginkgo.GinkgoT(), err, "deleting ingress nginx pod")
//nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated
err = wait.Poll(Poll, DefaultTimeout, func() (bool, error) {
err := f.updateIngressNGINXPod()
if err != nil || f.pod == nil {
@ -487,7 +488,7 @@ func (f *Framework) HTTPTestClientWithTLSConfig(config *tls.Config) *httpexpect.
func (f *Framework) newHTTPTestClient(config *tls.Config, setIngressURL bool) *httpexpect.HTTPRequest {
if config == nil {
config = &tls.Config{
InsecureSkipVerify: true,
InsecureSkipVerify: true, //nolint:gosec // Ignore the gosec error in testing
}
}
var baseURL string
@ -507,12 +508,13 @@ func (f *Framework) newHTTPTestClient(config *tls.Config, setIngressURL bool) *h
// WaitForNginxListening waits until NGINX starts accepting connections on a port
func (f *Framework) WaitForNginxListening(port int) {
err := waitForPodsReady(f.KubeClientSet, DefaultTimeout, 1, f.Namespace, metav1.ListOptions{
err := waitForPodsReady(f.KubeClientSet, DefaultTimeout, 1, f.Namespace, &metav1.ListOptions{
LabelSelector: "app.kubernetes.io/name=ingress-nginx",
})
assert.Nil(ginkgo.GinkgoT(), err, "waiting for ingress pods to be ready")
podIP := f.GetNginxIP()
//nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated
err = wait.Poll(500*time.Millisecond, DefaultTimeout, func() (bool, error) {
hostPort := net.JoinHostPort(podIP, fmt.Sprintf("%v", port))
conn, err := net.Dial("tcp", hostPort)
@ -529,7 +531,7 @@ func (f *Framework) WaitForNginxListening(port int) {
// WaitForPod waits for a specific Pod to be ready, using a label selector
func (f *Framework) WaitForPod(selector string, timeout time.Duration, shouldFail bool) {
err := waitForPodsReady(f.KubeClientSet, timeout, 1, f.Namespace, metav1.ListOptions{
err := waitForPodsReady(f.KubeClientSet, timeout, 1, f.Namespace, &metav1.ListOptions{
LabelSelector: selector,
})
@ -541,7 +543,7 @@ func (f *Framework) WaitForPod(selector string, timeout time.Duration, shouldFai
}
// UpdateDeployment runs the given updateFunc on the deployment and waits for it to be updated
func UpdateDeployment(kubeClientSet kubernetes.Interface, namespace string, name string, replicas int, updateFunc func(d *appsv1.Deployment) error) error {
func UpdateDeployment(kubeClientSet kubernetes.Interface, namespace, name string, replicas int, updateFunc func(d *appsv1.Deployment) error) error {
deployment, err := kubeClientSet.AppsV1().Deployments(namespace).Get(context.TODO(), name, metav1.GetOptions{})
if err != nil {
return err
@ -571,7 +573,7 @@ func UpdateDeployment(kubeClientSet kubernetes.Interface, namespace string, name
}
}
err = waitForPodsReady(kubeClientSet, DefaultTimeout, replicas, namespace, metav1.ListOptions{
err = waitForPodsReady(kubeClientSet, DefaultTimeout, replicas, namespace, &metav1.ListOptions{
LabelSelector: fields.SelectorFromSet(fields.Set(deployment.Spec.Template.ObjectMeta.Labels)).String(),
})
if err != nil {
@ -582,6 +584,7 @@ func UpdateDeployment(kubeClientSet kubernetes.Interface, namespace string, name
}
func waitForDeploymentRollout(kubeClientSet kubernetes.Interface, resource *appsv1.Deployment) error {
//nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated
return wait.Poll(Poll, 5*time.Minute, func() (bool, error) {
d, err := kubeClientSet.AppsV1().Deployments(resource.Namespace).Get(context.TODO(), resource.Name, metav1.GetOptions{})
if apierrors.IsNotFound(err) {
@ -605,7 +608,7 @@ func waitForDeploymentRollout(kubeClientSet kubernetes.Interface, resource *apps
}
// UpdateIngress runs the given updateFunc on the ingress
func UpdateIngress(kubeClientSet kubernetes.Interface, namespace string, name string, updateFunc func(d *networking.Ingress) error) error {
func UpdateIngress(kubeClientSet kubernetes.Interface, namespace, name string, updateFunc func(d *networking.Ingress) error) error {
ingress, err := kubeClientSet.NetworkingV1().Ingresses(namespace).Get(context.TODO(), name, metav1.GetOptions{})
if err != nil {
return err

View file

@ -14,6 +14,7 @@ See the License for the specific language governing permissions and
limitations under the License.
*/
//nolint:dupl // Ignore dupl errors for similar test case
package framework
import (
@ -75,7 +76,7 @@ func (f *Framework) NewNewGRPCFortuneTellerDeploymentWithReplicas(replicas int32
d := f.EnsureDeployment(deployment)
err := waitForPodsReady(f.KubeClientSet, DefaultTimeout, int(replicas), f.Namespace, metav1.ListOptions{
err := waitForPodsReady(f.KubeClientSet, DefaultTimeout, int(replicas), f.Namespace, &metav1.ListOptions{
LabelSelector: fields.SelectorFromSet(fields.Set(d.Spec.Template.ObjectMeta.Labels)).String(),
})
assert.Nil(ginkgo.GinkgoT(), err, "failed to wait for to become ready")

View file

@ -26,7 +26,7 @@ func (f *Framework) VerifyHealthz(ip string, statusCode int) error {
url := fmt.Sprintf("http://%v:10254/healthz", ip)
client := &http.Client{}
req, err := http.NewRequest(http.MethodGet, url, nil)
req, err := http.NewRequest(http.MethodGet, url, http.NoBody)
if err != nil {
return fmt.Errorf("creating GET request for URL %q failed: %v", url, err)
}

View file

@ -23,7 +23,7 @@ type Match struct {
names map[string]int
}
func makeMatch(chain chain, submatches []string, names []string) *Match {
func makeMatch(chain chain, submatches, names []string) *Match {
if submatches == nil {
submatches = []string{}
}

View file

@ -23,6 +23,8 @@ import (
"github.com/yudai/gojsondiff/formatter"
)
const unavailableMsg = " (unavailable)"
// Object provides methods to inspect attached map[string]interface{} object
// (Go representation of JSON object).
type Object struct {
@ -81,20 +83,21 @@ func diffValues(expected, actual interface{}) string {
var diff gojsondiff.Diff
if ve, ok := expected.(map[string]interface{}); ok {
switch ve := expected.(type) {
case map[string]interface{}:
if va, ok := actual.(map[string]interface{}); ok {
diff = differ.CompareObjects(ve, va)
} else {
return " (unavailable)"
return unavailableMsg
}
} else if ve, ok := expected.([]interface{}); ok {
case []interface{}:
if va, ok := actual.([]interface{}); ok {
diff = differ.CompareArrays(ve, va)
} else {
return " (unavailable)"
return unavailableMsg
}
} else {
return " (unavailable)"
default:
return unavailableMsg
}
config := formatter.AsciiFormatterConfig{
@ -104,7 +107,7 @@ func diffValues(expected, actual interface{}) string {
str, err := f.Format(diff)
if err != nil {
return " (unavailable)"
return unavailableMsg
}
return "--- expected\n+++ actual\n" + str

View file

@ -65,7 +65,7 @@ func (h *HTTPRequest) DoRequest(method, rpath string) *HTTPRequest {
var request *http.Request
uri.Path = path.Join(uri.Path, rpath)
if request, err = http.NewRequest(method, uri.String(), nil); err != nil {
if request, err = http.NewRequest(method, uri.String(), http.NoBody); err != nil {
h.chain.fail(err.Error())
}
@ -110,6 +110,7 @@ func (h *HTTPRequest) Expect() *HTTPResponse {
if err != nil {
h.chain.fail(err.Error())
}
defer response.Body.Close()
h.HTTPResponse.Response = response // set the HTTP response

View file

@ -47,7 +47,7 @@ func (f *Framework) EnsureSecret(secret *core.Secret) *core.Secret {
}
// GetConfigMap gets a ConfigMap object from the given namespace, name and returns it, throws error if it does not exist.
func (f *Framework) GetConfigMap(namespace string, name string) *core.ConfigMap {
func (f *Framework) GetConfigMap(namespace, name string) *core.ConfigMap {
cm, err := f.KubeClientSet.CoreV1().ConfigMaps(namespace).Get(context.TODO(), name, metav1.GetOptions{})
assert.Nil(ginkgo.GinkgoT(), err, "getting configmap")
assert.NotNil(ginkgo.GinkgoT(), cm, "expected a configmap but none returned")
@ -73,7 +73,7 @@ func (f *Framework) EnsureConfigMap(configMap *core.ConfigMap) *core.ConfigMap {
}
// GetIngress gets an Ingress object from the given namespace, name and returns it, throws error if it does not exists.
func (f *Framework) GetIngress(namespace string, name string) *networking.Ingress {
func (f *Framework) GetIngress(namespace, name string) *networking.Ingress {
ing, err := f.KubeClientSet.NetworkingV1().Ingresses(namespace).Get(context.TODO(), name, metav1.GetOptions{})
assert.Nil(ginkgo.GinkgoT(), err, "getting ingress")
assert.NotNil(ginkgo.GinkgoT(), ing, "expected an ingress but none returned")
@ -114,7 +114,7 @@ func (f *Framework) UpdateIngress(ingress *networking.Ingress) *networking.Ingre
}
// GetService gets a Service object from the given namespace, name and returns it, throws error if it does not exist.
func (f *Framework) GetService(namespace string, name string) *core.Service {
func (f *Framework) GetService(namespace, name string) *core.Service {
s, err := f.KubeClientSet.CoreV1().Services(namespace).Get(context.TODO(), name, metav1.GetOptions{})
assert.Nil(ginkgo.GinkgoT(), err, "getting service")
assert.NotNil(ginkgo.GinkgoT(), s, "expected a service but none returned")
@ -143,16 +143,21 @@ func (f *Framework) EnsureDeployment(deployment *appsv1.Deployment) *appsv1.Depl
}
// waitForPodsReady waits for a given amount of time until a group of Pods is running in the given namespace.
func waitForPodsReady(kubeClientSet kubernetes.Interface, timeout time.Duration, expectedReplicas int, namespace string, opts metav1.ListOptions) error {
func waitForPodsReady(kubeClientSet kubernetes.Interface, timeout time.Duration, expectedReplicas int, namespace string, opts *metav1.ListOptions) error {
//nolint:staticcheck // TODO: will replace it since wait.PollImmediate is deprecated
return wait.PollImmediate(1*time.Second, timeout, func() (bool, error) {
pl, err := kubeClientSet.CoreV1().Pods(namespace).List(context.TODO(), opts)
pl, err := kubeClientSet.CoreV1().Pods(namespace).List(context.TODO(), *opts)
if err != nil {
return false, nil
}
r := 0
for _, p := range pl.Items {
if isRunning, _ := podRunningReady(&p); isRunning {
for i := range pl.Items {
isRunning, err := podRunningReady(&pl.Items[i])
if err != nil {
Logf("error checking if pod is running : %v", err)
}
if isRunning {
r++
}
}
@ -166,9 +171,10 @@ func waitForPodsReady(kubeClientSet kubernetes.Interface, timeout time.Duration,
}
// waitForPodsDeleted waits for a given amount of time until a group of Pods are deleted in the given namespace.
func waitForPodsDeleted(kubeClientSet kubernetes.Interface, timeout time.Duration, namespace string, opts metav1.ListOptions) error {
func waitForPodsDeleted(kubeClientSet kubernetes.Interface, timeout time.Duration, namespace string, opts *metav1.ListOptions) error {
//nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated
return wait.Poll(Poll, timeout, func() (bool, error) {
pl, err := kubeClientSet.CoreV1().Pods(namespace).List(context.TODO(), opts)
pl, err := kubeClientSet.CoreV1().Pods(namespace).List(context.TODO(), *opts)
if err != nil {
return false, nil
}
@ -186,7 +192,7 @@ func WaitForEndpoints(kubeClientSet kubernetes.Interface, timeout time.Duration,
if expectedEndpoints == 0 {
return nil
}
//nolint:staticcheck // TODO: will replace it since wait.PollImmediate is deprecated
return wait.PollImmediate(Poll, timeout, func() (bool, error) {
endpoint, err := kubeClientSet.CoreV1().Endpoints(ns).Get(context.TODO(), name, metav1.GetOptions{})
if k8sErrors.IsNotFound(err) {
@ -248,6 +254,7 @@ func isPodReady(p *core.Pod) bool {
// getIngressNGINXPod returns the ingress controller running pod
func getIngressNGINXPod(ns string, kubeClientSet kubernetes.Interface) (*core.Pod, error) {
var pod *core.Pod
//nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated
err := wait.Poll(1*time.Second, DefaultTimeout, func() (bool, error) {
l, err := kubeClientSet.CoreV1().Pods(ns).List(context.TODO(), metav1.ListOptions{
LabelSelector: "app.kubernetes.io/name=ingress-nginx",
@ -256,15 +263,16 @@ func getIngressNGINXPod(ns string, kubeClientSet kubernetes.Interface) (*core.Po
return false, nil
}
for _, p := range l.Items {
for i := range l.Items {
p := &l.Items[i]
if strings.HasPrefix(p.GetName(), "nginx-ingress-controller") {
isRunning, err := podRunningReady(&p)
isRunning, err := podRunningReady(p)
if err != nil {
continue
}
if isRunning {
pod = &p
pod = p
return true, nil
}
}
@ -273,6 +281,7 @@ func getIngressNGINXPod(ns string, kubeClientSet kubernetes.Interface) (*core.Po
return false, nil
})
if err != nil {
//nolint:staticcheck // TODO: will replace it since wait.ErrWaitTimeout is deprecated
if err == wait.ErrWaitTimeout {
return nil, fmt.Errorf("timeout waiting at least one ingress-nginx pod running in namespace %v", ns)
}
@ -285,7 +294,7 @@ func getIngressNGINXPod(ns string, kubeClientSet kubernetes.Interface) (*core.Po
func createDeploymentWithRetries(c kubernetes.Interface, namespace string, obj *appsv1.Deployment) error {
if obj == nil {
return fmt.Errorf("Object provided to create is empty")
return fmt.Errorf("object provided to create is empty")
}
createFunc := func() (bool, error) {
_, err := c.AppsV1().Deployments(namespace).Create(context.TODO(), obj, metav1.CreateOptions{})
@ -298,7 +307,7 @@ func createDeploymentWithRetries(c kubernetes.Interface, namespace string, obj *
if isRetryableAPIError(err) {
return false, nil
}
return false, fmt.Errorf("Failed to create object with non-retriable error: %v", err)
return false, fmt.Errorf("failed to create object with non-retriable error: %v", err)
}
return retryWithExponentialBackOff(createFunc)
@ -306,7 +315,7 @@ func createDeploymentWithRetries(c kubernetes.Interface, namespace string, obj *
func createSecretWithRetries(c kubernetes.Interface, namespace string, obj *core.Secret) error {
if obj == nil {
return fmt.Errorf("Object provided to create is empty")
return fmt.Errorf("object provided to create is empty")
}
createFunc := func() (bool, error) {
_, err := c.CoreV1().Secrets(namespace).Create(context.TODO(), obj, metav1.CreateOptions{})
@ -319,14 +328,14 @@ func createSecretWithRetries(c kubernetes.Interface, namespace string, obj *core
if isRetryableAPIError(err) {
return false, nil
}
return false, fmt.Errorf("Failed to create object with non-retriable error: %v", err)
return false, fmt.Errorf("failed to create object with non-retriable error: %v", err)
}
return retryWithExponentialBackOff(createFunc)
}
func createServiceWithRetries(c kubernetes.Interface, namespace string, obj *core.Service) error {
if obj == nil {
return fmt.Errorf("Object provided to create is empty")
return fmt.Errorf("object provided to create is empty")
}
createFunc := func() (bool, error) {
_, err := c.CoreV1().Services(namespace).Create(context.TODO(), obj, metav1.CreateOptions{})
@ -339,7 +348,7 @@ func createServiceWithRetries(c kubernetes.Interface, namespace string, obj *cor
if isRetryableAPIError(err) {
return false, nil
}
return false, fmt.Errorf("Failed to create object with non-retriable error: %v", err)
return false, fmt.Errorf("failed to create object with non-retriable error: %v", err)
}
return retryWithExponentialBackOff(createFunc)
@ -347,7 +356,7 @@ func createServiceWithRetries(c kubernetes.Interface, namespace string, obj *cor
func createIngressWithRetries(c kubernetes.Interface, namespace string, obj *networking.Ingress) error {
if obj == nil {
return fmt.Errorf("Object provided to create is empty")
return fmt.Errorf("object provided to create is empty")
}
createFunc := func() (bool, error) {
_, err := c.NetworkingV1().Ingresses(namespace).Create(context.TODO(), obj, metav1.CreateOptions{})
@ -360,7 +369,7 @@ func createIngressWithRetries(c kubernetes.Interface, namespace string, obj *net
if isRetryableAPIError(err) {
return false, nil
}
return false, fmt.Errorf("Failed to create object with non-retriable error: %v", err)
return false, fmt.Errorf("failed to create object with non-retriable error: %v", err)
}
return retryWithExponentialBackOff(createFunc)
@ -368,7 +377,7 @@ func createIngressWithRetries(c kubernetes.Interface, namespace string, obj *net
func updateIngressWithRetries(c kubernetes.Interface, namespace string, obj *networking.Ingress) error {
if obj == nil {
return fmt.Errorf("Object provided to create is empty")
return fmt.Errorf("object provided to create is empty")
}
updateFunc := func() (bool, error) {
_, err := c.NetworkingV1().Ingresses(namespace).Update(context.TODO(), obj, metav1.UpdateOptions{})
@ -378,7 +387,7 @@ func updateIngressWithRetries(c kubernetes.Interface, namespace string, obj *net
if isRetryableAPIError(err) {
return false, nil
}
return false, fmt.Errorf("Failed to update object with non-retriable error: %v", err)
return false, fmt.Errorf("failed to update object with non-retriable error: %v", err)
}
return retryWithExponentialBackOff(updateFunc)

View file

@ -29,7 +29,7 @@ func (f *Framework) GetMetric(metricName, ip string) (*dto.MetricFamily, error)
url := fmt.Sprintf("http://%v:10254/metrics", ip)
client := &http.Client{}
req, err := http.NewRequest(http.MethodGet, url, nil)
req, err := http.NewRequest(http.MethodGet, url, http.NoBody)
if err != nil {
return nil, fmt.Errorf("creating GET request for URL %q failed: %v", url, err)
}
@ -44,7 +44,6 @@ func (f *Framework) GetMetric(metricName, ip string) (*dto.MetricFamily, error)
var parser expfmt.TextParser
metrics, err := parser.TextToMetricFamilies(resp.Body)
if err != nil {
return nil, fmt.Errorf("reading text format failed: %v", err)
}

View file

@ -93,8 +93,8 @@ func CreateIngressTLSSecret(client kubernetes.Interface, hosts []string, secretN
// CreateIngressMASecret creates or updates a Secret containing a Mutual Auth
// certificate-chain for the given Ingress and returns a TLS configuration suitable
// for HTTP clients to use against that particular Ingress.
func CreateIngressMASecret(client kubernetes.Interface, host string, secretName, namespace string) (*tls.Config, error) {
if len(host) == 0 {
func CreateIngressMASecret(client kubernetes.Interface, host, secretName, namespace string) (*tls.Config, error) {
if host == "" {
return nil, fmt.Errorf("requires a non-empty host")
}
@ -138,12 +138,13 @@ func CreateIngressMASecret(client kubernetes.Interface, host string, secretName,
return &tls.Config{
ServerName: host,
Certificates: []tls.Certificate{clientPair},
InsecureSkipVerify: true,
InsecureSkipVerify: true, //nolint:gosec // Ignore the gosec error in testing
}, nil
}
// WaitForTLS waits until the TLS handshake with a given server completes successfully.
func WaitForTLS(url string, tlsConfig *tls.Config) {
//nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated
err := wait.Poll(Poll, DefaultTimeout, matchTLSServerName(url, tlsConfig))
assert.Nil(ginkgo.GinkgoT(), err, "waiting for TLS configuration in URL %s", url)
}
@ -160,7 +161,6 @@ func generateRSACert(host string, isCA bool, keyOut, certOut io.Writer) error {
serialNumberLimit := new(big.Int).Lsh(big.NewInt(1), 128)
serialNumber, err := rand.Int(rand.Reader, serialNumberLimit)
if err != nil {
return fmt.Errorf("failed to generate serial number: %s", err)
}
@ -329,7 +329,7 @@ func tlsConfig(serverName string, pemCA []byte) (*tls.Config, error) {
if !rootCAPool.AppendCertsFromPEM(pemCA) {
return nil, fmt.Errorf("error creating CA certificate pool (%s)", serverName)
}
return &tls.Config{
return &tls.Config{ //nolint:gosec // Ignore the gosec error in testing
ServerName: serverName,
RootCAs: rootCAPool,
}, nil

View file

@ -23,7 +23,7 @@ import (
// TestContextType describes the client context to use in communications with the Kubernetes API.
type TestContextType struct {
KubeHost string
//KubeConfig string
// KubeConfig string
KubeContext string
}
@ -33,7 +33,6 @@ var TestContext TestContextType
// registerCommonFlags registers flags common to all e2e test suites.
func registerCommonFlags() {
flag.StringVar(&TestContext.KubeHost, "kubernetes-host", "http://127.0.0.1:8080", "The kubernetes host, or apiserver, to connect to")
//flag.StringVar(&TestContext.KubeConfig, "kubernetes-config", os.Getenv(clientcmd.RecommendedConfigPathEnvVar), "Path to config containing embedded authinfo for kubernetes. Default value is from environment variable "+clientcmd.RecommendedConfigPathEnvVar)
flag.StringVar(&TestContext.KubeContext, "kubernetes-context", "", "config context to use for kubernetes. If unset, will use value from 'current-context'")
}

View file

@ -49,24 +49,24 @@ func nowStamp() string {
return time.Now().Format(time.StampMilli)
}
func log(level string, format string, args ...interface{}) {
func logf(level, format string, args ...interface{}) {
fmt.Fprintf(ginkgo.GinkgoWriter, nowStamp()+": "+level+": "+format+"\n", args...)
}
// Logf logs to the INFO logs.
func Logf(format string, args ...interface{}) {
log("INFO", format, args...)
logf("INFO", format, args...)
}
// Failf logs to the INFO logs and fails the test.
func Failf(format string, args ...interface{}) {
msg := fmt.Sprintf(format, args...)
log("INFO", msg)
logf("INFO", msg)
ginkgo.Fail(nowStamp()+": "+msg, 1)
}
// RestclientConfig deserializes the contents of a kubeconfig file into a Config object.
func RestclientConfig(config, context string) (*api.Config, error) {
func RestclientConfig(config, newContext string) (*api.Config, error) {
Logf(">>> config: %s\n", config)
if config == "" {
return nil, fmt.Errorf("config file must be specified to load client config")
@ -75,9 +75,9 @@ func RestclientConfig(config, context string) (*api.Config, error) {
if err != nil {
return nil, fmt.Errorf("error loading config: %v", err.Error())
}
if context != "" {
Logf(">>> context: %s\n", context)
c.CurrentContext = context
if newContext != "" {
Logf(">>> context: %s\n", newContext)
c.CurrentContext = newContext
}
return c, nil
}
@ -98,6 +98,7 @@ func createNamespace(baseName string, labels map[string]string, c kubernetes.Int
var got *corev1.Namespace
var err error
//nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated
err = wait.Poll(Poll, DefaultTimeout, func() (bool, error) {
got, err = c.CoreV1().Namespaces().Create(context.TODO(), ns, metav1.CreateOptions{})
if err != nil {
@ -114,13 +115,11 @@ func createNamespace(baseName string, labels map[string]string, c kubernetes.Int
// CreateKubeNamespace creates a new namespace in the cluster
func CreateKubeNamespace(baseName string, c kubernetes.Interface) (string, error) {
return createNamespace(baseName, nil, c)
}
// CreateKubeNamespaceWithLabel creates a new namespace with given labels in the cluster
func CreateKubeNamespaceWithLabel(baseName string, labels map[string]string, c kubernetes.Interface) (string, error) {
return createNamespace(baseName, labels, c)
}
@ -150,7 +149,7 @@ func CreateIngressClass(namespace string, c kubernetes.Interface) (string, error
},
}, metav1.CreateOptions{})
if err != nil {
return "", fmt.Errorf("Unexpected error creating IngressClass %s: %v", icname, err)
return "", fmt.Errorf("unexpected error creating IngressClass %s: %v", icname, err)
}
_, err = c.RbacV1().ClusterRoles().Create(context.TODO(), &rbacv1.ClusterRole{
@ -162,7 +161,7 @@ func CreateIngressClass(namespace string, c kubernetes.Interface) (string, error
}},
}, metav1.CreateOptions{})
if err != nil {
return "", fmt.Errorf("Unexpected error creating IngressClass ClusterRole %s: %v", icname, err)
return "", fmt.Errorf("unexpected error creating IngressClass ClusterRole %s: %v", icname, err)
}
_, err = c.RbacV1().ClusterRoleBindings().Create(context.TODO(), &rbacv1.ClusterRoleBinding{
@ -184,7 +183,7 @@ func CreateIngressClass(namespace string, c kubernetes.Interface) (string, error
},
}, metav1.CreateOptions{})
if err != nil {
return "", fmt.Errorf("Unexpected error creating IngressClass ClusterRoleBinding %s: %v", icname, err)
return "", fmt.Errorf("unexpected error creating IngressClass ClusterRoleBinding %s: %v", icname, err)
}
return ic.Name, nil
}
@ -200,16 +199,16 @@ func deleteIngressClass(c kubernetes.Interface, ingressclass string) error {
}
err = c.NetworkingV1().IngressClasses().Delete(context.TODO(), ingressclass, deleteOptions)
if err != nil {
return fmt.Errorf("Unexpected error deleting IngressClass %s: %v", ingressclass, err)
return fmt.Errorf("unexpected error deleting IngressClass %s: %v", ingressclass, err)
}
err = c.RbacV1().ClusterRoleBindings().Delete(context.TODO(), ingressclass, deleteOptions)
if err != nil {
return fmt.Errorf("Unexpected error deleting IngressClass ClusterRoleBinding %s: %v", ingressclass, err)
return fmt.Errorf("unexpected error deleting IngressClass ClusterRoleBinding %s: %v", ingressclass, err)
}
err = c.RbacV1().ClusterRoles().Delete(context.TODO(), ingressclass, deleteOptions)
if err != nil {
return fmt.Errorf("Unexpected error deleting IngressClass ClusterRole %s: %v", ingressclass, err)
return fmt.Errorf("unexpected error deleting IngressClass ClusterRole %s: %v", ingressclass, err)
}
return nil
@ -223,6 +222,7 @@ func GetIngressClassName(namespace string) *string {
// WaitForKubeNamespaceNotExist waits until a namespaces is not present in the cluster
func WaitForKubeNamespaceNotExist(c kubernetes.Interface, namespace string) error {
//nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated
return wait.Poll(Poll, DefaultTimeout, namespaceNotExist(c, namespace))
}
@ -241,6 +241,7 @@ func namespaceNotExist(c kubernetes.Interface, namespace string) wait.ConditionF
// WaitForNoPodsInNamespace waits until there are no pods running in a namespace
func WaitForNoPodsInNamespace(c kubernetes.Interface, namespace string) error {
//nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated
return wait.Poll(Poll, DefaultTimeout, noPodsInNamespace(c, namespace))
}
@ -267,15 +268,17 @@ func WaitForPodRunningInNamespace(c kubernetes.Interface, pod *corev1.Pod) error
if pod.Status.Phase == corev1.PodRunning {
return nil
}
return waitTimeoutForPodRunningInNamespace(c, pod.Name, pod.Namespace, DefaultTimeout)
return waitTimeoutForPodRunningInNamespace(c, pod.Name, pod.Namespace)
}
func waitTimeoutForPodRunningInNamespace(c kubernetes.Interface, podName, namespace string, timeout time.Duration) error {
func waitTimeoutForPodRunningInNamespace(c kubernetes.Interface, podName, namespace string) error {
//nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated
return wait.Poll(Poll, DefaultTimeout, podRunning(c, podName, namespace))
}
// WaitForSecretInNamespace waits a default amount of time for the specified secret is present in a particular namespace
func WaitForSecretInNamespace(c kubernetes.Interface, namespace, name string) error {
//nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated
return wait.Poll(Poll, DefaultTimeout, secretInNamespace(c, namespace, name))
}
@ -298,6 +301,7 @@ func secretInNamespace(c kubernetes.Interface, namespace, name string) wait.Cond
// WaitForFileInFS waits a default amount of time for the specified file is present in the filesystem
func WaitForFileInFS(file string) error {
//nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated
return wait.Poll(Poll, DefaultTimeout, fileInFS(file))
}
@ -322,6 +326,7 @@ func fileInFS(file string) wait.ConditionFunc {
// WaitForNoIngressInNamespace waits until there is no ingress object in a particular namespace
func WaitForNoIngressInNamespace(c kubernetes.Interface, namespace, name string) error {
//nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated
return wait.Poll(Poll, DefaultTimeout, noIngressInNamespace(c, namespace, name))
}
@ -344,6 +349,7 @@ func noIngressInNamespace(c kubernetes.Interface, namespace, name string) wait.C
// WaitForIngressInNamespace waits until a particular ingress object exists namespace
func WaitForIngressInNamespace(c kubernetes.Interface, namespace, name string) error {
//nolint:staticcheck // TODO: will replace it since wait.Poll is deprecated
return wait.Poll(Poll, DefaultTimeout, ingressInNamespace(c, namespace, name))
}