/
load-balancer-lrs.ts
241 lines (221 loc) · 8.52 KB
/
load-balancer-lrs.ts
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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
/*
* Copyright 2020 gRPC authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import { connectivityState as ConnectivityState, StatusObject, status as Status, experimental } from '@grpc/grpc-js';
import { Locality__Output } from './generated/envoy/api/v2/core/Locality';
import { XdsClusterLocalityStats, XdsClient } from './xds-client';
import LoadBalancer = experimental.LoadBalancer;
import ChannelControlHelper = experimental.ChannelControlHelper;
import registerLoadBalancerType = experimental.registerLoadBalancerType;
import getFirstUsableConfig = experimental.getFirstUsableConfig;
import SubchannelAddress = experimental.SubchannelAddress;
import LoadBalancingConfig = experimental.LoadBalancingConfig;
import ChildLoadBalancerHandler = experimental.ChildLoadBalancerHandler;
import Picker = experimental.Picker;
import PickArgs = experimental.PickArgs;
import PickResultType = experimental.PickResultType;
import PickResult = experimental.PickResult;
import Filter = experimental.Filter;
import BaseFilter = experimental.BaseFilter;
import FilterFactory = experimental.FilterFactory;
import FilterStackFactory = experimental.FilterStackFactory;
import Call = experimental.CallStream;
import validateLoadBalancingConfig = experimental.validateLoadBalancingConfig
const TYPE_NAME = 'lrs';
export class LrsLoadBalancingConfig implements LoadBalancingConfig {
getLoadBalancerName(): string {
return TYPE_NAME;
}
toJsonObject(): object {
return {
[TYPE_NAME]: {
cluster_name: this.clusterName,
eds_service_name: this.edsServiceName,
lrs_load_reporting_server_name: this.lrsLoadReportingServerName,
locality: this.locality,
child_policy: this.childPolicy.map(policy => policy.toJsonObject())
}
}
}
constructor(private clusterName: string, private edsServiceName: string, private lrsLoadReportingServerName: string, private locality: Locality__Output, private childPolicy: LoadBalancingConfig[]) {}
getClusterName() {
return this.clusterName;
}
getEdsServiceName() {
return this.edsServiceName;
}
getLrsLoadReportingServerName() {
return this.lrsLoadReportingServerName;
}
getLocality() {
return this.locality;
}
getChildPolicy() {
return this.childPolicy;
}
static createFromJson(obj: any): LrsLoadBalancingConfig {
if (!('cluster_name' in obj && typeof obj.cluster_name === 'string')) {
throw new Error('lrs config must have a string field cluster_name');
}
if (!('eds_service_name' in obj && typeof obj.eds_service_name === 'string')) {
throw new Error('lrs config must have a string field eds_service_name');
}
if (!('lrs_load_reporting_server_name' in obj && typeof obj.lrs_load_reporting_server_name === 'string')) {
throw new Error('lrs config must have a string field lrs_load_reporting_server_name');
}
if (!('locality' in obj && obj.locality !== null && typeof obj.locality === 'object')) {
throw new Error('lrs config must have an object field locality');
}
if ('region' in obj.locality && typeof obj.locality.region !== 'string') {
throw new Error('lrs config locality.region field must be a string if provided');
}
if ('zone' in obj.locality && typeof obj.locality.zone !== 'string') {
throw new Error('lrs config locality.zone field must be a string if provided');
}
if ('sub_zone' in obj.locality && typeof obj.locality.sub_zone !== 'string') {
throw new Error('lrs config locality.sub_zone field must be a string if provided');
}
if (!('child_policy' in obj && Array.isArray(obj.child_policy))) {
throw new Error('lrs config must have a child_policy array');
}
return new LrsLoadBalancingConfig(obj.cluster_name, obj.eds_service_name, obj.lrs_load_reporting_server_name, {
region: obj.locality.region ?? '',
zone: obj.locality.zone ?? '',
sub_zone: obj.locality.sub_zone ?? ''
}, obj.child_policy.map(validateLoadBalancingConfig));
}
}
/**
* Filter class that reports when the call ends.
*/
class CallEndTrackingFilter extends BaseFilter implements Filter {
constructor(private localityStatsReporter: XdsClusterLocalityStats) {
super();
}
receiveTrailers(status: StatusObject) {
this.localityStatsReporter.addCallFinished(status.code !== Status.OK);
return status;
}
}
class CallEndTrackingFilterFactory
implements FilterFactory<CallEndTrackingFilter> {
constructor(private localityStatsReporter: XdsClusterLocalityStats) {}
createFilter(callStream: Call): CallEndTrackingFilter {
return new CallEndTrackingFilter(this.localityStatsReporter);
}
}
/**
* Picker that delegates picking to another picker, and reports when calls
* created using those picks start and end.
*/
class LoadReportingPicker implements Picker {
constructor(
private wrappedPicker: Picker,
private localityStatsReporter: XdsClusterLocalityStats
) {}
pick(pickArgs: PickArgs): PickResult {
const wrappedPick = this.wrappedPicker.pick(pickArgs);
if (wrappedPick.pickResultType === PickResultType.COMPLETE) {
const trackingFilterFactory = new CallEndTrackingFilterFactory(
this.localityStatsReporter
);
/* In the unlikely event that the wrappedPick already has an
* extraFilterFactory, preserve it in a FilterStackFactory. */
const extraFilterFactory = wrappedPick.extraFilterFactory
? new FilterStackFactory([
wrappedPick.extraFilterFactory,
trackingFilterFactory,
])
: trackingFilterFactory;
return {
pickResultType: PickResultType.COMPLETE,
subchannel: wrappedPick.subchannel,
status: null,
onCallStarted: () => {
wrappedPick.onCallStarted?.();
this.localityStatsReporter.addCallStarted();
},
extraFilterFactory: extraFilterFactory,
};
} else {
return wrappedPick;
}
}
}
/**
* "Load balancer" that delegates the actual load balancing logic to another
* LoadBalancer class and adds hooks to track when calls started using that
* LoadBalancer start and end, and uses the XdsClient to report that
* information back to the xDS server.
*/
export class LrsLoadBalancer implements LoadBalancer {
private childBalancer: ChildLoadBalancerHandler;
private localityStatsReporter: XdsClusterLocalityStats | null = null;
constructor(private channelControlHelper: ChannelControlHelper) {
this.childBalancer = new ChildLoadBalancerHandler({
createSubchannel: (subchannelAddress, subchannelArgs) =>
channelControlHelper.createSubchannel(
subchannelAddress,
subchannelArgs
),
requestReresolution: () => channelControlHelper.requestReresolution(),
updateState: (connectivityState: ConnectivityState, picker: Picker) => {
if (this.localityStatsReporter !== null) {
picker = new LoadReportingPicker(picker, this.localityStatsReporter);
}
channelControlHelper.updateState(connectivityState, picker);
},
});
}
updateAddressList(
addressList: SubchannelAddress[],
lbConfig: LoadBalancingConfig,
attributes: { [key: string]: unknown }
): void {
if (!(lbConfig instanceof LrsLoadBalancingConfig)) {
return;
}
if (!(attributes.xdsClient instanceof XdsClient)) {
return;
}
this.localityStatsReporter = attributes.xdsClient.addClusterLocalityStats(
lbConfig.getLrsLoadReportingServerName(),
lbConfig.getClusterName(),
lbConfig.getEdsServiceName(),
lbConfig.getLocality()
);
const childPolicy: LoadBalancingConfig = getFirstUsableConfig(
lbConfig.getChildPolicy(),
true
);
this.childBalancer.updateAddressList(addressList, childPolicy, attributes);
}
exitIdle(): void {
this.childBalancer.exitIdle();
}
resetBackoff(): void {
this.childBalancer.resetBackoff();
}
destroy(): void {
this.childBalancer.destroy();
}
getTypeName(): string {
return TYPE_NAME;
}
}
export function setup() {
registerLoadBalancerType(TYPE_NAME, LrsLoadBalancer, LrsLoadBalancingConfig);
}