CMS 3D CMS Logo

getPayloadData.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 
4 from __future__ import print_function
5 import shutil
6 import glob
7 import json
8 import sys
9 import sys
10 import os
11 
12 from importlib import import_module
13 from argparse import ArgumentParser, RawTextHelpFormatter
14 
15 
16 import pluginCondDBV2PyInterface
17 pluginCondDBV2PyInterface.CMSSWInit()
18 
19 
20 
21 def supress_output( f ):
22  '''
23  Temporarily disables stdout and stderr so that printouts from the plot
24  plugin does not compromise the purity of our ssh stream if
25  args.suppress_output is true
26  '''
27  def decorated( *fargs, **fkwargs ):
28 
29  suppress = args.suppress_output
30  if suppress:
31 
32  # Get rid of what is already there ( should be nothing for this script )
33  sys.stdout.flush()
34 
35  # Save file descriptors so it can be reactivated later
36  saved_stdout = os.dup( 1 )
37  saved_stderr = os.dup( 2 )
38 
39  # /dev/null is used just to discard what is being printed
40  devnull = os.open( '/dev/null', os.O_WRONLY )
41 
42  # Duplicate the file descriptor for /dev/null
43  # and overwrite the value for stdout (file descriptor 1)
44  os.dup2( devnull, 1 )
45  os.dup2( devnull, 2 )
46 
47  result = f( *fargs, **fkwargs )
48 
49  if suppress:
50 
51  # Close devnull after duplication (no longer needed)
52  os.close( devnull )
53 
54  # Reenable stdout and stderr
55  os.dup2( saved_stdout, 1 )
56  os.dup2( saved_stderr, 2 )
57 
58  return result
59 
60  return decorated
61 
62 
63 @supress_output
64 def deserialize_iovs(db, plugin_name, plot_name, tag, time_type, iovs):
65  ''' Deserializes given iovs data and returns plot coordinates '''
66 
67  output('Starting to deserialize iovs: ', '')
68  output('db: ', db)
69  output('plugin name: ', plugin_name)
70  output('plot name: ', plot_name)
71  output('tag name: ', tag)
72  output('tag time type: ', time_type)
73  output('iovs: ', iovs)
74 
75  plugin_base = import_module('pluginModule_PayloadInspector')
76  output('PI plugin base: ', plugin_base)
77 
78  plugin_obj = import_module(plugin_name)
79  output('PI plugin object: ', plugin_obj)
80 
81  # get plot method and execute it with given iovs
82  plot = getattr(plugin_obj, plot_name)()
83  output('plot object: ', plot)
84 
85  if db == "Prod":
86  db_name = 'frontier://FrontierProd/CMS_CONDITIONS'
87  elif db == 'Prep' :
88  db_name = 'frontier://FrontierPrep/CMS_CONDITIONS'
89  else:
90  db_name = db
91 
92  output('full DB name: ', db_name)
93 
94 
95  success = plot.process(db_name, tag, time_type, int(iovs['start_iov']), int(iovs['end_iov']))
96  output('plot processed data successfully: ', success)
97  if not success:
98  return False
99 
100 
101  result = plot.data()
102  output('deserialized data: ', result)
103  return result
104 @supress_output
105 def deserialize_twoiovs(db, plugin_name, plot_name, tag,tagtwo,iovs,iovstwo):
106  ''' Deserializes given iovs data and returns plot coordinates '''
107  #print "Starting to deserialize iovs:"
108  #print 'First Iovs',iovs
109  #print 'Two Iovs', iovstwo
110  output('Starting to deserialize iovs: ', '')
111  output('db: ', db)
112  output('plugin name: ', plugin_name)
113  output('plot name: ', plot_name)
114  output('tag name: ', tag)
115  output('tagtwo name: ', tagtwo)
116  #output('tag time type: ', time_type)
117  output('iovs: ', iovs)
118  output('iovstwo: ', iovstwo)
119 
120  plugin_base = import_module('pluginModule_PayloadInspector')
121  output('PI plugin base: ', plugin_base)
122 
123  plugin_obj = import_module(plugin_name)
124  output('PI plugin object: ', plugin_obj)
125 
126  # get plot method and execute it with given iovs
127  plot = getattr(plugin_obj, plot_name)()
128  output('plot object: ', plot)
129 
130  db_name = 'oracle://cms_orcon_adg/CMS_CONDITIONS' if db == 'Prod' else 'oracle://cms_orcoff_prep/CMS_CONDITIONS'
131  output('full DB name: ', db_name)
132 
133 
134  success = plot.processTwoTags(db_name, tag,tagtwo,int(iovs['start_iov']), int(iovstwo['end_iov']))
135  #print "All good",success
136  output('plot processed data successfully: ', success)
137  if not success:
138  return False
139 
140 
141  result = plot.data()
142  output('deserialized data: ', result)
143  return result
144 
146  ''' Returns a list of Payload Inspector plugin names
147  Example:
148  ['pluginBasicPayload_PayloadInspector', 'pluginBeamSpot_PayloadInspector', 'pluginSiStrip_PayloadInspector']
149  '''
150  architecture = os.environ.get('SCRAM_ARCH', None)
151  output('architecture: ', architecture)
152 
153  plugins = []
154  releases = [
155  os.environ.get('CMSSW_BASE', None),
156  os.environ.get('CMSSW_RELEASE_BASE', None)
157  ]
158 
159  for r in releases:
160  if not r: continue # skip if release base is not specified
161  output('* release: ', r)
162 
163  path = os.path.join(r, 'lib', architecture)
164  output('* full release path: ', path)
165 
166  plugins += glob.glob(path + '/plugin*_PayloadInspector.so' )
167  output('found plugins: ', plugins)
168 
169  if r: break # break loop if CMSSW_BASE is specified
170 
171  # extracts the object name from plugin path:
172  # /afs/cern.ch/cms/slc6_amd64_gcc493/cms/cmssw/CMSSW_8_0_6/lib/slc6_amd64_gcc493/pluginBasicPayload_PayloadInspector.so
173  # becomes pluginBasicPayload_PayloadInspector
174  result = []
175  for p in plugins:
176  result.append(p.split('/')[-1].replace('.so', ''))
177 
178  output('discovered plugins: ', result)
179  return result
180 
181 def discover():
182  ''' Discovers object types and plots for a given cmssw release
183  Example:
184  {
185  "BasicPayload": [
186  {"plot": "plot_BeamSpot_x", "plot_type": "History",
187  "single_iov": false, "plugin_name": "pluginBeamSpot_PayloadInspector",
188  "title": "x vs run number"},
189  ...
190  ],
191  ...
192  }
193  '''
194  plugin_base = import_module('pluginModule_PayloadInspector')
195  result = {}
196  for plugin_name in discover_plugins():
197  output(' - plugin name: ', plugin_name)
198  plugin_obj = import_module(plugin_name)
199  output('*** PI plugin object: ', plugin_obj)
200  for plot in dir(plugin_obj):
201  if 'plot_' not in plot: continue # skip if method doesn't start with 'plot_' prefix
202  output(' - plot name: ', plot)
203  plot_method= getattr(plugin_obj, plot)()
204  output(' - plot object: ', plot_method)
205  payload_type = plot_method.payloadType()
206  output(' - payload type: ', payload_type)
207  plot_title = plot_method.title()
208  output(' - plot title: ', plot_title)
209  plot_type = plot_method.type()
210  output(' - plot type: ', plot_type)
211  single_iov = plot_method.isSingleIov()
212  output(' - is single iov: ', single_iov)
213  two_tags = plot_method.isTwoTags()
214  output(' - is Two Tags: ', two_tags)
215  result.setdefault(payload_type, []).append({'plot': plot, 'plugin_name': plugin_name, 'title': plot_title, 'plot_type': plot_type, 'single_iov': single_iov, 'two_tags': two_tags})
216  output('currently discovered info: ', result)
217  output('*** final output:', '')
218  return json.dumps(result)
219 
220 def output(description, param):
221  if args.verbose:
222  print('')
223  print(description, param)
224 
225 if __name__ == '__main__':
226 
227  description = '''
228  Payload Inspector - data visualisation tool which is integrated into the cmsDbBrowser.
229  It allows to display plots and monitor the calibration and alignment data.
230 
231  You can access Payload Inspector with a link below:
232  https://cms-conddb.cern.ch/cmsDbBrowser/payload_inspector/Prod
233 
234  This script is a part of the Payload Inspector service and is responsible for:
235  a) discovering PI objects that are available in a given cmssw release
236  b) deserializing payload data which is later used as plot coordinates
237  c) testing new PI objects which are under development
238 
239  To test new PI objects please do the following:
240  a) run ./getPayloadData.py --discover
241  to check if your newly created object is found by the script.
242  Please note that we strongly rely on naming conventions so if you don't
243  see your object listed you probably misnamed it in objectType() method.
244  Also all plot methods should start with "plot_" prefix.
245 
246  b) second step is to test if it returns data correctly:
247  run ./getPayloadData.py --plugin YourPIPluginName --plot YourObjectPlot --tag tagName --time_type Run --iovs '{"start_iov": "201", "end_iov": "801"}' --db Prod --test
248 
249  Here is an example for BasicPayload object:
250  run ./getPayloadData.py --plugin pluginBasicPayload_PayloadInspector --plot plot_BasicPayload_data0 --tag BasicPayload_v2 --time_type Run --iovs '{"start_iov": "201", "end_iov": "801"}' --db Prod --test
251 
252  c) if it works correctly please make a pull request and once it's accepted
253  go to cmsDbBrowser and wait for the next IB to test it.
254  '''
255 
256  parser = ArgumentParser(description=description, formatter_class=RawTextHelpFormatter)
257  parser.add_argument("-d", "--discover", help="discovers object types and plots \nfor a given cmssw release", action="store_true")
258  parser.add_argument("-i", "--iovs", help="deserializes given iovs data encoded in base64 and returns plot coordinates also encoded in base64")
259  parser.add_argument("-i2", "--iovstwo", help="deserializes given iovs data encoded in base64 and returns plot coordinates also encoded in base64")
260  parser.add_argument("-o", "--plugin", help="Payload Inspector plugin name needed for iovs deserialization")
261  parser.add_argument("-p", "--plot", help="plot name needed for iovs deserialization")
262  parser.add_argument("-t", "--tag", help="tag name needed for iovs deserialization")
263  parser.add_argument("-t2", "--tagtwo", help="tag name needed for iovs deserialization")
264  parser.add_argument("-tt", "--time_type", help="tag time type name needed for iovs deserialization")
265  parser.add_argument("-b", "--db", help="db (Prod or Prep) needed for iovs deserialization")
266  parser.add_argument("-test", "--test", help="add this flag if you want to test the deserialization function and want to see a readable output", action="store_true")
267  parser.add_argument("-v", "--verbose", help="verbose mode. Shows more information", action="store_true")
268  parser.add_argument("-ip","--image_plot", help="Switch telling the script that this plot type is of type Image", action="store_true")
269  parser.add_argument("-s", "--suppress-output", help="Supresses output from so that stdout and stderr can be kept pure for the ssh transmission", action="store_true")
270 
271  # shows help if no arguments are provided
272  if len(sys.argv) == 1:
273  parser.print_help()
274  sys.exit(1)
275 
276  args = parser.parse_args()
277 
278  # Return discover of plot if requested
279  if args.discover:
280  os.write( 1, discover() )
281 
282  # Return a plot if iovs are provided
283  #print '* getiovs: ',args.iovs
284  #print '* getiovstwo: ',args.iovstwo
285  if args.iovstwo:
286 
287  # Run plugin with arguments
288  #print 'We are here'
289  a=json.loads(args.iovs)
290  #print 'A',a
291  b=json.loads(args.iovstwo)
292  #print 'B',b
293  result = deserialize_twoiovs(args.db, args.plugin, args.plot, args.tag,args.tagtwo,a,b)
294  # If test -> output the result as formatted json
295  if args.test:
296  os.write( 1, json.dumps( json.loads( result ), indent=4 ))
297  #print 'Result:',result
298  if args.image_plot:
299  try:
300  filename = json.loads( result )['file']
301  #print 'File name',filename
302  except ValueError as e:
303  os.write( 2, 'Value error when getting image name: %s\n' % str( e ))
304  except KeyError as e:
305  os.write( 2, 'Key error when getting image name: %s\n' % str( e ))
306 
307  if not filename or not os.path.isfile( filename ):
308  os.write( 2, 'Error: Generated image file (%s) not found\n' % filename )
309 
310  try:
311  with open( filename, 'r' ) as f:
312  shutil.copyfileobj( f, sys.stdout )
313  except IOError as e:
314  os.write( 2, 'IO error when streaming image: %s' % str( e ))
315  finally:
316  os.remove( filename )
317 
318 
319  # Else -> output result json string with base 64 encoding
320  elif args.iovs:
321  result = deserialize_iovs(args.db, args.plugin, args.plot, args.tag, args.time_type, json.loads(args.iovs))
322 
323  # If test -> output the result as formatted json
324  if args.test:
325  os.write( 1, json.dumps( json.loads( result ), indent=4 ))
326 
327  # If image plot -> get image file from result, open it and output bytes
328  elif args.image_plot:
329 
330  filename = None
331 
332  try:
333  filename = json.loads( result )['file']
334  #print 'File name',filename
335  except ValueError, e:
336  os.write( 2, 'Value error when getting image name: %s\n' % str( e ))
337  except KeyError, e:
338  os.write( 2, 'Key error when getting image name: %s\n' % str( e ))
339 
340  if not filename or not os.path.isfile( filename ):
341  os.write( 2, 'Error: Generated image file (%s) not found\n' % filename )
342 
343  try:
344  with open( filename, 'r' ) as f:
345  shutil.copyfileobj( f, sys.stdout )
346  except IOError, e:
347  os.write( 2, 'IO error when streaming image: %s' % str( e ))
348  finally:
349  os.remove( filename )
350 
351 
352  # Else -> output result json string with base 64 encoding
353  else:
354  os.write( 1, result.encode( 'base64' ))
355 
def supress_output(f)
def output(description, param)
def replace(string, replacements)
S & print(S &os, JobReport::InputFile const &f)
Definition: JobReport.cc:66
double f[11][100]
def deserialize_twoiovs(db, plugin_name, plot_name, tag, tagtwo, iovs, iovstwo)
def deserialize_iovs(db, plugin_name, plot_name, tag, time_type, iovs)
dbl *** dir
Definition: mlp_gen.cc:35
#define str(s)