#!/usr/bin/python

import netsnmp
import time
import copy
import pika

from os import chdir

import json
import sys
import os
import atexit

from signal import SIGTERM

HOST = '172.19.0.10'
COMMUNITY = 'public'

LOOP_SLEEPTIME = 10



# SLOTS_NUM = 18  # 12 leafs + 6 spine
# LAST_LEAF_SLOT = 12
# PORTS_IN_SLOT = 24


def snmpbulkwalk(oid, good_tag):
    sess = netsnmp.Session(Version = 2, DestHost=HOST, Community=COMMUNITY)

    vals = []
    curr_oid = oid

    while True:
        var_list = netsnmp.VarList(netsnmp.Varbind(curr_oid))
        sess.getbulk(0, 64, var_list)

        if not var_list:
            return vals

        for bind in var_list:
            if bind.tag == good_tag:
                vals.append(bind.val)
            else:
                return vals

        curr_oid = oid + var_list[-1].iid

    return vals


def compute_speed(old_vals, new_vals, old_time, new_time):
    time_diff = new_time - old_time

    if time_diff == 0:
        print("Time difference is 0")
        return

    if len(old_vals) != len(new_vals):
        print("Sizes of counters arrays are differ(%s vs %s)" % (len(old_vals), len(new_vals)))
        return

    counters_num = len(old_vals)

    sum_data = 0

    for i in range(counters_num):
        diff_val = int(new_vals[i]) - int(old_vals[i])
        if diff_val < 0:
            print("Strange, new value < old one")
        sum_data += diff_val


    speed = sum_data / time_diff

    speed_in_gbit = speed * 8 / 1000 / 1000 / 1000

    print("%s gbit/s (%s bytes in %s secs)" % (speed_in_gbit, sum_data, time_diff))
    return speed_in_gbit


class Daemon:
    """
    A generic daemon class.

    Usage: subclass the Daemon class and override the run() method
    """
    def __init__(self, pidfile, stdin='/dev/null', stdout='/dev/null',
                 stderr='/dev/null'):
        self.stdin = stdin
        self.stdout = stdout
        self.stderr = stderr
        self.pidfile = pidfile

    def daemonize(self):
        """
        do the UNIX double-fork magic, see Stevens' "Advanced
        Programming in the UNIX Environment" for details (ISBN 0201563177)
        http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
        """
        try:
            pid = os.fork()
            if pid > 0:
                # exit first parent
                sys.exit(0)
        except OSError, e:
            sys.stderr.write("fork #1 failed: %d (%s)\n" %
                             (e.errno, e.strerror))
            sys.exit(1)

        # decouple from parent environment
        os.chdir("/")
        os.setsid()
        os.umask(0)

        # do second fork
        try:
            pid = os.fork()
            if pid > 0:
                # exit from second parent
                sys.exit(0)
        except OSError, e:
            sys.stderr.write("fork #2 failed: %d (%s)\n" %
                             (e.errno, e.strerror))
            sys.exit(1)

        # redirect standard file descriptors
        sys.stdout.flush()
        sys.stderr.flush()
        si = file(self.stdin, 'r')
        so = file(self.stdout, 'a+', 1)
        se = file(self.stderr, 'a+', 1)
        os.dup2(si.fileno(), sys.stdin.fileno())
        os.dup2(so.fileno(), sys.stdout.fileno())
        os.dup2(se.fileno(), sys.stderr.fileno())

        # write pidfile
        atexit.register(self.delpid)
        pid = str(os.getpid())
        file(self.pidfile, 'w+').write("%s\n" % pid)

    def delpid(self):
        os.remove(self.pidfile)

    def start(self):
        """
        Start the daemon
        """
        # Check for a pidfile to see if the daemon already runs
        try:
            pf = file(self.pidfile, 'r')
            pid = int(pf.read().strip())
            pf.close()
        except IOError:
            pid = None

        if pid:
            message = "pidfile %s already exist. Daemon already running?\n"
            sys.stderr.write(message % self.pidfile)
            sys.exit(1)

        # Start the daemon
        self.daemonize()
        self.run()

    def stop(self):
        """
        Stop the daemon
        """
        # Get the pid from the pidfile
        try:
            pf = file(self.pidfile, 'r')
            pid = int(pf.read().strip())
            pf.close()
        except IOError:
            pid = None

        if not pid:
            message = "pidfile %s does not exist. Daemon not running?\n"
            sys.stderr.write(message % self.pidfile)
            return  # not an error in a restart

        # Try killing the daemon process
        try:
            while 1:
                os.kill(pid, SIGTERM)
                time.sleep(0.1)
        except OSError, err:
            err = str(err)
            if err.find("No such process") > 0:
                if os.path.exists(self.pidfile):
                    os.remove(self.pidfile)
            else:
                print str(err)
                sys.exit(1)

    def restart(self):
        """
        Restart the daemon
        """
        self.stop()
        self.start()

    def run(self):
        """
        You should override this method when you subclass Daemon.
        It will be called after the process has been
        daemonized by start() or restart().
        """


