#!/usr/bin/python import csv import re class infostor: '''Interface to node tables''' ''' Internally stores self.csvnodelist, which is a dictionary of dictionaries. The outer dictionary is keyed by the entries in the first column of the csv file (So the first column should be something unique like a nodename.) The inner dictionary is keyed by the header. Note that the items from first colum are both the outer key and also in the inner dictionary. The csv file inuse currently has the short private hostname as the first column. ''' def __init__(self, fname="/export/rocks/install/tools/nodeinfo/nodeinfo.csv"): '''Read in the csv file''' self.csvfname = fname '''need to do something here to verify input''' self.csvreader = csv.reader(open(self.csvfname, "rb")) self.csvheader = self.csvreader.next() self.csvnodelist = list(self.csvreader) ''' make a dictionary from the node list indexed by short local name''' self.csvnodedict = {} for row in self.csvnodelist: nodeid = row[0] '''nodedict forms the inner dictionary''' nodedict = {} for i in range(0, len(row)): nodedict[self.csvheader[i]] = row[i] self.csvnodedict[nodeid] = nodedict def get_header(self): '''return the header (var names)''' return self.csvheader def get_nodes(self): '''return a list with all the nodes''' return self.csvnodelist def get_node(self,node): '''return a single node''' return self.csvnodedict[node] def get_node_flex(self,var,val): '''find a node that matches a given variable for the specificied value''' for nodekey in self.csvnodedict.keys(): anode = self.csvnodedict[nodekey] if anode[var] == val: return anode return def get_node_var(self,node,var): try: anode = self.csvnodedict[node] return anode[var] except: return "" def get_node_var_flex(self,nodename,var): '''returns value for node:var tuple. also node to be specified by''' ''' short or long and private or public names''' '''assumes that the short private and public names uniquely identify one row from the table''' short_name = nodename.split('.')[0] try: anode = self.csvnodedict[short_name] return anode[var] except: try: anode = self.get_node_flex("NAME_PUBLIC",short_name) return anode[var] except: return "" def find_node_name(self,tofind): '''returns private node name based on either private or public name''' allnames = self.get_nodes if allnames[tofind]: return tofind def main(): '''Test for module''' info = infostor() print 'nodeinfo.py is running main. doing tests.' print 'there are %d nodes' % len(info.get_nodes()) print 'header is %s' % info.get_header() print "node cc-102-1" print info.get_node("cc-102-1") print "DOMAIN_PRIVATE for cc-102-1 is:" print info.get_node_var("cc-102-1", "DOMAIN_PRIVATE") print "CONDOR_CONFIG for c-119-3 using flex is:" print info.get_node_var_flex("c-119-3", "CONDOR_CONFIG") print "MAC_PRIVATE for c-119-3 using flex is:" print info.get_node_var_flex("c-119-3", "MAC_PRIVATE") if __name__ == '__main__' : main()