-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathvidCacheFS.py
More file actions
2371 lines (2058 loc) · 106 KB
/
Copy pathvidCacheFS.py
File metadata and controls
2371 lines (2058 loc) · 106 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# VidCacheFS - FUSE cache filesystem for media pre-warm
# Version: 0.1.0 (2025-08-23)
# Purpose: Near-instant Plex playback in environments with spundown HDDs by caching critical portions of video files + full subtitles on (NVME) SSD.
# See README for detailed features, limitations, and usage.
# Adjust the embedded configuration to your setup.
__version__ = "0.1.0"
import os
import sys
import errno
import time
import json
import glob
import threading
import argparse
import logging
import shutil
import multiprocessing
import stat # added for permission bit checks
from collections import OrderedDict
from fuse import FUSE, Operations, LoggingMixIn
import subprocess
try:
import inotify.adapters
INOTIFY_AVAILABLE = True
except ImportError:
INOTIFY_AVAILABLE = False
logging.warning("inotify module not available. File watching disabled. Run: pip install inotify")
logging.basicConfig(level = logging.INFO,format='%(created).6f [%(levelname)s] %(message)s')
# ---------- Default embedded configuration ----------
DEFAULT_CONFIG = {
"GLOBAL": {
"VERBOSE": True, # Enable verbose logging
"MAX_CACHE_SIZE_BYTES": 1850 * 1024 * 1024 * 1024, # Total cache size available on the disk/folder
"READ_ONLY": False, # If true, mount read-only (no cache writes)
"CHECK_FILE_MODIFICATIONS": False # Use when inotify is not available and you want to detect file modifications on the backing drives
},
"MOUNTS": [
{
"BACKING_DIR": "/mnt/user/video/Movies",
"MOUNT_POINT": "/mnt/ssd_cache/Movies",
"CACHE_DIR": "/mnt/videocache/Movies",
"MAX_FILES": 1500, # Maximum number of media files to cache. Cache Limit set to MAX_FILES*(HEAD_BYTES+TAIL+BYTES)
"HEAD_BYTES": 75 * 1024 * 1024,
"TAIL_BYTES": 1 * 1024 * 1024,
"SCHEDULES": [
{
"path": "/mnt/user/video/Movies",
"scan_interval_seconds": 14400,
"pattern": "*.{mkv,mp4,avi,mov,m4v,mpg,mpeg,wmv,flv,webm}"
}
],
"OPEN_SPINUP_TTL": 5
},
{
"BACKING_DIR": "/mnt/user/video/Series",
"MOUNT_POINT": "/mnt/ssd_cache/Series",
"CACHE_DIR": "/mnt/videocache/Series",
"MAX_FILES": 25000,
"HEAD_BYTES": 60 * 1024 * 1024,
"TAIL_BYTES": 1 * 1024 * 1024,
"SCHEDULES": [
{
"path": "/mnt/user/video/Series",
"scan_interval_seconds": 14400,
"pattern": "*.{mkv,mp4,avi,mov,m4v,mpg,mpeg,wmv,flv,webm}"
}
],
"OPEN_SPINUP_TTL": 5
}
],
"SUBTITLE_EXTENSIONS": [".srt", ".vtt", ".sub", ".ass", ".ssa", ".idx", ".smi"], # Subtitle file extensions to fully cache
"VIDEO_EXTENSIONS": [".mkv", ".mp4", ".avi", ".mov", ".m4v", ".mpg", ".mpeg", ".wmv", ".flv", ".webm"] # Video file extensions to partially cache
}
# Define standard locations to look for config files
CONFIG_PATHS = [
"/mnt/user/appdata/ssd_cache_config.json",
"config.json"
]
# ---------- Utility functions ----------
def ensure_parent_dir(path):
parent = os.path.dirname(path)
if parent and not os.path.exists(parent):
os.makedirs(parent, exist_ok=True)
def safe_copy_range(src_path, dst_path, length, offset=0, bufsize=4 * 1024 * 1024):
"""Copy `length` bytes from src_path starting at offset into dst_path."""
ensure_parent_dir(dst_path)
with open(src_path, 'rb') as s, open(dst_path, 'wb') as d:
s.seek(offset)
remaining = length
while remaining > 0:
toread = min(bufsize, remaining)
chunk = s.read(toread)
if not chunk:
break
d.write(chunk)
remaining -= len(chunk)
def safe_copy_file(src_path, dst_path):
"""Copy an entire file from src_path to dst_path."""
ensure_parent_dir(dst_path)
shutil.copy2(src_path, dst_path)
class MyLoggingMixIn(LoggingMixIn):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.mylog = logging.getLogger("fuse_custom")
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(
'%(asctime)s %(levelname)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
))
self.mylog.addHandler(handler)
self.mylog.setLevel(logging.INFO)
# ---------- Cache Manager (LRU) ----------
class CacheManager:
def __init__(self, cache_dir, max_cache_bytes, verbose=False):
self.cache_dir = cache_dir
self.max_cache_bytes = max_cache_bytes
self.verbose = verbose
# mapping from cache_path -> (size, last_access_time)
self.lock = threading.RLock()
self._load_existing_cache()
def _load_existing_cache(self):
# Build LRU state from cache directory
self.lru = OrderedDict()
total = 0
for root, dirs, files in os.walk(self.cache_dir):
for f in files:
if f.endswith('.head') or f.endswith('.tail') or f.endswith('.full'):
full = os.path.join(root, f)
try:
sz = os.path.getsize(full)
except OSError:
continue
total += sz
atime = os.path.getatime(full)
self.lru[full] = (sz, atime)
# Order by access time ascending (least recently used first)
self.lru = OrderedDict(sorted(self.lru.items(), key=lambda kv: kv[1][1]))
self.current_cache_bytes = total
if self.verbose:
logging.info(f"Loaded cache state: {len(self.lru)} items, {self.current_cache_bytes} bytes")
def touch(self, cache_path):
with self.lock:
if cache_path in self.lru:
sz, _ = self.lru.pop(cache_path)
at = time.time()
self.lru[cache_path] = (sz, at)
try:
os.utime(cache_path, (at, os.path.getmtime(cache_path)))
except Exception:
pass
def add(self, cache_path):
# Add a new cache file into LRU
with self.lock:
try:
sz = os.path.getsize(cache_path)
except OSError:
return
at = time.time()
if cache_path in self.lru:
self.lru.pop(cache_path)
self.lru[cache_path] = (sz, at)
self.current_cache_bytes += sz
if self.verbose:
logging.info(f"Added cache item {cache_path} ({sz} bytes). Total {self.current_cache_bytes}")
self._evict_if_needed()
def _evict_if_needed(self):
with self.lock:
while self.current_cache_bytes > self.max_cache_bytes and self.lru:
# pop oldest
oldest, (sz, at) = self.lru.popitem(last=False)
try:
os.remove(oldest)
# Also remove .meta if present
if oldest.endswith('.head'):
meta = oldest[:-5] + '.meta'
elif oldest.endswith('.tail'):
meta = oldest[:-5] + '.meta'
elif oldest.endswith('.full'):
meta = oldest[:-5] + '.meta'
else:
meta = None
if meta and os.path.exists(meta):
os.remove(meta)
except Exception as e:
logging.exception(f"Failed to remove cache item {oldest}: {e}")
self.current_cache_bytes -= sz
if self.verbose:
logging.info(f"Evicted {oldest} ({sz}) to free space. New total {self.current_cache_bytes}")
def get_path_for(self, relpath, kind):
# kind in ('head','tail','meta','full')
safe_rel = relpath.lstrip('/')
return os.path.join(self.cache_dir, safe_rel + f'.{kind}')
# --- Added: one-time reconciliation on startup ---
def reconcile_startup(self, head_bytes, tail_bytes, max_files):
"""Executed once after startup to:
1. Remove head/tail cache pieces whose size no longer matches configured head/tail bytes.
2. If cached file groups (.meta present) exceed max_files, prune oldest groups (LRU based on atime of their parts).
Only files with a .meta are considered valid groups. Subtitles (.full) are not resized.
"""
with self.lock:
if self.verbose:
logging.info(f"Starting cache reconciliation: head_bytes={head_bytes}, tail_bytes={tail_bytes}, max_files={max_files}")
# Build group map: base_path (without extension) -> dict(parts)
groups = {}
for root, _, files in os.walk(self.cache_dir):
for name in files:
if not (name.endswith('.meta') or name.endswith('.head') or name.endswith('.tail') or name.endswith('.full')):
continue
full = os.path.join(root, name)
base, _ = os.path.splitext(full)
g = groups.setdefault(base, {'meta': None, 'head': None, 'tail': None, 'full': None})
if name.endswith('.meta'):
g['meta'] = full
elif name.endswith('.head'):
g['head'] = full
elif name.endswith('.tail'):
g['tail'] = full
elif name.endswith('.full'):
g['full'] = full
# Keep only groups having meta
groups = {b: p for b, p in groups.items() if p['meta']}
# Pass 1: resize validation (delete mismatched head/tail)
for base, parts in groups.items():
try:
with open(parts['meta'], 'r') as f:
meta = json.load(f)
fsize = meta.get('size')
if fsize is None:
continue
# Expected sizes
expected_head_size = min(head_bytes, fsize) if head_bytes > 0 else 0
expected_tail_size = min(tail_bytes, fsize) if tail_bytes > 0 else 0
# head check
hp = parts.get('head')
if hp and os.path.exists(hp):
try:
if os.path.getsize(hp) != expected_head_size:
os.remove(hp)
if hp in self.lru:
sz,_ = self.lru.pop(hp)
self.current_cache_bytes -= sz
if self.verbose:
logging.info(f"Removed mismatched head cache: {hp}")
except Exception:
pass
# tail check
tp = parts.get('tail')
if tp and os.path.exists(tp):
try:
if os.path.getsize(tp) != expected_tail_size:
os.remove(tp)
if tp in self.lru:
sz,_ = self.lru.pop(tp)
self.current_cache_bytes -= sz
if self.verbose:
logging.info(f"Removed mismatched tail cache: {tp}")
except Exception:
pass
except Exception:
continue
# Pass 2: enforce max_files (count of groups)
group_count = len(groups)
if group_count > max_files:
# Build age list using min atime among existing part files
age_list = [] # (atime, base, parts)
for base, parts in groups.items():
at_list = []
for p in (parts.get('head'), parts.get('tail'), parts.get('full')):
if p and os.path.exists(p):
try:
at_list.append(os.path.getatime(p))
except Exception:
pass
if not at_list: # fallback to meta
try:
at_list.append(os.path.getatime(parts['meta']))
except Exception:
at_list.append(time.time())
age_list.append((min(at_list), base, parts))
age_list.sort(key=lambda x: x[0]) # oldest first
to_remove = group_count - max_files
removed = 0
for _, base, parts in age_list:
if removed >= to_remove:
break
for p in (parts.get('head'), parts.get('tail'), parts.get('full'), parts.get('meta')):
if p and os.path.exists(p):
try:
size = os.path.getsize(p)
except Exception:
size = 0
try:
os.remove(p)
if p in self.lru:
sz,_ = self.lru.pop(p)
self.current_cache_bytes -= sz
else:
self.current_cache_bytes -= size
except Exception:
pass
removed += 1
if self.verbose:
logging.info(f"Startup prune: removed {removed} old cached groups (now {group_count-removed}/{max_files}).")
# ---------- Scheduler: populates cache on interval ----------
class Scheduler(threading.Thread):
def __init__(self, schedules, cache_manager, head_bytes, tail_bytes, backing_root,
subtitle_extensions, video_extensions, verbose=False, use_cache_db=False,
check_file_modifications=False):
super().__init__(daemon=True)
self.schedules = schedules
self.cache_manager = cache_manager
self.head_bytes = head_bytes
self.tail_bytes = tail_bytes
self.backing_root = backing_root
self.subtitle_extensions = subtitle_extensions
self.video_extensions = video_extensions
self.verbose = verbose
self._stop = threading.Event()
self.cache = cache_manager # Alias for readability
self.use_cache_db = use_cache_db
self.last_db_check = 0
self.db_check_interval = 60 # Check database every 60 seconds
self.cache_db_path = os.path.join(self.cache_manager.cache_dir, ".cache_db.json")
# Add file modification check option
self.check_file_modifications = check_file_modifications
if self.check_file_modifications and self.verbose:
logging.info("File modification checking enabled - may cause drives to spin up during scheduled scans")
# Existing code for buffer initialization
self.cache_buffer = OrderedDict() # Maps path -> (mtime, size, relpath)
self.buffer_size_bytes = 0
self.max_buffer_size = self.cache_manager.max_cache_bytes # Use same limit as cache
def run(self):
logging.info(f"Cache scheduler started for {self.backing_root}")
# Schedule is map of path -> interval
last_scan = {}
while not self._stop.is_set():
now = time.time()
# First check cache database for pending files (this doesn't cause drive spin-up)
if self.use_cache_db and now - self.last_db_check >= self.db_check_interval:
self.last_db_check = now
try:
self._check_cache_database()
except Exception:
logging.exception("Cache database check failed")
# Then do normal scheduled scans
for sched in self.schedules:
path = sched['path']
interval = sched['scan_interval_seconds']
pattern = sched['pattern']
# Check if we should run this schedule
if path not in last_scan or now - last_scan[path] >= interval:
last_scan[path] = now
try:
if self.verbose:
logging.info(f"Running cache scan for {path} with pattern {pattern}")
self._scan_and_buffer(path, pattern)
except Exception as e:
logging.exception(f"Scheduler scan failed: {e}")
# After scan, process the buffer to cache files
self._process_buffer()
# Sleep a small amount so we can be responsive to stop
self._stop.wait(5)
def _scan_and_buffer(self, path, pattern):
"""Scan for files matching pattern and add them to buffer without immediately caching."""
# For patterns with multiple extensions like *.{mkv,mp4}, pass them directly
# to _scan_files_into_buffer which now handles brace expansion internally
self._scan_files_into_buffer(path, pattern)
# Also scan for subtitle files - each extension separately for clarity
for ext in self.subtitle_extensions:
self._scan_files_into_buffer(path, f"*{ext}")
def _scan_files_into_buffer(self, path, pattern):
"""Scan files by pattern and add to buffer with LRU eviction."""
try:
# For large directories, using glob recursively can hit system limits
# Use os.walk instead which is more efficient for large directory structures
total_files_found = 0
if '{' in pattern and '}' in pattern:
# Handle brace expansion patterns like "*.{mkv,mp4}"
base, extensions = pattern.split('{', 1)
extensions = extensions.split('}', 1)[0]
extensions_list = [ext.strip() for ext in extensions.split(',')]
# Create a list of patterns to match
patterns = [base + ext for ext in extensions_list]
else:
patterns = [pattern]
# Walk the directory tree manually
for root, _, files in os.walk(path):
for filename in files:
# Check each filename against our patterns
for pat in patterns:
if self._matches_simple_pattern(filename, pat):
total_files_found += 1
full_path = os.path.join(root, filename)
# Check if this is a file type we care about
_, ext = os.path.splitext(filename.lower())
if ext not in self.subtitle_extensions and ext not in self.video_extensions:
continue
try:
# Get file stats
st = os.stat(full_path)
mtime = st.st_mtime
size = st.st_size
# Calculate how much space this will use in cache
if ext in self.subtitle_extensions:
cache_size = size + 1024 # file + metadata
else:
cache_size = min(self.head_bytes, size) + min(self.tail_bytes, size) + 1024
# Get relative path
try:
rel = os.path.relpath(full_path, self.backing_root)
except ValueError:
# Not under backing_root
rel = os.path.basename(full_path)
# Add to buffer, possibly evicting older entries
self._add_to_buffer(full_path, mtime, cache_size, rel)
# Break out of pattern loop since we found a match
break
except (FileNotFoundError, PermissionError):
# Skip files we can't access
continue
except Exception as e:
if self.verbose:
logging.warning(f"Error processing file {full_path}: {e}")
if self.verbose and total_files_found > 0:
logging.info(f"Found {total_files_found} files matching pattern(s) {patterns} in {path}")
logging.info(f"Buffer now contains {len(self.cache_buffer)} files ({self.buffer_size_bytes/1024/1024:.2f} MB)")
except Exception as e:
logging.warning(f"Error scanning path {path} with pattern {pattern}: {e}")
def _matches_simple_pattern(self, filename, pattern):
"""Simple pattern matching for filenames (faster than regex for large datasets).
Supports basic wildcard patterns like "*.mp4" or "video.*"
"""
if pattern.startswith('*.'):
# Most common case - extension matching
return filename.lower().endswith(pattern[1:].lower())
elif pattern == '*':
# Match everything
return True
elif '*' not in pattern:
# Exact match
return filename.lower() == pattern.lower()
elif pattern.endswith('*'):
# Starts with pattern
prefix = pattern[:-1]
return filename.lower().startswith(prefix.lower())
elif pattern.startswith('*'):
# Ends with pattern
suffix = pattern[1:]
return filename.lower().endswith(suffix.lower())
else:
# More complex pattern - parts before and after *
parts = pattern.split('*', 1)
return (filename.lower().startswith(parts[0].lower()) and
filename.lower().endswith(parts[1].lower()))
def _add_to_buffer(self, filepath, mtime, cache_size, relpath):
"""Add a file to the buffer, evicting older files if needed."""
# If file is already in buffer, update its timestamp (make it most recent)
if filepath in self.cache_buffer:
_, old_size, _ = self.cache_buffer.pop(filepath)
self.buffer_size_bytes -= old_size
# Add the new file to the buffer (at the end, most recent)
self.cache_buffer[filepath] = (mtime, cache_size, relpath)
self.buffer_size_bytes += cache_size
# Evict older files if we exceed the buffer size limit
while self.buffer_size_bytes > self.max_buffer_size and self.cache_buffer:
# Remove the oldest entry (first in the OrderedDict)
oldest_path, (_, oldest_size, _) = next(iter(self.cache_buffer.items()))
self.cache_buffer.pop(oldest_path)
self.buffer_size_bytes -= oldest_size
if self.verbose and len(self.cache_buffer) % 100 == 0:
logging.debug(f"Buffer: {len(self.cache_buffer)} files, {self.buffer_size_bytes/1024/1024:.2f} MB")
def _process_buffer(self):
"""Process all files in the buffer and cache them using a single worker."""
if not self.cache_buffer:
return
count = 0
cache_size = 0
buffer_size = len(self.cache_buffer)
if self.verbose:
logging.info(f"Processing cache buffer with {buffer_size} files")
try:
# Process files from buffer (most recently modified first)
progress_interval = max(1, int(buffer_size * 0.1)) # Report progress at 10% intervals
for i, (filepath, (mtime, size_estimate, relpath)) in enumerate(list(self.cache_buffer.items())):
try:
self._ensure_cache_for(filepath, relpath)
count += 1
cache_size += size_estimate
# Report progress more frequently for large buffer sizes
if self.verbose and (i+1) % progress_interval == 0:
percent = 100.0 * (i+1) / buffer_size
logging.info(f"Cached {count}/{buffer_size} files ({percent:.1f}%)")
# Check if we should stop
if self._stop.is_set():
break
except Exception as e:
logging.warning(f"Error caching file {filepath}: {e}")
# Clear the buffer after processing
self.cache_buffer.clear()
self.buffer_size_bytes = 0
if self.verbose:
logging.info(f"Completed caching {count} files, ~{cache_size/1024/1024:.2f} MB")
except Exception as e:
logging.exception(f"Unexpected error in _process_buffer: {e}")
def stop(self):
self._stop.set()
self.join(timeout=2)
def _scan_and_cache(self, path, pattern):
# Handle patterns with multiple extensions like *.{mkv,mp4}
if '{' in pattern and '}' in pattern:
# Extract the extension part from the pattern
base, extensions = pattern.split('{', 1)
extensions = extensions.split('}', 1)[0]
extensions = extensions.split(',')
for ext in extensions:
self._scan_files_by_pattern(path, base + ext.strip())
else:
self._scan_files_by_pattern(path, pattern)
# Also scan for subtitle files
for ext in self.subtitle_extensions:
self._scan_files_by_pattern(path, f"*{ext}")
def _scan_files_by_pattern(self, path, pattern):
globp = os.path.join(path, '**', pattern)
for file in glob.glob(globp, recursive=True):
if not os.path.isfile(file):
continue
try:
rel = os.path.relpath(file, self.backing_root)
except ValueError:
# Not under backing_root
rel = os.path.basename(file)
self._ensure_cache_for(file, rel)
def _ensure_cache_for(self, fullpath, relpath):
# Check if this is a subtitle file
_, ext = os.path.splitext(fullpath.lower())
is_subtitle = ext in self.subtitle_extensions
is_video = ext in self.video_extensions
# For non-subtitle/video files, we don't cache
if not is_subtitle and not is_video:
return
# Check meta to see if cache valid
if is_subtitle:
# For subtitle files, cache the entire file
full_path = self.cache_manager.get_path_for(relpath, 'full')
meta_path = self.cache_manager.get_path_for(relpath, 'meta')
head_path = None
tail_path = None
else:
# For video files, cache head and tail portions
head_path = self.cache_manager.get_path_for(relpath, 'head')
tail_path = self.cache_manager.get_path_for(relpath, 'tail')
meta_path = self.cache_manager.get_path_for(relpath, 'meta')
full_path = None
need_head = not is_subtitle
need_tail = not is_subtitle
need_full = is_subtitle
need_meta = True # Always assume we need metadata initially
# First get file stats for metadata
try:
st = os.stat(fullpath)
metadata = {
'size': st.st_size,
'mtime': st.st_mtime,
'atime': st.st_atime,
'ctime': st.st_ctime,
'mode': st.st_mode,
'uid': st.st_uid,
'gid': st.st_gid,
'nlink': st.st_nlink
}
except Exception as e:
if self.verbose:
logging.warning(f"Failed to get stats for {relpath}: {e}")
return # Cannot continue without file stats
if os.path.exists(meta_path):
try:
with open(meta_path, 'r') as f:
old = json.load(f)
# Check if file has changed when file modification checking is enabled
if self.check_file_modifications:
# We already have current stats, so just compare
if (old.get('size') != metadata['size'] or old.get('mtime') != metadata['mtime']):
if self.verbose:
logging.info(f"File changed (size/mtime): {relpath}")
if old.get('size') != metadata['size']:
logging.info(f" Size changed: {old.get('size')} -> {metadata['size']}")
if old.get('mtime') != metadata['mtime']:
logging.info(f" Mtime changed: {old.get('mtime')} -> {metadata['mtime']}")
# Force recaching by keeping need_* as True
need_head = not is_subtitle
need_tail = not is_subtitle
need_full = is_subtitle
need_meta = True
else:
# File is unchanged, check if cache exists
need_meta = False # We already have valid metadata
if is_subtitle:
if os.path.exists(full_path) and os.path.getsize(full_path) >= old.get('size', 0):
need_full = False
else:
if os.path.exists(head_path) and os.path.getsize(head_path) >= min(self.head_bytes, old.get('size', 0)):
need_head = False
if os.path.exists(tail_path) and os.path.getsize(tail_path) >= min(self.tail_bytes, old.get('size', 0)):
need_tail = False
else:
# Standard check without comparing file modifications
need_meta = False # Existing metadata is fine
if old.get('size') == None or old.get('mtime') == None:
# Metadata is incomplete, force recache
need_head = not is_subtitle
need_tail = not is_subtitle
need_full = is_subtitle
need_meta = True
else:
# Just check if cache files exist
if is_subtitle:
if os.path.exists(full_path) and os.path.getsize(full_path) >= old.get('size', 0):
need_full = False
else:
if os.path.exists(head_path) and os.path.getsize(head_path) >= min(self.head_bytes, old.get('size', 0)):
need_head = False
if os.path.exists(tail_path) and os.path.getsize(tail_path) >= min(self.tail_bytes, old.get('size', 0)):
need_tail = False
except Exception as e:
if self.verbose:
logging.warning(f"Failed to read metadata for {relpath}: {e}")
# If we can't read metadata, force recache
need_head = not is_subtitle
need_tail = not is_subtitle
need_full = is_subtitle
need_meta = True
# Write metadata if needed
if need_meta:
ensure_parent_dir(meta_path)
with open(meta_path, 'w') as f:
json.dump(metadata, f)
# If file changed or no meta, we will write new cache parts
if is_subtitle and need_full:
try:
if self.verbose:
logging.info(f"Caching full subtitle file {relpath}")
ensure_parent_dir(full_path)
safe_copy_file(fullpath, full_path)
self.cache_manager.add(full_path)
except Exception as e:
logging.exception(f"Failed to cache subtitle file {fullpath}: {e}")
return
# Handle video file caching
if need_head:
length = min(self.head_bytes, metadata['size'])
if length > 0:
try:
ensure_parent_dir(head_path)
safe_copy_range(fullpath, head_path, length, offset=0)
self.cache_manager.add(head_path)
except Exception as e:
logging.exception(f"Failed to cache head for {fullpath}: {e}")
if need_tail:
# tail offset
if metadata['size'] <= self.tail_bytes:
# small file: tail is entire file (we'll copy entire)
offset = 0
length = metadata['size']
else:
offset = metadata['size'] - self.tail_bytes
length = self.tail_bytes
if length > 0:
try:
ensure_parent_dir(tail_path)
safe_copy_range(fullpath, tail_path, length, offset=offset)
self.cache_manager.add(tail_path)
except Exception as e:
logging.exception(f"Failed to cache tail for {fullpath}: {e}")
def _check_cache_database(self):
"""Check database of pending files to cache.
This allows you to add files to be cached without causing HDD spin-up.
Files are added to the database by external processes or scripts.
"""
if not os.path.exists(self.cache_db_path):
# Create empty database if it doesn't exist
with open(self.cache_db_path, 'w') as f:
json.dump({"pending": []}, f)
return
try:
with open(self.cache_db_path, 'r') as f:
db = json.load(f)
pending = db.get("pending", [])
if not pending:
return
if self.verbose:
logging.info(f"Found {len(pending)} files in cache database to process")
# Process pending files
remaining = []
for entry in pending:
if isinstance(entry, str):
# Simple path format
path = entry
if os.path.exists(path) and os.path.isfile(path):
try:
rel = os.path.relpath(path, self.backing_root)
self._ensure_cache_for(path, rel)
if self.verbose:
logging.info(f"Cached file from database: {path}")
except Exception as e:
logging.warning(f"Failed to cache file from database {path}: {e}")
remaining.append(path)
elif isinstance(entry, dict):
# Extended format with attributes
path = entry.get("path")
if path and os.path.exists(path) and os.path.isfile(path):
try:
rel = os.path.relpath(path, self.backing_root)
self._ensure_cache_for(path, rel)
if self.verbose:
logging.info(f"Cached file from database: {path}")
except Exception as e:
logging.warning(f"Failed to cache file from database {path}: {e}")
remaining.append(entry)
else:
remaining.append(entry)
# Update database with remaining files
with open(self.cache_db_path, 'w') as f:
json.dump({"pending": remaining}, f)
if self.verbose and len(remaining) < len(pending):
logging.info(f"Processed {len(pending) - len(remaining)} files from cache database")
except Exception as e:
logging.exception(f"Error checking cache database: {e}")
# ---------- SSD Cache Filesystem Implementation ----------
class VidCacheFS(MyLoggingMixIn, Operations):
def __init__(self, backing_root, cache_manager, head_bytes, tail_bytes,
subtitle_extensions, video_extensions,
open_spinup_ttl=5, verbose=False, read_only=False, schedule_interval=3600):
self.backing_root = backing_root
self.cache = cache_manager
self.head_bytes = head_bytes
self.tail_bytes = tail_bytes
self.subtitle_extensions = subtitle_extensions
self.video_extensions = video_extensions
self.open_spinup_ttl = open_spinup_ttl
self.verbose = verbose
self.read_only = read_only
self.fd = 0
self.open_files = {}
# Use fixed 60s like original to avoid long stale caches for Docker/Plex
self.attr_cache_ttl = 60
self.dir_cache_ttl = 60
self.attr_cache = {}
self.attr_cache_lock = threading.RLock()
self.dir_cache = {}
self.dir_cache_lock = threading.RLock()
# Always enable lazy video open by default (no env var needed)
self.lazy_video_open = True
def _backing_path(self, path):
path = path.lstrip('/')
return os.path.join(self.backing_root, path)
def _relative_path(self, path):
path = path.lstrip('/')
return path
def _relpath(self, path):
if path.startswith('/'):
return path[1:]
return path
def _cache_paths(self, relpath):
_, ext = os.path.splitext(relpath.lower())
is_subtitle = ext in self.subtitle_extensions
if is_subtitle:
full = self.cache.get_path_for(relpath, 'full')
meta = self.cache.get_path_for(relpath, 'meta')
# For consistency with the interface, return these as head/tail
return None, None, meta, full
else:
head = self.cache.get_path_for(relpath, 'head')
tail = self.cache.get_path_for(relpath, 'tail')
meta = self.cache.get_path_for(relpath, 'meta')
return head, tail, meta, None
# New helper for lazy open logic (was missing)
def _should_lazy_open_video(self, rel, acc_mode):
if not self.lazy_video_open:
return False
if acc_mode != os.O_RDONLY:
return False
_, ext = os.path.splitext(rel.lower())
if ext not in self.video_extensions:
return False
head_path, _, _, _ = self._cache_paths(rel)
return os.path.exists(head_path)
# Added helper methods for cache invalidation
def _invalidate_attr_cache(self, path):
try:
with self.attr_cache_lock:
self.attr_cache.pop(path, None)
except Exception:
pass
def _invalidate_dir_cache(self, path):
try:
with self.dir_cache_lock:
self.dir_cache.pop(path, None)
except Exception:
pass
# ---------- Filesystem methods ----------
def getattr(self, path, fh=None):
rel = self._relpath(path)
# For ANY path, check our in-memory attribute cache first
with self.attr_cache_lock:
if path in self.attr_cache:
attr_dict, timestamp = self.attr_cache[path]
# Check if cache entry is still valid
if time.time() - timestamp < self.attr_cache_ttl:
return attr_dict
# Check if it's a directory - but use backing storage only if needed
backing = self._backing_path(path)
if os.path.isdir(backing):
try:
st = os.lstat(backing)
attr_dict = dict((key, getattr(st, key)) for key in (
'st_atime', 'st_ctime', 'st_gid', 'st_mode', 'st_mtime',
'st_nlink', 'st_size', 'st_uid'))
# Cache directory attributes too
with self.attr_cache_lock:
self.attr_cache[path] = (attr_dict, time.time())
return attr_dict
except FileNotFoundError:
raise OSError(errno.ENOENT, '')
with self.attr_cache_lock:
if path in self.attr_cache:
attr_dict, timestamp = self.attr_cache[path]
# Check if cache entry is still valid
if time.time() - timestamp < self.attr_cache_ttl:
return attr_dict
# Next, check if we have metadata cached on disk
_, ext = os.path.splitext(rel.lower())
is_subtitle = ext in self.subtitle_extensions
is_video = ext in self.video_extensions
if is_subtitle or is_video:
# Get cache paths
_, _, meta_path, _ = self._cache_paths(rel)
if os.path.exists(meta_path):
try:
with open(meta_path, 'r') as f:
metadata = json.load(f)
# If the metadata has complete attributes, use them
if all(key in metadata for key in ('size', 'mtime', 'atime', 'ctime', 'mode', 'uid', 'gid', 'nlink')):
attr_dict = {
'st_size': metadata['size'],
'st_mtime': metadata['mtime'],
'st_atime': metadata['atime'],
'st_ctime': metadata['ctime'],
'st_mode': metadata['mode'],
'st_uid': metadata['uid'],
'st_gid': metadata['gid'],
'st_nlink': metadata['nlink']
}
# Store in memory cache
with self.attr_cache_lock:
self.attr_cache[path] = (attr_dict, time.time())
return attr_dict
except Exception:
# Fall through to backing access on failure
pass
# If we got here, we need to access the backing storage
try:
st = os.lstat(backing)
attr_dict = dict((key, getattr(st, key)) for key in (
'st_atime', 'st_ctime', 'st_gid', 'st_mode', 'st_mtime',
'st_nlink', 'st_size', 'st_uid'))
# Store in memory cache
with self.attr_cache_lock:
self.attr_cache[path] = (attr_dict, time.time())
# Update the metadata file if this is a file type we cache
if is_subtitle or is_video:
_, _, meta_path, _ = self._cache_paths(rel)
try:
ensure_parent_dir(meta_path)
with open(meta_path, 'w') as f:
json.dump({
'size': st.st_size,
'mtime': st.st_mtime,
'atime': st.st_atime,
'ctime': st.st_ctime,
'mode': st.st_mode,
'uid': st.st_uid,
'gid': st.st_gid,
'nlink': st.st_nlink
}, f)
except Exception as e:
if self.verbose:
logging.warning(f"Failed to update metadata cache for {path}: {e}")
return attr_dict
except FileNotFoundError: