CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Pages
ExtractAppInfoFromXML.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 """Syntax:
3  ExtracAppInfoFromXML [-sapc] file
4 Parameters:
5  file file from where to read a RCMS configuration
6  -s list application servers found in the XML file
7  -p list the ports used found in the XML file
8  -a list the names of the applications configured in the XML file
9  -c list the cfg (eg dqmfu09-1_cfg.py) files
10 Notes:
11  The default behavior is to present a table organized in the following way
12  SERVER PORT CFG_FILE APP_NAME
13  which is equivalent to using -sapc
14 
15  The options selected and their order will affect teeh fields shown and their
16  respective sorting. eg.
17  -sa will only show SERVER and APP_NAME and will sort first by SERVER and
18  then by APP_NAME
19 
20  OUTPUT is always unique in a per row bases
21 """
22 ################################################################################
23 import sys, os.path
24 from xml.dom import minidom
25 ################################################################################
26 # Some module's global variables.
27 xmldoc=""
28 
29 def printXMLtree(head,l=0,bn=0):
30  tabs=""
31  for a in range(l):
32  tabs+="\t"
33  try:
34  print "[%d-%d-%d]"%(l,bn,head.nodeType)+tabs+"+++++>"+head.tagName
35  except AttributeError as e:
36  print "[%d-%d-%d]"%(l,bn,head.nodeType)+tabs+"+++++>"+str(e)
37  print "[%d-%d-%d-v]"%(l,bn,head.nodeType)+tabs+"."+ (head.nodeValue or "None")
38  try:
39  for katt,vatt in head.attributes.items():
40  if katt!="environmentString":
41  print tabs+"%s=%s"%(katt,vatt)
42  else:
43  print tabs+"%s= 'Some Stuff'"%(katt,)
44  except:
45  pass
46  i=0
47  for node in head.childNodes:
48  printXMLtree(node,l+1,i)
49  i+=1
50 ################################################################################
51 def compactNodeValue(head):
52  firstborne=None
53  for item in head.childNodes:
54  if item.nodeType == 3:
55  firstborne = item
56  break
57  if not firstborne:
58  return
59  for item in head.childNodes[1:]:
60  if item.nodeType == 3:
61  firstborne.nodeValue+=item.nodeValue
62  item.nodeValue=None
63 
64 ################################################################################
65 def appendDataXML(head):
66  """Parses information that's XML format from value to the Docuemnt tree"""
67  compactNodeValue(head)
68  if head.firstChild.nodeValue:
69  newNode=minidom.parseString(head.firstChild.nodeValue)
70  for node in newNode.childNodes:
71  head.appendChild(node.cloneNode(True))
72  newNode.unlink()
73 ################################################################################
74 def getAppNameFromCfg(filename):
75  """it searches for the line containing the string consumerName, usually
76  found as a property of the process, and returns the set value found.
77  eg.
78  matches line:
79  process.EventStreamHttpReader.consumerName = 'EcalEndcap DQM Consumer'
80  returns:
81  EcalEndcap DQM Consumer
82  """
83  try:
84  f = open(filename)
85  consumer = f.readline()
86  name=""
87  while consumer :
88  consumer=consumer.strip()
89  if "consumerName" in consumer:
90  name=consumer[consumer.index("'")+1:consumer.index("'",consumer.index("'")+1)]
91  break
92  consumer = f.readline()
93  f.close()
94  except:
95  sys.stderr.write("WARNING: Unable to open file: " + filename + " from <configFile> section of XML\n")
96  name = "CONFIG FILE IS M.I.A"
97  return name
98 ################################################################################
99 def getProcNameFromCfg(filename):
100  """it searches for the line containing the string consumerName, usually
101  found as a property of the process, and returns the set value found.
102  eg.
103  matches line:
104  process = cms.Process ("ECALDQM")
105  returns:
106  ECALDQM
107  """
108  try:
109  f = open(filename)
110  except:
111  sys.stderr.write("Unable to open file: " + filename + " from <configFile> section of XML\n")
112  raise IOError
113  consumer = f.readline()
114  name=""
115  while consumer :
116  consumer=consumer.strip()
117  if "cms.Process(" in consumer:
118  name=consumer[consumer.index("(")+2:consumer.index(")")-1]
119  break
120  consumer = f.readline()
121  f.close()
122  return name
123 ################################################################################
124 def filterNodeList(branch1,nodeList):
125  if len(branch1) > 0:
126  branch=branch1[:len(branch1)]
127  idx=0
128  for item in range(len(nodeList)):
129  vals=[v for (k,v) in nodeList[idx].attributes.items()]
130  if branch[0] not in vals:
131  del nodeList[idx]
132  else:
133  idx=idx+1
134  del branch[0]
135  elif len(branch1)==0:
136  return nodeList
137  return filterNodeList(branch,nodeList)
138 
139 ################################################################################
140 def fillTable(order,branch=[]):
141  global xmldoc
142  table={}
143  if len(order)==0:
144  return table
145  key=min(order.keys())
146  k=order[key]
147  order.pop(key)
148  if k=="s":
149  lista=xmldoc.getElementsByTagName("XdaqExecutive")
150  lista=filterNodeList(branch,lista)
151  for item in lista:
152  table[item.attributes["hostname"].value]=""
153  for item in table.keys():
154  table[item]=fillTable(order.copy(),branch + [item])
155  elif k=="a":
156  lista=xmldoc.getElementsByTagName("XdaqExecutive")
157  lista=filterNodeList(branch,lista)
158  for item in lista:
159  pset=item.getElementsByTagName("parameterSet")
160  if len(pset):
161  arch=pset[0].firstChild.nodeValue[5:]
162  appname=getAppNameFromCfg(arch) or getProcNameFromCfg(arch)
163  table[appname]=""
164  else:
165  App=item.getElementsByTagName("xc:Application")
166  table[App[0].attributes["class"].value]=""
167  for item in table.keys():
168  table[item]=fillTable(order.copy(),branch)
169  elif k=="p":
170  lista=xmldoc.getElementsByTagName("XdaqExecutive")
171  lista=filterNodeList(branch,lista)
172  for item in lista:
173  table[item.attributes["port"].value]=""
174  for item in table.keys():
175  table[item]=fillTable(order.copy(),branch + [item])
176  elif k=="c":
177  lista=xmldoc.getElementsByTagName("XdaqExecutive")
178  lista=filterNodeList(branch,lista)
179  for item in lista:
180  pset=item.getElementsByTagName("parameterSet")
181  if not len(pset):
182  table["No additional file"]=""
183  else:
184  table[pset[0].firstChild.nodeValue]=""
185  for item in table.keys():
186  table[item]=fillTable(order.copy(),branch)
187  else:
188  pass
189  return table
190 ################################################################################
191 def SortAndGrid(table,order):
192  """table => {s:{p:{c:{a:{}}}}}"""
193  grid=[]
194  for (server,ports) in table.items():
195  for (port,configfiles) in ports.items():
196  for (configfile,appnames) in configfiles.items():
197  for appname in appnames.keys():
198  line=[]
199  for col in order.values():
200  if col=="s":
201  line.append(server)
202  if col=="p":
203  line.append(port)
204  if col=="c":
205  line.append(configfile)
206  if col=="a":
207  line.append(appname)
208  grid.append(line)
209  grid.sort()
210  return grid
211 ################################################################################
212 def printGrid(grid):
213  numcols=len(grid[0])
214  PPGrid=grid[:]
215  maxs=[]
216  for col in range(numcols):
217  maxs.append(0)
218  for line in grid:
219  for col in range(numcols):
220  if len(line[col])>maxs[col]:
221  maxs[col]=len(line[col])
222  for line in PPGrid:
223  pline=""
224  for col in range(numcols):
225  pline+=line[col].ljust(maxs[col]+2)
226  print pline
227 
228 ################################################################################
229 #getAppInfo #
230 ################################################################################
231 def getAppInfo(XMLf,s=0,a=2,p=1,c=3):
232  """ getAppInfo(XMLf,s=0,a=2,p=1,c=3) takes the file name of a valid RCMS
233  configuration and 4 variables that represent which fields are desired
234  and in which order.
235 
236  It returns a touple containing a directory that contains all the
237  relevant information in the XMLf file and a list of rows each row
238  containing the fiels specified by the other four variables in the r
239  espective order
240 
241  The fields are Servers (s) ports(p) Appnames a.k.a. consumer names(a)
242  and consumer config file. (Note: The consumerName is directly extracted
243  from the config file.) if one field is not desired it should be assigned
244  a value of -1 eg s=-1. other wise their value is mapped from smallest to
245  largest ==> left to right. Note the default values, they will take
246  precedence if not specifyed giving unexpected results
247  """
248  global xmldoc
249  try:
250  os.path.exists(XMLf)
251  except:
252  sys.stderr.write('File doesn\'t exist\n')
253  sys.exit(2)
254  try:
255  xmldoc = minidom.parse(XMLf)
256  except IOError:
257  sys.stderr.write('Unable to locate file ' +XMLf +'\n')
258  return ({},[])
259  except:
260  sys.stderr.write('Parser error\n')
261  return ({},[])
262 
263  configFileNodes=xmldoc.getElementsByTagName("configFile")
264  for node in configFileNodes:
265  appendDataXML(node)
266  ## The table is always filled in a specific order, to properly get the data
267  order={0:"s",1:"p",3:"a",2:"c"}
268  #try:
269  table=fillTable(order)
270  #except:
271  # return ({},[])
272  del order
273  order={}
274  if a != -1:
275  order[a]="a"
276  if c != -1:
277  order[c]="c"
278  if s != -1:
279  order[s]="s"
280  if p != -1:
281  order[p]="p"
282  grid=SortAndGrid(table,order)
283  #printXMLtree(xmldoc)
284  #Clean Up
285  xmldoc.unlink()
286  return (table,grid)
287 
288 ################################################################################
289 if __name__ == "__main__":
290  XMLfile=""
291  args=sys.argv
292  args.remove(args[0])
293  options=""
294  for arg in args:
295  if arg.startswith("-"):
296  options+=arg.strip("-")
297  else:
298  XMLfile=arg
299  if options.count("s")+options.count("a")+options.count("p")+options.count("c")!=len(options):
300  sys.stderr.write( "Sintax Error unrecognised option" )
301  sys.stderr.write( __doc__ )
302  sys.exit(2)
303  if options.count("s")+options.count("a")+options.count("p")+options.count("c")==0:
304  (apptable,appinfo)=getAppInfo(XMLfile)
305  else:
306  (apptable,appinfo)=getAppInfo(XMLfile,options.find("s"),options.find("a"),options.find("p"),options.find("c"))
307  if appinfo != []:
308  printGrid(appinfo)
309  apptable
T min(T a, T b)
Definition: MathUtil.h:58