]> git.proxmox.com Git - pve-storage.git/blame - PVE/Storage/PBSPlugin.pm
Added a LOG_EXT constant as a counterpart to NOTES_EXT
[pve-storage.git] / PVE / Storage / PBSPlugin.pm
CommitLineData
271fe394
DM
1package PVE::Storage::PBSPlugin;
2
3# Plugin to access Proxmox Backup Server
4
5use strict;
6use warnings;
4133e6e2 7
76bb5feb 8use Fcntl qw(F_GETFD F_SETFD FD_CLOEXEC);
76bb5feb 9use IO::File;
271fe394 10use JSON;
c56f7a71 11use MIME::Base64 qw(decode_base64);
bfba9626
FE
12use POSIX qw(mktime strftime ENOENT);
13use POSIX::strptime;
271fe394 14
2f9eb6dc 15use PVE::APIClient::LWP;
271fe394 16use PVE::JSONSchema qw(get_standard_option);
4133e6e2 17use PVE::Network;
53003cb5 18use PVE::PBSClient;
4133e6e2
TL
19use PVE::Storage::Plugin;
20use PVE::Tools qw(run_command file_read_firstline trim dir_glob_regex dir_glob_foreach $IPV6RE);
271fe394
DM
21
22use base qw(PVE::Storage::Plugin);
23
24# Configuration
25
26sub type {
27 return 'pbs';
28}
29
30sub plugindata {
31 return {
32 content => [ {backup => 1, none => 1}, { backup => 1 }],
33 };
34}
35
36sub properties {
37 return {
38 datastore => {
4133e6e2 39 description => "Proxmox Backup Server datastore name.",
271fe394
DM
40 type => 'string',
41 },
42 # openssl s_client -connect <host>:8007 2>&1 |openssl x509 -fingerprint -sha256
43 fingerprint => get_standard_option('fingerprint-sha256'),
ce2e2733 44 'encryption-key' => {
1aeb322b 45 description => "Encryption key. Use 'autogen' to generate one automatically without passphrase.",
76bb5feb
WB
46 type => 'string',
47 },
c56f7a71 48 'master-pubkey' => {
5b955999 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.",
c56f7a71
FG
50 type => 'string',
51 },
4133e6e2
TL
52 port => {
53 description => "For non default port.",
54 type => 'integer',
55 minimum => 1,
56 maximum => 65535,
57 default => 8007,
2f9eb6dc 58 },
271fe394
DM
59 };
60}
61
62sub options {
63 return {
64 server => { fixed => 1 },
65 datastore => { fixed => 1 },
78eac5ba 66 namespace => { optional => 1 },
4133e6e2 67 port => { optional => 1 },
271fe394
DM
68 nodes => { optional => 1},
69 disable => { optional => 1},
70 content => { optional => 1},
71 username => { optional => 1 },
ce2e2733
TL
72 password => { optional => 1 },
73 'encryption-key' => { optional => 1 },
c56f7a71 74 'master-pubkey' => { optional => 1 },
271fe394 75 maxfiles => { optional => 1 },
3353698f 76 'prune-backups' => { optional => 1 },
8009417d 77 'max-protected-backups' => { optional => 1 },
271fe394
DM
78 fingerprint => { optional => 1 },
79 };
80}
81
82# Helpers
83
84sub pbs_password_file_name {
85 my ($scfg, $storeid) = @_;
86
462537a2 87 return "/etc/pve/priv/storage/${storeid}.pw";
271fe394
DM
88}
89
90sub pbs_set_password {
91 my ($scfg, $storeid, $password) = @_;
92
93 my $pwfile = pbs_password_file_name($scfg, $storeid);
9e34813f 94 mkdir "/etc/pve/priv/storage";
271fe394
DM
95
96 PVE::Tools::file_set_contents($pwfile, "$password\n");
97}
98
99sub pbs_delete_password {
100 my ($scfg, $storeid) = @_;
101
102 my $pwfile = pbs_password_file_name($scfg, $storeid);
103
104 unlink $pwfile;
105}
106
107sub 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
76bb5feb
WB
115sub pbs_encryption_key_file_name {
116 my ($scfg, $storeid) = @_;
117
118 return "/etc/pve/priv/storage/${storeid}.enc";
119}
120
121sub 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
130sub pbs_delete_encryption_key {
131 my ($scfg, $storeid) = @_;
132
133 my $pwfile = pbs_encryption_key_file_name($scfg, $storeid);
134
4ef17e1f
TL
135 if (!unlink $pwfile) {
136 return if $! == ENOENT;
137 die "failed to delete encryption key! $!\n";
138 }
18cf6c9f 139 delete $scfg->{'encryption-key'};
76bb5feb
WB
140}
141
142sub 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.
151sub 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
c56f7a71
FG
165sub pbs_master_pubkey_file_name {
166 my ($scfg, $storeid) = @_;
167
168 return "/etc/pve/priv/storage/${storeid}.master.pem";
169}
170
171sub 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
180sub 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
192sub 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.
201sub 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
8602fd56
FE
215sub 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}
271fe394 223
78eac5ba
WB
224my sub ns : prototype($$) {
225 my ($scfg, $name) = @_;
226 my $ns = $scfg->{namespace};
227 return defined($ns) ? ($name, $ns) : ();
228}
229
bfba9626 230# essentially the inverse of print_volid
78eac5ba
WB
231my sub api_param_from_volname : prototype($$$) {
232 my ($class, $scfg, $volname) = @_;
bfba9626
FE
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 {
4c9c5f37 254 (ns($scfg, 'ns')),
bfba9626
FE
255 'backup-type' => $btype,
256 'backup-id' => $bid,
257 'backup-time' => $btime,
258 };
259}
260
02cc5e10
WB
261my $USE_CRYPT_PARAMS = {
262 backup => 1,
263 restore => 1,
264 'upload-log' => 1,
265};
266
c56f7a71
FG
267my $USE_MASTER_KEY = {
268 backup => 1,
269};
270
76bb5feb 271my sub do_raw_client_cmd {
02cc5e10
WB
272 my ($scfg, $storeid, $client_cmd, $param, %opts) = @_;
273
274 my $use_crypto = $USE_CRYPT_PARAMS->{$client_cmd};
c56f7a71 275 my $use_master = $USE_MASTER_KEY->{$client_cmd};
271fe394 276
1574a590
TL
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
53003cb5 281 my $repo = PVE::PBSClient::get_repository($scfg);
271fe394
DM
282
283 my $userns_cmd = delete $opts{userns_cmd};
284
285 my $cmd = [];
286
287 push @$cmd, @$userns_cmd if defined($userns_cmd);
288
1574a590 289 push @$cmd, $client_exe, $client_cmd;
271fe394 290
76bb5feb 291 # This must live in the top scope to not get closed before the `run_command`
c56f7a71 292 my ($keyfd, $master_fd);
02cc5e10 293 if ($use_crypto) {
76bb5feb
WB
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);
c56f7a71
FG
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 }
76bb5feb
WB
307 } else {
308 push @$cmd, '--crypt-mode=none';
309 }
310 }
311
271fe394
DM
312 push @$cmd, @$param if defined($param);
313
53003cb5 314 push @$cmd, "--repository", $repo;
78eac5ba
WB
315 if ($client_cmd ne 'status' && defined(my $ns = $scfg->{namespace})) {
316 push @$cmd, '--ns', $ns;
317 }
271fe394
DM
318
319 local $ENV{PBS_PASSWORD} = pbs_get_password($scfg, $storeid);
320
321 local $ENV{PBS_FINGERPRINT} = $scfg->{fingerprint};
322
8b4c2a7e
DM
323 # no ascii-art on task logs
324 local $ENV{PROXMOX_OUTPUT_NO_BORDER} = 1;
325 local $ENV{PROXMOX_OUTPUT_NO_HEADER} = 1;
326
271fe394 327 if (my $logfunc = $opts{logfunc}) {
e6d1edcb 328 $logfunc->("run: " . join(' ', @$cmd));
271fe394
DM
329 }
330
331 run_command($cmd, %opts);
332}
333
76bb5feb
WB
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
02cc5e10 341sub run_raw_client_cmd {
76bb5feb 342 my ($scfg, $storeid, $client_cmd, $param, %opts) = @_;
02cc5e10 343 return do_raw_client_cmd($scfg, $storeid, $client_cmd, $param, %opts);
76bb5feb
WB
344}
345
271fe394
DM
346sub run_client_cmd {
347 my ($scfg, $storeid, $client_cmd, $param, $no_output) = @_;
348
349 my $json_str = '';
fee2ece3 350 my $outfunc = sub { $json_str .= "$_[0]\n" };
271fe394
DM
351
352 $param = [] if !defined($param);
353 $param = [ $param ] if !ref($param);
354
355 $param = [@$param, '--output-format=json'] if !$no_output;
356
02cc5e10 357 do_raw_client_cmd($scfg, $storeid, $client_cmd, $param,
76bb5feb 358 outfunc => $outfunc, errmsg => 'proxmox-backup-client failed');
271fe394
DM
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
c855ac15
DM
369sub 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 = '';
fee2ece3 375 my $outfunc = sub { $config .= "$_[0]\n" };
c855ac15
DM
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
02cc5e10 386 do_raw_client_cmd($scfg, $storeid, 'restore', [ $name, $config_name, '-' ],
76bb5feb 387 outfunc => $outfunc, errmsg => 'proxmox-backup-client failed');
c855ac15
DM
388
389 return $config;
390}
391
8f26b391
FE
392sub 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;
1b87f013
FE
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 };
8f26b391
FE
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
bfba9626
FE
449 my $mark = $backup->{keep} ? 'keep' : 'remove';
450 $mark = 'protected' if $backup->{protected};
451
8f26b391
FE
452 push @{$prune_list}, {
453 ctime => $ctime,
bfba9626 454 mark => $mark,
8f26b391
FE
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
1aeb322b
TL
471my $autogen_encryption_key = sub {
472 my ($scfg, $storeid) = @_;
473 my $encfile = pbs_encryption_key_file_name($scfg, $storeid);
478609d3
TL
474 if (-f $encfile) {
475 rename $encfile, "$encfile.old";
476 }
4558cb6e
TL
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);
1aeb322b
TL
480};
481
271fe394
DM
482sub on_add_hook {
483 my ($class, $storeid, $scfg, %param) = @_;
484
0b6b98d1
TL
485 my $res = {};
486
76bb5feb
WB
487 if (defined(my $password = $param{password})) {
488 pbs_set_password($scfg, $storeid, $password);
b494636a
DM
489 } else {
490 pbs_delete_password($scfg, $storeid);
491 }
76bb5feb 492
ce2e2733 493 if (defined(my $encryption_key = $param{'encryption-key'})) {
d2c47b38 494 my $decoded_key;
1aeb322b 495 if ($encryption_key eq 'autogen') {
0b6b98d1 496 $res->{'encryption-key'} = $autogen_encryption_key->($scfg, $storeid);
3cc2eb73 497 $decoded_key = decode_json($res->{'encryption-key'});
1aeb322b 498 } else {
d2c47b38
TL
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 }
1aeb322b 503 pbs_set_encryption_key($scfg, $storeid, $encryption_key);
0b6b98d1 504 $res->{'encryption-key'} = $encryption_key;
1aeb322b 505 }
3cc2eb73 506 $scfg->{'encryption-key'} = $decoded_key->{fingerprint} || 1;
76bb5feb
WB
507 } else {
508 pbs_delete_encryption_key($scfg, $storeid);
509 }
0b6b98d1 510
c56f7a71
FG
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
0b6b98d1 522 return $res;
b494636a
DM
523}
524
525sub on_update_hook {
526 my ($class, $storeid, $scfg, %param) = @_;
527
0b6b98d1
TL
528 my $res = {};
529
76bb5feb
WB
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 }
b494636a 537
ce2e2733
TL
538 if (exists($param{'encryption-key'})) {
539 if (defined(my $encryption_key = delete($param{'encryption-key'}))) {
d2c47b38 540 my $decoded_key;
1aeb322b 541 if ($encryption_key eq 'autogen') {
0b6b98d1 542 $res->{'encryption-key'} = $autogen_encryption_key->($scfg, $storeid);
3cc2eb73 543 $decoded_key = decode_json($res->{'encryption-key'});
1aeb322b 544 } else {
d2c47b38
TL
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 }
1aeb322b 549 pbs_set_encryption_key($scfg, $storeid, $encryption_key);
0b6b98d1 550 $res->{'encryption-key'} = $encryption_key;
1aeb322b 551 }
3cc2eb73 552 $scfg->{'encryption-key'} = $decoded_key->{fingerprint} || 1;
76bb5feb
WB
553 } else {
554 pbs_delete_encryption_key($scfg, $storeid);
c56f7a71
FG
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);
76bb5feb 567 }
271fe394 568 }
0b6b98d1
TL
569
570 return $res;
271fe394
DM
571}
572
573sub on_delete_hook {
574 my ($class, $storeid, $scfg) = @_;
575
576 pbs_delete_password($scfg, $storeid);
76bb5feb 577 pbs_delete_encryption_key($scfg, $storeid);
c56f7a71 578 pbs_delete_master_pubkey($scfg, $storeid);
f3ccd0ef
FE
579
580 return;
271fe394
DM
581}
582
583sub 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
604sub 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
53003cb5 612 my $repo = PVE::PBSClient::get_repository($scfg);
271fe394 613
ffc31266 614 # artificial url - we currently do not use that anywhere
53003cb5 615 my $path = "pbs://$repo/$name";
78eac5ba
WB
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 }
271fe394
DM
620
621 return ($path, $vmid, $vtype);
622}
623
624sub create_base {
625 my ($class, $storeid, $scfg, $volname) = @_;
626
627 die "can't create base images in pbs storage\n";
628}
629
630sub clone_image {
631 my ($class, $scfg, $storeid, $volname, $vmid, $snap) = @_;
632
633 die "can't clone images in pbs storage\n";
634}
635
636sub alloc_image {
637 my ($class, $storeid, $scfg, $vmid, $fmt, $name, $size) = @_;
638
639 die "can't allocate space in pbs storage\n";
640}
641
642sub 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);
7ae13a34
FE
648
649 return;
271fe394
DM
650}
651
652
653sub list_images {
654 my ($class, $storeid, $scfg, $vmid, $vollist, $cache) = @_;
655
656 my $res = [];
657
658 return $res;
659}
660
878fe017
TL
661my 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';
dfa374d3 674 $any ||= defined($crypt) && $crypt eq 'encrypt';
878fe017
TL
675 }
676 return $any && $all;
677}
678
271fe394
DM
679sub 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"};
545e127e 691 my $epoch = $item->{"backup-time"};
271fe394
DM
692 my $size = $item->{size} // 1;
693
694 next if !($btype eq 'vm' || $btype eq 'ct');
695 next if $bid !~ m/^\d+$/;
ddf7fdaa 696 next if defined($vmid) && $bid ne $vmid;
271fe394 697
8602fd56 698 my $volid = print_volid($storeid, $btype, $bid, $epoch);
271fe394 699
545e127e 700 my $info = {
c05b1a8c
TL
701 volid => $volid,
702 format => "pbs-$btype",
703 size => $size,
704 content => 'backup',
705 vmid => int($bid),
706 ctime => $epoch,
c66e0b8a 707 subtype => $btype eq 'vm' ? 'qemu' : 'lxc', # convert to PVE backup type
545e127e 708 };
271fe394 709
9778e5c2 710 $info->{verification} = $item->{verification} if defined($item->{verification});
6fef456c 711 $info->{notes} = $item->{comment} if defined($item->{comment});
bfba9626 712 $info->{protected} = 1 if $item->{protected};
878fe017
TL
713 if (defined($item->{fingerprint})) {
714 $info->{encrypted} = $item->{fingerprint};
715 } elsif (snapshot_files_encrypted($item->{files})) {
716 $info->{encrypted} = '1';
717 }
9778e5c2 718
271fe394
DM
719 push @$res, $info;
720 }
721
722 return $res;
723}
724
725sub 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};
f155c912
TL
739 $free = $res->{avail};
740 };
271fe394
DM
741 if (my $err = $@) {
742 warn $err;
743 }
744
745 return ($total, $free, $used, $active);
746}
747
2f9eb6dc
TL
748# TODO: use a client with native rust/proxmox-backup bindings to profit from
749# API schema checks and types
750my 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)) {
ab90c3b1 758 $params->{apitoken} = "PBSAPIToken=${tokenid}:${password}";
2f9eb6dc
TL
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
8b62ac6a
TL
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# }
786sub 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
271fe394
DM
797sub activate_storage {
798 my ($class, $storeid, $scfg, $cache) = @_;
bb0a0f96 799
2cd10f58 800 my $password = pbs_get_password($scfg, $storeid);
bb0a0f96 801
2cd10f58
TL
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
ffc31266 813 die "$storeid: Cannot find datastore '$datastore', check permissions and existence!\n";
271fe394
DM
814}
815
816sub deactivate_storage {
817 my ($class, $storeid, $scfg, $cache) = @_;
818 return 1;
819}
820
821sub 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
829sub 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
f1de8281
FE
837# FIXME remove on the next APIAGE reset.
838# Deprecated, use get_volume_attribute instead.
45e93e6d
DC
839sub 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
f1de8281
FE
849# FIXME remove on the next APIAGE reset.
850# Deprecated, use update_volume_attribute instead.
45e93e6d
DC
851sub 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
f1de8281
FE
861sub 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
bfba9626 868 if ($attribute eq 'protected') {
78eac5ba 869 my $param = api_param_from_volname($class, $scfg, $volname);
bfba9626
FE
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
f1de8281
FE
883 return;
884}
885
886sub 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
bfba9626 893 if ($attribute eq 'protected') {
78eac5ba 894 my $param = api_param_from_volname($class, $scfg, $volname);
bfba9626
FE
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
904f06a8
FE
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 }
bfba9626
FE
907 return;
908 }
909
f1de8281
FE
910 die "attribute '$attribute' is not supported for storage type '$scfg->{type}'\n";
911}
912
271fe394
DM
913sub 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) {
d4e00f2b 922 if ($info->{size} && $info->{size} =~ /^(\d+)$/) { # untaints
ac598d85
SI
923 $size += $1;
924 }
271fe394
DM
925 }
926
927 my $used = $size;
928
929 return wantarray ? ($size, $format, $used, undef) : $size;
930}
931
932sub volume_resize {
933 my ($class, $scfg, $storeid, $volname, $size, $running) = @_;
934 die "volume resize is not possible on pbs device";
935}
936
937sub volume_snapshot {
938 my ($class, $scfg, $storeid, $volname, $snap) = @_;
939 die "volume snapshot is not possible on pbs device";
940}
941
942sub volume_snapshot_rollback {
943 my ($class, $scfg, $storeid, $volname, $snap) = @_;
944 die "volume snapshot rollback is not possible on pbs device";
945}
946
947sub volume_snapshot_delete {
948 my ($class, $scfg, $storeid, $volname, $snap) = @_;
949 die "volume snapshot delete is not possible on pbs device";
950}
951
952sub volume_has_feature {
953 my ($class, $scfg, $feature, $storeid, $volname, $snapname, $running) = @_;
954
955 return undef;
956}
957
9581;