]> git.proxmox.com Git - pmg-api.git/blame - bin/pmgsh
API get /config/cluster/nodes: inlude node status from other cluster members
[pmg-api.git] / bin / pmgsh
CommitLineData
1d18e90b
DM
1#!/usr/bin/perl
2
3use strict;
4use warnings;
5use Term::ReadLine;
6use File::Basename;
7use Getopt::Long;
8use HTTP::Status qw(:constants :is status_message);
9use Text::ParseWords;
10
11use PVE::JSONSchema;
12use PVE::SafeSyslog;
13use PVE::INotify;
807a5c2e
DM
14
15use PMG::RESTEnvironment;
1d18e90b 16
ba11e2d3 17use PMG::Ticket;
1d18e90b
DM
18use PMG::Cluster;
19use PMG::API2;
ba11e2d3 20
1d18e90b
DM
21use JSON;
22
23PVE::INotify::inotify_init();
24
807a5c2e 25my $rpcenv = PMG::RESTEnvironment->init('cli');
1d18e90b
DM
26
27$rpcenv->set_language($ENV{LANG});
ba11e2d3
DM
28$rpcenv->set_user('root@pam');
29my $ticket = PMG::Ticket::assemble_ticket('root@pam');
1d18e90b
DM
30
31my $logid = $ENV{PVE_LOG_ID} || 'pmgsh';
32initlog($logid);
33
34my $basedir = '/api2/json';
35
36my $cdir = '';
37
38sub print_usage {
39 my $msg = shift;
40
41 print STDERR "ERROR: $msg\n" if $msg;
42 print STDERR "USAGE: pmgsh [verifyapi]\n";
43 print STDERR " pmgsh CMD [OPTIONS]\n";
44
45}
46
47my $disable_proxy = 0;
48my $opt_nooutput = 0;
49
50my $cmd = shift;
51
52my $optmatch;
53do {
54 $optmatch = 0;
55 if ($cmd) {
56 if ($cmd eq '--noproxy') {
57 $cmd = shift;
58 $disable_proxy = 1;
59 $optmatch = 1;
60 } elsif ($cmd eq '--nooutput') {
61 # we use this when starting task in CLI (suppress printing upid)
62 $cmd = shift;
63 $opt_nooutput = 1;
64 $optmatch = 1;
65 }
66 }
67} while ($optmatch);
68
69if ($cmd) {
70 if ($cmd eq 'verifyapi') {
71 PVE::RESTHandler::validate_method_schemas();
72 exit 0;
73 } elsif ($cmd eq 'ls' || $cmd eq 'get' || $cmd eq 'create' ||
74 $cmd eq 'set' || $cmd eq 'delete' ||$cmd eq 'help' ) {
75 pmg_command([ $cmd, @ARGV], $opt_nooutput);
76 exit(0);
77 } else {
78 print_usage ("unknown command '$cmd'");
79 exit (-1);
80 }
81}
82
83if (scalar (@ARGV) != 0) {
84 print_usage();
85 exit(-1);
86}
87
88print "entering PMG shell - type 'help' for help\n";
89
90my $term = new Term::ReadLine('pmgsh');
91my $attribs = $term->Attribs;
92
93sub complete_path {
94 my($text) = @_;
95
96 my ($dir, undef, $rest) = $text =~ m|^(.*/)?(([^/]*))?$|;
97 my $path = abs_path($cdir, $dir);
98
99 my @res = ();
100
101 my $di = dir_info($path);
102 if (my $children = $di->{children}) {
103 foreach my $c (@$children) {
104 if ($c =~ /^\Q$rest/) {
105 my $new = $dir ? "$dir$c" : $c;
106 push @res, $new;
107 }
108 }
109 }
110
111 if (scalar(@res) == 0) {
112 return undef;
113 } elsif (scalar(@res) == 1) {
114 return ($res[0], $res[0], "$res[0]/");
115 }
116
117 # lcd : lowest common denominator
118 my $lcd = '';
119 my $tmp = $res[0];
120 for (my $i = 1; $i <= length($tmp); $i++) {
121 my $found = 1;
122 foreach my $p (@res) {
123 if (substr($tmp, 0, $i) ne substr($p, 0, $i)) {
124 $found = 0;
125 last;
126 }
127 }
128 if ($found) {
129 $lcd = substr($tmp, 0, $i);
130 } else {
131 last;
132 }
133 }
134
135 return ($lcd, @res);
136};
137
138# just to avoid an endless loop (called by attempted_completion_function)
139$attribs->{completion_entry_function} = sub {
140 my($text, $state) = @_;
141 return undef;
142};
143
144$attribs->{attempted_completion_function} = sub {
145 my ($text, $line, $start) = @_;
146
147 my $prefix = substr($line, 0, $start);
148 if ($prefix =~ /^\s*$/) { # first word (command completeion)
149 $attribs->{completion_word} = [qw(help ls cd get set create delete quit)];
150 return $term->completion_matches($text, $attribs->{list_completion_function});
151 }
152
153 if ($prefix =~ /^\s*\S+\s+$/) { # second word (path completion)
154 return complete_path($text);
155 }
156
157 return ();
158};
159
160sub abs_path {
161 my ($current, $path) = @_;
162
163 my $ret = $current;
164
165 return $current if !defined($path);
166
167 $ret = '' if $path =~ m|^\/|;
168
169 foreach my $d (split (/\/+/ , $path)) {
170 if ($d eq '.') {
171 next;
172 } elsif ($d eq '..') {
173 $ret = dirname($ret);
174 $ret = '' if $ret eq '.';
175 } else {
176 $ret = "$ret/$d";
177 }
178 }
179
180 $ret =~ s|\/+|\/|g;
181 $ret =~ s|^\/||;
182 $ret =~ s|\/$||;
183
184 return $ret;
185}
186
187my $read_password = sub {
188 my $attribs = $term->Attribs;
189 my $old = $attribs->{redisplay_function};
190 $attribs->{redisplay_function} = $attribs->{shadow_redisplay};
191 my $input = $term->readline('password: ');
192 my $conf = $term->readline('Retype new password: ');
193 $attribs->{redisplay_function} = $old;
194
195 # remove password from history
196 if ($term->Features->{autohistory}) {
197 my $historyPosition = $term->where_history();
198 $term->remove_history($historyPosition);
199 $term->remove_history($historyPosition - 1);
200 }
201
202 die "Passwords do not match.\n" if ($input ne $conf);
203 return $input;
204};
205
206sub reverse_map_cmd {
207 my $method = shift;
208
209 my $mmap = {
210 GET => 'get',
211 PUT => 'set',
212 POST => 'create',
213 DELETE => 'delete',
214 };
215
216 my $cmd = $mmap->{$method};
217
218 die "got strange value for method ('$method') - internal error" if !$cmd;
219
220 return $cmd;
221}
222
223sub map_cmd {
224 my $cmd = shift;
225
226 my $mmap = {
227 create => 'POST',
228 set => 'PUT',
229 get => 'GET',
230 ls => 'GET',
231 delete => 'DELETE',
232 };
233
234 my $method = $mmap->{$cmd};
235
236 die "unable to map method" if !$method;
237
238 return $method;
239}
240
241sub check_proxyto {
242 my ($info, $uri_param) = @_;
243
244 if ($info->{proxyto}) {
245 my $pn = $info->{proxyto};
0fb55414
DM
246 my $node;
247 if ($pn eq 'master') {
248 $node = PMG::Cluster::get_master_node();
249 } else {
250 $node = $uri_param->{$pn};
251 die "proxy parameter '$pn' does not exists" if !$node;
252 }
1d18e90b
DM
253
254 if ($node ne 'localhost' && ($node ne PVE::INotify::nodename())) {
255 die "proxy loop detected - aborting\n" if $disable_proxy;
256 my $remip = PMG::Cluster::remote_node_ip($node);
257 return ($node, $remip);
258 }
259 }
260
261 return undef;
262}
263
264sub proxy_handler {
265 my ($node, $remip, $dir, $cmd, $args) = @_;
266
267 my $remcmd = ['ssh', '-o', 'BatchMode=yes', "root\@$remip",
268 'pmgsh', '--noproxy', $cmd, $dir, @$args];
269
270 system(@$remcmd) == 0 || die "proxy handler failed\n";
271}
272
273sub call_method {
274 my ($dir, $cmd, $args, $nooutput) = @_;
275
276 my $method = map_cmd($cmd);
277
278 my $uri_param = {};
279 my ($handler, $info) = PMG::API2->find_handler($method, $dir, $uri_param);
280 if (!$handler || !$info) {
281 die "no '$cmd' handler for '$dir'\n";
282 }
283
284 my ($node, $remip) = check_proxyto($info, $uri_param);
285 return proxy_handler($node, $remip, $dir, $cmd, $args) if $node;
286
287 my $data = $handler->cli_handler("$cmd $dir", $info->{name}, $args, [], $uri_param, $read_password);
288
289 return if $nooutput;
290
291 warn "200 OK\n"; # always print OK status if successful
292
293 if ($info && $info->{returns} && $info->{returns}->{type}) {
294 my $rtype = $info->{returns}->{type};
295
296 return if $rtype eq 'null';
297
298 if ($rtype eq 'string') {
299 print $data if $data;
300 return;
301 }
302 }
303
304 print to_json($data, {utf8 => 1, allow_nonref => 1, canonical => 1, pretty => 1 });
305
306 return;
307}
308
309sub find_resource_methods {
310 my ($path, $ihash) = @_;
311
312 for my $method (qw(GET POST PUT DELETE)) {
313 my $uri_param = {};
314 my $path_match;
315 my ($handler, $info) = PMG::API2->find_handler($method, $path, $uri_param, \$path_match);
316 if ($handler && $info && !$ihash->{$info}) {
317 $ihash->{$info} = {
318 path => $path_match,
319 handler => $handler,
320 info => $info,
321 uri_param => $uri_param,
322 };
323 }
324 }
325}
326
327sub print_help {
328 my ($path, $opts) = @_;
329
330 my $ihash = {};
331
332 find_resource_methods($path, $ihash);
333
334 if (!scalar(keys(%$ihash))) {
335 die "no such resource\n";
336 }
337
338 my $di = dir_info($path);
339 if (my $children = $di->{children}) {
340 foreach my $c (@$children) {
341 my $cp = abs_path($path, $c);
342 find_resource_methods($cp, $ihash);
343 }
344 }
345
346 foreach my $mi (sort { $a->{path} cmp $b->{path} } values %$ihash) {
347 my $method = $mi->{info}->{method};
348
349 # we skip index methods for now.
350 next if ($method eq 'GET') && PVE::JSONSchema::method_get_child_link($mi->{info});
351
352 my $path = $mi->{path};
353 $path =~ s|/+$||; # remove trailing slash
354
355 my $cmd = reverse_map_cmd($method);
356
357 print $mi->{handler}->usage_str($mi->{info}->{name}, "$cmd $path", [], $mi->{uri_param},
358 $opts->{verbose} ? 'full' : 'short', 1);
359 print "\n\n" if $opts->{verbose};
360 }
361
362};
363
364sub resource_cap {
365 my ($path) = @_;
366
367 my $res = '';
368
369 my ($handler, $info) = PMG::API2->find_handler('GET', $path);
370 if (!($handler && $info)) {
371 $res .= '--';
372 } else {
373 if (PVE::JSONSchema::method_get_child_link($info)) {
374 $res .= 'Dr';
375 } else {
376 $res .= '-r';
377 }
378 }
379
380 ($handler, $info) = PMG::API2->find_handler('PUT', $path);
381 if (!($handler && $info)) {
382 $res .= '-';
383 } else {
384 $res .= 'w';
385 }
386
387 ($handler, $info) = PMG::API2->find_handler('POST', $path);
388 if (!($handler && $info)) {
389 $res .= '-';
390 } else {
391 $res .= 'c';
392 }
393
394 ($handler, $info) = PMG::API2->find_handler('DELETE', $path);
395 if (!($handler && $info)) {
396 $res .= '-';
397 } else {
398 $res .= 'd';
399 }
400
401 return $res;
402}
403
404sub extract_children {
405 my ($lnk, $data) = @_;
406
407 my $res = [];
408
409 return $res if !($lnk && $data);
410
411 my $href = $lnk->{href};
412 if ($href =~ m/^\{(\S+)\}$/) {
413 my $prop = $1;
414
415 foreach my $elem (sort {$a->{$prop} cmp $b->{$prop}} @$data) {
416 next if !ref($elem);
417 my $value = $elem->{$prop};
418 push @$res, $value;
419 }
420 }
421
422 return $res;
423}
424
425sub dir_info {
426 my ($path) = @_;
427
428 my $res = { path => $path };
429 my $uri_param = {};
430 my ($handler, $info, $pm) = PMG::API2->find_handler('GET', $path, $uri_param);
431 if ($handler && $info) {
432 eval {
433 my $data = $handler->handle($info, $uri_param);
434 my $lnk = PVE::JSONSchema::method_get_child_link($info);
435 $res->{children} = extract_children($lnk, $data);
436 }; # ignore errors ?
437 }
438 return $res;
439}
440
441sub list_dir {
442 my ($dir, $args) = @_;
443
444 my $uri_param = {};
445 my ($handler, $info) = PMG::API2->find_handler('GET', $dir, $uri_param);
446 if (!$handler || !$info) {
447 die "no such resource\n";
448 }
449
450 if (!PVE::JSONSchema::method_get_child_link($info)) {
451 die "resource does not define child links\n";
452 }
453
454 my ($node, $remip) = check_proxyto($info, $uri_param);
455 return proxy_handler($node, $remip, $dir, 'ls', $args) if $node;
456
457
458 my $data = $handler->cli_handler("ls $dir", $info->{name}, $args, [], $uri_param, $read_password);
459 my $lnk = PVE::JSONSchema::method_get_child_link($info);
460 my $children = extract_children($lnk, $data);
461
462 foreach my $c (@$children) {
463 my $cap = resource_cap(abs_path($dir, $c));
464 print "$cap $c\n";
465 }
466}
467
468sub pmg_command {
469 my ($args, $nooutput) = @_;
470
471 $rpcenv->init_request();
472
ba11e2d3
DM
473 $rpcenv->set_ticket($ticket);
474
1d18e90b
DM
475 my $cmd = shift @$args;
476
477 if ($cmd eq 'cd') {
478
479 my $path = shift @$args;
480
481 die "usage: cd [dir]\n" if scalar(@$args);
482
483 if (!defined($path)) {
484 $cdir = '';
485 return;
486 } else {
487 my $new_dir = abs_path($cdir, $path);
488 my ($handler, $info) = PMG::API2->find_handler('GET', $new_dir);
489 die "no such resource\n" if !$handler;
490 $cdir = $new_dir;
491 }
492
493 } elsif ($cmd eq 'help') {
494
495 my $help_usage_error = sub {
496 die "usage: help [path] [--verbose]\n";
497 };
498
499 my $opts = {};
500
501 &$help_usage_error() if !Getopt::Long::GetOptionsFromArray($args, $opts, 'verbose');
502
503 my $path;
504 if (scalar(@$args) && $args->[0] !~ m/^\-/) {
505 $path = shift @$args;
506 }
507
508 &$help_usage_error() if scalar(@$args);
509
510 print "help [path] [--verbose]\n";
511 print "cd [path]\n";
512 print "ls [path]\n\n";
513
514 print_help(abs_path($cdir, $path), $opts);
515
516 } elsif ($cmd eq 'ls') {
517 my $path;
518 if (scalar(@$args) && $args->[0] !~ m/^\-/) {
519 $path = shift @$args;
520 }
521
522 list_dir(abs_path($cdir, $path), $args);
523
524 } elsif ($cmd =~ m/^get|delete|set$/) {
525
526 my $path;
527 if (scalar(@$args) && $args->[0] !~ m/^\-/) {
528 $path = shift @$args;
529 }
530
531 call_method(abs_path($cdir, $path), $cmd, $args);
532
533 } elsif ($cmd eq 'create') {
534
535 my $path;
536 if (scalar(@$args) && $args->[0] !~ m/^\-/) {
537 $path = shift @$args;
538 }
539
540 call_method(abs_path($cdir, $path), $cmd, $args, $nooutput);
541
542 } else {
543 die "unknown command '$cmd'\n";
544 }
545
546}
547
548my $input;
549while (defined ($input = $term->readline("pmg:/$cdir> "))) {
550 chomp $input;
551
552 next if $input =~ m/^\s*$/;
553
554 if ($input =~ m/^\s*q(uit)?\s*$/) {
555 exit (0);
556 }
557
558 # add input to history if it gets not
559 # automatically added
560 if (!$term->Features->{autohistory}) {
561 $term->addhistory($input);
562 }
563
564 eval {
565 my $args = [ shellwords($input) ];
566 pmg_command($args);
567 };
568 warn $@ if $@;
569}
570
571__END__
572
573=head1 NAME
574
575pmgsh - shell interface to the Promox Mail Gateway API
576
577=head1 SYNOPSIS
578
579pmgsh [get|set|create|delete|help] [REST API path] [--verbose]
580
581=head1 DESCRIPTION
582
583pmgsh provides a shell-like interface to the Proxmox Mail Gateway API, in
584two different modes:
585
586=over
587
588=item interactive
589
590when called without parameters, pmgsh starts an interactive client,
591where you can navigate in the different parts of the API
592
593=item command line
594
595when started with parameters pmgsh will send a command to the
596corresponding REST url, and will return the JSON formatted output
597
598=back
599
600=head1 EXAMPLES
601
602get the list of nodes in my cluster
603
604pmgsh get /nodes
605