]> git.proxmox.com Git - pve-common.git/blob - src/PVE/PBSClient.pm
PBSClient: add file_restore_extract function
[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 backup => 1,
134 restore => 1,
135 'upload-log' => 1,
136 };
137
138 my sub do_raw_client_cmd {
139 my ($self, $client_cmd, $param, %opts) = @_;
140
141 my $use_crypto = $USE_CRYPT_PARAMS->{$client_cmd};
142
143 my $client_exe = (delete $opts{binary}) || 'proxmox-backup-client';
144 $client_exe = "/usr/bin/$client_exe";
145 die "executable not found '$client_exe'! proxmox-backup-client or proxmox-backup-file-restore not installed?\n"
146 if ! -x $client_exe;
147
148 my $scfg = $self->{scfg};
149 my $repo = get_repository($scfg);
150
151 my $userns_cmd = delete $opts{userns_cmd};
152
153 my $cmd = [];
154
155 push @$cmd, @$userns_cmd if defined($userns_cmd);
156
157 push @$cmd, $client_exe, $client_cmd;
158
159 # This must live in the top scope to not get closed before the `run_command`
160 my $keyfd;
161 if ($use_crypto) {
162 if (defined($keyfd = open_encryption_key($self))) {
163 my $flags = fcntl($keyfd, F_GETFD, 0)
164 // die "failed to get file descriptor flags: $!\n";
165 fcntl($keyfd, F_SETFD, $flags & ~FD_CLOEXEC)
166 or die "failed to remove FD_CLOEXEC from encryption key file descriptor\n";
167 push @$cmd, '--crypt-mode=encrypt', '--keyfd='.fileno($keyfd);
168 } else {
169 push @$cmd, '--crypt-mode=none';
170 }
171 }
172
173 push @$cmd, @$param if defined($param);
174
175 push @$cmd, "--repository", $repo;
176
177 local $ENV{PBS_PASSWORD} = $self->get_password();
178
179 local $ENV{PBS_FINGERPRINT} = $scfg->{fingerprint};
180
181 # no ascii-art on task logs
182 local $ENV{PROXMOX_OUTPUT_NO_BORDER} = 1;
183 local $ENV{PROXMOX_OUTPUT_NO_HEADER} = 1;
184
185 if (my $logfunc = $opts{logfunc}) {
186 $logfunc->("run: " . join(' ', @$cmd));
187 }
188
189 run_command($cmd, %opts);
190 }
191
192 my sub run_raw_client_cmd {
193 my ($self, $client_cmd, $param, %opts) = @_;
194 return do_raw_client_cmd($self, $client_cmd, $param, %opts);
195 }
196
197 my sub run_client_cmd {
198 my ($self, $client_cmd, $param, $no_output, $binary) = @_;
199
200 my $json_str = '';
201 my $outfunc = sub { $json_str .= "$_[0]\n" };
202
203 $binary //= 'proxmox-backup-client';
204
205 $param = [] if !defined($param);
206 $param = [ $param ] if !ref($param);
207
208 $param = [@$param, '--output-format=json'] if !$no_output;
209
210 do_raw_client_cmd(
211 $self,
212 $client_cmd,
213 $param,
214 outfunc => $outfunc,
215 errmsg => "$binary failed",
216 binary => $binary,
217 );
218
219 return undef if $no_output;
220
221 my $res = decode_json($json_str);
222
223 return $res;
224 }
225
226 sub autogen_encryption_key {
227 my ($self) = @_;
228 my $encfile = $self->encryption_key_file_name();
229 run_command(
230 ['proxmox-backup-client', 'key', 'create', '--kdf', 'none', $encfile],
231 errmsg => 'failed to create encryption key'
232 );
233 return file_get_contents($encfile);
234 };
235
236 # lists all snapshots, optionally limited to a specific group
237 sub get_snapshots {
238 my ($self, $group) = @_;
239
240 my $param = [];
241 push @$param, $group if defined($group);
242
243 return run_client_cmd($self, "snapshots", $param);
244 };
245
246 # create a new PXAR backup of a FS directory tree - doesn't cross FS boundary
247 # by default.
248 sub backup_fs_tree {
249 my ($self, $root, $id, $pxarname, $cmd_opts) = @_;
250
251 die "backup-id not provided\n" if !defined($id);
252 die "backup root dir not provided\n" if !defined($root);
253 die "archive name not provided\n" if !defined($pxarname);
254
255 my $param = [
256 "$pxarname.pxar:$root",
257 '--backup-type', 'host',
258 '--backup-id', $id,
259 ];
260
261 $cmd_opts //= {};
262
263 return run_raw_client_cmd($self, 'backup', $param, %$cmd_opts);
264 };
265
266 sub restore_pxar {
267 my ($self, $snapshot, $pxarname, $target, $cmd_opts) = @_;
268
269 die "snapshot not provided\n" if !defined($snapshot);
270 die "archive name not provided\n" if !defined($pxarname);
271 die "restore-target not provided\n" if !defined($target);
272
273 my $param = [
274 "$snapshot",
275 "$pxarname.pxar",
276 "$target",
277 "--allow-existing-dirs", 0,
278 ];
279 $cmd_opts //= {};
280
281 return run_raw_client_cmd($self, 'restore', $param, %$cmd_opts);
282 };
283
284 sub forget_snapshot {
285 my ($self, $snapshot) = @_;
286
287 die "snapshot not provided\n" if !defined($snapshot);
288
289 return run_raw_client_cmd($self, 'forget', ["$snapshot"]);
290 };
291
292 sub prune_group {
293 my ($self, $opts, $prune_opts, $group) = @_;
294
295 die "group not provided\n" if !defined($group);
296
297 # do nothing if no keep options specified for remote
298 return [] if scalar(keys %$prune_opts) == 0;
299
300 my $param = [];
301
302 push @$param, "--quiet";
303
304 if (defined($opts->{'dry-run'}) && $opts->{'dry-run'}) {
305 push @$param, "--dry-run", $opts->{'dry-run'};
306 }
307
308 foreach my $keep_opt (keys %$prune_opts) {
309 push @$param, "--$keep_opt", $prune_opts->{$keep_opt};
310 }
311 push @$param, "$group";
312
313 return run_client_cmd($self, 'prune', $param);
314 };
315
316 sub status {
317 my ($self) = @_;
318
319 my $total = 0;
320 my $free = 0;
321 my $used = 0;
322 my $active = 0;
323
324 eval {
325 my $res = run_client_cmd($self, "status");
326
327 $active = 1;
328 $total = $res->{total};
329 $used = $res->{used};
330 $free = $res->{avail};
331 };
332 if (my $err = $@) {
333 warn $err;
334 }
335
336 return ($total, $free, $used, $active);
337 };
338
339 sub file_restore_list {
340 my ($self, $snapshot, $filepath, $base64) = @_;
341 return run_client_cmd(
342 $self,
343 "list",
344 [ $snapshot, $filepath, "--base64", $base64 ? 1 : 0 ],
345 0,
346 "proxmox-file-restore",
347 );
348 }
349
350 # call sync from API, returns a fifo path for streaming data to clients,
351 # pass it to file_restore_extract to start transfering data
352 sub file_restore_extract_prepare {
353 my ($self) = @_;
354
355 my $tmpdir = tempdir();
356 mkfifo("$tmpdir/fifo", 0600)
357 or die "creating file download fifo '$tmpdir/fifo' failed: $!\n";
358
359 # allow reading data for proxy user
360 my $wwwid = getpwnam('www-data') ||
361 die "getpwnam failed";
362 chown $wwwid, -1, "$tmpdir"
363 or die "changing permission on fifo dir '$tmpdir' failed: $!\n";
364 chown $wwwid, -1, "$tmpdir/fifo"
365 or die "changing permission on fifo '$tmpdir/fifo' failed: $!\n";
366
367 return "$tmpdir/fifo";
368 }
369
370 # this blocks while data is transfered, call this from a background worker
371 sub file_restore_extract {
372 my ($self, $output_file, $snapshot, $filepath, $base64) = @_;
373
374 my $ret = eval {
375 local $SIG{ALRM} = sub { die "got timeout\n" };
376 alarm(30);
377 sysopen(my $fh, "$output_file", O_WRONLY)
378 or die "open target '$output_file' for writing failed: $!\n";
379 alarm(0);
380
381 my $fn = fileno($fh);
382 my $errfunc = sub { print $_[0], "\n"; };
383
384 return run_raw_client_cmd(
385 $self,
386 "extract",
387 [ $snapshot, $filepath, "-", "--base64", $base64 ? 1 : 0 ],
388 binary => "proxmox-file-restore",
389 errfunc => $errfunc,
390 output => ">&$fn",
391 );
392 };
393 my $err = $@;
394
395 unlink($output_file);
396 $output_file =~ s/fifo$//;
397 rmdir($output_file) if -d $output_file;
398
399 die "file restore task failed: $err" if $err;
400 return $ret;
401 }
402
403 1;