#!/usr/bin/env python

import whisper
import sys
import time
import os
import mmap
import struct
import itertools
import math
import json
import argparse
import uuid
import string
import socket
import requests
import random
import subprocess
from requests.adapters import HTTPAdapter

parser = argparse.ArgumentParser()

parser.add_argument("check", type=uuid.UUID, help="uuid for check which metrics belong to")
parser.add_argument("host", help="hostname or ip of snowth host to send metrics to")
parser.add_argument("period", type=int, help="period in seconds of smallest rollup for target snowth cluster")
parser.add_argument("rootpath", help="root directory of whisper metrics")
parser.add_argument("paths", nargs='+', help="one or more paths to directories or files containing whisper metrics", metavar="path")
parser.add_argument("--check_name", help="name of the check that matches the check (uuid) param, this should match the <check_name> setting in your graphite listener", required=True)
parser.add_argument("--account_id", type=int, default=1, help="account id of the check.  this should match the <account_id> setting in your graphite listener", required=True)
parser.add_argument("--minperiod", type=int, default=0, help="ignore data with secondsPerPoint < minperiod (default 0)")
parser.add_argument("--end", type=int, default=float("inf"), help="ignore data with timestamp > end (default +inf)")
parser.add_argument("--ssl", action="store_true", help="use ssl to connect")
parser.add_argument("--batch", action="store_true", help="abort on first POST error")
parser.add_argument("--debug", type=int, default=0, help="debug level.")
parser.add_argument("--noop", type=bool, default=False, help="Show what import would do without actually importing. Useful with debug.")
parser.add_argument("--writecount", type=int, default=0, help="Do not submit more than <writecount> data points per request.")
parser.add_argument("--find_closest_name", action="store_true", default=False, help="Query the database for each metric to find the name with the closest prefix and use that as submission name.")

args = parser.parse_args()

check = args.check
check_name = args.check_name
account_id = args.account_id
locate_host = args.host
period = args.period
minperiod = args.minperiod
end_timestamp = args.end
rootpath = args.rootpath
cli_paths = args.paths
debug = args.debug
noop = args.noop
writecount = args.writecount
find_closest_name = args.find_closest_name
resolved_names = {}

def calc_url(host, path):
    return 'http%s://%s/%s' % (('s' if args.ssl else ''), host, path)

paths = []

for path in cli_paths:
    if os.path.isfile(path):
        paths.append(path)
    elif os.path.isdir(path):
        abspath = os.path.abspath(path)
        out = subprocess.check_output(["find", abspath, "-type", "f", "-name", "*.wsp"])
        paths.extend(string.split(out, '\n')[0:-1])
    else:
        print("Path %s not file or directory, ignoring" % path)

def stddev(vals):
    mean = sum(vals) / len(vals)
    top = sum([ (vals[i] - mean)**2 for i in xrange(len(vals)) ])
    return math.sqrt(top / len(vals))

def weighted_stddev(vals, weights):
    mean = sum(vals) / len(vals)
    top = sum([ (vals[i] - mean)**2 * weights[i] for i in xrange(len(vals)) ])
    bottom = sum(weights)
    return math.sqrt(top / bottom)

def do_rollup(window):
    r = {}
    (vals, times) = zip(*[(v[1], v[0]) for v in window])
    r['count'] = len(vals)
    r['value'] = sum(vals) / len(vals)
    r['stddev'] = r['derivative'] = r['counter'] = r['derivative_stddev'] = r['counter_stddev'] = 0
    if len(vals) > 1:
        r['stddev'] = stddev(vals)
        dv = [ vals[i+1] - vals[i] for i in xrange(0, len(vals) - 1) ]
        dt = [ times[i+1] - times[i] for i in xrange(0, len(times) - 1) ]
        cz = filter(lambda x: x[0] >= 0, zip(dv, dt))
        (cv, ct) = zip(*cz) if len(cz) > 0 else (False, False)
        r['derivative'] = sum(dv) / sum(dt)
        r['counter'] = sum(cv) / sum(ct) if cv else 0
        if len(vals) > 2:
            r['derivative_stddev'] = weighted_stddev(dv, dt)
            r['counter_stddev'] = weighted_stddev(cv, ct) if cv else 0
    return r

def get_metric_name(path):
    if path in resolved_names:
        return resolved_names[path]

    relpath = os.path.relpath(path, rootpath)
    noext = os.path.splitext(relpath)[0]
    temp = string.replace(noext, '/', '.')
    if (args.find_closest_name):
        query_url = calc_url(locate_host, 'graphite/%d/graphite.%s./metrics/find?query=%s' % (args.account_id, args.check_name, temp))
        response = requests.get(query_url)
        if (response.status_code != requests.codes.ok):
            print >> sys.stderr, "Could not locate closest name for %s" % (temp)
        else:
            r = json.loads(response.text)
            if r and len(r) > 0 and "leaf_data" in r[0]:
                name = r[0]["leaf_data"]["name"]
                if debug >= 3:
                    print >> sys.stderr, "DEBUG: found name %s" % name
                resolved_names[path] = name
                return name
    resolved_names[path] = temp
    return temp

def get_ingestion_nodes(uuid, metric_name):
    locate_url = calc_url(locate_host, 'locate/json/%s/%s' % (uuid, metric_name))
    response = requests.get(locate_url)
    # TODO: multiple attempts
    if response.status_code != requests.codes.ok:
        print >> sys.stderr, "Could not locate ingestion point for %s-%s" % (uuid, metric_name)
        sys.exit(1)
    resp_text = json.loads(response.text)
    return [ "%s:%d" % (l["address"], l["apiport"]) for l in resp_text["location"] ]

