Skip to content

Commit 7473aa1

Browse files
committed
nas: address the second review of the RBD incremental backups
- restore: fail closed when the snapshots of an RBD image can not be listed, so a restore never removes snapshots it could not see; a missing image (exit code 2) has none. - removing the offering sends the anchor cleanup to a host which has the rbd command, and sends none when no host has it. - build the Ceph monitor list of an RBD disk string with RbdUtils, so a bare IPv6 monitor is bracketed, carries its port and survives nasbackup.sh's parser. - RBD backup: bound the freeze, pause and snapshot steps with timeouts and keep a state file in /run/csbackup while the guest is held. The guest is released by a TERM/HUP/INT trap of the script, by the take-backup wrapper when the script failed or was killed, and by the agent for every state file left when it starts (RbdBackupGuestReleaser), which covers SIGKILL, a crash and a restart of the agent. - nasbackup.sh holds a per-VM flock during the RBD backup, so two backups of a VM can not freeze the guest and share the state file at once. A refused backup exits with 21 and the wrapper then leaves the guest to the backup which holds the lock.
1 parent 0ddd97b commit 7473aa1

11 files changed

Lines changed: 565 additions & 12 deletions

File tree

‎plugins/backup/nas/src/main/java/org/apache/cloudstack/backup/NASBackupProvider.java‎

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -838,9 +838,15 @@ protected void removeBackupAnchors(VirtualMachine vm) {
838838
LOG.debug("No host to remove the backup anchors of VM id={} on", vmId);
839839
return;
840840
}
841+
Host cleanupHost = findHostForRbdAnchorCleanup(host);
842+
if (cleanupHost == null) {
843+
LOG.warn("Host {} has no rbd command and no other host of its cluster has it, so the backup anchors "
844+
+ "of VM id={} stay on the RBD images until a later backup of it sweeps them", host.getName(), vmId);
845+
return;
846+
}
841847
Pair<List<PrimaryDataStoreTO>, List<String>> volumePoolsAndPaths = getVolumePoolsAndPaths(volumes);
842848
RemoveBackupAnchorsCommand command = new RemoveBackupAnchorsCommand(volumePoolsAndPaths.first(), volumePoolsAndPaths.second());
843-
Answer answer = agentManager.send(host.getId(), command);
849+
Answer answer = agentManager.send(cleanupHost.getId(), command);
844850
if (answer == null || !answer.getResult()) {
845851
LOG.warn("Failed to remove the backup anchors of VM id={}: {}", vmId,
846852
answer != null ? answer.getDetails() : "no answer received");
@@ -933,6 +939,17 @@ && hostHasRbdCli(candidate)) {
933939
return null;
934940
}
935941

