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