def submit(urls, rollups):
    json_dump = json.dumps(rollups)
    headers = {}
    headers["X-Snowth-Check-Name"] = check_name
    headers["X-Snowth-Check-Category"] = "graphite"
    headers["X-Snowth-Account-Id"] = "%d" % account_id
    headers["Connection"] = "close"

    if debug >= 3:
        print >> sys.stderr, "DEBUG: submit: header %s" % headers
        print >> sys.stderr, "DEBUG: %s" % json.dumps(rollups, indent=2)

    if not noop:
        url = urls[random.randint(0, len(urls) - 1)]
        if debug >= 2:
	        print >> sys.stderr, "DEBUG: submit url %s" % url
        s = requests.Session()
        s.mount('http', HTTPAdapter(max_retries=3))
        s.mount('https', HTTPAdapter(max_retries=3))
        response = s.post(url, headers=headers, data=json_dump)
        if response.status_code != requests.codes.ok:
            print >> sys.stderr, "Rollup submission failed for metric %s" % rollups[0]['metric']
            print >> sys.stderr, "uri: %s" % url
            print >> sys.stderr, "Rollups: %s" % json_dump
            print >> sys.stderr, "Response status code: %s" % response.status_code
            print >> sys.stderr, "Response headers: %s" % response.headers
            print >> sys.stderr, "Response body: %s" % response.text
            if args.batch:
                sys.exit(1)

for path in paths:
    archives = whisper.info(path)['archives']
    if debug >= 2:
        print >> sys.stderr, "DEBUG: whisper path %s archives secondsPerPoint %s" % (path, [ archive['secondsPerPoint'] for archive in archives ])
        print >> sys.stderr, "DEBUG: whisper path %s archives retention %s" % (path, [ archive['retention'] for archive in archives ])

    # Do not roll up whisper archives with `secondsPerPoint <
    # minperiod`. Note that this _will_ include archives _coarser_
    # than `period` in the resulting list. We want this, since the
    # coarser data will likely go further back in time than the finer
    # data, but there are storage-related consequences of the approach
    # we take... Given the insertion logic below, if `period` is 60,
    # and one of the archives has `secondsPerPoint` of 300, then we
    # will submit data from the `300` archive at 60-second resolution,
    # at the same timestamp as the 300-second data. This will mostly
    # work out fine on display at 300s-or-coarser resolutions: the
    # Circonus roll-up logic will ignore the NULLs between the 300s
    # datapoints, and the displayed value will match the input value.
    # When zooming in closer than 300s, the output data will appear to
    # have gaps, but will still have the correct values.
    archives = [ archive for archive in archives if archive['secondsPerPoint'] >= minperiod ]

    fd = os.open(path, os.O_RDONLY)
    fmap = mmap.mmap(fd, os.fstat(fd).st_size, prot=mmap.PROT_READ)
    os.close(fd)

    values_by_archive = dict( [ (archive['offset'], []) for archive in archives ] )

    for archive in archives:
        offset = archive['offset']
        if debug >= 3:
           print >> sys.stderr, "DEBUG: archive offset %d points %d secondsPerPoint %d\n" % (archive['offset'], archive['points'], archive['secondsPerPoint'])
        for point in xrange(archive['points']):
            (timestamp, value) = struct.unpack(whisper.pointFormat, fmap[offset:offset+whisper.pointSize])
            if timestamp > 0 and timestamp < end_timestamp:
                values_by_archive[archive['offset']].append((timestamp, value))
            offset += whisper.pointSize

    # this turns values_by_archive(a dict mapping archive offsets to lists of values)
    # into a dict mapping archive offsets to dicts mapping window ids to lists of values
    windows_by_archive = {}
    for offset, values in values_by_archive.items():
        tmp = {}
        for window_id, value_group in itertools.groupby(values, lambda value: value[0] // period):
            tmp[window_id] = list(value_group)
        windows_by_archive[offset] = tmp

    windows = {}

    # we're going through every archive dict and aggregating the windows into `windows` if not
    # already present(based on window_id).
    # since whisper files are sorted by decreasing resolution, we sort the windows_by_archive dict
    # by archive offset, meaning that higher resolution windows will take precedence
    for windows_from_archive in sorted(windows_by_archive.items(), key=lambda t: t[0]):
        for window in windows_from_archive[1].items():
            if window[0] not in windows:
                windows[window[0]] = window[1]

    rollups = []

    for window in windows.items():
        rollup = do_rollup(window[1])
        rollup['metric'] = get_metric_name(path)
        rollup['id'] = str(check)
        rollup['offset'] = window[0] * period
        rollups.append(rollup)
    rollups = sorted(rollups, key=lambda t: t['offset'])

    if debug >= 1:
        print >> sys.stderr, "DEBUG: whisper path %s %d rollups" % (path, len(rollups))
    if len(rollups) > 0:
        ingestion_hosts = get_ingestion_nodes(rollup['id'], rollup['metric'])
        submit_urls = [ calc_url(host, "write/nnt") for host in ingestion_hosts ]
        itercount = writecount if writecount != 0 else len(rollups)
        for curbatch in xrange(0, len(rollups), itercount):
            try:
                submit(submit_urls, rollups[curbatch:(curbatch+itercount)])
            except:
                print >> sys.stderr, "Error on submissions [%d:%d] for %s" % (curbatch, curbatch+itercount, path)
                raise

    fmap.close()