class StatDaemon(Daemon):
    def __init__(self, *args, **kwargs):
        Daemon.__init__(self, *args, **kwargs)


    def get_new_and_publish_loop(self, channel):
        old_vals = snmpbulkwalk('.1.3.6.1.2.1.31.1.1.1.6.', 'ifHCInOctets')
        old_time = time.time()

        time.sleep(LOOP_SLEEPTIME)

        while True:
            vals = snmpbulkwalk('.1.3.6.1.2.1.31.1.1.1.6.', 'ifHCInOctets')
            vals_time = time.time()

            if not vals:
                print("Missing an iteration, some connection problem")
                time.sleep(1)
                continue

            new_vals = vals
            new_time = vals_time

            tx = compute_speed(old_vals, new_vals, old_time, new_time)

            serialized_msg = json.dumps({"tx": tx })
            channel.basic_publish(exchange='ethernet', routing_key='',
                                  body=serialized_msg)

            old_time = new_time
            old_vals = vals

            time.sleep(LOOP_SLEEPTIME)

        # old_vals = []
        # old_times = []
        # for slot in range(1, SLOTS_NUM + 1):
        #     old_vals.append(get_transmitted_bytes(slot))
        #     old_times.append(time.time())

        # time.sleep(LOOP_SLEEPTIME)

        # while True:
        #     vals = []
        #     times = []
        #     speeds = []
        #     for i in range(SLOTS_NUM):
        #         slot = i + 1
        #         vals.append(get_transmitted_bytes(slot))
        #         times.append(time.time())

        #         speeds.append(compute_speed(old_vals[i], vals[i], old_times[i], times[i]))

        #     # print(speeds)
        #     # readable_speeds = ["{0:.2f}".format(speed) for speed in speeds]
        #     # print(" ".join(readable_speeds))

        #     tx, tx_interblock = sum(speeds[:LAST_LEAF_SLOT]), sum(speeds[LAST_LEAF_SLOT:])

        #     serialized_msg = json.dumps({"tx": tx, "tx_interblock": tx_interblock})
        #     channel.basic_publish(exchange='infiniband', routing_key='',
        #                           body=serialized_msg)

        #     time.sleep(LOOP_SLEEPTIME)

        #     old_times = times
        #     old_vals = vals


    def run(self):
        while True:
            try:
                print("New iteration")

                connection = pika.BlockingConnection(pika.ConnectionParameters(
                    'clusters.imm.uran.ru'))
                channel = connection.channel()

                channel.exchange_declare(exchange='ethernet', type='fanout', durable=False)
                channel.queue_declare(exclusive=True)

                self.get_new_and_publish_loop(channel)

                connection.close()
            except Exception as E:
                print("Exception: %s" % E)
            finally:
                time.sleep(LOOP_SLEEPTIME)

if __name__ == "__main__":
    daemon = StatDaemon('/tmp/eth_publisher.pid',
                        stdout="/tmp/eth_publisher.log",
                        stderr="/tmp/eth_publisher.log")
    if len(sys.argv) == 2:
        if 'start' == sys.argv[1]:
            daemon.start()
        elif 'stop' == sys.argv[1]:
            daemon.stop()
        elif 'restart' == sys.argv[1]:
            daemon.restart()
        else:
            print "Unknown command"
            sys.exit(2)
        sys.exit(0)
    else:
        print "usage: %s start|stop|restart" % sys.argv[0]
        sys.exit(2)
