api_cache.js
4.04 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
import Memcached from 'memcached';
import ws from '../../lib/ws';
import _ from 'lodash';
class ApiCache {
constructor(host) {
this.host = host;
this.memcached = new Memcached(host);
}
delKey(key) {
this._log(`deleting ${key}`)
this.memcached.del(key, (err) => {
if (err) {
this._log(`deleted ${key} fail`)
} else {
this._log(`deleted ${key} success`)
}
});
}
flushAll() {
this.memcached.flush(err => {
if (err) {
this._log(`flush all fail.` + err.toString())
} else {
this._log(`flush all success`)
}
this.memcached.end();
});
}
stats() {
this.memcached.stats( (err, stats) => {
if (err) {
} else {
if (_.isArray(stats)) {
stats = stats[0];
}
stats.hits_percent = (stats.get_hits / (stats.get_hits + stats.get_misses) * 100).toFixed(2) + '%';
stats.heap_info = (stats.bytes / 1024 / 1024).toFixed(4) + 'mb' + ' / ' + stats.limit_maxbytes / 1024 / 1024 + 'mb';
ws.broadcast(`/api_cache/monit`, {
host: this.host,
stats: stats
});
}
});
}
clean(key) {
let begin = new Date();
let key1 = `apiCache:${key}`;
let key2 = `apiCache2:${key}`;
let count = 0;
this.memcached.items( ( err, result ) => {
if( err ) console.error( err );
if (result.length === 0) {
this._log('empty items')
}
// for each server...
result.forEach(itemSet => {
var keys = Object.keys( itemSet );
keys.pop(); // we don't need the "server" key, but the other indicate the slab id's
var len = keys.length;
if (keys.length === 0) {
this._log('empty item set');
}
keys.forEach(stats => {
// get a cachedump for each slabid and slab.number
this.memcached.cachedump( itemSet.server, parseInt(stats, 10), itemSet[stats].number, ( err, response ) => {
// dump the shizzle
if (response) {
if (_.isArray(response)) {
_.each(response, keyObj => {
count ++ ;
if (keyObj.key && (keyObj.key.indexOf(key1) >= 0 || keyObj.key.indexOf(key2) >= 0 || keyObj.key.indexOf(key) >= 0)) {
this.delKey(keyObj.key);
} else {
// this._log(`skip ${keyObj.key}`)
}
});
} else {
count ++;
if (response.key && (response.key.indexOf(key1) >= 0 || response.key.indexOf(key2) >= 0 || response.key.indexOf(key) >= 0)) {
this.delKey(response.key);
} else {
// this._log(`skip ${response.key}`)
}
}
}
len --;
if (len === 0) {
this.memcached.end();
let end = new Date();
this._log(`>>>>>> clean success in ${end.getTime() - begin.getTime()} , all keys: ${count}`)
}
})
})
})
});
}
_log(message) {
ws.broadcast(`/api_cache/log`, {
host: this.host,
msg: message
});
}
}
export default ApiCache;