-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlockImageUpdate.py
More file actions
2833 lines (2293 loc) · 120 KB
/
BlockImageUpdate.py
File metadata and controls
2833 lines (2293 loc) · 120 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
"""
Production-ready BlockImageUpdate implementation for Python 3.13
Optimized for transfer.list V4 command parsing and execution
"""
import asyncio
import sys
import os
import struct
import hashlib
import tempfile
import threading
import time
import queue
import mmap
import ctypes
from typing import Self, List, Dict, Any, Optional, BinaryIO, Iterator, Tuple, Union, AsyncIterator
from pathlib import Path
import json
from contextlib import suppress, contextmanager, redirect_stderr
from dataclasses import dataclass
import logging
from functools import lru_cache
from collections import OrderedDict
import weakref
import psutil # 用于内存监控
import gc # 垃圾回收控制
logger = logging.getLogger("BlockImageUpdate")
# ---------------------------------------------------------------------------
# Constants for IMGDIFF2
# ---------------------------------------------------------------------------
CHUNK_NORMAL = 0
CHUNK_GZIP = 1
CHUNK_DEFLATE = 2
CHUNK_RAW = 3
CHUNK_COMPRESSED_BSDIFF = 8 # 新增:标识“compressed bsdiff”块
def read_bin_file(filename):
with open(filename, 'rb') as f:
return f.read()
def write_bin_file(filename, data):
"""Windows-safe file writing with WinError 6 handling"""
filename = Path(filename)
filename.parent.mkdir(parents=True, exist_ok=True)
if os.name == 'nt':
# Windows-specific atomic write with retry logic
max_retries = 3
for attempt in range(max_retries):
temp_file = filename.with_suffix(f'.tmp_{os.getpid()}_{attempt}')
try:
with open(temp_file, 'wb') as f:
f.write(data)
f.flush()
os.fsync(f.fileno())
# Atomic rename on Windows
if filename.exists():
try:
filename.unlink()
except (PermissionError, OSError):
time.sleep(0.1)
filename.unlink()
temp_file.rename(filename)
break # Success
except OSError as e:
if temp_file.exists():
try:
temp_file.unlink()
except:
pass
if hasattr(e, 'winerror') and e.winerror == 6:
logger.warning(f"WinError 6 in write_bin_file, attempt {attempt + 1}")
if attempt < max_retries - 1:
time.sleep(0.2 * (attempt + 1))
continue
raise e
else:
with open(filename, 'wb') as f:
f.write(data)
def ensure_bytes(data):
if isinstance(data, (bytes, bytearray)):
return data
elif hasattr(data, "tobytes"):
return data.tobytes()
elif hasattr(data, "__getitem__"):
return bytes(data)
else:
raise TypeError(f"Unsupported data type for patch: {type(data)}")
@dataclass
class LargeFileConfig:
"""Large file processing configuration"""
chunk_size_mb: int = 64 # 块大小(MB)
memory_limit_mb: int = 1024 # 内存限制(MB)
enable_streaming: bool = True # 启用流式处理
gc_frequency: int = 10 # 垃圾回收频率
use_mmap_threshold_mb: int = 100 # 使用mmap的文件大小阈值
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
try:
from ApplyPatch import apply_bsdiff_patch,apply_imgdiff_patch_streaming
APPLYPATCH_AVAILABLE = True
except ImportError:
APPLYPATCH_AVAILABLE = False
logger.warning("ApplyPatch module not available, will use external process")
class LRUStashCache:
"""Thread-safe LRU cache for stash data with size limits"""
def __init__(self, max_items: int = 50, max_memory_mb: int = 500):
self.max_items = max_items
self.max_memory_bytes = max_memory_mb * 1024 * 1024
self.cache = OrderedDict()
self.current_memory = 0
self.lock = threading.RLock()
self.disk_cache_dir = None
def set_disk_cache_dir(self, cache_dir: Path):
"""Set directory for disk-based cache fallback"""
self.disk_cache_dir = cache_dir
def get(self, key: str) -> Optional[bytes]:
"""Get stash data, checking memory cache first, then disk"""
with self.lock:
# Check memory cache first
if key in self.cache:
# Move to end (most recently used)
value = self.cache.pop(key)
self.cache[key] = value
return value
# Check disk cache
if self.disk_cache_dir:
disk_file = self.disk_cache_dir / f"stash_{key}"
if disk_file.exists():
try:
data = disk_file.read_bytes()
# Add to memory cache if there's room
self._add_to_memory_cache(key, data)
return data
except Exception as e:
logger.warning(f"Failed to read disk cache for {key}: {e}")
return None
def put(self, key: str, value: bytes):
"""Store stash data with automatic eviction"""
with self.lock:
# Remove if already exists to update position
if key in self.cache:
old_value = self.cache.pop(key)
self.current_memory -= len(old_value)
# Try to add to memory cache
if self._can_fit_in_memory(value):
self._add_to_memory_cache(key, value)
else:
# Store to disk if too large for memory
self._store_to_disk(key, value)
def _can_fit_in_memory(self, value: bytes) -> bool:
"""Check if value can fit in memory cache"""
return len(value) <= self.max_memory_bytes // 4 # Don't use more than 25% for single item
def _add_to_memory_cache(self, key: str, value: bytes):
"""Add item to memory cache with eviction"""
value_size = len(value)
# Evict items if necessary
while (len(self.cache) >= self.max_items or
self.current_memory + value_size > self.max_memory_bytes):
if not self.cache:
break
self._evict_oldest()
# Add new item
self.cache[key] = value
self.current_memory += value_size
def _evict_oldest(self):
"""Evict the oldest item from memory cache"""
if not self.cache:
return
oldest_key, oldest_value = self.cache.popitem(last=False)
self.current_memory -= len(oldest_value)
# Store evicted item to disk if possible
self._store_to_disk(oldest_key, oldest_value)
def _store_to_disk(self, key: str, value: bytes):
"""Store item to disk cache"""
if not self.disk_cache_dir:
return
try:
disk_file = self.disk_cache_dir / f"stash_{key}"
disk_file.write_bytes(value)
logger.debug(f"Stored stash {key} to disk ({len(value)} bytes)")
except Exception as e:
logger.warning(f"Failed to store stash {key} to disk: {e}")
def remove(self, key: str):
"""Remove item from both memory and disk cache"""
with self.lock:
# Remove from memory
if key in self.cache:
value = self.cache.pop(key)
self.current_memory -= len(value)
# Remove from disk
if self.disk_cache_dir:
disk_file = self.disk_cache_dir / f"stash_{key}"
try:
if disk_file.exists():
disk_file.unlink()
except Exception as e:
logger.warning(f"Failed to remove disk cache for {key}: {e}")
def clear(self):
"""Clear all cached data"""
with self.lock:
self.cache.clear()
self.current_memory = 0
# Clear disk cache
if self.disk_cache_dir and self.disk_cache_dir.exists():
try:
for file_path in self.disk_cache_dir.glob("stash_*"):
file_path.unlink()
except Exception as e:
logger.warning(f"Failed to clear disk cache: {e}")
def get_memory_usage(self) -> dict:
"""Get current memory usage statistics"""
with self.lock:
return {
'items_in_memory': len(self.cache),
'memory_bytes': self.current_memory,
'memory_mb': self.current_memory / (1024 * 1024),
'max_items': self.max_items,
'max_memory_mb': self.max_memory_bytes / (1024 * 1024)
}
@dataclass
class IOSettings:
"""Platform-specific I/O optimization settings"""
buffer_size: int
use_direct_io: bool
sync_method: str
class RangeSet:
"""Optimized RangeSet implementation with better validation"""
__slots__ = ('pos', 'count', 'size')
def __init__(self, range_text: str):
if not range_text or not isinstance(range_text, str):
raise ValueError("Range text must be a non-empty string")
pieces = range_text.split(',')
if len(pieces) < 3:
raise ValueError(f"Invalid range format: {range_text}")
try:
num = int(pieces[0])
except ValueError:
raise ValueError(f"Invalid range count: {pieces[0]}")
if num == 0:
raise ValueError("Range count cannot be zero")
if num % 2 != 0:
raise ValueError("Range count must be even (pairs of start,end)")
if num != len(pieces) - 1:
raise ValueError(f"Range count mismatch: expected {num}, got {len(pieces) - 1}")
self.pos = []
self.count = num // 2
self.size = 0
# Parse and validate ranges
for i in range(0, num, 2):
try:
start = int(pieces[i + 1])
end = int(pieces[i + 2])
except (ValueError, IndexError) as e:
raise ValueError(f"Invalid range values at position {i}: {e}")
if start < 0 or end < 0:
raise ValueError(f"Range values cannot be negative: {start}, {end}")
if start >= end:
raise ValueError(f"Invalid range: start >= end ({start} >= {end})")
self.pos.extend([start, end])
self.size += end - start
# Validate ranges don't overlap
self._validate_no_overlaps()
def _validate_no_overlaps(self):
"""Ensure ranges don't overlap"""
ranges = [(self.pos[i], self.pos[i + 1]) for i in range(0, len(self.pos), 2)]
ranges.sort()
for i in range(len(ranges) - 1):
if ranges[i][1] > ranges[i + 1][0]:
raise ValueError(f"Overlapping ranges: [{ranges[i][0]}-{ranges[i][1]}) and [{ranges[i + 1][0]}-{ranges[i + 1][1]})")
def __iter__(self):
"""Iterate over (start, end) pairs"""
for i in range(0, len(self.pos), 2):
yield (self.pos[i], self.pos[i + 1])
def __len__(self) -> int:
return self.count
def get_ranges(self) -> List[Tuple[int, int]]:
"""Return list of (start, end) tuples"""
return [(self.pos[i], self.pos[i + 1]) for i in range(0, len(self.pos), 2)]
class RangeSinkState:
"""Python implementation of C++ RangeSinkState for precise range writing"""
def __init__(self, rangeset: RangeSet, fd: BinaryIO, blocksize: int = 4096):
self.tgt = rangeset
self.fd = fd
self.blocksize = blocksize
self.p_block = 0
self.p_remain = 0
self._setup_first_range()
def _setup_first_range(self):
"""Setup the first range for writing"""
if self.tgt.count > 0:
self.p_remain = (self.tgt.pos[1] - self.tgt.pos[0]) * self.blocksize
offset = self.tgt.pos[0] * self.blocksize
self.fd.seek(offset)
def write(self, data: bytes) -> int:
"""Write data using RangeSink logic, returns bytes written"""
if self.p_remain == 0:
logger.warning("Range sink write overrun")
return 0
written = 0
data_view = memoryview(data)
while len(data_view) > 0 and self.p_remain > 0:
write_now = min(len(data_view), self.p_remain)
try:
actual_written = self.fd.write(data_view[:write_now])
if actual_written != write_now:
logger.error(f"Short write: expected {write_now}, got {actual_written}")
break
except OSError as e:
logger.error(f"Write failed: {e}")
break
data_view = data_view[write_now:]
self.p_remain -= write_now
written += write_now
if self.p_remain == 0:
# Move to next block
self.p_block += 1
if self.p_block < self.tgt.count:
self.p_remain = (self.tgt.pos[self.p_block * 2 + 1] -
self.tgt.pos[self.p_block * 2]) * self.blocksize
offset = self.tgt.pos[self.p_block * 2] * self.blocksize
self.fd.seek(offset)
else:
break
return written
class AsyncBlockProcessor:
"""Async block processor for improved I/O performance"""
def __init__(self, blocksize: int = 4096, max_concurrent: int = 4):
self.blocksize = blocksize
self.max_concurrent = max_concurrent
self.semaphore = asyncio.Semaphore(max_concurrent)
async def read_blocks_async(self, fd: BinaryIO, rangeset: RangeSet) -> bytes:
"""Asynchronously read blocks from file descriptor"""
tasks = []
for start_block, end_block in rangeset:
task = self._read_range_async(fd, start_block, end_block)
tasks.append(task)
results = await asyncio.gather(*tasks)
return b''.join(results)
async def _read_range_async(self, fd: BinaryIO, start_block: int, end_block: int) -> bytes:
"""Read a single range asynchronously"""
async with self.semaphore:
loop = asyncio.get_event_loop()
def read_range():
offset = start_block * self.blocksize
size = (end_block - start_block) * self.blocksize
fd.seek(offset)
return fd.read(size)
return await loop.run_in_executor(None, read_range)
async def write_blocks_async(self, fd: BinaryIO, rangeset: RangeSet, data: bytes) -> bool:
"""Asynchronously write blocks to file descriptor"""
tasks = []
data_offset = 0
for start_block, end_block in rangeset:
chunk_size = (end_block - start_block) * self.blocksize
chunk_data = data[data_offset:data_offset + chunk_size]
task = self._write_range_async(fd, start_block, chunk_data)
tasks.append(task)
data_offset += chunk_size
results = await asyncio.gather(*tasks)
return all(results)
async def _write_range_async(self, fd: BinaryIO, start_block: int, data: bytes) -> bool:
"""Write a single range asynchronously"""
async with self.semaphore:
loop = asyncio.get_event_loop()
def write_range():
try:
offset = start_block * self.blocksize
fd.seek(offset)
fd.write(data)
return True
except Exception as e:
logger.error(f"Async write failed: {e}")
return False
return await loop.run_in_executor(None, write_range)
class BlockImageUpdate:
"""Production-ready BlockImageUpdate implementation for Python 3.13"""
BLOCKSIZE = 4096
def __init__(self, blockdev_path: str, transfer_list_path: str, new_data_path: str, patch_data_path: str, continue_on_error: bool = False):
self.blockdev_path = Path(blockdev_path)
self.transfer_list_path = Path(transfer_list_path)
self.new_data_path = Path(new_data_path)
self.patch_data_path = Path(patch_data_path)
self.image_path = self.blockdev_path
self.block_size = self.BLOCKSIZE
self.new_data_queue = queue.Queue(maxsize=20)
# 检测文件大小并配置处理策略
self.large_file_config = self._configure_large_file_handling()
# Core state
self.stash_cache = LRUStashCache(
max_items=5 if self.large_file_config.enable_streaming else 10, # Much smaller cache
max_memory_mb=min(64, self.large_file_config.memory_limit_mb // 4) # Very limited memory
)
self.written = 0
self.version = 1
self.total_blocks = 0
self.transfer_lines: List[str] = []
# REMOVE: File descriptors with streaming support
# self.new_data_fd: Optional[BinaryIO] = None
# self.patch_data_fd: Optional[BinaryIO] = None
# self.patch_data_mmap: Optional[mmap.mmap] = None
# 添加文件访问锁和流式处理状态
self.new_data_lock = threading.RLock()
self.patch_data_lock = threading.RLock()
self.streaming_state = {
'current_chunk': 0,
'total_chunks': 0,
'memory_usage': 0
}
# Platform-specific setup
self.io_settings = self._get_optimal_io_settings()
self.stash_base_dir = self._get_stash_directory()
# Enhanced threading for large files
self.new_data_queue: queue.Queue[Optional[bytes]] = queue.Queue(
maxsize=max(2, min(4, self.large_file_config.chunk_size_mb // 8)) # Very small queue
)
self.new_data_producer_thread: Optional[threading.Thread] = None
self.new_data_producer_running = threading.Event()
self.new_data_condition = threading.Condition()
# Progress tracking with memory monitoring
self._last_progress_time = time.time()
self._last_gc_time = time.time()
self.patch_stream_empty = False
# Error handling
self.continue_on_error = continue_on_error
self.failed_command_details = {}
def _configure_large_file_handling(self) -> LargeFileConfig:
"""Configure for extreme memory constraints (2GB RAM, 4-15GB files)"""
config = LargeFileConfig()
try:
available_memory_mb = psutil.virtual_memory().available // (1024 * 1024)
# Detect file sizes
file_sizes = {}
for name, path in [
('new_data', self.new_data_path),
('patch_data', self.patch_data_path),
('blockdev', self.blockdev_path)
]:
if path.exists():
size_mb = path.stat().st_size // (1024 * 1024)
file_sizes[name] = size_mb
max_file_size = max(file_sizes.values()) if file_sizes else 0
# Aggressive configuration for 2GB RAM constraint
if available_memory_mb < 3000: # Less than 3GB available
config.chunk_size_mb = 4 # Very small chunks
config.memory_limit_mb = 256 # Use only 256MB max
config.enable_streaming = True
config.gc_frequency = 1 # Very aggressive GC
config.use_mmap_threshold_mb = 20 # Use mmap for smaller files only
elif max_file_size > 4096: # >4GB files
config.chunk_size_mb = 8
config.memory_limit_mb = 512
config.enable_streaming = True
config.gc_frequency = 2
else:
config.enable_streaming = False
logger.info(f"Large file config for memory constraint: {config}")
return config
except Exception as e:
logger.warning(f"Failed to configure large file handling: {e}")
# Fallback to very conservative settings
config.chunk_size_mb = 4
config.memory_limit_mb = 256
config.enable_streaming = True
config.gc_frequency = 1
return config
def _get_optimal_io_settings(self) -> IOSettings:
"""Get platform-specific optimal I/O settings"""
if os.name == 'nt': # Windows
return IOSettings(
buffer_size=64 * 1024, # 64KB for Windows
use_direct_io=False,
sync_method='flush'
)
else: # Unix-like
return IOSettings(
buffer_size=1024 * 1024, # 1MB for Unix
use_direct_io=True,
sync_method='fsync'
)
def _get_stash_directory(self) -> Path:
"""Get platform-appropriate stash directory"""
if os.name == 'nt':
return Path(os.environ.get('TEMP', 'C:\\temp')) / 'biu_cache'
else:
return Path('/tmp/biu_cache')
@contextmanager
def _open_block_device(self, mode='rb'):
"""Context manager for opening block device with Windows WinError 6 handling"""
fd = None
try:
if os.name == 'nt':
# Windows-specific file handling with WinError 6 protection
max_retries = 3
for attempt in range(max_retries):
try:
fd = open(self.blockdev_path, mode)
break # Success
except OSError as e:
if hasattr(e, 'winerror') and e.winerror == 6: # ERROR_INVALID_HANDLE
logger.warning(f"WinError 6 on attempt {attempt + 1}, retrying...")
if attempt < max_retries - 1:
time.sleep(0.2 * (attempt + 1)) # Progressive delay
continue
raise
else:
fd = open(self.blockdev_path, mode)
yield fd
except PermissionError:
logger.error(f"Permission denied accessing {self.blockdev_path}")
if os.name == 'nt':
logger.info("Note: On Windows, you may need to run as Administrator")
raise
finally:
if fd is not None:
try:
fd.close()
except (OSError, ValueError):
pass # Ignore close errors on invalid handles
def _new_data_producer(self):
"""Producer thread with queue overflow handling"""
logger.info("New data producer thread starting")
buffer_size = self.BLOCKSIZE * 5 # 减小缓冲区以避免队列溢出
try:
with self.new_data_lock:
max_retries = 3
for attempt in range(max_retries):
fd = None
try:
fd = open(self.new_data_path, 'rb')
while self.new_data_producer_running.is_set():
data = fd.read(buffer_size)
if not data:
self.new_data_queue.put(None) # EOF signal
break
# Split into individual blocks
for i in range(0, len(data), self.BLOCKSIZE):
if not self.new_data_producer_running.is_set():
break
block = data[i:i + self.BLOCKSIZE]
if len(block) < self.BLOCKSIZE:
block = block.ljust(self.BLOCKSIZE, b'\x00')
# 增加超时时间并处理队列满的情况
try:
self.new_data_queue.put(block, timeout=10)
except queue.Full:
logger.warning("New data queue is full, waiting...")
# 等待队列有空间,避免数据丢失
time.sleep(0.1)
try:
self.new_data_queue.put(block, timeout=30)
except queue.Full:
logger.error("Queue remained full, may cause data corruption")
continue
with self.new_data_condition:
self.new_data_condition.notify_all()
break # Success, exit retry loop
except OSError as e:
if fd is not None:
try:
fd.close()
except:
pass
fd = None
if os.name == 'nt' and hasattr(e, 'winerror') and e.winerror == 6:
logger.warning(f"WinError 6 in producer thread, attempt {attempt + 1}")
if attempt < max_retries - 1:
time.sleep(0.5 * (attempt + 1))
continue
raise
finally:
if fd is not None:
try:
fd.close()
except:
pass
except Exception as e:
logger.error(f"Producer fatal error: {e}")
finally:
try:
self.new_data_queue.put(None)
except:
pass
logger.info("New data producer thread terminating")
def _restart_producer_thread(self) -> bool:
"""Restart producer thread, don't depend on global file descriptor."""
try:
# Stop existing thread if running
if self.new_data_producer_thread and self.new_data_producer_thread.is_alive():
self.new_data_producer_running.clear()
self.new_data_producer_thread.join(timeout=2)
# No need to check self.new_data_fd, just verify file exists
with self.new_data_lock:
if not self.new_data_path.exists():
logger.error("New data file is not available for restart")
return False
try:
file_size = self.new_data_path.stat().st_size
logger.info(f"Restarting producer, file size: {file_size}")
if file_size == 0:
logger.info("New data file is empty, producer may not need restart")
return True
except Exception as e:
logger.error(f"Cannot determine file size: {e}")
return False
# Restart the thread
self.new_data_producer_running.set()
self.new_data_producer_thread = threading.Thread(
target=self._new_data_producer,
daemon=True
)
self.new_data_producer_thread.start()
time.sleep(0.1)
is_alive = self.new_data_producer_thread.is_alive()
if not is_alive:
logger.error("Producer thread failed to start or died immediately")
return is_alive
except Exception as e:
logger.error(f"Failed to restart producer thread: {e}")
return False
def __enter__(self):
"""Enhanced context manager entry (Windows-safe, no global fd/mmap for big files)"""
logger.info("Initializing BlockImageUpdate")
if os.name == 'nt':
logger.warning("Running on Windows - some operations may require administrator privileges")
# Patch stream check
if self.patch_data_path.exists() and self.patch_data_path.stat().st_size == 0:
self.patch_stream_empty = True
logger.info("Patch stream is empty, will skip erase and zero commands")
self._create_empty_block_device_file()
try:
# Create stash directory and set up cache
self.stash_base_dir.mkdir(parents=True, exist_ok=True)
self.stash_cache.set_disk_cache_dir(self.stash_base_dir)
# Producer thread for new_data file (no global fd!)
if self.new_data_path.exists():
logger.info(f"Opening new data file: {self.new_data_path}")
self.new_data_file_size = self.new_data_path.stat().st_size
logger.info(f"New data file size: {self.new_data_file_size} bytes")
self.new_data_producer_running.set()
self.new_data_producer_thread = threading.Thread(
target=self._new_data_producer,
daemon=True
)
self.new_data_producer_thread.start()
time.sleep(0.1)
if not self.new_data_producer_thread.is_alive():
raise RuntimeError("Failed to start new data producer thread")
logger.info("New data producer thread started successfully")
# Patch data mmap/FD: REMOVE all global fd/mmap usage!
# If you need to mmap for small patch files (under 100M), do it in the function, not here!
# For big patch.dat: always use open/close per access (see _read_patch_bytes).
# If you want to keep a flag, just remember patch file exists and its path.
except Exception as e:
logger.error(f"Failed to initialize: {e}")
raise
return self
def _create_empty_block_device_file(self):
"""Create empty block device file when patch.dat is empty"""
try:
if self.blockdev_path.exists():
logger.info(f"Removing existing block device file: {self.blockdev_path}")
self.blockdev_path.unlink()
logger.info(f"Creating empty block device file: {self.blockdev_path}")
self.blockdev_path.touch()
logger.info("Successfully created empty block device file")
except Exception as e:
logger.error(f"Failed to create empty block device file: {e}")
raise
def _cleanup_stash(self):
"""Clean up stash files and directory with LRU cache cleanup"""
try:
# Clear the LRU cache first
self.stash_cache.clear()
logger.info("Stash cache cleared")
# Clean up any remaining files in stash directory
if self.stash_base_dir.exists():
for file_path in self.stash_base_dir.iterdir():
try:
file_path.unlink()
except Exception as e:
logger.warning(f"Failed to remove stash file {file_path}: {e}")
try:
self.stash_base_dir.rmdir()
logger.info("Stash directory cleaned up")
except OSError as e:
logger.warning(f"Failed to remove stash directory: {e}")
except Exception as e:
logger.warning(f"Failed to cleanup stash: {e}")
def _cleanup_progress_checkpoint(self):
"""Clean up progress checkpoint file after successful completion"""
try:
progress_file = self.stash_base_dir / "progress.json"
if progress_file.exists():
progress_file.unlink()
logger.info("Progress checkpoint cleaned up")
except Exception as e:
logger.warning(f"Failed to cleanup progress checkpoint: {e}")
def _skip_imgdiff_command(self, tokens: List[str], pos: int) -> int:
logger.info("Skipping imgdiff command")
return 0
def perform_command_zero(self, tokens: List[str]) -> int:
"""执行zero命令,将指定块范围填充为零"""
try:
if len(tokens) < 2:
logger.error("missing target blocks for zero")
return -1
# 解析目标范围 - 直接使用 tokens[1],因为 tokens[0] 是命令名
target_range = RangeSet(tokens[1])
total_blocks = target_range.size
logger.info(f"Zeroing {total_blocks} blocks")
# 创建单个块大小的零缓冲区
BLOCKSIZE = 4096
zero_buffer = bytes(BLOCKSIZE) # 4096字节的零数据
# 对每个范围中的每个块写入零数据
with self._open_block_device('r+b') as f:
for start_block, end_block in target_range:
for block_num in range(start_block, end_block):
offset = block_num * BLOCKSIZE
f.seek(offset)
f.write(zero_buffer)
self.written += total_blocks
return 0
except Exception as e:
logger.error(f"Failed to zero blocks: {e}")
return -1
def perform_command_new(self, tokens: List[str]) -> int:
"""Write new data with performance monitoring integration"""
if len(tokens) < 2:
logger.error("Missing target blocks for new")
return -1
try:
rangeset = RangeSet(tokens[1]) # 直接使用 tokens[1]
logger.info(f"Writing {rangeset.size} blocks of new data")
# 性能监控:数据处理开始
start_time = time.time()
# 检查生产者线程状态
if not self.new_data_producer_thread or not self.new_data_producer_thread.is_alive():
logger.warning("Producer thread not running, attempting to restart")
self._update_performance_stats('threading', 'producer_restart')
if not self._restart_producer_thread():
logger.error("Failed to restart producer thread")
return -1
# 自动扩展块设备
max_block_needed = max(end for _, end in rangeset)
required_device_size = max_block_needed * self.BLOCKSIZE
current_device_size = self.blockdev_path.stat().st_size
if current_device_size < required_device_size:
logger.info(f"Auto-expanding block device from {current_device_size} to {required_device_size} bytes")
with self._open_block_device('r+b') as f:
f.seek(0, 2)
padding_needed = required_device_size - current_device_size
f.write(b'\x00' * padding_needed)
f.flush()
with self._open_block_device('r+b') as f:
range_sink = RangeSinkState(rangeset, f, self.BLOCKSIZE)
blocks_to_write = rangeset.size
bytes_written = 0
for _ in range(blocks_to_write):
try:
data = self.new_data_queue.get(timeout=60)
if data is None: # EOF signal
logger.warning("Unexpected EOF from new data stream")
break
if len(data) != self.BLOCKSIZE:
data = data.ljust(self.BLOCKSIZE, b'\x00')
written = range_sink.write(data)
if written != self.BLOCKSIZE:
logger.error(f"Short write: expected {self.BLOCKSIZE}, got {written}")
return -1
bytes_written += written
self.new_data_queue.task_done()
except queue.Empty:
logger.error("Timeout waiting for new data")
self._update_performance_stats('threading', 'queue_overflow')
return -1
# 性能监控:数据处理完成
duration = time.time() - start_time
self._update_performance_stats('data', 'blocks_written', blocks=rangeset.size)
self._update_performance_stats('data', 'bytes_transferred', bytes=bytes_written)
self._update_performance_stats('io', 'write', bytes=bytes_written, duration=duration)
self.written += rangeset.size
return 0
except Exception as e:
logger.error(f"Failed to write new data: {e}")
self._update_performance_stats('error', error_type='new_command_failed')
return -1
def _handle_new_command(self, tokens: List[str], pos: int) -> int:
"""Handle new command"""
return self.perform_command_new(tokens)
def perform_command_diff(self, tokens: List[str], cmd_name: str) -> int:
"""Apply diff patches safely for both BSDIFF and IMGDIFF2 (including compressed-bsdiff)."""
if len(tokens) < 3:
logger.error(f"Missing patch offset/length for {cmd_name}")
return -1
try:
# 解析 offset, length
offset = int(tokens[1])
length = int(tokens[2])
# 文件总大小
total_size = self.patch_data_path.stat().st_size
logger.info(f"Reading patch @offset={offset}, length={length}, total_size={total_size}")
# 1) 读取主补丁数据(IMGDIFF2 header + chunk table + payload)
with open(self.patch_data_path, 'rb') as f:
f.seek(offset)
patch_data = f.read(length)
logger.info(f"patch_data len = {len(patch_data)}")
# 2) 读取 compressed-bsdiff 的 bonus_data(如果存在)
tail = offset + length
if tail < total_size:
with open(self.patch_data_path, 'rb') as f:
f.seek(tail)
bonus_data = f.read(total_size - tail)
else:
bonus_data = b''
logger.info(f"bonus_data size = {len(bonus_data)}")
# 3) 根据 transfer.list 版本加载源数据
pos = 3 # 已经消耗了 tokens[1]/tokens[2]
if self.version >= 3:
src_hash = tokens[pos]
tgt_hash = tokens[pos + 1]
tgt_range = tokens[pos + 2]
src_blocks = int(tokens[pos + 3])