api_cache.js 2.88 KB

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`)
            }
        });
    }

    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 );
            // 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;
                    
                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 )) {
                                        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 )) {
                                    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;