]> git.proxmox.com Git - pve-storage.git/blob - PVE/Storage/PBSPlugin.pm
pbs: backup-ns parameter was renamed to ns
[pve-storage.git] / PVE / Storage / PBSPlugin.pm
1 package PVE::Storage::PBSPlugin;
2
3 # Plugin to access Proxmox Backup Server
4
5 use strict;
6 use warnings;
7
8 use Fcntl qw(F_GETFD F_SETFD FD_CLOEXEC);
9 use IO::File;
10 use JSON;
11 use MIME::Base64 qw(decode_base64);
12 use POSIX qw(mktime strftime ENOENT);
13 use POSIX::strptime;
14
15 use PVE::APIClient::LWP;
16 use PVE::JSONSchema qw(get_standard_option);
17 use PVE::Network;
18 use PVE::PBSClient;
19 use PVE::Storage::Plugin;
20 use PVE::Tools qw(run_command file_read_firstline trim dir_glob_regex dir_glob_foreach $IPV6RE);
21
22 use base qw(PVE::Storage::Plugin);
23
24 # Configuration
25
26 sub type {
27 return 'pbs';
28 }
29
30 sub plugindata {
31 return {
32 content => [ {backup => 1, none => 1}, { backup => 1 }],
33 };
34 }
35
36 sub properties {
37 return {
38 datastore => {
39 description => "Proxmox Backup Server datastore name.",
40 type => 'string',
41 },
42 # openssl s_client -connect <host>:8007 2>&1 |openssl x509 -fingerprint -sha256
43 fingerprint => get_standard_option('fingerprint-sha256'),
44 'encryption-key' => {
45 description => "Encryption key. Use 'autogen' to generate one automatically without passphrase.",
46 type => 'string',
47 },
48 'master-pubkey' => {
49 description => "Base64-encoded, PEM-formatted public RSA key. Used to encrypt a copy of the encryption-key which will be added to each encrypted backup.",
50 type => 'string',
51 },
52 port => {
53 description => "For non default port.",
54 type => 'integer',
55 minimum => 1,
56 maximum => 65535,
57 default => 8007,
58 },
59 };
60 }
61
62 sub options {
63 return {
64 server => { fixed => 1 },
65 datastore => { fixed => 1 },
66 namespace => { optional => 1 },
67 port => { optional => 1 },
68 nodes => { optional => 1},
69 disable => { optional => 1},
70 content => { optional => 1},
71 username => { optional => 1 },
72 password => { optional => 1 },
73 'encryption-key' => { optional => 1 },
74 'master-pubkey' => { optional => 1 },
75 maxfiles => { optional => 1 },
76 'prune-backups' => { optional => 1 },
77 'max-protected-backups' => { optional => 1 },
78 fingerprint => { optional => 1 },
79 };
80 }
81
82 # Helpers
83
84 sub pbs_password_file_name {
85 my ($scfg, $storeid) = @_;
86
87 return "/etc/pve/priv/storage/${storeid}.pw";
88 }
89
90 sub pbs_set_password {
91 my ($scfg, $storeid, $password) = @_;
92
93 my $pwfile = pbs_password_file_name($scfg, $storeid);
94 mkdir "/etc/pve/priv/storage";
95
96 PVE::Tools::file_set_contents($pwfile, "$password\n");
97 }
98
99 sub pbs_delete_password {
100 my ($scfg, $storeid) = @_;
101
102 my $pwfile = pbs_password_file_name($scfg, $storeid);
103
104 unlink $pwfile;
105 }
106
107 sub pbs_get_password {
108 my ($scfg, $storeid) = @_;
109
110 my $pwfile = pbs_password_file_name($scfg, $storeid);
111
112 return PVE::Tools::file_read_firstline($pwfile);
113 }
114
115 sub pbs_encryption_key_file_name {
116 my ($scfg, $storeid) = @_;
117
118 return "/etc/pve/priv/storage/${storeid}.enc";
119 }
120
121 sub pbs_set_encryption_key {
122 my ($scfg, $storeid, $key) = @_;
123
124 my $pwfile = pbs_encryption_key_file_name($scfg, $storeid);
125 mkdir "/etc/pve/priv/storage";
126
127 PVE::Tools::file_set_contents($pwfile, "$key\n");
128 }
129
130 sub pbs_delete_encryption_key {
131 my ($scfg, $storeid) = @_;
132
133 my $pwfile = pbs_encryption_key_file_name($scfg, $storeid);
134
135 if (!unlink $pwfile) {
136 return if $! == ENOENT;
137 die "failed to delete encryption key! $!\n";
138 }
139 delete $scfg->{'encryption-key'};
140 }
141
142 sub pbs_get_encryption_key {
143 my ($scfg, $storeid) = @_;
144
145 my $pwfile = pbs_encryption_key_file_name($scfg, $storeid);
146
147 return PVE::Tools::file_get_contents($pwfile);
148 }
149
150 # Returns a file handle if there is an encryption key, or `undef` if there is not. Dies on error.
151 sub pbs_open_encryption_key {
152 my ($scfg, $storeid) = @_;
153
154 my $encryption_key_file = pbs_encryption_key_file_name($scfg, $storeid);
155
156 my $keyfd;
157 if (!open($keyfd, '<', $encryption_key_file)) {
158 return undef if $! == ENOENT;
159 die "failed to open encryption key: $encryption_key_file: $!\n";
160 }
161
162 return $keyfd;
163 }
164
165 sub pbs_master_pubkey_file_name {
166 my ($scfg, $storeid) = @_;
167
168 return "/etc/pve/priv/storage/${storeid}.master.pem";
169 }
170
171 sub pbs_set_master_pubkey {
172 my ($scfg, $storeid, $key) = @_;
173
174 my $pwfile = pbs_master_pubkey_file_name($scfg, $storeid);
175 mkdir "/etc/pve/priv/storage";
176
177 PVE::Tools::file_set_contents($pwfile, "$key\n");
178 }
179
180 sub pbs_delete_master_pubkey {
181 my ($scfg, $storeid) = @_;
182
183 my $pwfile = pbs_master_pubkey_file_name($scfg, $storeid);
184
185 if (!unlink $pwfile) {
186 return if $! == ENOENT;
187 die "failed to delete master public key! $!\n";
188 }
189 delete $scfg->{'master-pubkey'};
190 }
191
192 sub pbs_get_master_pubkey {
193 my ($scfg, $storeid) = @_;
194
195 my $pwfile = pbs_master_pubkey_file_name($scfg, $storeid);
196
197 return PVE::Tools::file_get_contents($pwfile);
198 }
199
200 # Returns a file handle if there is a master key, or `undef` if there is not. Dies on error.
201 sub pbs_open_master_pubkey {
202 my ($scfg, $storeid) = @_;
203
204 my $master_pubkey_file = pbs_master_pubkey_file_name($scfg, $storeid);
205
206 my $keyfd;
207 if (!open($keyfd, '<', $master_pubkey_file)) {
208 return undef if $! == ENOENT;
209 die "failed to open master public key: $master_pubkey_file: $!\n";
210 }
211
212 return $keyfd;
213 }
214
215 sub print_volid {
216 my ($storeid, $btype, $bid, $btime) = @_;
217
218 my $time_str = strftime("%FT%TZ", gmtime($btime));
219 my $volname = "backup/${btype}/${bid}/${time_str}";
220
221 return "${storeid}:${volname}";
222 }
223
224 my sub ns : prototype($$) {
225 my ($scfg, $name) = @_;
226 my $ns = $scfg->{namespace};
227 return defined($ns) ? ($name, $ns) : ();
228 }
229
230 # essentially the inverse of print_volid
231 my sub api_param_from_volname : prototype($$$) {
232 my ($class, $scfg, $volname) = @_;
233
234 my $name = ($class->parse_volname($volname))[1];
235
236 my ($btype, $bid, $timestr) = split('/', $name);
237
238 my @tm = (POSIX::strptime($timestr, "%FT%TZ"));
239 # expect sec, min, hour, mday, mon, year
240 die "error parsing time from '$volname'" if grep { !defined($_) } @tm[0..5];
241
242 my $btime;
243 {
244 local $ENV{TZ} = 'UTC'; # $timestr is UTC
245
246 # Fill in isdst to avoid undef warning. No daylight saving time for UTC.
247 $tm[8] //= 0;
248
249 my $since_epoch = mktime(@tm) or die "error converting time from '$volname'\n";
250 $btime = int($since_epoch);
251 }
252
253 return {
254 (ns($scfg, 'ns')),
255 'backup-type' => $btype,
256 'backup-id' => $bid,
257 'backup-time' => $btime,
258 };
259 }
260
261 my $USE_CRYPT_PARAMS = {
262 backup => 1,
263 restore => 1,
264 'upload-log' => 1,
265 };
266
267 my $USE_MASTER_KEY = {
268 backup => 1,
269 };
270
271 my sub do_raw_client_cmd {
272 my ($scfg, $storeid, $client_cmd, $param, %opts) = @_;
273
274 my $use_crypto = $USE_CRYPT_PARAMS->{$client_cmd};
275 my $use_master = $USE_MASTER_KEY->{$client_cmd};
276
277 my $client_exe = '/usr/bin/proxmox-backup-client';
278 die "executable not found '$client_exe'! Proxmox backup client not installed?\n"
279 if ! -x $client_exe;
280
281 my $repo = PVE::PBSClient::get_repository($scfg);
282
283 my $userns_cmd = delete $opts{userns_cmd};
284
285 my $cmd = [];
286
287 push @$cmd, @$userns_cmd if defined($userns_cmd);
288
289 push @$cmd, $client_exe, $client_cmd;
290
291 # This must live in the top scope to not get closed before the `run_command`
292 my ($keyfd, $master_fd);
293 if ($use_crypto) {
294 if (defined($keyfd = pbs_open_encryption_key($scfg, $storeid))) {
295 my $flags = fcntl($keyfd, F_GETFD, 0)
296 // die "failed to get file descriptor flags: $!\n";
297 fcntl($keyfd, F_SETFD, $flags & ~FD_CLOEXEC)
298 or die "failed to remove FD_CLOEXEC from encryption key file descriptor\n";
299 push @$cmd, '--crypt-mode=encrypt', '--keyfd='.fileno($keyfd);
300 if ($use_master && defined($master_fd = pbs_open_master_pubkey($scfg, $storeid))) {
301 my $flags = fcntl($master_fd, F_GETFD, 0)
302 // die "failed to get file descriptor flags: $!\n";
303 fcntl($master_fd, F_SETFD, $flags & ~FD_CLOEXEC)
304 or die "failed to remove FD_CLOEXEC from master public key file descriptor\n";
305 push @$cmd, '--master-pubkey-fd='.fileno($master_fd);
306 }
307 } else {
308 push @$cmd, '--crypt-mode=none';
309 }
310 }
311
312 push @$cmd, @$param if defined($param);
313
314 push @$cmd, "--repository", $repo;
315 if ($client_cmd ne 'status' && defined(my $ns = $scfg->{namespace})) {
316 push @$cmd, '--ns', $ns;
317 }
318
319 local $ENV{PBS_PASSWORD} = pbs_get_password($scfg, $storeid);
320
321 local $ENV{PBS_FINGERPRINT} = $scfg->{fingerprint};
322
323 # no ascii-art on task logs
324 local $ENV{PROXMOX_OUTPUT_NO_BORDER} = 1;
325 local $ENV{PROXMOX_OUTPUT_NO_HEADER} = 1;
326
327 if (my $logfunc = $opts{logfunc}) {
328 $logfunc->("run: " . join(' ', @$cmd));
329 }
330
331 run_command($cmd, %opts);
332 }
333
334 # FIXME: External perl code should NOT have access to this.
335 #
336 # There should be separate functions to
337 # - make backups
338 # - restore backups
339 # - restore files
340 # with a sane API
341 sub run_raw_client_cmd {
342 my ($scfg, $storeid, $client_cmd, $param, %opts) = @_;
343 return do_raw_client_cmd($scfg, $storeid, $client_cmd, $param, %opts);
344 }
345
346 sub run_client_cmd {
347 my ($scfg, $storeid, $client_cmd, $param, $no_output) = @_;
348
349 my $json_str = '';
350 my $outfunc = sub { $json_str .= "$_[0]\n" };
351
352 $param = [] if !defined($param);
353 $param = [ $param ] if !ref($param);
354
355 $param = [@$param, '--output-format=json'] if !$no_output;
356
357 do_raw_client_cmd($scfg, $storeid, $client_cmd, $param,
358 outfunc => $outfunc, errmsg => 'proxmox-backup-client failed');
359
360 return undef if $no_output;
361
362 my $res = decode_json($json_str);
363
364 return $res;
365 }
366
367 # Storage implementation
368
369 sub extract_vzdump_config {
370 my ($class, $scfg, $volname, $storeid) = @_;
371
372 my ($vtype, $name, $vmid, undef, undef, undef, $format) = $class->parse_volname($volname);
373
374 my $config = '';
375 my $outfunc = sub { $config .= "$_[0]\n" };
376
377 my $config_name;
378 if ($format eq 'pbs-vm') {
379 $config_name = 'qemu-server.conf';
380 } elsif ($format eq 'pbs-ct') {
381 $config_name = 'pct.conf';
382 } else {
383 die "unable to extract configuration for backup format '$format'\n";
384 }
385
386 do_raw_client_cmd($scfg, $storeid, 'restore', [ $name, $config_name, '-' ],
387 outfunc => $outfunc, errmsg => 'proxmox-backup-client failed');
388
389 return $config;
390 }
391
392 sub prune_backups {
393 my ($class, $scfg, $storeid, $keep, $vmid, $type, $dryrun, $logfunc) = @_;
394
395 $logfunc //= sub { print "$_[1]\n" };
396
397 my $backups = $class->list_volumes($storeid, $scfg, $vmid, ['backup']);
398
399 $type = 'vm' if defined($type) && $type eq 'qemu';
400 $type = 'ct' if defined($type) && $type eq 'lxc';
401
402 my $backup_groups = {};
403 foreach my $backup (@{$backups}) {
404 (my $backup_type = $backup->{format}) =~ s/^pbs-//;
405
406 next if defined($type) && $backup_type ne $type;
407
408 my $backup_group = "$backup_type/$backup->{vmid}";
409 $backup_groups->{$backup_group} = 1;
410 }
411
412 my @param;
413
414 my $keep_all = delete $keep->{'keep-all'};
415
416 if (!$keep_all) {
417 foreach my $opt (keys %{$keep}) {
418 next if $keep->{$opt} == 0;
419 push @param, "--$opt";
420 push @param, "$keep->{$opt}";
421 }
422 } else { # no need to pass anything to PBS
423 $keep = { 'keep-all' => 1 };
424 }
425
426 push @param, '--dry-run' if $dryrun;
427
428 my $prune_list = [];
429 my $failed;
430
431 foreach my $backup_group (keys %{$backup_groups}) {
432 $logfunc->('info', "running 'proxmox-backup-client prune' for '$backup_group'")
433 if !$dryrun;
434 eval {
435 my $res = run_client_cmd($scfg, $storeid, 'prune', [ $backup_group, @param ]);
436
437 foreach my $backup (@{$res}) {
438 die "result from proxmox-backup-client is not as expected\n"
439 if !defined($backup->{'backup-time'})
440 || !defined($backup->{'backup-type'})
441 || !defined($backup->{'backup-id'})
442 || !defined($backup->{'keep'});
443
444 my $ctime = $backup->{'backup-time'};
445 my $type = $backup->{'backup-type'};
446 my $vmid = $backup->{'backup-id'};
447 my $volid = print_volid($storeid, $type, $vmid, $ctime);
448
449 my $mark = $backup->{keep} ? 'keep' : 'remove';
450 $mark = 'protected' if $backup->{protected};
451
452 push @{$prune_list}, {
453 ctime => $ctime,
454 mark => $mark,
455 type => $type eq 'vm' ? 'qemu' : 'lxc',
456 vmid => $vmid,
457 volid => $volid,
458 };
459 }
460 };
461 if (my $err = $@) {
462 $logfunc->('err', "prune '$backup_group': $err\n");
463 $failed = 1;
464 }
465 }
466 die "error pruning backups - check log\n" if $failed;
467
468 return $prune_list;
469 }
470
471 my $autogen_encryption_key = sub {
472 my ($scfg, $storeid) = @_;
473 my $encfile = pbs_encryption_key_file_name($scfg, $storeid);
474 if (-f $encfile) {
475 rename $encfile, "$encfile.old";
476 }
477 my $cmd = ['proxmox-backup-client', 'key', 'create', '--kdf', 'none', $encfile];
478 run_command($cmd, errmsg => 'failed to create encryption key');
479 return PVE::Tools::file_get_contents($encfile);
480 };
481
482 sub on_add_hook {
483 my ($class, $storeid, $scfg, %param) = @_;
484
485 my $res = {};
486
487 if (defined(my $password = $param{password})) {
488 pbs_set_password($scfg, $storeid, $password);
489 } else {
490 pbs_delete_password($scfg, $storeid);
491 }
492
493 if (defined(my $encryption_key = $param{'encryption-key'})) {
494 my $decoded_key;
495 if ($encryption_key eq 'autogen') {
496 $res->{'encryption-key'} = $autogen_encryption_key->($scfg, $storeid);
497 $decoded_key = decode_json($res->{'encryption-key'});
498 } else {
499 $decoded_key = eval { decode_json($encryption_key) };
500 if ($@ || !exists($decoded_key->{data})) {
501 die "Value does not seems like a valid, JSON formatted encryption key!\n";
502 }
503 pbs_set_encryption_key($scfg, $storeid, $encryption_key);
504 $res->{'encryption-key'} = $encryption_key;
505 }
506 $scfg->{'encryption-key'} = $decoded_key->{fingerprint} || 1;
507 } else {
508 pbs_delete_encryption_key($scfg, $storeid);
509 }
510
511 if (defined(my $master_key = delete $param{'master-pubkey'})) {
512 die "'master-pubkey' can only be used together with 'encryption-key'\n"
513 if !defined($scfg->{'encryption-key'});
514
515 my $decoded = decode_base64($master_key);
516 pbs_set_master_pubkey($scfg, $storeid, $decoded);
517 $scfg->{'master-pubkey'} = 1;
518 } else {
519 pbs_delete_master_pubkey($scfg, $storeid);
520 }
521
522 return $res;
523 }
524
525 sub on_update_hook {
526 my ($class, $storeid, $scfg, %param) = @_;
527
528 my $res = {};
529
530 if (exists($param{password})) {
531 if (defined($param{password})) {
532 pbs_set_password($scfg, $storeid, $param{password});
533 } else {
534 pbs_delete_password($scfg, $storeid);
535 }
536 }
537
538 if (exists($param{'encryption-key'})) {
539 if (defined(my $encryption_key = delete($param{'encryption-key'}))) {
540 my $decoded_key;
541 if ($encryption_key eq 'autogen') {
542 $res->{'encryption-key'} = $autogen_encryption_key->($scfg, $storeid);
543 $decoded_key = decode_json($res->{'encryption-key'});
544 } else {
545 $decoded_key = eval { decode_json($encryption_key) };
546 if ($@ || !exists($decoded_key->{data})) {
547 die "Value does not seems like a valid, JSON formatted encryption key!\n";
548 }
549 pbs_set_encryption_key($scfg, $storeid, $encryption_key);
550 $res->{'encryption-key'} = $encryption_key;
551 }
552 $scfg->{'encryption-key'} = $decoded_key->{fingerprint} || 1;
553 } else {
554 pbs_delete_encryption_key($scfg, $storeid);
555 delete $scfg->{'encryption-key'};
556 }
557 }
558
559 if (exists($param{'master-pubkey'})) {
560 if (defined(my $master_key = delete($param{'master-pubkey'}))) {
561 my $decoded = decode_base64($master_key);
562
563 pbs_set_master_pubkey($scfg, $storeid, $decoded);
564 $scfg->{'master-pubkey'} = 1;
565 } else {
566 pbs_delete_master_pubkey($scfg, $storeid);
567 }
568 }
569
570 return $res;
571 }
572
573 sub on_delete_hook {
574 my ($class, $storeid, $scfg) = @_;
575
576 pbs_delete_password($scfg, $storeid);
577 pbs_delete_encryption_key($scfg, $storeid);
578 pbs_delete_master_pubkey($scfg, $storeid);
579
580 return;
581 }
582
583 sub parse_volname {
584 my ($class, $volname) = @_;
585
586 if ($volname =~ m!^backup/([^\s_]+)/([^\s_]+)/([0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z)$!) {
587 my $btype = $1;
588 my $bid = $2;
589 my $btime = $3;
590 my $format = "pbs-$btype";
591
592 my $name = "$btype/$bid/$btime";
593
594 if ($bid =~ m/^\d+$/) {
595 return ('backup', $name, $bid, undef, undef, undef, $format);
596 } else {
597 return ('backup', $name, undef, undef, undef, undef, $format);
598 }
599 }
600
601 die "unable to parse PBS volume name '$volname'\n";
602 }
603
604 sub path {
605 my ($class, $scfg, $volname, $storeid, $snapname) = @_;
606
607 die "volume snapshot is not possible on pbs storage"
608 if defined($snapname);
609
610 my ($vtype, $name, $vmid) = $class->parse_volname($volname);
611
612 my $repo = PVE::PBSClient::get_repository($scfg);
613
614 # artificial url - we currently do not use that anywhere
615 my $path = "pbs://$repo/$name";
616 if (defined(my $ns = $scfg->{namespace})) {
617 $ns =~ s|/|%2f|g; # other characters to escape aren't allowed in the namespace schema
618 $path .= "?ns=$ns";
619 }
620
621 return ($path, $vmid, $vtype);
622 }
623
624 sub create_base {
625 my ($class, $storeid, $scfg, $volname) = @_;
626
627 die "can't create base images in pbs storage\n";
628 }
629
630 sub clone_image {
631 my ($class, $scfg, $storeid, $volname, $vmid, $snap) = @_;
632
633 die "can't clone images in pbs storage\n";
634 }
635
636 sub alloc_image {
637 my ($class, $storeid, $scfg, $vmid, $fmt, $name, $size) = @_;
638
639 die "can't allocate space in pbs storage\n";
640 }
641
642 sub free_image {
643 my ($class, $storeid, $scfg, $volname, $isBase) = @_;
644
645 my ($vtype, $name, $vmid) = $class->parse_volname($volname);
646
647 run_client_cmd($scfg, $storeid, "forget", [ $name ], 1);
648
649 return;
650 }
651
652
653 sub list_images {
654 my ($class, $storeid, $scfg, $vmid, $vollist, $cache) = @_;
655
656 my $res = [];
657
658 return $res;
659 }
660
661 my sub snapshot_files_encrypted {
662 my ($files) = @_;
663 return 0 if !$files;
664
665 my $any;
666 my $all = 1;
667 for my $file (@$files) {
668 my $fn = $file->{filename};
669 next if $fn eq 'client.log.blob' || $fn eq 'index.json.blob';
670
671 my $crypt = $file->{'crypt-mode'};
672
673 $all = 0 if !$crypt || $crypt ne 'encrypt';
674 $any ||= defined($crypt) && $crypt eq 'encrypt';
675 }
676 return $any && $all;
677 }
678
679 sub list_volumes {
680 my ($class, $storeid, $scfg, $vmid, $content_types) = @_;
681
682 my $res = [];
683
684 return $res if !grep { $_ eq 'backup' } @$content_types;
685
686 my $data = run_client_cmd($scfg, $storeid, "snapshots");
687
688 foreach my $item (@$data) {
689 my $btype = $item->{"backup-type"};
690 my $bid = $item->{"backup-id"};
691 my $epoch = $item->{"backup-time"};
692 my $size = $item->{size} // 1;
693
694 next if !($btype eq 'vm' || $btype eq 'ct');
695 next if $bid !~ m/^\d+$/;
696 next if defined($vmid) && $bid ne $vmid;
697
698 my $volid = print_volid($storeid, $btype, $bid, $epoch);
699
700 my $info = {
701 volid => $volid,
702 format => "pbs-$btype",
703 size => $size,
704 content => 'backup',
705 vmid => int($bid),
706 ctime => $epoch,
707 subtype => $btype eq 'vm' ? 'qemu' : 'lxc', # convert to PVE backup type
708 };
709
710 $info->{verification} = $item->{verification} if defined($item->{verification});
711 $info->{notes} = $item->{comment} if defined($item->{comment});
712 $info->{protected} = 1 if $item->{protected};
713 if (defined($item->{fingerprint})) {
714 $info->{encrypted} = $item->{fingerprint};
715 } elsif (snapshot_files_encrypted($item->{files})) {
716 $info->{encrypted} = '1';
717 }
718
719 push @$res, $info;
720 }
721
722 return $res;
723 }
724
725 sub status {
726 my ($class, $storeid, $scfg, $cache) = @_;
727
728 my $total = 0;
729 my $free = 0;
730 my $used = 0;
731 my $active = 0;
732
733 eval {
734 my $res = run_client_cmd($scfg, $storeid, "status");
735
736 $active = 1;
737 $total = $res->{total};
738 $used = $res->{used};
739 $free = $res->{avail};
740 };
741 if (my $err = $@) {
742 warn $err;
743 }
744
745 return ($total, $free, $used, $active);
746 }
747
748 # TODO: use a client with native rust/proxmox-backup bindings to profit from
749 # API schema checks and types
750 my sub pbs_api_connect {
751 my ($scfg, $password) = @_;
752
753 my $params = {};
754
755 my $user = $scfg->{username} // 'root@pam';
756
757 if (my $tokenid = PVE::AccessControl::pve_verify_tokenid($user, 1)) {
758 $params->{apitoken} = "PBSAPIToken=${tokenid}:${password}";
759 } else {
760 $params->{password} = $password;
761 $params->{username} = $user;
762 }
763
764 if (my $fp = $scfg->{fingerprint}) {
765 $params->{cached_fingerprints}->{uc($fp)} = 1;
766 }
767
768 my $conn = PVE::APIClient::LWP->new(
769 %$params,
770 host => $scfg->{server},
771 port => $scfg->{port} // 8007,
772 timeout => 7, # cope with a 401 (3s api delay) and high latency
773 cookie_name => 'PBSAuthCookie',
774 );
775
776 return $conn;
777 }
778
779 # can also be used for not (yet) added storages, pass $scfg with
780 # {
781 # server
782 # user
783 # port (optional default to 8007)
784 # fingerprint (optional for trusted certs)
785 # }
786 sub scan_datastores {
787 my ($scfg, $password) = @_;
788
789 my $conn = pbs_api_connect($scfg, $password);
790
791 my $response = eval { $conn->get('/api2/json/admin/datastore', {}) };
792 die "error fetching datastores - $@" if $@;
793
794 return $response;
795 }
796
797 sub activate_storage {
798 my ($class, $storeid, $scfg, $cache) = @_;
799
800 my $password = pbs_get_password($scfg, $storeid);
801
802 my $datastores = eval { scan_datastores($scfg, $password) };
803 die "$storeid: $@" if $@;
804
805 my $datastore = $scfg->{datastore};
806
807 for my $ds (@$datastores) {
808 if ($ds->{store} eq $datastore) {
809 return 1;
810 }
811 }
812
813 die "$storeid: Cannot find datastore '$datastore', check permissions and existence!\n";
814 }
815
816 sub deactivate_storage {
817 my ($class, $storeid, $scfg, $cache) = @_;
818 return 1;
819 }
820
821 sub activate_volume {
822 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
823
824 die "volume snapshot is not possible on pbs device" if $snapname;
825
826 return 1;
827 }
828
829 sub deactivate_volume {
830 my ($class, $storeid, $scfg, $volname, $snapname, $cache) = @_;
831
832 die "volume snapshot is not possible on pbs device" if $snapname;
833
834 return 1;
835 }
836
837 # FIXME remove on the next APIAGE reset.
838 # Deprecated, use get_volume_attribute instead.
839 sub get_volume_notes {
840 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
841
842 my (undef, $name, undef, undef, undef, undef, $format) = $class->parse_volname($volname);
843
844 my $data = run_client_cmd($scfg, $storeid, "snapshot", [ "notes", "show", $name ]);
845
846 return $data->{notes};
847 }
848
849 # FIXME remove on the next APIAGE reset.
850 # Deprecated, use update_volume_attribute instead.
851 sub update_volume_notes {
852 my ($class, $scfg, $storeid, $volname, $notes, $timeout) = @_;
853
854 my (undef, $name, undef, undef, undef, undef, $format) = $class->parse_volname($volname);
855
856 run_client_cmd($scfg, $storeid, "snapshot", [ "notes", "update", $name, $notes ], 1);
857
858 return undef;
859 }
860
861 sub get_volume_attribute {
862 my ($class, $scfg, $storeid, $volname, $attribute) = @_;
863
864 if ($attribute eq 'notes') {
865 return $class->get_volume_notes($scfg, $storeid, $volname);
866 }
867
868 if ($attribute eq 'protected') {
869 my $param = api_param_from_volname($class, $scfg, $volname);
870
871 my $password = pbs_get_password($scfg, $storeid);
872 my $conn = pbs_api_connect($scfg, $password);
873 my $datastore = $scfg->{datastore};
874
875 my $res = eval { $conn->get("/api2/json/admin/datastore/$datastore/$attribute", $param); };
876 if (my $err = $@) {
877 return if $err->{code} == 404; # not supported
878 die $err;
879 }
880 return $res;
881 }
882
883 return;
884 }
885
886 sub update_volume_attribute {
887 my ($class, $scfg, $storeid, $volname, $attribute, $value) = @_;
888
889 if ($attribute eq 'notes') {
890 return $class->update_volume_notes($scfg, $storeid, $volname, $value);
891 }
892
893 if ($attribute eq 'protected') {
894 my $param = api_param_from_volname($class, $scfg, $volname);
895 $param->{$attribute} = $value;
896
897 my $password = pbs_get_password($scfg, $storeid);
898 my $conn = pbs_api_connect($scfg, $password);
899 my $datastore = $scfg->{datastore};
900
901 eval { $conn->put("/api2/json/admin/datastore/$datastore/$attribute", $param); };
902 if (my $err = $@) {
903 die "Server is not recent enough to support feature '$attribute'\n"
904 if $err->{code} == 404;
905 die $err;
906 }
907 return;
908 }
909
910 die "attribute '$attribute' is not supported for storage type '$scfg->{type}'\n";
911 }
912
913 sub volume_size_info {
914 my ($class, $scfg, $storeid, $volname, $timeout) = @_;
915
916 my ($vtype, $name, undef, undef, undef, undef, $format) = $class->parse_volname($volname);
917
918 my $data = run_client_cmd($scfg, $storeid, "files", [ $name ]);
919
920 my $size = 0;
921 foreach my $info (@$data) {
922 if ($info->{size} && $info->{size} =~ /^(\d+)$/) { # untaints
923 $size += $1;
924 }
925 }
926
927 my $used = $size;
928
929 return wantarray ? ($size, $format, $used, undef) : $size;
930 }
931
932 sub volume_resize {
933 my ($class, $scfg, $storeid, $volname, $size, $running) = @_;
934 die "volume resize is not possible on pbs device";
935 }
936
937 sub volume_snapshot {
938 my ($class, $scfg, $storeid, $volname, $snap) = @_;
939 die "volume snapshot is not possible on pbs device";
940 }
941
942 sub volume_snapshot_rollback {
943 my ($class, $scfg, $storeid, $volname, $snap) = @_;
944 die "volume snapshot rollback is not possible on pbs device";
945 }
946
947 sub volume_snapshot_delete {
948 my ($class, $scfg, $storeid, $volname, $snap) = @_;
949 die "volume snapshot delete is not possible on pbs device";
950 }
951
952 sub volume_has_feature {
953 my ($class, $scfg, $feature, $storeid, $volname, $snapname, $running) = @_;
954
955 return undef;
956 }
957
958 1;