manager.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  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. "github.com/flannel-io/flannel/subnet"
  20. "golang.org/x/net/context"
  21. )
  22. var constructors = make(map[string]BackendCtor)
  23. type Manager interface {
  24. GetBackend(backendType string) (Backend, error)
  25. }
  26. type manager struct {
  27. ctx context.Context
  28. sm subnet.Manager
  29. extIface *ExternalInterface
  30. mux sync.Mutex
  31. active map[string]Backend
  32. wg sync.WaitGroup
  33. }
  34. func NewManager(ctx context.Context, sm subnet.Manager, extIface *ExternalInterface) Manager {
  35. return &manager{
  36. ctx: ctx,
  37. sm: sm,
  38. extIface: extIface,
  39. active: make(map[string]Backend),
  40. }
  41. }
  42. func (bm *manager) GetBackend(backendType string) (Backend, error) {
  43. bm.mux.Lock()
  44. defer bm.mux.Unlock()
  45. betype := strings.ToLower(backendType)
  46. // see if one is already running
  47. if be, ok := bm.active[betype]; ok {
  48. return be, nil
  49. }
  50. // first request, need to create and run it
  51. befunc, ok := constructors[betype]
  52. if !ok {
  53. return nil, fmt.Errorf("unknown backend type: %v", betype)
  54. }
  55. be, err := befunc(bm.sm, bm.extIface)
  56. if err != nil {
  57. return nil, err
  58. }
  59. bm.active[betype] = be
  60. bm.wg.Add(1)
  61. go func() {
  62. <-bm.ctx.Done()
  63. // TODO(eyakubovich): this obviosly introduces a race.
  64. // GetBackend() could get called while we are here.
  65. // Currently though, all backends' Run exit only
  66. // on shutdown
  67. bm.mux.Lock()
  68. delete(bm.active, betype)
  69. bm.mux.Unlock()
  70. bm.wg.Done()
  71. }()
  72. return be, nil
  73. }
  74. func Register(name string, ctor BackendCtor) {
  75. constructors[name] = ctor
  76. }