Example #1
0
function autoPull(cb) {
  pm2.list(function(err, procs) {

    async.forEachLimit(procs, 1, function(proc, next) {
      if (proc.pm2_env && proc.pm2_env.versioning) {
        debug('pull And Reload %s', proc.name);
        pm2.pullAndReload(proc.name, function(err, meta) {
          if (meta) {
            var rev = meta.rev;

            app_updated.inc();

            if (rev)
              console.log('Successfully pulled [App name: %s] [Commit id: %s] [Repo: %s] [Branch: %s]',
                          proc.name,
                          rev.current_revision,
                          meta.procs[0].pm2_env.versioning.repo_path,
                          meta.procs[0].pm2_env.versioning.branch);
            else {
              // Backward compatibility
              console.log('App %s succesfully pulled');
            }
          }
          if (err)
            debug('App %s already at latest version', proc.name);
          return next();
        });
      }
      else next();
    }, cb);

  });
}
Example #2
0
 pm2.connect(function(err) {
     pm2.list(function(err, process_list) {
       res.setHeader('Content-Type', 'application/json');
       console.log(process_list)
       res.end(process_list);
     });
 });
Example #3
0
	pm2.connect(function(){

		var already = [], serverKeys = _.keys(serverList);
		var startOne = function( key ) {
			if ( key === undefined ) {return;}
			console.log(`launch ${key}`);
			if ( already.indexOf(key) === -1 ) {
				pm2.start( serverList[key], function(){
					startOne(serverKeys.shift());
				});
			} else {
				pm2.restart(key, function(){
					startOne(serverKeys.shift());
				});
			}
		};

		pm2.list(function(err, list){

			_.each(list, (app)=>{
				already.push(app.name);
			});

			startOne(serverKeys.shift());

		});

	});
Example #4
0
    function worker() {
        // Get process list managed by PM2
        pm2.list(function (err, apps) {
            if (err) return console.error(err.stack || err);

            // var oldApps = curApps;
            // curApps = apps;

            // console.log(_.difference(
            //     [{q: 1}, {q: 2}],
            //     [{q: 1}, {q: 3}]
            // ));

            apps.forEach(function (app) {
                // console.log(app);
                consul.agent.service.register(app.name + '-' + app.pm_id, function (err) {
                    if (err) {
                        console.error(err);
                    }
                    console.log(app.name, app.pm_id, app.pm2_env.instances, app.pm2_env.exec_mode);
                });

            });

        });
    };
Example #5
0
pm2.connect(function (err) {

    // Get all processes running
    pm2.list(function (err, process_list) {


        process_list.forEach(function (proc) {
            var env = proc.pm2_env;
            procs.push(proc.name);
            if ((config.all || config.process.indexOf(proc.name) !== -1 ) && config.ignore.indexOf(proc.name) === -1) {

                switch (env.status) {
                    case 'online':
                        if (output !== '') output += ', ';
                        output += proc.name + ' online';
                        break;
                    case 'stopped':
                        if (config.s) {
                            result = 'CRITICAL';
                        } else {
                            if (result !== 'CRITICAL') result = 'WARNING';
                        }
                        if (output !== '') output += ', ';
                        output += proc.name + ' stopped';
                        break;
                    case 'errored':
                        result = 'CRITICAL';
                        if (output !== '') output += ', ';
                        output += proc.name + ' errored';
                        break;
                    default:
                        if (result === 'OK') result = 'UNKNOWN';
                        if (output !== '') output += ', ';
                        output += proc.name + ' ' + env.status;
                }


                if (config.crit && (parseInt(config.crit, 10) < env.restart_time)) {
                    result = 'CRITICAL';
                    if (output !== '') output += ', ';
                    output += proc.name + ' restarted ' + env.restart_time + ' times';
                } else if (config.warn && (parseInt(config.warn, 10) < env.restart_time)) {
                    if (result !== 'CRITICAL') result = 'WARNING';
                    if (output !== '') output += ', ';
                    output += proc.name + ' restarted ' + env.restart_time + ' times';
                }

            }
        });

        if (output === '') output = 'All processes online';

        // Disconnect to PM2
        pm2.disconnect(function () {
            console.log('PM2', result + ':', output);
            process.exit(exit[result]);
        });
    });

});
        }, function(err, data) {
          //should(err).be.null;
          pm2.list(function(err, process_list) {

            console.log(process_list);

            // Disconnect to PM2
            pm2.disconnect(function() { process.exit(0) });
          });
        });
