From 7245716d7969142ccc8d24ff874a7e0549273a50 Mon Sep 17 00:00:00 2001 From: jeong da-young Date: Tue, 21 Oct 2025 10:47:18 +0900 Subject: [PATCH] =?UTF-8?q?=EB=B6=88=ED=95=84=EC=9A=94=ED=95=9C=20?= =?UTF-8?q?=EC=86=8C=EC=8A=A4=20=EC=A0=95=EB=A6=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cloud/resource/ServerResourceBase.java | 392 ++++++++---------- .../resource/LibvirtComputingResource.java | 6 +- .../cloud/server/ManagementServerImpl.java | 174 +------- 3 files changed, 178 insertions(+), 394 deletions(-) diff --git a/core/src/main/java/com/cloud/resource/ServerResourceBase.java b/core/src/main/java/com/cloud/resource/ServerResourceBase.java index 438de8d4f16a..22cafc57d2ce 100644 --- a/core/src/main/java/com/cloud/resource/ServerResourceBase.java +++ b/core/src/main/java/com/cloud/resource/ServerResourceBase.java @@ -28,6 +28,7 @@ import java.net.SocketException; import java.text.ParseException; import java.text.SimpleDateFormat; +import java.util.AbstractMap; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; @@ -39,12 +40,14 @@ import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.naming.ConfigurationException; import java.util.Set; import java.util.stream.Collectors; +import java.util.stream.Stream; import java.nio.file.Files; import java.nio.file.Path; @@ -249,8 +252,7 @@ public Answer listHostLunDevices(Command command) { OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); String result = cmd.execute(parser); - if (result != null) { - logger.error("Failed to execute lsblk command: " + result); + if (result != null || parser.getLines() == null || parser.getLines().trim().isEmpty()) { return new ListHostLunDeviceAnswer(false, hostDevicesNames, hostDevicesText, hasPartitions, scsiAddresses); } @@ -285,28 +287,21 @@ private ListHostLunDeviceAnswer listHostLunDevicesFast() { List scsiAddresses = new ArrayList<>(); Map scsiAddressCache = getScsiAddressesFromSysfs(); - Map realToById = buildByIdReverseMap(); + Map realToById = buildByIdReverseMap(); - java.io.File sysBlock = new java.io.File("/sys/block"); - java.io.File[] entries = sysBlock.listFiles(); + File sysBlock = new File("/sys/block"); + File[] entries = sysBlock.listFiles(); if (entries == null) { - logger.debug("No entries found in /sys/block"); return null; } - logger.debug("Found " + entries.length + " entries in /sys/block"); - // 통합된 디바이스 수집으로 변경 collectAllLunDevicesUnified(names, texts, hasPartitions, scsiAddresses, scsiAddressCache, realToById); - - logger.debug("Final LUN device count: " + names.size()); for (int i = 0; i < names.size(); i++) { - logger.debug("LUN device " + i + ": " + names.get(i)); } return new ListHostLunDeviceAnswer(true, names, texts, hasPartitions, scsiAddresses); } catch (Exception e) { - logger.debug("Fast sysfs scan failed, falling back: " + e.getMessage()); return null; } } @@ -316,16 +311,16 @@ private ListHostLunDeviceAnswer listHostLunDevicesFast() { */ private void collectAllLunDevicesUnified(List names, List texts, List hasPartitions, List scsiAddresses, Map scsiAddressCache, - Map realToById) { - java.io.File sysBlock = new java.io.File("/sys/block"); - java.io.File[] entries = sysBlock.listFiles(); + Map realToById) { + File sysBlock = new File("/sys/block"); + File[] entries = sysBlock.listFiles(); if (entries == null) return; // 중복 제거를 위한 Set Set addedDevices = new HashSet<>(); // 1. 직접 디바이스 수집 - for (java.io.File entry : entries) { + for (File entry : entries) { String bname = entry.getName(); if (!(bname.startsWith("sd") || bname.startsWith("vd") || bname.startsWith("xvd") || bname.startsWith("nvme") || bname.startsWith("dm-"))) { @@ -352,7 +347,7 @@ private void collectAllLunDevicesUnified(List names, List texts, /** * 디바이스를 리스트에 추가하는 공통 메서드 */ - private void addDeviceToList(String devPath, String preferred, java.io.File entry, + private void addDeviceToList(String devPath, String preferred, File entry, List names, List texts, List hasPartitionsList, List scsiAddresses, Map scsiAddressCache, String bname) { StringBuilder info = new StringBuilder(); @@ -381,14 +376,12 @@ private void addDeviceToList(String devPath, String preferred, java.io.File entr String byIdName = preferred.substring(preferred.lastIndexOf('/') + 1); String displayName = devPath + " (" + byIdName + ")"; - logger.debug("Adding LUN device: " + displayName + " (path: " + preferred + ", hasPartitions: " + deviceHasPartitions + ")"); names.add(displayName); texts.add(info.toString()); hasPartitionsList.add(deviceHasPartitions); scsiAddresses.add(scsiAddr != null ? scsiAddr : ""); } else { // ID 값이 없는 경우 리스트에 추가하지 않음 - logger.debug("Skipping LUN device (no ID): " + devPath + " (preferred: " + preferred + ")"); } } @@ -425,7 +418,7 @@ private void collectMultipathDevicesUnified(List names, List tex } } } catch (Exception e) { - logger.debug("Error collecting multipath devices: " + e.getMessage()); + // Error collecting multipath devices } } @@ -460,14 +453,12 @@ private void addMultipathDeviceToList(String devicePath, String preferredName, String byIdName = preferredName.substring(preferredName.lastIndexOf('/') + 1); String displayName = devicePath + " (" + byIdName + ")"; - logger.debug("Adding multipath LUN device: " + displayName + " (path: " + preferredName + ", hasPartitions: " + hasPartition + ")"); names.add(displayName); texts.add(deviceInfo.toString()); hasPartitionsList.add(hasPartition); scsiAddresses.add(scsiAddress != null ? scsiAddress : ""); } else { // ID 값이 없는 경우 리스트에 추가하지 않음 - logger.debug("Skipping multipath LUN device (no ID): " + devicePath + " (preferred: " + preferredName + ")"); } } @@ -482,22 +473,22 @@ private String extractDmDeviceFromLine(String line) { } } - java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("dm-\\d+"); - java.util.regex.Matcher matcher = pattern.matcher(line); + Pattern pattern = Pattern.compile("dm-\\d+"); + Matcher matcher = pattern.matcher(line); if (matcher.find()) { return matcher.group(); } return null; } - private Map buildByIdReverseMap() { - Map map = new java.util.HashMap<>(); - java.nio.file.Path byIdDir = java.nio.file.Paths.get("/dev/disk/by-id"); + private Map buildByIdReverseMap() { + Map map = new HashMap<>(); + Path byIdDir = Path.of("/dev/disk/by-id"); try { - if (!java.nio.file.Files.isDirectory(byIdDir)) return map; - try (java.util.stream.Stream s = java.nio.file.Files.list(byIdDir)) { - s.filter(java.nio.file.Files::isSymbolicLink).forEach(p -> { - java.nio.file.Path rp = safeRealPath(p); + if (!Files.isDirectory(byIdDir)) return map; + try (Stream s = Files.list(byIdDir)) { + s.filter(Files::isSymbolicLink).forEach(p -> { + Path rp = safeRealPath(p); if (rp != null) { String byIdPath = byIdDir.resolve(p.getFileName()).toString(); map.put(rp, byIdPath); @@ -510,9 +501,9 @@ private Map buildByIdReverseMap() { return map; } - private String resolveById(Map realToById, String devicePath) { + private String resolveById(Map realToById, String devicePath) { try { - java.nio.file.Path real = java.nio.file.Paths.get(devicePath).toRealPath(); + Path real = Path.of(devicePath).toRealPath(); String byId = realToById.get(real); if (byId != null) { // LUN 디바이스는 전체 디스크를 사용해야 하므로 파티션 부분 제거 @@ -530,25 +521,22 @@ private String resolveById(Map realToById, String de } } - private boolean sysHasPartitions(java.io.File sysBlockEntry) { + private boolean sysHasPartitions(File sysBlockEntry) { try { String name = sysBlockEntry.getName(); - java.io.File[] children = sysBlockEntry.listFiles(); + File[] children = sysBlockEntry.listFiles(); if (children == null) return false; - logger.debug("Checking partitions for device: " + name); - for (java.io.File child : children) { + for (File child : children) { String childName = child.getName(); - logger.debug("Checking child: " + childName); // 파티션 디렉토리인지 확인 (예: sda1, sda2 등) if (childName.startsWith(name) && childName.length() > name.length()) { String suffix = childName.substring(name.length()); // 숫자로만 구성된 경우 파티션으로 간주 if (suffix.matches("\\d+")) { - java.io.File partFile = new java.io.File(child, "partition"); + File partFile = new File(child, "partition"); if (partFile.exists()) { - logger.debug("Found partition: " + childName); return true; } } @@ -557,12 +545,17 @@ private boolean sysHasPartitions(java.io.File sysBlockEntry) { // 추가로 lsblk 명령어로도 확인 (예외 처리 강화) try { + // 디바이스가 존재하는지 먼저 확인 + File deviceFile = new File("/dev/" + name); + if (!deviceFile.exists()) { + return false; + } Script lsblkCmd = new Script("/usr/bin/lsblk"); lsblkCmd.add("--json", "--paths", "--output", "NAME,TYPE", "/dev/" + name); OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); String result = lsblkCmd.execute(parser); - if (result == null && parser.getLines() != null) { + if (result == null && parser.getLines() != null && !parser.getLines().trim().isEmpty()) { try { JSONObject json = new JSONObject(parser.getLines()); JSONArray blockdevices = json.getJSONArray("blockdevices"); @@ -574,56 +567,53 @@ private boolean sysHasPartitions(java.io.File sysBlockEntry) { JSONObject child = jsonChildren.getJSONObject(i); String childType = child.optString("type", ""); if ("part".equals(childType)) { - logger.debug("Found partition via lsblk: " + child.optString("name", "")); return true; } } } } } catch (Exception e) { - logger.debug("Error parsing lsblk output: " + e.getMessage()); + // Error parsing lsblk output } } } catch (Exception e) { - logger.debug("Error executing lsblk command for device {}: {}", name, e.getMessage()); // lsblk 실패 시 sysfs 기반 결과만 사용 } - logger.debug("No partitions found for device: " + name); return false; } catch (Exception e) { - logger.debug("Error checking partitions for " + sysBlockEntry.getName() + ": " + e.getMessage()); + // Error checking partitions return false; } } - private String sysGetSizeHuman(java.io.File sysBlockEntry) { + private String sysGetSizeHuman(File sysBlockEntry) { try { - java.io.File sizeFile = new java.io.File(sysBlockEntry, "size"); + File sizeFile = new File(sysBlockEntry, "size"); if (!sizeFile.exists()) return null; - String content = new String(java.nio.file.Files.readAllBytes(sizeFile.toPath())).trim(); + String content = new String(Files.readAllBytes(sizeFile.toPath())).trim(); if (content.isEmpty()) return null; long sectors = Long.parseLong(content); double gib = (sectors * 512.0) / 1024 / 1024 / 1024; - return String.format(java.util.Locale.ROOT, "%.2fG", gib); + return String.format(Locale.ROOT, "%.2fG", gib); } catch (Exception ignore) { return null; } } private Map getScsiAddressesFromSysfs() { - Map map = new java.util.HashMap<>(); + Map map = new HashMap<>(); try { - java.io.File sysBlock = new java.io.File("/sys/block"); - java.io.File[] entries = sysBlock.listFiles(); + File sysBlock = new File("/sys/block"); + File[] entries = sysBlock.listFiles(); if (entries == null) return map; - for (java.io.File e : entries) { + for (File e : entries) { String name = e.getName(); if (!(name.startsWith("sd") || name.startsWith("vd") || name.startsWith("xvd"))) continue; - java.nio.file.Path devLink = java.nio.file.Paths.get(e.getAbsolutePath(), "device"); + Path devLink = Path.of(e.getAbsolutePath(), "device"); try { - java.nio.file.Path real = java.nio.file.Files.readSymbolicLink(devLink); - java.nio.file.Path resolved = devLink.getParent().resolve(real).normalize(); + Path real = Files.readSymbolicLink(devLink); + Path resolved = devLink.getParent().resolve(real).normalize(); String scsi = resolved.getFileName().toString(); map.put("/dev/" + name, scsi); } catch (Exception ignore) {} @@ -654,7 +644,6 @@ private void addLunDeviceRecursiveOptimized(JSONObject device, List name String byIdName = preferredName.substring(preferredName.lastIndexOf('/') + 1); String displayName = name + " (" + byIdName + ")"; - logger.debug("Adding LUN device: " + displayName + " (path: " + preferredName + ", hasPartitions: " + hasPartition + ")"); names.add(displayName); StringBuilder deviceInfo = new StringBuilder(); deviceInfo.append("TYPE: ").append(type); @@ -674,7 +663,6 @@ private void addLunDeviceRecursiveOptimized(JSONObject device, List name scsiAddresses.add(scsiAddress != null ? scsiAddress : ""); } else { // ID 값이 없는 경우 리스트에 추가하지 않음 - logger.debug("Skipping LUN device (no ID): " + name + " (preferred: " + preferredName + ")"); } } @@ -697,17 +685,17 @@ private String resolveDevicePathToById(String devicePath) { return devicePath; } - java.nio.file.Path device = java.nio.file.Paths.get(devicePath).toRealPath(); - java.nio.file.Path byIdDir = java.nio.file.Paths.get("/dev/disk/by-id"); + Path device = Path.of(devicePath).toRealPath(); + Path byIdDir = Path.of("/dev/disk/by-id"); - if (!java.nio.file.Files.isDirectory(byIdDir)) { + if (!Files.isDirectory(byIdDir)) { return devicePath; } - try (java.util.stream.Stream stream = java.nio.file.Files.list(byIdDir)) { - java.util.Optional firstMatch = stream - .filter(java.nio.file.Files::isSymbolicLink) - .map(p -> new java.util.AbstractMap.SimpleEntry<>(p, safeRealPath(p))) + try (Stream stream = Files.list(byIdDir)) { + Optional firstMatch = stream + .filter(Files::isSymbolicLink) + .map(p -> new AbstractMap.SimpleEntry<>(p, safeRealPath(p))) .filter(e -> e.getValue() != null && e.getValue().equals(device)) .map(e -> byIdDir.resolve(e.getKey().getFileName()).toString()) .findFirst(); @@ -727,11 +715,11 @@ private String resolveDevicePathToById(String devicePath) { } } - private java.nio.file.Path safeRealPath(java.nio.file.Path link) { + private Path safeRealPath(Path link) { try { - java.nio.file.Path target = java.nio.file.Files.readSymbolicLink(link); + Path target = Files.readSymbolicLink(link); // 상대 링크일 수 있음 - java.nio.file.Path resolved = link.getParent().resolve(target).normalize(); + Path resolved = link.getParent().resolve(target).normalize(); return resolved.toRealPath(); } catch (Exception e) { return null; @@ -824,7 +812,7 @@ private Set getDmDevices() { } } } else { - logger.warn("Failed to execute multipath -l command: " + result); + // Failed to execute multipath -l command } } catch (Exception e) { @@ -925,7 +913,7 @@ private String getSymbolicLinkTarget(File file) { Path target = Files.readSymbolicLink(file.toPath()); return target.toString(); } catch (Exception e) { - logger.debug("Error reading symbolic link " + file.getPath() + ": " + e.getMessage()); + // Error reading symbolic link return null; } } @@ -1029,7 +1017,7 @@ private String resolveDmUuidToDevice(String dmUuid) { } } } catch (Exception e) { - logger.debug("Failed to resolve dm-uuid {}: {}", dmUuid, e.getMessage()); + // Failed to resolve dm-uuid } return null; } @@ -1050,7 +1038,7 @@ private String resolveByIdToDevice(String byIdPath) { return parser.getLines().trim(); } } catch (Exception e) { - logger.debug("Failed to resolve by-id path {}: {}", byIdPath, e.getMessage()); + // Failed to resolve by-id path } return null; } @@ -1074,7 +1062,6 @@ private String findSafeTargetDevForVm(String devicePath) { } // 모든 후보가 사용 중이면 sdd 반환 (fallback) - logger.warn("All target dev candidates are in use, using sdd as fallback for device: {}", devicePath); return "sdd"; } catch (Exception e) { @@ -1120,13 +1107,12 @@ private Set getCurrentlyUsedTargetDevs() { } } } catch (Exception e) { - logger.debug("Error checking target devs for VM {}: {}", vmName, e.getMessage()); + // Error checking target devs for VM } } } } - logger.debug("Currently used target devs: {}", usedDevs); return usedDevs; } catch (Exception e) { @@ -1201,7 +1187,7 @@ private String extractScsiAddressFromDevice(String devicePath) { } } } catch (Exception e) { - logger.debug("Failed to extract SCSI address from device {}: {}", devicePath, e.getMessage()); + // Failed to extract SCSI address from device } return null; @@ -1308,6 +1294,12 @@ private String getTargetDeviceName(String devicePath) { */ private boolean hasPartitionRecursiveForDevice(String devicePath) { try { + // 디바이스가 존재하는지 먼저 확인 + File deviceFile = new File(devicePath); + if (!deviceFile.exists()) { + return false; + } + Script cmd = new Script("/usr/bin/lsblk"); cmd.add("--json", "--paths", "--output", "NAME,TYPE", devicePath); OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); @@ -1315,11 +1307,11 @@ private boolean hasPartitionRecursiveForDevice(String devicePath) { try { result = cmd.execute(parser); } catch (Exception e) { - logger.debug("Error executing lsblk command for device {}: {}", devicePath, e.getMessage()); + // Error executing lsblk command for device return false; } - if (result == null && parser.getLines() != null) { + if (result == null && parser.getLines() != null && !parser.getLines().trim().isEmpty()) { try { JSONObject json = new JSONObject(parser.getLines()); JSONArray blockdevices = json.getJSONArray("blockdevices"); @@ -1329,12 +1321,12 @@ private boolean hasPartitionRecursiveForDevice(String devicePath) { return hasPartitionRecursive(device); } } catch (Exception e) { - logger.debug("Error parsing lsblk JSON output for device {}: {}", devicePath, e.getMessage()); + // Error parsing lsblk JSON output for device } } } catch (Exception e) { - logger.debug("Error executing lsblk command for device {}: {}", devicePath, e.getMessage()); + // Error executing lsblk command for device } return false; @@ -1345,12 +1337,18 @@ private boolean hasPartitionRecursiveForDevice(String devicePath) { */ private String getDeviceSize(String devicePath) { try { + // 디바이스가 존재하는지 먼저 확인 + File deviceFile = new File(devicePath); + if (!deviceFile.exists()) { + return null; + } + Script cmd = new Script("/usr/bin/lsblk"); cmd.add("--json", "--paths", "--output", "NAME,SIZE", devicePath); OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); String result = cmd.execute(parser); - if (result == null) { + if (result == null && parser.getLines() != null && !parser.getLines().trim().isEmpty()) { JSONObject json = new JSONObject(parser.getLines()); JSONArray blockdevices = json.getJSONArray("blockdevices"); @@ -1361,7 +1359,7 @@ private String getDeviceSize(String devicePath) { } } catch (Exception e) { - logger.debug("Error getting size for device " + devicePath + ": " + e.getMessage()); + // Error getting size for device } return null; @@ -1377,16 +1375,13 @@ private boolean hasPartitionRecursive(JSONObject device) { if ("lvm".equals(deviceType) || deviceName.startsWith("/dev/mapper/")) { if (deviceName.contains("ceph--") && deviceName.contains("--osd--block--")) { - logger.debug("Ceph OSD device, no partitions: " + deviceName); return false; } - logger.debug("LVM device, has partitions: " + deviceName); return true; } if (device.has("children")) { JSONArray children = device.getJSONArray("children"); - logger.debug("Device has " + children.length() + " children: " + deviceName); for (int i = 0; i < children.length(); i++) { JSONObject child = children.getJSONObject(i); @@ -1400,7 +1395,6 @@ private boolean hasPartitionRecursive(JSONObject device) { // LVM 볼륨이 있으면 true if ("lvm".equals(childType)) { - logger.debug("Found LVM child: " + childName); return true; } @@ -1409,7 +1403,7 @@ private boolean hasPartitionRecursive(JSONObject device) { } } } else { - logger.debug("Device has no children: " + deviceName); + // Device has no children } return false; } @@ -1444,7 +1438,7 @@ private Map getScsiAddressesBatch() { } } } catch (Exception e) { - logger.debug("Error executing lsscsi command in batch: {}", e.getMessage()); + // Error executing lsscsi command in batch } // sysfs에서 추가 정보 수집 (lsscsi에서 찾지 못한 디바이스들) @@ -1472,12 +1466,12 @@ private Map getScsiAddressesBatch() { } } } - } catch (Exception e) { - logger.debug("Error reading sysfs SCSI addresses: " + e.getMessage()); - } + } catch (Exception e) { + // Error reading sysfs SCSI addresses + } } catch (Exception e) { - logger.debug("Error getting SCSI addresses batch: " + e.getMessage()); + // Error getting SCSI addresses batch } return scsiAddressMap; @@ -1495,7 +1489,7 @@ private Set getDevicesInUseBatch() { OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); String result = listCommand.execute(parser); - if (result == null && parser.getLines() != null) { + if (result == null && parser.getLines() != null && !parser.getLines().trim().isEmpty()) { String[] vmIds = parser.getLines().split("\\n"); for (String vmId : vmIds) { vmId = vmId.trim(); @@ -1520,7 +1514,7 @@ private Set getDevicesInUseBatch() { } } } catch (Exception e) { - logger.debug("Error processing VM " + vmId + ": " + e.getMessage()); + // Error processing VM } } } @@ -1544,11 +1538,11 @@ private Set getDevicesInUseBatch() { } } } catch (Exception e) { - logger.debug("Error getting mounted devices: " + e.getMessage()); + // Error getting mounted devices } } catch (Exception e) { - logger.debug("Error getting devices in use batch: " + e.getMessage()); + // Error getting devices in use batch } return devicesInUse; @@ -1564,11 +1558,10 @@ private Set getDevicesInUseBatch(long timeoutMs) { } catch (java.util.concurrent.TimeoutException te) { timedOut.set(true); fut.cancel(true); - logger.warn("getDevicesInUseBatch timed out after " + timeoutMs + "ms; returning partial/empty set"); return new HashSet<>(); } } catch (Exception e) { - logger.debug("getDevicesInUseBatch with timeout failed: " + e.getMessage()); + // getDevicesInUseBatch with timeout failed return new HashSet<>(); } finally { es.shutdownNow(); @@ -1580,7 +1573,6 @@ private String getScsiAddress(String deviceName) { try { // Ceph OSD 디바이스인지 확인 if (deviceName.contains("ceph--") && deviceName.contains("--osd--block--")) { - logger.debug("Ceph OSD device detected: {}", deviceName); return generateVirtualScsiAddressForCeph(deviceName); } @@ -1597,7 +1589,7 @@ private String getScsiAddress(String deviceName) { return scsiAddress; } } catch (Exception e) { - logger.debug("Error reading SCSI device file {}: {}", scsiDevicePath, e.getMessage()); + // Error reading SCSI device file } try { @@ -1620,7 +1612,7 @@ private String getScsiAddress(String deviceName) { } } } catch (Exception e) { - logger.debug("Error executing lsscsi command for device {}: {}", deviceName, e.getMessage()); + // Error executing lsscsi command for device } return null; @@ -1716,7 +1708,7 @@ private String findVhbaDeviceByWwnn(String wwnn) { OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); String result = cmd.execute(parser); - if (result == null && parser.getLines() != null) { + if (result == null && parser.getLines() != null && !parser.getLines().trim().isEmpty()) { String[] devices = parser.getLines().split("\\n"); for (String device : devices) { device = device.trim(); @@ -1805,7 +1797,7 @@ private boolean isLunDeviceAllocatedToVm(String deviceName) { OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); String result = listCommand.execute(parser); - if (result == null && parser.getLines() != null) { + if (result == null && parser.getLines() != null && !parser.getLines().trim().isEmpty()) { boolean isAllocated = parser.getLines().trim().equals("allocated"); if (isAllocated) { } @@ -1829,7 +1821,7 @@ public Answer listHostScsiDevices(Command command) { if (fast != null && fast.getResult()) { return fast; } - Map realToById = buildByIdReverseMap(); + Map realToById = buildByIdReverseMap(); Script cmd = new Script("/usr/bin/lsscsi"); cmd.add("-g"); @@ -1883,10 +1875,10 @@ private com.cloud.agent.api.ListHostScsiDeviceAnswer listHostScsiDevicesFast() { // LUN과 동일한 최적화: 배치로 정보 수집 Map scsiAddressCache = getScsiAddressesBatch(); - Map realToById = buildByIdReverseMap(); + Map realToById = buildByIdReverseMap(); - java.io.File sysBlock = new java.io.File("/sys/block"); - java.io.File[] entries = sysBlock.listFiles(); + File sysBlock = new File("/sys/block"); + File[] entries = sysBlock.listFiles(); if (entries == null) { return null; } @@ -1894,12 +1886,12 @@ private com.cloud.agent.api.ListHostScsiDeviceAnswer listHostScsiDevicesFast() { // 통합된 디바이스 수집 (LUN과 동일한 패턴) collectAllScsiDevicesUnified(names, texts, hasPartitions, scsiAddressCache, realToById); for (int i = 0; i < names.size(); i++) { - logger.debug("SCSI device " + i + ": " + names.get(i)); + // SCSI device } return new com.cloud.agent.api.ListHostScsiDeviceAnswer(true, names, texts, hasPartitions); } catch (Exception ex) { - logger.debug("Fast SCSI sysfs scan failed: " + ex.getMessage()); + // Fast SCSI sysfs scan failed return null; } } @@ -1908,13 +1900,13 @@ private com.cloud.agent.api.ListHostScsiDeviceAnswer listHostScsiDevicesFast() { * 모든 SCSI 디바이스를 통합적으로 수집하는 메서드 (LUN과 동일한 최적화) */ private void collectAllScsiDevicesUnified(List names, List texts, List hasPartitions, - Map scsiAddressCache, Map realToById) { + Map scsiAddressCache, Map realToById) { try { - java.io.File sysBlock = new java.io.File("/sys/block"); - java.io.File[] entries = sysBlock.listFiles(); + File sysBlock = new File("/sys/block"); + File[] entries = sysBlock.listFiles(); if (entries == null) return; - for (java.io.File e : entries) { + for (File e : entries) { String bname = e.getName(); if (!(bname.startsWith("sd") || bname.startsWith("vd") || bname.startsWith("xvd"))) { continue; @@ -1925,8 +1917,8 @@ private void collectAllScsiDevicesUnified(List names, List texts // sg 매핑 String sg = null; try { - java.io.File sgDir = new java.io.File(e, "device/scsi_generic"); - java.io.File[] sgs = sgDir.listFiles(); + File sgDir = new File(e, "device/scsi_generic"); + File[] sgs = sgDir.listFiles(); if (sgs != null && sgs.length > 0) { sg = "/dev/" + sgs[0].getName(); } @@ -1936,17 +1928,17 @@ private void collectAllScsiDevicesUnified(List names, List texts String scsiAddress = scsiAddressCache.get(dev); if (scsiAddress == null) { try { - java.nio.file.Path devLink = java.nio.file.Paths.get(e.getAbsolutePath(), "device"); - java.nio.file.Path real = java.nio.file.Files.readSymbolicLink(devLink); - java.nio.file.Path resolved = devLink.getParent().resolve(real).normalize(); + Path devLink = Path.of(e.getAbsolutePath(), "device"); + Path real = Files.readSymbolicLink(devLink); + Path resolved = devLink.getParent().resolve(real).normalize(); scsiAddress = resolved.getFileName().toString(); } catch (Exception ignore) {} } // 벤더/모델/리비전 (배치 읽기) - String vendor = readFirstLineQuiet(new java.io.File(e, "device/vendor")); - String model = readFirstLineQuiet(new java.io.File(e, "device/model")); - String rev = readFirstLineQuiet(new java.io.File(e, "device/rev")); + String vendor = readFirstLineQuiet(new File(e, "device/vendor")); + String model = readFirstLineQuiet(new File(e, "device/model")); + String rev = readFirstLineQuiet(new File(e, "device/rev")); String byId = resolveById(realToById, dev); @@ -1971,14 +1963,14 @@ private void collectAllScsiDevicesUnified(List names, List texts hasPartitions.add(false); } } catch (Exception e) { - logger.debug("Error collecting SCSI devices unified: " + e.getMessage()); + // Error collecting SCSI devices unified } } - private String readFirstLineQuiet(java.io.File f) { + private String readFirstLineQuiet(File f) { try { if (!f.exists()) return null; - String s = new String(java.nio.file.Files.readAllBytes(f.toPath())).trim(); + String s = new String(Files.readAllBytes(f.toPath())).trim(); return s.isEmpty() ? null : s; } catch (Exception ignore) { return null; @@ -2028,13 +2020,12 @@ protected Answer listHostHbaDevices(Command command) { // 해당 scsi_host에 대한 SCSI 주소 정보 저장 if (!scsiAddressMap.containsKey(scsiHostName)) { scsiAddressMap.put(scsiHostName, scsiAddress); - logger.debug("Mapped " + scsiHostName + " to SCSI address: " + scsiAddress); } } } } } catch (Exception e) { - logger.debug("SCSI 디바이스 조회 중 오류 발생: " + e.getMessage()); + // SCSI 디바이스 조회 중 오류 발생 } // 2. virsh nodedev-list --cap vports로 vHBA 지원 물리 HBA 조회 (화면에 표시) @@ -2065,17 +2056,17 @@ protected Answer listHostHbaDevices(Command command) { } } } catch (Exception e) { - logger.debug("vHBA 지원 HBA 조회 중 오류 발생: " + e.getMessage()); + // vHBA 지원 HBA 조회 중 오류 발생 } // 3. virsh nodedev-list | grep vhba로 vHBA 추가 try { Script vhbaCommand = new Script("/bin/bash"); vhbaCommand.add("-c"); - vhbaCommand.add("virsh nodedev-list | grep vhba"); + vhbaCommand.add("virsh nodedev-list | grep vhba || true"); OutputInterpreter.AllLinesParser vhbaParser = new OutputInterpreter.AllLinesParser(); String vhbaResult = vhbaCommand.execute(vhbaParser); - if (vhbaResult == null && vhbaParser.getLines() != null) { + if (vhbaResult == null && vhbaParser.getLines() != null && !vhbaParser.getLines().trim().isEmpty()) { String[] vhbaLines = vhbaParser.getLines().split("\\n"); for (String vhbaLine : vhbaLines) { String vhbaName = vhbaLine.trim(); @@ -2132,7 +2123,7 @@ protected Answer listHostHbaDevices(Command command) { } } } catch (Exception e) { - logger.debug("vHBA 조회 중 오류 발생: " + e.getMessage()); + // vHBA 조회 중 오류 발생 } return new ListHostHbaDeviceAnswer(true, hostDevicesNames, hostDevicesText, deviceTypes, parentHbaNames); } @@ -2274,7 +2265,7 @@ public Answer createHostVHbaDevice(CreateVhbaDeviceCommand command, String paren try (FileWriter writer = new FileWriter(backupFilePath)) { writer.write(actualVhbaXml); } catch (IOException e) { - logger.warn("vHBA 백업 파일 생성 실패: " + e.getMessage()); + // vHBA 백업 파일 생성 실패 } } else { } @@ -2344,7 +2335,7 @@ public Answer deleteHostVHbaDevice(DeleteVhbaDeviceCommand command) { if (backupFile.exists()) { if (backupFile.delete()) { } else { - logger.warn("vHBA 백업 파일 삭제 실패: " + backupFilePath); + // vHBA 백업 파일 삭제 실패 } } else { } @@ -2375,12 +2366,12 @@ private boolean isVhbaAllocatedToVm(String vhbaName) { OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); String result = checkCommand.execute(parser); - if (result == null && parser.getLines() != null) { + if (result == null && parser.getLines() != null && !parser.getLines().trim().isEmpty()) { return parser.getLines().trim().equals("allocated"); } return false; } catch (Exception e) { - logger.debug("vHBA 할당 상태 확인 중 오류: " + e.getMessage()); + // vHBA 할당 상태 확인 중 오류 return false; } } @@ -2394,7 +2385,7 @@ private boolean validateParentHbaFromVports(String parentHbaName) { OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); String result = vportsCommand.execute(parser); - if (result == null && parser.getLines() != null) { + if (result == null && parser.getLines() != null && !parser.getLines().trim().isEmpty()) { String[] lines = parser.getLines().split("\\n"); for (String line : lines) { String hbaName = line.trim(); @@ -2404,10 +2395,8 @@ private boolean validateParentHbaFromVports(String parentHbaName) { } } - logger.warn("부모 HBA가 vports 지원 목록에 없음: " + parentHbaName); return false; } catch (Exception e) { - logger.debug("부모 HBA vports 검증 중 오류: " + e.getMessage()); return false; } } @@ -2430,7 +2419,6 @@ private String extractCreatedDeviceNameFromOutput(String output) { } } - logger.warn("생성된 디바이스명을 찾을 수 없음. 출력: " + output); return null; } @@ -2443,13 +2431,13 @@ private boolean validateCreatedVhba(String deviceName) { OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); String result = validateCommand.execute(parser); - if (result == null && parser.getLines() != null) { + if (result == null && parser.getLines() != null && !parser.getLines().trim().isEmpty()) { String count = parser.getLines().trim(); return !count.equals("0"); } return false; } catch (Exception e) { - logger.debug("생성된 vHBA 검증 중 오류: " + e.getMessage()); + // 생성된 vHBA 검증 중 오류 return false; } } @@ -2499,17 +2487,17 @@ protected Answer listHostVHbaDevices(Command command) { } } } catch (Exception e) { - logger.debug("특정 물리 HBA vHBA 조회 중 오류: " + e.getMessage()); + // 특정 물리 HBA vHBA 조회 중 오류 } } else { try { Script scsiHostCommand = new Script("/bin/bash"); scsiHostCommand.add("-c"); - scsiHostCommand.add("virsh nodedev-list | grep scsi_host"); + scsiHostCommand.add("virsh nodedev-list | grep scsi_host || true"); OutputInterpreter.AllLinesParser scsiHostParser = new OutputInterpreter.AllLinesParser(); String scsiHostResult = scsiHostCommand.execute(scsiHostParser); - if (scsiHostResult == null && scsiHostParser.getLines() != null) { + if (scsiHostResult == null && scsiHostParser.getLines() != null && !scsiHostParser.getLines().trim().isEmpty()) { String[] scsiHostLines = scsiHostParser.getLines().split("\\n"); for (String scsiHostLine : scsiHostLines) { @@ -2542,13 +2530,12 @@ protected Answer listHostVHbaDevices(Command command) { String vhbaName = extractVhbaNameFromPath(vhbaPath); if (vhbaName != null) { vhbaNames.add(vhbaName); - logger.debug("fc_remote_ports에서 발견된 vHBA: " + vhbaName); } } } } } catch (Exception e) { - logger.debug("fc_remote_ports 조회 중 오류: " + e.getMessage()); + // fc_remote_ports 조회 중 오류 } } @@ -2599,11 +2586,11 @@ protected Answer listHostVHbaDevices(Command command) { // vHBA 이름으로 검색 Script scsiAddressCommand = new Script("/bin/bash"); scsiAddressCommand.add("-c"); - scsiAddressCommand.add("lsscsi | grep -E '\\[.*:.*:.*:.*\\].*" + vhbaName + "' | head -1"); + scsiAddressCommand.add("lsscsi | grep -E '\\[.*:.*:.*:.*\\].*" + vhbaName + "' | head -1 || true"); OutputInterpreter.AllLinesParser scsiAddressParser = new OutputInterpreter.AllLinesParser(); String scsiAddressResult = scsiAddressCommand.execute(scsiAddressParser); - if (scsiAddressResult == null && scsiAddressParser.getLines() != null) { + if (scsiAddressResult == null && scsiAddressParser.getLines() != null && !scsiAddressParser.getLines().trim().isEmpty()) { String scsiLine = scsiAddressParser.getLines().trim(); if (!scsiLine.isEmpty()) { // lsscsi 출력에서 SCSI 주소 추출: [18:0:0:0] -> 18:0:0:0 @@ -2690,11 +2677,11 @@ protected Answer listHostVHbaDevices(Command command) { // vHBA 상태 확인 Script statusCommand = new Script("/bin/bash"); statusCommand.add("-c"); - statusCommand.add("virsh nodedev-info " + vhbaName + " | grep State"); + statusCommand.add("virsh nodedev-info " + vhbaName + " | grep State || true"); OutputInterpreter.AllLinesParser statusParser = new OutputInterpreter.AllLinesParser(); String statusResult = statusCommand.execute(statusParser); - if (statusResult == null && statusParser.getLines() != null) { + if (statusResult == null && statusParser.getLines() != null && !statusParser.getLines().trim().isEmpty()) { String statusLine = statusParser.getLines().trim(); if (statusLine.contains("State:")) { status = statusLine.replaceAll(".*State:\\s*([^\\s]+).*", "$1").trim(); @@ -2725,13 +2712,13 @@ private boolean isVhbaDevice(String deviceName) { OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); String result = checkCommand.execute(parser); - if (result == null && parser.getLines() != null) { + if (result == null && parser.getLines() != null && !parser.getLines().trim().isEmpty()) { String count = parser.getLines().trim(); return !count.equals("0"); } return false; } catch (Exception e) { - logger.debug("vHBA 확인 중 오류: " + e.getMessage()); + // vHBA 확인 중 오류 return false; } } @@ -2746,7 +2733,7 @@ private String extractVhbaNameFromPath(String path) { OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); String result = extractCommand.execute(parser); - if (result == null && parser.getLines() != null) { + if (result == null && parser.getLines() != null && !parser.getLines().trim().isEmpty()) { String scsiHostPath = parser.getLines().trim(); if (!scsiHostPath.isEmpty()) { return scsiHostPath.substring(scsiHostPath.lastIndexOf('/') + 1); @@ -2754,7 +2741,7 @@ private String extractVhbaNameFromPath(String path) { } return null; } catch (Exception e) { - logger.debug("vHBA 이름 추출 중 오류: " + e.getMessage()); + // vHBA 이름 추출 중 오류 return null; } } @@ -2771,7 +2758,7 @@ protected Answer listVhbaCapableHbas(Command command) { OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); String result = vportsCommand.execute(parser); - if (result == null && parser.getLines() != null) { + if (result == null && parser.getLines() != null && !parser.getLines().trim().isEmpty()) { String[] lines = parser.getLines().split("\\n"); for (String line : lines) { String hbaName = line.trim(); @@ -2822,7 +2809,7 @@ protected Answer listVhbaCapableHbas(Command command) { } } } catch (Exception e) { - logger.debug("vHBA 지원 HBA 조회 중 오류 발생: " + e.getMessage()); + // vHBA 지원 HBA 조회 중 오류 발생 } return new ListHostHbaDeviceAnswer(true, hostDevicesNames, hostDevicesText); @@ -3172,7 +3159,7 @@ protected Answer updateHostUsbDevices(Command command, String vmName, String xml virshCmd.add("attach-device", vmName, usbXmlPath); } else { if (!isUsbDeviceActuallyAttachedToVm(vmName, xmlConfig)) { - logger.warn("USB device is not actually attached to VM: {}. Skipping detach operation.", vmName); + // USB device is not actually attached to VM. Skipping detach operation. return new UpdateHostUsbDeviceAnswer(true, vmName, xmlConfig, isAttach); } virshCmd.add("detach-device", vmName, usbXmlPath); @@ -3187,7 +3174,6 @@ protected Answer updateHostUsbDevices(Command command, String vmName, String xml return new UpdateHostUsbDeviceAnswer(false, vmName, xmlConfig, isAttach); } - String action = isAttach ? "attached to" : "detached from"; return new UpdateHostUsbDeviceAnswer(true, vmName, xmlConfig, isAttach); } catch (Exception e) { @@ -3230,7 +3216,6 @@ protected Answer updateHostLunDevices(Command command, String vmName, String xml if (devicePath != null && isAttach) { // LUN과 SCSI 간 상호 배타적 할당 검증 if (isDeviceAllocatedInOtherType(devicePath, vmName, "LUN")) { - logger.warn("Device {} is already allocated as SCSI device in another VM", devicePath); return new UpdateHostLunDeviceAnswer(false, "Device is already allocated as SCSI device in another VM. Please remove it from SCSI allocation first."); } @@ -3274,15 +3259,11 @@ protected Answer updateHostLunDevices(Command command, String vmName, String xml if (baseGuess != null) { String altById = findExistingByIdForBaseDevice(baseGuess); - if (altById != null) { - xmlConfig = xmlConfig.replace(devicePath, altById); - devicePath = altById; - } else { - logger.warn("No alternative by-id found for base: {}", baseGuess); - } - } else { - logger.warn("Could not extract baseGuess from XML config"); + if (altById != null) { + xmlConfig = xmlConfig.replace(devicePath, altById); + devicePath = altById; } + } } } catch (Exception e) { @@ -3351,8 +3332,7 @@ protected Answer updateHostLunDevices(Command command, String vmName, String xml String scsiResult = scsiVirshCmd.execute(); if (scsiResult != null) { - logger.warn("Failed to {} mapped SCSI device {}: {}", - isAttach ? "attach" : "detach", mappedScsiDevice, scsiResult); + // Failed to attach/detach mapped SCSI device } else { } @@ -3360,11 +3340,10 @@ protected Answer updateHostLunDevices(Command command, String vmName, String xml new java.io.File(scsiXmlPath).delete(); } catch (Exception e) { - logger.warn("Error processing mapped SCSI device {}: {}", mappedScsiDevice, e.getMessage()); + // Error processing mapped SCSI device } } - String action = isAttach ? "attached to" : "detached from"; return new UpdateHostLunDeviceAnswer(true, vmName, xmlConfig, isAttach); } catch (Exception e) { @@ -3393,7 +3372,6 @@ protected Answer updateHostHbaDevices(Command command, String vmName, String xml } else { // detach 시도 전에 실제 VM에 해당 디바이스가 붙어있는지 확인 if (!isDeviceActuallyAttachedToVm(vmName, xmlConfig)) { - logger.warn("Device is not actually attached to VM: {}. Skipping detach operation.", vmName); // 실제로 붙어있지 않아도 성공으로 처리 (DB 상태만 정리) return new UpdateHostHbaDeviceAnswer(true, vmName, xmlConfig, isAttach); } @@ -3409,7 +3387,6 @@ protected Answer updateHostHbaDevices(Command command, String vmName, String xml return new UpdateHostHbaDeviceAnswer(false, vmName, xmlConfig, isAttach); } - String action = isAttach ? "attached to" : "detached from"; return new UpdateHostHbaDeviceAnswer(true, vmName, xmlConfig, isAttach); } catch (Exception e) { @@ -3439,7 +3416,6 @@ protected Answer updateHostVHbaDevices(Command command, String vmName, String xm } else { // detach 시도 전에 실제 VM에 해당 디바이스가 붙어있는지 확인 if (!isVhbaDeviceActuallyAttachedToVm(vmName, xmlConfig)) { - logger.warn("vHBA device is not actually attached to VM: {}. Skipping detach operation.", vmName); // 실제로 붙어있지 않아도 성공으로 처리 (DB 상태만 정리) return new UpdateHostVhbaDeviceAnswer(true, vhbaDeviceName, vmName, xmlConfig, isAttach); } @@ -3478,7 +3454,6 @@ protected Answer updateHostScsiDevices(UpdateHostScsiDeviceCommand command, Stri // SCSI와 LUN 간 상호 배타적 할당 검증 if (isAttach && isDeviceAllocatedInOtherType(devicePath, vmName, "SCSI")) { - logger.warn("Device {} is already allocated as LUN device in another VM", devicePath); return new UpdateHostScsiDeviceAnswer(false, "Device is already allocated as LUN device in another VM. Please remove it from LUN allocation first."); } @@ -3498,7 +3473,6 @@ protected Answer updateHostScsiDevices(UpdateHostScsiDeviceCommand command, Stri virshCmd.add("attach-device", vmName, scsiXmlPath); } else { if (!isScsiDeviceActuallyAttachedToVm(vmName, xmlConfig)) { - logger.warn("SCSI device is not actually attached to VM: {}. Skipping detach operation.", vmName); return new UpdateHostScsiDeviceAnswer(true, vmName, xmlConfig, isAttach); } virshCmd.add("detach-device", vmName, scsiXmlPath); @@ -3511,7 +3485,6 @@ protected Answer updateHostScsiDevices(UpdateHostScsiDeviceCommand command, Stri String action = isAttach ? "attach" : "detach"; String lower = result.toLowerCase(); if (!isAttach && (lower.contains("device not found") || lower.contains("host scsi device") && lower.contains("not found"))) { - logger.warn("virsh reported device not found during detach; treating as success. Details: {}", result); return new UpdateHostScsiDeviceAnswer(true, vmName, xmlConfig, isAttach); } logger.error("Failed to {} SCSI device: {}", action, result); @@ -3535,22 +3508,15 @@ protected Answer updateHostScsiDevices(UpdateHostScsiDeviceCommand command, Stri lunVirshCmd.add("detach-device", vmName, lunXmlPath); } - String lunResult = lunVirshCmd.execute(); - if (lunResult != null) { - logger.warn("Failed to {} mapped LUN device {}: {}", - isAttach ? "attach" : "detach", mappedLunDevice, lunResult); - } else { - } - + lunVirshCmd.execute(); // 임시 파일 정리 new java.io.File(lunXmlPath).delete(); } catch (Exception e) { - logger.warn("Error processing mapped LUN device {}: {}", mappedLunDevice, e.getMessage()); + logger.error("Error processing mapped LUN device {}: {}", mappedLunDevice, e.getMessage()); } } - String action = isAttach ? "attached to" : "detached from"; return new UpdateHostScsiDeviceAnswer(true, vmName, xmlConfig, isAttach); } catch (Exception e) { @@ -3573,7 +3539,6 @@ private boolean isDeviceActuallyAttachedToVm(String vmName, String xmlConfig) { // 해당 XML 파일이 존재하는지 확인 File xmlFile = new File(hbaXmlPath); if (!xmlFile.exists()) { - logger.warn("XML file does not exist for device check: {}", hbaXmlPath); return false; } @@ -3584,20 +3549,17 @@ private boolean isDeviceActuallyAttachedToVm(String vmName, String xmlConfig) { String result = dumpCommand.execute(parser); if (result != null) { - logger.warn("Failed to get VM XML for device check: {}", result); return false; } String vmXml = parser.getLines(); if (vmXml == null || vmXml.isEmpty()) { - logger.warn("Empty VM XML for device check"); return false; } // XML에서 adapter name 추출 String adapterName = extractAdapterNameFromXml(xmlConfig); if (adapterName == null) { - logger.warn("Could not extract adapter name from XML config"); return false; } @@ -3752,16 +3714,16 @@ private boolean isDeviceExists(String devicePath) { } try { - java.io.File device = new java.io.File(devicePath); + File device = new File(devicePath); if (!device.exists()) { return false; } // 심볼릭 링크인 경우 실제 타겟 확인 - if (java.nio.file.Files.isSymbolicLink(device.toPath())) { + if (Files.isSymbolicLink(device.toPath())) { try { - java.nio.file.Path realPath = device.toPath().toRealPath(); - java.io.File realDevice = realPath.toFile(); + Path realPath = device.toPath().toRealPath(); + File realDevice = realPath.toFile(); if (!realDevice.exists()) { return false; } @@ -3778,7 +3740,7 @@ private boolean isDeviceExists(String devicePath) { OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); String result = statCommand.execute(parser); - if (result == null && parser.getLines() != null) { + if (result == null && parser.getLines() != null && !parser.getLines().trim().isEmpty()) { String fileType = parser.getLines().trim(); return fileType.contains("block special file"); } @@ -3795,7 +3757,7 @@ private boolean isDeviceExists(String devicePath) { private boolean isPartitionDevice(String devicePath) { try { // /dev/sda1, /dev/sdb2 등 파티션 번호가 있는지 확인 - String deviceName = new java.io.File(devicePath).getName(); + String deviceName = new File(devicePath).getName(); // 숫자로 끝나는 디바이스명이 파티션인지 확인 if (deviceName.matches(".*\\d+$")) { @@ -3833,7 +3795,7 @@ private boolean isLunDeviceAllocatedToOtherVm(String devicePath, String currentV OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); String result = listCommand.execute(parser); - if (result == null && parser.getLines() != null) { + if (result == null && parser.getLines() != null && !parser.getLines().trim().isEmpty()) { return parser.getLines().trim().equals("allocated"); } return false; @@ -3904,7 +3866,7 @@ private boolean isDeviceReadOnly(String devicePath) { OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); String result = roCommand.execute(parser); - if (result == null && parser.getLines() != null) { + if (result == null && parser.getLines() != null && !parser.getLines().trim().isEmpty()) { String roValue = parser.getLines().trim(); return "1".equals(roValue); } @@ -3923,7 +3885,7 @@ private long getDeviceSizeBytes(String devicePath) { OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); String result = sizeCommand.execute(parser); - if (result == null && parser.getLines() != null) { + if (result == null && parser.getLines() != null && !parser.getLines().trim().isEmpty()) { String sizeStr = parser.getLines().trim(); return Long.parseLong(sizeStr); } @@ -3946,7 +3908,6 @@ private boolean isLunDeviceActuallyAttachedToVm(String vmName, String xmlConfig) // 해당 XML 파일이 존재하는지 확인 File xmlFile = new File(lunXmlPath); if (!xmlFile.exists()) { - logger.warn("XML file does not exist for device check: {}", lunXmlPath); return false; } @@ -3957,20 +3918,17 @@ private boolean isLunDeviceActuallyAttachedToVm(String vmName, String xmlConfig) String result = dumpCommand.execute(parser); if (result != null) { - logger.warn("Failed to get VM XML for device check: {}", result); return false; } String vmXml = parser.getLines(); if (vmXml == null || vmXml.isEmpty()) { - logger.warn("Empty VM XML for device check"); return false; } // XML에서 source dev 추출 String sourceDev = extractDeviceNameFromLunXml(xmlConfig); if (sourceDev == null) { - logger.warn("Could not extract source dev from XML config"); return false; } @@ -4014,7 +3972,6 @@ private boolean isScsiDeviceActuallyAttachedToVm(String vmName, String xmlConfig // 해당 XML 파일이 존재하는지 확인 File xmlFile = new File(scsiXmlPath); if (!xmlFile.exists()) { - logger.warn("XML file does not exist for device check: {}", scsiXmlPath); return false; } @@ -4025,20 +3982,17 @@ private boolean isScsiDeviceActuallyAttachedToVm(String vmName, String xmlConfig String result = dumpCommand.execute(parser); if (result != null) { - logger.warn("Failed to get VM XML for device check: {}", result); return false; } String vmXml = parser.getLines(); if (vmXml == null || vmXml.isEmpty()) { - logger.warn("Empty VM XML for device check"); return false; } // XML에서 adapter name 추출 String adapterName = extractDeviceNameFromScsiXml(xmlConfig); if (adapterName == null) { - logger.warn("Could not extract adapter name from XML config"); return false; } @@ -4071,7 +4025,7 @@ private String extractDeviceNameFromVhbaXml(String xmlConfig) { return null; } catch (Exception e) { - logger.debug("Error extracting device name from vHBA XML: {}", e.getMessage()); + // Error extracting device name from vHBA XML return null; } } @@ -4085,13 +4039,11 @@ private boolean isUsbDeviceActuallyAttachedToVm(String vmName, String xmlConfig) String result = dumpCommand.execute(parser); if (result != null) { - logger.warn("Failed to get VM XML for USB device check: {}", result); return false; } String vmXml = parser.getLines(); if (vmXml == null || vmXml.isEmpty()) { - logger.warn("Empty VM XML for USB device check"); return false; } @@ -4099,7 +4051,6 @@ private boolean isUsbDeviceActuallyAttachedToVm(String vmName, String xmlConfig) String deviceMatch = extractDeviceFromUsbXml(xmlConfig); if (busMatch == null || deviceMatch == null) { - logger.warn("Could not extract bus/device from USB XML config"); return false; } boolean deviceFound = vmXml.contains("bus='" + busMatch + "'") && @@ -4127,7 +4078,6 @@ private boolean isVhbaDeviceActuallyAttachedToVm(String vmName, String xmlConfig // 해당 XML 파일이 존재하는지 확인 File xmlFile = new File(vhbaXmlPath); if (!xmlFile.exists()) { - logger.warn("XML file does not exist for device check: {}", vhbaXmlPath); return false; } @@ -4138,20 +4088,17 @@ private boolean isVhbaDeviceActuallyAttachedToVm(String vmName, String xmlConfig String result = dumpCommand.execute(parser); if (result != null) { - logger.warn("Failed to get VM XML for device check: {}", result); return false; } String vmXml = parser.getLines(); if (vmXml == null || vmXml.isEmpty()) { - logger.warn("Empty VM XML for device check"); return false; } // XML에서 대상 이름 추출 (parent 또는 adapter name) String targetName = extractDeviceNameFromVhbaXml(xmlConfig); if (targetName == null) { - logger.warn("Could not extract device/parent name from XML config"); return false; } @@ -4257,11 +4204,11 @@ private String getVhbaDumpXml(String vhbaName) { OutputInterpreter.AllLinesParser parser = new OutputInterpreter.AllLinesParser(); String result = dumpCommand.execute(parser); - if (result == null && parser.getLines() != null) { + if (result == null && parser.getLines() != null && !parser.getLines().trim().isEmpty()) { String xmlContent = parser.getLines(); return xmlContent; } else { - logger.warn("vHBA dumpxml 가져오기 실패: " + vhbaName + " - " + result); + // vHBA dumpxml 가져오기 실패 return null; } } catch (Exception e) { @@ -4373,17 +4320,17 @@ protected Map buildDeviceMapping() { private String resolvePhysicalDeviceFromScsiAddress(String scsiAddress) { try { // /sys/class/scsi_device에서 SCSI 주소로 디바이스 찾기 - java.io.File scsiClassDir = new java.io.File("/sys/class/scsi_device"); - java.io.File[] scsiDevices = scsiClassDir.listFiles(); + File scsiClassDir = new File("/sys/class/scsi_device"); + File[] scsiDevices = scsiClassDir.listFiles(); if (scsiDevices != null) { - for (java.io.File scsiDevice : scsiDevices) { + for (File scsiDevice : scsiDevices) { String deviceName = scsiDevice.getName(); if (deviceName.equals(scsiAddress)) { // device/block 디렉토리에서 실제 블록 디바이스 찾기 - java.io.File blockDir = new java.io.File(scsiDevice, "device/block"); + File blockDir = new File(scsiDevice, "device/block"); if (blockDir.exists()) { - java.io.File[] blockDevices = blockDir.listFiles(); + File[] blockDevices = blockDir.listFiles(); if (blockDevices != null && blockDevices.length > 0) { String blockDeviceName = blockDevices[0].getName(); return "/dev/" + blockDeviceName; @@ -4730,4 +4677,3 @@ private String findExistingByIdForBaseDevice(String baseDevicePath) { return null; } } - diff --git a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java index c7435aefd0a6..5e151a77e1cb 100644 --- a/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java +++ b/plugins/hypervisors/kvm/src/main/java/com/cloud/hypervisor/kvm/resource/LibvirtComputingResource.java @@ -3818,7 +3818,7 @@ private void createVif(final LibvirtVMDef vm, final VirtualMachineTO vmSpec, fin enableOVSDriver = true; } - if (!nic.isSecurityGroupEnabled() && !enableOVSDriver && nic.getNwfilter()) { + if (!nic.isSecurityGroupEnabled() && !enableOVSDriver) { interfaceDef.setFilterrefFilterTag(); } if (vmSpec.getDetails() != null) { @@ -5894,7 +5894,7 @@ public String mapRbdDevice(final KVMPhysicalDisk disk, boolean kvdoEnable){ try { createKvdoCmdLine(splitPoolImage[0], pool.getAuthUserName(), splitPoolImage[1], String.valueOf(disk.getSize())); device = "/dev/mapper/vg_"+splitPoolImage[1].replace("-","")+"-ablestack_kvdo"; - logger.info("device name : "+device); + // device name } catch (InternalErrorException e) { logger.info("createKvdoCmdLine Action Error : "+e); } @@ -5916,7 +5916,7 @@ public String unmapRbdDevice(final KVMPhysicalDisk disk, boolean kvdoEnable){ String vgName = "vg_"+splitPoolImage[1].replace("-",""); Script.runSimpleBashScript("vgchange -an " + vgName); } catch (Exception e) { - logger.info("unmapRbdDevice Action error : "+e); + // unmapRbdDevice Action error } } createRBDSecretKeyFileIfNoExist(pool.getUuid(), DEFAULT_LOCAL_STORAGE_PATH, pool.getAuthSecret()); diff --git a/server/src/main/java/com/cloud/server/ManagementServerImpl.java b/server/src/main/java/com/cloud/server/ManagementServerImpl.java index f80636f22ce3..1f0b87d593e4 100644 --- a/server/src/main/java/com/cloud/server/ManagementServerImpl.java +++ b/server/src/main/java/com/cloud/server/ManagementServerImpl.java @@ -2284,7 +2284,7 @@ public ListResponse listHostUsbDevices(ListHostUsbDe hostDevicesNames.add(parts[0].trim()); pciDescriptions.add(parts[1].trim()); } else { - logger.warn("Unexpected PCI info format: " + hostDevicesText); + // Unexpected PCI info format } } @@ -2514,7 +2514,7 @@ public ListResponse listHostDevices(ListHostDevicesCmd hostDevicesNames.add(parts[0].trim()); pciDescriptions.add(parts[1].trim()); } else { - logger.warn("Unexpected PCI info format: " + hostDevicesText); + // Unexpected PCI info format } } @@ -2630,8 +2630,6 @@ public ListResponse updateHostDevices(UpdateHostDevic } } - logger.info("Updating host device allocation - hostId: {}, hostDeviceName: {}, virtualMachineId: {}", - hostId, hostDeviceName, vmId); try { DetailVO currentAllocation = _hostDetailsDao.findDetail(hostId, hostDeviceName); @@ -2650,15 +2648,12 @@ public ListResponse updateHostDevices(UpdateHostDevic if (detail.getName().startsWith("extraconfig-") && detail.getValue().contains(hostDeviceName)) { _vmDetailsDao.removeDetail(vm.getId(), detail.getName()); - logger.info("Successfully removed device configuration {} from VM {}", - detail.getName(), vm.getInstanceName()); break; } } } // DB에서 해당 디바이스 레코드 삭제 _hostDetailsDao.remove(currentAllocation.getId()); - logger.info("Successfully removed device {} allocation from host {}", hostDeviceName, hostId); } } else { // 새로운 할당 @@ -2688,15 +2683,11 @@ public ListResponse updateHostDevices(UpdateHostDevic while (usedNums.contains(nextConfigNum)) { nextConfigNum++; } - logger.info("Successfully added device configuration to VM {} with config number {}", - vmInstance.getInstanceName(), nextConfigNum); // DB에 할당 정보 저장 Map details = new HashMap<>(); details.put(hostDeviceName, vmId.toString()); _hostDetailsDao.persist(hostId, details); - logger.info("Successfully allocated device {} to VM {} on host {}", - hostDeviceName, vmId, hostId); } } catch (Exception e) { logger.error("Error during device allocation/deallocation - hostDeviceName: {}, error: {}", @@ -2758,8 +2749,6 @@ public ListResponse updateHostUsbDevices(UpdateHos } } - logger.info("Updating host device allocation - hostId: {}, hostDeviceName: {}, virtualMachineId: {}", - hostId, hostDeviceName, vmId); try { DetailVO currentAllocation = _hostDetailsDao.findDetail(hostId, hostDeviceName); @@ -2889,8 +2878,6 @@ public ListResponse updateHostLunDevices(UpdateHos } } - logger.info("Updating host device allocation - hostId: {}, hostDeviceName: {}, virtualMachineId: {}", - hostId, hostDeviceName, vmId); try { // 같은 디바이스 이름의 모든 할당을 가져오기 @@ -2919,7 +2906,6 @@ public ListResponse updateHostLunDevices(UpdateHos } } if (!found) { - logger.warn("Device {} is not allocated to the specified VM {}", hostDeviceName, currentVmId); // 특정 VM에 할당되지 않았다면 첫 번째 할당을 사용 vmIdToUse = currentAllocations.get(0).getValue(); } @@ -2940,7 +2926,6 @@ public ListResponse updateHostLunDevices(UpdateHos } } } else { - logger.warn("No current allocations found for device: {}", hostDeviceName); } } else { if (!currentAllocations.isEmpty()) { @@ -2998,8 +2983,6 @@ public ListResponse updateHostLunDevices(UpdateHos // VM extraconfig에서 해당 디바이스 설정 제거 removeDeviceFromVmExtraConfig(Long.parseLong(currentVmId), hostDeviceName, xmlConfig); - logger.info("Removed specific allocation for device: " + hostDeviceName + - " from VM: " + currentVmId); break; } } @@ -3012,17 +2995,12 @@ public ListResponse updateHostLunDevices(UpdateHos // VM extraconfig에서 해당 디바이스 설정 제거 removeDeviceFromVmExtraConfig(Long.parseLong(firstAllocation.getValue()), hostDeviceName, xmlConfig); - logger.info("Removed first allocation for device: " + hostDeviceName + - " from VM: " + firstAllocation.getValue()); } } } else { // LUN 디바이스는 같은 이름으로도 여러 할당 가능하도록 허용 // 기존 할당이 있어도 새로 할당 (덮어쓰지 않고 추가) if (!currentAllocations.isEmpty()) { - logger.info("Device is already allocated to VMs: " + - currentAllocations.stream().map(DetailVO::getValue).collect(Collectors.joining(", ")) + - ". Allowing multiple allocations for same LUN device."); } // LUN 디바이스를 host_details 테이블에 저장 (같은 이름으로도 여러 할당 가능) @@ -3032,8 +3010,6 @@ public ListResponse updateHostLunDevices(UpdateHos // VM extraconfig에 디바이스 설정 추가 addDeviceToVmExtraConfig(vmId, hostDeviceName, xmlConfig); - logger.info("Created allocation for device: " + hostDeviceName + - " to VM: " + vmId + " (multiple allocations allowed)"); } // 응답 생성 @@ -3091,8 +3067,6 @@ public ListResponse updateHostScsiDevices(UpdateH } } - logger.info("Updating host device allocation - hostId: {}, hostDeviceName: {}, virtualMachineId: {}", - hostId, hostDeviceName, vmId); try { // 같은 디바이스 이름의 모든 할당을 가져오기 @@ -3123,7 +3097,6 @@ public ListResponse updateHostScsiDevices(UpdateH } } if (!found) { - logger.warn("Device {} is not allocated to the specified VM {}", hostDeviceName, currentVmId); // 특정 VM에 할당되지 않았다면 첫 번째 할당을 사용 vmIdToUse = currentAllocations.get(0).getValue(); } @@ -3149,7 +3122,6 @@ public ListResponse updateHostScsiDevices(UpdateH logger.error("Error retrieving VM with ID: {}", vmIdToUse, e); } } else { - logger.warn("No VM ID found for deallocation of device: {}", hostDeviceName); } } else { // SCSI 디바이스는 같은 VM에 여러 개 할당 가능하므로 기존 할당 확인만 하고 계속 진행 @@ -3208,8 +3180,6 @@ public ListResponse updateHostScsiDevices(UpdateH // VM extraconfig에서 해당 디바이스 설정 제거 removeDeviceFromVmExtraConfig(Long.parseLong(currentVmId), hostDeviceName, xmlConfig); - logger.info("Removed specific allocation for device: " + hostDeviceName + - " from VM: " + currentVmId); break; } } @@ -3222,17 +3192,12 @@ public ListResponse updateHostScsiDevices(UpdateH // VM extraconfig에서 해당 디바이스 설정 제거 removeDeviceFromVmExtraConfig(Long.parseLong(firstAllocation.getValue()), hostDeviceName, xmlConfig); - logger.info("Removed first allocation for device: " + hostDeviceName + - " from VM: " + firstAllocation.getValue()); } } } else { // SCSI 디바이스는 같은 이름으로도 여러 할당 가능하도록 허용 // 기존 할당이 있어도 새로 할당 (덮어쓰지 않고 추가) if (!currentAllocations.isEmpty()) { - logger.info("Device is already allocated to VMs: " + - currentAllocations.stream().map(DetailVO::getValue).collect(Collectors.joining(", ")) + - ". Allowing multiple allocations for same SCSI device."); } // SCSI 디바이스를 host_details 테이블에 저장 (같은 이름으로도 여러 할당 가능) @@ -3242,8 +3207,6 @@ public ListResponse updateHostScsiDevices(UpdateH // VM extraconfig에 디바이스 설정 추가 addDeviceToVmExtraConfig(vmId, hostDeviceName, xmlConfig); - logger.info("Created allocation for device: " + hostDeviceName + - " to VM: " + vmId + " (multiple allocations allowed)"); } // 응답 생성 @@ -3327,8 +3290,6 @@ public ListResponse updateHostHbaDevices(UpdateHos throw new CloudRuntimeException("XML configuration is required for HBA device allocation"); } - logger.info("Updating host device allocation - hostId: {}, hostDeviceName: {}, virtualMachineId: {}, isAttach: {}", - hostId, hostDeviceName, vmId, isAttach); try { // 같은 디바이스 이름의 모든 할당을 가져오기 @@ -3365,9 +3326,6 @@ public ListResponse updateHostHbaDevices(UpdateHos } else { // HBA 디바이스는 같은 VM에 여러 개 할당 가능하므로 기존 할당 확인만 하고 계속 진행 if (!currentAllocations.isEmpty()) { - logger.info("Device is already allocated to VMs: " + - currentAllocations.stream().map(DetailVO::getValue).collect(Collectors.joining(", ")) + - ". Allowing multiple HBA allocation to same VM."); } vmInternalName = vmInstance.getInstanceName(); } @@ -3376,10 +3334,6 @@ public ListResponse updateHostHbaDevices(UpdateHos throw new CloudRuntimeException("Unable to get VM instance name"); } - // 호스트에 명령 전송 전 디버그 로그 (XML 포함) - String compactXml = xmlConfig != null ? xmlConfig.replaceAll("\\s+", " ") : ""; - logger.info("Sending UpdateHostHbaDeviceCommand: vmName=" + vmInternalName + - ", hostDeviceName=" + hostDeviceName + ", isAttach=" + isAttach + ", xmlConfig=" + compactXml); UpdateHostHbaDeviceCommand hbaCmd = new UpdateHostHbaDeviceCommand(vmInternalName, xmlConfig, isAttach); Answer answer; @@ -3394,18 +3348,11 @@ public ListResponse updateHostHbaDevices(UpdateHos if (answer == null) { throw new CloudRuntimeException("Answer is null"); } - if (!answer.getResult()) { - String errorDetails = (answer.getDetails() != null) ? - answer.getDetails() : "No additional details available"; - throw new CloudRuntimeException("Failed to update HBA device. Details: " + errorDetails); - } if (!(answer instanceof UpdateHostHbaDeviceAnswer)) { throw new CloudRuntimeException("Answer is not an instance of UpdateHostHbaDeviceAnswer"); } UpdateHostHbaDeviceAnswer hbaAnswer = (UpdateHostHbaDeviceAnswer) answer; - logger.info("Received UpdateHostHbaDeviceAnswer: success=" + hbaAnswer.isSuccessMessage() + - ", vmName=" + hbaAnswer.getVmName() + ", details=" + (hbaAnswer.getDetails() != null ? hbaAnswer.getDetails() : "") ); if (!hbaAnswer.isSuccessMessage()) { String agentDetails = hbaAnswer.getDetails() != null ? hbaAnswer.getDetails() : "No additional details available"; throw new CloudRuntimeException("Failed to update HBA device for VM: " + hbaAnswer.getVmName() + ". Details: " + agentDetails); @@ -3424,8 +3371,6 @@ public ListResponse updateHostHbaDevices(UpdateHos // VM extraconfig에서 해당 디바이스 설정 제거 removeDeviceFromVmExtraConfig(Long.parseLong(currentVmId), hostDeviceName, xmlConfig); - logger.info("Removed specific allocation for device: " + hostDeviceName + - " from VM: " + currentVmId); break; } } @@ -3438,17 +3383,12 @@ public ListResponse updateHostHbaDevices(UpdateHos // VM extraconfig에서 해당 디바이스 설정 제거 removeDeviceFromVmExtraConfig(Long.parseLong(firstAllocation.getValue()), hostDeviceName, xmlConfig); - logger.info("Removed first allocation for device: " + hostDeviceName + - " from VM: " + firstAllocation.getValue()); } } } else { // HBA 디바이스는 같은 이름으로도 여러 할당 가능하도록 허용 // 기존 할당이 있어도 새로 할당 (덮어쓰지 않고 추가) if (!currentAllocations.isEmpty()) { - logger.info("Device is already allocated to VMs: " + - currentAllocations.stream().map(DetailVO::getValue).collect(Collectors.joining(", ")) + - ". Allowing multiple allocations for same HBA device."); } // HBA 디바이스를 host_details 테이블에 저장 (같은 이름으로도 여러 할당 가능) @@ -3458,8 +3398,6 @@ public ListResponse updateHostHbaDevices(UpdateHos // VM extraconfig에 디바이스 설정 추가 addDeviceToVmExtraConfig(vmId, hostDeviceName, xmlConfig); - logger.info("Created allocation for device: " + hostDeviceName + - " to VM: " + vmId + " (multiple allocations allowed)"); } // 응답 생성 @@ -3503,8 +3441,6 @@ public ListResponse createVhbaDevice(CreateVhbaDeviceC String vhbaName = cmd.getVhbaName(); String xmlContent = cmd.getXmlContent(); - logger.info("createVhbaDevice 호출됨 - hostId: {}, parentHbaName: {}, vhbaName: {}, wwnn: {}, wwpn: {}", - hostId, parentHbaName, vhbaName, wwnn, wwpn); // 1. 호스트 존재 여부 확인 HostVO hostVO = _hostDao.findById(hostId); @@ -3527,20 +3463,13 @@ public ListResponse createVhbaDevice(CreateVhbaDeviceC throw new CloudRuntimeException(errorMsg); } - logger.info("호스트 정보 - ID: {}, 이름: {}, 상태: {}", hostVO.getId(), hostVO.getName(), hostVO.getStatus()); - // 3. CreateVhbaDeviceCommand 생성 CreateVhbaDeviceCommand hbaCmd = new CreateVhbaDeviceCommand(hostId, parentHbaName, wwnn, wwpn, vhbaName, xmlContent); - logger.info("CreateVhbaDeviceCommand 생성 완료 - hostId: {}, parentHbaName: {}, vhbaName: {}", - hbaCmd.getHostId(), hbaCmd.getParentHbaName(), hbaCmd.getVhbaName()); - // 4. 에이전트로 명령 전송 Answer answer; try { - logger.info("에이전트로 명령 전송 시작 - hostId: {}", hostVO.getId()); answer = _agentMgr.send(hostVO.getId(), hbaCmd); - logger.info("에이전트로부터 응답 수신"); } catch (Exception e) { String errorMsg = "Error sending CreateVhbaDeviceCommand: " + e.getMessage(); logger.error(errorMsg, e); @@ -3554,8 +3483,6 @@ public ListResponse createVhbaDevice(CreateVhbaDeviceC throw new CloudRuntimeException(errorMsg); } - logger.info("응답 결과: {}, 상세: {}", answer.getResult(), answer.getDetails()); - if (!answer.getResult()) { String errorDetails = (answer.getDetails() != null) ? answer.getDetails() : "No additional details available"; @@ -3572,9 +3499,6 @@ public ListResponse createVhbaDevice(CreateVhbaDeviceC // 6. 응답 처리 CreateVhbaDeviceAnswer hbaAnswer = (CreateVhbaDeviceAnswer) answer; - logger.info("vHBA 생성 결과 - 성공: {}, vHBA 이름: {}, 생성된 디바이스: {}", - hbaAnswer.isSuccess(), hbaAnswer.getVhbaName(), hbaAnswer.getCreatedDeviceName()); - List responses = new ArrayList<>(); ListResponse listResponse = new ListResponse<>(); @@ -3586,7 +3510,6 @@ public ListResponse createVhbaDevice(CreateVhbaDeviceC responses.add(response); listResponse.setResponses(responses); - logger.info("createVhbaDevice 완료 - 응답 생성 완료"); return listResponse; } @@ -3612,9 +3535,6 @@ public ListResponse updateHostVhbaDevices(UpdateH } } - logger.info("Updating vHBA device allocation - hostId: {}, hostDeviceName: {}, virtualMachineId: {}", - hostId, hostDeviceName, vmId); - try { // 현재 할당 상태 확인 (디바이스 이름으로 모두 조회 후 hostId로 필터) List currentAllocations = _hostDetailsDao.findByName(hostDeviceName); @@ -3891,9 +3811,7 @@ public ListResponse deleteVhbaDevice(DeleteVhbaDeviceC Answer answer; try { - logger.info("에이전트로 명령 전송 시작 - hostId: {}", hostVO.getId()); answer = _agentMgr.send(hostVO.getId(), deleteCmd); - logger.info("에이전트로부터 응답 수신"); } catch (Exception e) { String errorMsg = "Error sending DeleteVhbaDeviceCommand: " + e.getMessage(); logger.error(errorMsg, e); @@ -3907,8 +3825,6 @@ public ListResponse deleteVhbaDevice(DeleteVhbaDeviceC throw new CloudRuntimeException(errorMsg); } - logger.info("응답 결과: {}, 상세: {}", answer.getResult(), answer.getDetails()); - if (!answer.getResult()) { String errorDetails = (answer.getDetails() != null) ? answer.getDetails() : "No additional details available"; @@ -3925,8 +3841,6 @@ public ListResponse deleteVhbaDevice(DeleteVhbaDeviceC // 7. 응답 처리 DeleteVhbaDeviceAnswer deleteAnswer = (DeleteVhbaDeviceAnswer) answer; - logger.info("vHBA 삭제 결과 - 성공: {}, vHBA 이름: {}, 상세: {}", - deleteAnswer.getResult(), deleteAnswer.getVhbaName(), deleteAnswer.getDetails()); List responses = new ArrayList<>(); ListResponse listResponse = new ListResponse<>(); @@ -3939,7 +3853,6 @@ public ListResponse deleteVhbaDevice(DeleteVhbaDeviceC responses.add(response); listResponse.setResponses(responses); - logger.info("deleteVhbaDevice 완료 - 응답 생성 완료"); return listResponse; } @@ -7769,27 +7682,21 @@ private Object getVmExtraConfigLock(Long vmId) { */ private String findVmIdFromLunAllocation(Long hostId, String scsiDeviceName, String currentVmId) { try { - logger.debug("Looking for LUN allocation for SCSI device: {}", scsiDeviceName); // SCSI 디바이스에서 물리적 디바이스 경로 추출 String physicalDevicePath = extractPhysicalDeviceFromScsi(scsiDeviceName); if (physicalDevicePath == null) { - logger.debug("Could not extract physical device path from SCSI device: {}", scsiDeviceName); return null; } - logger.debug("Extracted physical device path: {}", physicalDevicePath); - // 호스트의 모든 LUN 디바이스 할당 확인 (findByName으로 모든 할당을 찾고 호스트 ID로 필터링) List allLunAllocations = _hostDetailsDao.findByName(physicalDevicePath); for (DetailVO detail : allLunAllocations) { if (detail.getHostId() == hostId) { String lunDeviceName = detail.getName(); - logger.debug("Checking LUN device: {}", lunDeviceName); // 같은 물리적 디바이스인지 확인 if (isSamePhysicalDevice(lunDeviceName, physicalDevicePath)) { - logger.info("Found matching LUN device: {} for SCSI device: {}", lunDeviceName, scsiDeviceName); if (currentVmId != null) { // 특정 VM ID가 요청되었으면 해당 VM의 할당만 확인 @@ -7804,7 +7711,6 @@ private String findVmIdFromLunAllocation(Long hostId, String scsiDeviceName, Str } } - logger.debug("No matching LUN allocation found for SCSI device: {}", scsiDeviceName); return null; } catch (Exception e) { @@ -7820,29 +7726,15 @@ private String extractPhysicalDeviceFromScsi(String scsiDeviceName) { try { // SCSI 디바이스 이름이 /dev/로 시작하면 직접 반환 (LUN과 같은 물리적 디바이스) if (scsiDeviceName.startsWith("/dev/")) { - logger.debug("SCSI device is already a physical device path: {}", scsiDeviceName); return scsiDeviceName; } - // SCSI 디바이스 이름 형태: "scsi_host0:0:0:0" 또는 "scsi_host0:0:1:0" - // 이를 /dev/sdX 형태로 변환해야 함 - // 실제 구현에서는 더 정교한 매핑이 필요할 수 있음 - if (scsiDeviceName.startsWith("scsi_host")) { - // SCSI 주소에서 물리적 디바이스 경로 추출 - // 이는 하이퍼바이저별로 다를 수 있음 - logger.debug("Extracting physical device from SCSI address: {}", scsiDeviceName); - - // 간단한 예시: scsi_host0:0:0:0 -> /dev/sda - // 실제로는 더 복잡한 매핑 로직이 필요 String[] parts = scsiDeviceName.split(":"); if (parts.length >= 4) { try { int target = Integer.parseInt(parts[2]); int lun = Integer.parseInt(parts[3]); - - // target과 lun을 기반으로 물리적 디바이스 경로 생성 - // 이는 하드코딩된 예시이며, 실제로는 호스트의 디바이스 정보를 확인해야 함 char deviceLetter = (char) ('a' + target); return "/dev/" + deviceLetter; } catch (NumberFormatException e) { @@ -7873,8 +7765,6 @@ private boolean isSamePhysicalDevice(String lunDeviceName, String physicalDevice lunBasePath = lunDeviceName; } - logger.debug("Comparing LUN device: {} with physical path: {}", lunBasePath, physicalDevicePath); - // 직접 경로 비교 if (lunBasePath.equals(physicalDevicePath)) { return true; @@ -7899,8 +7789,6 @@ private boolean isSamePhysicalDevice(String lunDeviceName, String physicalDevice private void removeDeviceFromVmExtraConfig(Long vmId, String deviceName, String xmlConfig) { try { List existingConfigs = _vmDetailsDao.listDetails(vmId); - logger.info("Removing device {} from VM {} extraconfig, total configs: {}", - deviceName, vmId, existingConfigs.size()); for (UserVmDetailVO detail : existingConfigs) { if (detail.getName().startsWith("extraconfig-") && detail.getValue() != null) { @@ -7955,8 +7843,6 @@ private void removeDeviceFromVmExtraConfig(Long vmId, String deviceName, String if (shouldRemove) { _vmDetailsDao.remove(detail.getId()); - logger.info("Removed device {} configuration from VM {} extraconfig key: {} (reason: {})", - deviceName, vmId, detail.getName(), matchReason); break; } } @@ -8011,9 +7897,6 @@ private boolean matchUsbDevice(String xmlValue, String deviceName) { boolean busMatch = xmlValue.contains(busPattern); boolean deviceMatch = xmlValue.contains(devicePattern); - logger.debug("USB device match - deviceName: {}, bus: {}, device: {}, busMatch: {}, deviceMatch: {}", - deviceName, bus, device, busMatch, deviceMatch); - return busMatch && deviceMatch; } } catch (Exception e) { @@ -8024,13 +7907,9 @@ private boolean matchUsbDevice(String xmlValue, String deviceName) { private boolean matchHbaDevice(String xmlValue, String deviceName) { try { - // "scsi_host18" -> adapter name="scsi_host18" String adapterPattern = "adapter name='" + deviceName + "'"; boolean match = xmlValue.contains(adapterPattern); - logger.debug("HBA device match - deviceName: {}, adapterPattern: {}, match: {}", - deviceName, adapterPattern, match); - return match; } catch (Exception e) { logger.warn("Error matching HBA device {}: {}", deviceName, e.getMessage()); @@ -8040,13 +7919,9 @@ private boolean matchHbaDevice(String xmlValue, String deviceName) { private boolean matchVhbaDevice(String xmlValue, String deviceName) { try { - // "scsi_host18" -> adapter name="scsi_host18" String adapterPattern = "adapter name='" + deviceName + "'"; boolean match = xmlValue.contains(adapterPattern); - logger.debug("vHBA device match - deviceName: {}, adapterPattern: {}, match: {}", - deviceName, adapterPattern, match); - return match; } catch (Exception e) { logger.warn("Error matching vHBA device {}: {}", deviceName, e.getMessage()); @@ -8056,9 +7931,6 @@ private boolean matchVhbaDevice(String xmlValue, String deviceName) { private boolean matchScsiDevice(String xmlValue, String deviceName) { try { - // "/dev/sg33" -> scsi_host 번호 추출하여 매칭 - // 실제로는 동적으로 생성된 SCSI 주소를 사용하므로 XML 내용으로 매칭 - // 이 경우는 xmlConfig 매개변수를 사용하는 것이 더 안전 return xmlValue.contains(deviceName); } catch (Exception e) { logger.warn("Error matching SCSI device {}: {}", deviceName, e.getMessage()); @@ -8068,11 +7940,6 @@ private boolean matchScsiDevice(String xmlValue, String deviceName) { private boolean matchLunDevice(String xmlValue, String deviceName) { try { - logger.debug("Matching LUN device - deviceName: {}, xmlValue: {}", deviceName, xmlValue); - - // LUN 디바이스 이름은 다음과 같은 형태일 수 있음: - // "/dev/sdc (scsi-360000000000000000000000000000000)" - // "/dev/dm-10 (dm-uuid-360000000000000000000000000000000)" // 1. XML에서 실제 사용되는 경로를 우선적으로 매칭 if (xmlValue.contains("/dev/disk/by-id/")) { @@ -8081,7 +7948,6 @@ private boolean matchLunDevice(String xmlValue, String deviceName) { java.util.regex.Matcher byIdMatcher = byIdPattern.matcher(xmlValue); if (byIdMatcher.find()) { String xmlByIdPath = byIdMatcher.group(1); - logger.debug("Found by-id path in XML: {}", xmlByIdPath); // 디바이스 이름에서 추출한 by-id 값과 비교 String byIdValue = extractByIdFromDeviceName(deviceName); @@ -8090,14 +7956,12 @@ private boolean matchLunDevice(String xmlValue, String deviceName) { String[] prefixes = {"wwn-", "scsi-", "scsi-SATA_", "dm-uuid-"}; for (String prefix : prefixes) { if (xmlByIdPath.equals(prefix + byIdValue)) { - logger.debug("XML by-id path match found: {}", xmlByIdPath); return true; } } // 접두사 없이도 매칭 시도 if (xmlByIdPath.equals(byIdValue)) { - logger.debug("XML by-id path match found (no prefix): {}", xmlByIdPath); return true; } } @@ -8106,7 +7970,6 @@ private boolean matchLunDevice(String xmlValue, String deviceName) { // 2. 직접적인 경로 매칭 if (xmlValue.contains(deviceName)) { - logger.debug("Direct device name match found"); return true; } @@ -8117,7 +7980,6 @@ private boolean matchLunDevice(String xmlValue, String deviceName) { if (byIdValue != null) { String byIdPath = "/dev/disk/by-id/" + byIdValue; if (xmlValue.contains(byIdPath)) { - logger.debug("DM by-ID path match found: {}", byIdPath); return true; } } @@ -8126,7 +7988,6 @@ private boolean matchLunDevice(String xmlValue, String deviceName) { if (deviceName.contains("dm-uuid-")) { String dmPath = convertDmUuidToDmPath(deviceName); if (dmPath != null && xmlValue.contains(dmPath)) { - logger.debug("DM path match found: {}", dmPath); return true; } } @@ -8134,12 +7995,10 @@ private boolean matchLunDevice(String xmlValue, String deviceName) { // 4. dm이 아닌 디바이스의 경우 기본 경로 우선 매칭 (마이그레이션 호환성) String basePath = extractBasePathFromDeviceName(deviceName); if (basePath != null && xmlValue.contains(basePath)) { - logger.debug("Base path match found: {}", basePath); return true; } } - logger.debug("No LUN device match found"); return false; } catch (Exception e) { logger.warn("Error matching LUN device {}: {}", deviceName, e.getMessage()); @@ -8149,48 +8008,37 @@ private boolean matchLunDevice(String xmlValue, String deviceName) { private String extractByIdFromDeviceName(String deviceName) { try { - // "/dev/sdc (scsi-360000000000000000000000000000000)" -> "scsi-360000000000000000000000000000000" - // "/dev/sdc (wwn-0x5ace42e4350075f6)" -> "wwn-0x5ace42e4350075f6" - // "/dev/sdc (scsi-SATA_HFS3T8G3H2X069N_KJD3N4392I0903D2S)" -> "scsi-SATA_HFS3T8G3H2X069N_KJD3N4392I0903D2S" java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("\\(([^)]+)\\)"); java.util.regex.Matcher matcher = pattern.matcher(deviceName); if (matcher.find()) { String byIdValue = matcher.group(1); - // 접두사가 있는 경우 접두사 제거하여 순수 ID만 반환 if (byIdValue.startsWith("wwn-") || byIdValue.startsWith("scsi-") || byIdValue.startsWith("dm-uuid-")) { - // scsi-SATA_ 같은 복합 접두사의 경우 첫 번째 '-' 이후의 모든 내용을 ID로 사용 return byIdValue.substring(byIdValue.indexOf('-') + 1); } return byIdValue; } } catch (Exception e) { - logger.debug("Error extracting by-id from device name: {}", e.getMessage()); } return null; } private String extractBasePathFromDeviceName(String deviceName) { try { - // "/dev/sdc (scsi-360000000000000000000000000000000)" -> "/dev/sdc" if (deviceName.contains(" (")) { return deviceName.split(" \\(")[0]; } return deviceName; } catch (Exception e) { - logger.debug("Error extracting base path from device name: {}", e.getMessage()); } return null; } private String convertDmUuidToDmPath(String deviceName) { try { - // dm-uuid가 포함된 경우 일반적으로 /dev/dm-X 형태로 변환 - // 실제 구현에서는 백엔드에서 동적으로 변환하므로 여기서는 일반적인 패턴 사용 if (deviceName.contains("dm-uuid-")) { - return "/dev/dm-10"; // 일반적인 dm 디바이스 경로 + return "/dev/dm-10"; } } catch (Exception e) { - logger.debug("Error converting dm-uuid to dm path: {}", e.getMessage()); } return null; } @@ -8205,8 +8053,6 @@ public void deallocateAllDevicesOnVmDestroy(Long vmId) { return; } - logger.info("Deallocating all devices for VM: {}", vmId); - try { // VM 정보 조회 VMInstanceVO vm = _vmInstanceDao.findById(vmId); @@ -8222,8 +8068,6 @@ public void deallocateAllDevicesOnVmDestroy(Long vmId) { hostId = vm.getLastHostId(); } - logger.info("VM {} (instance: {}) on host: {}", vmId, vmInstanceName, hostId); - // 1. PCI 디바이스 해제 deallocatePciDevicesForVm(vmIdStr, hostId); @@ -8242,7 +8086,6 @@ public void deallocateAllDevicesOnVmDestroy(Long vmId) { // 6. vHBA 디바이스 해제 deallocateVhbaDevicesForVm(vmIdStr, vmInstanceName, hostId); - logger.info("Successfully deallocated all devices for VM: {}", vmId); } catch (Exception e) { logger.error("Error deallocating devices for VM {}: {}", vmId, e.getMessage(), e); @@ -8262,7 +8105,6 @@ private void deallocatePciDevicesForVm(String vmId, Long hostId) { for (DetailVO allocation : allocations) { String deviceName = allocation.getName(); if (isPciDevice(deviceName)) { - logger.info("Deallocating PCI device {} from VM {}", deviceName, vmId); _hostDetailsDao.remove(allocation.getId()); // extraconfig 삭제 @@ -8290,7 +8132,6 @@ private void deallocateUsbDevicesForVm(String vmId, String vmInstanceName, Long for (DetailVO allocation : allocations) { String deviceName = allocation.getName(); if (isUsbDevice(deviceName)) { - logger.info("Deallocating USB device {} from VM {}", deviceName, vmId); _hostDetailsDao.remove(allocation.getId()); // extraconfig 삭제 @@ -8318,7 +8159,6 @@ private void deallocateHbaDevicesForVm(String vmId, String vmInstanceName, Long for (DetailVO allocation : allocations) { String deviceName = allocation.getName(); if (isHbaDevice(deviceName)) { - logger.info("Deallocating HBA device {} from VM {}", deviceName, vmId); _hostDetailsDao.remove(allocation.getId()); // extraconfig 삭제 @@ -8346,7 +8186,6 @@ private void deallocateLunDevicesForVm(String vmId, String vmInstanceName, Long for (DetailVO allocation : allocations) { String deviceName = allocation.getName(); if (isLunDevice(deviceName)) { - logger.info("Deallocating LUN device {} from VM {}", deviceName, vmId); _hostDetailsDao.remove(allocation.getId()); // extraconfig 삭제 @@ -8374,7 +8213,6 @@ private void deallocateScsiDevicesForVm(String vmId, String vmInstanceName, Long for (DetailVO allocation : allocations) { String deviceName = allocation.getName(); if (isScsiDevice(deviceName)) { - logger.info("Deallocating SCSI device {} from VM {}", deviceName, vmId); _hostDetailsDao.remove(allocation.getId()); // extraconfig 삭제 @@ -8402,14 +8240,14 @@ private void deallocateVhbaDevicesForVm(String vmId, String vmInstanceName, Long for (DetailVO allocation : allocations) { String deviceName = allocation.getName(); if (isVhbaDevice(deviceName)) { - logger.info("Deallocating vHBA device {} from VM {}", deviceName, vmId); + // Deallocating vHBA device _hostDetailsDao.remove(allocation.getId()); // extraconfig 삭제 try { removeDeviceFromVmExtraConfig(Long.parseLong(vmId), deviceName, ""); } catch (Exception e) { - logger.warn("Failed to remove vHBA device {} from extraconfig: {}", deviceName, e.getMessage()); + // Failed to remove vHBA device from extraconfig } } } @@ -8417,4 +8255,4 @@ private void deallocateVhbaDevicesForVm(String vmId, String vmInstanceName, Long logger.error("Error deallocating vHBA devices for VM {}: {}", vmId, e.getMessage()); } } -} \ No newline at end of file +}