Class: Pvectl::Presenters::Vm

Inherits:
Base
  • Object
show all
Defined in:
lib/pvectl/presenters/vm.rb,
sig/pvectl/presenters/vm.rbs

Overview

Presenter for QEMU virtual machines.

Defines column layout and formatting for table output. Used by formatters to render VM data in various formats.

Standard columns: NAME, VMID, STATUS, NODE, CPU, MEMORY Wide columns add: UPTIME, TEMPLATE, TAGS, DISK, IP, AGENT, HA, BACKUP

Examples:

Using with formatter

presenter = Vm.new
formatter = Formatters::Table.new
output = formatter.format(vms, presenter)

See Also:

Direct Known Subclasses

TopVm

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Base

#format_bytes, #format_firewall, #format_firewall_rules, #format_task_history, #tags_array, #tags_display, #template_display, #to_wide_row, #uptime_human, #wide_columns

Instance Attribute Details

#vmModels::Vm (readonly) Also known as: resource



249
250
251
# File 'lib/pvectl/presenters/vm.rb', line 249

def vm
  @vm
end

Instance Method Details

#build_mac_ip_map(agent_ips) ⇒ Hash

Builds MAC address to IP mapping from agent interfaces.



618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
# File 'lib/pvectl/presenters/vm.rb', line 618

def build_mac_ip_map(agent_ips)
  return {} if agent_ips.nil?

  map = {}
  agent_ips.each do |iface|
    mac = iface[:"hardware-address"]&.downcase
    next if mac.nil?

    # Find first non-loopback IPv4 address
    ip_addrs = iface[:"ip-addresses"] || []
    ipv4 = ip_addrs.find { |a| a[:"ip-address-type"] == "ipv4" && a[:"ip-address"] != "127.0.0.1" }
    map[mac] = ipv4[:"ip-address"] if ipv4
  end
  map
end

#columnsArray<String>

Returns column headers for standard table output.



27
28
29
# File 'lib/pvectl/presenters/vm.rb', line 27

def columns
  %w[NAME VMID STATUS NODE CPU MEMORY]
end

#consume(*keys) ⇒ void

This method returns an undefined value.

Registers config keys as consumed by a format method.



827
828
829
# File 'lib/pvectl/presenters/vm.rb', line 827

def consume(*keys)
  @consumed_keys.merge(keys.map(&:to_sym))
end

#consume_matching(config, pattern) ⇒ void

This method returns an undefined value.

Consumes all config keys matching a pattern.



836
837
838
# File 'lib/pvectl/presenters/vm.rb', line 836

def consume_matching(config, pattern)
  config.keys.select { |k| k.to_s.match?(pattern) }.each { |k| consume(k) }
end

#cpu_percentString

Returns CPU usage as percentage string.

For running VMs, shows actual usage percentage. For stopped VMs, shows "-" for usage but includes core count if available.



179
180
181
182
183
184
185
# File 'lib/pvectl/presenters/vm.rb', line 179

def cpu_percent
  return "-" if vm.maxcpu.nil?
  return "-/#{vm.maxcpu}" unless vm.running?
  return "-/#{vm.maxcpu}" if vm.cpu.nil?

  "#{(vm.cpu * 100).round}%/#{vm.maxcpu}"
end

#disk_displayString

Returns disk formatted as "used/total GB".



240
241
242
243
244
# File 'lib/pvectl/presenters/vm.rb', line 240

def disk_display
  return "-" if disk_used_gb.nil?

  "#{disk_used_gb}/#{disk_total_gb} GB"
end

#disk_total_gbInteger?

Returns total disk in GB.



231
232
233
234
235
# File 'lib/pvectl/presenters/vm.rb', line 231

def disk_total_gb
  return nil if vm.maxdisk.nil?

  (vm.maxdisk.to_f / 1024 / 1024 / 1024).round
end

#disk_used_gbInteger?

Returns disk used in GB.



222
223
224
225
226
# File 'lib/pvectl/presenters/vm.rb', line 222

def disk_used_gb
  return nil if vm.disk.nil?

  (vm.disk.to_f / 1024 / 1024 / 1024).round
end

#display_nameString

Returns display name, falling back to "VM-vmid" if name is nil.



169
170
171
# File 'lib/pvectl/presenters/vm.rb', line 169

def display_name
  vm.name || "VM-#{vm.vmid}"
end

#extra_columnsArray<String>

