Skip to content

Commit 3cc9cf8

Browse files
committed
StorPool: clean up volumes left behind by failed NAS backup/restore
Restore (KVM agent): - When restoring a backed-up volume to a new StorPool volume fails, either while copying the backup data or while attaching the volume to the running VM, the created volume was leaked. The management server persists the restored volume only on success, and StorPool assigns the volume's identity itself, so nothing else could find and delete it. - Add StorageAdaptor#cleanupCreatedPhysicalDisk (default: no-op) and call it from LibvirtRestoreBackupCommandWrapper on both failure paths. The StorPool implementation detaches the volume from this host and deletes it. The restore still fails; a cleanup failure is only logged. - Fix the delete when the attach in StorPoolStorageAdaptor #createPhysicalDisk fails: the volume was deleted by its bare globalId instead of "~<globalId>". Backup (nasbackup.sh) - Delete the clone with onAttached=detachForce, which removes it even if the attach succeeded but the device symlink never appeared. This replaces the separate detach-with-retries step.
1 parent 8587f09 commit 3cc9cf8

5 files changed

Lines changed: 119 additions & 26 deletions

File tree

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

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -196,12 +196,14 @@ private String restoreVolume(KVMStoragePoolManager storagePoolMgr, String backup
196196
volumeUuid = getVolumeUuidFromPath(volumePath, volumePool);
197197
verifyBackupFile(bkpPath, volumeUuid);
198198
Pair<Boolean, String> restoreResult = replaceVolumeWithBackup(storagePoolMgr, volumePool, volumePath, bkpPath, timeout, true, size);
199+
volumePath = restoreResult.second();
199200
if (!restoreResult.first()) {
201+
cleanupCreatedVolume(storagePoolMgr, volumePool, volumePath);
200202
throw new CloudRuntimeException(String.format("Unable to restore contents from the backup volume [%s].", volumeUuid));
201203
}
202-
volumePath = restoreResult.second();
203204
if (VirtualMachine.State.Running.equals(vmNameAndState.second())) {
204205
if (!attachVolumeToVm(storagePoolMgr, vmNameAndState.first(), volumePool, volumePath)) {
206+
cleanupCreatedVolume(storagePoolMgr, volumePool, volumePath);
205207
throw new CloudRuntimeException(String.format("Failed to attach volume to VM: %s", vmNameAndState.first()));
206208
}
207209
}
@@ -212,6 +214,22 @@ private String restoreVolume(KVMStoragePoolManager storagePoolMgr, String backup
212214
}
213215
}
214216

217+
/**
218+
* Best-effort release of a volume created for a restore that then failed. A failed restore
219+
* returns no volume path to the management server, so for storages that assign the created
220+
* volume's identity themselves (StorPool) nobody else could find and delete it.
221+
*/
222+
private void cleanupCreatedVolume(KVMStoragePoolManager storagePoolMgr, PrimaryDataStoreTO volumePool, String volumePath) {
223+
try {
224+
if (!storagePoolMgr.cleanupCreatedPhysicalDisk(volumePool.getPoolType(), volumePool.getUuid(), volumePath)) {
225+
logger.warn("Volume {} created for the failed restore was not cleaned up by the {} storage adaptor; it may need to be deleted manually",
226+
volumePath, volumePool.getPoolType());
227+
}
228+
} catch (Exception e) {
229+
logger.warn("Failed to clean up volume {} created for the failed restore; it may need to be deleted manually", volumePath, e);
230+
}
231+
}
232+
215233

