fastled 1.1.22__py2.py3-none-any.whl → 1.1.24__py2.py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
fastled/docker_manager.py CHANGED
@@ -1,526 +1,532 @@
1
- """
2
- New abstraction for Docker management with improved Ctrl+C handling.
3
- """
4
-
5
- import _thread
6
- import subprocess
7
- import sys
8
- import threading
9
- import time
10
- import traceback
11
- import warnings
12
- from datetime import datetime, timezone
13
- from pathlib import Path
14
-
15
- import docker
16
- from appdirs import user_data_dir
17
- from disklru import DiskLRUCache
18
- from docker.client import DockerClient
19
- from docker.models.containers import Container
20
- from docker.models.images import Image
21
- from filelock import FileLock
22
-
23
- CONFIG_DIR = Path(user_data_dir("fastled", "fastled"))
24
- CONFIG_DIR.mkdir(parents=True, exist_ok=True)
25
- DB_FILE = CONFIG_DIR / "db.db"
26
- DISK_CACHE = DiskLRUCache(str(DB_FILE), 10)
27
-
28
-
29
- # Docker uses datetimes in UTC but without the timezone info. If we pass in a tz
30
- # then it will throw an exception.
31
- def _utc_now_no_tz() -> datetime:
32
- now = datetime.now(timezone.utc)
33
- return now.replace(tzinfo=None)
34
-
35
-
36
- def _win32_docker_location() -> str | None:
37
- home_dir = Path.home()
38
- out = [
39
- "C:\\Program Files\\Docker\\Docker\\Docker Desktop.exe",
40
- f"{home_dir}\\AppData\\Local\\Docker\\Docker Desktop.exe",
41
- ]
42
- for loc in out:
43
- if Path(loc).exists():
44
- return loc
45
- return None
46
-
47
-
48
- def get_lock(image_name: str) -> FileLock:
49
- """Get the file lock for this DockerManager instance."""
50
- lock_file = CONFIG_DIR / f"{image_name}.lock"
51
- return FileLock(str(lock_file))
52
-
53
-
54
- class RunningContainer:
55
- def __init__(self, container, first_run=False):
56
- self.container = container
57
- self.first_run = first_run
58
- self.running = True
59
- self.thread = threading.Thread(target=self._log_monitor)
60
- self.thread.daemon = True
61
- self.thread.start()
62
-
63
- def _log_monitor(self):
64
- from_date = _utc_now_no_tz() if not self.first_run else None
65
- to_date = _utc_now_no_tz()
66
-
67
- while self.running:
68
- try:
69
- for log in self.container.logs(
70
- follow=False, since=from_date, until=to_date, stream=True
71
- ):
72
- print(log.decode("utf-8"), end="")
73
- time.sleep(0.1)
74
- from_date = to_date
75
- to_date = _utc_now_no_tz()
76
- except KeyboardInterrupt:
77
- print("Monitoring logs interrupted by user.")
78
- _thread.interrupt_main()
79
- break
80
- except Exception as e:
81
- print(f"Error monitoring logs: {e}")
82
- break
83
-
84
- def stop(self) -> None:
85
- """Stop monitoring the container logs"""
86
- self.running = False
87
- self.thread.join()
88
-
89
-
90
- class DockerManager:
91
- def __init__(self) -> None:
92
- try:
93
- self._client: DockerClient | None = None
94
- self.first_run = False
95
- except docker.errors.DockerException as e:
96
- stack = traceback.format_exc()
97
- warnings.warn(f"Error initializing Docker client: {e}\n{stack}")
98
- raise
99
-
100
- @property
101
- def client(self) -> DockerClient:
102
- if self._client is None:
103
- self._client = docker.from_env()
104
- return self._client
105
-
106
- @staticmethod
107
- def is_docker_installed() -> bool:
108
- """Check if Docker is installed on the system."""
109
- try:
110
- subprocess.run(["docker", "--version"], capture_output=True, check=True)
111
- print("Docker is installed.")
112
- return True
113
- except subprocess.CalledProcessError as e:
114
- print(f"Docker command failed: {str(e)}")
115
- return False
116
- except FileNotFoundError:
117
- print("Docker is not installed.")
118
- return False
119
-
120
- @staticmethod
121
- def is_running() -> bool:
122
- """Check if Docker is running by pinging the Docker daemon."""
123
- if not DockerManager.is_docker_installed():
124
- return False
125
- try:
126
- # self.client.ping()
127
- client = docker.from_env()
128
- client.ping()
129
- print("Docker is running.")
130
- return True
131
- except docker.errors.DockerException as e:
132
- print(f"Docker is not running: {str(e)}")
133
- return False
134
- except Exception as e:
135
- print(f"Error pinging Docker daemon: {str(e)}")
136
- return False
137
-
138
- def start(self) -> bool:
139
- """Attempt to start Docker Desktop (or the Docker daemon) automatically."""
140
- print("Attempting to start Docker...")
141
-
142
- try:
143
- if sys.platform == "win32":
144
- docker_path = _win32_docker_location()
145
- if not docker_path:
146
- print("Docker Desktop not found.")
147
- return False
148
- subprocess.run(["start", "", docker_path], shell=True)
149
- elif sys.platform == "darwin":
150
- subprocess.run(["open", "/Applications/Docker.app"])
151
- elif sys.platform.startswith("linux"):
152
- subprocess.run(["sudo", "systemctl", "start", "docker"])
153
- else:
154
- print("Unknown platform. Cannot auto-launch Docker.")
155
- return False
156
-
157
- # Wait for Docker to start up with increasing delays
158
- print("Waiting for Docker Desktop to start...")
159
- attempts = 0
160
- max_attempts = 20 # Increased max wait time
161
- while attempts < max_attempts:
162
- attempts += 1
163
- if self.is_running():
164
- print("Docker started successfully.")
165
- return True
166
-
167
- # Gradually increase wait time between checks
168
- wait_time = min(5, 1 + attempts * 0.5)
169
- print(
170
- f"Docker not ready yet, waiting {wait_time:.1f}s... (attempt {attempts}/{max_attempts})"
171
- )
172
- time.sleep(wait_time)
173
-
174
- print("Failed to start Docker within the expected time.")
175
- print(
176
- "Please try starting Docker Desktop manually and run this command again."
177
- )
178
- except KeyboardInterrupt:
179
- print("Aborted by user.")
180
- raise
181
- except Exception as e:
182
- print(f"Error starting Docker: {str(e)}")
183
- return False
184
-
185
- def validate_or_download_image(
186
- self, image_name: str, tag: str = "latest", upgrade: bool = False
187
- ) -> None:
188
- """
189
- Validate if the image exists, and if not, download it.
190
- If upgrade is True, will pull the latest version even if image exists locally.
191
- """
192
- print(f"Validating image {image_name}:{tag}...")
193
- remote_image_hash_from_local_image: str | None = None
194
- remote_image_hash: str | None = None
195
-
196
- with get_lock(f"{image_name}-{tag}"):
197
- try:
198
- local_image = self.client.images.get(f"{image_name}:{tag}")
199
- print(f"Image {image_name}:{tag} is already available.")
200
-
201
- if upgrade:
202
- remote_image = self.client.images.get_registry_data(
203
- f"{image_name}:{tag}"
204
- )
205
- remote_image_hash = remote_image.id
206
-
207
- try:
208
- remote_image_hash_from_local_image = DISK_CACHE.get(
209
- local_image.id
210
- )
211
- except KeyboardInterrupt:
212
- raise
213
- except Exception:
214
- remote_image_hash_from_local_image = None
215
- stack = traceback.format_exc()
216
- warnings.warn(
217
- f"Error getting remote image hash from local image: {stack}"
218
- )
219
- if remote_image_hash_from_local_image == remote_image_hash:
220
- print(f"Local image {image_name}:{tag} is up to date.")
221
- return
222
-
223
- # Quick check for latest version
224
-
225
- print(f"Pulling newer version of {image_name}:{tag}...")
226
- _ = self.client.images.pull(image_name, tag=tag)
227
- print(f"Updated to newer version of {image_name}:{tag}")
228
- local_image_hash = self.client.images.get(f"{image_name}:{tag}").id
229
- if remote_image_hash is not None:
230
- DISK_CACHE.put(local_image_hash, remote_image_hash)
231
-
232
- except docker.errors.ImageNotFound:
233
- print(f"Image {image_name}:{tag} not found. Downloading...")
234
- self.client.images.pull(image_name, tag=tag)
235
- try:
236
- local_image = self.client.images.get(f"{image_name}:{tag}")
237
- local_image_hash = local_image.id
238
- print(f"Image {image_name}:{tag} downloaded successfully.")
239
- except docker.errors.ImageNotFound:
240
- warnings.warn(f"Image {image_name}:{tag} not found after download.")
241
-
242
- def tag_image(self, image_name: str, old_tag: str, new_tag: str) -> None:
243
- """
244
- Tag an image with a new tag.
245
- """
246
- image: Image = self.client.images.get(f"{image_name}:{old_tag}")
247
- image.tag(image_name, new_tag)
248
- print(f"Image {image_name}:{old_tag} tagged as {new_tag}.")
249
-
250
- def _container_configs_match(
251
- self,
252
- container: Container,
253
- command: str | None,
254
- volumes: dict | None,
255
- ports: dict | None,
256
- ) -> bool:
257
- """Compare if existing container has matching configuration"""
258
- try:
259
- # Check if container is using the same image
260
- container_image_id = container.image.id
261
- container_image_tags = container.image.tags
262
-
263
- # Simplified image comparison - just compare the IDs directly
264
- if not container_image_tags:
265
- print(f"Container using untagged image with ID: {container_image_id}")
266
- else:
267
- current_image = self.client.images.get(container_image_tags[0])
268
- if container_image_id != current_image.id:
269
- print(
270
- f"Container using different image version. Container: {container_image_id}, Current: {current_image.id}"
271
- )
272
- return False
273
-
274
- # Check command if specified
275
- if command and container.attrs["Config"]["Cmd"] != command.split():
276
- print(
277
- f"Command mismatch: {container.attrs['Config']['Cmd']} != {command}"
278
- )
279
- return False
280
-
281
- # Check volumes if specified
282
- if volumes:
283
- container_mounts = (
284
- {
285
- m["Source"]: {"bind": m["Destination"], "mode": m["Mode"]}
286
- for m in container.attrs["Mounts"]
287
- }
288
- if container.attrs.get("Mounts")
289
- else {}
290
- )
291
-
292
- for host_dir, mount in volumes.items():
293
- if host_dir not in container_mounts:
294
- print(f"Volume {host_dir} not found in container mounts.")
295
- return False
296
- if container_mounts[host_dir] != mount:
297
- print(
298
- f"Volume {host_dir} has different mount options: {container_mounts[host_dir]} != {mount}"
299
- )
300
- return False
301
-
302
- # Check ports if specified
303
- if ports:
304
- container_ports = (
305
- container.attrs["Config"]["ExposedPorts"]
306
- if container.attrs["Config"].get("ExposedPorts")
307
- else {}
308
- )
309
- container_port_bindings = (
310
- container.attrs["HostConfig"]["PortBindings"]
311
- if container.attrs["HostConfig"].get("PortBindings")
312
- else {}
313
- )
314
-
315
- for container_port, host_port in ports.items():
316
- port_key = f"{container_port}/tcp"
317
- if port_key not in container_ports:
318
- print(f"Container port {port_key} not found.")
319
- return False
320
- if not container_port_bindings.get(port_key, [{"HostPort": None}])[
321
- 0
322
- ]["HostPort"] == str(host_port):
323
- print(f"Port {host_port} is not bound to {port_key}.")
324
- return False
325
- except KeyboardInterrupt:
326
- raise
327
- except docker.errors.NotFound:
328
- print("Container not found.")
329
- return False
330
- except Exception as e:
331
- stack = traceback.format_exc()
332
- warnings.warn(f"Error checking container config: {e}\n{stack}")
333
- return False
334
- return True
335
-
336
- def run_container(
337
- self,
338
- image_name: str,
339
- tag: str,
340
- container_name: str,
341
- command: str | None = None,
342
- volumes: dict[str, dict[str, str]] | None = None,
343
- ports: dict[int, int] | None = None,
344
- ) -> Container:
345
- """
346
- Run a container from an image. If it already exists with matching config, start it.
347
- If it exists with different config, remove and recreate it.
348
-
349
- Args:
350
- volumes: Dict mapping host paths to dicts with 'bind' and 'mode' keys
351
- Example: {'/host/path': {'bind': '/container/path', 'mode': 'rw'}}
352
- ports: Dict mapping host ports to container ports
353
- Example: {8080: 80} maps host port 8080 to container port 80
354
- """
355
- image_name = f"{image_name}:{tag}"
356
- try:
357
- container: Container = self.client.containers.get(container_name)
358
-
359
- # Check if configuration matches
360
- if not self._container_configs_match(container, command, volumes, ports):
361
- print(
362
- f"Container {container_name} exists but with different configuration. Removing and recreating..."
363
- )
364
- container.remove(force=True)
365
- raise docker.errors.NotFound("Container removed due to config mismatch")
366
- print(f"Container {container_name} found with matching configuration.")
367
-
368
- # Existing container with matching config - handle various states
369
- if container.status == "running":
370
- print(f"Container {container_name} is already running.")
371
- elif container.status == "exited":
372
- print(f"Starting existing container {container_name}.")
373
- container.start()
374
- elif container.status == "restarting":
375
- print(f"Waiting for container {container_name} to restart...")
376
- timeout = 10
377
- container.wait(timeout=10)
378
- if container.status == "running":
379
- print(f"Container {container_name} has restarted.")
380
- else:
381
- print(
382
- f"Container {container_name} did not restart within {timeout} seconds."
383
- )
384
- container.stop()
385
- print(f"Container {container_name} has been stopped.")
386
- container.start()
387
- elif container.status == "paused":
388
- print(f"Resuming existing container {container_name}.")
389
- container.unpause()
390
- else:
391
- print(f"Unknown container status: {container.status}")
392
- print(f"Starting existing container {container_name}.")
393
- self.first_run = True
394
- container.start()
395
- except docker.errors.NotFound:
396
- print(f"Creating and starting {container_name}")
397
- container = self.client.containers.run(
398
- image_name,
399
- command,
400
- name=container_name,
401
- detach=True,
402
- tty=True,
403
- volumes=volumes,
404
- ports=ports,
405
- )
406
- return container
407
-
408
- def attach_and_run(self, container: Container | str) -> RunningContainer:
409
- """
410
- Attach to a running container and monitor its logs in a background thread.
411
- Returns a RunningContainer object that can be used to stop monitoring.
412
- """
413
- if isinstance(container, str):
414
- container = self.get_container(container)
415
-
416
- print(f"Attaching to container {container.name}...")
417
-
418
- first_run = self.first_run
419
- self.first_run = False
420
-
421
- return RunningContainer(container, first_run)
422
-
423
- def suspend_container(self, container: Container | str) -> None:
424
- """
425
- Suspend (pause) the container.
426
- """
427
- if isinstance(container, str):
428
- container_name = container
429
- container = self.get_container(container)
430
- if not container:
431
- print(f"Could not put container {container_name} to sleep.")
432
- return
433
- try:
434
- container.pause()
435
- print(f"Container {container.name} has been suspended.")
436
- except KeyboardInterrupt:
437
- print(f"Container {container.name} interrupted by keyboard interrupt.")
438
- except Exception as e:
439
- print(f"Failed to suspend container {container.name}: {e}")
440
-
441
- def resume_container(self, container: Container | str) -> None:
442
- """
443
- Resume (unpause) the container.
444
- """
445
- if isinstance(container, str):
446
- container = self.get_container(container)
447
- try:
448
- container.unpause()
449
- print(f"Container {container.name} has been resumed.")
450
- except Exception as e:
451
- print(f"Failed to resume container {container.name}: {e}")
452
-
453
- def get_container(self, container_name: str) -> Container:
454
- """
455
- Get a container by name.
456
- """
457
- try:
458
- return self.client.containers.get(container_name)
459
- except docker.errors.NotFound:
460
- print(f"Container {container_name} not found.")
461
- raise
462
-
463
- def is_container_running(self, container_name: str) -> bool:
464
- """
465
- Check if a container is running.
466
- """
467
- try:
468
- container = self.client.containers.get(container_name)
469
- return container.status == "running"
470
- except docker.errors.NotFound:
471
- print(f"Container {container_name} not found.")
472
- return False
473
-
474
-
475
- def main():
476
- # Register SIGINT handler
477
- # signal.signal(signal.SIGINT, handle_sigint)
478
-
479
- docker_manager = DockerManager()
480
-
481
- # Parameters
482
- image_name = "python"
483
- tag = "3.10-slim"
484
- # new_tag = "my-python"
485
- container_name = "my-python-container"
486
- command = "python -m http.server"
487
-
488
- try:
489
- # Step 1: Validate or download the image
490
- docker_manager.validate_or_download_image(image_name, tag, upgrade=True)
491
-
492
- # Step 2: Tag the image
493
- # docker_manager.tag_image(image_name, tag, new_tag)
494
-
495
- # Step 3: Run the container
496
- container = docker_manager.run_container(
497
- image_name, tag, container_name, command
498
- )
499
-
500
- # Step 4: Attach and monitor the container logs
501
- running_container = docker_manager.attach_and_run(container)
502
-
503
- # Wait for keyboard interrupt
504
- while True:
505
- time.sleep(0.1)
506
-
507
- except KeyboardInterrupt:
508
- print("\nStopping container...")
509
- running_container.stop()
510
- container = docker_manager.get_container(container_name)
511
- docker_manager.suspend_container(container)
512
-
513
- try:
514
- # Suspend and resume the container
515
- container = docker_manager.get_container(container_name)
516
- docker_manager.suspend_container(container)
517
-
518
- input("Press Enter to resume the container...")
519
-
520
- docker_manager.resume_container(container)
521
- except Exception as e:
522
- print(f"An error occurred: {e}")
523
-
524
-
525
- if __name__ == "__main__":
526
- main()
1
+ """
2
+ New abstraction for Docker management with improved Ctrl+C handling.
3
+ """
4
+
5
+ import _thread
6
+ import subprocess
7
+ import sys
8
+ import threading
9
+ import time
10
+ import traceback
11
+ import warnings
12
+ from datetime import datetime, timezone
13
+ from pathlib import Path
14
+
15
+ import docker
16
+ from appdirs import user_data_dir
17
+ from disklru import DiskLRUCache
18
+ from docker.client import DockerClient
19
+ from docker.models.containers import Container
20
+ from docker.models.images import Image
21
+ from filelock import FileLock
22
+
23
+ from fastled.spinner import Spinner
24
+
25
+ CONFIG_DIR = Path(user_data_dir("fastled", "fastled"))
26
+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)
27
+ DB_FILE = CONFIG_DIR / "db.db"
28
+ DISK_CACHE = DiskLRUCache(str(DB_FILE), 10)
29
+
30
+
31
+ # Docker uses datetimes in UTC but without the timezone info. If we pass in a tz
32
+ # then it will throw an exception.
33
+ def _utc_now_no_tz() -> datetime:
34
+ now = datetime.now(timezone.utc)
35
+ return now.replace(tzinfo=None)
36
+
37
+
38
+ def _win32_docker_location() -> str | None:
39
+ home_dir = Path.home()
40
+ out = [
41
+ "C:\\Program Files\\Docker\\Docker\\Docker Desktop.exe",
42
+ f"{home_dir}\\AppData\\Local\\Docker\\Docker Desktop.exe",
43
+ ]
44
+ for loc in out:
45
+ if Path(loc).exists():
46
+ return loc
47
+ return None
48
+
49
+
50
+ def get_lock(image_name: str) -> FileLock:
51
+ """Get the file lock for this DockerManager instance."""
52
+ lock_file = CONFIG_DIR / f"{image_name}.lock"
53
+ CONFIG_DIR.mkdir(parents=True, exist_ok=True)
54
+ print(CONFIG_DIR)
55
+ if not lock_file.parent.exists():
56
+ lock_file.parent.mkdir(parents=True, exist_ok=True)
57
+ return FileLock(str(lock_file))
58
+
59
+
60
+ class RunningContainer:
61
+ def __init__(self, container, first_run=False):
62
+ self.container = container
63
+ self.first_run = first_run
64
+ self.running = True
65
+ self.thread = threading.Thread(target=self._log_monitor)
66
+ self.thread.daemon = True
67
+ self.thread.start()
68
+
69
+ def _log_monitor(self):
70
+ from_date = _utc_now_no_tz() if not self.first_run else None
71
+ to_date = _utc_now_no_tz()
72
+
73
+ while self.running:
74
+ try:
75
+ for log in self.container.logs(
76
+ follow=False, since=from_date, until=to_date, stream=True
77
+ ):
78
+ print(log.decode("utf-8"), end="")
79
+ time.sleep(0.1)
80
+ from_date = to_date
81
+ to_date = _utc_now_no_tz()
82
+ except KeyboardInterrupt:
83
+ print("Monitoring logs interrupted by user.")
84
+ _thread.interrupt_main()
85
+ break
86
+ except Exception as e:
87
+ print(f"Error monitoring logs: {e}")
88
+ break
89
+
90
+ def stop(self) -> None:
91
+ """Stop monitoring the container logs"""
92
+ self.running = False
93
+ self.thread.join()
94
+
95
+
96
+ class DockerManager:
97
+ def __init__(self) -> None:
98
+ try:
99
+ self._client: DockerClient | None = None
100
+ self.first_run = False
101
+ except docker.errors.DockerException as e:
102
+ stack = traceback.format_exc()
103
+ warnings.warn(f"Error initializing Docker client: {e}\n{stack}")
104
+ raise
105
+
106
+ @property
107
+ def client(self) -> DockerClient:
108
+ if self._client is None:
109
+ self._client = docker.from_env()
110
+ return self._client
111
+
112
+ @staticmethod
113
+ def is_docker_installed() -> bool:
114
+ """Check if Docker is installed on the system."""
115
+ try:
116
+ subprocess.run(["docker", "--version"], capture_output=True, check=True)
117
+ print("Docker is installed.")
118
+ return True
119
+ except subprocess.CalledProcessError as e:
120
+ print(f"Docker command failed: {str(e)}")
121
+ return False
122
+ except FileNotFoundError:
123
+ print("Docker is not installed.")
124
+ return False
125
+
126
+ @staticmethod
127
+ def is_running() -> bool:
128
+ """Check if Docker is running by pinging the Docker daemon."""
129
+ if not DockerManager.is_docker_installed():
130
+ return False
131
+ try:
132
+ # self.client.ping()
133
+ client = docker.from_env()
134
+ client.ping()
135
+ print("Docker is running.")
136
+ return True
137
+ except docker.errors.DockerException as e:
138
+ print(f"Docker is not running: {str(e)}")
139
+ return False
140
+ except Exception as e:
141
+ print(f"Error pinging Docker daemon: {str(e)}")
142
+ return False
143
+
144
+ def start(self) -> bool:
145
+ """Attempt to start Docker Desktop (or the Docker daemon) automatically."""
146
+ print("Attempting to start Docker...")
147
+
148
+ try:
149
+ if sys.platform == "win32":
150
+ docker_path = _win32_docker_location()
151
+ if not docker_path:
152
+ print("Docker Desktop not found.")
153
+ return False
154
+ subprocess.run(["start", "", docker_path], shell=True)
155
+ elif sys.platform == "darwin":
156
+ subprocess.run(["open", "/Applications/Docker.app"])
157
+ elif sys.platform.startswith("linux"):
158
+ subprocess.run(["sudo", "systemctl", "start", "docker"])
159
+ else:
160
+ print("Unknown platform. Cannot auto-launch Docker.")
161
+ return False
162
+
163
+ # Wait for Docker to start up with increasing delays
164
+ print("Waiting for Docker Desktop to start...")
165
+ attempts = 0
166
+ max_attempts = 20 # Increased max wait time
167
+ while attempts < max_attempts:
168
+ attempts += 1
169
+ if self.is_running():
170
+ print("Docker started successfully.")
171
+ return True
172
+
173
+ # Gradually increase wait time between checks
174
+ wait_time = min(5, 1 + attempts * 0.5)
175
+ print(
176
+ f"Docker not ready yet, waiting {wait_time:.1f}s... (attempt {attempts}/{max_attempts})"
177
+ )
178
+ time.sleep(wait_time)
179
+
180
+ print("Failed to start Docker within the expected time.")
181
+ print(
182
+ "Please try starting Docker Desktop manually and run this command again."
183
+ )
184
+ except KeyboardInterrupt:
185
+ print("Aborted by user.")
186
+ raise
187
+ except Exception as e:
188
+ print(f"Error starting Docker: {str(e)}")
189
+ return False
190
+
191
+ def validate_or_download_image(
192
+ self, image_name: str, tag: str = "latest", upgrade: bool = False
193
+ ) -> None:
194
+ """
195
+ Validate if the image exists, and if not, download it.
196
+ If upgrade is True, will pull the latest version even if image exists locally.
197
+ """
198
+ print(f"Validating image {image_name}:{tag}...")
199
+ remote_image_hash_from_local_image: str | None = None
200
+ remote_image_hash: str | None = None
201
+
202
+ with get_lock(f"{image_name}-{tag}"):
203
+ try:
204
+ local_image = self.client.images.get(f"{image_name}:{tag}")
205
+ print(f"Image {image_name}:{tag} is already available.")
206
+
207
+ if upgrade:
208
+ remote_image = self.client.images.get_registry_data(
209
+ f"{image_name}:{tag}"
210
+ )
211
+ remote_image_hash = remote_image.id
212
+
213
+ try:
214
+ remote_image_hash_from_local_image = DISK_CACHE.get(
215
+ local_image.id
216
+ )
217
+ except KeyboardInterrupt:
218
+ raise
219
+ except Exception:
220
+ remote_image_hash_from_local_image = None
221
+ stack = traceback.format_exc()
222
+ warnings.warn(
223
+ f"Error getting remote image hash from local image: {stack}"
224
+ )
225
+ if remote_image_hash_from_local_image == remote_image_hash:
226
+ print(f"Local image {image_name}:{tag} is up to date.")
227
+ return
228
+
229
+ # Quick check for latest version
230
+ with Spinner(f"Pulling newer version of {image_name}:{tag}..."):
231
+ _ = self.client.images.pull(image_name, tag=tag)
232
+ print(f"Updated to newer version of {image_name}:{tag}")
233
+ local_image_hash = self.client.images.get(f"{image_name}:{tag}").id
234
+ if remote_image_hash is not None:
235
+ DISK_CACHE.put(local_image_hash, remote_image_hash)
236
+
237
+ except docker.errors.ImageNotFound:
238
+ print(f"Image {image_name}:{tag} not found.")
239
+ with Spinner("Loading "):
240
+ self.client.images.pull(image_name, tag=tag)
241
+ try:
242
+ local_image = self.client.images.get(f"{image_name}:{tag}")
243
+ local_image_hash = local_image.id
244
+ print(f"Image {image_name}:{tag} downloaded successfully.")
245
+ except docker.errors.ImageNotFound:
246
+ warnings.warn(f"Image {image_name}:{tag} not found after download.")
247
+
248
+ def tag_image(self, image_name: str, old_tag: str, new_tag: str) -> None:
249
+ """
250
+ Tag an image with a new tag.
251
+ """
252
+ image: Image = self.client.images.get(f"{image_name}:{old_tag}")
253
+ image.tag(image_name, new_tag)
254
+ print(f"Image {image_name}:{old_tag} tagged as {new_tag}.")
255
+
256
+ def _container_configs_match(
257
+ self,
258
+ container: Container,
259
+ command: str | None,
260
+ volumes: dict | None,
261
+ ports: dict | None,
262
+ ) -> bool:
263
+ """Compare if existing container has matching configuration"""
264
+ try:
265
+ # Check if container is using the same image
266
+ container_image_id = container.image.id
267
+ container_image_tags = container.image.tags
268
+
269
+ # Simplified image comparison - just compare the IDs directly
270
+ if not container_image_tags:
271
+ print(f"Container using untagged image with ID: {container_image_id}")
272
+ else:
273
+ current_image = self.client.images.get(container_image_tags[0])
274
+ if container_image_id != current_image.id:
275
+ print(
276
+ f"Container using different image version. Container: {container_image_id}, Current: {current_image.id}"
277
+ )
278
+ return False
279
+
280
+ # Check command if specified
281
+ if command and container.attrs["Config"]["Cmd"] != command.split():
282
+ print(
283
+ f"Command mismatch: {container.attrs['Config']['Cmd']} != {command}"
284
+ )
285
+ return False
286
+
287
+ # Check volumes if specified
288
+ if volumes:
289
+ container_mounts = (
290
+ {
291
+ m["Source"]: {"bind": m["Destination"], "mode": m["Mode"]}
292
+ for m in container.attrs["Mounts"]
293
+ }
294
+ if container.attrs.get("Mounts")
295
+ else {}
296
+ )
297
+
298
+ for host_dir, mount in volumes.items():
299
+ if host_dir not in container_mounts:
300
+ print(f"Volume {host_dir} not found in container mounts.")
301
+ return False
302
+ if container_mounts[host_dir] != mount:
303
+ print(
304
+ f"Volume {host_dir} has different mount options: {container_mounts[host_dir]} != {mount}"
305
+ )
306
+ return False
307
+
308
+ # Check ports if specified
309
+ if ports:
310
+ container_ports = (
311
+ container.attrs["Config"]["ExposedPorts"]
312
+ if container.attrs["Config"].get("ExposedPorts")
313
+ else {}
314
+ )
315
+ container_port_bindings = (
316
+ container.attrs["HostConfig"]["PortBindings"]
317
+ if container.attrs["HostConfig"].get("PortBindings")
318
+ else {}
319
+ )
320
+
321
+ for container_port, host_port in ports.items():
322
+ port_key = f"{container_port}/tcp"
323
+ if port_key not in container_ports:
324
+ print(f"Container port {port_key} not found.")
325
+ return False
326
+ if not container_port_bindings.get(port_key, [{"HostPort": None}])[
327
+ 0
328
+ ]["HostPort"] == str(host_port):
329
+ print(f"Port {host_port} is not bound to {port_key}.")
330
+ return False
331
+ except KeyboardInterrupt:
332
+ raise
333
+ except docker.errors.NotFound:
334
+ print("Container not found.")
335
+ return False
336
+ except Exception as e:
337
+ stack = traceback.format_exc()
338
+ warnings.warn(f"Error checking container config: {e}\n{stack}")
339
+ return False
340
+ return True
341
+
342
+ def run_container(
343
+ self,
344
+ image_name: str,
345
+ tag: str,
346
+ container_name: str,
347
+ command: str | None = None,
348
+ volumes: dict[str, dict[str, str]] | None = None,
349
+ ports: dict[int, int] | None = None,
350
+ ) -> Container:
351
+ """
352
+ Run a container from an image. If it already exists with matching config, start it.
353
+ If it exists with different config, remove and recreate it.
354
+
355
+ Args:
356
+ volumes: Dict mapping host paths to dicts with 'bind' and 'mode' keys
357
+ Example: {'/host/path': {'bind': '/container/path', 'mode': 'rw'}}
358
+ ports: Dict mapping host ports to container ports
359
+ Example: {8080: 80} maps host port 8080 to container port 80
360
+ """
361
+ image_name = f"{image_name}:{tag}"
362
+ try:
363
+ container: Container = self.client.containers.get(container_name)
364
+
365
+ # Check if configuration matches
366
+ if not self._container_configs_match(container, command, volumes, ports):
367
+ print(
368
+ f"Container {container_name} exists but with different configuration. Removing and recreating..."
369
+ )
370
+ container.remove(force=True)
371
+ raise docker.errors.NotFound("Container removed due to config mismatch")
372
+ print(f"Container {container_name} found with matching configuration.")
373
+
374
+ # Existing container with matching config - handle various states
375
+ if container.status == "running":
376
+ print(f"Container {container_name} is already running.")
377
+ elif container.status == "exited":
378
+ print(f"Starting existing container {container_name}.")
379
+ container.start()
380
+ elif container.status == "restarting":
381
+ print(f"Waiting for container {container_name} to restart...")
382
+ timeout = 10
383
+ container.wait(timeout=10)
384
+ if container.status == "running":
385
+ print(f"Container {container_name} has restarted.")
386
+ else:
387
+ print(
388
+ f"Container {container_name} did not restart within {timeout} seconds."
389
+ )
390
+ container.stop()
391
+ print(f"Container {container_name} has been stopped.")
392
+ container.start()
393
+ elif container.status == "paused":
394
+ print(f"Resuming existing container {container_name}.")
395
+ container.unpause()
396
+ else:
397
+ print(f"Unknown container status: {container.status}")
398
+ print(f"Starting existing container {container_name}.")
399
+ self.first_run = True
400
+ container.start()
401
+ except docker.errors.NotFound:
402
+ print(f"Creating and starting {container_name}")
403
+ container = self.client.containers.run(
404
+ image_name,
405
+ command,
406
+ name=container_name,
407
+ detach=True,
408
+ tty=True,
409
+ volumes=volumes,
410
+ ports=ports,
411
+ )
412
+ return container
413
+
414
+ def attach_and_run(self, container: Container | str) -> RunningContainer:
415
+ """
416
+ Attach to a running container and monitor its logs in a background thread.
417
+ Returns a RunningContainer object that can be used to stop monitoring.
418
+ """
419
+ if isinstance(container, str):
420
+ container = self.get_container(container)
421
+
422
+ print(f"Attaching to container {container.name}...")
423
+
424
+ first_run = self.first_run
425
+ self.first_run = False
426
+
427
+ return RunningContainer(container, first_run)
428
+
429
+ def suspend_container(self, container: Container | str) -> None:
430
+ """
431
+ Suspend (pause) the container.
432
+ """
433
+ if isinstance(container, str):
434
+ container_name = container
435
+ container = self.get_container(container)
436
+ if not container:
437
+ print(f"Could not put container {container_name} to sleep.")
438
+ return
439
+ try:
440
+ container.pause()
441
+ print(f"Container {container.name} has been suspended.")
442
+ except KeyboardInterrupt:
443
+ print(f"Container {container.name} interrupted by keyboard interrupt.")
444
+ except Exception as e:
445
+ print(f"Failed to suspend container {container.name}: {e}")
446
+
447
+ def resume_container(self, container: Container | str) -> None:
448
+ """
449
+ Resume (unpause) the container.
450
+ """
451
+ if isinstance(container, str):
452
+ container = self.get_container(container)
453
+ try:
454
+ container.unpause()
455
+ print(f"Container {container.name} has been resumed.")
456
+ except Exception as e:
457
+ print(f"Failed to resume container {container.name}: {e}")
458
+
459
+ def get_container(self, container_name: str) -> Container:
460
+ """
461
+ Get a container by name.
462
+ """
463
+ try:
464
+ return self.client.containers.get(container_name)
465
+ except docker.errors.NotFound:
466
+ print(f"Container {container_name} not found.")
467
+ raise
468
+
469
+ def is_container_running(self, container_name: str) -> bool:
470
+ """
471
+ Check if a container is running.
472
+ """
473
+ try:
474
+ container = self.client.containers.get(container_name)
475
+ return container.status == "running"
476
+ except docker.errors.NotFound:
477
+ print(f"Container {container_name} not found.")
478
+ return False
479
+
480
+
481
+ def main():
482
+ # Register SIGINT handler
483
+ # signal.signal(signal.SIGINT, handle_sigint)
484
+
485
+ docker_manager = DockerManager()
486
+
487
+ # Parameters
488
+ image_name = "python"
489
+ tag = "3.10-slim"
490
+ # new_tag = "my-python"
491
+ container_name = "my-python-container"
492
+ command = "python -m http.server"
493
+
494
+ try:
495
+ # Step 1: Validate or download the image
496
+ docker_manager.validate_or_download_image(image_name, tag, upgrade=True)
497
+
498
+ # Step 2: Tag the image
499
+ # docker_manager.tag_image(image_name, tag, new_tag)
500
+
501
+ # Step 3: Run the container
502
+ container = docker_manager.run_container(
503
+ image_name, tag, container_name, command
504
+ )
505
+
506
+ # Step 4: Attach and monitor the container logs
507
+ running_container = docker_manager.attach_and_run(container)
508
+
509
+ # Wait for keyboard interrupt
510
+ while True:
511
+ time.sleep(0.1)
512
+
513
+ except KeyboardInterrupt:
514
+ print("\nStopping container...")
515
+ running_container.stop()
516
+ container = docker_manager.get_container(container_name)
517
+ docker_manager.suspend_container(container)
518
+
519
+ try:
520
+ # Suspend and resume the container
521
+ container = docker_manager.get_container(container_name)
522
+ docker_manager.suspend_container(container)
523
+
524
+ input("Press Enter to resume the container...")
525
+
526
+ docker_manager.resume_container(container)
527
+ except Exception as e:
528
+ print(f"An error occurred: {e}")
529
+
530
+
531
+ if __name__ == "__main__":
532
+ main()