options.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package vhostnet
  2. import (
  3. "errors"
  4. "github.com/slackhq/nebula/overlay/virtqueue"
  5. )
  6. type optionValues struct {
  7. queueSize int
  8. backendFD int
  9. }
  10. func (o *optionValues) apply(options []Option) {
  11. for _, option := range options {
  12. option(o)
  13. }
  14. }
  15. func (o *optionValues) validate() error {
  16. if o.queueSize == -1 {
  17. return errors.New("queue size is required")
  18. }
  19. if err := virtqueue.CheckQueueSize(o.queueSize); err != nil {
  20. return err
  21. }
  22. if o.backendFD == -1 {
  23. return errors.New("backend file descriptor is required")
  24. }
  25. return nil
  26. }
  27. var optionDefaults = optionValues{
  28. // Required.
  29. queueSize: -1,
  30. // Required.
  31. backendFD: -1,
  32. }
  33. // Option can be passed to [NewDevice] to influence device creation.
  34. type Option func(*optionValues)
  35. // WithQueueSize returns an [Option] that sets the size of the TX and RX queues
  36. // that are to be created for the device. It specifies the number of
  37. // entries/buffers each queue can hold. This also affects the memory
  38. // consumption.
  39. // This is required and must be an integer from 1 to 32768 that is also a power
  40. // of 2.
  41. func WithQueueSize(queueSize int) Option {
  42. return func(o *optionValues) { o.queueSize = queueSize }
  43. }
  44. // WithBackendFD returns an [Option] that sets the file descriptor of the
  45. // backend that will be used for the queues of the device. The device will write
  46. // and read packets to/from that backend. The file descriptor can either be of a
  47. // RAW socket or TUN/TAP device.
  48. // Either this or [WithBackendDevice] is required.
  49. func WithBackendFD(backendFD int) Option {
  50. return func(o *optionValues) { o.backendFD = backendFD }
  51. }
  52. //// WithBackendDevice returns an [Option] that sets the given TAP device as the
  53. //// backend that will be used for the queues of the device. The device will
  54. //// write and read packets to/from that backend. The TAP device should have been
  55. //// created with the [tuntap.WithVirtioNetHdr] option enabled.
  56. //// Either this or [WithBackendFD] is required.
  57. //func WithBackendDevice(dev *tuntap.Device) Option {
  58. // return func(o *optionValues) { o.backendFD = int(dev.File().Fd()) }
  59. //}