Example #7
0
 pm2.connect(true,(err)=>{
   if(err) return reject(err);
   pm2.list((err,list)=>{
     pm2.disconnect();
     if(err){
       return reject(err);
     }
     return resolve(list);
   });
 });
Example #8
0
				function(err, proc) {
					if (err instanceof Error) throw err;

					pm2.list(function(err, list) {
						 if (err instanceof Error) throw err;
						Array.prototype.forEach.call(list, function(item) {
							console.log('[ pm2 ]', '{', '"pid":', item.pid + ',', '"process":', '"' + item.name + '"', '}');
						})
						process.exit(0);
					})
				})
        }, function(err, proc) {
            if (err) throw new Error('err');

            // Get all processes running
            pm2.list(function(err, process_list) {
                console.log(process_list);

                // Disconnect to PM2
                pm2.disconnect(function() { process.exit(0) });
            });
        });
Example #10
0
    function(err, proc) {
      if (err) throw new Error(err);

      pm2.list(function(err, processList) {
        console.log(processList);

        /*pm2.disconnect(function() {
          process.exit(0);
        });*/
      });
    }
Example #11
0
pm2.connect(function(err) {
	if (err instanceof Error) throw err;
	var start = pm2.start;

	pm2.list(function(err, process_list) {
		var found = false;

		Array.prototype.forEach.call(process_list, function(process) {
			if (process.name === pm2Name) {
				found = true;
			}
		})

		var cb = function() {
			var options = {
				'name':pm2Name,
				'nodeArgs':['--harmony'],
				'watch':"./dist/app.es5.js",
				env: {
					'PORT': processPort
					,"args": ["--ignore-watch=\.git|node_modules|src"]
				}
			};
			console.log('[ pm2 ] start', path.join(__dirname, '../dist/app.es5.js'));
			console.log('[ pm2 ] options', options);
			start(
				path.join(__dirname, '../dist/app.es5.js'),
				options,
				function(err, proc) {
					if (err instanceof Error) throw err;

					pm2.list(function(err, list) {
						 if (err instanceof Error) throw err;
						Array.prototype.forEach.call(list, function(item) {
							console.log('[ pm2 ]', '{', '"pid":', item.pid + ',', '"process":', '"' + item.name + '"', '}');
						})
						process.exit(0);
					})
				})
		}

		if (!found) {
			cb();
		}else {
			console.log('[ pm2 ] stop ', pm2Name);
			pm2.delete(pm2Name, function(err, proc) {
		    if (err) throw new Error(err);
		    console.log('[ pm2 ]', pm2Name,  'server stopped');
		    cb()
			});
		}
	});
});
Example #12
0
    pm2.start('../../Mod04/Express/app/server.js', function(err, proc) {
        if (err) throw new Error(err);

        pm2.list(function(err, list) {
            console.log(list);
            pm2.disconnect(function() {
                process.exit(0)
            });
        });


    });
Example #13
0
  function worker() {
    // Get process list managed by PM2
    pm2.list(function(err, apps) {
      if (err) return console.error(err.stack || err);

      proceed_file(process.env.HOME + '/.pm2/pm2.log', false);
      proceed_file(process.env.HOME + '/.pm2/agent.log', false);

      // add no-need-cut app
      var force = is_it_time_yet();
      apps.forEach(function(app) {
        if (WHITE_LIST.indexOf(app.name) > -1) return;
        proceed_app(app, force);
      });
    });
  };
Example #14
0
				pm2.connect(function() {
					pm2.list(function(err, list) {
						rsp.statusCode = 200;
						rsp.setHeader('Content-Type', "application/json");
						rsp.setHeader("Access-Control-Allow-Origin", "*");
						if (err) {
							tiny.log.error('获取进程信息失败');
						} else {
							tiny.log.info('获取进程信息成功', list);
							var cipher = aesCrypt(JSON.stringify(list));
							rsp.setHeader('Content-Length', Buffer.byteLength(cipher, 'utf8'));
							rsp.write(cipher);
						}
						rsp.end();
						pm2.disconnect();
					});
				});
