device.go 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. Copyright © 2021 The CDI Authors
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package cdi
  14. import (
  15. "fmt"
  16. "github.com/container-orchestrated-devices/container-device-interface/internal/validation"
  17. "github.com/container-orchestrated-devices/container-device-interface/pkg/parser"
  18. cdi "github.com/container-orchestrated-devices/container-device-interface/specs-go"
  19. oci "github.com/opencontainers/runtime-spec/specs-go"
  20. )
  21. // Device represents a CDI device of a Spec.
  22. type Device struct {
  23. *cdi.Device
  24. spec *Spec
  25. }
  26. // Create a new Device, associate it with the given Spec.
  27. func newDevice(spec *Spec, d cdi.Device) (*Device, error) {
  28. dev := &Device{
  29. Device: &d,
  30. spec: spec,
  31. }
  32. if err := dev.validate(); err != nil {
  33. return nil, err
  34. }
  35. return dev, nil
  36. }
  37. // GetSpec returns the Spec this device is defined in.
  38. func (d *Device) GetSpec() *Spec {
  39. return d.spec
  40. }
  41. // GetQualifiedName returns the qualified name for this device.
  42. func (d *Device) GetQualifiedName() string {
  43. return parser.QualifiedName(d.spec.GetVendor(), d.spec.GetClass(), d.Name)
  44. }
  45. // ApplyEdits applies the device-speific container edits to an OCI Spec.
  46. func (d *Device) ApplyEdits(ociSpec *oci.Spec) error {
  47. return d.edits().Apply(ociSpec)
  48. }
  49. // edits returns the applicable container edits for this spec.
  50. func (d *Device) edits() *ContainerEdits {
  51. return &ContainerEdits{&d.ContainerEdits}
  52. }
  53. // Validate the device.
  54. func (d *Device) validate() error {
  55. if err := ValidateDeviceName(d.Name); err != nil {
  56. return err
  57. }
  58. name := d.Name
  59. if d.spec != nil {
  60. name = d.GetQualifiedName()
  61. }
  62. if err := validation.ValidateSpecAnnotations(name, d.Annotations); err != nil {
  63. return err
  64. }
  65. edits := d.edits()
  66. if edits.isEmpty() {
  67. return fmt.Errorf("invalid device, empty device edits")
  68. }
  69. if err := edits.Validate(); err != nil {
  70. return fmt.Errorf("invalid device %q: %w", d.Name, err)
  71. }
  72. return nil
  73. }