Add container.get() which removes the duplication of container.inspect() in every property, and provides a nicer interface for querying container data.

Signed-off-by: Daniel Nephin <dnephin@gmail.com>
This commit is contained in:
Daniel Nephin 2014-08-31 13:04:18 -04:00
parent 6b221d5687
commit dbd723659b
2 changed files with 31 additions and 17 deletions

View File

@ -67,7 +67,7 @@ class Container(object):
@property
def ports(self):
self.inspect_if_not_inspected()
return self.dictionary['NetworkSettings']['Ports'] or {}
return self.get('NetworkSettings.Ports') or {}
@property
def human_readable_ports(self):
@ -82,33 +82,35 @@ class Container(object):
@property
def human_readable_state(self):
self.inspect_if_not_inspected()
if self.dictionary['State']['Running']:
if self.dictionary['State'].get('Ghost'):
return 'Ghost'
else:
return 'Up'
if self.is_running:
return 'Ghost' if self.get('State.Ghost') else 'Up'
else:
return 'Exit %s' % self.dictionary['State']['ExitCode']
return 'Exit %s' % self.get('State.ExitCode')
@property
def human_readable_command(self):
self.inspect_if_not_inspected()
if self.dictionary['Config']['Cmd']:
return ' '.join(self.dictionary['Config']['Cmd'])
else:
return ''
return ' '.join(self.get('Config.Cmd') or '')
@property
def environment(self):
self.inspect_if_not_inspected()
return dict(var.split("=", 1)
for var in self.dictionary.get('Config', {}).get('Env', []))
return dict(var.split("=", 1) for var in self.get('Config.Env') or [])
@property
def is_running(self):
return self.get('State.Running')
def get(self, key):
"""Return a value from the container or None if the value is not set.
:param key: a string using dotted notation for nested dictionary
lookups
"""
self.inspect_if_not_inspected()
return self.dictionary['State']['Running']
def get_value(dictionary, key):
return (dictionary or {}).get(key)
return reduce(get_value, key.split('.'), self.dictionary)
def get_local_port(self, port, protocol='tcp'):
port = self.ports.get("%s/%s" % (port, protocol))

View File

@ -105,3 +105,15 @@ class ContainerTest(unittest.TestCase):
self.assertEqual(
container.get_local_port(45454, protocol='tcp'),
'0.0.0.0:49197')
def test_get(self):
container = Container(None, {
"Status":"Up 8 seconds",
"HostConfig": {
"VolumesFrom": ["volume_id",]
},
}, has_been_inspected=True)
self.assertEqual(container.get('Status'), "Up 8 seconds")
self.assertEqual(container.get('HostConfig.VolumesFrom'), ["volume_id",])
self.assertEqual(container.get('Foo.Bar.DoesNotExist'), None)