Mục tiêu buổi học
- Chẩn đoán và xử lý các lỗi phổ biến trong môi trường vSphere
- Sử dụng thành thạo ESXi diagnostic commands qua SSH
- Dùng esxtop để phân tích real-time performance (CPU, Memory, Disk, Network)
- Thành thạo PowerCLI cho automation và bulk operations
- Áp dụng best practices cho môi trường production enterprise
Lý Thuyết
Common Issues & Solutions
| Triệu chứng | Nguyên nhân | Giải pháp |
|---|---|---|
| vMotion failed: CPU incompatible | EVC mode không đúng | Set/Upgrade EVC mode trên cluster |
| VM not starting: No space left | Datastore đầy | Xóa snapshots, tăng storage, Storage vMotion |
| HA not triggering | Isolation response = leave powered on | Kiểm tra das.isolationaddress |
| DRS not migrating | Migration threshold quá cao | Giảm threshold hoặc Force migrate |
| iSCSI disconnect | Jumbo frames mismatch | Kiểm tra MTU end-to-end (host + switch + storage) |
| VCSA unreachable | PSC/SSO service down | Restart services via VAMI (port 5480) |
| High CPU Ready | vCPU overcommit | Giảm vCPU, tăng pCPU hoặc vMotion sang host ít tải |
| Memory balloon active | RAM overcommit | Giảm VM RAM allocation, thêm RAM host, vMotion |
| Snapshot consolidation needed | Delta disk không merge | VM → Snapshot → Consolidate |
| Time sync issues (VM clock drift) | VMware Tools time sync disabled | Enable time sync trong VMware Tools hoặc NTP guest |
Log Files Reference
=== ESXi Log Files (SSH) === /var/log/vmkernel.log ← Core VMkernel messages, storage errors, CPU/RAM events /var/log/hostd.log ← Host daemon: vSphere Client connections, VM operations /var/log/vpxa.log ← vCenter agent on host: vCenter communication /var/log/fdm.log ← HA Fault Domain Manager: HA election, failover events /var/log/vobd.log ← vSphere Observer: hardware alerts, storage path changes /var/log/auth.log ← SSH login attempts, authentication events /var/log/syslog.log ← General system syslog === vCenter Log Files === /var/log/vmware/vpxd/vpxd.log ← vCenter main service /var/log/vmware/sso/vmware-sts*.log ← SSO/Authentication logs /var/log/vmware/vdcs/dm.log ← Distributed Services (DRS, HA) === Collect Logs (Support Bundle) === vSphere Client → Host → Actions → Export System Logs Hoặc: vm-support (SSH trên ESXi): vm-support -w /tmp -z
esxtop — Real-time Performance Tool
SSH vào ESXi → esxtop === Navigation Keys === c → CPU view (most used) m → Memory view n → Network view d → Disk Adapter view u → Disk Device (LUN) view v → VM view i → Interrupt view p → Power Management h → Help q → Quit === CPU View — Cột quan trọng === %USED → CPU đang dùng (tổng) %RDY → CPU Ready — VM chờ được schedule (target: <5%) %CSTP → Co-stop — SMP VM bị block vì vCPU pair %MLMTD → CPU limit throttling (có limit set) %SWPWT → Swap wait (RAM issue bleeding to CPU) === Memory View — Cột quan trọng === MEMSZ → Memory allocated to VM (MB) GRANT → Memory actually given by VMkernel LIMIT → Memory limit configured for VM SZTGT → Target size (VMkernel wants to shrink to) TCHD → Touched (active) memory MCTLSZ → Balloon driver size (KB) — host memory pressure, bad if >0! SWPWRT → Swap write rate (MB/s) — CRITICAL if >0, performance disaster SWCUR → Current swap usage (KB) — very bad! === Network View — Cột quan trọng === %DRPTX → Packet drop Transmit — bad if >0 (NIC overload, uplink saturated) %DRPRX → Packet drop Receive — bad if >0 (vSwitch buffer overflow) === Batch Mode (để export phân tích) === esxtop -b -d 5 -n 12 > /tmp/esxtop-$(date +%Y%m%d).csv # -b = batch mode, -d 5 = 5 giây/sample, -n 12 = 12 samples (1 phút) # Import vào PerfMon hoặc Excel để phân tích
Lab Thực Hành
Lab 11.1 — ESXi Diagnostic Commands (SSH)
=== Network Diagnostics === esxcli network ip interface list # VMkernel interfaces esxcli network nic list # Physical NICs status esxcli network ip route list # Routing table esxcli network ip neighbor list # ARP table vmkping -I vmk1 192.168.20.12 # Ping qua specific vmknic vmkping -d -s 8972 -I vmk2 192.168.30.10 # Test jumbo frames (MTU 9000) # -d = don't fragment, -s 8972 = payload size (8972+28=9000 bytes) === Storage Diagnostics === esxcli storage core device list # All storage devices esxcli storage nmp device list # NMP multipathing info esxcfg-mpath -l # Detailed multipath info esxcli storage vmfs extent list # VMFS datastores esxcli storage core adapter list # HBAs and iSCSI adapters esxcli iscsi adapter list # iSCSI specific adapters === VM Management === vim-cmd vmsvc/getallvms # List all VMs với VMID vim-cmd vmsvc/power.getstate# Power state của VM vim-cmd vmsvc/power.on # Power on VM vim-cmd vmsvc/power.off # Power off (hard) vim-cmd vmsvc/snapshot.get # List snapshots vim-cmd vmsvc/consolidate # Force consolidate snapshots === System Information === esxcli system hostname get # Hostname esxcli system time get # System time esxcli software profile get # Installed ESXi build esxcli hardware cpu global get # CPU info esxcli hardware memory get # RAM info esxcli system version get # ESXi version detail === Process & Health === ps -c | grep vmx # VM processes esxcli system process list # All processes vsish -e get /sys/net/portsets/... # vSwitch internals
Lab 11.2 — PowerCLI Cheat Sheet
=== Connection === Connect-VIServer vcsa.company.com -Credential (Get-Credential) Connect-VIServer vcsa.company.com -User [email protected] -Password 'VMware1!' Disconnect-VIServer -Confirm:$false === Inventory === Get-Datacenter Get-Cluster Get-VMHost # All hosts Get-VMHost | Select Name, State, Version, NumCpu, MemoryTotalGB Get-VM # All VMs Get-VM | Where-Object {$_.PowerState -eq "PoweredOff"} Get-Datastore | Select Name, FreeSpaceGB, CapacityGB === VM Operations === Get-VM "web-01" | Start-VM Get-VM "web-01" | Stop-VM -Confirm:$false Get-VM "web-01" | Restart-VM -Confirm:$false Get-VM "web-01" | Suspend-VM Get-VM | Where-Object {$_.NumCpu -gt 8} | Select Name, NumCpu === Snapshots === New-Snapshot -VM "web-01" -Name "pre-patch" -Quiesce -Memory Get-VM "web-01" | Get-Snapshot Set-VM -VM "web-01" -Snapshot (Get-Snapshot -VM "web-01" -Name "pre-patch") Remove-Snapshot -Snapshot (Get-Snapshot -VM "web-01") -Confirm:$false # Find VMs với snapshots cũ hơn 7 ngày: Get-VM | Get-Snapshot | Where-Object {$_.Created -lt (Get-Date).AddDays(-7)} | Select VM, Name, Created, SizeMB === vMotion === Move-VM -VM "web-01" -Destination (Get-VMHost "esxi-02") Move-VM -VM "web-01" -Datastore (Get-Datastore "DS-SSD") Move-VM -VM "web-01" -Destination (Get-VMHost "esxi-03") ` -Datastore (Get-Datastore "DS-NFS-Dev") === Resource Config === Get-VM "web-01" | Get-VMResourceConfiguration Set-VMResourceConfiguration -VM "web-01" ` -CpuReservationMhz 2000 -MemReservationMB 4096 === Host Operations === Get-VMHost "esxi-01" | Set-VMHost -State Maintenance Get-VMHost "esxi-01" | Set-VMHost -State Connected Get-VMHost | Get-VMHostService | Where-Object {$_.Key -eq "TSM-SSH"} | Stop-VMHostService -Confirm:$false # Disable SSH on all hosts === Bulk Reports === # Export all VMs inventory to CSV Get-VM | Select Name, NumCpu, MemoryGB, PowerState, @{N='Host';E={$_.VMHost.Name}}, @{N='Datastore';E={($_ | Get-Datastore).Name}}, @{N='IP';E={@($_.Guest.IPAddress)[0]}} | Export-Csv -Path "C:\vm-inventory.csv" -NoTypeInformation # Find VMs without VMware Tools: Get-VM | Where-Object {$_.ExtensionData.Guest.ToolsStatus -ne "toolsOk"} | Select Name, @{N='ToolsStatus';E={$_.ExtensionData.Guest.ToolsStatus}} # Datastore capacity report: Get-Datastore | Select Name, @{N='CapacityGB';E={[math]::Round($_.CapacityGB,1)}}, @{N='FreeGB';E={[math]::Round($_.FreeSpaceGB,1)}}, @{N='UsedPct';E={[math]::Round((1-$_.FreeSpaceGB/$_.CapacityGB)*100,1)}} | Sort-Object UsedPct -Descending
Lab 11.3 — Xử lý sự cố thực tế: "VM không start, datastore đầy"
Triệu chứng: VM "oracle-db-01" không power on
Error: "Unable to access file [DS-iSCSI-01] oracle-db-01/oracle-db-01.vmdk"
Step 1: Kiểm tra datastore capacity
vSphere Client → Storage → DS-iSCSI-01 → Summary
Thấy: 98% used, 8 GB free
Step 2: Tìm snapshots lớn
PowerCLI:
Get-VM | Get-Snapshot | Sort-Object SizeMB -Desc | Select -First 10 VM, Name, SizeMB
Hoặc SSH vào ESXi:
find /vmfs/volumes/DS-iSCSI-01 -name "*-delta.vmdk" -size +5G
Step 3: Xóa snapshots không cần thiết
vSphere Client → VM → Snapshots → Manage Snapshots
→ Delete All Snapshots (nếu không cần)
Hoặc PowerCLI bulk:
Get-VM | Get-Snapshot | Where-Object {$_.Created -lt (Get-Date).AddDays(-3)} |
Remove-Snapshot -Confirm:$false
Step 4: Storage vMotion VM sang datastore khác (nếu cần)
Right-click VM → Migrate → Change storage only
Destination: DS-NFS-Dev
Step 5: Verify và Power On
Datastore free space > 20% → Power On VM
Lab 11.4 — Xử lý sự cố: "VCSA không kết nối được, SSO service down"
Triệu chứng: https://vcsa-01.lab.local/ui không load, treo ở login Step 1: Kiểm tra VAMI https://vcsa-01.lab.local:5480 Đăng nhập admin → Services tab Step 2: Kiểm tra services status SSH vào VCSA (root): service-control --status --all | grep -i stopped Thường bị dừng: - vmware-vpxd (vCenter main service) - vmware-sso (Platform Services Controller / SSO) - vmware-psc-client Step 3: Restart services theo thứ tự service-control --stop --all service-control --start --all Hoặc restart từng service: service-control --restart vmware-sso service-control --restart vmware-vpxd Step 4: Kiểm tra disk space VCSA df -h # Nếu /storage/log hoặc /storage/db gần đầy → clear old logs /usr/lib/vmware-vmon/vmon-cli --status Step 5: Check certificate expiry (common issue!) /usr/lib/vmware-vmafd/bin/vecs-cli entry list --store MACHINE_SSL_CERT # Nếu certificate hết hạn → Certificate Manager tool: /usr/lib/vmware-vmca/bin/certificate-manager
ỨNG DỤNG DOANH NGHIỆP — MODULE 11
Troubleshooting & Performance tuning thực chiến — đọc esxtop, điều tra NUMA imbalance, log collection, alarm thresholds và network packet loss investigation.
1. esxtop — Đọc & Phân Tích Metrics Quan Trọng
esxtop là công cụ CLI realtime mạnh nhất để diagnose performance issues trên ESXi host — phải biết đọc đúng các counter.
| Counter | Màn hình esxtop | Ngưỡng cảnh báo | Ngưỡng nghiêm trọng | Ý nghĩa |
|---|---|---|---|---|
| %RDY (CPU Ready) | CPU (c) | >5% | >10% | VM đang chờ được lên pCPU — host CPU contention |
| %CSTP (Co-Stop) | CPU (c) | >3% | >5% | SMP VM chờ vCPU pair — giảm vCPU count |
| MCTLSZ (Balloon) | Memory (m) | >0 MB | >256 MB | VMware balloon driver thu hồi RAM — host memory pressure |
| SWPWRT (Swap Write) | Memory (m) | >0 MB/s | >10 MB/s | VM đang swap write ra disk — CRITICAL, performance thảm họa |
| DAVG (Disk Avg Lat) | Disk (d) | >10 ms | >20 ms | Độ trễ trung bình disk — bad if >20ms, storage I/O bottleneck |
| KAVG (Kernel Avg) | Disk (d) | >2 ms | >5 ms | Delay trong VMkernel queue — ESXi storage stack issue |
### esxtop — Lệnh thực tế hay dùng # Kết nối SSH vào ESXi host ssh [email protected] # Chạy esxtop interactive esxtop # Hotkeys trong esxtop: # c → CPU screen m → Memory screen # d → Disk screen n → Network screen # v → Virtual machines only # f → Add/remove fields # Batch mode — ghi dữ liệu 60 giây, interval 2s esxtop -b -d 2 -n 30 > /tmp/esxtop-$(hostname)-$(date +%Y%m%d%H%M).csv # Copy về workstation để analyze scp root@esxi-hn-r01-01:/tmp/esxtop-*.csv C:\Troubleshoot\ # Filter VM cụ thể trong CSV # Column VMNAME, lọc bằng Excel Pivot hoặc Python pandas
2. DCUI vs SSH — Workflow Troubleshooting Đúng Chuẩn
DCUI (Direct Console User Interface) và SSH phục vụ các tình huống khác nhau — biết chọn đúng tool tiết kiệm thời gian.
### Khi nào dùng DCUI (màn hình vật lý / iDRAC/iLO)
✓ Host mất kết nối mạng management (không SSH được)
✓ Cần restart management agents (hostd, vpxa)
✓ Cấu hình lại IP management khi bị đổi sai
✓ Enable SSH từ DCUI khi bị disable qua policy
✓ Host bị lockdown — DCUI vẫn cho phép Exception Users
DCUI → Troubleshooting Options →
├── Restart Management Agents (fix hostd/vpxa hung)
├── Reset System Configuration (factory reset — cẩn thận!)
├── Enable/Disable SSH
└── View System Logs (vmkernel.log realtime)
### Khi nào dùng SSH
✓ esxtop, log analysis, tcpdump, vim-cmd
✓ Kiểm tra network, storage từ host perspective
✓ Chạy scripts, collect support bundle
### Restart Management Agents (quan trọng nhất)
# Via DCUI hoặc SSH:
/etc/init.d/hostd restart # Restart Host Daemon
/etc/init.d/vpxa restart # Restart vCenter Agent
/etc/init.d/hostd stop && /etc/init.d/hostd start
# Kiểm tra service status
/etc/init.d/hostd status
esxcli system process list | grep hostd
Security Policy — SSH trong Production
- SSH chỉ enable khi cần troubleshoot, disable sau khi xong — tối đa 4 giờ
- Tạo Change Request trước khi enable SSH trên production host
- Cấu hình
UserVars.SshSessionLimit = 3để giới hạn concurrent sessions - SSH access phải qua Jump Server/Bastion Host — không direct SSH từ laptop
3. Log Bundle Collection — vm-support & Phân Tích Log
Khi escalate lên VMware Support hoặc điều tra post-mortem, cần thu thập log bundle đầy đủ từ host và vCenter.
### Thu thập Log Bundle từ ESXi Host # Cách 1: SSH vào host vm-support -s # Thu thập tất cả log + config vm-support -l # Liệt kê các file sẽ thu thập # File tạo ra: /var/tmp/esx-HOSTNAME-YYYYMMDD-xxxxxxx.tgz scp root@esxi-hn-r01-01:/var/tmp/esx-*.tgz . # Cách 2: vSphere Client # Host → Monitor → System → Export System Logs # Chọn: Include vCenter Server logs nếu cần # Cách 3: vCenter Support Bundle # vSphere Client → Menu → Administration → Export System Logs # Chọn hosts + vCenter → Generate Bundle ### Log quan trọng cần kiểm tra # /var/log/vmkernel.log → Kernel events, storage errors, HA # /var/log/hostd.log → vSphere Client, API calls # /var/log/vpxa.log → vCenter Agent communication # /var/log/vmksummary.log → Daily summary, uptime, reboots # /var/log/fdm.log → HA Fault Domain Manager ### Quick log search (SSH vào host) # Tìm lỗi storage trong 30 phút qua grep -i "error\|failed\|lost" /var/log/vmkernel.log | tail -100 # Tìm VM power-off events grep "Powered off" /var/log/hostd.log | tail -50 # Xem ESXi uptime và reboot history cat /var/log/vmksummary.log | grep -i "reboot\|uptime"
Log Rotation & Centralized Logging
- ESXi log tự động rotate — chỉ giữ ~8 MB mỗi file. Forward đến syslog server ngay
- Cấu hình:
esxcli system syslog config set --loghost=tcp://siem.hoatranlab.io.local:514 - Persistent logging: cấu hình datastore scratch location, tránh mất log sau reboot
4. Performance Alarm Thresholds — Cấu Hình Chuẩn Production
Alarm đúng ngưỡng giúp phát hiện vấn đề trước khi ảnh hưởng production — quá thấp sẽ gây alert fatigue, quá cao sẽ bỏ lỡ sự cố.
| Alarm | Object | Warning | Critical | Action |
|---|---|---|---|---|
| CPU Usage | Host | 75% (5 phút) | 90% (5 phút) | Email + xem xét add host |
| Memory Usage | Host | 80% | 90% | Check balloon/swap VMs |
| Datastore Usage | Datastore | 75% | 85% | Clean snapshots, expand |
| VM CPU Ready | VM | 5% | 10% | Reduce vCPU, check DRS |
| Disk Read Latency | VM | 15 ms | 30 ms | Check storage queue, path |
| Host Connection | Host | Not responding | Disconnected | PagerDuty P1 ngay |
### PowerCLI — Tạo Custom Alarm cho CPU Ready >5% Connect-VIServer vcsa-01.lab.local $alarmMgr = Get-View AlarmManager $spec = New-Object VMware.Vim.AlarmSpec $spec.Name = "VM CPU Ready > 5%" $spec.Description = "VM experiencing CPU contention" $spec.Enabled = $true $expr = New-Object VMware.Vim.MetricAlarmExpression $expr.Comparator = "isAbove" $expr.MetricId = New-Object VMware.Vim.PerfMetricId $expr.MetricId.CounterId = 10 # CPU Ready counter $expr.MetricId.Instance = "" $expr.Yellow = 500 # 5% (unit: milliseconds per 10000ms = 0.01%) $expr.Red = 1000 # 10% $spec.Expression = New-Object VMware.Vim.OrAlarmExpression $spec.Expression.Expression = @($expr) # Áp dụng cho tất cả VMs trong cluster $alarmMgr.CreateAlarm((Get-Cluster "CL-HN-Prod-01" | Get-View).MoRef, $spec)
5. NUMA Imbalance Diagnosis — CPU Performance Deep Dive
NUMA (Non-Uniform Memory Access) imbalance là nguyên nhân phổ biến gây CPU performance kém trên server nhiều socket mà khó phát hiện bằng metric thông thường.
### Phát hiện NUMA Imbalance trong esxtop # esxtop → CPU screen (c) → thêm field NUMA stats (f → N → Enter) # Columns quan trọng: # NRMEM → Local memory (NUMA-local) — muốn >90% # NRMIG → NUMA migrations — muốn thấp # NLMEM → Remote memory access — muốn <10% # Dấu hiệu NUMA imbalance: # - CPU %RDY cao nhưng host CPU không overloaded tổng thể # - NLMEM > 20% → VM đang access RAM qua NUMA bus # - NRMIG nhiều → ESXi đang migrated NUMA domain liên tục ### Nguyên nhân và giải pháp # VẤN ĐỀ 1: VM lớn hơn 1 NUMA node # Ví dụ: Server 2-socket × 16 cores, 256 GB RAM/socket # VM 20 vCPU, 300 GB RAM → span 2 NUMA nodes → remote memory # Giải pháp: # 1. Giảm vCPU của VM xuống ≤ 16 (1 socket) # 2. Hoặc enable NUMA-aware memory allocation: esxcli system settings advanced set -o /Numa/LocalityWeightMemory -v 15 esxcli system settings advanced set -o /Numa/RebalanceCoolingTime -v 2000 # VẤN ĐỀ 2: vCPU count không là bội số của physical cores/socket # 30 vCPU trên host 16 cores/socket → không fit NUMA node sạch # Giải pháp: set vCPU = 16 hoặc 32, không dùng 30 ### Kiểm tra NUMA topology của host esxcli hardware numa stats get vsish -e get /hardware/cpu/cpuList | grep "NUMA Node"
Best Practice — VM Sizing để tránh NUMA Imbalance
- vCPU count = bội số của physical cores per NUMA node (thường 8, 16, 24)
- RAM của VM không vượt quá RAM per NUMA node (thường 128 GB hoặc 256 GB)
- Dùng vNUMA (virtual NUMA) cho VMs > 1 NUMA node — expose NUMA topology vào guest OS
- Guest OS phải là NUMA-aware (Windows Server 2016+, RHEL 8+)
6. Network Packet Loss Investigation — pktcap-uw Deep Dive
pktcap-uw là công cụ packet capture mạnh nhất trên ESXi — cho phép capture ở nhiều layer từ vNIC VM đến physical uplink để isolate vị trí mất gói.
### pktcap-uw — Packet Capture trên ESXi SSH vào ESXi host, sau đó: # 1. Tìm vNIC world ID của VM cần investigate vsish -e get /net/portsets/*/ports/*/clientName | grep -i "vm-name" # Hoặc: esxcli network vm list → lấy World ID # 2. Capture traffic tại vNIC của VM (Switchport egress) pktcap-uw --switchport [PORT-ID] --capture Tx --outfile /tmp/vm-tx.pcap & pktcap-uw --switchport [PORT-ID] --capture Rx --outfile /tmp/vm-rx.pcap & # 3. Capture tại physical uplink (vmnic) pktcap-uw --uplink vmnic0 --capture Tx --outfile /tmp/phy-tx.pcap & # 4. Dừng capture sau 60 giây kill %1 %2 %3 # SCP pcap files về workstation → mở trong Wireshark ### Diagnose packet loss theo layer # Layer 1 — Physical: kiểm tra vmnic errors esxcli network nic stats get -n vmnic0 | grep -i "drop\|error" # Nếu có drops → SFP bad, cable, switch port flapping # Layer 2 — vSwitch: kiểm tra port group drops esxcli network port filter stats get | grep -i "drop" # Drop ở đây → vDS uplink bandwidth limit, NIOC throttling # Layer 3 — Guest: ping flood test # Từ guest: ping -f -l 1472 gateway_ip # Nếu loss > 0% → MTU mismatch (Jumbo Frame chưa enabled end-to-end)
Checklist Troubleshooting Network
Checklist Performance Baseline