File: resources.go

package info (click to toggle)
incus 6.0.5-6
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 25,788 kB
  • sloc: sh: 16,313; ansic: 3,121; python: 457; makefile: 337; ruby: 51; sql: 50; lisp: 6
file content (102 lines) | stat: -rw-r--r-- 2,214 bytes parent folder | download | duplicates (2)
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
//go:build linux

package resources

import (
	"fmt"
	"sync"
	"time"

	"github.com/lxc/incus/v6/shared/api"
)

// Cache to speed up concurrent runs.
var (
	muResources   sync.Mutex
	lastResources *api.Resources
	lastRun       time.Time
)

// GetResources returns a filled api.Resources struct ready for use by Incus.
func GetResources() (*api.Resources, error) {
	// Ensure only one concurrent run.
	muResources.Lock()
	defer muResources.Unlock()

	// Check if we ran less than 10s ago.
	if lastResources != nil && lastRun.Add(10*time.Second).Before(time.Now()) {
		return lastResources, nil
	}

	// Get CPU information
	cpu, err := GetCPU()
	if err != nil {
		return nil, fmt.Errorf("Failed to retrieve CPU information: %w", err)
	}

	// Get memory information
	memory, err := GetMemory()
	if err != nil {
		return nil, fmt.Errorf("Failed to retrieve memory information: %w", err)
	}

	// Get GPU information
	gpu, err := GetGPU()
	if err != nil {
		return nil, fmt.Errorf("Failed to retrieve GPU information: %w", err)
	}

	// Get network card information
	network, err := GetNetwork()
	if err != nil {
		return nil, fmt.Errorf("Failed to retrieve network information: %w", err)
	}

	// Get storage information
	storage, err := GetStorage()
	if err != nil {
		return nil, fmt.Errorf("Failed to retrieve storage information: %w", err)
	}

	// Get USB information
	usb, err := GetUSB()
	if err != nil {
		return nil, fmt.Errorf("Failed to retrieve USB information: %w", err)
	}

	// Get PCI information
	pci, err := GetPCI()
	if err != nil {
		return nil, fmt.Errorf("Failed to retrieve PCI information: %w", err)
	}

	// Get system information
	system, err := GetSystem()
	if err != nil {
		return nil, fmt.Errorf("Failed to retrieve system information: %w", err)
	}

	load, err := GetLoad()
	if err != nil {
		return nil, fmt.Errorf("Failed to retrieve load information: %w", err)
	}

	// Build the final struct
	resources := api.Resources{
		CPU:     *cpu,
		Memory:  *memory,
		GPU:     *gpu,
		Network: *network,
		Storage: *storage,
		USB:     *usb,
		PCI:     *pci,
		System:  *system,
		Load:    *load,
	}

	// Update the cache.
	lastResources = &resources
	lastRun = time.Now()

	return &resources, nil
}