-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathdiagnose.ts
382 lines (343 loc) · 9.82 KB
/
diagnose.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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
import fs from "fs"
import path from "path"
import https from "https"
import http from "http"
import { URL, URLSearchParams } from "url"
import { createHash } from "crypto"
import { isWritable } from "./utils"
import { Extension } from "./extension"
import { Configuration } from "./config"
import { AGENT_VERSION, VERSION } from "./version"
import { JS_TO_RUBY_MAPPING } from "./config/configmap"
import { AppsignalOptions } from "."
import { HashMap } from "@appsignal/types"
interface FileMetadata {
content?: string[]
exists: boolean
mode?: string
ownership?: {
gid: number
uid: number
}
path?: string
type?: string
writable?: boolean
}
interface ParsingError {
error: string
backtrace: []
raw?: string
}
export class DiagnoseTool {
#config: Configuration
#extension: Extension
constructor({ active = true }) {
this.#config = new Configuration({ active })
this.#extension = new Extension({ active })
}
/**
* Reports are serialized to JSON and send to an endpoint that expects
* snake_case keys, thus the keys in the report on this side must be snake cased also.
*/
public async generate() {
let pushApiKeyValidation
await this.validatePushApiKey()
.then(result => (pushApiKeyValidation = result))
.catch(result => (pushApiKeyValidation = result))
return {
library: this.getLibraryData(),
installation: this.getInstallationReport(),
host: this.getHostData(),
agent: this.#extension.diagnose(),
config: {
options: this.#config.data,
sources: this.#config.sources
},
validation: { push_api_key: pushApiKeyValidation },
process: {
uid: process.getuid()
},
paths: this.getPathsData()
}
}
private getLibraryData() {
return {
language: "nodejs",
package_version: VERSION,
agent_version: AGENT_VERSION,
extension_loaded: this.#extension.isLoaded
}
}
private getHostData() {
const heroku = !!process.env["DYNO"]
return {
architecture: process.arch,
os: process.platform,
language_version: process.versions.node,
heroku,
root: process.getuid() === 0,
// @TODO: this is pretty much just a guess right now
// it assumes docker. no jails, lxc etc.
// we'll need to adjust this a little later
running_in_container: hasDockerEnv() || hasDockerCGroup() || heroku
}
}
private getInstallationReport() {
let rawReport
try {
rawReport = fs.readFileSync(reportPath(), "utf8")
return JSON.parse(rawReport)
} catch (error) {
const report = {
parsing_error: {
error: `${error.name}: ${error.message}`,
backtrace: error.stack.split("\n")
} as ParsingError
}
if (rawReport) {
report.parsing_error.raw = rawReport
}
return report
}
}
private async validatePushApiKey() {
return new Promise((resolve, reject) => {
const config = this.#config.data
const params = new URLSearchParams({
api_key: config["pushApiKey"] || "",
name: config["name"] || "",
environment: config["environment"] || "",
hostname: config["hostname"] || ""
})
const url = new URL(`/1/auth?${params.toString()}`, config["endpoint"])
const options = { method: "POST" }
const requestModule = url.protocol == "http:" ? http : https
const request = requestModule.request(url, options, function (response) {
const status = response.statusCode
if (status === 200) {
resolve("valid")
} else if (status === 401) {
reject("invalid")
} else {
reject(`Failed to validate: status ${status}`)
}
})
request.write("") // Send empty body
request.end()
})
}
private getPathsData() {
const paths: { [key: string]: FileMetadata } = {}
const logFilePath = this.#config.logFilePath
const pathsToCheck = {
working_dir: {
path: process.cwd()
},
log_dir_path: {
path: logFilePath ? path.dirname(logFilePath) : ""
},
"appsignal.log": {
path: logFilePath || "",
content: logFilePath
? safeReadFromPath(logFilePath).trimEnd().split("\n")
: []
}
}
Object.entries(pathsToCheck).forEach(([key, data]) => {
const { path } = data
if (fs.existsSync(path)) {
try {
let stats = fs.statSync(path)
const { mode, gid, uid } = stats
paths[key] = {
...data,
exists: true,
mode: mode.toString(8),
ownership: {
gid,
uid
},
type: getPathType(stats),
writable: isWritable(path)
}
} catch (_) {
paths[key] = {
...data,
exists: true
}
}
} else {
paths[key] = {
...data,
exists: false
}
}
})
return paths
}
/**
* Reads all configuration and re-maps it to keys with
* snake_case names.
*/
private getConfigData() {
return this.optionsObject(this.#config.data)
}
/**
* Converts an AppsignalOptions object into a plain JS object,
* re-mapping its keys to snake_case names as they appear
* in our API.
*/
private optionsObject(options: Partial<AppsignalOptions>) {
const config: { [key: string]: any } = {}
Object.keys(options).forEach(key => {
const newKey = JS_TO_RUBY_MAPPING[key]
config[newKey] = options[key]
})
return config
}
/**
* Reads all configuration sources, remapping each source's
* option keys with snake_case names.
*/
private getSources() {
return Object.entries(this.#config.sources).reduce(
(sources, [name, options]) => {
return { ...sources, [name]: this.optionsObject(options) }
},
{}
)
}
public sendReport(data: HashMap<any>) {
data.config.options = this.getConfigData()
data.config.sources = this.getSources()
const json = JSON.stringify({ diagnose: data })
const config = this.#config.data
const params = new URLSearchParams({
api_key: config["pushApiKey"] || "",
name: config["name"] || "",
environment: config["environment"] || "",
hostname: config["hostname"] || ""
})
const diagnoseEndpoint =
process.env.APPSIGNAL_DIAGNOSE_ENDPOINT || "https://appsignal.com/diag"
const url = new URL(diagnoseEndpoint)
const opts = {
method: "POST",
protocol: url.protocol,
host: url.hostname,
port: url.port,
path: `${url.pathname}?${params.toString()}`,
headers: {
"Content-Type": "application/json",
"Content-Length": json.length
},
cert: fs.readFileSync(
path.resolve(__dirname, "../cert/cacert.pem"),
"utf-8"
)
}
const requestModule = url.protocol == "http:" ? http : https
const request = requestModule.request(opts, (response: any) => {
const responseStatus = response.statusCode
response.setEncoding("utf8")
response.on("data", (responseData: any) => {
if (responseStatus === 200) {
const { token } = JSON.parse(responseData.toString())
console.log(` Your support token:`, token)
console.log(
` View this report: https://appsignal.com/diagnose/${token}`
)
} else {
console.error(
" Error: Something went wrong while submitting the report to AppSignal."
)
console.error(` Response code: ${responseStatus}`)
console.error(` Response body:\n${responseData}`)
}
})
})
request.write(json)
request.end()
}
}
// This implementation should match the `packages/nodejs-ext/scripts/report.js`
// implementation to generate the same path.
function reportPath(): string {
// Navigate up to the app dir. Move up the src dir, package dir, @appsignal
// dir and node_modules dir.
const appPath = path.join(__dirname, "../../../../")
const hash = createHash("sha256")
hash.update(appPath)
const reportPathDigest = hash.digest("hex")
return path.join(`/tmp/appsignal-${reportPathDigest}-install.report`)
}
function getPathType(stats: fs.Stats) {
if (stats.isDirectory()) {
return "directory"
} else if (stats.isFile()) {
return "file"
} else {
return "unknown"
}
}
const BYTES_TO_READ_FOR_FILES = 2 * 1024 * 1024 // 2 Mebibytes
/**
* Attempts to read a UTF-8 from `path`, and either returns the result
* as a string, or an empty string on error
*/
function safeReadFromPath(path: string): string {
try {
return readBytesFromPath(path, BYTES_TO_READ_FOR_FILES)
} catch (_) {
return ""
}
}
function readBytesFromPath(path: string, bytesToRead: number): string {
let fd
try {
const { readLength, startPosition } = readFileOptions(path, bytesToRead)
fd = fs.openSync(path, "r")
const buffer = Buffer.alloc(readLength)
fs.readSync(fd, buffer, 0, readLength, startPosition)
return buffer.toString("utf8")
} finally {
if (fd) {
fs.closeSync(fd)
}
}
}
function readFileOptions(path: string, bytesToRead: number) {
const stats = fs.statSync(path)
const fileSize = stats.size
if (fileSize < bytesToRead) {
return {
readLength: fileSize,
startPosition: 0
}
} else {
const startPosition = fileSize - bytesToRead
return {
readLength: bytesToRead,
startPosition
}
}
}
/**
* the following lines are borrowed from https://github.com/sindresorhus/is-docker/
* thanks sindre! <3
*/
function hasDockerEnv(): boolean {
try {
fs.statSync("/.dockerenv")
return true
} catch (_) {
return false
}
}
function hasDockerCGroup(): boolean {
try {
return fs.readFileSync("/proc/self/cgroup", "utf8").includes("docker")
} catch (_) {
return false
}
}