Skip to content

Commit e2233fc

Browse files
committed
* Moved _container_config to utils.create_container_config
* memswap_limit can now be provided as a string, similar to mem_limit
1 parent c5f4c7e commit e2233fc

File tree

3 files changed

+147
-134
lines changed

3 files changed

+147
-134
lines changed

docker/client.py

Lines changed: 5 additions & 133 deletions
Original file line numberDiff line numberDiff line change
@@ -105,134 +105,6 @@ def _result(self, response, json=False, binary=False):
105105
return response.content
106106
return response.text
107107

108-
def _container_config(self, image, command, hostname=None, user=None,
109-
detach=False, stdin_open=False, tty=False,
110-
mem_limit=0, ports=None, environment=None, dns=None,
111-
volumes=None, volumes_from=None,
112-
network_disabled=False, entrypoint=None,
113-
cpu_shares=None, working_dir=None,
114-
domainname=None, memswap_limit=0, cpuset=None,
115-
host_config=None, mac_address=None):
116-
if isinstance(command, six.string_types):
117-
command = shlex.split(str(command))
118-
if isinstance(environment, dict):
119-
environment = [
120-
six.text_type('{0}={1}').format(k, v)
121-
for k, v in six.iteritems(environment)
122-
]
123-
124-
if isinstance(mem_limit, six.string_types):
125-
if len(mem_limit) == 0:
126-
mem_limit = 0
127-
else:
128-
units = {'b': 1,
129-
'k': 1024,
130-
'm': 1024 * 1024,
131-
'g': 1024 * 1024 * 1024}
132-
suffix = mem_limit[-1].lower()
133-
134-
# Check if the variable is a string representation of an int
135-
# without a units part. Assuming that the units are bytes.
136-
if suffix.isdigit():
137-
digits_part = mem_limit
138-
suffix = 'b'
139-
else:
140-
digits_part = mem_limit[:-1]
141-
142-
if suffix in units.keys() or suffix.isdigit():
143-
try:
144-
digits = int(digits_part)
145-
except ValueError:
146-
message = ('Failed converting the string value for'
147-
' mem_limit ({0}) to a number.')
148-
formatted_message = message.format(digits_part)
149-
raise errors.DockerException(formatted_message)
150-
151-
mem_limit = digits * units[suffix]
152-
else:
153-
message = ('The specified value for mem_limit parameter'
154-
' ({0}) should specify the units. The postfix'
155-
' should be one of the `b` `k` `m` `g`'
156-
' characters')
157-
raise errors.DockerException(message.format(mem_limit))
158-
159-
if isinstance(ports, list):
160-
exposed_ports = {}
161-
for port_definition in ports:
162-
port = port_definition
163-
proto = 'tcp'
164-
if isinstance(port_definition, tuple):
165-
if len(port_definition) == 2:
166-
proto = port_definition[1]
167-
port = port_definition[0]
168-
exposed_ports['{0}/{1}'.format(port, proto)] = {}
169-
ports = exposed_ports
170-
171-
if isinstance(volumes, six.string_types):
172-
volumes = [volumes, ]
173-
174-
if isinstance(volumes, list):
175-
volumes_dict = {}
176-
for vol in volumes:
177-
volumes_dict[vol] = {}
178-
volumes = volumes_dict
179-
180-
if volumes_from:
181-
if not isinstance(volumes_from, six.string_types):
182-
volumes_from = ','.join(volumes_from)
183-
else:
184-
# Force None, an empty list or dict causes client.start to fail
185-
volumes_from = None
186-
187-
attach_stdin = False
188-
attach_stdout = False
189-
attach_stderr = False
190-
stdin_once = False
191-
192-
if not detach:
193-
attach_stdout = True
194-
attach_stderr = True
195-
196-
if stdin_open:
197-
attach_stdin = True
198-
stdin_once = True
199-
200-
if utils.compare_version('1.10', self._version) >= 0:
201-
message = ('{0!r} parameter has no effect on create_container().'
202-
' It has been moved to start()')
203-
if dns is not None:
204-
raise errors.DockerException(message.format('dns'))
205-
if volumes_from is not None:
206-
raise errors.DockerException(message.format('volumes_from'))
207-
208-
return {
209-
'Hostname': hostname,
210-
'Domainname': domainname,
211-
'ExposedPorts': ports,
212-
'User': user,
213-
'Tty': tty,
214-
'OpenStdin': stdin_open,
215-
'StdinOnce': stdin_once,
216-
'Memory': mem_limit,
217-
'AttachStdin': attach_stdin,
218-
'AttachStdout': attach_stdout,
219-
'AttachStderr': attach_stderr,
220-
'Env': environment,
221-
'Cmd': command,
222-
'Dns': dns,
223-
'Image': image,
224-
'Volumes': volumes,
225-
'VolumesFrom': volumes_from,
226-
'NetworkDisabled': network_disabled,
227-
'Entrypoint': entrypoint,
228-
'CpuShares': cpu_shares,
229-
'Cpuset': cpuset,
230-
'WorkingDir': working_dir,
231-
'MemorySwap': memswap_limit,
232-
'HostConfig': host_config,
233-
'MacAddress': mac_address
234-
}
235-
236108
def _post_json(self, url, data, **kwargs):
237109
# Go <1.1 can't unserialize null to a string
238110
# so we do this disgusting thing here.
@@ -547,11 +419,11 @@ def create_container(self, image, command=None, hostname=None, user=None,
547419
'host_config is not supported in API < 1.15'
548420
)
549421

