def stat(self, path, followlinks=0, path_is_real=False): if not path_is_real: virtpath = self.split_virtual_path(path) if (virtpath.search_name != '' and virtpath.search_name not in [r[0] for r in self.search_request.get_searches()]): # raise OSError like os.stat does raise OSError('No such file or directory: "%s"' % path) if virtpath.search_relpath == '/' or virtpath.search_relpath == '': return posix.stat_result(( self.dir_perm, 0, # st_ino 0, # st_dev 0, # st_nlink 0, # st_uid 0, # st_gid 4096, # st_size 0, # st_atime 0, # st_mtime 0, # st_ctime )) real_path = self.real_path(virtpath) else: real_path = path if followlinks: s = os.stat(real_path) else: s = os.lstat(real_path) if stat.S_ISDIR(s.st_mode): mode = self.dir_perm elif stat.S_ISREG(s.st_mode): mode = self.file_perm return posix.stat_result((mode,) + s[1:])
def stat(self, path, followlinks=0, path_is_real=False): if not path_is_real: virtpath = self.split_virtual_path(path) if (virtpath.search_name != '' and virtpath.search_name not in [r[0] for r in self.search_request.get_searches()]): # raise OSError like os.stat does raise OSError('No such file or directory: "%s"' % path) if virtpath.search_relpath == '/' or virtpath.search_relpath == '': return posix.stat_result(( self.dir_perm, 0, # st_ino 0, # st_dev 0, # st_nlink 0, # st_uid 0, # st_gid 4096, # st_size 0, # st_atime 0, # st_mtime 0, # st_ctime )) real_path = self.real_path(virtpath) else: real_path = path if followlinks: s = os.stat(real_path) else: s = os.lstat(real_path) if stat.S_ISDIR(s.st_mode): mode = self.dir_perm elif stat.S_ISREG(s.st_mode): mode = self.file_perm return posix.stat_result((mode, ) + s[1:])
def getStat(self, file): try: _time = (file['LastModified'].replace(tzinfo=None) - datetime.datetime.utcfromtimestamp(0)).total_seconds() top_level_filename = file['Key'].replace( "%s/%s/" % (self.username, self.homeDirectory), "") #This an equivalent to 744 mode = stat.S_IRWXU | stat.S_IRGRP | stat.S_IROTH #Stupid hack to detect when a key is a directory instead if top_level_filename.endswith('/'): top_level_filename = top_level_filename[:-1] mode |= stat.S_IFDIR else: mode |= stat.S_IFREG print( posix.stat_result( (mode, 0, 0, 1, 0, 0, file['Size'], _time, _time, _time))) d = paramiko.SFTPAttributes.from_stat( posix.stat_result( (mode, 0, 0, 1, 0, 0, file['Size'], _time, _time, _time)), top_level_filename) print(d) return d except Exception as e: print(e) raise
def testFile(self): self.mox.StubOutWithMock(os, 'stat') os.stat('/home/ebroder/root.img').AndReturn(posix.stat_result([ 0100644, 0, 0, 0, 0, 0, 0, 0, 0, 0])) self.mox.ReplayAll() self.assertEqual(utils.diskIsBlockDevice('/home/ebroder/root.img'), False)
def testBlockDevice(self): self.mox.StubOutWithMock(os, 'stat') os.stat('/home/ebroder/root.img').AndReturn(posix.stat_result([ # st_mode is the first argument 060644, 0, 0, 0, 0, 0, 0, 0, 0, 0])) self.mox.ReplayAll() self.assertEqual(utils.diskIsBlockDevice('/home/ebroder/root.img'), True)
def test_constructor_with_opt(self): self.assertRaises(TypeError, posix.terminal_size, range(9)) self.assertRaises(TypeError, posix.terminal_size, range(17)) x = posix.stat_result(range(10)) self.assertEqual('os.stat_result(st_mode=0, st_ino=1, st_dev=2, st_nlink=3, st_uid=4, st_gid=5, st_size=6, st_atime=7, st_mtime=8, st_ctime=9)', repr(x)) x = posix.stat_result(range(16)) self.assertEqual('os.stat_result(st_mode=0, st_ino=1, st_dev=2, st_nlink=3, st_uid=4, st_gid=5, st_size=6, st_atime=7, st_mtime=8, st_ctime=9)', repr(x)) x = posix.stat_result(range(10), {'st_atime': 42, 'st_atime_ns': 43, 'abc': 44}) self.assertEqual(7, x[7]) self.assertEqual(42, x.st_atime) self.assertEqual(43, x.st_atime_ns)
def stat(self, path, followlinks=0, path_is_real=False): """ Method to access a path state. Parameters ---------- path: str (mandatory) a path from which we want to get the associated statistics. followlinks: int (optional, default 0) if True the system will follow the symbolic links with the 'os.stat' method, otherwise the 'os.lstat' method is used. path_is_real: bool (optional, default False) if True the path really exists on the file system, otherwise we have a virtual cubicweb path. Returns ------- out: posix.stat_result the same structure returned by a stat or lstat. """ if not path_is_real: virtpath = self.split_virtual_path(path) if (virtpath.search_name != '' and virtpath.search_name not in (self.all_cw_search_names + self.INSTANCE_NAMES)): # raise OSError like os.stat does raise OSError('No such file or directory: "%s"' % path) if virtpath.search_relpath == '/' or virtpath.search_relpath == '': return posix.stat_result(( self.dir_perm, 0, # st_ino 0, # st_dev 0, # st_nlink 0, # st_uid 0, # st_gid 4096, # st_size 0, # st_atime 0, # st_mtime 0, # st_ctime )) real_path = self.real_path(virtpath) else: real_path = path if followlinks: s = os.stat(real_path) else: s = os.lstat(real_path) if stat.S_ISDIR(s.st_mode): mode = self.dir_perm elif stat.S_ISREG(s.st_mode): mode = self.file_perm return posix.stat_result((mode,) + s[1:])
def test_constructor_err(self): with self.assertRaisesRegex(TypeError, r'os.terminal_size\(\) takes a dict as second arg, if any'): posix.terminal_size((), "") self.assertRaises(TypeError, posix.terminal_size) with self.assertRaisesRegex(TypeError, r'constructor requires a sequence'): posix.terminal_size(42) with self.assertRaisesRegex(TypeError, r'os.terminal_size\(\) takes a 2-sequence \(0-sequence given\)'): posix.terminal_size(()) with self.assertRaisesRegex(TypeError, r'os.stat_result\(\) takes an at least 10-sequence \(1-sequence given\)'): posix.stat_result((1,)) with self.assertRaisesRegex(TypeError, r'os.stat_result\(\) takes an at most \d+-sequence \(30-sequence given\)'): posix.stat_result((1,) * 30) with self.assertRaisesRegex(TypeError, r'cannot create \'sys.flags\' instances'): type(sys.flags)()
def stat(self): if self.path == "": return posix.stat_result([stat.S_IFDIR + 0777, 0, 0, 0, 0, 0, 0, 0, 0, 0]) for data in commands.ls_files(repo=self.repo, index=self.index, path=self.path, children=False): if data["path"] == self.path: mode = int(data["mode"], 8) size = commands.get_object_size(repo=self.repo, object=data["object"]) return posix.stat_result([mode, 0, 0, 0, 0, 0, size, 0, 0, 0]) else: # if current path has children, it must be a dir assert data["path"].startswith(self.path + "/") return posix.stat_result([stat.S_IFDIR + 0777, 0, 0, 0, 0, 0, 0, 0, 0, 0]) # not found raise OSError(errno.ENOENT, os.strerror(errno.ENOENT))
def stat_file_entity(self, binary_len=0): """ Return the file state. Parameters ---------- binary_len: int (mandatory) the size of the file. Returns ------- out: posix.stat_result the same structure returned by a stat or lstat. """ return posix.stat_result(( self.file_perm, 0, # st_ino 0, # st_dev 0, # st_nlink 0, # st_uid 0, # st_gid binary_len, # st_size 0, # st_atime 0, # st_mtime 0, # st_ctime ))
def fake_stat(arg): if arg in test_filepaths: faked = list(orig_os_stat(arg)) faked[stat.ST_MTIME] = faked[stat.ST_MTIME] + 10 return stat_result(faked) else: return orig_os_stat(arg)
def test_get_device_number(self, lstat): lstat.return_value = posix.stat_result([ 16877, 16, 51729L, 3, 0, 0, 217, 0, 1458086872, 1458086872 ]) major, minor = replace_osd.get_device_number(1) assert major == 202 assert minor == 17
def fake_lstat(path): st_ino = 0 st_dev = 0 if path == ABSTFN: st_dev = 1 st_ino = 1 return posix.stat_result((0, st_ino, st_dev, 0, 0, 0, 0, 0, 0, 0))
def getattr(self, path): for backup in self.backups: fpath = backup + path if os.path.exists(fpath): f_stat = os.lstat(fpath) mode = f_stat.st_mode if S_ISDIR(mode): return f_stat else: # it is a file, show as dir f_stat = list(f_stat) f_stat[0] = mode & 0b111111111111 | S_IFDIR f_stat = stat_result(f_stat) assert S_ISDIR(f_stat.st_mode) parent = os.lstat(os.path.dirname(fpath)) # print 'done getattr - fake dir' # print 'fstat: ', f_stat # print 'parent: ', parent return parent # XXX workaround return f_stat # either the path does not exist or it actually is a file real_path = self._get_real_path(path) # print 'done getattr ', real_path if real_path: return os.lstat(real_path)
def fake_stat(arg): if arg == "foo": faked = list(orig_os_stat('/tmp')) faked[stat.ST_SIZE] = len('some stuff') return stat_result(faked) else: return orig_os_stat(arg)
def make_stat(mode=33200, uid=0, gid=0): """Return a mocked-up stat. The default is: mode = 0660 owner = root group = root Cheat sheet equivalents: 0600 = 33152 0640 = 33184 0644 = 33188 0660 = 33200 0666 = 33206 """ # (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) return posix.stat_result(( mode, 1, 42, 1, uid, gid, 0, 1, 1, 1, ))
def fake_stat(arg): if arg == '/some/file': # fake success return stat_result((16877, 2, 2049L, 23, 0, 0, 4096, 1381787843, 1381635971, 1381635971)) else: return orig_os_stat(arg)
def _os_stat(path): if path == working_dir: from posix import stat_result stat_info = list(real_stat(path)) stat_info[stat.ST_MODE] |= stat.S_IWOTH return stat_result(stat_info) else: return real_stat(path)
def stat(self): try: return os.stat(self.path) except IOError as e: with LogLimit(log, 'stat(%s): %s', self.path, limit=LOG_RLIMIT) as ll: ll.debug(self.path, e) self._reset() return posix.stat_result((0, ) * 10)
def fake_lstat(path): st_ino = 0 st_dev = 0 if path.startswith(ABSTFN) and path != ABSTFN: raise OSError('Fake [Errno 13] Permission denied') if path == ABSTFN: st_dev = 1 st_ino = 1 return posix.stat_result((0, st_ino, st_dev, 0, 0, 0, 0, 0, 0, 0))
def getattr(self, path): print 'getattr %s' % path stats = _get_cache(_ATTR, path) if stats is None: stats = self._request(self._server.remote_getattr, path) _set_cache(_ATTR, path, stats) if stats is -1: return -errno.ENOENT return posix.stat_result(stats)
def make_stat(mode=33200, uid=0, gid=0): """Return a mocked-up stat. The default is: mode = 0660 owner = root group = root """ return posix.stat_result((mode, 1, 42, 1, uid, gid, 0, 1, 1, 1,))
def getattr(self, path): print '****************************************** getattr %s' % path stat = stub.getattr(sankalpa_fs_pb2.Path(path=path), _TIMEOUT_SECONDS) if stat.status != 0: print '****************************************** getattr status != 0 %s' % stat.status raise OSError(stat.status,"OSError", path) print '****************************************** server_stat.st_size %s' % stat.st_size return posix.stat_result((stat.st_mode, stat.st_ino, stat.st_dev, stat.st_nlink, stat.st_uid, stat.st_gid, stat.st_size, stat.st_atime, stat.st_mtime, stat.st_ctime))
def test_reduce(self): x = posix.stat_result(range(10), {'st_atime': 42, 'st_atime_ns': 43, 'abc': 44}) r = x.__reduce__() self.assertEqual(posix.stat_result, r[0]) self.assertEqual(tuple(range(10)), r[1][0]) self.assertEqual(42, r[1][1]['st_atime']) self.assertEqual(None, r[1][1]['st_mtime_ns']) self.assertFalse('abc' in r[1][1]) x = posix.terminal_size((42, 3.14)) self.assertEqual((posix.terminal_size, ((42, 3.14), {})), x.__reduce__())
def stat(self): if not self._stat: e = OSError() e.errno = errno.ENOENT raise e if self._file: self._stat[6] = self._file.len ## bloat ... turning a list to a sequence to a stat_result object ;-) ## Well, StringIO implementation is not quite optimal anyway ;-) return posix.stat_result(list(self._stat))
def dispatch(me): stat_res = me._dispatch() #if os.path.split( me.q.path_in_aspect)[0] and isinstance( stat_res, stat_result): if Hardlink.getattr4symlink and isinstance(stat_res, stat_result): all = list(stat_res) log('original:', all) all[0] = all[0] | S_IFLNK log('new:', all) stat_res = stat_result(all) Hardlink.getattr4symlink = False return stat_res
def fake_lstat(path): st_ino = 0 st_dev = 0 if path.startswith(ABSTFN) and path != ABSTFN: # ismount tries to read something inside the ABSTFN directory; # simulate this being forbidden (no read permission). raise OSError("Fake [Errno 13] Permission denied") if path == ABSTFN: st_dev = 1 st_ino = 1 return posix.stat_result((0, st_ino, st_dev, 0, 0, 0, 0, 0, 0, 0))
def dispatch(me): stat_res = me._dispatch() # if os.path.split( me.q.path_in_aspect)[0] and isinstance( stat_res, stat_result): if Hardlink.getattr4symlink and isinstance(stat_res, stat_result): all = list(stat_res) log("original:", all) all[0] = all[0] | S_IFLNK log("new:", all) stat_res = stat_result(all) Hardlink.getattr4symlink = False return stat_res
def myLstat(path): s = origLstat(path) if path == fobj.name: # Convert the stat info to a tuple s = tuple(s) # Replace st_uid and st_gid s = s[:4] + (uid, gid) + s[6:] # Convert to stat_result s = posix.stat_result(s) self.assertEqual(s.st_uid, uid) self.assertEqual(s.st_gid, gid) return s
def stat_file_entity(self, binary_len=0): return posix.stat_result(( self.file_perm, 0, # st_ino 0, # st_dev 0, # st_nlink 0, # st_uid 0, # st_gid binary_len, # st_size 0, # st_atime 0, # st_mtime 0, # st_ctime ))
def fgetattr(self, file_descriptor, path): logging.debug('FGETATTR') try: op_result = os.fstat(file_descriptor) file_size = self.file_table[path + 'size'] stats_list = list(op_result) stats_list[stat.ST_SIZE] = file_size op_result = posix.stat_result(stats_list) except: op_result = -errno.EACCES return op_result
def fgetattr( self, file_descriptor, path ): logging.debug( 'FGETATTR' ) try: op_result = os.fstat( file_descriptor ) file_size = self.file_table[ path + 'size' ] stats_list = list( op_result ) stats_list[ stat.ST_SIZE ] = file_size op_result = posix.stat_result( stats_list ) except: op_result = -errno.EACCES return op_result
def getattr( self, path ): logging.debug( 'GETATTR' ) try: op_result = os.lstat( self.root + path[1:] ) if path in self.file_table.keys(): file_size = self.file_table[ path + 'size' ] stats_list = list( op_result ) stats_list[ stat.ST_SIZE ] = file_size op_result = posix.stat_result( stats_list ) except: op_result = -errno.ENOENT return op_result
def getattr(self, path): logging.debug('GETATTR') try: op_result = os.lstat(self.root + path[1:]) if path in self.file_table.keys(): file_size = self.file_table[path + 'size'] stats_list = list(op_result) stats_list[stat.ST_SIZE] = file_size op_result = posix.stat_result(stats_list) except: op_result = -errno.ENOENT return op_result
def stat(self, path): """Return stat result.""" local_path = self.resolve(path) cmd = 'stat --printf="%f %i %d %h %u %g %s %X %Y %W" {path}' \ .format(path=local_path) result = self.xal_session.sh.run(cmd) if not result.succeeded: if not self.exists(path): raise OSError(path) raise Exception() result = result.stdout.split(" ") result[0] = int(result[0], base=16) result = map(int, result) return posix.stat_result(result)
def stat(self, path): """ Returns ``os.stat(path)`` if `path` is legal. path: string Path to file to interrogate. """ timeout = 5 * 60 info = self._conn.invoke('stat', (path,), timeout=timeout) if sys.platform == 'win32': # pragma no cover import nt return nt.stat_result(info) else: import posix return posix.stat_result(info)
def test_simple(self): st = posix.stat_result((16877, 131078, 64769L, 154, 1000, 1000, 12288, 1323629595, 1324180496, 1324180496)) entry = index_entry_from_stat(st, "22" * 20, 0) self.assertEquals(entry, ( 1324180496, 1324180496, 64769L, 131078, 16877, 1000, 1000, 12288, '2222222222222222222222222222222222222222', 0))
def fake_stat(file: str): """ Create a real stat_result using an actual file, but change the st_mtime to a known value before returning it. Args: file: filename (not used) Returns: mocked stat_results """ s = os.stat(".") t = int(datetime.datetime(2021, 1, 29, 0, 0, 0).timestamp()) f = list(s) f[ST_MTIME] = t return stat_result(f)
def set_stat_info(self, value): """Sets the file stat information. Takes multiple parameter types: @param {tuple|list|stat_result|unicode|str} value """ if value is None: value = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0) if isinstance(value, tuple) or isinstance(value, list): value = os_platform.stat_result(tuple(value)) self._dict['statInfo'] = value self._dict['description'] = \ b64encode(compress(pickle.dumps(value))) return if isinstance(value, os_platform.stat_result): try: self._dict['description'] = \ b64encode(compress(pickle.dumps(value))) self._dict['statInfo'] = value except pickle.PicklingError: pass return if isinstance(value, unicode): value = unicode(value).encode("utf8") if isinstance(value, str): # First decode using new base64 compressed method. try: self._dict['statInfo'] = \ pickle.loads(decompress(b64decode(value))) self._dict['description'] = value return except Exception, ex: debug("Base 64 decode failed: %s" % repr(ex)) # That failed, try to decode using old hex encoding. try: dvalue = str(value).decode("hex") self._dict['statInfo'] = pickle.loads(dvalue) self._dict['description'] = value return except Exception, ex: debug("Hex decode failed: %s" % repr(ex))
def _setStatInfo(self, value): if value is None: value = (0,0,0,0,0,0,0,0,0,0) if isinstance(value, tuple) or isinstance(value, list): value = posix.stat_result(tuple(value)) self._dict['statInfo'] = value self._dict['description'] = \ b64encode(compress(pickle.dumps(value))) return if isinstance(value, posix.stat_result): try: self._dict['description'] = \ b64encode(compress(pickle.dumps(value))) self._dict['statInfo'] = value except pickle.PicklingError: pass return if isinstance(value, unicode): value = value.encode("utf8") if isinstance(value, str): # First decode using new base64 compressed method. try: self._dict['statInfo'] = \ pickle.loads(decompress(b64decode(value))) self._dict['description'] = value return except Exception, e: debug("Base 64 decode failed: %s" % repr(e)) pass # That failed, try to decode using old hex encoding. try: self._dict['statInfo'] = pickle.loads(value.decode("hex")) self._dict['description'] = value return except Exception, e: debug("Hex decode failed: %s" % repr(e)) pass
def _setStatInfo(self, value): if value is None: value = (0, 0, 0, 0, 0, 0, 0, 0, 0, 0) if isinstance(value, tuple) or isinstance(value, list): value = posix.stat_result(tuple(value)) self._dict['statInfo'] = value self._dict['description'] = \ b64encode(compress(pickle.dumps(value))) return if isinstance(value, posix.stat_result): try: self._dict['description'] = \ b64encode(compress(pickle.dumps(value))) self._dict['statInfo'] = value except pickle.PicklingError: pass return if isinstance(value, unicode): value = value.encode("utf8") if isinstance(value, str): # First decode using new base64 compressed method. try: self._dict['statInfo'] = \ pickle.loads(decompress(b64decode(value))) self._dict['description'] = value return except Exception, e: debug("Base 64 decode failed: %s" % repr(e)) pass # That failed, try to decode using old hex encoding. try: self._dict['statInfo'] = pickle.loads(value.decode("hex")) self._dict['description'] = value return except Exception, e: debug("Hex decode failed: %s" % repr(e)) pass
def _setStatInfo(self, value): if value is None: value = (0,0,0,0,0,0,0,0,0,0) if isinstance(value, tuple) or isinstance(value, list): value = posix.stat_result(tuple(value)) self._dict['statInfo'] = value self._dict['description'] = pickle.dumps( value ).encode("hex") return if isinstance(value, posix.stat_result): try: self._dict['description'] = pickle.dumps( value ).encode("hex") self._dict['statInfo'] = value except pickle.PicklingError: pass return if isinstance(value, unicode): value = str(value) if isinstance(value, str): try: self._dict['statInfo'] = pickle.loads( value.decode("hex") ) self._dict['description'] = value except pickle.UnpicklingError: pass except EOFError: pass return raise EInvalidStatInfoType(type(value))
def make_stat(mode=33200, uid=0, gid=0): """Return a mocked-up stat. The default is: mode = 0660 owner = root group = root """ # (mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime) return posix.stat_result(( mode, 1, 42, 1, uid, gid, 0, 1, 1, 1, ))
def PyStructSequence_New(typ): return stat_result([None] * stat_result.n_sequence_fields * 2)
def fake_lstat(*args, **kwargs): #posix.lstat_result(st_mode=1, st_ino=2, st_dev=3, st_nlink=4, # st_uid=5, st_gid=6, st_size=7, st_atime=8, # st_mtime=9, st_ctime=10) return stat_result((1, 2, 3, 4, 5, 6, 7, 8, 9, 10))
def fake_lstat(self, *args, **kwargs): self.lstat_calls.append((args, kwargs)) return stat_result(self.lstat_output_tuple)
def fake_stat_illegal(path): # Simulate stat to return the mode of a block device # make sure that st_mode (the first in the sequence( # matches the mode of a block device return posix.stat_result((17407, 5753, 5L, 1, 0, 6, 0, 1375881199, 1375881197, 1375881197))
def _stat_request_hadler(chunk): return func(posix.stat_result(msgpack.unpackb(chunk)))
def PyStructSequence_New(typ): from posix import stat_result return stat_result([None] * stat_result.n_sequence_fields * 2)
def fake_stat_illegal(path): # Simulate stat to return the mode of a block device # make sure that st_mode (the first in the sequence( # matches the mode of a block device return posix.stat_result( (17407, 5753, 5, 1, 0, 6, 0, 1375881199, 1375881197, 1375881197))