Skip to content

Commit 59d5260

Browse files
committed
Merge pull request #488 from docker/memoryswap
Container config cleanup
2 parents 6ff3623 + e2233fc commit 59d5260

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):
@@ -306,6 +313,41 @@ def datetime_to_timestamp(dt=datetime.now()):
306313
return delta.seconds + delta.days * 24 * 3600
307314

308315

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

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

0 commit comments

Comments
 (0)