-
Notifications
You must be signed in to change notification settings - Fork 846
/
Copy pathindex.ts
323 lines (307 loc) · 10.3 KB
/
index.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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
/*
* Copyright The OpenTelemetry 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
*
* https://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 type * as grpcJs from '@grpc/grpc-js';
import {
InstrumentationNodeModuleDefinition,
isWrapped,
} from '@opentelemetry/instrumentation';
import { InstrumentationBase } from '@opentelemetry/instrumentation';
import { GrpcInstrumentationConfig } from '../types';
import {
ServerCallWithMeta,
SendUnaryDataCallback,
ServerRegisterFunction,
HandleCall,
MakeClientConstructorFunction,
PackageDefinition,
GrpcClientFunc,
} from './types';
import {
context,
propagation,
ROOT_CONTEXT,
SpanOptions,
SpanKind,
trace,
} from '@opentelemetry/api';
import {
shouldNotTraceServerCall,
handleServerFunction,
handleUntracedServerFunction,
} from './serverUtils';
import {
getMethodsToWrap,
makeGrpcClientRemoteCall,
getMetadata,
} from './clientUtils';
import { EventEmitter } from 'events';
import { AttributeNames } from '../enums/AttributeNames';
export class GrpcJsInstrumentation extends InstrumentationBase {
constructor(
name: string,
version: string,
config?: GrpcInstrumentationConfig,
) {
super(name, version, config);
}
init() {
return [
new InstrumentationNodeModuleDefinition<typeof grpcJs>(
'@grpc/grpc-js',
['1.*'],
(moduleExports, version) => {
this._diag.debug(`Applying patch for @grpc/grpc-js@${version}`);
if (isWrapped(moduleExports.Server.prototype.register)) {
this._unwrap(moduleExports.Server.prototype, 'register');
}
// Patch Server methods
this._wrap(
moduleExports.Server.prototype,
'register',
this._patchServer() as any
);
// Patch Client methods
if (isWrapped(moduleExports.makeGenericClientConstructor)) {
this._unwrap(moduleExports, 'makeGenericClientConstructor');
}
this._wrap(
moduleExports,
'makeGenericClientConstructor',
this._patchClient(moduleExports)
);
if (isWrapped(moduleExports.makeClientConstructor)) {
this._unwrap(moduleExports, 'makeClientConstructor');
}
this._wrap(
moduleExports,
'makeClientConstructor',
this._patchClient(moduleExports)
);
if (isWrapped(moduleExports.loadPackageDefinition)) {
this._unwrap(moduleExports, 'loadPackageDefinition');
}
this._wrap(
moduleExports,
'loadPackageDefinition',
this._patchLoadPackageDefinition(moduleExports)
);
return moduleExports;
},
(moduleExports, version) => {
if (moduleExports === undefined) return;
this._diag.debug(`Removing patch for @grpc/grpc-js@${version}`);
this._unwrap(moduleExports.Server.prototype, 'register');
this._unwrap(moduleExports, 'makeClientConstructor');
this._unwrap(moduleExports, 'makeGenericClientConstructor');
this._unwrap(moduleExports, 'loadPackageDefinition');
}
),
];
}
override getConfig(): GrpcInstrumentationConfig {
return super.getConfig();
}
/**
* Patch for grpc.Server.prototype.register(...) function. Provides auto-instrumentation for
* client_stream, server_stream, bidi, unary server handler calls.
*/
private _patchServer(): (
originalRegister: ServerRegisterFunction
) => ServerRegisterFunction {
const instrumentation = this;
return (originalRegister: ServerRegisterFunction) => {
const config = this.getConfig();
instrumentation._diag.debug('patched gRPC server');
return function register<RequestType, ResponseType>(
this: grpcJs.Server,
name: string,
handler: HandleCall<unknown, unknown>,
serialize: grpcJs.serialize<unknown>,
deserialize: grpcJs.deserialize<unknown>,
type: string
): boolean {
const originalRegisterResult = originalRegister.call(
this,
name,
handler,
serialize,
deserialize,
type
);
const handlerSet = this['handlers'].get(name);
instrumentation._wrap(
handlerSet,
'func',
(originalFunc: HandleCall<unknown, unknown>) => {
return function func(
this: typeof handlerSet,
call: ServerCallWithMeta<RequestType, ResponseType>,
callback: SendUnaryDataCallback<unknown>
) {
const self = this;
if (
shouldNotTraceServerCall(
call.metadata,
name,
config.ignoreGrpcMethods
)
) {
return handleUntracedServerFunction(
type,
originalFunc,
call,
callback
);
}
const spanName = `grpc.${name.replace('/', '')}`;
const spanOptions: SpanOptions = {
kind: SpanKind.SERVER,
};
instrumentation._diag.debug(`patch func: ${JSON.stringify(spanOptions)}`);
context.with(
propagation.extract(ROOT_CONTEXT, call.metadata, {
get: (carrier, key) => carrier.get(key).map(String),
keys: carrier => Object.keys(carrier.getMap()),
}),
() => {
const span = instrumentation.tracer
.startSpan(spanName, spanOptions)
.setAttributes({
[AttributeNames.GRPC_KIND]: spanOptions.kind,
});
context.with(trace.setSpan(context.active(), span), () => {
handleServerFunction.call(
self,
span,
type,
originalFunc,
call,
callback
);
});
}
);
};
}
);
return originalRegisterResult;
} as typeof grpcJs.Server.prototype.register;
};
}
/**
* Entry point for applying client patches to `grpc.makeClientConstructor(...)` equivalents
* @param this GrpcJsPlugin
*/
private _patchClient(
grpcClient: typeof grpcJs
): (
original: MakeClientConstructorFunction
) => MakeClientConstructorFunction {
const instrumentation = this;
return (original: MakeClientConstructorFunction) => {
instrumentation._diag.debug('patching client');
return function makeClientConstructor(
this: typeof grpcJs.Client,
methods: grpcJs.ServiceDefinition,
serviceName: string,
options?: object
) {
const client = original.call(this, methods, serviceName, options);
instrumentation._massWrap<typeof client.prototype, string>(
client.prototype,
getMethodsToWrap.call(instrumentation, client, methods),
instrumentation._getPatchedClientMethods(grpcClient)
);
return client;
};
};
}
/**
* Entry point for client patching for grpc.loadPackageDefinition(...)
* @param this - GrpcJsPlugin
*/
private _patchLoadPackageDefinition(grpcClient: typeof grpcJs) {
const instrumentation = this;
instrumentation._diag.debug('patching loadPackageDefinition');
return (original: typeof grpcJs.loadPackageDefinition) => {
return function patchedLoadPackageDefinition(
this: null,
packageDef: PackageDefinition
) {
const result: grpcJs.GrpcObject = original.call(
this,
packageDef
) as grpcJs.GrpcObject;
instrumentation._patchLoadedPackage(grpcClient, result);
return result;
} as typeof grpcJs.loadPackageDefinition;
};
}
/**
* Parse initial client call properties and start a span to trace its execution
*/
private _getPatchedClientMethods(
grpcClient: typeof grpcJs
): (original: GrpcClientFunc) => () => EventEmitter {
const instrumentation = this;
return (original: GrpcClientFunc) => {
instrumentation._diag.debug('patch all client methods');
return function clientMethodTrace(this: grpcJs.Client) {
const name = `grpc.${original.path.replace('/', '')}`;
const args = [...arguments];
const metadata = getMetadata.call(
instrumentation,
grpcClient,
original,
args
);
const span = instrumentation.tracer.startSpan(name, {
kind: SpanKind.CLIENT,
});
return context.with(trace.setSpan(context.active(), span), () =>
makeGrpcClientRemoteCall(original, args, metadata, this)(span)
);
};
};
}
/**
* Utility function to patch *all* functions loaded through a proto file.
* Recursively searches for Client classes and patches all methods, reversing the
* parsing done by grpc.loadPackageDefinition
* https://github.com/grpc/grpc-node/blob/1d14203c382509c3f36132bd0244c99792cb6601/packages/grpc-js/src/make-client.ts#L200-L217
*/
private _patchLoadedPackage(
grpcClient: typeof grpcJs,
result: grpcJs.GrpcObject
): void {
Object.values(result).forEach(service => {
if (typeof service === 'function') {
this._massWrap<typeof service.prototype, string>(
service.prototype,
getMethodsToWrap.call(this, service, service.service),
this._getPatchedClientMethods.call(this, grpcClient)
);
} else if (typeof service.format !== 'string') {
// GrpcObject
this._patchLoadedPackage.call(
this,
grpcClient,
service as grpcJs.GrpcObject
);
}
});
}
}