1 # Copyright (c) 2019 Cisco and/or its affiliates.
2 # Licensed under the Apache License, Version 2.0 (the "License");
3 # you may not use this file except in compliance with the License.
4 # You may obtain a copy of the License at:
6 # http://www.apache.org/licenses/LICENSE-2.0
8 # Unless required by applicable law or agreed to in writing, software
9 # distributed under the License is distributed on an "AS IS" BASIS,
10 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
14 # Bug workaround in pylint for abstract classes.
15 # pylint: disable=W0223
17 """Library to manipulate Containers."""
19 from string import Template
20 from collections import OrderedDict, Counter
22 from resources.libraries.python.ssh import SSH
23 from resources.libraries.python.Constants import Constants
24 from resources.libraries.python.topology import Topology
25 from resources.libraries.python.VppConfigGenerator import VppConfigGenerator
28 __all__ = ["ContainerManager", "ContainerEngine", "LXC", "Docker", "Container"]
30 SUPERVISOR_CONF = '/etc/supervisord.conf'
33 class ContainerManager(object):
34 """Container lifecycle management class."""
36 def __init__(self, engine):
37 """Initialize Container Manager class.
39 :param engine: Container technology used (LXC/Docker/...).
41 :raises NotImplementedError: If container technology is not implemented.
44 self.engine = globals()[engine]()
46 raise NotImplementedError('{engine} is not implemented.'.
47 format(engine=engine))
48 self.containers = OrderedDict()
50 def get_container_by_name(self, name):
51 """Get container instance.
53 :param name: Container name.
55 :returns: Container instance.
57 :raises RuntimeError: If failed to get container with name.
60 return self.containers[name]
62 raise RuntimeError('Failed to get container with name: {name}'.
65 def construct_container(self, **kwargs):
66 """Construct container object on node with specified parameters.
68 :param kwargs: Key-value pairs used to construct container.
72 self.engine.initialize()
75 setattr(self.engine.container, key, kwargs[key])
77 # Set additional environmental variables
78 setattr(self.engine.container, 'env',
79 'MICROSERVICE_LABEL={label}'.format(label=kwargs['name']))
81 # Store container instance
82 self.containers[kwargs['name']] = self.engine.container
84 def construct_containers(self, **kwargs):
85 """Construct 1..N container(s) on node with specified name.
87 Ordinal number is automatically added to the name of container as
90 :param kwargs: Named parameters.
94 for i in range(kwargs['count']):
95 # Name will contain ordinal suffix
96 kwargs['name'] = ''.join([name, str(i+1)])
98 self.construct_container(i=i, **kwargs)
100 def acquire_all_containers(self):
101 """Acquire all containers."""
102 for container in self.containers:
103 self.engine.container = self.containers[container]
104 self.engine.acquire()
106 def build_all_containers(self):
107 """Build all containers."""
108 for container in self.containers:
109 self.engine.container = self.containers[container]
112 def create_all_containers(self):
113 """Create all containers."""
114 for container in self.containers:
115 self.engine.container = self.containers[container]
118 def execute_on_container(self, name, command):
119 """Execute command on container with name.
121 :param name: Container name.
122 :param command: Command to execute.
126 self.engine.container = self.get_container_by_name(name)
127 self.engine.execute(command)
129 def execute_on_all_containers(self, command):
130 """Execute command on all containers.
132 :param command: Command to execute.
135 for container in self.containers:
136 self.engine.container = self.containers[container]
137 self.engine.execute(command)
139 def start_vpp_in_all_containers(self):
140 """Start VPP in all containers."""
141 for container in self.containers:
142 self.engine.container = self.containers[container]
143 # We need to install supervisor client/server system to control VPP
145 self.engine.install_supervisor()
146 self.engine.start_vpp()
148 def restart_vpp_in_all_containers(self):
149 """Restart VPP in all containers."""
150 for container in self.containers:
151 self.engine.container = self.containers[container]
152 self.engine.restart_vpp()
154 def configure_vpp_in_all_containers(self, chain_topology, **kwargs):
155 """Configure VPP in all containers.
157 :param chain_topology: Topology used for chaining containers can be
158 chain or cross_horiz. Chain topology is using 1 memif pair per
159 container. Cross_horiz topology is using 1 memif and 1 physical
160 interface in container (only single container can be configured).
161 :param kwargs: Named parameters.
162 :type chain_topology: str
165 # Count number of DUTs based on node's host information
166 dut_cnt = len(Counter([self.containers[container].node['host']
167 for container in self.containers]))
168 mod = len(self.containers)/dut_cnt
170 for i, container in enumerate(self.containers):
173 sid1 = i % mod * 2 + 1
174 sid2 = i % mod * 2 + 2
175 self.engine.container = self.containers[container]
176 guest_dir = self.engine.container.mnt[0].split(':')[1]
178 if chain_topology == 'chain':
179 self._configure_vpp_chain_l2xc(mid1=mid1, mid2=mid2,
180 sid1=sid1, sid2=sid2,
183 elif chain_topology == 'cross_horiz':
184 self._configure_vpp_cross_horiz(mid1=mid1, mid2=mid2,
185 sid1=sid1, sid2=sid2,
188 elif chain_topology == 'chain_functional':
189 self._configure_vpp_chain_functional(mid1=mid1, mid2=mid2,
190 sid1=sid1, sid2=sid2,
193 elif chain_topology == 'chain_ip4':
194 self._configure_vpp_chain_ip4(mid1=mid1, mid2=mid2,
195 sid1=sid1, sid2=sid2,
198 elif chain_topology == 'pipeline_ip4':
199 self._configure_vpp_pipeline_ip4(mid1=mid1, mid2=mid2,
200 sid1=sid1, sid2=sid2,
204 raise RuntimeError('Container topology {name} not implemented'.
205 format(name=chain_topology))
207 def _configure_vpp_chain_l2xc(self, **kwargs):
208 """Configure VPP in chain topology with l2xc.
210 :param kwargs: Named parameters.
213 self.engine.create_vpp_startup_config()
214 self.engine.create_vpp_exec_config(
215 'memif_create_chain_l2xc.exec',
216 mid1=kwargs['mid1'], mid2=kwargs['mid2'],
217 sid1=kwargs['sid1'], sid2=kwargs['sid2'],
218 socket1='{guest_dir}/memif-{c.name}-{sid1}'.
219 format(c=self.engine.container, **kwargs),
220 socket2='{guest_dir}/memif-{c.name}-{sid2}'.
221 format(c=self.engine.container, **kwargs))
223 def _configure_vpp_cross_horiz(self, **kwargs):
224 """Configure VPP in cross horizontal topology (single memif).
226 :param kwargs: Named parameters.
229 if 'DUT1' in self.engine.container.name:
230 if_pci = Topology.get_interface_pci_addr(
231 self.engine.container.node, kwargs['dut1_if'])
232 if_name = Topology.get_interface_name(
233 self.engine.container.node, kwargs['dut1_if'])
234 if 'DUT2' in self.engine.container.name:
235 if_pci = Topology.get_interface_pci_addr(
236 self.engine.container.node, kwargs['dut2_if'])
237 if_name = Topology.get_interface_name(
238 self.engine.container.node, kwargs['dut2_if'])
239 self.engine.create_vpp_startup_config_dpdk_dev(if_pci)
240 self.engine.create_vpp_exec_config(
241 'memif_create_cross_horizon.exec',
242 mid1=kwargs['mid1'], sid1=kwargs['sid1'], if_name=if_name,
243 socket1='{guest_dir}/memif-{c.name}-{sid1}'.
244 format(c=self.engine.container, **kwargs))
246 def _configure_vpp_chain_functional(self, **kwargs):
247 """Configure VPP in chain topology with l2xc (functional).
249 :param kwargs: Named parameters.
252 self.engine.create_vpp_startup_config_func_dev()
253 self.engine.create_vpp_exec_config(
254 'memif_create_chain_functional.exec',
255 mid1=kwargs['mid1'], mid2=kwargs['mid2'],
256 sid1=kwargs['sid1'], sid2=kwargs['sid2'],
257 socket1='{guest_dir}/memif-{c.name}-{sid1}'.
258 format(c=self.engine.container, **kwargs),
259 socket2='{guest_dir}/memif-{c.name}-{sid2}'.
260 format(c=self.engine.container, **kwargs),
263 def _configure_vpp_chain_ip4(self, **kwargs):
264 """Configure VPP in chain topology with ip4.
266 :param kwargs: Named parameters.
269 self.engine.create_vpp_startup_config()
271 vif1_mac = kwargs['tg_if1_mac'] \
272 if (kwargs['mid1'] - 1) % kwargs['nodes'] + 1 == 1 \
273 else '52:54:00:00:{0:02X}:02'.format(kwargs['mid1'] - 1)
274 vif2_mac = kwargs['tg_if2_mac'] \
275 if (kwargs['mid2'] - 1) % kwargs['nodes'] + 1 == kwargs['nodes'] \
276 else '52:54:00:00:{0:02X}:01'.format(kwargs['mid2'] + 1)
277 self.engine.create_vpp_exec_config(
278 'memif_create_chain_ip4.exec',
279 mid1=kwargs['mid1'], mid2=kwargs['mid2'],
280 sid1=kwargs['sid1'], sid2=kwargs['sid2'],
281 socket1='{guest_dir}/memif-{c.name}-{sid1}'.
282 format(c=self.engine.container, **kwargs),
283 socket2='{guest_dir}/memif-{c.name}-{sid2}'.
284 format(c=self.engine.container, **kwargs),
285 mac1='52:54:00:00:{0:02X}:01'.format(kwargs['mid1']),
286 mac2='52:54:00:00:{0:02X}:02'.format(kwargs['mid2']),
287 vif1_mac=vif1_mac, vif2_mac=vif2_mac)
289 def _configure_vpp_pipeline_ip4(self, **kwargs):
290 """Configure VPP in pipeline topology with ip4.
292 :param kwargs: Named parameters.
295 self.engine.create_vpp_startup_config()
296 node = (kwargs['mid1'] - 1) % kwargs['nodes'] + 1
297 mid1 = kwargs['mid1']
298 mid2 = kwargs['mid2']
301 if node == kwargs['nodes'] or node == kwargs['nodes'] and node == 1\
303 kwargs['mid2'] = kwargs['mid2'] \
304 if node == kwargs['nodes'] or node == kwargs['nodes'] and node == 1\
305 else kwargs['mid2'] + 1
306 vif1_mac = kwargs['tg_if1_mac'] \
307 if (kwargs['mid1'] - 1) % kwargs['nodes'] + 1 == 1 \
308 else '52:54:00:00:{0:02X}:02'.format(kwargs['mid1'] - 1)
309 vif2_mac = kwargs['tg_if2_mac'] \
310 if (kwargs['mid2'] - 1) % kwargs['nodes'] + 1 == kwargs['nodes'] \
311 else '52:54:00:00:{0:02X}:01'.format(kwargs['mid2'] + 1)
312 socket1 = '{guest_dir}/memif-{c.name}-{sid1}'.\
313 format(c=self.engine.container, **kwargs) \
314 if node == 1 else '{guest_dir}/memif-pipe-{mid1}'.\
315 format(c=self.engine.container, **kwargs)
316 socket2 = '{guest_dir}/memif-{c.name}-{sid2}'.\
317 format(c=self.engine.container, **kwargs) \
318 if node == 1 and kwargs['nodes'] == 1 or node == kwargs['nodes'] \
319 else '{guest_dir}/memif-pipe-{mid2}'.\
320 format(c=self.engine.container, **kwargs)
322 self.engine.create_vpp_exec_config(
323 'memif_create_pipeline_ip4.exec',
324 mid1=kwargs['mid1'], mid2=kwargs['mid2'],
325 sid1=kwargs['sid1'], sid2=kwargs['sid2'],
326 socket1=socket1, socket2=socket2, role1=role1, role2=role2,
327 mac1='52:54:00:00:{0:02X}:01'.format(mid1),
328 mac2='52:54:00:00:{0:02X}:02'.format(mid2),
329 vif1_mac=vif1_mac, vif2_mac=vif2_mac)
331 def stop_all_containers(self):
332 """Stop all containers."""
333 for container in self.containers:
334 self.engine.container = self.containers[container]
337 def destroy_all_containers(self):
338 """Destroy all containers."""
339 for container in self.containers:
340 self.engine.container = self.containers[container]
341 self.engine.destroy()
344 class ContainerEngine(object):
345 """Abstract class for container engine."""
348 """Init ContainerEngine object."""
349 self.container = None
351 def initialize(self):
352 """Initialize container object."""
353 self.container = Container()
355 def acquire(self, force):
356 """Acquire/download container.
358 :param force: Destroy a container if exists and create.
361 raise NotImplementedError
364 """Build container (compile)."""
365 raise NotImplementedError
368 """Create/deploy container."""
369 raise NotImplementedError
371 def execute(self, command):
372 """Execute process inside container.
374 :param command: Command to run inside container.
377 raise NotImplementedError
380 """Stop container."""
381 raise NotImplementedError
384 """Destroy/remove container."""
385 raise NotImplementedError
388 """Info about container."""
389 raise NotImplementedError
391 def system_info(self):
393 raise NotImplementedError
395 def install_supervisor(self):
396 """Install supervisord inside a container."""
397 if isinstance(self, LXC):
398 self.execute('sleep 3; apt-get update')
399 self.execute('apt-get install -y supervisor')
400 self.execute('echo "{config}" > {config_file} && '
401 'supervisord -c {config_file}'.
403 config='[unix_http_server]\n'
404 'file = /tmp/supervisor.sock\n\n'
405 '[rpcinterface:supervisor]\n'
406 'supervisor.rpcinterface_factory = '
407 'supervisor.rpcinterface:make_main_rpcinterface\n\n'
409 'serverurl = unix:///tmp/supervisor.sock\n\n'
411 'pidfile = /tmp/supervisord.pid\n'
412 'identifier = supervisor\n'
414 'logfile=/tmp/supervisord.log\n'
416 'nodaemon=false\n\n',
417 config_file=SUPERVISOR_CONF))
420 """Start VPP inside a container."""
421 self.execute('echo "{config}" >> {config_file}'.
423 config='[program:vpp]\n'
424 'command=/usr/bin/vpp -c /etc/vpp/startup.conf\n'
426 'autorestart=false\n'
427 'redirect_stderr=true\n'
429 config_file=SUPERVISOR_CONF))
430 self.execute('supervisorctl reload')
431 self.execute('supervisorctl start vpp')
433 def restart_vpp(self):
434 """Restart VPP service inside a container."""
435 self.execute('supervisorctl restart vpp')
436 self.execute('cat /tmp/supervisord.log')
438 def create_base_vpp_startup_config(self):
439 """Create base startup configuration of VPP on container.
441 :returns: Base VPP startup configuration.
442 :rtype: VppConfigGenerator
444 cpuset_cpus = self.container.cpuset_cpus
446 # Create config instance
447 vpp_config = VppConfigGenerator()
448 vpp_config.set_node(self.container.node)
449 vpp_config.add_unix_cli_listen()
450 vpp_config.add_unix_nodaemon()
451 vpp_config.add_unix_exec('/tmp/running.exec')
452 vpp_config.add_socksvr()
453 # We will pop the first core from the list to be a main core
454 vpp_config.add_cpu_main_core(str(cpuset_cpus.pop(0)))
455 # If more cores in the list, the rest will be used as workers.
457 corelist_workers = ','.join(str(cpu) for cpu in cpuset_cpus)
458 vpp_config.add_cpu_corelist_workers(corelist_workers)
462 def create_vpp_startup_config(self):
463 """Create startup configuration of VPP without DPDK on container.
465 vpp_config = self.create_base_vpp_startup_config()
466 vpp_config.add_plugin('disable', 'dpdk_plugin.so')
468 # Apply configuration
469 self.execute('mkdir -p /etc/vpp/')
470 self.execute('echo "{config}" | tee /etc/vpp/startup.conf'
471 .format(config=vpp_config.get_config_str()))
473 def create_vpp_startup_config_dpdk_dev(self, *devices):
474 """Create startup configuration of VPP with DPDK on container.
476 :param devices: List of PCI devices to add.
479 vpp_config = self.create_base_vpp_startup_config()
480 vpp_config.add_dpdk_dev(*devices)
481 vpp_config.add_dpdk_no_tx_checksum_offload()
482 vpp_config.add_dpdk_log_level('debug')
483 vpp_config.add_plugin('disable', 'default')
484 vpp_config.add_plugin('enable', 'dpdk_plugin.so')
485 vpp_config.add_plugin('enable', 'memif_plugin.so')
487 # Apply configuration
488 self.execute('mkdir -p /etc/vpp/')
489 self.execute('echo "{config}" | tee /etc/vpp/startup.conf'
490 .format(config=vpp_config.get_config_str()))
492 def create_vpp_startup_config_func_dev(self):
493 """Create startup configuration of VPP on container for functional
496 # Create config instance
497 vpp_config = VppConfigGenerator()
498 vpp_config.set_node(self.container.node)
499 vpp_config.add_unix_cli_listen()
500 vpp_config.add_unix_nodaemon()
501 vpp_config.add_unix_exec('/tmp/running.exec')
502 vpp_config.add_socksvr()
503 vpp_config.add_plugin('disable', 'dpdk_plugin.so')
505 # Apply configuration
506 self.execute('mkdir -p /etc/vpp/')
507 self.execute('echo "{config}" | tee /etc/vpp/startup.conf'
508 .format(config=vpp_config.get_config_str()))
510 def create_vpp_exec_config(self, template_file, **kwargs):
511 """Create VPP exec configuration on container.
513 :param template_file: File name of a template script.
514 :param kwargs: Parameters for script.
515 :type template_file: str
518 running = '/tmp/running.exec'
520 template = '{res}/{tpl}'.format(
521 res=Constants.RESOURCES_TPL_CONTAINER, tpl=template_file)
523 with open(template, 'r') as src_file:
524 src = Template(src_file.read())
525 self.execute('echo "{out}" > {running}'.format(
526 out=src.safe_substitute(**kwargs), running=running))
528 def is_container_running(self):
529 """Check if container is running."""
530 raise NotImplementedError
532 def is_container_present(self):
533 """Check if container is present."""
534 raise NotImplementedError
536 def _configure_cgroup(self, name):
537 """Configure the control group associated with a container.
539 By default the cpuset cgroup is using exclusive CPU/MEM. When Docker/LXC
540 container is initialized a new cgroup /docker or /lxc is created under
541 cpuset parent tree. This newly created cgroup is inheriting parent
542 setting for cpu/mem exclusive parameter and thus cannot be overriden
543 within /docker or /lxc cgroup. This function is supposed to set cgroups
544 to allow coexistence of both engines.
546 :param name: Name of cgroup.
548 :raises RuntimeError: If applying cgroup settings via cgset failed.
550 ret, _, _ = self.container.ssh.exec_command_sudo(
551 'cgset -r cpuset.cpu_exclusive=0 /')
553 raise RuntimeError('Failed to apply cgroup settings.')
555 ret, _, _ = self.container.ssh.exec_command_sudo(
556 'cgset -r cpuset.mem_exclusive=0 /')
558 raise RuntimeError('Failed to apply cgroup settings.')
560 ret, _, _ = self.container.ssh.exec_command_sudo(
561 'cgcreate -g cpuset:/{name}'.format(name=name))
563 raise RuntimeError('Failed to copy cgroup settings from root.')
565 ret, _, _ = self.container.ssh.exec_command_sudo(
566 'cgset -r cpuset.cpu_exclusive=0 /{name}'.format(name=name))
568 raise RuntimeError('Failed to apply cgroup settings.')
570 ret, _, _ = self.container.ssh.exec_command_sudo(
571 'cgset -r cpuset.mem_exclusive=0 /{name}'.format(name=name))
573 raise RuntimeError('Failed to apply cgroup settings.')
576 class LXC(ContainerEngine):
577 """LXC implementation."""
579 # Implicit constructor is inherited.
581 def acquire(self, force=True):
582 """Acquire a privileged system object where configuration is stored.
584 :param force: If a container exists, destroy it and create a new
587 :raises RuntimeError: If creating the container or writing the container
590 if self.is_container_present():
596 target_arch = 'arm64' \
597 if Topology.get_node_arch(self.container.node) == 'aarch64' \
600 image = self.container.image if self.container.image else\
601 "-d ubuntu -r bionic -a {arch}".format(arch=target_arch)
603 cmd = 'lxc-create -t download --name {c.name} -- {image} '\
604 '--no-validate'.format(c=self.container, image=image)
606 ret, _, _ = self.container.ssh.exec_command_sudo(cmd, timeout=1800)
608 raise RuntimeError('Failed to create container.')
610 self._configure_cgroup('lxc')
613 """Create/deploy an application inside a container on system.
615 :raises RuntimeError: If creating the container fails.
617 if self.container.mnt:
618 for mount in self.container.mnt:
619 host_dir, guest_dir = mount.split(':')
620 options = 'bind,create=dir' \
621 if guest_dir.endswith('/') else 'bind,create=file'
622 entry = 'lxc.mount.entry = {host_dir} '\
623 '/var/lib/lxc/{c.name}/rootfs{guest_dir} none ' \
624 '{options} 0 0'.format(c=self.container,
628 ret, _, _ = self.container.ssh.exec_command_sudo(
629 "sh -c 'echo \"{e}\" >> /var/lib/lxc/{c.name}/config'".
630 format(e=entry, c=self.container))
632 raise RuntimeError('Failed to write {c.name} config.'
633 .format(c=self.container))
635 cpuset_cpus = '{0}'.format(
636 ','.join('%s' % cpu for cpu in self.container.cpuset_cpus))\
637 if self.container.cpuset_cpus else ''
639 ret, _, _ = self.container.ssh.exec_command_sudo(
640 'lxc-start --name {c.name} --daemon'.
641 format(c=self.container))
643 raise RuntimeError('Failed to start container {c.name}.'.
644 format(c=self.container))
645 self._lxc_wait('RUNNING')
647 # Workaround for LXC to be able to allocate all cpus including isolated.
648 ret, _, _ = self.container.ssh.exec_command_sudo(
649 'cgset --copy-from / lxc/')
651 raise RuntimeError('Failed to copy cgroup to LXC')
653 ret, _, _ = self.container.ssh.exec_command_sudo(
654 'lxc-cgroup --name {c.name} cpuset.cpus {cpus}'.
655 format(c=self.container, cpus=cpuset_cpus))
657 raise RuntimeError('Failed to set cpuset.cpus to container '
658 '{c.name}.'.format(c=self.container))
660 def execute(self, command):
661 """Start a process inside a running container.
663 Runs the specified command inside the container specified by name. The
664 container has to be running already.
666 :param command: Command to run inside container.
668 :raises RuntimeError: If running the command failed.
670 env = '--keep-env {0}'.format(
671 ' '.join('--set-var %s' % env for env in self.container.env))\
672 if self.container.env else ''
674 cmd = "lxc-attach {env} --name {c.name} -- /bin/sh -c '{command}; "\
675 "exit $?'".format(env=env, c=self.container, command=command)
677 ret, _, _ = self.container.ssh.exec_command_sudo(cmd, timeout=180)
679 raise RuntimeError('Failed to run command inside container '
680 '{c.name}.'.format(c=self.container))
685 :raises RuntimeError: If stopping the container failed.
687 cmd = 'lxc-stop --name {c.name}'.format(c=self.container)
689 ret, _, _ = self.container.ssh.exec_command_sudo(cmd)
691 raise RuntimeError('Failed to stop container {c.name}.'
692 .format(c=self.container))
693 self._lxc_wait('STOPPED|FROZEN')
696 """Destroy a container.
698 :raises RuntimeError: If destroying container failed.
700 cmd = 'lxc-destroy --force --name {c.name}'.format(c=self.container)
702 ret, _, _ = self.container.ssh.exec_command_sudo(cmd)
704 raise RuntimeError('Failed to destroy container {c.name}.'
705 .format(c=self.container))
708 """Query and shows information about a container.
710 :raises RuntimeError: If getting info about a container failed.
712 cmd = 'lxc-info --name {c.name}'.format(c=self.container)
714 ret, _, _ = self.container.ssh.exec_command_sudo(cmd)
716 raise RuntimeError('Failed to get info about container {c.name}.'
717 .format(c=self.container))
719 def system_info(self):
720 """Check the current kernel for LXC support.
722 :raises RuntimeError: If checking LXC support failed.
724 cmd = 'lxc-checkconfig'
726 ret, _, _ = self.container.ssh.exec_command_sudo(cmd)
728 raise RuntimeError('Failed to check LXC support.')
730 def is_container_running(self):
731 """Check if container is running on node.
733 :returns: True if container is running.
735 :raises RuntimeError: If getting info about a container failed.
737 cmd = 'lxc-info --no-humanize --state --name {c.name}'\
738 .format(c=self.container)
740 ret, stdout, _ = self.container.ssh.exec_command_sudo(cmd)
742 raise RuntimeError('Failed to get info about container {c.name}.'
743 .format(c=self.container))
744 return True if 'RUNNING' in stdout else False
746 def is_container_present(self):
747 """Check if container is existing on node.
749 :returns: True if container is present.
751 :raises RuntimeError: If getting info about a container failed.
753 cmd = 'lxc-info --no-humanize --name {c.name}'.format(c=self.container)
755 ret, _, _ = self.container.ssh.exec_command_sudo(cmd)
756 return False if int(ret) else True
758 def _lxc_wait(self, state):
759 """Wait for a specific container state.
761 :param state: Specify the container state(s) to wait for.
763 :raises RuntimeError: If waiting for state of a container failed.
765 cmd = 'lxc-wait --name {c.name} --state "{s}"'\
766 .format(c=self.container, s=state)
768 ret, _, _ = self.container.ssh.exec_command_sudo(cmd)
770 raise RuntimeError('Failed to wait for state "{s}" of container '
771 '{c.name}.'.format(s=state, c=self.container))
774 class Docker(ContainerEngine):
775 """Docker implementation."""
777 # Implicit constructor is inherited.
779 def acquire(self, force=True):
780 """Pull an image or a repository from a registry.
782 :param force: Destroy a container if exists.
784 :raises RuntimeError: If pulling a container failed.
786 if self.is_container_present():
792 if not self.container.image:
793 img = Constants.DOCKER_SUT_IMAGE_UBUNTU_ARM \
794 if Topology.get_node_arch(self.container.node) == 'aarch64' \
795 else Constants.DOCKER_SUT_IMAGE_UBUNTU
796 setattr(self.container, 'image', img)
798 cmd = 'docker pull {image}'.format(image=self.container.image)
800 ret, _, _ = self.container.ssh.exec_command_sudo(cmd, timeout=1800)
802 raise RuntimeError('Failed to create container {c.name}.'
803 .format(c=self.container))
805 if self.container.cpuset_cpus:
806 self._configure_cgroup('docker')
809 """Create/deploy container.
811 :raises RuntimeError: If creating a container failed.
813 cpuset_cpus = '--cpuset-cpus={0}'.format(
814 ','.join('%s' % cpu for cpu in self.container.cpuset_cpus))\
815 if self.container.cpuset_cpus else ''
817 cpuset_mems = '--cpuset-mems={0}'.format(self.container.cpuset_mems)\
818 if self.container.cpuset_mems is not None else ''
819 # Temporary workaround - disabling due to bug in memif
823 ' '.join('--env %s' % env for env in self.container.env))\
824 if self.container.env else ''
826 command = '{0}'.format(self.container.command)\
827 if self.container.command else ''
829 publish = '{0}'.format(
830 ' '.join('--publish %s' % var for var in self.container.publish))\
831 if self.container.publish else ''
833 volume = '{0}'.format(
834 ' '.join('--volume %s' % mnt for mnt in self.container.mnt))\
835 if self.container.mnt else ''
838 '--privileged --detach --interactive --tty --rm '\
839 '--cgroup-parent docker {cpuset_cpus} {cpuset_mems} {publish} '\
840 '{env} {volume} --name {container.name} {container.image} '\
841 '{command}'.format(cpuset_cpus=cpuset_cpus, cpuset_mems=cpuset_mems,
842 container=self.container, command=command,
843 env=env, publish=publish, volume=volume)
845 ret, _, _ = self.container.ssh.exec_command_sudo(cmd)
847 raise RuntimeError('Failed to create container {c.name}'
848 .format(c=self.container))
852 def execute(self, command):
853 """Start a process inside a running container.
855 Runs the specified command inside the container specified by name. The
856 container has to be running already.
858 :param command: Command to run inside container.
860 :raises RuntimeError: If running the command in a container failed.
862 cmd = "docker exec --interactive {c.name} /bin/sh -c '{command}; "\
863 "exit $?'".format(c=self.container, command=command)
865 ret, _, _ = self.container.ssh.exec_command_sudo(cmd, timeout=180)
867 raise RuntimeError('Failed to execute command in container '
868 '{c.name}.'.format(c=self.container))
871 """Stop running container.
873 :raises RuntimeError: If stopping a container failed.
875 cmd = 'docker stop {c.name}'.format(c=self.container)
877 ret, _, _ = self.container.ssh.exec_command_sudo(cmd)
879 raise RuntimeError('Failed to stop container {c.name}.'
880 .format(c=self.container))
883 """Remove a container.
885 :raises RuntimeError: If removing a container failed.
887 cmd = 'docker rm --force {c.name}'.format(c=self.container)
889 ret, _, _ = self.container.ssh.exec_command_sudo(cmd)
891 raise RuntimeError('Failed to destroy container {c.name}.'
892 .format(c=self.container))
895 """Return low-level information on Docker objects.
897 :raises RuntimeError: If getting info about a container failed.
899 cmd = 'docker inspect {c.name}'.format(c=self.container)
901 ret, _, _ = self.container.ssh.exec_command_sudo(cmd)
903 raise RuntimeError('Failed to get info about container {c.name}.'
904 .format(c=self.container))
906 def system_info(self):
907 """Display the docker system-wide information.
909 :raises RuntimeError: If displaying system information failed.
911 cmd = 'docker system info'
913 ret, _, _ = self.container.ssh.exec_command_sudo(cmd)
915 raise RuntimeError('Failed to get system info.')
917 def is_container_present(self):
918 """Check if container is present on node.
920 :returns: True if container is present.
922 :raises RuntimeError: If getting info about a container failed.
924 cmd = 'docker ps --all --quiet --filter name={c.name}'\
925 .format(c=self.container)
927 ret, stdout, _ = self.container.ssh.exec_command_sudo(cmd)
929 raise RuntimeError('Failed to get info about container {c.name}.'
930 .format(c=self.container))
931 return True if stdout else False
933 def is_container_running(self):
934 """Check if container is running on node.
936 :returns: True if container is running.
938 :raises RuntimeError: If getting info about a container failed.
940 cmd = 'docker ps --quiet --filter name={c.name}'\
941 .format(c=self.container)
943 ret, stdout, _ = self.container.ssh.exec_command_sudo(cmd)
945 raise RuntimeError('Failed to get info about container {c.name}.'
946 .format(c=self.container))
947 return True if stdout else False
950 class Container(object):
951 """Container class."""
954 """Initialize Container object."""
957 def __getattr__(self, attr):
958 """Get attribute custom implementation.
960 :param attr: Attribute to get.
962 :returns: Attribute value or None.
966 return self.__dict__[attr]
970 def __setattr__(self, attr, value):
971 """Set attribute custom implementation.
973 :param attr: Attribute to set.
974 :param value: Value to set.
979 # Check if attribute exists
982 # Creating new attribute
984 self.__dict__['ssh'] = SSH()
985 self.__dict__['ssh'].connect(value)
986 self.__dict__[attr] = value
988 # Updating attribute base of type
989 if isinstance(self.__dict__[attr], list):
990 self.__dict__[attr].append(value)
992 self.__dict__[attr] = value