sigs.k8s.io/cluster-api-provider-azure@v1.14.3/test/e2e/kubernetes/pod/pod.go (about)

     1  //go:build e2e
     2  // +build e2e
     3  
     4  /*
     5  Copyright 2020 The Kubernetes Authors.
     6  
     7  Licensed under the Apache License, Version 2.0 (the "License");
     8  you may not use this file except in compliance with the License.
     9  You may obtain a copy of the License at
    10  
    11      http://www.apache.org/licenses/LICENSE-2.0
    12  
    13  Unless required by applicable law or agreed to in writing, software
    14  distributed under the License is distributed on an "AS IS" BASIS,
    15  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    16  See the License for the specific language governing permissions and
    17  limitations under the License.
    18  */
    19  
    20  package pod
    21  
    22  import (
    23  	"context"
    24  	"os"
    25  	"time"
    26  
    27  	. "github.com/onsi/gomega"
    28  	corev1 "k8s.io/api/core/v1"
    29  	"k8s.io/client-go/kubernetes"
    30  	restclient "k8s.io/client-go/rest"
    31  	"k8s.io/client-go/tools/remotecommand"
    32  	"k8s.io/kubectl/pkg/scheme"
    33  )
    34  
    35  const (
    36  	podExecOperationTimeout             = 3 * time.Minute
    37  	podExecOperationSleepBetweenRetries = 3 * time.Second
    38  )
    39  
    40  func Exec(clientset *kubernetes.Clientset, config *restclient.Config, pod corev1.Pod, command []string, testSuccess bool) error {
    41  	req := clientset.CoreV1().RESTClient().Post().Resource("pods").Name(pod.GetName()).
    42  		Namespace(pod.GetNamespace()).SubResource("exec")
    43  	option := &corev1.PodExecOptions{
    44  		Command: command,
    45  		Stdin:   false,
    46  		Stdout:  true,
    47  		Stderr:  true,
    48  		TTY:     true,
    49  	}
    50  	if !testSuccess {
    51  		option.Stderr = false
    52  	}
    53  	req.VersionedParams(
    54  		option,
    55  		scheme.ParameterCodec,
    56  	)
    57  	exec, err := remotecommand.NewSPDYExecutor(config, "POST", req.URL())
    58  	if err != nil {
    59  		return err
    60  	}
    61  	Eventually(func(g Gomega) {
    62  		err = exec.StreamWithContext(context.Background(), remotecommand.StreamOptions{
    63  			Stdout: os.Stdout,
    64  			Stderr: os.Stderr,
    65  		})
    66  		if testSuccess {
    67  			g.Expect(err).NotTo(HaveOccurred())
    68  		} else {
    69  			// If we get here we are validating that the command returned an expected error
    70  			g.Expect(err).To(HaveOccurred())
    71  		}
    72  	}, podExecOperationTimeout, podExecOperationSleepBetweenRetries).Should(Succeed())
    73  
    74  	return nil
    75  }