aboutsummaryrefslogtreecommitdiff
path: root/vendor/github.com/container-orchestrated-devices/container-device-interface/pkg/cdi/device.go
blob: 0bb1f531bd3fb10c4d4060a1760d3147f529df90 (plain)
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
/*
   Copyright © 2021 The CDI Authors

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

       http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
*/

package cdi

import (
	cdi "github.com/container-orchestrated-devices/container-device-interface/specs-go"
	oci "github.com/opencontainers/runtime-spec/specs-go"
	"github.com/pkg/errors"
)

// Device represents a CDI device of a Spec.
type Device struct {
	*cdi.Device
	spec *Spec
}

// Create a new Device, associate it with the given Spec.
func newDevice(spec *Spec, d cdi.Device) (*Device, error) {
	dev := &Device{
		Device: &d,
		spec:   spec,
	}

	if err := dev.validate(); err != nil {
		return nil, err
	}

	return dev, nil
}

// GetSpec returns the Spec this device is defined in.
func (d *Device) GetSpec() *Spec {
	return d.spec
}

// GetQualifiedName returns the qualified name for this device.
func (d *Device) GetQualifiedName() string {
	return QualifiedName(d.spec.GetVendor(), d.spec.GetClass(), d.Name)
}

// ApplyEdits applies the device-speific container edits to an OCI Spec.
func (d *Device) ApplyEdits(ociSpec *oci.Spec) error {
	return d.edits().Apply(ociSpec)
}

// edits returns the applicable container edits for this spec.
func (d *Device) edits() *ContainerEdits {
	return &ContainerEdits{&d.ContainerEdits}
}

// Validate the device.
func (d *Device) validate() error {
	if err := ValidateDeviceName(d.Name); err != nil {
		return err
	}
	edits := d.edits()
	if edits.isEmpty() {
		return errors.Errorf("invalid device, empty device edits")
	}
	if err := edits.Validate(); err != nil {
		return errors.Wrapf(err, "invalid device %q", d.Name)
	}
	return nil
}