Skip to content

Commit

Permalink
Detaching containers to observe output before stop
Browse files Browse the repository at this point in the history
  • Loading branch information
faermanj committed Nov 16, 2023
1 parent 84119e8 commit 902908b
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 7 deletions.
1 change: 0 additions & 1 deletion up_splat/up_splat/up.yaml
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# here goes some yaml
prompts:
- prompt: "splat create cluster oci-standard"
env:
Expand Down
28 changes: 23 additions & 5 deletions uplib/uplib/containers.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,16 @@
import re
import docker
import subprocess

from dataclasses import dataclass, field
from typing import TypeAlias
from .logging import log
from datetime import datetime

# https://docker-py.readthedocs.io/en/stable/containers.html
@dataclass
class ContainerRun:
# Container Configuration
name: str = field(kw_only=True, default="")
image: str = field(kw_only=True, default="")
command: list[str] = field(kw_only=True, default_factory=list)
Expand All @@ -15,7 +19,7 @@ class ContainerRun:
volumes: dict[str, str] = field(kw_only=True, default_factory=dict)
auto_remove: bool = field(kw_only=True, default=True)
network_mode: str = field(kw_only=True, default="host")
#
# Feature Flags
bash_wrap: bool = field(kw_only=True, default=False)

ContainerRuns:TypeAlias = list[ContainerRun]
Expand All @@ -32,18 +36,32 @@ def run(self, run: ContainerRun):
if (run.bash_wrap):
command = ["sh", "-c", subprocess.list2cmdline(command)]
log.debug("$: %s", run)

name = run.name if run.name else generate_container_name(run)
try:
result = client.containers.run(
container = client.containers.run(
name=name,
image=run.image,
command= command,
auto_remove=run.auto_remove)
log.info("container result: \n %s", result)
auto_remove=run.auto_remove,
detach=True)
for line in container.logs(stream=True):
line = line.decode("utf-8").strip()
log.info("%s", line)
container.wait()
log.debug("container ended.")

except Exception as e:
log.error("Failed to run container")
log.debug("%s", run)
log.error("%s", e)

_container_name_pattern = '[^a-zA-Z0-9_.-]'
def generate_container_name(run):
timestamp = datetime.now().strftime("%H%M%S")
image_name = run.image
# replace all chars not valid ([a-zA-Z0-9][a-zA-Z0-9_.-]) with _
image_name = re.sub(_container_name_pattern, '_', image_name)
return f"up-{image_name}-{timestamp}"

class Containers:
delegate = DockerContainers()
Expand Down
2 changes: 1 addition & 1 deletion uplib/uplib/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def up_main(context: Context, prompt: Prompt):

def default_container(prompt):
return ContainerRun(
image=settings().get("default_image", "fedora"),
image=Config.default_image.get(),
command=prompt)


Expand Down

0 comments on commit 902908b

Please sign in to comment.