serve.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 server
  5. import (
  6. "github.com/coredhcp/coredhcp/config"
  7. "github.com/coredhcp/coredhcp/logger"
  8. "github.com/coredhcp/coredhcp/plugins"
  9. "github.com/insomniacslk/dhcp/dhcpv4/server4"
  10. "github.com/insomniacslk/dhcp/dhcpv6/server6"
  11. )
  12. var log = logger.GetLogger("server")
  13. // Start will start the server asynchronously. See `Wait` to wait until
  14. // the execution ends.
  15. func (s *Server) Start() error {
  16. var err error
  17. s.Handlers4, s.Handlers6, err = plugins.LoadPlugins(s.Config)
  18. if err != nil {
  19. return err
  20. }
  21. // listen
  22. if s.Config.Server6 != nil {
  23. log.Println("Starting DHCPv6 server")
  24. for _, l := range s.Config.Server6.Addresses {
  25. s6, err := server6.NewServer(l.Zone, l, s.MainHandler6)
  26. if err != nil {
  27. return err
  28. }
  29. s.Servers6 = append(s.Servers6, s6)
  30. log.Infof("Listen %s", l)
  31. go func() {
  32. s.errors <- s6.Serve()
  33. }()
  34. }
  35. }
  36. if s.Config.Server4 != nil {
  37. log.Println("Starting DHCPv4 server")
  38. for _, l := range s.Config.Server4.Addresses {
  39. s4, err := server4.NewServer(l.Zone, l, s.MainHandler4)
  40. if err != nil {
  41. return err
  42. }
  43. s.Servers4 = append(s.Servers4, s4)
  44. log.Infof("Listen %s", l)
  45. go func() {
  46. s.errors <- s4.Serve()
  47. }()
  48. }
  49. }
  50. return nil
  51. }
  52. // Wait waits until the end of the execution of the server.
  53. func (s *Server) Wait() error {
  54. log.Print("Waiting")
  55. err := <-s.errors
  56. for _, s6 := range s.Servers6 {
  57. if s6 != nil {
  58. s6.Close()
  59. }
  60. }
  61. for _, s4 := range s.Servers4 {
  62. if s4 != nil {
  63. s4.Close()
  64. }
  65. }
  66. return err
  67. }
  68. // NewServer creates a Server instance with the provided configuration.
  69. func NewServer(config *config.Config) *Server {
  70. return &Server{Config: config, errors: make(chan error, 1)}
  71. }