Add timeout to request, update ordering, make dev info message shorter, and (#4613)

update the other logger messages
This commit is contained in:
Fabian Affolter 2016-11-28 20:49:01 +01:00 committed by GitHub
parent b4841a17a6
commit 4bc37bd661

View File

@ -4,34 +4,39 @@ Support to check for available updates.
For more details about this component, please refer to the documentation at For more details about this component, please refer to the documentation at
https://home-assistant.io/components/updater/ https://home-assistant.io/components/updater/
""" """
from datetime import datetime, timedelta
import logging
import json import json
import logging
import os
import platform import platform
import uuid import uuid
import os from datetime import datetime, timedelta
# pylint: disable=no-name-in-module,import-error # pylint: disable=no-name-in-module, import-error
from distutils.version import StrictVersion from distutils.version import StrictVersion
import requests import requests
import voluptuous as vol import voluptuous as vol
import homeassistant.helpers.config_validation as cv
import homeassistant.util.dt as dt_util
from homeassistant.const import __version__ as CURRENT_VERSION from homeassistant.const import __version__ as CURRENT_VERSION
from homeassistant.const import ATTR_FRIENDLY_NAME from homeassistant.const import ATTR_FRIENDLY_NAME
import homeassistant.util.dt as dt_util
from homeassistant.helpers import event from homeassistant.helpers import event
import homeassistant.helpers.config_validation as cv
_LOGGER = logging.getLogger(__name__)
UPDATER_URL = 'https://updater.home-assistant.io/'
DOMAIN = 'updater'
ENTITY_ID = 'updater.updater'
ATTR_RELEASE_NOTES = 'release_notes'
UPDATER_UUID_FILE = '.uuid'
CONF_REPORTING = 'reporting'
REQUIREMENTS = ['distro==1.0.1'] REQUIREMENTS = ['distro==1.0.1']
_LOGGER = logging.getLogger(__name__)
ATTR_RELEASE_NOTES = 'release_notes'
CONF_REPORTING = 'reporting'
DOMAIN = 'updater'
ENTITY_ID = 'updater.updater'
UPDATER_URL = 'https://updater.home-assistant.io/'
UPDATER_UUID_FILE = '.uuid'
CONFIG_SCHEMA = vol.Schema({DOMAIN: { CONFIG_SCHEMA = vol.Schema({DOMAIN: {
vol.Optional(CONF_REPORTING, default=True): cv.boolean vol.Optional(CONF_REPORTING, default=True): cv.boolean
}}, extra=vol.ALLOW_EXTRA) }}, extra=vol.ALLOW_EXTRA)
@ -41,12 +46,12 @@ def _create_uuid(hass, filename=UPDATER_UUID_FILE):
"""Create UUID and save it in a file.""" """Create UUID and save it in a file."""
with open(hass.config.path(filename), 'w') as fptr: with open(hass.config.path(filename), 'w') as fptr:
_uuid = uuid.uuid4().hex _uuid = uuid.uuid4().hex
fptr.write(json.dumps({"uuid": _uuid})) fptr.write(json.dumps({'uuid': _uuid}))
return _uuid return _uuid
def _load_uuid(hass, filename=UPDATER_UUID_FILE): def _load_uuid(hass, filename=UPDATER_UUID_FILE):
"""Load UUID from a file, or return None.""" """Load UUID from a file or return None."""
try: try:
with open(hass.config.path(filename)) as fptr: with open(hass.config.path(filename)) as fptr:
jsonf = json.loads(fptr.read()) jsonf = json.loads(fptr.read())
@ -58,12 +63,11 @@ def _load_uuid(hass, filename=UPDATER_UUID_FILE):
def setup(hass, config): def setup(hass, config):
"""Setup the updater component.""" """Set up the updater component."""
if 'dev' in CURRENT_VERSION: if 'dev' in CURRENT_VERSION:
# This component only makes sense in release versions # This component only makes sense in release versions
_LOGGER.warning(('Updater component enabled in dev. ' _LOGGER.warning("Updater component enabled in 'dev'. "
'You will not receive notifications of new ' "No notifications but analytics will be submitted")
'versions but analytics will be submitted.'))
config = config.get(DOMAIN, {}) config = config.get(DOMAIN, {})
huuid = _load_uuid(hass) if config.get(CONF_REPORTING) else None huuid = _load_uuid(hass) if config.get(CONF_REPORTING) else None
@ -85,24 +89,29 @@ def check_newest_version(hass, huuid):
return return
if StrictVersion(newest) > StrictVersion(CURRENT_VERSION): if StrictVersion(newest) > StrictVersion(CURRENT_VERSION):
_LOGGER.info('The latest available version is %s.', newest) _LOGGER.info("The latest available version is %s", newest)
hass.states.set( hass.states.set(
ENTITY_ID, newest, {ATTR_FRIENDLY_NAME: 'Update Available', ENTITY_ID, newest, {ATTR_FRIENDLY_NAME: 'Update Available',
ATTR_RELEASE_NOTES: releasenotes} ATTR_RELEASE_NOTES: releasenotes}
) )
elif StrictVersion(newest) == StrictVersion(CURRENT_VERSION): elif StrictVersion(newest) == StrictVersion(CURRENT_VERSION):
_LOGGER.info('You are on the latest version (%s) of Home Assistant.', _LOGGER.info("You are on the latest version (%s) of Home Assistant",
newest) newest)
def get_newest_version(huuid): def get_newest_version(huuid):
"""Get the newest Home Assistant version.""" """Get the newest Home Assistant version."""
info_object = {'uuid': huuid, 'version': CURRENT_VERSION, info_object = {
'timezone': dt_util.DEFAULT_TIME_ZONE.zone, 'arch': platform.machine(),
'os_name': platform.system(), "arch": platform.machine(), 'dev': ('dev' in CURRENT_VERSION),
'docker': False,
'os_name': platform.system(),
'python_version': platform.python_version(), 'python_version': platform.python_version(),
'timezone': dt_util.DEFAULT_TIME_ZONE.zone,
'uuid': huuid,
'version': CURRENT_VERSION,
'virtualenv': (os.environ.get('VIRTUAL_ENV') is not None), 'virtualenv': (os.environ.get('VIRTUAL_ENV') is not None),
'docker': False, 'dev': ('dev' in CURRENT_VERSION)} }
if platform.system() == 'Windows': if platform.system() == 'Windows':
info_object['os_version'] = platform.win32_ver()[0] info_object['os_version'] = platform.win32_ver()[0]
@ -121,17 +130,20 @@ def get_newest_version(huuid):
info_object = {} info_object = {}
try: try:
req = requests.post(UPDATER_URL, json=info_object) req = requests.post(UPDATER_URL, json=info_object, timeout=5)
res = req.json() res = req.json()
_LOGGER.info(('Submitted analytics to Home Assistant servers. ' _LOGGER.info(("Submitted analytics to Home Assistant servers. "
'Information submitted includes %s'), info_object) "Information submitted includes %s"), info_object)
return (res['version'], res['release-notes']) return (res['version'], res['release-notes'])
except requests.RequestException: except requests.RequestException:
_LOGGER.exception('Could not contact HASS Update to check for updates') _LOGGER.exception("Could not contact Home Assistant Update to check"
"for updates")
return None return None
except ValueError: except ValueError:
_LOGGER.exception('Received invalid response from HASS Update') _LOGGER.exception("Received invalid response from Home Assistant"
"Update")
return None return None
except KeyError: except KeyError:
_LOGGER.exception('Response from HASS Update did not include version') _LOGGER.exception("Response from Home Assistant Update did not"
"include version")
return None return None