manager.go 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright 2017 fatedier, fatedier@gmail.com
  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 server
  15. import (
  16. "fmt"
  17. "sync"
  18. )
  19. type ControlManager struct {
  20. // controls indexed by run id
  21. ctlsByRunId map[string]*Control
  22. mu sync.RWMutex
  23. }
  24. func NewControlManager() *ControlManager {
  25. return &ControlManager{
  26. ctlsByRunId: make(map[string]*Control),
  27. }
  28. }
  29. func (cm *ControlManager) Add(runId string, ctl *Control) (oldCtl *Control) {
  30. cm.mu.Lock()
  31. defer cm.mu.Unlock()
  32. oldCtl, ok := cm.ctlsByRunId[runId]
  33. if ok {
  34. oldCtl.Replaced(ctl)
  35. }
  36. cm.ctlsByRunId[runId] = ctl
  37. return
  38. }
  39. func (cm *ControlManager) GetById(runId string) (ctl *Control, ok bool) {
  40. cm.mu.RLock()
  41. defer cm.mu.RUnlock()
  42. ctl, ok = cm.ctlsByRunId[runId]
  43. return
  44. }
  45. type ProxyManager struct {
  46. // proxies indexed by proxy name
  47. pxys map[string]Proxy
  48. mu sync.RWMutex
  49. }
  50. func NewProxyManager() *ProxyManager {
  51. return &ProxyManager{
  52. pxys: make(map[string]Proxy),
  53. }
  54. }
  55. func (pm *ProxyManager) Add(name string, pxy Proxy) error {
  56. pm.mu.Lock()
  57. defer pm.mu.Unlock()
  58. if _, ok := pm.pxys[name]; ok {
  59. return fmt.Errorf("proxy name [%s] is already in use", name)
  60. }
  61. pm.pxys[name] = pxy
  62. return nil
  63. }
  64. func (pm *ProxyManager) Del(name string) {
  65. pm.mu.Lock()
  66. defer pm.mu.Unlock()
  67. delete(pm.pxys, name)
  68. }
  69. func (pm *ProxyManager) GetByName(name string) (pxy Proxy, ok bool) {
  70. pm.mu.RLock()
  71. defer pm.mu.RUnlock()
  72. pxy, ok = pm.pxys[name]
  73. return
  74. }