init project

This commit is contained in:
root
2026-07-31 13:12:54 -04:00
parent 0da92d5e02
commit f3863f760c
7215 changed files with 1860260 additions and 1 deletions
+35
View File
@@ -0,0 +1,35 @@
{
"env": {
"mocha": true,
"node": true
},
"rules": {
/* Possible Errors */
"no-extra-parens": 2,
"valid-jsdoc": 2,
/* Best Practices */
"block-scoped-var": 2,
"complexity": [1, 3],
"default-case": 2,
"dot-notation": [2],
"guard-for-in": 2,
"no-div-regex": 2,
"no-else-return": 2,
"no-eq-null": 2,
"no-floating-decimal": 2,
"no-process-env": 2,
"no-self-compare": 2,
"no-void": 2,
"no-warning-comments": 2,
"radix": 2,
"vars-on-top": 2,
"wrap-iife": 2,
/* Variables */
"no-catch-shadow": 2,
/* Node.JS */
"no-sync": 2,
/* Stylistic Issues */
"no-mixed-spaces-and-tabs": 2,
"no-underscore-dangle": 2,
"quotes": [1, "single", "avoid-escape"]
}}
+1
View File
@@ -0,0 +1 @@
github: apocas
+63
View File
@@ -0,0 +1,63 @@
name: CI
on:
push:
branches: ['master']
pull_request:
branches: ['master']
permissions:
contents: read
jobs:
unit-tests:
name: unit tests / node ${{ matrix.node-version }}
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [16.x, 18.x, 20.x, 22.x, 24.x]
steps:
- uses: actions/checkout@v6
name: checkout docker-modem
with:
path: 'docker-modem'
- name: setup node ${{ matrix.node-version }}
uses: actions/setup-node@v6
with:
node-version: ${{ matrix.node-version }}
- name: npm ci (docker-modem)
run: npm ci
working-directory: 'docker-modem'
- name: npm test (docker-modem)
run: npm test
working-directory: 'docker-modem'
- uses: actions/checkout@v6
name: checkout apocas/dockerode
with:
repository: 'apocas/dockerode'
fetch-depth: '1'
path: 'dockerode'
- name: npm ci (dockerode)
run: npm ci
working-directory: 'dockerode'
- name: link docker-modem in dockerode/node_modules
run: |
rm -rf ./dockerode/node_modules/docker-modem
cp -R ./docker-modem ./dockerode/node_modules/docker-modem
- name: provisioning
run: |
docker pull ubuntu
- name: npm test (dockerode)
run: npm test
working-directory: 'dockerode'
+36
View File
@@ -0,0 +1,36 @@
sudo: required
git:
quiet: true
language: node_js
node_js:
- "8"
before_script:
- docker pull ubuntu
services:
- docker
before_install:
- curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo apt-key add -
- sudo add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable"
- sudo apt-get update
- sudo apt-get -y install docker-ce
- cd ..
- git clone --depth=50 --branch=master https://github.com/apocas/dockerode.git
- cd dockerode
- npm install
- cd ../docker-modem
install:
- npm install
script:
- npm test
- cd ../dockerode
- rm -rf ./node_modules/docker-modem
- npm install git://github.com/apocas/docker-modem
- npm test
+22
View File
@@ -0,0 +1,22 @@
{
"version": "0.2.0",
"configurations": [
{
"args": [
"--colors",
"${workspaceFolder}/test",
"-R",
"spec",
"--exit"
],
"internalConsoleOptions": "openOnSessionStart",
"name": "Mocha Tests",
"program": "./node_modules/mocha/bin/mocha.js",
"request": "launch",
"skipFiles": [
"<node_internals>/**"
],
"type": "node"
}
]
}
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright {yyyy} {name of copyright owner}
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+64
View File
@@ -0,0 +1,64 @@
# docker-modem
[Docker](https://www.docker.com/)'s Remote API network layer module.
`docker-modem` will help you interacting with `Docker`, since it already implements all the network strategies needed to support all `Docker`'s Remote API endpoints.
It is the module powering (network wise) [dockerode](https://github.com/apocas/dockerode) and other modules.
## Usage
### Getting started
``` js
var Modem = require('docker-modem');
var modem1 = new Modem({socketPath: '/var/run/docker.sock'});
var modem2 = new Modem(); //defaults to above if env variables are not used
var modem3 = new Modem({host: 'http://192.168.1.10', port: 3000});
var modem4 = new Modem({protocol:'http', host: '127.0.0.1', port: 3000});
var modem5 = new Modem({host: '127.0.0.1', port: 3000}); //defaults to http
```
### SSH
You can connect to the Docker daemon via SSH in two ways:
* Using the built-in SSH agent.
* Implement your own custom agent.
``` js
//built-in SSH agent
var modem1 = new Modem({
protocol: 'ssh',
host: 'ssh://127.0.0.1',
port: 22
});
//custom agent
var customAgent = myOwnSSHAgent({host: 'ssh://127.0.0.1', port: 22});
var modem2 = new Modem({
agent: customAgent,
});
```
## Tests
* Tests are implemented using `mocha` and `chai`. Run them with `npm test`.
* Check [dockerode](https://github.com/apocas/dockerode) tests, which is indirectly co-testing `docker-modem`.
## Sponsors
Amazing entities that [sponsor](https://github.com/sponsors/apocas) my open-source work. Check them out!
[![HTTP Toolkit](https://avatars.githubusercontent.com/u/39777515?s=100)](https://github.com/httptoolkit)
[![OOMOL - Oomol AI Studio](https://avatars.githubusercontent.com/u/146153906?s=100)](https://oomol.com)
## License
Pedro Dias - [@pedromdias](https://twitter.com/pedromdias)
Licensed under the Apache license, version 2.0 (the "license"); You may not use this file except in compliance with the license. You may obtain a copy of the license at:
http://www.apache.org/licenses/LICENSE-2.0.html
Unless required by applicable law or agreed to in writing, software distributed under the license is distributed on an "as is" basis, without warranties or conditions of any kind, either express or implied. See the license for the specific language governing permissions and limitations under the license.
+87
View File
@@ -0,0 +1,87 @@
//Based on follow-redirects v0.0.x
var nativeHttps = require('https'),
nativeHttp = require('http'),
url = require('url'),
utils = require('./utils');
var maxRedirects = module.exports.maxRedirects = 5;
var protocols = {
https: nativeHttps,
http: nativeHttp
};
for (var protocol in protocols) {
var h = function() {};
h.prototype = protocols[protocol];
h = new h();
h.request = function(h) {
return function(options, callback, redirectOptions) {
redirectOptions = redirectOptions || {};
var max = (typeof options === 'object' && 'maxRedirects' in options) ? options.maxRedirects : exports.maxRedirects;
var redirect = utils.extend({
count: 0,
max: max,
clientRequest: null,
userCallback: callback
}, redirectOptions);
if (redirect.count > redirect.max) {
var err = new Error('Max redirects exceeded. To allow more redirects, pass options.maxRedirects property.');
redirect.clientRequest.emit('error', err);
return redirect.clientRequest;
}
redirect.count++;
var reqUrl;
if (typeof options === 'string') {
reqUrl = options;
} else {
reqUrl = url.format(utils.extend({
protocol: protocol
}, options));
}
var clientRequest = Object.getPrototypeOf(h).request(options, redirectCallback(reqUrl, redirect));
if (!redirect.clientRequest) redirect.clientRequest = clientRequest;
function redirectCallback(reqUrl, redirect) {
return function(res) {
if (res.statusCode < 300 || res.statusCode > 399) {
return redirect.userCallback(res);
}
if (!('location' in res.headers)) {
return redirect.userCallback(res);
}
var redirectUrl = url.resolve(reqUrl, res.headers.location);
var proto = url.parse(redirectUrl).protocol;
proto = proto.substr(0, proto.length - 1);
return module.exports[proto].get(redirectUrl, redirectCallback(reqUrl, redirect), redirect);
};
}
return clientRequest;
};
}(h);
// see https://github.com/joyent/node/blob/master/lib/http.js#L1623
h.get = function(h) {
return function(options, cb, redirectOptions) {
var req = h.request(options, cb, redirectOptions);
req.end();
return req;
};
}(h);
module.exports[protocol] = h;
}
+55
View File
@@ -0,0 +1,55 @@
module.exports = HttpDuplex;
var util = require('util'),
stream = require('readable-stream');
util.inherits(HttpDuplex, stream.Duplex);
function HttpDuplex(req, res, options) {
var self = this;
if (!(self instanceof HttpDuplex)) return new HttpDuplex(req, res, options);
stream.Duplex.call(self, options);
self._output = null;
self.connect(req, res);
}
HttpDuplex.prototype.connect = function(req, res) {
var self = this;
self.req = req;
self._output = res;
self.emit('response', res);
res.on('data', function(c) {
if (!self.push(c)) self._output.pause();
});
res.on('end', function() {
self.push(null);
});
};
HttpDuplex.prototype._read = function(n) {
if (this._output) this._output.resume();
};
HttpDuplex.prototype._write = function(chunk, encoding, cb) {
this.req.write(chunk, encoding);
cb();
};
HttpDuplex.prototype.end = function(chunk, encoding, cb) {
this._output.socket.destroySoon();
return this.req.end(chunk, encoding, cb);
};
HttpDuplex.prototype.destroy = function() {
this.req.destroy();
this._output.socket.destroy();
};
HttpDuplex.prototype.destroySoon = function() {
this.req.destroy();
this._output.socket.destroy();
};
+577
View File
@@ -0,0 +1,577 @@
var querystring = require('querystring'),
http = require('./http'),
fs = require('fs'),
path = require('path'),
url = require('url'),
ssh = require('./ssh'),
HttpDuplex = require('./http_duplex'),
debug = require('debug')('modem'),
utils = require('./utils'),
util = require('util'),
splitca = require('split-ca'),
os = require('os'),
isWin = os.type() === 'Windows_NT',
stream = require('stream');
var defaultOpts = function () {
var host;
var opts = {};
if (!process.env.DOCKER_HOST) {
// Windows socket path: //./pipe/docker_engine ( Windows 10 )
// Linux & Darwin socket path is /var/run/docker.sock when running system-wide,
// or $HOME/.docker/run/docker.sock in new Docker Desktop installs.
opts.socketPath = isWin ? '//./pipe/docker_engine' : findDefaultUnixSocket;
} else if (process.env.DOCKER_HOST.indexOf('unix://') === 0) {
// Strip off unix://, fall back to default if unix:// was passed without a path
opts.socketPath = process.env.DOCKER_HOST.substring(7) || findDefaultUnixSocket;
} else if (process.env.DOCKER_HOST.indexOf('npipe://') === 0) {
// Strip off npipe://, fall back to default of //./pipe/docker_engine if
// npipe:// was passed without a path
opts.socketPath = process.env.DOCKER_HOST.substring(8) || '//./pipe/docker_engine';
} else {
var hostStr = process.env.DOCKER_HOST;
if (hostStr.indexOf('\/\/') < 0) {
hostStr = 'tcp://' + hostStr;
}
try {
host = new url.URL(hostStr);
} catch (err) {
throw new Error('DOCKER_HOST env variable should be something like tcp://localhost:1234');
}
opts.port = host.port;
if (process.env.DOCKER_TLS_VERIFY === '1' || opts.port === '2376') {
opts.protocol = 'https';
} else if (host.protocol === 'ssh:') {
opts.protocol = 'ssh';
opts.username = host.username;
opts.sshOptions = {
agent: process.env.SSH_AUTH_SOCK,
}
} else {
opts.protocol = 'http';
}
if (process.env.DOCKER_PATH_PREFIX) {
opts.pathPrefix = process.env.DOCKER_PATH_PREFIX;
}
else {
opts.pathPrefix = '/';
}
opts.host = host.hostname;
if (process.env.DOCKER_CERT_PATH) {
opts.ca = splitca(path.join(process.env.DOCKER_CERT_PATH, 'ca.pem'));
opts.cert = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'cert.pem'));
opts.key = fs.readFileSync(path.join(process.env.DOCKER_CERT_PATH, 'key.pem'));
}
if (process.env.DOCKER_CLIENT_TIMEOUT) {
opts.timeout = parseInt(process.env.DOCKER_CLIENT_TIMEOUT, 10);
}
}
return opts;
};
var findDefaultUnixSocket = function () {
return new Promise(function (resolve) {
var userDockerSocket = path.join(os.homedir(), '.docker', 'run', 'docker.sock');
fs.access(userDockerSocket, function (err) {
if (err) resolve('/var/run/docker.sock');
else resolve(userDockerSocket);
})
});
}
var Modem = function (options) {
var optDefaults = defaultOpts();
var opts = Object.assign({}, optDefaults, options);
this.host = opts.host;
if (!this.host) {
this.socketPath = opts.socketPath;
}
this.port = opts.port;
this.pathPrefix = opts.pathPrefix;
this.username = opts.username;
this.password = opts.password;
this.version = opts.version;
this.key = opts.key;
this.cert = opts.cert;
this.ca = opts.ca;
this.timeout = opts.timeout;
this.connectionTimeout = opts.connectionTimeout;
this.checkServerIdentity = opts.checkServerIdentity;
this.agent = opts.agent;
this.headers = opts.headers || {};
this.sshOptions = Object.assign({}, options ? options.sshOptions : {}, optDefaults.sshOptions);
//retrocompabitlity
if (this.sshOptions.agentForward === undefined) {
this.sshOptions.agentForward = opts.agentForward;
}
if (this.key && this.cert && this.ca) {
this.protocol = 'https';
}
this.protocol = opts.protocol || this.protocol || 'http';
};
Modem.prototype.dial = function (options, callback) {
var opts, address, data;
if (options.options) {
opts = options.options;
}
// Prevent credentials from showing up in URL
if (opts && opts.authconfig) {
delete opts.authconfig;
}
// Prevent abortsignal from showing up in the URL
if (opts && opts.abortSignal) {
delete opts.abortSignal;
}
if (this.version) {
options.path = '/' + this.version + options.path;
}
if (this.host) {
var parsed = url.parse(this.host);
address = url.format({
protocol: parsed.protocol || this.protocol,
hostname: parsed.hostname || this.host,
port: this.port,
pathname: parsed.pathname || this.pathPrefix,
});
address = url.resolve(address, options.path);
} else {
address = options.path;
}
if (options.path.indexOf('?') !== -1) {
if (opts && Object.keys(opts).length > 0) {
address += this.buildQuerystring(opts._query || opts);
} else {
address = address.substring(0, address.length - 1);
}
}
var optionsf = {
path: address,
method: options.method,
headers: options.headers || Object.assign({}, this.headers),
key: this.key,
cert: this.cert,
ca: this.ca
};
if (this.checkServerIdentity) {
optionsf.checkServerIdentity = this.checkServerIdentity;
}
if (this.agent) {
optionsf.agent = this.agent;
}
if (options.authconfig) {
optionsf.headers['X-Registry-Auth'] = options.authconfig.key || options.authconfig.base64 ||
Buffer.from(JSON.stringify(options.authconfig)).toString('base64').replace(/\+/g, "-").replace(/\//g, "_");
}
if (options.registryconfig) {
optionsf.headers['X-Registry-Config'] = options.registryconfig.base64 ||
Buffer.from(JSON.stringify(options.registryconfig)).toString('base64');
}
if (options.abortSignal) {
optionsf.signal = options.abortSignal;
}
if (options.file) {
if (typeof options.file === 'string') {
data = fs.createReadStream(path.resolve(options.file));
} else {
data = options.file;
}
optionsf.headers['Content-Type'] = options?.headers?.['Content-Type'] ?? 'application/tar';
} else if (opts && options.method === 'POST') {
data = JSON.stringify(opts._body || opts);
if (options.allowEmpty) {
optionsf.headers['Content-Type'] = options?.headers?.['Content-Type'] ?? 'application/json';
} else {
if (data !== '{}' && data !== '""') {
optionsf.headers['Content-Type'] = options?.headers?.['Content-Type'] ?? 'application/json';
} else {
data = undefined;
}
}
}
if (typeof data === 'string') {
optionsf.headers['Content-Length'] = Buffer.byteLength(data);
} else if (Buffer.isBuffer(data) === true) {
optionsf.headers['Content-Length'] = data.length;
} else if (optionsf.method === 'PUT' || options.hijack || options.openStdin) {
optionsf.headers['Transfer-Encoding'] = 'chunked';
}
if (options.hijack) {
optionsf.headers.Connection = 'Upgrade';
optionsf.headers.Upgrade = optionsf.headers.Upgrade ?? 'tcp';
}
if (this.socketPath) {
// SocketPath may be a function that can return a promise:
this.getSocketPath().then((socketPath) => {
optionsf.socketPath = socketPath;
this.buildRequest(optionsf, options, data, callback);
});
} else {
var urlp = url.parse(address);
optionsf.hostname = urlp.hostname;
optionsf.port = urlp.port;
optionsf.path = urlp.path;
this.buildRequest(optionsf, options, data, callback);
}
};
Modem.prototype.getSocketPath = function () {
if (!this.socketPath) return;
if (this.socketPathCache) return Promise.resolve(this.socketPathCache);
var socketPathValue = typeof this.socketPath === 'function'
? this.socketPath() : this.socketPath;
this.socketPathCache = socketPathValue;
return Promise.resolve(socketPathValue);
}
Modem.prototype.buildRequest = function (options, context, data, callback) {
var self = this;
var connectionTimeoutTimer;
var finished = false;
var opts = self.protocol === 'ssh' ? Object.assign(options, {
agent: ssh(Object.assign({}, self.sshOptions, {
'host': self.host,
'port': self.port,
'username': self.username,
'password': self.password,
})),
protocol: 'http:',
}) : options;
var req = null;
try {
req = http[self.protocol === 'ssh' ? 'http' : self.protocol].request(opts, function () { });
} catch (e) {
callback(e);
return;
}
debug('Sending: %s', util.inspect(options, {
showHidden: true,
depth: null
}));
if (self.connectionTimeout) {
connectionTimeoutTimer = setTimeout(function () {
debug('Connection Timeout of %s ms exceeded', self.connectionTimeout);
req.destroy();
}, self.connectionTimeout);
}
if (self.timeout) {
req.setTimeout(self.timeout);
req.on('timeout', function () {
debug('Timeout of %s ms exceeded', self.timeout);
req.destroy();
});
}
if (context.hijack === true) {
clearTimeout(connectionTimeoutTimer);
req.on('upgrade', function (res, sock, head) {
if (finished === false) {
finished = true;
if (head.length > 0) {
sock.unshift(head);
}
return callback(null, sock);
}
});
}
req.on('connect', function () {
clearTimeout(connectionTimeoutTimer);
});
req.on('disconnect', function () {
clearTimeout(connectionTimeoutTimer);
});
req.on('response', function (res) {
clearTimeout(connectionTimeoutTimer);
if (context.isStream === true) {
if (finished === false) {
finished = true;
self.buildPayload(null, context.isStream, context.statusCodes, context.openStdin, req, res, null, callback);
}
} else {
// The native 'request' method only handles aborting during the request lifecycle not the response lifecycle.
// We need to make the response stream abortable so that it's destroyed with an error on abort and then
// it triggers the request 'error' event
if (options.signal != null) {
stream.addAbortSignal(options.signal, res)
}
var chunks = [];
res.on('data', function (chunk) {
chunks.push(chunk);
});
res.on('end', function () {
var buffer = Buffer.concat(chunks);
var result = buffer.toString();
debug('Received: %s', result);
var json = utils.parseJSON(result) || buffer;
if (finished === false) {
finished = true;
self.buildPayload(null, context.isStream, context.statusCodes, false, req, res, json, callback);
}
});
}
});
req.on('error', function (error) {
clearTimeout(connectionTimeoutTimer);
if (finished === false) {
finished = true;
self.buildPayload(error, context.isStream, context.statusCodes, false, {}, {}, null, callback);
}
});
if (typeof data === 'string' || Buffer.isBuffer(data)) {
req.write(data);
} else if (data) {
data.on('error', function (error) {
req.destroy(error);
});
data.pipe(req);
}
if (!context.openStdin && (typeof data === 'string' || data === undefined || Buffer.isBuffer(data))) {
req.end();
}
};
Modem.prototype.buildPayload = function (err, isStream, statusCodes, openStdin, req, res, json, cb) {
if (err) return cb(err, null);
if (statusCodes[res.statusCode] !== true) {
getCause(isStream, res, json, function (err, cause) {
if (err) {
return cb(err, null);
}
var msg = new Error(
'(HTTP code ' + res.statusCode + ') ' +
(statusCodes[res.statusCode] || 'unexpected') + ' - ' +
(cause.message || cause.error || cause) + ' '
);
msg.reason = statusCodes[res.statusCode];
msg.statusCode = res.statusCode;
msg.json = json;
cb(msg, null);
});
} else {
if (openStdin) {
cb(null, new HttpDuplex(req, res));
} else if (isStream) {
cb(null, res);
} else {
cb(null, json);
}
}
function getCause(isStream, res, json, callback) {
var chunks = '';
var done = false;
if (isStream) {
res.on('data', function (chunk) {
chunks += chunk;
});
res.on('error', function (err) {
handler(err, null);
});
res.on('end', function () {
handler(null, utils.parseJSON(chunks) || chunks)
});
} else {
callback(null, json);
}
function handler(err, data) {
if (done === false) {
if (err) {
callback(err);
} else {
callback(null, data);
}
}
done = true;
}
}
};
Modem.prototype.demuxStream = function (streama, stdout, stderr) {
var pendingStreamType = null;
var pendingDataLength = null;
var buffer = Buffer.from('');
function processData(data) {
if (data) {
buffer = Buffer.concat([buffer, data]);
}
if (pendingStreamType === null) {
if (buffer.length >= 8) {
var header = bufferSlice(8);
var streamType = header.readUInt8(0);
var dataLength = header.readUInt32BE(4);
// Validate stream type per Docker multiplex protocol:
// 0 = stdin, 1 = stdout, 2 = stderr
if (streamType !== 0 && streamType !== 1 && streamType !== 2) {
// Invalid header — stream is likely not multiplexed (e.g. TTY mode)
// or has become misaligned. Write the entire buffer as stdout
// and stop trying to demux.
var remaining = Buffer.concat([header, buffer]);
stdout.write(remaining);
buffer = Buffer.from('');
pendingStreamType = null;
pendingDataLength = null;
// Switch to raw passthrough for the rest of the stream
streama.removeListener('data', processData);
streama.on('data', function(chunk) {
stdout.write(chunk);
});
return;
}
pendingStreamType = streamType;
pendingDataLength = dataLength;
// It's possible we got a "data" that contains multiple messages
// Process the next one
processData();
}
} else {
if (buffer.length >= pendingDataLength) {
var content = bufferSlice(pendingDataLength);
if (pendingStreamType === 1) {
stdout.write(content);
} else {
stderr.write(content);
}
pendingStreamType = null;
pendingDataLength = null;
// It's possible we got a "data" that contains multiple messages
// Process the next one
processData();
}
}
}
function bufferSlice(end) {
var out = buffer.subarray(0, end);
buffer = Buffer.from(buffer.subarray(end, buffer.length));
return out;
}
streama.on('data', processData);
};
Modem.prototype.followProgress = function (streama, onFinished, onProgress) {
var buf = '';
var output = [];
var finished = false;
streama.on('data', onStreamEvent);
streama.on('error', onStreamError);
streama.on('end', onStreamEnd);
streama.on('close', onStreamEnd);
function onStreamEvent(data) {
buf += data.toString();
pump();
function pump() {
var pos;
while ((pos = buf.indexOf('\n')) >= 0) {
if (pos == 0) {
buf = buf.slice(1);
continue;
}
processLine(buf.slice(0, pos));
buf = buf.slice(pos + 1);
}
}
function processLine(line) {
if (line[line.length - 1] == '\r') line = line.substr(0, line.length - 1);
if (line.length > 0) {
var obj = JSON.parse(line);
output.push(obj);
if (onProgress) {
onProgress(obj);
}
}
}
};
function onStreamError(err) {
finished = true;
streama.removeListener('data', onStreamEvent);
streama.removeListener('error', onStreamError);
streama.removeListener('end', onStreamEnd);
streama.removeListener('close', onStreamEnd);
onFinished(err, output);
}
function onStreamEnd() {
if (!finished) onFinished(null, output);
finished = true;
}
};
Modem.prototype.buildQuerystring = function (opts) {
var clone = {};
Object.keys(opts).map(function (key, i) {
if (
opts[key] &&
typeof opts[key] === 'object' &&
!Array.isArray(opts[key])
) {
clone[key] = JSON.stringify(opts[key]);
} else {
clone[key] = opts[key];
}
});
return querystring.stringify(clone);
};
module.exports = Modem;
+48
View File
@@ -0,0 +1,48 @@
var Client = require('ssh2').Client,
http = require('http');
module.exports = function (opt) {
var conn = new Client();
var agent = new http.Agent();
agent.createConnection = function (options, fn) {
try {
conn.once('ready', function () {
conn.exec('docker system dial-stdio', function (err, stream) {
if (err) {
handleError(err , fn);
}
fn(null, stream);
stream.addListener('error', (err) => {
handleError(err, fn);
});
stream.once('close', () => {
conn.end();
agent.destroy();
});
});
}).on('error', (err) => {
handleError(err, fn);
})
.connect(opt);
conn.once('end', () => agent.destroy());
} catch (err) {
handleError(err);
}
};
function handleError(err, cb) {
conn.end();
agent.destroy();
if (cb) {
cb(err);
} else {
throw err;
}
}
return agent;
};
+24
View File
@@ -0,0 +1,24 @@
// https://github.com/HenrikJoreteg/extend-object/blob/v0.1.0/extend-object.js
var arr = [];
var each = arr.forEach;
var slice = arr.slice;
module.exports.extend = function(obj) {
each.call(slice.call(arguments, 1), function(source) {
if (source) {
for (var prop in source) {
obj[prop] = source[prop];
}
}
});
return obj;
};
module.exports.parseJSON = function(s) {
try {
return JSON.parse(s);
} catch (e) {
return null;
}
};
+32
View File
@@ -0,0 +1,32 @@
{
"name": "docker-modem",
"description": "Docker remote API network layer module.",
"version": "5.0.7",
"author": "Pedro Dias <petermdias@gmail.com>",
"maintainers": [
"apocas <petermdias@gmail.com>"
],
"license": "Apache-2.0",
"repository": {
"type": "git",
"url": "http://github.com/apocas/docker-modem.git"
},
"keywords": [
"containers",
"api",
"docker"
],
"dependencies": {
"debug": "^4.1.1",
"readable-stream": "^3.5.0",
"split-ca": "^1.0.1",
"ssh2": "^1.15.0"
},
"main": "./lib/modem",
"scripts": {
"test": "node --test"
},
"engines": {
"node": ">= 8.0"
}
}
+248
View File
@@ -0,0 +1,248 @@
var assert = require('node:assert');
var path = require('node:path');
var os = require('node:os');
var http = require('node:http');
var { describe, it, beforeEach } = require('node:test');
var Modem = require('../lib/modem');
var unixDefaultSocketPaths = ['/var/run/docker.sock', path.join(os.homedir(), '.docker/run/docker.sock')]
var defaultSocketPaths = os.type() === 'Windows_NT' ? ['//./pipe/docker_engine'] : unixDefaultSocketPaths;
describe('Modem', function () {
beforeEach(function () {
delete process.env.DOCKER_HOST;
});
it('should default to default socket path', function () {
var modem = new Modem();
return modem.getSocketPath().then((socketPath) => {
assert.ok(socketPath);
assert.ok(defaultSocketPaths.includes(socketPath));
});
});
it('should use specific cert, key and ca', function () {
var ca = 'caaaaa';
var cert = 'certtttt';
var key = 'keyyyyy';
var modem = new Modem({
version: 'v1.39',
host: '127.0.0.1',
port: 2376,
ca,
cert,
key
});
assert.strictEqual(ca, modem.ca);
assert.strictEqual(cert, modem.cert);
assert.strictEqual(key, modem.key);
});
it('shouldn\'t default to default socket path', function () {
var modem = new Modem({
protocol: 'http',
host: '127.0.0.1',
port: 2375
});
assert.ok(modem.host);
assert.strictEqual(modem.socketPath, undefined);
});
it('should use default value if argument not defined in constructor parameter object', function () {
var customHeaders = {
host: 'my-custom-host'
};
var modem = new Modem({
headers: customHeaders
});
assert.ok(modem.headers);
assert.strictEqual(modem.headers, customHeaders);
return modem.getSocketPath().then((socketPath) => {
assert.ok(socketPath);
assert.ok(defaultSocketPaths.includes(socketPath));
});
});
it('should allow DOCKER_HOST=unix:///path/to/docker.sock', function () {
process.env.DOCKER_HOST = 'unix:///tmp/docker.sock';
var modem = new Modem();
assert.ok(modem.socketPath);
assert.strictEqual(modem.host, undefined);
assert.strictEqual(modem.socketPath, '/tmp/docker.sock');
});
it('should interpret DOCKER_HOST=unix:// as /var/run/docker.sock', function () {
process.env.DOCKER_HOST = 'unix://';
var modem = new Modem();
return modem.getSocketPath().then((socketPath) => {
assert.ok(socketPath);
assert.ok(unixDefaultSocketPaths.includes(socketPath));
});
});
it('should use custom socketPath function once', function () {
var count = 0;
var modem = new Modem();
modem.socketPath = function() {
assert(++count === 1);
return 'testpath';
}
modem.getSocketPath().then((socketPath) => {
assert.ok(socketPath);
assert.ok('testpath');
});
return modem.getSocketPath().then((socketPath) => {
assert.ok(socketPath);
assert.ok('testpath');
});
});
it('should interpret DOCKER_HOST=tcp://N.N.N.N:2376 as https', function () {
process.env.DOCKER_HOST = 'tcp://192.168.59.103:2376';
var modem = new Modem();
assert.ok(modem.host);
assert.ok(modem.port);
assert.ok(modem.protocol);
assert.strictEqual(modem.host, '192.168.59.103');
assert.strictEqual(modem.port, '2376');
assert.strictEqual(modem.protocol, 'https');
});
it('should interpret DOCKER_HOST=tcp://[::1]:12345', function () {
process.env.DOCKER_HOST = 'tcp://[::1]:12345';
var modem = new Modem();
assert.ok(modem.host);
assert.ok(modem.port);
assert.ok(modem.protocol);
assert.strictEqual(modem.host, '[::1]');
assert.strictEqual(modem.port, '12345');
assert.strictEqual(modem.protocol, 'http');
});
it('should interpret DOCKER_HOST=tcp://N.N.N.N:5555 as http', function () {
delete process.env.DOCKER_TLS_VERIFY;
process.env.DOCKER_HOST = 'tcp://192.168.59.105:5555';
var modem = new Modem();
assert.ok(modem.host);
assert.ok(modem.port);
assert.ok(modem.protocol);
assert.strictEqual(modem.host, '192.168.59.105');
assert.strictEqual(modem.port, '5555');
assert.strictEqual(modem.protocol, 'http');
});
it('should interpret DOCKER_HOST=tcp://N.N.N.N:5555 as http', function () {
process.env.DOCKER_TLS_VERIFY = '1';
process.env.DOCKER_HOST = 'tcp://192.168.59.105:5555';
var modem = new Modem();
assert.ok(modem.host);
assert.ok(modem.port);
assert.ok(modem.protocol);
assert.strictEqual(modem.host, '192.168.59.105');
assert.strictEqual(modem.port, '5555');
assert.strictEqual(modem.protocol, 'https');
});
it('should accept DOCKER_HOST=N.N.N.N:5555 as http', function () {
delete process.env.DOCKER_TLS_VERIFY;
process.env.DOCKER_HOST = '192.168.59.105:5555';
var modem = new Modem();
assert.ok(modem.host);
assert.ok(modem.port);
assert.ok(modem.protocol);
assert.strictEqual(modem.host, '192.168.59.105');
assert.strictEqual(modem.port, '5555');
assert.strictEqual(modem.protocol, 'http');
});
it('should auto encode querystring option maps as JSON', function () {
var modem = new Modem();
var opts = {
"limit": 12,
"filters": {
"label": [
"staging",
"env=green",
],
},
"t": [
"repo:latest",
"repo:1.0.0",
],
/* From /create/image */
changes: [
'WORKDIR /app',
'EXPOSE 80',
'ENTRYPOINT ["node"]',
'CMD ["app.js"]',
'USER root',
'ENV NODE_ENV=production',
'ENV SOME_PASSWORD=dockerpassword',
]
};
var control = 'limit=12&filters={"label"%3A["staging"%2C"env%3Dgreen"]}&t=repo%3Alatest&t=repo%3A1.0.0&changes=WORKDIR %2Fapp&changes=EXPOSE 80&changes=ENTRYPOINT ["node"]&changes=CMD ["app.js"]&changes=USER root&changes=ENV NODE_ENV%3Dproduction&changes=ENV SOME_PASSWORD%3Ddockerpassword';
var qs = modem.buildQuerystring(opts);
assert.strictEqual(decodeURI(qs), control);
});
it('should parse DOCKER_CLIENT_TIMEOUT from environment', function () {
process.env.DOCKER_HOST = '192.168.59.105:5555';
process.env.DOCKER_CLIENT_TIMEOUT = 3000;
var modem = new Modem();
assert.strictEqual(modem.timeout, 3000);
});
it('should use default http agent when no agent is specified', function () {
var modem = new Modem();
assert.strictEqual(typeof modem.agent, 'undefined');
});
it('should use custom http agent', function () {
var httpAgent = new http.Agent({
keepAlive: true
});
var modem = new Modem({
agent: httpAgent
});
assert.ok(modem.agent instanceof http.Agent);
assert.strictEqual(modem.agent, httpAgent);
});
it('should set default ssh agent options from DOCKER_HOST', function() {
process.env.DOCKER_HOST = 'ssh://user@192.168.59.105:5555';
process.env.SSH_AUTH_SOCK = '/var/lib/sock';
var modem = new Modem();
assert.strictEqual(modem.protocol, 'ssh');
assert.strictEqual(modem.username, 'user');
assert.ok(modem.sshOptions);
assert.strictEqual(modem.sshOptions.agent, '/var/lib/sock');
});
it('should combine custom ssh agent options', function() {
process.env.DOCKER_HOST = 'ssh://user@192.168.59.105:5555';
process.env.SSH_AUTH_SOCK = '/var/lib/sock';
var modem = new Modem({
sshOptions: {
foo: 'bar', // options are arbitrary, whatever ssh2 supports
},
});
assert.ok(modem.sshOptions);
assert.strictEqual(modem.sshOptions.agent, '/var/lib/sock');
assert.strictEqual(modem.sshOptions.foo, 'bar');
});
});