Line Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312
#!/usr/bin/env python3
"""Syntax:
	ExtracAppInfoFromXML [-sapc] file
Parameters:
	file	file from where to read a RCMS configuration
	-s  	list application servers found in the XML file
	-p  	list the ports used found in the XML file
	-a  	list the names of the applications configured in the XML file
	-c  	list the cfg (eg dqmfu09-1_cfg.py) files
Notes:	
	The default behavior is to present a table organized in the following way
		SERVER PORT CFG_FILE APP_NAME
	which is equivalent to using -sapc
	
	The options selected and their order will affect teeh fields shown and their
	respective sorting. eg.
		-sa will only show SERVER and APP_NAME and will sort first by SERVER and
		 then by APP_NAME 
		 
	OUTPUT is always unique in a per row bases
"""
################################################################################
import sys, os.path,re
from xml.dom import minidom
################################################################################
# Some module's global variables.
xmldoc=""

def printXMLtree(head,l=0,bn=0):
	tabs=""
	for a in range(l):
		tabs+="\t"
	try:
		print "[%d-%d-%d]"%(l,bn,head.nodeType)+tabs+"+++++>"+head.tagName
	except AttributeError, e:
		print "[%d-%d-%d]"%(l,bn,head.nodeType)+tabs+"+++++>"+str(e)
	print "[%d-%d-%d-v]"%(l,bn,head.nodeType)+tabs+"."+ (head.nodeValue or "None")
	try:
		for katt,vatt in head.attributes.items():
			if katt!="environmentString":
				print tabs+"%s=%s"%(katt,vatt)
			else:
				print tabs+"%s= 'Some Stuff'"%(katt,)
	except:
		pass	
	i=0
	for node in head.childNodes:
		printXMLtree(node,l+1,i)
		i+=1
################################################################################
def compactNodeValue(head):
	firstborne=None
	for item in head.childNodes:
		if item.nodeType == 3:
			firstborne = item
			break
	if not firstborne:
		return
	for item in head.childNodes[1:]:
		if item.nodeType == 3:
			firstborne.nodeValue+=item.nodeValue
			item.nodeValue=None
			
################################################################################
def appendDataXML(head):
	"""Parses information that's XML format from value to the Docuemnt tree"""
	compactNodeValue(head)
	if head.firstChild.nodeValue:
		newNode=minidom.parseString(head.firstChild.nodeValue)
		for node in newNode.childNodes:
			head.appendChild(node.cloneNode(True))
		newNode.unlink()			
################################################################################
def getAppNameFromCfg(filename):
	"""it searches for the line containing the string consumerName, usually
	found as a property of the process, and returns the set value found.
	eg. 
	matches line:
		process.EventStreamHttpReader.consumerName = 'EcalEndcap DQM Consumer' 
	returns:
		EcalEndcap DQM Consumer	
	"""
	try:
		f = open(filename)
		consumer = f.readline()
		name=""
		while consumer :
			consumer=consumer.strip()
			if "consumerName" in consumer:
				name=re.search(r"(\"|\').*(\"|\')",consumer).group(0)
				name=name.strip("\"")
				name=name.strip("\'")
				#consumer[consumer.index("'")+1:consumer.index("'",consumer.index("'")+1)] 
				break
			consumer = f.readline()
		f.close()
	except IOError:
		sys.stderr.write("WARNING: Unable to open file: " + filename + " from <configFile> section of XML\n")
		name = "CONFIG FILE IS M.I.A"        
	return name
################################################################################
def getProcNameFromCfg(filename):
	"""it searches for the line containing the string consumerName, usually
	found as a property of the process, and returns the set value found.
	eg. 
	matches line:
		process = cms.Process ("ECALDQM") 
	returns:
		ECALDQM
	"""
	try:
		f = open(filename)
	except:
		sys.stderr.write("Unable to open file: " + filename + " from <configFile> section of XML\n")
		raise IOError
	consumer = f.readline()
	name=""
	while consumer :
		consumer=consumer.strip()
		if "cms.Process(" in consumer:
			name=consumer[consumer.index("(")+2:consumer.index(")")-1] 
			break
		consumer = f.readline()
	f.close()
	return name
################################################################################
def filterNodeList(branch1,nodeList):
	if len(branch1) > 0:
		branch=branch1[:len(branch1)]
		idx=0
		for item in range(len(nodeList)):
			vals=[v for (k,v) in nodeList[idx].attributes.items()]
			if branch[0] not in vals:
				del nodeList[idx]
			else:
				idx=idx+1
		del branch[0]
	elif len(branch1)==0:
		return nodeList	
	return filterNodeList(branch,nodeList)
		