Returns additional column headers for wide output.



34
35
36
# File 'lib/pvectl/presenters/vm.rb', line 34

def extra_columns
  %w[UPTIME TEMPLATE TAGS DISK IP AGENT HA BACKUP]
end

#extra_values(model, **_context) ⇒ Array<String>

Returns additional values for wide output.

Note: IP, AGENT, and BACKUP are placeholders for future implementation that would require additional API calls to the QEMU guest agent.



63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/pvectl/presenters/vm.rb', line 63

def extra_values(model, **_context)
  @vm = model
  [
    uptime_human,
    template_display,
    tags_display,
    disk_display,
    "-",              # IP - requires QEMU agent (future enhancement)
    "-",              # AGENT status (future enhancement)
    vm.hastate || "-",
    "-"               # BACKUP schedule (future enhancement)
  ]
end

#find_bootdisk_size(config) ⇒ String

Finds the bootdisk size from boot order config.

Parses the boot order to find the first device, then extracts its size from the disk config string. Falls back to maxdisk from model.



298
299
300
301
302
303
304
305
306
307
308
309
# File 'lib/pvectl/presenters/vm.rb', line 298

def find_bootdisk_size(config)
  boot = config[:boot]
  if boot
    first_dev = boot.to_s.sub(/^order=/, "").split(";").first
    if first_dev && config[first_dev.to_sym]
      disk_str = config[first_dev.to_sym].to_s
      size_part = disk_str.split(",").find { |p| p.start_with?("size=") }
      return size_part.sub("size=", "") if size_part
    end
  end
  vm.maxdisk ? format_bytes(vm.maxdisk) : "-"
end

#format_agent_options(config) ⇒ Hash

Formats QEMU guest agent as sub-section Hash for Options.

Matches PVE Options tab layout with separate fields for enable/disable, guest-trim, and freeze-fs-on-backup.



492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
# File 'lib/pvectl/presenters/vm.rb', line 492

def format_agent_options(config)
  agent = config[:agent]
  unless agent
    return {
      "Use QEMU Guest Agent" => "No",
      "Run guest-trim after a disk move or VM migration" => "No",
      "Freeze/thaw guest filesystems on backup for consistency" => "No"
    }
  end

  parts = agent.to_s.split(",")
  enabled = parts.first == "1"

  opts = {}
  parts[1..].each { |p| k, v = p.split("=", 2); opts[k] = v }

  result = {
    "Use QEMU Guest Agent" => enabled ? "Yes" : "No",
    "Run guest-trim after a disk move or VM migration" => opts["fstrim_cloned_disks"] == "1" ? "Yes" : "No",
    "Freeze/thaw guest filesystems on backup for consistency" => opts["freeze-fs-on-backup"] == "1" ? "Yes" : "No"
  }
  result["Type"] = opts["type"] if opts["type"]
  result
end

#format_audio(config) ⇒ String

Formats audio device section.



761
762
763
764
# File 'lib/pvectl/presenters/vm.rb', line 761

def format_audio(config)
  consume(:audio0)
  config[:audio0]&.to_s || "-"
end

#format_blockstat(status) ⇒ Array<Hash>, String

Formats Block Device Statistics section.

Renders per-disk I/O statistics from the running VM's status payload. Available only for running VMs — Proxmox populates blockstat as part of /status/current when the QEMU process is alive.



319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
# File 'lib/pvectl/presenters/vm.rb', line 319

def format_blockstat(status)
  blockstat = status[:blockstat]
  return "-" if blockstat.nil? || blockstat.empty?

  blockstat.sort_by { |name, _| name.to_s }.map do |name, stats|
    stats ||= {}
    {
      "DEVICE" => name.to_s,
      "READ" => format_bytes(stats[:rd_bytes]),
      "WRITTEN" => format_bytes(stats[:wr_bytes]),
      "READ_IOPS" => (stats[:rd_operations] || 0).to_s,
      "WRITE_IOPS" => (stats[:wr_operations] || 0).to_s
    }
  end
end

#format_cloud_init(config) ⇒ Hash, String

Formats Cloud-Init section.

Detects cloud-init presence by checking for CI config keys (ciuser, sshkeys, etc.) OR a cloud-init drive (any disk with "cloudinit" in the volume name). This matches PVE behavior where the Cloud-Init tab appears when the drive exists, even without configuration.



683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
# File 'lib/pvectl/presenters/vm.rb', line 683

