Skip to content

Commit

Permalink
Allow custom networks feature from #6.
Browse files Browse the repository at this point in the history
Allow custom networks feature.
  • Loading branch information
touero committed Jan 1, 2024
2 parents 31d4f97 + 76317d7 commit 1658bdf
Show file tree
Hide file tree
Showing 8 changed files with 113 additions and 20 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
.gitignore
pyproject.toml
.idea/
__pycache__/
dist/
Expand Down
49 changes: 39 additions & 10 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,7 @@

## Repository Introduction
This is based on [docker-py](https://github.com/docker/docker-py?tab=readme-ov-file) which makes it easier to run your program in docker.
It can create a container based on the local image. If the image does not exist, the image will be pulled down.
If the container exists, it will be started directly. Then execute any service you want to execute in the container.
Configure your container image information more easily in python, allowing the container in docker to execute the configured program you want to execute.


## Install
Expand Down Expand Up @@ -48,14 +47,18 @@ if __name__ == '__main__':
easier_docker = EasierDocker(config)
easier_docker.start()
"""
>>> 2023-12-05 21:02:04,327 - INFO - easier-docker ==> Find docker image: [python:3.9] locally...
>>> 2023-12-05 21:02:04,330 - INFO - easier-docker ==> Image: [python:3.9] is found locally
>>> 2023-12-05 21:02:04,330 - INFO - easier-docker ==> Find docker container: [python_test] locally...
>>> 2023-12-05 21:02:04,332 - INFO - easier-docker ==> ContainerNotFound: [python_test], it will be created
>>> 2023-12-05 21:02:04,568 - INFO - easier-docker ==> Container name: [python_test] is running
>>> 2023-12-05 21:02:04,568 - INFO - easier-docker ==> Container id: [50e5ae686a9f] is running
>>> 2023-12-05 21:02:04,568 - INFO - easier-docker ==> Container ip address: []
>>> 2023-12-05 21:02:04,568 - INFO - easier-docker ==> Successfully container is running and be created at 2023-12-05T13:02:04.344804339Z
>>> 2023-12-29 15:17:31,901 - INFO - easier-docker ==> Network id: [13c5a6cb0137], name: [host]
>>> 2023-12-29 15:17:31,901 - INFO - easier-docker ==> Network id: [27d6b39aeef6], name: [none]
>>> 2023-12-29 15:17:31,901 - INFO - easier-docker ==> Network id: [2c9ae2fbfe9d], name: [bridge]
>>> 2023-12-29 15:17:31,901 - INFO - easier-docker ==> Network: [bridge] is found locally...
>>> 2023-12-29 15:17:31,901 - INFO - easier-docker ==> Find docker image: [python:3.9] locally...
>>> 2023-12-29 15:17:31,906 - INFO - easier-docker ==> Image: [python:3.9] is found locally
>>> 2023-12-29 15:17:31,906 - INFO - easier-docker ==> Find docker container: [python_test] locally...
>>> 2023-12-29 15:17:31,910 - INFO - easier-docker ==> ContainerNotFound: [python_test], it will be created
>>> 2023-12-29 15:17:34,217 - INFO - easier-docker ==> Container name: [python_test] is running
>>> 2023-12-29 15:17:34,217 - INFO - easier-docker ==> Container id: [fd7fad6e9995] is running
>>> 2023-12-29 15:17:34,217 - INFO - easier-docker ==> Container ip address: [172.17.0.2]
>>> 2023-12-29 15:17:34,217 - INFO - easier-docker ==> Successfully container is running and be created at 2023-12-29T07:17:31.912747785Z
"""
```
The content of docker_example.py is
Expand Down Expand Up @@ -94,6 +97,32 @@ command:
- sh
- -c
- cd /path/to/container && python docker_example.py

# >>> 2023-12-29 15:08:58,703 - INFO - easier-docker ==> config =
# >>> {
# >>> "image": "python:3.9",
# >>> "name": "python_test",
# >>> "volumes": {
# >>> "D:\\code-project\\EasierDocker\\example": {
# >>> "bind": "/path/to/container",
# >>> "mode": "rw"
# >>> }
# >>> },
# >>> "detach": true,
# >>> "command": [
# >>> "sh",
# >>> "-c",
# >>> "cd /path/to/container && python docker_example.py"
# >>> ]
# >>> }
# >>> 2023-12-29 15:08:58,707 - INFO - easier-docker ==> Find docker image: [python:3.9] locally...
# >>> 2023-12-29 15:08:58,724 - INFO - easier-docker ==> Image: [python:3.9] is found locally
# >>> 2023-12-29 15:08:58,725 - INFO - easier-docker ==> Find docker container: [python_test] locally...
# >>> 2023-12-29 15:08:58,730 - INFO - easier-docker ==> ContainerNotFound: [python_test], it will be created
# >>> 2023-12-29 15:09:00,989 - INFO - easier-docker ==> Container name: [python_test] is running
# >>> 2023-12-29 15:09:00,990 - INFO - easier-docker ==> Container id: [a9b642f2ddf3] is running
# >>> 2023-12-29 15:09:00,990 - INFO - easier-docker ==> Container ip address: [172.17.0.2]
# >>> 2023-12-29 15:09:00,991 - INFO - easier-docker ==> Successfully container is running and be created at 2023-12-29T07:08:58.738605891Z

```

Expand Down
7 changes: 7 additions & 0 deletions easierdocker/constants.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from enum import IntEnum, unique


@unique
class ContainerStatus(IntEnum):
RUNNING = 1 # running
EXITED = 2 # exited
17 changes: 17 additions & 0 deletions easierdocker/docker_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import time

from docker.models.containers import Container
from .log_re import log
from .constants import ContainerStatus


def check_container(container: Container) -> ContainerStatus:
for _ in range(60):
time.sleep(1)
if container.status != ContainerStatus.RUNNING.name.lower():
container.reload()
elif container.status == ContainerStatus.RUNNING.name.lower():
return ContainerStatus.RUNNING
elif container.status == ContainerStatus.EXITED.name.lower():
log(f'Container name: [{container.name}] is exited')
return ContainerStatus.EXITED
33 changes: 28 additions & 5 deletions easierdocker/easier_docker.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import docker
import json
from .exceptions import DockerConnectionError
from .log_re import log

from typing import Union
from docker.errors import ImageNotFound, APIError, DockerException
from docker.models.containers import Container
from .exceptions import DockerConnectionError
from .log_re import log
from .constants import ContainerStatus
from .docker_utils import check_container


class EasierDocker:
Expand Down Expand Up @@ -60,6 +62,9 @@ def __get_container(self) -> Union[Container, None]:
containers = self._client.containers.list(all=True)
for container in containers:
if self.container_name == container.name:
container.start()
if check_container(container) is ContainerStatus.EXITED:
return container
log(f'Container name: [{container.name}] is found locally')
log(f'Container id: [{container.short_id}] is found locally')
ip_address = container.attrs['NetworkSettings']['IPAddress']
Expand All @@ -73,6 +78,8 @@ def __get_container(self) -> Union[Container, None]:
def __run_container(self):
try:
container: Container = self._client.containers.run(**self.config)
if check_container(container) is ContainerStatus.EXITED:
return
log(f'Container name: [{container.name}] is running')
log(f'Container id: [{container.short_id}] is running')
ip_address = container.attrs['NetworkSettings']['IPAddress']
Expand All @@ -86,10 +93,26 @@ def __run_container(self):
log(f'An error occurred: {str(e)}')
raise e

def __get_all_networks(self) -> list:
networks = self._client.networks.list()
for network in networks:
log(f'Network id: [{network.short_id}], name: [{network.name}]')
return networks

def create_network(self, network_name, driver):
networks = self.__get_all_networks()
for network in networks:
if network.name == network_name:
log(f'Network: [{network_name}] is found locally...')
self._config['network'] = network_name
return
log(f'Network: [{network_name}] is not found locally, it will be created')
self._client.networks.create(network_name, driver)
log(f'Network: [{network_name}] is created')
self._config['network'] = network_name

def start(self):
self.__get_image()
container = self.__get_container()
if container:
container.start()
else:
if container is None:
self.__run_container()
16 changes: 16 additions & 0 deletions easierdocker/easier_docker.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,22 @@ class EasierDocker:
"""
...

def __get_all_networks(self) -> list:
"""
Return all the networks.
"""
...

def create_network(self, network_name: str, driver: str) -> None:
"""
Create a network.
Args:
network_name (str): The name of the network.
driver (str): The driver to be used.
"""
...

def start(self) -> None:
"""
Start the portal.
Expand Down
1 change: 1 addition & 0 deletions example/example.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,5 @@
'python docker_example.py'],
}
easier_docker = EasierDocker(config)
easier_docker.create_network('bridge', 'bridge')
easier_docker.start()
9 changes: 4 additions & 5 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,16 @@

setup(
name='easier-docker',
version='2.1.1',
version='2.2.1',
author='EnSong Wei',
author_email='[email protected]',
description='It can create a container based on the local image. If the image does not exist, the image will be '
'pulled down. If the container exists, it will be started directly. Then execute any service you want '
'to execute in the container.',
description='Configure your container image information more easily in python, allowing the container in docker '
'to execute the configured program you want to execute',
long_description=open('README.md', encoding='utf-8').read(),
long_description_content_type='text/markdown',
url='https://github.com/weiensong/easierdocker',
packages=find_packages(),
license='Apache License 2.0',
install_requires=[
'docker~=6.1.3',
'setuptools~=68.2.0',
Expand All @@ -20,7 +20,6 @@
entry_points={
'console_scripts': [
'easier-docker=easierdocker.__main__:main',

],
},
classifiers=[
Expand Down

0 comments on commit 1658bdf

Please sign in to comment.