Example #15
0
function getPm2Id( appPath, cb ){
    pm2.list(function(err, list){
        if(err){
            cb(err);
        }
        else{
            var pm2Id = null;
            list.forEach(function(p, i){
                if(p.pm2_env.pm_exec_path === appPath){
                    // log('dev', p);
                    // log('dev', p.pm2_env.pm_id);
                    pm2Id = p.pm2_env.pm_id;
                }
            });
            cb(err, pm2Id);
        }
    });
}
Example #16
0
pm2.connect(err => {


  onError(err);

  pm2.list((err, list) => {

    onError(err);
    const pList = list.filter(p => p.name === scriptName);

    if(pList.length > 0) {

      if(pList[0].pm2_env.status === 'online') {

        pm2.stop(scriptName, err => {
          onError(err);
          pm2.start(scriptName, err => {
            onError(err);
            pm2.disconnect();
          });
        });
      } else {

        pm2.start(scriptName, err => {
          onError(err);
          pm2.disconnect();
        });
      }



    } else {

      pm2.start({
        script: './server/index.js',         // Script to be run
        name: 'api-server'
      }, function(err, apps) {
        onError(err);
        pm2.disconnect();   // Disconnect from PM2
      });

    }
  });
})
Example #17
0
	pm2.connect(function(err){

		console.log('Just connected to PM2');

		// Pull down the list
		pm2.list(function(err, list) {

			// Start an output message
			var agent = {};
			agent.host = os.hostname();
			agent.pid = process.pid;
			agent.version = ver;
			
			var msg = {};
			msg.agent = agent;

			// Get the components
			var cmps = [];

			// Pull down data for each function
			list.forEach(function(l) {

				// Basic information
				var name = l.pm2_env.name
				var metrics = {};
				metrics['Component/pm2[uptime]'] = calcUptime(l.pm2_env.pm_uptime);
				metrics['Component/pm2[restarts]'] = l.pm2_env.restart_time;
				metrics['Component/pm2[cpu]'] = l.monit.cpu;
				metrics['Component/pm2[memory]'] = l.monit.memory;

				var cmp = {};
				cmp['name'] = name;
				cmp['guid'] = guid;
				cmp['duration'] = 60;
				cmp['metrics'] = metrics;
				cmps.push(cmp);
			});

			msg.components = cmps;
			postToNewRelic(msg);
		});
	});
Example #18
0
    return new Promise((resolve, reject) => {
      pm2.list((err, list) => {
        if (err) {
          reject(err);
        } else {
          var data = list.filter((element) => {
            return (element.name.indexOf('tis-server') !== -1 && element.pm2_env.status === 'online');
          }).map((element) => {
            return {
              name: element.name,
              id: element.pm_id,
              pid: element.pid,
              port: element.pm2_env.NODE_PORT || 8080
            };
          })

          this.list = data;
          resolve(data);
        }
      });
    });
Example #19
0
    pm2.connect(function(err){
        if(err) throw new Error(err);
        pm2.list( function(err, process_list){
            if(err) throw new Error(err);

            plist = process_list;
            for(var proc in plist) {
                plist[proc].monit.memory = parseInt(plist[proc].monit.memory / 1048576) + " MB";
            }


            pm2.disconnect(function(err){ if (err) throw new Error(err);});

            res.render('actions/processes',
            {
                title:'ArchiPi :: Process',
                siteTitle: 'Archi Pi',
                content:plist,
                status: false,
                proc: true
            });
        });
    });
Example #20
0
		var getRunningServices = function(next) {
			pm2.list(function(err, list) {
				next(err, _.pluck(list,'name'));				
			});
		}
Example #21
0
		pm2.connect(function(err) {
			pm2.list(function(err, list) {
			
				//	Identifies the unique route/key + service/path combination,
				//	which key is used to uniquely identify the process pm2 will
				//	spawn (see > pm2 list)
				//
				var procName = [
					self.topic,
					lkg
				].concat(mpath.split('/').splice(-4)).join('/');
			
				//	Ensure that unique route/key + service/path combinations
				//	are allotted only one process. Note that the same
				//	service/path can be used for different route/key combos.
				//
				//	e.g 	.receive('/foo/bar')		// unique route
				//			.fulfill('key')
				//			.use('services/baz')		// identical service
				//
				//			.receive('/foo/bar/baz')	// unique route
				//			.fulfill('key')
				//			.use('services/baz')		// identical service
				//
				//			.receive('/foo/bar/baz')	// same route
				//			.fulfill('key')
				//			.use('services/baz')		// identical service
				//	...will result in TWO spawned /services/baz processes, with
				//	the third group being ignored (/foo/bar/baz is already being
				//	handled by the correct process /servics/baz). Uniqueness of
				//	#key has the same effect.
				//
				var dup = Helpers.isDuplicate(list, procName);
				if(dup.duplicate) {
					console.log("DUPLICATE: ", procName, dup.duplicate.pid);
					return self.dealer.send([
						'SERVICE_SUBSCRIBED',
						self.topic,
						lkg,
						dup.duplicate.pid
					].join(' '))
				}

				pm2.start(mpath, { 
					name: procName,
					scriptArgs: [
						self.socketConfig.publisherUri,
						self.socketConfig.routerUri,
						self.topic,
						lkg
					],
					watch : path.join(mpath, 'index.js'),
					instances: 1,
					execMode : 'fork_mode',
					force : true
				}, function(err, proc) {
					if(err) {
						throw new Error(err);
					}
				});
			})
		});