216234
private String mountBackupDirectory(String backupRepoAddress, String backupRepoType, String mountOptions, Integer mountTimeout) {
217235
String randomChars = RandomStringUtils.random(5, true, false);

‎plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/KVMStoragePoolManager.java‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -443,6 +443,13 @@ public boolean disconnectPhysicalDisk(StoragePoolType type, String poolUuid, Str
443443
return adaptor.disconnectPhysicalDisk(volPath, pool);
444444
}
445445

446+
public boolean cleanupCreatedPhysicalDisk(StoragePoolType type, String poolUuid, String volPath) {
447+
StorageAdaptor adaptor = getStorageAdaptor(type);
448+
KVMStoragePool pool = adaptor.getStoragePool(poolUuid);
449+
450+
return adaptor.cleanupCreatedPhysicalDisk(volPath, pool);
451+
}
452+
446453
public synchronized boolean deleteStoragePool(StoragePoolType type, String uuid) {
447454
StorageAdaptor adaptor = getStorageAdaptor(type);
448455
if (type == StoragePoolType.NetworkFilesystem) {

‎plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/storage/StorageAdaptor.java‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -152,4 +152,18 @@ default Pair<Boolean, String> unprepareStorageClient(String uuid, Map<String, St
152152
default void createTemplate(String templatePath, String templateUuid, int timeout, KVMStoragePool pool) {
153153
// no-op
154154
}
155+
156+
/**
157+
* Releases a disk this host created via {@link #createPhysicalDisk} that could not be put into
158+
* use (e.g. populating it from a backup failed), for storages where the management server
159+
* can't clean it up because the storage assigned the disk's identity itself: disconnects it
160+
* from this host and deletes it from the storage.
161+
*
162+
* @param volumePath the path of the disk, as returned in {@link KVMPhysicalDisk#getPath()}
163+
* @param pool storage pool the disk is part of
164+
* @return true if the disk was deleted; false if it wasn't or the adaptor doesn't support it
165+
*/
166+
default boolean cleanupCreatedPhysicalDisk(String volumePath, KVMStoragePool pool) {
167+
return false;
168+
}
155169
}

‎plugins/storage/volume/storpool/src/main/java/com/cloud/hypervisor/kvm/storage/StorPoolStorageAdaptor.java‎

Lines changed: 21 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -328,6 +328,26 @@ public boolean deletePhysicalDisk(String volumeUuid, KVMStoragePool pool, Storag
328328
return true; // apparently ignored
329329
}
330330

331+
@Override
332+
public boolean cleanupCreatedPhysicalDisk(String volumePath, KVMStoragePool pool) {
333+
SP_LOG("StorPoolStorageAdaptor.cleanupCreatedPhysicalDisk: path=%s, pool=%s", volumePath, pool);
334+
final String name = getVolumeNameFromPath(volumePath, true);
335+
if (name == null) {
336+
LOGGER.warn(String.format("Unable to clean up created disk '%s': not a StorPool volume path", volumePath));
337+
return false;
338+
}
339+
340+
try {
341+
disconnectPhysicalDisk(volumePath, pool);
342+
volumeDelete(name);
343+
} catch (CloudRuntimeException e) {
344+
SP_LOG("Failed to delete created StorPool volume %s: %s", name, e.getMessage());
345+
LOGGER.warn(String.format("Failed to delete created StorPool volume %s, it must be deleted manually: %s", name, e.getMessage()));
346+
return false;
347+
}
348+
return true;
349+
}
350+
331351
@Override
332352
public List<KVMPhysicalDisk> listPhysicalDisks(String storagePoolUuid, KVMStoragePool pool) {
333353
SP_LOG("StorPoolStorageAdaptor.listPhysicalDisks: uuid=%s, pool=%s", storagePoolUuid, pool);
@@ -489,7 +509,7 @@ public KVMPhysicalDisk createPhysicalDisk(String name, KVMStoragePool pool, Phys
489509
try {
490510
attachOrDetachVolume("attach", "volume", volumePath);
491511
} catch (CloudRuntimeException e) {
492-
volumeDelete(globalId);
512+
volumeDelete("~" + globalId);
493513
throw e;
494514
}
495515

‎scripts/vm/hypervisor/kvm/nasbackup.sh‎

Lines changed: 58 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -455,23 +455,61 @@ sp_wait_for_device_symlink() {
455455
return 1
456456
}
457457

458-
# detach is retried (a live volume's detach can transiently fail while still in use), attach is
459-
# not. A successful attach also waits for the device symlink.
460-
sp_attach_detach_volume() {
461-
local cmd="$1" name="$2"
462-
local tries=10 i
463-
for ((i = 0; i < tries; i++)); do
464-
if [[ "$cmd" == "attach" ]]; then
465-
storpool -M -B attach volume "$name" here onRemoteAttached export >>"$logFile" 2>&1 && { sp_wait_for_device_symlink "$name"; return $?; }
466-
break
467-
else
468-
storpool -M -B detach volume "$name" here >>"$logFile" 2>&1 && return 0
469-
sleep 1
470-
fi
471-
done
458+
# A successful attach also waits for the device symlink.
459+
sp_attach_volume() {
460+
local name="$1"
461+
storpool -M -B attach volume "$name" here onRemoteAttached export >>"$logFile" 2>&1 && { sp_wait_for_device_symlink "$name"; return $?; }
472462
return 1
473463
}
474464

465+
sp_api_post() {
466+
local query="$1" json="$2"
467+
local key value host="" port="81" token=""
468+
while IFS='=' read -r key value; do
469+
case "$key" in
470+
SP_API_HTTP_HOST) host="$value" ;;
471+
SP_API_HTTP_PORT) port="$value" ;;
472+
SP_AUTH_TOKEN) token="$value" ;;
473+
esac
474+
done < <(storpool_confget 2>>"$logFile")
475+
if [[ -z "$host" || -z "$token" ]]; then
476+
log -ne "StorPool: SP_API_HTTP_HOST or SP_AUTH_TOKEN missing from storpool_confget, cannot call $query"
477+
return 1
478+
fi
479+
480+
local resp
481+
if ! resp=$(curl -sS --connect-timeout 10 -X POST \
482+
-H @<(printf 'Authorization: Storpool v1:%s\n' "$token") \
483+
-H "Content-Type: application/json" -d "$json" \
484+
"http://$host:$port/ctrl/1.0/$query" 2>>"$logFile"); then
485+
log -ne "StorPool: API call $query failed, see above for curl output"
486+
return 1
487+
fi
488+
python3 -c '
489+
import sys, json
490+
try:
491+
resp = json.load(sys.stdin)
492+
except Exception:
493+
sys.exit(1)
494+
if "error" in resp or "data" not in resp:
495+
sys.exit(1)
496+
print(json.dumps(resp["data"]))
497+
' <<< "$resp" || {
498+
log -ne "StorPool: API call $query returned an error: $resp"
499+
return 1
500+
}
501+
}
502+
503+
# Deletes $1, force-detaching it first wherever it is still attached (StorPool refuses to delete
504+
# an attached volume). Returns 1, after logging, if the delete failed.
505+
sp_delete_volume() {
506+
local volume_name="$1"
507+
if ! sp_api_post "MultiCluster/VolumeDelete/$volume_name" '{"onAttached":"detachForce"}' >/dev/null; then
508+
log -ne "StorPool: failed to delete volume $volume_name, it must be deleted manually"
509+
return 1
510+
fi
511+
}
512+
475513
# Clones $1 (a live StorPool volume path) into a new, point-in-time StorPool volume via the
476514
# VolumeCreate API's baseOn option, attaches it, and echoes the clone's device path. Only called
477515
# once this script's own (fresh, right-here) VM liveness check has already routed to the cold
@@ -487,8 +525,8 @@ sp_create_backup_source_disk() {
487525
log -ne "StorPool: creating backup source volume based on $base_on (from $volume_path)"
488526

489527
local resp
490-
if ! resp=$(storpool_req -P -M --json "{\"baseOn\":\"$base_on\",\"tags\":{\"cs\":\"backup\"}}" VolumeCreate 2>>"$logFile"); then
491-
log -ne "StorPool: VolumeCreate baseOn=$base_on failed, see above for storpool_req output"
528+
if ! resp=$(sp_api_post "MultiCluster/VolumeCreate" "{\"baseOn\":\"$base_on\",\"tags\":{\"cs\":\"backup\"}}"); then
529+
log -ne "StorPool: VolumeCreate baseOn=$base_on failed, see above"
492530
echo "Could not create a backup source volume based on $base_on" >&2
493531
return 1
494532
fi
@@ -513,9 +551,9 @@ print(gid)
513551
local clone_path="/dev/storpool-byid/$global_id"
514552
local clone_name="~$global_id"
515553
log -ne "StorPool: created backup source volume $clone_name ($clone_path), attaching"
516-
if ! sp_attach_detach_volume "attach" "$clone_name"; then
554+
if ! sp_attach_volume "$clone_name"; then
517555
log -ne "StorPool: failed to attach backup source volume $clone_name, deleting it"
518-
storpool_req -P -M VolumeDelete "$clone_name" >>"$logFile" 2>&1 || true
556+
sp_delete_volume "$clone_name" || true
519557
echo "Could not attach backup source volume $clone_path cloned from $base_on" >&2
520558
return 1
521559
fi
@@ -528,16 +566,12 @@ print(gid)
528566
echo "$clone_path"
529567
}
530568

531-
# Detach + delete a volume previously returned by sp_create_backup_source_disk. Best-effort:
569+
# Deletes a volume previously returned by sp_create_backup_source_disk. Best-effort:
532570
# logs on failure rather than aborting the backup, matching the wrapper's old cleanup semantics.
533571
sp_delete_backup_source_disk() {
534572
local clone_name="$1"
535573
log -ne "StorPool: releasing backup source volume $clone_name"
536-
sp_attach_detach_volume "detach" "$clone_name" || log -ne "Failed to detach StorPool backup source volume $clone_name"
537-
if ! storpool_req -P -M VolumeDelete "$clone_name" >>"$logFile" 2>&1; then
538-
log -ne "Failed to delete StorPool backup source volume $clone_name"
539-
return 1
540-
fi
574+
sp_delete_volume "$clone_name"
541575
}
542576

543577
# Safety net for any clone not already released by its own per-disk cleanup (e.g. the script

0 commit comments

Comments
 (0)