forked from canonical/lxd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
container_console.go
427 lines (342 loc) · 8.87 KB
/
container_console.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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"os/exec"
"strconv"
"sync"
"syscall"
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"gopkg.in/lxc/go-lxc.v2"
"github.com/lxc/lxd/lxd/util"
"github.com/lxc/lxd/shared"
"github.com/lxc/lxd/shared/api"
"github.com/lxc/lxd/shared/logger"
)
type consoleWs struct {
// container currently worked on
container container
// uid to chown pty to
rootUid int64
// gid to chown pty to
rootGid int64
// websocket connections to bridge pty fds to
conns map[int]*websocket.Conn
// locks needed to access the "conns" member
connsLock sync.Mutex
// channel to wait until all websockets are properly connected
allConnected chan bool
// channel to wait until the control socket is connected
controlConnected chan bool
// map file descriptors -> secret
fds map[int]string
// terminal width
width int
// terminal height
height int
}
func (s *consoleWs) Metadata() interface{} {
fds := shared.Jmap{}
for fd, secret := range s.fds {
if fd == -1 {
fds["control"] = secret
} else {
fds[strconv.Itoa(fd)] = secret
}
}
return shared.Jmap{"fds": fds}
}
func (s *consoleWs) Connect(op *operation, r *http.Request, w http.ResponseWriter) error {
secret := r.FormValue("secret")
if secret == "" {
return fmt.Errorf("missing secret")
}
for fd, fdSecret := range s.fds {
if secret == fdSecret {
conn, err := shared.WebsocketUpgrader.Upgrade(w, r, nil)
if err != nil {
return err
}
s.connsLock.Lock()
s.conns[fd] = conn
s.connsLock.Unlock()
if fd == -1 {
s.controlConnected <- true
return nil
}
s.connsLock.Lock()
for i, c := range s.conns {
if i != -1 && c == nil {
s.connsLock.Unlock()
return nil
}
}
s.connsLock.Unlock()
s.allConnected <- true
return nil
}
}
/* If we didn't find the right secret, the user provided a bad one,
* which 403, not 404, since this operation actually exists */
return os.ErrPermission
}
func (s *consoleWs) Do(op *operation) error {
<-s.allConnected
var err error
master := &os.File{}
slave := &os.File{}
master, slave, err = shared.OpenPty(s.rootUid, s.rootGid)
if err != nil {
return err
}
if s.width > 0 && s.height > 0 {
shared.SetSize(int(master.Fd()), s.width, s.height)
}
controlExit := make(chan bool)
var wgEOF sync.WaitGroup
consolePidChan := make(chan int)
wgEOF.Add(1)
go func() {
select {
case <-s.controlConnected:
break
case <-controlExit:
return
}
consolePid := <-consolePidChan
for {
s.connsLock.Lock()
conn := s.conns[-1]
s.connsLock.Unlock()
_, r, err := conn.NextReader()
if err != nil {
logger.Debugf("Got error getting next reader %s", err)
err := syscall.Kill(consolePid, syscall.SIGTERM)
if err != nil {
logger.Debugf("Failed to send SIGTERM to pid %d", consolePid)
} else {
logger.Debugf("Sent SIGTERM to pid %d", consolePid)
}
return
}
buf, err := ioutil.ReadAll(r)
if err != nil {
logger.Debugf("Failed to read message %s", err)
break
}
command := api.ContainerConsoleControl{}
err = json.Unmarshal(buf, &command)
if err != nil {
logger.Debugf("Failed to unmarshal control socket command: %s", err)
continue
}
if command.Command == "window-resize" {
winchWidth, err := strconv.Atoi(command.Args["width"])
if err != nil {
logger.Debugf("Unable to extract window width: %s", err)
continue
}
winchHeight, err := strconv.Atoi(command.Args["height"])
if err != nil {
logger.Debugf("Unable to extract window height: %s", err)
continue
}
err = shared.SetSize(int(master.Fd()), winchWidth, winchHeight)
if err != nil {
logger.Debugf("Failed to set window size to: %dx%d", winchWidth, winchHeight)
continue
}
logger.Debugf("Set window size to: %dx%d", winchWidth, winchHeight)
}
}
}()
go func() {
s.connsLock.Lock()
conn := s.conns[0]
s.connsLock.Unlock()
logger.Debugf("Starting to mirror websocket")
readDone, writeDone := shared.WebsocketConsoleMirror(conn, master, master)
<-readDone
logger.Debugf("Finished to read websocket")
<-writeDone
logger.Debugf("Finished to write websocket")
logger.Debugf("Finished to mirror websocket")
conn.Close()
wgEOF.Done()
}()
finisher := func(cmdErr error) error {
slave.Close()
s.connsLock.Lock()
conn := s.conns[-1]
s.connsLock.Unlock()
if conn == nil {
controlExit <- true
}
wgEOF.Wait()
master.Close()
return cmdErr
}
consCmd := s.container.Console(slave)
consCmd.Start()
consolePidChan <- consCmd.Process.Pid
err = consCmd.Wait()
if err == nil {
return finisher(nil)
}
exitErr, ok := err.(*exec.ExitError)
if ok {
status, _ := exitErr.Sys().(syscall.WaitStatus)
// If we received SIGTERM someone told us to detach from the
// console.
if status.Signaled() && status.Signal() == syscall.SIGTERM {
return finisher(nil)
}
}
return finisher(err)
}
func containerConsolePost(d *Daemon, r *http.Request) Response {
name := mux.Vars(r)["name"]
c, err := containerLoadByName(d.State(), name)
if err != nil {
return SmartError(err)
}
err = fmt.Errorf("Container is not running")
if !c.IsRunning() {
return BadRequest(err)
}
err = fmt.Errorf("Container is frozen")
if c.IsFrozen() {
return BadRequest(err)
}
post := api.ContainerConsolePost{}
buf, err := ioutil.ReadAll(r.Body)
if err != nil {
return BadRequest(err)
}
err = json.Unmarshal(buf, &post)
if err != nil {
return BadRequest(err)
}
ws := &consoleWs{}
ws.fds = map[int]string{}
idmapset, err := c.IdmapSet()
if err != nil {
return InternalError(err)
}
if idmapset != nil {
ws.rootUid, ws.rootGid = idmapset.ShiftIntoNs(0, 0)
}
ws.conns = map[int]*websocket.Conn{}
ws.conns[-1] = nil
ws.conns[0] = nil
for i := -1; i < len(ws.conns)-1; i++ {
ws.fds[i], err = shared.RandomCryptoString()
if err != nil {
return InternalError(err)
}
}
ws.allConnected = make(chan bool, 1)
ws.controlConnected = make(chan bool, 1)
ws.container = c
ws.width = post.Width
ws.height = post.Height
resources := map[string][]string{}
resources["containers"] = []string{ws.container.Name()}
op, err := operationCreate(operationClassWebsocket, "Showing console", resources,
ws.Metadata(), ws.Do, nil, ws.Connect)
if err != nil {
return InternalError(err)
}
return OperationResponse(op)
}
func containerConsoleLogGet(d *Daemon, r *http.Request) Response {
if !util.RuntimeLiblxcVersionAtLeast(3, 0, 0) {
return BadRequest(fmt.Errorf("Querying the console buffer requires liblxc >= 3.0"))
}
name := mux.Vars(r)["name"]
c, err := containerLoadByName(d.State(), name)
if err != nil {
return SmartError(err)
}
ent := fileResponseEntry{}
if !c.IsRunning() {
// Hand back the contents of the console ringbuffer logfile.
consoleBufferLogPath := c.ConsoleBufferLogPath()
ent.path = consoleBufferLogPath
ent.filename = consoleBufferLogPath
return FileResponse(r, []fileResponseEntry{ent}, nil, false)
}
// Query the container's console ringbuffer.
console := lxc.ConsoleLogOptions{
ClearLog: false,
ReadLog: true,
ReadMax: 0,
WriteToLogFile: true,
}
// Send a ringbuffer request to the container.
logContents, err := c.ConsoleLog(console)
if err != nil {
errno, isErrno := shared.GetErrno(err)
if !isErrno {
return SmartError(err)
}
if errno == syscall.ENODATA {
return FileResponse(r, []fileResponseEntry{ent}, nil, false)
}
return SmartError(err)
}
ent.buffer = []byte(logContents)
return FileResponse(r, []fileResponseEntry{ent}, nil, false)
}
func containerConsoleLogDelete(d *Daemon, r *http.Request) Response {
if !util.RuntimeLiblxcVersionAtLeast(3, 0, 0) {
return BadRequest(fmt.Errorf("Clearing the console buffer requires liblxc >= 3.0"))
}
name := mux.Vars(r)["name"]
c, err := containerLoadByName(d.State(), name)
if err != nil {
return SmartError(err)
}
truncateConsoleLogFile := func(path string) error {
// Check that this is a regular file. We don't want to try and unlink
// /dev/stderr or /dev/null or something.
st, err := os.Stat(path)
if err != nil {
return err
}
if !st.Mode().IsRegular() {
return fmt.Errorf("The console log is not a regular file")
}
if path == "" {
return fmt.Errorf("Container does not keep a console logfile")
}
return os.Truncate(path, 0)
}
if !c.IsRunning() {
consoleLogpath := c.ConsoleBufferLogPath()
return SmartError(truncateConsoleLogFile(consoleLogpath))
}
// Send a ringbuffer request to the container.
console := lxc.ConsoleLogOptions{
ClearLog: true,
ReadLog: false,
ReadMax: 0,
WriteToLogFile: false,
}
_, err = c.ConsoleLog(console)
if err != nil {
errno, isErrno := shared.GetErrno(err)
if !isErrno {
return SmartError(err)
}
if errno == syscall.ENODATA {
return SmartError(nil)
}
return SmartError(err)
}
return SmartError(nil)
}