Skip to content

Commit 76b34fb

Browse files
author
Glover, Rene (rg9975)
committed
add use of virsh domifaddr to get VM external DHCP IP
1 parent ae1d7cc commit 76b34fb

File tree

1 file changed

+36
-2
lines changed

1 file changed

+36
-2
lines changed

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

Lines changed: 36 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -47,15 +47,33 @@ public Answer execute(final GetVmIpAddressCommand command, final LibvirtComputin
4747
}
4848
String sanitizedVmName = sanitizeBashCommandArgument(vmName);
4949
String networkCidr = command.getVmNetworkCidr();
50-
List<String[]> commands = new ArrayList<>();
5150
final String virt_ls_path = Script.getExecutableAbsolutePath("virt-ls");
5251
final String virt_cat_path = Script.getExecutableAbsolutePath("virt-cat");
5352
final String virt_win_reg_path = Script.getExecutableAbsolutePath("virt-win-reg");
5453
final String tail_path = Script.getExecutableAbsolutePath("tail");
5554
final String grep_path = Script.getExecutableAbsolutePath("grep");
5655
final String awk_path = Script.getExecutableAbsolutePath("awk");
5756
final String sed_path = Script.getExecutableAbsolutePath("sed");
58-
if(!command.isWindows()) {
57+
final String virsh_path = Script.getExecutableAbsolutePath("virsh");
58+
59+
// first run virsh domiflist to get the network interface name from libvirt. This is set if qemu guest agent is running in the VM
60+
// and is the most reliable and least intrusive
61+
List<String[]> commands = new ArrayList<>();
62+
commands.add(new String[]{virsh_path, "domifaddr", sanitizedVmName, "--source", "agent"});
63+
String output = Script.executePipedCommands(commands, 0).second();
64+
if (output != null) {
65+
String[] lines = output.split("\n");
66+
for (String line : lines) {
67+
ip = parseDomIfListOutput(line, networkCidr);
68+
if (ip != null) {
69+
break;
70+
}
71+
}
72+
}
73+
74+
commands.clear();
75+
commands.add(new String[]{grep_path, ".*\\*"});
76+
if(ip == null && !command.isWindows()) {
5977
//List all dhcp lease files inside guestVm
6078
commands.add(new String[]{virt_ls_path, sanitizedVmName, "/var/lib/dhclient/"});
6179
commands.add(new String[]{grep_path, ".*\\*.leases"});
@@ -106,4 +124,20 @@ public Answer execute(final GetVmIpAddressCommand command, final LibvirtComputin
106124
}
107125
return new Answer(command, result, ip);
108126
}
127+
128+
private String parseDomIfListOutput(String line, String networkCidr) {
129+
String ip = null;
130+
if (line.contains("ipv4")) {
131+
String[] parts = line.split(" ");
132+
if (parts.length > 2) {
133+
String[] ipParts = parts[2].split("/");
134+
if (ipParts.length > 0) {
135+
if (NetUtils.isIpWithInCidrRange(ipParts[0], networkCidr)) {
136+
ip = ipParts[0];
137+
}
138+
}
139+
}
140+
}
141+
return ip;
142+
}
109143
}

0 commit comments

Comments
 (0)