0
# Data Structures and Types
1
2
FUSE data structures for representing file attributes, directory entries, filesystem statistics, and other metadata used in filesystem operations.
3
4
## Capabilities
5
6
### Base Structure Class
7
8
All FUSE data structures inherit from a common base class that provides initialization and representation functionality.
9
10
```python { .api }
11
class FuseStruct:
12
"""
13
Base class for FUSE data structures.
14
15
Provides keyword argument initialization and string representation.
16
"""
17
18
def __init__(self, **kwargs):
19
"""
20
Initialize structure with keyword arguments.
21
22
Args:
23
**kwargs: Attribute values to set
24
"""
25
26
def __repr__(self):
27
"""Return string representation of structure."""
28
```
29
30
**Usage Example:**
31
32
```python
33
# Initialize with keyword arguments
34
st = fuse.Stat(st_mode=0o644, st_size=1024)
35
36
# Access attributes directly
37
st.st_nlink = 1
38
st.st_uid = 1000
39
```
40
41
### File Attributes
42
43
Structure representing file and directory attributes, similar to the result of `stat()` system call.
44
45
```python { .api }
46
class Stat(FuseStruct):
47
"""
48
File/directory attributes structure.
49
50
Contains all standard POSIX file attributes.
51
"""
52
53
st_mode: int # File type and permissions (default: None)
54
st_ino: int # Inode number (default: 0)
55
st_dev: int # Device ID (default: 0)
56
st_nlink: int # Number of hard links (default: 0)
57
st_uid: int # User ID of owner (default: 0)
58
st_gid: int # Group ID of owner (default: 0)
59
st_size: int # Size in bytes (default: 0)
60
st_atime: int # Last access time (default: 0)
61
st_mtime: int # Last modification time (default: 0)
62
st_ctime: int # Last status change time (default: 0)
63
```
64
65
**Usage Example:**
66
67
```python
68
import stat
69
import time
70
71
def getattr(self, path):
72
st = fuse.Stat()
73
74
if path == '/':
75
# Directory attributes
76
st.st_mode = stat.S_IFDIR | 0o755
77
st.st_nlink = 2
78
st.st_size = 4096
79
else:
80
# File attributes
81
st.st_mode = stat.S_IFREG | 0o644
82
st.st_nlink = 1
83
st.st_size = len(self.get_file_content(path))
84
85
# Common attributes
86
current_time = int(time.time())
87
st.st_atime = current_time
88
st.st_mtime = current_time
89
st.st_ctime = current_time
90
st.st_uid = os.getuid()
91
st.st_gid = os.getgid()
92
93
return st
94
```
95
96
### Filesystem Statistics
97
98
Structure for filesystem-wide statistics, similar to the result of `statvfs()` system call.
99
100
```python { .api }
101
class StatVfs(FuseStruct):
102
"""
103
Filesystem statistics structure.
104
105
Contains information about filesystem capacity and usage.
106
"""
107
108
f_bsize: int # Filesystem block size
109
f_frsize: int # Fragment size
110
f_blocks: int # Total number of blocks
111
f_bfree: int # Number of free blocks
112
f_bavail: int # Number of available blocks for unprivileged users
113
f_files: int # Total number of file nodes (inodes)
114
f_ffree: int # Number of free file nodes
115
f_favail: int # Number of available file nodes for unprivileged users
116
f_flag: int # Filesystem flags
117
f_namemax: int # Maximum filename length
118
```
119
120
**Usage Example:**
121
122
```python
123
def statfs(self, path):
124
stv = fuse.StatVfs()
125
126
# Block information
127
stv.f_bsize = 4096 # 4KB blocks
128
stv.f_frsize = 4096 # Fragment size same as block size
129
stv.f_blocks = 1000000 # 1M total blocks (~4GB)
130
stv.f_bfree = 500000 # 500K free blocks
131
stv.f_bavail = 450000 # 450K available (some reserved)
132
133
# Inode information
134
stv.f_files = 100000 # 100K total inodes
135
stv.f_ffree = 80000 # 80K free inodes
136
stv.f_favail = 80000 # Same as free for unprivileged
137
138
# Filesystem properties
139
stv.f_flag = 0 # No special flags
140
stv.f_namemax = 255 # Maximum 255 character filenames
141
142
return stv
143
```
144
145
### Directory Entries
146
147
Structure representing individual entries in directory listings.
148
149
```python { .api }
150
class Direntry(FuseStruct):
151
"""
152
Directory entry structure.
153
154
Represents a single item in a directory listing.
155
"""
156
157
def __init__(self, name, **kwargs):
158
"""
159
Initialize directory entry.
160
161
Args:
162
name (str): Entry name (required)
163
**kwargs: Additional attributes (type, ino, offset)
164
"""
165
166
name: str # Entry name (required)
167
type: int # File type (optional, from stat module, default: None)
168
ino: int # Inode number (optional, default: None)
169
offset: int # Offset for next entry (optional, default: None)
170
```
171
172
**Usage Example:**
173
174
```python
175
def readdir(self, path, offset):
176
# Standard entries
177
yield fuse.Direntry('.')
178
yield fuse.Direntry('..')
179
180
# File entries with type information
181
for filename, content in self.files.items():
182
if filename.startswith(path.rstrip('/') + '/'):
183
basename = filename[len(path.rstrip('/') + '/'):]
184
if '/' not in basename: # Direct child only
185
yield fuse.Direntry(
186
name=basename,
187
type=stat.S_IFREG,
188
ino=hash(filename) % 2**32
189
)
190
191
# Directory entries
192
for dirname in self.dirs:
193
if dirname.startswith(path.rstrip('/') + '/'):
194
basename = dirname[len(path.rstrip('/') + '/'):]
195
if '/' not in basename: # Direct child only
196
yield fuse.Direntry(
197
name=basename,
198
type=stat.S_IFDIR,
199
ino=hash(dirname) % 2**32
200
)
201
```
202
203
### File Locking
204
205
Structure for file locking operations, similar to `struct flock`.
206
207
```python { .api }
208
class Flock(FuseStruct):
209
"""
210
File locking structure.
211
212
Used for advisory file locking operations.
213
"""
214
215
l_type: int # Lock type (F_RDLCK, F_WRLCK, F_UNLCK)
216
l_start: int # Starting offset for lock
217
l_len: int # Number of bytes to lock (0 = to EOF)
218
l_pid: int # Process ID of lock owner
219
```
220
221
**Usage Example:**
222
223
```python
224
def lock(self, path, fip, cmd, lock):
225
"""Handle file locking operations."""
226
227
if cmd == fcntl.F_GETLK:
228
# Check if lock would block
229
if self.would_block_lock(path, lock):
230
# Return conflicting lock info
231
conflicting_lock = fuse.Flock()
232
conflicting_lock.l_type = fcntl.F_WRLCK
233
conflicting_lock.l_start = 0
234
conflicting_lock.l_len = 0
235
conflicting_lock.l_pid = 1234
236
return conflicting_lock
237
else:
238
# No conflict
239
lock.l_type = fcntl.F_UNLCK
240
return 0
241
242
elif cmd == fcntl.F_SETLK:
243
# Set lock (non-blocking)
244
return self.set_lock(path, lock, blocking=False)
245
246
elif cmd == fcntl.F_SETLKW:
247
# Set lock (blocking)
248
return self.set_lock(path, lock, blocking=True)
249
```
250
251
### Time Specification
252
253
High-precision time structure for nanosecond-accurate timestamps.
254
255
```python { .api }
256
class Timespec(FuseStruct):
257
"""
258
Time specification with nanosecond precision.
259
260
Used for high-precision timestamp operations.
261
"""
262
263
tv_sec: int # Seconds since epoch
264
tv_nsec: int # Nanoseconds (0-999999999)
265
```
266
267
**Usage Example:**
268
269
```python
270
def utimens(self, path, ts_acc, ts_mod):
271
"""Set file timestamps with nanosecond precision."""
272
273
if path not in self.files:
274
return -errno.ENOENT
275
276
# Convert Timespec to float seconds
277
atime = ts_acc.tv_sec + ts_acc.tv_nsec / 1e9
278
mtime = ts_mod.tv_sec + ts_mod.tv_nsec / 1e9
279
280
# Store timestamps (implementation dependent)
281
self.file_times[path] = {
282
'atime': atime,
283
'mtime': mtime,
284
'ctime': time.time() # Change time is now
285
}
286
287
return 0
288
```
289
290
### File Information
291
292
Structure containing file operation context and flags.
293
294
```python { .api }
295
class FuseFileInfo(FuseStruct):
296
"""
297
File information structure.
298
299
Provides context for file operations.
300
"""
301
302
keep: bool # Whether to keep cached data
303
direct_io: bool # Whether to use direct I/O
304
```
305
306
**Usage Example:**
307
308
```python
309
def open(self, path, flags):
310
"""Open file with specific flags."""
311
312
if path not in self.files:
313
return -errno.ENOENT
314
315
# Check access permissions
316
if flags & os.O_WRONLY and self.is_readonly(path):
317
return -errno.EACCES
318
319
# Create file info for this open
320
fip = fuse.FuseFileInfo()
321
fip.keep = True # Enable caching
322
fip.direct_io = False # Use buffered I/O
323
324
return 0
325
```
326
327
## Type Constants
328
329
Common constants used with data structures, primarily from the `stat` module:
330
331
### File Types
332
- `stat.S_IFREG`: Regular file
333
- `stat.S_IFDIR`: Directory
334
- `stat.S_IFLNK`: Symbolic link
335
- `stat.S_IFCHR`: Character device
336
- `stat.S_IFBLK`: Block device
337
- `stat.S_IFIFO`: Named pipe (FIFO)
338
- `stat.S_IFSOCK`: Socket
339
340
### Permission Bits
341
- `stat.S_IRUSR`, `stat.S_IWUSR`, `stat.S_IXUSR`: User read/write/execute
342
- `stat.S_IRGRP`, `stat.S_IWGRP`, `stat.S_IXGRP`: Group read/write/execute
343
- `stat.S_IROTH`, `stat.S_IWOTH`, `stat.S_IXOTH`: Other read/write/execute
344
345
### Access Modes
346
- `os.R_OK`: Test for read permission
347
- `os.W_OK`: Test for write permission
348
- `os.X_OK`: Test for execute permission
349
- `os.F_OK`: Test for file existence
350
351
## Best Practices
352
353
- Always initialize structures with appropriate default values
354
- Use keyword arguments for clarity when creating structures
355
- Set all required fields for each structure type
356
- Use appropriate constants from `stat` and `os` modules
357
- Handle optional fields gracefully (check for None values)
358
- Consider precision requirements when working with timestamps