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