################################################################################
def fillTable(order,branch=[]):
	global xmldoc
	table={} 
	if len(order)==0: 
		return table
	key=min(order.keys())	
	k=order[key]
	order.pop(key)
	if k=="s":
		lista=xmldoc.getElementsByTagName("XdaqExecutive")
		lista=filterNodeList(branch,lista)
		for item in lista:
			table[item.attributes["hostname"].value]=""
		for item in table.keys():
			table[item]=fillTable(order.copy(),branch + [item])
	elif k=="a":
		lista=xmldoc.getElementsByTagName("XdaqExecutive")
		lista=filterNodeList(branch,lista)
		for item in lista:
			pset=item.getElementsByTagName("parameterSet")
			if len(pset):
				arch=pset[0].firstChild.nodeValue[5:]
				appname=getAppNameFromCfg(arch) or getProcNameFromCfg(arch)
				table[appname]=""
			else:
				App=item.getElementsByTagName("xc:Application")
				table[App[0].attributes["class"].value]=""
		for item in table.keys():
			table[item]=fillTable(order.copy(),branch)
	elif k=="p":
		lista=xmldoc.getElementsByTagName("XdaqExecutive")
		lista=filterNodeList(branch,lista)
		for item in lista:
			table[item.attributes["port"].value]=""
		for item in table.keys():
			table[item]=fillTable(order.copy(),branch + [item])
	elif k=="c":
		lista=xmldoc.getElementsByTagName("XdaqExecutive")
		lista=filterNodeList(branch,lista)
		for item in lista:
			pset=item.getElementsByTagName("parameterSet")
			if not len(pset):
				table["No additional file"]=""	
			else:
				table[pset[0].firstChild.nodeValue]=""
		for item in table.keys():
			table[item]=fillTable(order.copy(),branch)
	else:
		pass
	return table
################################################################################
def SortAndGrid(table,order):
	"""table => {s:{p:{c:{a:{}}}}}"""
	grid=[]
	for (server,ports) in table.items():
		for (port,configfiles) in ports.items():
			for (configfile,appnames) in configfiles.items():
				for appname in appnames.keys():
					line=[]
					for col in order.values():
						if col=="s":
							line.append(server)
						if col=="p":
							line.append(port)
						if col=="c":
							line.append(configfile)
						if col=="a":
							line.append(appname)
					grid.append(line)
	grid.sort()
	return grid
################################################################################
def printGrid(grid):
	numcols=len(grid[0])
	PPGrid=grid[:]
	maxs=[]
	for col in range(numcols):
		maxs.append(0)
	for line in grid:
		for col in range(numcols):
			if len(line[col])>maxs[col]:
				maxs[col]=len(line[col])
	for line in PPGrid:
		pline=""
		for col in range(numcols):
			pline+=line[col].ljust(maxs[col]+2)
		print pline
			
################################################################################	
#getAppInfo                                                                    #
################################################################################
def getAppInfo(XMLf,s=0,a=2,p=1,c=3):
	"""	getAppInfo(XMLf,s=0,a=2,p=1,c=3) takes the file name of a valid RCMS 
		configuration and 4	variables that represent which fields are desired 
		and in which order. 
		
		It returns a touple containing a directory that contains all the 
		relevant information in the XMLf file and a list of rows each row 
		containing the fiels specified by the other four variables in the r
		espective order
		
		The fields are Servers (s) ports(p) Appnames a.k.a. consumer names(a) 
		and consumer config file. (Note: The consumerName is directly extracted 
		from the config file.) if one field is not desired it should be assigned
		a value of -1 eg s=-1. other wise their value is mapped from smallest to
		largest ==> left to right. Note the default values, they will take 
		precedence if not specifyed giving unexpected results
	"""
	global xmldoc
	try: 
		os.path.exists(XMLf)
	except:
		sys.stderr.write('File doesn\'t exist\n')
		sys.exit(2)
	try:
		xmldoc = minidom.parse(XMLf)
	except IOError:
		sys.stderr.write('Unable to locate file ' +XMLf +'\n')
		return ({},[])
	except:
		sys.stderr.write('Parser error\n')
		return ({},[])
		
	configFileNodes=xmldoc.getElementsByTagName("configFile")
	for node in configFileNodes:
		appendDataXML(node)
	## The table is always filled in a specific order, to properly get the data
	order={0:"s",1:"p",3:"a",2:"c"}
	#try:
	table=fillTable(order)
	#except:
	#	return ({},[])
	del order
	order={}
	if a != -1:
		order[a]="a"
	if c != -1:
		order[c]="c"
	if s != -1:
		order[s]="s"
	if p != -1:
		order[p]="p"
	grid=SortAndGrid(table,order)
	#printXMLtree(xmldoc)	
	#Clean Up
	xmldoc.unlink()
	return (table,grid)
	                                                          
################################################################################
if __name__ == "__main__":             
	XMLfile=""
	args=sys.argv
	args.remove(args[0])
	options=""
	for arg in args:
		if arg.startswith("-"):
			options+=arg.strip("-")
		else:
			XMLfile=arg
	if options.count("s")+options.count("a")+options.count("p")+options.count("c")!=len(options):
		sys.stderr.write(  "Sintax Error unrecognised option" )
		sys.stderr.write( __doc__ )
		sys.exit(2)
	if options.count("s")+options.count("a")+options.count("p")+options.count("c")==0:
		(apptable,appinfo)=getAppInfo(XMLfile)
	else:
		(apptable,appinfo)=getAppInfo(XMLfile,options.find("s"),options.find("a"),options.find("p"),options.find("c"))
	if appinfo != []:
		printGrid(appinfo)
	apptable