Skip to content
This repository has been archived by the owner on May 16, 2019. It is now read-only.

Commit

Permalink
Merge pull request #1487 from rmisio/selective-local-server-start
Browse files Browse the repository at this point in the history
Selective local server start
  • Loading branch information
jjeffryes committed May 10, 2016
2 parents 407578e + e22d454 commit 3fecf84
Show file tree
Hide file tree
Showing 3 changed files with 115 additions and 33 deletions.
16 changes: 10 additions & 6 deletions js/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ window.onblur = function() {

var Polyglot = require('node-polyglot'),
ipcRenderer = require('ipc-renderer'),
remote = require('electron').remote,
getBTPrice = require('./utils/getBitcoinPrice'),
router = require('./router'),
userModel = require('./models/userMd'),
Expand All @@ -46,8 +47,6 @@ var Polyglot = require('node-polyglot'),
ServerConnectModal = require('./views/serverConnectModal'),
OnboardingModal = require('./views/onboardingModal'),
PageConnectModal = require('./views/pageConnectModal'),
serverConfigMd = app.serverConfig,
heartbeat = app.getHeartbeatSocket(),
loadProfileNeeded = true,
startUpConnectMaxRetries = 2,
startUpConnectRetryDelay = 2 * 1000,
Expand Down Expand Up @@ -141,6 +140,12 @@ app.serverConfigs.fetch().done(() => {
}
});

ipcRenderer.send('activeServerChange', app.serverConfigs.getActive().toJSON());

app.serverConfigs.on('activeServerChange', (server) => {
ipcRenderer.send('activeServerChange', server.toJSON());
});

