ATLAS Offline Software
rfio.py
Go to the documentation of this file.
1 # Copyright (C) 2002-2019 CERN for the benefit of the ATLAS collaboration
2 
3 import os,time
4 import stat as statconsts
5 
6 from future import standard_library
7 standard_library.install_aliases()
8 import subprocess
9 
10 __doc__ = """Module with utilities for rfio files"""
11 
12 class RFIOError(IOError):
13  def __init__(self,*vargs):
14  IOError.__init__(self,*vargs)
15 
16 def _remove_prefix(filename,prefix):
17  if filename.startswith(prefix): filename = filename[len(prefix):]
18  return filename
19 
20 
21 def rfstat(filename):
22  """Return tuple (status,output) of rfstat shell command. Output is a list of strings
23  (one entry per line). Raises RFIOError if rfstat command is not found."""
24  statcmd = 'rfstat'
25  from PyJobTransformsCore import envutil
26  if not envutil.find_executable(statcmd):
27  raise RFIOError( '%s not found in PATH' % statcmd )
28  cmd = '%s %s' % (statcmd,_remove_prefix(filename,'rfio:'))
29  status,output = subprocess.getstatusoutput( cmd )
30  status >>= 8
31 
32  return (status, output.split(os.linesep))
33 
34 
35 def rfdir(dirname):
36  """Return tuple (status,output) of rfdir shell command. Output in a list of strings (one entry per line).
37  The format is the same as the unix shell command \'ls -la\'
38  Raises RFIOError if rfdir command is not found"""
39  dircmd = 'rfdir'
40  from PyJobTransformsCore import envutil
41  if not envutil.find_executable(dircmd):
42  raise RFIOError( '%s not found in PATH' % dircmd )
43  cmd = '%s %s' % (dircmd,_remove_prefix(dirname,'rfio:'))
44  status,ls_la = subprocess.getstatusoutput( cmd )
45  status >>= 8
46 
47  return (status, ls_la.split(os.linesep))
48 
49 
50 def rfstat_dict(filename):
51  """Return dictionary with name:value pairs of the rfstat output. Returns None
52  if rfstat returns an error code (i.e. file does not exist)."""
53  status,output = rfstat(filename)
54  if status: return None
55  rfdict = { }
56  for line in output:
57  colon = line.index(':')
58  name = line[:colon].strip()
59  value = line[colon+1:].strip()
60  rfdict[name] = value
61 
62  return rfdict
63 
64 
65 def rfstat_item(filename,item):
66  """Return the contents of <item> in the rfstat output"""
67  status,output = rfstat(filename)
68  if status: return None
69  for line in output:
70  if line.startswith( item ):
71  colon = line.index(':')
72  return line[colon+1:].strip()
73 
74  # nothing found
75  return None
76 
77 
78 def listdir(dirname):
79  """Return the contents of directory <dirname> in a python list a-la os.listdir(),
80  i.e. only the filenames, and not including the current dir (.) and parent dir (..)"""
81  status,ls_la = rfdir(dirname)
82  if status: raise RFIOError('Directory %s not found' % dirname)
83  dir = [ ]
84  for d in ls_la:
85  dd = d.split()[-1]
86  if dd != os.curdir and dd != os.pardir:
87  dir.append( dd )
88 
89  return dir
90 
91 
92 def exists(filename):
93  status,output = rfstat(filename)
94  return status == 0
95 
96 
97 def getsize(filename):
98  """Return size of file <filename> in bytes"""
99  return int(rfstat_item(filename,'Size'))
100 
101 
102 def getmtime(filename):
103  return lstat(filename).st_mtime
104 
105 
107  def __init__(self):
108  self.st_mode = 0
109  self.st_ino = 0
110  self.st_dev = 0
111  self.st_nlink = 0
112  self.st_uid = 0
113  self.st_gid = 0
114  self.st_size = 0
115  self.st_atime = 0
116  self.st_mtime = 0
117  self.st_ctime = 0
118 
119  self.__items = [ i.upper() for i in self.__dict__ if i.startswith('st_') ]
120 
121 
122  def __getitem__(self,idx):
123  for i in self.__items:
124  if idx == getattr(statconsts,i):
125  return getattr(self,i.lower())
126  return None
127 
128 
129  def __setitem__(self,idx,val):
130  for i in self.__items:
131  if idx == getattr(statconsts,i):
132  setattr(self,i.lower(),val)
133 
134 
135  def __str__(self):
136  vals = []
137  for i in range(len(self.__items)):
138  vals.append( self[i] )
139  return str( tuple(vals) )
140 
141 
142 
143 def _stat_time(time_string):
144  t = time.mktime(time.strptime(time_string))
145  if os.stat_float_times():
146  return float(t)
147  else:
148  return int(t)
149 
150 
151 
152 def lstat(filename):
153  st = StatResult()
154  output = rfstat_dict(filename)
155  if output is None: raise RFIOError('file %s not found' % filename)
156  for name in output:
157  value = output[name]
158  if name == 'Device':
159  st.st_dev = eval('0x' + value)
160  elif name.startswith('Inode'):
161  st.st_ino = int(value)
162  elif name.find('blocks') != -1:
163  st.st_blocks = int(value)
164  elif name == 'Protection':
165  octal = value.split()[-1][1:-1]
166  st.st_mode = eval('0' + octal)
167  elif name == 'Hard Links':
168  st.st_nlink = int(value)
169  elif name == 'Uid':
170  st.st_uid = int(value.split()[0])
171  elif name == 'Gid':
172  st.st_gid = int(value.split()[0])
173  elif name.startswith('Size'):
174  st.st_size = int(value)
175  elif name == 'Last access':
176  st.st_atime = _stat_time(value)
177  elif name == 'Last modify':
178  st.st_mtime = _stat_time(value)
179  elif name == 'Last stat. mod.':
180  st.st_ctime = _stat_time(value)
181 
182  return st
183 
184 # never follow symbolic links, so stat == lstat
185 stat = lstat
186 
187 
188 def access(filename,mode):
189  if mode == os.F_OK: return exists(filename)
190 
191  st = stat(filename)
192  filemode = st.st_mode
193  uid = st.st_uid
194  gid = st.st_gid
195  if mode & os.R_OK:
196  rOK = ( filemode & statconsts.S_IROTH ) or \
197  ( filemode & statconsts.S_IRGRP and os.getgid() == gid ) or \
198  ( filemode & statconsts.S_IRUSR and os.getuid() == uid ) or \
199  ( filemode & statconsts.S_ISGID and os.getegid() == gid ) or \
200  ( filemode & statconsts.S_ISUID and os.geteuid() == uid )
201  else:
202  rOK = True
203 
204  if mode & os.W_OK:
205  wOK = ( filemode & statconsts.S_IWOTH ) or \
206  ( filemode & statconsts.S_IWGRP and os.getgid() == gid ) or \
207  ( filemode & statconsts.S_IWUSR and os.getuid() == uid ) or \
208  ( filemode & statconsts.S_ISGID and os.getegid() == gid ) or \
209  ( filemode & statconsts.S_ISUID and os.geteuid() == uid )
210  else:
211  wOK = True
212 
213  if mode & os.X_OK:
214  xOK = ( filemode & statconsts.S_IXOTH ) or \
215  ( filemode & statconsts.S_IXGRP and os.getgid() == gid ) or \
216  ( filemode & statconsts.S_IXUSR and os.getuid() == uid ) or \
217  ( filemode & statconsts.S_ISGID and os.getegid() == gid ) or \
218  ( filemode & statconsts.S_ISUID and os.geteuid() == uid )
219  else:
220  xOK = True
221 
222  return rOK and wOK and xOK
223 
224 
python.rfio.StatResult.__str__
def __str__(self)
Definition: rfio.py:135
python.rfio.getmtime
def getmtime(filename)
Definition: rfio.py:102
python.rfio.exists
def exists(filename)
Definition: rfio.py:92
CaloCellPos2Ntuple.int
int
Definition: CaloCellPos2Ntuple.py:24
python.rfio.StatResult
Definition: rfio.py:106
python.rfio.StatResult.__setitem__
def __setitem__(self, idx, val)
Definition: rfio.py:129
python.rfio.StatResult.__init__
def __init__(self)
Definition: rfio.py:107
python.rfio.StatResult.st_nlink
st_nlink
Definition: rfio.py:111
python.rfio._stat_time
def _stat_time(time_string)
Definition: rfio.py:143
python.rfio.rfstat
def rfstat(filename)
Definition: rfio.py:21
python.rfio.StatResult.st_atime
st_atime
Definition: rfio.py:115
python.rfio.rfstat_item
def rfstat_item(filename, item)
Definition: rfio.py:65
python.rfio.lstat
def lstat(filename)
Definition: rfio.py:152
python.rfio.rfdir
def rfdir(dirname)
Definition: rfio.py:35
python.rfio.listdir
def listdir(dirname)
Definition: rfio.py:78
python.rfio.StatResult.st_size
st_size
Definition: rfio.py:114
python.rfio.StatResult.st_ino
st_ino
Definition: rfio.py:109
plotBeamSpotVxVal.range
range
Definition: plotBeamSpotVxVal.py:195
python.rfio.getsize
def getsize(filename)
Definition: rfio.py:97
python.rfio.RFIOError.__init__
def __init__(self, *vargs)
Definition: rfio.py:13
python.rfio.stat
stat
Definition: rfio.py:185
python.rfio.StatResult.st_ctime
st_ctime
Definition: rfio.py:117
python.rfio.StatResult.st_gid
st_gid
Definition: rfio.py:113
python.rfio._remove_prefix
def _remove_prefix(filename, prefix)
Definition: rfio.py:16
python.rfio.StatResult.st_mtime
st_mtime
Definition: rfio.py:116
python.rfio.StatResult.st_mode
st_mode
Definition: rfio.py:108
python.rfio.rfstat_dict
def rfstat_dict(filename)
Definition: rfio.py:50
python.rfio.StatResult.st_dev
st_dev
Definition: rfio.py:110
python.rfio.access
def access(filename, mode)
Definition: rfio.py:188
python.rfio.StatResult.st_uid
st_uid
Definition: rfio.py:112
str
Definition: BTagTrackIpAccessor.cxx:11
python.rfio.StatResult.__getitem__
def __getitem__(self, idx)
Definition: rfio.py:122
python.rfio.StatResult.__items
__items
Definition: rfio.py:119
python.rfio.RFIOError
Definition: rfio.py:12
readCCLHist.float
float
Definition: readCCLHist.py:83