diff --git a/AUTHORS.md b/AUTHORS.md index 412f90772..0a1a26c56 100644 --- a/AUTHORS.md +++ b/AUTHORS.md @@ -55,6 +55,7 @@ date of first contribution): * [Thomas Hou](https://github.com/masterhou) * [Mark Bastiaans](https://github.com/markbastiaans) * [Marcel Hellwig](https://github.com/punkkeks) + * [Kevin Murphy](https://github.com/kevingelion) OctoPrint started off as a fork of [Cura](https://github.com/daid/Cura) by [Daid Braam](https://github.com/daid). Parts of its communication layer and diff --git a/docs/modules/cli.rst b/docs/modules/cli.rst new file mode 100644 index 000000000..74f7458bb --- /dev/null +++ b/docs/modules/cli.rst @@ -0,0 +1,31 @@ +.. _sec-modules-cli: + +octoprint.cli +------------- + +.. automodule:: octoprint.cli + :members: + +.. _sec-modules-cli-dev: + +octoprint.cli.dev +----------------- + +.. automodule:: octoprint.cli.dev + :members: + +.. _sec-modules-cli-plugins: + +octoprint.cli.plugins +--------------------- + +.. automodule:: octoprint.cli.plugins + :members: + +.. _sec-modules-cli-server: + +octoprint.cli.server +-------------------- + +.. automodule:: octoprint.cli.server + :members: diff --git a/docs/modules/index.rst b/docs/modules/index.rst index db82bdde2..1cdb36a0a 100644 --- a/docs/modules/index.rst +++ b/docs/modules/index.rst @@ -7,6 +7,7 @@ Internal Modules .. toctree:: :maxdepth: 3 + cli.rst filemanager.rst plugin.rst printer.rst diff --git a/docs/plugins/gettingstarted.rst b/docs/plugins/gettingstarted.rst index 3c6c60d27..63c7ece70 100644 --- a/docs/plugins/gettingstarted.rst +++ b/docs/plugins/gettingstarted.rst @@ -10,6 +10,37 @@ Over the course of this little tutorial we'll build a full fledged, installable at some locations throughout OctoPrint and also offers some other basic functionality to give you an idea of what you can achieve with OctoPrint's plugin system. +First of all let use make sure that you have OctoPrint checked out and set up for development on your local +development environment:: + + $ cd ~/devel + $ git clone https://github.com/foosel/OctoPrint + [...] + $ cd OctoPrint + $ virtualenv venv + [...] + $ source venv/bin/activate + (venv) $ pip install -e[develop] + [...] + (venv) $ octoprint --help + Usage: octoprint [OPTIONS] COMMAND [ARGS]... + + [...] + +.. note:: + + You can also develop your plugin directly on your Raspberry Pi running OctoPi of course. In that + case please ignore the above instructions, you'll only need to activate the ``oprint`` + virtual environment: + + .. code-block:: none + + $ source ~/oprint/bin/activate + (oprint) $ octoprint --help + Usage: octoprint [OPTIONS] COMMAND [ARGS]... + + [...] + We'll start at the most basic form a plugin can take - just a couple of simple lines of Python code: .. code-block:: python @@ -24,14 +55,15 @@ We'll start at the most basic form a plugin can take - just a couple of simple l Saving this as ``helloworld.py`` in ``~/.octoprint/plugins`` yields you something resembling these log entries upon server startup:: + (venv) $ octoprint serve 2015-01-27 11:14:35,124 - octoprint.server - INFO - Starting OctoPrint 1.2.0-dev-448-gd96e56e (devel branch) [...] 2015-01-27 11:14:35,124 - octoprint.plugin.core - INFO - Loading plugins from /home/pi/.octoprint/plugins, /home/pi/OctoPrint/src/octoprint/plugins and installed plugin packages... [...] 2015-01-27 11:14:36,135 - octoprint.plugin.core - INFO - 3 plugin(s) registered with the system: - | CuraEngine (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/cura - | Discovery (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/discovery + [...] | Hello World (1.0.0) = /home/pi/.octoprint/plugins/helloworld.py + [...] OctoPrint found that plugin in the folder and took a look into it. The name and the version it displays in that log entry it got from the ``__plugin_name__`` and ``__plugin_version__`` lines. It also read the description from @@ -101,31 +133,35 @@ or alternatively manually utilizing Python's standard package manager ``pip`` di So let's begin. We'll use the `cookiecutter `_ template for OctoPrint plugins here, so we'll first need to install that:: - $ pip install cookiecutter + (venv) $ pip install cookiecutter -Then we can use the ``cookiecutter`` command to generate a new OctoPrint plugin skeleton for us:: +Then we can use the ``octoprint dev plugin:new`` command [#f1]_ to generate a new OctoPrint plugin skeleton for us:: - $ cookiecutter gh:OctoPrint/cookiecutter-octoprint-plugin + (venv) $ cd ~/devel + (venv) $ octoprint dev plugin:new helloworld Cloning into 'cookiecutter-octoprint-plugin'... - remote: Counting objects: 70, done. - remote: Compressing objects: 100% (17/17), done. - emote: Total 70 (delta 0), reused 0 (delta 0), pack-reused 51 - Unpacking objects: 100% (70/70), done. - Checking connectivity... done. - plugin_identifier (default is "skeleton")? helloworld - plugin_package (default is "octoprint_helloworld")? - plugin_name (default is "OctoPrint-Helloworld")? - repo_name (default is "OctoPrint-Helloworld")? - full_name (default is "You")? Your Name - email (default is "you@example.com")? you@somewhere.net - github_username (default is "you")? yourGithubName - plugin_version (default is "0.1.0")? 1.0.0 - plugin_description (default is "TODO")? A quick "Hello World" example plugin for OctoPrint - plugin_license (default is "AGPLv3")? - plugin_homepage (default is "https://github.com/yourGithubName/OctoPrint-Helloworld")? - plugin_source (default is "https://github.com/yourGithubName/OctoPrint-Helloworld")? - plugin_installurl (default is "https://github.com/yourGithubName/OctoPrint-Helloworld/archive/master.zip")? - $ cd OctoPrint-HelloWorld + remote: Counting objects: 101, done. + remote: Total 101 (delta 0), reused 0 (delta 0), pack-reused 101 + Receiving objects: 100% (101/101), 53.69 KiB, done. + Resolving deltas: 100% (35/35), done. + plugin_package [octoprint_helloworld]: + plugin_name [OctoPrint-Helloworld]: + repo_name [OctoPrint-Helloworld]: + full_name [You]: Your Name + email [you@example.com]: you@somewhere.net + github_username [you]: yourGithubName + plugin_version [0.1.0]: 1.0.0 + plugin_description [TODO]: A quick "Hello World" example plugin for OCtoPrint + plugin_license [AGPLv3]: + plugin_homepage [https://github.com/yourGithubName/OctoPrint-Helloworld]: + plugin_source [https://github.com/yourGithubName/OctoPrint-Helloworld]: + plugin_installurl [https://github.com/yourGithubName/OctoPrint-Helloworld/archive/master.zip]: + (venv) $ cd OctoPrint-HelloWorld + +.. note:: + + If ``octoprint dev plugin:new`` isn't recognized as a command (and also doesn't show up in the output of + ``octoprint --help``, make sure you installed cookiecutter into the same python environment as OctoPrint. This will create a project structure in the ``OctoPrint-HelloWorld`` folder we just changed to that looks like this:: @@ -193,9 +229,11 @@ Now all that's left to do is to move our ``helloworld.py`` into the ``octoprint_ The plugin is now ready to be installed via ``python setup.py install``. However, since we are still working on our plugin, it makes more sense to use ``python setup.py develop`` for now -- this way the plugin becomes -discoverable by OctoPrint, however we don't have to reinstall it after any changes we will still do:: +discoverable by OctoPrint, however we don't have to reinstall it after any changes we will still do. We can have the +``octoprint dev plugin:install`` command do everything for us here, it will ensure to use the python binary belonging +to your OctoPrint installation:: - $ python setup.py develop + (venv) $ octoprint dev plugin:install running develop running egg_info creating OctoPrint_HelloWorld.egg-info @@ -209,9 +247,8 @@ Restart OctoPrint. Your plugin should still be properly discovered and the log l 2015-01-27 13:43:34,134 - octoprint.plugin.core - INFO - Loading plugins from /home/pi/.octoprint/plugins, /home/pi/OctoPrint/src/octoprint/plugins and installed plugin packages... [...] 2015-01-27 13:43:34,818 - octoprint.plugin.core - INFO - 3 plugin(s) registered with the system: - | CuraEngine (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/cura - | Discovery (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/discovery - | Hello World (1.0.0) = /home/pi/OctoPrint-HelloWorld/octoprint_helloworld + [...] + | Hello World (1.0.0) = /home/pi/devel/OctoPrint-HelloWorld/octoprint_helloworld [...] 2015-01-27 13:43:38,997 - octoprint.plugins.helloworld - INFO - Hello World! @@ -257,9 +294,9 @@ and ``__plugin_description__`` from ``__init__.py``: and restart OctoPrint:: 2015-01-27 13:46:33,786 - octoprint.plugin.core - INFO - 3 plugin(s) registered with the system: - | CuraEngine (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/cura - | Discovery (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/discovery - | OctoPrint-HelloWorld (1.0.0) = /home/pi/OctoPrint-HelloWorld/octoprint_helloworld + [...] + | OctoPrint-HelloWorld (1.0.0) = /home/pi/devel/OctoPrint-HelloWorld/octoprint_helloworld + [...] Our "Hello World" Plugin still gets detected fine, but it's now listed under the same name it's installed under, "OctoPrint-HelloWorld". That's a bit redundant and squashed, so we'll override that bit via ``__plugin_name__`` again: @@ -284,9 +321,9 @@ Our "Hello World" Plugin still gets detected fine, but it's now listed under the Restart OctoPrint again:: 2015-01-27 13:48:54,122 - octoprint.plugin.core - INFO - 3 plugin(s) registered with the system: - | CuraEngine (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/cura - | Discovery (bundled) = /home/pi/OctoPrint/src/octoprint/plugins/discovery + [...] | Hello World (1.0.0) = /home/pi/OctoPrint-HelloWorld/octoprint_helloworld + [...] Much better! You can override pretty much all of the metadata defined within ``setup.py`` from within your Plugin itself -- take a look at :ref:`the available control properties ` for all available @@ -295,7 +332,7 @@ overrides. Following the README of the `Plugin Skeleton `_ you could now already publish your plugin on Github and it would be directly installable by others using pip:: - pip install https://github.com/yourGithubName/OctoPrint-HelloWorld/archive/master.zip + (venv) $ pip install https://github.com/yourGithubName/OctoPrint-HelloWorld/archive/master.zip But let's add some more features instead. @@ -857,7 +894,7 @@ generated CSS files (and compiles them on the fly in your browser using `lessjs which makes development so much easier. Let's try that, so you know how it works for future bigger projects. Add another folder to our ``static`` folder called ``less`` and within that create a file ``helloworld.less``. Put -into that the same content as into our CSS file. Compile that LESS file to CSS [#f1]_, overwriting our old ``helloworld.css`` +into that the same content as into our CSS file. Compile that LESS file to CSS [#f2]_, overwriting our old ``helloworld.css`` in the process. The folder structure of our plugin should now look like this:: octoprint_helloworld/ @@ -1038,6 +1075,12 @@ looking for examples. .. rubric:: Footnotes -.. [#f1] Refer to the `LESS documentation `_ on how to do that. If you are developing +.. [#f1] Instead of the ``octoprint dev plugin:new`` you could also have manually called cookiecutter with the + template's repository URL shortcut: ``cookiecutter gh:OctoPrint/cookiecutter-octoprint-plugin``. The + ``devel:newplugin`` command already does this for you, makes sure cookiecutter always uses a fresh + checkout without prompting you for it and also allows to pre-specify a bunch of settings (like the + plugin's identifier) directly from the command line. Take a look at ``octoprint dev plugin:new --help`` + for the usage details. +.. [#f2] Refer to the `LESS documentation `_ on how to do that. If you are developing your plugin under Windows you might also want to give `WinLESS `_ a look which will run in the background and keep your CSS files up to date with your various project's LESS files automatically. diff --git a/docs/plugins/hooks.rst b/docs/plugins/hooks.rst index add3d78b4..8cd32abfe 100644 --- a/docs/plugins/hooks.rst +++ b/docs/plugins/hooks.rst @@ -37,6 +37,143 @@ octoprint.accesscontrol.appkey :return: A list of 3-tuples as described above :rtype: list +.. _sec-plugins-hook-cli-commands: + +octoprint.cli.commands +---------------------- + +.. py:function:: hook(cli_group, pass_octoprint_ctx, *args, **kwargs) + + By providing a handler for this hook plugins may register commands on OctoPrint's command line interface (CLI). + + Handlers are expected to return a list of callables annotated as `Click commands `_ to register with the + CLI. + + The custom ``MultiCommand`` instance :class:`~octoprint.cli.plugins.OctoPrintPluginCommands` is provided + as parameter. Via that object handlers may access the *global* :class:`~octoprint.settings.Settings` + and the :class:`~octoprint.plugin.core.PluginManager` instance as ``cli_group.settings`` and ``cli_group.plugin_manager``. + + **Example:** + + Registers two new commands, ``custom_cli_command:greet`` and ``custom_cli_command:random`` with + OctoPrint: + + .. onlineinclude:: https://raw.githubusercontent.com/OctoPrint/Plugin-Examples/master/custom_cli_command.py + :linenos: + :tab-width: 4 + :caption: `custom_cli_command.py `_ + + Calling ``octoprint --help`` shows the two new commands: + + .. code-block:: none + + $ octoprint --help + Usage: octoprint [OPTIONS] COMMAND [ARGS]... + + Options: + -b, --basedir PATH Specify the basedir to use for uploads, timelapses etc. + -c, --config PATH Specify the config file to use. + -v, --verbose Increase logging verbosity + --version Show the version and exit. + --help Show this message and exit. + + Commands: + daemon Starts, stops or restarts in daemon mode. + dev:plugin Helpers for plugin developers + plugin:custom_cli_command custom_cli_command commands + serve Starts the OctoPrint server. + + $ octoprint plugin:custom_cli_command --help + Usage: octoprint plugin:custom_cli_command [OPTIONS] COMMAND [ARGS]... + + custom_cli_command commands + + Options: + --help Show this message and exit. + + Commands: + greet Greet someone by name, the greeting can be... + random Greet someone by name with a random greeting. + + Each also has an individual help output: + + .. code-block:: none + + $ octoprint plugin:custom_cli_command greet --help + Usage: octoprint plugin:custom_cli_command greet [OPTIONS] [NAME] + + Greet someone by name, the greeting can be customized. + + Options: + -g, --greeting TEXT The greeting to use + --help Show this message and exit. + + $ octoprint plugin:custom_cli_command random --help + Usage: octoprint plugin:custom_cli_command random [OPTIONS] [NAME] + + Greet someone by name with a random greeting. + + Options: + --help Show this message and exit. + + And of course they work too: + + .. code-block:: none + + $ octoprint plugin:custom_cli_command greet + Hello World! + + $ octoprint plugin:custom_cli_command greet --greeting "Good morning" + Good morning World! + + $ octoprint plugin:custom_cli_command random stranger + Hola stranger! + + .. note:: + + If your hook handler is an instance method of a plugin mixin implementation, be aware that the hook will be + called without OctoPrint initializing your implementation instance. That means that **none** of the + :ref:`injected properties ` will be available and also the + :method:`~octoprint.plugin.Plugin.initialize` method will not be called. + + Your hook handler will have access to the plugin manager as ``cli_group.plugin_manager`` and to the + *global* settings as ``cli_group.settings``. You can have your handler turn the latter into a + :class:`~octoprint.plugin.PluginSettings` instance by using :func:`octoprint.plugin.plugin_settings_from_settings_plugin` + if your plugin's implementation implements the :class:`~octoprint.plugin.SettingsPlugin` mixin and inject + that and the plugin manager instance yourself: + + .. code-block:: python + + import octoprint.plugin + + class MyPlugin(octoprint.plugin.SettingsPlugin): + + def get_cli_commands(self, cli_group, pass_octoprint_ctx, *args, **kwargs): + import logging + + settings = cli_group._settings + plugin_settings = octoprint.plugin.plugin_settings_for_settings_plugin("myplugin", self) + if plugin_settings is None: + # this can happen if anything goes wrong with preparing the PluginSettings instance + return dict() + + self._settings = plugin_settings + self._plugin_manager = cli_group._plugin_manager + self._logger = logging.getLogger(__name__) + + ### command definition starts here + + # ... + + + No other platform components will be available - the CLI runs outside of a running, fully initialized + OctoPrint server context, so there is absolutely no way to access a printer connection, the event bus or + anything else like that. The only things available are the settings and the plugin manager. + + :return: A list of `Click commands or groups `_ to provide on + OctoPrint's CLI. + :rtype: list + .. _sec-plugins-hook-comm-protocol-action: octoprint.comm.protocol.action diff --git a/scripts/octoprint.default b/scripts/octoprint.default index 2d9a46d7f..1f58092a6 100644 --- a/scripts/octoprint.default +++ b/scripts/octoprint.default @@ -3,11 +3,17 @@ # The init.d script will only run if this variable non-empty. OCTOPRINT_USER=pi +# base directory to use +#BASEDIR=/home/pi/.octoprint + +# configuration file to use +#CONFIGFILE=/home/pi/.octoprint/config.yaml + # On what port to run daemon, default is 5000 PORT=5000 -# Path to the OctoPrint executable, use this to override the default setting "/usr/bin/octoprint" -#DAEMON=/path/to/octoprint/executable +# Path to the OctoPrint executable, you need to set this to match your installation! +#DAEMON=/home/pi/OctoPrint/venv/bin/octoprint # What arguments to pass to octoprint, usually no need to touch this DAEMON_ARGS="--port=$PORT" diff --git a/scripts/octoprint.init b/scripts/octoprint.init index be66b6a89..97601ebb4 100644 --- a/scripts/octoprint.init +++ b/scripts/octoprint.init @@ -16,17 +16,23 @@ # Author: Sami Olmari PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin -DESC="Octoprint Daemon" -NAME="Octoprint" -DAEMON=/usr/local/bin/octoprint -PIDFILE=/var/run/$NAME.pid +DESC="OctoPrint Daemon" +NAME="OctoPrint" PKGNAME=octoprint +PIDFILE=/var/run/$PKGNAME.pid SCRIPTNAME=/etc/init.d/$PKGNAME # Read configuration variable file if it is present [ -r /etc/default/$PKGNAME ] && . /etc/default/$PKGNAME -# Exit if the octoprint is not installed +# Exit if the DAEMON is not set +if [ -z "$DAEMON" ] +then + log_warning_msg "Not starting $PKGNAME, DAEMON not set in /etc/default/$PKGNAME." + exit 0 +fi + +# Exit if the DAEMON is not installed [ -x "$DAEMON" ] || exit 0 # Load the VERBOSE setting and other rcS variables @@ -48,6 +54,17 @@ then exit 0 fi +COMMAND_ARGS= +if [ -z "$BASEDIR" ] +then + COMMAND_ARGS="--basedir $BASEDIR $COMMAND_ARGS" +fi + +if [ -z "$CONFIGFILE" ] +then + COMMAND_ARGS="--config $CONFIGFILE $COMMAND_ARGS" +fi + # # Function to verify if a pid is alive # @@ -74,7 +91,7 @@ do_start() if [ $RETVAL != 0 ]; then start-stop-daemon --start --background --quiet --pidfile $PIDFILE --make-pidfile \ --exec $DAEMON --chuid $OCTOPRINT_USER --user $OCTOPRINT_USER --umask $UMASK --nicelevel=$NICELEVEL \ - -- $DAEMON_ARGS + -- $COMMAND_ARGS serve $DAEMON_ARGS RETVAL="$?" fi } diff --git a/setup.py b/setup.py index 31dbb8de6..c8ba6b727 100644 --- a/setup.py +++ b/setup.py @@ -34,7 +34,8 @@ INSTALL_REQUIRES = [ "pkginfo==1.2.1", "requests==2.7.0", "semantic_version==2.4.2", - "psutil==3.2.1" + "psutil==3.2.1", + "Click" ] # Additional requirements for optional install options diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index 883acc5d9..485f7214a 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -1,85 +1,214 @@ #!/usr/bin/env python2 +# coding=utf-8 +from __future__ import absolute_import, print_function import sys -from octoprint.daemon import Daemon -from octoprint.server import Server +import logging #~~ version from ._version import get_versions -__version__ = get_versions()['version'] +versions = get_versions() + +__version__ = versions['version'] +__branch__ = versions['branch'] if 'branch' in versions else None +__display_version__ = "{} ({} branch)".format(__version__, __branch__) if __branch__ else __version__ + +del versions del get_versions -#~~ main class +#~~ sane logging defaults -class Main(Daemon): - def __init__(self, pidfile, configfile, basedir, host, port, debug, allowRoot, logConf): - Daemon.__init__(self, pidfile) +logging.basicConfig() - self._configfile = configfile - self._basedir = basedir - self._host = host - self._port = port - self._debug = debug - self._allowRoot = allowRoot - self._logConf = logConf +#~~ try to ensure a sound SSL environment - def run(self): - octoprint = Server(self._configfile, self._basedir, self._host, self._port, self._debug, self._allowRoot) - octoprint.run() +urllib3_ssl = True +"""Whether requests/urllib3 and urllib3 (if installed) should be able to establish + a sound SSL environment or not.""" + +version_info = sys.version_info +if version_info.major == 2 and version_info.minor <= 7 and version_info.micro < 9: + try: + # make sure our requests version of urllib3 is properly patched (if possible) + import requests.packages.urllib3.contrib.pyopenssl + requests.packages.urllib3.contrib.pyopenssl.inject_into_urllib3() + except ImportError: + urllib3_ssl = False + + try: + import urllib3 + + # only proceed if urllib3 is even installed on its own + try: + # urllib3 is there, let's patch that too + import urllib3.contrib.pyopenssl + urllib3.contrib.pyopenssl.inject_into_urllib3() + except ImportError: + urllib3_ssl = False + except ImportError: + pass + +del version_info + +#~~ init methods to bring up platform + +def init_platform(basedir, configfile, use_logging_file=True, logging_file=None, + logging_config=None, debug=False, verbosity=0, uncaught_logger=None, + uncaught_handler=None, after_settings=None, after_logging=None): + settings = init_settings(basedir, configfile) + if callable(after_settings): + after_settings(settings) + + logger = init_logging(settings, + use_logging_file=use_logging_file, + logging_file=logging_file, + default_config=logging_config, + debug=debug, + verbosity=verbosity, + uncaught_logger=uncaught_logger, + uncaught_handler=uncaught_handler) + if callable(after_logging): + after_logging(logger) + + plugin_manager = init_pluginsystem(settings) + return settings, logger, plugin_manager + + +def init_settings(basedir, configfile): + """Inits the settings instance based on basedir and configfile to use.""" + + from octoprint.settings import settings + return settings(init=True, basedir=basedir, configfile=configfile) + + +def init_logging(settings, use_logging_file=True, logging_file=None, default_config=None, debug=False, verbosity=0, uncaught_logger=None, uncaught_handler=None): + """Sets up logging.""" + + import os + + from octoprint.util import dict_merge + + # default logging configuration + if default_config is None: + default_config = { + "version": 1, + "formatters": { + "simple": { + "format": "%(asctime)s - %(name)s - %(levelname)s - %(message)s" + } + }, + "handlers": { + "console": { + "class": "logging.StreamHandler", + "level": "DEBUG", + "formatter": "simple", + "stream": "ext://sys.stdout" + }, + "file": { + "class": "logging.handlers.TimedRotatingFileHandler", + "level": "DEBUG", + "formatter": "simple", + "when": "D", + "backupCount": "1", + "filename": os.path.join(settings.getBaseFolder("logs"), "octoprint.log") + }, + "serialFile": { + "class": "logging.handlers.RotatingFileHandler", + "level": "DEBUG", + "formatter": "simple", + "maxBytes": 2 * 1024 * 1024, # let's limit the serial log to 2MB in size + "filename": os.path.join(settings.getBaseFolder("logs"), "serial.log") + } + }, + "loggers": { + "SERIAL": { + "level": "CRITICAL", + "handlers": ["serialFile"], + "propagate": False + }, + "octoprint": { + "level": "INFO" + }, + "octoprint.util": { + "level": "INFO" + }, + "octoprint.plugins": { + "level": "INFO" + } + }, + "root": { + "level": "WARN", + "handlers": ["console", "file"] + } + } + + if debug or verbosity > 0: + default_config["loggers"]["octoprint"]["level"] = "DEBUG" + default_config["root"]["level"] = "INFO" + if verbosity > 1: + default_config["loggers"]["octoprint.plugins"]["level"] = "DEBUG" + if verbosity > 2: + default_config["root"]["level"] = "DEBUG" + + if use_logging_file: + # further logging configuration from file... + if logging_file is None: + logging_file = os.path.join(settings.getBaseFolder("base"), "logging.yaml") + + config_from_file = {} + if os.path.exists(logging_file) and os.path.isfile(logging_file): + import yaml + with open(logging_file, "r") as f: + config_from_file = yaml.safe_load(f) + + # we merge that with the default config + config = dict_merge(default_config, config_from_file) + else: + config = default_config + + # configure logging globally + import logging.config + logging.config.dictConfig(config) + + # make sure we log any warnings + logging.captureWarnings(True) + + import warnings + + categories = (DeprecationWarning, PendingDeprecationWarning) + if verbosity > 2: + warnings.simplefilter("always") + elif debug or verbosity > 0: + for category in categories: + warnings.simplefilter("always", category=category) + + # make sure we also log any uncaught exceptions + if uncaught_logger is None: + logger = logging.getLogger(__name__) + else: + logger = logging.getLogger(uncaught_logger) + + if uncaught_handler is None: + def exception_logger(exc_type, exc_value, exc_tb): + logger.error("Uncaught exception", exc_info=(exc_type, exc_value, exc_tb)) + uncaught_handler = exception_logger + sys.excepthook = uncaught_handler + + return logger + + +def init_pluginsystem(settings): + """Initializes the plugin manager based on the settings.""" + from octoprint.plugin import plugin_manager + return plugin_manager(init=True, settings=settings) + +#~~ server main method def main(): - import argparse + from octoprint.cli import octo + octo(prog_name="octoprint", auto_envvar_prefix="OCTOPRINT") - parser = argparse.ArgumentParser(prog="run") - - parser.add_argument("-v", "--version", action="store_true", dest="version", - help="Output OctoPrint's version and exit") - - parser.add_argument("-d", "--debug", action="store_true", dest="debug", - help="Enable debug mode") - - parser.add_argument("--host", action="store", type=str, dest="host", - help="Specify the host on which to bind the server") - parser.add_argument("--port", action="store", type=int, dest="port", - help="Specify the port on which to bind the server") - - parser.add_argument("-c", "--config", action="store", dest="config", - help="Specify the config file to use. OctoPrint needs to have write access for the settings dialog to work. Defaults to ~/.octoprint/config.yaml") - parser.add_argument("-b", "--basedir", action="store", dest="basedir", - help="Specify the basedir to use for uploads, timelapses etc. OctoPrint needs to have write access. Defaults to ~/.octoprint") - parser.add_argument("--logging", action="store", dest="logConf", - help="Specify the config file to use for configuring logging. Defaults to ~/.octoprint/logging.yaml") - - parser.add_argument("--daemon", action="store", type=str, choices=["start", "stop", "restart"], - help="Daemonize/control daemonized OctoPrint instance (only supported under Linux right now)") - parser.add_argument("--pid", action="store", type=str, dest="pidfile", default="/tmp/octoprint.pid", - help="Pidfile to use for daemonizing, defaults to /tmp/octoprint.pid") - - parser.add_argument("--iknowwhatimdoing", action="store_true", dest="allowRoot", - help="Allow OctoPrint to run as user root") - - args = parser.parse_args() - - if args.version: - print "OctoPrint version %s" % __version__ - sys.exit(0) - - if args.daemon: - if sys.platform == "darwin" or sys.platform == "win32": - print >> sys.stderr, "Sorry, daemon mode is only supported under Linux right now" - sys.exit(2) - - daemon = Main(args.pidfile, args.config, args.basedir, args.host, args.port, args.debug, args.allowRoot, args.logConf) - if "start" == args.daemon: - daemon.start() - elif "stop" == args.daemon: - daemon.stop() - elif "restart" == args.daemon: - daemon.restart() - else: - octoprint = Server(args.config, args.basedir, args.host, args.port, args.debug, args.allowRoot, args.logConf) - octoprint.run() if __name__ == "__main__": main() diff --git a/src/octoprint/cli/__init__.py b/src/octoprint/cli/__init__.py new file mode 100644 index 000000000..113f737b7 --- /dev/null +++ b/src/octoprint/cli/__init__.py @@ -0,0 +1,151 @@ +# coding=utf-8 +from __future__ import absolute_import + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" + + +import click +import octoprint + +#~~ click context + +class OctoPrintContext(object): + """Custom context wrapping the standard options.""" + + def __init__(self, configfile=None, basedir=None, verbosity=0): + self.configfile = configfile + self.basedir = basedir + self.verbosity = verbosity + +pass_octoprint_ctx = click.make_pass_decorator(OctoPrintContext, ensure=True) +"""Decorator to pass in the :class:`OctoPrintContext` instance.""" + +#~~ Custom click option to hide from help + +class HiddenOption(click.Option): + """Custom option sub class with empty help.""" + def get_help_record(self, ctx): + pass + +def hidden_option(*param_decls, **attrs): + """Attaches a hidden option to the command. All positional arguments are + passed as parameter declarations to :class:`Option`; all keyword + arguments are forwarded unchanged. This is equivalent to creating an + :class:`Option` instance manually and attaching it to the + :attr:`Command.params` list. + """ + + import inspect + from click.decorators import _param_memo + + def decorator(f): + if 'help' in attrs: + attrs['help'] = inspect.cleandoc(attrs['help']) + _param_memo(f, HiddenOption(param_decls, **attrs)) + return f + return decorator + +#~~ helper for settings context options + +def set_ctx_obj_option(ctx, param, value): + """Helper for setting eager options on the context.""" + if ctx.obj is None: + ctx.obj = OctoPrintContext() + + if hasattr(ctx.obj, param.name): + setattr(ctx.obj, param.name, value) + +#~~ helper for setting a lot of bulk options + +def bulk_options(options): + """ + Utility decorator to decorate a function with a list of click decorators. + + The provided list of ``options`` will be reversed to ensure correct + processing order (inverse from what would be intuitive). + """ + + def decorator(f): + options.reverse() + for option in options: + option(f) + return f + return decorator + +#~~ helper for setting --basedir, --config and --verbose options + +def standard_options(hidden=False): + """ + Decorator to add the standard options shared among all "octoprint" commands. + + Adds the options ``--basedir``, ``--config`` and ``--verbose``. If ``hidden`` + is set to ``True``, the options will be available on the command but not + listed in its help page. + """ + + factory = click.option + if hidden: + factory = hidden_option + + options = [ + factory("--basedir", "-b", type=click.Path(), callback=set_ctx_obj_option, is_eager=True, expose_value=False, + help="Specify the basedir to use for uploads, timelapses etc."), + factory("--config", "-c", "configfile", type=click.Path(), callback=set_ctx_obj_option, is_eager=True, expose_value=False, + help="Specify the config file to use."), + factory("--verbose", "-v", "verbosity", count=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False, + help="Increase logging verbosity"), + ] + + return bulk_options(options) + +#~~ helper for settings legacy options we still have to support on "octoprint" + +legacy_options = bulk_options([ + hidden_option("--host", type=click.STRING), + hidden_option("--port", type=click.INT), + hidden_option("--logging", type=click.Path()), + hidden_option("--debug", "-d", is_flag=True), + hidden_option("--daemon", type=click.Choice(["start", "stop", "restart"])), + hidden_option("--pid", type=click.Path(), default="/tmp/octoprint.pid"), + hidden_option("--iknowwhatimdoing", "allow_root", is_flag=True), +]) +"""Legacy options available directly on the "octoprint" command in earlier versions. + Kept available for reasons of backwards compatibility, but hidden from the + generated help pages.""" + +#~~ "octoprint" command, merges server_commands and plugin_commands groups + +from .server import server_commands +from .plugins import plugin_commands +from .dev import dev_commands +from .client import client_commands + +@click.group(name="octoprint", invoke_without_command=True, cls=click.CommandCollection, + sources=[server_commands, plugin_commands, dev_commands, client_commands]) +@standard_options() +@legacy_options +@click.version_option(version=octoprint.__version__) +@click.pass_context +def octo(ctx, debug, host, port, logging, daemon, pid, allow_root): + + if ctx.invoked_subcommand is None: + # We have to support calling the octoprint command without any + # sub commands to remain backwards compatible. + # + # But better print a message to inform people that they should + # use the sub commands instead. + + if daemon: + click.echo("Daemon operation via \"octoprint --daemon " + "start|stop|restart\" is deprecated, please use " + "\"octoprint daemon start|stop|restart\" from now on") + + from octoprint.cli.server import daemon_command + ctx.invoke(daemon_command, debug=debug, pid=pid, daemon=daemon, allow_root=allow_root) + else: + click.echo("Starting the server via \"octoprint\" is deprecated, " + "please use \"octoprint serve\" from now on.") + + from octoprint.cli.server import serve_command + ctx.invoke(serve_command, debug=debug, host=host, port=port, logging=logging, allow_root=allow_root) diff --git a/src/octoprint/cli/client.py b/src/octoprint/cli/client.py new file mode 100644 index 000000000..9615ddee9 --- /dev/null +++ b/src/octoprint/cli/client.py @@ -0,0 +1,176 @@ +# coding=utf-8 +from __future__ import absolute_import + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" + +import click +import json + +import octoprint_client + +from octoprint.cli import pass_octoprint_ctx, bulk_options, standard_options +from octoprint import init_settings + + +class JsonStringParamType(click.ParamType): + name = "json" + + def convert(self, value, param, ctx): + try: + return json.loads(value) + except: + self.fail("%s is not a valid json string" % value, param, ctx) + + +@click.group() +def client_commands(): + pass + + +@client_commands.group("client", context_settings=dict(ignore_unknown_options=True)) +@click.option("--host", "-h", type=click.STRING) +@click.option("--port", "-p", type=click.INT) +@click.option("--httpuser", type=click.STRING) +@click.option("--httppass", type=click.STRING) +@click.option("--https", is_flag=True) +@click.option("--prefix", type=click.STRING) +@pass_octoprint_ctx +def client(obj, host, port, httpuser, httppass, https, prefix): + """Basic API client.""" + obj.settings = init_settings(obj.basedir, obj.configfile) + octoprint_client.init_client(obj.settings, https=https, httpuser=httpuser, httppass=httppass, host=host, port=port, prefix=prefix) + + +def log_response(response, status_code=True, body=True, headers=False): + if status_code: + click.echo("Status Code: {}".format(response.status_code)) + if headers: + for header, value in response.headers.items(): + click.echo("{}: {}".format(header, value)) + click.echo() + if body: + click.echo(response.text) + + +@client.command("get") +@click.argument("path") +def get(path): + """Performs a GET request against the specified server path.""" + r = octoprint_client.get(path) + log_response(r) + + +@client.command("post_json") +@click.argument("path") +@click.argument("data", type=JsonStringParamType()) +def post_json(path, data): + """POSTs JSON data to the specified server path.""" + r = octoprint_client.post_json(path, data) + log_response(r) + + +@client.command("patch_json") +@click.argument("path") +@click.argument("data", type=JsonStringParamType()) +def patch_json(path, data): + """PATCHes JSON data to the specified server path.""" + r = octoprint_client.patch(path, data, encoding="json") + log_response(r) + + +@client.command("post_from_file") +@click.argument("path") +@click.argument("file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True)) +@click.option("--json", is_flag=True) +@click.option("--yaml", is_flag=True) +def post_from_file(path, file_path, json_flag, yaml_flag): + """POSTs JSON data to the specified server path.""" + if json_flag or yaml_flag: + if json_flag: + with open(file_path, "rb") as fp: + data = json.load(fp) + else: + import yaml + with open(file_path, "rb") as fp: + data = yaml.safe_load(fp) + + r = octoprint_client.post_json(path, data) + else: + with open(file_path, "rb") as fp: + data = fp.read() + + r = octoprint_client.post(path, data) + + log_response(r) + + +@client.command("command") +@click.argument("path") +@click.argument("command") +@click.option("--str", "-s", "str_params", multiple=True, nargs=2, type=click.Tuple([unicode, unicode])) +@click.option("--int", "-i", "int_params", multiple=True, nargs=2, type=click.Tuple([unicode, int])) +@click.option("--float", "-f", "float_params", multiple=True, nargs=2, type=click.Tuple([unicode, float])) +@click.option("--bool", "-b", "bool_params", multiple=True, nargs=2, type=click.Tuple([unicode, bool])) +def command(path, command, str_params, int_params, float_params, bool_params): + """Sends a JSON command to the specified server path.""" + data = dict() + params = str_params + int_params + float_params + bool_params + for param in params: + data[param[0]] = param[1] + r = octoprint_client.post_command(path, command, additional=data) + log_response(r, body=False) + + +@client.command("upload") +@click.argument("path") +@click.argument("file_path", type=click.Path(exists=True, dir_okay=False, resolve_path=True)) +@click.option("--parameter", "-P", "params", multiple=True, nargs=2, type=click.Tuple([unicode, unicode])) +@click.option("--file-name", type=click.STRING) +@click.option("--content-type", type=click.STRING) +def upload(path, file_path, params, file_name, content_type): + """Uploads the specified file to the specified server path.""" + data = dict() + for param in params: + data[param[0]] = param[1] + + r = octoprint_client.upload(path, file_path, additional=data, file_name=file_name, content_type=content_type) + log_response(r) + + +@client.command("delete") +@click.argument("path") +def delete(path): + """Sends a DELETE request to the specified server path.""" + r = octoprint_client.delete(path) + log_response(r) + + +@client.command("listen") +def listen(): + def on_connect(ws): + click.echo(">>> Connected!") + + def on_close(ws): + click.echo(">>> Connection closed!") + + def on_error(ws, error): + click.echo("!!! Error: {}".format(error)) + + def on_heartbeat(ws): + click.echo("<3") + + def on_message(ws, message_type, message_payload): + click.echo("Message: {}, Payload: {}".format(message_type, json.dumps(message_payload))) + + socket = octoprint_client.connect_socket(on_connect=on_connect, + on_close=on_close, + on_error=on_error, + on_heartbeat=on_heartbeat, + on_message=on_message) + + click.echo(">>> Waiting for client to exit") + try: + socket.wait() + finally: + click.echo(">>> Goodbye...") diff --git a/src/octoprint/cli/dev.py b/src/octoprint/cli/dev.py new file mode 100644 index 000000000..d9902e8f9 --- /dev/null +++ b/src/octoprint/cli/dev.py @@ -0,0 +1,233 @@ +# coding=utf-8 +from __future__ import absolute_import + +__author__ = "Gina Häußge " +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" + + +import click + +class OctoPrintDevelCommands(click.MultiCommand): + """ + Custom `click.MultiCommand `_ + implementation that provides commands relevant for (plugin) development + based on availability of development dependencies. + """ + + sep = ":" + groups = ("plugin",) + + def __init__(self, *args, **kwargs): + click.MultiCommand.__init__(self, *args, **kwargs) + + from octoprint.util.commandline import CommandlineCaller + from functools import partial + + def log_util(f): + def log(*lines): + for line in lines: + f(line) + return log + + self.command_caller = CommandlineCaller() + self.command_caller.on_log_call = log_util(lambda x: click.echo(">> {}".format(x))) + self.command_caller.on_log_stdout = log_util(click.echo) + self.command_caller.on_log_stderr = log_util(partial(click.echo, err=True)) + + def _get_prefix_methods(self, method_prefix): + for name in [x for x in dir(self) if x.startswith(method_prefix)]: + method = getattr(self, name) + yield method + + def _get_commands_from_prefix_methods(self, method_prefix): + for method in self._get_prefix_methods(method_prefix): + result = method() + if result is not None and isinstance(result, click.Command): + yield result + + def _get_commands(self): + result = dict() + for group in self.groups: + for command in self._get_commands_from_prefix_methods("{}_".format(group)): + result[group + self.sep + command.name] = command + return result + + def list_commands(self, ctx): + result = [name for name in self._get_commands()] + result.sort() + return result + + def get_command(self, ctx, cmd_name): + commands = self._get_commands() + return commands.get(cmd_name, None) + + def plugin_new(self): + try: + import cookiecutter.main + except ImportError: + return None + + import contextlib + + @contextlib.contextmanager + def custom_cookiecutter_config(config): + """ + Allows overriding cookiecutter's user config with a custom dict + with fallback to the original data. + """ + from octoprint.util import fallback_dict + + original_get_user_config = cookiecutter.main.get_user_config + original_config = original_get_user_config() + try: + cookiecutter.main.get_user_config = lambda: fallback_dict(config, original_config) + yield + finally: + cookiecutter.main.get_user_config = original_get_user_config + + @contextlib.contextmanager + def custom_cookiecutter_prompt(options): + """ + Custom cookiecutter prompter for the template config. + + If a setting is available in the provided options (read from the CLI) + that will be used, otherwise the user will be prompted for a value + via click. + """ + original_prompt_for_config = cookiecutter.main.prompt_for_config + + def custom_prompt_for_config(context, no_input=False): + import cookiecutter.prompt + + cookiecutter_dict = {} + env = cookiecutter.prompt.Environment() + + for key, raw in context['cookiecutter'].items(): + if key in options: + val = options[key] + else: + raw = raw if isinstance(raw, basestring) else str(raw) + val = env.from_string(raw).render(cookiecutter=cookiecutter_dict) + + if not no_input: + val = click.prompt(key, default=val) + + cookiecutter_dict[key] = val + return cookiecutter_dict + + try: + cookiecutter.main.prompt_for_config = custom_prompt_for_config + yield + finally: + cookiecutter.main.prompt_for_config = original_prompt_for_config + + @click.command("new") + @click.option("--name", "-n", help="The name of the plugin") + @click.option("--package", "-p", help="The plugin package") + @click.option("--author", "-a", help="The plugin author's name") + @click.option("--email", "-e", help="The plugin author's mail address") + @click.option("--license", "-l", help="The plugin's license") + @click.option("--description", "-d", help="The plugin's description") + @click.option("--homepage", help="The plugin's homepage URL") + @click.option("--source", "-s", help="The URL to the plugin's source") + @click.option("--installurl", "-i", help="The plugin's install URL") + @click.argument("identifier", required=False) + def command(name, package, author, email, description, license, homepage, source, installurl, identifier): + """Creates a new plugin based on the OctoPrint Plugin cookiecutter template.""" + from octoprint.util import tempdir + + # deleting a git checkout folder might run into access errors due + # to write-protected sub folders, so we use a custom onerror handler + # that tries to fix such permissions + def onerror(func, path, exc_info): + """Originally from http://stackoverflow.com/a/2656405/2028598""" + import stat + import os + + if not os.access(path, os.W_OK): + os.chmod(path, stat.S_IWUSR) + func(path) + else: + raise + + with tempdir(onerror=onerror) as path: + custom = dict(cookiecutters_dir=path) + with custom_cookiecutter_config(custom): + raw_options = dict( + plugin_identifier=identifier, + plugin_package=package, + plugin_name=name, + full_name=author, + email=email, + plugin_description=description, + plugin_license=license, + plugin_homepage=homepage, + plugin_source=source, + plugin_installurl=installurl + ) + options = dict((k, v) for k, v in raw_options.items() if v is not None) + + with custom_cookiecutter_prompt(options): + cookiecutter.main.cookiecutter("gh:OctoPrint/cookiecutter-octoprint-plugin") + + return command + + def plugin_install(self): + @click.command("install") + @click.option("--path", help="Path of the local plugin development folder to install") + def command(path): + """ + Installs the local plugin in development mode. + + Note: This can NOT be used to install plugins from remote locations + such as the plugin repository! It is strictly for local development + of plugins, to ensure the plugin is installed (editable) into the + same python environment that OctoPrint is installed under. + """ + + import os + import sys + + if not path: + path = os.getcwd() + + # check if this really looks like a plugin + if not os.path.isfile(os.path.join(path, "setup.py")): + click.echo("This doesn't look like an OctoPrint plugin folder") + sys.exit(1) + + self.command_caller.call([sys.executable, "setup.py", "develop"], cwd=path) + + return command + + def plugin_uninstall(self): + from octoprint.util.pip import PipCaller + pip_command = PipCaller.autodetect_pip() + if pip_command is None: + return + + @click.command("uninstall") + @click.argument("name") + def command(name): + """Uninstalls the plugin with the given name.""" + import sys + + lower_name = name.lower() + if not lower_name.startswith("octoprint_") and not lower_name.startswith("octoprint-"): + click.echo("This doesn't look like an OctoPrint plugin name") + sys.exit(1) + + call = [pip_command, "uninstall", "--yes", name] + self.command_caller.call(call) + + return command + +@click.group() +def dev_commands(): + pass + +@dev_commands.group(name="dev", cls=OctoPrintDevelCommands) +def dev(): + """Additional commands for development tasks.""" + pass diff --git a/src/octoprint/cli/plugins.py b/src/octoprint/cli/plugins.py new file mode 100644 index 000000000..47bf887a6 --- /dev/null +++ b/src/octoprint/cli/plugins.py @@ -0,0 +1,99 @@ +# coding=utf-8 +from __future__ import absolute_import + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" + + +import click +import logging + +from octoprint.cli import pass_octoprint_ctx, OctoPrintContext + +#~~ "octoprint plugin:command" commands + +class OctoPrintPluginCommands(click.MultiCommand): + """ + Custom `click.MultiCommand `_ + implementation that collects commands from the plugin hook + :ref:`octoprint.cli.commands `. + + .. attribute:: settings + + The global :class:`~octoprint.settings.Settings` instance. + + .. attribute:: plugin_manager + + The :class:`~octoprint.plugin.core.PluginManager` instance. + """ + + sep = ":" + + def __init__(self, *args, **kwargs): + click.MultiCommand.__init__(self, *args, **kwargs) + + self.settings = None + self.plugin_manager = None + self.hooks = dict() + + self._logger = logging.getLogger(__name__) + self._initialized = False + + def _initialize(self, ctx): + if self._initialized: + return + + if ctx.obj is None: + ctx.obj = OctoPrintContext() + + # initialize settings and plugin manager based on provided + # context (basedir and configfile) + from octoprint import init_settings, init_pluginsystem + self.settings = init_settings(ctx.obj.basedir, ctx.obj.configfile) + self.plugin_manager = init_pluginsystem(self.settings) + + # fetch registered hooks + self.hooks = self.plugin_manager.get_hooks("octoprint.cli.commands") + + self._initialized = True + + def list_commands(self, ctx): + self._initialize(ctx) + result = [name for name in self._get_commands()] + result.sort() + return result + + def get_command(self, ctx, cmd_name): + self._initialize(ctx) + commands = self._get_commands() + return commands.get(cmd_name, None) + + def _get_commands(self): + """Fetch all commands from plugins providing any.""" + + import collections + result = collections.OrderedDict() + + for name, hook in self.hooks.items(): + try: + commands = hook(self, pass_octoprint_ctx) + for command in commands: + if not isinstance(command, click.Command): + self._logger.warn("Plugin {} provided invalid CLI command, ignoring it: {!r}".format(name, command)) + continue + result[name + self.sep + command.name] = command + except: + self._logger.exception("Error while retrieving cli commants for plugin {}".format(name)) + + return result + +@click.group() +@pass_octoprint_ctx +def plugin_commands(obj): + logging.basicConfig(level=logging.DEBUG if obj.verbosity > 0 else logging.WARN) + +@plugin_commands.group(name="plugins", cls=OctoPrintPluginCommands) +def plugins(): + """Additional commands provided by plugins.""" + pass + diff --git a/src/octoprint/cli/server.py b/src/octoprint/cli/server.py new file mode 100644 index 000000000..e5737ffc0 --- /dev/null +++ b/src/octoprint/cli/server.py @@ -0,0 +1,131 @@ +# coding=utf-8 +from __future__ import absolute_import + +__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' +__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License" + + +import click +import logging +import sys + +from octoprint.cli import pass_octoprint_ctx, bulk_options, standard_options + +def run_server(basedir, configfile, host, port, debug, allow_root, logging_config, verbosity): + """Initializes the environment and starts up the server.""" + + from octoprint import init_platform, __display_version__ + + def log_startup(_): + logging.getLogger("octoprint.server").info("Starting OctoPrint {}".format(__display_version__)) + + from octoprint import urllib3_ssl + if not urllib3_ssl: + logging.getLogger("octoprint.server")\ + .warn("requests/urllib3 will run in an insecure SSL environment. " + "You might see corresponding warnings logged later " + "(\"InsecurePlatformWarning\"). It is recommended to either " + "update to a Python version >= 2.7.9 or alternatively " + "install PyOpenSSL plus its dependencies. For details see " + "https://urllib3.readthedocs.org/en/latest/security.html#openssl-pyopenssl") + + settings, _, plugin_manager = init_platform(basedir, + configfile, + logging_file=logging_config, + debug=debug, + verbosity=verbosity, + uncaught_logger=__name__, + after_logging=log_startup) + + from octoprint.server import Server + octoprint_server = Server(settings=settings, plugin_manager=plugin_manager, host=host, port=port, debug=debug, allow_root=allow_root) + octoprint_server.run() + +#~~ server options + +server_options = bulk_options([ + click.option("--host", type=click.STRING, + help="Specify the host on which to bind the server."), + click.option("--port", type=click.INT, + help="Specify the port on which to bind the server."), + click.option("--logging", type=click.Path(), + help="Specify the config file to use for configuring logging."), + click.option("--iknowwhatimdoing", "allow_root", is_flag=True, + help="Allow OctoPrint to run as user root."), + click.option("--debug", is_flag=True, help="Enable debug mode"), +]) +"""Decorator to add the options shared among the server commands: ``--host``, ``--port``, + ``--logging``, ``--iknowwhatimdoing`` and ``--debug``.""" + +#~~ "octoprint serve" and "octoprint daemon" commands + +@click.group() +@pass_octoprint_ctx +def server_commands(obj): + pass + + +@server_commands.command(name="serve") +@server_options +@standard_options(hidden=True) +@pass_octoprint_ctx +def serve_command(obj, host, port, logging, allow_root, debug): + """Starts the OctoPrint server.""" + run_server(obj.basedir, obj.configfile, host, port, debug, + allow_root, logging, obj.verbosity) + + +@server_commands.command(name="daemon") +@click.option("--pid", type=click.Path(), default="/tmp/octoprint.pid", + help="Pidfile to use for daemonizing.") +@server_options +@standard_options(hidden=True) +@click.argument("command", type=click.Choice(["start", "stop", "restart", "status"]), + metavar="start|stop|restart|status") +@pass_octoprint_ctx +def daemon_command(octoprint_ctx, pid, host, port, logging, allow_root, debug, command): + """ + Starts, stops or restarts in daemon mode. + + Please note that daemon mode is only supported under Linux right now. + """ + if sys.platform == "darwin" or sys.platform == "win32": + click.echo("Sorry, daemon mode is only supported under Linux right now", + file=sys.stderr) + sys.exit(2) + + if pid is None: + click.echo("No path to a pidfile set", + file=sys.stderr) + sys.exit(1) + + from octoprint.daemon import Daemon + class OctoPrintDaemon(Daemon): + def __init__(self, pidfile, basedir, configfile, host, port, debug, allow_root, logging_config, verbosity): + Daemon.__init__(self, pidfile) + + self._basedir = basedir + self._configfile = configfile + self._host = host + self._port = port + self._debug = debug + self._allow_root = allow_root + self._logging_config = logging_config + self._verbosity = verbosity + + def run(self): + run_server(self._basedir, self._configfile, self._host, self._port, self._debug, self._allow_root, self._logging_config, self._verbosity) + + octoprint_daemon = OctoPrintDaemon(pid, octoprint_ctx.basedir, octoprint_ctx.configfile, + host, port, debug, allow_root, logging, octoprint_ctx.verbosity) + + if command == "start": + octoprint_daemon.start() + elif command == "stop": + octoprint_daemon.stop() + elif command == "restart": + octoprint_daemon.restart() + elif command == "status": + octoprint_daemon.status() + + diff --git a/src/octoprint/daemon.py b/src/octoprint/daemon.py index 4ef56b162..4d00252f7 100644 --- a/src/octoprint/daemon.py +++ b/src/octoprint/daemon.py @@ -1,46 +1,65 @@ +# coding=utf-8 """ -Generic linux daemon base class for python 3.x +Generic linux daemon base class Originally from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon_in_python/#c35 """ +from __future__ import (print_function, absolute_import) import sys, os, time, signal class Daemon: - """A generic daemon class. + """ + A generic daemon class. - Usage: subclass the daemon class and override the run() method.""" + Usage: subclass the daemon class and override the run() method. - def __init__(self, pidfile): self.pidfile = pidfile - - def daemonize(self): - """Deamonize class. UNIX double fork mechanism.""" + If you want to log the output to someplace different that stdout and stderr, + also override the echo() and error() methods. + """ - try: - pid = os.fork() + def __init__(self, pidfile): + self.pidfile = pidfile + + def _daemonize(self): + """Daemonize class. UNIX double fork mechanism.""" + + self._double_fork() + self._redirect_io() + + # write pidfile + pid = str(os.getpid()) + self.set_pid(pid) + + # register listener for SIGTERM + signal.signal(signal.SIGTERM, self._on_sigterm) + + def _double_fork(self): + try: + pid = os.fork() if pid > 0: # exit first parent - sys.exit(0) - except OSError as err: - sys.stderr.write('fork #1 failed: {0}\n'.format(err)) + sys.exit(0) + except OSError as err: + self.error("First fork failed: {}".format(str(err))) sys.exit(1) - - # decouple from parent environment - os.chdir('/') - os.setsid() - os.umask(002) - - # do second fork - try: - pid = os.fork() - if pid > 0: + # decouple from parent environment + os.chdir('/') + os.setsid() + os.umask(002) + + # do second fork + try: + pid = os.fork() + if pid > 0: # exit from second parent - sys.exit(0) - except OSError as err: - sys.stderr.write('fork #2 failed: {0}\n'.format(err)) - sys.exit(1) - + sys.exit(0) + except OSError as err: + self.error("Second fork failed: {}".format(str(err))) + sys.exit(1) + + def _redirect_io(self): # redirect standard file descriptors sys.stdout.flush() sys.stderr.flush() @@ -51,57 +70,39 @@ class Daemon: os.dup2(si.fileno(), sys.stdin.fileno()) os.dup2(so.fileno(), sys.stdout.fileno()) os.dup2(se.fileno(), sys.stderr.fileno()) - - # write pidfile - pid = str(os.getpid()) - with open(self.pidfile,'w+') as f: - f.write(pid + '\n') - # register listener for SIGTERM - signal.signal(signal.SIGTERM, self.term) - - def term(self, _signo, _stack_frame): - os.remove(self.pidfile) + def _on_sigterm(self, _signo, _stack_frame): + """Signal handler for SIGTERM, deletes the pidfile.""" + self.remove_pidfile() sys.exit(0) def start(self): """Start the daemon.""" # Check for a pidfile to see if the daemon already runs - try: - with open(self.pidfile,'r') as pf: - - pid = int(pf.read().strip()) - except IOError: - pid = None - + pid = self.get_pid() if pid: - message = "pidfile {0} already exist. " + \ - "Daemon already running?\n" - sys.stderr.write(message.format(self.pidfile)) + self.error("pidfile {} already exist. Is the daemon already running?".format(self.pidfile)) sys.exit(1) - + + self.echo("Starting daemon...") + # Start the daemon - self.daemonize() + self._daemonize() self.run() - def stop(self): + def stop(self, check_running=True): """Stop the daemon.""" - - # Get the pid from the pidfile - try: - with open(self.pidfile,'r') as pf: - pid = int(pf.read().strip()) - except IOError: - pid = None - + pid = self.get_pid() if not pid: - message = "pidfile {0} does not exist. " + \ - "Daemon not running?\n" - sys.stderr.write(message.format(self.pidfile)) - return # not an error in a restart + if not check_running: + return + self.error("pidfile {} does not exist. Is the daemon really running?".format(self.pidfile)) + sys.exit(1) - # Try killing the daemon process + self.echo("Stopping daemon...") + + # Try killing the daemon process try: while 1: os.kill(pid, signal.SIGTERM) @@ -109,20 +110,71 @@ class Daemon: except OSError as err: e = str(err.args) if e.find("No such process") > 0: - if os.path.exists(self.pidfile): - os.remove(self.pidfile) + self.remove_pidfile() else: - print (str(err.args)) + self.error(e) sys.exit(1) def restart(self): """Restart the daemon.""" - self.stop() + self.stop(check_running=False) self.start() + def status(self): + """Prints the daemon status.""" + if self.is_running(): + self.echo("Daemon is running") + else: + self.echo("Daemon is not running") + + def is_running(self): + """Check if a process is running under the specified pid.""" + pid = self.get_pid() + if pid is None: + return False + + try: + os.kill(pid, 0) + except OSError: + try: + self.remove_pidfile() + except: + self.error("Daemon found not running, but could not remove stale pidfile") + return False + else: + return True + + def get_pid(self): + """Get the pid from the pidfile.""" + try: + with open(self.pidfile,'r') as pf: + pid = int(pf.read().strip()) + except (IOError, ValueError): + pid = None + return pid + + def set_pid(self, pid): + """Write the pid to the pidfile.""" + with open(self.pidfile,'w+') as f: + f.write(str(pid) + '\n') + + def remove_pidfile(self): + """Removes the pidfile.""" + if os.path.isfile(self.pidfile): + os.remove(self.pidfile) + def run(self): """You should override this method when you subclass Daemon. - - It will be called after the process has been daemonized by + + It will be called after the process has been daemonized by start() or restart().""" + raise NotImplementedError() + + @classmethod + def echo(cls, line): + print(line) + + @classmethod + def error(cls, line): + print(line, stream=sys.stderr) diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index c1d453aa7..ddeec6978 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -22,7 +22,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import os import logging -from octoprint.settings import settings +from octoprint.settings import settings as s from octoprint.plugin.core import (PluginInfo, PluginManager, Plugin) from octoprint.plugin.types import * @@ -44,7 +44,7 @@ def _validate_plugin(phase, plugin_info): setattr(plugin_info.instance, PluginInfo.attr_hooks, hooks) def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None, plugin_disabled_list=None, - plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None): + plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None, settings=None): """ Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager` singleton. @@ -87,9 +87,12 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en else: if init: + if settings is None: + settings = s() + if plugin_folders is None: plugin_folders = ( - settings().getBaseFolder("plugins"), + settings.getBaseFolder("plugins"), (os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "plugins")), True) ) if plugin_types is None: @@ -109,7 +112,7 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en if plugin_entry_points is None: plugin_entry_points = "octoprint.plugin" if plugin_disabled_list is None: - plugin_disabled_list = settings().get(["plugins", "_disabled"]) + plugin_disabled_list = settings.get(["plugins", "_disabled"]) if plugin_restart_needing_hooks is None: plugin_restart_needing_hooks = [ "octoprint.server.http" @@ -136,7 +139,7 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en return _instance -def plugin_settings(plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None): +def plugin_settings(plugin_key, defaults=None, get_preprocessors=None, set_preprocessors=None, settings=None): """ Factory method for creating a :class:`PluginSettings` instance. @@ -145,12 +148,45 @@ def plugin_settings(plugin_key, defaults=None, get_preprocessors=None, set_prepr defaults (dict): The default settings for the plugin. get_preprocessors (dict): The getter preprocessors for the plugin. set_preprocessors (dict): The setter preprocessors for the plugin. + settings (octoprint.settings.Settings): The settings instance to use. Returns: PluginSettings: A fully initialized :class:`PluginSettings` instance to be used to access the plugin's settings """ - return PluginSettings(settings(), plugin_key, defaults=defaults, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors) + if settings is None: + settings = s() + return PluginSettings(settings, plugin_key, defaults=defaults, + get_preprocessors=get_preprocessors, + set_preprocessors=set_preprocessors) + + +def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None): + """ + Factory method for creating a :class:`PluginSettings` instance for a given :class:`SettingsPlugin` instance. + + Will return `None` if the provided `instance` is not a :class:`SettingsPlugin` instance. + + Arguments: + plugin_key (string): The plugin identifier for which to create the settings instance. + implementation (octoprint.plugin.SettingsPlugin): The :class:`SettingsPlugin` instance. + settings (octoprint.settings.Settings): The settings instance to use. Defaults to the global OctoPrint settings. + + Returns: + PluginSettings or None: A fully initialized :class:`PluginSettings` instance to be used to access the plugin's + settings, or `None` if the provided `instance` was not a class:`SettingsPlugin` + """ + if not isinstance(instance, SettingsPlugin): + return None + + try: + defaults = instance.get_settings_defaults() + get_preprocessors, set_preprocessors = instance.get_settings_preprocessors() + except: + logging.getLogger(__name__).exception("Error while retrieving defaults or preprocessors for plugin {}".format(plugin_key)) + return None + + return plugin_settings(plugin_key, defaults=defaults, get_preprocessors=get_preprocessors, set_preprocessors=set_preprocessors, settings=settings) def call_plugin(types, method, args=None, kwargs=None, callback=None, error_callback=None, sorting_context=None): diff --git a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 index ae1379762..6804c6849 100644 --- a/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 +++ b/src/octoprint/plugins/pluginmanager/templates/pluginmanager_settings.jinja2 @@ -113,8 +113,10 @@ {{ pluginmanager_sudopip() }}

{{ _('... from the Plugin Repository', url='http://plugins.octoprint.org') }} - - +