summaryrefslogtreecommitdiffstats
path: root/module/plugins/hooks/UpdateManager.py
diff options
context:
space:
mode:
Diffstat (limited to 'module/plugins/hooks/UpdateManager.py')
-rw-r--r--module/plugins/hooks/UpdateManager.py209
1 files changed, 119 insertions, 90 deletions
diff --git a/module/plugins/hooks/UpdateManager.py b/module/plugins/hooks/UpdateManager.py
index 6ed756d13..c72699228 100644
--- a/module/plugins/hooks/UpdateManager.py
+++ b/module/plugins/hooks/UpdateManager.py
@@ -1,12 +1,12 @@
# -*- coding: utf-8 -*-
+from __future__ import with_statement
+
import re
import sys
from operator import itemgetter
-from os import remove, stat
-from os.path import isfile
-from time import time
+from os import path, remove, stat
from module.network.RequestFactory import getURL
from module.plugins.Hook import Expose, Hook, threaded
@@ -14,23 +14,26 @@ from module.utils import save_join
class UpdateManager(Hook):
- __name__ = "UpdateManager"
- __version__ = "0.33"
- __type__ = "hook"
+ __name__ = "UpdateManager"
+ __type__ = "hook"
+ __version__ = "0.42"
+
+ __config__ = [("activated" , "bool" , "Activated" , True ),
+ ("mode" , "pyLoad + plugins;plugins only", "Check updates for" , "pyLoad + plugins"),
+ ("interval" , "int" , "Check interval in hours" , 8 ),
+ ("autorestart" , "bool" , "Automatically restart pyLoad when required" , True ),
+ ("reloadplugins", "bool" , "Monitor plugins for code changes in debug mode", True ),
+ ("nodebugupdate", "bool" , "Don't check for updates in debug mode" , True )]
- __config__ = [("activated", "bool", "Activated", True),
- ("mode", "pyLoad + plugins;plugins only", "Check updates for", "pyLoad + plugins"),
- ("interval", "int", "Check interval in hours", 8),
- ("reloadplugins", "bool", "Monitor plugins for code changes (debug mode only)", True),
- ("nodebugupdate", "bool", "Don't check for updates in debug mode", True)]
+ __description__ = """ Check for updates """
+ __license__ = "GPLv3"
+ __authors__ = [("Walter Purcaro", "vuolter@gmail.com")]
- __description__ = """Check for updates"""
- __author_name__ = "Walter Purcaro"
- __author_mail__ = "vuolter@gmail.com"
- event_list = ["pluginConfigChanged"]
+ # event_list = ["pluginConfigChanged"]
- SERVER_URL = "http://updatemanager.pyload.org"
+ SERVER_URL = "http://updatemanager.pyload.org"
+ VERSION = re.compile(r'__version__.*=.*("|\')([\d.]+)')
MIN_INTERVAL = 3 * 60 * 60 #: 3h minimum check interval (value is in seconds)
@@ -38,33 +41,43 @@ class UpdateManager(Hook):
if name == "interval":
interval = value * 60 * 60
if self.MIN_INTERVAL <= interval != self.interval:
- self.scheduler.removeJob(self.cb)
+ self.core.scheduler.removeJob(self.cb)
self.interval = interval
self.initPeriodical()
else:
self.logDebug("Invalid interval value, kept current")
+
elif name == "reloadplugins":
if self.cb2:
- self.scheduler.removeJob(self.cb2)
+ self.core.scheduler.removeJob(self.cb2)
if value is True and self.core.debug:
self.periodical2()
+
def coreReady(self):
self.pluginConfigChanged(self.__name__, "interval", self.getConfig("interval"))
- self.pluginConfigChanged(self.__name__, "reloadplugins", self.getConfig("reloadplugins"))
+ x = lambda: self.pluginConfigChanged(self.__name__, "reloadplugins", self.getConfig("reloadplugins"))
+ self.core.scheduler.addJob(10, x, threaded=False)
+
+
+ def unload(self):
+ self.pluginConfigChanged(self.__name__, "reloadplugins", False)
+
def setup(self):
- self.scheduler = self.core.scheduler
- self.cb2 = None
+ self.cb2 = None
self.interval = self.MIN_INTERVAL
self.updating = False
- self.info = {"pyload": False, "version": None, "plugins": False}
- self.mtimes = {} #: store modification time for each plugin
+ self.info = {'pyload': False, 'version': None, 'plugins': False}
+ self.mtimes = {} #: store modification time for each plugin
+
def periodical2(self):
if not self.updating:
self.autoreloadPlugins()
- self.cb2 = self.scheduler.addJob(10, self.periodical2, threaded=False)
+
+ self.cb2 = self.core.scheduler.addJob(4, self.periodical2, threaded=False)
+
@Expose
def autoreloadPlugins(self):
@@ -82,7 +95,7 @@ class UpdateManager(Hook):
id = (type, name)
if type in self.core.pluginManager.plugins:
f = m.__file__.replace(".pyc", ".py")
- if not isfile(f):
+ if not path.isfile(f):
continue
mtime = stat(f).st_mtime
@@ -95,42 +108,53 @@ class UpdateManager(Hook):
return True if self.core.pluginManager.reloadPlugins(reloads) else False
+
def periodical(self):
if not self.info['pyload'] and not (self.getConfig("nodebugupdate") and self.core.debug):
self.updateThread()
+
def server_request(self):
try:
return getURL(self.SERVER_URL, get={'v': self.core.api.getServerVersion()}).splitlines()
except:
self.logWarning(_("Unable to contact server to get updates"))
+
@threaded
def updateThread(self):
self.updating = True
- status = self.update(onlyplugin=True if self.getConfig("mode") == "plugins only" else False)
- if status == 2:
+
+ status = self.update(onlyplugin=self.getConfig("mode") == "plugins only")
+
+ if status is 2 and self.getConfig("autorestart"):
self.core.api.restart()
else:
self.updating = False
+
@Expose
def updatePlugins(self):
""" simple wrapper for calling plugin update quickly """
return self.update(onlyplugin=True)
+
@Expose
def update(self, onlyplugin=False):
""" check for updates """
data = self.server_request()
+
if not data:
exitcode = 0
+
elif data[0] == "None":
self.logInfo(_("No new pyLoad version available"))
updates = data[1:]
exitcode = self._updatePlugins(updates)
+
elif onlyplugin:
exitcode = 0
+
else:
newversion = data[0]
self.logInfo(_("*** New pyLoad Version %s available ***") % newversion)
@@ -138,38 +162,62 @@ class UpdateManager(Hook):
exitcode = 3
self.info['pyload'] = True
self.info['version'] = newversion
+
return exitcode #: 0 = No plugins updated; 1 = Plugins updated; 2 = Plugins updated, but restart required; 3 = No plugins updated, new pyLoad version available
+
def _updatePlugins(self, updates):
""" check for plugin updates """
if self.info['plugins']:
return False #: plugins were already updated
- updated = []
+ exitcode = 0
+ updated = []
- vre = re.compile(r'__version__.*=.*("|\')([0-9.]+)')
- url = updates[0]
+ url = updates[0]
schema = updates[1].split('|')
+
if "BLACKLIST" in updates:
blacklist = updates[updates.index('BLACKLIST') + 1:]
- updates = updates[2:updates.index('BLACKLIST')]
+ updates = updates[2:updates.index('BLACKLIST')]
else:
blacklist = None
- updates = updates[2:]
+ updates = updates[2:]
+
+ upgradable = [dict(zip(schema, x.split('|'))) for x in updates]
+ blacklisted = [(x.split('|')[0], x.split('|')[1].rsplit('.', 1)[0]) for x in blacklist] if blacklist else []
+
+ if blacklist:
+ # Protect UpdateManager from self-removing
+ try:
+ blacklisted.remove(("hook", "UpdateManager"))
+ except:
+ pass
+
+ for t, n in blacklisted:
+ for idx, plugin in enumerate(upgradable):
+ if n == plugin['name'] and t == plugin['type']:
+ upgradable.pop(idx)
+ break
+
+ for t, n in self.removePlugins(sorted(blacklisted)):
+ self.logInfo(_("Removed blacklisted plugin [%(type)s] %(name)s") % {
+ 'type': t,
+ 'name': n,
+ })
- upgradable = sorted(map(lambda x: dict(zip(schema, x.split('|'))), updates), key=itemgetter("type", "name"))
- for plugin in upgradable:
+ for plugin in sorted(upgradable, key=itemgetter("type", "name")):
filename = plugin['name']
- prefix = plugin['type']
- version = plugin['version']
+ prefix = plugin['type']
+ version = plugin['version']
if filename.endswith(".pyc"):
name = filename[:filename.find("_")]
else:
name = filename.replace(".py", "")
- #TODO: obsolete in 0.5.0
+ #@TODO: obsolete after 0.4.10
if prefix.endswith("s"):
type = prefix[:-1]
else:
@@ -181,47 +229,30 @@ class UpdateManager(Hook):
newver = float(version)
if not oldver:
- msg = "New version of [%(type)s] %(name)s (v%(newver)s)"
+ msg = "New plugin: [%(type)s] %(name)s (v%(newver).2f)"
elif newver > oldver:
- msg = "New version of [%(type)s] %(name)s (v%(oldver)s -> v%(newver)s)"
+ msg = "New version of plugin: [%(type)s] %(name)s (v%(oldver).2f -> v%(newver).2f)"
else:
continue
- self.logInfo(_(msg) % {
- "type": type,
- "name": name,
- "oldver": oldver,
- "newver": newver
- })
-
+ self.logInfo(_(msg) % {'type' : type,
+ 'name' : name,
+ 'oldver': oldver,
+ 'newver': newver})
try:
content = getURL(url % plugin)
- m = vre.search(content)
+ m = self.VERSION.search(content)
+
if m and m.group(2) == version:
- f = open(save_join("userplugins", prefix, filename), "wb")
- f.write(content)
- f.close()
+ with open(save_join("userplugins", prefix, filename), "wb") as f:
+ f.write(content)
+
updated.append((prefix, name))
else:
- raise Exception(_("Version mismatch"))
- except Exception, e:
- self.logError(_("Error updating plugin %s") % filename, str(e))
-
- if blacklist:
- blacklisted = sorted(map(lambda x: (x.split('|')[0], x.split('|')[1].rsplit('.', 1)[0]), blacklist))
+ raise Exception, _("Version mismatch")
- # Always protect UpdateManager from self-removing
- try:
- blacklisted.remove(("hook", "UpdateManager"))
- except:
- pass
-
- removed = self.removePlugins(blacklisted)
- for t, n in removed:
- self.logInfo(_("Removed blacklisted plugin [%(type)s] %(name)s") % {
- "type": t,
- "name": n
- })
+ except Exception, e:
+ self.logError(_("Error updating plugin: %s") % filename, str(e))
if updated:
reloaded = self.core.pluginManager.reloadPlugins(updated)
@@ -234,47 +265,45 @@ class UpdateManager(Hook):
exitcode = 2
else:
self.logInfo(_("No plugin updates available"))
- exitcode = 0
return exitcode #: 0 = No plugins updated; 1 = Plugins updated; 2 = Plugins updated, but restart required
+
@Expose
def removePlugins(self, type_plugins):
- """ delete plugins from disk"""
+ """ delete plugins from disk """
if not type_plugins:
- return None
+ return
- self.logDebug("Request deletion of plugins: %s" % type_plugins)
+ self.logDebug("Requested deletion of plugins: %s" % type_plugins)
removed = []
for type, name in type_plugins:
- rflag = False
- py_file = name + ".py"
- pyc_file = name + ".pyc"
+ err = False
+ file = name + ".py"
- for root in ("userplugins", save_join(pypath, "module", "plugins")):
- py_filename = save_join(root, type, py_file)
- pyc_filename = save_join(root, type, pyc_file)
+ for root in ("userplugins", path.join(pypath, "module", "plugins")):
- if isfile(py_filename):
- try:
- remove(py_filename)
- except Exception, e:
- self.logError("Error deleting file %s" % py_filename, str(e))
- rflag = False
- else:
- rflag = True
+ filename = save_join(root, type, file)
+ try:
+ remove(filename)
+ except Exception, e:
+ self.logDebug("Error removing: %s" % path.basename(filename), str(e))
+ err = True
- if isfile(pyc_filename):
+ filename += "c"
+ if path.isfile(filename):
try:
if type == "hook":
self.manager.deactivateHook(name)
- remove(pyc_filename)
+ remove(filename)
except Exception, e:
- self.logError("Error deleting file %s" % pyc_filename, str(e))
- if rflag:
+ self.logDebug("Error removing: %s" % path.basename(filename), str(e))
+ err = True
+
+ if not err:
id = (type, name)
removed.append(id)