Ejemplo n.º 1
1
var http = require('http');
var throng = require('throng');
var App = require('./app.js');

http.globalAgent.maxSockets = Infinity;
throng(start, { workers: 1 });

function start() {
  console.log('server.start');
  var instance = App.create();
  createServer();

  function createServer() {
    console.log('server.start.createServer');
    var server = http.createServer(instance);
    process.on('SIGTERM', shutdown);

    /**
    * Get port from environment and store in Express.
    */
    var port = normalizePort(process.env.PORT || '3000');
    instance.set('port', port);

    /**
     * Listen on provided port, on all network interfaces.
     */
    server.listen(port, onListen);
    server.on('error', onError);

    function onListen() {
      console.log({ type: 'info', msg: 'listening', port: server.address().port });
Ejemplo n.º 2
0
function cli() {
  if (argv['rtail-web-port']) {
    console.log('loading rtail')
    rtailServer()
  }
  if (argv.cfhttp) {
    getHttpServer(argv.cfhttp, cloudFoundryHandler)
  }
  if (argv.heroku) {
    throng(start, {
      workers: WORKERS,
      lifetime: Infinity
    })
  }
  if (argv.stdin) {
    readStdIn()
  }
  if (argv._.length > 0) {
    // tail files
    tailFiles(argv._)
  } else if (globPattern) {
    // checks for file list and start tail for all files
    console.log('using glob pattern: ' + globPattern)
    tailFilesFromGlob(globPattern)
  } else if (argv.u) {
    try {
      getSyslogServer(logseneToken, argv.u)
    } catch (err) {
      console.error(err)
      process.exit(-1)
    }
  } else {
    readStdIn()
  }
}
Ejemplo n.º 3
0
        start: function() {
            var listen = function(id) {
                util.log('start worker', id);
                app.listen(config.port, config.ip);
            };

            //app.use(express.static(config.env.root));
            if(config.debug) {
                listen();
            } else {
                throng({
                    start: listen,
                    workers: config.workers,
                    lifetime: Infinity
                });
            }
        }
Ejemplo n.º 4
0
  var url = this.params[0];
  if (!url || !is_url(url)) {
    return yield next;
  }

  // run the page pipe
  // TODO: yieldable
  this.body = yield function(done) {
    pagepipe(url, done);
  }
})

/**
 * /
 */

roo.get('/', function *(next) {
  this.body = 'hello from the page pipe!';
});

/**
 * Listen
 */

throng(function listen() {
  roo.listen(port, function() {
    var addr = this.address();
    console.log('listening on [%s]:%d', addr.address, addr.port);
  })
}, { lifetime: Infinity });
Ejemplo n.º 5
0
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import { renderToString } from './../../node_modules/react-dom/server'
import cacheSimulatorApp from './../client/reducers'
import config from './config/'
import logger from './util/logger'
import { match, RouterContext } from 'react-router'
import createRoutes from './../routes/index';
import { createMemoryHistory, useQueries } from 'history';
import throng from 'throng';

const WORKERS = process.env.WEB_CONCURRENCY || 1;
const PORT = process.env.PORT || 8080;

throng({
    workers: WORKERS,
    start: start
});

function start() {

    const server = express()

    logger.info('configuring express....');
    config(server, express);
    logger.info('express configured');

    // This is fired every time the server side receives a request
    server.use(handleRender)

    /**
     * Function that handles server-side rendering with react-router.
Ejemplo n.º 6
0
/*
 * Main entry point for this application.
 */

/* eslint no-console:0 */

const fs = require('fs');
const throng = require('throng');
const serverStart = require('./lib/local/system/server').default;
const WORKERS = process.env.WEB_CONCURRENCY || 1;

// read in package details
global.__package = JSON.parse(fs.readFileSync('./package.json', 'utf8'));

// configure servers
const serverOptions = {
  distPath: __dirname + '/dist/',
  version: __package.version,
  baseUrlPath: '/dist'
};

// start servers
throng(function (id) { serverStart(id, serverOptions); }, { workers: WORKERS, lifetime: Infinity });
Ejemplo n.º 7
0
var logger = require('logfmt');
var cpus = require('os').cpus().length;
var http = require('http');
var throng = require('throng');

var config = require('./config');
var app = require('./app');
var web = require('./web');

http.globalAgent.maxSockets = Infinity;
throng(start, { workers: config.concurrency });

function start() {
  var instance = app(config);
  instance.on('ready', createServer);

  function createServer() {
    if (config.thrifty) instance.startScraping();
    var server = http.createServer(web(instance, config));

    server.listen(config.port, onListen);
    process.on('SIGTERM', shutdown);

    function onListen() {
      logger.log({ type: 'info', msg: 'listening', port: server.address().port });
    }

    function shutdown() {
      logger.log({ type: 'info', msg: 'shutting down' });
      server.close(function() {
        logger.log({ type: 'info', msg: 'exiting' });
Ejemplo n.º 8
0
// make sure there is a NODE_ENV var
process.env.NODE_ENV = process.env.NODE_ENV || 'development';

var logger = require('../components/logger')();
var cpus = require('os').cpus().length;
var http = require('http');
var throng = require('throng');
var config = require('../config/environment');
var app = require('../app/index.js'); // I don't know why but this is requiring the full pathname to index.js
var web = require('../web-server');
var async = require("async");

http.globalAgent.maxSockets = Infinity;

// spin up our workers...? ok
throng(start, { workers: config.max_concurrency ? config.max_concurrency : 1 });

var instance;

function start() {
	instance = app(config);
	instance.on('ready', onSuccess);
	instance.on('lost', abort);

	function abort() {
		logger.info("Lunge: abort()");
		logger.log({ type: 'info', msg: 'shutting down', abort: true });
		process.exit();
	}
}
Ejemplo n.º 9
0
(function() {
  'use strict';
  // Module Dependencies
  require('coffee-script');
  require('coffee-script/register');

  var express = require('express');
  var http = require('http');
  var path = require('path');
  var favicon = require('serve-favicon');
  var logger = require('morgan');
  var bodyParser = require('body-parser');
  var methodOverride = require('method-override');
  var static_dir = require('serve-static');
  var errorHandler = require('errorhandler');
  var helmet = require('helmet');
  var throng = require('throng');
  var cookieParser = require('cookie-parser');
  var LocalStrategy = require('passport-local').Strategy;
  var jwt = require('express-jwt');
  var timeout = require('connect-timeout');
  var flash = require('connect-flash');
  var device = require('express-device');
  var mailer = require('nodemailer');

  require('dotenv').config({silent: process.env.NODE_ENV !== 'development'});

  var WORKERS = process.env.WEB_CONCURRENCY || 1;
  //Create workers on all the threads
  throng({
    workers: WORKERS,
    lifetime: Infinity
  }, start);

  // The application
  function start() {
    var app = express();
    var port = process.env.PORT || 3000;
    var server = app.listen(port);

    require('./routes/redirects')(app);
    app.use(helmet());

    // Extras
    // Rendering tools
    app.locals.moment = require('moment');

    // Passport Logic
    var passport = require('passport');
    var User = require('./entities/users/model');
    var Sponsor = require('./entities/sponsors/model');

    // Node mailer
    var transporter = mailer.createTransport({
      host: process.env.MAIL_HOST,
      port: process.env.MAIL_PORT,
      secure: true,
      auth: {
        user: process.env.MAIL_USER,
        pass: process.env.MAIL_PASS
      }
    });

    // all environments
    app.set('views', path.join(__dirname, 'views'));
    app.set('view engine', 'jade');
    app.use(favicon(path.join(__dirname, 'static/assets/img/favicon.png')));
    if('development' == app.get('env'))
      app.use(logger('dev'))
    else
      app.use(logger('common', {
        skip: function (req, res) { return res.statusCode < 400 }
      }));
    app.use(cookieParser());
    app.use(bodyParser.json({type: 'application/vnd.api+json', limit: '50mb'}));
    app.use(device.capture());
    app.use(bodyParser.urlencoded({extended: true, limit: '50mb', parameterLimit: 3000}));

    app.use(passport.initialize());
    app.use(flash());
    app.use(methodOverride('X-HTTP-Method-Override'));
    app.use(static_dir(path.join(__dirname, 'static')));
    var appRoutes = require('./routes/index')(app, process.env);
    var apiRoutes = require('./routes/api')(app, process.env, transporter);
    app.get('*', function(req, res){
      res.status(404);
      res.render('error', {'error': 'Page not found'});
    });


    // Error Handling
    // Development only
    if ('development' == app.get('env')) {
      app.use(errorHandler());
    } else {
      // 404
      app.use(function(req, res) {
       res.sendStatus(404);
      });

      // 500
      app.use(function(err, req, res, next) {
       res.sendStatus(500);
      });
    }

    http.createServer(app).listen(app.get(port), function(){
      console.log('Express server listening on port ' + port + ' on ' + WORKERS + ' worker(s)');
    });
  }
}).call(this);
Ejemplo n.º 10
0
const startWorker = id => {
  console.log(`Started worker ${id}`)

  cache.connect()
  setup(app)

  app.listen(PORT, () => {
    console.log(`Listening on port ${PORT}`)
    // eslint-disable-next-line
    return typeof process.send === 'function'
      ? process.send('listening')
      : void 0
  })

  process.on('SIGTERM', () => {
    console.log(`Worker ${id} exiting`)
    process.exit()
  })
}

throng(
  {
    workers: WORKERS,
    lifetime: Infinity,
  },
  startWorker
)

module.exports = app
const log4js = require('log4js');
const logger = log4js.getLogger('server');

server
    .version(constants.VERSION)
    .option('-m --method <method>', 'encryption method, default: aes-256-cfb')
    .option('-k --password <password>', 'password')
    .option('-s --server-address <address>', 'server address')
    .option('-p --server-port <port>', 'server port, default: 8388')
    .option('--log-level <level>', 'log level(debug|info|warn|error|fatal)', /^(debug|info|warn|error|fatal)$/i, 'info')
    .option('--log-file <file>', 'log file')
    .parse(process.argv);

throng({
    workers: process.env.WEB_CONCURRENCY || 1,
    master: startMaster,
    start: startWorker
});

function startMaster() {
    logger.info('started master');
}

function startWorker(id) {
    logger.info(`started worker ${id}`);
    var relay = new TCPRelay({
        serverAddress: process.env['SERVER_ADDRESS'] || server.serverAddress || '127.0.0.1',
        serverPort: process.env['PORT'] || server.serverPort || 8388,
        password: process.env['PASSWORD'] || server.password || 'shadowsocks-over-websocket',
        method: process.env['METHOD'] || server.method || 'aes-256-cfb'
    }, false);
Ejemplo n.º 12
0
var cpus = require('os').cpus().length;

var concurrency = parseInt(process.env.CONCURRENCY, 10) || cpus;

http.globalAgent.maxSockets = Infinity;

var web = require('./web');

function start() {
  logger.log({
    type: 'info',
    msg: 'starting server',
    concurrency: concurrency
  });

  function createServer() {
    var server = http.createServer(web());


    function onListen() {
      logger.log({ type: 'info', msg: 'listening', port: server.address().port });
    }

    server.listen(process.env.PORT, onListen);
  }

  createServer();
}

throng({ workers: concurrency }, start);
Ejemplo n.º 13
0
try {
    local = require('../../local.json');
    for (key in local) {
        process.env[key] = local[key];
    }
} catch (err) {
    console.log('File local.json not found.')
}

const MAX_CPUS = process.env.MAX_CPUS || 'max';
const IS_DEV = process.env.NODE_ENV === 'development';

function count() {
	const max = parseInt(MAX_CPUS)
    const value = MAX_CPUS === 'max' ? cpus : max > 0 ? max : cpus
    // we only need 1 core running during development
    return IS_DEV ? 1 : Math.max(1, Math.min(value, cpus))
}

function start() {
    if (IS_DEV) {
        require('babel-register');
    }
    require('./app').start();
}

throng(start, {
    workers: count(),
    lifetime: Infinity
});
Ejemplo n.º 14
0
process.env.NODE_ENV = 'production';

const express = require('express');
const app = express();
const session = require('express-session');
const createWorker = require('throng');
const MemoryStore = require('session-memory-store')(session);

createWorker(createWebServer)

function createWebServer() {
  // Use the session middleware with the memory-store as
  // recommended for production local use, like with iris and netcore.
  app.use(session({ store: new MemoryStore({expires: 1*60, checkperiod: 1*60}), secret: '.cookiesession.id', resave: true, saveUninitialized: false, cookie: { secure: true, maxAge: 60000 } }));
  
  app.get('/setget', function (req, res) {
    req.session.key = 'value';

    var value = req.session.key;
    if (value == '') {
      res.send('NOT_OK');
      return;
    }

    res.send(value);
  });

  app.listen(5000, function () {
    console.log(
      'Now listening on: http://localhost:5000\nApplication started. Press CTRL+C to shut down.'
    )
Ejemplo n.º 15
0
keystone.mongoose.connection.on('open', function() {

    throng(start, { workers: config.worker_concurrency });

});
Ejemplo n.º 16
0
const Hapi = require('hapi')
const throng = require('throng')
const routes = require('./routes')
const models = require('./models')
const controllers = require('./controllers')
const middlewares = require('./middlewares')

try {
  var WORKERS = process.env.WEB_CONCURRENCY || os.cpus().length
} catch (e) {
  // do nothing
}

throng({
  start,
  lifetime: Infinity,
  workers: process.env.NODE_ENV === 'development' ? 1 : (WORKERS || 1)
})

function start () {
  const __DEV__ = process.env.NODE_ENV === 'development'
  const server = new Hapi.Server()

  server.connection({
    labels: ['api'],
    port: __DEV__ ? 3000 : (process.env.PORT || 3000),
    routes: {
      plugins: {
        hapiAuthoriation: {
          roles: ['ADMIN'] // default role for all endpoints
        }
Ejemplo n.º 17
0
        } );
    };

    var serve = function () {
        broker.handle( config.sensorQueue, handleMessage );
    };

    var create = function () {
        broker.create( config.sensorQueue, { prefetch: 5 }, serve );
    };

    process.once( "uncaughtException", function ( err ) {
        logger.log( "Stopping Pi-Sensor-RPC-Service" );
        logger.log( err );
        process.exit();
    } );

    SerialPort.on( "open", function () {
        SerialPort.on( "data", function ( data ) {
            serialResponse = utils.parseSerialData( data );
        } );
        broker.once( "connected", create );
    } );
};


throng( run, {
    workers: os.cpus().length,
    lifetime: Infinity
} );
Ejemplo n.º 18
0
var throng = require('throng');

var WORKERS = process.env.WEB_CONCURRENCY || 1;
var PORT = process.env.PORT || 8085;
var ENV = process.env.NODE_ENV;
var STATIC = (ENV === 'production' ? '/cdn' : '/dist');
var SERVER_PATH = __dirname + '/server';

// allow app clustering
throng({
  workers: WORKERS,
  lifetime: Infinity,
  start: startServer
});

function startServer() {
  var path = require('path'),
      express = require('express'),
      debug = require('debug')('webapp'),
      jade = require('jade'),
      expressHelpers = require(SERVER_PATH + '/utils/express-helpers'),
      app = express();

  // register express helpers
  // those will be exposed to the templating engine
  app.locals.helpers = expressHelpers;

  // warm up cache by precompiling jade templates
  jade.compileFile(path.join(SERVER_PATH + '/views/index.jade'), { cache: true });

  // configure the view engine
Ejemplo n.º 19
0
// Require keystone
var keystone 	= require('keystone'),
	handlebars 	= require('express-handlebars'),

	// other requires
	logger 		= require('logfmt'),
	// cpus 		= require('os').cpus().length,
	throng 		= require('throng'),
	config 		= require('./lib/config'),
	http 		= require('http');


	// Let it all begin
http.globalAgent.maxSockets = Infinity;
throng(startRollin, { workers: config.concurrency });
// startRollin();

// Initialise Keystone with your project's configuration.
// See http://keystonejs.com/guide/config for available options
// and documentation.
function initKeystone() {
	keystone.init({

		'name': 'fantn',
		'brand': 'fantn',
		'static': 'public',
		'favicon': 'public/favicon.ico',
		'views': 'templates/views',
		'view engine': 'hbs',
		'mongo': config.mongo_url,
Ejemplo n.º 20
0
  id: 1,
  port,
  webpackConfig,
  statsFile,
  publicDir,
  sessionDomain: SessionDomain,
  sessionSecret: SessionSecret
}

export const startServer = (serverConfig) => {
  const config = {
    ...DefaultServerConfig,
    ...serverConfig
  }

  const server = process.env.NODE_ENV === 'production'
    ? createServer(config)
    : createDevServer(config)

  server.listen(config.port, () => {
    console.log('Server #%s listening on port %s, Ctrl+C to stop', config.id, config.port)
  })
}

if (require.main === module)
  throng({
    start: (id) => startServer({ id }),
    workers: process.env.WEB_CONCURRENCY || 1,
    lifetime: Infinity
  })
Ejemplo n.º 21
0
"use strict";

const throng = require("throng");
const thimble = require("./server");
const workers = process.env.WEB_CONCURRENCY || 1;

const start = function() {
  const server = thimble.listen(process.env.PORT);

  const shutdown = function() {
    server.close(function() {
      process.exit(0);
    });
  };

  process.on("SIGINT", shutdown);
  process.on("SIGTERM", shutdown);
};

throng(workers, start);
Ejemplo n.º 22
0
"use strict";

const dotenv = require("dotenv");
const service = require("./service");
const throng = require("throng");

dotenv.load();

const options = {
	log: console,
	name: "Origami Polyfill Service",
	workers: process.env.WEB_CONCURRENCY || 1
};

throng({
	workers: options.workers,
	start: startWorker
});

function startWorker(id) {
	console.log(`Started worker ${id}`);
	service(options)
		.listen()
		.catch(() => {
			process.exit(1);
		});
}
Ejemplo n.º 23
0
const p = isomorphic
  .development(__DEV__)
  .server(path.resolve(__dirname, '..', '..'))

const start = function (i) {
  console.log(`starting worker ${i}`)
  p
    .then(function () {
      return server({
        assets:  isomorphic.assets()
      , refresh: isomorphic.refresh.bind(isomorphic)
      })
    })
    .then(function (app) {
      app.listen(port)
      console.log(`worker ${i} listenting on ${port}`)
    })
    .catch(function (err) {
      console.log(`\n ${err.stack}`)
    })
}

throng({
  workers
, lifetime: Infinity
}, start)

if ( cluster.isMaster ) {
  console.log(`starting server with ${workers} workers`)
}
Ejemplo n.º 24
0
var jackrabbit = require('jackrabbit');
var logger = require('logfmt');
var throng = require('throng');
var cpus = require('os').cpus().length;

var RABBIT_URL = process.env.CLOUDAMQP_URL || 'amqp://localhost';

throng(start, { workers: cpus, lifetime: Infinity });

function start() {
  logger.log({ type: 'info', message: 'starting time service on process ' + process.pid });

  var broker = jackrabbit(RABBIT_URL, 1);
  broker.once('connected', create);
  process.once('uncaughtException', onError);

  function create() {
    broker.create('time.get', serve);
  }

  function serve() {
    logger.log({ type: 'time', message: 'serving time' });

    broker.handle('time.get', function gettime(message, reply) {
      logger.log({ type: 'time', message: 'time served from process: ' + process.pid });
      var currentTime = 'The time is: ' + (new Date()).toTimeString();
      reply({
        time: currentTime,
        served_from_process: process.pid
      });
    });
Ejemplo n.º 25
0
    app.listen(3000);
  }
}


// worker function, first listen for a message from master and then decide to start up based on that.
function start(id) {
  process.on('message', function(m) {
    console.log(`Worker: ${id} - We have a message from master: ${JSON.stringify(m)}`)
    process.env.BESPOKE = m.value;
    bootstrap(process.env.BESPOKE);
  });
}

// master function, publish some messages for the workers to share information.
function master() {
  var shareVal = process.env.SHARE_VAL || 'NOTHING';
  cluster.on('fork', function(worker) {
    worker.send({ cmd: 'broadcast', value: shareVal });
  });
}

// cluster the app
throng({
  lifetime: Infinity,
  grace: 4000,
  workers: workers,
  master: master,
  start: start
});
Ejemplo n.º 26
0
'use strict';

const throng = require('throng');

const app = require('./app');

const WORKERS = process.env.WEB_CONCURRENCY || 1;

throng(app, {
  workers: WORKERS,
  lifetime: Infinity
});
Ejemplo n.º 27
0
var server = require('http').createServer(app);

var throng = require('throng');
var port = process.env.PORT || 3000;
var WORKERS = process.env.WEB_CONCURRENCY || 1;

var io = require('socket.io')(server);

var players = [];
var coords = {
  latitude: undefined,
  longitude: undefined
};

throng(start, {
  workers: WORKERS,
  lifetime: Infinity
});

function start() {
  app.set('views', __dirname + '/public');
  app.use(express.static('public'));
  app.set('view engine', 'ejs');
  app.engine('html', require('ejs').renderFile);

  server.listen(port, function() {
    console.log('server listening on port ' + port)
  });

/* ==================================
  Socket.io logic
=================================== */
Ejemplo n.º 28
0
throng(() => {
  const server = express();
  server.use(cookieParser());
  server.use('/dist', express.static('dist/client'));
  server.use(express.static('dist/server/public'));

  server.get('*', (req, res) => {
    const store = createStore(combineReducers(reducers));
    const unplug = reactCookie.plugToRequest(req, res);
    const context = {};
    const preloadedState = JSON.stringify(store.getState());
    const reactString = ReactDOMServer.renderToString(
      <Provider store={store}>
        <StaticRouter location={req.url} context={context}>
          {routes(store)}
        </StaticRouter>
      </Provider>
    );
    if (context.url) {
      res.redirect(context.url);
    } else {
      const $template = cheerio.load(HTML_TEMPLATE);
      $template('#react-mount')
        .html(reactString)
        .after(`<script>window.reduxPreloadedState=${preloadedState}</script>`);
      res.send($template.html());
    }
    unplug();
  });
  const port = process.env.PORT || 3000;
  server.listen(port);
});
require('dotenv').load({silent: true});

/* istanbul ignore next */
process.env.NODE_ENV = process.env.NODE_ENV || 'development';

const throng = require('throng');
const config = require('./config/config');
const shutdown = require('./app/utils/shutdown.server.utils');
const Queue = require('./app/services/queues.server.service');

const loggerId = 'SERVER:' + config.processId;

function start() {

  console.log('starting batch worker');

  let instance = new Queue(config, config.batchPrefetchLimit);

  instance.on('ready', beginWork);
  process.on('SIGTERM', () => shutdown(loggerId, instance));

  function beginWork() {
    console.log('worker ready to process queue');
    instance.on('lost', () => shutdown(loggerId, instance));
    instance.startConsumingBatches();
  }
}

throng({workers: config.workers, lifetime: Infinity}, start);
Ejemplo n.º 30
0
        .export()
        .pipe(uploadStream)
        .on('error', error => logger.info(`Snapshot error: ${error}`));
    });
    profiler.start();
  }

  // set app properties
  app.set('currentProcess', processId);
  app.set('apiKey', config.apiKey);
  app.set('environment', config.environment);

  // Expose which worker is handling request through middleware
  // TODO: Move to external middleware
  app.use((req, res, next) => {
    logger.info(`Request handled by worker ${app.get('currentProcess')}`);
    next();
  });

  return app.listen(config.port, () => {
    logger.info(`Gambit is listening on port:${config.port} env:${config.environment}.`);
  });
}

// Initialize Concurrency
throng({
  workers: config.webConcurrency,
  lifetime: Infinity,
  start,
});