#!/usr/bin/env python2
#
# The MySQLdb package only works in python2, so far

import MySQLdb     # pSQL setzt auf MySQLdb auf
import os
import sys
import json
import zlib
from base64 import encodestring

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

err = 0
ports = {}
instances = {}
invalid = {}
output = ""

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

cur = neutron_db.cursor()

sql = "select p.id, bind.host, p.device_id instance_id from ports p, ml2_port_bindings bind where p.device_owner like 'compute:%' and p.id = bind.port_id and bind.host like 'hv%' and p.device_id <> '' and p.device_id is not NULL"
cur.execute(sql)

for row in cur.fetchall():
  port_id = row[0]
  ports[port_id] = { 'host' : row[1] }
  ports[port_id]['instance'] = row[2]

cur2 = nova_db.cursor()
sql = "select uuid, host from instances where deleted=0 and host is not null"
cur2.execute(sql)

for row in cur2.fetchall():
  instances[row[0]] = { 'host' : row[1] }  

invalid['ports'] = []

for port in ports:
  host_port = ports[port]['host']
  # print("checking port " + port)
  try:
    host_instance = instances[ports[port]['instance']]['host']
  except KeyError:
    # print("instance " + ports[port]['instance'] + " doesn't have a host.")
    # e.g. the instance is shelved but the port still exists
    continue
  if host_port == host_instance:
    instances[ports[port]['instance']]['visited'] = 1
  else:
    invalid['ports'].append({ 'uuid': port, 'location_port': host_port, 'location_instance': host_instance })
    output += "suggest: openstack port set --host " +  host_instance + " " + port + "\n"
    err = 2 # Critical

if err == 0:
  print("OK")
else:
  print("wrong locations found")
  print("###BASE64BEGIN###")
  print( encodestring(zlib.compress(json.dumps(invalid),9)) + "###BASE64END###")
  print output

sys.exit(err);
