]> git.proxmox.com Git - pve-common.git/blob - src/PVE/PBSClient.pm
bump version to 8.1.2
[pve-common.git] / src / PVE / PBSClient.pm
1 package PVE::PBSClient;
2 # utility functions for interaction with Proxmox Backup client CLI executable
3
4 use strict;
5 use warnings;
6
7 use Fcntl qw(F_GETFD F_SETFD FD_CLOEXEC);
8 use File::Temp qw(tempdir);
9 use IO::File;
10 use JSON;
11 use POSIX qw(mkfifo strftime ENOENT);
12
13 use PVE::JSONSchema qw(get_standard_option);
14 use PVE::Tools qw(run_command file_set_contents file_get_contents file_read_firstline $IPV6RE);
15
16 # returns a repository string suitable for proxmox-backup-client, pbs-restore, etc.
17 # $scfg must have the following structure:
18 # {
19 # datastore
20 # server
21 # port (optional defaults to 8007)
22 # username (optional defaults to 'root@pam')
23 # }
24 sub get_repository {
25 my ($scfg) = @_;
26
27 my $server = $scfg->{server};
28 die "no server given\n" if !defined($server);
29
30 $server = "[$server]" if $server =~ /^$IPV6RE$/;
31
32 if (my $port = $scfg->{port}) {
33 $server .= ":$port" if $port != 8007;
34 }
35
36 my $datastore = $scfg->{datastore};
37 die "no datastore given\n" if !defined($datastore);
38
39 my $username = $scfg->{username} // 'root@pam';
40
41 return "$username\@$server:$datastore";
42 }
43
44 sub new {
45 my ($class, $scfg, $storeid, $sdir) = @_;
46
47 die "no section config provided\n" if ref($scfg) eq '';
48 die "undefined store id\n" if !defined($storeid);
49
50 my $secret_dir = $sdir // '/etc/pve/priv/storage';
51
52 my $self = bless {
53 scfg => $scfg,
54 storeid => $storeid,
55 secret_dir => $secret_dir
56 }, $class;
57 return $self;
58 }
59
60 my sub password_file_name {
61 my ($self) = @_;
62
63 return "$self->{secret_dir}/$self->{storeid}.pw";
64 }
65
66 sub set_password {
67 my ($self, $password) = @_;
68
69 my $pwfile = password_file_name($self);
70 mkdir $self->{secret_dir};
71
72 PVE::Tools::file_set_contents($pwfile, "$password\n", 0600);
73 };
74
75 sub delete_password {
76 my ($self) = @_;
77
78 my $pwfile = password_file_name($self);
79
80 unlink $pwfile or die "deleting password file failed - $!\n";
81 };
82
83 sub get_password {
84 my ($self) = @_;
85
86 my $pwfile = password_file_name($self);
87
88 return PVE::Tools::file_read_firstline($pwfile);
89 }
90
91 sub encryption_key_file_name {
92 my ($self) = @_;
93
94 return "$self->{secret_dir}/$self->{storeid}.enc";
95 };
96
97 sub set_encryption_key {
98 my ($self, $key) = @_;
99
100 my $encfile = $self->encryption_key_file_name();
101 mkdir $self->{secret_dir};
102
103 PVE::Tools::file_set_contents($encfile, "$key\n", 0600);
104 };
105
106 sub delete_encryption_key {
107 my ($self) = @_;
108
109 my $encfile = $self->encryption_key_file_name();
110
111 if (!unlink $encfile) {
112 return if $! == ENOENT;
113 die "failed to delete encryption key! $!\n";
114 }
115 };
116
117 # Returns a file handle if there is an encryption key, or `undef` if there is not. Dies on error.
118 my sub open_encryption_key {
119 my ($self) = @_;
120
121 my $encryption_key_file = $self->encryption_key_file_name();
122
123 my $keyfd;
124 if (!open($keyfd, '<', $encryption_key_file)) {
125 return undef if $! == ENOENT;
126 die "failed to open encryption key: $encryption_key_file: $!\n";
127 }
128
129 return $keyfd;
130 }
131
132 my $USE_CRYPT_PARAMS = {
133 'proxmox-backup-client' => {
134 backup => 1,
135 restore => 1,
136 'upload-log' => 1,
137 },
138 'proxmox-file-restore' => {
139 list => 1,
140 extract => 1,
141 },
142 };
143
144 my sub do_raw_client_cmd {
145 my ($self, $client_cmd, $param, %opts) = @_;
146
147 my $client_bin = (delete $opts{binary}) || 'proxmox-backup-client';
148 my $use_crypto = $USE_CRYPT_PARAMS->{$client_bin}->{$client_cmd} // 0;
149
150 my $client_exe = "/usr/bin/$client_bin";
151 die "executable not found '$client_exe'! $client_bin not installed?\n" if ! -x $client_exe;
152
153 my $scfg = $self->{scfg};
154 my $repo = get_repository($scfg);
155
156 my $userns_cmd = delete $opts{userns_cmd};
157
158 my $cmd = [];
159
160 push @$cmd, @$userns_cmd if defined($userns_cmd);
161
162 push @$cmd, $client_exe, $client_cmd;
163
164 # This must live in the top scope to not get closed before the `run_command`
165 my $keyfd;
166 if ($use_crypto) {
167 if (defined($keyfd = open_encryption_key($self))) {
168 my $flags = fcntl($keyfd, F_GETFD, 0)
169 // die "failed to get file descriptor flags: $!\n";
170 fcntl($keyfd, F_SETFD, $flags & ~FD_CLOEXEC)
171 or die "failed to remove FD_CLOEXEC from encryption key file descriptor\n";
172 push @$cmd, '--crypt-mode=encrypt', '--keyfd='.fileno($keyfd);
173 } else {
174 push @$cmd, '--crypt-mode=none';
175 }
176 }
177
178 push @$cmd, @$param if defined($param);
179
180 push @$cmd, "--repository", $repo;
181
182 local $ENV{PBS_PASSWORD} = $self->get_password();
183
184 local $ENV{PBS_FINGERPRINT} = $scfg->{fingerprint};
185
186 # no ascii-art on task logs
187 local $ENV{PROXMOX_OUTPUT_NO_BORDER} = 1;
188 local $ENV{PROXMOX_OUTPUT_NO_HEADER} = 1;
189
190 if (my $logfunc = $opts{logfunc}) {
191 $logfunc->("run: " . join(' ', @$cmd));
192 }
193
194 run_command($cmd, %opts);
195 }
196
197 my sub run_raw_client_cmd {
198 my ($self, $client_cmd, $param, %opts) = @_;
199 return do_raw_client_cmd($self, $client_cmd, $param, %opts);
200 }
201
202 my sub run_client_cmd {
203 my ($self, $client_cmd, $param, $no_output, $binary) = @_;
204
205 my $json_str = '';
206 my $outfunc = sub { $json_str .= "$_[0]\n" };
207
208 $binary //= 'proxmox-backup-client';
209
210 $param = [] if !defined($param);
211 $param = [ $param ] if !ref($param);
212
213 $param = [@$param, '--output-format=json'] if !$no_output;
214
215 do_raw_client_cmd(
216 $self,
217 $client_cmd,
218 $param,
219 outfunc => $outfunc,
220 errmsg => "$binary failed",
221 binary => $binary,
222 );
223
224 return undef if $no_output;
225
226 my $res = decode_json($json_str);
227
228 return $res;
229 }
230
231 sub autogen_encryption_key {
232 my ($self) = @_;
233 my $encfile = $self->encryption_key_file_name();
234 run_command(
235 ['proxmox-backup-client', 'key', 'create', '--kdf', 'none', $encfile],
236 errmsg => 'failed to create encryption key'
237 );
238 return file_get_contents($encfile);
239 };
240
241 # lists all snapshots, optionally limited to a specific group
242 sub get_snapshots {
243 my ($self, $group) = @_;
244
245 my $param = [];
246 push @$param, $group if defined($group);
247
248 return run_client_cmd($self, "snapshots", $param);
249 };
250
251 # create a new PXAR backup of a FS directory tree - doesn't cross FS boundary
252 # by default.
253 sub backup_fs_tree {
254 my ($self, $root, $id, $pxarname, $cmd_opts) = @_;
255
256 die "backup-id not provided\n" if !defined($id);
257 die "backup root dir not provided\n" if !defined($root);
258 die "archive name not provided\n" if !defined($pxarname);
259
260 my $param = [
261 "$pxarname.pxar:$root",
262 '--backup-type', 'host',
263 '--backup-id', $id,
264 ];
265
266 $cmd_opts //= {};
267
268 return run_raw_client_cmd($self, 'backup', $param, %$cmd_opts);
269 };
270
271 sub restore_pxar {
272 my ($self, $snapshot, $pxarname, $target, $cmd_opts) = @_;
273
274 die "snapshot not provided\n" if !defined($snapshot);
275 die "archive name not provided\n" if !defined($pxarname);
276 die "restore-target not provided\n" if !defined($target);
277
278 my $param = [
279 "$snapshot",
280 "$pxarname.pxar",
281 "$target",
282 "--allow-existing-dirs", 0,
283 ];
284 $cmd_opts //= {};
285
286 return run_raw_client_cmd($self, 'restore', $param, %$cmd_opts);
287 };
288
289 sub forget_snapshot {
290 my ($self, $snapshot) = @_;
291
292 die "snapshot not provided\n" if !defined($snapshot);
293
294 return run_raw_client_cmd($self, 'forget', ["$snapshot"]);
295 };
296
297 sub prune_group {
298 my ($self, $opts, $prune_opts, $group) = @_;
299
300 die "group not provided\n" if !defined($group);
301
302 # do nothing if no keep options specified for remote
303 return [] if scalar(keys %$prune_opts) == 0;
304
305 my $param = [];
306
307 push @$param, "--quiet";
308
309 if (defined($opts->{'dry-run'}) && $opts->{'dry-run'}) {
310 push @$param, "--dry-run", $opts->{'dry-run'};
311 }
312
313 foreach my $keep_opt (keys %$prune_opts) {
314 push @$param, "--$keep_opt", $prune_opts->{$keep_opt};
315 }
316 push @$param, "$group";
317
318 return run_client_cmd($self, 'prune', $param);
319 };
320
321 sub status {
322 my ($self) = @_;
323
324 my $total = 0;
325 my $free = 0;
326 my $used = 0;
327 my $active = 0;
328
329 eval {
330 my $res = run_client_cmd($self, "status");
331
332 $active = 1;
333 $total = $res->{total};
334 $used = $res->{used};
335 $free = $res->{avail};
336 };
337 if (my $err = $@) {
338 warn $err;
339 }
340
341 return ($total, $free, $used, $active);
342 };
343
344 sub file_restore_list {
345 my ($self, $snapshot, $filepath, $base64) = @_;
346 return run_client_cmd(
347 $self,
348 "list",
349 [ $snapshot, $filepath, "--base64", $base64 ? 1 : 0 ],
350 0,
351 "proxmox-file-restore",
352 );
353 }
354
355 # call sync from API, returns a fifo path for streaming data to clients,
356 # pass it to file_restore_extract to start transfering data
357 sub file_restore_extract_prepare {
358 my ($self) = @_;
359
360 my $tmpdir = tempdir();
361 mkfifo("$tmpdir/fifo", 0600)
362 or die "creating file download fifo '$tmpdir/fifo' failed: $!\n";
363
364 # allow reading data for proxy user
365 my $wwwid = getpwnam('www-data') ||
366 die "getpwnam failed";
367 chown $wwwid, -1, "$tmpdir"
368 or die "changing permission on fifo dir '$tmpdir' failed: $!\n";
369 chown $wwwid, -1, "$tmpdir/fifo"
370 or die "changing permission on fifo '$tmpdir/fifo' failed: $!\n";
371
372 return "$tmpdir/fifo";
373 }
374
375 # this blocks while data is transfered, call this from a background worker
376 sub file_restore_extract {
377 my ($self, $output_file, $snapshot, $filepath, $base64) = @_;
378
379 my $ret = eval {
380 local $SIG{ALRM} = sub { die "got timeout\n" };
381 alarm(30);
382 sysopen(my $fh, "$output_file", O_WRONLY)
383 or die "open target '$output_file' for writing failed: $!\n";
384 alarm(0);
385
386 my $fn = fileno($fh);
387 my $errfunc = sub { print $_[0], "\n"; };
388
389 return run_raw_client_cmd(
390 $self,
391 "extract",
392 [ $snapshot, $filepath, "-", "--base64", $base64 ? 1 : 0 ],
393 binary => "proxmox-file-restore",
394 errfunc => $errfunc,
395 output => ">&$fn",
396 );
397 };
398 my $err = $@;
399
400 unlink($output_file);
401 $output_file =~ s/fifo$//;
402 rmdir($output_file) if -d $output_file;
403
404 die "file restore task failed: $err" if $err;
405 return $ret;
406 }
407
408 1;