def format_cloud_init(config)
  ci_keys = i[citype ciuser cipassword cicustom ciupgrade searchdomain nameserver sshkeys]
  ipconfig_keys = config.keys.select { |k| k.to_s.match?(/^ipconfig\d+$/) }
  consume(*ci_keys)
  consume_matching(config, /^ipconfig\d+$/)

  ci_drive = config.keys.any? do |k|
    k.to_s.match?(/^(scsi|ide|virtio|sata)\d+$/) && config[k].to_s.include?("cloudinit")
  end
  has_ci = ci_keys.any? { |k| config[k] } || ipconfig_keys.any? || ci_drive
  return "-" unless has_ci

  result = {
    "User" => config[:ciuser] || "-",
    "Password" => config[:cipassword] ? "set" : "-",
    "DNS Server" => config[:nameserver] || "-",
    "Search Domain" => config[:searchdomain] || "-",
    "SSH Keys" => config[:sshkeys] ? "configured" : "-",
    "Upgrade Packages" => config[:ciupgrade] == 0 ? "No" : "Yes",
    "CI Type" => config[:citype] || "nocloud",
    "CI Custom" => config[:cicustom] || "-"
  }

  if ipconfig_keys.any?
    result["IP Config"] = ipconfig_keys.sort.map do |key|
      { "INTERFACE" => key.to_s.sub("ipconfig", "net"), "CONFIG" => config[key].to_s }
    end
  end

  result
end

#format_efi_disk(config) ⇒ String

Formats EFI disk section.



770
771
772
773
# File 'lib/pvectl/presenters/vm.rb', line 770

def format_efi_disk(config)
  consume(:efidisk0)
  config[:efidisk0]&.to_s || "-"
end

#format_hardware(config, data) ⇒ Hash

Formats Hardware section (PVE Hardware tab).

Shows memory, balloon, processors, BIOS, machine type, display, SCSI controller, disks, network, and peripheral devices.



343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
# File 'lib/pvectl/presenters/vm.rb', line 343

def format_hardware(config, data)
  consume(:bios, :machine, :scsihw, :memory, :balloon, :shares,
          :sockets, :cores, :cpu, :vcpus, :cpulimit, :cpuunits, :vga)

  # Memory line — flat string by default, expanded to a Hash with
  # ballooning details when status payload contains ballooninfo.
  total_mb = config[:memory] || (vm.maxmem ? vm.maxmem / 1024 / 1024 : nil)
  memory_str = total_mb ? "#{(total_mb.to_f / 1024).round(2)} GiB" : "-"
  memory_section = format_memory_section(memory_str, data[:status])

  # Balloon line
  balloon = config[:balloon]
  balloon_str = if balloon && balloon > 0
                  "enabled (min: #{(balloon.to_f / 1024).round(1)} GiB)"
                else
                  "disabled"
                end

  # Processors line: "4 (2 sockets, 2 cores) [host]"
  sockets = config[:sockets] || 1
  cores = config[:cores] || 1
  cpu_type = config[:cpu] || "kvm64"
  total = sockets * cores
  processors_str = "#{total} (#{sockets} sockets, #{cores} cores) [#{cpu_type}]"

  # BIOS
  bios = config[:bios] || "seabios"
  bios_display = bios == "ovmf" ? "UEFI (OVMF)" : "SeaBIOS"

  # Machine
  machine_str = config[:machine] || "i440fx"

  {
    "Memory" => memory_section,
    "Balloon" => balloon_str,
    "Processors" => processors_str,
    "BIOS" => bios_display,
    "Machine" => machine_str,
    "Display" => config[:vga] || "Default",
    "SCSI Controller" => config[:scsihw] || "lsi",
    "EFI Disk" => format_efi_disk(config),
    "TPM" => format_tpm(config),
    "Disks" => parse_disks(config),
    "Network" => format_network(config, data[:agent_ips]),
    "USB Devices" => format_usb_devices(config),
    "PCI Passthrough" => format_pci_passthrough(config),
    "Serial Ports" => format_serial_ports(config),
    "Audio" => format_audio(config)
  }
end

#format_memory_section(memory_str, status) ⇒ String, Hash

Formats Memory entry in the Hardware section.

Returns a flat string with configured memory when ballooning info is not available (balloon driver inactive or VM stopped). When the status payload contains ballooninfo, returns a Hash with the configured value plus runtime balloon metrics from the guest: actual ballooned size, maximum, free memory inside the guest, and total guest-visible memory.



