#!/usr/bin/env python3
#

import MySQLdb     # pSQL setzt auf MySQLdb auf
import os
import sys
import pprint 

db_host = '127.0.0.1'
db_user = 'noris_monitoring'
db_pass = os.environ['DBAUTH']

pp = pprint.PrettyPrinter(indent=4)

ret = 0
failed_network_ids = []
data = {}

neutron_db = MySQLdb.connect(host=db_host, user=db_user, passwd=db_pass, db='neutron')

cur = neutron_db.cursor(MySQLdb.cursors.DictCursor)

sql = "select * from ports JOIN ml2_port_bindings ON ports.id = ml2_port_bindings.port_id JOIN networkdhcpagentbindings on ports.network_id = networkdhcpagentbindings.network_id JOIN agents ON dhcp_agent_id = agents.id AND agents.host = ml2_port_bindings.host WHERE ports.status = 'ACTIVE' AND ports.device_owner = 'network:dhcp'"
cur.execute(sql)

for row in cur.fetchall():
    network_id = row["network_id"]
    az = row["availability_zone"]
    port_id = row["port_id"]
    
    if network_id in data:
        # check if AZ is already defined
        if az in data[network_id]:
            # if yes, thats bad
            failed_network_ids.append(network_id)
            data[network_id][az].append(port_id)
        else:
            # else, create az with port_id-array
            data[network_id][az] = [ port_id ]
    else:
        # network_id not defined - create a new entry
        data[network_id] = { az: [ port_id ] }

# check if there are at least 2 AZs with active ports
for network_id in data:
    if len(data[network_id].keys()) != 2:
        ret = 2
        print("network: " + network_id + " has " + str(len(data[network_id].keys())) + " AZ(s)")
        failed_network_ids.append(network_id)

if len(failed_network_ids) > 0:
    ret=2
    print("There are networks with more than 1 dhcp-port per AZ:\n")
    for network_id in failed_network_ids:
        print("network_id: " + network_id)
        pp.pprint(data[network_id])
        print("---")
else:
    print("OK: There are no networks with more than 1 dhcp-port per AZ")

sys.exit(ret);
