2014-09-01 05:45:55 +00:00
|
|
|
package agent
|
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
2017-10-25 09:18:07 +00:00
|
|
|
osexec "os/exec"
|
2014-09-01 05:45:55 +00:00
|
|
|
"path"
|
|
|
|
"strconv"
|
|
|
|
"sync"
|
|
|
|
"syscall"
|
|
|
|
"time"
|
|
|
|
|
2017-10-25 09:18:07 +00:00
|
|
|
"github.com/hashicorp/consul/agent/exec"
|
2017-07-06 10:34:00 +00:00
|
|
|
"github.com/hashicorp/consul/agent/structs"
|
2017-04-19 23:00:11 +00:00
|
|
|
"github.com/hashicorp/consul/api"
|
2014-09-01 05:45:55 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
const (
|
|
|
|
// remoteExecFileName is the name of the file we append to
|
|
|
|
// the path, e.g. _rexec/session_id/job
|
|
|
|
remoteExecFileName = "job"
|
|
|
|
|
|
|
|
// rExecAck is the suffix added to an ack path
|
|
|
|
remoteExecAckSuffix = "ack"
|
|
|
|
|
|
|
|
// remoteExecAck is the suffix added to an exit code
|
|
|
|
remoteExecExitSuffix = "exit"
|
|
|
|
|
|
|
|
// remoteExecOutputDivider is used to namespace the output
|
|
|
|
remoteExecOutputDivider = "out"
|
|
|
|
|
|
|
|
// remoteExecOutputSize is the size we chunk output too
|
|
|
|
remoteExecOutputSize = 4 * 1024
|
|
|
|
|
|
|
|
// remoteExecOutputDeadline is how long we wait before uploading
|
|
|
|
// less than the chunk size
|
|
|
|
remoteExecOutputDeadline = 500 * time.Millisecond
|
|
|
|
)
|
|
|
|
|
|
|
|
// remoteExecEvent is used as the payload of the user event to transmit
|
|
|
|
// what we need to know about the event
|
|
|
|
type remoteExecEvent struct {
|
|
|
|
Prefix string
|
|
|
|
Session string
|
|
|
|
}
|
|
|
|
|
|
|
|
// remoteExecSpec is used as the specification of the remote exec.
|
|
|
|
// It is stored in the KV store
|
|
|
|
type remoteExecSpec struct {
|
|
|
|
Command string
|
2017-10-04 23:48:00 +00:00
|
|
|
Args []string
|
2014-09-01 05:45:55 +00:00
|
|
|
Script []byte
|
|
|
|
Wait time.Duration
|
|
|
|
}
|
|
|
|
|
|
|
|
type rexecWriter struct {
|
2014-09-01 17:42:35 +00:00
|
|
|
BufCh chan []byte
|
|
|
|
BufSize int
|
|
|
|
BufIdle time.Duration
|
|
|
|
CancelCh chan struct{}
|
|
|
|
|
|
|
|
buf []byte
|
|
|
|
bufLen int
|
|
|
|
bufLock sync.Mutex
|
|
|
|
flush *time.Timer
|
2014-09-01 05:45:55 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (r *rexecWriter) Write(b []byte) (int, error) {
|
|
|
|
r.bufLock.Lock()
|
|
|
|
defer r.bufLock.Unlock()
|
|
|
|
if r.flush != nil {
|
|
|
|
r.flush.Stop()
|
|
|
|
r.flush = nil
|
|
|
|
}
|
|
|
|
inpLen := len(b)
|
2014-09-01 17:42:35 +00:00
|
|
|
if r.buf == nil {
|
|
|
|
r.buf = make([]byte, r.BufSize)
|
|
|
|
}
|
2014-09-01 05:45:55 +00:00
|
|
|
|
|
|
|
COPY:
|
|
|
|
remain := len(r.buf) - r.bufLen
|
2014-09-01 17:42:35 +00:00
|
|
|
if remain > len(b) {
|
2014-09-01 05:45:55 +00:00
|
|
|
copy(r.buf[r.bufLen:], b)
|
|
|
|
r.bufLen += len(b)
|
|
|
|
} else {
|
|
|
|
copy(r.buf[r.bufLen:], b[:remain])
|
|
|
|
b = b[remain:]
|
|
|
|
r.bufLen += remain
|
|
|
|
r.bufLock.Unlock()
|
2014-09-01 17:42:35 +00:00
|
|
|
r.Flush()
|
2014-09-01 05:45:55 +00:00
|
|
|
r.bufLock.Lock()
|
|
|
|
goto COPY
|
|
|
|
}
|
|
|
|
|
2014-09-01 17:42:35 +00:00
|
|
|
r.flush = time.AfterFunc(r.BufIdle, r.Flush)
|
2014-09-01 05:45:55 +00:00
|
|
|
return inpLen, nil
|
|
|
|
}
|
|
|
|
|
2014-09-01 17:42:35 +00:00
|
|
|
func (r *rexecWriter) Flush() {
|
2014-09-01 05:45:55 +00:00
|
|
|
r.bufLock.Lock()
|
|
|
|
defer r.bufLock.Unlock()
|
2014-09-01 17:42:35 +00:00
|
|
|
if r.flush != nil {
|
|
|
|
r.flush.Stop()
|
|
|
|
r.flush = nil
|
|
|
|
}
|
2014-09-01 05:45:55 +00:00
|
|
|
if r.bufLen == 0 {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
select {
|
2014-09-01 17:42:35 +00:00
|
|
|
case r.BufCh <- r.buf[:r.bufLen]:
|
|
|
|
r.buf = make([]byte, r.BufSize)
|
2014-09-01 05:45:55 +00:00
|
|
|
r.bufLen = 0
|
2014-09-01 17:42:35 +00:00
|
|
|
case <-r.CancelCh:
|
2014-09-01 05:45:55 +00:00
|
|
|
r.bufLen = 0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// handleRemoteExec is invoked when a new remote exec request is received
|
|
|
|
func (a *Agent) handleRemoteExec(msg *UserEvent) {
|
2020-01-28 23:50:41 +00:00
|
|
|
a.logger.Debug("received remote exec event", "id", msg.ID)
|
2015-09-15 12:22:08 +00:00
|
|
|
// Decode the event payload
|
2014-09-01 05:45:55 +00:00
|
|
|
var event remoteExecEvent
|
|
|
|
if err := json.Unmarshal(msg.Payload, &event); err != nil {
|
2020-01-28 23:50:41 +00:00
|
|
|
a.logger.Error("failed to decode remote exec event", "error", err)
|
2014-09-01 05:45:55 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Read the job specification
|
|
|
|
var spec remoteExecSpec
|
|
|
|
if !a.remoteExecGetSpec(&event, &spec) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Write the acknowledgement
|
|
|
|
if !a.remoteExecWriteAck(&event) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Ensure we write out an exit code
|
|
|
|
exitCode := 0
|
2014-09-17 19:17:51 +00:00
|
|
|
defer a.remoteExecWriteExitCode(&event, &exitCode)
|
2014-09-01 05:45:55 +00:00
|
|
|
|
|
|
|
// Check if this is a script, we may need to spill to disk
|
|
|
|
var script string
|
|
|
|
if len(spec.Script) != 0 {
|
|
|
|
tmpFile, err := ioutil.TempFile("", "rexec")
|
|
|
|
if err != nil {
|
2020-01-28 23:50:41 +00:00
|
|
|
a.logger.Debug("failed to make tmp file", "error", err)
|
2014-09-01 05:45:55 +00:00
|
|
|
exitCode = 255
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer os.Remove(tmpFile.Name())
|
|
|
|
os.Chmod(tmpFile.Name(), 0750)
|
|
|
|
tmpFile.Write(spec.Script)
|
|
|
|
tmpFile.Close()
|
|
|
|
script = tmpFile.Name()
|
|
|
|
} else {
|
|
|
|
script = spec.Command
|
|
|
|
}
|
|
|
|
|
|
|
|
// Create the exec.Cmd
|
2020-01-28 23:50:41 +00:00
|
|
|
a.logger.Info("remote exec script", "script", script)
|
2017-10-25 09:18:07 +00:00
|
|
|
var cmd *osexec.Cmd
|
2017-10-04 23:48:00 +00:00
|
|
|
var err error
|
|
|
|
if len(spec.Args) > 0 {
|
2017-10-25 09:18:07 +00:00
|
|
|
cmd, err = exec.Subprocess(spec.Args)
|
2017-10-04 23:48:00 +00:00
|
|
|
} else {
|
2017-10-25 09:18:07 +00:00
|
|
|
cmd, err = exec.Script(script)
|
2017-10-04 23:48:00 +00:00
|
|
|
}
|
2014-09-01 05:45:55 +00:00
|
|
|
if err != nil {
|
2020-01-28 23:50:41 +00:00
|
|
|
a.logger.Debug("failed to start remote exec", "error", err)
|
2014-09-01 05:45:55 +00:00
|
|
|
exitCode = 255
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Setup the output streaming
|
|
|
|
writer := &rexecWriter{
|
2014-09-01 17:42:35 +00:00
|
|
|
BufCh: make(chan []byte, 16),
|
|
|
|
BufSize: remoteExecOutputSize,
|
|
|
|
BufIdle: remoteExecOutputDeadline,
|
|
|
|
CancelCh: make(chan struct{}),
|
2014-09-01 05:45:55 +00:00
|
|
|
}
|
|
|
|
cmd.Stdout = writer
|
|
|
|
cmd.Stderr = writer
|
|
|
|
|
|
|
|
// Start execution
|
2017-10-04 23:48:00 +00:00
|
|
|
if err := cmd.Start(); err != nil {
|
2020-01-28 23:50:41 +00:00
|
|
|
a.logger.Debug("failed to start remote exec", "error", err)
|
2014-09-01 05:45:55 +00:00
|
|
|
exitCode = 255
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Wait for the process to exit
|
|
|
|
exitCh := make(chan int, 1)
|
|
|
|
go func() {
|
|
|
|
err := cmd.Wait()
|
2014-09-01 17:42:35 +00:00
|
|
|
writer.Flush()
|
|
|
|
close(writer.BufCh)
|
2014-09-17 19:17:51 +00:00
|
|
|
if err == nil {
|
2014-09-01 05:45:55 +00:00
|
|
|
exitCh <- 0
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
// Try to determine the exit code
|
2017-10-25 09:18:07 +00:00
|
|
|
if exitErr, ok := err.(*osexec.ExitError); ok {
|
2014-09-01 05:45:55 +00:00
|
|
|
if status, ok := exitErr.Sys().(syscall.WaitStatus); ok {
|
|
|
|
exitCh <- status.ExitStatus()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
}
|
|
|
|
exitCh <- 1
|
|
|
|
}()
|
|
|
|
|
|
|
|
// Wait until we are complete, uploading as we go
|
|
|
|
WAIT:
|
|
|
|
for num := 0; ; num++ {
|
|
|
|
select {
|
2014-09-01 17:42:35 +00:00
|
|
|
case out := <-writer.BufCh:
|
2014-09-01 05:45:55 +00:00
|
|
|
if out == nil {
|
|
|
|
break WAIT
|
|
|
|
}
|
|
|
|
if !a.remoteExecWriteOutput(&event, num, out) {
|
2014-09-01 17:42:35 +00:00
|
|
|
close(writer.CancelCh)
|
2014-09-01 05:45:55 +00:00
|
|
|
exitCode = 255
|
|
|
|
return
|
|
|
|
}
|
|
|
|
case <-time.After(spec.Wait):
|
|
|
|
// Acts like a heartbeat, since there is no output
|
2014-09-01 20:13:15 +00:00
|
|
|
if !a.remoteExecWriteOutput(&event, num, nil) {
|
|
|
|
close(writer.CancelCh)
|
|
|
|
exitCode = 255
|
|
|
|
return
|
|
|
|
}
|
2014-09-01 05:45:55 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// Get the exit code
|
|
|
|
exitCode = <-exitCh
|
|
|
|
}
|
|
|
|
|
|
|
|
// remoteExecGetSpec is used to get the exec specification.
|
|
|
|
// Returns if execution should continue
|
|
|
|
func (a *Agent) remoteExecGetSpec(event *remoteExecEvent, spec *remoteExecSpec) bool {
|
|
|
|
get := structs.KeyRequest{
|
|
|
|
Datacenter: a.config.Datacenter,
|
|
|
|
Key: path.Join(event.Prefix, event.Session, remoteExecFileName),
|
|
|
|
QueryOptions: structs.QueryOptions{
|
|
|
|
AllowStale: true, // Stale read for scale! Retry on failure.
|
|
|
|
},
|
|
|
|
}
|
2017-07-26 18:03:43 +00:00
|
|
|
get.Token = a.tokens.AgentToken()
|
2014-09-01 05:45:55 +00:00
|
|
|
var out structs.IndexedDirEntries
|
|
|
|
QUERY:
|
|
|
|
if err := a.RPC("KVS.Get", &get, &out); err != nil {
|
2020-01-28 23:50:41 +00:00
|
|
|
a.logger.Error("failed to get remote exec job", "error", err)
|
2014-09-01 05:45:55 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
if len(out.Entries) == 0 {
|
|
|
|
// If the initial read was stale and had no data, retry as a consistent read
|
|
|
|
if get.QueryOptions.AllowStale {
|
2020-01-28 23:50:41 +00:00
|
|
|
a.logger.Debug("trying consistent fetch of remote exec job spec")
|
2014-09-01 05:45:55 +00:00
|
|
|
get.QueryOptions.AllowStale = false
|
|
|
|
goto QUERY
|
|
|
|
} else {
|
2020-01-28 23:50:41 +00:00
|
|
|
a.logger.Debug("remote exec aborted, job spec missing")
|
2014-09-01 05:45:55 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if err := json.Unmarshal(out.Entries[0].Value, &spec); err != nil {
|
2020-01-28 23:50:41 +00:00
|
|
|
a.logger.Error("failed to decode remote exec spec", "error", err)
|
2014-09-01 05:45:55 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
// remoteExecWriteAck is used to write an ack. Returns if execution should
|
|
|
|
// continue.
|
|
|
|
func (a *Agent) remoteExecWriteAck(event *remoteExecEvent) bool {
|
2014-09-01 17:51:15 +00:00
|
|
|
if err := a.remoteExecWriteKey(event, remoteExecAckSuffix, nil); err != nil {
|
2020-01-28 23:50:41 +00:00
|
|
|
a.logger.Error("failed to ack remote exec job", "error", err)
|
2014-09-01 05:45:55 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
// remoteExecWriteOutput is used to write output
|
|
|
|
func (a *Agent) remoteExecWriteOutput(event *remoteExecEvent, num int, output []byte) bool {
|
2014-09-01 17:51:15 +00:00
|
|
|
suffix := path.Join(remoteExecOutputDivider, fmt.Sprintf("%05x", num))
|
|
|
|
if err := a.remoteExecWriteKey(event, suffix, output); err != nil {
|
2020-01-28 23:50:41 +00:00
|
|
|
a.logger.Error("failed to write output for remote exec job", "error", err)
|
2014-09-01 05:45:55 +00:00
|
|
|
return false
|
|
|
|
}
|
|
|
|
return true
|
|
|
|
}
|
|
|
|
|
|
|
|
// remoteExecWriteExitCode is used to write an exit code
|
2014-09-17 19:17:51 +00:00
|
|
|
func (a *Agent) remoteExecWriteExitCode(event *remoteExecEvent, exitCode *int) bool {
|
|
|
|
val := []byte(strconv.FormatInt(int64(*exitCode), 10))
|
2014-09-01 17:51:15 +00:00
|
|
|
if err := a.remoteExecWriteKey(event, remoteExecExitSuffix, val); err != nil {
|
2020-01-28 23:50:41 +00:00
|
|
|
a.logger.Error("failed to write exit code for remote exec job", "error", err)
|
2014-09-01 18:21:57 +00:00
|
|
|
return false
|
2014-09-01 17:51:15 +00:00
|
|
|
}
|
2014-09-01 18:21:57 +00:00
|
|
|
return true
|
2014-09-01 17:51:15 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// remoteExecWriteKey is used to write an output key for a remote exec job
|
|
|
|
func (a *Agent) remoteExecWriteKey(event *remoteExecEvent, suffix string, val []byte) error {
|
|
|
|
key := path.Join(event.Prefix, event.Session, a.config.NodeName, suffix)
|
2014-09-01 05:45:55 +00:00
|
|
|
write := structs.KVSRequest{
|
|
|
|
Datacenter: a.config.Datacenter,
|
2017-04-19 23:00:11 +00:00
|
|
|
Op: api.KVLock,
|
2014-09-01 05:45:55 +00:00
|
|
|
DirEnt: structs.DirEntry{
|
2014-09-01 17:51:15 +00:00
|
|
|
Key: key,
|
|
|
|
Value: val,
|
2014-09-01 05:45:55 +00:00
|
|
|
Session: event.Session,
|
|
|
|
},
|
|
|
|
}
|
2017-07-26 18:03:43 +00:00
|
|
|
write.Token = a.tokens.AgentToken()
|
2014-09-01 05:45:55 +00:00
|
|
|
var success bool
|
|
|
|
if err := a.RPC("KVS.Apply", &write, &success); err != nil {
|
2014-09-01 17:51:15 +00:00
|
|
|
return err
|
2014-09-01 05:45:55 +00:00
|
|
|
}
|
|
|
|
if !success {
|
2014-09-01 17:51:15 +00:00
|
|
|
return fmt.Errorf("write failed")
|
2014-09-01 05:45:55 +00:00
|
|
|
}
|
2014-09-01 17:51:15 +00:00
|
|
|
return nil
|
2014-09-01 05:45:55 +00:00
|
|
|
}
|