#!/usr/bin/python
import pprint
import subprocess
import json
import re
import pika
import socket
import signal
import ConfigParser
import sys

# Read Config
config = ConfigParser.ConfigParser()
config.read('/etc/noris/check_mq_helper.ini')

def handler(signum, frame):
    print 'Signal handler called with signal', signum
    raise RuntimeError("Timeout while waiting for reply")

signal.signal(signal.SIGALRM, handler)
signal.alarm(10)

pp = pprint.PrettyPrinter(indent=4)
fqdn = socket.getfqdn()
ovs_vsctl_connection = "tcp:127.0.0.1:6640"

# RabbitMQ
rabbitmq_connection_url = config.get('rabbitmq', 'connection_url')
rabbitmq_exchange = config.get('rabbitmq', 'exchange')

connection = pika.BlockingConnection(pika.URLParameters(rabbitmq_connection_url))

# define rabbitmq channel, exchange and queue
channel = connection.channel()
channel.exchange_declare(exchange=rabbitmq_exchange, exchange_type='direct')
result = channel.queue_declare(exclusive=True)
queue_name = result.method.queue
channel.queue_bind(exchange=rabbitmq_exchange, queue=queue_name, routing_key=fqdn)

ret_value = 0

def debug(msg):
    #print (msg)
    return 0

def send_request(connection):
    #
    # Sends msg to exchange with routing_key 'control'
    #
    # this msg will be processed by control-nodes and answered with routing_key 'fqdn'
    #
    data = {}
    channel = connection.channel()

    data['fqdn'] = fqdn
    data['function'] = 'get_active_ports'

    json_string = json.dumps(data)
    channel.basic_publish(exchange=rabbitmq_exchange, routing_key='control', body=json_string)
    debug("Sent Req: " + json_string)

def recv_reply(body):
    #
    # Process given json-data
    #
    data = json.loads(body)

    ret_value = 0

    debug("---")
    debug("Input JSON")
    debug("---")
    debug(pp.pformat(data))

    #
    # Erzeuge liste der PortIDs
    #
    debug("---")
    debug("OVS-Port-IDs")
    debug("---")
    output = subprocess.check_output(["/usr/bin/ovsdb-client -f csv dump Open_vSwitch Interface"], shell=True).split('\n')

    debug(pp.pformat(output))

    for neutron_port in data:
	found = 0
    	for ovs_port_line in output:
		if re.search(neutron_port, ovs_port_line):
			found = 1
			continue;

	if found == 1:
		debug("Found " + neutron_port)
	else:
		print("Neutron Port " + neutron_port + " is not running on this maschine")
		ret_value=2

    return ret_value


debug('Sending Req to Control')
send_request(connection)
debug('Waiting for messages in queue:' + queue_name + ' To exit press CTRL+C')
for method, properties, body in channel.consume(queue_name):
    ret_value = recv_reply(body)
    break

connection.close()

if(ret_value == 0):
    print("OK")

exit(ret_value)