550-
config = self._container_config(
551-
image, command, hostname, user, detach, stdin_open, tty, mem_limit,
552-
ports, environment, dns, volumes, volumes_from, network_disabled,
553-
entrypoint, cpu_shares, working_dir, domainname, memswap_limit,
554-
cpuset, host_config, mac_address
422+
config = utils.create_container_config(
423+
self._version, image, command, hostname, user, detach, stdin_open,
424+
tty, mem_limit, ports, environment, dns, volumes, volumes_from,
425+
network_disabled, entrypoint, cpu_shares, working_dir, domainname,
426+
memswap_limit, cpuset, host_config, mac_address
555427
)
556428
return self.create_container_from_config(config, name)
557429

docker/utils/__init__.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
from .utils import (
22
compare_version, convert_port_bindings, convert_volume_binds,
33
mkbuildcontext, ping, tar, parse_repository_tag, parse_host,
4-
kwargs_from_env, convert_filters, create_host_config
4+
kwargs_from_env, convert_filters, create_host_config,
5+
create_container_config, parse_bytes
56
) # flake8: noqa

docker/utils/utils.py

Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import os
1717
import os.path
1818
import json
19+
import shlex
1920
import tarfile
2021
import tempfile
2122
from distutils.version import StrictVersion
@@ -31,6 +32,12 @@
3132

3233
DEFAULT_HTTP_HOST = "127.0.0.1"
3334
DEFAULT_UNIX_SOCKET = "http+unix://var/run/docker.sock"
35+
BYTE_UNITS = {
36+
'b': 1,
37+
'k': 1024,
38+
'm': 1024 * 1024,
39+
'g': 1024 * 1024 * 1024
40+
}
3441

3542

3643
def mkbuildcontext(dockerfile):
@@ -304,6 +311,41 @@ def datetime_to_timestamp(dt=datetime.now()):
304311
return delta.seconds + delta.days * 24 * 3600
305312

306313

314+
def parse_bytes(s):
315+
if len(s) == 0:
316+
s = 0
317+
else:
318+
units = BYTE_UNITS
319+
suffix = s[-1].lower()
320+
321+
# Check if the variable is a string representation of an int
322+
# without a units part. Assuming that the units are bytes.
323+
if suffix.isdigit():
324+
digits_part = s
325+
suffix = 'b'
326+
else:
327+
digits_part = s[:-1]
328+
329+
if suffix in units.keys() or suffix.isdigit():
330+
try:
331+
digits = int(digits_part)
332+
except ValueError:
333+
message = ('Failed converting the string value for'
334+
'memory ({0}) to a number.')
335+
formatted_message = message.format(digits_part)
336+
raise errors.DockerException(formatted_message)
337+
338+
s = digits * units[suffix]
339+
else:
340+
message = ('The specified value for memory'
341+
' ({0}) should specify the units. The postfix'
342+
' should be one of the `b` `k` `m` `g`'
343+
' characters')
344+
raise errors.DockerException(message.format(s))
345+
346+
return s
347+
348+
307349
def create_host_config(
308350
binds=None, port_bindings=None, lxc_conf=None,
309351
publish_all_ports=False, links=None, privileged=False,
@@ -392,3 +434,101 @@ def create_host_config(
392434
host_config['LxcConf'] = lxc_conf
393435

394436
return host_config
437+
438+
439+
def create_container_config(
440+
version, image, command, hostname=None, user=None, detach=False,
441+
stdin_open=False, tty=False, mem_limit=0, ports=None, environment=None,
442+
dns=None, volumes=None, volumes_from=None, network_disabled=False,
443+
entrypoint=None, cpu_shares=None, working_dir=None, domainname=None,
444+
memswap_limit=0, cpuset=None, host_config=None, mac_address=None
445+
):
446+
if isinstance(command, six.string_types):
447+
command = shlex.split(str(command))
448+
if isinstance(environment, dict):
449+
environment = [
450+
six.text_type('{0}={1}').format(k, v)
451+
for k, v in six.iteritems(environment)
452+
]
453+
454+
if isinstance(mem_limit, six.string_types):
455+
mem_limit = parse_bytes(mem_limit)
456+
if isinstance(memswap_limit, six.string_types):
457+
memswap_limit = parse_bytes(memswap_limit)
458+
459+
if isinstance(ports, list):
460+
exposed_ports = {}
461+
for port_definition in ports:
462+
port = port_definition
463+
proto = 'tcp'
464+
if isinstance(port_definition, tuple):
465+
if len(port_definition) == 2:
466+
proto = port_definition[1]
467+
port = port_definition[0]
468+
exposed_ports['{0}/{1}'.format(port, proto)] = {}
469+
ports = exposed_ports
470+
471+
if isinstance(volumes, six.string_types):
472+
volumes = [volumes, ]
473+
474+
if isinstance(volumes, list):
475+
volumes_dict = {}
476+
for vol in volumes:
477+
volumes_dict[vol] = {}
478+
volumes = volumes_dict
479+
480+
if volumes_from:
481+
if not isinstance(volumes_from, six.string_types):
482+
volumes_from = ','.join(volumes_from)
483+
else:
484+
# Force None, an empty list or dict causes client.start to fail
485+
volumes_from = None
486+
487+
attach_stdin = False
488+
attach_stdout = False
489+
attach_stderr = False
490+
stdin_once = False
491+
492+
if not detach:
493+
attach_stdout = True
494+
attach_stderr = True
495+
496+
if stdin_open:
497+
attach_stdin = True
498+
stdin_once = True
499+
500+
if compare_version('1.10', version) >= 0:
501+
message = ('{0!r} parameter has no effect on create_container().'
502+
' It has been moved to start()')
503+
if dns is not None:
504+
raise errors.DockerException(message.format('dns'))
505+
if volumes_from is not None:
506+
raise errors.DockerException(message.format('volumes_from'))
507+
508+
return {
509+
'Hostname': hostname,
510+
'Domainname': domainname,
511+
'ExposedPorts': ports,
512+
'User': user,
513+
'Tty': tty,
514+
'OpenStdin': stdin_open,
515+
'StdinOnce': stdin_once,
516+
'Memory': mem_limit,
517+
'AttachStdin': attach_stdin,
518+
'AttachStdout': attach_stdout,
519+
'AttachStderr': attach_stderr,
520+
'Env': environment,
521+
'Cmd': command,
522+
'Dns': dns,
523+
'Image': image,
524+
'Volumes': volumes,
525+
'VolumesFrom': volumes_from,
526+
'NetworkDisabled': network_disabled,
527+
'Entrypoint': entrypoint,
528+
'CpuShares': cpu_shares,
529+
'Cpuset': cpuset,
530+
'WorkingDir': working_dir,
531+
'MemorySwap': memswap_limit,
532+
'HostConfig': host_config,
533+
'MacAddress': mac_address
534+
}

0 commit comments

Comments
 (0)