Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added state with Docker alike state like 'Up 10 days', 'Exit (0) 5 days ago' #5

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion docker_monitor/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@

VERSION = '0.0.3'

REQUIREMENTS = ['docker==3.7.0', 'python-dateutil==2.7.5']
REQUIREMENTS = ['docker==3.7.0', 'python-dateutil==2.7.5', 'pytz']

_LOGGER = logging.getLogger(__name__)

Expand Down Expand Up @@ -57,6 +57,7 @@
UTILISATION_MONITOR_VERSION = 'utilization_version'

CONTAINER_MONITOR_STATUS = 'container_status'
CONTAINER_MONITOR_STATE = 'container_state'
CONTAINER_MONITOR_UPTIME = 'container_uptime'
CONTAINER_MONITOR_IMAGE = 'container_image'
CONTAINER_MONITOR_CPU_PERCENTAGE = 'container_cpu_percentage_usage'
Expand All @@ -73,6 +74,7 @@

_CONTAINER_MON_COND = {
CONTAINER_MONITOR_STATUS: ['Status', None, 'mdi:checkbox-marked-circle-outline', None],
CONTAINER_MONITOR_STATE: ['State', None, 'mdi:checkbox-marked-circle-outline', None],
CONTAINER_MONITOR_UPTIME: ['Up Time', '', 'mdi:clock', 'timestamp'],
CONTAINER_MONITOR_IMAGE: ['Image', None, 'mdi:information-outline', None],
CONTAINER_MONITOR_CPU_PERCENTAGE: ['CPU use', '%', 'mdi:chip', None],
Expand Down Expand Up @@ -285,6 +287,8 @@ def get_info(self):
'status': self._container.attrs['State']['Status'],
'created': parser.parse(self._container.attrs['Created']),
'started': parser.parse(self._container.attrs['State']['StartedAt']),
'ended': parser.parse(self._container.attrs['State']['FinishedAt']),
'exitcode': self._container.attrs['State']['ExitCode'],
}

return info
Expand Down
65 changes: 64 additions & 1 deletion docker_monitor/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
https://github.com/Sanderhuisman/home-assistant-custom-components
'''
import logging
from datetime import timedelta
from datetime import timedelta, datetime
from dateutil import relativedelta
import pytz

import homeassistant.util.dt as dt_util
from homeassistant.const import (
Expand All @@ -31,6 +33,7 @@
CONTAINER_MONITOR_NETWORK_SPEED_UP,
CONTAINER_MONITOR_NETWORK_TOTAL_UP,
CONTAINER_MONITOR_STATUS,
CONTAINER_MONITOR_STATE,
CONTAINER_MONITOR_UPTIME,
DATA_CONFIG,
DATA_DOCKER_API,
Expand Down Expand Up @@ -174,6 +177,26 @@ def update_callback(stats):
# Info
if self._var_id == CONTAINER_MONITOR_STATUS:
state = stats['info']['status']
if self._var_id == CONTAINER_MONITOR_STATE:

# Up 6 days
# Up 6 days (Paused)
# Exited (0) 2 months ago
# Restarting (99) 5 seconds ago

if stats['info']['status'] == 'running':
state = 'Up {}'.format(self.calcdockerformat(stats.get('info', {}).get('started')))
elif stats['info']['status'] == 'exited':
state = 'Exited ({}) {} ago'.format(stats['info']['exitcode'], self.calcdockerformat(stats.get('info', {}).get('ended')))
elif stats['info']['status'] == 'created':
state = 'Created {} ago'.format(self.calcdockerformat(stats.get('info', {}).get('created')))
elif stats['info']['status'] == 'restarting':
state = 'Restarting'
elif stats['info']['status'] == 'paused':
state = 'Up {} (Paused)'.format(self.calcdockerformat(stats.get('info', {}).get('started')))
else:
state = 'None ({})'.format(stats['info']['status'])

elif self._var_id == CONTAINER_MONITOR_UPTIME:
up_time = stats.get('info', {}).get('started')
if up_time is not None:
Expand Down Expand Up @@ -271,3 +294,43 @@ def unit_of_measurement(self):
def device_state_attributes(self):
"""Return the state attributes."""
return self._attributes

@staticmethod
def calcdockerformat(dt):

if dt == None:
return 'None'

delta = relativedelta.relativedelta(datetime.now(pytz.utc), dt)

if delta.years != 0:
if delta.years == 1:
return '{} {}'.format(delta.years, 'year')
else:
return '{} {}'.format(delta.years, 'years')
elif delta.months != 0:
if delta.months == 1:
return '{} {}'.format(delta.months, 'month')
else:
return '{} {}'.format(delta.months, 'months')
elif delta.days != 0:
if delta.days == 1:
return '{} {}'.format(delta.days, 'day')
else:
return '{} {}'.format(delta.days, 'days')
elif delta.hours != 0:
if delta.hours == 1:
return '{} {}'.format(delta.hours, 'hour')
else:
return '{} {}'.format(delta.hours, 'hours')
elif delta.minutes != 0:
if delta.minutes == 1:
return '{} {}'.format(delta.minutes, 'minute')
else:
return '{} {}'.format(delta.minutes, 'minutes')
else:
if delta.seconds == 1:
return '{} {}'.format(delta.seconds, 'second')
else:
return '{} {}'.format(delta.seconds, 'seconds')