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 .option('--ws', 'websocket mode')
586 .option('--axon', 'axon mode')
587 .description('link with the pm2 monitoring dashboard')
588 .action(pm2.linkManagement.bind(pm2));
589
590commander.command('unlink')
591 .description('unlink with the pm2 monitoring dashboard')
592 .action(function() {
593 pm2.unlink();
594 });
595
596commander.command('monitor [name]')
597 .description('monitor target process')
598 .action(function(name) {
599 if (name === undefined) {
600 return plusHandler()
601 }
602 pm2.monitorState('monitor', name);
603 });
604
605commander.command('unmonitor [name]')
606 .description('unmonitor target process')
607 .action(function(name) {
608 pm2.monitorState('unmonitor', name);
609 });
610
611commander.command('open')
612 .description('open the pm2 monitoring dashboard')
613 .action(function(name) {
614 pm2.openDashboard();
615 });
616
617function plusHandler (command, opts) {
618 if (opts && opts.infoNode) {
619 process.env.KEYMETRICS_NODE = opts.infoNode
620 }
621
622 return PM2ioHandler.launch(command, opts)
623}
624
625commander.command('plus [command] [option]')
626 .alias('register')
627 .option('--info-node [url]', 'set url info node for on-premise pm2 plus')
628 .option('-d --discrete', 'silent mode')
629 .option('-a --install-all', 'install all modules (force yes)')
630 .description('enable pm2 plus')
631 .action(plusHandler);
632
633commander.command('login')
634 .description('Login to pm2 plus')
635 .action(function() {
636 return plusHandler('login')
637 });
638
639commander.command('logout')
640 .description('Logout from pm2 plus')
641 .action(function() {
642 return plusHandler('logout')
643 });
644
645//
646// Save processes to file
647//
648commander.command('dump')
649 .alias('save')
650 .option('--force', 'force deletion of dump file, even if empty')
651 .description('dump all processes for resurrecting them later')
652 .action(failOnUnknown(function(opts) {
653 pm2.dump(commander.force)
654 }));
655
656//
657// Delete dump file
658//
659commander.command('cleardump')
660 .description('Create empty dump file')
661 .action(failOnUnknown(function() {
662 pm2.clearDump();
663 }));
664
665//
666// Save processes to file
667//
668commander.command('send <pm_id> <line>')
669 .description('send stdin to <pm_id>')
670 .action(function(pm_id, line) {
671 pm2.sendLineToStdin(pm_id, line);
672 });
673
674//
675// Attach to stdin/stdout
676// Not TTY ready
677//
678commander.command('attach <pm_id> [command separator]')
679 .description('attach stdin/stdout to application identified by <pm_id>')
680 .action(function(pm_id, separator) {
681 pm2.attach(pm_id, separator);
682 });
683
684//
685// Resurrect
686//
687commander.command('resurrect')
688 .description('resurrect previously dumped processes')
689 .action(failOnUnknown(function() {
690 console.log(cst.PREFIX_MSG + 'Resurrecting');
691 pm2.resurrect();
692 }));
693
694//
695// Set pm2 to startup
696//
697commander.command('unstartup [platform]')
698 .description('disable the pm2 startup hook')
699 .action(function(platform) {
700 pm2.uninstallStartup(platform, commander);
701 });
702
703//
704// Set pm2 to startup
705//
706commander.command('startup [platform]')
707 .description('enable the pm2 startup hook')
708 .action(function(platform) {
709 pm2.startup(platform, commander);
710 });
711
712//
713// Logrotate
714//
715commander.command('logrotate')
716 .description('copy default logrotate configuration')
717 .action(function(cmd) {
718 pm2.logrotate(commander);
719 });
720
721//
722// Sample generate
723//
724
725commander.command('ecosystem [mode]')
726 .alias('init')
727 .description('generate a process conf file. (mode = null or simple)')
728 .action(function(mode) {
729 pm2.generateSample(mode);
730 });
731
732commander.command('reset <name|id|all>')
733 .description('reset counters for process')
734 .action(function(proc_id) {
735 pm2.reset(proc_id);
736 });
737
738commander.command('describe <name|id>')
739 .description('describe all parameters of a process')
740 .action(function(proc_id) {
741 pm2.describe(proc_id);
742 });
743
744commander.command('desc <name|id>')
745 .description('(alias) describe all parameters of a process')
746 .action(function(proc_id) {
747 pm2.describe(proc_id);
748 });
749
750commander.command('info <name|id>')
751 .description('(alias) describe all parameters of a process')
752 .action(function(proc_id) {
753 pm2.describe(proc_id);
754 });
755
756commander.command('show <name|id>')
757 .description('(alias) describe all parameters of a process')
758 .action(function(proc_id) {
759 pm2.describe(proc_id);
760 });
761
762commander.command('env <id>')
763 .description('list all environment variables of a process id')
764 .action(function(proc_id) {
765 pm2.env(proc_id);
766 });
767
768//
769// List command
770//
771commander
772 .command('list')
773 .alias('ls')
774 .description('list all processes')
775 .action(function() {
776 pm2.list(commander)
777 });
778
779commander.command('l')
780 .description('(alias) list all processes')
781 .action(function() {
782 pm2.list()
783 });
784
785commander.command('ps')
786 .description('(alias) list all processes')
787 .action(function() {
788 pm2.list()
789 });
790
791commander.command('status')
792 .description('(alias) list all processes')
793 .action(function() {
794 pm2.list()
795 });
796
797
798// List in raw json
799commander.command('jlist')
800 .description('list all processes in JSON format')
801 .action(function() {
802 pm2.jlist()
803 });
804
805commander.command('sysmonit')
806 .description('start system monitoring daemon')
807 .action(function() {
808 pm2.launchSysMonitoring()
809 })
810
811commander.command('slist')
812 .alias('sysinfos')
813 .option('-t --tree', 'show as tree')
814 .description('list system infos in JSON')
815 .action(function(opts) {
816 pm2.slist(opts.tree)
817 })
818
819// List in prettified Json
820commander.command('prettylist')
821 .description('print json in a prettified JSON')
822 .action(failOnUnknown(function() {
823 pm2.jlist(true);
824 }));
825
826//
827// Dashboard command
828//
829commander.command('monit')
830 .description('launch termcaps monitoring')
831 .action(function() {
832 pm2.dashboard();
833 });
834
835commander.command('imonit')
836 .description('launch legacy termcaps monitoring')
837 .action(function() {
838 pm2.monit();
839 });
840
841commander.command('dashboard')
842 .alias('dash')
843 .description('launch dashboard with monitoring and logs')
844 .action(function() {
845 pm2.dashboard();
846 });
847
848
849//
850// Flushing command
851//
852
853commander.command('flush [api]')
854.description('flush logs')
855.action(function(api) {
856 pm2.flush(api);
857});
858
859/* old version
860commander.command('flush')
861 .description('flush logs')
862 .action(failOnUnknown(function() {
863 pm2.flush();
864 }));
865*/
866//
867// Reload all logs
868//
869commander.command('reloadLogs')
870 .description('reload all logs')
871 .action(function() {
872 pm2.reloadLogs();
873 });
874
875//
876// Log streaming
877//
878commander.command('logs [id|name|namespace]')
879 .option('--json', 'json log output')
880 .option('--format', 'formated log output')
881 .option('--raw', 'raw output')
882 .option('--err', 'only shows error output')
883 .option('--out', 'only shows standard output')
884 .option('--lines <n>', 'output the last N lines, instead of the last 15 by default')
885 .option('--timestamp [format]', 'add timestamps (default format YYYY-MM-DD-HH:mm:ss)')
886 .option('--nostream', 'print logs without lauching the log stream')
887 .option('--highlight [value]', 'highlights the given value')
888 .description('stream logs file. Default stream all logs')
889 .action(function(id, cmd) {
890 var Logs = require('../API/Log.js');
891
892 if (!id) id = 'all';
893
894 var line = 15;
895 var raw = false;
896 var exclusive = false;
897 var timestamp = false;
898 var highlight = false;
899
900 if(!isNaN(parseInt(cmd.lines))) {
901 line = parseInt(cmd.lines);
902 }
903
904 if (cmd.parent.rawArgs.indexOf('--raw') !== -1)
905 raw = true;
906
907 if (cmd.timestamp)
908 timestamp = typeof cmd.timestamp === 'string' ? cmd.timestamp : 'YYYY-MM-DD-HH:mm:ss';
909
910 if (cmd.highlight)
911 highlight = typeof cmd.highlight === 'string' ? cmd.highlight : false;
912
913 if (cmd.out === true)
914 exclusive = 'out';
915
916 if (cmd.err === true)
917 exclusive = 'err';
918
919 if (cmd.nostream === true)
920 pm2.printLogs(id, line, raw, timestamp, exclusive);
921 else if (cmd.json === true)
922 Logs.jsonStream(pm2.Client, id);
923 else if (cmd.format === true)
924 Logs.formatStream(pm2.Client, id, false, 'YYYY-MM-DD-HH:mm:ssZZ', exclusive, highlight);
925 else
926 pm2.streamLogs(id, line, raw, timestamp, exclusive, highlight);
927 });
928
929
930//
931// Kill
932//
933commander.command('kill')
934 .description('kill daemon')
935 .action(failOnUnknown(function(arg) {
936 pm2.killDaemon(function() {
937 process.exit(cst.SUCCESS_EXIT);
938 });
939 }));
940
941//
942// Update repository for a given app
943//
944
945commander.command('pull <name> [commit_id]')
946 .description('updates repository for a given app')
947 .action(function(pm2_name, commit_id) {
948
949 if (commit_id !== undefined) {
950 pm2._pullCommitId({
951 pm2_name: pm2_name,
952 commit_id: commit_id
953 });
954 }
955 else
956 pm2.pullAndRestart(pm2_name);
957 });
958
959//
960// Update repository to the next commit for a given app
961//
962commander.command('forward <name>')
963 .description('updates repository to the next commit for a given app')
964 .action(function(pm2_name) {
965 pm2.forward(pm2_name);
966 });
967
968//
969// Downgrade repository to the previous commit for a given app
970//
971commander.command('backward <name>')
972 .description('downgrades repository to the previous commit for a given app')
973 .action(function(pm2_name) {
974 pm2.backward(pm2_name);
975 });
976
977//
978// Perform a deep update of PM2
979//
980commander.command('deepUpdate')
981 .description('performs a deep update of PM2')
982 .action(function() {
983 pm2.deepUpdate();
984 });
985
986//
987// Launch a http server that expose a given path on given port
988//
989commander.command('serve [path] [port]')
990 .alias('expose')
991 .option('--port [port]', 'specify port to listen to')
992 .option('--spa', 'always serving index.html on inexistant sub path')
993 .option('--basic-auth-username [username]', 'set basic auth username')
994 .option('--basic-auth-password [password]', 'set basic auth password')
995 .option('--monitor [frontend-app]', 'frontend app monitoring (auto integrate snippet on html files)')
996 .description('serve a directory over http via port')
997 .action(function (path, port, cmd) {
998 pm2.serve(path, port || cmd.port, cmd, commander);
999 });
1000
1001commander.command('autoinstall')
1002 .action(function() {
1003 pm2.autoinstall()
1004 })
1005
1006commander.command('examples')
1007 .description('display pm2 usage examples')
1008 .action(() => {
1009 console.log(cst.PREFIX_MSG + chalk.grey('pm2 usage examples:\n'));
1010 displayExamples();
1011 process.exit(cst.SUCCESS_EXIT);
1012 })
1013
1014//
1015// Catch all
1016//
1017commander.command('*')
1018 .action(function() {
1019 console.log(cst.PREFIX_MSG_ERR + chalk.bold('Command not found\n'));
1020 displayUsage();
1021 // Check if it does not forget to close fds from RPC
1022 process.exit(cst.ERROR_EXIT);
1023 });
1024
1025//
1026// Display help if 0 arguments passed to pm2
1027//
1028if (process.argv.length == 2) {
1029 commander.parse(process.argv);
1030 displayUsage();
1031 // Check if it does not forget to close fds from RPC
1032 process.exit(cst.ERROR_EXIT);
1033}