CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-fuse-python

Python bindings for FUSE (Filesystem in USErspace) enabling custom userspace filesystems

Pending
Overview
Eval results
Files

data-structures.mddocs/

Data Structures and Types

FUSE data structures for representing file attributes, directory entries, filesystem statistics, and other metadata used in filesystem operations.

Capabilities

Base Structure Class

All FUSE data structures inherit from a common base class that provides initialization and representation functionality.

class FuseStruct:
    """
    Base class for FUSE data structures.
    
    Provides keyword argument initialization and string representation.
    """
    
    def __init__(self, **kwargs):
        """
        Initialize structure with keyword arguments.
        
        Args:
            **kwargs: Attribute values to set
        """
    
    def __repr__(self):
        """Return string representation of structure."""

Usage Example:

# Initialize with keyword arguments
st = fuse.Stat(st_mode=0o644, st_size=1024)

# Access attributes directly
st.st_nlink = 1
st.st_uid = 1000

File Attributes

Structure representing file and directory attributes, similar to the result of stat() system call.

class Stat(FuseStruct):
    """
    File/directory attributes structure.
    
    Contains all standard POSIX file attributes.
    """
    
    st_mode: int     # File type and permissions (default: None)
    st_ino: int      # Inode number (default: 0)
    st_dev: int      # Device ID (default: 0)
    st_nlink: int    # Number of hard links (default: 0)
    st_uid: int      # User ID of owner (default: 0)
    st_gid: int      # Group ID of owner (default: 0)
    st_size: int     # Size in bytes (default: 0)
    st_atime: int    # Last access time (default: 0)
    st_mtime: int    # Last modification time (default: 0)
    st_ctime: int    # Last status change time (default: 0)

Usage Example:

import stat
import time

def getattr(self, path):
    st = fuse.Stat()
    
    if path == '/':
        # Directory attributes
        st.st_mode = stat.S_IFDIR | 0o755
        st.st_nlink = 2
        st.st_size = 4096
    else:
        # File attributes
        st.st_mode = stat.S_IFREG | 0o644
        st.st_nlink = 1
        st.st_size = len(self.get_file_content(path))
    
    # Common attributes
    current_time = int(time.time())
    st.st_atime = current_time
    st.st_mtime = current_time  
    st.st_ctime = current_time
    st.st_uid = os.getuid()
    st.st_gid = os.getgid()
    
    return st

Filesystem Statistics

Structure for filesystem-wide statistics, similar to the result of statvfs() system call.

class StatVfs(FuseStruct):
    """
    Filesystem statistics structure.
    
    Contains information about filesystem capacity and usage.
    """
    
    f_bsize: int     # Filesystem block size
    f_frsize: int    # Fragment size
    f_blocks: int    # Total number of blocks
    f_bfree: int     # Number of free blocks
    f_bavail: int    # Number of available blocks for unprivileged users
    f_files: int     # Total number of file nodes (inodes)
    f_ffree: int     # Number of free file nodes
    f_favail: int    # Number of available file nodes for unprivileged users
    f_flag: int      # Filesystem flags
    f_namemax: int   # Maximum filename length

Usage Example:

def statfs(self, path):
    stv = fuse.StatVfs()
    
    # Block information
    stv.f_bsize = 4096        # 4KB blocks
    stv.f_frsize = 4096       # Fragment size same as block size
    stv.f_blocks = 1000000    # 1M total blocks (~4GB)
    stv.f_bfree = 500000      # 500K free blocks
    stv.f_bavail = 450000     # 450K available (some reserved)
    
    # Inode information
    stv.f_files = 100000      # 100K total inodes
    stv.f_ffree = 80000       # 80K free inodes
    stv.f_favail = 80000      # Same as free for unprivileged
    
    # Filesystem properties
    stv.f_flag = 0            # No special flags
    stv.f_namemax = 255       # Maximum 255 character filenames
    
    return stv

Directory Entries

Structure representing individual entries in directory listings.

class Direntry(FuseStruct):
    """
    Directory entry structure.
    
    Represents a single item in a directory listing.
    """
    
    def __init__(self, name, **kwargs):
        """
        Initialize directory entry.
        
        Args:
            name (str): Entry name (required)
            **kwargs: Additional attributes (type, ino, offset)
        """
    
    name: str        # Entry name (required)
    type: int        # File type (optional, from stat module, default: None)
    ino: int         # Inode number (optional, default: None)  
    offset: int      # Offset for next entry (optional, default: None)

Usage Example:

