2016-11-05 17:09:05 -07:00
/*
Copyright 2016 The Rook Authors. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
2016-10-12 09:04:07 -07:00
package exec
2016-09-15 08:00:43 -07:00
import (
"bufio"
2017-09-14 09:40:34 -07:00
"bytes"
2019-05-02 13:16:28 -07:00
"context"
2017-06-15 18:40:18 -07:00
"fmt"
2016-09-15 08:00:43 -07:00
"io"
2017-06-15 18:40:18 -07:00
"io/ioutil"
2017-03-23 17:14:05 -07:00
"os"
2016-09-15 08:00:43 -07:00
"os/exec"
"strings"
2017-09-14 09:40:34 -07:00
"time"
2016-11-11 17:37:08 -08:00
"github.com/coreos/pkg/capnslog"
2016-09-15 08:00:43 -07:00
)
type Executor interface {
2020-03-17 18:23:16 -06:00
ExecuteCommand ( suppressLogOutput bool , command string , arg ... string ) error
ExecuteCommandWithOutput ( suppressLogCommand bool , command string , arg ... string ) ( string , error )
ExecuteCommandWithCombinedOutput ( suppressLogOutput bool , command string , arg ... string ) ( string , error )
ExecuteCommandWithOutputFile ( suppressLogOutput bool , command , outfileArg string , arg ... string ) ( string , error )
ExecuteCommandWithOutputFileTimeout ( suppressLogOutput bool , timeout time . Duration , command , outfileArg string , arg ... string ) ( string , error )
ExecuteCommandWithTimeout ( suppressLogOutput bool , timeout time . Duration , command string , arg ... string ) ( string , error )
2016-09-15 08:00:43 -07:00
}
type CommandExecutor struct {
}
2016-10-28 17:07:31 -07:00
// Start a process and wait for its completion
2020-03-17 18:23:16 -06:00
func ( * CommandExecutor ) ExecuteCommand ( suppressLogOutput bool , command string , arg ... string ) error {
2020-03-17 15:58:04 -06:00
cmd , stdout , stderr , err := startCommand ( suppressLogOutput , command , arg ... )
2016-10-28 17:07:31 -07:00
if err != nil {
2020-03-17 18:23:16 -06:00
return err
2016-09-15 08:00:43 -07:00
}
2020-03-17 18:23:16 -06:00
logOutput ( suppressLogOutput , stdout , stderr )
2016-09-15 08:00:43 -07:00
if err := cmd . Wait (); err != nil {
2020-03-17 18:23:16 -06:00
return err
2016-09-15 08:00:43 -07:00
}
return nil
}
2017-09-14 09:40:34 -07:00
// ExecuteCommandWithTimeout starts a process and wait for its completion with timeout.
2020-03-17 18:23:16 -06:00
func ( * CommandExecutor ) ExecuteCommandWithTimeout ( suppressLogOutput bool , timeout time . Duration , command string , arg ... string ) ( string , error ) {
2020-03-17 15:58:04 -06:00
logCommand ( suppressLogOutput , command , arg ... )
2017-09-14 09:40:34 -07:00
cmd := exec . Command ( command , arg ... )
var b bytes . Buffer
cmd . Stdout = & b
cmd . Stderr = & b
if err := cmd . Start (); err != nil {
2020-03-17 18:23:16 -06:00
return "" , err
2017-09-14 09:40:34 -07:00
}
done := make ( chan error , 1 )
go func () {
done <- cmd . Wait ()
}()
2020-03-17 15:58:04 -06:00
interruptSent := false
2017-09-14 09:40:34 -07:00
for {
select {
case <- time . After ( timeout ):
2020-03-17 15:58:04 -06:00
if interruptSent {
2020-03-17 18:23:16 -06:00
logger . Infof ( "timeout waiting for process %s to return after interrupt signal was sent. Sending kill signal to the process" , command )
2017-09-14 09:40:34 -07:00
var e error
if err := cmd . Process . Kill (); err != nil {
logger . Errorf ( "Failed to kill process %s: %+v" , command , err )
2020-03-17 18:23:16 -06:00
e = fmt . Errorf ( "timeout waiting for the command %s to return after interrupt signal was sent. Tried to kill the process but that failed: %+v" , command , err )
2017-09-14 09:40:34 -07:00
} else {
2020-03-17 18:23:16 -06:00
e = fmt . Errorf ( "timeout waiting for the command %s to return" , command )
2017-09-14 09:40:34 -07:00
}
2020-03-17 18:23:16 -06:00
return strings . TrimSpace ( b . String ()), e
2017-09-14 09:40:34 -07:00
}
2020-03-17 18:23:16 -06:00
logger . Infof ( "timeout waiting for process %s to return. Sending interrupt signal to the process" , command )
2017-09-14 09:40:34 -07:00
if err := cmd . Process . Signal ( os . Interrupt ); err != nil {
logger . Errorf ( "Failed to send interrupt signal to process %s: %+v" , command , err )
// kill signal will be sent next loop
}
2020-03-17 15:58:04 -06:00
interruptSent = true
2017-09-14 09:40:34 -07:00
case err := <- done :
if err != nil {
2020-03-17 18:23:16 -06:00
return strings . TrimSpace ( b . String ()), err
2017-09-14 09:40:34 -07:00
}
2020-03-17 15:58:04 -06:00
if interruptSent {
2020-03-17 18:23:16 -06:00
return strings . TrimSpace ( b . String ()), fmt . Errorf ( "timeout waiting for the command %s to return" , command )
2017-09-14 09:40:34 -07:00
}
2019-11-07 19:37:32 +08:00
return strings . TrimSpace ( b . String ()), nil
2017-09-14 09:40:34 -07:00
}
}
}
2020-03-17 18:23:16 -06:00
func ( * CommandExecutor ) ExecuteCommandWithOutput ( suppressLogOutput bool , command string , arg ... string ) ( string , error ) {
2020-03-17 15:58:04 -06:00
logCommand ( suppressLogOutput , command , arg ... )
2016-10-28 17:07:31 -07:00
cmd := exec . Command ( command , arg ... )
2020-03-17 18:23:16 -06:00
return runCommandWithOutput ( cmd , false )
2017-02-03 13:16:36 -08:00
}
2020-03-17 18:23:16 -06:00
func ( * CommandExecutor ) ExecuteCommandWithCombinedOutput ( suppressLogOutput bool , command string , arg ... string ) ( string , error ) {
2020-03-17 15:58:04 -06:00
logCommand ( suppressLogOutput , command , arg ... )
2017-02-03 13:16:36 -08:00
cmd := exec . Command ( command , arg ... )
2020-03-17 18:23:16 -06:00
return runCommandWithOutput ( cmd , true )
2016-09-15 08:00:43 -07:00
}
2019-05-02 13:16:28 -07:00
// Same as ExecuteCommandWithOutputFile but with a timeout limit.
2020-03-17 18:23:16 -06:00
func ( * CommandExecutor ) ExecuteCommandWithOutputFileTimeout ( suppressLogOutput bool , timeout time . Duration ,
2019-05-02 13:16:28 -07:00
command , outfileArg string , arg ... string ) ( string , error ) {
outFile , err := ioutil . TempFile ( "" , "" )
if err != nil {
return "" , fmt . Errorf ( "failed to open output file: %+v" , err )
}
defer outFile . Close ()
defer os . Remove ( outFile . Name ())
arg = append ( arg , outfileArg , outFile . Name ())
2020-03-17 15:58:04 -06:00
logCommand ( suppressLogOutput , command , arg ... )
2019-05-02 13:16:28 -07:00
ctx , cancel := context . WithTimeout ( context . Background (), timeout )
defer cancel ()
cmd := exec . CommandContext ( ctx , command , arg ... )
cmdOut , err := cmd . CombinedOutput ()
// if there was anything that went to stdout/stderr then log it, even before
// we return an error
if string ( cmdOut ) != "" {
2020-03-17 15:58:04 -06:00
writeToLog ( suppressLogOutput , string ( cmdOut ))
2019-05-02 13:16:28 -07:00
}
if ctx . Err () == context . DeadlineExceeded {
return string ( cmdOut ), ctx . Err ()
}
if err != nil {
return string ( cmdOut ), err
}
fileOut , err := ioutil . ReadAll ( outFile )
return string ( fileOut ), err
}
2020-03-17 18:23:16 -06:00
func ( * CommandExecutor ) ExecuteCommandWithOutputFile ( suppressLogOutput bool , command , outfileArg string , arg ... string ) ( string , error ) {
2017-06-15 18:40:18 -07:00
// create a temporary file to serve as the output file for the command to be run and ensure
// it is cleaned up after this function is done
outFile , err := ioutil . TempFile ( "" , "" )
if err != nil {
return "" , fmt . Errorf ( "failed to open output file: %+v" , err )
}
defer outFile . Close ()
defer os . Remove ( outFile . Name ())
// append the output file argument to the list or args
arg = append ( arg , outfileArg , outFile . Name ())
2020-03-17 15:58:04 -06:00
logCommand ( suppressLogOutput , command , arg ... )
2017-06-15 18:40:18 -07:00
cmd := exec . Command ( command , arg ... )
2017-06-21 11:29:03 -07:00
cmdOut , err := cmd . CombinedOutput ()
// if there was anything that went to stdout/stderr then log it, even before we return an error
2020-02-25 18:07:01 +01:00
if string ( cmdOut ) != "" {
2020-03-17 15:58:04 -06:00
writeToLog ( suppressLogOutput , string ( cmdOut ))
2017-06-15 18:40:18 -07:00
}
2017-06-21 11:29:03 -07:00
if err != nil {
return string ( cmdOut ), err
2017-06-15 18:40:18 -07:00
}
// read the entire output file and return that to the caller
fileOut , err := ioutil . ReadAll ( outFile )
return string ( fileOut ), err
}
2020-03-17 15:58:04 -06:00
func startCommand ( suppressLogOutput bool , command string , arg ... string ) ( * exec . Cmd , io . ReadCloser , io . ReadCloser , error ) {
logCommand ( suppressLogOutput , command , arg ... )
2016-10-28 17:07:31 -07:00
cmd := exec . Command ( command , arg ... )
2019-01-23 13:55:58 -08:00
stdout , err := cmd . StdoutPipe ()
if err != nil {
logger . Warningf ( "failed to open stdout pipe: %+v" , err )
}
stderr , err := cmd . StderrPipe ()
if err != nil {
logger . Warningf ( "failed to open stderr pipe: %+v" , err )
}
2016-10-28 17:07:31 -07:00
2019-01-23 13:55:58 -08:00
err = cmd . Start ()
2016-10-28 17:07:31 -07:00
return cmd , stdout , stderr , err
}
2019-01-23 13:55:58 -08:00
// read from reader line by line and write it to the log
2020-03-17 15:58:04 -06:00
func logFromReader ( suppressLogOutput bool , logger * capnslog . PackageLogger , reader io . ReadCloser ) {
2019-01-23 13:55:58 -08:00
in := bufio . NewScanner ( reader )
lastLine := ""
for in . Scan () {
lastLine = in . Text ()
2020-03-17 15:58:04 -06:00
writeToLog ( suppressLogOutput , lastLine )
2019-01-23 13:55:58 -08:00
}
}
2020-03-17 18:23:16 -06:00
func logOutput ( suppressLogOutput bool , stdout , stderr io . ReadCloser ) {
2016-10-28 17:07:31 -07:00
if stdout == nil || stderr == nil {
2016-11-11 17:37:08 -08:00
logger . Warningf ( "failed to collect stdout and stderr" )
2016-10-28 17:07:31 -07:00
return
}
2016-11-18 08:27:18 -08:00
// The child processes should appropriately be outputting at the desired global level. Therefore,
2016-11-11 17:37:08 -08:00
// we always log at INFO level here, so that log statements from child procs at higher levels
// (e.g., WARNING) will still be displayed. We are relying on the child procs to output appropriately.
2020-03-17 18:23:16 -06:00
childLogger := capnslog . NewPackageLogger ( "github.com/rook/rook" , "exec" )
2016-11-18 08:27:18 -08:00
if ! childLogger . LevelAt ( capnslog . INFO ) {
2016-11-11 17:37:08 -08:00
rl , err := capnslog . GetRepoLogger ( "github.com/rook/rook" )
if err == nil {
2020-03-17 18:23:16 -06:00
rl . SetLogLevel ( map [ string ] capnslog . LogLevel { "exec" : capnslog . INFO })
2016-11-11 17:37:08 -08:00
}
}
2020-03-17 15:58:04 -06:00
go logFromReader ( suppressLogOutput , childLogger , stderr )
logFromReader ( suppressLogOutput , childLogger , stdout )
2016-10-28 17:07:31 -07:00
}
2020-03-17 18:23:16 -06:00
func runCommandWithOutput ( cmd * exec . Cmd , combinedOutput bool ) ( string , error ) {
2017-02-03 13:16:36 -08:00
var output [] byte
var err error
if combinedOutput {
output , err = cmd . CombinedOutput ()
} else {
output , err = cmd . Output ()
}
2017-06-14 16:07:36 -07:00
out := strings . TrimSpace ( string ( output ))
2016-09-15 08:00:43 -07:00
if err != nil {
2020-03-17 18:23:16 -06:00
return out , err
2016-09-15 08:00:43 -07:00
}
2017-06-14 16:07:36 -07:00
return out , nil
2016-09-15 08:00:43 -07:00
}
2020-03-17 15:58:04 -06:00
func logCommand ( suppressLogOutput bool , command string , arg ... string ) {
2017-08-07 10:58:52 -07:00
msg := fmt . Sprintf ( "Running command: %s %s" , command , strings . Join ( arg , " " ))
2020-03-17 15:58:04 -06:00
writeToLog ( suppressLogOutput , msg )
}
func writeToLog ( suppressLogOutput bool , msg string ) {
if suppressLogOutput {
2017-08-07 10:58:52 -07:00
logger . Debug ( msg )
} else {
logger . Info ( msg )
}
2016-09-15 08:00:43 -07:00
}