-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhealthcheck.js
More file actions
186 lines (157 loc) · 4.96 KB
/
healthcheck.js
File metadata and controls
186 lines (157 loc) · 4.96 KB
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
const http = require('http');
/**
* Health check script for Stack Blog
* Used by Docker and monitoring systems to verify application health
*/
const config = {
host: process.env.HEALTH_CHECK_HOST || 'localhost',
port: process.env.PORT || 3000,
path: process.env.HEALTH_CHECK_PATH || '/api/status',
timeout: parseInt(process.env.HEALTH_CHECK_TIMEOUT) || 5000
};
function performHealthCheck() {
return new Promise((resolve, reject) => {
const options = {
hostname: config.host,
port: config.port,
path: config.path,
method: 'GET',
timeout: config.timeout,
headers: {
'User-Agent': 'StackBlog-HealthCheck/1.0'
}
};
const req = http.request(options, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
if (res.statusCode === 200) {
try {
const response = JSON.parse(data);
if (response.success && response.data.status === 'operational') {
resolve({
status: 'healthy',
statusCode: res.statusCode,
responseTime: Date.now() - startTime,
data: response.data
});
} else {
reject(new Error(`Service not operational: ${JSON.stringify(response)}`));
}
} catch (error) {
reject(new Error(`Invalid JSON response: ${error.message}`));
}
} else {
reject(new Error(`HTTP ${res.statusCode}: ${data}`));
}
});
});
req.on('error', (error) => {
reject(new Error(`Request failed: ${error.message}`));
});
req.on('timeout', () => {
req.destroy();
reject(new Error(`Health check timeout after ${config.timeout}ms`));
});
const startTime = Date.now();
req.end();
});
}
// Advanced health checks
async function performAdvancedChecks() {
const checks = {
api: false,
disk: false,
memory: false
};
// Check API endpoint
try {
await performHealthCheck();
checks.api = true;
} catch (error) {
console.error('API health check failed:', error.message);
}
// Check disk space
try {
const fs = require('fs');
const stats = fs.statSync('./');
// Basic disk check - ensure we can read filesystem
checks.disk = stats.isDirectory();
} catch (error) {
console.error('Disk health check failed:', error.message);
}
// Check memory usage
try {
const memUsage = process.memoryUsage();
const maxMemory = 512 * 1024 * 1024; // 512MB default limit
const heapUsedPercent = (memUsage.heapUsed / maxMemory) * 100;
checks.memory = heapUsedPercent < 90; // Fail if using >90% of allocated memory
if (process.env.HEALTH_CHECK_VERBOSE === 'true') {
console.log('Memory usage:', {
heapUsed: Math.round(memUsage.heapUsed / 1024 / 1024) + 'MB',
heapTotal: Math.round(memUsage.heapTotal / 1024 / 1024) + 'MB',
rss: Math.round(memUsage.rss / 1024 / 1024) + 'MB',
external: Math.round(memUsage.external / 1024 / 1024) + 'MB',
heapUsedPercent: Math.round(heapUsedPercent) + '%'
});
}
} catch (error) {
console.error('Memory health check failed:', error.message);
}
return checks;
}
// Main execution
async function main() {
const verbose = process.env.HEALTH_CHECK_VERBOSE === 'true';
const advanced = process.env.HEALTH_CHECK_ADVANCED === 'true';
try {
if (advanced) {
if (verbose) console.log('Performing advanced health checks...');
const checks = await performAdvancedChecks();
const allPassed = Object.values(checks).every(check => check === true);
if (verbose) {
console.log('Health check results:', checks);
}
if (allPassed) {
if (verbose) console.log('All health checks passed');
process.exit(0);
} else {
console.error('Some health checks failed:', checks);
process.exit(1);
}
} else {
if (verbose) console.log('Performing basic health check...');
const result = await performHealthCheck();
if (verbose) {
console.log('Health check passed:', {
status: result.status,
responseTime: result.responseTime + 'ms',
version: result.data.version,
uptime: process.uptime() + 's'
});
}
process.exit(0);
}
} catch (error) {
console.error('Health check failed:', error.message);
if (verbose) {
console.error('Health check configuration:', config);
console.error('Process uptime:', process.uptime() + 's');
console.error('Node version:', process.version);
}
process.exit(1);
}
}
// Handle process signals
process.on('SIGTERM', () => {
console.log('Health check interrupted by SIGTERM');
process.exit(1);
});
process.on('SIGINT', () => {
console.log('Health check interrupted by SIGINT');
process.exit(1);
});
// Run the health check
main();