From 731ce1f7c8099102117050de9b8b7a6b5bc0baea Mon Sep 17 00:00:00 2001 From: Alexey Kasyanchuk Date: Tue, 17 Jan 2017 23:53:41 +0300 Subject: [PATCH] =?UTF-8?q?=D0=B2=D0=BE=D0=B7=D0=BC=D0=BE=D0=B6=D0=BD?= =?UTF-8?q?=D0=BE=D1=81=D1=82=D1=8C=20=D1=83=D1=81=D1=82=D0=B0=D0=BD=D0=BE?= =?UTF-8?q?=D0=B2=D0=B8=D1=82=D1=8C=20=D0=BB=D0=B8=D0=BC=D0=B8=D1=82=20?= =?UTF-8?q?=D0=B8=D1=81=D0=BF=D0=BE=D0=BB=D1=8C=D0=B7=D0=BE=D0=B2=D0=B0?= =?UTF-8?q?=D0=BD=D0=B8=D1=8F=20cpu?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/spider.js | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/lib/spider.js b/lib/spider.js index 1fb1b4a..aa6826a 100644 --- a/lib/spider.js +++ b/lib/spider.js @@ -5,6 +5,7 @@ const Emiter = require('events') const bencode = require('bencode') const {Table, Node} = require('./table') const Token = require('./token') +const cpuUsage = require('./cpu-usage') const bootstraps = [{ address: 'router.bittorrent.com', @@ -40,6 +41,8 @@ class Spider extends Emiter { this.ignore = false; // ignore all requests this.walkInterval = 5; + this.cpuLimit = 0; + this.cpuInterval = 10; } send(message, address) { @@ -68,7 +71,7 @@ class Spider extends Emiter { walk() { if(!this.client || this.client.isIdle()) { - if(!this.ignore) + if(!this.ignore && (this.cpuLimit <= 0 || cpuUsage() < this.cpuLimit + this.cpuInterval)) { const node = this.table.shift() if (node) { @@ -90,6 +93,10 @@ class Spider extends Emiter { } onFindNodeRequest(message, address) { + if(this.cpuLimit > 0 && cpuUsage() > this.cpuLimit) { + return + } + const {t: tid, a: {id: nid, target: infohash}} = message if (tid === undefined || target.length != 20 || nid.length != 20) { @@ -107,6 +114,10 @@ class Spider extends Emiter { } onGetPeersRequest(message, address) { + if(this.cpuLimit > 0 && cpuUsage() > this.cpuLimit) { + return + } + const {t: tid, a: {id: nid, info_hash: infohash}} = message if (tid === undefined || infohash.length != 20 || nid.length != 20) { @@ -143,7 +154,10 @@ class Spider extends Emiter { }; this.emit('ensureHash', infohash.toString('hex').toUpperCase(), addressPair) if(this.client && !this.ignore) { - this.client.add(addressPair, infohash); + console.log('cpu usage:' + cpuUsage()) + if(this.cpuLimit <= 0 || cpuUsage() <= this.cpuLimit + this.cpuInterval) { + this.client.add(addressPair, infohash); + } } }