def readdir(self, path, offset):
    # Standard entries
    yield fuse.Direntry('.')
    yield fuse.Direntry('..')
    
    # File entries with type information
    for filename, content in self.files.items():
        if filename.startswith(path.rstrip('/') + '/'):
            basename = filename[len(path.rstrip('/') + '/'):]
            if '/' not in basename:  # Direct child only
                yield fuse.Direntry(
                    name=basename,
                    type=stat.S_IFREG,
                    ino=hash(filename) % 2**32
                )
    
    # Directory entries
    for dirname in self.dirs:
        if dirname.startswith(path.rstrip('/') + '/'):
            basename = dirname[len(path.rstrip('/') + '/'):]
            if '/' not in basename:  # Direct child only
                yield fuse.Direntry(
                    name=basename,
                    type=stat.S_IFDIR,
                    ino=hash(dirname) % 2**32
                )

File Locking

Structure for file locking operations, similar to struct flock.

class Flock(FuseStruct):
    """
    File locking structure.
    
    Used for advisory file locking operations.
    """
    
    l_type: int      # Lock type (F_RDLCK, F_WRLCK, F_UNLCK)
    l_start: int     # Starting offset for lock
    l_len: int       # Number of bytes to lock (0 = to EOF)
    l_pid: int       # Process ID of lock owner

Usage Example:

def lock(self, path, fip, cmd, lock):
    """Handle file locking operations."""
    
    if cmd == fcntl.F_GETLK:
        # Check if lock would block
        if self.would_block_lock(path, lock):
            # Return conflicting lock info
            conflicting_lock = fuse.Flock()
            conflicting_lock.l_type = fcntl.F_WRLCK
            conflicting_lock.l_start = 0
            conflicting_lock.l_len = 0
            conflicting_lock.l_pid = 1234
            return conflicting_lock
        else:
            # No conflict
            lock.l_type = fcntl.F_UNLCK
            return 0
    
    elif cmd == fcntl.F_SETLK:
        # Set lock (non-blocking)
        return self.set_lock(path, lock, blocking=False)
    
    elif cmd == fcntl.F_SETLKW:
        # Set lock (blocking)
        return self.set_lock(path, lock, blocking=True)

Time Specification

High-precision time structure for nanosecond-accurate timestamps.

class Timespec(FuseStruct):
    """
    Time specification with nanosecond precision.
    
    Used for high-precision timestamp operations.
    """
    
    tv_sec: int      # Seconds since epoch
    tv_nsec: int     # Nanoseconds (0-999999999)

Usage Example:

def utimens(self, path, ts_acc, ts_mod):
    """Set file timestamps with nanosecond precision."""
    
    if path not in self.files:
        return -errno.ENOENT
    
    # Convert Timespec to float seconds
    atime = ts_acc.tv_sec + ts_acc.tv_nsec / 1e9
    mtime = ts_mod.tv_sec + ts_mod.tv_nsec / 1e9
    
    # Store timestamps (implementation dependent)
    self.file_times[path] = {
        'atime': atime,
        'mtime': mtime,
        'ctime': time.time()  # Change time is now
    }
    
    return 0

File Information

Structure containing file operation context and flags.

class FuseFileInfo(FuseStruct):
    """
    File information structure.
    
    Provides context for file operations.
    """
    
    keep: bool          # Whether to keep cached data
    direct_io: bool     # Whether to use direct I/O

Usage Example:

def open(self, path, flags):
    """Open file with specific flags."""
    
    if path not in self.files:
        return -errno.ENOENT
    
    # Check access permissions
    if flags & os.O_WRONLY and self.is_readonly(path):
        return -errno.EACCES
    
    # Create file info for this open
    fip = fuse.FuseFileInfo()
    fip.keep = True          # Enable caching
    fip.direct_io = False    # Use buffered I/O
    
    return 0

Type Constants

Common constants used with data structures, primarily from the stat module:

File Types

  • stat.S_IFREG: Regular file
  • stat.S_IFDIR: Directory
  • stat.S_IFLNK: Symbolic link
  • stat.S_IFCHR: Character device
  • stat.S_IFBLK: Block device
  • stat.S_IFIFO: Named pipe (FIFO)
  • stat.S_IFSOCK: Socket

Permission Bits

  • stat.S_IRUSR, stat.S_IWUSR, stat.S_IXUSR: User read/write/execute
  • stat.S_IRGRP, stat.S_IWGRP, stat.S_IXGRP: Group read/write/execute
  • stat.S_IROTH, stat.S_IWOTH, stat.S_IXOTH: Other read/write/execute

Access Modes

  • os.R_OK: Test for read permission
  • os.W_OK: Test for write permission
  • os.X_OK: Test for execute permission
  • os.F_OK: Test for file existence

Best Practices

  • Always initialize structures with appropriate default values
  • Use keyword arguments for clarity when creating structures
  • Set all required fields for each structure type
  • Use appropriate constants from stat and os modules
  • Handle optional fields gracefully (check for None values)
  • Consider precision requirements when working with timestamps

Install with Tessl CLI

npx tessl i tessl/pypi-fuse-python

docs

configuration.md

core-operations.md

data-structures.md

extended-features.md

file-management.md

index.md

tile.json