k8s.io/perf-tests/clusterloader2@v0.0.0-20240304094227-64bdb12da87e/pkg/measurement/common/exec.go (about) 1 /* 2 Copyright 2020 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 common 18 19 import ( 20 "context" 21 "fmt" 22 "os" 23 "os/exec" 24 "time" 25 26 "k8s.io/klog/v2" 27 28 "k8s.io/perf-tests/clusterloader2/pkg/measurement" 29 "k8s.io/perf-tests/clusterloader2/pkg/util" 30 ) 31 32 const ( 33 execName = "Exec" 34 defaultTimeoutString = "1h" 35 ) 36 37 func init() { 38 if err := measurement.Register(execName, createExecMeasurement); err != nil { 39 klog.Fatalf("Cannot register %s: %v", execName, err) 40 } 41 } 42 43 func createExecMeasurement() measurement.Measurement { 44 return &execMeasurement{} 45 } 46 47 type execMeasurement struct{} 48 49 func (e *execMeasurement) Execute(config *measurement.Config) ([]measurement.Summary, error) { 50 timeoutStr, err := util.GetStringOrDefault(config.Params, "timeout", defaultTimeoutString) 51 if err != nil { 52 return nil, err 53 } 54 timeout, err := time.ParseDuration(timeoutStr) 55 if err != nil { 56 return nil, err 57 } 58 command, err := util.GetStringArray(config.Params, "command") 59 if err != nil { 60 return nil, fmt.Errorf("error parsing command: %v", err) 61 } 62 if len(command) == 0 { 63 return nil, fmt.Errorf("command is a required argument. Got empty slice instead") 64 } 65 66 // Make a copy of command, to avoid overriding a slice we don't own. 67 command = append([]string{}, command...) 68 for i := range command { 69 command[i] = os.ExpandEnv(command[i]) 70 } 71 klog.V(2).Infof("Running %v with timeout %v", command, timeout) 72 ctx, cancel := context.WithTimeout(context.Background(), timeout) 73 defer cancel() 74 cmd := exec.CommandContext(ctx, command[0], command[1:]...) 75 out, err := cmd.CombinedOutput() 76 klog.V(2).Infof("Exec command output: %v", string(out)) 77 if err != nil { 78 return nil, fmt.Errorf("command %v failed: %v", command, err) 79 } 80 return nil, nil 81 } 82 83 func (e *execMeasurement) Dispose() {} 84 85 func (e *execMeasurement) String() string { return execName }