File: util.go

package info (click to toggle)
incus 6.21.0-1~exp1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 27,496 kB
  • sloc: sh: 17,280; ansic: 3,201; python: 458; makefile: 340; ruby: 51; sql: 50; lisp: 6
file content (375 lines) | stat: -rw-r--r-- 9,415 bytes parent folder | download
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
package drivers

import (
	"context"
	"crypto/sha256"
	"encoding/base64"
	"errors"
	"fmt"
	"io/fs"
	"os"
	"regexp"
	"slices"
	"sort"
	"strconv"
	"strings"
	"time"

	yaml "gopkg.in/yaml.v2"

	"github.com/lxc/incus/v6/internal/linux"
	"github.com/lxc/incus/v6/internal/server/cluster"
	"github.com/lxc/incus/v6/internal/server/db"
	"github.com/lxc/incus/v6/internal/server/instance/drivers/cfg"
	"github.com/lxc/incus/v6/internal/server/instance/drivers/qmp"
	"github.com/lxc/incus/v6/internal/server/instance/instancetype"
	"github.com/lxc/incus/v6/internal/server/state"
	internalUtil "github.com/lxc/incus/v6/internal/util"
	"github.com/lxc/incus/v6/shared/api"
	"github.com/lxc/incus/v6/shared/logger"
	"github.com/lxc/incus/v6/shared/resources"
	"github.com/lxc/incus/v6/shared/units"
)

// GetClusterCPUFlags returns the list of shared CPU flags across.
func GetClusterCPUFlags(ctx context.Context, s *state.State, servers []string, archName string) ([]string, error) {
	// Get the list of cluster members.
	var nodes []db.RaftNode
	err := s.DB.Node.Transaction(ctx, func(ctx context.Context, tx *db.NodeTx) error {
		var err error
		nodes, err = tx.GetRaftNodes(ctx)
		return err
	})
	if err != nil {
		return nil, err
	}

	// Get all the CPU flags for the architecture.
	flagMembers := map[string]int{}
	coreCount := 0

	for _, node := range nodes {
		// Skip if not in the list of servers we're interested in.
		if servers != nil && !slices.Contains(servers, node.Name) {
			continue
		}

		// Get node resources.
		res, err := getNodeResources(s, node.Name, node.Address)
		if err != nil {
			logger.Errorf("Failed to get resources for CPU baseline on %q: %v", node.Name, err)
			continue
		}

		// Skip if not the correct architecture.
		if res.CPU.Architecture != archName {
			continue
		}

		// Add the CPU flags to the map.
		for _, socket := range res.CPU.Sockets {
			for _, core := range socket.Cores {
				coreCount += 1
				for _, flag := range core.Flags {
					flagMembers[flag] += 1
				}
			}
		}
	}

	// Get the host flags.
	info := DriverStatuses()[instancetype.VM].Info
	hostFlags, ok := info.Features["flags"].(map[string]bool)
	if !ok {
		// No CPU flags found.
		return nil, nil
	}

	// Build a set of flags common to all cores.
	flags := []string{}

	for k, v := range flagMembers {
		if v != coreCount {
			continue
		}

		hostVal, ok := hostFlags[k]
		if !ok || hostVal {
			continue
		}

		flags = append(flags, k)
	}

	return flags, nil
}

// ParseMemoryStr parses a human representation of memory value as int64 type.
func ParseMemoryStr(memory string) (valueInt int64, err error) {
	if strings.HasSuffix(memory, "%") {
		var percent, memoryTotal int64

		percent, err = strconv.ParseInt(strings.TrimSuffix(memory, "%"), 10, 64)
		if err != nil {
			return 0, err
		}

		memoryTotal, err = linux.DeviceTotalMemory()
		if err != nil {
			return 0, err
		}

		valueInt = (memoryTotal / 100) * percent
	} else {
		valueInt, err = units.ParseByteSizeString(memory)
	}

	return valueInt, err
}

func qemuEscapeCmdline(value string) string {
	return strings.ReplaceAll(value, ",", ",,")
}

// roundDownToBlockSize returns the largest multiple of blockSize less than or equal to the input value.
func roundDownToBlockSize(value int64, blockSize int64) int64 {
	if value%blockSize == 0 {
		return value
	}

	return ((value / blockSize) - 1) * blockSize
}

// memoryConfigSectionToMap converts a memory object of type cfg.Section to type map[string]any.
func memoryConfigSectionToMap(section *cfg.Section) map[string]any {
	const blockSize = 128 * 1024 * 1024 // 128MiB
	obj := map[string]any{}
	hostNodes := []int{}

	for key, value := range section.Entries {
		if strings.HasPrefix(key, "host-nodes") {
			hostNode, err := strconv.Atoi(value)
			if err != nil {
				continue
			}

			hostNodes = append(hostNodes, hostNode)
		} else if key == "size" {
			// Size in the config is specified in the format: 1024M, so the last character needs to be removed before parsing.
			memSizeMB, err := strconv.Atoi(value[:len(value)-1])
			if err != nil {
				continue
			}

			obj["size"] = roundDownToBlockSize(int64(memSizeMB)*1024*1024, blockSize)
		} else if key == "merge" || key == "dump" || key == "prealloc" || key == "share" || key == "reserve" {
			val := false
			if value == "on" {
				val = true
			}

			obj[key] = val
		} else {
			obj[key] = value
		}
	}

	if len(hostNodes) > 0 {
		obj["host-nodes"] = hostNodes
	}

	return obj
}

