plugin.go 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright 2018-present the CoreDHCP Authors. All rights reserved
  2. // This source code is licensed under the MIT license found in the
  3. // LICENSE file in the root directory of this source tree.
  4. package sleep
  5. // This plugin introduces a delay in the DHCP response.
  6. import (
  7. "fmt"
  8. "time"
  9. "github.com/coredhcp/coredhcp/handler"
  10. "github.com/coredhcp/coredhcp/logger"
  11. "github.com/coredhcp/coredhcp/plugins"
  12. "github.com/insomniacslk/dhcp/dhcpv4"
  13. "github.com/insomniacslk/dhcp/dhcpv6"
  14. )
  15. var (
  16. pluginName = "sleep"
  17. log = logger.GetLogger("plugins/" + pluginName)
  18. )
  19. // Example configuration of the `sleep` plugin:
  20. //
  21. // server4:
  22. // plugins:
  23. // - sleep 300ms
  24. // - file: "leases4.txt"
  25. //
  26. // server6:
  27. // plugins:
  28. // - sleep 1s
  29. // - file: "leases6.txt"
  30. //
  31. // For the duration format, see the documentation of `time.ParseDuration`,
  32. // https://golang.org/pkg/time/#ParseDuration .
  33. // Plugin contains the `sleep` plugin data.
  34. var Plugin = plugins.Plugin{
  35. Name: pluginName,
  36. Setup6: setup6,
  37. Setup4: setup4,
  38. }
  39. func setup6(args ...string) (handler.Handler6, error) {
  40. if len(args) != 1 {
  41. return nil, fmt.Errorf("want exactly one argument, got %d", len(args))
  42. }
  43. delay, err := time.ParseDuration(args[0])
  44. if err != nil {
  45. return nil, fmt.Errorf("failed to parse duration: %w", err)
  46. }
  47. log.Printf("loaded plugin for DHCPv6.")
  48. return makeSleepHandler6(delay), nil
  49. }
  50. func setup4(args ...string) (handler.Handler4, error) {
  51. if len(args) != 1 {
  52. return nil, fmt.Errorf("want exactly one argument, got %d", len(args))
  53. }
  54. delay, err := time.ParseDuration(args[0])
  55. if err != nil {
  56. return nil, fmt.Errorf("failed to parse duration: %w", err)
  57. }
  58. log.Printf("loaded plugin for DHCPv4.")
  59. return makeSleepHandler4(delay), nil
  60. }
  61. func makeSleepHandler6(delay time.Duration) handler.Handler6 {
  62. return func(req, resp dhcpv6.DHCPv6) (dhcpv6.DHCPv6, bool) {
  63. log.Printf("introducing delay of %s in response", delay)
  64. // return the unmodified response, and instruct coredhcp to continue to
  65. // the next plugin.
  66. time.Sleep(delay)
  67. return resp, false
  68. }
  69. }
  70. func makeSleepHandler4(delay time.Duration) handler.Handler4 {
  71. return func(req, resp *dhcpv4.DHCPv4) (*dhcpv4.DHCPv4, bool) {
  72. log.Printf("introducing delay of %s in response", delay)
  73. // return the unmodified response, and instruct coredhcp to continue to
  74. // the next plugin.
  75. time.Sleep(delay)
  76. return resp, false
  77. }
  78. }