forked from Shopify/toxiproxy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproxy_collection.go
98 lines (77 loc) · 2.11 KB
/
proxy_collection.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
package main
import (
"fmt"
"sync"
)
// ProxyCollection is a collection of proxies. It's the interface for anything
// to add and remove proxies from the toxiproxy instance. It's responsibilty is
// to maintain the integrity of the proxy set, by guarding for things such as
// duplicate names.
type ProxyCollection struct {
sync.RWMutex
proxies map[string]*Proxy
}
func NewProxyCollection() *ProxyCollection {
return &ProxyCollection{
proxies: make(map[string]*Proxy),
}
}
func (collection *ProxyCollection) Add(proxy *Proxy, start bool) error {
collection.Lock()
defer collection.Unlock()
if _, exists := collection.proxies[proxy.Name]; exists {
return fmt.Errorf("Proxy with name %s already exists", proxy.Name)
}
if start {
err := proxy.Start()
if err != nil {
return err
}
}
collection.proxies[proxy.Name] = proxy
return nil
}
func (collection *ProxyCollection) Proxies() map[string]*Proxy {
collection.RLock()
defer collection.RUnlock()
// Copy the map since using the existing one isn't thread-safe
proxies := make(map[string]*Proxy, len(collection.proxies))
for k, v := range collection.proxies {
proxies[k] = v
}
return proxies
}
func (collection *ProxyCollection) Get(name string) (*Proxy, error) {
collection.RLock()
defer collection.RUnlock()
return collection.getByName(name)
}
func (collection *ProxyCollection) Remove(name string) error {
collection.Lock()
defer collection.Unlock()
proxy, err := collection.getByName(name)
if err != nil {
return err
}
proxy.Stop()
delete(collection.proxies, proxy.Name)
return nil
}
func (collection *ProxyCollection) Clear() error {
collection.Lock()
defer collection.Unlock()
for _, proxy := range collection.proxies {
proxy.Stop()
delete(collection.proxies, proxy.Name)
}
return nil
}
// getByName returns a proxy by its name. Its used from #remove and #get.
// It assumes the lock has already been acquired.
func (collection *ProxyCollection) getByName(name string) (*Proxy, error) {
proxy, exists := collection.proxies[name]
if !exists {
return nil, fmt.Errorf("Proxy with name %s doesn't exist", name)
}
return proxy, nil
}