-
Notifications
You must be signed in to change notification settings - Fork 2
/
dockermanager.py
executable file
·178 lines (160 loc) · 8.23 KB
/
dockermanager.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
"""
The DockerManager handles all communication with docker api and provides an API for all actions webrob need to perform
with the docker host.
"""
import os
import traceback
import json
import docker
from docker.errors import *
from filemanager import data_container_name, knowrob_container_name, mongo_container_name, user_network_name, absolute_userpath
from utils import sysout
USER_DATA_IMAGE='knowrob/user_data'
# TODO: make configurable
KNOWROB_IMAGE_PREFIX='openease'
class DockerManager(object):
def __init__(self):
self.__client = docker.Client(base_url='unix://var/run/docker.sock',
version='1.22',
timeout=60)
try:
self.__client.pull(USER_DATA_IMAGE)
except Exception, e:
sysout("Error in DockerManager: " + str(e.message))
traceback.print_exc()
def start_user_container(self, user_name, neemHubSettings, knowrob_image, knowrob_version):
try:
all_containers = self.__client.containers(all=True)
# Stop user container if running
self.__stop_user_container__(user_name, all_containers)
# make sure the image is locally available
# TODO: manage knowrob images, delete old ones that were not used for a while
# FIXME: this overwrites any local image with this tag
#self.__client.pull(KNOWROB_IMAGE_PREFIX+'/'+knowrob_image,
# tag=knowrob_version)
# Host directory where the NEEM is located.
# This directory is mounted as volume into the dockerbridge container.
# neem_dir_local = neem_group+'/'+neem_name #+'/'+neem_version
# create user container
self.__create_user_data_container__(user_name,all_containers)
self.__create_user_network__(user_name)
self.__create_knowrob_container__(user_name,neemHubSettings,knowrob_image,knowrob_version)
except Exception, e:
sysout("Error in start_user_container: " + str(e.message))
traceback.print_exc()
def create_user_data_container(self, user_name):
try:
all_containers = self.__client.containers(all=True)
self.__create_user_data_container__(user_name, all_containers)
return True
except (APIError, DockerException), e:
sysout("Error in create_user_data_container: " + str(e.message))
traceback.print_exc()
return False
def __create_user_network__(self, user_name):
network_name = user_network_name(user_name)
if self.__client.networks(names=[network_name]) == []:
sysout("Creating "+network_name+" network.")
self.__client.create_network(name=network_name)
def __remove_user_network__(self, user_name):
network_name = user_network_name(user_name)
if not (self.__client.networks(names=[network_name]) == []):
sysout("Remove "+network_name+" network.")
self.__client.remove_network(network_name)
def __create_user_data_container__(self, user_name, all_containers):
user_data_container = data_container_name(user_name)
if self.__get_container(user_data_container, all_containers) is None:
sysout("Creating "+user_data_container+" container.")
self.__client.create_container('knowrob/user_data',
detach=True,
tty=True,
name=user_data_container,
volumes=['/etc/rosauth'],
entrypoint='true')
# TODO: start needed for volume? will exit right away, or not?
self.__client.start(user_data_container)
def __create_knowrob_container__(self, user_name, neemHubSettings, knowrob_image, knowrob_version):
knowrob_container = knowrob_container_name(user_name)
network_name = user_network_name(user_name)
user_home_dir = absolute_userpath('')
sysout("Creating user container " + knowrob_container)
parsed_json_neemHubSettings = (json.loads(neemHubSettings))
env = {"VIRTUAL_HOST": knowrob_container,
"VIRTUAL_PORT": '9090',
"KNOWROB_MONGO_USER": parsed_json_neemHubSettings['mongo_user'],
"KNOWROB_MONGO_PASS": parsed_json_neemHubSettings['mongo_pass'],
"KNOWROB_MONGO_DB": parsed_json_neemHubSettings['mongo_db'],
"KNOWROB_MONGO_HOST": parsed_json_neemHubSettings['mongo_host'],
"KNOWROB_MONGO_PORT": parsed_json_neemHubSettings['mongo_port'],
"KNOWROB_URDF_SERVER": parsed_json_neemHubSettings['urdf_server']
}
# TODO: make this configurable based on the roles of the user
limit_resources = True
if limit_resources:
mem_limit = 256 * 1024 * 1024
# default is 1024, meaning that 4 of these containers will receive the same cpu time as one default
# container. decrease this further if you want to increase the maximum amount of users on the host.
cpu_shares = 256
else:
mem_limit = 0
cpu_shares = 1024 # Default value
#
volume_bindings={
'openease_rules': {'bind': '/openease_ws/openease_rules', 'mode': 'ro'}
}
#
host_config = self.__client.create_host_config(
mem_limit=mem_limit,
memswap_limit=mem_limit*4,
binds=volume_bindings
)
# TODO: handle version tag
self.__client.create_container("openease/knowrob",
detach=True,
tty=True,
environment=env,
name=knowrob_container,
cpu_shares=cpu_shares,
host_config=host_config)
self.__client.connect_container_to_network(knowrob_container, network_name)
##
sysout("Starting user container " + knowrob_container)
volumes_from = [data_container_name(user_name)]
self.__client.start(knowrob_container,
port_bindings={9090: ('127.0.0.1',)},
volumes_from=volumes_from)
def stop_user_container(self, user_name):
try:
self.__stop_user_container__(user_name, self.__client.containers(all=True))
except (APIError, DockerException), e:
sysout("Error in stop_user_container: " + str(e.message))
def __stop_user_container__(self, user_name, all_containers):
self.__stop_container__(knowrob_container_name(user_name), all_containers)
self.__stop_container__(mongo_container_name(user_name), all_containers)
self.__remove_user_network__(user_name)
def __stop_container__(self, container_name, all_containers):
# check if containers exist:
if self.__get_container(container_name, all_containers) is not None:
sysout("Stopping container " + container_name + "...")
self.__client.stop(container_name, timeout=5)
sysout("Removing container " + container_name + "...")
self.__client.remove_container(container_name)
def get_container_ip(self, user_name):
try:
inspect = self.__client.inspect_container(knowrob_container_name(user_name))
return inspect['NetworkSettings']['IPAddress']
except (APIError, DockerException), e:
sysout("Error in get_container_ip: " + str(e.message) + "\n")
return 'error'
def container_started(self, user_name, base_image_name=None):
try:
return self.__get_container(knowrob_container_name(user_name), self.__client.containers()) is not None
except (APIError, DockerException), e:
sysout("Error in container_exists: " + str(e.message))
return False
@staticmethod
def __get_container(container_name, all_containers):
for cont in all_containers:
if cont['Names'] != None and "/" + container_name in cont['Names']:
return cont
return None