// extractTrailingNumber extracts the trailing number from a string.
// For example, given "dimm1", it returns 1.
func extractTrailingNumber(s string, prefix string) (int, error) {
	if !strings.HasPrefix(s, prefix) {
		return -1, fmt.Errorf("Prefix %s not found in %s", prefix, s)
	}

	trimmed := strings.TrimPrefix(s, prefix)
	num, err := strconv.Atoi(trimmed)
	if err != nil {
		return -1, err
	}

	return num, nil
}

// findNextDimmIndex finds the next available index for a pc-dimm device
// whose ID starts with the prefix "dimm".
func findNextDimmIndex(monitor *qmp.Monitor) (int, error) {
	devices, err := monitor.GetDimmDevices()
	if err != nil {
		return -1, err
	}

	index := -1
	for _, dev := range devices {
		i, err := extractTrailingNumber(dev.ID, "dimm")
		if err != nil {
			continue
		}

		if i > index {
			index = i
		}
	}

	return index + 1, nil
}

// findNextMemoryIndex finds the next available index for a memory object
// whose ID starts with the prefix "mem".
func findNextMemoryIndex(monitor *qmp.Monitor) (int, error) {
	memDevs, err := monitor.GetMemdev()
	if err != nil {
		return -1, err
	}

	memIndex := -1
	for _, mem := range memDevs {
		var index int
		index, err := extractTrailingNumber(mem.ID, "mem")
		if err != nil {
			continue
		}

		if index > memIndex {
			memIndex = index
		}
	}

	return memIndex + 1, nil
}

// getNodeResources updates the cluster resource cache..
func getNodeResources(s *state.State, name string, address string) (*api.Resources, error) {
	resourcesPath := internalUtil.CachePath("resources", fmt.Sprintf("%s.yaml", name))

	// Check if cache is recent (less than 24 hours).
	fi, err := os.Stat(resourcesPath)
	if err == nil && time.Since(fi.ModTime()) < 24*time.Hour {
		data, err := os.ReadFile(resourcesPath)
		if err == nil {
			var res api.Resources
			if yaml.Unmarshal(data, &res) == nil {
				return &res, nil
			}
		}
	} else if err != nil && !errors.Is(err, fs.ErrNotExist) {
		return nil, err
	}

	var res *api.Resources
	if name == s.ServerName {
		// Handle the local node.
		// We still cache the data as it's not particularly cheap to get.
		res, err = resources.GetResources()
		if err != nil {
			return nil, err
		}
	} else {
		// Handle remote nodes.
		client, err := cluster.Connect(address, s.Endpoints.NetworkCert(), s.ServerCert(), nil, true)
		if err != nil {
			return nil, err
		}

		res, err = client.GetServerResources()
		if err != nil {
			return nil, err
		}
	}

	// Cache the data.
	data, err := yaml.Marshal(res)
	if err == nil {
		_ = os.WriteFile(resourcesPath, data, 0o600)
	}

	return res, nil
}

type qcow2BlockdevKind int

const (
	backingBlockdevKind qcow2BlockdevKind = iota
	rootBlockdevKind
	overlayBlockdevKind
)

type qcow2BlockdevInfo struct {
	name  string
	kind  qcow2BlockdevKind
	index int
}

// classifyQcow2Blockdev classifies a block device as a qcow2 backing, root, or overlay device.
func classifyQcow2Blockdev(name string, rootDevName string) (*qcow2BlockdevInfo, bool) {
	reBacking := regexp.MustCompile(fmt.Sprintf(`^%s_backing(\d+)$`, rootDevName))
	reOverlay := regexp.MustCompile(fmt.Sprintf(`^%s_overlay(\d+)$`, rootDevName))

	if name == rootDevName {
		return &qcow2BlockdevInfo{name: name, kind: rootBlockdevKind, index: 0}, true
	}

	m := reBacking.FindStringSubmatch(name)
	if m != nil {
		i, _ := strconv.Atoi(m[1])
		return &qcow2BlockdevInfo{name: name, kind: backingBlockdevKind, index: i}, true
	}

	m = reOverlay.FindStringSubmatch(name)
	if m != nil {
		i, _ := strconv.Atoi(m[1])
		return &qcow2BlockdevInfo{name: name, kind: overlayBlockdevKind, index: i}, true
	}

	return nil, false
}

// filterAndSortQcow2Blockdevs selects qcow2 related block devices and sorts them in the correct order.
func filterAndSortQcow2Blockdevs(names []string, rootDevName string) []string {
	items := make([]qcow2BlockdevInfo, 0, len(names))

	for _, n := range names {
		info, ok := classifyQcow2Blockdev(n, rootDevName)
		if ok {
			items = append(items, *info)
		}
	}

	sort.Slice(items, func(i, j int) bool {
		if items[i].kind != items[j].kind {
			return items[i].kind < items[j].kind
		}

		return items[i].index < items[j].index
	})

	result := make([]string, len(items))
	for i, it := range items {
		result[i] = it.name
	}

	return result
}

// hashValue returns a hash of the name if it exceeds the given length limit.
// Otherwise, it returns the original name unchanged.
func hashValue(value string, maxLength int) string {
	if len(value) > maxLength {
		// If the name is too long, hash it as SHA-256 (32 bytes).
		// Then encode the SHA-256 binary hash as Base64 Raw URL format and trim down to 'maxLength' chars.
		// Raw URL avoids the use of "+" character and the padding "=" character which QEMU doesn't allow.
		hash256 := sha256.New()
		hash256.Write([]byte(value))
		binaryHash := hash256.Sum(nil)
		value = base64.RawURLEncoding.EncodeToString(binaryHash)
		value = value[0:maxLength]
	}

	return value
}