406
407
408
409
410
411
412
413
414
415
416
417
# File 'lib/pvectl/presenters/vm.rb', line 406

def format_memory_section(memory_str, status)
  info = status.is_a?(Hash) ? status[:ballooninfo] : nil
  return memory_str unless info.is_a?(Hash)

  {
    "Configured" => memory_str,
    "Actual" => format_bytes(info[:actual]),
    "Max" => format_bytes(info[:max_mem]),
    "Free (inside guest)" => format_bytes(info[:free_mem]),
    "Total (guest visible)" => format_bytes(info[:total_mem])
  }
end

#format_network(config, agent_ips) ⇒ Array<Hash>, String

Formats network section with IP addresses from agent.

Network keys: net0-31 Format: "model=X,bridge=Y,macaddr=Z,..." Example: "virtio=BC:24:11:AA:BB:CC,bridge=vmbr0"



599
600
601
602
603
604
605
606
607
608
609
610
611
612
# File 'lib/pvectl/presenters/vm.rb', line 599

def format_network(config, agent_ips)
  consume_matching(config, /^net\d+$/)
  net_keys = config.keys.select { |k| k.to_s.match?(/^net\d+$/) }
  return "-" if net_keys.empty?

  # Build MAC -> IP mapping from agent data
  mac_to_ip = build_mac_ip_map(agent_ips)

  networks = net_keys.sort.map do |key|
    parse_network_string(key.to_s, config[key], mac_to_ip)
  end.compact

  networks.empty? ? "-" : networks
end

#format_options(config) ⇒ Hash

Formats Options section (PVE Options tab).

Shows boot, startup, OS type, agent, security, and other VM options.



425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
# File 'lib/pvectl/presenters/vm.rb', line 425

def format_options(config)
  consume(:onboot, :startup, :ostype, :boot, :tablet, :hotplug,
          :acpi, :kvm, :freeze, :localtime, :numa, :agent,
          :protection, :firewall, :lock, :hookscript,
          :args, :vmgenid, :meta, :ha)
  consume_matching(config, /^numa\d+$/)
  consume_matching(config, /^unused\d+$/)

  on_boot = config[:onboot] == 1 ? "Yes" : "No"

  startup = config[:startup]
  startup_display = startup ? startup.to_s : "-"

  ostype_display = format_ostype(config[:ostype])

  boot = config[:boot]
  boot_display = if boot
                   order = boot.to_s.sub(/^order=/, "").split(";").join(", ")
                   order.empty? ? "-" : order
                 else
                   "-"
                 end

  tablet = config[:tablet] == 0 ? "No" : "Yes"
  hotplug_raw = config[:hotplug]
  hotplug = if hotplug_raw
              hotplug_raw.to_s == "0" ? "Disabled" : hotplug_raw.to_s.split(",").join(", ")
            else
              "disk, network, usb"
            end
  acpi = config[:acpi] == 0 ? "No" : "Yes"
  kvm = config[:kvm] == 0 ? "No" : "Yes"
  freeze_cpu = config[:freeze] == 1 ? "Yes" : "No"
  localtime = config[:localtime] == 1 ? "Yes" : "Default"
  numa = config[:numa] == 1 ? "Yes" : "No"

  agent_display = format_agent_options(config)
  protection = config[:protection] == 1 ? "Yes" : "No"
  firewall = config[:firewall] == 1 ? "Yes" : "No"
  hookscript = config[:hookscript] || "-"

  {
    "Start at Boot" => on_boot,
    "Start/Shutdown Order" => startup_display,
    "OS Type" => ostype_display,
    "Boot Order" => boot_display,
    "Use Tablet for Pointer" => tablet,
    "Hotplug" => hotplug,
    "ACPI Support" => acpi,
    "KVM Hardware Virtualization" => kvm,
    "Freeze CPU at Startup" => freeze_cpu,
    "Use Local Time for RTC" => localtime,
    "NUMA" => numa,
    "QEMU Guest Agent" => agent_display,
    "Protection" => protection,
    "Firewall" => firewall,
    "Hookscript" => hookscript
  }
end

#format_ostype(ostype) ⇒ String

Formats OS type for display.



521
522
523
524
525
526
527
528
529
530
531
532
533
# File 'lib/pvectl/presenters/vm.rb', line 521

