-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.node.js
205 lines (176 loc) · 7.34 KB
/
index.node.js
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
'use strict';
const { NodeSDK } = require("@opentelemetry/sdk-node");
const { OTLPTraceExporter } = require("@opentelemetry/exporter-trace-otlp-grpc");
const { Resource } = require("@opentelemetry/resources");
const { SemanticResourceAttributes } = require("@opentelemetry/semantic-conventions");
const { getNodeAutoInstrumentations } = require("@opentelemetry/auto-instrumentations-node");
const { GrpcInstrumentation } = require("@opentelemetry/instrumentation-grpc");
const { logs, SeverityNumber } = require('@opentelemetry/api-logs');
const { OTLPLogExporter } = require('@opentelemetry/exporter-logs-otlp-grpc');
const { LoggerProvider, SimpleLogRecordProcessor } = require('@opentelemetry/sdk-logs');
module.exports.track = (args = {}) => {
/*if (process.env.NEXT_RUNTIME !== 'nodejs') {
return;
}*/
const constants = {
mwAuthUrl: 'https://app.middleware.io/api/v1/auth',
};
const config = {
hostUrl: 'http://localhost:9319',
projectName: `Project-${process.pid}`,
serviceName: `Service-${process.pid}`,
accessToken: '',
profilingServerUrl: '',
target: '',
envVercelDeploymentId: process.env.VERCEL_DEPLOYMENT_ID || '',
envVercelProjectId: process.env.VERCEL_PROJECT_ID || '',
envVercelEnv: process.env.VERCEL_ENV || '',
envVercelUrl: process.env.VERCEL_URL || '',
envVercelRegion: process.env.VERCEL_REGION || '',
...args,
};
// For backward compatibility
if (args.hasOwnProperty('accountKey') && args.accountKey !== '') {
config.accessToken = args.accountKey;
}
const _resourceAttributes = {
[SemanticResourceAttributes.SERVICE_NAME]: config.serviceName,
'mw_agent': true,
"channel": "vercel",
'mw_serverless': true,
'project.name': config.projectName,
...(config.accessToken && {'mw.account_key': config.accessToken}),
...(config.accessToken && {'accessToken': config.accessToken}),
...(config.envVercelDeploymentId && {'deploymentId': config.envVercelDeploymentId}),
...(config.envVercelProjectId && {'projectId': config.envVercelProjectId}),
...(config.envVercelEnv && {'environment': config.envVercelEnv}),
...(config.envVercelUrl && {'host': config.envVercelUrl}),
...(config.envVercelRegion && {'region': config.envVercelRegion}),
};
if (config.target !== "") {
config.hostUrl = config.target;
}
if (!!(process.env.MW_AGENT_SERVICE && process.env.MW_AGENT_SERVICE !== "")) {
config.hostUrl = `http://${process.env.MW_AGENT_SERVICE}:9319`;
}
const _hostUrl = ((config.target).toLowerCase() === 'vercel') ? {} : {url: `${config.hostUrl}`};
setupTracer(_hostUrl, _resourceAttributes);
setupLogger(_hostUrl, _resourceAttributes);
setupProfiling({
authUrl: constants.mwAuthUrl,
profilingServerUrl: config.profilingServerUrl,
accessToken: config.accessToken,
serviceName: config.serviceName,
}).then(() => {});
};
const setupTracer = (hostUrl, resourceAttributes) => {
const api = require('@opentelemetry/api');
const { CompositePropagator } = require('@opentelemetry/core');
const { B3Propagator, B3InjectEncoding } = require('@opentelemetry/propagator-b3');
api.propagation.setGlobalPropagator(
new CompositePropagator({
propagators: [
new B3Propagator(),
new B3Propagator({ injectEncoding: B3InjectEncoding.MULTI_HEADER }),
],
})
);
const sdk = new NodeSDK({
traceExporter: new OTLPTraceExporter(hostUrl),
instrumentations: [
getNodeAutoInstrumentations({
'@opentelemetry/instrumentation-fs': {
enabled: false,
},
}),
new GrpcInstrumentation({
ignoreGrpcMethods:["Export"]
})
],
});
sdk.addResource(new Resource(resourceAttributes));
sdk.start();
process.on('SIGTERM', () => {
sdk.shutdown()
.catch(error => console.log('Error terminating tracing', error))
.finally(() => process.exit(0));
});
};
const setupLogger = (hostUrl, resourceAttributes) => {
const loggerProvider = new LoggerProvider({
resource: new Resource(resourceAttributes)
});
loggerProvider.addLogRecordProcessor(
new SimpleLogRecordProcessor(new OTLPLogExporter(hostUrl)),
);
logs.setGlobalLoggerProvider(loggerProvider);
};
const logger = (level, message, attributes = {}) => {
const logger = logs.getLogger("@middleware.io/agent-apm-nextjs", "latest");
logger.emit({
severityNumber: SeverityNumber[level],
severityText: level,
body: message,
attributes: {
'fluent.tag': 'nextjs.app',
'mw.app.lang': 'nextjs',
'level': level.toLowerCase(),
...(typeof attributes === 'object' && Object.keys(attributes).length ? attributes : {})
},
});
};
module.exports.info = (message, attributes = {}) => {
logger('INFO', message, attributes);
};
module.exports.warn = (message, attributes = {}) => {
logger('WARN', message, attributes);
};
module.exports.debug = (message, attributes = {}) => {
logger('DEBUG', message, attributes);
};
module.exports.error = (message, attributes = {}) => {
logger('ERROR', message, attributes);
};
const setupProfiling = async (obj) => {
if (obj.accessToken !== '') {
try {
const Pyroscope = require('@pyroscope/nodejs');
const axios = require('axios');
const authUrl = process.env.MW_AUTH_URL || obj.authUrl;
const response = await axios.post(authUrl, null, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'Bearer ' + obj.accessToken,
},
});
if (response.status === 200) {
const data = response.data;
if (data.hasOwnProperty('success') && data.success === true) {
const account = data.data.account;
if (data.hasOwnProperty('data')
&& data.data.hasOwnProperty('account')
&& typeof data.data.account === 'string') {
let profilingServerUrl = obj.profilingServerUrl
if (!profilingServerUrl) {
profilingServerUrl = process.env.MW_PROFILING_SERVER_URL || `https://${account}.middleware.io/profiling`
}
Pyroscope.init({
serverAddress: profilingServerUrl,
appName: obj.serviceName,
tenantID: account,
});
Pyroscope.start();
} else {
console.log('Failed to retrieve TenantID from API response');
}
} else {
console.log('Failed to authenticate with Middleware API, kindly check your access token');
}
} else {
console.log('Error making auth request');
}
} catch (e) {
console.log('Error starting profiling:', e.message);
}
}
};