UNPKG

31.1 kBJavaScriptView Raw
1'use strict';
2
3process.env.PM2_USAGE = 'CLI';
4
5var cst = require('../../constants.js');
6
7var commander = require('commander');
8var chalk = require('chalk');
9var forEachLimit = require('async/forEachLimit');
10
11var debug = require('debug')('pm2:cli');
12var PM2 = require('../API.js');
13var pkg = require('../../package.json');
14var tabtab = require('../completion.js');
15var Common = require('../Common.js');
16var PM2ioHandler = require('../API/pm2-plus/PM2IO');
17
18
19Common.determineSilentCLI();
20Common.printVersion();
21
22var pm2 = new PM2();
23
24PM2ioHandler.usePM2Client(pm2)
25
26commander.version(pkg.version)
27 .option('-v --version', 'print pm2 version')
28 .option('-s --silent', 'hide all messages', false)
29 .option('--ext <extensions>', 'watch only this file extensions')
30 .option('-n --name <name>', 'set a name for the process in the process list')
31 .option('-m --mini-list', 'display a compacted list without formatting')
32 .option('--interpreter <interpreter>', 'set a specific interpreter to use for executing app, default: node')
33 .option('--interpreter-args <arguments>', 'set arguments to pass to the interpreter (alias of --node-args)')
34 .option('--node-args <node_args>', 'space delimited arguments to pass to node')
35 .option('-o --output <path>', 'specify log file for stdout')
36 .option('-e --error <path>', 'specify log file for stderr')
37 .option('-l --log [path]', 'specify log file which gathers both stdout and stderr')
38 .option('--filter-env [envs]', 'filter out outgoing global values that contain provided strings', function(v, m) { m.push(v); return m;}, [])
39 .option('--log-type <type>', 'specify log output style (raw by default, json optional)')
40 .option('--log-date-format <date format>', 'add custom prefix timestamp to logs')
41 .option('--time', 'enable time logging')
42 .option('--disable-logs', 'disable all logs storage')
43 .option('--env <environment_name>', 'specify which set of environment variables from ecosystem file must be injected')
44 .option('-a --update-env', 'force an update of the environment with restart/reload (-a <=> apply)')
45 .option('-f --force', 'force actions')
46 .option('-i --instances <number>', 'launch [number] instances (for networked app)(load balanced)')
47 .option('--parallel <number>', 'number of parallel actions (for restart/reload)')
48 .option('--shutdown-with-message', 'shutdown an application with process.send(\'shutdown\') instead of process.kill(pid, SIGINT)')
49 .option('-p --pid <pid>', 'specify pid file')
50 .option('-k --kill-timeout <delay>', 'delay before sending final SIGKILL signal to process')
51 .option('--listen-timeout <delay>', 'listen timeout on application reload')
52 .option('--max-memory-restart <memory>', 'Restart the app if an amount of memory is exceeded (in bytes)')
53 .option('--restart-delay <delay>', 'specify a delay between restarts (in milliseconds)')
54 .option('--exp-backoff-restart-delay <delay>', 'specify a delay between restarts (in milliseconds)')
55 .option('-x --execute-command', 'execute a program using fork system')
56 .option('--max-restarts [count]', 'only restart the script COUNT times')
57 .option('-u --user <username>', 'define user when generating startup script')
58 .option('--uid <uid>', 'run target script with <uid> rights')
59 .option('--gid <gid>', 'run target script with <gid> rights')
60 .option('--namespace <ns>', 'start application within specified namespace')
61 .option('--cwd <path>', 'run target script from path <cwd>')
62 .option('--hp <home path>', 'define home path when generating startup script')
63 .option('--wait-ip', 'override systemd script to wait for full internet connectivity to launch pm2')
64 .option('--service-name <name>', 'define service name when generating startup script')
65 .option('-c --cron <cron_pattern>', 'restart a running process based on a cron pattern')
66 .option('-c --cron-restart <cron_pattern>', '(alias) restart a running process based on a cron pattern')
67 .option('-w --write', 'write configuration in local folder')
68 .option('--no-daemon', 'run pm2 daemon in the foreground if it doesn\'t exist already')
69 .option('--source-map-support', 'force source map support')
70 .option('--only <application-name>', 'with json declaration, allow to only act on one application')
71 .option('--disable-source-map-support', 'force source map support')
72 .option('--wait-ready', 'ask pm2 to wait for ready event from your app')
73 .option('--merge-logs', 'merge logs from different instances but keep error and out separated')
74 .option('--watch [paths]', 'watch application folder for changes', function(v, m) { m.push(v); return m;}, [])
75 .option('--ignore-watch <folders|files>', 'List of paths to ignore (name or regex)')
76 .option('--watch-delay <delay>', 'specify a restart delay after changing files (--watch-delay 4 (in sec) or 4000ms)')
77 .option('--no-color', 'skip colors')
78 .option('--no-vizion', 'start an app without vizion feature (versioning control)')
79 .option('--no-autorestart', 'start an app without automatic restart')
80 .option('--no-treekill', 'Only kill the main process, not detached children')
81 .option('--no-pmx', 'start an app without pmx')
82 .option('--no-automation', 'start an app without pmx')
83 .option('--trace', 'enable transaction tracing with km')
84 .option('--disable-trace', 'disable transaction tracing with km')
85 .option('--sort <field_name:sort>', 'sort process according to field\'s name')
86 .option('--attach', 'attach logging after your start/restart/stop/reload')
87 .option('--v8', 'enable v8 data collecting')
88 .option('--event-loop-inspector', 'enable event-loop-inspector dump in pmx')
89 .option('--deep-monitoring', 'enable all monitoring tools (equivalent to --v8 --event-loop-inspector --trace)')
90 .usage('[cmd] app');
91
92function displayUsage() {
93 console.log('usage: pm2 [options] <command>')
94 console.log('');
95 console.log('pm2 -h, --help all available commands and options');
96 console.log('pm2 examples display pm2 usage examples');
97 console.log('pm2 <command> -h help on a specific command');
98 console.log('');
99 console.log('Access pm2 files in ~/.pm2');
100}
101
102function displayExamples() {
103 console.log('- Start and add a process to the pm2 process list:')
104 console.log('');
105 console.log(chalk.cyan(' $ pm2 start app.js --name app'));
106 console.log('');
107 console.log('- Show the process list:');
108 console.log('');
109 console.log(chalk.cyan(' $ pm2 ls'));
110 console.log('');
111 console.log('- Stop and delete a process from the pm2 process list:');
112 console.log('');
113 console.log(chalk.cyan(' $ pm2 delete app'));
114 console.log('');
115 console.log('- Stop, start and restart a process from the process list:');
116 console.log('');
117 console.log(chalk.cyan(' $ pm2 stop app'));
118 console.log(chalk.cyan(' $ pm2 start app'));
119 console.log(chalk.cyan(' $ pm2 restart app'));
120 console.log('');
121 console.log('- Clusterize an app to all CPU cores available:');
122 console.log('');
123 console.log(chalk.cyan(' $ pm2 start -i max'));
124 console.log('');
125 console.log('- Update pm2 :');
126 console.log('');
127 console.log(chalk.cyan(' $ npm install pm2 -g && pm2 update'));
128 console.log('');
129 console.log('- Install pm2 auto completion:')
130 console.log('');
131 console.log(chalk.cyan(' $ pm2 completion install'))
132 console.log('');
133 console.log('Check the full documentation on https://pm2.keymetrics.io/');
134 console.log('');
135}
136
137function beginCommandProcessing() {
138 pm2.getVersion(function(err, remote_version) {
139 if (!err && (pkg.version != remote_version)) {
140 console.log('');
141 console.log(chalk.red.bold('>>>> In-memory PM2 is out-of-date, do:\n>>>> $ pm2 update'));
142 console.log('In memory PM2 version:', chalk.blue.bold(remote_version));
143 console.log('Local PM2 version:', chalk.blue.bold(pkg.version));
144 console.log('');
145 }
146 });
147 commander.parse(process.argv);
148}
149
150function checkCompletion(){
151 return tabtab.complete('pm2', function(err, data) {
152 if(err || !data) return;
153 if(/^--\w?/.test(data.last)) return tabtab.log(commander.options.map(function (data) {
154 return data.long;
155 }), data);
156 if(/^-\w?/.test(data.last)) return tabtab.log(commander.options.map(function (data) {
157 return data.short;
158 }), data);
159 // array containing commands after which process name should be listed
160 var cmdProcess = ['stop', 'restart', 'scale', 'reload', 'delete', 'reset', 'pull', 'forward', 'backward', 'logs', 'describe', 'desc', 'show'];
161
162 if (cmdProcess.indexOf(data.prev) > -1) {
163 pm2.list(function(err, list){
164 tabtab.log(list.map(function(el){ return el.name }), data);
165 pm2.disconnect();
166 });
167 }
168 else if (data.prev == 'pm2') {
169 tabtab.log(commander.commands.map(function (data) {
170 return data._name;
171 }), data);
172 pm2.disconnect();
173 }
174 else
175 pm2.disconnect();
176 });
177};
178
179var _arr = process.argv.indexOf('--') > -1 ? process.argv.slice(0, process.argv.indexOf('--')) : process.argv;
180
181if (_arr.indexOf('log') > -1) {
182 process.argv[_arr.indexOf('log')] = 'logs';
183}
184
185if (_arr.indexOf('--no-daemon') > -1) {
186 //
187 // Start daemon if it does not exist
188 //
189 // Function checks if --no-daemon option is present,
190 // and starts daemon in the same process if it does not exist
191 //
192 console.log('pm2 launched in no-daemon mode (you can add DEBUG="*" env variable to get more messages)');
193
194 var pm2NoDaeamon = new PM2({
195 daemon_mode : false
196 });
197
198 pm2NoDaeamon.connect(function() {
199 pm2 = pm2NoDaeamon;
200 beginCommandProcessing();
201 });
202
203}
204else if (_arr.indexOf('startup') > -1 || _arr.indexOf('unstartup') > -1) {
205 setTimeout(function() {
206 commander.parse(process.argv);
207 }, 100);
208}
209else {
210 // HERE we instanciate the Client object
211 pm2.connect(function() {
212 debug('Now connected to daemon');
213 if (process.argv.slice(2)[0] === 'completion') {
214 checkCompletion();
215 //Close client if completion related installation
216 var third = process.argv.slice(3)[0];
217 if ( third == null || third === 'install' || third === 'uninstall')
218 pm2.disconnect();
219 }
220 else {
221 beginCommandProcessing();
222 }
223 });
224}
225
226//
227// Helper function to fail when unknown command arguments are passed
228//
229function failOnUnknown(fn) {
230 return function(arg) {
231 if (arguments.length > 1) {
232 console.log(cst.PREFIX_MSG + '\nUnknown command argument: ' + arg);
233 commander.outputHelp();
234 process.exit(cst.ERROR_EXIT);
235 }
236 return fn.apply(this, arguments);
237 };
238}
239
240/**
241 * @todo to remove at some point once it's fixed in official commander.js
242 * https://github.com/tj/commander.js/issues/475
243 *
244 * Patch Commander.js Variadic feature
245 */
246function patchCommanderArg(cmd) {
247 var argsIndex;
248 if ((argsIndex = commander.rawArgs.indexOf('--')) >= 0) {
249 var optargs = commander.rawArgs.slice(argsIndex + 1);
250 cmd = cmd.slice(0, cmd.indexOf(optargs[0]));
251 }
252 return cmd;
253}
254
255//
256// Start command
257//
258commander.command('start [name|namespace|file|ecosystem|id...]')
259 .option('--watch', 'Watch folder for changes')
260 .option('--fresh', 'Rebuild Dockerfile')
261 .option('--daemon', 'Run container in Daemon mode (debug purposes)')
262 .option('--container', 'Start application in container mode')
263 .option('--dist', 'with --container; change local Dockerfile to containerize all files in current directory')
264 .option('--image-name [name]', 'with --dist; set the exported image name')
265 .option('--node-version [major]', 'with --container, set a specific major Node.js version')
266 .option('--dockerdaemon', 'for debugging purpose')
267 .description('start and daemonize an app')
268 .action(function(cmd, opts) {
269 if (opts.container == true && opts.dist == true)
270 return pm2.dockerMode(cmd, opts, 'distribution');
271 else if (opts.container == true)
272 return pm2.dockerMode(cmd, opts, 'development');
273
274 if (cmd == "-") {
275 process.stdin.resume();
276 process.stdin.setEncoding('utf8');
277 process.stdin.on('data', function (cmd) {
278 process.stdin.pause();
279 pm2._startJson(cmd, commander, 'restartProcessId', 'pipe');
280 });
281 }
282 else {
283 // Commander.js patch
284 cmd = patchCommanderArg(cmd);
285 if (cmd.length === 0) {
286 cmd = [cst.APP_CONF_DEFAULT_FILE];
287 }
288 let acc = []
289 forEachLimit(cmd, 1, function(script, next) {
290 pm2.start(script, commander, (err, apps) => {
291 acc = acc.concat(apps)
292 next(err)
293 });
294 }, function(err, dt) {
295 if (err && err.message &&
296 (err.message.includes('Script not found') === true ||
297 err.message.includes('NOT AVAILABLE IN PATH') === true)) {
298 pm2.exitCli(1)
299 }
300 else
301 pm2.speedList(err ? 1 : 0, acc);
302 });
303 }
304 });
305
306commander.command('trigger <id|proc_name|namespace|all> <action_name> [params]')
307 .description('trigger process action')
308 .action(function(pm_id, action_name, params) {
309 pm2.trigger(pm_id, action_name, params);
310 });
311
312commander.command('deploy <file|environment>')
313 .description('deploy your json')
314 .action(function(cmd) {
315 pm2.deploy(cmd, commander);
316 });
317
318commander.command('startOrRestart <json>')
319 .description('start or restart JSON file')
320 .action(function(file) {
321 pm2._startJson(file, commander, 'restartProcessId');
322 });
323
324commander.command('startOrReload <json>')
325 .description('start or gracefully reload JSON file')
326 .action(function(file) {
327 pm2._startJson(file, commander, 'reloadProcessId');
328 });
329
330commander.command('pid [app_name]')
331 .description('return pid of [app_name] or all')
332 .action(function(app) {
333 pm2.getPID(app);
334 });
335
336commander.command('create')
337 .description('return pid of [app_name] or all')
338 .action(function() {
339 pm2.boilerplate()
340 });
341
342commander.command('startOrGracefulReload <json>')
343 .description('start or gracefully reload JSON file')
344 .action(function(file) {
345 pm2._startJson(file, commander, 'reloadProcessId');
346 });
347
348//
349// Stop specific id
350//
351commander.command('stop <id|name|namespace|all|json|stdin...>')
352 .option('--watch', 'Stop watching folder for changes')
353 .description('stop a process')
354 .action(function(param) {
355 forEachLimit(param, 1, function(script, next) {
356 pm2.stop(script, next);
357 }, function(err) {
358 pm2.speedList(err ? 1 : 0);
359 });
360 });
361
362//
363// Stop All processes
364//
365commander.command('restart <id|name|namespace|all|json|stdin...>')
366 .option('--watch', 'Toggle watching folder for changes')
367 .description('restart a process')
368 .action(function(param) {
369 // Commander.js patch
370 param = patchCommanderArg(param);
371 let acc = []
372 forEachLimit(param, 1, function(script, next) {
373 pm2.restart(script, commander, (err, apps) => {
374 acc = acc.concat(apps)
375 next(err)
376 });
377 }, function(err) {
378 pm2.speedList(err ? 1 : 0, acc);
379 });
380 });
381
382//
383// Scale up/down a process in cluster mode
384//
385commander.command('scale <app_name> <number>')
386 .description('scale up/down a process in cluster mode depending on total_number param')
387 .action(function(app_name, number) {
388 pm2.scale(app_name, number);
389 });
390
391//
392// snapshot PM2
393//
394commander.command('profile:mem [time]')
395 .description('Sample PM2 heap memory')
396 .action(function(time) {
397 pm2.profile('mem', time);
398 });
399
400//
401// snapshot PM2
402//
403commander.command('profile:cpu [time]')
404 .description('Profile PM2 cpu')
405 .action(function(time) {
406 pm2.profile('cpu', time);
407 });
408
409//
410// Reload process(es)
411//
412commander.command('reload <id|name|namespace|all>')
413 .description('reload processes (note that its for app using HTTP/HTTPS)')
414 .action(function(pm2_id) {
415 pm2.reload(pm2_id, commander);
416 });
417
418commander.command('id <name>')
419 .description('get process id by name')
420 .action(function(name) {
421 pm2.getProcessIdByName(name);
422 });
423
424// Inspect a process
425commander.command('inspect <name>')
426 .description('inspect a process')
427 .action(function(cmd) {
428 pm2.inspect(cmd, commander);
429 });
430
431//
432// Stop and delete a process by name from database
433//
434commander.command('delete <name|id|namespace|script|all|json|stdin...>')
435 .alias('del')
436 .description('stop and delete a process from pm2 process list')
437 .action(function(name) {
438 if (name == "-") {
439 process.stdin.resume();
440 process.stdin.setEncoding('utf8');
441 process.stdin.on('data', function (param) {
442 process.stdin.pause();
443 pm2.delete(param, 'pipe');
444 });
445 } else
446 forEachLimit(name, 1, function(script, next) {
447 pm2.delete(script,'', next);
448 }, function(err) {
449 pm2.speedList(err ? 1 : 0);
450 });
451 });
452
453//
454// Send system signal to process
455//
456commander.command('sendSignal <signal> <pm2_id|name>')
457 .description('send a system signal to the target process')
458 .action(function(signal, pm2_id) {
459 if (isNaN(parseInt(pm2_id))) {
460 console.log(cst.PREFIX_MSG + 'Sending signal to process name ' + pm2_id);
461 pm2.sendSignalToProcessName(signal, pm2_id);
462 } else {
463 console.log(cst.PREFIX_MSG + 'Sending signal to process id ' + pm2_id);
464 pm2.sendSignalToProcessId(signal, pm2_id);
465 }
466 });
467
468//
469// Stop and delete a process by name from database
470//
471commander.command('ping')
472 .description('ping pm2 daemon - if not up it will launch it')
473 .action(function() {
474 pm2.ping();
475 });
476
477commander.command('updatePM2')
478 .description('update in-memory PM2 with local PM2')
479 .action(function() {
480 pm2.update();
481 });
482commander.command('update')
483 .description('(alias) update in-memory PM2 with local PM2')
484 .action(function() {
485 pm2.update();
486 });
487
488/**
489 * Module specifics
490 */
491commander.command('install <module|git:// url>')
492 .alias('module:install')
493 .option('--tarball', 'is local tarball')
494 .option('--install', 'run yarn install before starting module')
495 .option('--docker', 'is docker container')
496 .option('--v1', 'install module in v1 manner (do not use it)')
497 .option('--safe [time]', 'keep module backup, if new module fail = restore with previous')
498 .description('install or update a module and run it forever')
499 .action(function(plugin_name, opts) {
500 require('util')._extend(commander, opts);
501 pm2.install(plugin_name, commander);
502 });
503
504commander.command('module:update <module|git:// url>')
505 .description('update a module and run it forever')
506 .action(function(plugin_name) {
507 pm2.install(plugin_name);
508 });
509
510
511commander.command('module:generate [app_name]')
512 .description('Generate a sample module in current folder')
513 .action(function(app_name) {
514 pm2.generateModuleSample(app_name);
515 });
516
517commander.command('uninstall <module>')
518 .alias('module:uninstall')
519 .description('stop and uninstall a module')
520 .action(function(plugin_name) {
521 pm2.uninstall(plugin_name);
522 });
523
524commander.command('package [target]')
525 .description('Check & Package TAR type module')
526 .action(function(target) {
527 pm2.package(target);
528 });
529
530commander.command('publish [folder]')
531 .option('--npm', 'publish on npm')
532 .alias('module:publish')
533 .description('Publish the module you are currently on')
534 .action(function(folder, opts) {
535 pm2.publish(folder, opts);
536 });
537
538commander.command('set [key] [value]')
539 .description('sets the specified config <key> <value>')
540 .action(function(key, value) {
541 pm2.set(key, value);
542 });
543
544commander.command('multiset <value>')
545 .description('multiset eg "key1 val1 key2 val2')
546 .action(function(str) {
547 pm2.multiset(str);
548 });
549
550commander.command('get [key]')
551 .description('get value for <key>')
552 .action(function(key) {
553 pm2.get(key);
554 });
555
556commander.command('conf [key] [value]')
557 .description('get / set module config values')
558 .action(function(key, value) {
559 pm2.get()
560 });
561
562commander.command('config <key> [value]')
563 .description('get / set module config values')
564 .action(function(key, value) {
565 pm2.conf(key, value);
566 });
567
568commander.command('unset <key>')
569 .description('clears the specified config <key>')
570 .action(function(key) {
571 pm2.unset(key);
572 });
573
574commander.command('report')
575 .description('give a full pm2 report for https://github.com/Unitech/pm2/issues')
576 .action(function(key) {
577 pm2.report();
578 });
579
580//
581// PM2 I/O
582//
583commander.command('link [secret] [public] [name]')
584 .option('--info-node [url]', 'set url info node')
585 .description('link with the pm2 monitoring dashboard')
586 .action(pm2.linkManagement.bind(pm2));
587
588commander.command('unlink')
589 .description('unlink with the pm2 monitoring dashboard')
590 .action(function() {
591 pm2.unlink();
592 });
593
594commander.command('monitor [name]')
595 .description('monitor target process')
596 .action(function(name) {
597 if (name === undefined) {
598 return plusHandler()
599 }
600 pm2.monitorState('monitor', name);
601 });
602
603commander.command('unmonitor [name]')
604 .description('unmonitor target process')
605 .action(function(name) {
606 pm2.monitorState('unmonitor', name);
607 });
608
609commander.command('open')
610 .description('open the pm2 monitoring dashboard')
611 .action(function(name) {
612 pm2.openDashboard();
613 });
614
615function plusHandler (command, opts) {
616 if (opts && opts.infoNode) {
617 process.env.KEYMETRICS_NODE = opts.infoNode
618 }
619
620 return PM2ioHandler.launch(command, opts)
621}
622
623commander.command('plus [command] [option]')
624 .alias('register')
625 .option('--info-node [url]', 'set url info node for on-premise pm2 plus')
626 .option('-d --discrete', 'silent mode')
627 .option('-a --install-all', 'install all modules (force yes)')
628 .description('enable pm2 plus')
629 .action(plusHandler);
630
631commander.command('login')
632 .description('Login to pm2 plus')
633 .action(function() {
634 return plusHandler('login')
635 });
636
637commander.command('logout')
638 .description('Logout from pm2 plus')
639 .action(function() {
640 return plusHandler('logout')
641 });
642
643//
644// Save processes to file
645//
646commander.command('dump')
647 .alias('save')
648 .option('--force', 'force deletion of dump file, even if empty')
649 .description('dump all processes for resurrecting them later')
650 .action(failOnUnknown(function(opts) {
651 pm2.dump(commander.force)
652 }));
653
654//
655// Delete dump file
656//
657commander.command('cleardump')
658 .description('Create empty dump file')
659 .action(failOnUnknown(function() {
660 pm2.clearDump();
661 }));
662
663//
664// Save processes to file
665//
666commander.command('send <pm_id> <line>')
667 .description('send stdin to <pm_id>')
668 .action(function(pm_id, line) {
669 pm2.sendLineToStdin(pm_id, line);
670 });
671
672//
673// Attach to stdin/stdout
674// Not TTY ready
675//
676commander.command('attach <pm_id> [command separator]')
677 .description('attach stdin/stdout to application identified by <pm_id>')
678 .action(function(pm_id, separator) {
679 pm2.attach(pm_id, separator);
680 });
681
682//
683// Resurrect
684//
685commander.command('resurrect')
686 .description('resurrect previously dumped processes')
687 .action(failOnUnknown(function() {
688 console.log(cst.PREFIX_MSG + 'Resurrecting');
689 pm2.resurrect();
690 }));
691
692//
693// Set pm2 to startup
694//
695commander.command('unstartup [platform]')
696 .description('disable the pm2 startup hook')
697 .action(function(platform) {
698 pm2.uninstallStartup(platform, commander);
699 });
700
701//
702// Set pm2 to startup
703//
704commander.command('startup [platform]')
705 .description('enable the pm2 startup hook')
706 .action(function(platform) {
707 pm2.startup(platform, commander);
708 });
709
710//
711// Logrotate
712//
713commander.command('logrotate')
714 .description('copy default logrotate configuration')
715 .action(function(cmd) {
716 pm2.logrotate(commander);
717 });
718
719//
720// Sample generate
721//
722
723commander.command('ecosystem [mode]')
724 .alias('init')
725 .description('generate a process conf file. (mode = null or simple)')
726 .action(function(mode) {
727 pm2.generateSample(mode);
728 });
729
730commander.command('reset <name|id|all>')
731 .description('reset counters for process')
732 .action(function(proc_id) {
733 pm2.reset(proc_id);
734 });
735
736commander.command('describe <name|id>')
737 .description('describe all parameters of a process')
738 .action(function(proc_id) {
739 pm2.describe(proc_id);
740 });
741
742commander.command('desc <name|id>')
743 .description('(alias) describe all parameters of a process')
744 .action(function(proc_id) {
745 pm2.describe(proc_id);
746 });
747
748commander.command('info <name|id>')
749 .description('(alias) describe all parameters of a process')
750 .action(function(proc_id) {
751 pm2.describe(proc_id);
752 });
753
754commander.command('show <name|id>')
755 .description('(alias) describe all parameters of a process')
756 .action(function(proc_id) {
757 pm2.describe(proc_id);
758 });
759
760commander.command('env <id>')
761 .description('list all environment variables of a process id')
762 .action(function(proc_id) {
763 pm2.env(proc_id);
764 });
765
766//
767// List command
768//
769commander
770 .command('list')
771 .alias('ls')
772 .description('list all processes')
773 .action(function() {
774 pm2.list(commander)
775 });
776
777commander.command('l')
778 .description('(alias) list all processes')
779 .action(function() {
780 pm2.list()
781 });
782
783commander.command('ps')
784 .description('(alias) list all processes')
785 .action(function() {
786 pm2.list()
787 });
788
789commander.command('status')
790 .description('(alias) list all processes')
791 .action(function() {
792 pm2.list()
793 });
794
795
796// List in raw json
797commander.command('jlist')
798 .description('list all processes in JSON format')
799 .action(function() {
800 pm2.jlist()
801 });
802
803commander.command('sysmonit')
804 .description('start system monitoring daemon')
805 .action(function() {
806 pm2.launchSysMonitoring()
807 })
808
809commander.command('slist')
810 .alias('sysinfos')
811 .option('-t --tree', 'show as tree')
812 .description('list system infos in JSON')
813 .action(function(opts) {
814 pm2.slist(opts.tree)
815 })
816
817// List in prettified Json
818commander.command('prettylist')
819 .description('print json in a prettified JSON')
820 .action(failOnUnknown(function() {
821 pm2.jlist(true);
822 }));
823
824//
825// Dashboard command
826//
827commander.command('monit')
828 .description('launch termcaps monitoring')
829 .action(function() {
830 pm2.dashboard();
831 });
832
833commander.command('imonit')
834 .description('launch legacy termcaps monitoring')
835 .action(function() {
836 pm2.monit();
837 });
838
839commander.command('dashboard')
840 .alias('dash')
841 .description('launch dashboard with monitoring and logs')
842 .action(function() {
843 pm2.dashboard();
844 });
845
846
847//
848// Flushing command
849//
850
851commander.command('flush [api]')
852.description('flush logs')
853.action(function(api) {
854 pm2.flush(api);
855});
856
857/* old version
858commander.command('flush')
859 .description('flush logs')
860 .action(failOnUnknown(function() {
861 pm2.flush();
862 }));
863*/
864//
865// Reload all logs
866//
867commander.command('reloadLogs')
868 .description('reload all logs')
869 .action(function() {
870 pm2.reloadLogs();
871 });
872
873//
874// Log streaming
875//
876commander.command('logs [id|name|namespace]')
877 .option('--json', 'json log output')
878 .option('--format', 'formated log output')
879 .option('--raw', 'raw output')
880 .option('--err', 'only shows error output')
881 .option('--out', 'only shows standard output')
882 .option('--lines <n>', 'output the last N lines, instead of the last 15 by default')
883 .option('--timestamp [format]', 'add timestamps (default format YYYY-MM-DD-HH:mm:ss)')
884 .option('--nostream', 'print logs without lauching the log stream')
885 .option('--highlight [value]', 'highlights the given value')
886 .description('stream logs file. Default stream all logs')
887 .action(function(id, cmd) {
888 var Logs = require('../API/Log.js');
889
890 if (!id) id = 'all';
891
892 var line = 15;
893 var raw = false;
894 var exclusive = false;
895 var timestamp = false;
896 var highlight = false;
897
898 if(!isNaN(parseInt(cmd.lines))) {
899 line = parseInt(cmd.lines);
900 }
901
902 if (cmd.parent.rawArgs.indexOf('--raw') !== -1)
903 raw = true;
904
905 if (cmd.timestamp)
906 timestamp = typeof cmd.timestamp === 'string' ? cmd.timestamp : 'YYYY-MM-DD-HH:mm:ss';
907
908 if (cmd.highlight)
909 highlight = typeof cmd.highlight === 'string' ? cmd.highlight : false;
910
911 if (cmd.out === true)
912 exclusive = 'out';
913
914 if (cmd.err === true)
915 exclusive = 'err';
916
917 if (cmd.nostream === true)
918 pm2.printLogs(id, line, raw, timestamp, exclusive);
919 else if (cmd.json === true)
920 Logs.jsonStream(pm2.Client, id);
921 else if (cmd.format === true)
922 Logs.formatStream(pm2.Client, id, false, 'YYYY-MM-DD-HH:mm:ssZZ', exclusive, highlight);
923 else
924 pm2.streamLogs(id, line, raw, timestamp, exclusive, highlight);
925 });
926
927
928//
929// Kill
930//
931commander.command('kill')
932 .description('kill daemon')
933 .action(failOnUnknown(function(arg) {
934 pm2.killDaemon(function() {
935 process.exit(cst.SUCCESS_EXIT);
936 });
937 }));
938
939//
940// Update repository for a given app
941//
942
943commander.command('pull <name> [commit_id]')
944 .description('updates repository for a given app')
945 .action(function(pm2_name, commit_id) {
946
947 if (commit_id !== undefined) {
948 pm2._pullCommitId({
949 pm2_name: pm2_name,
950 commit_id: commit_id
951 });
952 }
953 else
954 pm2.pullAndRestart(pm2_name);
955 });
956
957//
958// Update repository to the next commit for a given app
959//
960commander.command('forward <name>')
961 .description('updates repository to the next commit for a given app')
962 .action(function(pm2_name) {
963 pm2.forward(pm2_name);
964 });
965
966//
967// Downgrade repository to the previous commit for a given app
968//
969commander.command('backward <name>')
970 .description('downgrades repository to the previous commit for a given app')
971 .action(function(pm2_name) {
972 pm2.backward(pm2_name);
973 });
974
975//
976// Perform a deep update of PM2
977//
978commander.command('deepUpdate')
979 .description('performs a deep update of PM2')
980 .action(function() {
981 pm2.deepUpdate();
982 });
983
984//
985// Launch a http server that expose a given path on given port
986//
987commander.command('serve [path] [port]')
988 .alias('expose')
989 .option('--port [port]', 'specify port to listen to')
990 .option('--spa', 'always serving index.html on inexistant sub path')
991 .option('--basic-auth-username [username]', 'set basic auth username')
992 .option('--basic-auth-password [password]', 'set basic auth password')
993 .option('--monitor [frontend-app]', 'frontend app monitoring (auto integrate snippet on html files)')
994 .description('serve a directory over http via port')
995 .action(function (path, port, cmd) {
996 pm2.serve(path, port || cmd.port, cmd, commander);
997 });
998
999commander.command('autoinstall')
1000 .action(function() {
1001 pm2.autoinstall()
1002 })
1003
1004commander.command('examples')
1005 .description('display pm2 usage examples')
1006 .action(() => {
1007 console.log(cst.PREFIX_MSG + chalk.grey('pm2 usage examples:\n'));
1008 displayExamples();
1009 process.exit(cst.SUCCESS_EXIT);
1010 })
1011
1012//
1013// Catch all
1014//
1015commander.command('*')
1016 .action(function() {
1017 console.log(cst.PREFIX_MSG_ERR + chalk.bold('Command not found\n'));
1018 displayUsage();
1019 // Check if it does not forget to close fds from RPC
1020 process.exit(cst.ERROR_EXIT);
1021 });
1022
1023//
1024// Display help if 0 arguments passed to pm2
1025//
1026if (process.argv.length == 2) {
1027 commander.parse(process.argv);
1028 displayUsage();
1029 // Check if it does not forget to close fds from RPC
1030 process.exit(cst.ERROR_EXIT);
1031}