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

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

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

err = 0
ports = {}
instances = {}

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, p.device_id from neutron.ports p JOIN nova.instances i ON p.device_id = i.uuid WHERE device_owner LIKE 'compute:%' AND status='DOWN' AND admin_state_up = true AND device_id <> '' and device_id is not NULL AND i.vm_state  = 'active'"
cur.execute(sql)

header_printed = 0;
for row in cur.fetchall():
  if header_printed == 0:
    print("The following ports are down:")
    header_printed = 1
  print("Port " + row[0] + ", of instance ID " + row[1])
  err = 2 # Crit
if header_printed == 1:
  print

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

sys.exit(err);
