summaryrefslogtreecommitdiffstats
path: root/eows/eows-in.go
blob: 5e74c76cb11337c5c387db93aa4600a0bf8d796f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
package eows

import (
	"fmt"
	"os"
	"syscall"
	"time"
)

// DoneChan Channel used to propagate status+error on command exit
type DoneChan struct {
	status int
	err    error
}

// pumpStdin is in charge of receive characters and send them to stdin
func (e *ExecOverWS) pumpStdin(inw *os.File) {

	done := make(chan DoneChan, 1)

	if e.InputEvent != "" && e.InputCB != nil {

		err := (*e.SocketIO).On(e.InputEvent, func(stdin []byte) {
			in, err := e.InputCB(e, stdin)
			if err != nil {
				e.logDebug("Error stdin: %s", err.Error())
				inw.Close()
				return
			}
			if _, err := inw.Write(in); err != nil {
				e.logError("Error while writing to stdin: %s", err.Error())
			}
		})
		if err != nil {
			e.logError("Error stdin on event: %s", err.Error())
		}
	}

	// Monitor process exit
	go func() {
		status := 0
		sts, err := e.proc.Wait()
		if !sts.Success() {
			s := sts.Sys().(syscall.WaitStatus)
			status = s.ExitStatus()
		}
		e.procExited = true

		done <- DoneChan{status, err}
	}()

	// Wait cmd complete
	select {
	case dC := <-done:
		e.ExitCB(e, dC.status, dC.err)
	case <-time.After(time.Duration(e.CmdExecTimeout) * time.Second):
		e.ExitCB(e, -999, fmt.Errorf("Exit Timeout for command ID %v", e.CmdID))
	}
}