config.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. package presence
  2. import (
  3. "context"
  4. "fmt"
  5. "net"
  6. "os"
  7. "time"
  8. "goa.design/clue/log"
  9. "gopkg.in/yaml.v3"
  10. "douglasthrift.net/presence/wrap"
  11. )
  12. type (
  13. Config struct {
  14. Interval time.Duration `yaml:"interval"`
  15. Interfaces []string `yaml:"interfaces"`
  16. MACAddresses []string `yaml:"mac_addresses"`
  17. PingCount uint `yaml:"ping_count"`
  18. }
  19. )
  20. func ParseConfig(name string, wNet wrap.Net) (*Config, error) {
  21. return ParseConfigWithContext(context.Background(), name, wNet)
  22. }
  23. func ParseConfigWithContext(ctx context.Context, name string, wNet wrap.Net) (*Config, error) {
  24. f, err := os.Open(name)
  25. if err != nil {
  26. return nil, err
  27. }
  28. defer f.Close()
  29. d := yaml.NewDecoder(f)
  30. d.KnownFields(true)
  31. c := &Config{}
  32. err = d.Decode(c)
  33. if err != nil {
  34. return nil, err
  35. }
  36. if c.Interval < 0 {
  37. return nil, fmt.Errorf("negative interval (%v)", c.Interval)
  38. } else if c.Interval == 0 {
  39. c.Interval = 30 * time.Second
  40. }
  41. if len(c.Interfaces) == 0 {
  42. ifs, err := wNet.Interfaces()
  43. if err != nil {
  44. return nil, err
  45. }
  46. c.Interfaces = make([]string, 0, len(ifs))
  47. for _, i := range ifs {
  48. c.Interfaces = append(c.Interfaces, i.Name)
  49. }
  50. } else {
  51. for _, i := range c.Interfaces {
  52. _, err = wNet.InterfaceByName(i)
  53. if err != nil {
  54. return nil, fmt.Errorf("interface %v: %w", i, err)
  55. }
  56. }
  57. }
  58. if len(c.MACAddresses) == 0 {
  59. return nil, fmt.Errorf("no MAC addresses")
  60. }
  61. as := make(map[string]bool, len(c.MACAddresses))
  62. for i, a := range c.MACAddresses {
  63. hw, err := net.ParseMAC(a)
  64. if err != nil {
  65. return nil, err
  66. }
  67. a = hw.String()
  68. if as[a] {
  69. return nil, fmt.Errorf("duplicate MAC address (%v)", a)
  70. }
  71. as[a] = true
  72. c.MACAddresses[i] = a
  73. }
  74. if c.PingCount == 0 {
  75. c.PingCount = 1
  76. }
  77. log.Print(ctx, log.KV{K: "msg", V: "interval"}, log.KV{K: "value", V: c.Interval})
  78. log.Print(ctx, log.KV{K: "msg", V: "interfaces"}, log.KV{K: "value", V: c.Interfaces})
  79. log.Print(ctx, log.KV{K: "msg", V: "MAC addresses"}, log.KV{K: "value", V: c.MACAddresses})
  80. log.Print(ctx, log.KV{K: "msg", V: "ping count"}, log.KV{K: "value", V: c.PingCount})
  81. return c, nil
  82. }