942+
/**
943+
* The host that removes the backup anchors: it drives the {@code rbd} command against the images
944+
* and needs nothing of the Instance's libvirt domain, so any host of the cluster that has the
945+
* command will do, whether the Instance is stopped or not. {@code preferred} is used when it has it.
946+
*
947+
* @return the host to use, or {@code null} when none has the {@code rbd} command
948+
*/
949+
protected Host findHostForRbdAnchorCleanup(Host preferred) {
950+
return hostHasRbdCli(preferred) ? preferred : findOtherHostWithRbdCli(preferred);
951+
}
952+
936953
/**
937954
* The host a restore of an RBD chain has to run on: it recreates the image and replays the
938955
* chain with the {@code rbd} command. {@code preferred} is used when it has the command;

‎plugins/backup/nas/src/test/java/org/apache/cloudstack/backup/NASBackupProviderTest.java‎

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
import static org.mockito.Mockito.mock;
2121

2222
import java.util.ArrayList;
23+
import java.util.Arrays;
2324
import java.util.Collections;
2425
import java.util.List;
2526
import java.util.Objects;
@@ -1596,6 +1597,12 @@ public void sweepContinuesPastFailedTombstoneDelete()
15961597

15971598
// -- the backup anchors are removed once the chain is gone ---------------------------
15981599

1600+
private void setRbdCliOfHost(long hostId, boolean hasRbdCli) {
1601+
DetailVO detail = mock(DetailVO.class);
1602+
Mockito.lenient().when(detail.getValue()).thenReturn(String.valueOf(hasRbdCli));
1603+
Mockito.lenient().when(hostDetailsDao.findDetail(hostId, Host.HOST_RBD_CLI)).thenReturn(detail);
1604+
}
1605+
15991606
// Defaults for an Instance with one RBD volume; lenient, as a test may override a stub or
16001607
// return before reaching it.
16011608
private VMInstanceVO vmWithRbdVolume(long vmId, long hostId, long poolId) {
@@ -1607,6 +1614,7 @@ private VMInstanceVO vmWithRbdVolume(long vmId, long hostId, long poolId) {
16071614
Mockito.lenient().when(host.getStatus()).thenReturn(Status.Up);
16081615
Mockito.lenient().when(host.getId()).thenReturn(hostId);
16091616
Mockito.lenient().when(hostDao.findById(hostId)).thenReturn(host);
1617+
setRbdCliOfHost(hostId, true);
16101618

16111619
VolumeVO volume = mock(VolumeVO.class);
16121620
Mockito.lenient().when(volume.getPoolId()).thenReturn(poolId);
@@ -1639,6 +1647,42 @@ public void removingTheOfferingRemovesTheBackupAnchors() throws AgentUnavailable
16391647
Mockito.verify(agentManager).send(Mockito.eq(22L), Mockito.any(RemoveBackupAnchorsCommand.class));
16401648
}
16411649

1650+
/**
1651+
* A stopped Instance can be backed up on another host than its own when that one lacks the rbd
1652+
* command, so the anchor it left on the images can be on any host: removing it must not be sent
1653+
* to a host which cannot run the command either.
1654+
*/
1655+
@Test
1656+
public void removingTheOfferingRemovesTheBackupAnchorsOnAHostThatHasTheRbdCommand() throws AgentUnavailableException, OperationTimedoutException {
1657+
VMInstanceVO vm = vmWithRbdVolume(51L, 52L, 53L);
1658+
setRbdCliOfHost(52L, false);
1659+
HostVO ownHost = (HostVO) hostDao.findById(52L);
1660+
Mockito.lenient().when(ownHost.getClusterId()).thenReturn(10L);
1661+
HostVO withCli = hostWithRbdCli(54L, true, 10L);
1662+
Mockito.when(hostDao.findHypervisorHostInCluster(10L)).thenReturn(Arrays.asList(ownHost, withCli));
1663+
Mockito.when(agentManager.send(anyLong(), Mockito.any(RemoveBackupAnchorsCommand.class)))
1664+
.thenReturn(new BackupAnswer(null, true, null));
1665+
1666+
Assert.assertTrue(nasBackupProvider.removeVMFromBackupOffering(vm));
1667+
1668+
Mockito.verify(agentManager).send(Mockito.eq(54L), Mockito.any(RemoveBackupAnchorsCommand.class));
1669+
Mockito.verify(agentManager, Mockito.never()).send(Mockito.eq(52L), Mockito.any(RemoveBackupAnchorsCommand.class));
1670+
}
1671+
1672+
@Test
1673+
public void removingTheOfferingSendsNoCommandWhenNoHostHasTheRbdCommand() throws AgentUnavailableException, OperationTimedoutException {
1674+
VMInstanceVO vm = vmWithRbdVolume(61L, 62L, 63L);
1675+
setRbdCliOfHost(62L, false);
1676+
HostVO ownHost = (HostVO) hostDao.findById(62L);
1677+
Mockito.lenient().when(ownHost.getClusterId()).thenReturn(10L);
1678+
HostVO otherWithoutCli = hostWithRbdCli(64L, false, 10L);
1679+
Mockito.when(hostDao.findHypervisorHostInCluster(10L)).thenReturn(Arrays.asList(ownHost, otherWithoutCli));
1680+
1681+
Assert.assertTrue(nasBackupProvider.removeVMFromBackupOffering(vm));
1682+
1683+
Mockito.verify(agentManager, Mockito.never()).send(anyLong(), Mockito.any(RemoveBackupAnchorsCommand.class));
1684+
}
1685+
16421686
/**
16431687
* An Instance whose volumes are on no RBD pool carries no anchor, so no command is sent to
16441688
* its host at all.

‎plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,7 @@
106106
import org.apache.cloudstack.storage.volume.VolumeOnStorageTO;
107107
import org.apache.cloudstack.utils.bytescale.ByteScaleUtils;
108108
import org.apache.cloudstack.utils.cryptsetup.CryptSetup;
109+
import org.apache.cloudstack.utils.rbd.RbdBackupGuestManager;
109110
import org.apache.cloudstack.utils.rbd.RbdEncryption;
110111
import org.apache.cloudstack.utils.hypervisor.HypervisorUtils;
111112
import org.apache.cloudstack.utils.linux.CPUStat;
@@ -1432,6 +1433,9 @@ public boolean configure(final String name, final Map<String, Object> params) th
14321433
throw new CloudRuntimeException(e.getMessage());
14331434
}
14341435

1436+
// A backup of an RBD volume which this agent was running when it went down may have left its guest frozen or paused.
1437+
new RbdBackupGuestManager().releaseAllGuests();
1438+
14351439
// destroy default network, see https://libvirt.org/sources/java/javadoc/org/libvirt/Network.html
14361440
try {
14371441
Network network = conn.networkLookupByName("default");

‎plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtRestoreBackupCommandWrapper.java‎

Lines changed: 16 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,8 @@ public class LibvirtRestoreBackupCommandWrapper extends CommandWrapper<RestoreBa
7878
// `rbd info --format json` reports the image size in bytes.
7979
private static final Pattern RBD_INFO_SIZE = Pattern.compile("\"size\"\\s*:\\s*(\\d+)");
8080
private static final Pattern RBD_SNAP_NAME = Pattern.compile("\"name\"\\s*:\\s*\"([^\"]+)\"");
81+
/** What the rbd command exits with when the image does not exist (ENOENT). */
82+
private static final int RBD_EXIT_NO_SUCH_IMAGE = 2;
8183

