This repository has been archived by the owner on Oct 3, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 97
/
http2.ts
336 lines (299 loc) · 10 KB
/
http2.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
324
325
326
327
328
329
330
331
332
333
334
335
336
/**
* Copyright 2018, OpenCensus 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 {
Func,
HeaderGetter,
HeaderSetter,
MessageEventType,
Span,
SpanKind,
TraceOptions,
} from '@opencensus/core';
import { HttpPlugin } from '@opencensus/instrumentation-http';
import * as http2 from 'http2';
import * as shimmer from 'shimmer';
import * as url from 'url';
export type Http2Module = typeof http2;
export type ConnectFunction = typeof http2.connect;
type RequestFunction = (
this: http2.ClientHttp2Session,
headers?: http2.OutgoingHttpHeaders,
options?: http2.ClientSessionRequestOptions
) => http2.ClientHttp2Stream;
export type CreateServerFunction = typeof http2.createServer;
/** Http2 instrumentation plugin for Opencensus */
export class Http2Plugin extends HttpPlugin {
/** Constructs a new Http2Plugin instance. */
constructor() {
super('http2');
}
/**
* Patches HTTP2 incoming and outcoming request functions.
*/
protected applyPatch() {
shimmer.wrap(
this.moduleExports,
'createServer',
this.getPatchCreateServerFunction()
);
shimmer.wrap(
this.moduleExports,
'createSecureServer',
this.getPatchCreateServerFunction()
);
shimmer.wrap(this.moduleExports, 'connect', this.getPatchConnectFunction());
return this.moduleExports;
}
/** Unpatches all HTTP2 patched function. */
protected applyUnpatch(): void {
// Only Client and Server constructors will be unwrapped. Any existing
// Client or Server instances will still trace
shimmer.unwrap(this.moduleExports, 'createServer');
shimmer.unwrap(this.moduleExports, 'createSecureServer');
shimmer.unwrap(this.moduleExports, 'connect');
}
private getPatchConnectFunction() {
const plugin = this;
return (original: ConnectFunction): Func<http2.ClientHttp2Session> => {
return function patchedConnect(
this: Http2Plugin,
authority: string | url.URL
): http2.ClientHttp2Session {
const client = original.apply(this, arguments);
shimmer.wrap(client, 'request', original =>
plugin.getPatchRequestFunction()(original, authority)
);
return client;
};
};
}
private getPatchRequestFunction() {
const plugin = this;
return (
original: RequestFunction,
authority: string | url.URL
): Func<http2.ClientHttp2Stream> => {
return function patchedRequest(
this: http2.Http2Session,
headers: http2.OutgoingHttpHeaders
): http2.ClientHttp2Stream {
// Do not trace ourselves
if (headers['x-opencensus-outgoing-request']) {
return original.apply(this, arguments);
}
const request = original.apply(this, arguments);
plugin.tracer.wrapEmitter(request);
const traceOptions = {
name: `${headers[':method'] || 'GET'} ${headers[':path']}`,
kind: SpanKind.CLIENT,
};
// Checks if this outgoing request is part of an operation by checking
// if there is a current root span, if so, we create a child span. In
// case there is no root span, this means that the outgoing request is
// the first operation, therefore we create a root span.
if (!plugin.tracer.currentRootSpan) {
return plugin.tracer.startRootSpan(
traceOptions,
plugin.getMakeHttp2RequestTraceFunction(
request,
headers,
authority,
plugin
)
);
} else {
const span = plugin.tracer.startChildSpan({
name: traceOptions.name,
kind: traceOptions.kind,
});
return plugin.getMakeHttp2RequestTraceFunction(
request,
headers,
authority,
plugin
)(span);
}
};
};
}
private getMakeHttp2RequestTraceFunction(
request: http2.ClientHttp2Stream,
headers: http2.OutgoingHttpHeaders,
authority: string | url.URL,
plugin: Http2Plugin
): Func<http2.ClientHttp2Stream> {
return (span: Span): http2.ClientHttp2Stream => {
if (!span) return request;
const setter: HeaderSetter = {
setHeader(name: string, value: string) {
headers[name] = value;
},
};
const propagation = plugin.tracer.propagation;
if (propagation) {
propagation.inject(setter, span.spanContext);
}
request.on('response', (responseHeaders: http2.IncomingHttpHeaders) => {
const statusCode = responseHeaders[':status'] || 200;
span.addAttribute(
Http2Plugin.ATTRIBUTE_HTTP_STATUS_CODE,
`${statusCode}`
);
span.setStatus(Http2Plugin.parseResponseStatus(+statusCode));
});
request.on('end', () => {
const userAgent =
headers['user-agent'] || headers['User-Agent'] || null;
const host = (authority instanceof url.URL
? authority
: url.parse(authority)
).host;
if (host) {
span.addAttribute(Http2Plugin.ATTRIBUTE_HTTP_HOST, host);
}
span.addAttribute(
Http2Plugin.ATTRIBUTE_HTTP_METHOD,
`${headers[':method']}`
);
span.addAttribute(
Http2Plugin.ATTRIBUTE_HTTP_PATH,
`${headers[':path']}`
);
span.addAttribute(
Http2Plugin.ATTRIBUTE_HTTP_ROUTE,
`${headers[':path']}`
);
if (userAgent) {
span.addAttribute(
Http2Plugin.ATTRIBUTE_HTTP_USER_AGENT,
`${userAgent}`
);
}
span.addMessageEvent(MessageEventType.SENT, 1);
span.end();
});
request.on('error', (err: Error) => {
span.addAttribute(HttpPlugin.ATTRIBUTE_HTTP_ERROR_NAME, err.name);
span.addAttribute(HttpPlugin.ATTRIBUTE_HTTP_ERROR_MESSAGE, err.message);
span.end();
});
return request;
};
}
private getPatchCreateServerFunction() {
const plugin = this;
return (original: CreateServerFunction): Func<http2.Http2Server> => {
return function patchedCreateServer(
this: Http2Plugin
): http2.Http2Server {
const server = original.apply(this, arguments);
shimmer.wrap(
server.constructor.prototype,
'emit',
plugin.getPatchEmitFunction()
);
shimmer.unwrap(plugin.moduleExports, 'createServer');
shimmer.unwrap(plugin.moduleExports, 'createSecureServer');
return server;
};
};
}
private getPatchEmitFunction() {
const plugin = this;
return (original: RequestFunction): Func<http2.ClientHttp2Stream> => {
return function patchedEmit(
this: http2.Http2Server,
event: string,
stream: http2.ServerHttp2Stream,
headers: http2.IncomingHttpHeaders
): http2.ClientHttp2Stream {
if (event !== 'stream') {
return original.apply(this, arguments);
}
const propagation = plugin.tracer.propagation;
const getter: HeaderGetter = {
getHeader(name: string) {
return headers[name];
},
};
const traceOptions: TraceOptions = {
name: headers[':path'] || '',
kind: SpanKind.SERVER,
};
if (propagation) {
const spanContext = propagation.extract(getter);
if (spanContext) {
traceOptions.spanContext = spanContext;
}
}
// Respond is called in a stream event. We wrap it to get the sent
// status code.
let statusCode: number;
const originalRespond = stream.respond;
stream.respond = function(this: http2.Http2Stream) {
// Unwrap it since respond is not allowed to be called more than once
// per stream.
stream.respond = originalRespond;
statusCode = arguments[0][':status'];
return stream.respond.apply(this, arguments);
};
return plugin.tracer.startRootSpan(traceOptions, rootSpan => {
if (!rootSpan) return original.apply(this, arguments);
plugin.tracer.wrapEmitter(stream);
const originalEnd = stream.end;
stream.end = function(this: http2.Http2Stream) {
stream.end = originalEnd;
const returned = stream.end.apply(this, arguments);
const userAgent = (headers['user-agent'] ||
headers['User-Agent'] ||
null) as string;
rootSpan.addAttribute(
Http2Plugin.ATTRIBUTE_HTTP_HOST,
`${headers[':authority']}`
);
rootSpan.addAttribute(
Http2Plugin.ATTRIBUTE_HTTP_METHOD,
`${headers[':method']}`
);
rootSpan.addAttribute(
Http2Plugin.ATTRIBUTE_HTTP_PATH,
`${headers[':path']}`
);
rootSpan.addAttribute(
Http2Plugin.ATTRIBUTE_HTTP_ROUTE,
`${headers[':path']}`
);
rootSpan.addAttribute(
Http2Plugin.ATTRIBUTE_HTTP_USER_AGENT,
userAgent
);
rootSpan.addAttribute(
Http2Plugin.ATTRIBUTE_HTTP_STATUS_CODE,
`${statusCode}`
);
rootSpan.setStatus(Http2Plugin.parseResponseStatus(statusCode));
rootSpan.addMessageEvent(MessageEventType.RECEIVED, 1);
rootSpan.end();
return returned;
};
return original.apply(this, arguments);
});
};
};
}
}
const plugin = new Http2Plugin();
export { plugin };