-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdocker_pull.py
More file actions
executable file
·1681 lines (1368 loc) · 59.9 KB
/
docker_pull.py
File metadata and controls
executable file
·1681 lines (1368 loc) · 59.9 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
"""
Docker Image Puller - Pure Python CLI for pulling and saving Docker images
A pure Python tool for downloading Docker images from Docker Hub without requiring
Docker itself. Perfect for air-gapped environments, corporate networks with proxies,
and transferring images between systems.
Features:
- No Docker installation required (pure Python, standard library only)
- Full corporate proxy support with authentication
- Multi-architecture support (amd64, arm64, etc.)
- SSL/TLS configuration options
- Real-time download progress tracking
- Outputs Docker-compatible tar files
Usage:
python docker_pull.py <image:tag> [options]
Examples:
python docker_pull.py ubuntu:latest
python docker_pull.py nginx:alpine --output my-nginx.tar
python docker_pull.py --arch arm64 alpine:latest
python docker_pull.py ubuntu:20.04 --proxy http://proxy:8080 --proxy-auth user:pass
Requirements:
- Python 3.6 or later
- Internet connection (or corporate network with proxy)
Copyright (c) 2025 ZacharyArthur
Licensed under the MIT License - see LICENSE file for details
"""
import argparse
import gzip
import json
import logging
import os
import re
import shutil
import signal
import socket
import ssl
import sys
import tarfile
import tempfile
import time
import traceback
import urllib.request
from datetime import datetime, timezone
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode, urlparse
from urllib.request import (
HTTPRedirectHandler,
ProxyHandler,
Request,
build_opener,
install_opener,
urlopen,
)
# Module-level logger
logger = logging.getLogger(__name__)
# =============================================================================
# UTILITY FUNCTIONS
# =============================================================================
def setup_logging(level=logging.INFO, debug=False):
"""Configure logging for the application.
Args:
level (int): Base logging level (INFO, WARNING, ERROR)
debug (bool): Enable debug logging if True
"""
# Set debug level if requested
if debug:
level = logging.DEBUG
# Configure root logger
logging.basicConfig(
level=level,
format="%(message)s", # Clean format for CLI tool
handlers=[logging.StreamHandler(sys.stdout)],
)
# Configure module logger
logger.setLevel(level)
# Suppress urllib3 warnings unless in debug mode
if not debug:
logging.getLogger("urllib3").setLevel(logging.WARNING)
# =============================================================================
# CONFIGURATION CLASSES
# =============================================================================
class Config:
"""Configuration management for Docker Image Puller"""
def __init__(
self, auth_token=None, proxy_config=None, debug=False, timeout_config=None
):
# Registry configuration
self.registry_url = "https://registry-1.docker.io"
self.auth_url = "https://auth.docker.io"
self.auth_token = auth_token
self.debug = debug
# Proxy configuration
self.proxy_config = self._validate_proxy_config(proxy_config or {})
# Timeout configuration
timeout_config = timeout_config or {}
self.request_timeout = timeout_config.get("request_timeout", 30)
self.download_timeout = timeout_config.get("download_timeout", 300)
self.chunk_timeout = timeout_config.get("chunk_timeout", 60)
# Validate configuration
self._validate_config()
def _validate_proxy_config(self, proxy_config):
"""Validate and normalize proxy configuration.
Merges provided proxy settings with environment variables.
Environment variables are used as fallback when not explicitly provided.
Args:
proxy_config (dict): User-provided proxy configuration
Returns:
dict: Validated and normalized proxy configuration
"""
# Merge environment proxy settings
if not proxy_config.get("http_proxy"):
proxy_config["http_proxy"] = os.environ.get("HTTP_PROXY") or os.environ.get(
"http_proxy"
)
if not proxy_config.get("https_proxy"):
proxy_config["https_proxy"] = os.environ.get(
"HTTPS_PROXY"
) or os.environ.get("https_proxy")
if not proxy_config.get("no_proxy"):
proxy_config["no_proxy"] = os.environ.get("NO_PROXY") or os.environ.get(
"no_proxy"
)
return proxy_config
def _validate_config(self):
"""Validate configuration values"""
if self.request_timeout <= 0:
raise ValueError("request_timeout must be positive")
if self.download_timeout <= 0:
raise ValueError("download_timeout must be positive")
if self.chunk_timeout <= 0:
raise ValueError("chunk_timeout must be positive")
def has_proxy(self):
"""Check if proxy configuration is present"""
return bool(
self.proxy_config.get("http_proxy") or self.proxy_config.get("https_proxy")
)
def get_no_proxy_list(self):
"""Get list of hosts that should bypass proxy"""
no_proxy = self.proxy_config.get("no_proxy")
if not no_proxy:
return []
return [host.strip() for host in no_proxy.split(",")]
# =============================================================================
# SUPPORT CLASSES
# =============================================================================
class ProxyManager:
"""Handles proxy configuration and URL sanitization"""
def __init__(self, config):
self.config = config
self.no_proxy_list = config.get_no_proxy_list()
self.setup_proxy()
def setup_proxy(self):
"""Configure proxy settings for urllib"""
if not self.config.has_proxy():
self._setup_no_proxy()
return
proxy_handlers = {}
logger.info("Using proxy configuration:")
http_proxy = self.config.proxy_config.get("http_proxy")
https_proxy = self.config.proxy_config.get("https_proxy")
if http_proxy:
if self.config.proxy_config.get("proxy_auth"):
http_proxy = self._add_proxy_auth(
http_proxy, self.config.proxy_config["proxy_auth"]
)
proxy_handlers["http"] = http_proxy
logger.info(f" HTTP Proxy: {self.sanitize_proxy_url(http_proxy)}")
if https_proxy:
if self.config.proxy_config.get("proxy_auth"):
https_proxy = self._add_proxy_auth(
https_proxy, self.config.proxy_config["proxy_auth"]
)
proxy_handlers["https"] = https_proxy
logger.info(f" HTTPS Proxy: {self.sanitize_proxy_url(https_proxy)}")
if self.config.proxy_config.get("no_proxy"):
logger.info(f" No Proxy: {self.config.proxy_config.get('no_proxy')}")
proxy_handler = ProxyHandler(proxy_handlers)
# Create redirect handler that strips auth headers
class NoAuthRedirectHandler(HTTPRedirectHandler):
def http_error_301(self, req, fp, code, msg, headers):
if "Authorization" in req.headers:
del req.headers["Authorization"]
return super().http_error_301(req, fp, code, msg, headers)
def http_error_302(self, req, fp, code, msg, headers):
if "Authorization" in req.headers:
del req.headers["Authorization"]
return super().http_error_302(req, fp, code, msg, headers)
def http_error_303(self, req, fp, code, msg, headers):
if "Authorization" in req.headers:
del req.headers["Authorization"]
return super().http_error_303(req, fp, code, msg, headers)
def http_error_307(self, req, fp, code, msg, headers):
if "Authorization" in req.headers:
del req.headers["Authorization"]
return super().http_error_307(req, fp, code, msg, headers)
if self.config.proxy_config.get("insecure"):
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
https_handler = urllib.request.HTTPSHandler(context=ctx)
opener = build_opener(proxy_handler, https_handler, NoAuthRedirectHandler)
logger.info(" SSL Verification: Disabled (insecure mode)")
else:
opener = build_opener(proxy_handler, NoAuthRedirectHandler)
install_opener(opener)
def _setup_no_proxy(self):
"""Setup opener without proxy"""
class NoAuthRedirectHandler(HTTPRedirectHandler):
def http_error_301(self, req, fp, code, msg, headers):
if "Authorization" in req.headers:
del req.headers["Authorization"]
return super().http_error_301(req, fp, code, msg, headers)
def http_error_302(self, req, fp, code, msg, headers):
if "Authorization" in req.headers:
del req.headers["Authorization"]
return super().http_error_302(req, fp, code, msg, headers)
def http_error_303(self, req, fp, code, msg, headers):
if "Authorization" in req.headers:
del req.headers["Authorization"]
return super().http_error_303(req, fp, code, msg, headers)
def http_error_307(self, req, fp, code, msg, headers):
if "Authorization" in req.headers:
del req.headers["Authorization"]
return super().http_error_307(req, fp, code, msg, headers)
if self.config.proxy_config.get("insecure"):
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
https_handler = urllib.request.HTTPSHandler(context=ctx)
opener = build_opener(https_handler, NoAuthRedirectHandler)
else:
opener = build_opener(NoAuthRedirectHandler)
install_opener(opener)
def _add_proxy_auth(self, proxy_url, auth_string):
"""Add authentication credentials to proxy URL.
Args:
proxy_url (str): Base proxy URL
auth_string (str): Authentication in format "username:password"
Returns:
str: Proxy URL with embedded authentication credentials
"""
if "@" in proxy_url:
return proxy_url
parsed = urlparse(proxy_url)
if ":" in auth_string:
username, password = auth_string.split(":", 1)
else:
logger.warning("Proxy authentication must be in format 'username:password'")
return proxy_url
if parsed.port:
netloc = f"{username}:{password}@{parsed.hostname}:{parsed.port}"
else:
netloc = f"{username}:{password}@{parsed.hostname}"
return f"{parsed.scheme}://{netloc}{parsed.path}"
def sanitize_proxy_url(self, url):
"""Remove credentials from proxy URL for display"""
if not url:
return url
try:
parsed = urlparse(url)
if parsed.username or parsed.password:
if parsed.port:
netloc = f"{parsed.hostname}:{parsed.port}"
else:
netloc = parsed.hostname
sanitized = f"{parsed.scheme}://{netloc}"
if parsed.path:
sanitized += parsed.path
if parsed.params:
sanitized += f";{parsed.params}"
if parsed.query:
sanitized += f"?{parsed.query}"
if parsed.fragment:
sanitized += f"#{parsed.fragment}"
return sanitized
except (ValueError, TypeError, AttributeError):
return self._mask_credentials_fallback(url)
return url
def _mask_credentials_fallback(self, text):
"""Fallback credential masking for malformed URLs or general text"""
if not text:
return text
patterns = [
r"://[^:/@]+:[^@]+@", # ://user:pass@
r"://[^:/@]+@", # ://user@
]
result = text
for pattern in patterns:
result = re.sub(pattern, "://***:***@", result)
return result
def sanitize_debug_output(self, text):
"""Sanitize any text that might contain credentials for debug output"""
if not text or not self.config.debug:
return text
return self._mask_credentials_fallback(str(text))
def should_bypass_proxy(self, hostname):
"""Check if hostname should bypass proxy"""
if not self.no_proxy_list:
return False
for no_proxy_host in self.no_proxy_list:
if no_proxy_host == "*":
return True
elif no_proxy_host.startswith(".") and hostname.endswith(no_proxy_host):
return True
elif hostname == no_proxy_host or hostname.endswith("." + no_proxy_host):
return True
return False
class ProgressReporter:
"""Enhanced progress reporting with Unicode progress bars and ETA calculation"""
def __init__(self, total_size=None, description="Download", show_speed=True):
"""Initialize progress reporter.
Args:
total_size (int, optional): Total expected size in bytes
description (str): Description to show before progress bar
show_speed (bool): Whether to show download speed and ETA
"""
self.total_size = total_size
self.downloaded = 0
self.description = description
self.show_speed = show_speed
self.start_time = self._get_time()
self.last_update = self.start_time
# Terminal width detection
self.terminal_width = self._get_terminal_width()
def _get_time(self):
"""Get current time in seconds"""
return time.time()
def _get_terminal_width(self):
"""Get terminal width, default to 80 if detection fails"""
try:
return shutil.get_terminal_size().columns
except (OSError, AttributeError):
return 80
def update(self, bytes_downloaded):
"""Update progress with new bytes downloaded.
Args:
bytes_downloaded (int): Additional bytes downloaded since last update
"""
if bytes_downloaded <= 0:
return
self.downloaded += bytes_downloaded
current_time = self._get_time()
# Throttle display updates
if current_time - self.last_update < 0.1 and self.downloaded < (
self.total_size or float("inf")
):
return
self._display_progress()
self.last_update = current_time
def _display_progress(self):
"""Display current progress bar and stats"""
# Calculate progress percentage
if self.total_size:
progress_pct = min(100.0, (self.downloaded / self.total_size) * 100)
else:
progress_pct = 0
# Format downloaded amount
downloaded_str = self._format_bytes(self.downloaded)
# Build progress bar
if self.total_size:
total_str = self._format_bytes(self.total_size)
size_info = f"{downloaded_str}/{total_str}"
progress_bar = self._build_progress_bar(progress_pct)
else:
size_info = downloaded_str
progress_bar = f"[{'█' * 10}] ???%"
# Calculate speed and ETA
speed_info = ""
if self.show_speed:
elapsed = self._get_time() - self.start_time
if elapsed > 0:
speed = self.downloaded / elapsed
speed_str = f"{self._format_bytes(speed)}/s"
if self.total_size and speed > 0:
remaining = (self.total_size - self.downloaded) / speed
eta_str = self._format_duration(remaining)
speed_info = f" | {speed_str} | ETA: {eta_str}"
else:
speed_info = f" | {speed_str}"
# Build complete progress line
progress_line = f" {self.description}: {progress_bar} {size_info}{speed_info}"
# Truncate to terminal width if needed
if len(progress_line) > self.terminal_width:
available = (
self.terminal_width
- len(f" {self.description}: ")
- len(size_info)
- len(speed_info)
- 3
)
if available > 10: # Minimum width required
progress_bar = self._build_progress_bar(progress_pct, available)
progress_line = (
f" {self.description}: {progress_bar} {size_info}{speed_info}"
)
else:
# Minimal display for narrow terminals
progress_line = f" {downloaded_str} {int(progress_pct)}%"
# Print with carriage return for overwrite
print(f"\r{progress_line}", end="", flush=True)
def _build_progress_bar(self, progress_pct, width=30):
"""Build Unicode progress bar.
Args:
progress_pct (float): Progress percentage (0-100)
width (int): Width of progress bar in characters
Returns:
str: Formatted progress bar
"""
filled_width = int(width * progress_pct / 100)
# Unicode block characters for smooth progress
filled_char = "█"
empty_char = "░"
# Create partial fill for smoother appearance
partial_progress = (width * progress_pct / 100) - filled_width
if partial_progress > 0.75:
partial_char = "▉"
elif partial_progress > 0.5:
partial_char = "▊"
elif partial_progress > 0.25:
partial_char = "▌"
elif partial_progress > 0:
partial_char = "▎"
else:
partial_char = ""
# Build the bar
bar_content = (
filled_char * filled_width
+ partial_char
+ empty_char * (width - filled_width - len(partial_char))
)
return f"[{bar_content[:width]}] {progress_pct:5.1f}%"
def _format_bytes(self, size):
"""Format bytes into human readable string.
Args:
size (int): Size in bytes
Returns:
str: Formatted size string
"""
for unit in ["B", "KB", "MB", "GB"]:
if size < 1024.0:
if unit == "B":
return f"{int(size)} {unit}"
else:
return f"{size:.1f} {unit}"
size /= 1024.0
return f"{size:.1f} TB"
def _format_duration(self, seconds):
"""Format duration into human readable string.
Args:
seconds (float): Duration in seconds
Returns:
str: Formatted duration string
"""
if seconds < 60:
return f"{int(seconds)}s"
elif seconds < 3600:
minutes = int(seconds / 60)
secs = int(seconds % 60)
return f"{minutes}m{secs:02d}s"
else:
hours = int(seconds / 3600)
minutes = int((seconds % 3600) / 60)
return f"{hours}h{minutes:02d}m"
def finish(self):
"""Complete the progress display with a newline"""
if self.downloaded > 0:
print() # New line to finish progress display
# =============================================================================
# CORE FUNCTIONALITY
# =============================================================================
class DockerImagePuller:
def __init__(
self, auth_token=None, proxy_config=None, debug=False, timeout_config=None
):
# Create configuration object
self.config = Config(auth_token, proxy_config, debug, timeout_config)
# Public API attributes - provide direct access to configuration
self.registry_url = self.config.registry_url
self.auth_url = self.config.auth_url
self.auth_token = self.config.auth_token
self.proxy_config = self.config.proxy_config
self.request_timeout = self.config.request_timeout
self.download_timeout = self.config.download_timeout
self.chunk_timeout = self.config.chunk_timeout
# Create proxy manager
self.proxy_manager = ProxyManager(self.config)
# Set up no_proxy_list for direct access
self.no_proxy_list = self.proxy_manager.no_proxy_list
def setup_proxy(self):
"""Configure proxy settings for urllib - delegated to ProxyManager"""
self.proxy_manager.setup_proxy()
def add_proxy_auth(self, proxy_url, auth_string):
"""Add authentication to proxy URL - delegated to ProxyManager"""
return self.proxy_manager._add_proxy_auth(proxy_url, auth_string)
def sanitize_proxy_url(self, url):
"""Remove credentials from proxy URL for display - delegated to ProxyManager"""
return self.proxy_manager.sanitize_proxy_url(url)
def _mask_credentials_fallback(self, text):
"""Fallback credential masking - delegated to ProxyManager"""
return self.proxy_manager._mask_credentials_fallback(text)
def sanitize_debug_output(self, text):
"""Sanitize any text that might contain credentials for debug output - delegated to ProxyManager"""
return self.proxy_manager.sanitize_debug_output(text)
def _stream_download(self, response, digest, expected_size=None):
"""Stream download with progress tracking and memory efficiency.
Downloads large blobs using streaming to avoid memory issues.
Includes enhanced progress reporting with Unicode bars and ETA.
Args:
response: HTTP response object to stream from
digest (str): Blob digest for identification in error messages
expected_size (int, optional): Expected download size in bytes
Returns:
bytes: Downloaded data, or None if download failed
Raises:
TimeoutError: If download stalls or chunk timeout exceeded
"""
# Setup timeout handling for stuck downloads
def timeout_handler(_signum, _frame):
raise TimeoutError(f"Download chunk timeout after {self.chunk_timeout}s")
# Use temporary file for streaming
temp_data = tempfile.NamedTemporaryFile(delete=False)
total_size = 0
chunk_size = 65536 # 64KB chunks
last_activity = time.time()
# Initialize progress reporter for files > 1MB
progress_reporter = None
if expected_size and expected_size > 1024 * 1024: # Over 1MB
blob_name = digest[:12] + "..." if len(digest) > 12 else digest
progress_reporter = ProgressReporter(expected_size, f"Layer {blob_name}")
try:
if hasattr(signal, "SIGALRM"): # Unix systems only
signal.signal(signal.SIGALRM, timeout_handler)
while True:
if hasattr(signal, "SIGALRM"):
signal.alarm(self.chunk_timeout)
try:
chunk = response.read(chunk_size)
if not chunk:
break
temp_data.write(chunk)
chunk_len = len(chunk)
total_size += chunk_len
last_activity = time.time()
# Update progress reporter
if progress_reporter:
progress_reporter.update(chunk_len)
elif total_size > 1024 * 1024: # Fallback for unknown size
# Fallback progress display
mb_downloaded = total_size / (1024 * 1024)
print(f" Downloaded {mb_downloaded:.1f} MB...", end="\r")
# Check for stalled downloads
if time.time() - last_activity > self.chunk_timeout:
raise TimeoutError(
f"Download stalled - no data received for {self.chunk_timeout}s"
)
except socket.timeout:
raise TimeoutError("Download chunk timeout")
finally:
if hasattr(signal, "SIGALRM"):
signal.alarm(0) # Cancel timeout
# Finish progress reporting
if progress_reporter:
progress_reporter.finish()
elif total_size > 1024 * 1024:
print() # New line after fallback progress
# Read the data back from temp file
temp_data.close()
with open(temp_data.name, "rb") as f:
data = f.read()
return data
except (TimeoutError, socket.timeout) as e:
if progress_reporter:
progress_reporter.finish()
logger.error(f"Download timeout for blob {digest}: {e}")
return None
except Exception as e:
if progress_reporter:
progress_reporter.finish()
logger.error(f"Streaming error for blob {digest}: {e}")
return None
finally:
# Cleanup
if hasattr(signal, "SIGALRM"):
signal.alarm(0)
temp_data.close()
try:
os.unlink(temp_data.name)
except OSError:
pass
def should_bypass_proxy(self, hostname):
"""Check if hostname should bypass proxy - delegated to ProxyManager"""
return self.proxy_manager.should_bypass_proxy(hostname)
def make_request(self, url, headers=None):
"""Make HTTP request with proxy handling"""
req_headers = headers or {}
logger.debug(f"Request URL: {self.sanitize_debug_output(url)}")
logger.debug(f"Headers: {self.sanitize_debug_output(req_headers)}")
# Check if we should bypass proxy for this URL
parsed_url = urlparse(url)
if self.should_bypass_proxy(parsed_url.hostname):
logger.debug(f"Bypassing proxy for {parsed_url.hostname}")
# Temporarily disable proxy for this request
old_proxies = {}
for proxy_var in ["HTTP_PROXY", "HTTPS_PROXY", "http_proxy", "https_proxy"]:
if proxy_var in os.environ:
old_proxies[proxy_var] = os.environ[proxy_var]
del os.environ[proxy_var]
try:
req = Request(url, headers=req_headers)
response = urlopen(req, timeout=self.request_timeout)
logger.debug(f"Response code: {response.code}")
return response
finally:
# Restore proxy settings
for proxy_var, value in old_proxies.items():
os.environ[proxy_var] = value
else:
req = Request(url, headers=req_headers)
response = urlopen(req, timeout=self.request_timeout)
logger.debug(f"Response code: {response.code}")
return response
def get_auth_token(self, image_name):
"""Get authentication token for Docker Hub"""
if self.auth_token:
return self.auth_token
scope = f"repository:{image_name}:pull"
params = {"service": "registry.docker.io", "scope": scope}
url = f"{self.auth_url}/token?{urlencode(params)}"
try:
with self.make_request(url) as response:
data = json.loads(response.read())
return data.get("token")
except (HTTPError, URLError) as e:
logger.error(f"Error getting auth token: {e}")
logger.info(
"If using a corporate proxy, verify proxy configuration is correct"
)
sys.exit(1)
except (json.JSONDecodeError, KeyError) as e:
logger.error(f"Error parsing auth token response: {e}")
sys.exit(1)
except Exception as e:
logger.error(f"Unexpected error getting auth token: {e}")
sys.exit(1)
def get_manifest(
self, image_name, tag, token, architecture="amd64", os_type="linux"
):
"""Get image manifest from registry, handling multi-arch manifest lists"""
url = f"{self.registry_url}/v2/{image_name}/manifests/{tag}"
# First, try to get manifest list (for multi-arch images)
headers = {
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.docker.distribution.manifest.list.v2+json,application/vnd.docker.distribution.manifest.v2+json,application/vnd.oci.image.index.v1+json,application/vnd.oci.image.manifest.v1+json",
}
try:
with self.make_request(url, headers) as response:
manifest_data = json.loads(response.read())
# Check if this is a manifest list (multi-arch)
if "manifests" in manifest_data:
logger.info(
"Multi-architecture image detected. Available platforms:"
)
# List available platforms
valid_manifests = []
for m in manifest_data["manifests"]:
platform = m.get("platform", {})
arch = platform.get("architecture", "unknown")
os = platform.get("os", "unknown")
variant = platform.get("variant", "")
# Skip invalid entries
if arch == "unknown" or os == "unknown":
continue
valid_manifests.append(m)
variant_str = f"-{variant}" if variant else ""
logger.info(f" - {os}/{arch}{variant_str}")
# Find matching manifest for requested architecture
selected_manifest = None
# First try exact match
for m in valid_manifests:
platform = m.get("platform", {})
if (
platform.get("architecture") == architecture
and platform.get("os") == os_type
):
selected_manifest = m
break
# If no exact match and looking for arm, try variants
if not selected_manifest and architecture in ["arm", "arm64"]:
for m in valid_manifests:
platform = m.get("platform", {})
p_arch = platform.get("architecture", "")
p_os = platform.get("os", "")
p_variant = platform.get("variant", "")
# Match arm variants
if p_os == os_type:
if architecture == "arm64" and (
p_arch == "arm64"
or (p_arch == "arm" and p_variant == "v8")
):
selected_manifest = m
break
elif architecture == "arm" and p_arch == "arm":
selected_manifest = m
break
if not selected_manifest and valid_manifests:
# Fallback to first available platform
logger.warning(f"No exact match for {os_type}/{architecture}")
logger.info("Using first available platform as fallback")
selected_manifest = valid_manifests[0]
platform = selected_manifest.get("platform", {})
logger.info(
f"Using: {platform.get('os')}/{platform.get('architecture')}"
)
if not selected_manifest:
logger.error("No valid manifest found")
sys.exit(1)
platform = selected_manifest.get("platform", {})
logger.info(
f"Selected platform: {platform.get('os')}/{platform.get('architecture')}"
)
# Now fetch the specific manifest using its digest
specific_digest = selected_manifest["digest"]
url = f"{self.registry_url}/v2/{image_name}/manifests/{specific_digest}"
headers = {
"Authorization": f"Bearer {token}",
"Accept": "application/vnd.docker.distribution.manifest.v2+json,application/vnd.oci.image.manifest.v1+json",
}
with self.make_request(url, headers) as response:
specific_manifest = json.loads(response.read())
# Check if we got an OCI manifest and convert if needed
if (
"mediaType" in specific_manifest
and "oci" in specific_manifest.get("mediaType", "")
):
logger.info(" (OCI format image)")
return specific_manifest
# It's already a regular manifest
elif "config" in manifest_data:
return manifest_data
# OCI format manifest
elif "mediaType" in manifest_data:
return manifest_data
# Older schema v1 manifest (deprecated but might still exist)
elif (
"schemaVersion" in manifest_data
and manifest_data["schemaVersion"] == 1
):
logger.warning("Image uses deprecated manifest schema v1")
logger.warning(
"This format is not fully supported. Image may not load correctly."
)
# Try to convert v1 to v2-like structure
return self.convert_schema_v1(manifest_data)
else:
logger.error(
f"Unknown manifest format. Keys found: {list(manifest_data.keys())}"
)
logger.error(
"Manifest content: %s",
json.dumps(manifest_data, indent=2)[:500],
)
sys.exit(1)
except HTTPError as e:
if e.code == 404:
logger.error(f"Image {image_name}:{tag} not found")
else:
logger.error(f"Error getting manifest: {e}")
try:
error_body = e.read().decode("utf-8")
if error_body:
logger.error("Error details: %s", error_body)
except (UnicodeDecodeError, AttributeError):
pass
sys.exit(1)
except (json.JSONDecodeError, KeyError) as e:
logger.error(f"Error parsing manifest response: {e}")
sys.exit(1)
except Exception as e:
logger.error(f"Unexpected error getting manifest: {e}")
traceback.print_exc()
sys.exit(1)
def convert_schema_v1(self, v1_manifest):
"""Attempt to convert schema v1 manifest to v2-like structure"""
# Best-effort v1 to v2 conversion
logger.info("Converting v1 manifest to v2 format...")
# Extract layer digests from v1 fsLayers
layers = []
if "fsLayers" in v1_manifest:
for fs_layer in v1_manifest["fsLayers"]:
layers.append(
{
"digest": fs_layer.get("blobSum", ""),
"size": 0, # v1 doesn't include size
"mediaType": "application/vnd.docker.image.rootfs.diff.tar.gzip",
}
)
# Create a minimal v2-like structure
# Note: v1 doesn't have a separate config blob
return {
"schemaVersion": 2,
"config": {
"digest": "sha256:" + "0" * 64, # Placeholder
"size": 0,
"mediaType": "application/vnd.docker.container.image.v1+json",
},
"layers": layers,
}
def download_blob(self, image_name, digest, token, retry_with_new_token=True):
"""Download a blob (layer) from Docker registry.
Handles authentication, redirects, and CDN optimization.
Automatically retries with fresh token on 401 errors.
Args:
image_name (str): Repository name (e.g., 'library/alpine')
digest (str): SHA256 digest of the blob to download
token (str): Bearer token for authentication
retry_with_new_token (bool): Retry once with fresh token on 401