-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrun-interactive.js
More file actions
101 lines (89 loc) · 2.33 KB
/
Copy pathrun-interactive.js
File metadata and controls
101 lines (89 loc) · 2.33 KB
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
var Docker = require('dockerode')
var docker = new Docker()
var previousKey
var CTRL_P = '\u0010'
var CTRL_Q = '\u0011'
function handleError (err) {
console.log(err)
process.exit(1)
}
function handler (err, container) {
var attachOpts = {stream: true, stdin: true, stdout: true, stderr: true}
if (err) handleError(err)
container.attach(attachOpts, function handler (err, stream) {
if (err) handleError(err)
// Show outputs
stream.pipe(process.stdout)
// Connect stdin
var isRaw = process.isRaw
process.stdin.resume()
process.stdin.setEncoding('utf8')
process.stdin.setRawMode(true)
process.stdin.pipe(stream)
process.stdin.on('data', function (key) {
// Detects it is detaching a running container
if (previousKey === CTRL_P && key === CTRL_Q) exit(stream, isRaw)
previousKey = key
})
container.start(function (err, data) {
if (err) handleError(err)
resize(container)
process.stdout.on('resize', function () {
resize(container)
})
container.wait(function (err, data) {
if (err) handleError(err)
exit(stream, isRaw)
})
})
})
}
// Resize tty
function resize (container) {
var dimensions = {
h: process.stdout.rows,
w: process.stderr.columns
}
if (dimensions.h !== 0 && dimensions.w !== 0) {
container.resize(dimensions, function () {})
}
}
// Exit container
function exit (stream, isRaw) {
process.stdout.removeListener('resize', resize)
process.stdin.removeAllListeners()
process.stdin.setRawMode(isRaw)
process.stdin.resume()
stream.end()
process.exit()
}
function runInteractive (params) {
if (params.command && !Array.isArray(params.command)) {
params.command = params.command.split(' ')
}
if (params.entrypoint && !Array.isArray(params.entrypoint)) {
params.entrypoint = params.entrypoint.split(' ')
}
var optsc = {
Hostname: '',
User: '',
AttachStdin: true,
AttachStdout: true,
AttachStderr: true,
Tty: true,
OpenStdin: true,
StdinOnce: false,
Env: params.env || null,
Entrypoint: params.entrypoint,
Cmd: params.cmd,
Image: params.image,
HostConfig: {
Links: params.links,
Binds: params.binds
},
Volumes: {},
VolumesFrom: []
}
docker.createContainer(optsc, handler)
}
module.exports = runInteractive