Skip to content

Commit 4ceea3a

Browse files
committed
refactor: removed duplication from block device attachment
Moved duplicated code into a macro in `attach_block_devices` Signed-off-by: Egor Lazarchuk <[email protected]>
1 parent e113916 commit 4ceea3a

File tree

1 file changed

+26
-37
lines changed

1 file changed

+26
-37
lines changed

src/vmm/src/builder.rs

Lines changed: 26 additions & 37 deletions
Original file line numberDiff line numberDiff line change
@@ -884,49 +884,38 @@ fn attach_block_devices<'a, I: Iterator<Item = &'a BlockDeviceType> + Debug>(
884884
blocks: I,
885885
event_manager: &mut EventManager,
886886
) -> Result<(), StartMicrovmError> {
887+
macro_rules! attach_block {
888+
($block:ident) => {
889+
let id = {
890+
let locked = $block.lock().expect("Poisoned lock");
891+
if locked.root_device {
892+
match locked.partuuid {
893+
Some(ref partuuid) => {
894+
cmdline.insert_str(format!("root=PARTUUID={}", partuuid))?
895+
}
896+
None => cmdline.insert_str("root=/dev/vda")?,
897+
}
898+
match locked.read_only {
899+
true => cmdline.insert_str("ro")?,
900+
false => cmdline.insert_str("rw")?,
901+
}
902+
}
903+
locked.id.clone()
904+
};
905+
// The device mutex mustn't be locked here otherwise it will deadlock.
906+
attach_virtio_device(event_manager, vmm, id, $block.clone(), cmdline)?;
907+
};
908+
}
909+
887910
for block in blocks {
888911
match block {
889912
BlockDeviceType::VirtioBlock(block) => {
890-
let id = {
891-
let locked = block.lock().expect("Poisoned lock");
892-
if locked.root_device {
893-
cmdline.insert_str(if let Some(ref partuuid) = locked.partuuid {
894-
format!("root=PARTUUID={}", partuuid)
895-
} else {
896-
// If no PARTUUID was specified for the root device, try with the
897-
// /dev/vda.
898-
"root=/dev/vda".to_string()
899-
})?;
900-
901-
let flags = if locked.read_only { "ro" } else { "rw" };
902-
cmdline.insert_str(flags)?;
903-
}
904-
locked.id.clone()
905-
};
906-
// The device mutex mustn't be locked here otherwise it will deadlock.
907-
attach_virtio_device(event_manager, vmm, id, block.clone(), cmdline)?;
913+
attach_block!(block);
908914
}
909915
BlockDeviceType::VhostUserBlock(block) => {
910-
let id = {
911-
let locked = block.lock().expect("Poisoned lock");
912-
if locked.root_device {
913-
cmdline.insert_str(if let Some(ref partuuid) = locked.partuuid {
914-
format!("root=PARTUUID={}", partuuid)
915-
} else {
916-
// If no PARTUUID was specified for the root device, try with the
917-
// /dev/vda.
918-
"root=/dev/vda".to_string()
919-
})?;
920-
921-
let flags = if locked.read_only { "ro" } else { "rw" };
922-
cmdline.insert_str(flags)?;
923-
}
924-
locked.id.clone()
925-
};
926-
// The device mutex mustn't be locked here otherwise it will deadlock.
927-
attach_virtio_device(event_manager, vmm, id, block.clone(), cmdline)?;
916+
attach_block!(block);
928917
}
929-
}
918+
};
930919
}
931920
Ok(())
932921
}

0 commit comments

Comments
 (0)