-
Notifications
You must be signed in to change notification settings - Fork 32
/
index.js
264 lines (232 loc) · 8.4 KB
/
index.js
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
'use strict'
// call `docker inspect` for one or more containers
// errback receives an array of "docker run objects"
module.exports = function rekcod (containers, cb) {
let cbCalled = false
const stdout = []
const stderr = []
const child = require('child_process').spawn('docker', ['inspect'].concat(containers))
child.stderr.on('data', data => {
stderr.push(data)
})
child.stdout.on('data', data => {
stdout.push(data)
})
child.on('error', err => {
if (!cbCalled) {
cbCalled = true
cb(err)
}
})
child.on('close', (code, signal) => {
if (cbCalled) return
if (code !== 0) {
const err = new Error('docker inspect failed with code ' + code + ' from signal ' + signal)
err.code = code
err.signal = signal
if (stderr.length) err.stderr = stderr.join('')
if (stdout.length) err.stdout = stdout.join('')
cbCalled = true
return cb(err)
}
try {
cb(null, parse(stdout.join('')))
} catch (err) {
cb(err)
}
})
}
// file should be path to a file containing `docker inspect` output
// errback receives an array of "docker run objects"
module.exports.readFile = function readFile (file, cb) {
require('fs').readFile(file, { encoding: 'utf8' }, (err, fileContents) => {
if (err) return cb(err)
try {
cb(null, parse(fileContents))
} catch (err) {
cb(err)
}
})
}
// json string could be an array from `docker inspect` or
// a single inspected object; always returns an array
const parse = module.exports.parse = function parse (jsonString) {
return [].concat(translate(JSON.parse(jsonString)))
}
// translate a parsed array or object into "docker run objects"
// returns an array if given an array, otherwise returns an object
const translate = module.exports.translate = function translate (parsed) {
return Array.isArray(parsed) ? parsed.map(o => toRunObject(o)) : toRunObject(parsed)
}
function toRunObject (inspectObj) {
const run = {}
run.image = shortHash(inspectObj.Image)
run.id = shortHash(inspectObj.Id)
run.name = inspectObj.Name
if (run.name && run.name.indexOf('/') === 0) run.name = run.name.substring(1)
run.command = toRunCommand(inspectObj, run.name)
return run
}
function shortHash (hash) {
if (hash && hash.length && hash.length > 12) return hash.substring(0, 12)
return hash
}
function toRunCommand (inspectObj, name) {
let rc = append('docker run', '--name', name)
const hostcfg = inspectObj.HostConfig || {}
const networkMode = hostcfg.NetworkMode
const utsMode = hostcfg.UTSMode
const modes = { networkMode, utsMode }
rc = appendBoolean(rc, hostcfg.Privileged, '--privileged') // fixes #49
// TODO something about devices or capabilities instead of privileged?
// --cap-add: Add Linux capabilities
// --cap-drop: Drop Linux capabilities
// --device=[]: Allows you to run devices inside the container without the --privileged flag
// see https://docs.docker.com/engine/reference/run/#runtime-privilege-and-linux-capabilities
if (hostcfg.Runtime) rc = append(rc, '--runtime', hostcfg.Runtime)
rc = appendArray(rc, '-v', hostcfg.Binds)
rc = appendArray(rc, '--volumes-from', hostcfg.VolumesFrom)
if (hostcfg.PortBindings && isCompatible('-p', modes)) {
rc = appendObjectKeys(rc, '-p', hostcfg.PortBindings, ipPort => {
return ipPort.HostIp ? ipPort.HostIp + ':' + ipPort.HostPort : ipPort.HostPort
})
}
rc = appendArray(rc, '--link', hostcfg.Links, link => {
link = link.split(':')
if (link[0] && ~link[0].lastIndexOf('/')) link[0] = link[0].substring(link[0].lastIndexOf('/') + 1)
if (link[1] && ~link[1].lastIndexOf('/')) link[1] = link[1].substring(link[1].lastIndexOf('/') + 1)
return link[0] + ':' + link[1]
})
if (hostcfg.PublishAllPorts && isCompatible('-P', modes)) rc = rc + ' -P'
if (networkMode && networkMode !== 'default') {
rc = append(rc, '--net', networkMode)
}
if (utsMode && isCompatible('--uts', modes)) {
rc = append(rc, '--uts', utsMode)
}
if (hostcfg.RestartPolicy && hostcfg.RestartPolicy.Name) {
rc = append(rc, '--restart', hostcfg.RestartPolicy, policy => {
return policy.Name === 'on-failure' ? policy.Name + ':' + policy.MaximumRetryCount : policy.Name
})
}
if (isCompatible('--add-host', modes)) rc = appendArray(rc, '--add-host', hostcfg.ExtraHosts)
rc = appendArray(rc, '--group-add', hostcfg.GroupAdd)
if (hostcfg.PidMode) rc = append(rc, '--pid', hostcfg.PidMode)
rc = appendArray(rc, '--security-opt', hostcfg.SecurityOpt, quote)
const cfg = inspectObj.Config || {}
if (cfg.Hostname && isCompatible('-h', modes)) rc = append(rc, '-h', cfg.Hostname)
if (cfg.Domainname && isCompatible('--domainname', modes)) rc = append(rc, '--domainname', cfg.Domainname)
if (cfg.ExposedPorts && isCompatible('--expose', modes)) {
rc = appendObjectKeys(rc, '--expose', cfg.ExposedPorts)
}
if (cfg.Labels) {
// rc = appendObjectEntries(rc, '-l', cfg.Labels, '=')
rc = appendObjectKeys(rc, '-l', cfg.Labels)
}
rc = appendArray(rc, '-e', cfg.Env, quote)
rc = appendConfigBooleans(rc, cfg)
if (cfg.Entrypoint) rc = appendJoinedArray(rc, '--entrypoint', cfg.Entrypoint, ' ')
rc = rc + ' ' + (cfg.Image || inspectObj.Image)
if (cfg.Cmd) rc = appendJoinedArray(rc, null, cfg.Cmd, ' ')
return rc
}
// The following options are invalid in 'container' NetworkMode:
// --add-host
// -h, --hostname
// --dns
// --dns-search
// --dns-option
// --mac-address
// -p, --publish
// -P, --publish-all
// --expose
// The following options are invalid in 'host' UTSMode:
// -h, --hostname
// --domainname
function isCompatible (flag, modes) {
switch (flag) {
case '-h':
return !(modes.networkMode || '').startsWith('container:') && modes.utsMode !== 'host'
case '--add-host':
case '--dns':
case '--dns-search':
case '--dns-option':
case '--mac-address':
case '-p':
case '-P':
case '--expose':
return !(modes.networkMode || '').startsWith('container:')
case '--domainname':
return modes.utsMode !== 'host'
default:
return true
}
}
function quote (str) {
return '\'' + str.replace(/'/g, '\'\\\'\'') + '\''
}
function appendConfigBooleans (str, cfg) {
const stdin = cfg.AttachStdin === true
const stdout = cfg.AttachStdout === true
const stderr = cfg.AttachStderr === true
str = appendBoolean(str, !stdin && !stdout && !stderr, '-d')
str = appendBoolean(str, stdin, '-a', 'stdin')
str = appendBoolean(str, stdout, '-a', 'stdout')
str = appendBoolean(str, stderr, '-a', 'stderr')
str = appendBoolean(str, cfg.Tty === true, '-t')
str = appendBoolean(str, cfg.OpenStdin === true, '-i')
return str
}
function appendBoolean (str, bool, key, val) {
return bool ? (val ? append(str, key, val) : str + ' ' + key) : str
}
function appendJoinedArray (str, key, array, join) {
if (!Array.isArray(array)) return str
// --entrypoint "tini -- /docker-entrypoint.sh"
if (key) return append(str, key, array.join(join), joined => '"' + joined + '"')
// 'sh' '-c' '(a -a) && (b -b)'
return append(str, key, array.map(quote).join(join))
}
function appendObjectKeys (str, key, obj, transformer) {
let newStr = str
Object.keys(obj).forEach(k => {
newStr = append(newStr, key, { key: k, val: obj[k] }, agg => {
if (!agg.val) return agg.key
let v = ''
if (Array.isArray(agg.val)) {
// used for PortBindings
agg.val.forEach(valObj => {
v = (typeof transformer === 'function' ? transformer(valObj) : valObj)
})
} else if (typeof agg.val === 'string') {
// used for Labels
return agg.key + '=' + quote(agg.val)
}
// prefix used for PortBindings, key-only used for ExposedPorts
return (v ? v + ':' : '') + agg.key
})
})
return newStr
}
// function appendObjectEntries (str, key, obj, joiner) {
// let newStr = str
// Object.entries(obj).forEach(([k, v]) => {
// newStr = append(newStr, key, { key: k, val: v }, typeof joiner === 'function'
// ? joiner
// : agg => `${agg.key}${joiner}${quote(agg.val)}`
// )
// })
// return newStr
// }
function appendArray (str, key, array, transformer) {
if (!Array.isArray(array)) return str
let newStr = str
array.forEach(v => {
newStr = append(newStr, key, v, transformer)
})
return newStr
}
function append (str, key, val, transformer) {
if (!val) return str
return str + ' ' + (key ? key + ' ' : '') + (typeof transformer === 'function' ? transformer(val) : val)
}