manager.go 2.2 KB

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