Last active
November 25, 2016 10:27
-
-
Save tweinfeld/e737c2c126e65753b4b44920e6565265 to your computer and use it in GitHub Desktop.
Lib for executing command-line on Docker images. Shares similar interface to "child_process".
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const | |
| _ = require('lodash'), | |
| spawn = require('child_process').spawn, | |
| bacon = require('baconjs'); | |
| const bufferUp = function(stream){ | |
| return bacon | |
| .fromEvent(stream, 'data') | |
| .takeUntil(bacon.fromEvent(stream, 'close').take(1)) | |
| .fold([], '.concat') | |
| .map(Buffer.concat) | |
| }; | |
| const DockerShell = class { | |
| constructor(settings = { | |
| tls_verify: 1, | |
| host: "tcp://localhost:2376", | |
| cert_path: "", | |
| machine_name: "localhost" | |
| }){ | |
| this._env = { | |
| "DOCKER_TLS_VERIFY": settings["tls_verify"], | |
| "DOCKER_HOST": settings["host"], | |
| "DOCKER_CERT_PATH": settings["cert_path"], | |
| "DOCKER_MACHINE_NAME": settings["machine_name"] | |
| }; | |
| } | |
| spawn(imageName, args, { env } = {}){ | |
| return spawn('docker', ["run", "--rm -i", _.map( env || {}, (val, key)=>`-e "${key}"="${val}"`), imageName, args.join(' ')], { | |
| env: this._env, | |
| shell: true, | |
| cwd: __dirname, | |
| stdio: [] | |
| }); | |
| } | |
| exec(imageName, args, options){ | |
| let dockerShell = this.spawn(imageName, args, options); | |
| const cnv = (function(encoding){ return encoding ? (buf)=>buf.toString(encoding) : _.identity })(options.encoding); | |
| return bacon | |
| .combineTemplate({ | |
| stdout: bufferUp(dockerShell.stdout).map(cnv), | |
| stderr: bufferUp(dockerShell.stderr).map(cnv), | |
| code: bacon.fromEvent(dockerShell, 'close').take(1) | |
| }) | |
| .flatMap(({ stderr, stdout, code }) => bacon.once(code > 0 ? new bacon.Error(stderr) : stdout)) | |
| .take(1) | |
| .endOnError() | |
| .toPromise(); | |
| } | |
| }; | |
| module.exports = DockerShell; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment