Skip to content

Commit

Permalink
Remove useless code, simplify code, fix volume creation
Browse files Browse the repository at this point in the history
Remove the logic of getting ip information as now we always use traefik
Fix the creation of missing volume
Raise the right error message when the config is not valid
  • Loading branch information
sebastienbeau committed Oct 15, 2024
1 parent 9946aaa commit cfb645a
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 71 deletions.
7 changes: 2 additions & 5 deletions docky/cmd/run_open.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,10 +20,7 @@ class DockyExec(DockySub):
service = cli.SwitchAttr(["service"])

def _use_specific_user(self, service):
user = self.project.get_user(service)
if self.root:
user = "root"
return user
return "root" if self.root else self.project.get_user(service)

def _get_cmd_line(self, optionnal_command_line):
user = self._use_specific_user(self.service)
Expand Down Expand Up @@ -53,7 +50,7 @@ class DockyRun(DockyExec):
"""Start services and enter in your dev container"""

def _check_running(self):
if self.project.get_containers(service=self.service):
if docker.compose.ps(services=[self.service], all=True):
raise_error("This container is already running, kill it or "
"use open to go inside")

Expand Down
86 changes: 20 additions & 66 deletions docky/common/project.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

from python_on_whales import docker
from plumbum import local

import os
from .api import logger


Expand All @@ -13,92 +13,46 @@ class Project(object):
def __init__(self):
try:
self.project = docker.compose.config(return_json=True)
except:
logger.error("No docker-compose file found, create one with :")
logger.error("$ docky init")
exit(-1)
except Exception as e:
logger.error("Fail to load the configuration, try to validate it")
# If we fail to read the config file, it's mean that the config
# is not valid. In order to raise the same error as docker compose
# we launch the cmd to validate the config
os.execvpe("docker", [
"docker", "--log-level", "ERROR", "compose", "config"
], local.env)

self.name = self.project.get("name")
self.loaded_config = self.project
self.service = self._get_main_service(self.project)

def _get_main_service(self, project):
"""main_service has docky.main.service defined in
his label."""
for service in project.get("services"):
labels = project["services"][service].get("labels")
# service.labels() do not contain docky.main.service
# see also compose.service.merge_labels
if labels:
if labels.get("docky.main.service"):
return service

def get_containers(self, service=None):
kwargs = {}
if service:
kwargs["services"] = [service]
return docker.compose.ps(**kwargs)
if labels and labels.get("docky.main.service"):
return service

def display_service_tooltip(self):
infos = self._get_services_info()
for service in self.project.get("services"):
dict_service = self.project["services"].get(service)
labels = dict_service.get("labels", {})
if labels.get("docky.access.help"):
# TODO remove after some versions
logger.warning(
"'docky.access.help' is replaced by 'docky.help'. "
"Please update this key in your docker files.")
if infos.get(dict_service.get("name")):
# some applications provide extra parameters to access resource
infos[service.name] += labels.get("docky.url_suffix", "")
logger.info(infos[service.name])
if labels.get("docky.help"):
logger.info(labels.get("docky.help"))

def _get_services_info(self):
""" Search IP and Port for each services
"""
infos = {}
main_service = self._get_main_service(self.project)
for service in self.project.get("services"):
if service != main_service:
continue
serv = self.project["services"][service]
proj_key = [
x for x in serv["networks"].keys()]
proj_key = proj_key and proj_key[0] or False
if not serv["networks"]:
continue
ip = serv["networks"].get("IPAdress", "")
info = {
"name": serv["labels"].get(
"com.docker.compose.service", ""),
"ip": ip,
"port": [x for x in serv.get("ports", "")],
}
if info["name"] != "db" and info.get("port"):
urls = ["http://%s:%s" % (info["ip"], port.replace("/tcp", ""))
for port in info["port"][0]]
# There is no web app to access 'db' service: try adminer for that
infos[info["name"]] = "%s %s" % (info["name"], " ".join(urls))
return infos
for _name, service in self.project.get("services").items():
docky_help = service.get("labels", {}).get("docky.help")
if docky_help:
logger.info(docky_help)

def create_volume(self):
"""Mkdir volumes if they don't exist yet.
Only apply to external volumes.
docker-compose up do not attemps to create it
so we have to do it ourselves"""
for service in self.project.get("services"):
dict_service = self.project["services"].get(service)
for volume in dict_service.get("volumes", []):
if volume.get("external"):
path = local.path(local.env.expand(volume.external))
for service_name, service in self.project.get("services").items():
for volume in service.get("volumes", []):
if volume["type"] == "bind":
path = local.path(local.env.expand(volume["source"]))
if not path.exists():
logger.info(
"Create missing directory %s for service %s",
path, service.name)
path, service_name)
path.mkdir()

def get_user(self, service_name):
Expand Down

0 comments on commit cfb645a

Please sign in to comment.