/
index.ts
313 lines (294 loc) · 10 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
/*
* 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 grpcTypes from 'grpc';
import {
InstrumentationNodeModuleDefinition,
InstrumentationNodeModuleFile,
InstrumentationBase,
InstrumentationConfig,
isWrapped,
} from '@opentelemetry/instrumentation';
import {
GrpcInternalClientTypes,
ServerCallWithMeta,
SendUnaryDataCallback,
GrpcClientFunc,
} from './types';
import { GrpcInstrumentationConfig } from '../types';
import {
context,
propagation,
SpanOptions,
SpanKind,
trace,
} from '@opentelemetry/api';
import {
clientStreamAndUnaryHandler,
shouldNotTraceServerCall,
serverStreamAndBidiHandler,
} from './serverUtils';
import { makeGrpcClientRemoteCall, getMetadata } from './clientUtils';
import { _methodIsIgnored } from '../utils';
import { AttributeNames } from '../enums/AttributeNames';
/**
* Holding reference to grpc module here to access constant of grpc modules
* instead of just requiring it avoid directly depending on grpc itself.
*/
let grpcClient: typeof grpcTypes;
export class GrpcNativeInstrumentation extends InstrumentationBase<
typeof grpcTypes
> {
constructor(
protected override _config: GrpcInstrumentationConfig & InstrumentationConfig = {},
name: string,
version: string
) {
super(name, version, _config);
}
public override setConfig(
config: GrpcInstrumentationConfig & InstrumentationConfig = {}
) {
this._config = Object.assign({}, config);
}
init() {
return [
new InstrumentationNodeModuleDefinition<typeof grpcTypes>(
'grpc',
['1.*'],
(moduleExports, version) => {
this._diag.debug(`Applying patch for grpc@${version}`);
grpcClient = moduleExports;
if (isWrapped(moduleExports.Server.prototype.register)) {
this._unwrap(moduleExports.Server.prototype, 'register');
}
this._wrap(
moduleExports.Server.prototype,
'register',
this._patchServer(moduleExports) as any
);
// Wrap the externally exported client constructor
if (isWrapped(moduleExports.makeGenericClientConstructor)) {
this._unwrap(moduleExports, 'makeGenericClientConstructor');
}
this._wrap(
moduleExports,
'makeGenericClientConstructor',
this._patchClient()
);
return moduleExports;
},
(moduleExports, version) => {
if (moduleExports === undefined) return;
this._diag.debug(`Removing patch for grpc@${version}`);
this._unwrap(moduleExports.Server.prototype, 'register');
},
this._getInternalPatchs()
),
];
}
private _getInternalPatchs() {
const onPatch = (
moduleExports: GrpcInternalClientTypes,
version?: string
) => {
this._diag.debug(`Applying internal patch for grpc@${version}`);
if (isWrapped(moduleExports.makeClientConstructor)) {
this._unwrap(moduleExports, 'makeClientConstructor');
}
this._wrap(moduleExports, 'makeClientConstructor', this._patchClient());
return moduleExports;
};
const onUnPatch = (
moduleExports?: GrpcInternalClientTypes,
version?: string
) => {
if (moduleExports === undefined) return;
this._diag.debug(`Removing internal patch for grpc@${version}`);
this._unwrap(moduleExports, 'makeClientConstructor');
};
return [
new InstrumentationNodeModuleFile<GrpcInternalClientTypes>(
'grpc/src/node/src/client.js',
['0.13 - 1.6'],
onPatch,
onUnPatch
),
new InstrumentationNodeModuleFile<GrpcInternalClientTypes>(
'grpc/src/client.js',
['^1.7'],
onPatch,
onUnPatch
),
];
}
private _patchServer(grpcModule: typeof grpcTypes) {
const instrumentation = this;
return (originalRegister: typeof grpcTypes.Server.prototype.register) => {
instrumentation._diag.debug('patched gRPC server');
return function register<RequestType, ResponseType>(
this: grpcTypes.Server & { handlers: any },
name: string,
handler: grpcTypes.handleCall<RequestType, ResponseType>,
serialize: grpcTypes.serialize<RequestType>,
deserialize: grpcTypes.deserialize<RequestType>,
type: string
) {
const originalResult = originalRegister.apply(this, arguments as any);
const handlerSet = this.handlers[name];
instrumentation._wrap(
handlerSet,
'func',
(originalFunc: grpcTypes.handleCall<RequestType, ResponseType>) => {
return function func(
this: typeof handlerSet,
call: ServerCallWithMeta,
callback: SendUnaryDataCallback
) {
const self = this;
if (shouldNotTraceServerCall.call(instrumentation, call, name)) {
switch (type) {
case 'unary':
case 'client_stream':
return (originalFunc as Function).call(
self,
call,
callback
);
case 'server_stream':
case 'bidi':
return (originalFunc as Function).call(self, call);
default:
return originalResult;
}
}
const spanName = `grpc.${name.replace('/', '')}`;
const spanOptions: SpanOptions = {
kind: SpanKind.SERVER,
};
instrumentation._diag.debug('patch func: %s', JSON.stringify(spanOptions));
context.with(
propagation.extract(context.active(), call.metadata, {
get: (metadata, key) => metadata.get(key).map(String),
keys: metadata => Object.keys(metadata.getMap()),
}),
() => {
const span = instrumentation.tracer
.startSpan(spanName, spanOptions)
.setAttributes({
[AttributeNames.GRPC_KIND]: spanOptions.kind,
});
context.with(trace.setSpan(context.active(), span), () => {
switch (type) {
case 'unary':
case 'client_stream':
return clientStreamAndUnaryHandler(
grpcModule,
span,
call,
callback,
originalFunc,
self
);
case 'server_stream':
case 'bidi':
return serverStreamAndBidiHandler(
span,
call,
originalFunc,
self
);
default:
break;
}
});
}
);
};
}
);
return originalResult;
};
};
}
private _patchClient() {
const instrumentation = this;
return (original: typeof grpcTypes.makeGenericClientConstructor): never => {
instrumentation._diag.debug('patching client');
return function makeClientConstructor(
this: typeof grpcTypes.Client,
methods: { [key: string]: { originalName?: string } },
_serviceName: string,
_options: grpcTypes.GenericClientOptions
) {
const client = original.apply(this, arguments as any);
instrumentation._massWrap(
client.prototype as never,
instrumentation._getMethodsToWrap(client, methods) as never[],
instrumentation._getPatchedClientMethods() as any
);
return client;
} as never;
};
}
private _getMethodsToWrap(
client: typeof grpcTypes.Client,
methods: { [key: string]: { originalName?: string } }
): string[] {
const methodList: string[] = [];
// For a method defined in .proto as "UnaryMethod"
Object.entries(methods).forEach(([name, { originalName }]) => {
if (!_methodIsIgnored(name, this._config.ignoreGrpcMethods)) {
methodList.push(name); // adds camel case method name: "unaryMethod"
if (
originalName &&
// eslint-disable-next-line no-prototype-builtins
client.prototype.hasOwnProperty(originalName) &&
name !== originalName // do not add duplicates
) {
// adds original method name: "UnaryMethod",
methodList.push(originalName);
}
}
});
return methodList;
}
private _getPatchedClientMethods() {
const instrumentation = this;
return (original: GrpcClientFunc) => {
instrumentation._diag.debug('patch all client methods');
return function clientMethodTrace(this: grpcTypes.Client) {
const name = `grpc.${(original.path as string | undefined)?.replace(
'/',
''
)}`;
const args = Array.prototype.slice.call(arguments);
const metadata = getMetadata(grpcClient, original, args);
const span = instrumentation.tracer.startSpan(name, {
kind: SpanKind.CLIENT,
});
return context.with(trace.setSpan(context.active(), span), () =>
makeGrpcClientRemoteCall(
grpcClient,
original,
args,
metadata,
this
)(span)
);
};
};
}
}