fastled 1.2.23__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/__init__.py +352 -0
- fastled/app.py +107 -0
- fastled/assets/example.txt +1 -0
- fastled/cli.py +19 -0
- fastled/client_server.py +401 -0
- fastled/compile_server.py +92 -0
- fastled/compile_server_impl.py +247 -0
- fastled/docker_manager.py +784 -0
- fastled/filewatcher.py +202 -0
- fastled/keyboard.py +116 -0
- fastled/live_client.py +86 -0
- fastled/open_browser.py +161 -0
- fastled/open_browser2.py +111 -0
- fastled/parse_args.py +195 -0
- fastled/paths.py +4 -0
- fastled/project_init.py +129 -0
- fastled/select_sketch_directory.py +35 -0
- fastled/settings.py +13 -0
- fastled/site/build.py +457 -0
- fastled/sketch.py +97 -0
- fastled/spinner.py +34 -0
- fastled/string_diff.py +42 -0
- fastled/test/can_run_local_docker_tests.py +13 -0
- fastled/test/examples.py +49 -0
- fastled/types.py +61 -0
- fastled/util.py +10 -0
- fastled/web_compile.py +285 -0
- fastled-1.2.23.dist-info/LICENSE +21 -0
- fastled-1.2.23.dist-info/METADATA +382 -0
- fastled-1.2.23.dist-info/RECORD +33 -0
- fastled-1.2.23.dist-info/WHEEL +5 -0
- fastled-1.2.23.dist-info/entry_points.txt +4 -0
- fastled-1.2.23.dist-info/top_level.txt +1 -0
@@ -0,0 +1,784 @@
|
|
1
|
+
"""
|
2
|
+
New abstraction for Docker management with improved Ctrl+C handling.
|
3
|
+
"""
|
4
|
+
|
5
|
+
import _thread
|
6
|
+
import os
|
7
|
+
import platform
|
8
|
+
import subprocess
|
9
|
+
import sys
|
10
|
+
import threading
|
11
|
+
import time
|
12
|
+
import traceback
|
13
|
+
import warnings
|
14
|
+
from datetime import datetime, timezone
|
15
|
+
from pathlib import Path
|
16
|
+
|
17
|
+
import docker
|
18
|
+
from appdirs import user_data_dir
|
19
|
+
from disklru import DiskLRUCache
|
20
|
+
from docker.client import DockerClient
|
21
|
+
from docker.models.containers import Container
|
22
|
+
from docker.models.images import Image
|
23
|
+
from filelock import FileLock
|
24
|
+
|
25
|
+
from fastled.spinner import Spinner
|
26
|
+
|
27
|
+
CONFIG_DIR = Path(user_data_dir("fastled", "fastled"))
|
28
|
+
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
29
|
+
DB_FILE = CONFIG_DIR / "db.db"
|
30
|
+
DISK_CACHE = DiskLRUCache(str(DB_FILE), 10)
|
31
|
+
_IS_GITHUB = "GITHUB_ACTIONS" in os.environ
|
32
|
+
|
33
|
+
|
34
|
+
# Docker uses datetimes in UTC but without the timezone info. If we pass in a tz
|
35
|
+
# then it will throw an exception.
|
36
|
+
def _utc_now_no_tz() -> datetime:
|
37
|
+
now = datetime.now(timezone.utc)
|
38
|
+
return now.replace(tzinfo=None)
|
39
|
+
|
40
|
+
|
41
|
+
def _win32_docker_location() -> str | None:
|
42
|
+
home_dir = Path.home()
|
43
|
+
out = [
|
44
|
+
"C:\\Program Files\\Docker\\Docker\\Docker Desktop.exe",
|
45
|
+
f"{home_dir}\\AppData\\Local\\Docker\\Docker Desktop.exe",
|
46
|
+
]
|
47
|
+
for loc in out:
|
48
|
+
if Path(loc).exists():
|
49
|
+
return loc
|
50
|
+
return None
|
51
|
+
|
52
|
+
|
53
|
+
def get_lock(image_name: str) -> FileLock:
|
54
|
+
"""Get the file lock for this DockerManager instance."""
|
55
|
+
lock_file = CONFIG_DIR / f"{image_name}.lock"
|
56
|
+
CONFIG_DIR.mkdir(parents=True, exist_ok=True)
|
57
|
+
print(CONFIG_DIR)
|
58
|
+
if not lock_file.parent.exists():
|
59
|
+
lock_file.parent.mkdir(parents=True, exist_ok=True)
|
60
|
+
return FileLock(str(lock_file))
|
61
|
+
|
62
|
+
|
63
|
+
class RunningContainer:
|
64
|
+
def __init__(self, container, first_run=False):
|
65
|
+
self.container = container
|
66
|
+
self.first_run = first_run
|
67
|
+
self.running = True
|
68
|
+
self.thread = threading.Thread(target=self._log_monitor)
|
69
|
+
self.thread.daemon = True
|
70
|
+
self.thread.start()
|
71
|
+
|
72
|
+
def _log_monitor(self):
|
73
|
+
from_date = _utc_now_no_tz() if not self.first_run else None
|
74
|
+
to_date = _utc_now_no_tz()
|
75
|
+
|
76
|
+
while self.running:
|
77
|
+
try:
|
78
|
+
for log in self.container.logs(
|
79
|
+
follow=False, since=from_date, until=to_date, stream=True
|
80
|
+
):
|
81
|
+
print(log.decode("utf-8"), end="")
|
82
|
+
time.sleep(0.1)
|
83
|
+
from_date = to_date
|
84
|
+
to_date = _utc_now_no_tz()
|
85
|
+
except KeyboardInterrupt:
|
86
|
+
print("Monitoring logs interrupted by user.")
|
87
|
+
_thread.interrupt_main()
|
88
|
+
break
|
89
|
+
except Exception as e:
|
90
|
+
print(f"Error monitoring logs: {e}")
|
91
|
+
break
|
92
|
+
|
93
|
+
def detach(self) -> None:
|
94
|
+
"""Stop monitoring the container logs"""
|
95
|
+
self.running = False
|
96
|
+
self.thread.join()
|
97
|
+
|
98
|
+
|
99
|
+
class DockerManager:
|
100
|
+
def __init__(self) -> None:
|
101
|
+
from docker.errors import DockerException
|
102
|
+
|
103
|
+
try:
|
104
|
+
self._client: DockerClient | None = None
|
105
|
+
self.first_run = False
|
106
|
+
except DockerException as e:
|
107
|
+
stack = traceback.format_exc()
|
108
|
+
warnings.warn(f"Error initializing Docker client: {e}\n{stack}")
|
109
|
+
raise
|
110
|
+
|
111
|
+
@property
|
112
|
+
def client(self) -> DockerClient:
|
113
|
+
if self._client is None:
|
114
|
+
self._client = docker.from_env()
|
115
|
+
return self._client
|
116
|
+
|
117
|
+
@staticmethod
|
118
|
+
def is_docker_installed() -> bool:
|
119
|
+
"""Check if Docker is installed on the system."""
|
120
|
+
try:
|
121
|
+
subprocess.run(["docker", "--version"], capture_output=True, check=True)
|
122
|
+
print("Docker is installed.")
|
123
|
+
return True
|
124
|
+
except subprocess.CalledProcessError as e:
|
125
|
+
print(f"Docker command failed: {str(e)}")
|
126
|
+
return False
|
127
|
+
except FileNotFoundError:
|
128
|
+
print("Docker is not installed.")
|
129
|
+
return False
|
130
|
+
|
131
|
+
@staticmethod
|
132
|
+
def ensure_linux_containers_for_windows() -> bool:
|
133
|
+
"""Ensure Docker is using Linux containers on Windows."""
|
134
|
+
if sys.platform != "win32":
|
135
|
+
return True # Only needed on Windows
|
136
|
+
|
137
|
+
try:
|
138
|
+
# Check if we're already in Linux container mode
|
139
|
+
result = subprocess.run(
|
140
|
+
["docker", "info"], capture_output=True, text=True, check=True
|
141
|
+
)
|
142
|
+
|
143
|
+
if "linux" in result.stdout.lower():
|
144
|
+
print("Already using Linux containers")
|
145
|
+
return True
|
146
|
+
|
147
|
+
if not _IS_GITHUB:
|
148
|
+
answer = (
|
149
|
+
input(
|
150
|
+
"\nDocker on Windows must be in linux mode, this is a global change, switch? [y/n]"
|
151
|
+
)
|
152
|
+
.strip()
|
153
|
+
.lower()[:1]
|
154
|
+
)
|
155
|
+
if answer != "y":
|
156
|
+
return False
|
157
|
+
|
158
|
+
print("Switching to Linux containers...")
|
159
|
+
warnings.warn("Switching Docker to use Linux container context...")
|
160
|
+
|
161
|
+
# Explicitly specify the Linux container context
|
162
|
+
linux_context = "desktop-linux"
|
163
|
+
subprocess.run(
|
164
|
+
["cmd", "/c", f"docker context use {linux_context}"],
|
165
|
+
check=True,
|
166
|
+
capture_output=True,
|
167
|
+
)
|
168
|
+
|
169
|
+
# Verify the switch worked
|
170
|
+
verify = subprocess.run(
|
171
|
+
["docker", "info"], capture_output=True, text=True, check=True
|
172
|
+
)
|
173
|
+
if "linux" in verify.stdout.lower():
|
174
|
+
print(
|
175
|
+
f"Successfully switched to Linux containers using '{linux_context}' context"
|
176
|
+
)
|
177
|
+
return True
|
178
|
+
|
179
|
+
warnings.warn(
|
180
|
+
f"Failed to switch to Linux containers with context '{linux_context}': {verify.stdout}"
|
181
|
+
)
|
182
|
+
return False
|
183
|
+
|
184
|
+
except subprocess.CalledProcessError as e:
|
185
|
+
print(f"Error occurred: {e}")
|
186
|
+
return False
|
187
|
+
|
188
|
+
except subprocess.CalledProcessError as e:
|
189
|
+
print(f"Failed to switch to Linux containers: {e}")
|
190
|
+
if e.stdout:
|
191
|
+
print(f"stdout: {e.stdout}")
|
192
|
+
if e.stderr:
|
193
|
+
print(f"stderr: {e.stderr}")
|
194
|
+
return False
|
195
|
+
except Exception as e:
|
196
|
+
print(f"Unexpected error switching to Linux containers: {e}")
|
197
|
+
return False
|
198
|
+
|
199
|
+
@staticmethod
|
200
|
+
def is_running() -> bool:
|
201
|
+
"""Check if Docker is running by pinging the Docker daemon."""
|
202
|
+
if not DockerManager.is_docker_installed():
|
203
|
+
return False
|
204
|
+
try:
|
205
|
+
# self.client.ping()
|
206
|
+
client = docker.from_env()
|
207
|
+
client.ping()
|
208
|
+
print("Docker is running.")
|
209
|
+
return True
|
210
|
+
except docker.errors.DockerException as e:
|
211
|
+
print(f"Docker is not running: {str(e)}")
|
212
|
+
return False
|
213
|
+
except Exception as e:
|
214
|
+
print(f"Error pinging Docker daemon: {str(e)}")
|
215
|
+
return False
|
216
|
+
|
217
|
+
def start(self) -> bool:
|
218
|
+
"""Attempt to start Docker Desktop (or the Docker daemon) automatically."""
|
219
|
+
print("Attempting to start Docker...")
|
220
|
+
|
221
|
+
try:
|
222
|
+
if sys.platform == "win32":
|
223
|
+
docker_path = _win32_docker_location()
|
224
|
+
if not docker_path:
|
225
|
+
print("Docker Desktop not found.")
|
226
|
+
return False
|
227
|
+
subprocess.run(["start", "", docker_path], shell=True)
|
228
|
+
elif sys.platform == "darwin":
|
229
|
+
subprocess.run(["open", "/Applications/Docker.app"])
|
230
|
+
elif sys.platform.startswith("linux"):
|
231
|
+
subprocess.run(["sudo", "systemctl", "start", "docker"])
|
232
|
+
else:
|
233
|
+
print("Unknown platform. Cannot auto-launch Docker.")
|
234
|
+
return False
|
235
|
+
|
236
|
+
# Wait for Docker to start up with increasing delays
|
237
|
+
print("Waiting for Docker Desktop to start...")
|
238
|
+
attempts = 0
|
239
|
+
max_attempts = 20 # Increased max wait time
|
240
|
+
while attempts < max_attempts:
|
241
|
+
attempts += 1
|
242
|
+
if self.is_running():
|
243
|
+
print("Docker started successfully.")
|
244
|
+
return True
|
245
|
+
|
246
|
+
# Gradually increase wait time between checks
|
247
|
+
wait_time = min(5, 1 + attempts * 0.5)
|
248
|
+
print(
|
249
|
+
f"Docker not ready yet, waiting {wait_time:.1f}s... (attempt {attempts}/{max_attempts})"
|
250
|
+
)
|
251
|
+
time.sleep(wait_time)
|
252
|
+
|
253
|
+
print("Failed to start Docker within the expected time.")
|
254
|
+
print(
|
255
|
+
"Please try starting Docker Desktop manually and run this command again."
|
256
|
+
)
|
257
|
+
except KeyboardInterrupt:
|
258
|
+
print("Aborted by user.")
|
259
|
+
raise
|
260
|
+
except Exception as e:
|
261
|
+
print(f"Error starting Docker: {str(e)}")
|
262
|
+
return False
|
263
|
+
|
264
|
+
def validate_or_download_image(
|
265
|
+
self, image_name: str, tag: str = "latest", upgrade: bool = False
|
266
|
+
) -> None:
|
267
|
+
"""
|
268
|
+
Validate if the image exists, and if not, download it.
|
269
|
+
If upgrade is True, will pull the latest version even if image exists locally.
|
270
|
+
"""
|
271
|
+
ok = DockerManager.ensure_linux_containers_for_windows()
|
272
|
+
if not ok:
|
273
|
+
warnings.warn(
|
274
|
+
"Failed to ensure Linux containers on Windows. This build may fail."
|
275
|
+
)
|
276
|
+
print(f"Validating image {image_name}:{tag}...")
|
277
|
+
remote_image_hash_from_local_image: str | None = None
|
278
|
+
remote_image_hash: str | None = None
|
279
|
+
|
280
|
+
with get_lock(f"{image_name}-{tag}"):
|
281
|
+
try:
|
282
|
+
local_image = self.client.images.get(f"{image_name}:{tag}")
|
283
|
+
print(f"Image {image_name}:{tag} is already available.")
|
284
|
+
|
285
|
+
if upgrade:
|
286
|
+
remote_image = self.client.images.get_registry_data(
|
287
|
+
f"{image_name}:{tag}"
|
288
|
+
)
|
289
|
+
remote_image_hash = remote_image.id
|
290
|
+
|
291
|
+
try:
|
292
|
+
remote_image_hash_from_local_image = DISK_CACHE.get(
|
293
|
+
local_image.id
|
294
|
+
)
|
295
|
+
except KeyboardInterrupt:
|
296
|
+
raise
|
297
|
+
except Exception:
|
298
|
+
remote_image_hash_from_local_image = None
|
299
|
+
stack = traceback.format_exc()
|
300
|
+
warnings.warn(
|
301
|
+
f"Error getting remote image hash from local image: {stack}"
|
302
|
+
)
|
303
|
+
if remote_image_hash_from_local_image == remote_image_hash:
|
304
|
+
print(f"Local image {image_name}:{tag} is up to date.")
|
305
|
+
return
|
306
|
+
|
307
|
+
# Quick check for latest version
|
308
|
+
with Spinner(f"Pulling newer version of {image_name}:{tag}..."):
|
309
|
+
# This needs to be swapped out using the the command line interface AI!
|
310
|
+
# _ = self.client.images.pull(image_name, tag=tag)
|
311
|
+
cmd_list = ["docker", "pull", f"{image_name}:{tag}"]
|
312
|
+
cmd_str = subprocess.list2cmdline(cmd_list)
|
313
|
+
print(f"Running command: {cmd_str}")
|
314
|
+
subprocess.run(cmd_list, check=True)
|
315
|
+
print(f"Updated to newer version of {image_name}:{tag}")
|
316
|
+
local_image_hash = self.client.images.get(f"{image_name}:{tag}").id
|
317
|
+
if remote_image_hash is not None:
|
318
|
+
DISK_CACHE.put(local_image_hash, remote_image_hash)
|
319
|
+
|
320
|
+
except docker.errors.ImageNotFound:
|
321
|
+
print(f"Image {image_name}:{tag} not found.")
|
322
|
+
with Spinner("Loading "):
|
323
|
+
cmd_list = ["docker", "pull", f"{image_name}:{tag}"]
|
324
|
+
cmd_str = subprocess.list2cmdline(cmd_list)
|
325
|
+
print(f"Running command: {cmd_str}")
|
326
|
+
subprocess.run(cmd_list, check=True)
|
327
|
+
try:
|
328
|
+
local_image = self.client.images.get(f"{image_name}:{tag}")
|
329
|
+
local_image_hash = local_image.id
|
330
|
+
print(f"Image {image_name}:{tag} downloaded successfully.")
|
331
|
+
except docker.errors.ImageNotFound:
|
332
|
+
warnings.warn(f"Image {image_name}:{tag} not found after download.")
|
333
|
+
|
334
|
+
def tag_image(self, image_name: str, old_tag: str, new_tag: str) -> None:
|
335
|
+
"""
|
336
|
+
Tag an image with a new tag.
|
337
|
+
"""
|
338
|
+
image: Image = self.client.images.get(f"{image_name}:{old_tag}")
|
339
|
+
image.tag(image_name, new_tag)
|
340
|
+
print(f"Image {image_name}:{old_tag} tagged as {new_tag}.")
|
341
|
+
|
342
|
+
def _container_configs_match(
|
343
|
+
self,
|
344
|
+
container: Container,
|
345
|
+
command: str | None,
|
346
|
+
volumes: dict | None,
|
347
|
+
ports: dict | None,
|
348
|
+
) -> bool:
|
349
|
+
"""Compare if existing container has matching configuration"""
|
350
|
+
try:
|
351
|
+
# Check if container is using the same image
|
352
|
+
container_image_id = container.image.id
|
353
|
+
container_image_tags = container.image.tags
|
354
|
+
|
355
|
+
# Simplified image comparison - just compare the IDs directly
|
356
|
+
if not container_image_tags:
|
357
|
+
print(f"Container using untagged image with ID: {container_image_id}")
|
358
|
+
else:
|
359
|
+
current_image = self.client.images.get(container_image_tags[0])
|
360
|
+
if container_image_id != current_image.id:
|
361
|
+
print(
|
362
|
+
f"Container using different image version. Container: {container_image_id}, Current: {current_image.id}"
|
363
|
+
)
|
364
|
+
return False
|
365
|
+
|
366
|
+
# Check command if specified
|
367
|
+
if command and container.attrs["Config"]["Cmd"] != command.split():
|
368
|
+
print(
|
369
|
+
f"Command mismatch: {container.attrs['Config']['Cmd']} != {command}"
|
370
|
+
)
|
371
|
+
return False
|
372
|
+
|
373
|
+
# Check volumes if specified
|
374
|
+
if volumes:
|
375
|
+
container_mounts = (
|
376
|
+
{
|
377
|
+
m["Source"]: {"bind": m["Destination"], "mode": m["Mode"]}
|
378
|
+
for m in container.attrs["Mounts"]
|
379
|
+
}
|
380
|
+
if container.attrs.get("Mounts")
|
381
|
+
else {}
|
382
|
+
)
|
383
|
+
|
384
|
+
for host_dir, mount in volumes.items():
|
385
|
+
if host_dir not in container_mounts:
|
386
|
+
print(f"Volume {host_dir} not found in container mounts.")
|
387
|
+
return False
|
388
|
+
if container_mounts[host_dir] != mount:
|
389
|
+
print(
|
390
|
+
f"Volume {host_dir} has different mount options: {container_mounts[host_dir]} != {mount}"
|
391
|
+
)
|
392
|
+
return False
|
393
|
+
|
394
|
+
# Check ports if specified
|
395
|
+
if ports:
|
396
|
+
container_ports = (
|
397
|
+
container.attrs["Config"]["ExposedPorts"]
|
398
|
+
if container.attrs["Config"].get("ExposedPorts")
|
399
|
+
else {}
|
400
|
+
)
|
401
|
+
container_port_bindings = (
|
402
|
+
container.attrs["HostConfig"]["PortBindings"]
|
403
|
+
if container.attrs["HostConfig"].get("PortBindings")
|
404
|
+
else {}
|
405
|
+
)
|
406
|
+
|
407
|
+
for container_port, host_port in ports.items():
|
408
|
+
port_key = f"{container_port}/tcp"
|
409
|
+
if port_key not in container_ports:
|
410
|
+
print(f"Container port {port_key} not found.")
|
411
|
+
return False
|
412
|
+
if not container_port_bindings.get(port_key, [{"HostPort": None}])[
|
413
|
+
0
|
414
|
+
]["HostPort"] == str(host_port):
|
415
|
+
print(f"Port {host_port} is not bound to {port_key}.")
|
416
|
+
return False
|
417
|
+
except KeyboardInterrupt:
|
418
|
+
raise
|
419
|
+
except docker.errors.NotFound:
|
420
|
+
print("Container not found.")
|
421
|
+
return False
|
422
|
+
except Exception as e:
|
423
|
+
stack = traceback.format_exc()
|
424
|
+
warnings.warn(f"Error checking container config: {e}\n{stack}")
|
425
|
+
return False
|
426
|
+
return True
|
427
|
+
|
428
|
+
def run_container_detached(
|
429
|
+
self,
|
430
|
+
image_name: str,
|
431
|
+
tag: str,
|
432
|
+
container_name: str,
|
433
|
+
command: str | None = None,
|
434
|
+
volumes: dict[str, dict[str, str]] | None = None,
|
435
|
+
ports: dict[int, int] | None = None,
|
436
|
+
remove_previous: bool = False,
|
437
|
+
) -> Container:
|
438
|
+
"""
|
439
|
+
Run a container from an image. If it already exists with matching config, start it.
|
440
|
+
If it exists with different config, remove and recreate it.
|
441
|
+
|
442
|
+
Args:
|
443
|
+
volumes: Dict mapping host paths to dicts with 'bind' and 'mode' keys
|
444
|
+
Example: {'/host/path': {'bind': '/container/path', 'mode': 'rw'}}
|
445
|
+
ports: Dict mapping host ports to container ports
|
446
|
+
Example: {8080: 80} maps host port 8080 to container port 80
|
447
|
+
"""
|
448
|
+
image_name = f"{image_name}:{tag}"
|
449
|
+
try:
|
450
|
+
container: Container = self.client.containers.get(container_name)
|
451
|
+
|
452
|
+
if remove_previous:
|
453
|
+
print(f"Removing existing container {container_name}...")
|
454
|
+
container.remove(force=True)
|
455
|
+
raise docker.errors.NotFound("Container removed due to remove_previous")
|
456
|
+
# Check if configuration matches
|
457
|
+
elif not self._container_configs_match(container, command, volumes, ports):
|
458
|
+
print(
|
459
|
+
f"Container {container_name} exists but with different configuration. Removing and recreating..."
|
460
|
+
)
|
461
|
+
container.remove(force=True)
|
462
|
+
raise docker.errors.NotFound("Container removed due to config mismatch")
|
463
|
+
print(f"Container {container_name} found with matching configuration.")
|
464
|
+
|
465
|
+
# Existing container with matching config - handle various states
|
466
|
+
if container.status == "running":
|
467
|
+
print(f"Container {container_name} is already running.")
|
468
|
+
elif container.status == "exited":
|
469
|
+
print(f"Starting existing container {container_name}.")
|
470
|
+
container.start()
|
471
|
+
elif container.status == "restarting":
|
472
|
+
print(f"Waiting for container {container_name} to restart...")
|
473
|
+
timeout = 10
|
474
|
+
container.wait(timeout=10)
|
475
|
+
if container.status == "running":
|
476
|
+
print(f"Container {container_name} has restarted.")
|
477
|
+
else:
|
478
|
+
print(
|
479
|
+
f"Container {container_name} did not restart within {timeout} seconds."
|
480
|
+
)
|
481
|
+
container.stop(timeout=0)
|
482
|
+
print(f"Container {container_name} has been stopped.")
|
483
|
+
container.start()
|
484
|
+
elif container.status == "paused":
|
485
|
+
print(f"Resuming existing container {container_name}.")
|
486
|
+
container.unpause()
|
487
|
+
else:
|
488
|
+
print(f"Unknown container status: {container.status}")
|
489
|
+
print(f"Starting existing container {container_name}.")
|
490
|
+
self.first_run = True
|
491
|
+
container.start()
|
492
|
+
except docker.errors.NotFound:
|
493
|
+
print(f"Creating and starting {container_name}")
|
494
|
+
out_msg = f"# Running in container: {command}"
|
495
|
+
msg_len = len(out_msg)
|
496
|
+
print("\n" + "#" * msg_len)
|
497
|
+
print(out_msg)
|
498
|
+
print("#" * msg_len + "\n")
|
499
|
+
container = self.client.containers.run(
|
500
|
+
image_name,
|
501
|
+
command,
|
502
|
+
name=container_name,
|
503
|
+
detach=True,
|
504
|
+
tty=True,
|
505
|
+
volumes=volumes,
|
506
|
+
ports=ports,
|
507
|
+
remove=True,
|
508
|
+
)
|
509
|
+
return container
|
510
|
+
|
511
|
+
def run_container_interactive(
|
512
|
+
self,
|
513
|
+
image_name: str,
|
514
|
+
tag: str,
|
515
|
+
container_name: str,
|
516
|
+
command: str | None = None,
|
517
|
+
volumes: dict[str, dict[str, str]] | None = None,
|
518
|
+
ports: dict[int, int] | None = None,
|
519
|
+
) -> None:
|
520
|
+
# Remove existing container
|
521
|
+
try:
|
522
|
+
container: Container = self.client.containers.get(container_name)
|
523
|
+
container.remove(force=True)
|
524
|
+
except docker.errors.NotFound:
|
525
|
+
pass
|
526
|
+
try:
|
527
|
+
docker_command: list[str] = [
|
528
|
+
"docker",
|
529
|
+
"run",
|
530
|
+
"-it",
|
531
|
+
"--rm",
|
532
|
+
"--name",
|
533
|
+
container_name,
|
534
|
+
]
|
535
|
+
if volumes:
|
536
|
+
for host_dir, mount in volumes.items():
|
537
|
+
docker_command.extend(["-v", f"{host_dir}:{mount['bind']}"])
|
538
|
+
if ports:
|
539
|
+
for host_port, container_port in ports.items():
|
540
|
+
docker_command.extend(["-p", f"{host_port}:{container_port}"])
|
541
|
+
docker_command.append(f"{image_name}:{tag}")
|
542
|
+
if command:
|
543
|
+
docker_command.append(command)
|
544
|
+
cmd_str: str = subprocess.list2cmdline(docker_command)
|
545
|
+
print(f"Running command: {cmd_str}")
|
546
|
+
subprocess.run(docker_command, check=True)
|
547
|
+
except subprocess.CalledProcessError as e:
|
548
|
+
print(f"Error running Docker command: {e}")
|
549
|
+
raise
|
550
|
+
|
551
|
+
def attach_and_run(self, container: Container | str) -> RunningContainer:
|
552
|
+
"""
|
553
|
+
Attach to a running container and monitor its logs in a background thread.
|
554
|
+
Returns a RunningContainer object that can be used to stop monitoring.
|
555
|
+
"""
|
556
|
+
if isinstance(container, str):
|
557
|
+
container = self.get_container(container)
|
558
|
+
|
559
|
+
assert container is not None, "Container not found."
|
560
|
+
|
561
|
+
print(f"Attaching to container {container.name}...")
|
562
|
+
|
563
|
+
first_run = self.first_run
|
564
|
+
self.first_run = False
|
565
|
+
|
566
|
+
return RunningContainer(container, first_run)
|
567
|
+
|
568
|
+
def suspend_container(self, container: Container | str) -> None:
|
569
|
+
"""
|
570
|
+
Suspend (pause) the container.
|
571
|
+
"""
|
572
|
+
if isinstance(container, str):
|
573
|
+
container_name = container
|
574
|
+
container = self.get_container(container)
|
575
|
+
if not container:
|
576
|
+
print(f"Could not put container {container_name} to sleep.")
|
577
|
+
return
|
578
|
+
try:
|
579
|
+
if platform.system() == "Windows":
|
580
|
+
container.pause()
|
581
|
+
else:
|
582
|
+
container.stop()
|
583
|
+
container.remove()
|
584
|
+
print(f"Container {container.name} has been suspended.")
|
585
|
+
except KeyboardInterrupt:
|
586
|
+
print(f"Container {container.name} interrupted by keyboard interrupt.")
|
587
|
+
except Exception as e:
|
588
|
+
print(f"Failed to suspend container {container.name}: {e}")
|
589
|
+
|
590
|
+
def resume_container(self, container: Container | str) -> None:
|
591
|
+
"""
|
592
|
+
Resume (unpause) the container.
|
593
|
+
"""
|
594
|
+
if isinstance(container, str):
|
595
|
+
container = self.get_container(container)
|
596
|
+
if not container:
|
597
|
+
print(f"Could not resume container {container}.")
|
598
|
+
return
|
599
|
+
try:
|
600
|
+
container.unpause()
|
601
|
+
print(f"Container {container.name} has been resumed.")
|
602
|
+
except Exception as e:
|
603
|
+
print(f"Failed to resume container {container.name}: {e}")
|
604
|
+
|
605
|
+
def get_container(self, container_name: str) -> Container | None:
|
606
|
+
"""
|
607
|
+
Get a container by name.
|
608
|
+
"""
|
609
|
+
try:
|
610
|
+
return self.client.containers.get(container_name)
|
611
|
+
except docker.errors.NotFound:
|
612
|
+
return None
|
613
|
+
|
614
|
+
def is_container_running(self, container_name: str) -> bool:
|
615
|
+
"""
|
616
|
+
Check if a container is running.
|
617
|
+
"""
|
618
|
+
try:
|
619
|
+
container = self.client.containers.get(container_name)
|
620
|
+
return container.status == "running"
|
621
|
+
except docker.errors.NotFound:
|
622
|
+
print(f"Container {container_name} not found.")
|
623
|
+
return False
|
624
|
+
|
625
|
+
def build_image(
|
626
|
+
self,
|
627
|
+
image_name: str,
|
628
|
+
tag: str,
|
629
|
+
dockerfile_path: Path,
|
630
|
+
build_context: Path,
|
631
|
+
build_args: dict[str, str] | None = None,
|
632
|
+
platform_tag: str = "",
|
633
|
+
) -> None:
|
634
|
+
"""
|
635
|
+
Build a Docker image from a Dockerfile.
|
636
|
+
|
637
|
+
Args:
|
638
|
+
image_name: Name for the image
|
639
|
+
tag: Tag for the image
|
640
|
+
dockerfile_path: Path to the Dockerfile
|
641
|
+
build_context: Path to the build context directory
|
642
|
+
build_args: Optional dictionary of build arguments
|
643
|
+
platform_tag: Optional platform tag (e.g. "-arm64")
|
644
|
+
"""
|
645
|
+
if not dockerfile_path.exists():
|
646
|
+
raise FileNotFoundError(f"Dockerfile not found at {dockerfile_path}")
|
647
|
+
|
648
|
+
if not build_context.exists():
|
649
|
+
raise FileNotFoundError(
|
650
|
+
f"Build context directory not found at {build_context}"
|
651
|
+
)
|
652
|
+
|
653
|
+
print(f"Building Docker image {image_name}:{tag} from {dockerfile_path}")
|
654
|
+
|
655
|
+
# Prepare build arguments
|
656
|
+
buildargs = build_args or {}
|
657
|
+
if platform_tag:
|
658
|
+
buildargs["PLATFORM_TAG"] = platform_tag
|
659
|
+
|
660
|
+
try:
|
661
|
+
cmd_list = [
|
662
|
+
"docker",
|
663
|
+
"build",
|
664
|
+
"-t",
|
665
|
+
f"{image_name}:{tag}",
|
666
|
+
]
|
667
|
+
|
668
|
+
# Add build args
|
669
|
+
for arg_name, arg_value in buildargs.items():
|
670
|
+
cmd_list.extend(["--build-arg", f"{arg_name}={arg_value}"])
|
671
|
+
|
672
|
+
# Add dockerfile and context paths
|
673
|
+
cmd_list.extend(["-f", str(dockerfile_path), str(build_context)])
|
674
|
+
|
675
|
+
cmd_str = subprocess.list2cmdline(cmd_list)
|
676
|
+
print(f"Running command: {cmd_str}")
|
677
|
+
|
678
|
+
# Run the build command
|
679
|
+
# cp = subprocess.run(cmd_list, check=True, capture_output=True)
|
680
|
+
proc: subprocess.Popen = subprocess.Popen(
|
681
|
+
cmd_list, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
|
682
|
+
)
|
683
|
+
stdout = proc.stdout
|
684
|
+
assert stdout is not None, "stdout is None"
|
685
|
+
for line in iter(stdout.readline, b""):
|
686
|
+
try:
|
687
|
+
line_str = line.decode("utf-8")
|
688
|
+
print(line_str, end="")
|
689
|
+
except UnicodeDecodeError:
|
690
|
+
print("Error decoding line")
|
691
|
+
rtn = proc.wait()
|
692
|
+
if rtn != 0:
|
693
|
+
print(f"Error building Docker image: {rtn}")
|
694
|
+
raise subprocess.CalledProcessError(rtn, cmd_str)
|
695
|
+
print(f"Successfully built image {image_name}:{tag}")
|
696
|
+
|
697
|
+
except subprocess.CalledProcessError as e:
|
698
|
+
print(f"Error building Docker image: {e}")
|
699
|
+
raise
|
700
|
+
|
701
|
+
def purge(self, image_name: str) -> None:
|
702
|
+
"""
|
703
|
+
Remove all containers and images associated with the given image name.
|
704
|
+
|
705
|
+
Args:
|
706
|
+
image_name: The name of the image to purge (without tag)
|
707
|
+
"""
|
708
|
+
print(f"Purging all containers and images for {image_name}...")
|
709
|
+
|
710
|
+
# Remove all containers using this image
|
711
|
+
try:
|
712
|
+
containers = self.client.containers.list(all=True)
|
713
|
+
for container in containers:
|
714
|
+
if any(image_name in tag for tag in container.image.tags):
|
715
|
+
print(f"Removing container {container.name}")
|
716
|
+
container.remove(force=True)
|
717
|
+
|
718
|
+
except Exception as e:
|
719
|
+
print(f"Error removing containers: {e}")
|
720
|
+
|
721
|
+
# Remove all images with this name
|
722
|
+
try:
|
723
|
+
self.client.images.prune(filters={"dangling": False})
|
724
|
+
images = self.client.images.list()
|
725
|
+
for image in images:
|
726
|
+
if any(image_name in tag for tag in image.tags):
|
727
|
+
print(f"Removing image {image.tags}")
|
728
|
+
self.client.images.remove(image.id, force=True)
|
729
|
+
except Exception as e:
|
730
|
+
print(f"Error removing images: {e}")
|
731
|
+
|
732
|
+
|
733
|
+
def main():
|
734
|
+
# Register SIGINT handler
|
735
|
+
# signal.signal(signal.SIGINT, handle_sigint)
|
736
|
+
|
737
|
+
docker_manager = DockerManager()
|
738
|
+
|
739
|
+
# Parameters
|
740
|
+
image_name = "python"
|
741
|
+
tag = "3.10-slim"
|
742
|
+
# new_tag = "my-python"
|
743
|
+
container_name = "my-python-container"
|
744
|
+
command = "python -m http.server"
|
745
|
+
|
746
|
+
try:
|
747
|
+
# Step 1: Validate or download the image
|
748
|
+
docker_manager.validate_or_download_image(image_name, tag, upgrade=True)
|
749
|
+
|
750
|
+
# Step 2: Tag the image
|
751
|
+
# docker_manager.tag_image(image_name, tag, new_tag)
|
752
|
+
|
753
|
+
# Step 3: Run the container
|
754
|
+
container = docker_manager.run_container_detached(
|
755
|
+
image_name, tag, container_name, command
|
756
|
+
)
|
757
|
+
|
758
|
+
# Step 4: Attach and monitor the container logs
|
759
|
+
running_container = docker_manager.attach_and_run(container)
|
760
|
+
|
761
|
+
# Wait for keyboard interrupt
|
762
|
+
while True:
|
763
|
+
time.sleep(0.1)
|
764
|
+
|
765
|
+
except KeyboardInterrupt:
|
766
|
+
print("\nStopping container...")
|
767
|
+
running_container.stop()
|
768
|
+
container = docker_manager.get_container(container_name)
|
769
|
+
docker_manager.suspend_container(container)
|
770
|
+
|
771
|
+
try:
|
772
|
+
# Suspend and resume the container
|
773
|
+
container = docker_manager.get_container(container_name)
|
774
|
+
docker_manager.suspend_container(container)
|
775
|
+
|
776
|
+
input("Press Enter to resume the container...")
|
777
|
+
|
778
|
+
docker_manager.resume_container(container)
|
779
|
+
except Exception as e:
|
780
|
+
print(f"An error occurred: {e}")
|
781
|
+
|
782
|
+
|
783
|
+
if __name__ == "__main__":
|
784
|
+
main()
|