Example #22
0
Runner.prototype.list = function(detailed, next) {
	pm2.list(function(err, list) {
		if(!detailed) return next(err, _.pluck(list,'name'));
		next(err, list);
	});
}
Example #23
0
 }).on('pm2', function(data){
     if (!data.filename)
         return;
     var filename = path.join(config.path, data.filename);
     if (path.extname(filename)!='.js')
     {
         if (!data.run)
             return socket.emit('pm2', {filename: data.filename});
         var cmd = config.run(filename);
         if (!cmd)
             return;
         var child = exec(cmd[0], cmd.slice(1),
             {cwd: config.path});
         child.on('stdout', function(data, clear){
             socket.emit('pm2', {filename: data.filename, stdout: data,
                 clear: clear});
         });
         child.on('stderr', function(data, clear){
             socket.emit('pm2', {filename: data.filename, stderr: data,
                 clear: clear});
         });
         child.on('close', function(code, signal){ });
         child.on('error', function(err){ console.error(err); });
         return;
     }
     if (debug && debug.filename==filename)
     {
         if (data.run)
         {
             delete debug.break;
             debug.request('continue', _.pick(data, 'stepaction'));
         }
         else if (data.stop)
         {
             debug.stop();
             debug = null;
             io.emit('debug', {filename: data.filename});
             return socket.emit('pm2', {filename: data.filename});
         }
         return socket.emit('pm2', {filename: data.filename, debug: true});
     }
     pm2.list(function(err, list){
         if (err)
             return console.error(err);
         var running = list.some(function(p){
             return p.pm2_env.pm_exec_path==filename; });
         if (data.run)
         {
             pm2[running ? 'restart' : 'start'].call(pm2, filename, function(err, p){
                 if (err)
                     return console.error(err);
                 socket.emit('pm2', {filename: data.filename, running: true});
             });
         }
         else if (data.stop)
         {
             if (running)
             {
                 pm2.delete(filename, function(err, p){
                     if (err)
                         return console.error(err);
                     socket.emit('pm2', {filename: data.filename});
                 });
             }
         }
         else if (data.debug && !running)
         {
             debug = new Debug();
             debug.breakpoints = [];
             debug.on('event', function(res){
                 if (res.event=='afterCompile')
                     return;
                 if (res.event=='break')
                 {
                     debug.request('scripts').then(function(scripts){
                         var scripts = scripts.body.reduce(function(o, s){
                             if (s.name && s.name.startsWith('/'))
                                 o[s.handle] = s.name;
                             return o;
                         }, {});
                         debug.request('backtrace').then(function(res){
                             return Promise.all(res.body.frames.filter(function(f){
                                 return scripts[f.script.ref];
                             }).map(function(f){
                                 var args = [].concat(f.arguments, f.locals).reduce(function(o, arg){
                                     o[arg.value.ref] = arg.name;
                                     return o;
                                 }, {});
                                 return debug.request('lookup', {handles: Object.keys(args)}).then(function(res){
                                     return {
                                         filename: path.relative(config.path,
                                             scripts[f.script.ref]),
                                         line: f.line,
                                         frame: f.index,
                                         locals: Object.keys(args).reduce(function(o, id){
                                             var data = {text: res.body[id].text};
                                             if (res.body[id].script && scripts[res.body[id].script.ref])
                                             {
                                                 data.filename = path.relative(config.path,
                                                     scripts[res.body[id].script.ref]);
                                                 data.line = res.body[id].line;
                                             }
                                             o[args[id]] = data;
                                             return o;
                                         }, {}),
                                     };
                                 });
                             }));
                         }).then(function(res){
                             debug.break = res;
                             io.emit('debug', {breakpoints: debug.breakpoints,
                                 break: debug.break});
                         });
                     });
                 }
             });
             debug.start(filename, {cwd: __dirname}).then(function(){
                 return debug.connect();
             }).then(function(){
                 return debug.request('version');
             }).then(function(){
                 io.emit('pm2', {filename: data.filename, debug: true});
             }).catch(function(err){
                 console.error(err);
             });
         }
         else
             socket.emit('pm2', {filename: data.filename, running: running});
     });
 }).on('terminal', function(data){
Example #24
0
 .then(function () {
     return pm2Instance.list();
 })