manager.go 2.3 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. log "github.com/coreos/flannel/Godeps/_workspace/src/github.com/golang/glog"
  20. "github.com/coreos/flannel/Godeps/_workspace/src/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. }
  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 := backendCtors[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.wg.Add(1)
  61. go func() {
  62. be.Run(bm.ctx)
  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 (bm *manager) Wait() {
  75. bm.wg.Wait()
  76. }
  77. func Register(name string, ctor BackendCtor) {
  78. log.Infof("Register: %v", name)
  79. backendCtors[name] = ctor
  80. }