-
Notifications
You must be signed in to change notification settings - Fork 31
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Feature/shell refactor #172
Merged
Merged
Changes from all commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
4870740
initial incomplete shell refactor
ae632d9
removed extraneous cmd executor
3c4cf7c
render values
11ad6e6
preparer updats
c4c9e2d
printer updates
723d7c0
additional refactoring and updates
f8de2ea
wip: bug in uniq and unlinkwhen causing segfault
c312226
fix segfaults and refactor
1337926
refactor how exec.Cmd is being generator to enhance testibility
3e6f033
Surpress duplicate runs of check
980cdea
linter suggestion changes
c15df7e
added shelloutput sample file
903c0ab
backfill tests
5e884d1
add tests
82b7c9b
add license
0761e31
fix output formatting in tests
00e500b
werker doesn't have ruby
41d2efb
remove debugging output
8b77f74
move error sample since it was valid as an hcl file
0d7a494
don't dump status object anymore when printing output
fc5a372
Add a detailed comment
67b3867
change hcl to match field name (run_flags -> exec_flags)
db39408
typo
a6bd685
removed bad_rm until we have someplace to put it
5fbda30
change shellOutput comment to deal with HCL prettyprinter bug
6c35b31
indent always adds a single tab level now
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,174 @@ | ||
// Copyright © 2016 Asteris, LLC | ||
// | ||
// 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. | ||
|
||
package shell | ||
|
||
import ( | ||
"io" | ||
"io/ioutil" | ||
"log" | ||
"os/exec" | ||
"syscall" | ||
"time" | ||
|
||
"github.com/pkg/errors" | ||
) | ||
|
||
// NB: Known Bug with timed script execution: | ||
|
||
// Currently when a script executes beyond it's alloted time a timeout will | ||
// occur and nil is returned by timeoutExec. The goroutine running the script | ||
// will continue to drain stdout and stderr from the process sockets and they | ||
// will be GCed when the script finally finishes. This means that there is no | ||
// mechanism for getting the output of a script when it has timed out. A | ||
// proposed solution to this would be to implement a ReadUntilWouldBlock-type | ||
// function that would allow us to read into a buffer from a ReadCloser until | ||
// the read operation would block, then return the contents of the buffer (along | ||
// with some marker if we recevied an error or EOF). Then exec function would | ||
// then take in pointers to buffers for stdout and stderr and populate them | ||
// directly, so that if the script execution timed out we would still have a | ||
// reference to those buffers. | ||
var ( | ||
ErrTimedOut = errors.New("execution timed out") | ||
) | ||
|
||
// A CommandExecutor supports running a script and returning the results wrapped | ||
// in a *CommandResults structure. | ||
type CommandExecutor interface { | ||
Run(string) (*CommandResults, error) | ||
} | ||
|
||
// CommandGenerator provides a container to wrap generating a system command | ||
type CommandGenerator struct { | ||
Interpreter string | ||
Flags []string | ||
Timeout *time.Duration | ||
} | ||
|
||
// Run will generate a new command and run it with optional timeout parameters | ||
func (cmd *CommandGenerator) Run(script string) (*CommandResults, error) { | ||
ctx, err := cmd.start() | ||
if err != nil { | ||
return nil, err | ||
} | ||
return ctx.Run(script, cmd.Timeout) | ||
} | ||
|
||
func (cmd *CommandGenerator) start() (*commandIOContext, error) { | ||
command := newCommand(cmd.Interpreter, cmd.Flags) | ||
stdin, stdout, stderr, err := cmdGetPipes(command) | ||
return &commandIOContext{ | ||
Command: command, | ||
Stdin: stdin, | ||
Stdout: stdout, | ||
Stderr: stderr, | ||
}, err | ||
} | ||
|
||
// commandIOContext provides the context for a command that includes it's stdin, | ||
// stdout, and stderr pipes along with the underlying command. | ||
type commandIOContext struct { | ||
Command *exec.Cmd | ||
Stdin io.WriteCloser | ||
Stdout io.ReadCloser | ||
Stderr io.ReadCloser | ||
} | ||
|
||
// Run wraps exec and timeoutExec, executing the script with or without a | ||
// timeout depending whether or not timeout is nil. | ||
func (c *commandIOContext) Run(script string, timeout *time.Duration) (results *CommandResults, err error) { | ||
if timeout == nil { | ||
results, err = c.exec(script) | ||
} else { | ||
results, err = c.timeoutExec(script, *timeout) | ||
} | ||
return | ||
} | ||
|
||
// timeoutExec will run the given script with a timelimit specified by | ||
// timeout. If the script does not return with that time duration a | ||
// ScriptTimeoutError is returned. | ||
func (c *commandIOContext) timeoutExec(script string, timeout time.Duration) (*CommandResults, error) { | ||
timeoutChannel := make(chan []interface{}, 1) | ||
go func() { | ||
cmdResults, err := c.exec(script) | ||
timeoutChannel <- []interface{}{cmdResults, err} | ||
}() | ||
select { | ||
case result := <-timeoutChannel: | ||
var errResult error | ||
if result[1] != nil { | ||
errResult = result[1].(error) | ||
} | ||
return result[0].(*CommandResults), errResult | ||
case <-time.After(timeout): | ||
return nil, ErrTimedOut | ||
} | ||
} | ||
|
||
func (c *commandIOContext) exec(script string) (results *CommandResults, err error) { | ||
results = &CommandResults{ | ||
Stdin: script, | ||
} | ||
|
||
if err = c.Command.Start(); err != nil { | ||
return | ||
} | ||
if _, err = c.Stdin.Write([]byte(script)); err != nil { | ||
return | ||
} | ||
if err = c.Stdin.Close(); err != nil { | ||
return | ||
} | ||
|
||
if data, readErr := ioutil.ReadAll(c.Stdout); readErr == nil { | ||
results.Stdout = string(data) | ||
} else { | ||
log.Printf("[WARNING] cannot read stdout from script") | ||
} | ||
|
||
if data, readErr := ioutil.ReadAll(c.Stderr); readErr == nil { | ||
results.Stderr = string(data) | ||
} else { | ||
log.Printf("[WARNING] cannot read stderr from script") | ||
} | ||
|
||
if waitErr := c.Command.Wait(); waitErr == nil { | ||
results.ExitStatus = 0 | ||
} else { | ||
exitErr, ok := waitErr.(*exec.ExitError) | ||
if !ok { | ||
err = errors.Wrap(waitErr, "failed to wait on process") | ||
return | ||
} | ||
status, ok := exitErr.Sys().(syscall.WaitStatus) | ||
if !ok { | ||
err = errors.New("unexpected error getting exit status") | ||
} | ||
results.ExitStatus = uint32(status.ExitStatus()) | ||
} | ||
results.State = c.Command.ProcessState | ||
return | ||
} | ||
|
||
func newCommand(interpreter string, flags []string) *exec.Cmd { | ||
if interpreter == "" { | ||
if len(flags) > 0 { | ||
log.Println("[INFO] passing flags to default interpreter (/bin/sh)") | ||
return exec.Command(defaultInterpreter, flags...) | ||
} | ||
return exec.Command(defaultInterpreter, defaultExecFlags...) | ||
} | ||
return exec.Command(interpreter, flags...) | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't see this used?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
That's an artefact of an earlier approach I was taking to handling template output; missed cleaning it up when I backed out those changes. I'll remove it.