def format_ostype(ostype)
  case ostype
  when "l26" then "l26 (Linux 2.6+)"
  when "l24" then "l24 (Linux 2.4)"
  when "win11" then "win11 (Windows 11)"
  when "win10" then "win10 (Windows 10)"
  when "win8" then "win8 (Windows 8)"
  when "win7" then "win7 (Windows 7)"
  when "wxp" then "wxp (Windows XP)"
  when "other" then "other"
  else ostype || "-"
  end
end

#format_pci_passthrough(config) ⇒ Array<Hash>, String

Formats PCI passthrough section.



733
734
735
736
737
738
739
740
741
# File 'lib/pvectl/presenters/vm.rb', line 733

def format_pci_passthrough(config)
  pci_keys = config.keys.select { |k| k.to_s.match?(/^hostpci\d+$/) }
  consume_matching(config, /^hostpci\d+$/)
  return "-" if pci_keys.empty?

  pci_keys.sort.map do |key|
    { "NAME" => key.to_s, "CONFIG" => config[key].to_s }
  end
end

#format_pending_changes(pending) ⇒ Array<Hash>, String

Formats pending configuration changes.



808
809
810
811
812
813
814
815
816
817
818
819
820
821
# File 'lib/pvectl/presenters/vm.rb', line 808

def format_pending_changes(pending)
  return "No pending changes" if pending.nil? || pending.empty?

  # Only show entries with actual pending changes (new value or deletion)
  changes = pending.select { |c| c.key?(:pending) || c[:delete] }
  return "No pending changes" if changes.empty?

  changes.map do |change|
    row = { "KEY" => change[:key].to_s, "CURRENT" => change[:value].to_s }
    row["PENDING"] = change[:pending].to_s if change.key?(:pending)
    row["DELETE"] = "yes" if change[:delete]
    row
  end
end

#format_remaining(config) ⇒ Array<Hash>, String

Formats remaining unconsumed config keys as catch-all table.



844
845
846
847
848
849
850
# File 'lib/pvectl/presenters/vm.rb', line 844

def format_remaining(config)
  excluded = i[digest]
  remaining = config.keys.map(&:to_sym) - @consumed_keys.to_a - excluded
  return "-" if remaining.empty?

  remaining.sort.map { |k| { "KEY" => k.to_s, "VALUE" => config[k].to_s } }
end

#format_serial_ports(config) ⇒ Array<Hash>, String

Formats serial ports section.



747
748
749
750
751
752
753
754
755
# File 'lib/pvectl/presenters/vm.rb', line 747

def format_serial_ports(config)
  serial_keys = config.keys.select { |k| k.to_s.match?(/^serial\d+$/) }
  consume_matching(config, /^serial\d+$/)
  return "-" if serial_keys.empty?

  serial_keys.sort.map do |key|
    { "NAME" => key.to_s, "TYPE" => config[key].to_s }
  end
end

#format_snapshots(snapshots) ⇒ Array<Hash>, String

Formats snapshots for table display.



788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
# File 'lib/pvectl/presenters/vm.rb', line 788

def format_snapshots(snapshots)
  return "No snapshots" if snapshots.nil? || snapshots.empty?

  snapshots.map do |snap|
    snaptime = snap[:snaptime]
    date = snaptime ? Time.at(snaptime).strftime("%Y-%m-%d %H:%M:%S") : "-"

    {
      "NAME" => snap[:name],
      "DATE" => date,
      "VMSTATE" => snap[:vmstate] ? "yes" : "no",
      "DESCRIPTION" => snap[:description] || "-"
    }
  end
end

#format_summary(config, status) ⇒ Hash

Formats Summary section (PVE Summary tab).

Shows HA state, resource usage, and (for running VMs) runtime info including uptime, PID, QEMU version, machine type, and I/O statistics.



261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
# File 'lib/pvectl/presenters/vm.rb', line 261

