-
-
Notifications
You must be signed in to change notification settings - Fork 684
/
handle_docker_runtime.go
407 lines (341 loc) · 10.2 KB
/
handle_docker_runtime.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
package debug
import (
"fmt"
"io"
"os"
"strings"
"time"
dockerapi "github.com/fsouza/go-dockerclient"
log "github.com/sirupsen/logrus"
"github.com/slimtoolkit/slim/pkg/app"
"github.com/slimtoolkit/slim/pkg/app/master/command"
"github.com/slimtoolkit/slim/pkg/app/master/container"
"github.com/slimtoolkit/slim/pkg/app/master/inspectors/image"
"github.com/slimtoolkit/slim/pkg/docker/dockerutil"
"github.com/slimtoolkit/slim/pkg/util/errutil"
)
// HandleDockerRuntime implements support for the docker runtime
func HandleDockerRuntime(
logger *log.Entry,
xc *app.ExecutionContext,
gparams *command.GenericParams,
commandParams *CommandParams,
client *dockerapi.Client,
sid string,
debugContainerName string) {
if commandParams.ActionListDebuggableContainers {
xc.Out.State("action.list_debuggable_containers")
result, err := listDockerDebuggableContainers(client)
if err != nil {
logger.WithError(err).Error("listDockerDebuggableContainers")
xc.FailOn(err)
}
xc.Out.Info("debuggable.containers", ovars{"count": len(result)})
for cname, iname := range result {
xc.Out.Info("debuggable.container", ovars{"name": cname, "image": iname})
}
return
}
//todo: need to check that if targetRef is not empty it is valid
if commandParams.ActionListSessions {
xc.Out.State("action.list_sessions", ovars{"target": commandParams.TargetRef})
//later will track/show additional debug session info
result, err := listDockerDebugContainers(client, commandParams.TargetRef, false)
if err != nil {
logger.WithError(err).Error("listDockerDebugContainers")
xc.FailOn(err)
}
var waitingCount int
var runningCount int
var terminatedCount int
for _, info := range result {
switch info.State {
case CSWaiting:
waitingCount++
case CSRunning:
runningCount++
case CSTerminated:
terminatedCount++
}
}
xc.Out.Info("debug.session.count",
ovars{
"total": len(result),
"running": runningCount,
"waiting": waitingCount,
"terminated": terminatedCount,
})
for name, info := range result {
outParams := ovars{
"target": info.TargetContainerName,
"name": name,
"image": info.SpecImage,
"state": info.State,
"start.time": info.StartTime,
}
/*
if info.State == CSTerminated {
outParams["exit.code"] = info.ExitCode
outParams["finish.time"] = info.FinishTime
if info.ExitReason != "" {
outParams["exit.reason"] = info.ExitReason
}
if info.ExitMessage != "" {
outParams["exit.message"] = info.ExitMessage
}
}
*/
xc.Out.Info("debug.session", outParams)
}
return
}
if commandParams.ActionShowSessionLogs {
xc.Out.State("action.show_session_logs",
ovars{
"target": commandParams.TargetRef,
"session": commandParams.Session})
result, err := listDockerDebugContainers(client, commandParams.TargetRef, false)
if err != nil {
logger.WithError(err).Error("listDockerDebugContainers")
xc.FailOn(err)
}
if len(result) < 1 {
xc.Out.Info("no.debug.session")
return
}
//todo: need to pick the last session if commandParams.Session is empty
var containerID string
for _, info := range result {
if commandParams.Session == "" {
commandParams.Session = info.Name
}
if commandParams.Session == info.Name {
containerID = info.ContainerID
}
break
}
xc.Out.Info("container.logs.target", ovars{
"container.name": commandParams.Session,
"container.id": containerID})
if err := dumpDockerContainerLogs(logger, xc, client, containerID); err != nil {
logger.WithError(err).Error("dumpDockerContainerLogs")
}
return
}
if commandParams.ActionConnectSession {
xc.Out.State("action.connect_session",
ovars{
"target": commandParams.TargetRef,
"session": commandParams.Session})
result, err := listDockerDebugContainers(client, commandParams.TargetRef, true)
if err != nil {
logger.WithError(err).Error("listDockerDebugContainers")
xc.FailOn(err)
}
if len(result) < 1 {
xc.Out.Info("no.debug.session")
return
}
//todo: need to pick the last session if commandParams.Session is empty
var containerID string
for _, info := range result {
if commandParams.Session == "" {
commandParams.Session = info.Name
}
if commandParams.Session == info.Name {
containerID = info.ContainerID
}
break
}
//todo: need to validate that the session container exists and it's running
r, w := io.Pipe()
go io.Copy(w, os.Stdin)
options := dockerapi.AttachToContainerOptions{
Container: containerID,
InputStream: r,
OutputStream: os.Stdout,
ErrorStream: os.Stderr,
Stdin: true,
Stdout: true,
Stderr: true,
Stream: true,
RawTerminal: true,
Logs: true,
}
err = client.AttachToContainer(options)
xc.FailOn(err)
return
}
imageInspector, err := image.NewInspector(client, commandParams.DebugContainerImage)
errutil.FailOn(err)
noImage, err := imageInspector.NoImage()
errutil.FailOn(err)
if noImage {
err := imageInspector.Pull(true, "", "", "")
xc.FailOn(err)
}
targetContainerInfo, err := client.InspectContainer(commandParams.TargetRef)
if err != nil {
xc.Out.Error("target.container.inspect", err.Error())
xc.Out.State("exited",
ovars{
"exit.code": -1,
})
xc.Exit(-1)
}
if commandParams.DoRunAsTargetShell {
logger.Trace("doRunAsTargetShell")
commandParams.Entrypoint = ShellCommandPrefix(commandParams.DebugContainerImage)
shellConfig := configShell(sid, false)
if CgrSlimToolkitDebugImage == commandParams.DebugContainerImage {
shellConfig = configShellAlt(sid, false)
}
commandParams.Cmd = []string{shellConfig}
} else {
if len(commandParams.Cmd) == 0 &&
CgrSlimToolkitDebugImage == commandParams.DebugContainerImage {
commandParams.Cmd = []string{bashShellName}
}
}
options := container.ExecutionOptions{
ContainerName: debugContainerName,
Entrypoint: commandParams.Entrypoint,
Cmd: commandParams.Cmd,
Terminal: commandParams.DoTerminal,
}
exe, err := container.NewExecution(
xc,
logger,
client,
commandParams.DebugContainerImage,
&options,
nil,
true,
true)
// attach network, IPC & PIDs, essentially this is run --network container:golang_service --pid container:golang_service --ipc container:golang_service
mode := fmt.Sprintf("container:%s", commandParams.TargetRef)
if targetContainerInfo.HostConfig.IpcMode == "shareable" {
exe.IpcMode = mode
}
exe.NetworkMode = mode
exe.PidMode = mode
xc.FailOn(err)
err = exe.Start()
xc.FailOn(err)
_, err = exe.Wait()
xc.FailOn(err)
defer func() {
err = exe.Cleanup()
errutil.WarnOn(err)
}()
if !commandParams.DoTerminal {
exe.ShowContainerLogs()
}
}
func listDockerDebuggableContainers(client *dockerapi.Client) (map[string]string, error) {
const op = "debug.listDockerDebuggableContainers"
containers, err := dockerutil.ListContainers(client, "", false)
if err != nil {
log.WithFields(log.Fields{
"op": op,
"containers.count": len(containers),
}).Error("dockerutil.ListContainers")
return nil, err
}
activeContainers := map[string]string{}
for name, info := range containers {
if info.State != dockerutil.CSRunning {
log.WithFields(log.Fields{
"op": "listDockerDebuggableContainers",
"container": name,
"state": info.State,
}).Trace("ignoring.nonrunning.container")
continue
}
if strings.HasPrefix(name, containerNamePrefix) {
log.WithFields(log.Fields{
"op": "listDockerDebuggableContainers",
"container": name,
}).Trace("ignoring.debug.container")
continue
}
activeContainers[name] = info.Image
}
return activeContainers, nil
}
func listDebuggableDockerContainersWithConfig(client *dockerapi.Client) (map[string]string, error) {
//todo: pass the docker client config params instead of the existing client
return listDockerDebuggableContainers(client)
}
func listDockerDebugContainers(
client *dockerapi.Client,
targetContainer string,
onlyActive bool) (map[string]*DebugContainerInfo, error) {
containers, err := dockerutil.ListContainers(client, "", true)
if err != nil {
return nil, err
}
result := map[string]*DebugContainerInfo{}
for name, container := range containers {
if !strings.HasPrefix(name, containerNamePrefix) {
log.WithFields(log.Fields{
"op": "listDockerDebugContainers",
"container": name,
}).Trace("ignoring.nondebug.container")
continue
}
//todo: filter by targetContainer (when info.TargetContainerName is populated)
t := time.Unix(container.Created, 0) //UnixMilli, UnixMicro
info := &DebugContainerInfo{
//TargetContainerName: info.TargetContainerName,
Name: container.Name,
SpecImage: container.Image,
ContainerID: container.ID,
//Command: info.Command,
//Args: info.Args,
//WorkingDir: info.WorkingDir,
//TTY: info.TTY,
StartTime: fmt.Sprintf("%v", t),
}
switch container.State {
case dockerutil.CSCreated, dockerutil.CSRestarting, dockerutil.CSPaused:
info.State = CSWaiting
case dockerutil.CSRunning:
info.State = CSRunning
case dockerutil.CSRemoving, dockerutil.CSExited, dockerutil.CSDead:
info.State = CSTerminated
}
if onlyActive {
if info.State == CSRunning {
result[info.Name] = info
}
} else {
result[info.Name] = info
}
}
return result, nil
}
func listDockerDebugContainersWithConfig(
client *dockerapi.Client,
targetContainer string,
onlyActive bool) (map[string]*DebugContainerInfo, error) {
//todo: pass the docker client config params instead of the existing client
return listDockerDebugContainers(client, targetContainer, onlyActive)
}
func dumpDockerContainerLogs(
logger *log.Entry,
xc *app.ExecutionContext,
client *dockerapi.Client,
containerID string) error {
logger.Tracef("dumpDockerContainerLogs(%s)", containerID)
outData, errData, err := dockerutil.GetContainerLogs(client, containerID, true)
if err != nil {
logger.WithError(err).Error("error reading container logs")
return err
}
xc.Out.Info("container.logs.start")
xc.Out.LogDump("debug.container.logs.stdout", string(outData))
xc.Out.LogDump("debug.container.logs.stderr", string(errData))
xc.Out.Info("container.logs.end")
return nil
}