]> git.proxmox.com Git - pve-container.git/blob - src/PVE/VZDump/LXC.pm
VZDump lock update, drop lock_aquire/lock_release
[pve-container.git] / src / PVE / VZDump / LXC.pm
1 package PVE::VZDump::LXC;
2
3 use strict;
4 use warnings;
5 use File::Path;
6 use File::Basename;
7 use PVE::INotify;
8 use PVE::Cluster qw(cfs_read_file);
9 use PVE::Storage;
10 use PVE::VZDump;
11 use PVE::LXC;
12 use PVE::Tools;
13
14 use base qw (PVE::VZDump::Plugin);
15
16 my $default_mount_point = "/mnt/vzsnap0";
17
18 my $rsync_vm = sub {
19 my ($self, $task, $to, $text) = @_;
20
21 my $disks = $task->{disks};
22 my $from = $disks->[0]->{dir} . '/';
23 $self->loginfo ("starting $text sync $from to $to");
24
25 my $opts = $self->{vzdump}->{opts};
26
27 my @xattr = $task->{no_xattrs} ? () : ('-X', '-A');
28
29 my $rsync = ['rsync', '--stats', @xattr, '--numeric-ids',
30 '-aH', '--delete', '--no-whole-file', '--inplace',
31 '--one-file-system', '--relative'];
32 push @$rsync, "--bwlimit=$opts->{bwlimit}" if $opts->{bwlimit};
33 push @$rsync, map { "--exclude=$_" } @{$self->{vzdump}->{findexcl}};
34 push @$rsync, map { "--exclude=$_" } @{$task->{exclude_dirs}};
35
36 my $starttime = time();
37 # See the rsync(1) manpage for --relative in conjunction with /./ in paths.
38 # This is the only way to have exclude-dirs work together with the
39 # --one-file-system option.
40 # This way we can pass multiple source paths and tell rsync which directory
41 # they're supposed to be relative to.
42 # Otherwise with eg. using multiple rsync commands means the --exclude
43 # directives need to be modified for every command as they are meant to be
44 # relative to the rootdir, while rsync treats them as relative to the
45 # source dir.
46 foreach my $disk (@$disks) {
47 push @$rsync, "$from/.$disk->{mp}";
48 }
49 $self->cmd([@$rsync, $to]);
50 my $delay = time () - $starttime;
51
52 $self->loginfo ("$text sync finished ($delay seconds)");
53 };
54
55 sub new {
56 my ($class, $vzdump) = @_;
57
58 PVE::VZDump::check_bin('lxc-stop');
59 PVE::VZDump::check_bin('lxc-start');
60 PVE::VZDump::check_bin('lxc-freeze');
61 PVE::VZDump::check_bin('lxc-unfreeze');
62
63 my $self = bless {};
64
65 $self->{vzdump} = $vzdump;
66 $self->{storecfg} = PVE::Storage::config();
67
68 $self->{vmlist} = PVE::LXC::config_list();
69
70 return $self;
71 }
72
73 sub type {
74 return 'lxc';
75 }
76
77 sub vm_status {
78 my ($self, $vmid) = @_;
79
80 my $running = PVE::LXC::check_running($vmid) ? 1 : 0;
81
82 return wantarray ? ($running, $running ? 'running' : 'stopped') : $running;
83 }
84
85 my $check_mountpoint_empty = sub {
86 my ($mountpoint) = @_;
87
88 die "mountpoint '$mountpoint' is not a directory\n" if ! -d $mountpoint;
89
90 PVE::Tools::dir_glob_foreach($mountpoint, qr/.*/, sub {
91 my $entry = shift;
92 return if $entry eq '.' || $entry eq '..';
93 die "mountpoint '$mountpoint' not empty\n";
94 });
95 };
96
97 sub prepare {
98 my ($self, $task, $vmid, $mode) = @_;
99
100 my $conf = $self->{vmlist}->{$vmid} = PVE::LXC::load_config($vmid);
101 my $storage_cfg = $self->{storecfg};
102
103 my $running = PVE::LXC::check_running($vmid);
104
105 my $disks = $task->{disks} = [];
106 my $exclude_dirs = $task->{exclude_dirs} = [];
107
108 $task->{hostname} = $conf->{'hostname'} || "CT$vmid";
109
110 my ($id_map, $rootuid, $rootgid) = PVE::LXC::parse_id_maps($conf);
111 $task->{userns_cmd} = PVE::LXC::userns_command($id_map);
112
113 my $volid_list = [];
114 PVE::LXC::foreach_mountpoint($conf, sub {
115 my ($name, $data) = @_;
116 my $volid = $data->{volume};
117 my $mount = $data->{mp};
118 my $type = $data->{type};
119
120 return if !$volid || !$mount;
121
122 if ($name ne 'rootfs' && !$data->{backup}) {
123 push @$exclude_dirs, $mount;
124 return;
125 }
126
127 push @$disks, $data;
128 push @$volid_list, $volid
129 if $type eq 'volume';
130 });
131
132 if ($mode eq 'snapshot') {
133 if (!PVE::LXC::has_feature('vzdump', $conf, $storage_cfg)) {
134 die "mode failure - some volumes do not support snapshots\n";
135 }
136
137 unlock_vm($self, $vmid);
138
139 if ($conf->{snapshots} && $conf->{snapshots}->{vzdump}) {
140 $self->loginfo("found old vzdump snapshot (force removal)");
141 PVE::LXC::snapshot_delete($vmid, 'vzdump', 1);
142 }
143
144 my $rootdir = $default_mount_point;
145 mkpath $rootdir;
146 &$check_mountpoint_empty($rootdir);
147
148 # set snapshot_count (freezes CT if snapshot_count > 1)
149 $task->{snapshot_count} = scalar(@$volid_list);
150 } elsif ($mode eq 'stop') {
151 my $rootdir = $default_mount_point;
152 mkpath $rootdir;
153 &$check_mountpoint_empty($rootdir);
154 PVE::Storage::activate_volumes($storage_cfg, $volid_list);
155 } elsif ($mode eq 'suspend') {
156 my $pid = PVE::LXC::find_lxc_pid($vmid);
157 foreach my $disk (@$disks) {
158 $disk->{dir} = "/proc/$pid/root$disk->{mp}";
159 }
160 $task->{snapdir} = $task->{tmpdir};
161 } else {
162 unlock_vm($self, $vmid);
163 die "unknown mode '$mode'\n"; # should not happen
164 }
165
166 if ($mode ne 'suspend') {
167 # If we perform mount operations, let's unshare the mount namespace
168 # to not influence the running host.
169 PVE::Tools::unshare(PVE::Tools::CLONE_NEWNS);
170 PVE::Tools::run_command(['mount', '--make-rprivate', '/']);
171 }
172 }
173
174 sub lock_vm {
175 my ($self, $vmid) = @_;
176
177 my $lockconfig = sub {
178 my ($self, $vmid) = @_;
179
180 my $conf = PVE::LXC::load_config($vmid);
181
182 PVE::LXC::check_lock($conf);
183 $conf->{lock} = 'backup';
184
185 PVE::LXC::write_config($vmid, $conf);
186 };
187
188 PVE::LXC::lock_container($vmid, 10, $lockconfig, ($self, $vmid));
189 }
190
191 sub unlock_vm {
192 my ($self, $vmid) = @_;
193
194 my $unlockconfig = sub {
195 my ($self, $vmid) = @_;
196
197 my $conf = PVE::LXC::load_config($vmid);
198
199 if ($conf->{lock} && $conf->{lock} eq 'backup') {
200 delete $conf->{lock};
201 PVE::LXC::write_config($vmid, $conf);
202 }
203 };
204
205 PVE::LXC::lock_container($vmid, 60, $unlockconfig, ($self, $vmid));
206 }
207
208 sub snapshot {
209 my ($self, $task, $vmid) = @_;
210
211 $self->loginfo("create storage snapshot 'vzdump'");
212
213 # todo: freeze/unfreeze if we have more than one volid
214 PVE::LXC::snapshot_create($vmid, 'vzdump', "vzdump backup snapshot");
215 $task->{cleanup}->{remove_snapshot} = 1;
216
217 # reload config
218 my $conf = $self->{vmlist}->{$vmid} = PVE::LXC::load_config($vmid);
219 die "unable to read vzdump snapshot config - internal error"
220 if !($conf->{snapshots} && $conf->{snapshots}->{vzdump});
221
222 my $disks = $task->{disks};
223 #todo: reevaluate bind/dev mount handling when implementing snapshots for mps
224 my $volid_list = [map { $_->{volume} } @$disks];
225
226 my $rootdir = $default_mount_point;
227 my $storage_cfg = $self->{storecfg};
228
229 PVE::Storage::activate_volumes($storage_cfg, $volid_list, 'vzdump');
230 foreach my $disk (@$disks) {
231 $disk->{dir} = "${rootdir}$disk->{mp}";
232 PVE::LXC::mountpoint_mount($disk, $rootdir, $storage_cfg, 'vzdump');
233 }
234
235 $task->{snapdir} = $rootdir;
236 }
237
238 sub copy_data_phase1 {
239 my ($self, $task) = @_;
240
241 if (my $mntinfo = PVE::VZDump::get_mount_info($task->{snapdir})) {
242 if ($mntinfo->{fstype} =~ /^nfs4?/) {
243 warn "temporary directory is on NFS, disabling xattr and acl support"
244 . ", consider configuring a local tmpdir via /etc/vzdump.conf\n";
245 $task->{no_xattrs} = 1;
246 }
247 }
248
249 $self->$rsync_vm($task, $task->{snapdir}, "first");
250 }
251
252 sub copy_data_phase2 {
253 my ($self, $task) = @_;
254
255 $self->$rsync_vm($task, $task->{snapdir}, "final");
256 }
257
258 sub stop_vm {
259 my ($self, $task, $vmid) = @_;
260
261 $self->cmd("lxc-stop -n $vmid");
262
263 # make sure container is stopped
264 $self->cmd("lxc-wait -n $vmid -s STOPPED");
265 }
266
267 sub start_vm {
268 my ($self, $task, $vmid) = @_;
269
270 $self->cmd ("lxc-start -n $vmid");
271 }
272
273 sub suspend_vm {
274 my ($self, $task, $vmid) = @_;
275
276 $self->cmd ("lxc-freeze -n $vmid");
277 }
278
279 sub resume_vm {
280 my ($self, $task, $vmid) = @_;
281
282 $self->cmd ("lxc-unfreeze -n $vmid");
283 }
284
285 sub assemble {
286 my ($self, $task, $vmid) = @_;
287
288 my $tmpdir = $task->{tmpdir};
289
290 mkpath "$tmpdir/etc/vzdump/";
291
292 my $conf = PVE::LXC::load_config($vmid);
293 delete $conf->{lock};
294 delete $conf->{snapshots};
295 delete $conf->{'pve.parent'};
296
297 PVE::Tools::file_set_contents("$tmpdir/etc/vzdump/pct.conf", PVE::LXC::write_pct_config("/lxc/$vmid.conf", $conf));
298
299 my $firewall ="/etc/pve/firewall/$vmid.fw";
300 if (-e $firewall) {
301 PVE::Tools::file_copy($firewall, "$tmpdir/etc/vzdump/pct.fw");
302 $task->{fw} = 1;
303 }
304 }
305
306 sub archive {
307 my ($self, $task, $vmid, $filename, $comp) = @_;
308
309 my $disks = $task->{disks};
310 my @sources;
311
312 if ($task->{mode} eq 'stop') {
313 my $rootdir = $default_mount_point;
314 my $storage_cfg = $self->{storecfg};
315 foreach my $disk (@$disks) {
316 $disk->{dir} = "${rootdir}$disk->{mp}";
317 PVE::LXC::mountpoint_mount($disk, $rootdir, $storage_cfg);
318 # add every enabled mountpoint (since we use --one-file-system)
319 # mp already starts with a / so we only need to add the dot
320 push @sources, ".$disk->{mp}";
321 }
322 $task->{snapdir} = $rootdir;
323 } else {
324 # the data was rsynced to a temporary location, only use '.' to avoid
325 # having mountpoints duplicated
326 push @sources, '.';
327 }
328
329 my $opts = $self->{vzdump}->{opts};
330 my $snapdir = $task->{snapdir};
331 my $tmpdir = $task->{tmpdir};
332
333 my $userns_cmd = $task->{userns_cmd};
334 my $tar = [@$userns_cmd, 'tar', 'cpf', '-', '--totals',
335 @$PVE::LXC::COMMON_TAR_FLAGS,
336 '--one-file-system', '--warning=no-file-ignored'];
337
338 # note: --remove-files does not work because we do not
339 # backup all files (filters). tar complains:
340 # Cannot rmdir: Directory not empty
341 # we disable this optimization for now
342 #if ($snapdir eq $task->{tmpdir} && $snapdir =~ m|^$opts->{dumpdir}/|) {
343 # push @$tar, "--remove-files"; # try to save space
344 #}
345
346 # The directory parameter can give an alternative directory as source.
347 # the second parameter gives the structure in the tar.
348 push @$tar, "--directory=$tmpdir", './etc/vzdump/pct.conf';
349 push @$tar, "./etc/vzdump/pct.fw" if $task->{fw};
350 push @$tar, "--directory=$snapdir";
351 push @$tar, '--no-anchored', '--exclude=lost+found' if $userns_cmd;
352 push @$tar, '--anchored';
353 push @$tar, map { "--exclude=.$_" } @{$self->{vzdump}->{findexcl}};
354
355 push @$tar, @sources;
356
357 my $cmd = [ $tar ];
358
359 my $bwl = $opts->{bwlimit}*1024; # bandwidth limit for cstream
360 push @$cmd, [ 'cstream', '-t', $bwl ] if $opts->{bwlimit};
361 push @$cmd, [ split(/\s+/, $comp) ] if $comp;
362
363 if ($opts->{stdout}) {
364 push @{$cmd->[-1]}, \(">&" . fileno($opts->{stdout}));
365 } else {
366 push @{$cmd->[-1]}, \(">" . PVE::Tools::shellquote($filename));
367 }
368 $self->cmd($cmd);
369 }
370
371 sub cleanup {
372 my ($self, $task, $vmid) = @_;
373
374 my $conf = PVE::LXC::load_config($vmid);
375
376 if ($task->{mode} ne 'suspend') {
377 my $rootdir = $default_mount_point;
378 my $disks = $task->{disks};
379 foreach my $disk (reverse @$disks) {
380 PVE::Tools::run_command(['umount', '-l', '-d', $disk->{dir}]) if $disk->{dir};
381 }
382 }
383
384 if ($task->{cleanup}->{remove_snapshot}) {
385 $self->loginfo("remove vzdump snapshot");
386 PVE::LXC::snapshot_delete($vmid, 'vzdump', 0);
387 }
388 }
389
390 1;