]> git.proxmox.com Git - pve-common.git/blob - src/PVE/CLIHandler.pm
add run() method to CLIHandler
[pve-common.git] / src / PVE / CLIHandler.pm
1 package PVE::CLIHandler;
2
3 use strict;
4 use warnings;
5 use Data::Dumper;
6
7 use PVE::SafeSyslog;
8 use PVE::Exception qw(raise raise_param_exc);
9 use PVE::RESTHandler;
10 use PVE::PodParser;
11
12 use base qw(PVE::RESTHandler);
13
14 my $cmddef;
15 my $exename;
16
17 my $expand_command_name = sub {
18 my ($def, $cmd) = @_;
19
20 if (!$def->{$cmd}) {
21 my $expanded;
22 for my $k (keys(%$def)) {
23 if ($k =~ m/^$cmd/) {
24 if ($expanded) {
25 $expanded = undef; # more than one match
26 last;
27 } else {
28 $expanded = $k;
29 }
30 }
31 }
32 $cmd = $expanded if $expanded;
33 }
34 return $cmd;
35 };
36
37 __PACKAGE__->register_method ({
38 name => 'help',
39 path => 'help',
40 method => 'GET',
41 description => "Get help about specified command.",
42 parameters => {
43 additionalProperties => 0,
44 properties => {
45 cmd => {
46 description => "Command name",
47 type => 'string',
48 optional => 1,
49 },
50 verbose => {
51 description => "Verbose output format.",
52 type => 'boolean',
53 optional => 1,
54 },
55 },
56 },
57 returns => { type => 'null' },
58
59 code => sub {
60 my ($param) = @_;
61
62 die "not initialized" if !($cmddef && $exename);
63
64 my $cmd = $param->{cmd};
65
66 my $verbose = defined($cmd) && $cmd;
67 $verbose = $param->{verbose} if defined($param->{verbose});
68
69 if (!$cmd) {
70 if ($verbose) {
71 print_usage_verbose();
72 } else {
73 print_usage_short(\*STDOUT);
74 }
75 return undef;
76 }
77
78 $cmd = &$expand_command_name($cmddef, $cmd);
79
80 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd} || []};
81
82 raise_param_exc({ cmd => "no such command '$cmd'"}) if !$class;
83
84
85 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param, $verbose ? 'full' : 'short');
86 if ($verbose) {
87 print "$str\n";
88 } else {
89 print "USAGE: $str\n";
90 }
91
92 return undef;
93
94 }});
95
96 sub print_pod_manpage {
97 my ($podfn) = @_;
98
99 die "not initialized" if !($cmddef && $exename);
100 die "no pod file specified" if !$podfn;
101
102 my $synopsis = "";
103
104 $synopsis .= " $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
105
106 my $style = 'full'; # or should we use 'short'?
107 my $oldclass;
108 foreach my $cmd (sorted_commands()) {
109 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd}};
110 my $str = $class->usage_str($name, "$exename $cmd", $arg_param,
111 $uri_param, $style);
112 $str =~ s/^USAGE: //;
113
114 $synopsis .= "\n" if $oldclass && $oldclass ne $class;
115 $str =~ s/\n/\n /g;
116 $synopsis .= " $str\n\n";
117 $oldclass = $class;
118 }
119
120 $synopsis .= "\n";
121
122 my $parser = PVE::PodParser->new();
123 $parser->{include}->{synopsis} = $synopsis;
124 $parser->parse_from_file($podfn);
125 }
126
127 sub print_usage_verbose {
128
129 die "not initialized" if !($cmddef && $exename);
130
131 print "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n\n";
132
133 foreach my $cmd (sort keys %$cmddef) {
134 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd}};
135 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param, 'full');
136 print "$str\n\n";
137 }
138 }
139
140 sub sorted_commands {
141 return sort { ($cmddef->{$a}->[0] cmp $cmddef->{$b}->[0]) || ($a cmp $b)} keys %$cmddef;
142 }
143
144 sub print_usage_short {
145 my ($fd, $msg) = @_;
146
147 die "not initialized" if !($cmddef && $exename);
148
149 print $fd "ERROR: $msg\n" if $msg;
150 print $fd "USAGE: $exename <COMMAND> [ARGS] [OPTIONS]\n";
151
152 my $oldclass;
153 foreach my $cmd (sorted_commands()) {
154 my ($class, $name, $arg_param, $uri_param) = @{$cmddef->{$cmd}};
155 my $str = $class->usage_str($name, "$exename $cmd", $arg_param, $uri_param, 'short');
156 print $fd "\n" if $oldclass && $oldclass ne $class;
157 print $fd " $str";
158 $oldclass = $class;
159 }
160 }
161
162 my $print_bash_completion = sub {
163 my ($cmddef, $simple_cmd, $bash_command, $cur, $prev) = @_;
164
165 my $debug = 0;
166
167 return if !(defined($cur) && defined($prev) && defined($bash_command));
168 return if !defined($ENV{COMP_LINE});
169 return if !defined($ENV{COMP_POINT});
170
171 my $cmdline = substr($ENV{COMP_LINE}, 0, $ENV{COMP_POINT});
172 print STDERR "\nCMDLINE: $ENV{COMP_LINE}\n" if $debug;
173
174 # fixme: shell quoting??
175 my @args = split(/\s+/, $cmdline);
176 my $pos = scalar(@args) - 2;
177 $pos += 1 if $cmdline =~ m/\s+$/;
178
179 print STDERR "CMDLINE:$pos:$cmdline\n" if $debug;
180
181 return if $pos < 0;
182
183 my $print_result = sub {
184 foreach my $p (@_) {
185 print "$p\n" if $p =~ m/^$cur/;
186 }
187 };
188
189 my $cmd;
190 if ($simple_cmd) {
191 $cmd = $simple_cmd;
192 } else {
193 if ($pos == 0) {
194 &$print_result(keys %$cmddef);
195 return;
196 }
197 $cmd = $args[1];
198 }
199
200 my $def = $cmddef->{$cmd};
201 return if !$def;
202
203 print STDERR "CMDLINE1:$pos:$cmdline\n" if $debug;
204
205 my $skip_param = {};
206
207 my ($class, $name, $arg_param, $uri_param) = @$def;
208 $arg_param //= [];
209 $uri_param //= {};
210
211 map { $skip_param->{$_} = 1; } @$arg_param;
212 map { $skip_param->{$_} = 1; } keys %$uri_param;
213
214 my $fpcount = scalar(@$arg_param);
215
216 my $info = $class->map_method_by_name($name);
217
218 my $schema = $info->{parameters};
219 my $prop = $schema->{properties};
220
221 my $print_parameter_completion = sub {
222 my ($pname) = @_;
223 my $d = $prop->{$pname};
224 if ($d->{completion}) {
225 my $vt = ref($d->{completion});
226 if ($vt eq 'CODE') {
227 my $res = $d->{completion}->($cmd, $pname, $cur);
228 &$print_result(@$res);
229 }
230 } elsif ($d->{type} eq 'boolean') {
231 &$print_result('0', '1');
232 } elsif ($d->{enum}) {
233 &$print_result(@{$d->{enum}});
234 }
235 };
236
237 # positional arguments
238 $pos += 1 if $simple_cmd;
239 if ($fpcount && $pos <= $fpcount) {
240 my $pname = $arg_param->[$pos -1];
241 &$print_parameter_completion($pname);
242 return;
243 }
244
245 my @option_list = ();
246 foreach my $key (keys %$prop) {
247 next if $skip_param->{$key};
248 push @option_list, "--$key";
249 }
250
251 if ($cur =~ m/^-/) {
252 &$print_result(@option_list);
253 return;
254 }
255
256 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
257 my $pname = $1;
258 &$print_parameter_completion($pname);
259 return;
260 }
261
262 &$print_result(@option_list);
263 };
264
265 sub verify_api {
266 my ($class) = @_;
267
268 # simply verify all registered methods
269 PVE::RESTHandler::validate_method_schemas();
270 }
271
272 sub generate_pod_manpage {
273 my ($class, $podfn) = @_;
274
275 no strict 'refs';
276 $cmddef = ${"${class}::cmddef"};
277
278 $exename = $class;
279 $exename =~ s/^.*:://;
280
281 if (!defined($podfn)) {
282 my $cpath = "$class.pm";
283 $cpath =~ s/::/\//g;
284 foreach my $p (@INC) {
285 my $testfn = "$p/$cpath";
286 if (-f $testfn) {
287 $podfn = $testfn;
288 last;
289 }
290 }
291 }
292
293 die "unable to find source for class '$class'" if !$podfn;
294
295 print_pod_manpage($podfn);
296 }
297
298 sub run {
299 my ($class, $pwcallback, $preparefunc) = @_;
300
301 $ENV{'PATH'} = '/sbin:/bin:/usr/sbin:/usr/bin';
302
303 no strict 'refs';
304 $cmddef = ${"${class}::cmddef"};
305
306 $exename = $class;
307 $exename =~ s/^.*:://;
308
309 initlog($exename);
310
311 die "please run as root\n" if $> != 0;
312
313 PVE::INotify::inotify_init();
314
315 my $rpcenv = PVE::RPCEnvironment->init('cli');
316 $rpcenv->init_request();
317 $rpcenv->set_language($ENV{LANG});
318 $rpcenv->set_user('root@pam');
319
320 my $cmd = shift @ARGV;
321
322 handle_cmd($cmddef, $exename, $cmd, \@ARGV, $pwcallback, $0, $preparefunc);
323
324 exit 0;
325 }
326
327 sub handle_cmd {
328 my ($def, $cmdname, $cmd, $args, $pwcallback, $podfn, $preparefunc) = @_;
329
330 $cmddef = $def;
331 $exename = $cmdname;
332
333 $cmddef->{help} = [ __PACKAGE__, 'help', ['cmd'] ];
334
335 if (!$cmd) {
336 print_usage_short (\*STDERR, "no command specified");
337 exit (-1);
338 } elsif ($cmd eq 'verifyapi') {
339 PVE::RESTHandler::validate_method_schemas();
340 return;
341 } elsif ($cmd eq 'printmanpod') {
342 print_pod_manpage($podfn);
343 return;
344 } elsif ($cmd eq 'bashcomplete') {
345 &$print_bash_completion($cmddef, 0, @$args);
346 return;
347 }
348
349 &$preparefunc() if $preparefunc;
350
351 $cmd = &$expand_command_name($cmddef, $cmd);
352
353 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$cmddef->{$cmd} || []};
354
355 if (!$class) {
356 print_usage_short (\*STDERR, "unknown command '$cmd'");
357 exit (-1);
358 }
359
360 my $prefix = "$exename $cmd";
361 my $res = $class->cli_handler($prefix, $name, \@ARGV, $arg_param, $uri_param, $pwcallback);
362
363 &$outsub($res) if $outsub;
364 }
365
366 sub handle_simple_cmd {
367 my ($def, $args, $pwcallback, $podfn) = @_;
368
369 my ($class, $name, $arg_param, $uri_param, $outsub) = @{$def};
370 die "no class specified" if !$class;
371
372 if (scalar(@$args) >= 1) {
373 if ($args->[0] eq 'help') {
374 my $str = "USAGE: $name help\n";
375 $str .= $class->usage_str($name, $name, $arg_param, $uri_param, 'long');
376 print STDERR "$str\n\n";
377 return;
378 } elsif ($args->[0] eq 'bashcomplete') {
379 shift @$args;
380 &$print_bash_completion({ $name => $def }, $name, @$args);
381 return;
382 } elsif ($args->[0] eq 'verifyapi') {
383 PVE::RESTHandler::validate_method_schemas();
384 return;
385 } elsif ($args->[0] eq 'printmanpod') {
386 my $synopsis = " $name help\n\n";
387 my $str = $class->usage_str($name, $name, $arg_param, $uri_param, 'long');
388 $str =~ s/^USAGE://;
389 $str =~ s/\n/\n /g;
390 $synopsis .= $str;
391
392 my $parser = PVE::PodParser->new();
393 $parser->{include}->{synopsis} = $synopsis;
394 $parser->parse_from_file($podfn);
395 return;
396 }
397 }
398
399 my $res = $class->cli_handler($name, $name, \@ARGV, $arg_param, $uri_param, $pwcallback);
400
401 &$outsub($res) if $outsub;
402 }
403
404 1;