forked from flynn/flynn
/
attach.go
269 lines (247 loc) · 6.17 KB
/
attach.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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
package main
import (
"bufio"
"encoding/binary"
"encoding/json"
"fmt"
"io"
"net/http"
"sync"
"github.com/flynn/flynn/host/types"
"github.com/julienschmidt/httprouter"
"gopkg.in/inconshreveable/log15.v2"
)
type attachHandler struct {
state *State
backend Backend
// attached is a map of job IDs which are currently attached and is
// used to prevent multiple clients attaching to interactive jobs (i.e.
// ones which have DisableLog set)
attached map[string]struct{}
attachedMtx sync.Mutex
logger log15.Logger
}
func newAttachHandler(state *State, backend Backend, logger log15.Logger) *attachHandler {
return &attachHandler{
state: state,
backend: backend,
logger: logger,
attached: make(map[string]struct{}),
}
}
func (h *attachHandler) ServeHTTP(w http.ResponseWriter, req *http.Request, _ httprouter.Params) {
var attachReq host.AttachReq
if err := json.NewDecoder(req.Body).Decode(&attachReq); err != nil {
http.Error(w, "invalid JSON", 400)
return
}
w.Header().Set("Connection", "upgrade")
w.Header().Set("Upgrade", "flynn-attach/0")
w.WriteHeader(http.StatusSwitchingProtocols)
conn, _, err := w.(http.Hijacker).Hijack()
if err != nil {
return
}
h.attach(&attachReq, conn)
}
func (h *attachHandler) attach(req *host.AttachReq, conn io.ReadWriteCloser) {
defer conn.Close()
log := h.logger.New("fn", "attach", "job.id", req.JobID)
log.Info("starting")
attachWait := make(chan struct{})
job := h.state.AddAttacher(req.JobID, attachWait)
if job == nil {
defer h.state.RemoveAttacher(req.JobID, attachWait)
if _, err := conn.Write([]byte{host.AttachWaiting}); err != nil {
return
}
// TODO: add timeout
log.Info("waiting for attach")
<-attachWait
job = h.state.GetJob(req.JobID)
}
w := bufio.NewWriter(conn)
writeError := func(err string) {
w.WriteByte(host.AttachError)
binary.Write(w, binary.BigEndian, uint32(len(err)))
w.WriteString(err)
w.Flush()
}
if job.Status == host.StatusFailed {
close(attachWait)
writeError(*job.Error)
return
}
// if the job has DisableLog set and is already attached, return an
// error, otherwise mark it as attached
h.attachedMtx.Lock()
if _, ok := h.attached[job.Job.ID]; ok && job.Job.Config.DisableLog {
h.attachedMtx.Unlock()
writeError(host.ErrAttached.Error())
return
}
h.attached[job.Job.ID] = struct{}{}
h.attachedMtx.Unlock()
defer func() {
h.attachedMtx.Lock()
delete(h.attached, job.Job.ID)
h.attachedMtx.Unlock()
}()
writeMtx := &sync.Mutex{}
writeMtx.Lock()
attached := make(chan struct{})
failed := make(chan struct{})
opts := &AttachRequest{
Job: job,
Logs: req.Flags&host.AttachFlagLogs != 0,
Stream: req.Flags&host.AttachFlagStream != 0,
Height: req.Height,
Width: req.Width,
Attached: attached,
}
var stdinW *io.PipeWriter
if req.Flags&host.AttachFlagStdin != 0 {
opts.Stdin, stdinW = io.Pipe()
}
if req.Flags&host.AttachFlagStdout != 0 {
opts.Stdout = newFrameWriter(1, w, writeMtx)
}
if req.Flags&host.AttachFlagStderr != 0 {
opts.Stderr = newFrameWriter(2, w, writeMtx)
}
if req.Flags&host.AttachFlagInitLog != 0 {
opts.InitLog = newFrameWriter(3, w, writeMtx)
}
go func() {
defer func() {
if stdinW != nil {
stdinW.Close()
}
}()
select {
case <-attached:
log.Info("sucessfully attached")
conn.Write([]byte{host.AttachSuccess})
writeMtx.Unlock()
close(attached)
case <-failed:
log.Error("failed to attach to job")
writeMtx.Unlock()
return
}
close(attachWait)
r := bufio.NewReader(conn)
var buf [4]byte
for {
frameType, err := r.ReadByte()
if err != nil {
// TODO: signal close to attach and close all connections
return
}
switch frameType {
case host.AttachData:
stream, err := r.ReadByte()
if err != nil || stream != 0 || stdinW == nil {
return
}
if _, err := io.ReadFull(r, buf[:]); err != nil {
return
}
length := int64(binary.BigEndian.Uint32(buf[:]))
if length == 0 {
stdinW.Close()
stdinW = nil
continue
}
if _, err := io.CopyN(stdinW, r, length); err != nil {
return
}
case host.AttachSignal:
if _, err := io.ReadFull(r, buf[:]); err != nil {
return
}
signal := int(binary.BigEndian.Uint32(buf[:]))
log.Info("signaling", "signal", signal)
if err := h.backend.Signal(req.JobID, signal); err != nil {
log.Error("error signalling job", "err", err)
return
}
case host.AttachResize:
if !job.Job.Config.TTY {
return
}
if _, err := io.ReadFull(r, buf[:]); err != nil {
return
}
height := binary.BigEndian.Uint16(buf[:])
width := binary.BigEndian.Uint16(buf[2:])
log.Info("resizing tty", "height", height, "width", width)
if err := h.backend.ResizeTTY(req.JobID, height, width); err != nil {
log.Error("error resizing tty", "err", err)
return
}
default:
return
}
}
}()
log.Info("attaching")
if err := h.backend.Attach(opts); err != nil && err != io.EOF {
if exit, ok := err.(ExitError); ok {
writeMtx.Lock()
w.WriteByte(host.AttachExit)
binary.Write(w, binary.BigEndian, uint32(exit))
w.Flush()
writeMtx.Unlock()
} else {
close(failed)
writeMtx.Lock()
writeError(err.Error())
writeMtx.Unlock()
log.Error("attach error", "err", err)
}
} else {
if opts.Stdout != nil {
opts.Stdout.Close()
}
if opts.Stderr != nil {
opts.Stderr.Close()
}
}
log.Info("finished")
}
type ExitError int
func (e ExitError) Error() string {
return fmt.Sprintf("exit status %d", e)
}
type frameWriter struct {
mtx *sync.Mutex
buf [6]byte
w *bufio.Writer
closed bool
}
func newFrameWriter(stream byte, w *bufio.Writer, mtx *sync.Mutex) io.WriteCloser {
f := &frameWriter{w: w, mtx: mtx}
f.buf[0] = host.AttachData
f.buf[1] = stream
return f
}
func (w *frameWriter) Write(p []byte) (int, error) {
w.mtx.Lock()
defer w.mtx.Unlock()
binary.BigEndian.PutUint32(w.buf[2:], uint32(len(p)))
w.w.Write(w.buf[:])
n, _ := w.w.Write(p)
return n, w.w.Flush()
}
func (w *frameWriter) Close() error {
w.mtx.Lock()
defer w.mtx.Unlock()
if w.closed {
return nil
}
w.closed = true
binary.BigEndian.PutUint32(w.buf[2:], 0)
w.w.Write(w.buf[:])
return w.w.Flush()
}