/
tmux.go
194 lines (150 loc) · 3.95 KB
/
tmux.go
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package start
import (
"bufio"
"bytes"
"fmt"
"os"
"os/exec"
"regexp"
"strconv"
"sync"
"syscall"
"time"
"github.com/DarthSim/overmind/utils"
"github.com/pkg/term/termios"
)
var tmuxUnescapeRe = regexp.MustCompile(`\\(\d{3})`)
var tmuxOutputRe = regexp.MustCompile("%(\\S+) (.+)")
var tmuxProcessRe = regexp.MustCompile("%(\\d+) (.+) (\\d+)")
var outputRe = regexp.MustCompile("%(\\d+) (.+)")
const tmuxPaneFmt = "%overmind-process #{pane_id} #{window_name} #{pane_pid}"
type tmuxClient struct {
pty, tty *os.File
processesByPane processesMap
processesByName processesMap
cmdMutex sync.Mutex
cmd *exec.Cmd
initKilled bool
Root string
Socket string
Session string
}
func newTmuxClient(session, socket, root string) (*tmuxClient, error) {
t := tmuxClient{
processesByName: make(processesMap),
processesByPane: make(processesMap),
Root: root,
Session: session,
Socket: socket,
}
var err error
t.pty, t.tty, err = termios.Pty()
if err != nil {
return nil, err
}
return &t, nil
}
func (t *tmuxClient) Start() error {
go t.listen()
args := []string{"-CC", "-L", t.Socket}
first := true
for name, p := range t.processesByName {
if first {
first = false
args = append(args, "new", "-n", name, "-s", t.Session, "-P", "-F", tmuxPaneFmt, p.Command, ";")
args = append(args, "setw", "-g", "remain-on-exit", "on", ";")
args = append(args, "setw", "-g", "allow-rename", "off", ";")
} else {
args = append(args, "neww", "-n", name, "-P", "-F", tmuxPaneFmt, p.Command, ";")
}
}
t.cmd = exec.Command("tmux", args...)
t.cmd.Stdout = t.tty
// t.cmd.Stdout = io.MultiWriter(t.tty, os.Stdout)
t.cmd.Stderr = os.Stderr
t.cmd.Stdin = t.tty
t.cmd.SysProcAttr = &syscall.SysProcAttr{Setctty: true, Setsid: true}
t.cmd.Dir = t.Root
if err := t.cmd.Start(); err != nil {
return err
}
return nil
}
func (t *tmuxClient) sendCmd(cmd string, arg ...interface{}) {
t.cmdMutex.Lock()
defer t.cmdMutex.Unlock()
fmt.Fprintln(t.pty, fmt.Sprintf(cmd, arg...))
}
func (t *tmuxClient) listen() {
scanner := bufio.NewScanner(t.pty)
for scanner.Scan() {
// fmt.Println(scanner.Text())
tmuxOut := tmuxOutputRe.FindStringSubmatch(scanner.Text())
if len(tmuxOut) < 2 {
continue
}
switch tmuxOut[1] {
case "overmind-process":
procbind := tmuxProcessRe.FindStringSubmatch(tmuxOut[2])
if len(procbind) > 3 {
t.mapProcess(procbind[1], procbind[2], procbind[3])
}
case "output":
output := outputRe.FindStringSubmatch(tmuxOut[2])
if len(output) > 2 {
t.sendOutput(output[1], output[2])
}
}
}
utils.FatalOnErr(scanner.Err())
}
func (t *tmuxClient) mapProcess(pane, name, pid string) {
if p, ok := t.processesByName[name]; ok {
t.processesByPane[pane] = p
p.tmuxPane = pane
if ipid, err := strconv.Atoi(pid); err == nil {
p.proc, _ = os.FindProcess(-ipid)
}
}
}
func (t *tmuxClient) sendOutput(name, str string) {
if proc, ok := t.processesByPane[name]; ok {
unescaped := tmuxUnescapeRe.ReplaceAllStringFunc(str, func(src string) string {
code, _ := strconv.ParseUint(src[1:], 8, 8)
return string([]byte{byte(code)})
})
fmt.Fprint(proc.in, unescaped)
}
}
func (t *tmuxClient) AddProcess(p *process) {
t.processesByName[p.Name] = p
}
func (t *tmuxClient) RespawnProcess(p *process) {
t.sendCmd("neww -k -t %s -n %s -P -F \"%s\" %s", p.Name, p.Name, tmuxPaneFmt, p.Command)
}
func (t *tmuxClient) ExitCode() (status int) {
buf := new(bytes.Buffer)
cmd := exec.Command("tmux", "-L", t.Socket, "list-windows", "-t", t.Session, "-F", "#{pane_dead_status}")
cmd.Stdout = buf
cmd.Stderr = os.Stderr
cmd.Run()
scanner := bufio.NewScanner(buf)
for scanner.Scan() {
if s, err := strconv.Atoi(scanner.Text()); err == nil && s > status {
status = s
}
}
return
}
func (t *tmuxClient) Shutdown() {
t.sendCmd("kill-session")
stopped := make(chan struct{})
go func() {
t.cmd.Process.Wait()
close(stopped)
}()
select {
case <-stopped:
case <-time.After(5 * time.Second):
}
}