Skip to content

Commit 76daae1

Browse files
Merge pull request #672 from embark-framework/3_1_0_defaultHost
docker awareness for 3_1_0
2 parents 807950d + 4d0b536 commit 76daae1

File tree

11 files changed

+100
-26
lines changed

11 files changed

+100
-26
lines changed

lib/cmds/blockchain/blockchain.js

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@ const constants = require('../../constants.json');
88
const GethCommands = require('./geth_commands.js');
99
const DevFunds = require('./dev_funds.js');
1010

11+
const {defaultHost, dockerHostSwap} = require('../../utils/host');
12+
1113
/*eslint complexity: ["error", 36]*/
1214
var Blockchain = function(options) {
1315
this.blockchainConfig = options.blockchainConfig;
@@ -31,7 +33,7 @@ var Blockchain = function(options) {
3133
genesisBlock: this.blockchainConfig.genesisBlock || false,
3234
datadir: this.blockchainConfig.datadir || false,
3335
mineWhenNeeded: this.blockchainConfig.mineWhenNeeded || false,
34-
rpcHost: this.blockchainConfig.rpcHost || 'localhost',
36+
rpcHost: dockerHostSwap(this.blockchainConfig.rpcHost) || defaultHost,
3537
rpcPort: this.blockchainConfig.rpcPort || 8545,
3638
rpcCorsDomain: this.blockchainConfig.rpcCorsDomain || false,
3739
networkId: this.blockchainConfig.networkId || 1337,
@@ -44,7 +46,7 @@ var Blockchain = function(options) {
4446
bootnodes: this.blockchainConfig.bootnodes || "",
4547
rpcApi: (this.blockchainConfig.rpcApi || ['eth', 'web3', 'net', 'debug']),
4648
wsRPC: (this.blockchainConfig.wsRPC === undefined) || this.blockchainConfig.wsRPC,
47-
wsHost: this.blockchainConfig.wsHost || 'localhost',
49+
wsHost: dockerHostSwap(this.blockchainConfig.wsHost) || defaultHost,
4850
wsPort: this.blockchainConfig.wsPort || 8546,
4951
wsOrigins: this.blockchainConfig.wsOrigins || false,
5052
wsApi: (this.blockchainConfig.wsApi || defaultWsApi),

lib/cmds/simulator.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ let shelljs = require('shelljs');
22
let proxy = require('../core/proxy');
33
const Ipc = require('../core/ipc');
44
const constants = require('../constants.json');
5+
const {defaultHost, dockerHostSwap} = require('../utils/host');
56

67
class Simulator {
78
constructor(options) {
@@ -21,7 +22,7 @@ class Simulator {
2122
}
2223

2324
let useProxy = this.blockchainConfig.proxy || false;
24-
let host = (options.host || this.blockchainConfig.rpcHost || 'localhost');
25+
let host = (dockerHostSwap(options.host || this.blockchainConfig.rpcHost) || defaultHost);
2526
let port = (options.port || this.blockchainConfig.rpcPort || 8545);
2627

2728
cmds.push("-p " + (port + (useProxy ? constants.blockchain.servicePortOnProxy : 0)));

lib/core/config.js

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ const utils = require('../utils/utils.js');
55
const path = require('path');
66
const deepEqual = require('deep-equal');
77
const constants = require('../constants');
8+
const {canonicalHost, defaultHost} = require('../utils/host');
89

910
var Config = function(options) {
1011
const self = this;
@@ -106,6 +107,9 @@ Config.prototype._updateBlockchainCors = function(){
106107
// remove /ipfs or /bzz: from getUrl if it's there
107108
let getUrlParts = storageConfig.upload.getUrl.split('/');
108109
getUrlParts = getUrlParts.slice(0, 3);
110+
let host = canonicalHost(getUrlParts[2].split(':')[0]);
111+
let port = getUrlParts[2].split(':')[1];
112+
getUrlParts[2] = port ? [host, port].join(':') : host;
109113
corsParts.push(getUrlParts.join('/'));
110114
}
111115
// use our modified getUrl or in case it wasn't specified, use a built url
@@ -246,7 +250,7 @@ Config.prototype.loadStorageConfigFile = function() {
246250
"upload": {
247251
"provider": "ipfs",
248252
"protocol": "http",
249-
"host": "localhost",
253+
"host" : defaultHost,
250254
"port": 5001,
251255
"getUrl": "http://localhost:8080/ipfs/"
252256
},
@@ -281,7 +285,9 @@ Config.prototype.loadCommunicationConfigFile = function() {
281285
"provider": "whisper",
282286
"available_providers": ["whisper"],
283287
"connection": {
284-
"host": "localhost", "port": 8546, "type": "ws"
288+
"host": defaultHost,
289+
"port": 8546,
290+
"type": "ws"
285291
}
286292
}
287293
};
@@ -293,7 +299,9 @@ Config.prototype.loadCommunicationConfigFile = function() {
293299

294300
Config.prototype.loadWebServerConfigFile = function() {
295301
var configObject = {
296-
"enabled": true, "host": "localhost", "port": 8000
302+
"enabled": true,
303+
"host": defaultHost,
304+
"port": 8000
297305
};
298306

299307
let configFilePath = this._getFileOrOject(this.configDir, 'webserver', 'webserver');

lib/core/proxy.js

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,11 @@ const http = require('http');
33
const constants = require('../constants.json');
44

55
let commList = {};
6-
let transactions = {};
6+
let transactions = {};
77
let receipts = {};
88

9+
const {canonicalHost, defaultHost} = require('../utils/host');
10+
911
const parseRequest = function(reqBody){
1012
let jsonO;
1113
try {
@@ -42,7 +44,7 @@ const parseResponse = function(ipc, resBody){
4244
commList[receipts[jsonO.id]].blockNumber = jsonO.result.blockNumber;
4345
commList[receipts[jsonO.id]].gasUsed = jsonO.result.gasUsed;
4446
commList[receipts[jsonO.id]].status = jsonO.result.status;
45-
47+
4648
if(ipc.connected && !ipc.connecting){
4749
ipc.request('log', commList[receipts[jsonO.id]]);
4850
} else {
@@ -61,7 +63,7 @@ const parseResponse = function(ipc, resBody){
6163
exports.serve = function(ipc, host, port, ws){
6264
let proxy = httpProxy.createProxyServer({
6365
target: {
64-
host,
66+
host: canonicalHost(host),
6567
port: port + constants.blockchain.servicePortOnProxy
6668
},
6769
ws: ws
@@ -80,7 +82,7 @@ exports.serve = function(ipc, host, port, ws){
8082
if(resBody){
8183
parseResponse(ipc, resBody);
8284
}
83-
});
85+
});
8486
});
8587

8688
let server = http.createServer((req, res) => {
@@ -110,16 +112,16 @@ exports.serve = function(ipc, host, port, ws){
110112
parseResponse(ipc, data.toString().substr(data.indexOf("{")));
111113
});
112114
});
113-
115+
114116
proxy.on('proxyReqWs', (proxyReq, req, socket) => {
115117
var parser = new WsParser(0, false);
116118
socket.pipe(parser);
117119
parser.on('frame', function (frame) {
118120
parseRequest(frame.data);
119121
});
120-
122+
121123
});
122124
}
123125

124-
server.listen(port);
126+
server.listen(port, defaultHost);
125127
};

lib/modules/webserver/index.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
var {canonicalHost} = require('../../utils/host.js');
12
var utils = require('../../utils/utils.js');
23
var Server = require('./server.js');
34

@@ -26,7 +27,7 @@ class WebServer {
2627
}
2728

2829
setServiceCheck() {
29-
let url = 'http://' + this.host + ':' + this.port;
30+
let url = 'http://' + canonicalHost(this.host) + ':' + this.port;
3031

3132
this.events.request("services:register", 'Webserver', function (cb) {
3233
utils.checkIsAvailable(url, function (available) {

lib/modules/webserver/server.js

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,19 +1,23 @@
11
let finalhandler = require('finalhandler');
22
let http = require('http');
33
let serveStatic = require('serve-static');
4+
const {canonicalHost, defaultHost, dockerHostSwap} = require('../../utils/host');
45
require('http-shutdown').extend();
56

67
class Server {
78
constructor(options) {
89
this.dist = options.dist || 'dist/';
910
this.port = options.port || 8000;
10-
this.hostname = options.host || 'localhost';
11+
this.hostname = dockerHostSwap(options.host) || defaultHost;
1112
this.logger = options.logger;
1213
}
1314

1415
start(callback) {
1516
if (this.server && this.server.listening) {
16-
this.logger.warn(__("a webserver is already running at") + " " + ("http://" + this.hostname + ":" + this.port).bold.underline.green);
17+
this.logger.warn(__("a webserver is already running at") +
18+
" " +
19+
("http://" + canonicalHost(this.hostname) +
20+
":" + this.port).bold.underline.green);
1721
if (callback) {
1822
callback();
1923
}
@@ -25,7 +29,10 @@ class Server {
2529
serve(req, res, finalhandler(req, res));
2630
}).withShutdown();
2731

28-
this.logger.info(__("webserver available at") + " " + ("http://" + this.hostname + ":" + this.port).bold.underline.green);
32+
this.logger.info(__("webserver available at") +
33+
" " +
34+
("http://" + canonicalHost(this.hostname) +
35+
":" + this.port).bold.underline.green);
2936
this.server.listen(this.port, this.hostname);
3037
if (callback) {
3138
callback();

lib/modules/whisper/index.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ let utils = require('../../utils/utils.js');
22
let fs = require('../../core/fs.js');
33
let Web3 = require('web3');
44

5+
const {canonicalHost, defaultHost} = require('../../utils/host');
6+
57
class Whisper {
68

79
constructor(embark, _options) {
@@ -69,7 +71,7 @@ class Whisper {
6971
let connection = this.communicationConfig.connection || {};
7072
// todo: make the add code a function as well
7173
let config = JSON.stringify({
72-
server: connection.host || 'localhost',
74+
server: canonicalHost(connection.host || defaultHost),
7375
port: connection.port || '8546',
7476
type: connection.type || 'ws'
7577
});

lib/processes/storageProcesses/storageProcessesLauncher.js

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ const utils = require('../../utils/utils');
44
const ProcessLauncher = require('../../process/processLauncher');
55
const constants = require('../../constants');
66
const StorageUtils = require('./storageUtils');
7+
const {canonicalHost} = require('../../utils/host');
78

89
class StorageProcessesLauncher {
910
constructor(options) {
@@ -46,6 +47,9 @@ class StorageProcessesLauncher {
4647
// remove /ipfs or /bzz: from getUrl if it's there
4748
let getUrlParts = dappConn.getUrl.split('/');
4849
getUrlParts = getUrlParts.slice(0, 3);
50+
let host = canonicalHost(getUrlParts[2].split(':')[0]);
51+
let port = getUrlParts[2].split(':')[1];
52+
getUrlParts[2] = port ? [host, port].join(':') : host;
4953
corsParts.push(getUrlParts.join('/'));
5054
}
5155
// in case getUrl wasn't specified, use a built url
@@ -59,12 +63,12 @@ class StorageProcessesLauncher {
5963
if(this.blockchainConfig.enabled) {
6064
// add our rpc endpoints to CORS
6165
if(this.blockchainConfig.rpcHost && this.blockchainConfig.rpcPort){
62-
corsParts.push(`http://${this.blockchainConfig.rpcHost}:${this.blockchainConfig.rpcPort}`);
66+
corsParts.push(`http://${canonicalHost(this.blockchainConfig.rpcHost)}:${this.blockchainConfig.rpcPort}`);
6367
}
6468

6569
// add our ws endpoints to CORS
6670
if(this.blockchainConfig.wsRPC && this.blockchainConfig.wsHost && this.blockchainConfig.wsPort){
67-
corsParts.push(`ws://${this.blockchainConfig.wsHost}:${this.blockchainConfig.wsPort}`);
71+
corsParts.push(`ws://${canonicalHost(this.blockchainConfig.wsHost)}:${this.blockchainConfig.wsPort}`);
6872
}
6973
}
7074
return corsParts;

lib/utils/host.js

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
const isDocker = (() => {
2+
let isDocker;
3+
4+
const hostname = require('os').hostname();
5+
const pattern = new RegExp(
6+
'[0-9]+\:[a-z_-]+\:\/docker\/' + hostname + '[0-9a-z]+', 'i'
7+
);
8+
9+
try {
10+
isDocker = require('child_process')
11+
.execSync(
12+
'cat /proc/self/cgroup',
13+
{stdio: ['ignore', 'pipe', 'ignore']}
14+
)
15+
.toString().match(pattern) !== null;
16+
} catch (e) {
17+
isDocker = false;
18+
}
19+
20+
return isDocker;
21+
})();
22+
23+
const defaultHost = isDocker ? '0.0.0.0' : 'localhost';
24+
25+
// when we're runing in Docker, we can expect (generally, in a development
26+
// scenario) that the user would like to connect to the service in the
27+
// container via the **host's** loopback address, so this helper can be used to
28+
// swap 0.0.0.0 for localhost in code/messages that pertain to client-side
29+
function canonicalHost(host) {
30+
return isDocker && host === '0.0.0.0' ? 'localhost' : host;
31+
}
32+
33+
function dockerHostSwap(host) {
34+
return (isDocker && (host === 'localhost' || host === '127.0.0.1')) ? defaultHost : host;
35+
}
36+
37+
const defaultCorsHost = canonicalHost(defaultHost);
38+
39+
module.exports = {
40+
canonicalHost,
41+
defaultCorsHost,
42+
defaultHost,
43+
dockerHostSwap,
44+
isDocker
45+
};

lib/utils/utils.js

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
let http = require('follow-redirects').http;
22
let https = require('follow-redirects').https;
3+
const {canonicalHost} = require('./host');
34

45
const balanceRegex = /([0-9]+) ?([a-zA-Z]*)/;
56

@@ -296,7 +297,7 @@ function buildUrl (protocol, host, port){
296297
function buildUrlFromConfig (configObj){
297298
if(!configObj) throw new Error('[utils.buildUrlFromConfig]: config object must cannot be null');
298299
if(!configObj.host) throw new Error('[utils.buildUrlFromConfig]: object must contain a \'host\' property');
299-
return this.buildUrl(configObj.protocol, configObj.host, configObj.port);
300+
return this.buildUrl(configObj.protocol, canonicalHost(configObj.host), configObj.port);
300301
}
301302

302303
function getWeiBalanceFromString(balanceString, web3){

0 commit comments

Comments
 (0)