-
Notifications
You must be signed in to change notification settings - Fork 2
/
device.go
91 lines (76 loc) · 2.49 KB
/
device.go
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
package machina
import (
"fmt"
"github.com/gentlemanautomaton/machina/summary"
)
// DeviceAddress is a device address on the host system.
type DeviceAddress string
// DeviceName is the name of a device on a machine.
type DeviceName string
// DeviceClass identifies a class of device on the host system that can be
// assigned to a virtual machine.
type DeviceClass string
// DeviceID is a universally uniqued identifer for a device.
type DeviceID UUID
// IsZero returns true if the device ID holds a zero value.
func (d DeviceID) IsZero() bool {
return d == DeviceID{}
}
// String returns a string representation of the device ID.
func (d DeviceID) String() string {
return UUID(d).String()
}
// MarshalText implements the encoding.TextMarshaler interface.
func (d DeviceID) MarshalText() (text []byte, err error) {
return UUID(d).MarshalText()
}
// UnmarshalText implements the encoding.TextUnmarshaler interface.
func (d *DeviceID) UnmarshalText(text []byte) error {
return (*UUID)(d).UnmarshalText(text)
}
// Device identifies a mediated or passthrough host device required by a
// machine.
//
// The type of device is identified by its class, which must match a device
// classification on the system. The ID optionally provides a unique
// identifier in UUID format that can be used by some device types.
type Device struct {
Name DeviceName `json:"name"`
Class DeviceClass `json:"class"`
ID DeviceID `json:"id,omitempty"`
}
// MergeDevices merges a set of connections in order. If more than one
// device exists with the same ID, only the first is included.
func MergeDevices(devs ...Device) []Device {
lookup := make(map[DeviceName]bool)
out := make([]Device, 0, len(devs))
for _, dev := range devs {
if seen := lookup[dev.Name]; seen {
continue
}
lookup[dev.Name] = true
out = append(out, dev)
}
return out
}
// String returns a string representation of the device configuration.
func (d Device) String() string {
if d.ID.IsZero() {
return fmt.Sprintf("%s: %s", d.Name, d.Class)
}
return fmt.Sprintf("%s: %s (%s)", d.Name, d.Class, d.ID)
}
// Populate returns a copy of the device with a device ID, if one is not already
// present.
//
// The provided machine seed is used to generate the device ID.
func (d Device) Populate(seed Seed) Device {
if d.ID.IsZero() {
d.ID = seed.DeviceID([]byte("device"), []byte("id"), []byte(d.Class), []byte(d.Name))
}
return d
}
// Config adds the device configuration to the summary.
func (d Device) Config(out summary.Interface) {
out.Add("%s", d)
}