-
Notifications
You must be signed in to change notification settings - Fork 7
/
backend_mgr.go
99 lines (81 loc) · 1.91 KB
/
backend_mgr.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package main
import (
"fmt"
"sync"
)
var indexOutOfBoundError error = fmt.Errorf("Index out of bound")
type BackendMgr struct {
sync.Mutex
backends []Backend
}
// NewBackendMgr create a BackendMgr object
func NewBackendMgr() *BackendMgr {
return &BackendMgr{backends: make([]Backend, 0)}
}
// Exists Check if the backend with address exists or not
func (b *BackendMgr) Exists(addr string) bool {
b.Lock()
defer b.Unlock()
_, err := b.getIndex(addr)
return err == nil
}
// Size get number of backends
func (b *BackendMgr) Size() int {
b.Lock()
defer b.Unlock()
return len(b.backends)
}
// GetIndex get backend by index
func (b *BackendMgr) GetIndex(index int) (Backend, error) {
b.Lock()
defer b.Unlock()
if index >= 0 && index < len(b.backends) {
return b.backends[index], nil
}
return nil, indexOutOfBoundError
}
// Add add a backend
func (b *BackendMgr) Add(backend Backend) {
b.Lock()
defer b.Unlock()
b.backends = append(b.backends, backend)
}
// Get get backend by address
func (b *BackendMgr) Get(addr string) (Backend, error) {
b.Lock()
defer b.Unlock()
index, err := b.getIndex(addr)
if err == nil {
return b.backends[index], nil
}
return nil, err
}
// Remove remove backend by address
func (b *BackendMgr) Remove(addr string) (Backend, error) {
b.Lock()
defer b.Unlock()
index, err := b.getIndex(addr)
if err == nil {
backend := b.backends[index]
b.backends = append(b.backends[0:index], b.backends[index+1:]...)
return backend, nil
}
return nil, err
}
// GetAll get all the backend
func (b *BackendMgr) GetAll() []Backend {
b.Lock()
defer b.Unlock()
r := make([]Backend, 0)
r = append(r, b.backends...)
return r
}
// getIndex get the index of backend by address
func (b *BackendMgr) getIndex(addr string) (int, error) {
for index, backend := range b.backends {
if backend.GetAddr() == addr {
return index, nil
}
}
return -1, fmt.Errorf("No such backend %s", addr)
}