def format_summary(config, status)
  sockets = config[:sockets] || 1
  cores = config[:cores] || 1
  total_cpus = sockets * cores
  cpu_usage = vm.running? && vm.cpu ? "#{(vm.cpu * 100).round(2)}% of #{total_cpus} CPU(s)" : "-"

  mem_usage = if vm.running? && vm.mem && vm.maxmem && vm.maxmem > 0
                pct = ((vm.mem.to_f / vm.maxmem) * 100).round(2)
                "#{pct}% (#{format_bytes(vm.mem)} of #{format_bytes(vm.maxmem)})"
              else
                "-"
              end

  bootdisk_size = find_bootdisk_size(config)

  result = { "HA State" => vm.hastate || "-", "CPU Usage" => cpu_usage,
             "Memory Usage" => mem_usage, "Bootdisk Size" => bootdisk_size }
  if vm.running?
    result["Uptime"] = uptime_human
    result["PID"] = (status[:pid] || "-").to_s
    result["QEMU Version"] = status[:"running-qemu"] || "-"
    result["Machine Type"] = status[:"running-machine"] || "-"
    result["Network In"] = format_bytes(vm.netin)
    result["Network Out"] = format_bytes(vm.netout)
    result["Disk Read"] = format_bytes(status[:diskread])
    result["Disk Written"] = format_bytes(status[:diskwrite])
  end
  result
end

#format_tpm(config) ⇒ String

Formats TPM section.



779
780
781
782
# File 'lib/pvectl/presenters/vm.rb', line 779

def format_tpm(config)
  consume(:tpmstate0)
  config[:tpmstate0]&.to_s || "-"
end

#format_usb_devices(config) ⇒ Array<Hash>, String

Formats USB devices section.



719
720
721
722
723
724
725
726
727
# File 'lib/pvectl/presenters/vm.rb', line 719

def format_usb_devices(config)
  usb_keys = config.keys.select { |k| k.to_s.match?(/^usb\d+$/) }
  consume_matching(config, /^usb\d+$/)
  return "-" if usb_keys.empty?

  usb_keys.sort.map do |key|
    { "NAME" => key.to_s, "CONFIG" => config[key].to_s }
  end
end

#memory_displayString

Returns memory formatted as "used/total GB".

For running VMs, shows actual usage and total. For stopped VMs, shows "-" for usage but includes total if available.



211
212
213
214
215
216
217
# File 'lib/pvectl/presenters/vm.rb', line 211

def memory_display
  return "-" if memory_total_gb.nil?
  return "-/#{memory_total_gb} GB" unless vm.running?
  return "-/#{memory_total_gb} GB" if memory_used_gb.nil?

  "#{memory_used_gb}/#{memory_total_gb} GB"
end

#memory_total_gbFloat?

Returns total memory in GB.



199
200
201
202
203
# File 'lib/pvectl/presenters/vm.rb', line 199

def memory_total_gb
  return nil if vm.maxmem.nil?

  (vm.maxmem.to_f / 1024 / 1024 / 1024).round(1)
end

#memory_used_gbFloat?

Returns memory used in GB.



190
191
192
193
194
# File 'lib/pvectl/presenters/vm.rb', line 190

def memory_used_gb
  return nil if vm.mem.nil?

  (vm.mem.to_f / 1024 / 1024 / 1024).round(1)
end

#parse_disk_string(name, value) ⇒ Hash?

Parses a single disk config string.



560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
# File 'lib/pvectl/presenters/vm.rb', line 560

def parse_disk_string(name, value)
  return nil if value.nil? || value.to_s.empty?
  return nil if value.to_s == "none"

  # Format: "storage:volume,key=value,..."
  parts = value.to_s.split(",")
  storage_part = parts.first

  # Extract storage name (before colon)
  storage = storage_part.include?(":") ? storage_part.split(":").first : storage_part

  # Extract size and format from key=value pairs
  size = nil
  format = nil
  parts[1..].each do |part|
    key, val = part.split("=", 2)
    case key
    when "size" then size = val
    when "format" then format = val
    end
  end

  {
    "NAME" => name,
    "SIZE" => size || "-",
    "STORAGE" => storage,
    "FORMAT" => format || "-"
  }
end

#parse_disks(config) ⇒ Array<Hash>, String

Parses disk configuration strings from VM config.

Disk keys: scsi0-30, ide0-3, virtio0-15, sata0-5 Format: "storage:volume,size=X,format=Y,..." Example: "local-lvm:vm-100-disk-0,size=50G,format=raw"



543
544
545
546
547
548
549
550
551
552
553
# File 'lib/pvectl/presenters/vm.rb', line 543

def parse_disks(config)
  consume_matching(config, /^(scsi|ide|virtio|sata)\d+$/)
  disk_keys = config.keys.select { |k| k.to_s.match?(/^(scsi|ide|virtio|sata)\d+$/) }
  return "-" if disk_keys.empty?

  disks = disk_keys.sort.map do |key|
    parse_disk_string(key.to_s, config[key])
  end.compact

  disks.empty? ? "-" : disks
