Added HTTP traffic accounting.

Ylian Saint-Hilaire committed May 5, 2021 at 11:37 UTC 03becc3f0fcacf5106c4844c08d49210ea68c1ef
1 file changed +28 -2
webserver.js
+28 -2
@@ -345,6 +345,9 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
345 // Traffic counters
346 obj.trafficStats = {
347 httpRequestCount: 0,
348 + httpWebSocketCount: 0,
349 + httpIn: 0,
350 + httpOut: 0,
351 relayCount: {},
352 relayIn: {},
353 relayOut: {},
@@ -5267,8 +5270,31 @@ module.exports.CreateWebServer = function (parent, db, args, certificates) {
5270 // Useful for debugging reverse proxy issues
5271 parent.debug('httpheaders', req.method, req.url, req.headers);
5272
5270 - // Count the HTTP request
5271 - obj.trafficStats.httpRequestCount++;
5273 + // Perform traffic accounting
5274 + if (req.headers.upgrade == 'websocket') {
5275 + // We don't count traffic on WebSockets since it's counted by the handling modules.
5276 + obj.trafficStats.httpWebSocketCount++;
5277 + } else {
5278 + // Normal HTTP traffic is counted
5279 + obj.trafficStats.httpRequestCount++;
5280 + if (typeof req.socket.xbytesRead != 'number') {
5281 + req.socket.xbytesRead = 0;
5282 + req.socket.xbytesWritten = 0;
5283 + req.socket.on('close', function () {
5284 + // Perform final accounting
5285 + obj.trafficStats.httpIn += (this.bytesRead - this.xbytesRead);
5286 + obj.trafficStats.httpOut += (this.bytesWritten - this.xbytesWritten);
5287 + this.xbytesRead = this.bytesRead;
5288 + this.xbytesWritten = this.bytesWritten;
5289 + });
5290 + } else {
5291 + // Update counters
5292 + obj.trafficStats.httpIn += (req.socket.bytesRead - req.socket.xbytesRead);
5293 + obj.trafficStats.httpOut += (req.socket.bytesWritten - req.socket.xbytesWritten);
5294 + req.socket.xbytesRead = req.socket.bytesRead;
5295 + req.socket.xbytesWritten = req.socket.bytesWritten;
5296 + }
5297 + }
5298
5299 // Set the real IP address of the request
5300 // If a trusted reverse-proxy is sending us the remote IP address, use it.