8284
// Matches the features CloudStack itself creates RBD volumes with
8385
// (LibvirtStorageAdaptor.RBD_FEATURES), so a restored image behaves like any other. object-map
@@ -638,11 +640,12 @@ private Long rbdImageSize(List<String> connection, String image) {
638640
private boolean recreateRbdImage(List<String> connection, String image, long sizeBytes, String dataPool) {
639641
// `rbd rm` refuses to delete an image that still has snapshots, and a restore target
640642
// normally carries the anchor snapshot of the backup chain it belongs to. Ask first, so an
641-
// image without snapshots is not handed a purge with nothing to do; when the listing itself
642-
// fails we cannot tell, and purging is what we would have done anyway.
643+
// image without snapshots is not handed a purge with nothing to do. When the listing fails
644+
// the restore stops: a purge of snapshots which could not be looked at may remove one that
645+
// was not ours to remove.
643646
List<String> snapshots = rbdSnapshots(connection, image);
644647
failIfImageCarriesForeignSnapshots(image, snapshots);
645-
if (snapshots == null || CollectionUtils.isNotEmpty(snapshots)) {
648+
if (CollectionUtils.isNotEmpty(snapshots)) {
646649
Script.executeCommandForExitValue(rbdCommand(connection, "snap", "purge", image));
647650
}
648651
if (Script.executeCommandForExitValue(rbdCommand(connection, "rm", image)) != 0
@@ -673,9 +676,6 @@ && rbdImageSize(connection, image) != null) {
673676
* not something a restore should do quietly.
674677
*/
675678
private void failIfImageCarriesForeignSnapshots(String image, List<String> snapshots) {
676-
if (snapshots == null) {
677-
return;
678-
}
679679
List<String> foreign = snapshots.stream()
680680
.filter(snapshot -> !snapshot.startsWith(RBD_BACKUP_SNAPSHOT_PREFIX))
681681
.collect(Collectors.toList());
@@ -687,12 +687,20 @@ private void failIfImageCarriesForeignSnapshots(String image, List<String> snaps
687687
}
688688
}
689689

690-
/** The snapshots an image carries, or {@code null} when they could not be listed at all. */
690+
/**
691+
* The snapshots an image carries; none for an image which does not exist yet, as when a restore
692+
* creates a new volume. Any other failure to list them is an error: the caller is about to
693+
* purge the snapshots, so it must not go on without having seen them.
694+
*/
691695
private List<String> rbdSnapshots(List<String> connection, String image) {
692696
Pair<Integer, String> result = Script.executePipedCommands(
693697
Collections.singletonList(rbdCommand(connection, "snap", "ls", image, "--format", "json")), 0);
698+
if (result.first() != null && result.first() == RBD_EXIT_NO_SUCH_IMAGE) {
699+
return new ArrayList<>();
700+
}
694701
if (result.first() == null || result.first() != 0 || StringUtils.isBlank(result.second())) {
695-
return null;
702+
throw new CloudRuntimeException(String.format("Unable to list the snapshots of RBD image %s, so the restore "
703+
+ "cannot tell whether it would remove a snapshot it did not take.", image));
696704
}
697705
List<String> names = new ArrayList<>();
698706
Matcher matcher = RBD_SNAP_NAME.matcher(result.second());

‎plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/wrapper/LibvirtTakeBackupCommandWrapper.java‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
import org.apache.cloudstack.backup.BackupAnswer;
3535
import org.apache.cloudstack.backup.TakeBackupCommand;
3636
import org.apache.cloudstack.storage.to.PrimaryDataStoreTO;
37+
import org.apache.cloudstack.utils.rbd.RbdBackupGuestManager;
3738
import org.apache.commons.collections.CollectionUtils;
3839
import org.apache.commons.lang3.StringUtils;
3940
import org.libvirt.Connect;
@@ -52,6 +53,8 @@
5253
@ResourceWrapper(handles = TakeBackupCommand.class)
5354
public class LibvirtTakeBackupCommandWrapper extends CommandWrapper<TakeBackupCommand, Answer, LibvirtComputingResource> {
5455
private static final Integer EXIT_CLEANUP_FAILED = 20;
56+
// nasbackup.sh found another backup of the VM running: that one may hold the guest, so leave it alone.
57+
private static final Integer EXIT_BACKUP_IN_PROGRESS = 21;
5558
// nasbackup.sh prints this on stdout when it could not proceed as an incremental and
5659
// completed a full backup instead; the orchestrator then records the backup as a full.
5760
private static final String INCREMENTAL_FALLBACK_MARKER = "INCREMENTAL_FALLBACK=true";
@@ -166,6 +169,9 @@ private Answer runBackup(LibvirtComputingResource libvirtComputingResource, Take
166169
if (Script.ERR_TIMEOUT.equals(result.second()) && METHOD_CONTENT.equals(command.getMethod())) {
167170
abortPullBackupJob(vmName);
168171
}
172+
if (METHOD_RBD.equals(command.getMethod()) && !EXIT_BACKUP_IN_PROGRESS.equals(result.first())) {
173+
releaseGuestOfFailedRbdBackup(vmName);
174+
}
169175
BackupAnswer answer = new BackupAnswer(command, false, StringUtils.trimToEmpty(result.second()));
170176
if (EXIT_CLEANUP_FAILED.equals(result.first())) {
171177
logger.debug("Backup cleanup failed");
@@ -289,6 +295,20 @@ static long scratchSize(long diskSize) {
289295
return diskSize + diskSize / 4096 + SCRATCH_EXTRA_BYTES;
290296
}
291297

298+
protected RbdBackupGuestManager guestManager() {
299+
return new RbdBackupGuestManager();
300+
}
301+
302+
/**
303+
* The RBD method freezes or pauses the guest while it takes its snapshots. A script which is
304+
* killed because the backup timed out, or which fails at the wrong moment, cannot be relied on to
305+
* undo that: SIGKILL runs no trap. Release the guest here, but only if the script says in its state
306+
* file that it was the one holding it, so a VM which an operator paused is left alone.
307+
*/
308+
private void releaseGuestOfFailedRbdBackup(String vmName) {
309+
guestManager().releaseGuest(vmName);
310+
}
311+
292312
/** Remove nasbackup.sh's stdout signalling marker lines so they don't pollute size parsing. */
293313
private String stripMarkerLines(String stdout) {
294314
if (StringUtils.isBlank(stdout)) {
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
// Licensed to the Apache Software Foundation (ASF) under one
2+
// or more contributor license agreements. See the NOTICE file
3+
// distributed with this work for additional information
4+
// regarding copyright ownership. The ASF licenses this file
5+
// to you under the Apache License, Version 2.0 (the
6+
// "License"); you may not use this file except in compliance
7+
// with the License. You may obtain a copy of the License at
8+
//
9+
// http://www.apache.org/licenses/LICENSE-2.0
10+
//
11+
// Unless required by applicable law or agreed to in writing,
12+
// software distributed under the License is distributed on an
13+
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14+
// KIND, either express or implied. See the License for the
15+
// specific language governing permissions and limitations
16+
// under the License.
17+
package org.apache.cloudstack.utils.rbd;
18+
19+
import java.io.File;
20+
import java.io.IOException;
21+
import java.nio.charset.StandardCharsets;
22+
import java.nio.file.Files;
23+
24+
import org.apache.commons.lang3.StringUtils;
25+
import org.apache.logging.log4j.LogManager;
26+
import org.apache.logging.log4j.Logger;
27+
28+
import com.cloud.utils.script.Script;
29+
30+
/**
31+
* Looks after the guests which the RBD method of nasbackup.sh freezes or pauses while it takes its
32+
* snapshots. The script records that in a state file per VM. If the script is killed, or the agent which
33+
* ran it restarts, nothing else undoes it: SIGKILL runs no trap. This releases the guests the state
34+
* files say are still held.
35+
*/
36+
public class RbdBackupGuestManager {
37+
protected static final Logger LOGGER = LogManager.getLogger(RbdBackupGuestManager.class);
38+
39+
// Keep in step with RBD_STATE_DIR of nasbackup.sh.
40+
public static final String STATE_DIRECTORY = "/run/csbackup";
41+
public static final String STATE_FILE_SUFFIX = ".guest";
42+
43+
private final File stateDirectory;
44+
45+
public RbdBackupGuestManager() {
46+
this(new File(STATE_DIRECTORY));
47+
}
48+
49+
public RbdBackupGuestManager(File stateDirectory) {
50+
this.stateDirectory = stateDirectory;
51+
}
52+
53+
/**
54+
* The file nasbackup.sh keeps while its RBD method holds the guest frozen or paused.
55+
*/
56+
public File getStateFile(String vmName) {
57+
return new File(stateDirectory, vmName + STATE_FILE_SUFFIX);
58+
}
59+
60+
/**
61+
* Releases the guest of every state file left in the directory, which the agent does when it
62+
* starts: the scripts of the agent which went down are gone with it.
63+
*/
64+
public void releaseAllGuests() {
65+
File[] stateFiles = stateDirectory.listFiles((dir, name) -> name.endsWith(STATE_FILE_SUFFIX));
66+
if (stateFiles == null) {
67+
return;
68+
}
69+
for (File stateFile : stateFiles) {
70+
String name = stateFile.getName();
71+
String vmName = name.substring(0, name.length() - STATE_FILE_SUFFIX.length());
72+
if (!vmName.isEmpty()) {
73+
releaseGuest(vmName);
74+
}
75+
}
76+
}
77+
78+
/**
79+
* Releases the guest, but only if the state file says the script held it, so a VM which an
80+
* operator paused is left alone. The state file is removed once the guest is released.
81+
*/
82+
public void releaseGuest(String vmName) {
83+
File stateFile = getStateFile(vmName);
84+
if (!stateFile.isFile()) {
85+
return;
86+
}
87+
String state;
88+
try {
89+
state = new String(Files.readAllBytes(stateFile.toPath()), StandardCharsets.UTF_8);
90+
} catch (IOException e) {
91+
LOGGER.warn("Unable to read the state file [{}] of the backup of VM {}", stateFile, vmName, e);
92+
return;
93+
}
94+
LOGGER.warn("The RBD backup of VM {} ended while holding the guest ({}), releasing it", vmName, state.trim().replace('\n', ' '));
95+
String virsh = Script.getExecutableAbsolutePath("virsh");
96+
boolean released = true;
97+
if (state.contains("suspended")) {
98+
String domState = Script.executeCommand(virsh, "-c", "qemu:///system", "domstate", vmName);
99+
if (domState != null && StringUtils.equals(domState.trim(), "paused")
100+
&& Script.executeCommandForExitValue(virsh, "-c", "qemu:///system", "resume", vmName) != 0) {
101+
LOGGER.warn("Failed to resume VM {} after its backup", vmName);
102+
released = false;
103+
}
104+
}
105+
if (state.contains("frozen")) {
106+
// Thawing a guest which is not frozen only makes the agent complain.
107+
if (Script.executeCommandForExitValue(virsh, "-c", "qemu:///system", "qemu-agent-command", vmName,
108+
"{\"execute\":\"guest-fsfreeze-thaw\"}") != 0) {
109+
LOGGER.warn("Failed to thaw the filesystems of VM {} after its backup", vmName);
110+
}
111+
}
112+
if (released && !stateFile.delete()) {
113+
LOGGER.warn("Failed to delete the state file [{}]", stateFile);
114+
}
115+
}
116+
}

0 commit comments

Comments
 (0)