#!/usr/bin/env python

import threading
import MySQLdb
import sys
import _mysql_exceptions

sample_nodes = [ "ipp004", "ipp005", "ipp006", "ipp007", "ipp008", "ipp009", 
                 "ipp060", "ipp061", "ipp062", "ipp063", ]

def usage():
    pass

class QueryingThread(threading.Thread):
    count_query_exact = "SELECT COUNT(*) FROM %s WHERE nebkey = '%s'"
    count_query_approximate = "SELECT COUNT(*) FROM %s WHERE nebkey LIKE '%s'"
    query_exact = "SELECT subdirname, filename FROM %s WHERE nebkey = '%s'"
    query_approximate = "SELECT subdirname, filename FROM %s WHERE nebkey LIKE '%s'"
    letters = "0123456789abcdef"

    def __init__(self, node, pattern):
        threading.Thread.__init__(self)
        self.node = node
        self.db = MySQLdb.connect(host=node, user='ippuser', passwd='ipp', db='DisksMonitoring')
        self.cursor = self.db.cursor()
        if '%' in pattern:
            self.count_query = QueryingThread.count_query_approximate
            self.query = QueryingThread.query_approximate
        else:
            self.count_query = QueryingThread.count_query_exact
            self.query = QueryingThread.query_exact

    def run(self):
        try:
            for letter1 in QueryingThread.letters:
                for letter2 in QueryingThread.letters:
                    tablename = 'neb_0_%s%s' % (letter1, letter2)
                    self.cursor.execute(self.count_query % (tablename, pattern))
                    rows = self.cursor.fetchall()
                    count = rows[0][0]
                    if count != 0:
                        self.cursor.execute(self.query % (tablename, pattern))
                        for row in self.cursor.fetchall():
                            print '/data/%s.0/nebulous/%s%s/%s/%s' % (self.node, letter1, letter2, row[0], row[1])
        except _mysql_exceptions.ProgrammingError, e:
            print e
            print 'Problem with %s %s' % (self.node, tablename)
            
if __name__ == '__main__':
    pattern = sys.argv[1]
    queryingThreads = []
    nodesFilename = '/home/panstarrs/schastel/local/share/ippMhpccStorageNodes'
    nodesFile = open(nodesFilename)
    nodes = []
    for line in nodesFile:
        nodes.append(line[:-1])
    for node in nodes:
        try:
            queryingThreads.append(QueryingThread(node, pattern))
        except _mysql_exceptions.OperationalError, e:
            print e
    for t in queryingThreads:
        t.start()
    for t in queryingThreads:
        t.join()

