Beispiel #1
0
var MockBot = module.exports = function (config) {
    // Run the event emitter constructor.
    EventEmitter.call(this);

    this.config = new Config(config);

    this.plugins = {};
    this.memory = {};

    // Mock out extra bot functionality.
    this.log = winston;
    this.transports = {};
    this.buffer = {};

    winston.level = 'error';
};
Beispiel #2
0
 self.child.once('exit',function(code){
   ee2.emit('exit', code)
   self.child = null
   if ((code != 0) && !self.stopFlag) {
     self.crashed++
     if (!self.max || self.crashed < self.max) {
       if ((Date.now()-self.ctime) > 5000)
         self.restartTimeout = 200
       else if (self.restartTimeout < 4000)
         self.restartTimeout += 100
       setTimeout(function(){
         start()
       },self.restartTimeout)
     }
   }
 })
Beispiel #3
0
  function start(cb) {
    self.startedOnce = true
    if (self.child)
      return cb(new Error('is already running'))
    var env = process.env
    if (self.env) {
      for (var x in self.env)
        env[x] = self.env[x]
    }
    self.child = spawn( self.command
                      , [self.script].concat(self.options)
                      , { cwd : self.cwd
                        , env : env
                        } )

    ee2.emit('start', self.child.pid)

    self.ctime = Date.now()
    var fsStdout = fstream.Writer({path:self.logScriptStdout,flags:'a'})
    var fsStderr = fstream.Writer({path:self.logScriptStderr,flags:'a'})
    self.child.stdout.pipe(fsStdout)
    self.child.stderr.pipe(fsStderr)

    self.child.stdout.on('data',function(data){
      ee2.emit('stdout', data.toString())
    })
    self.child.stderr.on('data',function(data){
      ee2.emit('stderr', data.toString())
    })
    self.child.once('exit',function(code){
      ee2.emit('exit', code)
      self.child = null
      if ((code != 0) && !self.stopFlag) {
        self.crashed++
        if (!self.max || self.crashed < self.max) {
          if ((Date.now()-self.ctime) > 5000)
            self.restartTimeout = 200
          else if (self.restartTimeout < 4000)
            self.restartTimeout += 100
          setTimeout(function(){
            start()
          },self.restartTimeout)
        }
      }
    })
    cb && info(cb)
  }
