/
docker.py
237 lines (198 loc) · 9.03 KB
/
docker.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
# -*- coding: utf-8 -*-
#
# Copyright 2018-2022 - Swiss Data Science Center (SDSC)
# A partnership between École Polytechnique Fédérale de Lausanne (EPFL) and
# Eidgenössische Technische Hochschule Zürich (ETHZ).
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""Docker based interactive session provider."""
from pathlib import Path
from typing import Any, Dict, Iterable, List, Optional, cast
from uuid import uuid4
import docker
from renku.core import errors
from renku.core.management.client import LocalClient
from renku.core.plugin import hookimpl
from renku.core.util import communication
from renku.domain_model.session import ISessionProvider, Session
class DockerSessionProvider(ISessionProvider):
"""A docker based interactive session provider."""
JUPYTER_PORT = 8888
def __init__(self):
self._docker_client = None
def docker_client(self) -> docker.client.DockerClient:
"""Get the docker client.
Note:
This is not a @property, even though it should be, because ``pluggy``
will call it in that case in unrelated parts of the code that will
Raises:
errors.DockerError: Exception when docker is not available.
Returns:
The docker client.
"""
if self._docker_client is None:
try:
self._docker_client = docker.from_env()
except docker.errors.DockerException as e:
raise errors.DockerError(f"Error while initializing docker client: {str(e)}")
return self._docker_client
@staticmethod
def _get_jupyter_urls(ports: Dict[str, Any], auth_token: str, jupyter_port: int = 8888) -> Iterable[str]:
port_key = f"{jupyter_port}/tcp"
if port_key not in ports:
return list()
return map(lambda x: f'http://{x["HostIp"]}:{x["HostPort"]}/?token={auth_token}', ports[port_key])
def _get_docker_containers(self, project_name: str) -> List[docker.models.containers.Container]:
return self.docker_client().containers.list(filters={"label": f"renku_project={project_name}"})
def get_name(self) -> str:
"""Return session provider's name."""
return "docker"
def build_image(self, image_descriptor: Path, image_name: str, config: Optional[Dict[str, Any]]):
"""Builds the container image."""
self.docker_client().images.build(path=str(image_descriptor), tag=image_name)
def find_image(self, image_name: str, config: Optional[Dict[str, Any]]) -> bool:
"""Find the given container image."""
try:
self.docker_client().images.get(image_name)
except docker.errors.ImageNotFound:
try:
with communication.busy(msg=f"Pulling image from remote {image_name}"):
self.docker_client().images.pull(image_name)
except docker.errors.NotFound:
return False
else:
return True
else:
return True
@hookimpl
def session_provider(self) -> ISessionProvider:
"""Supported session provider.
Returns:
a reference to ``self``.
"""
return self
def session_list(self, project_name: str, config: Optional[Dict[str, Any]]) -> List[Session]:
"""Lists all the sessions currently running by the given session provider.
Returns:
list: a list of sessions.
"""
return list(
map(
lambda x: Session(
id=cast(str, x.short_id),
status=x.status,
url=next(iter(DockerSessionProvider()._get_jupyter_urls(x.ports, x.labels["jupyter_token"]))),
),
self._get_docker_containers(project_name),
)
)
def session_start(
self,
image_name: str,
project_name: str,
config: Optional[Dict[str, Any]],
client: LocalClient,
cpu_request: Optional[float] = None,
mem_request: Optional[str] = None,
disk_request: Optional[str] = None,
gpu_request: Optional[str] = None,
) -> str:
"""Creates an interactive session.
Returns:
str: a unique id for the created interactive session.
"""
try:
docker_is_running = self.docker_client().ping()
if not docker_is_running:
raise errors.DockerError(
"Could not communicate with the docker instance. Please make sure it is running!"
)
auth_token = uuid4().hex
default_url = client.get_value("interactive", "default_url")
# resource requests
resource_requests: Dict[str, Any] = dict()
if cpu_request:
# based on the docker go cli: func ParseCPUs
resource_requests["nano_cpus"] = int(cpu_request * 10**9)
if mem_request:
resource_requests["mem_limit"] = mem_request
if disk_request:
resource_requests["storage_opt"] = {"size": disk_request}
if gpu_request:
if gpu_request == "all":
resource_requests["device_requests"] = [
docker.types.DeviceRequest(count=-1, capabilities=[["compute", "utility"]])
]
else:
resource_requests["device_requests"] = [
docker.types.DeviceRequest(count=[gpu_request], capabilities=[["compute", "utility"]])
]
# NOTE: set git user
image_data = self.docker_client().api.inspect_image(image_name)
working_dir = image_data.get("Config", {}).get("WorkingDir", None)
if working_dir is None:
working_dir = "/home/jovyan"
work_dir = Path(working_dir) / "work" / project_name.split("/")[-1]
volumes = [f"{str(client.path.resolve())}:{work_dir}"]
user = client.repository.get_user()
environment = {
"GIT_AUTHOR_NAME": user.name,
"GIT_AUTHOR_EMAIL": user.email,
"GIT_COMMITTER_EMAIL": user.email,
"EMAIL": user.email,
}
container = self.docker_client().containers.run(
image_name,
f'jupyter notebook --NotebookApp.ip="0.0.0.0" --NotebookApp.port={DockerSessionProvider.JUPYTER_PORT}'
f' --NotebookApp.token="{auth_token}" --NotebookApp.default_url="{default_url}"'
f" --NotebookApp.notebook_dir={work_dir}",
detach=True,
labels={"renku_project": project_name, "jupyter_token": auth_token},
ports={f"{DockerSessionProvider.JUPYTER_PORT}/tcp": None},
remove=True,
environment=environment,
volumes=volumes,
working_dir=str(work_dir),
**resource_requests,
)
if not container.ports:
container.reload()
jupyter_urls = DockerSessionProvider._get_jupyter_urls(
container.ports, auth_token, jupyter_port=DockerSessionProvider.JUPYTER_PORT
)
message = f"The session for '{image_name}' has been successfully started. It is available at:\n\t"
message += "\n\t".join(jupyter_urls)
return message
except (docker.errors.APIError, docker.errors.BuildError) as error:
raise errors.DockerError(str(error))
def session_stop(self, project_name: str, session_name: Optional[str], stop_all: bool) -> bool:
"""Stops all or a given interactive session."""
try:
docker_containers = (
self._get_docker_containers(project_name)
if stop_all
else self.docker_client().containers.list(filters={"id": session_name})
)
if len(docker_containers) == 0:
return False
[c.stop() for c in docker_containers]
return True
except docker.errors.APIError as error:
raise errors.DockerError(error.msg)
def session_url(self, session_name: str) -> Optional[str]:
"""Get the URL of the interactive session."""
for c in self.docker_client().containers.list():
if c.short_id == session_name and f"{DockerSessionProvider.JUPYTER_PORT}/tcp" in c.ports:
host = c.ports[f"{DockerSessionProvider.JUPYTER_PORT}/tcp"][0]
return f'http://{host["HostIp"]}:{host["HostPort"]}/?token={c.labels["jupyter_token"]}'
return None