-
Notifications
You must be signed in to change notification settings - Fork 20
/
cluster.go
56 lines (48 loc) · 1.03 KB
/
cluster.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
package client
import (
"context"
"math/rand"
"sync"
)
// Cluster is a list of clients belonging to a cluster.
type Cluster []Client
// SelectRandom returns a randomly selected client.
func (c Cluster) SelectRandom() Client {
return c[rand.Intn(len(c))]
}
// Query executes the given hook across all members of the cluster.
func (c Cluster) Query(ctx context.Context, concurrent bool, query func(context.Context, *Client) error) error {
if !concurrent {
for _, client := range c {
err := query(ctx, &client)
if err != nil {
return err
}
}
return nil
}
errors := make([]error, 0, len(c))
mut := sync.Mutex{}
wg := sync.WaitGroup{}
for _, client := range c {
wg.Add(1)
go func(client Client) {
defer wg.Done()
err := query(ctx, &client)
if err != nil {
mut.Lock()
errors = append(errors, err)
mut.Unlock()
return
}
}(client)
}
// Wait for all queries to complete and check for any errors.
wg.Wait()
for _, err := range errors {
if err != nil {
return err
}
}
return nil
}