end

#parse_network_string(name, value, mac_to_ip) ⇒ Hash?

Parses a single network config string.



640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
# File 'lib/pvectl/presenters/vm.rb', line 640

def parse_network_string(name, value, mac_to_ip)
  return nil if value.nil? || value.to_s.empty?

  parts = value.to_s.split(",")
  model = nil
  mac = nil
  bridge = nil
  firewall = "no"

  parts.each do |part|
    key, val = part.split("=", 2)
    case key
    when "bridge" then bridge = val
    when "firewall" then firewall = val == "1" ? "yes" : "no"
    when "virtio", "e1000", "rtl8139", "vmxnet3"
      model = key
      mac = val&.upcase
    when "model" then model = val
    when "macaddr" then mac = val&.upcase
    end
  end

  ip = mac ? mac_to_ip[mac.downcase] : nil

  {
    "NAME" => name,
    "MODEL" => model || "-",
    "BRIDGE" => bridge || "-",
    "FIREWALL" => firewall,
    "MAC" => mac || "-",
    "IP" => ip || "-"
  }
end

#to_description(model) ⇒ Hash

Converts VM model to description format for describe command.

Returns a structured Hash organized by Proxmox VE web UI tabs: Summary, Hardware, Cloud-Init, Options, Task History, Snapshots, Pending Changes. Nested Hashes create indented subsections. Arrays of Hashes render as inline tables.



132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/pvectl/presenters/vm.rb', line 132

def to_description(model)
  @vm = model
  @consumed_keys = Set.new
  data = vm.describe_data || {}
  config = data[:config] || {}
  status = data[:status] || {}

  consume(:name, :description, :tags, :pool, :template)

  {
    "Name" => display_name,
    "VMID" => vm.vmid,
    "Status" => vm.status,
    "Node" => vm.node,
    "Tags" => tags_display,
    "Description" => config[:description] || "-",
    "Summary" => format_summary(config, status),
    "Block Device Statistics" => format_blockstat(status),
    "Hardware" => format_hardware(config, data),
    "Cloud-Init" => format_cloud_init(config),
    "Options" => format_options(config),
    "Firewall" => format_firewall(data[:firewall]),
    "Firewall Rules" => format_firewall_rules(data[:firewall]),
    "Task History" => format_task_history(data[:tasks]),
    "Snapshots" => format_snapshots(data[:snapshots]),
    "Pending Changes" => format_pending_changes(data[:pending]),
    "Additional Configuration" => format_remaining(config)
  }
end

#to_hash(model) ⇒ Hash

Converts VM model to hash for JSON/YAML output.

Returns a structured hash with nested objects for complex data like CPU, memory, disk, uptime, and network.



84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
# File 'lib/pvectl/presenters/vm.rb', line 84

def to_hash(model)
  @vm = model
  {
    "vmid" => vm.vmid,
    "name" => vm.name,
    "status" => vm.status,
    "node" => vm.node,
    "template" => vm.template?,
    "cpu" => {
      "usage_percent" => vm.cpu.nil? ? nil : (vm.cpu * 100).round,
      "cores" => vm.maxcpu
    },
    "memory" => {
      "used_gb" => memory_used_gb,
      "total_gb" => memory_total_gb,
      "used_bytes" => vm.mem,
      "total_bytes" => vm.maxmem
    },
    "disk" => {
      "used_gb" => disk_used_gb,
      "total_gb" => disk_total_gb,
      "used_bytes" => vm.disk,
      "total_bytes" => vm.maxdisk
    },
    "uptime" => {
      "seconds" => vm.uptime,
      "human" => uptime_human
    },
    "network" => {
      "in_bytes" => vm.netin,
      "out_bytes" => vm.netout
    },
    "ha" => {
      "state" => vm.hastate
    },
    "tags" => tags_array
  }
end

#to_row(model, **_context) ⇒ Array<String>

Converts VM model to table row values.



43
44
45
46
47
48
49
50
51
52
53
# File 'lib/pvectl/presenters/vm.rb', line 43

def to_row(model, **_context)
  @vm = model
  [
    display_name,
    vm.vmid.to_s,
    vm.status,
    vm.node,
    cpu_percent,
    memory_display
  ]
end