//keep user and profile urls synced with the active server configuration
(setServerUrl = function() {
var baseServerUrl = app.serverConfigs.getActive().getServerBaseUrl();
Expand Down Expand Up @@ -360,7 +365,7 @@ var loadProfile = function(landingRoute, onboarded) {

//get user bitcoin price before loading pages
setCurrentBitCoin(cCode, user, function() {
newSocketView = new socketView({model: serverConfigMd});
newSocketView = new socketView();

newPageNavView = new pageNavView({
model: user,
Expand Down Expand Up @@ -425,7 +430,6 @@ launchOnboarding = function(guidCreating) {
onboardingModal = new OnboardingModal({
model: user,
userProfile: userProfile,
serverConfig: serverConfigMd,
guidCreationPromise: guidCreating
});
onboardingModal.render().open();
Expand Down Expand Up @@ -465,7 +469,7 @@ app.connectHeartbeatSocket();
app.serverConnectModal = new ServerConnectModal().render();
app.serverConnectModal.on('connected', () => {
if (profileLoaded) {
// If we've already called loadProfile() and then, we connect
// If we've already loaded called loadProfile() and then, we connect
// to a new server (or reconnect to the same server) we'll reload the
// app since some of the "global" components (Router, PageNav,
// SocketView...) were not designed to handle a new connection.
Expand Down Expand Up @@ -584,4 +588,4 @@ app.getHeartbeatSocket().on('message', function(e) {
}
}
});
// end - server connection and app initialization flow
// end - server connection and app initialization flow
54 changes: 43 additions & 11 deletions js/views/serverConnectModal.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@
var __ = require('underscore'),
Backbone = require('backbone'),
loadTemplate = require('../utils/loadTemplate'),
app = require('../App.js').getApp(),
app = require('../App.js').getApp(),
remote = require('electron').remote,
ServerConfigMd = require('../models/serverConfigMd'),
ServerConfigsCl = require('../collections/serverConfigsCl'),
BaseModal = require('./baseModal'),
Expand Down Expand Up @@ -203,7 +204,15 @@ module.exports = BaseModal.extend({
},

connect: function(configMd) {
var connectAttempt;
var deferred = $.Deferred(),
promise = deferred.promise(),
attempt = 1,
maxAttempts = 5,
timeoutBetweenAttempts = 2 * 1000,
maxAttemptsTime = 20 * 1000,
startTime = Date.now(),
attemptConnection,
connectAttempt;

configMd = configMd || this.serverConfigs.getActive();

Expand Down Expand Up @@ -232,18 +241,41 @@ module.exports = BaseModal.extend({
this.setModalOptions({ showCloseButton: false });
this.serverConfigs.setActive(configMd.id);

this._connectAttempt = this.attemptConnection().done(() => {
this.succeedConnection(configMd);
}).fail((reason) => {
this.failConnection(reason, configMd)
}).always(() => {
(attemptConnection = () => {
connectAttempt = this.attemptConnection().done(() => {
deferred.resolve();
this.succeedConnection(configMd);
}).fail((reason) => {
// If we're using the client launched from the installer
// and we're trying to connect to the default server, it will
// take some time for the server to launch, so we'll retry a few
// times.
if (
remote.getGlobal('launched_from_installer') && configMd.get('default') &&
attempt < maxAttempts && Date.now() < (startTime + maxAttemptsTime) &&
reason !== 'canceled'
) {
attempt += 1;
attemptConnection();
} else {
deferred.reject(reason);
this.failConnection(reason, configMd)
}
});
})();

deferred.always(() => {
this._connectAttempt = null;
});

promise.serverId = configMd.id;
promise.cancel = function() {
connectAttempt && connectAttempt.cancel();
};

this._connectAttempt = promise;

this._connectAttempt.serverId = configMd.id;
connectAttempt = this._connectAttempt;

return connectAttempt;
return promise;
},

attemptConnection: function(options) {
Expand Down
78 changes: 62 additions & 16 deletions main.js
Original file line number Diff line number Diff line change
Expand Up @@ -100,11 +100,49 @@ if(platform == "mac" || platform == "linux") {
daemon = "openbazaard";
}

var serverPath = __dirname + path.sep + '..' + path.sep + 'OpenBazaar-Server' + path.sep;
var serverOut = '';
var serverPath = __dirname + path.sep + '..' + path.sep + 'OpenBazaar-Server' + path.sep,
serverOut = '',
serverRunning = false,
pendingKill,
startAfterClose;

var kill_local_server = function() {
if (subpy) {
if (pendingKill) {
startAfterClose && pendingKill.removeListener('close', startAfterClose);
return;
} else if (!serverRunning) {
return;
} else {
pendingKill = subpy;
pendingKill.once('close', () => {
pendingKill = null;
});
}

console.log('Shutting down server daemon');

if(platform == "mac" || platform == "linux") {
subpy.kill('SIGINT');
} else {
require('child_process').spawn("taskkill", ["/pid", subpy.pid, '/f', '/t']);
}
}
}

var start_local_server = function() {
if(fs.existsSync(serverPath)) {
if (pendingKill) {
pendingKill.once('close', (startAfterClose = () => {
start_local_server();
}));

return;
}

if (serverRunning) return;

console.log('Starting OpenBazaar Server');

var random_port = Math.floor((Math.random() * 10000) + 30000);

Expand All @@ -113,6 +151,8 @@ var start_local_server = function() {
cwd: __dirname + path.sep + '..' + path.sep + 'OpenBazaar-Server'
});

serverRunning = true;

var stdout = '';
var stderr = '';

Expand All @@ -132,6 +172,7 @@ var start_local_server = function() {
console.log('exited with ' + code);
console.log('[END] stdout "%s"', stdout);
console.log('[END] stderr "%s"', stderr);
serverRunning = false;
});
subpy.unref();
}
Expand All @@ -142,11 +183,19 @@ var start_local_server = function() {

// Check if we need to kick off the python server-daemon (Desktop app)
if(fs.existsSync(__dirname + path.sep + ".." + path.sep + "OpenBazaar-Server" + path.sep + daemon)) {
launched_from_installer = true;
console.log('Starting OpenBazaar Server');
start_local_server();
global.launched_from_installer = launched_from_installer = true;
}

ipcMain.on('activeServerChange', function(event, server) {
if (launched_from_installer) {
if (server.default) {
start_local_server();
} else {
kill_local_server();
}
}
});

// Report crashes to our server.
//require('crash-reporter').start();

Expand Down Expand Up @@ -261,9 +310,8 @@ app.on('window-all-closed', function() {
app.on('before-quit', function (e) {
// Handle menu-item or keyboard shortcut quit here
console.log('Closing Application');
if(launched_from_installer) {
console.log('Shutting down server daemon');
subpy.kill();
if (launched_from_installer) {
kill_local_server();
}
});

Expand Down Expand Up @@ -440,14 +488,7 @@ app.on('ready', function() {
// when you should delete the corresponding element.
mainWindow = null;

if(subpy) {
if(platform == "mac" || platform == "linux") {
subpy.kill('SIGINT');
} else {
require('child_process').spawn("taskkill", ["/pid", subpy.pid, '/f', '/t']);
}
}

if (launched_from_installer) kill_local_server();
});

mainWindow.on('close', function() {
Expand Down Expand Up @@ -510,3 +551,8 @@ app.on('open-url', function(event, uri) {
openURL(uri);
event.preventDefault();
});

// some cleanup when our app is exiting
process.on('exit', () => {
kill_local_server();
});

0 comments on commit 3fecf84

Please sign in to comment.