/
index.js
232 lines (209 loc) · 6.53 KB
/
index.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
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
'use strict'
var pkg = require('./package.json')
var Promise = require('bluebird')
var request = require('request')
var os = require('os')
var https = require('https')
var system = (process.platform === 'linux') ? require('./src/system.js') : require('./src/mockSystem.js')
var getCollectorUrl = require('./src/collector.js')
var Context = require('./src/context.js')
var Callback = require('./src/callback.js')
const VERSION = pkg.version
const MODULE_LOAD_TIME = Date.now()
const httpsAgent = new https.Agent({
maxCachedSessions: 1,
keepAlive: true
});
// Default on module load; changed to false on first handler invocation.
var COLDSTART = true
function _make_generateLog(metrics, func, start_time, config, context) {
var pre_stat_promise = system.readstat('self')
return function generateLog(err, callback) {
Promise.join(
pre_stat_promise,
system.readstat('self'),
system.readstatus('self'),
system.readbootid()
).spread((
pre_proc_self_stat,
proc_self_stat,
proc_self_status,
boot_id
) => {
var runtime_env = {
agent: {
runtime: 'nodejs',
version: VERSION,
load_time: MODULE_LOAD_TIME
},
host: {
container_id: boot_id
},
os: {
hostname: os.hostname(),
uptime: os.uptime(),
totalmem: os.totalmem(),
freemem: os.freemem(),
usedmem: os.totalmem() - os.freemem(),
cpus: os.cpus(),
arch: os.arch(),
linux: {
pid: {
self: {
stat_start: pre_proc_self_stat,
stat: proc_self_stat,
status: proc_self_status
}
}
}
},
nodejs: {
title: process.title,
version: process.version,
modulesloadList: process.modulesloadList,
versions: process.versions,
arch: process.arch,
platform: process.platform,
argv: process.argv,
execArgv: process.execArgv,
pid: process.pid,
features: process.features,
execPath: process.execPath,
debugPort: process.debugPort,
_maxListeners: process._maxListeners,
config: process.config,
maxTickDepth: process.maxTickDepth,
// /* Circular ref */ mainModule: process.mainModule,
release: process.release,
uptime: process.uptime(),
getuid: process.getuid(),
getgid: process.getgid(),
geteuid: process.geteuid(),
getegid: process.getegid(),
memoryUsage: process.memoryUsage(),
}
}
var retainErr = {}
if (err) {
retainErr = ((err) => {
return {
name: err.name,
message: err.message,
stack: err.stack,
lineNumber: err.lineNumber,
columnNumber: err.columnNumber,
fileName: err.fileName
}
})((typeof(err) === 'string') ? new Error(err) : err)
}
var time_sec_nanosec = process.hrtime(start_time)
/*
depreciated fields:
- time_sec_nanosec (use duration; 11/23/2016)
- time_sec (use duration; 11/23/2016)
*/
var response_body = {
environment: runtime_env,
aws: {
functionName: context.functionName,
functionVersion: context.functionVersion,
invokedFunctionArn: context.invokedFunctionArn,
memoryLimitInMB: context.memoryLimitInMB,
awsRequestId: context.awsRequestId,
logGroupName: context.logGroupName,
logStreamName: context.logStreamName
},
coldstart: COLDSTART,
errors: retainErr,
custom_metrics: metrics,
time_sec_nanosec: time_sec_nanosec,
time_sec: time_sec_nanosec[0],
time_nanosec: time_sec_nanosec[1],
duration: Math.ceil(time_sec_nanosec[0] * 1000000000.0 + time_sec_nanosec[1]),
client_id: config.clientId
}
if (COLDSTART === true) {
COLDSTART = false
}
if (context.getRemainingTimeInMillis) {
response_body.aws.getRemainingTimeInMillis = context.getRemainingTimeInMillis()
}
if (config.debug) {
console.log('IOPIPE-DEBUG: ', JSON.stringify(response_body))
}
if (!config.clientId) {
callback()
return
}
request(
{
url: getCollectorUrl(config.url),
method: 'POST',
json: true,
body: response_body,
agent: httpsAgent,
timeout: config.network_timeout,
},
function(err) {
// Log errors, don't block on failed requests
if (err && config.debug) {
console.log('Write to IOpipe failed:')
console.log(err)
}
callback()
}
)
}
)
}
}
function setConfig(configObject) {
return {
url: (configObject && configObject.url) ? configObject.url : '',
clientId: configObject && configObject.clientId || process.env.IOPIPE_TOKEN || process.env.IOPIPE_CLIENTID || '',
debug: configObject && configObject.debug || process.env.IOPIPE_DEBUG || false,
network_timeout: 5000,
}
}
module.exports = function(options) {
var fn = function(func) {
fn.metricsQueue = []
const config = setConfig(options)
return function() {
fn.metricsQueue = []
let args = [].slice.call(arguments)
var start_time = process.hrtime()
var generateLog = _make_generateLog(fn.metricsQueue, func, start_time, config, args[1])
/* Mangle arguments, wrapping callbacks. */
args[1] = Context(generateLog, args[1])
args[2] = Callback(generateLog, args[2])
try {
return func.apply(this, args)
}
catch (err) {
generateLog(err, () => {})
return undefined
}
}
}
// Alias decorate to the wrapper function
fn.decorate = fn
fn.log = function(name, value) {
var numberValue, stringValue
if (typeof value === 'number') {
numberValue = value
} else {
if(typeof value === 'object') {
JSON.stringify(value)
} else {
stringValue = String(value)
}
}
fn.metricsQueue.push({
name: name,
n: numberValue,
s: stringValue
})
}
return fn
}