def daemonize(self): # převzato v rámci citační zákonné licence z: https://webdevdesigner.com/q/how-to-make-a-python-script-run-like-a-service-or-daemon-in-linux-60093/ try: pid = os.fork() if pid > 0: # if fork succeeded #exit first parent sys.exit(0) except OSError as e: sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror)) sys.exit(1) # decouple from parent environment os.chdir("/") os.setsid() # start a new session with no controlling terminals os.umask(0) # donner tous les droits en lecture/écriture au démon sur les fichiers qu'il crée. #0222 with these permissions will be created the socket and also the pidfile # second fork try: pid = os.fork() if pid > 0: # if fork succeeded # exit second parent sys.exit(0) except OSError as e: sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror)) sys.exit(1) # redirect standard file descriptors sys.stdout.flush() sys.stderr.flush() mode = 'a' if not stat.S_ISCHR(os.stat(self.stdout).st_mode) else 'w' si = open(self.stdin, 'r') so = open(self.stdout, mode) # or /dev/null for no standard output anywhere se = open(self.stderr, mode) os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) # write pid file atexit.register(self.delpid) print("GGH is running in daemon mode [pid -> {}]".format(os.getpid()))
def remove_temporary_paths(self): ''' Everything stored in self._temp_paths is examined and deleted if possible. The list elements are removed in LIFO order. Also, self._known_paths 'type' info is updated here. NOTE: Included additional stat checks to detect FIFOs as well as other special files. ''' for _ in self.get_temp_paths()[::-1]: # Check file type pathmode = os.stat(_).st_mode isdir = False if stat.S_ISDIR(pathmode) == 0 else True ischaracter = False if stat.S_ISCHR(pathmode) == 0 else True isblock = False if stat.S_ISBLK(pathmode) == 0 else True isfile = False if stat.S_ISREG(pathmode) == 0 else True isfifo = False if stat.S_ISFIFO(pathmode) == 0 else True islink = False if stat.S_ISLNK(pathmode) == 0 else True issock = False if stat.S_ISSOCK(pathmode) == 0 else True # Update 'type' value if _ in self.get_known_paths().keys(): if isfile: logger.debug("Set %s 'type' info to 'file'" % _) self.get_known_paths()[_]['type'] = 'file' elif isdir: logger.debug("Set %s 'type' info to 'directory'" % _) self.get_known_paths()[_]['type'] = 'directory' elif isfifo: logger.debug("Set %s 'type' info to 'fifo'" % _) self.get_known_paths()[_]['type'] = 'fifo' if os.path.isdir(_) and isdir: try: logger.info("Now deleting directory: %s" % _) os.rmdir(_) except OSError as e: logger.error("errno: %s" % e.errno) logger.error("strerror: %s" % e.strerror) logger.error("filename: %s" % e.filename) pass else: try: logger.info("Now deleting: %s" % _) os.unlink(_) except OSError as e: pass
def _process_tree(srcpath, destpath, actionfunc): file_stat = os.lstat(srcpath) mode = file_stat.st_mode if stat.S_ISDIR(mode): # Ensure directory exists in destination, then recurse. if not os.path.lexists(destpath): os.makedirs(destpath) dest_stat = os.stat(os.path.realpath(destpath)) if not stat.S_ISDIR(dest_stat.st_mode): raise IOError('Destination not a directory. source has %s' ' destination has %s' % (srcpath, destpath)) for entry in os.listdir(srcpath): _process_tree(os.path.join(srcpath, entry), os.path.join(destpath, entry), actionfunc) elif stat.S_ISLNK(mode): # Copy the symlink. if os.path.lexists(destpath): import re path = re.search('/.*$', re.search('tmp[^/]+/.*$', destpath).group(0)).group(0) app.config['new-overlaps'] += [path] os.remove(destpath) os.symlink(os.readlink(srcpath), destpath) elif stat.S_ISREG(mode): # Process the file. if os.path.lexists(destpath): os.remove(destpath) actionfunc(srcpath, destpath) elif stat.S_ISCHR(mode) or stat.S_ISBLK(mode): # Block or character device. Put contents of st_dev in a mknod. if os.path.lexists(destpath): os.remove(destpath) os.mknod(destpath, file_stat.st_mode, file_stat.st_rdev) os.chmod(destpath, file_stat.st_mode) else: # Unsupported type. raise IOError('Cannot extract %s into staging-area. Unsupported' ' type.' % srcpath)
def create_file(self, path, parent=None): file_obj = None #if stat.S_ISFIFO(os.stat(path).st_mode) or stat.S_ISCHR(os.stat(path).st_mod): if stat.S_ISFIFO(os.stat(path).st_mode) or stat.S_ISCHR( os.stat(path).st_mode): return None magic_str, mime_str = self.get_file_magic(path) metadata = get_metadata(path) for regex, file_class in self.CONTAINER_TYPES_MAP.items(): if file_class and re.search(regex, magic_str, flags=re.IGNORECASE): try: file_obj = file_class(path, magic_str=magic_str, mime_type=mime_str, metadata=metadata, parent=parent) break except IncompatibleFS: log.error( "Attempted to create filesystem from block device without success" ) pass if not file_obj: for regex, file_class in self.MIME_TYPES_MAP.items(): if file_class and re.search( regex, mime_str, flags=re.IGNORECASE): try: file_obj = file_class(path, magic_str=magic_str, mime_type=mime_str, metadata=metadata, parent=parent) break except Exception as e: log.exception(e) pass if not file_obj: file_obj = Data(path, magic_str) return file_obj
def _process(self, archive, cache, excludes, exclude_caches, skip_inodes, path, restrict_dev): if exclude_path(path, excludes): return try: st = os.lstat(path) except OSError as e: self.print_error('%s: %s', path, e) return if (st.st_ino, st.st_dev) in skip_inodes: return # Entering a new filesystem? if restrict_dev and st.st_dev != restrict_dev: return # Ignore unix sockets if stat.S_ISSOCK(st.st_mode): return self.print_verbose(remove_surrogates(path)) if stat.S_ISREG(st.st_mode): try: archive.process_file(path, st, cache) except IOError as e: self.print_error('%s: %s', path, e) elif stat.S_ISDIR(st.st_mode): if exclude_caches and is_cachedir(path): return archive.process_item(path, st) try: entries = os.listdir(path) except OSError as e: self.print_error('%s: %s', path, e) else: for filename in sorted(entries): self._process(archive, cache, excludes, exclude_caches, skip_inodes, os.path.join(path, filename), restrict_dev) elif stat.S_ISLNK(st.st_mode): archive.process_symlink(path, st) elif stat.S_ISFIFO(st.st_mode): archive.process_item(path, st) elif stat.S_ISCHR(st.st_mode) or stat.S_ISBLK(st.st_mode): archive.process_dev(path, st) else: self.print_error('Unknown file type: %s', path)
def _configure(self): if self.name not in shared.NODE.cd: # this thread will be stopped. don't reconfigure to avoid logging errors return self.get_hb_nodes() self.peer_config = {} if not hasattr(self, "meta_slot_buff"): self.meta_slot_buff = mmap.mmap(-1, 2 * mmap.PAGESIZE) if not hasattr(self, "slot_buff"): self.slot_buff = mmap.mmap(-1, self.SLOTSIZE) self.timeout = shared.NODE.oget(self.name, "timeout") try: new_dev = shared.NODE.oget(self.name, "dev") except ex.RequiredOptNotFound: raise ex.AbortAction("no %s.dev is not set in node.conf" % self.name) if not os.path.exists(new_dev): raise ex.AbortAction("%s does not exist" % new_dev) new_dev = os.path.realpath(new_dev) new_flags = os.O_RDWR statinfo = os.stat(new_dev) if Env.sysname == "Linux": if stat.S_ISBLK(statinfo.st_mode): self.log.info("using directio") new_flags |= os.O_DIRECT | os.O_SYNC | os.O_DSYNC # (Darwin, SunOS) pylint: disable=no-member else: raise ex.AbortAction("%s must be a block device" % new_dev) else: if not stat.S_ISCHR(statinfo.st_mode): raise ex.AbortAction("%s must be a char device" % new_dev) if new_dev != self.dev: self.dev = new_dev self.flags = new_flags self.peer_config = {} self.log.info("set dev=%s", self.dev) with self.hb_fo() as fo: self.load_peer_config(fo=fo)
def filetype(filename): st = os.stat(filename, follow_symlinks=False) mode = st.st_mode if stat.S_ISFIFO(mode): return "fifo" elif stat.S_ISCHR(mode): return "char" elif stat.S_ISDIR(mode): return "dir" elif stat.S_ISBLK(mode): return "block" elif stat.S_ISLNK(mode): return "link" elif stat.S_ISSOCK(mode): return "socket" elif stat.S_ISREG(mode): return "file" else: return "unknown"
def testSetStats(self): node = mis.manifest.nodes.Directory('/tmp', os.stat('/tmp')) #check that all stats, except inode are set for key in [ key for key in node.__slots__ if key.startswith("st_")]: if (key == 'st_ino'): continue if (getattr(node,key) == None): print key self.assertFalse(True) manifest = mis.manifest.serializer.fromPath('tmp/testdir') childdict = manifest.root.children_as_dict self.assertTrue(stat.S_ISDIR(childdict['testdir'].stats.st_mode)) self.assertTrue(stat.S_ISCHR(childdict['mixer-testdev'].stats.st_mode)) self.assertTrue(stat.S_ISREG(childdict['testdir'].children_as_dict['deeper_file'].stats.st_mode)) self.assertEquals(os.stat('tmp/testdir/mixer-testdev').st_rdev, childdict['mixer-testdev'].rdev) self.assertTrue(isinstance(manifest.root.children_as_dict['testfile_a'], WhiteoutNode))
def __translate_type(self, __mode): '''Translate the type of the file to a generic name''' if stat.S_ISREG(__mode): if self.__fileinfo[stat.ST_NLINK] > 1: return 'l' else: return 'f' elif stat.S_ISDIR(__mode): return 'd' elif stat.S_ISCHR(__mode): return 'c' elif stat.S_ISLNK(__mode): return 's' elif stat.S_BLK(__mode): return 'b' elif stat.S_ISSOCK(__mode): return 'k' elif stat.S_ISFIFO(__mode): return 'o'
def fpga_update(ifile, mtd_dev, target_offset, input_offset, erase_len, no_verify): if not mtd_dev: raise Exception("null mtd_dev") try: mode = os.stat(mtd_dev).st_mode except Exception as ex: print(ex) return 1 if not stat.S_ISCHR(mode): print("{} is not a device file.".format(mtd_dev)) return 1 update_flash(ifile, mtd_dev, target_offset, input_offset, erase_len, no_verify) return 0
def _get_type_of(path): mode = path.stat().st_mode if stat.S_ISDIR(mode): if path.is_mount(): return "mountpoint" else: return "directory" elif stat.S_ISLNK(mode): return "symlink" elif stat.S_ISSOCK(mode): return "socket" elif stat.S_ISFIFO(mode): return "fifo" elif stat.S_ISCHR(mode) or stat.S_ISBLK(mode): return "device" elif stat.S_ISREG(mode): return "file" else: return None
def filetypeToString(mode): if stat.S_ISDIR(mode): return "directory" elif stat.S_ISCHR(mode): return "character device" elif stat.S_ISBLK(mode): return "block device" elif stat.S_ISREG(mode): return "regular file" elif stat.S_ISFIFO(mode): return "FIFO (named pipe)" elif stat.S_ISLNK(mode): return "symbolic link" elif stat.S_ISDOOR(mode): return "door" elif stat.S_ISPORT(mode): return "event port" else: return "unknown"
def st_mode_to_str(st_mode): # type: (int, ) -> str if stat.S_ISDIR(st_mode): return "directory" elif stat.S_ISREG(st_mode): return "regular file" elif stat.S_ISCHR(st_mode): return "character special device file" elif stat.S_ISBLK(st_mode): return "block special device file" elif stat.S_ISFIFO(st_mode): return "named pipe" elif stat.S_ISLNK(st_mode): return "symbolic link" elif stat.S_ISSOCK(st_mode): return "socket" else: return "unknown"
def __init__(self, loop, pipe, protocol, waiter=None, extra=None): super(_UnixReadPipeTransport, self).__init__(extra) self._extra['pipe'] = pipe self._loop = loop self._pipe = pipe self._fileno = pipe.fileno() mode = os.fstat(self._fileno).st_mode if not (stat.S_ISFIFO(mode) or stat.S_ISSOCK(mode) or stat.S_ISCHR(mode)): raise ValueError("Pipe transport is for pipes/sockets only.") _set_nonblocking(self._fileno) self._protocol = protocol self._closing = False self._loop.add_reader(self._fileno, self._read_ready) self._loop.call_soon(self._protocol.connection_made, self) if waiter is not None: # wait until protocol.connection_made() has been called self._loop.call_soon(waiter._set_result_unless_cancelled, None)
def scan_directory(path: str, excluded_paths: List[str]) -> Tuple[List[str], List[str]]: """Return sub-directories' paths and regular-file's paths. Ignore all other file types. """ logging.debug(f"Scanning directory: {path}...") try: scan = os.scandir(path) except (PermissionError, FileNotFoundError): scan = [] # type: ignore[assignment] subdirs = [] filepaths = [] for dir_entry in scan: try: mode = os.lstat(dir_entry.path).st_mode if (stat.S_ISLNK(mode) or stat.S_ISSOCK(mode) or stat.S_ISFIFO(mode) or stat.S_ISBLK(mode) or stat.S_ISCHR(mode)): logging.info(f"Non-processable file: {dir_entry.path}") continue except PermissionError: logging.info(f"Permission denied: {dir_entry.path}") continue if is_excluded_path(dir_entry.path, excluded_paths): continue # append if it's a directory if dir_entry.is_dir(): subdirs.append(dir_entry.path) # print if it's a good file elif dir_entry.is_file(): if not dir_entry.path.strip(): logging.info( f"Blank file name in: {os.path.dirname(dir_entry.path)}") else: filepaths.append(dir_entry.path) logging.debug(f"Scan finished, directory: {path}") return subdirs, filepaths
def get_mode(self): mode_str = '' if stat.S_ISDIR(self.mode): mode_str += 'd' if stat.S_ISREG(self.mode): mode_str += 'f' elif stat.S_ISLNK(self.mode): mode_str += 'l' elif stat.S_ISBLK(self.mode): mode_str += 'b' elif stat.S_ISCHR(self.mode): mode_str += 'c' elif stat.S_ISFIFO(self.mode): mode_str += 'p' elif stat.S_ISSOCK(self.mode): mode_str += 's' else: mode_str += '-' # Deal with mode bits mode_str += 'r' if (self.mode & stat.S_IRUSR) else '-' mode_str += 'w' if (self.mode & stat.S_IWUSR) else '-' if (self.mode & stat.S_IXUSR): mode_str += 's' if (self.mode & stat.S_ISUID) else 'x' else: mode_str += 'S' if (self.mode & stat.S_ISUID) else '-' mode_str += 'r' if (self.mode & stat.S_IRGRP) else '-' mode_str += 'w' if (self.mode & stat.S_IWGRP) else '-' if (self.mode & stat.S_IXGRP): mode_str += 's' if (self.mode & stat.S_ISGID) else 'x' else: mode_str += 'S' if (self.mode & stat.S_ISGID) else '-' mode_str += 'r' if (self.mode & stat.S_IROTH) else '-' mode_str += 'w' if (self.mode & stat.S_IWOTH) else '-' if (self.mode & stat.S_IXOTH): mode_str += 't' if (self.mode & stat.S_ISVTX) else 'x' else: mode_str += 'T' if (self.mode & stat.S_ISVTX) else '-' return mode_str
def get_type(path, follow=1, name_pri=100): """Returns type of file indicated by path. path - pathname to check (need not exist) follow - when reading file, follow symbolic links name_pri - Priority to do name matches. 100=override magic""" if not _cache_uptodate: _cache_database() try: if follow: st = os.stat(path) else: st = os.lstat(path) except: t = get_type_by_name(path) return t or text try: if xattr.present(path): name = xattr.get(path, xattr.USER_MIME_TYPE) if name and '/' in name: media, subtype=name.split('/') return lookup(media, subtype) except: pass if stat.S_ISREG(st.st_mode): t = get_type_by_contents(path, min_pri=name_pri) if not t: t = get_type_by_name(path) if not t: t = get_type_by_contents(path, max_pri=name_pri) if t is None: if stat.S_IMODE(st.st_mode) & 0111: return app_exe else: return text return t elif stat.S_ISDIR(st.st_mode): return inode_dir elif stat.S_ISCHR(st.st_mode): return inode_char elif stat.S_ISBLK(st.st_mode): return inode_block elif stat.S_ISFIFO(st.st_mode): return inode_fifo elif stat.S_ISLNK(st.st_mode): return inode_symlink elif stat.S_ISSOCK(st.st_mode): return inode_socket return inode_door
def _match_file_type(clazz, filename, file_type): want_file = clazz._want_file_type(file_type, clazz.FILE) want_dir = clazz._want_file_type(file_type, clazz.DIR) want_link = clazz._want_file_type(file_type, clazz.LINK) want_device = clazz._want_file_type(file_type, clazz.DEVICE) try: st = os.lstat(filename) except OSError as ex: if ex.errno == errno.EBADF: # Some devices on macos result in bad access when trying to stat so ignore them return False else: raise is_file = stat.S_ISREG(st.st_mode) is_dir = stat.S_ISDIR(st.st_mode) is_device = stat.S_ISBLK(st.st_mode) or stat.S_ISCHR(st.st_mode) is_link = stat.S_ISLNK(st.st_mode) return (want_file and is_file) or (want_dir and is_dir) or ( want_link and is_link) or (want_device and is_device)
def stats(path, hash_type='md5', follow_symlink=False): ''' Return a dict containing the stats for a given file CLI Example:: salt '*' file.stats /etc/passwd ''' ret = {} if not os.path.exists(path): return ret if follow_symlink: pstat = os.stat(path) else: pstat = os.lstat(path) ret['inode'] = pstat.st_ino ret['uid'] = pstat.st_uid ret['gid'] = pstat.st_gid ret['group'] = gid_to_group(pstat.st_gid) ret['user'] = uid_to_user(pstat.st_uid) ret['atime'] = pstat.st_atime ret['mtime'] = pstat.st_mtime ret['ctime'] = pstat.st_ctime ret['size'] = pstat.st_size ret['mode'] = str(oct(stat.S_IMODE(pstat.st_mode))) ret['sum'] = get_sum(path, hash_type) ret['type'] = 'file' if stat.S_ISDIR(pstat.st_mode): ret['type'] = 'dir' if stat.S_ISCHR(pstat.st_mode): ret['type'] = 'char' if stat.S_ISBLK(pstat.st_mode): ret['type'] = 'block' if stat.S_ISREG(pstat.st_mode): ret['type'] = 'file' if stat.S_ISLNK(pstat.st_mode): ret['type'] = 'link' if stat.S_ISFIFO(pstat.st_mode): ret['type'] = 'pipe' if stat.S_ISSOCK(pstat.st_mode): ret['type'] = 'socket' ret['target'] = os.path.realpath(path) return ret
def open(device, baudrate=None): """ Open a serial port. @param device Device name. @param baudrate Initial baud rate to set. Defaults to port's default. @return Port instance, or None if device not found. """ port = None device_stat = None try: device_stat = os.stat(device) except OSError: pass if device_stat and stat.S_ISCHR(device_stat.st_mode): port = SerialPort(device, baudrate) return port
def ftype_string(mode): """ Format stat.st_mode field as file-type string (file, directory, symlink, etc). """ if stat.S_ISREG(mode): return 'file' if stat.S_ISDIR(mode): return 'directory' if stat.S_ISLNK(mode): return 'symlink' if stat.S_ISBLK(mode) or stat.S_ISCHR(mode): return 'device' if stat.S_ISFIFO(mode): return 'fifo' if stat.S_ISSOCK(mode): return 'socket' # bsd only whiteout is not supported return 'mystery-file-mode={:07o}' % mode
def _create_hole(full_path, stat_data, link_path, deferred_dir_times): # Should be in sync with _simplify_item(). ( st_mode, st_uid, st_gid, st_rdev, st_size, st_atime, st_mtime, ) = stat_data # TODO: Add st_flags. # TODO: Add xattrs. if stat.S_ISDIR(st_mode): os.mkdir(full_path, stat.S_IMODE(st_mode)) # Change atime/mtime later, after creating files inside directories. # Order should be reverse. deferred_dir_times.insert(0, (full_path, (st_atime, st_mtime))) elif stat.S_ISCHR(st_mode) or \ stat.S_ISBLK(st_mode) or \ stat.S_ISFIFO(st_mode): os.mknod(full_path, st_mode, st_rdev) os.utime(full_path, (st_atime, st_mtime)) elif stat.S_ISLNK(st_mode): os.symlink(link_path, full_path) elif stat.S_ISSOCK(st_mode): _mksock(full_path) os.chmod(full_path, stat.S_IMODE(st_mode)) os.utime(full_path, (st_atime, st_mtime)) elif stat.S_ISREG(st_mode): _touch(full_path, st_size) os.chmod(full_path, stat.S_IMODE(st_mode)) os.utime(full_path, (st_atime, st_mtime)) else: raise RuntimeError( 'Type of \"{}\" is not supported (st_mode == 0o{:o})'.format( full_path, st_mode)) os.lchown(full_path, st_uid, st_gid)
def __init__(self, host_device: str, container_device: Optional[str] = None) -> None: """ .. note:: ``host_device`` MUST exist on the host and the binding in the container will be made with the same stat information (with exceptions to the ``can_read``, ``can_write`` and ``can_mknod``) .. todo:: implement knobs to be able to restrict file modes on the binding """ # interesting read: # https://github.com/opencontainers/runtime-spec/blob/master/config-linux.md#devices if os.path.abspath(host_device) != host_device: raise ValueError( "host_device must be an absolute and normalized path") self.host_device = host_device if (container_device and os.path.abspath(container_device) != container_device): raise ValueError( "container_device must be an absolute and normalized path") # assume the same abspath as the host if omitted from args self.container_device = (container_device if container_device else self.host_device) debug("identifying properties of device {!r} to bind it in a " "container".format(self.host_device)) devstat = os.lstat(self.host_device) # lstat don't follow symlinks if stat.S_ISCHR(devstat.st_mode): self.device_type = "c" # char device elif stat.S_ISBLK(devstat.st_mode): self.device_type = "b" # block device else: raise ValueError( "host_device must be a path to a host device node") self.device_major = os.major(devstat.st_rdev) self.device_minor = os.minor(devstat.st_rdev) self.filemode = stat.S_IMODE(devstat.st_mode) self.uid = devstat.st_uid self.gid = devstat.st_gid
def add_device_node(self, path, destpath=None): """ Add block/char device to running container. """ if not self.running: return False if not destpath: destpath = path if not os.path.exists(path): return False # Lookup the source path_stat = os.stat(path) mode = stat.S_IMODE(path_stat.st_mode) # Allow the target if stat.S_ISBLK(path_stat.st_mode): self.set_cgroup_item("devices.allow", "b %s:%s rwm" % (int(path_stat.st_rdev / 256), int(path_stat.st_rdev % 256))) elif stat.S_ISCHR(path_stat.st_mode): self.set_cgroup_item("devices.allow", "c %s:%s rwm" % (int(path_stat.st_rdev / 256), int(path_stat.st_rdev % 256))) # Create the target rootfs = "/proc/%s/root/" % self.init_pid container_path = "%s/%s" % (rootfs, destpath) if os.path.exists(container_path): os.remove(container_path) os.mknod(container_path, path_stat.st_mode, path_stat.st_rdev) os.chmod(container_path, mode) os.chown(container_path, 0, 0) return True
def summary_str(meta): mode_val = xstat.mode_str(meta.mode) user_val = meta.user if not user_val: user_val = str(meta.uid) group_val = meta.group if not group_val: group_val = str(meta.gid) size_or_dev_val = '-' if stat.S_ISCHR(meta.mode) or stat.S_ISBLK(meta.mode): size_or_dev_val = '%d,%d' % (os.major(meta.rdev), os.minor(meta.rdev)) elif meta.size: size_or_dev_val = meta.size mtime_secs = xstat.fstime_floor_secs(meta.mtime) time_val = time.strftime('%Y-%m-%d %H:%M', time.localtime(mtime_secs)) path_val = meta.path or '' if stat.S_ISLNK(meta.mode): path_val += ' -> ' + meta.symlink_target return '%-10s %-11s %11s %16s %s' % (mode_val, user_val + "/" + group_val, size_or_dev_val, time_val, path_val)
def file_type(mode): """ Turn the stat mode into it's standard representational character """ if stat.S_ISREG(mode): return 'f' elif stat.S_ISDIR(mode): return 'd' elif stat.S_ISLNK(mode): return 'l' elif stat.S_ISSOCK(mode): return 's' elif stat.S_ISBLK(mode): return 'b' elif stat.S_ISCHR(mode): return 'c' elif stat.S_ISFIFO(mode): return 'F' else: return 'X'
def _get_seed_file_object(self): if not self.seed: raise AttributeError("seed device is not set") if self.smartos_type == 'lx-brand': if not stat.S_ISSOCK(os.stat(self.seed).st_mode): LOG.debug("Seed %s is not a socket", self.seed) return None sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.connect(self.seed) return sock.makefile('rwb') else: if not stat.S_ISCHR(os.stat(self.seed).st_mode): LOG.debug("Seed %s is not a character device") return None ser = serial.Serial(self.seed, timeout=self.seed_timeout) if not ser.isOpen(): raise SystemError("Unable to open %s" % self.seed) return ser return None
def is_special_file(path): """ This function checks to see if a special file. It checks if the file is a character special device, block special device, FIFO, or socket. """ mode = os.stat(path).st_mode # Character special device. if stat.S_ISCHR(mode): return True # Block special device if stat.S_ISBLK(mode): return True # FIFO. if stat.S_ISFIFO(mode): return True # Socket. if stat.S_ISSOCK(mode): return True return False
def get_type(pathname): """for the given path name return the type""" info = os.lstat(pathname) mode = info[stat.ST_MODE] if stat.S_ISLNK(mode): return TYPE_SYMBOLIC_LINK elif stat.S_ISDIR(mode): return TYPE_DIRECTORY elif stat.S_ISCHR(mode): return TYPE_SPECIAL_CHARACTER_DEVICE elif stat.S_ISBLK(mode): return TYPE_BLOK_DEVICE elif stat.S_ISREG(mode): return TYPE_FILE elif stat.S_ISFIFO(mode): return TYPE_FIFO elif stat.S_ISSOCK(mode): return TYPE_SOCKET else: return TYPE_UNKNOW
def size(self): """ Return size in bytes of device. Returns int """ statinfo = os.stat(self.path) if stat.S_ISBLK(statinfo.st_mode): blockdev_cmd = self.module.get_bin_path("blockdev", required=True) dummy, out, dummy = self.module.run_command( [blockdev_cmd, "--getsize64", self.path], check_rc=True) devsize_in_bytes = int(out) elif stat.S_ISCHR(statinfo.st_mode) and platform.system() == 'FreeBSD': diskinfo_cmd = self.module.get_bin_path("diskinfo", required=True) dummy, out, dummy = self.module.run_command( [diskinfo_cmd, self.path], check_rc=True) devsize_in_bytes = int(out.split()[2]) elif os.path.isfile(self.path): devsize_in_bytes = os.path.getsize(self.path) else: self.module.fail_json(changed=False, msg="Target device not supported: %s" % self) return devsize_in_bytes