]> git.proxmox.com Git - pve-client.git/blame - PVE/APIClient/Helpers.pm
complete_api_path: minimize completions
[pve-client.git] / PVE / APIClient / Helpers.pm
CommitLineData
29505e2c
DM
1package PVE::APIClient::Helpers;
2
3use strict;
4use warnings;
5
ab79ce78 6use Storable;
29505e2c 7use JSON;
df89fcb9
DM
8use File::Path qw(make_path);
9
51da1502 10use PVE::APIClient::JSONSchema;
29505e2c 11use PVE::APIClient::Exception qw(raise);
5101e472
DM
12use PVE::APIClient::CLIFormatter;
13use PVE::APIClient::CLIHandler;
14use PVE::APIClient::PTY;
29505e2c
DM
15use Encode::Locale;
16use Encode;
17use HTTP::Status qw(:constants);
18
19my $pve_api_definition;
29505e2c 20
ab79ce78 21my $pve_api_definition_fn = "/usr/share/pve-client/pve-api-definition.dat";
29505e2c 22
55d17e7e 23our $method_map = {
b133a905
DM
24 create => 'POST',
25 set => 'PUT',
26 get => 'GET',
27 delete => 'DELETE',
28};
29
51da1502
DM
30my $__real_remove_formats; $__real_remove_formats = sub {
31 my ($properties) = @_;
32
33 foreach my $pname (keys %$properties) {
34 if (my $d = $properties->{$pname}) {
35 if (defined(my $format = $d->{format})) {
36 if (ref($format)) {
37 $__real_remove_formats->($format);
38 } elsif (!PVE::APIClient::JSONSchema::get_format($format)) {
39 # simply remove unknown format definitions
40 delete $d->{format};
41 }
42 }
43 }
44 }
45};
46
47my $remove_unknown_formats; $remove_unknown_formats = sub {
48 my ($tree) = @_;
49
50 my $class = ref($tree);
51 return if !$class;
52
53 if ($class eq 'ARRAY') {
54 foreach my $el (@$tree) {
55 $remove_unknown_formats->($el);
56 }
57 } elsif ($class eq 'HASH') {
58 if (my $info = $tree->{info}) {
59 for my $method (qw(GET PUT PUSH DELETE)) {
60 next if !$info->{$method};
61 my $properties = $info->{$method}->{parameters}->{properties};
62 $__real_remove_formats->($properties) if $properties;
63 }
64 }
65 if ($tree->{children}) {
66 $remove_unknown_formats->($tree->{children});
67 }
68 }
69 return;
70};
71
29505e2c
DM
72sub get_api_definition {
73
74 if (!defined($pve_api_definition)) {
29505e2c
DM
75 open(my $fh, '<', $pve_api_definition_fn) ||
76 die "unable to open '$pve_api_definition_fn' - $!\n";
ab79ce78 77 $pve_api_definition = Storable::fd_retrieve($fh);
51da1502
DM
78
79 $remove_unknown_formats->($pve_api_definition);
29505e2c
DM
80 }
81
29505e2c
DM
82 return $pve_api_definition;
83}
84
520f543e
DM
85my $map_path_to_info = sub {
86 my ($child_list, $stack, $uri_param) = @_;
87
88 while (defined(my $comp = shift @$stack)) {
89 foreach my $child (@$child_list) {
90 my $text = $child->{text};
91
92 if ($text eq $comp) {
93 # found
94 } elsif ($text =~ m/^\{(\S+)\}$/) {
95 # found
96 $uri_param->{$1} = $comp;
97 } else {
98 next; # text next child
99 }
100 if ($child->{leaf} || !scalar(@$stack)) {
101 return $child;
102 } else {
103 $child_list = $child->{children};
104 last; # test next path component
105 }
106 }
107 }
108 return undef;
109};
29505e2c 110
520f543e
DM
111sub find_method_info {
112 my ($path, $method, $uri_param, $noerr) = @_;
29505e2c 113
520f543e 114 $uri_param //= {};
635c0511 115
520f543e 116 my $stack = [ grep { length($_) > 0 } split('\/+' , $path)]; # skip empty fragments
29505e2c 117
2ecf9b57
DM
118 my $api = get_api_definition();
119
120 my $child = scalar(@$stack) ? $map_path_to_info->($api->{children}, $stack, $uri_param) : $api;
635c0511 121
520f543e 122 if (!($child && $child->{info} && $child->{info}->{$method})) {
635c0511 123 return undef if $noerr;
29505e2c 124 die "unable to find API method '$method' for path '$path'\n";
635c0511 125 }
29505e2c 126
520f543e 127 return $child->{info}->{$method};
29505e2c
DM
128}
129
635c0511
DM
130sub complete_api_call_options {
131 my ($cmd, $prop, $prev, $cur, $args) = @_;
132
133 my $print_result = sub {
134 foreach my $p (@_) {
135 print "$p\n" if $p =~ m/^$cur/;
136 }
137 };
138
139 my $print_parameter_completion = sub {
140 my ($pname) = @_;
141 my $d = $prop->{$pname};
142 if ($d->{completion}) {
143 my $vt = ref($d->{completion});
144 if ($vt eq 'CODE') {
145 my $res = $d->{completion}->($cmd, $pname, $cur, $args);
146 &$print_result(@$res);
147 }
148 } elsif ($d->{type} eq 'boolean') {
149 &$print_result('0', '1');
150 } elsif ($d->{enum}) {
151 &$print_result(@{$d->{enum}});
152 }
153 };
154
155 my @option_list = ();
156 foreach my $key (keys %$prop) {
157 push @option_list, "--$key";
158 }
159
160 if ($cur =~ m/^-/) {
161 &$print_result(@option_list);
162 return;
163 }
164
165 if ($prev =~ m/^--?(.+)$/ && $prop->{$1}) {
166 my $pname = $1;
167 &$print_parameter_completion($pname);
168 return;
169 }
170
171 &$print_result(@option_list);
172}
173
b7db4587
RJ
174sub merge_api_definition_properties {
175 my ($path, $method, $properties) = @_;
176
177 my $info = PVE::APIClient::Helpers::find_method_info($path, $method);
178
179 return { %{$info->{parameters}->{properties}}, %$properties };
180}
181
635c0511
DM
182sub complete_api_path {
183 my ($text) = @_;
184
2ecf9b57 185 my $api = get_api_definition(); # make sure API data is loaded
635c0511
DM
186
187 $text =~ s!^/!!;
188
189 my ($dir, $rest) = $text =~ m|^(?:(.*)/)?(?:([^/]*))?$|;
190
191 my $info;
192 if (!defined($dir)) {
193 $dir = '';
2ecf9b57 194 $info = $api;
635c0511 195 } else {
520f543e 196 my $stack = [ grep { length($_) > 0 } split('\/+' , $dir)]; # skip empty fragments
2ecf9b57 197 $info = $map_path_to_info->($api->{children}, $stack, {});
635c0511
DM
198 }
199
b133a905 200 my $res = [];
635c0511 201 if ($info) {
520f543e 202 my $prefix = length($dir) ? "/$dir/" : '/';
635c0511
DM
203 if (my $children = $info->{children}) {
204 foreach my $c (@$children) {
520f543e 205 my $ctext = $c->{text};
a00bef99 206 push @$res, "${prefix}$ctext" if $ctext =~ m/^\Q$rest/;
520f543e 207 if ($ctext =~ m/^\{(\S+)\}$/) {
a00bef99 208 if (length($rest) && $rest ne $ctext) {
520f543e 209 push @$res, "$prefix$rest";
520f543e 210 }
635c0511
DM
211 }
212 }
213 }
214 }
520f543e 215
a00bef99
DM
216 if (scalar(@$res) == 1) {
217 $res = [$res->[0], "$res->[0]/"];
218 }
219
b133a905
DM
220 return $res;
221}
222
223# test for command lines with api calls (or similar bash completion calls):
224# example1: pveclient api get remote1 /cluster
225sub extract_path_info {
520f543e 226 my ($uri_param) = @_;
b133a905
DM
227
228 my $info;
229
230 my $test_path_properties = sub {
231 my ($args) = @_;
232
233 return if scalar(@$args) < 5;
234 return if $args->[1] ne 'api';
235
236 my $path = $args->[4];
237 if (my $method = $method_map->{$args->[2]}) {
520f543e 238 $info = find_method_info($path, $method, $uri_param, 1);
b133a905
DM
239 }
240 };
241
242 if (defined(my $cmd = $ARGV[0])) {
243 if ($cmd eq 'api') {
244 $test_path_properties->([$0, @ARGV]);
245 } elsif ($cmd eq 'bashcomplete') {
246 my $cmdline = substr($ENV{COMP_LINE}, 0, $ENV{COMP_POINT});
ca3269f4 247 my $args = PVE::APIClient::Tools::split_args($cmdline);
b133a905
DM
248 $test_path_properties->($args);
249 }
250 }
251
252 return $info;
635c0511
DM
253}
254
2f964a75
RJ
255sub get_vmid_resource {
256 my ($conn, $vmid) = @_;
257
258 my $resources = $conn->get('api2/json/cluster/resources', {type => 'vm'});
259
260 my $resource;
261 for my $tmp (@$resources) {
262 if ($tmp->{vmid} eq $vmid) {
263 $resource = $tmp;
264 last;
265 }
266 }
267
268 if (!defined($resource)) {
269 die "\"$vmid\" not found";
270 }
271
272 return $resource;
273}
274
275sub poll_task {
2b267ba2 276 my ($conn, $node, $upid, $quiet) = @_;
2f964a75
RJ
277
278 my $path = "api2/json/nodes/$node/tasks/$upid/status";
279
280 my $task_status;
2b267ba2 281 my $last_line = 0;
2f964a75 282 while(1) {
2b267ba2
RJ
283 if (!$quiet) {
284 my $path = "api2/json/nodes/$node/tasks/$upid/log";
285 my $task_log = $conn->get($path, {start => $last_line});
286
287 my $printme = '';
288 for my $li (@$task_log) {
289 if ($li->{t} eq 'no content') {
290 next;
291 }
292 $printme .= $li->{t} . "\n";
293 $last_line = $li->{n};
294 }
295
296 if ($printme ne '') {
297 print $printme;
298 }
299 }
300
2f964a75
RJ
301 $task_status = $conn->get($path, {});
302
303 if ($task_status->{status} eq "stopped") {
304 last;
305 }
306
2b267ba2 307 sleep(2);
2f964a75
RJ
308 }
309
20e7131b
RJ
310 if ($task_status->{exitstatus} ne "OK") {
311 die $task_status->{exitstatus};
312 }
313
2f964a75
RJ
314 return $task_status->{exitstatus};
315}
316
0ca37028
DM
317sub configuration_directory {
318
319 my $home = $ENV{HOME} // '';
320 my $xdg = $ENV{XDG_CONFIG_HOME} // '';
321
322 my $subdir = "pveclient";
323
324 return "$xdg/$subdir" if length($xdg);
325
326 return "$home/.config/$subdir" if length($home);
327
328 die "neither XDG_CONFIG_HOME nor HOME environment variable set\n";
329}
330
df89fcb9
DM
331my $ticket_cache_filename = "/.tickets";
332
333sub ticket_cache_lookup {
334 my ($remote) = @_;
335
336 my $dir = configuration_directory();
337 my $filename = "$dir/$ticket_cache_filename";
338
339 my $data = {};
340 eval { $data = from_json(PVE::APIClient::Tools::file_get_contents($filename)); };
341 # ignore errors
342
343 my $ticket = $data->{$remote};
344 return undef if !defined($ticket);
345
346 my $min_age = - 60;
347 my $max_age = 3600*2 - 60;
348
349 if ($ticket =~ m/:([a-fA-F0-9]{8})::/) {
350 my $ttime = hex($1);
351 my $ctime = time();
352 my $age = $ctime - $ttime;
353
354 return $ticket if ($age > $min_age) && ($age < $max_age);
355 }
356
357 return undef;
358}
359
360sub ticket_cache_update {
361 my ($remote, $ticket) = @_;
362
363 my $dir = configuration_directory();
364 my $filename = "$dir/$ticket_cache_filename";
365
366 my $code = sub {
367 make_path($dir);
368 my $data = {};
369 if (-f $filename) {
370 my $raw = PVE::APIClient::Tools::file_get_contents($filename);
371 eval { $data = from_json($raw); };
372 # ignore errors
373 }
374 $data->{$remote} = $ticket;
375
376 PVE::APIClient::Tools::file_set_contents($filename, to_json($data), 0600);
377 };
378
379 PVE::APIClient::Tools::lock_file($filename, undef, $code);
380 die $@ if $@;
381}
382
5101e472
DM
383sub extract_even_elements {
384 my ($list) = @_;
385
386 my $ind = 0;
387 return [ grep { ($ind++ % 2) == 0 } @$list ];
388}
389
390sub print_ordered_result {
59d3653b 391 my ($property_list, $data, $result_schema, $options) = @_;
5101e472 392
5101e472
DM
393 my $param_order = extract_even_elements($property_list);
394
59d3653b 395 PVE::APIClient::CLIFormatter::print_api_result($data, $result_schema, $param_order, $options);
5101e472 396}
df89fcb9 397
29505e2c 3981;