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