knative.dev/pkg@v0.0.0-20260602142205-ac97e43f6622/test/monitoring/monitoring.go (about) 1 /* 2 Copyright 2019 The Knative Authors 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package monitoring 18 19 import ( 20 "context" 21 "fmt" 22 "net" 23 "os" 24 "os/exec" 25 "time" 26 27 v1 "k8s.io/api/core/v1" 28 metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" 29 "k8s.io/client-go/kubernetes" 30 "knative.dev/pkg/test/logging" 31 ) 32 33 // CheckPortAvailability checks to see if the port is available on the machine. 34 func CheckPortAvailability(port int) error { 35 server, err := net.Listen("tcp", fmt.Sprint(":", port)) 36 if err != nil { 37 // Port is likely taken 38 return err 39 } 40 return server.Close() 41 } 42 43 // GetPods retrieves the current existing podlist for the app in monitoring namespace 44 // This uses app=<app> as labelselector for selecting pods 45 func GetPods(ctx context.Context, kubeClientset kubernetes.Interface, app, namespace string) (*v1.PodList, error) { 46 pods, err := kubeClientset.CoreV1().Pods(namespace).List(ctx, metav1.ListOptions{LabelSelector: "app=" + app}) 47 if err == nil && len(pods.Items) == 0 { 48 err = fmt.Errorf("pod %s not found on the cluster. Ensure monitoring is switched on for your Knative Setup", app) 49 } 50 return pods, err 51 } 52 53 // Cleanup will clean the background process used for port forwarding 54 func Cleanup(pid int) error { 55 ps := os.Process{Pid: pid} 56 if err := ps.Kill(); err != nil { 57 return err 58 } 59 60 errCh := make(chan error) 61 go func() { 62 _, err := ps.Wait() 63 errCh <- err 64 }() 65 66 select { 67 case err := <-errCh: 68 return err 69 case <-time.After(30 * time.Second): 70 return fmt.Errorf("timed out waiting for process %d to exit", pid) 71 } 72 } 73 74 // PortForward sets up local port forward to the pod specified by the "app" label in the given namespace 75 func PortForward(logf logging.FormatLogger, podList *v1.PodList, localPort, remotePort int, namespace string) (int, error) { 76 podName := podList.Items[0].Name 77 cmd := exec.Command("kubectl", "port-forward", podName, fmt.Sprintf("%d:%d", localPort, remotePort), "-n", namespace) 78 if err := cmd.Start(); err != nil { 79 return 0, fmt.Errorf("failed to port forward: %w", err) 80 } 81 82 logf("Running %s port-forward in background, pid = %d", podName, cmd.Process.Pid) 83 return cmd.Process.Pid, nil 84 }