k8s.io/perf-tests/clusterloader2@v0.0.0-20240304094227-64bdb12da87e/pkg/util/ssh.go (about) 1 /* 2 Copyright 2019 The Kubernetes 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 util 18 19 import ( 20 "fmt" 21 "io" 22 "os/exec" 23 24 "k8s.io/api/core/v1" 25 "k8s.io/klog/v2" 26 ) 27 28 // SSHExecutor interface can run commands in cluster nodes via SSH 29 type SSHExecutor interface { 30 Exec(command string, node *v1.Node, stdin io.Reader) error 31 } 32 33 // GCloudSSHExecutor runs commands in GCloud cluster nodes 34 type GCloudSSHExecutor struct{} 35 36 // Exec executes command on a given node with stdin provided. 37 // If stdin is nil, the process reads from null device. 38 func (e *GCloudSSHExecutor) Exec(command string, node *v1.Node, stdin io.Reader) error { 39 zone, ok := node.Labels["topology.kubernetes.io/zone"] 40 if !ok { 41 // Fallback to old label to make it work for old k8s versions. 42 zone, ok = node.Labels["failure-domain.beta.kubernetes.io/zone"] 43 if !ok { 44 return fmt.Errorf("unknown zone for %q node: no topology-related labels", node.Name) 45 } 46 } 47 cmd := exec.Command("gcloud", "compute", "ssh", "--zone", zone, "--command", command, node.Name) 48 cmd.Stdin = stdin 49 output, err := cmd.CombinedOutput() 50 klog.V(2).Infof("ssh to %q finished with %q: %v", node.Name, string(output), err) 51 return err 52 }