Beispiel #4
0
var Server = module.exports = function(opts, readyCb) {
    EventEmitter2.call(this, {
        wildcard: true,
        delimiter: '::',
        maxListeners: 25
    });

    if(typeof opts === 'function') {
        readyCb = opts;
        opts = null;
    }

    readyCb = readyCb || function() {};

    this.connections = {};

    //OR 0 will floor the value
    this.seq = Date.now() | 0;

    this.once('ready', readyCb);

    opts = opts || {};

    this.bindEvents = opts.myevents || false;

    if(opts.server) {
        this.port = opts.server.address().port;
        this.host = opts.server.address().host;

        this.server = opts.server;

        //make sure we dont call the callback before the function returns
        var self = this;
        process.nextTick(function() {
            self.emit('ready');
        });

        this.server.on('connection', this._onConnection.bind(this));
    }
    else {
        this.port = opts.port || 8022;
        this.host = opts.host || '127.0.0.1';

        this.server = net.createServer(this._onConnection.bind(this));
        this.server.listen(this.port, this.host, this._onListening.bind(this));
    }
};
Beispiel #5
0
function kju (configuration) {
  var self = this
    , option;

  // defaults
  this.limit = 500;
  this.ms = 100;
  this.interval = 15000;
  this.warnings = true;
  this.enabled = true;
  this.recover = true;
  this.dump = true;
  this.path = process.cwd() + '/';
  this.name = 'node_kju_backup.{sequence}.kju';

  // apply the configuration
  for (var option in configuration)
    this[option] = configuration[option];

  // these values should not be configured
  this.buffer = [];
  this.length = 0;

  this.drained = 0;
  this.processed = 0;
  this.since = Date.now();

  this.minimum = this.interval / 2;
  this.maximum = this.interval * 2;

  // initialize the event emitter
  EventEmitter2.call(this, { wildcard: true });

  if (this.recover) this.recovery();
  if (this.enabled) this.enable();

  // make sure our backup path exists
  path.exists(this.path, function exists (exists) {
    if (!exists) {
      return self.emit('error', new Error(self.path + ' does not exist.'));
    }

    if (self.path[self.path.length - 1] !== '/') {
      return self.emit('error', new Error(self.path + ' should end with a slash'));
    }
  });
};
Beispiel #6
0
module.exports.create = function( port ) {

    // make an event emitter to use for the hardcore stuff
    var eventaur = new EventEmitter2({
	delimter: ':',
	maxListeners: 0
    });

    // return a function that
    //   a) holds its own server/port/whatever
    //   b) exposes a listen method
    //   c) is a function that returns a new Gith object
    var ret = function( map ) {
	// make a new Gith with a reference to this factory
	return new Gith( eventaur, map );
    };

    // https://github.com/danheberden/gith/issues/13
    ret.ips = [ 
	'207.97.227.253', 
	'50.57.128.197', 
	'108.171.174.178', 
	'50.57.231.61' 
    ];

    // add the listen method to the function - bind to ret
    // and send eventaur to it
    ret.listen = listen.bind( ret, eventaur );

    // expose ability to close http server
    ret.close = function(){
	this.server.close();
    };

    ret.payload = function( payload ) {
	eventaur.emit( 'payload', payload );
    };

    // if create was sent port, call listen automatically
    if ( port ) {
	ret.listen( port );
    }

    // return the new function
    return ret;
};
Beispiel #7
0
var Identity = exports.Identity = function (options) {
  var self = this;

  events.EventEmitter2.call(this, { delimiter: '::', wildcard: true });

  self.options = options || {};
  self.name = 'OpenstackIdentity';
  self.useServiceCatalog = (typeof options.useServiceCatalog === 'boolean')
    ? options.useServiceCatalog
    : true;

  _.each(['url'], function (value) {
    if (!self.options[value]) {
      throw new Error('options.' + value + ' is a required option');
    }
  });
};
Beispiel #8
0
function Handle(workerFilePath, payload) {
  Emitter.call(this);
  var self = this;
  this.id = puid.generate();
  this.payload = payload;
  var setupData = JSON.stringify({
    id: this.id,
    payload: payload
  })
  this.worker = fork(workerFilePath, [setupData]);
  this.worker.on('message', function (data) {
    var obj = JSON.parse(data.toString());
    if (typeof obj.event == 'string') {
      self.emit(obj.event, obj.data);
    }
  });
}
function BlizzardNamespace(session, ns) {
    this.session = session;
    this.ns = ns;

    EventEmitter2.call(this, {
        wildcard: true
    });

    this.rpcListener = null;

    this.sessionRequestEvent = null;
    this.sessionRequestListener = null;

    this.bound = false;

    this.bind();
}
Beispiel #10
0
var Requester = function(advertisement, discoveryOptions) {
    EventEmitter.call(this, {
        wildcard: true, // should the event emitter use wildcards.
        delimiter: '::', // the delimiter used to segment namespaces, defaults to `.`.
        newListener: false, // if you want to emit the newListener event set to true.
        maxListeners: 2000 // the max number of listeners that can be assigned to an event, defaults to 10.
    });

    advertisement.key = Requester.environment + (advertisement.key || '');

    var that = this;
    advertisement.axon_type = 'req';

    this.advertisement = advertisement;

    var host = discoveryOptions && discoveryOptions.address || '0.0.0.0';

    portfinder.getPort({host: host, port: advertisement.port}, onPort);

    function onPort(err, port) {
        advertisement.port = +port;

        var d = that.discovery = Discovery(advertisement, discoveryOptions);

        that.sock = new axon.ReqSocket();
        that.sock.bind(port);
        that.sock.server.on('error', function(err) {
            if (err.code != 'EADDRINUSE') throw err;

            portfinder.getPort({host: host, port: advertisement.port}, onPort);
        });

        that.sock.on('bind', function() {
            that.emit('ready', that.sock);

            d.on('added', function(obj) {
                that.emit('added', obj);
            });

            d.on('removed', function(obj) {
                that.emit('removed', obj);
            });
        });
    }
};
Beispiel #11
0
Datei: wbfs.js Projekt: gaye/wbfs
  return co(function*() {
    var node = yield createDOMPromise(store('readonly').get(path));
    if (node.nodeType === 'file') {
      return Promise.reject(new Error(`Cannot remove ${path}: Not a directory`));
    }

    var children = yield indexGetAll(store('readonly').index('directory'), {
      range: IDBKeyRange.only(path)
    });

    if (children.length) {
      return Promise.reject(new Error(`Cannot remove ${path}: Directory not empty`));
    }

    yield createDOMPromise(store().delete(path));
    events.emit('change', path);
    debug(`rmdir ${path}: Done`);
  });
