CMS 3D CMS Logo

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
cmssw_das_client.py
Go to the documentation of this file.
1 import time
2 import os
3 from json import loads, dumps
4 from types import GeneratorType
5 import subprocess
6 
7 #Copied from das_client.py
8 
9 def convert_time(val):
10  "Convert given timestamp into human readable format"
11  if isinstance(val, int) or isinstance(val, float):
12  return time.strftime('%d/%b/%Y_%H:%M:%S_GMT', time.gmtime(val))
13  return val
14 
15 def size_format(uinput, ibase=0):
16  """
17  Format file size utility, it converts file size into KB, MB, GB, TB, PB units
18  """
19  if not ibase:
20  return uinput
21  try:
22  num = float(uinput)
23  except Exception as _exc:
24  return uinput
25  if ibase == 2.: # power of 2
26  base = 1024.
27  xlist = ['', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB']
28  else: # default base is 10
29  base = 1000.
30  xlist = ['', 'KB', 'MB', 'GB', 'TB', 'PB']
31  for xxx in xlist:
32  if num < base:
33  return "%3.1f%s" % (num, xxx)
34  num /= base
35 
36 def extract_value(row, key, base=10):
37  """Generator which extracts row[key] value"""
38  if isinstance(row, dict) and key in row:
39  if key == 'creation_time':
40  row = convert_time(row[key])
41  elif key == 'size':
42  row = size_format(row[key], base)
43  else:
44  row = row[key]
45  yield row
46  if isinstance(row, list) or isinstance(row, GeneratorType):
47  for item in row:
48  for vvv in extract_value(item, key, base):
49  yield vvv
50 
51 def get_value(data, filters, base=10):
52  """Filter data from a row for given list of filters"""
53  for ftr in filters:
54  if ftr.find('>') != -1 or ftr.find('<') != -1 or ftr.find('=') != -1:
55  continue
56  row = dict(data)
57  values = []
58  keys = ftr.split('.')
59  for key in keys:
60  val = [v for v in extract_value(row, key, base)]
61  if key == keys[-1]: # we collect all values at last key
62  values += [dumps(i) for i in val]
63  else:
64  row = val
65  if len(values) == 1:
66  yield values[0]
67  else:
68  yield values
69 
70 def get_data(query, limit=None, threshold=None, idx=None, host=None, cmd=None):
71  cmd_opts = "--format=json"
72  if threshold is not None: cmd_opts += " --threshold=%s" % threshold
73  if limit is not None: cmd_opts += " --limit=%s" % limit
74  if idx is not None: cmd_opts += " --idx=%s" % idx
75  if host is not None: cmd_opts += " --host=%s" % host
76  if not cmd:
77  cmd = "das_client"
78  for path in os.getenv('PATH').split(':'):
79  if os.path.isfile(os.path.join(path, 'dasgoclient')):
80  cmd = "dasgoclient"
81  break
82 
83  p = subprocess.Popen("%s %s --query '%s'" % (cmd, cmd_opts, query),shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
84  stdout, stderr = p.communicate()
85  if not p.returncode: return loads(stdout)
86  return {'status' : 'error', 'reason' : stdout}