github.com/looshlee/beatles@v0.0.0-20220727174639-742810ab631c/pkg/command/exec/exec.go (about) 1 // Copyright 2018 Authors of Cilium 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package exec 16 17 import ( 18 "bufio" 19 "bytes" 20 "context" 21 "fmt" 22 "os/exec" 23 "strings" 24 "time" 25 26 "github.com/sirupsen/logrus" 27 ) 28 29 // combinedOutput is the core implementation of catching deadline exceeded 30 // options and logging errors, with an optional set of filtered outputs. 31 func combinedOutput(ctx context.Context, cmd *exec.Cmd, filters []string, scopedLog *logrus.Entry, verbose bool) ([]byte, error) { 32 out, err := cmd.CombinedOutput() 33 if ctx.Err() != nil { 34 scopedLog.WithError(err).WithField("cmd", cmd.Args).Error("Command execution failed") 35 return nil, fmt.Errorf("Command execution failed for %s: %s", cmd.Args, ctx.Err()) 36 } 37 if err != nil { 38 if verbose { 39 scopedLog.WithError(err).WithField("cmd", cmd.Args).Error("Command execution failed") 40 41 scanner := bufio.NewScanner(bytes.NewReader(out)) 42 scan: 43 for scanner.Scan() { 44 text := scanner.Text() 45 for _, filter := range filters { 46 if strings.Contains(text, filter) { 47 continue scan 48 } 49 } 50 scopedLog.Warn(text) 51 } 52 } 53 } 54 return out, err 55 } 56 57 // Cmd wraps exec.Cmd with a context to provide convenient execution of a 58 // command with nice checking of the context timeout in the form: 59 // 60 // err := exec.Prog().WithTimeout(5*time.Second, myprog, myargs...).CombinedOutput(log, verbose) 61 type Cmd struct { 62 *exec.Cmd 63 ctx context.Context 64 cancelFn func() 65 66 // filters is a slice of strings that should be omitted from logging. 67 filters []string 68 } 69 70 // CommandContext wraps exec.CommandContext to allow this package to be used as 71 // a drop-in replacement for the standard exec library. 72 func CommandContext(ctx context.Context, prog string, args ...string) *Cmd { 73 return &Cmd{ 74 Cmd: exec.CommandContext(ctx, prog, args...), 75 ctx: ctx, 76 } 77 } 78 79 // WithTimeout creates a Cmd with a context that times out after the specified 80 // duration. 81 func WithTimeout(timeout time.Duration, prog string, args ...string) *Cmd { 82 ctx, cancel := context.WithTimeout(context.Background(), timeout) 83 cmd := CommandContext(ctx, prog, args...) 84 cmd.cancelFn = cancel 85 return cmd 86 } 87 88 // WithCancel creates a Cmd with a context that can be cancelled by calling the 89 // resulting Cancel() function. 90 func WithCancel(ctx context.Context, prog string, args ...string) (*Cmd, context.CancelFunc) { 91 newCtx, cancel := context.WithCancel(ctx) 92 cmd := CommandContext(newCtx, prog, args...) 93 return cmd, cancel 94 } 95 96 // WithFilters modifies the specified command to filter any output lines from 97 // logs if they contain any of the substrings specified as arguments to this 98 // function. 99 func (c *Cmd) WithFilters(filters ...string) *Cmd { 100 c.filters = append(c.filters, filters...) 101 return c 102 } 103 104 // CombinedOutput runs the command and returns its combined standard output and 105 // standard error. Unlike the standard library, if the context is exceeded, it 106 // will return an error indicating so. 107 // 108 // Logs any errors that occur to the specified logger. 109 func (c *Cmd) CombinedOutput(scopedLog *logrus.Entry, verbose bool) ([]byte, error) { 110 out, err := combinedOutput(c.ctx, c.Cmd, c.filters, scopedLog, verbose) 111 if c.cancelFn != nil { 112 c.cancelFn() 113 } 114 return out, err 115 }