manager.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. // Copyright 2015 flannel authors
  2. //
  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. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package backend
  15. import (
  16. "fmt"
  17. "strings"
  18. "sync"
  19. "golang.org/x/net/context"
  20. "github.com/coreos/flannel/subnet"
  21. )
  22. var constructors = make(map[string]BackendCtor)
  23. type Manager interface {
  24. GetBackend(backendType string) (Backend, error)
  25. Wait()
  26. }
  27. type manager struct {
  28. ctx context.Context
  29. sm subnet.Manager
  30. extIface *ExternalInterface
  31. mux sync.Mutex
  32. active map[string]Backend
  33. wg sync.WaitGroup
  34. }
  35. func NewManager(ctx context.Context, sm subnet.Manager, extIface *ExternalInterface) Manager {
  36. return &manager{
  37. ctx: ctx,
  38. sm: sm,
  39. extIface: extIface,
  40. active: make(map[string]Backend),
  41. }
  42. }
  43. func (bm *manager) GetBackend(backendType string) (Backend, error) {
  44. bm.mux.Lock()
  45. defer bm.mux.Unlock()
  46. betype := strings.ToLower(backendType)
  47. // see if one is already running
  48. if be, ok := bm.active[betype]; ok {
  49. return be, nil
  50. }
  51. // first request, need to create and run it
  52. befunc, ok := constructors[betype]
  53. if !ok {
  54. return nil, fmt.Errorf("unknown backend type: %v", betype)
  55. }
  56. be, err := befunc(bm.sm, bm.extIface)
  57. if err != nil {
  58. return nil, err
  59. }
  60. bm.active[betype] = be
  61. bm.wg.Add(1)
  62. go func() {
  63. be.Run(bm.ctx)
  64. // TODO(eyakubovich): this obviosly introduces a race.
  65. // GetBackend() could get called while we are here.
  66. // Currently though, all backends' Run exit only
  67. // on shutdown
  68. bm.mux.Lock()
  69. delete(bm.active, betype)
  70. bm.mux.Unlock()
  71. bm.wg.Done()
  72. }()
  73. return be, nil
  74. }
  75. func (bm *manager) Wait() {
  76. bm.wg.Wait()
  77. }
  78. func Register(name string, ctor BackendCtor) {
  79. constructors[name] = ctor
  80. }