blob: 0b24dd88a957e501ff39de17a0fc9d3d3b57c24d [file] [log] [blame]
Zsolt Haraszti86be6f12016-09-27 09:56:49 -07001#
2# Copyright 2016 the original author or authors.
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15#
16
17"""
18Some docker related convenience functions
19"""
20
21import os
22from structlog import get_logger
23
24from docker import Client
25
26
27log = get_logger()
28
29
30def get_my_containers_name():
31 """
32 Return the docker containers name in which this process is running.
33 To look up the container name, we use the container ID extracted from the
34 $HOSTNAME environment variable (which is set by docker conventions).
35 :return: String with the docker container name (or None if any issue is
36 encountered)
37 """
38 my_container_id = os.environ.get('HOSTNAME', None)
39
40 try:
41 docker_cli = Client(base_url='unix://tmp/docker.sock')
42 info = docker_cli.inspect_container(my_container_id)
43
44 except Exception, e:
45 log.exception('failed', my_container_id=my_container_id, e=e)
46 raise
47
48 name = info['Name'].lstrip('/')
49
50 return name
alshabibc67ee3a2016-10-25 23:24:03 -070051
52def create_container_network(name, links):
53 """
54 Creates a container networks based on a set of containers.
55 :param name: the network name
56 :param links: the set of containers to link
57 :return: a network configuration
58 """
59 try:
60 docker_cli = Client(base_url='unix://tmp/docker.sock')
61 docker_cli.create_network(name)
62 networking_config = docker_cli.create_networking_config({
63 'network1': docker_cli.create_endpoint_config(links = links)
64 })
65 except Exception, e:
66 log.exception('failed network creation', name, e=e)
67 raise
68
69 return networking_config
70
71
72def start_container(args):
73 """
74 Starts a requested container with the appropriate configuration.
75 :param args: contains arguments for container creation
76 (see https://docker-py.readthedocs.io/en/stable/api/#create_container)
77 :return: the containers name
78 """
79 try:
80 docker_cli = Client(base_url='unix://tmp/docker.sock')
81 docker_cli.create_container(**args)
82 except Exception, e:
83 log.exception('failed', e=e)
84 raise
85