...
1
18
19 package clustermanager
20
21 import (
22 "context"
23
24 "google.golang.org/grpc/balancer"
25 "google.golang.org/grpc/codes"
26 "google.golang.org/grpc/status"
27 )
28
29
30
31 type pickerGroup struct {
32 pickers map[string]balancer.Picker
33 }
34
35 func newPickerGroup(idToPickerState map[string]*subBalancerState) *pickerGroup {
36 pickers := make(map[string]balancer.Picker)
37 for id, st := range idToPickerState {
38 pickers[id] = st.state.Picker
39 }
40 return &pickerGroup{
41 pickers: pickers,
42 }
43 }
44
45 func (pg *pickerGroup) Pick(info balancer.PickInfo) (balancer.PickResult, error) {
46 cluster := getPickedCluster(info.Ctx)
47 if p := pg.pickers[cluster]; p != nil {
48 return p.Pick(info)
49 }
50 return balancer.PickResult{}, status.Errorf(codes.Unavailable, "unknown cluster selected for RPC: %q", cluster)
51 }
52
53 type clusterKey struct{}
54
55 func getPickedCluster(ctx context.Context) string {
56 cluster, _ := ctx.Value(clusterKey{}).(string)
57 return cluster
58 }
59
60
61
62 func GetPickedClusterForTesting(ctx context.Context) string {
63 return getPickedCluster(ctx)
64 }
65
66
67
68 func SetPickedCluster(ctx context.Context, cluster string) context.Context {
69 return context.WithValue(ctx, clusterKey{}, cluster)
70 }
71
View as plain text