Skip to content

Commit edb6b24

Browse files
committed
Handle Swarm-style prefixed names in Service.containers()
Signed-off-by: Aanand Prasad <aanand.prasad@gmail.com>
1 parent 608f29c commit edb6b24

2 files changed

Lines changed: 14 additions & 3 deletions

File tree

fig/service.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -545,9 +545,8 @@ def get_container_name(container):
545545
if 'Name' in container:
546546
return container['Name']
547547
# ps
548-
for name in container['Names']:
549-
if len(name.split('/')) == 2:
550-
return name[1:]
548+
shortest_name = min(container['Names'], key=lambda n: len(n.split('/')))
549+
return shortest_name.split('/')[-1]
551550

552551

553552
def parse_restart_spec(restart_config):

tests/unit/service_test.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ def test_get_container_name(self):
5454
self.assertIsNone(get_container_name({}))
5555
self.assertEqual(get_container_name({'Name': 'myproject_db_1'}), 'myproject_db_1')
5656
self.assertEqual(get_container_name({'Names': ['/myproject_db_1', '/myproject_web_1/db']}), 'myproject_db_1')
57+
self.assertEqual(get_container_name({'Names': ['/swarm-host-1/myproject_db_1', '/swarm-host-1/myproject_web_1/db']}), 'myproject_db_1')
5758

5859
def test_containers(self):
5960
service = Service('db', client=self.mock_client, project='myproject')
@@ -69,6 +70,17 @@ def test_containers(self):
6970
]
7071
self.assertEqual([c.id for c in service.containers()], ['IN_1'])
7172

73+
def test_containers_prefixed(self):
74+
service = Service('db', client=self.mock_client, project='myproject')
75+
76+
self.mock_client.containers.return_value = [
77+
{'Image': 'busybox', 'Id': 'OUT_1', 'Names': ['/swarm-host-1/myproject', '/swarm-host-1/foo/bar']},
78+
{'Image': 'busybox', 'Id': 'OUT_2', 'Names': ['/swarm-host-1/myproject_db']},
79+
{'Image': 'busybox', 'Id': 'OUT_3', 'Names': ['/swarm-host-1/db_1']},
80+
{'Image': 'busybox', 'Id': 'IN_1', 'Names': ['/swarm-host-1/myproject_db_1', '/swarm-host-1/myproject_web_1/db']},
81+
]
82+
self.assertEqual([c.id for c in service.containers()], ['IN_1'])
83+
7284
def test_get_volumes_from_container(self):
7385
container_id = 'aabbccddee'
7486
service = Service(

0 commit comments

Comments
 (0)