from monserver.PerfDataCache import PerfDataCache
from monserver.RRD.RRDHandler import RRDHandler
from monserver.utils.utils import encode
from monserver.utils.load_config import load_global_config
from monserver.utils.get_logger import get_logger
from xmlrpclib import ServerProxy

logger = get_logger('PerfDataCacheHTTPServer')


config = load_global_config()
cache_size = config.get('cache_size')
rrd_root = config.get("RRD_root")

db_handler = RRDHandler.getInstance(rrd_root)
cache = PerfDataCache.getInstance(cache_size, db_handler)

@app.route('/monitor')
def index():
    return redirect(url_for('static', filename='simple-monitor.html'))

@app.route('/monitor/json/<host>/<metric>')
def get_stats(host, metric):
    only_latest = False
    cf = request.args.get('cf', 'AVERAGE')
    step = request.args.get('step', 15)
    start = request.args.get('start')
    if start is None:
        only_latest = True
        start = '-%s' % step
output_file = "/tmp/test_rrdfetch_out%d"

time_log = "/tmp/test_rrdfetch_time"
with open(time_log, "w") as f:
    f.write("start at: %d\n" % time.time())

nc = 0
while nc < MAX_CLIENTS:
    pid = os.fork()
    if pid == 0:
        so = file(output_file % nc, "a+")
        os.dup2(so.fileno(), sys.stdout.fileno())
        os.dup2(so.fileno(), sys.stderr.fileno())
        print "child #%d" % nc
        p = RRDHandler.getInstance(RRD_DIR)
        nq = 0
        while nq < MAX_REQUEST:
            now = int(time.time())
            req = (
                "localhost",
                random.choice(test_metrics),
                random.choice(test_stats),
                random.choice(test_steps),
                now - random.randint(600, 3600),
                now - random.randint(0, 600),
            )
            print req
            print p.read(*req)
            nq += 1
            time.sleep(0.4)