blob: 2961e3748b332d170bf331d6258ca4f1af6d63aa [file] [log] [blame]
alshabib6ca05622017-01-31 14:08:36 -08001#
2# Copyright 2017 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#
16import os
17
18from docker import Client
19from structlog import get_logger
20
21docker_socket = os.environ.get('DOCKER_SOCK', 'unix://tmp/docker.sock')
22log = get_logger()
23
24
25def get_my_containers_name():
26 """
27 Return the docker containers name in which this process is running.
28 To look up the container name, we use the container ID extracted from the
29 $HOSTNAME environment variable (which is set by docker conventions).
30 :return: String with the docker container name (or None if any issue is
31 encountered)
32 """
33 my_container_id = os.environ.get('HOSTNAME', None)
34
35 try:
36 docker_cli = Client(base_url=docker_socket)
37 info = docker_cli.inspect_container(my_container_id)
38
39 except Exception, e:
40 log.exception('failed', my_container_id=my_container_id, e=e)
41 raise
42
43 name = info['Name'].lstrip('/')
44
45 return name