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