Beispiel #12
0
 }).exec(function (err, icons) {
     // console.log('obj是这个:',obj);
     if (!icons.length) {
         var icon = new Icon({
             name: obj.name,
             business: obj.business,
             path: obj.path,
             author: obj.author,
             className: 'i-' + obj.name,
             id: obj.id
         });
         icon.save(function (err, icon) {
             emitter.emit('insert_success', err, obj);
         });
     } else {
         emitter.emit('insert_success', '系统存在同名icon', obj);
     }
 });
function Generator(opts) {
	var options = Object.assign(this, parseOpts(opts));

	this._ramlParser;

	if(!options.raml_file){
		this._ramlParser = options.api;
	}

	else{
		this._ramlParser = new raml(options.raml_file, false);
	}

	this._ramlErrors = null;
	this._ramlResources = null;

	EventEmitter.call(this);
};
Beispiel #14
0
var Parser = module.exports = function(socket) {
    EventEmitter2.call(this, {
        wildcard: true,
        delimiter: '::',
        maxListeners: 25
    });

    this.buffer = new Buffer([]);
    this.bodyLen = 0;
    this.encoding = 'utf8';

    this.socket = socket;

    this.event = null;

    socket.on('data', this._onData.bind(this));
    socket.on('end', this._onEnd.bind(this));
};
Beispiel #15
0
function SharedConfig(targetdb) {
  var config = this;

  // call the eventemitter2 constructor
  EventEmitter2.call(this, { wildcard: true });

  // initialise the rePrivate regex based on the contents of the
  // eventemitter members
  this._privateRegex = new RegExp('^(' + privateMembers.concat(Object.keys(this)).join('|') + ')');

  // initialise the data
  this._data = {};

  // initialise the current environment to null
  this._current = null;

  // initialise the environments array to empty
  this._environments = null;

  // initialise the nano connection
  this._db = nano(targetdb);

  // initialise the feed
  this._feed = null;

  // read the environments from the db
  debug('requesting environments from config endpoint');
  this._db.list(function(err, info) {
    if (! err) {
      debug('retrieve list of config docs from db: ', info.rows);
      if (info.rows.length === 0) {
        console.log('error connecting to the db');
        console.log(err, info);
      }

      config._environments = info.rows.map(function(doc) {
        return doc.id;
      });
    }

    debug('finished querying db, triggering appropriate event');
    config.emit(err ? 'error' : 'connect', err);
  });
}
JournalTOCs.prototype.runQuery = function(url) {
  var req = request(url);
  var parser = new FeedParser();
  var emitter = new EventEmitter2();

  req.on('error', function (error) {
    // handle any request errors
  });

  req.on('response', function (res) {
    var stream = this;

    if (res.statusCode != 200) {
      emitter.emit('error', new Error('Bad status code'));
    }

    stream.pipe(parser);
  });

  parser.on('error', function(error) {
    emitter.emit('error', error);
  });

  var items = [];

  parser.on('readable', function() {

    var stream = this
      , meta = this.meta
      , item;

    while (item = stream.read()) {
      items.push(item);
    }

  });

  parser.on('end', function() {
    emitter.emit('result', items);
  });

  return emitter;

}
Beispiel #17
0
var EventCom = module.exports = function(options) {
  // Setup list of event names that are used by this class and can 
  // therefore not be emitted to the other side!!! (to prevent circular emits)
  this.localEvents = ['error', 'stdout', 'stderr', 'warn', 'exit', 'close', 'start', 'restart', 'stop', 'rpcready', 
                      'rpcexit', 'disconnect', 'disconnected']; 

  // rpc event session is not started yet
  this.started = false;

  // Call the parent EventEmitter2 constructor
  options = options || {};
  EventEmitter2.call(this, options.eventOptions || EVENT_OPTIONS);
  
  this.on('error', function() {
    var msg = (arguments[1] && arguments[1] instanceof Error) ? arguments[1].message : arguments[0],
        stack = (arguments[1] && arguments[1] instanceof Error) ? arguments[1].stack : arguments[1];
    console.error(msg, stack, arguments);
  });
};
Beispiel #18
0
function OctopullView() {
	EventEmitter.call(this);
	var self = this;
	
	self._counter = 0;
	self._loaded = false;
	self._waitForElements = [];
	
	self.diffView = null;
	self.repoActions = new RepoActionsView();
	self._progressBar = null;
	self._msgView = null;
	
	$(document).ready(self.onLoad.bind(self));
	$(document).leave("[data-loader-id]", { fireOnAttributesModification: true }, function() {
		var id = $(this).attr("data-loader-id");
		self._doneWaitingFor(id);
	});
}
Beispiel #19
0
	obj.unsubscribe = function(subKey) {
	    
	    // if the given subKey exists
	    if (typeof obj.allSubscriptions[subKey] != 'undefined') {
	       
    	    // look up our subscription info by our subKey
    	    var subscription = obj.allSubscriptions[subKey];
    	    
    	    // remove from hub
    		server.off(subscription.name, subscription.callback);
    		
    		// remove subKey from our list
    		delete obj.allSubscriptions[subKey];
    		
	    } else {
// @TODO How do we handle this error?
	        
	    }
	}
