]> git.proxmox.com Git - pve-common.git/blame - src/PVE/PBSClient.pm
pbs: keep a separate $USE_CRYPT_PARAMS list per command exe
[pve-common.git] / src / PVE / PBSClient.pm
CommitLineData
0904f388 1package PVE::PBSClient;
243568ca 2# utility functions for interaction with Proxmox Backup client CLI executable
0904f388
SI
3
4use strict;
5use warnings;
243568ca 6
0904f388 7use Fcntl qw(F_GETFD F_SETFD FD_CLOEXEC);
77e402f0 8use File::Temp qw(tempdir);
0904f388
SI
9use IO::File;
10use JSON;
77e402f0 11use POSIX qw(mkfifo strftime ENOENT);
0904f388 12
0904f388 13use PVE::JSONSchema qw(get_standard_option);
5640c3db
DC
14use 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# }
24sub 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}
0904f388
SI
43
44sub 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
243568ca
TL
52 my $self = bless {
53 scfg => $scfg,
54 storeid => $storeid,
55 secret_dir => $secret_dir
56 }, $class;
57 return $self;
0904f388
SI
58}
59
60my sub password_file_name {
61 my ($self) = @_;
62
63 return "$self->{secret_dir}/$self->{storeid}.pw";
64}
65
66sub set_password {
67 my ($self, $password) = @_;
68
69a3a585 69 my $pwfile = password_file_name($self);
0904f388
SI
70 mkdir $self->{secret_dir};
71
72 PVE::Tools::file_set_contents($pwfile, "$password\n", 0600);
73};
74
75sub delete_password {
76 my ($self) = @_;
77
69a3a585 78 my $pwfile = password_file_name($self);
0904f388 79
69a3a585 80 unlink $pwfile or die "deleting password file failed - $!\n";
0904f388
SI
81};
82
83sub get_password {
84 my ($self) = @_;
85
69a3a585 86 my $pwfile = password_file_name($self);
0904f388
SI
87
88 return PVE::Tools::file_read_firstline($pwfile);
89}
90
91sub encryption_key_file_name {
92 my ($self) = @_;
93
94 return "$self->{secret_dir}/$self->{storeid}.enc";
95};
96
97sub set_encryption_key {
98 my ($self, $key) = @_;
99
243568ca 100 my $encfile = $self->encryption_key_file_name();
0904f388
SI
101 mkdir $self->{secret_dir};
102
103 PVE::Tools::file_set_contents($encfile, "$key\n", 0600);
104};
105
106sub delete_encryption_key {
107 my ($self) = @_;
108
243568ca 109 my $encfile = $self->encryption_key_file_name();
0904f388
SI
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.
118my sub open_encryption_key {
119 my ($self) = @_;
120
243568ca 121 my $encryption_key_file = $self->encryption_key_file_name();
0904f388
SI
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
132my $USE_CRYPT_PARAMS = {
6b00e70c
TL
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 },
0904f388
SI
142};
143
144my sub do_raw_client_cmd {
145 my ($self, $client_cmd, $param, %opts) = @_;
146
76ddb876 147 my $client_bin = (delete $opts{binary}) || 'proxmox-backup-client';
6b00e70c 148 my $use_crypto = $USE_CRYPT_PARAMS->{$client_bin}->{$client_cmd} // 0;
0904f388 149
76ddb876
TL
150 my $client_exe = "/usr/bin/$client_bin";
151 die "executable not found '$client_exe'! $client_bin not installed?\n" if ! -x $client_exe;
0904f388
SI
152
153 my $scfg = $self->{scfg};
5640c3db 154 my $repo = get_repository($scfg);
0904f388
SI
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) {
69a3a585 167 if (defined($keyfd = open_encryption_key($self))) {
0904f388
SI
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
5640c3db 180 push @$cmd, "--repository", $repo;
0904f388 181
243568ca 182 local $ENV{PBS_PASSWORD} = $self->get_password();
0904f388
SI
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
197my sub run_raw_client_cmd {
198 my ($self, $client_cmd, $param, %opts) = @_;
69a3a585 199 return do_raw_client_cmd($self, $client_cmd, $param, %opts);
0904f388
SI
200}
201
202my sub run_client_cmd {
b15abdfe 203 my ($self, $client_cmd, $param, $no_output, $binary) = @_;
0904f388
SI
204
205 my $json_str = '';
206 my $outfunc = sub { $json_str .= "$_[0]\n" };
207
b15abdfe
SR
208 $binary //= 'proxmox-backup-client';
209
0904f388
SI
210 $param = [] if !defined($param);
211 $param = [ $param ] if !ref($param);
212
213 $param = [@$param, '--output-format=json'] if !$no_output;
214
69a3a585 215 do_raw_client_cmd(
b15abdfe
SR
216 $self,
217 $client_cmd,
218 $param,
219 outfunc => $outfunc,
220 errmsg => "$binary failed",
221 binary => $binary,
243568ca 222 );
0904f388
SI
223
224 return undef if $no_output;
225
226 my $res = decode_json($json_str);
227
228 return $res;
229}
230
231sub autogen_encryption_key {
232 my ($self) = @_;
243568ca 233 my $encfile = $self->encryption_key_file_name();
0cc6c7e0
TL
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);
0904f388
SI
239};
240
2113c7e8 241# lists all snapshots, optionally limited to a specific group
0904f388 242sub get_snapshots {
2113c7e8 243 my ($self, $group) = @_;
0904f388
SI
244
245 my $param = [];
2113c7e8 246 push @$param, $group if defined($group);
0904f388 247
69a3a585 248 return run_client_cmd($self, "snapshots", $param);
0904f388
SI
249};
250
6674eb1e
TL
251# create a new PXAR backup of a FS directory tree - doesn't cross FS boundary
252# by default.
253sub backup_fs_tree {
254 my ($self, $root, $id, $pxarname, $cmd_opts) = @_;
0904f388 255
0904f388 256 die "backup-id not provided\n" if !defined($id);
6674eb1e 257 die "backup root dir not provided\n" if !defined($root);
0904f388 258 die "archive name not provided\n" if !defined($pxarname);
0904f388 259
ad6b3237
TL
260 my $param = [
261 "$pxarname.pxar:$root",
6674eb1e 262 '--backup-type', 'host',
ad6b3237
TL
263 '--backup-id', $id,
264 ];
0904f388 265
6674eb1e
TL
266 $cmd_opts //= {};
267
268 return run_raw_client_cmd($self, 'backup', $param, %$cmd_opts);
0904f388
SI
269};
270
271sub restore_pxar {
8b88b2f6 272 my ($self, $snapshot, $pxarname, $target, $cmd_opts) = @_;
0904f388 273
0904f388 274 die "snapshot not provided\n" if !defined($snapshot);
0904f388 275 die "archive name not provided\n" if !defined($pxarname);
0904f388 276 die "restore-target not provided\n" if !defined($target);
0904f388 277
ad6b3237
TL
278 my $param = [
279 "$snapshot",
280 "$pxarname.pxar",
281 "$target",
282 "--allow-existing-dirs", 0,
283 ];
8b88b2f6 284 $cmd_opts //= {};
0904f388 285
69a3a585 286 return run_raw_client_cmd($self, 'restore', $param, %$cmd_opts);
0904f388
SI
287};
288
289sub forget_snapshot {
290 my ($self, $snapshot) = @_;
291
292 die "snapshot not provided\n" if !defined($snapshot);
293
69a3a585 294 return run_raw_client_cmd($self, 'forget', ["$snapshot"]);
0904f388
SI
295};
296
297sub 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
69a3a585 318 return run_client_cmd($self, 'prune', $param);
0904f388
SI
319};
320
321sub status {
322 my ($self) = @_;
323
324 my $total = 0;
325 my $free = 0;
326 my $used = 0;
327 my $active = 0;
328
329 eval {
69a3a585 330 my $res = run_client_cmd($self, "status");
0904f388
SI
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
67252649
SR
344sub 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
77e402f0
SR
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
357sub 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
376sub 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
0904f388 4081;