1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 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 122 123 124 125 126 127 128 129 130 131 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 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 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 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 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 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 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 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 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 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 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 673 674 675 676 677 678 679 680 681 682 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 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766
|
//go:build linux
package resources
import (
"errors"
"fmt"
"io/fs"
"net"
"net/http"
"os"
"path/filepath"
"slices"
"strconv"
"strings"
"github.com/jaypipes/pcidb"
"golang.org/x/sys/unix"
"github.com/lxc/incus/v6/shared/api"
)
var sysClassNet = "/sys/class/net"
var netProtocols = map[uint64]string{
1: "ethernet",
19: "ATM",
32: "infiniband",
}
func networkAddDeviceInfo(devicePath string, pciDB *pcidb.PCIDB, uname unix.Utsname, card *api.ResourcesNetworkCard) error {
deviceDeviceDir, err := getDeviceDir(devicePath)
if err != nil {
return fmt.Errorf("Failed to read %q: %w", devicePath, err)
}
// VDPA
vDPAMatches, err := filepath.Glob(filepath.Join(deviceDeviceDir, "vdpa*"))
if err != nil {
return fmt.Errorf("Malformed VDPA device name search pattern: %w", err)
}
if len(vDPAMatches) > 0 {
vdpa := api.ResourcesNetworkCardVDPA{}
splittedPath := strings.Split(vDPAMatches[0], "/")
vdpa.Name = splittedPath[len(splittedPath)-1]
vDPADevMatches, err := filepath.Glob(filepath.Join(vDPAMatches[0], "vhost-vdpa-*"))
if err != nil {
return fmt.Errorf("Malformed VDPA device name search pattern: %w", err)
}
if len(vDPADevMatches) == 0 {
return fmt.Errorf("Failed to find VDPA device at device path %q", vDPAMatches[0])
}
splittedPath = strings.Split(vDPADevMatches[0], "/")
vdpa.Device = splittedPath[len(splittedPath)-1]
// Add the VDPA data to the card
card.VDPA = &vdpa
}
// SRIOV
if sysfsExists(filepath.Join(deviceDeviceDir, "sriov_numvfs")) {
sriov := api.ResourcesNetworkCardSRIOV{}
// Get maximum and current VF count
vfMaximum, err := readUint(filepath.Join(deviceDeviceDir, "sriov_totalvfs"))
if err != nil {
return fmt.Errorf("Failed to read %q: %w", filepath.Join(deviceDeviceDir, "sriov_totalvfs"), err)
}
vfCurrent, err := readUint(filepath.Join(deviceDeviceDir, "sriov_numvfs"))
if err != nil {
return fmt.Errorf("Failed to read %q: %w", filepath.Join(deviceDeviceDir, "sriov_numvfs"), err)
}
sriov.MaximumVFs = vfMaximum
sriov.CurrentVFs = vfCurrent
// Add the SRIOV data to the card
card.SRIOV = &sriov
}
// NUMA node
if sysfsExists(filepath.Join(deviceDeviceDir, "numa_node")) {
numaNode, err := readInt(filepath.Join(deviceDeviceDir, "numa_node"))
if err != nil {
return fmt.Errorf("Failed to read %q: %w", filepath.Join(deviceDeviceDir, "numa_node"), err)
}
if numaNode > 0 {
card.NUMANode = uint64(numaNode)
}
}
// USB address
usbAddr, err := usbAddress(deviceDeviceDir)
if err != nil {
return fmt.Errorf("Failed to find USB address for %q: %w", deviceDeviceDir, err)
}
if usbAddr != "" {
card.USBAddress = usbAddr
}
// Vendor and product
deviceVendorPath := filepath.Join(deviceDeviceDir, "vendor")
if sysfsExists(deviceVendorPath) {
id, err := os.ReadFile(deviceVendorPath)
if err != nil {
return fmt.Errorf("Failed to read %q: %w", deviceVendorPath, err)
}
card.VendorID = strings.TrimPrefix(strings.TrimSpace(string(id)), "0x")
}
deviceDevicePath := filepath.Join(deviceDeviceDir, "device")
if sysfsExists(deviceDevicePath) {
id, err := os.ReadFile(deviceDevicePath)
if err != nil {
return fmt.Errorf("Failed to read %q: %w", deviceDevicePath, err)
}
card.ProductID = strings.TrimPrefix(strings.TrimSpace(string(id)), "0x")
}
// Fill vendor and product names
if pciDB != nil {
vendor, ok := pciDB.Vendors[card.VendorID]
if ok {
card.Vendor = vendor.Name
for _, product := range vendor.Products {
if product.ID == card.ProductID {
card.Product = product.Name
break
}
}
}
}
// Driver information
driverPath := filepath.Join(deviceDeviceDir, "driver")
if sysfsExists(driverPath) {
linkTarget, err := filepath.EvalSymlinks(driverPath)
if err != nil {
return fmt.Errorf("Failed to find device directory %q: %w", driverPath, err)
}
// Set the driver name
card.Driver = filepath.Base(linkTarget)
// Try to get the version, fallback to kernel version
out, err := os.ReadFile(filepath.Join(driverPath, "module", "version"))
if err == nil {
card.DriverVersion = strings.TrimSpace(string(out))
} else {
card.DriverVersion = strings.TrimRight(string(uname.Release[:]), "\x00")
}
}
// Port information
netPath := filepath.Join(devicePath, "net")
if sysfsExists(netPath) {
card.Ports = []api.ResourcesNetworkCardPort{}
entries, err := os.ReadDir(netPath)
if err != nil {
return fmt.Errorf("Failed to list %q: %w", netPath, err)
}
// Iterate and record port data
for _, entry := range entries {
interfacePath := filepath.Join(netPath, entry.Name())
info := &api.ResourcesNetworkCardPort{
ID: entry.Name(),
}
// Add type
if sysfsExists(filepath.Join(interfacePath, "type")) {
devType, err := readUint(filepath.Join(interfacePath, "type"))
if err != nil {
return fmt.Errorf("Failed to read %q: %w", filepath.Join(interfacePath, "type"), err)
}
protocol, ok := netProtocols[devType]
if !ok {
info.Protocol = "unknown"
} else {
info.Protocol = protocol
}
}
// Add MAC address
if info.Address == "" && sysfsExists(filepath.Join(interfacePath, "address")) {
address, err := os.ReadFile(filepath.Join(interfacePath, "address"))
if err != nil {
return fmt.Errorf("Failed to read %q: %w", filepath.Join(interfacePath, "address"), err)
}
info.Address = strings.TrimSpace(string(address))
}
// Add port number
if sysfsExists(filepath.Join(interfacePath, "dev_port")) {
port, err := readUint(filepath.Join(interfacePath, "dev_port"))
if err != nil {
return fmt.Errorf("Failed to read %q: %w", filepath.Join(interfacePath, "dev_port"), err)
}
info.Port = port
}
// Add infiniband specific information
if info.Protocol == "infiniband" && sysfsExists(filepath.Join(devicePath, "infiniband")) {
infiniband := &api.ResourcesNetworkCardPortInfiniband{}
madPath := filepath.Join(devicePath, "infiniband_mad")
if sysfsExists(madPath) {
ibPort := info.Port + 1
entries, err := os.ReadDir(madPath)
if err != nil {
return fmt.Errorf("Failed to list %q: %w", madPath, err)
}
for _, entry := range entries {
entryName := entry.Name()
currentPort, err := readUint(filepath.Join(madPath, entryName, "port"))
if err != nil {
return fmt.Errorf("Failed to read %q: %w", filepath.Join(madPath, entryName, "port"), err)
}
if currentPort != ibPort {
continue
}
if !sysfsExists(filepath.Join(madPath, entryName, "dev")) {
continue
}
dev, err := os.ReadFile(filepath.Join(madPath, entryName, "dev"))
if err != nil {
return fmt.Errorf("Failed to read %q: %w", filepath.Join(madPath, entryName, "dev"), err)
}
if strings.HasPrefix(entryName, "issm") {
infiniband.IsSMName = entryName
infiniband.IsSMDevice = strings.TrimSpace(string(dev))
}
if strings.HasPrefix(entryName, "umad") {
infiniband.MADName = entryName
infiniband.MADDevice = strings.TrimSpace(string(dev))
}
}
}
verbsPath := filepath.Join(devicePath, "infiniband_verbs")
if sysfsExists(verbsPath) {
entries, err := os.ReadDir(verbsPath)
if err != nil {
return fmt.Errorf("Failed to list %q: %w", verbsPath, err)
}
if len(entries) == 1 {
verbName := entries[0].Name()
infiniband.VerbName = verbName
if !sysfsExists(filepath.Join(verbsPath, verbName, "dev")) {
continue
}
dev, err := os.ReadFile(filepath.Join(verbsPath, verbName, "dev"))
if err != nil {
return fmt.Errorf("Failed to read %q: %w", filepath.Join(verbsPath, verbName, "dev"), err)
}
infiniband.VerbDevice = strings.TrimSpace(string(dev))
}
}
info.Infiniband = infiniband
}
if sysfsExists(filepath.Join(devicePath, "physfn")) {
// Getting physical port info for VFs makes no sense
card.Ports = append(card.Ports, *info)
continue
}
// Attempt to add ethtool details (ignore failures)
err = ethtoolAddPortInfo(info)
if err != nil {
continue
}
card.Ports = append(card.Ports, *info)
}
if len(card.Ports) > 0 {
err = ethtoolAddCardInfo(card.Ports[0].ID, card)
if err != nil {
return fmt.Errorf("Failed to add card info: %w", err)
}
}
}
return nil
}
// GetNetwork returns a filled api.ResourcesNetwork struct ready for use by Incus.
func GetNetwork() (*api.ResourcesNetwork, error) {
network := api.ResourcesNetwork{}
network.Cards = []api.ResourcesNetworkCard{}
// Get uname for driver version
uname := unix.Utsname{}
err := unix.Uname(&uname)
if err != nil {
return nil, fmt.Errorf("Failed to get uname: %w", err)
}
// Load PCI database
pciDB, err := pcidb.New()
if err != nil {
pciDB = nil
}
// Temporary variables
pciKnown := []string{}
pciVFs := map[string][]api.ResourcesNetworkCard{}
// Detect all Networks available through kernel network interface
if sysfsExists(sysClassNet) {
entries, err := os.ReadDir(sysClassNet)
if err != nil {
return nil, fmt.Errorf("Failed to list %q: %w", sysClassNet, err)
}
// Iterate and add to our list
for _, entry := range entries {
entryName := entry.Name()
entryPath := filepath.Join(sysClassNet, entryName)
devicePath := filepath.Join(entryPath, "device")
// Only keep physical network devices
if !sysfsExists(filepath.Join(entryPath, "device")) {
continue
}
// Setup the entry
card := api.ResourcesNetworkCard{}
// PCI address.
pciAddr, err := pciAddress(devicePath)
if err != nil {
return nil, fmt.Errorf("Failed to find PCI address for %q: %w", devicePath, err)
}
if pciAddr != "" {
card.PCIAddress = pciAddr
// Skip devices we already know about
if slices.Contains(pciKnown, card.PCIAddress) {
continue
}
pciKnown = append(pciKnown, card.PCIAddress)
}
// Add device information for PFs
err = networkAddDeviceInfo(devicePath, pciDB, uname, &card)
if err != nil {
return nil, fmt.Errorf("Failed to add device information for %q: %w", devicePath, err)
}
// Add to list
if sysfsExists(filepath.Join(devicePath, "physfn")) {
// Virtual functions need to be added to the parent
linkTarget, err := filepath.EvalSymlinks(filepath.Join(devicePath, "physfn"))
if err != nil {
return nil, fmt.Errorf("Failed to find %q: %w", filepath.Join(devicePath, "physfn"), err)
}
parentAddress := filepath.Base(linkTarget)
_, ok := pciVFs[parentAddress]
if !ok {
pciVFs[parentAddress] = []api.ResourcesNetworkCard{}
}
pciVFs[parentAddress] = append(pciVFs[parentAddress], card)
} else {
network.Cards = append(network.Cards, card)
}
}
}
// Detect remaining Networks on PCI bus
if sysfsExists(sysBusPci) {
entries, err := os.ReadDir(sysBusPci)
if err != nil {
return nil, fmt.Errorf("Failed to list %q: %w", sysBusPci, err)
}
// Iterate and add to our list
for _, entry := range entries {
entryName := entry.Name()
devicePath := filepath.Join(sysBusPci, entryName)
// Skip devices we already know about
if slices.Contains(pciKnown, entryName) {
continue
}
// Only care about identifiable devices
if !sysfsExists(filepath.Join(devicePath, "class")) {
continue
}
class, err := os.ReadFile(filepath.Join(devicePath, "class"))
if err != nil {
return nil, fmt.Errorf("Failed to read %q: %w", filepath.Join(devicePath, "class"), err)
}
// Only care about VGA devices
if !strings.HasPrefix(string(class), "0x02") {
continue
}
// Start building up data
card := api.ResourcesNetworkCard{}
card.PCIAddress = entryName
// Add device information
err = networkAddDeviceInfo(devicePath, pciDB, uname, &card)
if err != nil {
return nil, fmt.Errorf("Failed to add device information for %q: %w", devicePath, err)
}
// Add to list
if sysfsExists(filepath.Join(devicePath, "physfn")) {
// Virtual functions need to be added to the parent
linkTarget, err := filepath.EvalSymlinks(filepath.Join(devicePath, "physfn"))
if err != nil {
return nil, fmt.Errorf("Failed to find %q: %w", filepath.Join(devicePath, "physfn"), err)
}
parentAddress := filepath.Base(linkTarget)
_, ok := pciVFs[parentAddress]
if !ok {
pciVFs[parentAddress] = []api.ResourcesNetworkCard{}
}
pciVFs[parentAddress] = append(pciVFs[parentAddress], card)
} else {
network.Cards = append(network.Cards, card)
}
}
}
// Add SRIOV devices and count devices
network.Total = 0
for _, card := range network.Cards {
if card.SRIOV != nil {
card.SRIOV.VFs = pciVFs[card.PCIAddress]
network.Total += uint64(len(card.SRIOV.VFs))
}
network.Total++
}
return &network, nil
}
// GetNetworkState returns the OS configuration for the network interface.
func GetNetworkState(name string) (*api.NetworkState, error) {
// Get some information
netIf, err := net.InterfaceByName(name)
if err != nil {
return nil, api.StatusErrorf(http.StatusNotFound, "Network interface %q not found", name)
}
netState := "down"
netType := "unknown"
if netIf.Flags&net.FlagBroadcast > 0 {
netType = "broadcast"
}
if netIf.Flags&net.FlagPointToPoint > 0 {
netType = "point-to-point"
}
if netIf.Flags&net.FlagLoopback > 0 {
netType = "loopback"
}
if netIf.Flags&net.FlagUp > 0 {
netState = "up"
}
network := api.NetworkState{
Addresses: []api.NetworkStateAddress{},
Hwaddr: netIf.HardwareAddr.String(),
Mtu: netIf.MTU,
State: netState,
Type: netType,
}
// Populate address information.
addrs, err := netIf.Addrs()
if err == nil {
for _, addr := range addrs {
fields := strings.SplitN(addr.String(), "/", 2)
if len(fields) != 2 {
continue
}
family := "inet"
if strings.Contains(fields[0], ":") {
family = "inet6"
}
scope := "global"
if strings.HasPrefix(fields[0], "127") {
scope = "local"
}
if fields[0] == "::1" {
scope = "local"
}
if strings.HasPrefix(fields[0], "169.254") {
scope = "link"
}
if strings.HasPrefix(fields[0], "fe80:") {
scope = "link"
}
address := api.NetworkStateAddress{}
address.Family = family
address.Address = fields[0]
address.Netmask = fields[1]
address.Scope = scope
network.Addresses = append(network.Addresses, address)
}
}
// Populate bond details.
bondPath := fmt.Sprintf("/sys/class/net/%s/bonding", name)
if sysfsExists(bondPath) {
bonding := api.NetworkStateBond{}
// Bond mode.
strValue, err := os.ReadFile(filepath.Join(bondPath, "mode"))
if err == nil {
bonding.Mode = strings.Split(strings.TrimSpace(string(strValue)), " ")[0]
}
// Bond transmit policy.
strValue, err = os.ReadFile(filepath.Join(bondPath, "xmit_hash_policy"))
if err == nil {
bonding.TransmitPolicy = strings.Split(strings.TrimSpace(string(strValue)), " ")[0]
}
// Up delay.
uintValue, err := readUint(filepath.Join(bondPath, "updelay"))
if err == nil {
bonding.UpDelay = uintValue
}
// Down delay.
uintValue, err = readUint(filepath.Join(bondPath, "downdelay"))
if err == nil {
bonding.DownDelay = uintValue
}
// MII frequency.
uintValue, err = readUint(filepath.Join(bondPath, "miimon"))
if err == nil {
bonding.MIIFrequency = uintValue
}
// MII state.
strValue, err = os.ReadFile(filepath.Join(bondPath, "mii_status"))
if err == nil {
bonding.MIIState = strings.TrimSpace(string(strValue))
}
// Lower devices.
strValue, err = os.ReadFile(filepath.Join(bondPath, "slaves"))
if err == nil {
bonding.LowerDevices = strings.Split(strings.TrimSpace(string(strValue)), " ")
}
network.Bond = &bonding
}
// Populate bridge details.
bridgePath := fmt.Sprintf("/sys/class/net/%s/bridge", name)
if sysfsExists(bridgePath) {
bridge := api.NetworkStateBridge{}
// Bridge ID.
strValue, err := os.ReadFile(filepath.Join(bridgePath, "bridge_id"))
if err == nil {
bridge.ID = strings.TrimSpace(string(strValue))
}
// Bridge STP.
uintValue, err := readUint(filepath.Join(bridgePath, "stp_state"))
if err == nil {
bridge.STP = uintValue == 1
}
// Bridge forward delay.
uintValue, err = readUint(filepath.Join(bridgePath, "forward_delay"))
if err == nil {
bridge.ForwardDelay = uintValue
}
// Bridge default VLAN.
uintValue, err = readUint(filepath.Join(bridgePath, "default_pvid"))
if err == nil {
bridge.VLANDefault = uintValue
}
// Bridge VLAN filtering.
uintValue, err = readUint(filepath.Join(bridgePath, "vlan_filtering"))
if err == nil {
bridge.VLANFiltering = uintValue == 1
}
// Upper devices.
bridgeIfPath := fmt.Sprintf("/sys/class/net/%s/brif", name)
if sysfsExists(bridgeIfPath) {
entries, err := os.ReadDir(bridgeIfPath)
if err == nil {
bridge.UpperDevices = []string{}
for _, entry := range entries {
bridge.UpperDevices = append(bridge.UpperDevices, entry.Name())
}
}
}
network.Bridge = &bridge
}
// Populate VLAN details.
type vlan struct {
lower string
vid uint64
}
vlans := map[string]vlan{}
vlanPath := "/proc/net/vlan/config"
if sysfsExists(vlanPath) {
entries, err := os.ReadFile(vlanPath)
if err != nil {
return nil, err
}
for _, line := range strings.Split(string(entries), "\n") {
fields := strings.Split(line, "|")
if len(fields) != 3 {
continue
}
vName := strings.TrimSpace(fields[0])
vVID, err := strconv.ParseUint(strings.TrimSpace(fields[1]), 10, 64)
if err != nil {
continue
}
vLower := strings.TrimSpace(fields[2])
vlans[vName] = vlan{
lower: vLower,
vid: vVID,
}
}
}
// Check if the interface is a VLAN.
entry, ok := vlans[name]
if ok {
network.VLAN = &api.NetworkStateVLAN{
LowerDevice: entry.lower,
VID: entry.vid,
}
}
// Get counters.
counters, err := GetNetworkCounters(name)
if err != nil {
return nil, err
}
network.Counters = counters
return &network, nil
}
// GetNetworkCounters returns the current packet counters for the network interface.
func GetNetworkCounters(name string) (*api.NetworkStateCounters, error) {
counters := api.NetworkStateCounters{}
// Get counters
content, err := os.ReadFile("/proc/net/dev")
if err != nil {
if errors.Is(err, fs.ErrNotExist) {
return &counters, nil
}
return nil, err
}
for _, line := range strings.Split(string(content), "\n") {
fields := strings.Fields(line)
if len(fields) != 17 {
continue
}
intName := strings.TrimSuffix(fields[0], ":")
if intName != name {
continue
}
rxBytes, err := strconv.ParseInt(fields[1], 10, 64)
if err != nil {
return nil, err
}
rxPackets, err := strconv.ParseInt(fields[2], 10, 64)
if err != nil {
return nil, err
}
txBytes, err := strconv.ParseInt(fields[9], 10, 64)
if err != nil {
return nil, err
}
txPackets, err := strconv.ParseInt(fields[10], 10, 64)
if err != nil {
return nil, err
}
counters.BytesSent = txBytes
counters.BytesReceived = rxBytes
counters.PacketsSent = txPackets
counters.PacketsReceived = rxPackets
break
}
return &counters, nil
}
|