Beispiel #20
0
// Sends an event to one child
function sendToChild(/*pid, event, arg1, arg2, ...*/) {
  var child = childs[arguments[0]]
  
  if(child) {
    // create the message
    var msg = {
          from: em.pid                                     // pid of the origin
          , to: arguments[0]                               // target pid
          , pids: [em.pid]                                 // chain of pids
          , type: MSG_TYPE_TOCHILD                         // type of command
          , event: arguments[1]                            // name of the event
          , args: Array.prototype.slice.call(arguments, 2) // arguments of the event
        }
    child.send(msg)
  } else {
    em.emit('error', new Error('.sendToChild() failed: Child with pid '+arguments[0]+' not found.'))
  }
  
  return em
}
Beispiel #21
0
// Sends an event to the grand master
function sendToGrandMaster(/*pid, event, arg1, arg2, ...*/) {  
  if(process.send) {
    // create the message
    var msg = {
          from: em.pid                                     // pid of the origin
          , pids: [em.pid]                                 // chain of pids
          , type: MSG_TYPE_TOGM                            // type of command
          , event: arguments[0]                            // name of the event
          , args: Array.prototype.slice.call(arguments, 1) // arguments of the event
        }
    process.send(msg)
  } else if(em.isGrandMaster) {
    // emit
    em.emit.apply(em, arguments)
  } else {
    em.emit('error', new Error('.sendToGrandMaster() failed: process.send not defined.'))
  }
  
  return em
}
Beispiel #22
0
  function handledOpen () {
    var authMsg = {
      type: 'auth',
      id: config.id,
      token: config.token
    }

    ws.send(JSON.stringify(authMsg), function ack (err) {
      if (err) {
        handledError(err)
        log.error('Authorization to the Beep Boop Server failed with:', err.toString())
      }
    })

    resourcer.emit('open')
    log.debug('Web Socket connection opened to Beep Boop Server:', config.serverURL)
    // Reset retry backoff
    retry = Retry()
    pingInterval = setInterval(pingPonger, config.pingFrequency)
  }
Beispiel #23
0
var Bootstrapper = exports.Bootstrapper = function (options) {
  if (!options) {
    throw new Error('Missing required `options`');
  }

  events2.EventEmitter2.call(this, options);

  this.provider   = (options.compute && options.compute.provider) || 'rackspace';
  this.keys       = options.keys;
  this.retryLimit = options.retryLimit || 3;
  this.remoteUser = options.remoteUser || 'root';

  //
  // Create a pkgcloud compute client with `options.compute` or
  // the stored configuration in `conservatory`.
  //
  if (options.compute) {
    this.compute = pkgcloud.compute.createClient(options.compute);
  }
};
Beispiel #24
0
var CommandQueue = function(options) {

  EventEmitter2.call(this, {
    // EventEmitter2 options go here
  });

  _.bindAll(this, 'enqueue', 'dequeue', 'end');

  this.options = options = _.defaults(options || {}, {
    // Default parameters go here
  });

  var logger = logging.getLogger('Parsley.CommandQueue');
  logger.extend(this);

  this.key = _.partial(common.redisKey, 'command');

  this.redis = redis.get();

  proxyEvents(this.redis, this, 'ready');
};
Beispiel #25
0
/**
 * Database object. Creates and manages database files, models etc.
 *
 * @class
 * @param {string} name - The name of the database (and file)
 * @param {object} [options] - Database options
 * @constructor
 * @example
 * var db = new require('radic').DB('myfileDB4', {
 *     path: 'HOMEDIR/.radic/stores',
 *     ext: '.db',
 *     onLoaded: function(){}
 * });;
 *
 */
