blob: 4a0c4346c71eb1266f8133d1b7006b2f224b866b [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
Zack Williamsf97bf092018-03-22 21:27:28 -070017import sys
18from distutils.version import LooseVersion
alshabib6ca05622017-01-31 14:08:36 -080019
alshabib6ca05622017-01-31 14:08:36 -080020from structlog import get_logger
Zack Williamsf97bf092018-03-22 21:27:28 -070021log = get_logger()
22
23# handle the python docker v1 to v2 API differences
24try:
25 from docker import __version__ as docker_version
26
27 if LooseVersion(docker_version) < LooseVersion('2.0.0'):
28 log.error("Unsupported python docker module!"
29 "Please upgrade to docker 2.x or later")
30
31 # <2.x compatible import
32 from docker import Client as DockerClient
33 else:
34 # >2.x compatible import
35 from docker import APIClient as DockerClient
36
37except ImportError:
38 log.error("Unable to load python docker module!")
39 sys.exit(1)
alshabib6ca05622017-01-31 14:08:36 -080040
41docker_socket = os.environ.get('DOCKER_SOCK', 'unix://tmp/docker.sock')
alshabib6ca05622017-01-31 14:08:36 -080042
43
44def get_my_containers_name():
45 """
46 Return the docker containers name in which this process is running.
47 To look up the container name, we use the container ID extracted from the
48 $HOSTNAME environment variable (which is set by docker conventions).
49 :return: String with the docker container name (or None if any issue is
50 encountered)
51 """
52 my_container_id = os.environ.get('HOSTNAME', None)
53
54 try:
Zack Williamsf97bf092018-03-22 21:27:28 -070055 docker_cli = DockerClient(base_url=docker_socket)
alshabib6ca05622017-01-31 14:08:36 -080056 info = docker_cli.inspect_container(my_container_id)
57
Zack Williams7eb36d02019-03-19 07:16:12 -070058 except Exception as e:
alshabib6ca05622017-01-31 14:08:36 -080059 log.exception('failed', my_container_id=my_container_id, e=e)
60 raise
61
62 name = info['Name'].lstrip('/')
63
Zack Williamsf97bf092018-03-22 21:27:28 -070064 return name