aboutsummaryrefslogtreecommitdiffstats
path: root/resources/libraries/python/ContainerUtils.py
blob: 363411c070565f3d3d8f85024309acd90405bfc1 (plain)
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
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441

@media only all and (prefers-color-scheme: dark) {
.highlight .hll { background-color: #49483e }
.highlight .c { color: #75715e } /* Comment */
.highlight .err { color: #960050; background-color: #1e0010 } /* Error */
.highlight .k { color: #66d9ef } /* Keyword */
.highlight .l { color: #ae81ff } /* Literal */
.highlight .n { color: #f8f8f2 } /* Name */
.highlight .o { color: #f92672 } /* Operator */
.highlight .p { color: #f8f8f2 } /* Punctuation */
.highlight .ch { color: #75715e } /* Comment.Hashbang */
.highlight .cm { color: #75715e } /* Comment.Multiline */
.highlight .cp { color: #75715e } /* Comment.Preproc */
.highlight .cpf { color: #75715e } /* Comment.PreprocFile */
.highlight .c1 { color: #75715e } /* Comment.Single */
.highlight .cs { color: #75715e } /* Comment.Special */
.highlight .gd { color: #f92672 } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gi { color: #a6e22e } /* Generic.Inserted */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #75715e } /* Generic.Subheading */
.highlight .kc { color: #66d9ef } /* Keyword.Constant */
.highlight .kd { color: #66d9ef } /* Keyword.Declaration */
.highlight .kn { color: #f92672 } /* Keyword.Namespace */
.highlight .kp { color: #66d9ef } /* Keyword.Pseudo */
.highlight .kr { color: #66d9ef } /* Keyword.Reserved */
.highlight .kt { color: #66d9ef } /* Keyword.Type */
.highlight .ld { color: #e6db74 } /* Literal.Date */
.highlight .m { color: #ae81ff } /* Literal.Number */
.highlight .s { color: #e6db74 } /* Literal.String */
.highlight .na { color: #a6e22e } /* Name.Attribute */
.highlight .nb { color: #f8f8f2 } /* Name.Builtin */
.highlight .nc { color: #a6e22e } /* Name.Class */
.highlight .no { color: #66d9ef } /* Name.Constant */
.highlight .nd { color: #a6e22e } /* Name.Decorator */
.highlight .ni { color: #f8f8f2 } /* Name.Entity */
.highlight .ne { color: #a6e22e } /* Name.Exception */
.highlight .nf { color: #a6e22e } /* Name.Function */
.highlight .nl { color: #f8f8f2 } /* Name.Label */
.highlight .nn { color: #f8f8f2 } /* Name.Namespace */
.highlight .nx { color: #a6e22e } /* Name.Other */
.highlight .py { color: #f8f8f2 } /* Name.Property */
.highlight .nt { color: #f92672 } /* Name.Tag */
.highlight .nv { color: #f8f8f2 } /* Name.Variable */
.highlight .ow { color: #f92672 } /* Operator.Word */
.highlight .w { color: #f8f8f2 } /* Text.Whitespace */
.highlight .mb { color: #ae81ff } /* Literal.Number.Bin */
.highlight .mf { color: #ae81ff } /* Literal.Number.Float */
.highlight .mh { color: #ae81ff } /* Literal.Number.Hex */
.highlight .mi { color: #ae81ff } /* Literal.Number.Integer */
.highlight .mo { color: #ae81ff } /* Literal.Number.Oct */
.highlight .sa { color: #e6db74 } /* Literal.String.Affix */
.highlight .sb { color: #e6db74 } /* Literal.String.Backtick */
.highlight .sc { color: #e6db74 } /* Literal.String.Char */
.highlight .dl { color: #e6db74 } /* Literal.String.Delimiter */
.highlight .sd { color: #e6db74 } /* Literal.String.Doc */
.highlight .s2 { color: #e6db74 } /* Literal.String.Double */
.highlight .se { color: #ae81ff } /* Literal.String.Escape */
.highlight .sh { color: #e6db74 } /* Literal.String.Heredoc */
.highlight .si { color: #e6db74 } /* Literal.String.Interpol */
.highlight .sx { color: #e6db74 } /* Literal.String.Other */
.highlight .sr { color: #e6db74 } /* Literal.String.Regex */
.highlight .s1 { color: #e6db74 } /* Literal.String.Single */
.highlight .ss { color: #e6db74 } /* Literal.String.Symbol */
.highlight .bp { color: #f8f8f2 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #a6e22e } /* Name.Function.Magic */
.highlight .vc { color: #f8f8f2 } /* Name.Variable.Class */
.highlight .vg { color: #f8f8f2 } /* Name.Variable.Global */
.highlight .vi { color: #f8f8f2 } /* Name.Variable.Instance */
.highlight .vm { color: #f8f8f2 } /* Name.Variable.Magic */
.highlight .il { color: #ae81ff } /* Literal.Number.Integer.Long */
}
@media (prefers-color-scheme: light) {
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
}
= Developing plugins for VPP

link:release_notes.html[< Home]

Honeycomb's primary use case is to provide an agent for VPP. This section provides a tutorial for how to develop a Honeycomb plugin that translates YANG modeled data into VPP binary API invocation.

== Analyzing VPP's API
For this tutorial, VPP's VXLAN management API. Honeycomb already contains VXLAN management translation code inside V3PO plugin. This will be a simplified version.

Looking at VPP's API definition file, there are 3 calls related to VXLAN:

vxlan_add_del_tunnel - Creates and Deletes VXLAN tunnel (Update not supported)
vxlan_tunnel_dump - Reads all VXLAN tunnels
These are the shared-memory, binary APIs of VPP that would be difficult to use from Java. But VPP contains a jvpp component, that's completely generated from VPP's API definition file and allows Java applications to manage VPP in plain Java using JNI in the background. Honeycomb provides a component that can be included in a distribution.

== Updating sample-plugin to manage VPP

This tutorial starts where the previous one left and will continue to modify the sample plugin in order to be able to manage VPP's VXLAN tunnels.

=== Updating YANG models
YANG models need to reflect the intent of managing VXLAN tunnels in VPP. As mentioned before, VPP exposes 2 calls to manage VXLAN tunnels. Each vxlan tunnel has a set of attributes, but for simplicity, only 2 of them will be exposed in YANG : source IP address and destination IP address. Rest of attributes will be set to default values in the code.

So let's update the sample-plugin-params grouping to:

[source,yang]
----
grouping sample-plugin-params {
    container vxlans {
        list vxlan-tunnel {

            key id;
            leaf id {
                type string;
            }

            leaf src {
              type inet:ip-address;
            }
            leaf dst {
              type inet:ip-address;
            }
        }
    }
}
----

Since ietf-inet-types YANG model is used for the ip-address type, it needs to be imported (after the prefix statement):

[source,yang]
----
import ietf-inet-types { prefix "inet"; }
----

NOTE: The reason this works is that there are some general YANG models such as ietf-inet-types added to *-api module in its pom.xml.

Now rebuild the *-api module.

=== JVpp dependency
Another important thing that the plugin needs is dependency to VPP's JVpp (Java APIs). To do so, just update *-impl's pom.xml with:

[source,xml]
----
<!-- VPP's core Java APIs -->
<dependency>
    <groupId>io.fd.vpp</groupId>
    <artifactId>jvpp-core</artifactId>
    <version>{project-vpp-snapshot-version}</version>
</dependency>
----

Also add vpp-translate-utils dependency so that writing translation code is easier:

[source,xml]
----
<dependency>
    <groupId>io.fd.honeycomb.vpp</groupId>
    <artifactId>vpp-translate-utils</artifactId>
    <version>{project-version}</version>
</dependency>
----

Do not rebuild yet, since the APIs for this plugin have changed and the compilation would fail. But make sure to update the project if using an IDE to pick up the Jvpp dependency.

=== Updating the customizers

First of all, remove CrudService interface and ElementCrudService class. Will not be needed now.

==== Changes to ElementStateCustomizer

Rename it to VxlanReadCustomzier. Update the code to:

[source,java]
----
package io.fd.honeycomb.tutorial.read;

import com.google.common.base.Preconditions;
import io.fd.honeycomb.translate.read.ReadContext;
import io.fd.honeycomb.translate.read.ReadFailedException;
import io.fd.honeycomb.translate.spi.read.ListReaderCustomizer;
import io.fd.honeycomb.translate.v3po.util.NamingContext;
import io.fd.honeycomb.translate.v3po.util.TranslateUtils;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import javax.annotation.Nonnull;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.sample.plugin.rev160918.sample.plugin.params.VxlansBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.sample.plugin.rev160918.sample.plugin.params.vxlans.VxlanTunnel;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.sample.plugin.rev160918.sample.plugin.params.vxlans.VxlanTunnelBuilder;
import org.opendaylight.yang.gen.v1.urn.opendaylight.params.xml.ns.yang.sample.plugin.rev160918.sample.plugin.params.vxlans.VxlanTunnelKey;
import org.opendaylight.yangtools.concepts.Builder;
import org.opendaylight.yangtools.yang.binding.DataObject;
import org.opendaylight.yangtools.yang.binding.InstanceIdentifier;
import org.openvpp.jvpp.VppBaseCallException;
import org.openvpp.jvpp.core.dto.VxlanTunnelDetails;
import org.openvpp.jvpp.core.dto.VxlanTunnelDetailsReplyDump;
import org.openvpp.jvpp.core.dto.VxlanTunnelDump;
import org.openvpp.jvpp.core.future.FutureJVppCore;

/**
 * Reader for {@link VxlanTunnel} list node from our YANG model.
 */
public final class VxlanReadCustomizer implements
        ListReaderCustomizer<VxlanTunnel, VxlanTunnelKey, VxlanTunnelBuilder> {

    // JVpp core. This is the Java API for VPP's core API.
    private final FutureJVppCore jVppCore;
    // Naming context for interfaces
    // Honeycomb provides a "context" storage for plugins. This storage is used for storing metadata required during
    // data translation (just like in this plugin). An example of such metadata would be interface identifier. In Honeycomb
    // we use string names for interfaces, however VPP uses only indices (that are created automatically).
    // This means that translation layer has to store the mapping between HC interface name <-> VPP' interface index.
    // And since vxlan tunnel is a type of interface in VPP, the same applies here
    //
    // Honeycomb provides a couple utilities on top of context storage such as NamingContext. It is just a map
    // backed by context storage that makes the lookup and storing easier.
    private final NamingContext vxlanNamingContext;

    public VxlanReadCustomizer(final FutureJVppCore jVppCore, final NamingContext vxlanNamingContext) {
        this.jVppCore = jVppCore;
        this.vxlanNamingContext = vxlanNamingContext;
    }

    /**
     * Provide a list of IDs for all VXLANs in VPP
     */
    @Nonnull
    @Override
    public List<VxlanTunnelKey> getAllIds(@Nonnull final InstanceIdentifier<VxlanTunnel> id,
                                          @Nonnull final ReadContext context)
            throws ReadFailedException {
        // Create Dump request
        final VxlanTunnelDump vxlanTunnelDump = new VxlanTunnelDump();
        // Set Dump request attributes
        // Set interface index to 0, so all interfaces are dumped and we can get the list of all IDs
        vxlanTunnelDump.swIfIndex = 0;
        final VxlanTunnelDetailsReplyDump reply;
        try {
            reply = TranslateUtils.getReplyForRead(jVppCore.vxlanTunnelDump(vxlanTunnelDump).toCompletableFuture(), id);
        } catch (VppBaseCallException e) {
            throw new ReadFailedException(id, e);
        }

        // Check for empty response (no vxlan tunnels to read)
        if (reply == null || reply.vxlanTunnelDetails == null) {
            return Collections.emptyList();
        }

        return reply.vxlanTunnelDetails.stream()
                // Need a name of an interface here. Use context to look it up from index
                // In case the naming context does not contain such mapping, it creates an artificial one
                .map(a -> new VxlanTunnelKey(vxlanNamingContext.getName(a.swIfIndex, context.getMappingContext())))
                .collect(Collectors.toList());
    }

    @Override
    public void merge(@Nonnull final Builder<? extends DataObject> builder, @Nonnull final List<VxlanTunnel> readData) {
        // Just set the readValue into parent builder
        // The cast has to be performed here
        ((VxlansBuilder) builder).setVxlanTunnel(readData);
    }

    @Nonnull
    @Override
    public VxlanTunnelBuilder getBuilder(@Nonnull final InstanceIdentifier<VxlanTunnel> id) {
        // Setting key from id is not necessary, builder will take care of that
        return new VxlanTunnelBuilder();
    }

    /**
     * Read all the attributes of a single VXLAN tunnel
     */
    @Override
    public void readCurrentAttributes(@Nonnull final InstanceIdentifier<VxlanTunnel> id,
                                      @Nonnull final VxlanTunnelBuilder builder,
                                      @Nonnull final ReadContext ctx) throws ReadFailedException {
        // The ID received here contains the name of a particular interface that should be read
        // It was either requested directly by HC users or is one of the IDs from getAllIds that could have been invoked
        // just before this method invocation

        // Create Dump request
        final VxlanTunnelDump vxlanTunnelDump = new VxlanTunnelDump();
        // Set Dump request attributes
        // Set the vxlan index from naming context
        // Naming context must contain the mapping because:
        // 1. The vxlan tunnel was created in VPP using HC + this plugin meaning we stored the mapping in write customizer
        // 2. The vxlan tunnel was already present in VPP, but HC reconciliation mechanism took care of that (as long as proper Initializer is provided by this plugin)
        final String vxlanName = id.firstKeyOf(VxlanTunnel.class).getId();
        vxlanTunnelDump.swIfIndex = vxlanNamingContext.getIndex(vxlanName, ctx.getMappingContext());

        final VxlanTunnelDetailsReplyDump reply;
        try {
            reply = TranslateUtils.getReplyForRead(jVpp
# Copyright (c) 2019 Cisco and/or its affiliates.
# 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.

# Bug workaround in pylint for abstract classes.
# pylint: disable=W0223

"""Library to manipulate Containers."""

from string import Template
from collections import OrderedDict, Counter

from resources.libraries.python.ssh import SSH
from resources.libraries.python.Constants import Constants
from resources.libraries.python.topology import Topology
from resources.libraries.python.VppConfigGenerator import VppConfigGenerator


__all__ = ["ContainerManager", "ContainerEngine", "LXC", "Docker", "Container"]

SUPERVISOR_CONF = '/etc/supervisord.conf'


class ContainerManager(object):
    """Container lifecycle management class."""

    def __init__(self, engine):
        """Initialize Container Manager class.

        :param engine: Container technology used (LXC/Docker/...).
        :type engine: str
        :raises NotImplementedError: If container technology is not implemented.
        """
        try:
            self.engine = globals()[engine]()
        except KeyError:
            raise NotImplementedError('{engine} is not implemented.'.
                                      format(engine=engine))
        self.containers = OrderedDict()

    def get_container_by_name(self, name):
        """Get container instance.

        :param name: Container name.
        :type name: str
        :returns: Container instance.
        :rtype: Container
        :raises RuntimeError: If failed to get container with name.
        """
        try:
            return self.containers[name]
        except KeyError:
            raise RuntimeError('Failed to get container with name: {name}'.
                               format(name=name))

    def construct_container(self, **kwargs):
        """Construct container object on node with specified parameters.

        :param kwargs: Key-value pairs used to construct container.
        :param kwargs: dict
        """
        # Create base class
        self.engine.initialize()
        # Set parameters
        for key in kwargs:
            setattr(self.engine.container, key, kwargs[key])

        # Set additional environmental variables
        setattr(self.engine.container, 'env',
                'MICROSERVICE_LABEL={label}'.format(label=kwargs['name']))

        # Store container instance
        self.containers[kwargs['name']] = self.engine.container

    def construct_containers(self, **kwargs):
        """Construct 1..N container(s) on node with specified name.

        Ordinal number is automatically added to the name of container as
        suffix.

        :param kwargs: Named parameters.
        :param kwargs: dict
        """
        name = kwargs['name']
        for i in range(kwargs['count']):
            # Name will contain ordinal suffix
            kwargs['name'] = ''.join([name, str(i+1)])
            # Create container
            self.construct_container(i=i, **kwargs)

    def acquire_all_containers(self):
        """Acquire all containers."""
        for container in self.containers:
            self.engine.container = self.containers[container]
            self.engine.acquire()

    def build_all_containers(self):
        """Build all containers."""
        for container in self.containers:
            self.engine.container = self.containers[container]
            self.engine.build()

    def create_all_containers(self):
        """Create all containers."""
        for container in self.containers:
            self.engine.container = self.containers[container]
            self.engine.create()

    def execute_on_container(self, name, command):
        """Execute command on container with name.

        :param name: Container name.
        :param command: Command to execute.
        :type name: str
        :type command: str
        """
        self.engine.container = self.get_container_by_name(name)
        self.engine.execute(command)

    def execute_on_all_containers(self, command):
        """Execute command on all containers.

        :param command: Command to execute.
        :type command: str
        """
        for container in self.containers:
            self.engine.container = self.containers[container]
            self.engine.execute(command)

    def start_vpp_in_all_containers(self):
        """Start VPP in all containers."""
        for container in self.containers:
            self.engine.container = self.containers[container]
            # We need to install supervisor client/server system to control VPP
            # as a service
            self.engine.install_supervisor()
            self.engine.start_vpp()

    def restart_vpp_in_all_containers(self):
        """Restart VPP in all containers."""
        for container in self.containers:
            self.engine.container = self.containers[container]
            self.engine.restart_vpp()

    def configure_vpp_in_all_containers(self, chain_topology, **kwargs):
        """Configure VPP in all containers.

        :param chain_topology: Topology used for chaining containers can be
            chain or cross_horiz. Chain topology is using 1 memif pair per
            container. Cross_horiz topology is using 1 memif and 1 physical
            interface in container (only single container can be configured).
        :param kwargs: Named parameters.
        :type chain_topology: str
        :param kwargs: dict
        """
        # Count number of DUTs based on node's host information
        dut_cnt = len(Counter([self.containers[container].node['host']
                               for container in self.containers]))
        mod = len(self.containers)/dut_cnt

        for i, container in enumerate(self.containers):
            mid1 = i % mod + 1
            mid2 = i % mod + 1
            sid1 = i % mod * 2 + 1
            sid2 = i % mod * 2 + 2
            self.engine.container = self.containers[container]
            guest_dir = self.engine.container.mnt[0].split(':')[1]

            if chain_topology == 'chain':
                self._configure_vpp_chain_l2xc(mid1=mid1, mid2=mid2,
                                               sid1=sid1, sid2=sid2,
                                               guest_dir=guest_dir,
                                               **kwargs)
            elif chain_topology == 'cross_horiz':
                self._configure_vpp_cross_horiz(mid1=mid1, mid2=mid2,
                                                sid1=sid1, sid2=sid2,
                                                guest_dir=guest_dir,
                                                **kwargs)
            elif chain_topology == 'chain_functional':
                self._configure_vpp_chain_functional(mid1=mid1, mid2=mid2,
                                                     sid1=sid1, sid2=sid2,
                                                     guest_dir=guest_dir,
                                                     **kwargs)
            elif chain_topology == 'chain_ip4':
                self._configure_vpp_chain_ip4(mid1=mid1, mid2=mid2,
                                              sid1=sid1, sid2=sid2,
                                              guest_dir=guest_dir,
                                              **kwargs)
            elif chain_topology == 'pipeline_ip4':
                self._configure_vpp_pipeline_ip4(mid1=mid1, mid2=mid2,
                                                 sid1=sid1, sid2=sid2,
                                                 guest_dir=guest_dir,
                                                 **kwargs)
            else:
                raise RuntimeError('Container topology {name} not implemented'.
                                   format(name=chain_topology))

    def _configure_vpp_chain_l2xc(self, **kwargs):
        """Configure VPP in chain topology with l2xc.

        :param kwargs: Named parameters.
        :param kwargs: dict
        """
        self.engine.create_vpp_startup_config()
        self.engine.create_vpp_exec_config(
            'memif_create_chain_l2xc.exec',
            mid1=kwargs['mid1'], mid2=kwargs['mid2'],
            sid1=kwargs['sid1'], sid2=kwargs['sid2'],
            socket1='{guest_dir}/memif-{c.name}-{sid1}'.
            format(c=self.engine.container, **kwargs),
            socket2='{guest_dir}/memif-{c.name}-{sid2}'.
            format(c=self.engine.container, **kwargs))

    def _configure_vpp_cross_horiz(self, **kwargs):
        """Configure VPP in cross horizontal topology (single memif).

        :param kwargs: Named parameters.
        :param kwargs: dict
        """
        if 'DUT1' in self.engine.container.name:
            if_pci = Topology.get_interface_pci_addr(
                self.engine.container.node, kwargs['dut1_if'])
            if_name = Topology.get_interface_name(
                self.engine.container.node, kwargs['dut1_if'])
        if 'DUT2' in self.engine.container.name:
            if_pci = Topology.get_interface_pci_addr(
                self.engine.container.node, kwargs['dut2_if'])
            if_name = Topology.get_interface_name(
                self.engine.container.node, kwargs['dut2_if'])
        self.engine.create_vpp_startup_config_dpdk_dev(if_pci)
        self.engine.create_vpp_exec_config(
            'memif_create_cross_horizon.exec',
            mid1=kwargs['mid1'], sid1=kwargs['sid1'], if_name=if_name,
            socket1='{guest_dir}/memif-{c.name}-{sid1}'.
            format(c=self.engine.container, **kwargs))

    def _configure_vpp_chain_functional(self, **kwargs):
        """Configure VPP in chain topology with l2xc (functional).

        :param kwargs: Named parameters.
        :param kwargs: dict
        """
        self.engine.create_vpp_startup_config_func_dev()
        self.engine.create_vpp_exec_config(
            'memif_create_chain_functional.exec',
            mid1=kwargs['mid1'], mid2=kwargs['mid2'],
            sid1=kwargs['sid1'], sid2=kwargs['sid2'],
            socket1='{guest_dir}/memif-{c.name}-{sid1}'.
            format(c=self.engine.container, **kwargs),
            socket2='{guest_dir}/memif-{c.name}-{sid2}'.
            format(c=self.engine.container, **kwargs),
            rx_mode='interrupt')

    def _configure_vpp_chain_ip4(self, **kwargs):
        """Configure VPP in chain topology with ip4.

        :param kwargs: Named parameters.
        :param kwargs: dict
        """
        self.engine.create_vpp_startup_config()

        vif1_mac = kwargs['tg_if1_mac'] \
            if (kwargs['mid1'] - 1) % kwargs['nodes'] + 1 == 1 \
            else '52:54:00:00:{0:02X}:02'.format(kwargs['mid1'] - 1)
        vif2_mac = kwargs['tg_if2_mac'] \
            if (kwargs['mid2'] - 1) % kwargs['nodes'] + 1 == kwargs['nodes'] \
            else '52:54:00:00:{0:02X}:01'.format(kwargs['mid2'] + 1)
        self.engine.create_vpp_exec_config(
            'memif_create_chain_ip4.exec',
            mid1=kwargs['mid1'], mid2=kwargs['mid2'],
            sid1=kwargs['sid1'], sid2=kwargs['sid2'],
            socket1='{guest_dir}/memif-{c.name}-{sid1}'.
            format(c=self.engine.container, **kwargs),
            socket2='{guest_dir}/memif-{c.name}-{sid2}'.
            format(c=self.engine.container, **kwargs),
            mac1='52:54:00:00:{0:02X}:01'.format(kwargs['mid1']),
            mac2='52:54:00:00:{0:02X}:02'.format(kwargs['mid2']),
            vif1_mac=vif1_mac, vif2_mac=vif2_mac)

    def _configure_vpp_pipeline_ip4(self, **kwargs):
        """Configure VPP in pipeline topology with ip4.

        :param kwargs: Named parameters.
        :param kwargs: dict
        """
        self.engine.create_vpp_startup_config()
        node = (kwargs['mid1'] - 1) % kwargs['nodes'] + 1
        mid1 = kwargs['mid1']
        mid2 = kwargs['mid2']
        role1 = 'master'
        role2 = 'master' \
            if node == kwargs['nodes'] or node == kwargs['nodes'] and node == 1\
            else 'slave'
        kwargs['mid2'] = kwargs['mid2'] \
            if node == kwargs['nodes'] or node == kwargs['nodes'] and node == 1\
            else kwargs['mid2'] + 1
        vif1_mac = kwargs['tg_if1_mac'] \
            if (kwargs['mid1'] - 1) % kwargs['nodes'] + 1 == 1 \
            else '52:54:00:00:{0:02X}:02'.format(kwargs['mid1'] - 1)
        vif2_mac = kwargs['tg_if2_mac'] \
            if (kwargs['mid2'] - 1) % kwargs['nodes'] + 1 == kwargs['nodes'] \
            else '52:54:00:00:{0:02X}:01'.format(kwargs['mid2'] + 1)
        socket1 = '{guest_dir}/memif-{c.name}-{sid1}'.\
            format(c=self.engine.container, **kwargs) \
            if node == 1 else '{guest_dir}/memif-pipe-{mid1}'.\
            format(c=self.engine.container, **kwargs)
        socket2 = '{guest_dir}/memif-{c.name}-{sid2}'.\
            format(c=self.engine.container, **kwargs) \
            if node == 1 and kwargs['nodes'] == 1 or node == kwargs['nodes'] \
            else '{guest_dir}/memif-pipe-{mid2}'.\
            format(c=self.engine.container, **kwargs)

        self.engine.create_vpp_exec_config(
            'memif_create_pipeline_ip4.exec',
            mid1=kwargs['mid1'], mid2=kwargs['mid2'],
            sid1=kwargs['sid1'], sid2=kwargs['sid2'],
            socket1=socket1, socket2=socket2, role1=role1, role2=role2,
            mac1='52:54:00:00:{0:02X}:01'.format(mid1),
            mac2='52:54:00:00:{0:02X}:02'.format(mid2),
            vif1_mac=vif1_mac, vif2_mac=vif2_mac)

    def stop_all_containers(self):
        """Stop all containers."""
        for container in self.containers:
            self.engine.container = self.containers[container]
            self.engine.stop()

    def destroy_all_containers(self):
        """Destroy all containers."""
        for container in self.containers:
            self.engine.container = self.containers[container]
            self.engine.destroy()


class ContainerEngine(object):
    """Abstract class for container engine."""

    def __init__(self):
        """Init ContainerEngine object."""
        self.container = None

    def initialize(self):
        """Initialize container object."""
        self.container = Container()

    def acquire(self, force):
        """Acquire/download container.

        :param force: Destroy a container if exists and create.
        :type force: bool
        """
        raise NotImplementedError

    def build(self):
        """Build container (compile)."""
        raise NotImplementedError

    def create(self):
        """Create/deploy container."""
        raise NotImplementedError

    def execute(self, command):
        """Execute process inside container.

        :param command: Command to run inside container.
        :type command: str
        """
        raise NotImplementedError

    def stop(self):
        """Stop container."""
        raise NotImplementedError

    def destroy(self):
        """Destroy/remove container."""
        raise NotImplementedError

    def info(self):
        """Info about container."""
        raise NotImplementedError

    def system_info(self):
        """System info."""
        raise NotImplementedError

    def install_supervisor(self):
        """Install supervisord inside a container."""
        if isinstance(self, LXC):
            self.execute('sleep 3; apt-get update')
            self.execute('apt-get install -y supervisor')
        self.execute('echo "{config}" > {config_file} && '
                     'supervisord -c {config_file}'.
                     format(
                         config='[unix_http_server]\n'
                         'file  = /tmp/supervisor.sock\n\n'
                         '[rpcinterface:supervisor]\n'
                         'supervisor.rpcinterface_factory = '
                         'supervisor.rpcinterface:make_main_rpcinterface\n\n'
                         '[supervisorctl]\n'
                         'serverurl = unix:///tmp/supervisor.sock\n\n'
                         '[supervisord]\n'
                         'pidfile = /tmp/supervisord.pid\n'
                         'identifier = supervisor\n'
                         'directory = /tmp\n'
                         'logfile=/tmp/supervisord.log\n'
                         'loglevel=debug\n'
                         'nodaemon=false\n\n',
                         config_file=SUPERVISOR_CONF))

    def start_vpp(self):
        """Start VPP inside a container."""
        self.execute('echo "{config}" >> {config_file}'.
                     format(
                         config='[program:vpp]\n'
                         'command=/usr/bin/vpp -c /etc/vpp/startup.conf\n'
                         'autostart=false\n'
                         'autorestart=false\n'
                         'redirect_stderr=true\n'
                         'priority=1',
                         config_file=SUPERVISOR_CONF))
        self.execute('supervisorctl reload')
        self.execute('supervisorctl start vpp')

    def restart_vpp(self):
        """Restart VPP service inside a container."""
        self.execute('supervisorctl restart vpp')
        self.execute('cat /tmp/supervisord.log')

    def create_base_vpp_startup_config(self):
        """Create base startup configuration of VPP on container.

        :returns: Base VPP startup configuration.
        :rtype: VppConfigGenerator
        """
        cpuset_cpus = self.container.cpuset_cpus

        # Create config instance
        vpp_config = VppConfigGenerator()
        vpp_config.set_node(self.container.node)
        vpp_config.add_unix_cli_listen()
        vpp_config.add_unix_nodaemon()
        vpp_config.add_unix_exec('/tmp/running.exec')
        vpp_config.add_socksvr()
        # We will pop the first core from the list to be a main core
        vpp_config.add_cpu_main_core(str(cpuset_cpus.pop(0)))
        # If more cores in the list, the rest will be used as workers.
        if cpuset_cpus:
            corelist_workers = ','.join(str(cpu) for cpu in cpuset_cpus)
            vpp_config.add_cpu_corelist_workers(corelist_workers)

        return vpp_config

    def create_vpp_startup_config(self):
        """Create startup configuration of VPP without DPDK on container.
        """
        vpp_config = self.create_base_vpp_startup_config()
        vpp_config.add_plugin('disable', 'dpdk_plugin.so')

        # Apply configuration
        self.execute('mkdir -p /etc/vpp/')
        self.execute('echo "{config}" | tee /etc/vpp/startup.conf'
                     .format(config=vpp_config.get_config_str()))

    def create_vpp_startup_config_dpdk_dev(self, *devices):
        """Create startup configuration of VPP with DPDK on container.

        :param devices: List of PCI devices to add.
        :type devices: list
        """
        vpp_config = self.create_base_vpp_startup_config()
        vpp_config.add_dpdk_dev(*devices)
        vpp_config.add_dpdk_no_tx_checksum_offload()
        vpp_config.add_dpdk_log_level('debug')
        vpp_config.add_plugin('disable', 'default')
        vpp_config.add_plugin('enable', 'dpdk_plugin.so')
        vpp_config.add_plugin('enable', 'memif_plugin.so')

        # Apply configuration
        self.execute('mkdir -p /etc/vpp/')
        self.execute('echo "{config}" | tee /etc/vpp/startup.conf'
                     .format(config=vpp_config.get_config_str()))

    def create_vpp_startup_config_func_dev(self):
        """Create startup configuration of VPP on container for functional
        vpp_device tests.
        """
        # Create config instance
        vpp_config = VppConfigGenerator()
        vpp_config.set_node(self.container.node)
        vpp_config.add_unix_cli_listen()
        vpp_config.add_unix_nodaemon()
        vpp_config.add_unix_exec('/tmp/running.exec')
        vpp_config.add_socksvr()
        vpp_config.add_plugin('disable', 'dpdk_plugin.so')

        # Apply configuration
        self.execute('mkdir -p /etc/vpp/')
        self.execute('echo "{config}" | tee /etc/vpp/startup.conf'
                     .format(config=vpp_config.get_config_str()))

    def create_vpp_exec_config(self, template_file, **kwargs):
        """Create VPP exec configuration on container.

        :param template_file: File name of a template script.
        :param kwargs: Parameters for script.
        :type template_file: str
        :type kwargs: dict
        """
        running = '/tmp/running.exec'

        template = '{res}/{tpl}'.format(
            res=Constants.RESOURCES_TPL_CONTAINER, tpl=template_file)

        with open(template, 'r') as src_file:
            src = Template(src_file.read())
            self.execute('echo "{out}" > {running}'.format(
                out=src.safe_substitute(**kwargs), running=running))

    def is_container_running(self):
        """Check if container is running."""
        raise NotImplementedError

    def is_container_present(self):
        """Check if container is present."""
        raise NotImplementedError

    def _configure_cgroup(self, name):
        """Configure the control group associated with a container.

        By default the cpuset cgroup is using exclusive CPU/MEM. When Docker/LXC
        container is initialized a new cgroup /docker or /lxc is created under
        cpuset parent tree. This newly created cgroup is inheriting parent
        setting for cpu/mem exclusive parameter and thus cannot be overriden
        within /docker or /lxc cgroup. This function is supposed to set cgroups
        to allow coexistence of both engines.

        :param name: Name of cgroup.
        :type name: str
        :raises RuntimeError: If applying cgroup settings via cgset failed.
        """
        ret, _, _ = self.container.ssh.exec_command_sudo(
            'cgset -r cpuset.cpu_exclusive=0 /')
        if int(ret) != 0:
            raise RuntimeError('Failed to apply cgroup settings.')

        ret, _, _ = self.container.ssh.exec_command_sudo(
            'cgset -r cpuset.mem_exclusive=0 /')
        if int(ret) != 0:
            raise RuntimeError('Failed to apply cgroup settings.')

        ret, _, _ = self.container.ssh.exec_command_sudo(
            'cgcreate -g cpuset:/{name}'.format(name=name))
        if int(ret) != 0:
            raise RuntimeError('Failed to copy cgroup settings from root.')

        ret, _, _ = self.container.ssh.exec_command_sudo(
            'cgset -r cpuset.cpu_exclusive=0 /{name}'.format(name=name))
        if int(ret) != 0:
            raise RuntimeError('Failed to apply cgroup settings.')

        ret, _, _ = self.container.ssh.exec_command_sudo(
            'cgset -r cpuset.mem_exclusive=0 /{name}'.format(name=name))
        if int(ret) != 0:
            raise RuntimeError('Failed to apply cgroup settings.')


class LXC(ContainerEngine):
    """LXC implementation."""

    # Implicit constructor is inherited.

    def acquire(self, force=True):
        """Acquire a privileged system object where configuration is stored.

        :param force: If a container exists, destroy it and create a new
            container.
        :type force: bool
        :raises RuntimeError: If creating the container or writing the container
            config fails.
        """
        if self.is_container_present():
            if force:
                self.destroy()
            else:
                return

        target_arch = 'arm64' \
            if Topology.get_node_arch(self.container.node) == 'aarch64' \
            else 'amd64'

        image = self.container.image if self.container.image else\
            "-d ubuntu -r bionic -a {arch}".format(arch=target_arch)

        cmd = 'lxc-create -t download --name {c.name} -- {image} '\
            '--no-validate'.format(c=self.container, image=image)

        ret, _, _ = self.container.ssh.exec_command_sudo(cmd, timeout=1800)
        if int(ret) != 0:
            raise RuntimeError('Failed to create container.')

        self._configure_cgroup('lxc')

    def create(self):
        """Create/deploy an application inside a container on system.

        :raises RuntimeError: If creating the container fails.
        """
        if self.container.mnt:
            for mount in self.container.mnt:
                host_dir, guest_dir = mount.split(':')
                options = 'bind,create=dir' \
                    if guest_dir.endswith('/') else 'bind,create=file'
                entry = 'lxc.mount.entry = {host_dir} '\
                    '/var/lib/lxc/{c.name}/rootfs{guest_dir} none ' \
                    '{options} 0 0'.format(c=self.container,
                                           host_dir=host_dir,
                                           guest_dir=guest_dir,
                                           options=options)
                ret, _, _ = self.container.ssh.exec_command_sudo(
                    "sh -c 'echo \"{e}\" >> /var/lib/lxc/{c.name}/config'".
                    format(e=entry, c=self.container))
                if int(ret) != 0:
                    raise RuntimeError('Failed to write {c.name} config.'
                                       .format(c=self.container))

        cpuset_cpus = '{0}'.format(
            ','.join('%s' % cpu for cpu in self.container.cpuset_cpus))\
            if self.container.cpuset_cpus else ''

        ret, _, _ = self.container.ssh.exec_command_sudo(
            'lxc-start --name {c.name} --daemon'.
            format(c=self.container))
        if int(ret) != 0:
            raise RuntimeError('Failed to start container {c.name}.'.
                               format(c=self.container))
        self._lxc_wait('RUNNING')

        # Workaround for LXC to be able to allocate all cpus including isolated.
        ret, _, _ = self.container.ssh.exec_command_sudo(
            'cgset --copy-from / lxc/')
        if int(ret) != 0:
            raise RuntimeError('Failed to copy cgroup to LXC')

        ret, _, _ = self.container.ssh.exec_command_sudo(
            'lxc-cgroup --name {c.name} cpuset.cpus {cpus}'.
            format(c=self.container, cpus=cpuset_cpus))
        if int(ret) != 0:
            raise RuntimeError('Failed to set cpuset.cpus to container '
                               '{c.name}.'.format(c=self.container))

    def execute(self, command):
        """Start a process inside a running container.

        Runs the specified command inside the container specified by name. The
        container has to be running already.

        :param command: Command to run inside container.
        :type command: str
        :raises RuntimeError: If running the command failed.
        """
        env = '--keep-env {0}'.format(
            ' '.join('--set-var %s' % env for env in self.container.env))\
            if self.container.env else ''

        cmd = "lxc-attach {env} --name {c.name} -- /bin/sh -c '{command}; "\
            "exit $?'".format(env=env, c=self.container, command=command)

        ret, _, _ = self.container.ssh.exec_command_sudo(cmd, timeout=180)
        if int(ret) != 0:
            raise RuntimeError('Failed to run command inside container '
                               '{c.name}.'.format(c=self.container))

    def stop(self):
        """Stop a container.

        :raises RuntimeError: If stopping the container failed.
        """
        cmd = 'lxc-stop --name {c.name}'.format(c=self.container)

        ret, _, _ = self.container.ssh.exec_command_sudo(cmd)
        if int(ret) != 0:
            raise RuntimeError('Failed to stop container {c.name}.'
                               .format(c=self.container))
        self._lxc_wait('STOPPED|FROZEN')

    def destroy(self):
        """Destroy a container.

        :raises RuntimeError: If destroying container failed.
        """
        cmd = 'lxc-destroy --force --name {c.name}'.format(c=self.container)

        ret, _, _ = self.container.ssh.exec_command_sudo(cmd)
        if int(ret) != 0:
            raise RuntimeError('Failed to destroy container {c.name}.'
                               .format(c=self.container))

    def info(self):
        """Query and shows information about a container.

        :raises RuntimeError: If getting info about a container failed.
        """
        cmd = 'lxc-info --name {c.name}'.format(c=self.container)

        ret, _, _ = self.container.ssh.exec_command_sudo(cmd)
        if int(ret) != 0:
            raise RuntimeError('Failed to get info about container {c.name}.'
                               .format(c=self.container))

    def system_info(self):
        """Check the current kernel for LXC support.

        :raises RuntimeError: If checking LXC support failed.
        """
        cmd = 'lxc-checkconfig'

        ret, _, _ = self.container.ssh.exec_command_sudo(cmd)
        if int(ret) != 0:
            raise RuntimeError('Failed to check LXC support.')

    def is_container_running(self):
        """Check if container is running on node.

        :returns: True if container is running.
        :rtype: bool
        :raises RuntimeError: If getting info about a container failed.
        """
        cmd = 'lxc-info --no-humanize --state --name {c.name}'\
            .format(c=self.container)

        ret, stdout, _ = self.container.ssh.exec_command_sudo(cmd)
        if int(ret) != 0:
            raise RuntimeError('Failed to get info about container {c.name}.'
                               .format(c=self.container))
        return True if 'RUNNING' in stdout else False

    def is_container_present(self):
        """Check if container is existing on node.

        :returns: True if container is present.
        :rtype: bool
        :raises RuntimeError: If getting info about a container failed.
        """
        cmd = 'lxc-info --no-humanize --name {c.name}'.format(c=self.container)

        ret, _, _ = self.container.ssh.exec_command_sudo(cmd)
        return False if int(ret) else True

    def _lxc_wait(self, state):
        """Wait for a specific container state.

        :param state: Specify the container state(s) to wait for.
        :type state: str
        :raises RuntimeError: If waiting for state of a container failed.
        """
        cmd = 'lxc-wait --name {c.name} --state "{s}"'\
            .format(c=self.container, s=state)

        ret, _, _ = self.container.ssh.exec_command_sudo(cmd)
        if int(ret) != 0:
            raise RuntimeError('Failed to wait for state "{s}" of container '
                               '{c.name}.'.format(s=state, c=self.container))


class Docker(ContainerEngine):
    """Docker implementation."""

    # Implicit constructor is inherited.

    def acquire(self, force=True):
        """Pull an image or a repository from a registry.

        :param force: Destroy a container if exists.
        :type force: bool
        :raises RuntimeError: If pulling a container failed.
        """
        if self.is_container_present():
            if force:
                self.destroy()
            else:
                return

        if not self.container.image:
            img = Constants.DOCKER_SUT_IMAGE_UBUNTU_ARM \
                if Topology.get_node_arch(self.container.node) == 'aarch64' \
                else Constants.DOCKER_SUT_IMAGE_UBUNTU
            setattr(self.container, 'image', img)

        cmd = 'docker pull {image}'.format(image=self.container.image)

        ret, _, _ = self.container.ssh.exec_command_sudo(cmd, timeout=1800)
        if int(ret) != 0:
            raise RuntimeError('Failed to create container {c.name}.'
                               .format(c=self.container))

        if self.container.cpuset_cpus:
            self._configure_cgroup('docker')

    def create(self):
        """Create/deploy container.

        :raises RuntimeError: If creating a container failed.
        """
        cpuset_cpus = '--cpuset-cpus={0}'.format(
            ','.join('%s' % cpu for cpu in self.container.cpuset_cpus))\
            if self.container.cpuset_cpus else ''

        cpuset_mems = '--cpuset-mems={0}'.format(self.container.cpuset_mems)\
            if self.container.cpuset_mems is not None else ''
        # Temporary workaround - disabling due to bug in memif
        cpuset_mems = ''

        env = '{0}'.format(
            ' '.join('--env %s' % env for env in self.container.env))\
            if self.container.env else ''

        command = '{0}'.format(self.container.command)\
            if self.container.command else ''

        publish = '{0}'.format(
            ' '.join('--publish %s' % var for var in self.container.publish))\
            if self.container.publish else ''

        volume = '{0}'.format(
            ' '.join('--volume %s' % mnt for mnt in self.container.mnt))\
            if self.container.mnt else ''

        cmd = 'docker run '\
            '--privileged --detach --interactive --tty --rm '\
            '--cgroup-parent docker {cpuset_cpus} {cpuset_mems} {publish} '\
            '{env} {volume} --name {container.name} {container.image} '\
            '{command}'.format(cpuset_cpus=cpuset_cpus, cpuset_mems=cpuset_mems,
                               container=self.container, command=command,
                               env=env, publish=publish, volume=volume)

        ret, _, _ = self.container.ssh.exec_command_sudo(cmd)
        if int(ret) != 0:
            raise RuntimeError('Failed to create container {c.name}'
                               .format(c=self.container))

        self.info()

    def execute(self, command):
        """Start a process inside a running container.

        Runs the specified command inside the container specified by name. The
        container has to be running already.

        :param command: Command to run inside container.
        :type command: str
        :raises RuntimeError: If running the command in a container failed.
        """
        cmd = "docker exec --interactive {c.name} /bin/sh -c '{command}; "\
            "exit $?'".format(c=self.container, command=command)

        ret, _, _ = self.container.ssh.exec_command_sudo(cmd, timeout=180)
        if int(ret) != 0:
            raise RuntimeError('Failed to execute command in container '
                               '{c.name}.'.format(c=self.container))

    def stop(self):
        """Stop running container.

        :raises RuntimeError: If stopping a container failed.
        """
        cmd = 'docker stop {c.name}'.format(c=self.container)

        ret, _, _ = self.container.ssh.exec_command_sudo(cmd)
        if int(ret) != 0:
            raise RuntimeError('Failed to stop container {c.name}.'
                               .format(c=self.container))

    def destroy(self):
        """Remove a container.

        :raises RuntimeError: If removing a container failed.
        """
        cmd = 'docker rm --force {c.name}'.format(c=self.container)

        ret, _, _ = self.container.ssh.exec_command_sudo(cmd)
        if int(ret) != 0:
            raise RuntimeError('Failed to destroy container {c.name}.'
                               .format(c=self.container))

    def info(self):
        """Return low-level information on Docker objects.

        :raises RuntimeError: If getting info about a container failed.
        """
        cmd = 'docker inspect {c.name}'.format(c=self.container)

        ret, _, _ = self.container.ssh.exec_command_sudo(cmd)
        if int(ret) != 0:
            raise RuntimeError('Failed to get info about container {c.name}.'
                               .format(c=self.container))

    def system_info(self):
        """Display the docker system-wide information.

        :raises RuntimeError: If displaying system information failed.
        """
        cmd = 'docker system info'

        ret, _, _ = self.container.ssh.exec_command_sudo(cmd)
        if int(ret) != 0:
            raise RuntimeError('Failed to get system info.')

    def is_container_present(self):
        """Check if container is present on node.

        :returns: True if container is present.
        :rtype: bool
        :raises RuntimeError: If getting info about a container failed.
        """
        cmd = 'docker ps --all --quiet --filter name={c.name}'\
            .format(c=self.container)

        ret, stdout, _ = self.container.ssh.exec_command_sudo(cmd)
        if int(ret) != 0:
            raise RuntimeError('Failed to get info about container {c.name}.'
                               .format(c=self.container))
        return True if stdout else False

    def is_container_running(self):
        """Check if container is running on node.

        :returns: True if container is running.
        :rtype: bool
        :raises RuntimeError: If getting info about a container failed.
        """
        cmd = 'docker ps --quiet --filter name={c.name}'\
            .format(c=self.container)

        ret, stdout, _ = self.container.ssh.exec_command_sudo(cmd)
        if int(ret) != 0:
            raise RuntimeError('Failed to get info about container {c.name}.'
                               .format(c=self.container))
        return True if stdout else False


class Container(object):
    """Container class."""

    def __init__(self):
        """Initialize Container object."""
        pass

    def __getattr__(self, attr):
        """Get attribute custom implementation.

        :param attr: Attribute to get.
        :type attr: str
        :returns: Attribute value or None.
        :rtype: any
        """
        try:
            return self.__dict__[attr]
        except KeyError:
            return None

    def __setattr__(self, attr, value):
        """Set attribute custom implementation.

        :param attr: Attribute to set.
        :param value: Value to set.
        :type attr: str
        :type value: any
        """
        try:
            # Check if attribute exists
            self.__dict__[attr]
        except KeyError:
            # Creating new attribute
            if attr == 'node':
                self.__dict__['ssh'] = SSH()
                self.__dict__['ssh'].connect(value)
            self.__dict__[attr] = value
        else:
            # Updating attribute base of type
            if isinstance(self.__dict__[attr], list):
                self.__dict__[attr].append(value)
            else:
                self.__dict__[attr] = value