From 18952c57ff649a52a8f6eee9bebac5f48842eedc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 14 May 2014 12:59:57 +0200 Subject: [PATCH 01/39] Added automatic migration of old event subscription format to the new one (cherry picked from commit e7088ef) --- src/octoprint/events.py | 101 ++++++++++++++++-------------- src/octoprint/server/__init__.py | 5 +- src/octoprint/settings.py | 103 ++++++++++++++++++++++++++++--- 3 files changed, 150 insertions(+), 59 deletions(-) diff --git a/src/octoprint/events.py b/src/octoprint/events.py index f9216b067..6b3324545 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -203,36 +203,42 @@ class DebugEventListener(GenericEventListener): class CommandTrigger(GenericEventListener): - def __init__(self, triggerType, printer): + def __init__(self, printer): GenericEventListener.__init__(self) self._printer = printer self._subscriptions = {} - self._initSubscriptions(triggerType) + self._initSubscriptions() - def _initSubscriptions(self, triggerType): + def _initSubscriptions(self): """ Subscribes all events as defined in "events > $triggerType > subscriptions" in the settings with their respective commands. """ - if not settings().get(["events", triggerType]): + if not settings().get(["events"]): return - if not settings().getBoolean(["events", triggerType, "enabled"]): + if not settings().getBoolean(["events", "enabled"]): return eventsToSubscribe = [] - for subscription in settings().get(["events", triggerType, "subscriptions"]): - if not "event" in subscription.keys() or not "command" in subscription.keys(): - self._logger.info("Invalid %s, missing either event or command: %r" % (triggerType, subscription)) + for subscription in settings().get(["events", "subscriptions"]): + if not "event" in subscription.keys() or not "command" in subscription.keys() \ + or not "type" in subscription.keys() or not subscription["type"] in ["system", "gcode"]: + self._logger.info("Invalid command trigger, missing either event, type or command or type is invalid: %r" % subscription) + continue + + if "enabled" in subscription.keys() and not subscription["enabled"]: + self._logger.info("Disabled command trigger: %r" % subscription) continue event = subscription["event"] command = subscription["command"] + commandType = subscription["type"] if not event in self._subscriptions.keys(): self._subscriptions[event] = [] - self._subscriptions[event].append(command) + self._subscriptions[event].append((command, commandType)) if not event in eventsToSubscribe: eventsToSubscribe.append(event) @@ -250,18 +256,48 @@ class CommandTrigger(GenericEventListener): if not event in self._subscriptions: return - for command in self._subscriptions[event]: + for command, commandType in self._subscriptions[event]: try: - processedCommand = self._processCommand(command, payload) - self.executeCommand(processedCommand) + if isinstance(command, (tuple, list, set)): + processedCommand = [] + for c in command: + processedCommand.append(self._processCommand(c, payload)) + else: + processedCommand = self._processCommand(command, payload) + self.executeCommand(processedCommand, commandType) except KeyError, e: self._logger.warn("There was an error processing one or more placeholders in the following command: %s" % command) - def executeCommand(self, command): - """ - Not implemented, override in child classes - """ - pass + def executeCommand(self, command, commandType): + if commandType == "system": + self._executeSystemCommand(command) + elif commandType == "gcode": + self._executeGcodeCommand(command) + + def _executeSystemCommand(self, command): + def commandExecutioner(command): + self._logger.info("Executing system command: %s" % command) + subprocess.Popen(command, shell=True) + + try: + if isinstance(command, (list, tuple, set)): + for c in command: + commandExecutioner(c) + else: + commandExecutioner(command) + except subprocess.CalledProcessError, e: + self._logger.warn("Command failed with return code %i: %s" % (e.returncode, e.message)) + except Exception, ex: + self._logger.exception("Command failed") + + def _executeGcodeCommand(self, command): + commands = [command] + if isinstance(command, (list, tuple, set)): + self.logger.debug("Executing GCode commands: %r" % command) + commands = list(command) + else: + self._logger.debug("Executing GCode command: %s" % command) + self._printer.commands(commands) def _processCommand(self, command, payload): """ @@ -302,34 +338,3 @@ class CommandTrigger(GenericEventListener): params.update(payload) return command.format(**params) - - -class SystemCommandTrigger(CommandTrigger): - """ - Performs configured system commands for configured events. - """ - - def __init__(self, printer): - CommandTrigger.__init__(self, "systemCommandTrigger", printer) - - def executeCommand(self, command): - try: - self._logger.info("Executing system command: %s" % command) - subprocess.Popen(command, shell=True) - except subprocess.CalledProcessError, e: - self._logger.warn("Command failed with return code %i: %s" % (e.returncode, e.message)) - except Exception, ex: - self._logger.exception("Command failed") - - -class GcodeCommandTrigger(CommandTrigger): - """ - Sends configured GCODE commands to the printer for configured events. - """ - - def __init__(self, printer): - CommandTrigger.__init__(self, "gcodeCommandTrigger", printer) - - def executeCommand(self, command): - self._logger.debug("Executing GCode command: %s" % command) - self._printer.commands(command.split(",")) diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 28f186ccc..692bc5f09 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -135,9 +135,8 @@ class Server(): # configure timelapse octoprint.timelapse.configureTimelapse() - # setup system and gcode command triggers - events.SystemCommandTrigger(printer) - events.GcodeCommandTrigger(printer) + # setup command triggers + events.CommandTrigger(printer) if self._debug: events.DebugEventListener() diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index e116f652f..4a724138f 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -125,12 +125,8 @@ default_settings = { "config": "/default/path/to/your/cura/config.ini" }, "events": { - "systemCommandTrigger": { - "enabled": False - }, - "gcodeCommandTrigger": { - "enabled": False - } + "enabled": False, + "subscriptions": [] }, "api": { "enabled": False, @@ -173,7 +169,7 @@ class Settings(object): self._configfile = configfile else: self._configfile = os.path.join(self.settings_dir, "config.yaml") - self.load() + self.load(migrate=True) def _init_settings_dir(self, basedir): if basedir is not None: @@ -189,7 +185,7 @@ class Settings(object): #~~ load and save - def load(self): + def load(self, migrate=False): if os.path.exists(self._configfile) and os.path.isfile(self._configfile): with open(self._configfile, "r") as f: self._config = yaml.safe_load(f) @@ -197,6 +193,97 @@ class Settings(object): if not self._config: self._config = {} + if migrate: + self._migrateConfig() + + def _migrateConfig(self): + if not self._config: + return + + if "events" in self._config.keys() and ("gcodeCommandTrigger" in self._config["events"] or "systemCommandTrigger" in self._config["events"]): + self._logger.info("Migrating config (event subscriptions)...") + + # migrate event hooks to new format + placeholderRe = re.compile("%\((.*?)\)s") + + eventNameReplacements = { + "ClientOpen": "ClientOpened", + "TransferStart": "TransferStarted" + } + payloadDataReplacements = { + "Upload": {"data": "{file}", "filename": "{file}"}, + "Connected": {"data": "{port} at {baudrate} baud"}, + "FileSelected": {"data": "{file}", "filename": "{file}"}, + "TransferStarted": {"data": "{remote}", "filename": "{remote}"}, + "TransferDone": {"data": "{remote}", "filename": "{remote}"}, + "ZChange": {"data": "{new}"}, + "CaptureStart": {"data": "{file}"}, + "CaptureDone": {"data": "{file}"}, + "MovieDone": {"data": "{movie}", "filename": "{gcode}"}, + "Error": {"data": "{error}"}, + "PrintStarted": {"data": "{file}", "filename": "{file}"}, + "PrintDone": {"data": "{file}", "filename": "{file}"}, + } + + def migrateEventHook(event, command): + # migrate placeholders + command = placeholderRe.sub("{__\\1}", command) + + # migrate event names + if event in eventNameReplacements: + event = eventNameReplacements["event"] + + # migrate payloads to more specific placeholders + if event in payloadDataReplacements: + for key in payloadDataReplacements[event]: + command = command.replace("{__%s}" % key, payloadDataReplacements[event][key]) + + # return processed tuple + return event, command + + disableSystemCommands = False + if "systemCommandTrigger" in self._config["events"] and "enabled" in self._config["events"]["systemCommandTrigger"]: + disableSystemCommands = not self._config["events"]["systemCommandTrigger"]["enabled"] + + disableGcodeCommands = False + if "gcodeCommandTrigger" in self._config["events"] and "enabled" in self._config["events"]["gcodeCommandTrigger"]: + disableGcodeCommands = not self._config["events"]["gcodeCommandTrigger"]["enabled"] + + disableAllCommands = disableSystemCommands and disableGcodeCommands + newEvents = { + "enabled": not disableAllCommands, + "subscriptions": [] + } + + if "systemCommandTrigger" in self._config["events"] and "subscriptions" in self._config["events"]["systemCommandTrigger"]: + for trigger in self._config["events"]["systemCommandTrigger"]["subscriptions"]: + if not ("event" in trigger and "command" in trigger): + continue + + newTrigger = {"type": "system"} + if disableSystemCommands and not disableAllCommands: + newTrigger["enabled"] = False + + newTrigger["event"], newTrigger["command"] = migrateEventHook(trigger["event"], trigger["command"]) + newEvents["subscriptions"].append(newTrigger) + + if "gcodeCommandTrigger" in self._config["events"] and "subscriptions" in self._config["events"]["gcodeCommandTrigger"]: + for trigger in self._config["events"]["gcodeCommandTrigger"]["subscriptions"]: + if not ("event" in trigger and "command" in trigger): + continue + + newTrigger = {"type": "gcode"} + if disableGcodeCommands and not disableAllCommands: + newTrigger["enabled"] = False + + newTrigger["event"], newTrigger["command"] = migrateEventHook(trigger["event"], trigger["command"]) + newTrigger["command"] = newTrigger["command"].split(",") + newEvents["subscriptions"].append(newTrigger) + + self._config["events"] = newEvents + self.save(force=True) + self._logger.info("Migrated %d event subscriptions to new format and structure" % len(newEvents["subscriptions"])) + def save(self, force=False): if not self._dirty and not force: return From e51d9439c53a50ac7e11780a391d52c17dceb6ae Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 2 Sep 2014 11:35:42 +0200 Subject: [PATCH 02/39] Modified versioneer to allow specification of manual versions based on branches You can now define a lookup file explicitely mapping virtual version tags to branches via regular expressions and a reference commit from which the commit distance will be calculated. Format of the file is The file is processed from top to bottom, the first matching line wins. If or are left out, the lookup table does not apply to the matched branches and the regular versioneer resolution (via git describe) takes place. Current configuration makes "master", "staging" and any branch starting with "fix/" make use the default behaviour, all other branches (so basically all development branches) are defined as "1.2.0-dev" (cherry picked from commit 212f40c) --- .versioneer-lookup | 18 ++++ setup.py | 1 + src/octoprint/_version.py | 101 +++++++++++++++++-- versioneer.py | 206 +++++++++++++++++++++++++++++++++++--- 4 files changed, 303 insertions(+), 23 deletions(-) create mode 100644 .versioneer-lookup diff --git a/.versioneer-lookup b/.versioneer-lookup new file mode 100644 index 000000000..8e1218d79 --- /dev/null +++ b/.versioneer-lookup @@ -0,0 +1,18 @@ +# Configuration file for the versioneer lookup, manually mapping tags based on branches +# +# Format is +# +# +# +# The file is processed from top to bottom, the first matching line wins. If or are left out, +# the lookup table does not apply to the matched branches + +# master and staging shall not use the lookup table +master +staging + +# fix/ branches are fixes for master, so we don't handle those either +fix/.* + +# every other branch is a development branch and thus gets resolved to 1.2.0-dev for now +.* 1.2.0-dev 50cf776e70b9 diff --git a/setup.py b/setup.py index 471e546f3..d06296ea2 100644 --- a/setup.py +++ b/setup.py @@ -7,6 +7,7 @@ versioneer.versionfile_source = 'src/octoprint/_version.py' versioneer.versionfile_build = 'octoprint/_version.py' versioneer.tag_prefix = '' versioneer.parentdir_prefix = '' +versioneer.lookupfile = '.versioneer-lookup' from setuptools import setup, find_packages, Command import os diff --git a/src/octoprint/_version.py b/src/octoprint/_version.py index f9a41364b..52aefd494 100644 --- a/src/octoprint/_version.py +++ b/src/octoprint/_version.py @@ -54,6 +54,18 @@ import sys import re import os.path +def get_gits(root, verbose=False): + if not os.path.exists(os.path.join(root, ".git")): + if verbose: + print("no .git in %s" % root) + return None + + GITS = ["git"] + if sys.platform == "win32": + GITS = ["git.cmd", "git.exe"] + return GITS + + def get_expanded_variables(versionfile_abs): # the code embedded in _version.py can just fetch the value of these # variables. When used from setup.py, we don't want to import @@ -114,20 +126,60 @@ def versions_from_expanded_variables(variables, tag_prefix, verbose=False): return { "version": variables["full"].strip(), "full": variables["full"].strip() } +def versions_from_lookup(lookup, root, verbose=False): + GITS = get_gits(root, verbose=verbose) + if GITS is None: + return {} + + stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], + cwd=root) + if stdout is None: + return {} + + current_branch = stdout.strip() + for matcher, tag, ref_commit in lookup: + if matcher.match(current_branch): + if tag is None or ref_commit is None: + return {} + + stdout = run_command(GITS, ["rev-list", "%s..HEAD" % ref_commit, "--count"], cwd=root) + if stdout is None: + return {} + num_commits = stdout.strip() + + stdout =run_command(GITS, ["rev-parse", "--short", "HEAD"], cwd=root) + if stdout is None: + return {} + short_hash = stdout.strip() + + stdout = run_command(GITS, ["describe", "--tags", "--dirty", "--always"], cwd=root) + if stdout is None: + return {} + dirty = stdout.strip().endswith("-dirty") + + stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + if stdout is None: + return {} + full = stdout.strip() + + version = "%s-%s-g%s" % (tag, num_commits, short_hash) + if dirty: + version += "-dirty" + full += "-dirty" + return {"version": version, "full": full} + + return {} + def versions_from_vcs(tag_prefix, root, verbose=False): # this runs 'git' from the root of the source tree. This only gets called # if the git-archive 'subst' variables were *not* expanded, and # _version.py hasn't already been rewritten with a short version string, # meaning we're inside a checked out source tree. - if not os.path.exists(os.path.join(root, ".git")): - if verbose: - print("no .git in %s" % root) + GITS = get_gits(root, verbose=verbose) + if GITS is None: return {} - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] stdout = run_command(GITS, ["describe", "--tags", "--dirty", "--always"], cwd=root) if stdout is None: @@ -158,10 +210,39 @@ def versions_from_parentdir(parentdir_prefix, root, verbose=False): return {"version": dirname[len(parentdir_prefix):], "full": ""} tag_prefix = "" -parentdir_prefix = "octoprint-" +parentdir_prefix = "" versionfile_source = "src/octoprint/_version.py" +lookupfile = ".versioneer-lookup" -def get_versions(default={"version": "unknown", "full": ""}, verbose=False): +def parse_lookup_file(root, lookup_path=None): + if not lookup_path: + lookup_path = lookupfile + if not lookup_path: + return [] + + path = os.path.join(root, lookup_path) + if not os.path.exists(path): + return [] + + import re + lookup = [] + with open(os.path.join(root, lookup_path), "r") as f: + for line in f: + if '#' in line: + line = line[:line.rindex('#')] + line = line.strip() + try: + split_line = line.split() + if len(split_line) == 3: + pattern, tag, ref_commit = split_line + lookup.append([re.compile(pattern), tag, ref_commit]) + elif len(split_line) >= 1: + lookup.append([re.compile(split_line[0]), None, None]) + except: + break + return lookup + +def get_versions(default={"version": "unknown", "full": ""}, lookup_path=None, verbose=False): # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which @@ -182,7 +263,9 @@ def get_versions(default={"version": "unknown", "full": ""}, verbose=False): except NameError: return default - return (versions_from_vcs(tag_prefix, root, verbose) + lookup = parse_lookup_file(root, lookup_path=lookup_path) + return (versions_from_lookup(lookup, root, verbose) + or versions_from_vcs(tag_prefix, root, verbose) or versions_from_parentdir(parentdir_prefix, root, verbose) or default) diff --git a/versioneer.py b/versioneer.py index a01ab1cef..237968f19 100644 --- a/versioneer.py +++ b/versioneer.py @@ -252,6 +252,7 @@ versionfile_source = None versionfile_build = None tag_prefix = None parentdir_prefix = None +lookupfile = None VCS = "git" @@ -312,6 +313,18 @@ import sys import re import os.path +def get_gits(root, verbose=False): + if not os.path.exists(os.path.join(root, ".git")): + if verbose: + print("no .git in %%s" %% root) + return None + + GITS = ["git"] + if sys.platform == "win32": + GITS = ["git.cmd", "git.exe"] + return GITS + + def get_expanded_variables(versionfile_abs): # the code embedded in _version.py can just fetch the value of these # variables. When used from setup.py, we don't want to import @@ -372,20 +385,60 @@ def versions_from_expanded_variables(variables, tag_prefix, verbose=False): return { "version": variables["full"].strip(), "full": variables["full"].strip() } +def versions_from_lookup(lookup, root, verbose=False): + GITS = get_gits(root, verbose=verbose) + if GITS is None: + return {} + + stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], + cwd=root) + if stdout is None: + return {} + + current_branch = stdout.strip() + for matcher, tag, ref_commit in lookup: + if matcher.match(current_branch): + if tag is None or ref_commit is None: + return {} + + stdout = run_command(GITS, ["rev-list", "%%s..HEAD" %% ref_commit, "--count"], cwd=root) + if stdout is None: + return {} + num_commits = stdout.strip() + + stdout =run_command(GITS, ["rev-parse", "--short", "HEAD"], cwd=root) + if stdout is None: + return {} + short_hash = stdout.strip() + + stdout = run_command(GITS, ["describe", "--tags", "--dirty", "--always"], cwd=root) + if stdout is None: + return {} + dirty = stdout.strip().endswith("-dirty") + + stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + if stdout is None: + return {} + full = stdout.strip() + + version = "%%s-%%s-g%%s" %% (tag, num_commits, short_hash) + if dirty: + version += "-dirty" + full += "-dirty" + return {"version": version, "full": full} + + return {} + def versions_from_vcs(tag_prefix, root, verbose=False): # this runs 'git' from the root of the source tree. This only gets called # if the git-archive 'subst' variables were *not* expanded, and # _version.py hasn't already been rewritten with a short version string, # meaning we're inside a checked out source tree. - if not os.path.exists(os.path.join(root, ".git")): - if verbose: - print("no .git in %%s" %% root) + GITS = get_gits(root, verbose=verbose) + if GITS is None: return {} - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] stdout = run_command(GITS, ["describe", "--tags", "--dirty", "--always"], cwd=root) if stdout is None: @@ -418,8 +471,37 @@ def versions_from_parentdir(parentdir_prefix, root, verbose=False): tag_prefix = "%(TAG_PREFIX)s" parentdir_prefix = "%(PARENTDIR_PREFIX)s" versionfile_source = "%(VERSIONFILE_SOURCE)s" +lookupfile = %(LOOKUPFILE)s -def get_versions(default={"version": "unknown", "full": ""}, verbose=False): +def parse_lookup_file(root, lookup_path=None): + if not lookup_path: + lookup_path = lookupfile + if not lookup_path: + return [] + + path = os.path.join(root, lookup_path) + if not os.path.exists(path): + return [] + + import re + lookup = [] + with open(os.path.join(root, lookup_path), "r") as f: + for line in f: + if '#' in line: + line = line[:line.rindex('#')] + line = line.strip() + try: + split_line = line.split() + if len(split_line) == 3: + pattern, tag, ref_commit = split_line + lookup.append([re.compile(pattern), tag, ref_commit]) + elif len(split_line) >= 1: + lookup.append([re.compile(split_line[0]), None, None]) + except: + break + return lookup + +def get_versions(default={"version": "unknown", "full": ""}, lookup_path=None, verbose=False): # I am in _version.py, which lives at ROOT/VERSIONFILE_SOURCE. If we have # __file__, we can work backwards from there to the root. Some # py2exe/bbfreeze/non-CPython implementations don't do __file__, in which @@ -440,7 +522,9 @@ def get_versions(default={"version": "unknown", "full": ""}, verbose=False): except NameError: return default - return (versions_from_vcs(tag_prefix, root, verbose) + lookup = parse_lookup_file(root, lookup_path=lookup_path) + return (versions_from_lookup(lookup, root, verbose) + or versions_from_vcs(tag_prefix, root, verbose) or versions_from_parentdir(parentdir_prefix, root, verbose) or default) @@ -488,6 +572,18 @@ import sys import re import os.path +def get_gits(root, verbose=False): + if not os.path.exists(os.path.join(root, ".git")): + if verbose: + print("no .git in %s" % root) + return None + + GITS = ["git"] + if sys.platform == "win32": + GITS = ["git.cmd", "git.exe"] + return GITS + + def get_expanded_variables(versionfile_abs): # the code embedded in _version.py can just fetch the value of these # variables. When used from setup.py, we don't want to import @@ -548,20 +644,62 @@ def versions_from_expanded_variables(variables, tag_prefix, verbose=False): return { "version": variables["full"].strip(), "full": variables["full"].strip() } + +def versions_from_lookup(lookup, root, verbose=False): + GITS = get_gits(root, verbose=verbose) + if GITS is None: + return {} + + stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], + cwd=root) + if stdout is None: + return {} + + current_branch = stdout.strip() + for matcher, tag, ref_commit in lookup: + if matcher.match(current_branch): + if tag is None or ref_commit is None: + return {} + + stdout = run_command(GITS, ["rev-list", "%s..HEAD" % ref_commit, "--count"], cwd=root) + if stdout is None: + return {} + num_commits = stdout.strip() + + stdout =run_command(GITS, ["rev-parse", "--short", "HEAD"], cwd=root) + if stdout is None: + return {} + short_hash = stdout.strip() + + stdout = run_command(GITS, ["describe", "--tags", "--dirty", "--always"], cwd=root) + if stdout is None: + return {} + dirty = stdout.strip().endswith("-dirty") + + stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root) + if stdout is None: + return {} + full = stdout.strip() + + version = "%s-%s-g%s" % (tag, num_commits, short_hash) + if dirty: + version += "-dirty" + full += "-dirty" + return {"version": version, "full": full} + + return {} + + def versions_from_vcs(tag_prefix, root, verbose=False): # this runs 'git' from the root of the source tree. This only gets called # if the git-archive 'subst' variables were *not* expanded, and # _version.py hasn't already been rewritten with a short version string, # meaning we're inside a checked out source tree. - if not os.path.exists(os.path.join(root, ".git")): - if verbose: - print("no .git in %s" % root) + GITS = get_gits(root, verbose=verbose) + if GITS is None: return {} - GITS = ["git"] - if sys.platform == "win32": - GITS = ["git.cmd", "git.exe"] stdout = run_command(GITS, ["describe", "--tags", "--dirty", "--always"], cwd=root) if stdout is None: @@ -684,11 +822,38 @@ def get_root(): except NameError: return os.path.dirname(os.path.abspath(sys.argv[0])) +def parse_lookup_file(root, lookup_path=None): + if not lookup_path: + lookup_path = lookupfile + + path = os.path.join(root, lookup_path) + if not os.path.exists(path): + return [] + + import re + lookup = [] + with open(os.path.join(root, lookup_path), "r") as f: + for line in f: + if '#' in line: + line = line[:line.rindex("#")] + line = line.strip() + try: + split_line = line.split() + if len(split_line) == 3: + pattern, tag, ref_commit = split_line + lookup.append([re.compile(pattern), tag, ref_commit]) + elif len(split_line) >= 1: + lookup.append([re.compile(split_line[0]), None, None]) + except: + break + return lookup + def get_versions(default=DEFAULT, verbose=False): # returns dict with two keys: 'version' and 'full' assert versionfile_source is not None, "please set versioneer.versionfile_source" assert tag_prefix is not None, "please set versioneer.tag_prefix" assert parentdir_prefix is not None, "please set versioneer.parentdir_prefix" + # I am in versioneer.py, which must live at the top of the source tree, # which we use to compute the root directory. py2exe/bbfreeze/non-CPython # don't have __file__, in which case we fall back to sys.argv[0] (which @@ -697,6 +862,11 @@ def get_versions(default=DEFAULT, verbose=False): root = get_root() versionfile_abs = os.path.join(root, versionfile_source) + if lookupfile: + lookup = parse_lookup_file(root, lookup_path = lookupfile) + else: + lookup = None + # extract version from first of _version.py, 'git describe', parentdir. # This is meant to work for developers using a source checkout, for users # of a tarball created by 'setup.py sdist', and for users of a @@ -715,6 +885,12 @@ def get_versions(default=DEFAULT, verbose=False): if verbose: print("got version from file %s %s" % (versionfile_abs,ver)) return ver + if lookup: + ver = versions_from_lookup(lookup, root, verbose=verbose) + if ver: + if verbose: print("got version from lookup %s" % ver) + return ver + ver = versions_from_vcs(tag_prefix, root, verbose) if ver: if verbose: print("got version from git %s" % ver) @@ -792,6 +968,7 @@ if 'cx_Freeze' in sys.modules: # cx_freeze enabled? "TAG_PREFIX": tag_prefix, "PARENTDIR_PREFIX": parentdir_prefix, "VERSIONFILE_SOURCE": versionfile_source, + "LOOKUPFILE": '"%s"' % lookupfile if lookupfile is not None else "None", }) f.close() @@ -835,6 +1012,7 @@ class cmd_update_files(Command): "TAG_PREFIX": tag_prefix, "PARENTDIR_PREFIX": parentdir_prefix, "VERSIONFILE_SOURCE": versionfile_source, + "LOOKUPFILE": '"%s"' % lookupfile if lookupfile is not None else "None", }) f.close() From 45c1958d8368084090c0bdd3706cf59a0d15e239 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 2 Sep 2014 12:06:02 +0200 Subject: [PATCH 03/39] Versioneer now also returns and persists the branch from which OctoPrint was installed Changed version output accordingly to now display "{version} ({branch} branch)" if branch information is available (which should be the case if installation was performed from git). (cherry picked from commit a48b5de) --- src/octoprint/_version.py | 11 +++++++++-- src/octoprint/server/__init__.py | 9 +++++++-- src/octoprint/templates/index.jinja2 | 2 +- versioneer.py | 25 +++++++++++++++++++++---- 4 files changed, 38 insertions(+), 9 deletions(-) diff --git a/src/octoprint/_version.py b/src/octoprint/_version.py index 52aefd494..3808a4f84 100644 --- a/src/octoprint/_version.py +++ b/src/octoprint/_version.py @@ -166,7 +166,7 @@ def versions_from_lookup(lookup, root, verbose=False): if dirty: version += "-dirty" full += "-dirty" - return {"version": version, "full": full} + return {"version": version, "full": full, "branch": current_branch} return {} @@ -195,7 +195,14 @@ def versions_from_vcs(tag_prefix, root, verbose=False): full = stdout.strip() if tag.endswith("-dirty"): full += "-dirty" - return {"version": tag, "full": full} + + stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], + cwd=root) + if stdout is None: + branch = None + else: + branch = stdout.strip() + return {"version": tag, "full": full, "branch": branch} def versions_from_parentdir(parentdir_prefix, root, verbose=False): diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 692bc5f09..3f38b899e 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -41,8 +41,12 @@ import octoprint.timelapse import octoprint._version -VERSION = octoprint._version.get_versions()['version'] +versions = octoprint._version.get_versions() +VERSION = versions['version'] +BRANCH = versions['branch'] if 'branch' in versions else None +DISPLAY_VERSION = "%s (%s branch)" % (VERSION, BRANCH) if BRANCH else VERSION +del versions @app.route("/") def index(): @@ -58,6 +62,7 @@ def index(): firstRun=settings().getBoolean(["server", "firstRun"]) and (userManager is None or not userManager.hasBeenCustomized()), debug=debug, version=VERSION, + display_version=DISPLAY_VERSION, stylesheet=settings().get(["devel", "stylesheet"]), gcodeMobileThreshold=settings().get(["gcodeViewer", "mobileSizeThreshold"]), gcodeThreshold=settings().get(["gcodeViewer", "sizeThreshold"]) @@ -126,7 +131,7 @@ class Server(): self._initLogging(self._debug) logger = logging.getLogger(__name__) - logger.info("Starting OctoPrint (%s)" % VERSION) + logger.info("Starting OctoPrint %s" % DISPLAY_VERSION) eventManager = events.eventManager() gcodeManager = gcodefiles.GcodeManager() diff --git a/src/octoprint/templates/index.jinja2 b/src/octoprint/templates/index.jinja2 index 70c30fd61..28d5b4f3a 100644 --- a/src/octoprint/templates/index.jinja2 +++ b/src/octoprint/templates/index.jinja2 @@ -597,7 +597,7 @@ From 1c0721f179c9b2a0c0d8d15dbb940edbc7b5e521 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 12 Sep 2014 11:21:39 +0200 Subject: [PATCH 28/39] Introduced __plugin_init__ method called after all plugins have been discovered Plugins may be able to use this method for final setups before the implementations and hooks are evaluated, e.g. for adjusting their offered functionality based on what other plugins are available. --- src/octoprint/plugin/core.py | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index 1a4eae0e6..627e9eee5 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -28,6 +28,8 @@ class PluginInfo(object): attr_check = '__plugin_check__' + attr_init = '__plugin_init__' + def __init__(self, key, location, instance, version=None): self.key = key self.location = location @@ -82,6 +84,10 @@ class PluginInfo(object): def check(self): return self._get_instance_attribute(self.__class__.attr_check, default=lambda: True) + @property + def init(self): + return self._get_instance_attribute(self.__class__.attr_init, default=lambda: True) + def _get_instance_attribute(self, attr, default=None): if not hasattr(self.instance, attr): return default @@ -205,8 +211,14 @@ class PluginManager(object): self.plugins = self._find_plugins() for name, plugin in self.plugins.items(): + # initialize the plugin + plugin.init() + + # evaluate registered hooks for hook, callback in plugin.hooks.items(): self.plugin_hooks[hook].append((name, callback)) + + # evaluate registered implementations for plugin_type in self.plugin_types: implementations = plugin.get_implementations(plugin_type) self.plugin_implementations[plugin_type] += ( (name, implementation) for implementation in implementations ) @@ -240,13 +252,13 @@ class PluginManager(object): return set() return {impl[0]: impl[1] for impl in result} - def get_helpers(self, name, helpers=None): + def get_helpers(self, name, *helpers): if not name in self.plugins: return None plugin = self.plugins[name] all_helpers = plugin.helpers - if helpers: + if len(helpers): return dict((k, v) for (k, v) in all_helpers.items() if k in helpers) else: return all_helpers From e69c1e8e93fa9a8500feaf69ee6bc56bee78bed4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 12 Sep 2014 11:22:06 +0200 Subject: [PATCH 29/39] Added some comments to discovery plugin --- src/octoprint/plugins/discovery/__init__.py | 375 ++++++++++++------ .../discovery_settings_dialog.jinja2 | 0 2 files changed, 248 insertions(+), 127 deletions(-) delete mode 100644 src/octoprint/plugins/discovery/templates/discovery_settings_dialog.jinja2 diff --git a/src/octoprint/plugins/discovery/__init__.py b/src/octoprint/plugins/discovery/__init__.py index f72b3f25a..1268efe25 100644 --- a/src/octoprint/plugins/discovery/__init__.py +++ b/src/octoprint/plugins/discovery/__init__.py @@ -5,6 +5,9 @@ __author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" +""" +The SSDP/UPNP implementations has been largely inspired by https://gist.github.com/schlamar/2428250 +""" import logging import os @@ -18,6 +21,33 @@ try: except: pybonjour = False + +__plugin_name__ = "Discovery" +__plugin_version__ = "0.1" +__plugin_description__ = "Makes the OctoPrint instance discoverable via Bonjour/Avahi/Zeroconf and uPnP" + +def __plugin_init__(): + if not pybonjour: + # no pybonjour available, we can't use that + logging.getLogger("octoprint.plugins." + __name__).info("pybonjour is not installed, Zeroconf Discovery won't be available") + + discovery_plugin = DiscoveryPlugin() + + global __plugin_implementations__ + __plugin_implementations__ = [discovery_plugin] + + global __plugin_helpers__ + __plugin_helpers__ = dict( + ssdp_browse=discovery_plugin.ssdp_browse + ) + if pybonjour: + __plugin_helpers__.update(dict( + zeroconf_browse=discovery_plugin.zeroconf_browse, + zeroconf_register=discovery_plugin.zeroconf_register, + zeroconf_unregister=discovery_plugin.zeroconf_unregister + )) + + default_settings = { "publicHost": None, "publicPort": None, @@ -38,7 +68,6 @@ default_settings = { } s = octoprint.plugin.plugin_settings("discovery", defaults=default_settings) - def get_uuid(): upnpUuid = s.get(["upnpUuid"]) if upnpUuid is None: @@ -60,6 +89,8 @@ def get_instance_name(): return "OctoPrint instance on {}".format(socket.gethostname()) +#~~ custom blueprint for providing discovery.xml + blueprint = flask.Blueprint("plugin.discovery", __name__, template_folder=os.path.join(os.path.dirname(os.path.realpath(__file__)), "templates")) @blueprint.route("/discovery.xml") @@ -91,16 +122,15 @@ def discovery(): response.headers['Content-Type'] = 'application/xml' return response + class DiscoveryPlugin(octoprint.plugin.StartupPlugin, octoprint.plugin.ShutdownPlugin, - octoprint.plugin.BlueprintPlugin, - octoprint.plugin.SettingsPlugin): + octoprint.plugin.BlueprintPlugin): ssdp_multicast_addr = "239.255.255.250" ssdp_multicast_port = 1900 - def __init__(self): self.logger = logging.getLogger("octoprint.plugins." + __name__) @@ -117,22 +147,12 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, self._ssdp_notify_timeout = 10 self._ssdp_last_notify = 0 - ##~~ BlueprintPlugin API + ##~~ BlueprintPlugin API -- used for providing the SSDP device descriptor XML def get_blueprint(self): return blueprint - ##~~ TemplatePlugin API (part of SettingsPlugin) - - def get_template_vars(self): - return dict( - _settings_menu_entry="Network discovery" - ) - - def get_template_folder(self): - return os.path.join(os.path.dirname(os.path.realpath(__file__)), "templates") - - #~~ StartupPlugin API + ##~~ StartupPlugin API -- used for registering OctoPrint's Zeroconf and SSDP services upon application startup def on_startup(self, host, port): public_host = s.get(["publicHost"]) @@ -146,7 +166,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, self.port = port # Zeroconf - self.zeroconf_register("_http._tcp", get_instance_name(), txt_record=self._create_base_txt_record_dict()) + self.zeroconf_register("_http._tcp", get_instance_name(), txt_record=self._create_http_txt_record_dict()) self.zeroconf_register("_octoprint._tcp", get_instance_name(), txt_record=self._create_octoprint_txt_record_dict()) for zeroconf in s.get(["zeroConf"]): if "service" in zeroconf: @@ -160,7 +180,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, # SSDP self._ssdp_register() - #~~ ShutdownPlugin API + ##~~ ShutdownPlugin API -- used for unregistering OctoPrint's Zeroconf and SSDP service upon application shutdown def on_shutdown(self): for key in self._sd_refs: @@ -169,37 +189,25 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, self._ssdp_unregister() - #~~ SettingsPlugin API - - def on_settings_load(self): - return { - "publicHost": s.get(["publicHost"]), - "publicPort": s.getInt(["publicPort"]), - "pathPrefix": s.get(["pathPrefix"]), - "httpUsername": s.get(["httpUsername"]), - "httpPassword": s.get(["httpPassword"]) - } - - def on_settings_save(self, data): - if "publicHost" in data and data["publicHost"]: - s.set(["publicHost"], data["publicHost"]) - if "publicPort" in data and data["publicPort"]: - s.setInt(["publicPort"], data["publicPort"]) - if "pathPrefix" in data and data["pathPrefix"]: - s.set(["pathPrefix"], data["pathPrefix"]) - if "httpUsername" in data and data["httpUsername"]: - s.set(["httpUsername"], data["httpUsername"]) - if "httpPassword" in data and data["httpPassword"]: - s.set(["httpPassword"], data["httpPassword"]) - - #~~ internals + ##~~ helpers # ZeroConf - def zeroconf_register(self, reg_type, name, port=None, txt_record=None, timeout=5): + def zeroconf_register(self, reg_type, name=None, port=None, txt_record=None): + """ + Registers a new service with Zeroconf/Bonjour/Avahi. + + :param reg_type: type of service to register, e.g. "_gntp._tcp" + :param name: displayable name of the service, if not given defaults to the OctoPrint instance name + :param port: port to register for the service, if not given defaults to OctoPrint's (public) port + :param txt_record: optional txt record to attach to the service, dictionary of key-value-pairs + """ + if not pybonjour: return + if not name: + name = get_instance_name() if not port: port = self.port @@ -215,10 +223,21 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, self._sd_refs[key] = pybonjour.DNSServiceRegister(**params) self.logger.info("Registered {name} for {reg_type}".format(**locals())) - def zeroconf_unregister(self, reg_type, port): + def zeroconf_unregister(self, reg_type, port=None): + """ + Unregisteres a previously registered Zeroconf/Bonjour/Avahi service identified by service and port. + + :param reg_type: the type of the service to be unregistered + :param port: the port of the service to be unregistered, defaults to OctoPrint's (public) port if not given + :return: + """ + if not pybonjour: return + if not port: + port = self.port + key = (reg_type, port) if not key in self._sd_refs: return @@ -230,18 +249,56 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, except: self.logger.exception("Could not unregister {reg_type} on port {port}".format(reg_type=reg_type, port=port)) - def zeroconf_browse(self, service_type, block=False, callback=None, timeout=5, resolve_timeout=5): + def zeroconf_browse(self, service_type, block=True, callback=None, browse_timeout=5, resolve_timeout=5): + """ + Browses for services on the local network providing the specified service type. Can be used either blocking or + non-blocking. + + The non-blocking version (default behaviour) will not return until the lookup has completed and + return all results that were found. + + For non-blocking version, set `block` to `False` and provide a `callback` to be called once the lookup completes. + If no callback is provided in non-blocking mode, a ValueError will be raised. + + The results are provided as a list of discovered services, with each service being described by a dictionary + with the following keys: + + * `name`: display name of the service + * `host`: host name of the service + * `post`: port the service is listening on + * `txt_record`: TXT record of the service as a dictionary, exact contents depend on the service + + Callbacks will be called with that list as the single parameter supplied to them. Thus, the following is an + example for a valid callback: + + def browse_callback(results): + for result in results: + print "Name: {name}, Host: {host}, Port: {port}, TXT: {txt_record!r}".format(**result) + + :param service_type: the service type to browse for + :param block: whether to block, defaults to True + :param callback: callback to call once lookup has completed, must be set when `block` is set to `False` + :param browse_timeout: timeout for browsing operation + :param resolve_timeout: timeout for resolving operations for discovered records + :return: if `block` is `True` a list of the discovered services, an empty list otherwise (results will then be + supplied to the callback instead) + """ + if not pybonjour: return None import threading - import time import select + if not block and not callback: + raise ValueError("Non-blocking mode but no callback given") + result = [] result_available = threading.Event() result_available.clear() + resolved = [] + def resolve_callback(sd_ref, flags, interface_index, error_code, fullname, hosttarget, port, txt_record): if error_code == pybonjour.kDNSServiceErr_NoError: txt_record_dict = None @@ -261,6 +318,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, port=port, txt_record=txt_record_dict )) + resolved.append(True) def browse_callback(sd_ref, flags, interface_index, error_code, service_name, regtype, reply_domain): if error_code != pybonjour.kDNSServiceErr_NoError: @@ -271,14 +329,16 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, self.logger.debug("Got a browsing result for Zeroconf resolution of {service_type}, resolving...".format(service_type=service_type)) resolve_ref = pybonjour.DNSServiceResolve(0, interface_index, service_name, regtype, reply_domain, resolve_callback) + try: - while True: + while not resolved: ready = select.select([resolve_ref], [], [], resolve_timeout) - if resolve_ref in ready[0]: - pybonjour.DNSServiceProcessResult(resolve_ref) - else: - self.logger.warn("Timeout while trying to resolve a service") + if resolve_ref not in ready[0]: break + + pybonjour.DNSServiceProcessResult(resolve_ref) + else: + resolved.pop() finally: resolve_ref.close() @@ -286,10 +346,13 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, def browse(): sd_ref = pybonjour.DNSServiceBrowse(regtype=service_type, callBack=browse_callback) - start = time.time() try: - while start + timeout > time.time(): - ready = select.select([sd_ref], [], [], timeout) + while True: + ready = select.select([sd_ref], [], [], browse_timeout) + + if not ready[0]: + break + if sd_ref in ready[0]: pybonjour.DNSServiceProcessResult(sd_ref) finally: @@ -305,56 +368,41 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, if block: result_available.wait() - return result - - def _create_octoprint_txt_record_dict(self): - entries = self._create_base_txt_record_dict() - - import octoprint.server - import octoprint.server.api - - entries.update(dict( - version=octoprint.server.VERSION, - api=octoprint.server.api.VERSION, - )) - - modelName = s.get(["model", "name"]) - if modelName: - entries.update(dict(model=modelName)) - vendor = s.get(["model", "vendor"]) - if vendor: - entries.update(dict(vendor=vendor)) - - return entries - - def _create_base_txt_record_dict(self): - # determine path entry - path = "/" - if s.get(["pathPrefix"]): - path = s.get(["pathPrefix"]) + return result else: - prefix = s.globalGet(["server", "reverseProxy", "prefixFallback"]) - if prefix: - path = prefix - - # fetch username and password (if set) - username = s.get(["httpUsername"]) - password = s.get(["httpPassword"]) - - entries = dict( - path=path - ) - - if username and password: - entries.update(dict(u=username, p=password)) - - return entries + return [] # SSDP/UPNP - ## The SSDP/UPNP implementations has been largely inspired by https://gist.github.com/schlamar/2428250 + def ssdp_browse(self, query, block=True, callback=None, timeout=1, retries=5): + """ + Browses for UPNP services matching the supplied query. Can be used either blocking or + non-blocking. + + The non-blocking version (default behaviour) will not return until the lookup has completed and + return all results that were found. + + For non-blocking version, set `block` to `False` and provide a `callback` to be called once the lookup completes. + If no callback is provided in non-blocking mode, a ValueError will be raised. + + The results are provided as a list of discovered locations of device descriptor files. + + Callbacks will be called with that list as the single parameter supplied to them. Thus, the following is an + example for a valid callback: + + def browse_callback(results): + for result in results: + print "Location: {}".format(result) + + :param query: the SSDP query to send, e.g. "upnp:rootdevice" to search for all devices + :param block: whether to block, defaults to True + :param callback: callback to call in non-blocking mode when lookup has finished, must be set if block is False + :param timeout: timeout in seconds to wait for replies to the M-SEARCH query per interface, defaults to 1 + :param retries: number of retries to perform the lookup on all interfaces, defaults to 5 + :return: if `block` is `True` a list of the discovered devices, an empty list otherwise (results will then be + supplied to the callback instead) + """ - def ssdp_browse(self, query, block=False, callback=None, timeout=1, retries=5): import threading import httplib @@ -407,7 +455,7 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, response = Response(data) result.append(response.getheader("Location")) - except Exception as e: + except: pass if callback: @@ -420,10 +468,88 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, if block: result_available.wait() + return result + else: + return [] - return result + ##~~ internals + + # Zeroconf + + def _create_http_txt_record_dict(self): + """ + Creates a TXT record for the _http._tcp Zeroconf service supplied by this OctoPrint instance. + + Defines the keys for _http._tcp as defined in http://www.dns-sd.org/txtrecords.html + + :return: a dictionary containing the defined key-value-pairs, ready to be turned into a TXT record + """ + + # determine path entry + path = "/" + if s.get(["pathPrefix"]): + path = s.get(["pathPrefix"]) + else: + prefix = s.globalGet(["server", "reverseProxy", "prefixFallback"]) + if prefix: + path = prefix + + # fetch username and password (if set) + username = s.get(["httpUsername"]) + password = s.get(["httpPassword"]) + + entries = dict( + path=path + ) + + if username and password: + entries.update(dict(u=username, p=password)) + + return entries + + def _create_octoprint_txt_record_dict(self): + """ + Creates a TXT record for the _octoprint._tcp Zeroconf service supplied by this OctoPrint instance. + + The following keys are defined: + + * `path`: path prefix to actual OctoPrint instance, inherited from _http._tcp + * `u`: username if HTTP Basic Auth is used, optional, inherited from _http._tcp + * `p`: password if HTTP Basic Auth is used, optional, inherited from _http._tcp + * `version`: OctoPrint software version + * `api`: OctoPrint API version + * `model`: Model of the device that is running OctoPrint + * `vendor`: Vendor of the device that is running OctoPrint + + :return: a dictionary containing the defined key-value-pairs, ready to be turned into a TXT record + """ + + entries = self._create_http_txt_record_dict() + + import octoprint.server + import octoprint.server.api + + entries.update(dict( + version=octoprint.server.VERSION, + api=octoprint.server.api.VERSION, + )) + + modelName = s.get(["model", "name"]) + if modelName: + entries.update(dict(model=modelName)) + vendor = s.get(["model", "vendor"]) + if vendor: + entries.update(dict(vendor=vendor)) + + return entries + + # SSDP/UPNP def _ssdp_register(self): + """ + Registers the OctoPrint instance as basic service with a presentation URL pointing to the web interface + """ + import threading self._ssdp_monitor_active = True @@ -433,19 +559,31 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, self._ssdp_monitor_thread.start() def _ssdp_unregister(self): + """ + Unregisters the OctoPrint instance again + """ + self._ssdp_monitor_active = False if self.host and self.port: for _ in xrange(2): self._ssdp_notify(alive=False) def _ssdp_notify(self, alive=True): + """ + Sends an SSDP notify message across the connected networks. + + :param alive: True to send an "ssdp:alive" message, False to send an "ssdp:byebye" message + """ + import socket import time - if self._ssdp_last_notify + self._ssdp_notify_timeout > time.time(): + if alive and self._ssdp_last_notify + self._ssdp_notify_timeout > time.time(): + # we just sent an alive, no need to send another one now return if alive and not self._ssdp_monitor_active: + # the monitor already shut down, alive messages don't make sense anymore as byebye will shortly follow return for addr in octoprint.util.interface_addresses(): @@ -474,13 +612,20 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, mcast_addr=self.__class__.ssdp_multicast_addr, mcast_port=self.__class__.ssdp_multicast_port) for _ in xrange(2): + # send twice, stuff might get lost, it's only UDP sock.sendto(message, (self.__class__.ssdp_multicast_addr, self.__class__.ssdp_multicast_port)) - except Exception as e: + except: pass self._ssdp_last_notify = time.time() def _ssdp_monitor(self, timeout=5): + """ + Monitor thread that listens on the multicast address for M-SEARCH requests and answers them if they are relevant + + :param timeout: timeout after which to stop waiting for M-SEARCHs for a short while in order to put out an + alive message + """ from BaseHTTPServer import BaseHTTPRequestHandler from StringIO import StringIO @@ -543,27 +688,3 @@ class DiscoveryPlugin(octoprint.plugin.StartupPlugin, pass -__plugin_name__ = "Discovery" -__plugin_version__ = "0.1" -__plugin_description__ = "Makes the OctoPrint instance discoverable via Bonjour/Avahi/Zeroconf and uPnP" - -def __plugin_check__(): - if not pybonjour: - # no pybonjour available, we can't continue - logging.getLogger("octoprint.plugins." + __name__).info("pybonjour is not installed, Zeroconf Discovery won't be available") - - discovery_plugin = DiscoveryPlugin() - - global __plugin_implementations__ - __plugin_implementations__ = [discovery_plugin] - - global __plugin_helpers__ - __plugin_helpers__ = dict( - ssdp_browse=discovery_plugin.ssdp_browse - ) - if pybonjour: - __plugin_helpers__["zeroconf_browse"] = discovery_plugin.zeroconf_browse - __plugin_helpers__["zeroconf_register"] = discovery_plugin.zeroconf_register - - return True - diff --git a/src/octoprint/plugins/discovery/templates/discovery_settings_dialog.jinja2 b/src/octoprint/plugins/discovery/templates/discovery_settings_dialog.jinja2 deleted file mode 100644 index e69de29bb..000000000 From fe34bdc6566e1bba395295c17217f85fe9edd4f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 12 Sep 2014 12:18:15 +0200 Subject: [PATCH 30/39] Fixed a bug that broke the first-run-dialog --- src/octoprint/server/api/__init__.py | 1 - 1 file changed, 1 deletion(-) diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index bab0cdd78..a8c98cad7 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -150,7 +150,6 @@ def pluginCommand(name): @api.route("/setup", methods=["POST"]) -@restricted_access def firstRunSetup(): if not s().getBoolean(["server", "firstRun"]): abort(403) From 3a0aac3c364898babe01ef376285750a350e1c3b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 12 Sep 2014 12:21:25 +0200 Subject: [PATCH 31/39] Fixed issue that broke the offline dialog Javascript is not python... --- src/octoprint/static/js/app/dataupdater.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/octoprint/static/js/app/dataupdater.js b/src/octoprint/static/js/app/dataupdater.js index 6f6fedb58..d1a1206c5 100644 --- a/src/octoprint/static/js/app/dataupdater.js +++ b/src/octoprint/static/js/app/dataupdater.js @@ -37,7 +37,7 @@ function DataUpdater(allViewModels) { return; } - if (viewModel.hasattr("onServerDisconnect")) { + if (viewModel.hasOwnProperty("onServerDisconnect")) { if (!viewModel.onServerDisconnect()) { handled = true; } @@ -71,7 +71,7 @@ function DataUpdater(allViewModels) { return; } - if (viewModel.hasattr("onServerDisconnect")) { + if (viewModel.hasOwnProperty("onServerDisconnect")) { if (!viewModel.onServerDisconnect()) { handled = true; } From 3aca55205ec5b41ec81c22340d718d78799ad02f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 12 Sep 2014 12:39:33 +0200 Subject: [PATCH 32/39] Fixed a bug that crept in during adding i18n support and made gcode viewer slides stop working --- src/octoprint/static/js/app/viewmodels/gcode.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/static/js/app/viewmodels/gcode.js b/src/octoprint/static/js/app/viewmodels/gcode.js index bcfd90240..b7396d326 100644 --- a/src/octoprint/static/js/app/viewmodels/gcode.js +++ b/src/octoprint/static/js/app/viewmodels/gcode.js @@ -332,7 +332,7 @@ function GcodeViewModel(loginStateViewModel, settingsViewModel) { } output.push(gettext("Estimated print time") + ": " + formatDuration(model.printTime)); output.push(gettext("Estimated layer height") + ": " + model.layerHeight.toFixed(2) + gettext("mm")); - output.push(gettext("Layer count") + ": " + model.layersPrinted.toFixed(0) + " " + gettext(printed) + ", " + model.layersTotal.toFixed(0) + " " + gettext("visited")); + output.push(gettext("Layer count") + ": " + model.layersPrinted.toFixed(0) + " " + gettext("printed") + ", " + model.layersTotal.toFixed(0) + " " + gettext("visited")); self.ui_modelInfo(output.join("
")); From fa43600cd90385b3d08099582d280fe3248d6d6f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 12 Sep 2014 12:40:11 +0200 Subject: [PATCH 33/39] Always use absolute paths as root for static response handler in tornado --- src/octoprint/server/util/tornado.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py index 735489d12..b88fe27e8 100644 --- a/src/octoprint/server/util/tornado.py +++ b/src/octoprint/server/util/tornado.py @@ -710,7 +710,7 @@ class LargeResponseHandler(tornado.web.StaticFileHandler): CHUNK_SIZE = 16 * 1024 def initialize(self, path, default_filename=None, as_attachment=False, access_validation=None): - tornado.web.StaticFileHandler.initialize(self, path, default_filename) + tornado.web.StaticFileHandler.initialize(self, os.path.abspath(path), default_filename) self._as_attachment = as_attachment self._access_validation = access_validation From 26e9a17c6bc7361f66ba941855e5c3c131a8ed18 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 12 Sep 2014 14:26:29 +0200 Subject: [PATCH 34/39] Started working on the documentation of the plugin system --- docs/index.rst | 1 + docs/plugins/index.rst | 61 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 docs/plugins/index.rst diff --git a/docs/index.rst b/docs/index.rst index 774c6da13..3375a90cb 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -18,4 +18,5 @@ Contents api/index.rst events/index.rst + plugins/index.rst diff --git a/docs/plugins/index.rst b/docs/plugins/index.rst new file mode 100644 index 000000000..c71261c20 --- /dev/null +++ b/docs/plugins/index.rst @@ -0,0 +1,61 @@ +.. _sec-plugins: + +##################### +Plugins Documentation +##################### + +.. contents:: + +Starting with OctoPrint 1.2.0, there's now a plugin system in place which allows to individually +extend OctoPrint's functionality. + +Right now plugins can be used to extend OctoPrint's settings dialog, to execute specific tasks on server startup and +shutdown or to provide custom (API) endpoints with special functionality. More plugin types are planned for the future. + +.. _sec-plugins-installation: + +Installing Plugins +================== + +Plugins can be installed either by unpacking them into one of the configured plugin folders (regularly those are +``/plugins`` and ``~/.octoprint/plugins`` or by installing them as regular python modules via ``pip``. +Please refer to the documentation of the plugin for installations instructions. + +The latter is the more common case since all currently published plugins not bundled with OctoPrint can and should be installed +this way. + +For a plugin available on the Python Package Index (PyPi), the process is as simple as issuing a + +.. code-block:: bash + + pip install + +For plugins not available on PyPi, you'll have to give ``pip`` an URL from which to install the package (e.g. the URL to +a ZIP file of the current master branch of a Github repository hosting a plugin, or even a ``git+https`` URL), example: + +.. code-block:: bash + + pip install https://github.com/OctoPrint/OctoPrint-Growl/archive/master.zip + +See `the pip install documentation `_ for what URL +types are possible. + +.. _sec-plugins-available: + +Available Plugins +================= + +Currently there's no such thing as a centralized plugin repository for available plugins. + +Plugins may be found in the lists provided in `the OctoPrint wiki `_ +and on the `OctoPrint organization Github page `_. + +.. _sec-plugins-developing: + +Developing Plugins +================== + +.. todo:: + + A section on how to develop plugins yourself, including a tutorial creating an exemplatory plugin as well as + a documentation of the plugin API, will be added in the near future. From 9e9da5355c0f97a1ea164c76c520c712fc44ad9f Mon Sep 17 00:00:00 2001 From: Dattas Moonchaser Date: Fri, 12 Sep 2014 10:23:08 -0600 Subject: [PATCH 35/39] Initial comm protocol gcode hooks --- src/octoprint/util/comm.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/src/octoprint/util/comm.py b/src/octoprint/util/comm.py index e03d89355..befc001a2 100644 --- a/src/octoprint/util/comm.py +++ b/src/octoprint/util/comm.py @@ -13,6 +13,7 @@ import threading import Queue as queue import logging import serial +import octoprint.plugin from collections import deque @@ -151,6 +152,10 @@ class MachineCom(object): self._resendDelta = None self._lastLines = deque([], 50) + # hooks + self._pluginManager = octoprint.plugin.plugin_manager() + self._gcode_hooks = self._pluginManager.get_hooks("octoprint.comm.protocol.gcode") + # SD status data self._sdAvailable = False self._sdFileList = False @@ -1089,6 +1094,10 @@ class MachineCom(object): return if not self.isStreaming(): + for hook in self._gcode_hooks: + hook_cmd = self._gcode_hooks[hook](self, cmd) + if hook_cmd and isinstance(hook_cmd, basestring): + cmd = hook_cmd gcode = self._regex_command.search(cmd) if gcode: gcode = gcode.group(1) From 192e606feab01d933d6972603623ac0afb222f77 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Fri, 12 Sep 2014 20:15:07 +0200 Subject: [PATCH 36/39] Don't hiccup on templates provided by plugins we can't resolve --- src/octoprint/templates/settings.jinja2 | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/templates/settings.jinja2 b/src/octoprint/templates/settings.jinja2 index a1a05b0fe..fee807432 100644 --- a/src/octoprint/templates/settings.jinja2 +++ b/src/octoprint/templates/settings.jinja2 @@ -631,7 +631,7 @@ {% for plugin_name, vars in settingsPlugins.items() %}
- {% include plugin_name+"_settings_dialog.jinja2" %} + {% include plugin_name+"_settings_dialog.jinja2" ignore missing %}
{% endfor %} From ea2890091382cf258e8f4499d81edbaaa6db070f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Sat, 13 Sep 2014 21:49:26 +0200 Subject: [PATCH 37/39] Properly unset job data when instructed so by callers Closes #580 --- src/octoprint/printer.py | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/src/octoprint/printer.py b/src/octoprint/printer.py index 5c7de08db..65daeb099 100644 --- a/src/octoprint/printer.py +++ b/src/octoprint/printer.py @@ -388,6 +388,17 @@ class Printer(): } else: self._selectedFile = None + self._stateMonitor.setJobData({ + "file": { + "name": None, + "origin": None, + "size": None, + "date": None + }, + "estimatedPrintTime": None, + "filament": None, + }) + return estimatedPrintTime = None date = None From 858d87a732f88fc8192c9865a380dcff4b9e6351 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Sat, 13 Sep 2014 21:58:41 +0200 Subject: [PATCH 38/39] Forgot entry in changelog --- CHANGELOG.md | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 02299b007..08687c92d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,12 @@ # OctoPrint Changelog -## 1.1.0 +## 1.1.1 (Unreleased) + +### Bug Fixes + +* [#580](https://github.com/foosel/OctoPrint/issues/580) - Properly unset job data when instructed so by callers + +## 1.1.0 (2014-09-03) ### New Features @@ -70,6 +76,6 @@ ([Commits](https://github.com/foosel/OctoPrint/compare/1.0.0...1.1.0)) -## 1.0.0 +## 1.0.0 (2014-06-22) First release with new versioning scheme. \ No newline at end of file From 604c2a0bdd7595a168287471aeaa0e06cdb976cd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Sun, 14 Sep 2014 14:41:18 +0200 Subject: [PATCH 39/39] Some small bugfixes in the plugin handling code and a changelog entry --- CHANGELOG.md | 2 ++ src/octoprint/server/__init__.py | 4 ++-- src/octoprint/util/__init__.py | 5 ++++- 3 files changed, 8 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e73aaef1..2d9c17314 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,8 @@ search * You can now define a folder (default: `~/.octoprint/watched`) to be watched for newly added GCODE (or -- if slicing support is enabled -- STL) files to automatically add. +* OctoPrint now has a [plugin system](http://docs.octoprint.org/en/devel/plugins/index.html) which allows extending its + core functionality. ### Improvements diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 1f32ba083..84b055dbf 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -133,11 +133,11 @@ def plugin_assets(name, filename): asset_plugins = pluginManager.get_implementations(octoprint.plugin.AssetPlugin) if not name in asset_plugins: - return make_response(404) + return make_response("Asset not found", 404) asset_plugin = asset_plugins[name] asset_folder = asset_plugin.get_asset_folder() if asset_folder is None: - make_response(404) + return make_response("Asset not found", 404) return send_from_directory(asset_folder, filename) diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 14876a933..e5f4e4b69 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -259,7 +259,10 @@ def interface_addresses(family=None): family = netifaces.AF_INET for interface in netifaces.interfaces(): - ifaddresses = netifaces.ifaddresses(interface) + try: + ifaddresses = netifaces.ifaddresses(interface) + except: + continue if family in ifaddresses: for ifaddress in ifaddresses[family]: if not ifaddress["addr"].startswith("169.254."):