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