function DB(name, options){
    EventEmitter.call(this, {
        maxListeners: 30,
        wildcard: true,
        newListener: true,
        delimiter: ':'
    });
    options = options || {};
    this.defaults = {
        path: path.join(app.path, 'stores'),
        type: 'file',
        name: name,
        ext: '.db',
        onLoaded: function(){}
    };
    this.options = _.extend({}, this.defaults, options);
    this._dbPath = path.resolve(this.options.path, this.options.name + this.options.ext);
    this._db = new Datastore(this._dbPath);
    this._models = {};
    this._db.loadDatabase(this.options.onLoaded);
}
Beispiel #26
0
// 
function _emitScoped(scope, eventName, args) {
  var listeners = em.listeners(eventName)
  if(listeners.length) {
    listeners.forEach(function(listener) {
      switch(args.length) {
        case 1:
          listener.call(scope, args[0])
          break
        case 2:
          listener.call(scope, args[0], args[1])
          break
        case 3:
          listener.call(scope, args[0], args[1], args[2])
          break
        default:
          listener.apply(scope, args)
          break
      }
    })
  }
}
Beispiel #27
0
Datei: wbfs.js Projekt: gaye/wbfs
  return co(function*() {
    var {parent, directory} = yield getParentDirectory(path);
    if (parent.nodeType === 'file') {
      return Promise.reject(new Error(`${directory}: Not a directory`));
    }

    var node = yield createDOMPromise(store().get(path));
    if (node) {
      return Promise.reject(new Error(`Cannot create directory ${path}: File exists`));
    }

    var dir = {
      path: path,
      directory: directory,
      nodeType: 'directory'
    };

    yield createDOMPromise(store().add(dir));
    events.emit('change', path);
    debug(`mkdir ${path}: Done`);
  });
Beispiel #28
0
function Bot(config) {
  events.EventEmitter2.call(this, {
    wildcard: true
  });

  this.cl = new xmpp.Client({
    jid: config.jid,
    password: config.password
  });

  this.contexts = {};
  this.modules = {};
  this.config = config;

  utils.log.info('Starting HTTP server');
  this.web = new web.HTTPServer(this);

  this.cmd = new cmd.CommandReader(this);

  this.load_extensions(this.config.extension_dir);
}
Beispiel #29
0
 sendResult(postfix, data) {
     if (this._resultLock) {
         throw Error('result function should call once');
     }
     let DELIMITER = this.options.delimiter;
     this.status = postfix;
     this.result = data;
     this._resultLock = true;
     this.emitter.emitAsync('before-result', this)
     .catch((err) => {
         let error = Context._formatError(err, this.options);
         postfix = this.options.errorPostfix;
         this.result = error;
         this.status = postfix;
     })
     .then(() => {
         let responseEventName = this.event.name + DELIMITER + this.status;
         this.socket.emit(responseEventName, this.result);
         this.emitter.emitAsync('result', this);
     });
 }
Beispiel #30
0
/**
 * @todo plugins should be able set status at any time
 * @todo plugins should have service level events
 * @todo logging service should be available to plugins
 * @todo revise logic
 *  1) Load all plugins 
 *  2) Register plugins event handlers
 *  3) register plugins
 *  4) init plugins
 */
function Service(name, module, config, services) {

	EventEmitter.call(this, {
		wildcard: true,
		maxListeners: 20
	});

	this.name          = name;
	this.module        = module;
	this.config        = config;
	
	this._services     = services;
	this.priority      = 0;
	this.booted        = false;
	this.uses          = [];
	this.defer         = true;
	this.provides      = [name];
	this.meta          = {}

	return this;
}