🎨 Switch to black formatting

This commit is contained in:
Gina Häußge committed 2020-10-07 13:13:06 +02:00
1 parent 60f45ffaf6
commit 1f93b2355a
184 files changed
+63526 -51203

No files matched your search

+12 -4
View File
@@ -10,10 +10,6 @@ insert_final_newline = true
trim_trailing_whitespace = true
[**.py]
indent_style = tab
indent_size = 4
[src/octoprint/vendor/sockjs/**.py]
indent_style = space
indent_size = 4
@@ -21,6 +17,18 @@ indent_size = 4
indent_style = space
indent_size = 4
[src/octoprint/static/js/login/**.js]
indent_style = space
indent_size = 4
[src/octoprint/static/js/recovery/**.js]
indent_style = space
indent_size = 4
[src/octoprint/static/less/octoprint.less]
indent_style = space
indent_size = 2
[.travis.yml]
indent_style = space
indent_size = 2
+21
View File
@@ -0,0 +1,21 @@
[tool.black]
line-length = 90
include = '''
(
(
src
| tests
| .github
).*\.pyi?$
)|(
setup\.py
)
'''
exclude = '''
(
src/octoprint/vendor # we want to still be able to apply patches from upstream w/o
# match issues
)
'''
+89 -69
View File
@@ -18,8 +18,8 @@ import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
sys.path.insert(0, os.path.abspath('../src/'))
sys.path.append(os.path.abspath('sphinxext'))
sys.path.insert(0, os.path.abspath("../src/"))
sys.path.append(os.path.abspath("sphinxext"))
import octoprint._version
from datetime import date
@@ -30,32 +30,46 @@ year_current = date.today().year
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
needs_sphinx = '1.3'
needs_sphinx = "1.3"
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = ['codeblockext', 'onlineinclude', 'sphinx.ext.todo', 'sphinx.ext.autodoc', 'sphinxcontrib.httpdomain',
'sphinx.ext.napoleon', 'sphinxcontrib.mermaid', 'sphinx.ext.intersphinx']
extensions = [
"codeblockext",
"onlineinclude",
"sphinx.ext.todo",
"sphinx.ext.autodoc",
"sphinxcontrib.httpdomain",
"sphinx.ext.napoleon",
"sphinxcontrib.mermaid",
"sphinx.ext.intersphinx",
]
todo_include_todos = True
intersphinx_mapping = {'python': ('https://docs.python.org/3', None),
'python2': ('https://docs.python.org/2', None),
'pyserial': ('https://pythonhosted.org/pyserial', None)}
intersphinx_mapping = {
"python": ("https://docs.python.org/3", None),
"python2": ("https://docs.python.org/2", None),
"pyserial": ("https://pythonhosted.org/pyserial", None),
}
# Add any paths that contain templates here, relative to this directory.
templates_path = ['_templates']
templates_path = ["_templates"]
# The suffix of source filenames.
source_suffix = '.rst'
source_suffix = ".rst"
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
master_doc = "index"
# General information about the project.
project = 'OctoPrint'
copyright = '%d-%d, Gina Häußge' % (year_since, year_current) if year_current > year_since else '%d, Gina Häußge' % year_since
project = "OctoPrint"
copyright = (
"%d-%d, Gina Häußge" % (year_since, year_current)
if year_current > year_since
else "%d, Gina Häußge" % year_since
)
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
@@ -68,133 +82,136 @@ release = version
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
exclude_patterns = ["_build"]
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
pygments_style = "sphinx"
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# modindex_common_prefix = []
# If true, keep warnings as "system message" paragraphs in the built documents.
#keep_warnings = False
# keep_warnings = False
numfig = True
# -- Options for HTML output ---------------------------------------------------
import sphinx_rtd_theme
html_theme = 'sphinx_rtd_theme'
html_theme = "sphinx_rtd_theme"
html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of built-in themes.
#html_theme = "sphinx_rtd_theme"
# html_theme = "sphinx_rtd_theme"
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# html_theme_path = [sphinx_rtd_theme.get_html_theme_path()]
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
#html_title = None
# html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the built-in static files,
# so a file named "default.css" will overwrite the built-in "default.css".
html_static_path = ['_static']
html_static_path = ["_static"]
def setup(app):
app.add_css_file("theme_overrides.css")
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a <link> tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'OctoPrintDoc'
htmlhelp_basename = "OctoPrintDoc"
# -- Options for LaTeX output --------------------------------------------------
#latex_elements = {
# latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
@@ -203,47 +220,44 @@ htmlhelp_basename = 'OctoPrintDoc'
# Additional stuff for the LaTeX preamble.
#'preamble': '',
#}
# }
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
#latex_documents = [
# latex_documents = [
# ('index', 'OctoPrint.tex', 'OctoPrint Documentation',
# 'Gina Häußge', 'manual'),
#]
# ]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# latex_logo = None
# For "manual" documents, if this is true, then top-level headings are parts,
# not chapters.
#latex_use_parts = False
# latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'octoprint', 'OctoPrint Documentation',
['Gina Häußge'], 1)
]
man_pages = [("index", "octoprint", "OctoPrint Documentation", ["Gina Häußge"], 1)]
# If true, show URL addresses after external links.
#man_show_urls = False
# man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
@@ -252,19 +266,25 @@ man_pages = [
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'OctoPrint', 'OctoPrint Documentation',
'Gina Häußge', 'OctoPrint', 'One line description of project.',
'Miscellaneous'),
(
"index",
"OctoPrint",
"OctoPrint Documentation",
"Gina Häußge",
"OctoPrint",
"One line description of project.",
"Miscellaneous",
),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
# texinfo_show_urls = 'footnote'
# If true, do not generate a @detailmenu in the "Top" node's menu.
#texinfo_no_detailmenu = False
# texinfo_no_detailmenu = False
+214 -186
View File
@@ -2,7 +2,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'The MIT License <http://opensource.org/licenses/MIT>'
__license__ = "The MIT License <http://opensource.org/licenses/MIT>"
__copyright__ = "Copyright (C) 2015 Gina Häußge - Released under terms of the MIT License"
from sphinx.directives.code import CodeBlock
@@ -21,235 +21,263 @@ from pygments.lexers.python import PythonConsoleLexer
from pygments.util import ClassNotFound
if False:
# For type annotation
from typing import Any, Dict, List, Tuple # NOQA
# For type annotation
from typing import Any, Dict, List, Tuple # NOQA
def _merge_dict(a, b):
"""
Little helper to merge two dicts a and b on the fly.
"""
result = dict(a)
result.update(b)
return result
"""
Little helper to merge two dicts a and b on the fly.
"""
result = dict(a)
result.update(b)
return result
class literal_block_ext(nodes.General, nodes.FixedTextElement):
"""
Custom node which is basically the same as a :class:`literal_block`, just with whitespace support and introduced
in order to be able to have a custom visitor.
"""
"""
Custom node which is basically the same as a :class:`literal_block`, just with whitespace support and introduced
in order to be able to have a custom visitor.
"""
@classmethod
def from_literal_block(cls, block):
"""
Factory method constructing an instance exactly copying all attributes over from ``block`` and settings a
custom ``tagname``.
"""
new = literal_block_ext()
for a in (
"attributes",
"basic_attributes",
"child_text_separator",
"children",
"document",
"known_attributes",
"line",
"list_attributes",
"local_attributes",
"parent",
"rawsource",
"source",
):
setattr(new, a, getattr(block, a))
new.tagname = "literal_block_ext"
return new
@classmethod
def from_literal_block(cls, block):
"""
Factory method constructing an instance exactly copying all attributes over from ``block`` and settings a
custom ``tagname``.
"""
new = literal_block_ext()
for a in ("attributes", "basic_attributes", "child_text_separator", "children", "document", "known_attributes",
"line", "list_attributes", "local_attributes", "parent", "rawsource", "source"):
setattr(new, a, getattr(block, a))
new.tagname = "literal_block_ext"
return new
class CodeBlockExt(CodeBlock):
"""
This is basically an extension of a regular :class:`CodeBlock` directive which just supports an additional option
``whitespace`` which if present will enable (together with everything else in here) to render whitespace in
code blocks.
"""
"""
This is basically an extension of a regular :class:`CodeBlock` directive which just supports an additional option
``whitespace`` which if present will enable (together with everything else in here) to render whitespace in
code blocks.
"""
option_spec = _merge_dict(CodeBlock.option_spec, dict(whitespace=directives.flag))
option_spec = _merge_dict(CodeBlock.option_spec, dict(whitespace=directives.flag))
def run(self):
# type: () -> List[nodes.Node]
# get result from parent implementation
code_block = CodeBlock.run(self)
def run(self):
# type: () -> List[nodes.Node]
# get result from parent implementation
code_block = CodeBlock.run(self)
def find_and_wrap_literal_block(node):
"""
Recursive method to turn all literal blocks located within a node into :class:`literal_block_ext`.
"""
def find_and_wrap_literal_block(node):
"""
Recursive method to turn all literal blocks located within a node into :class:`literal_block_ext`.
"""
if isinstance(node, nodes.container):
# container node => handle all children
children = []
for child in node.children:
children.append(find_and_wrap_literal_block(child))
node.children = children
return node
if isinstance(node, nodes.container):
# container node => handle all children
children = []
for child in node.children:
children.append(find_and_wrap_literal_block(child))
node.children = children
return node
elif isinstance(node, nodes.literal_block):
# literal block => replace it
return self._wrap_literal_block(node)
elif isinstance(node, nodes.literal_block):
# literal block => replace it
return self._wrap_literal_block(node)
else:
# no idea what that is => leave it alone
return node
else:
# no idea what that is => leave it alone
return node
# replace all created literal_blocks with literal_block_ext instances
return list(map(find_and_wrap_literal_block, code_block))
# replace all created literal_blocks with literal_block_ext instances
return list(map(find_and_wrap_literal_block, code_block))
def _wrap_literal_block(self, node):
literal = literal_block_ext.from_literal_block(node)
literal["whitespace"] = "whitespace" in self.options
return literal
def _wrap_literal_block(self, node):
literal = literal_block_ext.from_literal_block(node)
literal["whitespace"] = "whitespace" in self.options
return literal
class PygmentsBridgeExt(object):
"""
Wrapper for :class:`PygmentsBridge`, delegates everything to the wrapped ``bridge`` but :method:`highlight_block`,
which calls the parent implementation for lexer selection, then
"""
"""
Wrapper for :class:`PygmentsBridge`, delegates everything to the wrapped ``bridge`` but :method:`highlight_block`,
which calls the parent implementation for lexer selection, then
"""
def __init__(self, bridge, whitespace):
self._bridge = bridge
self._whitespace = whitespace
def __init__(self, bridge, whitespace):
self._bridge = bridge
self._whitespace = whitespace
def __getattr__(self, item):
return getattr(self._bridge, item)
def __getattr__(self, item):
return getattr(self._bridge, item)
def highlight_block(self, source, lang, opts=None, warn=None, force=False, **kwargs):
if not self._whitespace:
return self._bridge.highlight_block(source, lang, opts=opts, warn=warn, force=force, **kwargs)
def highlight_block(self, source, lang, opts=None, warn=None, force=False, **kwargs):
if not self._whitespace:
return self._bridge.highlight_block(
source, lang, opts=opts, warn=warn, force=force, **kwargs
)
# We are still here => we need to basically do everything the parent implementation does (and does so in a very
# inextensible way...), but inject the whitespace filter into the used lexer just before the highlighting run
# and remove it afterwards so the lexer can be safely reused.
#
# For this we define a context manager that will allow us to wrap a lexer and modify its filters on the fly to
# include the whitespace filter.
# We are still here => we need to basically do everything the parent implementation does (and does so in a very
# inextensible way...), but inject the whitespace filter into the used lexer just before the highlighting run
# and remove it afterwards so the lexer can be safely reused.
#
# For this we define a context manager that will allow us to wrap a lexer and modify its filters on the fly to
# include the whitespace filter.
class whitespace(object):
def __init__(self, lexer):
self._lexer = lexer
self._orig_filters = lexer.filters
self._orig_tabsize = lexer.tabsize
class whitespace(object):
def __init__(self, lexer):
self._lexer = lexer
self._orig_filters = lexer.filters
self._orig_tabsize = lexer.tabsize
def __enter__(self):
new_filters = list(self._orig_filters)
new_filters.append(VisibleWhitespaceFilter(spaces=True, tabs=True, tabsize=self._lexer.tabsize))
self._lexer.filters = new_filters
self._lexer.tabsize = 0
return self._lexer
def __enter__(self):
new_filters = list(self._orig_filters)
new_filters.append(
VisibleWhitespaceFilter(
spaces=True, tabs=True, tabsize=self._lexer.tabsize
)
)
self._lexer.filters = new_filters
self._lexer.tabsize = 0
return self._lexer
def __exit__(self, type, value, traceback):
self._lexer.filters = self._orig_filters
self._lexer.tabsize = self._orig_tabsize
def __exit__(self, type, value, traceback):
self._lexer.filters = self._orig_filters
self._lexer.tabsize = self._orig_tabsize
# Then a ton of copy-pasted code follows. Sadly, we need to do this since we have no way to inject ourselves
# into the highlighting call otherwise - lexer selection and actual call are tightly coupled in the original
# "highlight_block" method, with no means for external code to inject different functionality.
#
# Unless otherwise marked ("MODIFIED"), any code in this method after this line is copied verbatim from the
# implementation of sphinx.highlighting.PygmentsBridge, released under the Simplified BSD License, the copyright
# lies with the respective authors.
# Then a ton of copy-pasted code follows. Sadly, we need to do this since we have no way to inject ourselves
# into the highlighting call otherwise - lexer selection and actual call are tightly coupled in the original
# "highlight_block" method, with no means for external code to inject different functionality.
#
# Unless otherwise marked ("MODIFIED"), any code in this method after this line is copied verbatim from the
# implementation of sphinx.highlighting.PygmentsBridge, released under the Simplified BSD License, the copyright
# lies with the respective authors.
if not isinstance(source, text_type):
source = source.decode()
if not isinstance(source, text_type):
source = source.decode()
# find out which lexer to use
if lang in ('py', 'python'):
if source.startswith('>>>'):
# interactive session
lexer = sphinx.highlighting.lexers['pycon']
elif not force:
# maybe Python -- try parsing it
if self.try_parse(source):
lexer = sphinx.highlighting.lexers['python']
else:
lexer = sphinx.highlighting.lexers['none']
else:
lexer = sphinx.highlighting.lexers['python']
elif lang in ('python3', 'py3') and source.startswith('>>>'):
# for py3, recognize interactive sessions, but do not try parsing...
lexer = sphinx.highlighting.lexers['pycon3']
elif lang == 'guess':
# try:
lexer = sphinx.highlighting.guess_lexer(source)
# except Exception:
# lexer = sphinx.highlighting.lexers['none']
else:
if lang in sphinx.highlighting.lexers:
lexer = sphinx.highlighting.lexers[lang]
else:
try:
lexer = sphinx.highlighting.lexers[lang] = sphinx.highlighting.get_lexer_by_name(lang, **opts or {})
except ClassNotFound:
if warn:
warn('Pygments lexer name %r is not known' % lang)
lexer = sphinx.highlighting.lexers['none']
else:
raise
else:
lexer.add_filter('raiseonerror')
# find out which lexer to use
if lang in ("py", "python"):
if source.startswith(">>>"):
# interactive session
lexer = sphinx.highlighting.lexers["pycon"]
elif not force:
# maybe Python -- try parsing it
if self.try_parse(source):
lexer = sphinx.highlighting.lexers["python"]
else:
lexer = sphinx.highlighting.lexers["none"]
else:
lexer = sphinx.highlighting.lexers["python"]
elif lang in ("python3", "py3") and source.startswith(">>>"):
# for py3, recognize interactive sessions, but do not try parsing...
lexer = sphinx.highlighting.lexers["pycon3"]
elif lang == "guess":
# try:
lexer = sphinx.highlighting.guess_lexer(source)
# except Exception:
# lexer = sphinx.highlighting.lexers['none']
else:
if lang in sphinx.highlighting.lexers:
lexer = sphinx.highlighting.lexers[lang]
else:
try:
lexer = sphinx.highlighting.lexers[
lang
] = sphinx.highlighting.get_lexer_by_name(lang, **opts or {})
except ClassNotFound:
if warn:
warn("Pygments lexer name %r is not known" % lang)
lexer = sphinx.highlighting.lexers["none"]
else:
raise
else:
lexer.add_filter("raiseonerror")
if not isinstance(source, text_type):
source = source.decode()
if not isinstance(source, text_type):
source = source.decode()
# trim doctest options if wanted
if isinstance(lexer, PythonConsoleLexer) and self._bridge.trim_doctest_flags:
source = doctest.blankline_re.sub('', source)
source = doctest.doctestopt_re.sub('', source)
# trim doctest options if wanted
if isinstance(lexer, PythonConsoleLexer) and self._bridge.trim_doctest_flags:
source = doctest.blankline_re.sub("", source)
source = doctest.doctestopt_re.sub("", source)
# highlight via Pygments
formatter = self._bridge.get_formatter(**kwargs)
try:
# MODIFIED: replaced by whitespace wrapped call
with whitespace(lexer) as l:
hlsource = highlight(source, l, formatter)
# /MODIFIED
except ErrorToken:
# this is most probably not the selected language,
# so let it pass unhighlighted
# highlight via Pygments
formatter = self._bridge.get_formatter(**kwargs)
try:
# MODIFIED: replaced by whitespace wrapped call
with whitespace(lexer) as l:
hlsource = highlight(source, l, formatter)
# /MODIFIED
except ErrorToken:
# this is most probably not the selected language,
# so let it pass unhighlighted
# MODIFIED: replaced by whitespace wrapped call
with whitespace(sphinx.highlighting.lexers["none"]) as l:
hlsource = highlight(source, l, formatter)
# /MODIFIED
return hlsource
# MODIFIED: replaced by whitespace wrapped call
with whitespace(sphinx.highlighting.lexers["none"]) as l:
hlsource = highlight(source, l, formatter)
# /MODIFIED
return hlsource
class whitespace_highlighter(object):
"""
Context manager for adapting the used highlighter on a translator for a given node's whitespace properties.
"""
def __init__(self, translator, node):
self.translator = translator
self.node = node
"""
Context manager for adapting the used highlighter on a translator for a given node's whitespace properties.
"""
self._orig_highlighter = self.translator.highlighter
def __init__(self, translator, node):
self.translator = translator
self.node = node
def __enter__(self):
whitespace = self.node["whitespace"] if "whitespace" in self.node else False
if whitespace:
self.translator.highlighter = PygmentsBridgeExt(self._orig_highlighter, whitespace)
return self.translator
self._orig_highlighter = self.translator.highlighter
def __exit__(self, exc_type, exc_val, exc_tb):
self.translator.highlighter = self._orig_highlighter
def __enter__(self):
whitespace = self.node["whitespace"] if "whitespace" in self.node else False
if whitespace:
self.translator.highlighter = PygmentsBridgeExt(
self._orig_highlighter, whitespace
)
return self.translator
def __exit__(self, exc_type, exc_val, exc_tb):
self.translator.highlighter = self._orig_highlighter
def visit_literal_block_ext(translator, node):
"""
When our custom code block is visited, we temporarily exchange the highlighter used in the translator, call the
visitor for regular literal blocks, then switch back again.
"""
with whitespace_highlighter(translator, node):
translator.visit_literal_block(node)
"""
When our custom code block is visited, we temporarily exchange the highlighter used in the translator, call the
visitor for regular literal blocks, then switch back again.
"""
with whitespace_highlighter(translator, node):
translator.visit_literal_block(node)
def depart_literal_block_ext(translator, node):
"""
Just call the depart function for regular literal blocks.
"""
with whitespace_highlighter(translator, node):
translator.depart_literal_block(node)
"""
Just call the depart function for regular literal blocks.
"""
with whitespace_highlighter(translator, node):
translator.depart_literal_block(node)
def setup(app):
# custom directive
app.add_directive("code-block-ext", CodeBlockExt)
# custom directive
app.add_directive("code-block-ext", CodeBlockExt)
# custom node type
handler = (visit_literal_block_ext, depart_literal_block_ext)
app.add_node(literal_block_ext, html=handler, latex=handler, text=handler)
# custom node type
handler = (visit_literal_block_ext, depart_literal_block_ext)
app.add_node(literal_block_ext, html=handler, latex=handler, text=handler)
return dict(version="0.1")
return dict(version="0.1")
+89 -74
View File
@@ -2,7 +2,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'The MIT License <http://opensource.org/licenses/MIT>'
__license__ = "The MIT License <http://opensource.org/licenses/MIT>"
__copyright__ = "Copyright (C) 2015 Gina Häußge - Released under terms of the MIT License"
@@ -10,103 +10,118 @@ import codecs
import requests
from contextlib import closing
from sphinx.directives.code import LiteralIncludeReader, LiteralInclude, dedent_lines, \
nodes, parselinenos, logger, container_wrapper
from sphinx.directives.code import (
LiteralIncludeReader,
LiteralInclude,
dedent_lines,
nodes,
parselinenos,
logger,
container_wrapper,
)
from sphinx.util.nodes import set_source_info
if False:
# For type annotation
from typing import Any, List # NOQA
# For type annotation
from typing import Any, List # NOQA
cache = dict()
class OnlineIncludeReader(LiteralIncludeReader):
def read_file(self, filename, location=None):
# type: (unicode, Any) -> List[unicode]
def read_file(self, filename, location=None):
# type: (unicode, Any) -> List[unicode]
global cache
try:
if filename in cache:
lines = cache[filename]
else:
with closing(requests.get(filename, stream=True)) as r:
r.encoding = self.encoding
lines = r.text.splitlines(True)
cache[filename] = lines
global cache
try:
if filename in cache:
lines = cache[filename]
else:
with closing(requests.get(filename, stream=True)) as r:
r.encoding = self.encoding
lines = r.text.splitlines(True)
cache[filename] = lines
if "tab-width" in self.options:
lines = [line.expandtabs(self.options["tab-width"]) for line in lines]
if 'tab-width' in self.options:
lines = [line.expandtabs(self.options['tab-width']) for line in lines]
return lines
except (IOError, OSError):
raise IOError('Include file %r not found or reading it failed' % filename)
except UnicodeError:
raise UnicodeError('Encoding %r used for reading included file %r seems to '
'be wrong, try giving an :encoding: option' % (self.encoding, filename))
return lines
except (IOError, OSError):
raise IOError("Include file %r not found or reading it failed" % filename)
except UnicodeError:
raise UnicodeError(
"Encoding %r used for reading included file %r seems to "
"be wrong, try giving an :encoding: option" % (self.encoding, filename)
)
class OnlineIncludeDirective(LiteralInclude):
def run(self):
# type: () -> List[nodes.Node]
document = self.state.document
if not document.settings.file_insertion_enabled:
return [
document.reporter.warning("File insertion disabled", line=self.lineno)
]
# convert options['diff'] to absolute path
if "diff" in self.options:
_, path = self.env.relfn2path(self.options["diff"])
self.options["diff"] = path
def run(self):
# type: () -> List[nodes.Node]
document = self.state.document
if not document.settings.file_insertion_enabled:
return [document.reporter.warning('File insertion disabled',
line=self.lineno)]
# convert options['diff'] to absolute path
if 'diff' in self.options:
_, path = self.env.relfn2path(self.options['diff'])
self.options['diff'] = path
try:
location = self.state_machine.get_source_and_line(self.lineno)
url = self.arguments[0]
try:
location = self.state_machine.get_source_and_line(self.lineno)
url = self.arguments[0]
reader = OnlineIncludeReader(url, self.options, self.config)
text, lines = reader.read(location=location)
reader = OnlineIncludeReader(url, self.options, self.config)
text, lines = reader.read(location=location)
retnode = nodes.literal_block(text, text, source=url)
set_source_info(self, retnode)
if self.options.get("diff"): # if diff is set, set udiff
retnode["language"] = "udiff"
elif "language" in self.options:
retnode["language"] = self.options["language"]
retnode["linenos"] = (
"linenos" in self.options
or "lineno-start" in self.options
or "lineno-match" in self.options
)
retnode["classes"] += self.options.get("class", [])
extra_args = retnode["highlight_args"] = {}
if "emphasize-lines" in self.options:
hl_lines = parselinenos(self.options["emphasize-lines"], lines)
if any(i >= lines for i in hl_lines):
logger.warning(
"line number spec is out of range(1-%d): %r"
% (lines, self.options["emphasize-lines"]),
location=location,
)
extra_args["hl_lines"] = [x + 1 for x in hl_lines if x < lines]
extra_args["linenostart"] = reader.lineno_start
retnode = nodes.literal_block(text, text, source=url)
set_source_info(self, retnode)
if self.options.get('diff'): # if diff is set, set udiff
retnode['language'] = 'udiff'
elif 'language' in self.options:
retnode['language'] = self.options['language']
retnode['linenos'] = ('linenos' in self.options or
'lineno-start' in self.options or
'lineno-match' in self.options)
retnode['classes'] += self.options.get('class', [])
extra_args = retnode['highlight_args'] = {}
if 'emphasize-lines' in self.options:
hl_lines = parselinenos(self.options['emphasize-lines'], lines)
if any(i >= lines for i in hl_lines):
logger.warning('line number spec is out of range(1-%d): %r' %
(lines, self.options['emphasize-lines']),
location=location)
extra_args['hl_lines'] = [x + 1 for x in hl_lines if x < lines]
extra_args['linenostart'] = reader.lineno_start
if "caption" in self.options:
caption = self.options["caption"] or self.arguments[0]
retnode = container_wrapper(self, retnode, caption)
if 'caption' in self.options:
caption = self.options['caption'] or self.arguments[0]
retnode = container_wrapper(self, retnode, caption)
# retnode will be note_implicit_target that is linked from caption and numref.
# when options['name'] is provided, it should be primary ID.
self.add_name(retnode)
# retnode will be note_implicit_target that is linked from caption and numref.
# when options['name'] is provided, it should be primary ID.
self.add_name(retnode)
return [retnode]
except Exception as exc:
return [document.reporter.warning(str(exc), line=self.lineno)]
return [retnode]
except Exception as exc:
return [document.reporter.warning(str(exc), line=self.lineno)]
def visit_onlineinclude(translator, node):
translator.visit_literal_block(node)
translator.visit_literal_block(node)
def depart_onlineinclude(translator, node):
translator.depart_literal_block(node)
translator.depart_literal_block(node)
def setup(app):
app.add_directive("onlineinclude", OnlineIncludeDirective)
app.add_directive("onlineinclude", OnlineIncludeDirective)
handler = (visit_onlineinclude, depart_onlineinclude)
app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler)
handler = (visit_onlineinclude, depart_onlineinclude)
app.add_node(OnlineIncludeDirective, html=handler, latex=handler, text=handler)
+5 -2
View File
@@ -10,17 +10,20 @@ basedir = os.path.dirname(os.path.realpath(__file__))
old = os.path.join(basedir, "octoprint")
if os.path.exists(old):
# rename left-overs from old file structure
print("""
print(
"""
Found left-overs from old file structure, renaming to
"octoprint.backup". Please remove this manually (I don't
dare to do so myself since you might have changes in there
I don't know anything about).
""")
"""
)
os.rename(old, os.path.join(basedir, "octoprint.backup"))
sys.path.insert(0, os.path.join(basedir, "src"))
import octoprint
if len(sys.argv) == 1:
sys.argv.append("serve")
octoprint.main()
+17
View File
@@ -14,11 +14,28 @@ parentdir_prefix =
lookupfile = .versioneer-lookup
[flake8]
max-line-length = 90
ignore =
D
E
W
F401
F523
extend-ignore = E203
exclude =
src/octoprint/vendor
[isort]
multi_line_output = 3
include_trailing_comma = True
force_grid_wrap = 0
use_parentheses = True
ensure_newline_before_comments = True
line_length = 90
skip =
src/octoprint/vendor
known_first_party =
octoprint
octoprint_setuptools
octoprint_client
+231 -222
View File
@@ -6,121 +6,113 @@ import os
import versioneer
import sys
sys.path.insert(0, os.path.join(os.path.dirname(os.path.realpath(__file__)), "src"))
import octoprint_setuptools
import setuptools
#-----------------------------------------------------------------------------------------------------------------------
# ----------------------------------------------------------------------------------------
# Supported python versions
# we test against 2.7, 3.6 and 3.7, so that's what we'll mark as supported
PYTHON_REQUIRES = ">=2.7.9, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, <4"
# Requirements for setup.py
SETUP_REQUIRES = [
"markdown>=3.1,<3.2" # newer versions require Python 3
]
SETUP_REQUIRES = ["markdown>=3.1,<3.2"] # newer versions require Python 3
# Requirements for our application
INSTALL_REQUIRES = [
# additional OctoPrint plugins that are maintained on a different release cycle
"OctoPrint-FirmwareCheck>=2020.06.22",
"OctoPrint-FileCheck>=2020.07.06",
# the following dependencies are non trivial to update since later versions introduce backwards incompatible
# changes that might affect plugins, or due to other observed problems
"markupsafe>=1.1,<2.0", # Jinja dependency, newer versions require Python 3
"tornado==5.1.1", # newer versions require Python 3
"markdown>=3.1,<3.2", # newer versions require Python 3
"rsa==4.0", # newer versions require Python 3
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
# anything below this should be checked on releases for new versions
"flask>=1.1.2,<2",
"Jinja2>=2.11.2,<3",
"Flask-Login>=0.5,<0.6", # flask-login doesn't use semver & breaks stuff on minor version increases
"Flask-Babel>=1.0,<2",
"Flask-Assets>=2.0,<3",
"werkzeug>=1.0.1,<2",
"itsdangerous>=1.1.0,<2",
"cachelib>=0.1,<1",
"PyYAML>=5.3.1,<6",
"pyserial>=3.4,<4",
"netaddr>=0.7.19,<1",
"watchdog>=0.10.2,<1",
"sarge==0.1.5post0",
"netifaces>=0.10.9,<1",
"pylru>=1.2,<2",
"pkginfo>=1.5.0.1,<2",
"requests>=2.23.0,<3",
"semantic_version>=2.8.5,<3",
"psutil>=5.7,<6",
"Click>=7.1.2,<8",
"feedparser>=5.2.1,<6",
"future>=0.18.2,<1",
"websocket-client>=0.57,<1",
"wrapt>=1.12.1,<2",
"emoji>=0.5.4,<1",
"frozendict>=1.2,<2",
"sentry-sdk>=0.15.1,<1",
"filetype>=1.0.7,<2",
# vendor bundle dependencies
"unidecode>=0.04.14,<0.05", # dependency of awesome-slugify
"blinker>=1.4,<2" # dependency of flask_principal
# additional OctoPrint plugins that are maintained on a different release cycle
"OctoPrint-FirmwareCheck>=2020.06.22",
"OctoPrint-FileCheck>=2020.07.06",
# the following dependencies are non trivial to update since later versions
# introduce backwards incompatible changes that might affect plugins, or due to
# other observed problems
"markupsafe>=1.1,<2.0", # Jinja dependency, newer versions require Python 3
"tornado==5.1.1", # newer versions require Python 3
"markdown>=3.1,<3.2", # newer versions require Python 3
"rsa==4.0", # newer versions require Python 3
"regex!=2018.11.6", # avoid broken 2018.11.6. See #2874
# anything below this should be checked on releases for new versions
"flask>=1.1.2,<2",
"Jinja2>=2.11.2,<3",
"Flask-Login>=0.5,<0.6", # flask-login doesn't use semver & breaks stuff on minor version increases
"Flask-Babel>=1.0,<2",
"Flask-Assets>=2.0,<3",
"werkzeug>=1.0.1,<2",
"itsdangerous>=1.1.0,<2",
"cachelib>=0.1,<1",
"PyYAML>=5.3.1,<6",
"pyserial>=3.4,<4",
"netaddr>=0.7.19,<1",
"watchdog>=0.10.2,<1",
"sarge==0.1.5post0",
"netifaces>=0.10.9,<1",
"pylru>=1.2,<2",
"pkginfo>=1.5.0.1,<2",
"requests>=2.23.0,<3",
"semantic_version>=2.8.5,<3",
"psutil>=5.7,<6",
"Click>=7.1.2,<8",
"feedparser>=5.2.1,<6",
"future>=0.18.2,<1",
"websocket-client>=0.57,<1",
"wrapt>=1.12.1,<2",
"emoji>=0.5.4,<1",
"frozendict>=1.2,<2",
"sentry-sdk>=0.15.1,<1",
"filetype>=1.0.7,<2",
# vendor bundled dependencies
"unidecode>=0.04.14,<0.05", # dependency of awesome-slugify
"blinker>=1.4,<2", # dependency of flask_principal
]
# Python 2 specific requirements
INSTALL_REQUIRES_PYTHON2 = [
"futures>=3.3,<4",
"monotonic>=1.5,<2",
"scandir>=1.10,<2",
"chainmap>=1.0.3,<2",
"typing>=3.7.4.1,<4"
"futures>=3.3,<4",
"monotonic>=1.5,<2",
"scandir>=1.10,<2",
"chainmap>=1.0.3,<2",
"typing>=3.7.4.1,<4",
]
# Python 3 specific requirements
INSTALL_REQUIRES_PYTHON3 = [
"zeroconf>=0.24,<0.25"
]
INSTALL_REQUIRES_PYTHON3 = ["zeroconf>=0.24,<0.25"]
# OSX specific requirements
INSTALL_REQUIRES_OSX = [
"appdirs>=1.4.4",
"appdirs>=1.4.4",
]
# Additional requirements for optional install options
EXTRA_REQUIRES = dict(
# Dependencies for developing OctoPrint
develop=[
# Testing dependencies - SEE ALSO tox.ini
"mock>=3.0.5,<4",
"pytest==4.6.10",
"pytest-doctest-custom>=1.0.0,<2",
"ddt",
# linter
"flake8",
# profiler
"pyinstrument",
],
# Dependencies for developing OctoPrint plugins
plugins=[
"cookiecutter>=1.7.2,<1.8"
],
# Dependencies for building the documentation - Python 3 required!
docs=[
"sphinx>=3,<4",
"sphinxcontrib-httpdomain",
"sphinxcontrib-mermaid",
"sphinx_rtd_theme",
"readthedocs-sphinx-ext"
],
# Dependencies for developing OctoPrint
develop=[
# Testing dependencies
"mock>=3.0.5,<4",
"pytest==4.6.10",
"pytest-doctest-custom>=1.0.0,<2",
"ddt",
# linter
"flake8",
# formatters
"black",
"isort",
# pre-commit
"pre-commit",
# profiler
"pyinstrument",
],
# Dependencies for developing OctoPrint plugins
plugins=["cookiecutter>=1.7.2,<1.8"],
# Dependencies for building the documentation - Python 3 required!
docs=[
"sphinx>=3,<4",
"sphinxcontrib-httpdomain",
"sphinxcontrib-mermaid",
"sphinx_rtd_theme",
"readthedocs-sphinx-ext",
],
)
# Dependency links for any of the aforementioned dependencies
@@ -128,175 +120,192 @@ DEPENDENCY_LINKS = []
# adapted from https://hynek.me/articles/conditional-python-dependencies/
if int(setuptools.__version__.split(".", 1)[0]) < 18:
# no bdist_wheel support for setuptools < 18 since we build universal wheels and our optional dependencies
# would get lost there
assert "bdist_wheel" not in sys.argv
# no bdist_wheel support for setuptools < 18 since we build universal wheels and our optional dependencies
# would get lost there
assert "bdist_wheel" not in sys.argv
# add optional dependencies for setuptools versions < 18 that don't yet support environment markers
if sys.version_info[0] < 3:
INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON2
else:
INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON3
# add optional dependencies for setuptools versions < 18 that don't yet support environment markers
if sys.version_info[0] < 3:
INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON2
else:
INSTALL_REQUIRES += INSTALL_REQUIRES_PYTHON3
if sys.platform == "darwin":
INSTALL_REQUIRES += INSTALL_REQUIRES_OSX
if sys.platform == "darwin":
INSTALL_REQUIRES += INSTALL_REQUIRES_OSX
else:
# environment markers supported
EXTRA_REQUIRES[":python_version < '3'"] = INSTALL_REQUIRES_PYTHON2
EXTRA_REQUIRES[":python_version >= '3'"] = INSTALL_REQUIRES_PYTHON3
EXTRA_REQUIRES[":sys_platform == 'darwin'"] = INSTALL_REQUIRES_OSX
# environment markers supported
EXTRA_REQUIRES[":python_version < '3'"] = INSTALL_REQUIRES_PYTHON2
EXTRA_REQUIRES[":python_version >= '3'"] = INSTALL_REQUIRES_PYTHON3
EXTRA_REQUIRES[":sys_platform == 'darwin'"] = INSTALL_REQUIRES_OSX
#-----------------------------------------------------------------------------------------------------------------------
# -----------------------------------------------------------------------------------------------------------------------
# Anything below here is just command setup and general setup configuration
here = os.path.abspath(os.path.dirname(__file__))
def read_file_contents(path):
import codecs
with codecs.open(path, encoding="utf-8") as f:
return f.read()
import codecs
with codecs.open(path, encoding="utf-8") as f:
return f.read()
def md_to_html_build_py_factory(files, baseclass):
class md_to_html_build_py(baseclass):
files = dict()
class md_to_html_build_py(baseclass):
files = dict()
def run(self):
print("RUNNING md_to_html_build_py")
if not self.dry_run:
for directory, files in self.files.items():
target_dir = os.path.join(self.build_lib, directory)
self.mkpath(target_dir)
def run(self):
print("RUNNING md_to_html_build_py")
if not self.dry_run:
for directory, files in self.files.items():
target_dir = os.path.join(self.build_lib, directory)
self.mkpath(target_dir)
for entry in files:
if isinstance(entry, tuple):
if len(entry) != 2:
continue
source, dest = entry[0], os.path.join(target_dir, entry[1])
else:
source = entry
dest = os.path.join(target_dir, source + ".html")
for entry in files:
if isinstance(entry, tuple):
if len(entry) != 2:
continue
source, dest = entry[0], os.path.join(target_dir, entry[1])
else:
source = entry
dest = os.path.join(target_dir, source + ".html")
print("Rendering markdown from {} to {}".format(source, dest))
print("Rendering markdown from {} to {}".format(source, dest))
from markdown import markdownFromFile
markdownFromFile(input=source,
output=dest,
encoding="utf-8")
baseclass.run(self)
from markdown import markdownFromFile
markdownFromFile(input=source, output=dest, encoding="utf-8")
baseclass.run(self)
return type(md_to_html_build_py)(
md_to_html_build_py.__name__, (md_to_html_build_py,), dict(files=files)
)
return type(md_to_html_build_py)(md_to_html_build_py.__name__,
(md_to_html_build_py,),
dict(files=files))
def get_cmdclass():
# make sure these are always available, even when run by dependabot
global versioneer, octoprint_setuptools, md_to_html_build_py_factory
# make sure these are always available, even when run by dependabot
global versioneer, octoprint_setuptools, md_to_html_build_py_factory
cmdclass = versioneer.get_cmdclass()
cmdclass = versioneer.get_cmdclass()
# add clean command
cmdclass.update(dict(clean=octoprint_setuptools.CleanCommand.for_options(source_folder="src", eggs=["OctoPrint*.egg-info"])))
# add clean command
cmdclass.update(
dict(
clean=octoprint_setuptools.CleanCommand.for_options(
source_folder="src", eggs=["OctoPrint*.egg-info"]
)
)
)
# add translation commands
translation_dir = "translations"
pot_file = os.path.join(translation_dir, "messages.pot")
bundled_dir = os.path.join("src", "octoprint", "translations")
cmdclass.update(octoprint_setuptools.get_babel_commandclasses(pot_file=pot_file, output_dir=translation_dir, pack_name_prefix="OctoPrint-i18n-", pack_path_prefix="", bundled_dir=bundled_dir))
# add translation commands
translation_dir = "translations"
pot_file = os.path.join(translation_dir, "messages.pot")
bundled_dir = os.path.join("src", "octoprint", "translations")
cmdclass.update(
octoprint_setuptools.get_babel_commandclasses(
pot_file=pot_file,
output_dir=translation_dir,
pack_name_prefix="OctoPrint-i18n-",
pack_path_prefix="",
bundled_dir=bundled_dir,
)
)
cmdclass["build_py"] = md_to_html_build_py_factory({
"octoprint/templates/_data": [
"AUTHORS.md",
"SUPPORTERS.md",
"THIRDPARTYLICENSES.md",
]
}, cmdclass["build_py"] if "build_py" in cmdclass else _build_py)
cmdclass["build_py"] = md_to_html_build_py_factory(
{
"octoprint/templates/_data": [
"AUTHORS.md",
"SUPPORTERS.md",
"THIRDPARTYLICENSES.md",
]
},
cmdclass["build_py"] if "build_py" in cmdclass else _build_py,
)
return cmdclass
return cmdclass
def params():
# make sure these are always available, even when run by dependabot
global versioneer, get_cmdclass, read_file_contents, here, \
PYTHON_REQUIRES, SETUP_REQUIRES, INSTALL_REQUIRES, EXTRA_REQUIRES, DEPENDENCY_LINKS
# make sure these are always available, even when run by dependabot
global versioneer, get_cmdclass, read_file_contents, here, PYTHON_REQUIRES, SETUP_REQUIRES, INSTALL_REQUIRES, EXTRA_REQUIRES, DEPENDENCY_LINKS
name = "OctoPrint"
version = versioneer.get_version()
cmdclass = get_cmdclass()
name = "OctoPrint"
version = versioneer.get_version()
cmdclass = get_cmdclass()
description = "The snappy web interface for your 3D printer"
long_description = read_file_contents(os.path.join(here, "README.md"))
long_description_content_type = "text/markdown"
description = "The snappy web interface for your 3D printer"
long_description = read_file_contents(os.path.join(here, "README.md"))
long_description_content_type = "text/markdown"
python_requires = PYTHON_REQUIRES
setup_requires = SETUP_REQUIRES
install_requires = INSTALL_REQUIRES
extras_require = EXTRA_REQUIRES
dependency_links = DEPENDENCY_LINKS
python_requires = PYTHON_REQUIRES
setup_requires = SETUP_REQUIRES
install_requires = INSTALL_REQUIRES
extras_require = EXTRA_REQUIRES
dependency_links = DEPENDENCY_LINKS
classifiers = [
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Framework :: Flask",
"Intended Audience :: Developers",
"Intended Audience :: Education",
"Intended Audience :: End Users/Desktop",
"Intended Audience :: Manufacturing",
"Intended Audience :: Other Audience",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: GNU Affero General Public License v3",
"Natural Language :: English",
"Natural Language :: German",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: JavaScript",
"Topic :: Printing",
"Topic :: System :: Monitoring"
]
author = "Gina Häußge"
author_email = "gina@octoprint.org"
url = "https://octoprint.org"
license = "GNU Affero General Public License v3"
keywords = "3dprinting 3dprinter 3d-printing 3d-printer octoprint"
classifiers = [
"Development Status :: 5 - Production/Stable",
"Environment :: Web Environment",
"Framework :: Flask",
"Intended Audience :: Developers",
"Intended Audience :: Education",
"Intended Audience :: End Users/Desktop",
"Intended Audience :: Manufacturing",
"Intended Audience :: Other Audience",
"Intended Audience :: Science/Research",
"License :: OSI Approved :: GNU Affero General Public License v3",
"Natural Language :: English",
"Natural Language :: German",
"Operating System :: OS Independent",
"Programming Language :: Python",
"Programming Language :: Python :: 2",
"Programming Language :: Python :: 2.7",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: Implementation :: CPython",
"Programming Language :: JavaScript",
"Topic :: Printing",
"Topic :: System :: Monitoring",
]
author = "Gina Häußge"
author_email = "gina@octoprint.org"
url = "https://octoprint.org"
license = "GNU Affero General Public License v3"
keywords = "3dprinting 3dprinter 3d-printing 3d-printer octoprint"
project_urls={
"Community Forum": "https://community.octoprint.org",
"Bug Reports": "https://github.com/foosel/OctoPrint/issues",
"Source": "https://github.com/foosel/OctoPrint",
"Funding": "https://donate.octoprint.org"
}
project_urls = {
"Community Forum": "https://community.octoprint.org",
"Bug Reports": "https://github.com/foosel/OctoPrint/issues",
"Source": "https://github.com/foosel/OctoPrint",
"Funding": "https://donate.octoprint.org",
}
packages = setuptools.find_packages(where="src")
package_dir = {
"": "src",
}
package_data = {
"octoprint": octoprint_setuptools.package_data_dirs('src/octoprint',
['static', 'templates', 'plugins', 'translations'])
+ ['util/piptestballoon/setup.py']
}
packages = setuptools.find_packages(where="src")
package_dir = {
"": "src",
}
package_data = {
"octoprint": octoprint_setuptools.package_data_dirs(
"src/octoprint", ["static", "templates", "plugins", "translations"]
)
+ ["util/piptestballoon/setup.py"]
}
include_package_data = True
zip_safe = False
include_package_data = True
zip_safe = False
if os.environ.get('READTHEDOCS', None) == 'True':
# we can't tell read the docs to please perform a pip install -e .[docs], so we help
# it a bit here by explicitly adding the development dependencies, which include our
# documentation dependencies
install_requires = install_requires + extras_require['docs']
if os.environ.get("READTHEDOCS", None) == "True":
# we can't tell read the docs to please perform a pip install -e .[docs], so we help
# it a bit here by explicitly adding the development dependencies, which include our
# documentation dependencies
install_requires = install_requires + extras_require["docs"]
entry_points = {
"console_scripts": [
"octoprint = octoprint:main"
]
}
entry_points = {"console_scripts": ["octoprint = octoprint:main"]}
return locals()
return locals()
setuptools.setup(**params())
+628 -508
View File
File diff suppressed because it is too large. Load diff
+3 -2
View File
@@ -3,5 +3,6 @@
from __future__ import absolute_import, division, print_function, unicode_literals
if __name__ == "__main__":
import octoprint
octoprint.main()
import octoprint
octoprint.main()
+112 -80
View File
@@ -64,12 +64,14 @@ HANDLERS = {}
def register_vcs_handler(vcs, method): # decorator
"""Decorator to mark a method as the handler for a particular VCS."""
def decorate(f):
"""Store f in HANDLERS[vcs][method]."""
if vcs not in HANDLERS:
HANDLERS[vcs] = {}
HANDLERS[vcs][method] = f
return f
return decorate
@@ -81,9 +83,12 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
try:
dispcmd = str([c] + args)
# remember shell=False, so use git.cmd on windows, not just git
p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,
stderr=(subprocess.PIPE if hide_stderr
else None))
p = subprocess.Popen(
[c] + args,
cwd=cwd,
stdout=subprocess.PIPE,
stderr=(subprocess.PIPE if hide_stderr else None),
)
break
except EnvironmentError:
e = sys.exc_info()[1]
@@ -116,12 +121,17 @@ def versions_from_parentdir(parentdir_prefix, root, verbose):
dirname = os.path.basename(root)
if not dirname.startswith(parentdir_prefix):
if verbose:
print("guessing rootdir is '%s', but '%s' doesn't start with "
"prefix '%s'" % (root, dirname, parentdir_prefix))
print(
"guessing rootdir is '%s', but '%s' doesn't start with "
"prefix '%s'" % (root, dirname, parentdir_prefix)
)
raise NotThisMethod("rootdir doesn't start with parentdir_prefix")
return {"version": dirname[len(parentdir_prefix):],
"full-revisionid": None,
"dirty": False, "error": None}
return {
"version": dirname[len(parentdir_prefix) :],
"full-revisionid": None,
"dirty": False,
"error": None,
}
@register_vcs_handler("git", "get_keywords")
@@ -163,7 +173,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
# starting in git-1.8.3, tags are listed as "tag: foo-1.0" instead of
# just "foo-1.0". If we see a "tag: " prefix, prefer those.
TAG = "tag: "
tags = {r[len(TAG):] for r in refs if r.startswith(TAG)}
tags = {r[len(TAG) :] for r in refs if r.startswith(TAG)}
if not tags:
# Either we're using git < 1.8.3, or there really are no tags. We use
# a heuristic: assume all version tags have a digit. The old git %d
@@ -172,12 +182,15 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
# between branches and tags. By ignoring refnames without digits, we
# filter out many common branch names like "release" and
# "stabilization", as well as "HEAD" and "master".
tags = {r for r in refs if re.search(r'\d', r)}
tags = {r for r in refs if re.search(r"\d", r)}
if verbose:
print("discarding '%s', no digits" % ",".join(refs-tags))
print("discarding '%s', no digits" % ",".join(refs - tags))
branches = [r for r in refs if not r.startswith(TAG)
and r != "HEAD" and not r.startswith("refs/")]
branches = [
r
for r in refs
if not r.startswith(TAG) and r != "HEAD" and not r.startswith("refs/")
]
if verbose:
print("likely branches: %s" % ",".join(sorted(branches)))
branch = None
@@ -189,22 +202,28 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
for ref in sorted(tags):
# sorting will prefer e.g. "2.0" over "2.0rc1"
if ref.startswith(tag_prefix):
r = ref[len(tag_prefix):]
r = ref[len(tag_prefix) :]
if verbose:
print("picking %s" % r)
result = {"version": r,
"full-revisionid": keywords["full"].strip(),
"dirty": False, "error": None}
result = {
"version": r,
"full-revisionid": keywords["full"].strip(),
"dirty": False,
"error": None,
}
if branch is not None:
result["branch"] = branch
return result
# no suitable tags, so version is "0+unknown", but full hex is still there
if verbose:
print("no suitable tags, using unknown + full revision id")
return {"version": "0+unknown",
"full-revisionid": keywords["full"].strip(),
"dirty": False, "error": "no suitable tags"}
return {
"version": "0+unknown",
"full-revisionid": keywords["full"].strip(),
"dirty": False,
"error": "no suitable tags",
}
@register_vcs_handler("git", "pieces_from_vcs")
@@ -225,10 +244,19 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
GITS = ["git.cmd", "git.exe"]
# if there is a tag matching tag_prefix, this yields TAG-NUM-gHEX[-dirty]
# if there isn't one, this yields HEX[-dirty] (no NUM)
describe_out = run_command(GITS, ["describe", "--tags", "--dirty",
"--always", "--long",
"--match", "%s*" % tag_prefix],
cwd=root)
describe_out = run_command(
GITS,
[
"describe",
"--tags",
"--dirty",
"--always",
"--long",
"--match",
"%s*" % tag_prefix,
],
cwd=root,
)
# --long was added in git-1.5.5
if describe_out is None:
raise NotThisMethod("'git describe' failed")
@@ -251,12 +279,10 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
dirty = git_describe.endswith("-dirty")
pieces["dirty"] = dirty
if dirty:
git_describe = git_describe[:git_describe.rindex("-dirty")]
git_describe = git_describe[: git_describe.rindex("-dirty")]
# figure out our branch
abbrev_ref_out = run_command(GITS,
["rev-parse", "--abbrev-ref", "HEAD"],
cwd=root)
abbrev_ref_out = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root)
if abbrev_ref_out is not None and abbrev_ref_out != "HEAD":
pieces["branch"] = abbrev_ref_out.strip()
@@ -264,11 +290,10 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
if "-" in git_describe:
# TAG-NUM-gHEX
mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
mo = re.search(r"^(.+)-(\d+)-g([0-9a-f]+)$", git_describe)
if not mo:
# unparseable. Maybe git-describe is misbehaving?
pieces["error"] = ("unable to parse git-describe output: '%s'"
% describe_out)
pieces["error"] = "unable to parse git-describe output: '%s'" % describe_out
return pieces
# tag
@@ -277,10 +302,12 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
if verbose:
fmt = "tag '%s' doesn't start with prefix '%s'"
print(fmt % (full_tag, tag_prefix))
pieces["error"] = ("tag '%s' doesn't start with prefix '%s'"
% (full_tag, tag_prefix))
pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % (
full_tag,
tag_prefix,
)
return pieces
pieces["closest-tag"] = full_tag[len(tag_prefix):]
pieces["closest-tag"] = full_tag[len(tag_prefix) :]
# distance: number of commits since tag
pieces["distance"] = int(mo.group(2))
@@ -291,8 +318,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
else:
# HEX: no tags
pieces["closest-tag"] = None
count_out = run_command(GITS, ["rev-list", "HEAD", "--count"],
cwd=root)
count_out = run_command(GITS, ["rev-list", "HEAD", "--count"], cwd=root)
pieces["distance"] = int(count_out) # total number of commits
return pieces
@@ -309,11 +335,12 @@ def git_parse_lookup_file(path):
return []
import re
lookup = []
with io.open(path, "rt", encoding="utf-8") as f:
for line in f:
if '#' in line:
line = line[:line.index("#")]
if "#" in line:
line = line[: line.index("#")]
line = line.strip()
if not line:
continue
@@ -353,8 +380,7 @@ def git_pieces_from_lookup(lookup, root, verbose, run_command=run_command):
if sys.platform == "win32":
GITS = ["git.cmd", "git.exe"]
stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"],
cwd=root)
stdout = run_command(GITS, ["rev-parse", "--abbrev-ref", "HEAD"], cwd=root)
if stdout is None:
raise NotThisMethod("git rev-parse --abbrev-ref HEAD failed")
@@ -365,37 +391,33 @@ def git_pieces_from_lookup(lookup, root, verbose, run_command=run_command):
for matcher, render, tag, ref_commit in lookup:
if matcher.match(current_branch):
if tag is None or ref_commit is None:
raise NotThisMethod("tag or ref_commit is unset for "
"this branch")
raise NotThisMethod("tag or ref_commit is unset for " "this branch")
stdout = run_command(GITS,
["rev-list", "%s..HEAD" % ref_commit,
"--count"],
cwd=root)
stdout = run_command(
GITS, ["rev-list", "%s..HEAD" % ref_commit, "--count"], cwd=root
)
if stdout is None:
raise NotThisMethod("git rev-list %s..HEAD "
"--count failed" % ref_commit)
raise NotThisMethod(
"git rev-list %s..HEAD " "--count failed" % ref_commit
)
try:
num_commits = int(stdout.strip())
except ValueError:
raise NotThisMethod("git rev-list %s..HEAD --count didn't "
"return a valid number" % ref_commit)
raise NotThisMethod(
"git rev-list %s..HEAD --count didn't "
"return a valid number" % ref_commit
)
stdout = run_command(GITS,
["rev-parse", "--short", "HEAD"],
cwd=root)
stdout = run_command(GITS, ["rev-parse", "--short", "HEAD"], cwd=root)
if stdout is None:
raise NotThisMethod("git describe rev-parse "
"--short HEAD failed")
raise NotThisMethod("git describe rev-parse " "--short HEAD failed")
short_hash = stdout.strip()
stdout = run_command(GITS,
["describe", "--tags",
"--dirty", "--always"],
cwd=root)
stdout = run_command(
GITS, ["describe", "--tags", "--dirty", "--always"], cwd=root
)
if stdout is None:
raise NotThisMethod("git describe --tags --dirty "
"--always failed")
raise NotThisMethod("git describe --tags --dirty " "--always failed")
dirty = stdout.strip().endswith("-dirty")
stdout = run_command(GITS, ["rev-parse", "HEAD"], cwd=root)
@@ -411,7 +433,7 @@ def git_pieces_from_lookup(lookup, root, verbose, run_command=run_command):
"closest-tag": tag,
"distance": num_commits,
"error": None,
"render": render
"render": render,
}
raise NotThisMethod("no matching lookup definition found")
@@ -442,8 +464,7 @@ def render_pep440(pieces):
rendered += ".dirty"
else:
# exception #1
rendered = "0+untagged.%d.g%s" % (pieces["distance"],
pieces["short"])
rendered = "0+untagged.%d.g%s" % (pieces["distance"], pieces["short"])
if pieces["dirty"]:
rendered += ".dirty"
return rendered
@@ -603,10 +624,12 @@ def render_git_describe_long(pieces):
def render(pieces, style):
"""Render the given version pieces into the requested style."""
if pieces["error"]:
return {"version": "unknown",
"full-revisionid": pieces.get("long"),
"dirty": None,
"error": pieces["error"]}
return {
"version": "unknown",
"full-revisionid": pieces.get("long"),
"dirty": None,
"error": pieces["error"],
}
if "render" in pieces and pieces["render"] is not None:
style = pieces["render"]
@@ -633,8 +656,12 @@ def render(pieces, style):
else:
raise ValueError("unknown style '%s'" % style)
result = {"version": rendered, "full-revisionid": pieces["long"],
"dirty": pieces["dirty"], "error": None}
result = {
"version": rendered,
"full-revisionid": pieces["long"],
"dirty": pieces["dirty"],
"error": None,
}
if "branch" in pieces and pieces["branch"] is not None:
result["branch"] = pieces["branch"]
return result
@@ -651,8 +678,7 @@ def get_versions():
verbose = cfg.verbose
try:
return git_versions_from_keywords(get_keywords(), cfg.tag_prefix,
verbose)
return git_versions_from_keywords(get_keywords(), cfg.tag_prefix, verbose)
except NotThisMethod:
pass
@@ -661,14 +687,17 @@ def get_versions():
# versionfile_source is the relative path from the top of the source
# tree (where the .git directory might live) to this file. Invert
# this to find the root from __file__.
for i in cfg.versionfile_source.split('/'):
for i in cfg.versionfile_source.split("/"):
root = os.path.dirname(root)
except NameError:
return {"version": "0+unknown", "full-revisionid": None,
"dirty": None,
"error": "unable to find root of source tree"}
return {
"version": "0+unknown",
"full-revisionid": None,
"dirty": None,
"error": "unable to find root of source tree",
}
lookupfile = cfg.lookupfile if cfg.lookupfile is not None else ".versioneer-lookup"
lookupfile = cfg.lookupfile if cfg.lookupfile is not None else ".versioneer-lookup"
lookuppath = os.path.join(root, lookupfile)
if os.path.exists(lookuppath):
try:
@@ -690,6 +719,9 @@ def get_versions():
except NotThisMethod:
pass
return {"version": "0+unknown", "full-revisionid": None,
"dirty": None,
"error": "unable to compute version"}
return {
"version": "0+unknown",
"full-revisionid": None,
"dirty": None,
"error": "unable to compute version",
}
File diff suppressed because it is too large. Load diff
+358 -285
View File
@@ -2,7 +2,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Marc Hannappel <salandora@gmail.com>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
from future.utils import with_metaclass
@@ -20,371 +20,444 @@ from octoprint.access import ADMIN_GROUP, USER_GROUP, READONLY_GROUP
class OctoPrintPermission(Permission):
@classmethod
def convert_needs_to_dict(cls, needs):
ret_needs = defaultdict(list)
for need in needs:
if need.value not in ret_needs[need.method]:
ret_needs[need.method].append(need.value)
return ret_needs
@classmethod
def convert_needs_to_dict(cls, needs):
ret_needs = defaultdict(list)
for need in needs:
if need.value not in ret_needs[need.method]:
ret_needs[need.method].append(need.value)
return ret_needs
@classmethod
def convert_to_needs(cls, needs):
result = []
for need in needs:
# noinspection PyCompatibility
if isinstance(need, Need):
result.append(need)
elif isinstance(need, Permission):
result += need.needs
elif isinstance(need, basestring):
result.append(RoleNeed(need))
return result
@classmethod
def convert_to_needs(cls, needs):
result = []
for need in needs:
# noinspection PyCompatibility
if isinstance(need, Need):
result.append(need)
elif isinstance(need, Permission):
result += need.needs
elif isinstance(need, basestring):
result.append(RoleNeed(need))
return result
def __init__(self, name, description, *needs, **kwargs):
self._name = name
self._description = description
self._dangerous = kwargs.pop("dangerous", False)
self._default_groups = kwargs.pop("default_groups", [])
def __init__(self, name, description, *needs, **kwargs):
self._name = name
self._description = description
self._dangerous = kwargs.pop("dangerous", False)
self._default_groups = kwargs.pop("default_groups", [])
self._key = None
self._key = None
Permission.__init__(self, *self.convert_to_needs(needs))
Permission.__init__(self, *self.convert_to_needs(needs))
def as_dict(self):
return {"key": self.key,
"name": self.get_name(),
"dangerous": self._dangerous,
"default_groups": self._default_groups,
"description": self.get_description(),
"needs": self.convert_needs_to_dict(self.needs)}
def as_dict(self):
return {
"key": self.key,
"name": self.get_name(),
"dangerous": self._dangerous,
"default_groups": self._default_groups,
"description": self.get_description(),
"needs": self.convert_needs_to_dict(self.needs),
}
@property
def key(self):
return self._key
@property
def key(self):
return self._key
@key.setter
def key(self, value):
self._key = value
@key.setter
def key(self, value):
self._key = value
@property
def default_groups(self):
return self._default_groups
@property
def default_groups(self):
return self._default_groups
def get_name(self):
return self._name
def get_name(self):
return self._name
def get_description(self):
return self._description
def get_description(self):
return self._description
def allows(self, identity):
"""Whether the identity can access this permission.
Overridden from Permission.allows to make sure the Identity provides ALL
required needs instead of ANY required need.
def allows(self, identity):
"""Whether the identity can access this permission.
Overridden from Permission.allows to make sure the Identity provides ALL
required needs instead of ANY required need.
:param identity: The identity
"""
if self.needs and len(self.needs.intersection(identity.provides)) != len(self.needs):
return False
:param identity: The identity
"""
if self.needs and len(self.needs.intersection(identity.provides)) != len(
self.needs
):
return False
if self.excludes and self.excludes.intersection(identity.provides):
return False
if self.excludes and self.excludes.intersection(identity.provides):
return False
return True
return True
def union(self, other):
"""Create a new OctoPrintPermission with the requirements of the union of this
and other.
def union(self, other):
"""Create a new OctoPrintPermission with the requirements of the union of this
and other.
:param other: The other permission
"""
p = self.__class__(self._name, self._description, *self.needs.union(other.needs))
p.excludes.update(self.excludes.union(other.excludes))
return p
:param other: The other permission
"""
p = self.__class__(self._name, self._description, *self.needs.union(other.needs))
p.excludes.update(self.excludes.union(other.excludes))
return p
def difference(self, other):
"""Create a new OctoPrintPermission consisting of requirements in this
permission and not in the other.
"""
def difference(self, other):
"""Create a new OctoPrintPermission consisting of requirements in this
permission and not in the other.
"""
p = self.__class__(
self._name, self._description, *self.needs.difference(other.needs)
)
p.excludes.update(self.excludes.difference(other.excludes))
return p
p = self.__class__(self._name, self._description, *self.needs.difference(other.needs))
p.excludes.update(self.excludes.difference(other.excludes))
return p
def __repr__(self):
return "{}({!r}, {!r}, {})".format(
self.__class__.__name__,
self.get_name(),
self.get_description(),
", ".join(map(repr, self.needs)),
)
def __repr__(self):
return '{}({!r}, {!r}, {})'.format(self.__class__.__name__,
self.get_name(),
self.get_description(),
', '.join(map(repr, self.needs)))
def __hash__(self):
return self.get_name().__hash__()
def __hash__(self):
return self.get_name().__hash__()
def __eq__(self, other):
return isinstance(other, OctoPrintPermission) and other.get_name() == self.get_name()
def __eq__(self, other):
return (
isinstance(other, OctoPrintPermission) and other.get_name() == self.get_name()
)
class PluginOctoPrintPermission(OctoPrintPermission):
def __init__(self, *args, **kwargs):
self.plugin = kwargs.pop("plugin", None)
OctoPrintPermission.__init__(self, *args, **kwargs)
def __init__(self, *args, **kwargs):
self.plugin = kwargs.pop("plugin", None)
OctoPrintPermission.__init__(self, *args, **kwargs)
def as_dict(self):
result = OctoPrintPermission.as_dict(self)
result["plugin"] = self.plugin
return result
def as_dict(self):
result = OctoPrintPermission.as_dict(self)
result["plugin"] = self.plugin
return result
class PluginIdentityContext(object):
"""Identity context for not initialized Permissions
"""Identity context for not initialized Permissions
Needed to support @Permissions.PLUGIN_X_Y.require()
Needed to support @Permissions.PLUGIN_X_Y.require()
Will search the permission when needed
"""
def __init__(self, key, http_exception=None):
self.key = key
self.http_exception = http_exception
"""The permission of this principal
Will search the permission when needed
"""
def __init__(self, key, http_exception=None):
self.key = key
self.http_exception = http_exception
"""The permission of this principal
"""
@property
def identity(self):
"""The identity of this principal
"""
return g.identity
@property
def identity(self):
"""The identity of this principal"""
return g.identity
def can(self):
"""Whether the identity has access to the permission
"""
permission = getattr(Permissions, self.key)
if permission is None or isinstance(permission, PluginPermissionDecorator):
raise UnknownPermission(self.key)
def can(self):
"""Whether the identity has access to the permission"""
permission = getattr(Permissions, self.key)
if permission is None or isinstance(permission, PluginPermissionDecorator):
raise UnknownPermission(self.key)
return permission.can()
return permission.can()
def __call__(self, f):
@wraps(f)
def _decorated(*args, **kw):
with self:
rv = f(*args, **kw)
return rv
def __call__(self, f):
@wraps(f)
def _decorated(*args, **kw):
with self:
rv = f(*args, **kw)
return rv
return _decorated
return _decorated
def __enter__(self):
permission = getattr(Permissions, self.key)
if permission is None or isinstance(permission, PluginPermissionDecorator):
raise UnknownPermission(self.key)
def __enter__(self):
permission = getattr(Permissions, self.key)
if permission is None or isinstance(permission, PluginPermissionDecorator):
raise UnknownPermission(self.key)
# check the permission here
if not permission.can():
if self.http_exception:
abort(self.http_exception, permission)
raise PermissionDenied(permission)
# check the permission here
if not permission.can():
if self.http_exception:
abort(self.http_exception, permission)
raise PermissionDenied(permission)
def __exit__(self, *args):
return False
def __exit__(self, *args):
return False
class PluginPermissionDecorator(Permission):
"""Decorator Class for not initialized Permissions
"""Decorator Class for not initialized Permissions
Needed to support @Permissions.PLUGIN_X_Y.require()
"""
def __init__(self, key):
self.key = key
Needed to support @Permissions.PLUGIN_X_Y.require()
"""
def require(self, http_exception=None):
return PluginIdentityContext(self.key, http_exception)
def __init__(self, key):
self.key = key
def require(self, http_exception=None):
return PluginIdentityContext(self.key, http_exception)
class PermissionsMetaClass(type):
permissions = OrderedDict()
permissions = OrderedDict()
def __new__(mcs, name, bases, args):
cls = type.__new__(mcs, name, bases, args)
def __new__(mcs, name, bases, args):
cls = type.__new__(mcs, name, bases, args)
for key, value in args.items():
if isinstance(value, OctoPrintPermission):
value.key = key
mcs.permissions[key] = value
delattr(cls, key)
for key, value in args.items():
if isinstance(value, OctoPrintPermission):
value.key = key
mcs.permissions[key] = value
delattr(cls, key)
return cls
return cls
def __setattr__(cls, key, value):
if isinstance(value, OctoPrintPermission):
if key in cls.permissions:
raise PermissionAlreadyExists(key)
value.key = key
cls.permissions[key] = value
def __setattr__(cls, key, value):
if isinstance(value, OctoPrintPermission):
if key in cls.permissions:
raise PermissionAlreadyExists(key)
value.key = key
cls.permissions[key] = value
def __getattr__(cls, key):
permission = cls.permissions.get(key)
def __getattr__(cls, key):
permission = cls.permissions.get(key)
if key.startswith("PLUGIN_") and permission is None:
return PluginPermissionDecorator(key)
if key.startswith("PLUGIN_") and permission is None:
return PluginPermissionDecorator(key)
return permission
return permission
def all(cls):
return list(cls.permissions.values())
def all(cls):
return list(cls.permissions.values())
def filter(cls, cb):
return list(filter(cb, cls.all()))
def filter(cls, cb):
return list(filter(cb, cls.all()))
def find(cls, p, filter=None):
key = None
if isinstance(p, OctoPrintPermission):
key = p.key
elif isinstance(p, dict):
key = p.get("key")
elif isinstance(p, basestring):
key = p
def find(cls, p, filter=None):
key = None
if isinstance(p, OctoPrintPermission):
key = p.key
elif isinstance(p, dict):
key = p.get("key")
elif isinstance(p, basestring):
key = p
if key is None:
return None
if key is None:
return None
return cls.match(lambda p: p.key == key, filter=filter)
return cls.match(lambda p: p.key == key, filter=filter)
def match(cls, match, filter=None):
if callable(filter):
permissions = cls.filter(filter)
else:
permissions = cls.all()
def match(cls, match, filter=None):
if callable(filter):
permissions = cls.filter(filter)
else:
permissions = cls.all()
for permission in permissions:
if match(permission):
return permission
for permission in permissions:
if match(permission):
return permission
return None
return None
class Permissions(with_metaclass(PermissionsMetaClass)):
# Special permission
ADMIN = OctoPrintPermission("Admin",
gettext("Admin is allowed to do everything"),
RoleNeed("admin"),
dangerous=True,
default_groups=[ADMIN_GROUP])
# Special permission
ADMIN = OctoPrintPermission(
"Admin",
gettext("Admin is allowed to do everything"),
RoleNeed("admin"),
dangerous=True,
default_groups=[ADMIN_GROUP],
)
STATUS = OctoPrintPermission("Status",
gettext("Allows to gather basic status information, e.g. job progress, "
"printer state, temperatures, ... Mandatory for the default UI "
"to work"),
RoleNeed("status"),
default_groups=[USER_GROUP, READONLY_GROUP])
STATUS = OctoPrintPermission(
"Status",
gettext(
"Allows to gather basic status information, e.g. job progress, "
"printer state, temperatures, ... Mandatory for the default UI "
"to work"
),
RoleNeed("status"),
default_groups=[USER_GROUP, READONLY_GROUP],
)
CONNECTION = OctoPrintPermission("Connection",
gettext("Allows to connect to and disconnect from a printer"),
RoleNeed("connection"),
default_groups=[USER_GROUP])
CONNECTION = OctoPrintPermission(
"Connection",
gettext("Allows to connect to and disconnect from a printer"),
RoleNeed("connection"),
default_groups=[USER_GROUP],
)
WEBCAM = OctoPrintPermission("Webcam",
gettext("Allows to watch the webcam stream"),
RoleNeed("webcam"),
default_groups=[USER_GROUP, READONLY_GROUP])
WEBCAM = OctoPrintPermission(
"Webcam",
gettext("Allows to watch the webcam stream"),
RoleNeed("webcam"),
default_groups=[USER_GROUP, READONLY_GROUP],
)
SYSTEM = OctoPrintPermission("System",
gettext("Allows to run system commands, e.g. restart OctoPrint, "
"shutdown or reboot the system"),
RoleNeed("system"),
dangerous=True)
SYSTEM = OctoPrintPermission(
"System",
gettext(
"Allows to run system commands, e.g. restart OctoPrint, "
"shutdown or reboot the system"
),
RoleNeed("system"),
dangerous=True,
)
FILES_LIST = OctoPrintPermission("File List",
gettext("Allows to retrieve a list of all uploaded files and folders, including"
"their metadata (e.g. date, file size, analysis results, ...)"),
RoleNeed("files_list"),
default_groups=[USER_GROUP, READONLY_GROUP])
FILES_UPLOAD = OctoPrintPermission("File Upload",
gettext("Allows users to upload new files, create new folders and copy existing ones. If "
"the File Delete permission is also set, File Upload also allows "
"moving files and folders."),
RoleNeed("files_upload"),
default_groups=[USER_GROUP])
FILES_DOWNLOAD = OctoPrintPermission("File Download",
gettext("Allows users to download files. The GCODE viewer is "
"affected by this as well."),
RoleNeed("files_download"),
default_groups=[USER_GROUP, READONLY_GROUP])
FILES_DELETE = OctoPrintPermission("File Delete",
gettext("Allows users to delete files and folders. If the File Upload permission is "
"also set, File Delete also allows moving files and folders."),
RoleNeed("files_delete"),
default_groups=[USER_GROUP])
FILES_SELECT = OctoPrintPermission("File Select",
gettext("Allows to select a file for printing"),
RoleNeed("files_select"),
default_groups=[USER_GROUP])
FILES_LIST = OctoPrintPermission(
"File List",
gettext(
"Allows to retrieve a list of all uploaded files and folders, including"
"their metadata (e.g. date, file size, analysis results, ...)"
),
RoleNeed("files_list"),
default_groups=[USER_GROUP, READONLY_GROUP],
)
FILES_UPLOAD = OctoPrintPermission(
"File Upload",
gettext(
"Allows users to upload new files, create new folders and copy existing ones. If "
"the File Delete permission is also set, File Upload also allows "
"moving files and folders."
),
RoleNeed("files_upload"),
default_groups=[USER_GROUP],
)
FILES_DOWNLOAD = OctoPrintPermission(
"File Download",
gettext(
"Allows users to download files. The GCODE viewer is "
"affected by this as well."
),
RoleNeed("files_download"),
default_groups=[USER_GROUP, READONLY_GROUP],
)
FILES_DELETE = OctoPrintPermission(
"File Delete",
gettext(
"Allows users to delete files and folders. If the File Upload permission is "
"also set, File Delete also allows moving files and folders."
),
RoleNeed("files_delete"),
default_groups=[USER_GROUP],
)
FILES_SELECT = OctoPrintPermission(
"File Select",
gettext("Allows to select a file for printing"),
RoleNeed("files_select"),
default_groups=[USER_GROUP],
)
PRINT = OctoPrintPermission("Print",
gettext("Allows to start, pause and cancel a print job"),
RoleNeed("print"),
default_groups=[USER_GROUP])
PRINT = OctoPrintPermission(
"Print",
gettext("Allows to start, pause and cancel a print job"),
RoleNeed("print"),
default_groups=[USER_GROUP],
)
GCODE_VIEWER = OctoPrintPermission("GCODE viewer",
gettext("Allows access to the GCODE viewer if the \"File Download\""
"permission is also set."),
RoleNeed("gcodeviewer"),
default_groups=[USER_GROUP, READONLY_GROUP])
GCODE_VIEWER = OctoPrintPermission(
"GCODE viewer",
gettext(
'Allows access to the GCODE viewer if the "File Download"'
"permission is also set."
),
RoleNeed("gcodeviewer"),
default_groups=[USER_GROUP, READONLY_GROUP],
)
MONITOR_TERMINAL = OctoPrintPermission("Terminal",
gettext("Allows to watch the terminal tab but not to send commands "
"to the printer from it"),
RoleNeed("monitor_terminal"),
default_groups=[USER_GROUP, READONLY_GROUP])
MONITOR_TERMINAL = OctoPrintPermission(
"Terminal",
gettext(
"Allows to watch the terminal tab but not to send commands "
"to the printer from it"
),
RoleNeed("monitor_terminal"),
default_groups=[USER_GROUP, READONLY_GROUP],
)
CONTROL = OctoPrintPermission("Control",
gettext("Allows to control of the printer by using the temperature controls,"
"the control tab or sending commands through the terminal."),
RoleNeed("control"),
default_groups=[USER_GROUP])
CONTROL = OctoPrintPermission(
"Control",
gettext(
"Allows to control of the printer by using the temperature controls,"
"the control tab or sending commands through the terminal."
),
RoleNeed("control"),
default_groups=[USER_GROUP],
)
SLICE = OctoPrintPermission("Slice",
gettext("Allows to slice files"),
RoleNeed("slice"),
default_groups=[USER_GROUP])
SLICE = OctoPrintPermission(
"Slice",
gettext("Allows to slice files"),
RoleNeed("slice"),
default_groups=[USER_GROUP],
)
TIMELAPSE_LIST = OctoPrintPermission("Timelapse List",
gettext("Allows to list timelapse videos"),
RoleNeed("timelapse_list"),
default_groups=[USER_GROUP, READONLY_GROUP])
TIMELAPSE_DOWNLOAD = OctoPrintPermission("Timelapse Download",
gettext("Allows to download timelapse videos"),
RoleNeed("timelapse_download"),
default_groups=[USER_GROUP, READONLY_GROUP])
TIMELAPSE_DELETE = OctoPrintPermission("Timelapse Delete",
gettext("Allows to delete timelapse videos and unrendered timelapses"),
RoleNeed("timelapse_delete"),
default_groups=[USER_GROUP])
TIMELAPSE_ADMIN = OctoPrintPermission("Timelapse Admin",
gettext("Allows to change the timelapse settings and delete or "
"render unrendered timelapses. Includes the \"Timelapse List\","
"\"Timelapse Delete\" and \"Timelapse Download\" permissions"),
RoleNeed("timelapse_admin"), TIMELAPSE_LIST, TIMELAPSE_DOWNLOAD,
default_groups=[USER_GROUP])
SETTINGS_READ = OctoPrintPermission("Settings Access",
gettext("Allows to read non sensitive settings. Mandatory for the "
"default UI to work."),
RoleNeed("settings_read"),
default_groups=[USER_GROUP, READONLY_GROUP])
SETTINGS = OctoPrintPermission("Settings Admin",
gettext("Allows to manage settings and also to read sensitive settings"),
RoleNeed("settings"),
dangerous=True)
TIMELAPSE_LIST = OctoPrintPermission(
"Timelapse List",
gettext("Allows to list timelapse videos"),
RoleNeed("timelapse_list"),
default_groups=[USER_GROUP, READONLY_GROUP],
)
TIMELAPSE_DOWNLOAD = OctoPrintPermission(
"Timelapse Download",
gettext("Allows to download timelapse videos"),
RoleNeed("timelapse_download"),
default_groups=[USER_GROUP, READONLY_GROUP],
)
TIMELAPSE_DELETE = OctoPrintPermission(
"Timelapse Delete",
gettext("Allows to delete timelapse videos and unrendered timelapses"),
RoleNeed("timelapse_delete"),
default_groups=[USER_GROUP],
)
TIMELAPSE_ADMIN = OctoPrintPermission(
"Timelapse Admin",
gettext(
"Allows to change the timelapse settings and delete or "
'render unrendered timelapses. Includes the "Timelapse List",'
'"Timelapse Delete" and "Timelapse Download" permissions'
),
RoleNeed("timelapse_admin"),
TIMELAPSE_LIST,
TIMELAPSE_DOWNLOAD,
default_groups=[USER_GROUP],
)
SETTINGS_READ = OctoPrintPermission(
"Settings Access",
gettext(
"Allows to read non sensitive settings. Mandatory for the "
"default UI to work."
),
RoleNeed("settings_read"),
default_groups=[USER_GROUP, READONLY_GROUP],
)
SETTINGS = OctoPrintPermission(
"Settings Admin",
gettext("Allows to manage settings and also to read sensitive settings"),
RoleNeed("settings"),
dangerous=True,
)
class PermissionAlreadyExists(Exception):
def __init__(self, permission):
Exception.__init__(self, "Permission %s already exists" % permission)
def __init__(self, permission):
Exception.__init__(self, "Permission %s already exists" % permission)
class UnknownPermission(Exception):
def __init__(self, permissionname):
Exception.__init__(self, "Unknown permission: %s" % permissionname)
def __init__(self, permissionname):
Exception.__init__(self, "Unknown permission: %s" % permissionname)
+1293 -1114
View File
File diff suppressed because it is too large. Load diff
+197 -110
View File
@@ -1,136 +1,201 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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
click.disable_unicode_literals_warning = True
import octoprint
import sys
#~~ click context
# ~~ click context
class OctoPrintContext(object):
"""Custom context wrapping the standard options."""
"""Custom context wrapping the standard options."""
def __init__(self, configfile=None, basedir=None, verbosity=0, safe_mode=False):
self.configfile = configfile
self.basedir = basedir
self.verbosity = verbosity
self.safe_mode = safe_mode
def __init__(self, configfile=None, basedir=None, verbosity=0, safe_mode=False):
self.configfile = configfile
self.basedir = basedir
self.verbosity = verbosity
self.safe_mode = safe_mode
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
# ~~ 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
"""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.
"""
"""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
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
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 setting context options
#~~ helper for setting 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 value != param.default:
setattr(ctx.obj, param.name, value)
elif param.default is not None:
setattr(ctx.obj, param.name, param.default)
"""Helper for setting eager options on the context."""
if ctx.obj is None:
ctx.obj = OctoPrintContext()
if value != param.default:
setattr(ctx.obj, param.name, value)
elif param.default is not None:
setattr(ctx.obj, param.name, param.default)
# ~~ helper for retrieving context options
#~~ helper for retrieving context options
def get_ctx_obj_option(ctx, key, default, include_parents=True):
if include_parents and hasattr(ctx, "parent") and ctx.parent:
fallback = get_ctx_obj_option(ctx.parent, key, default)
else:
fallback = default
return getattr(ctx.obj, key, fallback)
if include_parents and hasattr(ctx, "parent") and ctx.parent:
fallback = get_ctx_obj_option(ctx.parent, key, default)
else:
fallback = default
return getattr(ctx.obj, key, fallback)
# ~~ helper for setting a lot of bulk options
#~~ helper for setting a lot of bulk options
def bulk_options(options):
"""
Utility decorator to decorate a function with a list of click decorators.
"""
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).
"""
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
def decorator(f):
options.reverse()
for option in options:
option(f)
return f
return decorator
# ~~ helper for setting --basedir, --config and --verbose options
#~~ helper for setting --basedir, --config and --verbose options
def standard_options(hidden=False):
"""
Decorator to add the standard options shared among all "octoprint" commands.
"""
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.
"""
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
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 configs, 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."),
factory("--safe", "safe_mode", is_flag=True, callback=set_ctx_obj_option, is_eager=True, expose_value=False,
help="Enable safe mode; disables all third party plugins.")
]
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 configs, 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.",
),
factory(
"--safe",
"safe_mode",
is_flag=True,
callback=set_ctx_obj_option,
is_eager=True,
expose_value=False,
help="Enable safe mode; disables all third party plugins.",
),
]
return bulk_options(options)
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, callback=set_ctx_obj_option),
hidden_option("--port", type=click.INT, callback=set_ctx_obj_option),
hidden_option("--logging", type=click.Path(), callback=set_ctx_obj_option),
hidden_option("--debug", "-d", is_flag=True, callback=set_ctx_obj_option),
hidden_option("--daemon", type=click.Choice(["start", "stop", "restart"]), callback=set_ctx_obj_option),
hidden_option("--pid", type=click.Path(), default="/tmp/octoprint.pid", callback=set_ctx_obj_option),
hidden_option("--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option),
hidden_option("--ignore-blacklist", "ignore_blacklist", is_flag=True, callback=set_ctx_obj_option)
])
# ~~ helper for settings legacy options we still have to support on "octoprint"
legacy_options = bulk_options(
[
hidden_option("--host", type=click.STRING, callback=set_ctx_obj_option),
hidden_option("--port", type=click.INT, callback=set_ctx_obj_option),
hidden_option("--logging", type=click.Path(), callback=set_ctx_obj_option),
hidden_option("--debug", "-d", is_flag=True, callback=set_ctx_obj_option),
hidden_option(
"--daemon",
type=click.Choice(["start", "stop", "restart"]),
callback=set_ctx_obj_option,
),
hidden_option(
"--pid",
type=click.Path(),
default="/tmp/octoprint.pid",
callback=set_ctx_obj_option,
),
hidden_option(
"--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option
),
hidden_option(
"--ignore-blacklist",
"ignore_blacklist",
is_flag=True,
callback=set_ctx_obj_option,
),
]
)
"""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
# ~~ "octoprint" command, merges server_commands and plugin_commands groups
from .server import server_commands
from .plugins import plugin_commands
@@ -140,38 +205,60 @@ from .config import config_commands
from .analysis import analysis_commands
from .user import user_commands
@click.group(name="octoprint", invoke_without_command=True, cls=click.CommandCollection,
sources=[server_commands, plugin_commands, dev_commands, client_commands, config_commands, analysis_commands, user_commands])
@click.group(
name="octoprint",
invoke_without_command=True,
cls=click.CommandCollection,
sources=[
server_commands,
plugin_commands,
dev_commands,
client_commands,
config_commands,
analysis_commands,
user_commands,
],
)
@standard_options()
@legacy_options
@click.version_option(version=octoprint.__version__, allow_from_autoenv=False)
@click.pass_context
def octo(ctx, **kwargs):
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 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.
def get_value(key):
return get_ctx_obj_option(ctx, key, kwargs.get(key))
daemon = get_value("daemon")
def get_value(key):
return get_ctx_obj_option(ctx, key, kwargs.get(key))
if daemon:
click.echo("Daemon operation via \"octoprint --daemon "
"start|stop|restart\" is deprecated, please use "
"\"octoprint daemon start|stop|restart\" from now on")
daemon = get_value("daemon")
if sys.platform == "win32" or sys.platform == "darwin":
click.echo("Sorry, daemon mode is not supported under your operating system right now")
else:
from octoprint.cli.server import daemon_command
ctx.invoke(daemon_command, command=daemon, **kwargs)
else:
click.echo("Starting the server via \"octoprint\" is deprecated, "
"please use \"octoprint serve\" from now on.")
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 serve_command
ctx.invoke(serve_command, **kwargs)
if sys.platform == "win32" or sys.platform == "darwin":
click.echo(
"Sorry, daemon mode is not supported under your operating system right now"
)
else:
from octoprint.cli.server import daemon_command
ctx.invoke(daemon_command, command=daemon, **kwargs)
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, **kwargs)
+69 -42
View File
@@ -1,22 +1,25 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
import click
click.disable_unicode_literals_warning = True
#~~ "octoprint util" commands
# ~~ "octoprint util" commands
@click.group()
def analysis_commands():
pass
pass
@analysis_commands.group(name="analysis")
def util():
"""Analysis tools."""
pass
"""Analysis tools."""
pass
@util.command(name="gcode")
@@ -30,49 +33,73 @@ def util():
@click.option("--g90-extruder", "g90_extruder", is_flag=True)
@click.option("--progress", "progress", is_flag=True)
@click.argument("path", type=click.Path())
def gcode_command(path, speedx, speedy, speedz, offset, maxt, throttle, throttle_lines, g90_extruder, progress):
"""Runs a GCODE file analysis."""
def gcode_command(
path,
speedx,
speedy,
speedz,
offset,
maxt,
throttle,
throttle_lines,
g90_extruder,
progress,
):
"""Runs a GCODE file analysis."""
import time
import yaml
from octoprint.util import monotonic_time
from octoprint.util.gcodeInterpreter import gcode
import time
import yaml
from octoprint.util import monotonic_time
from octoprint.util.gcodeInterpreter import gcode
throttle_callback = None
if throttle:
def throttle_callback(filePos, readBytes):
if filePos % throttle_lines == 0:
# only apply throttle every $throttle_lines lines
time.sleep(throttle)
throttle_callback = None
if throttle:
offsets = offset
if offsets is None:
offsets = []
elif isinstance(offset, tuple):
offsets = list(offsets)
offsets = [(0, 0)] + offsets
if len(offsets) < maxt:
offsets += [(0, 0)] * (maxt - len(offsets))
def throttle_callback(filePos, readBytes):
if filePos % throttle_lines == 0:
# only apply throttle every $throttle_lines lines
time.sleep(throttle)
start_time = monotonic_time()
offsets = offset
if offsets is None:
offsets = []
elif isinstance(offset, tuple):
offsets = list(offsets)
offsets = [(0, 0)] + offsets
if len(offsets) < maxt:
offsets += [(0, 0)] * (maxt - len(offsets))
progress_callback = None
if progress:
def progress_callback(percentage):
click.echo("PROGRESS:{}".format(percentage))
interpreter = gcode(progress_callback=progress_callback)
start_time = monotonic_time()
interpreter.load(path,
speedx=speedx,
speedy=speedy,
offsets=offsets,
throttle=throttle_callback,
max_extruders=maxt,
g90_extruder=g90_extruder)
progress_callback = None
if progress:
def progress_callback(percentage):
click.echo("PROGRESS:{}".format(percentage))
interpreter = gcode(progress_callback=progress_callback)
interpreter.load(
path,
speedx=speedx,
speedy=speedy,
offsets=offsets,
throttle=throttle_callback,
max_extruders=maxt,
g90_extruder=g90_extruder,
)
click.echo("DONE:{}s".format(monotonic_time() - start_time))
click.echo("RESULTS:")
click.echo(
yaml.safe_dump(
interpreter.get_result(),
default_flow_style=False,
indent=4,
allow_unicode=True,
)
)
click.echo("DONE:{}s".format(monotonic_time() - start_time))
click.echo("RESULTS:")
click.echo(yaml.safe_dump(interpreter.get_result(), default_flow_style=False, indent=4, allow_unicode=True))
if __name__ == "__main__":
gcode_command()
gcode_command()
+199 -132
View File
@@ -1,10 +1,11 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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
click.disable_unicode_literals_warning = True
import io
@@ -17,91 +18,110 @@ from octoprint import init_settings, FatalStartupError
from past.builtins import unicode
class JsonStringParamType(click.ParamType):
name = "json"
name = "json"
def convert(self, value, param, ctx):
try:
return json.loads(value)
except Exception:
self.fail("%s is not a valid json string" % value, param, ctx)
def convert(self, value, param, ctx):
try:
return json.loads(value)
except Exception:
self.fail("%s is not a valid json string" % value, param, ctx)
def create_client(settings=None, apikey=None, host=None, port=None, httpuser=None, httppass=None, https=False, prefix=None):
assert(host is not None or settings is not None)
assert(port is not None or settings is not None)
assert(apikey is not None or settings is not None)
def create_client(
settings=None,
apikey=None,
host=None,
port=None,
httpuser=None,
httppass=None,
https=False,
prefix=None,
):
assert host is not None or settings is not None
assert port is not None or settings is not None
assert apikey is not None or settings is not None
if not host:
host = settings.get(["server", "host"])
host = host if host != "0.0.0.0" else "127.0.0.1"
if not port:
port = settings.getInt(["server", "port"])
if not host:
host = settings.get(["server", "host"])
host = host if host != "0.0.0.0" else "127.0.0.1"
if not port:
port = settings.getInt(["server", "port"])
if not apikey:
apikey = settings.get(["api", "key"])
if not apikey:
apikey = settings.get(["api", "key"])
baseurl = octoprint_client.build_base_url(https=https,
httpuser=httpuser,
httppass=httppass,
host=host,
port=port,
prefix=prefix)
baseurl = octoprint_client.build_base_url(
https=https,
httpuser=httpuser,
httppass=httppass,
host=host,
port=port,
prefix=prefix,
)
return octoprint_client.Client(baseurl, apikey)
return octoprint_client.Client(baseurl, apikey)
client_options = bulk_options([
click.option("--apikey", "-a", type=click.STRING),
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)
])
client_options = bulk_options(
[
click.option("--apikey", "-a", type=click.STRING),
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),
]
)
"""Common options to configure an API client."""
@click.group()
def client_commands():
pass
pass
@client_commands.group("client", context_settings={"ignore_unknown_options": True})
@client_options
@click.pass_context
def client(ctx, apikey, host, port, httpuser, httppass, https, prefix):
"""Basic API client."""
try:
settings = None
if not host or not port or not apikey:
settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
"""Basic API client."""
try:
settings = None
if not host or not port or not apikey:
settings = init_settings(
get_ctx_obj_option(ctx, "basedir", None),
get_ctx_obj_option(ctx, "configfile", None),
)
ctx.obj.client = create_client(settings=settings,
apikey=apikey,
host=host,
port=port,
httpuser=httpuser,
httppass=httppass,
https=https,
prefix=prefix)
ctx.obj.client = create_client(
settings=settings,
apikey=apikey,
host=host,
port=port,
httpuser=httpuser,
httppass=httppass,
https=https,
prefix=prefix,
)
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the client.", err=True)
ctx.exit(-1)
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the client.", err=True)
ctx.exit(-1)
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)
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")
@@ -109,9 +129,9 @@ def log_response(response, status_code=True, body=True, headers=False):
@click.option("--timeout", type=float, default=None)
@click.pass_context
def get(ctx, path, timeout):
"""Performs a GET request against the specified server path."""
r = ctx.obj.client.get(path, timeout=timeout)
log_response(r)
"""Performs a GET request against the specified server path."""
r = ctx.obj.client.get(path, timeout=timeout)
log_response(r)
@client.command("post_json")
@@ -120,9 +140,9 @@ def get(ctx, path, timeout):
@click.option("--timeout", type=float, default=None)
@click.pass_context
def post_json(ctx, path, data, timeout):
"""POSTs JSON data to the specified server path."""
r = ctx.obj.client.post_json(path, data, timeout=timeout)
log_response(r)
"""POSTs JSON data to the specified server path."""
r = ctx.obj.client.post_json(path, data, timeout=timeout)
log_response(r)
@client.command("patch_json")
@@ -131,75 +151,118 @@ def post_json(ctx, path, data, timeout):
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
@click.pass_context
def patch_json(ctx, path, data, timeout):
"""PATCHes JSON data to the specified server path."""
r = ctx.obj.client.patch(path, data, encoding="json", timeout=timeout)
log_response(r)
"""PATCHes JSON data to the specified server path."""
r = ctx.obj.client.patch(path, data, encoding="json", timeout=timeout)
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.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)
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
@click.pass_context
def post_from_file(ctx, path, file_path, json_flag, yaml_flag, timeout):
"""POSTs JSON data to the specified server path, taking the data from the specified file."""
if json_flag or yaml_flag:
if json_flag:
with io.open(file_path, 'rt') as fp:
data = json.load(fp)
else:
import yaml
with io.open(file_path, 'rt') as fp:
data = yaml.safe_load(fp)
"""POSTs JSON data to the specified server path, taking the data from the specified file."""
if json_flag or yaml_flag:
if json_flag:
with io.open(file_path, "rt") as fp:
data = json.load(fp)
else:
import yaml
r = ctx.obj.client.post_json(path, data, timeout=timeout)
else:
with io.open(file_path, 'rb') as fp:
data = fp.read()
with io.open(file_path, "rt") as fp:
data = yaml.safe_load(fp)
r = ctx.obj.client.post(path, data, timeout=timeout)
r = ctx.obj.client.post_json(path, data, timeout=timeout)
else:
with io.open(file_path, "rb") as fp:
data = fp.read()
log_response(r)
r = ctx.obj.client.post(path, data, timeout=timeout)
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]))
@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]),
)
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
@click.pass_context
def command(ctx, path, command, str_params, int_params, float_params, bool_params, timeout):
"""Sends a JSON command to the specified server path."""
data = {}
params = str_params + int_params + float_params + bool_params
for param in params:
data[param[0]] = param[1]
r = ctx.obj.client.post_command(path, command, additional=data, timeout=timeout)
log_response(r, body=False)
def command(
ctx, path, command, str_params, int_params, float_params, bool_params, timeout
):
"""Sends a JSON command to the specified server path."""
data = {}
params = str_params + int_params + float_params + bool_params
for param in params:
data[param[0]] = param[1]
r = ctx.obj.client.post_command(path, command, additional=data, timeout=timeout)
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.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)
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
@click.pass_context
def upload(ctx, path, file_path, params, file_name, content_type, timeout):
"""Uploads the specified file to the specified server path."""
data = {}
for param in params:
data[param[0]] = param[1]
"""Uploads the specified file to the specified server path."""
data = {}
for param in params:
data[param[0]] = param[1]
r = ctx.obj.client.upload(path, file_path,
additional=data, file_name=file_name, content_type=content_type, timeout=timeout)
log_response(r)
r = ctx.obj.client.upload(
path,
file_path,
additional=data,
file_name=file_name,
content_type=content_type,
timeout=timeout,
)
log_response(r)
@client.command("delete")
@@ -207,41 +270,45 @@ def upload(ctx, path, file_path, params, file_name, content_type, timeout):
@click.option("--timeout", type=float, default=None, help="Request timeout in seconds")
@click.pass_context
def delete(ctx, path, timeout):
"""Sends a DELETE request to the specified server path."""
r = ctx.obj.client.delete(path, timeout=timeout)
log_response(r)
"""Sends a DELETE request to the specified server path."""
r = ctx.obj.client.delete(path, timeout=timeout)
log_response(r)
@client.command("listen")
@click.pass_context
def listen(ctx):
def on_connect(ws):
click.echo("--- Connected!")
def on_connect(ws):
click.echo("--- Connected!")
def on_close(ws):
click.echo("--- Connection closed!")
def on_close(ws):
click.echo("--- Connection closed!")
def on_error(ws, error):
click.echo("!!! Error: {}".format(error))
def on_error(ws, error):
click.echo("!!! Error: {}".format(error))
def on_sent(ws, data):
click.echo(">>> {}".format(json.dumps(data)))
def on_sent(ws, data):
click.echo(">>> {}".format(json.dumps(data)))
def on_heartbeat(ws):
click.echo("<3")
def on_heartbeat(ws):
click.echo("<3")
def on_message(ws, message_type, message_payload):
click.echo("<<< {}, Payload: {}".format(message_type, json.dumps(message_payload)))
def on_message(ws, message_type, message_payload):
click.echo(
"<<< {}, Payload: {}".format(message_type, json.dumps(message_payload))
)
socket = ctx.obj.client.create_socket(on_connect=on_connect,
on_close=on_close,
on_error=on_error,
on_sent=on_sent,
on_heartbeat=on_heartbeat,
on_message=on_message)
socket = ctx.obj.client.create_socket(
on_connect=on_connect,
on_close=on_close,
on_error=on_error,
on_sent=on_sent,
on_heartbeat=on_heartbeat,
on_message=on_message,
)
click.echo("--- Waiting for client to exit")
try:
socket.wait()
finally:
click.echo("--- Goodbye...")
click.echo("--- Waiting for client to exit")
try:
socket.wait()
finally:
click.echo("--- Goodbye...")
+150 -139
View File
@@ -1,11 +1,12 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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
click.disable_unicode_literals_warning = True
import logging
@@ -16,80 +17,88 @@ import yaml
import json
import pprint
def _to_settings_path(path):
if not isinstance(path, (list, tuple)):
path = list(filter(lambda x: x, map(lambda x: x.strip(), path.split("."))))
return path
if not isinstance(path, (list, tuple)):
path = list(filter(lambda x: x, map(lambda x: x.strip(), path.split("."))))
return path
def _set_helper(settings, path, value, data_type=None):
path = _to_settings_path(path)
path = _to_settings_path(path)
method = settings.set
if data_type is not None:
name = None
if data_type == bool:
name = "setBoolean"
elif data_type == float:
name = "setFloat"
elif data_type == int:
name = "setInt"
method = settings.set
if data_type is not None:
name = None
if data_type == bool:
name = "setBoolean"
elif data_type == float:
name = "setFloat"
elif data_type == int:
name = "setInt"
if name is not None:
method = getattr(settings, name)
if name is not None:
method = getattr(settings, name)
method(path, value)
settings.save()
method(path, value)
settings.save()
# ~~ "octoprint config" commands
#~~ "octoprint config" commands
@click.group()
def config_commands():
pass
pass
@config_commands.group(name="config")
@click.pass_context
def config(ctx):
"""Basic config manipulation."""
logging.basicConfig(level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN)
try:
ctx.obj.settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the settings manager.", err=True)
ctx.exit(-1)
"""Basic config manipulation."""
logging.basicConfig(
level=logging.DEBUG
if get_ctx_obj_option(ctx, "verbosity", 0) > 0
else logging.WARN
)
try:
ctx.obj.settings = init_settings(
get_ctx_obj_option(ctx, "basedir", None),
get_ctx_obj_option(ctx, "configfile", None),
)
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the settings manager.", err=True)
ctx.exit(-1)
@config.command(name="set")
@standard_options(hidden=True)
@click.argument("path", type=click.STRING)
@click.argument("value", type=click.STRING)
@click.option("--bool", "as_bool", is_flag=True,
help="Interpret value as bool")
@click.option("--float", "as_float", is_flag=True,
help="Interpret value as float")
@click.option("--int", "as_int", is_flag=True,
help="Interpret value as int")
@click.option("--json", "as_json", is_flag=True,
help="Parse value from json")
@click.option("--bool", "as_bool", is_flag=True, help="Interpret value as bool")
@click.option("--float", "as_float", is_flag=True, help="Interpret value as float")
@click.option("--int", "as_int", is_flag=True, help="Interpret value as int")
@click.option("--json", "as_json", is_flag=True, help="Parse value from json")
@click.pass_context
def set_command(ctx, path, value, as_bool, as_float, as_int, as_json):
"""Sets a config path to the provided value."""
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
"""Sets a config path to the provided value."""
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
data_type = None
if as_bool:
data_type = bool
elif as_float:
data_type = float
elif as_int:
data_type = int
data_type = None
if as_bool:
data_type = bool
elif as_float:
data_type = float
elif as_int:
data_type = int
_set_helper(ctx.obj.settings, path, value, data_type=data_type)
_set_helper(ctx.obj.settings, path, value, data_type=data_type)
@config.command(name="remove")
@@ -97,8 +106,8 @@ def set_command(ctx, path, value, as_bool, as_float, as_int, as_json):
@click.argument("path", type=click.STRING)
@click.pass_context
def remove_command(ctx, path):
"""Removes a config path."""
_set_helper(ctx.obj.settings, path, None)
"""Removes a config path."""
_set_helper(ctx.obj.settings, path, None)
@config.command(name="append_value")
@@ -108,25 +117,25 @@ def remove_command(ctx, path):
@click.option("--json", "as_json", is_flag=True)
@click.pass_context
def append_value_command(ctx, path, value, as_json=False):
"""Appends value to list behind config path."""
path = _to_settings_path(path)
"""Appends value to list behind config path."""
path = _to_settings_path(path)
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
current = ctx.obj.settings.get(path)
if current is None:
current = []
if not isinstance(current, list):
click.echo("Cannot append to non-list value at given path", err=True)
ctx.exit(-1)
current = ctx.obj.settings.get(path)
if current is None:
current = []
if not isinstance(current, list):
click.echo("Cannot append to non-list value at given path", err=True)
ctx.exit(-1)
current.append(value)
_set_helper(ctx.obj.settings, path, current)
current.append(value)
_set_helper(ctx.obj.settings, path, current)
@config.command(name="insert_value")
@@ -137,25 +146,25 @@ def append_value_command(ctx, path, value, as_json=False):
@click.option("--json", "as_json", is_flag=True)
@click.pass_context
def insert_value_command(ctx, path, index, value, as_json=False):
"""Inserts value at index of list behind config key."""
path = _to_settings_path(path)
"""Inserts value at index of list behind config key."""
path = _to_settings_path(path)
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
current = ctx.obj.settings.get(path)
if current is None:
current = []
if not isinstance(current, list):
click.echo("Cannot insert into non-list value at given path", err=True)
ctx.exit(-1)
current = ctx.obj.settings.get(path)
if current is None:
current = []
if not isinstance(current, list):
click.echo("Cannot insert into non-list value at given path", err=True)
ctx.exit(-1)
current.insert(index, value)
_set_helper(ctx.obj.settings, path, current)
current.insert(index, value)
_set_helper(ctx.obj.settings, path, current)
@config.command(name="remove_value")
@@ -165,78 +174,80 @@ def insert_value_command(ctx, path, index, value, as_json=False):
@click.option("--json", "as_json", is_flag=True)
@click.pass_context
def remove_value_command(ctx, path, value, as_json=False):
"""Removes value from list at config path."""
path = _to_settings_path(path)
"""Removes value from list at config path."""
path = _to_settings_path(path)
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
if as_json:
try:
value = json.loads(value)
except Exception as e:
click.echo(e.message, err=True)
ctx.exit(-1)
current = ctx.obj.settings.get(path)
if current is None:
current = []
if not isinstance(current, list):
click.echo("Cannot remove value from non-list value at given path", err=True)
ctx.exit(-1)
current = ctx.obj.settings.get(path)
if current is None:
current = []
if not isinstance(current, list):
click.echo("Cannot remove value from non-list value at given path", err=True)
ctx.exit(-1)
if not value in current:
click.echo("Value is not contained in list at given path")
ctx.exit()
if not value in current:
click.echo("Value is not contained in list at given path")
ctx.exit()
current.remove(value)
_set_helper(ctx.obj.settings, path, current)
current.remove(value)
_set_helper(ctx.obj.settings, path, current)
@config.command(name="get")
@click.argument("path", type=click.STRING)
@click.option("--json", "as_json", is_flag=True,
help="Output value formatted as JSON")
@click.option("--yaml", "as_yaml", is_flag=True,
help="Output value formatted as YAML")
@click.option("--raw", "as_raw", is_flag=True,
help="Output value as raw string representation")
@click.option("--json", "as_json", is_flag=True, help="Output value formatted as JSON")
@click.option("--yaml", "as_yaml", is_flag=True, help="Output value formatted as YAML")
@click.option(
"--raw", "as_raw", is_flag=True, help="Output value as raw string representation"
)
@standard_options(hidden=True)
@click.pass_context
def get_command(ctx, path, as_json=False, as_yaml=False, as_raw=False):
"""Retrieves value from config path."""
path = _to_settings_path(path)
value = ctx.obj.settings.get(path, merged=True)
"""Retrieves value from config path."""
path = _to_settings_path(path)
value = ctx.obj.settings.get(path, merged=True)
if as_json:
output = json.dumps(value)
elif as_yaml:
output = yaml.safe_dump(value, default_flow_style=False, indent=4, allow_unicode=True)
elif as_raw:
output = value
else:
output = pprint.pformat(value)
if as_json:
output = json.dumps(value)
elif as_yaml:
output = yaml.safe_dump(
value, default_flow_style=False, indent=4, allow_unicode=True
)
elif as_raw:
output = value
else:
output = pprint.pformat(value)
click.echo(output)
click.echo(output)
@config.command(name="effective")
@click.option("--json", "as_json", is_flag=True,
help="Output value formatted as JSON")
@click.option("--yaml", "as_yaml", is_flag=True,
help="Output value formatted as YAML")
@click.option("--raw", "as_raw", is_flag=True,
help="Output value as raw string representation")
@click.option("--json", "as_json", is_flag=True, help="Output value formatted as JSON")
@click.option("--yaml", "as_yaml", is_flag=True, help="Output value formatted as YAML")
@click.option(
"--raw", "as_raw", is_flag=True, help="Output value as raw string representation"
)
@standard_options(hidden=True)
@click.pass_context
def effective_command(ctx, as_json=False, as_yaml=False, as_raw=False):
"""Retrieves the full effective config."""
value = ctx.obj.settings.effective
"""Retrieves the full effective config."""
value = ctx.obj.settings.effective
if as_json:
output = json.dumps(value)
elif as_yaml:
output = yaml.safe_dump(value, default_flow_style=False, indent=4, allow_unicode=True)
elif as_raw:
output = value
else:
output = pprint.pformat(value)
if as_json:
output = json.dumps(value)
elif as_yaml:
output = yaml.safe_dump(
value, default_flow_style=False, indent=4, allow_unicode=True
)
elif as_raw:
output = value
else:
output = pprint.pformat(value)
click.echo(output)
click.echo(output)
+210 -178
View File
@@ -2,236 +2,268 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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
click.disable_unicode_literals_warning = True
from past.builtins import basestring
class OctoPrintDevelCommands(click.MultiCommand):
"""
Custom `click.MultiCommand <http://click.pocoo.org/5/api/#click.MultiCommand>`_
implementation that provides commands relevant for (plugin) development
based on availability of development dependencies.
"""
"""
Custom `click.MultiCommand <http://click.pocoo.org/5/api/#click.MultiCommand>`_
implementation that provides commands relevant for (plugin) development
based on availability of development dependencies.
"""
sep = ":"
groups = ("plugin",)
sep = ":"
groups = ("plugin",)
def __init__(self, *args, **kwargs):
click.MultiCommand.__init__(self, *args, **kwargs)
def __init__(self, *args, **kwargs):
click.MultiCommand.__init__(self, *args, **kwargs)
from octoprint.util.commandline import CommandlineCaller
from functools import partial
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
def log_util(f):
def log(*lines):
for line in lines:
f(line)
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))
return log
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
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_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_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(self):
result = {}
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 _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 list_commands(self, ctx):
result = [name for name in self._get_commands()]
result.sort()
return result
def _get_commands(self):
result = {}
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 get_command(self, ctx, cmd_name):
commands = self._get_commands()
return commands.get(cmd_name, None)
def list_commands(self, ctx):
result = [name for name in self._get_commands()]
result.sort()
return result
def plugin_new(self):
try:
import cookiecutter.main
except ImportError:
return None
def get_command(self, ctx, cmd_name):
commands = self._get_commands()
return commands.get(cmd_name, None)
try:
# we depend on Cookiecutter >= 1.4
from cookiecutter.prompt import StrictEnvironment
except ImportError:
return None
def plugin_new(self):
try:
import cookiecutter.main
except ImportError:
return None
import contextlib
try:
# we depend on Cookiecutter >= 1.4
from cookiecutter.prompt import StrictEnvironment
except ImportError:
return None
@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
import contextlib
original_get_user_config = cookiecutter.main.get_user_config
try:
def f(*args, **kwargs):
original_config = original_get_user_config(*args, **kwargs)
return fallback_dict(config, original_config)
cookiecutter.main.get_user_config = f
yield
finally:
cookiecutter.main.get_user_config = original_get_user_config
@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
@contextlib.contextmanager
def custom_cookiecutter_prompt(options):
"""
Custom cookiecutter prompter for the template config.
original_get_user_config = cookiecutter.main.get_user_config
try:
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 f(*args, **kwargs):
original_config = original_get_user_config(*args, **kwargs)
return fallback_dict(config, original_config)
def custom_prompt_for_config(context, no_input=False):
cookiecutter_dict = {}
cookiecutter.main.get_user_config = f
yield
finally:
cookiecutter.main.get_user_config = original_get_user_config
env = StrictEnvironment()
@contextlib.contextmanager
def custom_cookiecutter_prompt(options):
"""
Custom cookiecutter prompter for the template config.
for key, raw in context['cookiecutter'].items():
if key in options:
val = options[key]
else:
if not isinstance(raw, basestring):
raw = str(raw)
val = env.from_string(raw).render(cookiecutter=cookiecutter_dict)
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
if not no_input:
val = click.prompt(key, default=val)
def custom_prompt_for_config(context, no_input=False):
cookiecutter_dict = {}
cookiecutter_dict[key] = val
return cookiecutter_dict
env = StrictEnvironment()
try:
cookiecutter.main.prompt_for_config = custom_prompt_for_config
yield
finally:
cookiecutter.main.prompt_for_config = original_prompt_for_config
for key, raw in context["cookiecutter"].items():
if key in options:
val = options[key]
else:
if not isinstance(raw, basestring):
raw = str(raw)
val = env.from_string(raw).render(cookiecutter=cookiecutter_dict)
@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
if not no_input:
val = click.prompt(key, default=val)
# 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
cookiecutter_dict[key] = val
return cookiecutter_dict
if not os.access(path, os.W_OK):
os.chmod(path, stat.S_IWUSR)
func(path)
else:
raise
try:
cookiecutter.main.prompt_for_config = custom_prompt_for_config
yield
finally:
cookiecutter.main.prompt_for_config = original_prompt_for_config
with tempdir(onerror=onerror) as path:
custom = {"cookiecutters_dir": path}
with custom_cookiecutter_config(custom):
raw_options = {"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)
@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
with custom_cookiecutter_prompt(options):
cookiecutter.main.cookiecutter("gh:OctoPrint/cookiecutter-octoprint-plugin")
# 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
return command
if not os.access(path, os.W_OK):
os.chmod(path, stat.S_IWUSR)
func(path)
else:
raise
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.
with tempdir(onerror=onerror) as path:
custom = {"cookiecutters_dir": path}
with custom_cookiecutter_config(custom):
raw_options = {
"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
)
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.
"""
with custom_cookiecutter_prompt(options):
cookiecutter.main.cookiecutter(
"gh:OctoPrint/cookiecutter-octoprint-plugin"
)
import os
import sys
return command
if not path:
path = os.getcwd()
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.
# 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)
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.
"""
self.command_caller.call([sys.executable, "-m", "pip", "install", "-e", "."], cwd=path)
import os
import sys
return command
if not path:
path = os.getcwd()
def plugin_uninstall(self):
@click.command("uninstall")
@click.argument("name")
def command(name):
"""Uninstalls the plugin with the given name."""
import sys
# 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)
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)
self.command_caller.call(
[sys.executable, "-m", "pip", "install", "-e", "."], cwd=path
)
call = [sys.executable, "-m", "pip", "uninstall", "--yes", name]
self.command_caller.call(call)
return command
def plugin_uninstall(self):
@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 = [sys.executable, "-m", "pip", "uninstall", "--yes", name]
self.command_caller.call(call)
return command
return command
@click.group()
def dev_commands():
pass
pass
@dev_commands.group(name="dev", cls=OctoPrintDevelCommands)
def dev():
"""Additional commands for development tasks."""
pass
"""Additional commands for development tasks."""
pass
+106 -91
View File
@@ -1,11 +1,12 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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
click.disable_unicode_literals_warning = True
import logging
import logging.config
@@ -14,124 +15,138 @@ from octoprint.cli import pass_octoprint_ctx, OctoPrintContext, get_ctx_obj_opti
from octoprint.util import dict_merge
LOGGING_CONFIG = {
"version": 1,
"formatters": {
"brief": {
"format": "%(message)s"
}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"formatter": "brief",
"stream": "ext://sys.stdout"
}
},
"loggers": {
"octoprint.plugin.core": {
"level": logging.ERROR
}
},
"root": {
"level": logging.WARNING
}
"version": 1,
"formatters": {"brief": {"format": "%(message)s"}},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"formatter": "brief",
"stream": "ext://sys.stdout",
}
},
"loggers": {"octoprint.plugin.core": {"level": logging.ERROR}},
"root": {"level": logging.WARNING},
}
#~~ "octoprint plugin:command" commands
# ~~ "octoprint plugin:command" commands
class OctoPrintPluginCommands(click.MultiCommand):
"""
Custom `click.MultiCommand <http://click.pocoo.org/5/api/#click.MultiCommand>`_
implementation that collects commands from the plugin hook
:ref:`octoprint.cli.commands <sec-plugins-hook-cli-commands>`.
"""
Custom `click.MultiCommand <http://click.pocoo.org/5/api/#click.MultiCommand>`_
implementation that collects commands from the plugin hook
:ref:`octoprint.cli.commands <sec-plugins-hook-cli-commands>`.
.. attribute:: settings
.. attribute:: settings
The global :class:`~octoprint.settings.Settings` instance.
The global :class:`~octoprint.settings.Settings` instance.
.. attribute:: plugin_manager
.. attribute:: plugin_manager
The :class:`~octoprint.plugin.core.PluginManager` instance.
"""
The :class:`~octoprint.plugin.core.PluginManager` instance.
"""
sep = ":"
sep = ":"
def __init__(self, *args, **kwargs):
click.MultiCommand.__init__(self, *args, **kwargs)
def __init__(self, *args, **kwargs):
click.MultiCommand.__init__(self, *args, **kwargs)
self.settings = None
self.plugin_manager = None
self.hooks = {}
self.settings = None
self.plugin_manager = None
self.hooks = {}
self._logger = logging.getLogger(__name__)
self._initialized = False
self._logger = logging.getLogger(__name__)
self._initialized = False
def _initialize(self, ctx):
if self._initialized:
return
def _initialize(self, ctx):
if self._initialized:
return
click.echo("Initializing settings & plugin subsystem...")
if ctx.obj is None:
ctx.obj = OctoPrintContext()
click.echo("Initializing settings & plugin subsystem...")
if ctx.obj is None:
ctx.obj = OctoPrintContext()
logging_config = dict_merge(LOGGING_CONFIG, {"root": {"level": logging.DEBUG if ctx.obj.verbosity > 0 else logging.WARNING}})
logging.config.dictConfig(logging_config)
logging_config = dict_merge(
LOGGING_CONFIG,
{
"root": {
"level": logging.DEBUG if ctx.obj.verbosity > 0 else logging.WARNING
}
},
)
logging.config.dictConfig(logging_config)
# initialize settings and plugin manager based on provided
# context (basedir and configfile)
from octoprint import init_settings, init_pluginsystem, FatalStartupError
try:
self.settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
self.plugin_manager = init_pluginsystem(self.settings,
safe_mode=get_ctx_obj_option(ctx, "safe_mode", False))
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the settings or the plugin system.", err=True)
ctx.exit(-1)
# initialize settings and plugin manager based on provided
# context (basedir and configfile)
from octoprint import init_settings, init_pluginsystem, FatalStartupError
# fetch registered hooks
self.hooks = self.plugin_manager.get_hooks("octoprint.cli.commands")
try:
self.settings = init_settings(
get_ctx_obj_option(ctx, "basedir", None),
get_ctx_obj_option(ctx, "configfile", None),
)
self.plugin_manager = init_pluginsystem(
self.settings, safe_mode=get_ctx_obj_option(ctx, "safe_mode", False)
)
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo(
"There was a fatal error initializing the settings or the plugin system.",
err=True,
)
ctx.exit(-1)
self._initialized = True
# fetch registered hooks
self.hooks = self.plugin_manager.get_hooks("octoprint.cli.commands")
def list_commands(self, ctx):
self._initialize(ctx)
result = [name for name in self._get_commands()]
result.sort()
return result
self._initialized = True
def get_command(self, ctx, cmd_name):
self._initialize(ctx)
commands = self._get_commands()
return commands.get(cmd_name, None)
def list_commands(self, ctx):
self._initialize(ctx)
result = [name for name in self._get_commands()]
result.sort()
return result
def _get_commands(self):
"""Fetch all commands from plugins providing any."""
def get_command(self, ctx, cmd_name):
self._initialize(ctx)
commands = self._get_commands()
return commands.get(cmd_name, None)
import collections
result = collections.OrderedDict()
def _get_commands(self):
"""Fetch all commands from plugins providing any."""
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.warning("Plugin {} provided invalid CLI command, ignoring it: {!r}".format(name, command))
continue
result[name + self.sep + command.name] = command
except Exception:
self._logger.exception("Error while retrieving cli commands for plugin {}".format(name),
extra={"plugin": name})
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.warning(
"Plugin {} provided invalid CLI command, ignoring it: {!r}".format(
name, command
)
)
continue
result[name + self.sep + command.name] = command
except Exception:
self._logger.exception(
"Error while retrieving cli commands for plugin {}".format(name),
extra={"plugin": name},
)
return result
return result
@click.group()
@pass_octoprint_ctx
def plugin_commands(obj):
pass
pass
@plugin_commands.group(name="plugins", cls=OctoPrintPluginCommands)
def plugins():
"""Additional commands provided by plugins."""
pass
"""Additional commands provided by plugins."""
pass
+357 -214
View File
@@ -1,180 +1,276 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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
click.disable_unicode_literals_warning = True
import logging
import sys
from octoprint.cli import bulk_options, standard_options, set_ctx_obj_option, get_ctx_obj_option
from octoprint.cli import (
bulk_options,
standard_options,
set_ctx_obj_option,
get_ctx_obj_option,
)
def run_server(basedir, configfile, host, port, v6_only, debug, allow_root, logging_config, verbosity, safe_mode,
ignore_blacklist, octoprint_daemon=None):
"""Initializes the environment and starts up the server."""
from octoprint import init_platform, __display_version__, FatalStartupError
def run_server(
basedir,
configfile,
host,
port,
v6_only,
debug,
allow_root,
logging_config,
verbosity,
safe_mode,
ignore_blacklist,
octoprint_daemon=None,
):
"""Initializes the environment and starts up the server."""
def log_startup(recorder=None, safe_mode=None, **kwargs):
from octoprint.logging import get_divider_line
from octoprint.logging.handlers import PluginTimingsLogHandler
from octoprint import init_platform, __display_version__, FatalStartupError
logger = logging.getLogger("octoprint.startup")
PluginTimingsLogHandler.arm_rollover()
def log_startup(recorder=None, safe_mode=None, **kwargs):
from octoprint.logging import get_divider_line
from octoprint.logging.handlers import PluginTimingsLogHandler
logger.info(get_divider_line("*"))
logger.info("Starting OctoPrint {}".format(__display_version__))
if safe_mode:
logger.info("Starting in SAFE MODE. Third party plugins will be disabled!")
if safe_mode == "flag":
reason = "command line flag"
elif safe_mode == "settings":
reason = "setting in config.yaml"
elif safe_mode == "incomplete_startup":
reason = "problem during last startup"
else:
reason = "unknown"
logger.info("Reason for safe mode: {}".format(reason))
logger = logging.getLogger("octoprint.startup")
PluginTimingsLogHandler.arm_rollover()
if recorder and len(recorder):
logger.info(get_divider_line("-", "Logged during platform initialization:"))
logger.info(get_divider_line("*"))
logger.info("Starting OctoPrint {}".format(__display_version__))
if safe_mode:
logger.info("Starting in SAFE MODE. Third party plugins will be disabled!")
if safe_mode == "flag":
reason = "command line flag"
elif safe_mode == "settings":
reason = "setting in config.yaml"
elif safe_mode == "incomplete_startup":
reason = "problem during last startup"
else:
reason = "unknown"
logger.info("Reason for safe mode: {}".format(reason))
from octoprint.logging.handlers import CombinedLogHandler
handler = CombinedLogHandler(*logging.getLogger().handlers)
recorder.setTarget(handler)
recorder.flush()
if recorder and len(recorder):
logger.info(get_divider_line("-", "Logged during platform initialization:"))
logger.info(get_divider_line("-"))
from octoprint.logging.handlers import CombinedLogHandler
from octoprint import urllib3_ssl
if not urllib3_ssl:
logging.getLogger("octoprint.server")\
.warning("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")
logger.info(get_divider_line("*"))
handler = CombinedLogHandler(*logging.getLogger().handlers)
recorder.setTarget(handler)
recorder.flush()
def log_register_rollover(safe_mode=None, plugin_manager=None, environment_detector=None, **kwargs):
from octoprint.logging import get_handler, log_to_handler, get_divider_line
from octoprint.logging.handlers import OctoPrintLogHandler
logger.info(get_divider_line("-"))
def rollover_callback():
handler = get_handler("file")
if handler is None:
return
from octoprint import urllib3_ssl
logger = logging.getLogger("octoprint.server")
if not urllib3_ssl:
logging.getLogger("octoprint.server").warning(
"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"
)
logger.info(get_divider_line("*"))
def _log(message, level=logging.INFO):
log_to_handler(logger, handler, level, message)
def log_register_rollover(
safe_mode=None, plugin_manager=None, environment_detector=None, **kwargs
):
from octoprint.logging import get_handler, log_to_handler, get_divider_line
from octoprint.logging.handlers import OctoPrintLogHandler
_log(get_divider_line("-", "Log roll over detected"))
_log("OctoPrint {}".format(__display_version__))
if safe_mode:
_log("SAFE MODE is active. Third party plugins are disabled!")
plugin_manager.log_all_plugins(only_to_handler=handler)
environment_detector.log_detected_environment(only_to_handler=handler)
_log(get_divider_line("-"))
def rollover_callback():
handler = get_handler("file")
if handler is None:
return
OctoPrintLogHandler.registerRolloverCallback(rollover_callback)
logger = logging.getLogger("octoprint.server")
try:
components = init_platform(basedir, configfile,
logging_file=logging_config,
debug=debug,
verbosity=verbosity,
uncaught_logger=__name__,
safe_mode=safe_mode,
ignore_blacklist=ignore_blacklist,
after_safe_mode=log_startup,
after_environment_detector=log_register_rollover)
settings, _, safe_mode, event_manager, connectivity_checker, plugin_manager, environment_detector = components
def _log(message, level=logging.INFO):
log_to_handler(logger, handler, level, message)
except FatalStartupError as e:
logger = logging.getLogger("octoprint.startup").fatal
echo = lambda x: click.echo(x, err=True)
_log(get_divider_line("-", "Log roll over detected"))
_log("OctoPrint {}".format(__display_version__))
if safe_mode:
_log("SAFE MODE is active. Third party plugins are disabled!")
plugin_manager.log_all_plugins(only_to_handler=handler)
environment_detector.log_detected_environment(only_to_handler=handler)
_log(get_divider_line("-"))
for method in logger, echo:
method(str(e))
method("There was a fatal error starting up OctoPrint.")
OctoPrintLogHandler.registerRolloverCallback(rollover_callback)
else:
from octoprint.server import Server
octoprint_server = Server(settings=settings,
plugin_manager=plugin_manager,
event_manager=event_manager,
connectivity_checker=connectivity_checker,
environment_detector=environment_detector,
host=host,
port=port,
v6_only=v6_only,
debug=debug,
safe_mode=safe_mode,
allow_root=allow_root,
octoprint_daemon=octoprint_daemon)
octoprint_server.run()
try:
components = init_platform(
basedir,
configfile,
logging_file=logging_config,
debug=debug,
verbosity=verbosity,
uncaught_logger=__name__,
safe_mode=safe_mode,
ignore_blacklist=ignore_blacklist,
after_safe_mode=log_startup,
after_environment_detector=log_register_rollover,
)
(
settings,
_,
safe_mode,
event_manager,
connectivity_checker,
plugin_manager,
environment_detector,
) = components
#~~ server options
except FatalStartupError as e:
logger = logging.getLogger("octoprint.startup").fatal
echo = lambda x: click.echo(x, err=True)
server_options = bulk_options([
click.option("--host", type=click.STRING, callback=set_ctx_obj_option,
help="Specify the host address on which to bind the server."),
click.option("--port", type=click.INT, callback=set_ctx_obj_option,
help="Specify the port on which to bind the server."),
click.option("-4", "--ipv4", "v4", is_flag=True, callback=set_ctx_obj_option,
help="Bind to IPv4 addresses only. Implies '--host 0.0.0.0'. Silently ignored if -6 is present."),
click.option("-6", "--ipv6", "v6", is_flag=True, callback=set_ctx_obj_option,
help="Bind to IPv6 addresses only. Disables dual stack when binding to any v6 addresses. Silently ignored if -4 is present."),
click.option("--logging", type=click.Path(), callback=set_ctx_obj_option,
help="Specify the config file to use for configuring logging."),
click.option("--iknowwhatimdoing", "allow_root", is_flag=True, callback=set_ctx_obj_option,
help="Allow OctoPrint to run as user root."),
click.option("--debug", is_flag=True, callback=set_ctx_obj_option,
help="Enable debug mode."),
click.option("--ignore-blacklist", "ignore_blacklist", is_flag=True, callback=set_ctx_obj_option,
help="Disable processing of the plugin blacklist.")
])
for method in logger, echo:
method(str(e))
method("There was a fatal error starting up OctoPrint.")
else:
from octoprint.server import Server
octoprint_server = Server(
settings=settings,
plugin_manager=plugin_manager,
event_manager=event_manager,
connectivity_checker=connectivity_checker,
environment_detector=environment_detector,
host=host,
port=port,
v6_only=v6_only,
debug=debug,
safe_mode=safe_mode,
allow_root=allow_root,
octoprint_daemon=octoprint_daemon,
)
octoprint_server.run()
# ~~ server options
server_options = bulk_options(
[
click.option(
"--host",
type=click.STRING,
callback=set_ctx_obj_option,
help="Specify the host address on which to bind the server.",
),
click.option(
"--port",
type=click.INT,
callback=set_ctx_obj_option,
help="Specify the port on which to bind the server.",
),
click.option(
"-4",
"--ipv4",
"v4",
is_flag=True,
callback=set_ctx_obj_option,
help="Bind to IPv4 addresses only. Implies '--host 0.0.0.0'. Silently ignored if -6 is present.",
),
click.option(
"-6",
"--ipv6",
"v6",
is_flag=True,
callback=set_ctx_obj_option,
help="Bind to IPv6 addresses only. Disables dual stack when binding to any v6 addresses. Silently ignored if -4 is present.",
),
click.option(
"--logging",
type=click.Path(),
callback=set_ctx_obj_option,
help="Specify the config file to use for configuring logging.",
),
click.option(
"--iknowwhatimdoing",
"allow_root",
is_flag=True,
callback=set_ctx_obj_option,
help="Allow OctoPrint to run as user root.",
),
click.option(
"--debug",
is_flag=True,
callback=set_ctx_obj_option,
help="Enable debug mode.",
),
click.option(
"--ignore-blacklist",
"ignore_blacklist",
is_flag=True,
callback=set_ctx_obj_option,
help="Disable processing of the plugin blacklist.",
),
]
)
"""Decorator to add the options shared among the server commands: ``--host``, ``--port``, ``-4``, ``-6``
``--logging``, ``--iknowwhatimdoing`` and ``--debug``."""
daemon_options = bulk_options([
click.option("--pid", type=click.Path(), default="/tmp/octoprint.pid", callback=set_ctx_obj_option,
help="Pidfile to use for daemonizing.")
])
daemon_options = bulk_options(
[
click.option(
"--pid",
type=click.Path(),
default="/tmp/octoprint.pid",
callback=set_ctx_obj_option,
help="Pidfile to use for daemonizing.",
)
]
)
"""Decorator to add the options for the daemon subcommand: ``--pid``."""
#~~ "octoprint serve" and "octoprint daemon" commands
# ~~ "octoprint serve" and "octoprint daemon" commands
@click.group()
def server_commands():
pass
pass
@server_commands.command(name="safemode")
@standard_options()
@click.pass_context
def enable_safemode(ctx, **kwargs):
"""Sets the safe mode flag for the next start."""
from octoprint import init_settings, FatalStartupError
"""Sets the safe mode flag for the next start."""
from octoprint import init_settings, FatalStartupError
logging.basicConfig(level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN)
try:
settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the settings manager.", err=True)
ctx.exit(-1)
else:
settings.setBoolean(["server", "startOnceInSafeMode"], True)
settings.save()
logging.basicConfig(
level=logging.DEBUG
if get_ctx_obj_option(ctx, "verbosity", 0) > 0
else logging.WARN
)
try:
settings = init_settings(
get_ctx_obj_option(ctx, "basedir", None),
get_ctx_obj_option(ctx, "configfile", None),
)
except FatalStartupError as e:
click.echo(e.message, err=True)
click.echo("There was a fatal error initializing the settings manager.", err=True)
ctx.exit(-1)
else:
settings.setBoolean(["server", "startOnceInSafeMode"], True)
settings.save()
click.echo("Safe mode flag set, OctoPrint will start in safe mode on next restart.")
click.echo(
"Safe mode flag set, OctoPrint will start in safe mode on next restart."
)
@server_commands.command(name="serve")
@@ -182,109 +278,156 @@ def enable_safemode(ctx, **kwargs):
@server_options
@click.pass_context
def serve_command(ctx, **kwargs):
"""Starts the OctoPrint server."""
"""Starts the OctoPrint server."""
def get_value(key):
return get_ctx_obj_option(ctx, key, kwargs.get(key))
def get_value(key):
return get_ctx_obj_option(ctx, key, kwargs.get(key))
host = get_value("host")
port = get_value("port")
v4 = get_value("v4")
v6 = get_value("v6")
logging = get_value("logging")
allow_root = get_value("allow_root")
debug = get_value("debug")
host = get_value("host")
port = get_value("port")
v4 = get_value("v4")
v6 = get_value("v6")
logging = get_value("logging")
allow_root = get_value("allow_root")
debug = get_value("debug")
basedir = get_value("basedir")
configfile = get_value("configfile")
verbosity = get_value("verbosity")
safe_mode = "flag" if get_value("safe_mode") else None
ignore_blacklist = get_value("ignore_blacklist")
basedir = get_value("basedir")
configfile = get_value("configfile")
verbosity = get_value("verbosity")
safe_mode = "flag" if get_value("safe_mode") else None
ignore_blacklist = get_value("ignore_blacklist")
if v4 and not host:
host = "0.0.0.0"
if v4 and not host:
host = "0.0.0.0"
run_server(basedir, configfile, host, port, v6, debug,
allow_root, logging, verbosity, safe_mode,
ignore_blacklist)
run_server(
basedir,
configfile,
host,
port,
v6,
debug,
allow_root,
logging,
verbosity,
safe_mode,
ignore_blacklist,
)
if sys.platform != "win32" and sys.platform != "darwin":
# we do not support daemon mode under windows or macosx
# we do not support daemon mode under windows or macosx
@server_commands.command(name="daemon")
@standard_options()
@server_options
@daemon_options
@click.argument("command", type=click.Choice(["start", "stop", "restart", "status"]),
metavar="start|stop|restart|status")
@click.pass_context
def daemon_command(ctx, command, **kwargs):
"""
Starts, stops or restarts in daemon mode.
@server_commands.command(name="daemon")
@standard_options()
@server_options
@daemon_options
@click.argument(
"command",
type=click.Choice(["start", "stop", "restart", "status"]),
metavar="start|stop|restart|status",
)
@click.pass_context
def daemon_command(ctx, command, **kwargs):
"""
Starts, stops or restarts in daemon mode.
Please note that daemon mode is not supported under Windows and MacOSX right now.
"""
Please note that daemon mode is not supported under Windows and MacOSX right now.
"""
def get_value(key):
return get_ctx_obj_option(ctx, key, kwargs.get(key))
def get_value(key):
return get_ctx_obj_option(ctx, key, kwargs.get(key))
host = get_value("host")
port = get_value("port")
v4 = get_value("v4")
v6 = get_value("v6")
logging = get_value("logging")
allow_root = get_value("allow_root")
debug = get_value("debug")
pid = get_value("pid")
host = get_value("host")
port = get_value("port")
v4 = get_value("v4")
v6 = get_value("v6")
logging = get_value("logging")
allow_root = get_value("allow_root")
debug = get_value("debug")
pid = get_value("pid")
basedir = get_value("basedir")
configfile = get_value("configfile")
verbosity = get_value("verbosity")
safe_mode = "flag" if get_value("safe_mode") else None
ignore_blacklist = get_value("ignore_blacklist")
basedir = get_value("basedir")
configfile = get_value("configfile")
verbosity = get_value("verbosity")
safe_mode = "flag" if get_value("safe_mode") else None
ignore_blacklist = get_value("ignore_blacklist")
if v4 and not host:
host = "0.0.0.0"
if v4 and not host:
host = "0.0.0.0"
if pid is None:
click.echo("No path to a pidfile set",
file=sys.stderr)
sys.exit(1)
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, v6_only, debug, allow_root, logging_config,
verbosity, safe_mode, ignore_blacklist):
Daemon.__init__(self, pidfile)
from octoprint.daemon import Daemon
self._basedir = basedir
self._configfile = configfile
self._host = host
self._port = port
self._v6_only = v6_only
self._debug = debug
self._allow_root = allow_root
self._logging_config = logging_config
self._verbosity = verbosity
self._safe_mode = safe_mode
self._ignore_blacklist = ignore_blacklist
class OctoPrintDaemon(Daemon):
def __init__(
self,
pidfile,
basedir,
configfile,
host,
port,
v6_only,
debug,
allow_root,
logging_config,
verbosity,
safe_mode,
ignore_blacklist,
):
Daemon.__init__(self, pidfile)
def run(self):
run_server(self._basedir, self._configfile, self._host, self._port, self._v6_only, self._debug,
self._allow_root, self._logging_config, self._verbosity, self._safe_mode,
self._ignore_blacklist, octoprint_daemon=self)
self._basedir = basedir
self._configfile = configfile
self._host = host
self._port = port
self._v6_only = v6_only
self._debug = debug
self._allow_root = allow_root
self._logging_config = logging_config
self._verbosity = verbosity
self._safe_mode = safe_mode
self._ignore_blacklist = ignore_blacklist
octoprint_daemon = OctoPrintDaemon(pid, basedir, configfile, host, port, v6, debug, allow_root, logging,
verbosity, safe_mode, ignore_blacklist)
if command == "start":
octoprint_daemon.start()
elif command == "stop":
octoprint_daemon.stop()
elif command == "restart":
octoprint_daemon.restart()
elif command == "status":
octoprint_daemon.status()
def run(self):
run_server(
self._basedir,
self._configfile,
self._host,
self._port,
self._v6_only,
self._debug,
self._allow_root,
self._logging_config,
self._verbosity,
self._safe_mode,
self._ignore_blacklist,
octoprint_daemon=self,
)
octoprint_daemon = OctoPrintDaemon(
pid,
basedir,
configfile,
host,
port,
v6,
debug,
allow_root,
logging,
verbosity,
safe_mode,
ignore_blacklist,
)
if command == "start":
octoprint_daemon.start()
elif command == "stop":
octoprint_daemon.stop()
elif command == "restart":
octoprint_daemon.restart()
elif command == "status":
octoprint_daemon.status()
+136 -103
View File
@@ -1,7 +1,7 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License"
@@ -16,109 +16,136 @@ from octoprint.util import get_class, sv
click.disable_unicode_literals_warning = True
#~~ "octoprint user" commands
# ~~ "octoprint user" commands
@click.group()
def user_commands():
pass
pass
@user_commands.group(name="user")
@click.pass_context
def user(ctx):
"""
User management.
"""
User management.
Note that this currently only supports managing user accounts stored in the configured user manager, not any
user managers added through plugins and the "octoprint.users.factory" hook.
"""
try:
logging.basicConfig(level=logging.DEBUG if get_ctx_obj_option(ctx, "verbosity", 0) > 0 else logging.WARN)
settings = init_settings(get_ctx_obj_option(ctx, "basedir", None), get_ctx_obj_option(ctx, "configfile", None))
Note that this currently only supports managing user accounts stored in the configured user manager, not any
user managers added through plugins and the "octoprint.users.factory" hook.
"""
try:
logging.basicConfig(
level=logging.DEBUG
if get_ctx_obj_option(ctx, "verbosity", 0) > 0
else logging.WARN
)
settings = init_settings(
get_ctx_obj_option(ctx, "basedir", None),
get_ctx_obj_option(ctx, "configfile", None),
)
group_manager_name = settings.get(["accessControl", "groupManager"])
try:
clazz = get_class(group_manager_name)
group_manager = clazz()
except AttributeError:
click.echo("Could not instantiate group manager {}, "
"falling back to FilebasedGroupManager!".format(group_manager_name), err=True)
group_manager = FilebasedGroupManager()
group_manager_name = settings.get(["accessControl", "groupManager"])
try:
clazz = get_class(group_manager_name)
group_manager = clazz()
except AttributeError:
click.echo(
"Could not instantiate group manager {}, "
"falling back to FilebasedGroupManager!".format(group_manager_name),
err=True,
)
group_manager = FilebasedGroupManager()
ctx.obj.group_manager = group_manager
ctx.obj.group_manager = group_manager
name = settings.get(["accessControl", "userManager"])
try:
clazz = get_class(name)
user_manager = clazz(group_manager=group_manager, settings=settings)
except Exception:
click.echo("Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(name), err=True)
user_manager = FilebasedUserManager(group_manager, settings=settings)
finally:
user_manager.enabled = settings.getBoolean(["accessControl", "enabled"])
name = settings.get(["accessControl", "userManager"])
try:
clazz = get_class(name)
user_manager = clazz(group_manager=group_manager, settings=settings)
except Exception:
click.echo(
"Could not instantiate user manager {}, falling back to FilebasedUserManager!".format(
name
),
err=True,
)
user_manager = FilebasedUserManager(group_manager, settings=settings)
finally:
user_manager.enabled = settings.getBoolean(["accessControl", "enabled"])
ctx.obj.user_manager = user_manager
ctx.obj.user_manager = user_manager
except Exception:
click.echo("Could not instantiate user manager", err=True)
return
except Exception:
click.echo("Could not instantiate user manager", err=True)
return
@user.command(name="list")
@click.pass_context
def list_users_command(ctx):
"""Lists user information"""
users = ctx.obj.user_manager.get_all_users()
_print_list(users)
"""Lists user information"""
users = ctx.obj.user_manager.get_all_users()
_print_list(users)
@user.command(name="add")
@click.argument("username", type=click.STRING, required=True)
@click.password_option("--password", "password", help="Password for the user")
@click.option("-g", "--group", "groups", multiple=True,
help="Groups to set on the user")
@click.option("-p", "--permission", "permissions", multiple=True,
help="Individual permissions to set on the user")
@click.option("--admin", "is_admin", type=click.BOOL, is_flag=True, default=False,
help="Adds user to admin group")
@click.option("-g", "--group", "groups", multiple=True, help="Groups to set on the user")
@click.option(
"-p",
"--permission",
"permissions",
multiple=True,
help="Individual permissions to set on the user",
)
@click.option(
"--admin",
"is_admin",
type=click.BOOL,
is_flag=True,
default=False,
help="Adds user to admin group",
)
@click.pass_context
def add_user_command(ctx, username, password, groups, permissions, is_admin):
"""Add a new user."""
if not groups:
groups = []
"""Add a new user."""
if not groups:
groups = []
if is_admin:
groups.append(ctx.obj.group_manager.admin_group)
if is_admin:
groups.append(ctx.obj.group_manager.admin_group)
try:
ctx.obj.user_manager.add_user(username,
password,
groups=groups,
permissions=permissions,
active=True)
try:
ctx.obj.user_manager.add_user(
username, password, groups=groups, permissions=permissions, active=True
)
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.as_dict())))
except UserAlreadyExists:
click.echo("A user with the name {} does already exist!".format(username), err=True)
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.as_dict())))
except UserAlreadyExists:
click.echo(
"A user with the name {} does already exist!".format(username), err=True
)
@user.command(name="remove")
@click.argument("username", type=click.STRING)
@click.pass_context
def remove_user_command(ctx, username):
"""Remove an existing user."""
confirm = click.prompt("This is will irreversibly destroy the user account! Enter 'yes' to confirm",
type=click.STRING)
"""Remove an existing user."""
confirm = click.prompt(
"This is will irreversibly destroy the user account! Enter 'yes' to confirm",
type=click.STRING,
)
if confirm.lower() == "yes":
ctx.obj.user_manager.remove_user(username)
click.echo("User {} removed.".format(username))
else:
click.echo("User {} not removed.".format(username))
if confirm.lower() == "yes":
ctx.obj.user_manager.remove_user(username)
click.echo("User {} removed.".format(username))
else:
click.echo("User {} not removed.".format(username))
@user.command(name="password")
@@ -126,59 +153,65 @@ def remove_user_command(ctx, username):
@click.password_option("--password", "password", help="New password for user")
@click.pass_context
def change_password_command(ctx, username, password):
"""Change an existing user's password."""
try:
ctx.obj.user_manager.change_user_password(username, password)
click.echo("Password changed for user {}.".format(username))
except UnknownUser:
click.echo("User {} does not exist!".format(username), err=True)
"""Change an existing user's password."""
try:
ctx.obj.user_manager.change_user_password(username, password)
click.echo("Password changed for user {}.".format(username))
except UnknownUser:
click.echo("User {} does not exist!".format(username), err=True)
@user.command(name="activate")
@click.argument("username", type=click.STRING)
@click.pass_context
def activate_command(ctx, username):
"""Activate a user account."""
try:
ctx.obj.user_manager.change_user_activation(username, True)
click.echo("User {} activated.".format(username))
"""Activate a user account."""
try:
ctx.obj.user_manager.change_user_activation(username, True)
click.echo("User {} activated.".format(username))
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.asDict())))
except UnknownUser:
click.echo("User {} does not exist!".format(username), err=True)
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.asDict())))
except UnknownUser:
click.echo("User {} does not exist!".format(username), err=True)
@user.command(name="deactivate")
@click.argument("username", type=click.STRING)
@click.pass_context
def deactivate_command(ctx, username):
"""Activate a user account."""
try:
ctx.obj.user_manager.change_user_activation(username, False)
click.echo("User {} activated.".format(username))
"""Activate a user account."""
try:
ctx.obj.user_manager.change_user_activation(username, False)
click.echo("User {} activated.".format(username))
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.asDict())))
except UnknownUser:
click.echo("User {} does not exist!".format(username), err=True)
user = ctx.obj.user_manager.find_user(username)
if user:
click.echo("User created:")
click.echo("\t{}".format(_user_to_line(user.asDict())))
except UnknownUser:
click.echo("User {} does not exist!".format(username), err=True)
def _print_list(users):
click.echo("{} users registered in the system:".format(len(users)))
for user in sorted(map(lambda x: x.as_dict(), users), key=lambda x: sv(x.get("name"))):
click.echo("\t{}".format(_user_to_line(user)))
click.echo("{} users registered in the system:".format(len(users)))
for user in sorted(
map(lambda x: x.as_dict(), users), key=lambda x: sv(x.get("name"))
):
click.echo("\t{}".format(_user_to_line(user)))
def _user_to_line(user):
return "{name}" \
"\n\t\tactive: {active}" \
"\n\t\tgroups: {groups}" \
"\n\t\tpermissions: {permissions}".format(name=user.get("name"),
active=user.get("active", "False"),
groups=", ".join(user.get("groups", [])),
permissions=", ".join(user.get("permissions", [])))
return (
"{name}"
"\n\t\tactive: {active}"
"\n\t\tgroups: {groups}"
"\n\t\tpermissions: {permissions}".format(
name=user.get("name"),
active=user.get("active", "False"),
groups=", ".join(user.get("groups", [])),
permissions=", ".join(user.get("permissions", [])),
)
)
+142 -133
View File
@@ -9,168 +9,177 @@ Originally from http://www.jejik.com/articles/2007/02/a_simple_unix_linux_daemon
import io, 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.
If you want to log the output to someplace different that stdout and stderr,
also override the echo() and error() methods.
"""
If you want to log the output to someplace different that stdout and stderr,
also override the echo() and error() methods.
"""
def __init__(self, pidfile):
self.pidfile = pidfile
def __init__(self, pidfile):
self.pidfile = pidfile
def _daemonize(self):
"""Daemonize class. UNIX double fork mechanism."""
def _daemonize(self):
"""Daemonize class. UNIX double fork mechanism."""
self._double_fork()
self._redirect_io()
self._double_fork()
self._redirect_io()
# write pidfile
pid = str(os.getpid())
self.set_pid(pid)
# write pidfile
pid = str(os.getpid())
self.set_pid(pid)
def _double_fork(self):
try:
pid = os.fork()
if pid > 0:
# exit first parent
sys.exit(0)
except OSError as err:
self.error("First fork failed: {}".format(str(err)))
sys.exit(1)
def _double_fork(self):
try:
pid = os.fork()
if pid > 0:
# exit first parent
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(0o002)
# decouple from parent environment
os.chdir("/")
os.setsid()
os.umask(0o002)
# do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent
sys.exit(0)
except OSError as err:
self.error("Second fork failed: {}".format(str(err)))
sys.exit(1)
# do second fork
try:
pid = os.fork()
if pid > 0:
# exit from second parent
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()
si = io.open(os.devnull, 'rt', encoding='utf-8')
so = io.open(os.devnull, 'at+', encoding='utf-8')
se = io.open(os.devnull, 'at+', encoding='utf-8')
def _redirect_io(self):
# redirect standard file descriptors
sys.stdout.flush()
sys.stderr.flush()
si = io.open(os.devnull, "rt", encoding="utf-8")
so = io.open(os.devnull, "at+", encoding="utf-8")
se = io.open(os.devnull, "at+", encoding="utf-8")
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
os.dup2(si.fileno(), sys.stdin.fileno())
os.dup2(so.fileno(), sys.stdout.fileno())
os.dup2(se.fileno(), sys.stderr.fileno())
def terminated(self):
self.remove_pidfile()
def terminated(self):
self.remove_pidfile()
def start(self):
"""Start the daemon."""
def start(self):
"""Start the daemon."""
# Check for a pidfile to see if the daemon already runs
pid = self.get_pid()
if pid:
self.error("pidfile {} already exist. Is the daemon already running?".format(self.pidfile))
sys.exit(1)
# Check for a pidfile to see if the daemon already runs
pid = self.get_pid()
if pid:
self.error(
"pidfile {} already exist. Is the daemon already running?".format(
self.pidfile
)
)
sys.exit(1)
self.echo("Starting daemon...")
self.echo("Starting daemon...")
# Start the daemon
self._daemonize()
self.run()
# Start the daemon
self._daemonize()
self.run()
def stop(self, check_running=True):
"""Stop the daemon."""
pid = self.get_pid()
if not pid:
if not check_running:
return
self.error("pidfile {} does not exist. Is the daemon really running?".format(self.pidfile))
sys.exit(1)
def stop(self, check_running=True):
"""Stop the daemon."""
pid = self.get_pid()
if not pid:
if not check_running:
return
self.error(
"pidfile {} does not exist. Is the daemon really running?".format(
self.pidfile
)
)
sys.exit(1)
self.echo("Stopping daemon...")
self.echo("Stopping daemon...")
# Try killing the daemon process
try:
while 1:
os.kill(pid, signal.SIGTERM)
time.sleep(0.1)
except OSError as err:
e = str(err.args)
if e.find("No such process") > 0:
self.remove_pidfile()
else:
self.error(e)
sys.exit(1)
# Try killing the daemon process
try:
while 1:
os.kill(pid, signal.SIGTERM)
time.sleep(0.1)
except OSError as err:
e = str(err.args)
if e.find("No such process") > 0:
self.remove_pidfile()
else:
self.error(e)
sys.exit(1)
def restart(self):
"""Restart the daemon."""
self.stop(check_running=False)
self.start()
def restart(self):
"""Restart the daemon."""
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 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
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 Exception:
self.error("Daemon found not running, but could not remove stale pidfile")
return False
else:
return True
try:
os.kill(pid, 0)
except OSError:
try:
self.remove_pidfile()
except Exception:
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 io.open(self.pidfile,'rt', encoding='utf-8') as pf:
pid = int(pf.read().strip())
except (IOError, ValueError):
pid = None
return pid
def get_pid(self):
"""Get the pid from the pidfile."""
try:
with io.open(self.pidfile, "rt", encoding="utf-8") 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 io.open(self.pidfile,'wt+', encoding='utf-8') as f:
f.write(str(pid) + '\n')
def set_pid(self, pid):
"""Write the pid to the pidfile."""
with io.open(self.pidfile, "wt+", encoding="utf-8") 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 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.
def run(self):
"""You should override this method when you subclass Daemon.
It will be called after the process has been daemonized by
start() or restart()."""
It will be called after the process has been daemonized by
start() or restart()."""
raise NotImplementedError()
raise NotImplementedError()
@classmethod
def echo(cls, line):
print(line)
@classmethod
def echo(cls, line):
print(line)
@classmethod
def error(cls, line):
print(line, file=sys.stderr)
@classmethod
def error(cls, line):
print(line, file=sys.stderr)
+146 -126
View File
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
import copy
@@ -17,157 +17,177 @@ from octoprint.plugin import EnvironmentDetectionPlugin
from octoprint.util.platform import get_os
from octoprint.util.version import get_python_version_string
class EnvironmentDetector(object):
def __init__(self, plugin_manager):
self._plugin_manager = plugin_manager
def __init__(self, plugin_manager):
self._plugin_manager = plugin_manager
self._cache = None
self._cache_lock = threading.RLock()
self._cache = None
self._cache_lock = threading.RLock()
self._logger = logging.getLogger(__name__)
self._logger = logging.getLogger(__name__)
try:
self._environment_plugins = self._plugin_manager.get_implementations(
EnvironmentDetectionPlugin
)
except Exception:
# just in case, see #3100...
self._logger.exception(
"There was an error fetching EnvironmentDetectionPlugins from the plugin manager"
)
self._environment_plugins = []
try:
self._environment_plugins = self._plugin_manager.get_implementations(EnvironmentDetectionPlugin)
except Exception:
# just in case, see #3100...
self._logger.exception("There was an error fetching EnvironmentDetectionPlugins from the plugin manager")
self._environment_plugins = []
@property
def environment(self):
with self._cache_lock:
if self._cache is None:
self.run_detection()
return copy.deepcopy(self._cache)
@property
def environment(self):
with self._cache_lock:
if self._cache is None:
self.run_detection()
return copy.deepcopy(self._cache)
def run_detection(self, notify_plugins=True):
try:
environment = {}
environment["os"] = self._detect_os()
environment["python"] = self._detect_python()
environment["hardware"] = self._detect_hardware()
def run_detection(self, notify_plugins=True):
try:
environment = {}
environment["os"] = self._detect_os()
environment["python"] = self._detect_python()
environment["hardware"] = self._detect_hardware()
plugin_result = self._detect_from_plugins()
if plugin_result:
environment["plugins"] = plugin_result
plugin_result = self._detect_from_plugins()
if plugin_result:
environment["plugins"] = plugin_result
with self._cache_lock:
self._cache = environment
with self._cache_lock:
self._cache = environment
if notify_plugins:
self.notify_plugins()
if notify_plugins:
self.notify_plugins()
return environment
except Exception:
self._logger.exception("Unexpected error while detecting environment")
with self._cache_lock:
self._cache = {}
return self._cache
return environment
except Exception:
self._logger.exception("Unexpected error while detecting environment")
with self._cache_lock:
self._cache = {}
return self._cache
def _detect_os(self):
return {"id": get_os(), "platform": sys.platform}
def _detect_os(self):
return {"id": get_os(),
"platform": sys.platform}
def _detect_python(self):
result = {"version": "unknown", "pip": "unknown"}
def _detect_python(self):
result = {"version": "unknown",
"pip": "unknown"}
# determine python version
try:
result["version"] = get_python_version_string()
except Exception:
self._logger.exception("Error detecting python version")
# determine python version
try:
result["version"] = get_python_version_string()
except Exception:
self._logger.exception("Error detecting python version")
# determine if we are running from a virtual environment
try:
if hasattr(sys, "real_prefix") or (
hasattr(sys, "base_prefix")
and os.path.realpath(sys.prefix) != os.path.realpath(sys.base_prefix)
):
result["virtualenv"] = sys.prefix
except Exception:
self._logger.exception(
"Error detecting whether we are running in a virtual environment"
)
# determine if we are running from a virtual environment
try:
if hasattr(sys, "real_prefix") or (hasattr(sys, "base_prefix") and os.path.realpath(sys.prefix) != os.path.realpath(sys.base_prefix)):
result["virtualenv"] = sys.prefix
except Exception:
self._logger.exception("Error detecting whether we are running in a virtual environment")
# try to find pip version
try:
import pkg_resources
# try to find pip version
try:
import pkg_resources
result["pip"] = pkg_resources.get_distribution("pip").version
except Exception:
self._logger.exception("Error detecting pip version")
result["pip"] = pkg_resources.get_distribution("pip").version
except Exception:
self._logger.exception("Error detecting pip version")
return result
return result
def _detect_hardware(self):
result = {"cores": "unknown",
"freq": "unknown",
"ram": "unknown"}
def _detect_hardware(self):
result = {"cores": "unknown", "freq": "unknown", "ram": "unknown"}
try:
cores = psutil.cpu_count()
cpu_freq = psutil.cpu_freq()
ram = psutil.virtual_memory()
if cores:
result["cores"] = cores
if cpu_freq and hasattr(cpu_freq, "max"):
result["freq"] = cpu_freq.max
if ram and hasattr(ram, "total"):
result["ram"] = ram.total
except Exception:
self._logger.exception("Error while detecting hardware environment")
try:
cores = psutil.cpu_count()
cpu_freq = psutil.cpu_freq()
ram = psutil.virtual_memory()
if cores:
result["cores"] = cores
if cpu_freq and hasattr(cpu_freq, "max"):
result["freq"] = cpu_freq.max
if ram and hasattr(ram, "total"):
result["ram"] = ram.total
except Exception:
self._logger.exception("Error while detecting hardware environment")
return result
return result
def _detect_from_plugins(self):
result = {}
def _detect_from_plugins(self):
result = {}
for implementation in self._environment_plugins:
try:
additional = implementation.get_additional_environment()
if additional is not None and isinstance(additional, dict) and len(additional):
result[implementation._identifier] = additional
except Exception:
self._logger.exception("Error while fetching additional "
"environment data from plugin {}".format(implementation._identifier),
extra={"plugin": implementation._identifier})
for implementation in self._environment_plugins:
try:
additional = implementation.get_additional_environment()
if (
additional is not None
and isinstance(additional, dict)
and len(additional)
):
result[implementation._identifier] = additional
except Exception:
self._logger.exception(
"Error while fetching additional "
"environment data from plugin {}".format(implementation._identifier),
extra={"plugin": implementation._identifier},
)
return result
return result
def log_detected_environment(self, only_to_handler=None):
def _log(message, level=logging.INFO):
if only_to_handler is not None:
import octoprint.logging
octoprint.logging.log_to_handler(self._logger, only_to_handler, level, message, [])
else:
self._logger.log(level, message)
def log_detected_environment(self, only_to_handler=None):
def _log(message, level=logging.INFO):
if only_to_handler is not None:
import octoprint.logging
try:
_log(self._format())
except Exception:
self._logger.exception("Error logging detected environment")
octoprint.logging.log_to_handler(
self._logger, only_to_handler, level, message, []
)
else:
self._logger.log(level, message)
def _format(self):
with self._cache_lock:
if self._cache is None:
self.run_detection()
environment = copy.deepcopy(self._cache)
try:
_log(self._format())
except Exception:
self._logger.exception("Error logging detected environment")
dumped_environment = yaml.safe_dump(environment,
default_flow_style=False,
indent=4,
allow_unicode=True).strip()
environment_lines = "\n".join(map(lambda l: "| {}".format(l), dumped_environment.split("\n")))
return "Detected environment is Python {} under {} ({}). Details:\n{}".format(environment["python"]["version"],
environment["os"]["id"].title(),
environment["os"]["platform"],
environment_lines)
def _format(self):
with self._cache_lock:
if self._cache is None:
self.run_detection()
environment = copy.deepcopy(self._cache)
def notify_plugins(self):
with self._cache_lock:
if self._cache is None:
self.run_detection(notify_plugins=False)
environment = copy.deepcopy(self._cache)
dumped_environment = yaml.safe_dump(
environment, default_flow_style=False, indent=4, allow_unicode=True
).strip()
environment_lines = "\n".join(
map(lambda l: "| {}".format(l), dumped_environment.split("\n"))
)
return "Detected environment is Python {} under {} ({}). Details:\n{}".format(
environment["python"]["version"],
environment["os"]["id"].title(),
environment["os"]["platform"],
environment_lines,
)
for implementation in self._environment_plugins:
try:
implementation.on_environment_detected(environment)
except Exception:
self._logger.exception("Error while sending environment "
"detection result to plugin {}".format(implementation._identifier))
def notify_plugins(self):
with self._cache_lock:
if self._cache is None:
self.run_detection(notify_plugins=False)
environment = copy.deepcopy(self._cache)
for implementation in self._environment_plugins:
try:
implementation.on_environment_detected(environment)
except Exception:
self._logger.exception(
"Error while sending environment "
"detection result to plugin {}".format(implementation._identifier)
)
+423 -371
View File
@@ -2,16 +2,17 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>, Lars Norpchen"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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"
import datetime
import logging
import subprocess
try:
import queue
import queue
except ImportError:
import Queue as queue
import Queue as queue
import threading
import collections
import re
@@ -24,465 +25,516 @@ _instance = None
def all_events():
return [getattr(Events, name) for name in Events.__dict__ if not name.startswith("_") and not name in ("register_event",)]
return [
getattr(Events, name)
for name in Events.__dict__
if not name.startswith("_") and not name in ("register_event",)
]
class Events(object):
# server
STARTUP = "Startup"
SHUTDOWN = "Shutdown"
CONNECTIVITY_CHANGED = "ConnectivityChanged"
# server
STARTUP = "Startup"
SHUTDOWN = "Shutdown"
CONNECTIVITY_CHANGED = "ConnectivityChanged"
# connect/disconnect to printer
CONNECTING = "Connecting"
CONNECTED = "Connected"
DISCONNECTING = "Disconnecting"
DISCONNECTED = "Disconnected"
# connect/disconnect to printer
CONNECTING = "Connecting"
CONNECTED = "Connected"
DISCONNECTING = "Disconnecting"
DISCONNECTED = "Disconnected"
# State changes
PRINTER_STATE_CHANGED = "PrinterStateChanged"
PRINTER_RESET = "PrinterReset"
# State changes
PRINTER_STATE_CHANGED = "PrinterStateChanged"
PRINTER_RESET = "PrinterReset"
# connect/disconnect by client
CLIENT_OPENED = "ClientOpened"
CLIENT_CLOSED = "ClientClosed"
CLIENT_AUTHED = "ClientAuthed"
CLIENT_DEAUTHED = "ClientDeauthed"
# connect/disconnect by client
CLIENT_OPENED = "ClientOpened"
CLIENT_CLOSED = "ClientClosed"
CLIENT_AUTHED = "ClientAuthed"
CLIENT_DEAUTHED = "ClientDeauthed"
# user login/logout
USER_LOGGED_IN = "UserLoggedIn"
USER_LOGGED_OUT = "UserLoggedOut"
# user login/logout
USER_LOGGED_IN = "UserLoggedIn"
USER_LOGGED_OUT = "UserLoggedOut"
# File management
UPLOAD = "Upload"
FILE_SELECTED = "FileSelected"
FILE_DESELECTED = "FileDeselected"
UPDATED_FILES = "UpdatedFiles"
METADATA_ANALYSIS_STARTED = "MetadataAnalysisStarted"
METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished"
METADATA_STATISTICS_UPDATED = "MetadataStatisticsUpdated"
# File management
UPLOAD = "Upload"
FILE_SELECTED = "FileSelected"
FILE_DESELECTED = "FileDeselected"
UPDATED_FILES = "UpdatedFiles"
METADATA_ANALYSIS_STARTED = "MetadataAnalysisStarted"
METADATA_ANALYSIS_FINISHED = "MetadataAnalysisFinished"
METADATA_STATISTICS_UPDATED = "MetadataStatisticsUpdated"
FILE_ADDED = "FileAdded"
FILE_REMOVED = "FileRemoved"
FOLDER_ADDED = "FolderAdded"
FOLDER_REMOVED = "FolderRemoved"
FILE_ADDED = "FileAdded"
FILE_REMOVED = "FileRemoved"
FOLDER_ADDED = "FolderAdded"
FOLDER_REMOVED = "FolderRemoved"
# SD Upload
TRANSFER_STARTED = "TransferStarted"
TRANSFER_DONE = "TransferDone"
TRANSFER_FAILED = "TransferFailed"
# SD Upload
TRANSFER_STARTED = "TransferStarted"
TRANSFER_DONE = "TransferDone"
TRANSFER_FAILED = "TransferFailed"
# print job
PRINT_STARTED = "PrintStarted"
PRINT_DONE = "PrintDone"
PRINT_FAILED = "PrintFailed"
PRINT_CANCELLING = "PrintCancelling"
PRINT_CANCELLED = "PrintCancelled"
PRINT_PAUSED = "PrintPaused"
PRINT_RESUMED = "PrintResumed"
ERROR = "Error"
# print job
PRINT_STARTED = "PrintStarted"
PRINT_DONE = "PrintDone"
PRINT_FAILED = "PrintFailed"
PRINT_CANCELLING = "PrintCancelling"
PRINT_CANCELLED = "PrintCancelled"
PRINT_PAUSED = "PrintPaused"
PRINT_RESUMED = "PrintResumed"
ERROR = "Error"
# print/gcode events
POWER_ON = "PowerOn"
POWER_OFF = "PowerOff"
HOME = "Home"
Z_CHANGE = "ZChange"
WAITING = "Waiting"
DWELL = "Dwelling"
COOLING = "Cooling"
ALERT = "Alert"
CONVEYOR = "Conveyor"
EJECT = "Eject"
E_STOP = "EStop"
POSITION_UPDATE = "PositionUpdate"
FIRMWARE_DATA = "FirmwareData"
TOOL_CHANGE = "ToolChange"
REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived"
# print/gcode events
POWER_ON = "PowerOn"
POWER_OFF = "PowerOff"
HOME = "Home"
Z_CHANGE = "ZChange"
WAITING = "Waiting"
DWELL = "Dwelling"
COOLING = "Cooling"
ALERT = "Alert"
CONVEYOR = "Conveyor"
EJECT = "Eject"
E_STOP = "EStop"
POSITION_UPDATE = "PositionUpdate"
FIRMWARE_DATA = "FirmwareData"
TOOL_CHANGE = "ToolChange"
REGISTERED_MESSAGE_RECEIVED = "RegisteredMessageReceived"
# Timelapse
CAPTURE_START = "CaptureStart"
CAPTURE_DONE = "CaptureDone"
CAPTURE_FAILED = "CaptureFailed"
POSTROLL_START = "PostRollStart"
POSTROLL_END = "PostRollEnd"
MOVIE_RENDERING = "MovieRendering"
MOVIE_DONE = "MovieDone"
MOVIE_FAILED = "MovieFailed"
# Timelapse
CAPTURE_START = "CaptureStart"
CAPTURE_DONE = "CaptureDone"
CAPTURE_FAILED = "CaptureFailed"
POSTROLL_START = "PostRollStart"
POSTROLL_END = "PostRollEnd"
MOVIE_RENDERING = "MovieRendering"
MOVIE_DONE = "MovieDone"
MOVIE_FAILED = "MovieFailed"
# Slicing
SLICING_STARTED = "SlicingStarted"
SLICING_DONE = "SlicingDone"
SLICING_FAILED = "SlicingFailed"
SLICING_CANCELLED = "SlicingCancelled"
SLICING_PROFILE_ADDED = "SlicingProfileAdded"
SLICING_PROFILE_MODIFIED = "SlicingProfileModified"
SLICING_PROFILE_DELETED = "SlicingProfileDeleted"
# Slicing
SLICING_STARTED = "SlicingStarted"
SLICING_DONE = "SlicingDone"
SLICING_FAILED = "SlicingFailed"
SLICING_CANCELLED = "SlicingCancelled"
SLICING_PROFILE_ADDED = "SlicingProfileAdded"
SLICING_PROFILE_MODIFIED = "SlicingProfileModified"
SLICING_PROFILE_DELETED = "SlicingProfileDeleted"
# Printer Profiles
PRINTER_PROFILE_ADDED = "PrinterProfileAdded"
PRINTER_PROFILE_MODIFIED = "PrinterProfileModified"
PRINTER_PROFILE_DELETED = "PrinterProfileDeleted"
# Printer Profiles
PRINTER_PROFILE_ADDED = "PrinterProfileAdded"
PRINTER_PROFILE_MODIFIED = "PrinterProfileModified"
PRINTER_PROFILE_DELETED = "PrinterProfileDeleted"
# Settings
SETTINGS_UPDATED = "SettingsUpdated"
# Settings
SETTINGS_UPDATED = "SettingsUpdated"
@classmethod
def register_event(cls, event, prefix=None):
name = cls._to_identifier(event)
if prefix:
event = prefix + event
name = cls._to_identifier(prefix) + name
setattr(cls, name, event)
return name, event
@classmethod
def register_event(cls, event, prefix=None):
name = cls._to_identifier(event)
if prefix:
event = prefix + event
name = cls._to_identifier(prefix) + name
setattr(cls, name, event)
return name, event
# based on https://stackoverflow.com/a/1176023
_first_cap_re = re.compile('(.)([A-Z][a-z]+)')
_all_cap_re = re.compile('([a-z0-9])([A-Z])')
# based on https://stackoverflow.com/a/1176023
_first_cap_re = re.compile("(.)([A-Z][a-z]+)")
_all_cap_re = re.compile("([a-z0-9])([A-Z])")
@classmethod
def _to_identifier(cls, name):
s1 = cls._first_cap_re.sub(r"\1_\2", name)
return cls._all_cap_re.sub(r"\1_\2", s1).upper()
@classmethod
def _to_identifier(cls, name):
s1 = cls._first_cap_re.sub(r'\1_\2', name)
return cls._all_cap_re.sub(r'\1_\2', s1).upper()
def eventManager():
global _instance
if _instance is None:
_instance = EventManager()
return _instance
global _instance
if _instance is None:
_instance = EventManager()
return _instance
class EventManager(object):
"""
Handles receiving events and dispatching them to subscribers
"""
"""
Handles receiving events and dispatching them to subscribers
"""
def __init__(self):
self._registeredListeners = collections.defaultdict(list)
self._logger = logging.getLogger(__name__)
self._logger_fire = logging.getLogger("{}.fire".format(__name__))
def __init__(self):
self._registeredListeners = collections.defaultdict(list)
self._logger = logging.getLogger(__name__)
self._logger_fire = logging.getLogger("{}.fire".format(__name__))
self._startup_signaled = False
self._shutdown_signaled = False
self._startup_signaled = False
self._shutdown_signaled = False
self._queue = queue.Queue()
self._held_back = queue.Queue()
self._queue = queue.Queue()
self._held_back = queue.Queue()
self._worker = threading.Thread(target=self._work)
self._worker.daemon = True
self._worker.start()
self._worker = threading.Thread(target=self._work)
self._worker.daemon = True
self._worker.start()
def _work(self):
try:
while not self._shutdown_signaled:
event, payload = self._queue.get(True)
if event == Events.SHUTDOWN:
# we've got the shutdown event here, stop event loop processing after this has been processed
self._logger.info("Processing shutdown event, this will be our last event")
self._shutdown_signaled = True
def _work(self):
try:
while not self._shutdown_signaled:
event, payload = self._queue.get(True)
if event == Events.SHUTDOWN:
# we've got the shutdown event here, stop event loop processing after this has been processed
self._logger.info(
"Processing shutdown event, this will be our last event"
)
self._shutdown_signaled = True
eventListeners = self._registeredListeners[event]
self._logger_fire.debug("Firing event: {} (Payload: {!r})".format(event, payload))
eventListeners = self._registeredListeners[event]
self._logger_fire.debug(
"Firing event: {} (Payload: {!r})".format(event, payload)
)
for listener in eventListeners:
self._logger.debug("Sending action to {!r}".format(listener))
try:
listener(event, payload)
except Exception:
self._logger.exception("Got an exception while sending event {} (Payload: {!r}) to {}".format(event, payload, listener))
for listener in eventListeners:
self._logger.debug("Sending action to {!r}".format(listener))
try:
listener(event, payload)
except Exception:
self._logger.exception(
"Got an exception while sending event {} (Payload: {!r}) to {}".format(
event, payload, listener
)
)
octoprint.plugin.call_plugin(octoprint.plugin.types.EventHandlerPlugin,
"on_event",
args=(event, payload))
self._logger.info("Event loop shut down")
except Exception:
self._logger.exception("Ooops, the event bus worker loop crashed")
octoprint.plugin.call_plugin(
octoprint.plugin.types.EventHandlerPlugin,
"on_event",
args=(event, payload),
)
self._logger.info("Event loop shut down")
except Exception:
self._logger.exception("Ooops, the event bus worker loop crashed")
def fire(self, event, payload=None):
"""
Fire an event to anyone subscribed to it
def fire(self, event, payload=None):
"""
Fire an event to anyone subscribed to it
Any object can generate an event and any object can subscribe to the event's name as a string (arbitrary, but
case sensitive) and any extra payload data that may pertain to the event.
Any object can generate an event and any object can subscribe to the event's name as a string (arbitrary, but
case sensitive) and any extra payload data that may pertain to the event.
Callbacks must implement the signature "callback(event, payload)", with "event" being the event's name and
payload being a payload object specific to the event.
"""
Callbacks must implement the signature "callback(event, payload)", with "event" being the event's name and
payload being a payload object specific to the event.
"""
send_held_back = False
if event == Events.STARTUP:
self._logger.info("Processing startup event, this is our first event")
self._startup_signaled = True
send_held_back = True
send_held_back = False
if event == Events.STARTUP:
self._logger.info("Processing startup event, this is our first event")
self._startup_signaled = True
send_held_back = True
self._enqueue(event, payload)
self._enqueue(event, payload)
if send_held_back:
self._logger.info("Adding {} events to queue that "
"were held back before startup event".format(self._held_back.qsize()))
while True:
try:
self._queue.put(self._held_back.get(block=False))
except queue.Empty:
break
if send_held_back:
self._logger.info(
"Adding {} events to queue that "
"were held back before startup event".format(self._held_back.qsize())
)
while True:
try:
self._queue.put(self._held_back.get(block=False))
except queue.Empty:
break
def _enqueue(self, event, payload):
if self._startup_signaled:
q = self._queue
else:
q = self._held_back
def _enqueue(self, event, payload):
if self._startup_signaled:
q = self._queue
else:
q = self._held_back
q.put((event, payload))
q.put((event, payload))
def subscribe(self, event, callback):
"""
Subscribe a listener to an event -- pass in the event name (as a string) and the callback object
"""
def subscribe(self, event, callback):
"""
Subscribe a listener to an event -- pass in the event name (as a string) and the callback object
"""
if callback in self._registeredListeners[event]:
# callback is already subscribed to the event
return
if callback in self._registeredListeners[event]:
# callback is already subscribed to the event
return
self._registeredListeners[event].append(callback)
self._logger.debug("Subscribed listener {!r} for event {}".format(callback, event))
self._registeredListeners[event].append(callback)
self._logger.debug(
"Subscribed listener {!r} for event {}".format(callback, event)
)
def unsubscribe (self, event, callback):
"""
Unsubscribe a listener from an event -- pass in the event name (as string) and the callback object
"""
def unsubscribe(self, event, callback):
"""
Unsubscribe a listener from an event -- pass in the event name (as string) and the callback object
"""
try:
self._registeredListeners[event].remove(callback)
except ValueError:
# not registered
pass
try:
self._registeredListeners[event].remove(callback)
except ValueError:
# not registered
pass
def join(self, timeout=None):
self._worker.join(timeout)
return self._worker.is_alive()
def join(self, timeout=None):
self._worker.join(timeout)
return self._worker.is_alive()
class GenericEventListener(object):
"""
The GenericEventListener can be subclassed to easily create custom event listeners.
"""
"""
The GenericEventListener can be subclassed to easily create custom event listeners.
"""
def __init__(self):
self._logger = logging.getLogger(__name__)
def __init__(self):
self._logger = logging.getLogger(__name__)
def subscribe(self, events):
"""
Subscribes the eventCallback method for all events in the given list.
"""
def subscribe(self, events):
"""
Subscribes the eventCallback method for all events in the given list.
"""
for event in events:
eventManager().subscribe(event, self.eventCallback)
for event in events:
eventManager().subscribe(event, self.eventCallback)
def unsubscribe(self, events):
"""
Unsubscribes the eventCallback method for all events in the given list
"""
def unsubscribe(self, events):
"""
Unsubscribes the eventCallback method for all events in the given list
"""
for event in events:
eventManager().unsubscribe(event, self.eventCallback)
for event in events:
eventManager().unsubscribe(event, self.eventCallback)
def eventCallback(self, event, payload):
"""
Actual event callback called with name of event and optional payload. Not implemented here, override in
child classes.
"""
pass
def eventCallback(self, event, payload):
"""
Actual event callback called with name of event and optional payload. Not implemented here, override in
child classes.
"""
pass
class DebugEventListener(GenericEventListener):
def __init__(self):
GenericEventListener.__init__(self)
def __init__(self):
GenericEventListener.__init__(self)
events = list(filter(lambda x: not x.startswith("__"), dir(Events)))
self.subscribe(events)
events = list(filter(lambda x: not x.startswith("__"), dir(Events)))
self.subscribe(events)
def eventCallback(self, event, payload):
GenericEventListener.eventCallback(self, event, payload)
self._logger.debug("Received event: %s (Payload: %r)" % (event, payload))
def eventCallback(self, event, payload):
GenericEventListener.eventCallback(self, event, payload)
self._logger.debug("Received event: %s (Payload: %r)" % (event, payload))
class CommandTrigger(GenericEventListener):
def __init__(self, printer):
GenericEventListener.__init__(self)
self._printer = printer
self._subscriptions = {}
def __init__(self, printer):
GenericEventListener.__init__(self)
self._printer = printer
self._subscriptions = {}
self._initSubscriptions()
self._initSubscriptions()
def _initSubscriptions(self):
"""
Subscribes all events as defined in "events > $triggerType > subscriptions" in the settings with their
respective commands.
"""
if not settings().get(["events"]):
return
def _initSubscriptions(self):
"""
Subscribes all events as defined in "events > $triggerType > subscriptions" in the settings with their
respective commands.
"""
if not settings().get(["events"]):
return
if not settings().getBoolean(["events", "enabled"]):
return
if not settings().getBoolean(["events", "enabled"]):
return
eventsToSubscribe = []
subscriptions = settings().get(["events", "subscriptions"])
for subscription in subscriptions:
if not isinstance(subscription, dict):
self._logger.info("Invalid subscription definition, not a dictionary: {!r}".format(subscription))
continue
eventsToSubscribe = []
subscriptions = settings().get(["events", "subscriptions"])
for subscription in subscriptions:
if not isinstance(subscription, dict):
self._logger.info(
"Invalid subscription definition, not a dictionary: {!r}".format(
subscription
)
)
continue
if not "event" in subscription or not "command" in subscription \
or not "type" in subscription or not subscription["type"] in ["system", "gcode"]:
self._logger.info("Invalid command trigger, missing either event, type or command or type is invalid: {!r}".format(subscription))
continue
if (
not "event" in subscription
or not "command" in subscription
or not "type" in subscription
or not subscription["type"] in ["system", "gcode"]
):
self._logger.info(
"Invalid command trigger, missing either event, type or command or type is invalid: {!r}".format(
subscription
)
)
continue
if "enabled" in subscription and not subscription["enabled"]:
self._logger.info("Disabled command trigger: {!r}".format(subscription))
continue
if "enabled" in subscription and not subscription["enabled"]:
self._logger.info("Disabled command trigger: {!r}".format(subscription))
continue
events = subscription["event"]
command = subscription["command"]
commandType = subscription["type"]
debug = subscription["debug"] if "debug" in subscription else False
events = subscription["event"]
command = subscription["command"]
commandType = subscription["type"]
debug = subscription["debug"] if "debug" in subscription else False
# "event" in the configuration can be a string, or
# a list of strings. If it's the former, convert it
# into the latter.
if not isinstance(events, (tuple, list, set)):
events = [events]
# "event" in the configuration can be a string, or
# a list of strings. If it's the former, convert it
# into the latter.
if not isinstance(events, (tuple, list, set)):
events = [events]
for event in events:
if event not in self._subscriptions:
self._subscriptions[event] = []
self._subscriptions[event].append((command, commandType, debug))
for event in events:
if event not in self._subscriptions:
self._subscriptions[event] = []
self._subscriptions[event].append((command, commandType, debug))
if event not in eventsToSubscribe:
eventsToSubscribe.append(event)
if event not in eventsToSubscribe:
eventsToSubscribe.append(event)
self.subscribe(eventsToSubscribe)
self.subscribe(eventsToSubscribe)
def eventCallback(self, event, payload):
"""
Event callback, iterates over all subscribed commands for the given event, processes the command
string and then executes the command via the abstract executeCommand method.
"""
def eventCallback(self, event, payload):
"""
Event callback, iterates over all subscribed commands for the given event, processes the command
string and then executes the command via the abstract executeCommand method.
"""
GenericEventListener.eventCallback(self, event, payload)
GenericEventListener.eventCallback(self, event, payload)
if not event in self._subscriptions:
return
if not event in self._subscriptions:
return
for command, commandType, debug in self._subscriptions[event]:
try:
if isinstance(command, (tuple, list, set)):
processedCommand = []
for c in command:
processedCommand.append(self._processCommand(c, event, payload))
else:
processedCommand = self._processCommand(command, event, payload)
self.executeCommand(processedCommand, commandType, debug=debug)
except KeyError:
self._logger.warning("There was an error processing one or more placeholders in the following command: %s" % command)
for command, commandType, debug in self._subscriptions[event]:
try:
if isinstance(command, (tuple, list, set)):
processedCommand = []
for c in command:
processedCommand.append(self._processCommand(c, event, payload))
else:
processedCommand = self._processCommand(command, event, payload)
self.executeCommand(processedCommand, commandType, debug=debug)
except KeyError:
self._logger.warning(
"There was an error processing one or more placeholders in the following command: %s"
% command
)
def executeCommand(self, command, commandType, debug=False):
if commandType == "system":
self._executeSystemCommand(command, debug=debug)
elif commandType == "gcode":
self._executeGcodeCommand(command, debug=debug)
def executeCommand(self, command, commandType, debug=False):
if commandType == "system":
self._executeSystemCommand(command, debug=debug)
elif commandType == "gcode":
self._executeGcodeCommand(command, debug=debug)
def _executeSystemCommand(self, command, debug=False):
def commandExecutioner(cmd):
if debug:
self._logger.info("Executing system command: {}".format(cmd))
else:
self._logger.info("Executing a system command")
# we run this with shell=True since we have to trust whatever
# our admin configured as command and since we want to allow
# shell-alike handling here...
subprocess.check_call(cmd, shell=True)
def _executeSystemCommand(self, command, debug=False):
def commandExecutioner(cmd):
if debug:
self._logger.info("Executing system command: {}".format(cmd))
else:
self._logger.info("Executing a system command")
# we run this with shell=True since we have to trust whatever
# our admin configured as command and since we want to allow
# shell-alike handling here...
subprocess.check_call(cmd, shell=True)
def process():
try:
if isinstance(command, (list, tuple, set)):
for c in command:
commandExecutioner(c)
else:
commandExecutioner(command)
except subprocess.CalledProcessError as e:
if debug:
self._logger.warning("Command failed with return code {}: {}".format(e.returncode, str(e)))
else:
self._logger.warning("Command failed with return code {}, enable debug logging on target 'octoprint.events' for details".format(e.returncode))
except Exception:
self._logger.exception("Command failed")
def process():
try:
if isinstance(command, (list, tuple, set)):
for c in command:
commandExecutioner(c)
else:
commandExecutioner(command)
except subprocess.CalledProcessError as e:
if debug:
self._logger.warning(
"Command failed with return code {}: {}".format(
e.returncode, str(e)
)
)
else:
self._logger.warning(
"Command failed with return code {}, enable debug logging on target 'octoprint.events' for details".format(
e.returncode
)
)
except Exception:
self._logger.exception("Command failed")
t = threading.Thread(target=process)
t.daemon = True
t.start()
t = threading.Thread(target=process)
t.daemon = True
t.start()
def _executeGcodeCommand(self, command, debug=False):
commands = [command]
if isinstance(command, (list, tuple, set)):
commands = list(command)
if debug:
self._logger.info("Executing GCode commands: %r" % command)
self._printer.commands(commands)
def _executeGcodeCommand(self, command, debug=False):
commands = [command]
if isinstance(command, (list, tuple, set)):
commands = list(command)
if debug:
self._logger.info("Executing GCode commands: %r" % command)
self._printer.commands(commands)
def _processCommand(self, command, event, payload):
"""
Performs string substitutions in the command string based on a few current parameters.
def _processCommand(self, command, event, payload):
"""
Performs string substitutions in the command string based on a few current parameters.
The following substitutions are currently supported:
The following substitutions are currently supported:
- {__currentZ} : current Z position of the print head, or -1 if not available
- {__eventname} : the name of the event hook being triggered
- {__filename} : name of currently selected file, or "NO FILE" if no file is selected
- {__filepath} : path in origin location of currently selected file, or "NO FILE" if no file is selected
- {__fileorigin} : origin of currently selected file, or "NO FILE" if no file is selected
- {__progress} : current print progress in percent, 0 if no print is in progress
- {__data} : the string representation of the event's payload
- {__json} : the json representation of the event's payload, "{}" if there is no payload, "" if there was an error on serialization
- {__now} : ISO 8601 representation of the current date and time
- {__currentZ} : current Z position of the print head, or -1 if not available
- {__eventname} : the name of the event hook being triggered
- {__filename} : name of currently selected file, or "NO FILE" if no file is selected
- {__filepath} : path in origin location of currently selected file, or "NO FILE" if no file is selected
- {__fileorigin} : origin of currently selected file, or "NO FILE" if no file is selected
- {__progress} : current print progress in percent, 0 if no print is in progress
- {__data} : the string representation of the event's payload
- {__json} : the json representation of the event's payload, "{}" if there is no payload, "" if there was an error on serialization
- {__now} : ISO 8601 representation of the current date and time
Additionally, the keys of the event's payload can also be used as placeholder.
"""
Additionally, the keys of the event's payload can also be used as placeholder.
"""
json_string = "{}"
if payload:
import json
try:
json_string = json.dumps(payload)
except Exception:
self._logger.exception("JSON: Cannot dump %r", payload)
json_string = ""
json_string = "{}"
if payload:
import json
params = {
"__currentZ": "-1",
"__eventname": event,
"__filename": "NO FILE",
"__filepath": "NO PATH",
"__progress": "0",
"__data": str(payload),
"__json": json_string,
"__now": datetime.datetime.now().isoformat()
}
try:
json_string = json.dumps(payload)
except Exception:
self._logger.exception("JSON: Cannot dump %r", payload)
json_string = ""
currentData = self._printer.get_current_data()
params = {
"__currentZ": "-1",
"__eventname": event,
"__filename": "NO FILE",
"__filepath": "NO PATH",
"__progress": "0",
"__data": str(payload),
"__json": json_string,
"__now": datetime.datetime.now().isoformat(),
}
if "currentZ" in currentData and currentData["currentZ"] is not None:
params["__currentZ"] = str(currentData["currentZ"])
currentData = self._printer.get_current_data()
if "job" in currentData and "file" in currentData["job"] and "name" in currentData["job"]["file"] \
and currentData["job"]["file"]["name"] is not None:
params["__filename"] = currentData["job"]["file"]["name"]
params["__filepath"] = currentData["job"]["file"]["path"]
params["__fileorigin"] = currentData["job"]["file"]["origin"]
if "progress" in currentData and currentData["progress"] is not None \
and "completion" in currentData["progress"] and currentData["progress"]["completion"] is not None:
params["__progress"] = str(round(currentData["progress"]["completion"]))
if "currentZ" in currentData and currentData["currentZ"] is not None:
params["__currentZ"] = str(currentData["currentZ"])
# now add the payload keys as well
if isinstance(payload, dict):
params.update(payload)
if (
"job" in currentData
and "file" in currentData["job"]
and "name" in currentData["job"]["file"]
and currentData["job"]["file"]["name"] is not None
):
params["__filename"] = currentData["job"]["file"]["name"]
params["__filepath"] = currentData["job"]["file"]["path"]
params["__fileorigin"] = currentData["job"]["file"]["origin"]
if (
"progress" in currentData
and currentData["progress"] is not None
and "completion" in currentData["progress"]
and currentData["progress"]["completion"] is not None
):
params["__progress"] = str(round(currentData["progress"]["completion"]))
return command.format(**params)
# now add the payload keys as well
if isinstance(payload, dict):
params.update(payload)
return command.format(**params)
File diff suppressed because it is too large. Load diff
+402 -336
View File
@@ -2,15 +2,16 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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"
import logging
try:
import queue
import queue
except ImportError:
import Queue as queue
import Queue as queue
import os
import threading
import collections
@@ -23,417 +24,482 @@ from octoprint.util import get_fully_qualified_classname as fqcn, dict_merge
from octoprint.util.platform import CLOSE_FDS
class QueueEntry(collections.namedtuple("QueueEntry", "name, path, type, location, absolute_path, printer_profile, analysis")):
"""
A :class:`QueueEntry` for processing through the :class:`AnalysisQueue`. Wraps the entry's properties necessary
for processing.
class QueueEntry(
collections.namedtuple(
"QueueEntry",
"name, path, type, location, absolute_path, printer_profile, analysis",
)
):
"""
A :class:`QueueEntry` for processing through the :class:`AnalysisQueue`. Wraps the entry's properties necessary
for processing.
Arguments:
name (str): Name of the file to analyze.
path (str): Storage location specific path to the file to analyze.
type (str): Type of file to analyze, necessary to map to the correct :class:`AbstractAnalysisQueue` sub class.
At the moment, only ``gcode`` is supported here.
location (str): Location the file is located on.
absolute_path (str): Absolute path on disk through which to access the file.
printer_profile (PrinterProfile): :class:`PrinterProfile` which to use for analysis.
analysis (dict): :class:`GcodeAnalysisQueue` results from prior analysis, or ``None`` if there is none.
"""
Arguments:
name (str): Name of the file to analyze.
path (str): Storage location specific path to the file to analyze.
type (str): Type of file to analyze, necessary to map to the correct :class:`AbstractAnalysisQueue` sub class.
At the moment, only ``gcode`` is supported here.
location (str): Location the file is located on.
absolute_path (str): Absolute path on disk through which to access the file.
printer_profile (PrinterProfile): :class:`PrinterProfile` which to use for analysis.
analysis (dict): :class:`GcodeAnalysisQueue` results from prior analysis, or ``None`` if there is none.
"""
def __str__(self):
return "{location}:{path}".format(location=self.location, path=self.path)
def __str__(self):
return "{location}:{path}".format(location=self.location, path=self.path)
class AnalysisAborted(Exception):
def __init__(self, reenqueue=True, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
self.reenqueue = reenqueue
def __init__(self, reenqueue=True, *args, **kwargs):
Exception.__init__(self, *args, **kwargs)
self.reenqueue = reenqueue
class AnalysisQueue(object):
"""
OctoPrint's :class:`AnalysisQueue` can manage various :class:`AbstractAnalysisQueue` implementations, mapped
by their machine code type.
"""
OctoPrint's :class:`AnalysisQueue` can manage various :class:`AbstractAnalysisQueue` implementations, mapped
by their machine code type.
By invoking :meth:`register_finish_callback` it is possible to register oneself as a callback to be invoked each
time the analysis of a queue entry finishes. The call parameters will be the finished queue entry as the first
and the analysis result as the second parameter. It is also possible to remove the registration again by invoking
:meth:`unregister_finish_callback`.
By invoking :meth:`register_finish_callback` it is possible to register oneself as a callback to be invoked each
time the analysis of a queue entry finishes. The call parameters will be the finished queue entry as the first
and the analysis result as the second parameter. It is also possible to remove the registration again by invoking
:meth:`unregister_finish_callback`.
:meth:`enqueue` allows enqueuing :class:`QueueEntry` instances to analyze. If the :attr:`QueueEntry.type` is unknown
(no specific child class of :class:`AbstractAnalysisQueue` is registered for it), nothing will happen. Otherwise the
entry will be enqueued with the type specific analysis queue.
"""
:meth:`enqueue` allows enqueuing :class:`QueueEntry` instances to analyze. If the :attr:`QueueEntry.type` is unknown
(no specific child class of :class:`AbstractAnalysisQueue` is registered for it), nothing will happen. Otherwise the
entry will be enqueued with the type specific analysis queue.
"""
def __init__(self, queue_factories):
self._logger = logging.getLogger(__name__)
self._callbacks = []
def __init__(self, queue_factories):
self._logger = logging.getLogger(__name__)
self._callbacks = []
self._queues = {}
for key, queue_factory in queue_factories.items():
self._queues[key] = queue_factory(self._analysis_finished)
self._queues = {}
for key, queue_factory in queue_factories.items():
self._queues[key] = queue_factory(self._analysis_finished)
def register_finish_callback(self, callback):
self._callbacks.append(callback)
def register_finish_callback(self, callback):
self._callbacks.append(callback)
def unregister_finish_callback(self, callback):
self._callbacks.remove(callback)
def unregister_finish_callback(self, callback):
self._callbacks.remove(callback)
def enqueue(self, entry, high_priority=False):
if entry is None:
return False
def enqueue(self, entry, high_priority=False):
if entry is None:
return False
if not entry.type in self._queues:
return False
if not entry.type in self._queues:
return False
self._queues[entry.type].enqueue(entry, high_priority=high_priority)
return True
self._queues[entry.type].enqueue(entry, high_priority=high_priority)
return True
def dequeue(self, entry):
if entry is None:
return False
def dequeue(self, entry):
if entry is None:
return False
if not entry.type in self._queues:
return False
if not entry.type in self._queues:
return False
self._queues[entry.type].dequeue(entry.location, entry.path)
self._queues[entry.type].dequeue(entry.location, entry.path)
def dequeue_folder(self, destination, path):
for q in self._queues.values():
q.dequeue_folder(destination, path)
def dequeue_folder(self, destination, path):
for q in self._queues.values():
q.dequeue_folder(destination, path)
def pause(self):
for q in self._queues.values():
q.pause()
def pause(self):
for q in self._queues.values():
q.pause()
def resume(self):
for q in self._queues.values():
q.resume()
def resume(self):
for q in self._queues.values():
q.resume()
def _analysis_finished(self, entry, result):
for callback in self._callbacks:
try:
callback(entry, result)
except:
self._logger.exception(
"Error while pushing analysis data to callback {}".format(callback),
extra={"callback": fqcn(callback)},
)
eventManager().fire(
Events.METADATA_ANALYSIS_FINISHED,
{
"name": entry.name,
"path": entry.path,
"origin": entry.location,
"result": result,
},
)
def _analysis_finished(self, entry, result):
for callback in self._callbacks:
try:
callback(entry, result)
except:
self._logger.exception(u"Error while pushing analysis data to callback {}".format(callback),
extra={"callback": fqcn(callback)})
eventManager().fire(Events.METADATA_ANALYSIS_FINISHED, {"name": entry.name,
"path": entry.path,
"origin": entry.location,
"result": result})
class AbstractAnalysisQueue(object):
"""
The :class:`AbstractAnalysisQueue` is the parent class of all specific analysis queues such as the
:class:`GcodeAnalysisQueue`. It offers methods to enqueue new entries to analyze and pausing and resuming analysis
processing.
"""
The :class:`AbstractAnalysisQueue` is the parent class of all specific analysis queues such as the
:class:`GcodeAnalysisQueue`. It offers methods to enqueue new entries to analyze and pausing and resuming analysis
processing.
Arguments:
finished_callback (callable): Callback that will be called upon finishing analysis of an entry in the queue.
The callback will be called with the analyzed entry as the first argument and the analysis result as
returned from the queue implementation as the second parameter.
Arguments:
finished_callback (callable): Callback that will be called upon finishing analysis of an entry in the queue.
The callback will be called with the analyzed entry as the first argument and the analysis result as
returned from the queue implementation as the second parameter.
.. automethod:: _do_analysis
.. automethod:: _do_analysis
.. automethod:: _do_abort
"""
.. automethod:: _do_abort
"""
LOW_PRIO = 100
LOW_PRIO_ABORTED = 75
HIGH_PRIO = 50
HIGH_PRIO_ABORTED = 0
LOW_PRIO = 100
LOW_PRIO_ABORTED = 75
HIGH_PRIO = 50
HIGH_PRIO_ABORTED = 0
def __init__(self, finished_callback):
self._logger = logging.getLogger(__name__)
def __init__(self, finished_callback):
self._logger = logging.getLogger(__name__)
self._finished_callback = finished_callback
self._finished_callback = finished_callback
self._active = threading.Event()
self._active.set()
self._active = threading.Event()
self._active.set()
self._done = threading.Event()
self._done.clear()
self._done = threading.Event()
self._done.clear()
self._currentFile = None
self._currentProgress = None
self._currentFile = None
self._currentProgress = None
self._queue = queue.PriorityQueue()
self._current = None
self._current_highprio = False
self._queue = queue.PriorityQueue()
self._current = None
self._current_highprio = False
self._worker = threading.Thread(target=self._work)
self._worker.daemon = True
self._worker.start()
self._worker = threading.Thread(target=self._work)
self._worker.daemon = True
self._worker.start()
def enqueue(self, entry, high_priority=False):
"""
Enqueues an ``entry`` for analysis by the queue.
def enqueue(self, entry, high_priority=False):
"""
Enqueues an ``entry`` for analysis by the queue.
If ``high_priority`` is True (defaults to False), the entry will be prioritized and hence processed before
other entries in the queue with normal priority.
If ``high_priority`` is True (defaults to False), the entry will be prioritized and hence processed before
other entries in the queue with normal priority.
Arguments:
entry (QueueEntry): The :class:`QueueEntry` to analyze.
high_priority (boolean): Whether to process the provided entry with high priority (True) or not
(False, default)
"""
Arguments:
entry (QueueEntry): The :class:`QueueEntry` to analyze.
high_priority (boolean): Whether to process the provided entry with high priority (True) or not
(False, default)
"""
if settings().get(["gcodeAnalysis", "runAt"]) == "never":
self._logger.debug("Ignoring entry {entry} for analysis queue".format(entry=entry))
return
elif high_priority:
self._logger.debug("Adding entry {entry} to analysis queue with high priority".format(entry=entry))
prio = self.__class__.HIGH_PRIO
else:
self._logger.debug("Adding entry {entry} to analysis queue with low priority".format(entry=entry))
prio = self.__class__.LOW_PRIO
if settings().get(["gcodeAnalysis", "runAt"]) == "never":
self._logger.debug(
"Ignoring entry {entry} for analysis queue".format(entry=entry)
)
return
elif high_priority:
self._logger.debug(
"Adding entry {entry} to analysis queue with high priority".format(
entry=entry
)
)
prio = self.__class__.HIGH_PRIO
else:
self._logger.debug(
"Adding entry {entry} to analysis queue with low priority".format(
entry=entry
)
)
prio = self.__class__.LOW_PRIO
self._queue.put((prio, entry, high_priority))
if high_priority and self._current is not None and not self._current_highprio:
self._logger.debug("Aborting current analysis in favor of high priority one")
self._do_abort()
self._queue.put((prio, entry, high_priority))
if high_priority and self._current is not None and not self._current_highprio:
self._logger.debug("Aborting current analysis in favor of high priority one")
self._do_abort()
def dequeue(self, location, path):
if self._current is not None and self._current.location == location \
and self._current.path == path:
self._do_abort(reenqueue=False)
self._done.wait()
self._done.clear()
def dequeue(self, location, path):
if (
self._current is not None
and self._current.location == location
and self._current.path == path
):
self._do_abort(reenqueue=False)
self._done.wait()
self._done.clear()
def dequeue_folder(self, location, path):
if self._current is not None and self._current.location == location \
and self._current.path.startswith(path + "/"):
self._do_abort(reenqueue=False)
self._done.wait()
self._done.clear()
def dequeue_folder(self, location, path):
if (
self._current is not None
and self._current.location == location
and self._current.path.startswith(path + "/")
):
self._do_abort(reenqueue=False)
self._done.wait()
self._done.clear()
def pause(self):
"""
Pauses processing of the queue, e.g. when a print is active.
"""
def pause(self):
"""
Pauses processing of the queue, e.g. when a print is active.
"""
self._logger.debug("Pausing analysis")
self._active.clear()
if self._current is not None:
self._logger.debug("Aborting running analysis, will restart when analyzer is resumed")
self._do_abort()
self._logger.debug("Pausing analysis")
self._active.clear()
if self._current is not None:
self._logger.debug(
"Aborting running analysis, will restart when analyzer is resumed"
)
self._do_abort()
def resume(self):
"""
Resumes processing of the queue, e.g. when a print has finished.
"""
def resume(self):
"""
Resumes processing of the queue, e.g. when a print has finished.
"""
self._logger.debug("Resuming analyzer")
self._active.set()
self._logger.debug("Resuming analyzer")
self._active.set()
def _work(self):
while True:
(priority, entry, high_priority) = self._queue.get()
self._logger.debug("Processing entry {} from queue (priority {})".format(entry, priority))
self._active.wait()
def _work(self):
while True:
(priority, entry, high_priority) = self._queue.get()
self._logger.debug(
"Processing entry {} from queue (priority {})".format(entry, priority)
)
self._active.wait()
try:
self._analyze(entry, high_priority=high_priority)
self._queue.task_done()
self._done.set()
except AnalysisAborted as ex:
if ex.reenqueue:
self._queue.put((self.__class__.HIGH_PRIO_ABORTED if high_priority else self.__class__.LOW_PRIO_ABORTED,
entry,
high_priority))
self._logger.debug("Running analysis of entry {} aborted".format(entry))
self._queue.task_done()
self._done.set()
else:
time.sleep(1.0)
try:
self._analyze(entry, high_priority=high_priority)
self._queue.task_done()
self._done.set()
except AnalysisAborted as ex:
if ex.reenqueue:
self._queue.put(
(
self.__class__.HIGH_PRIO_ABORTED
if high_priority
else self.__class__.LOW_PRIO_ABORTED,
entry,
high_priority,
)
)
self._logger.debug("Running analysis of entry {} aborted".format(entry))
self._queue.task_done()
self._done.set()
else:
time.sleep(1.0)
def _analyze(self, entry, high_priority=False):
path = entry.absolute_path
if path is None or not os.path.exists(path):
return
def _analyze(self, entry, high_priority=False):
path = entry.absolute_path
if path is None or not os.path.exists(path):
return
self._current = entry
self._current_highprio = high_priority
self._current_progress = 0
self._current = entry
self._current_highprio = high_priority
self._current_progress = 0
try:
start_time = monotonic_time()
self._logger.info("Starting analysis of {}".format(entry))
eventManager().fire(Events.METADATA_ANALYSIS_STARTED, {"name": entry.name,
"path": entry.path,
"origin": entry.location,
"type": entry.type})
try:
result = self._do_analysis(high_priority=high_priority)
except TypeError:
result = self._do_analysis()
self._logger.info("Analysis of entry {} finished, needed {:.2f}s".format(entry, monotonic_time() - start_time))
self._finished_callback(self._current, result)
finally:
self._current = None
self._current_progress = None
try:
start_time = monotonic_time()
self._logger.info("Starting analysis of {}".format(entry))
eventManager().fire(
Events.METADATA_ANALYSIS_STARTED,
{
"name": entry.name,
"path": entry.path,
"origin": entry.location,
"type": entry.type,
},
)
try:
result = self._do_analysis(high_priority=high_priority)
except TypeError:
result = self._do_analysis()
self._logger.info(
"Analysis of entry {} finished, needed {:.2f}s".format(
entry, monotonic_time() - start_time
)
)
self._finished_callback(self._current, result)
finally:
self._current = None
self._current_progress = None
def _do_analysis(self, high_priority=False):
"""
Performs the actual analysis of the current entry which can be accessed via ``self._current``. Needs to be
overridden by sub classes.
def _do_analysis(self, high_priority=False):
"""
Performs the actual analysis of the current entry which can be accessed via ``self._current``. Needs to be
overridden by sub classes.
Arguments:
high_priority (bool): Whether the current entry has high priority or not.
Arguments:
high_priority (bool): Whether the current entry has high priority or not.
Returns:
object: The result of the analysis which will be forwarded to the ``finished_callback`` provided during
construction.
"""
return None
Returns:
object: The result of the analysis which will be forwarded to the ``finished_callback`` provided during
construction.
"""
return None
def _do_abort(self, reenqueue=True):
"""
Aborts analysis of the current entry. Needs to be overridden by sub classes.
"""
pass
def _do_abort(self, reenqueue=True):
"""
Aborts analysis of the current entry. Needs to be overridden by sub classes.
"""
pass
class GcodeAnalysisQueue(AbstractAnalysisQueue):
"""
A queue to analyze GCODE files. Analysis results are :class:`dict` instances structured as follows:
"""
A queue to analyze GCODE files. Analysis results are :class:`dict` instances structured as follows:
.. list-table::
:widths: 25 70
.. list-table::
:widths: 25 70
- * **Key**
* **Description**
- * ``estimatedPrintTime``
* Estimated time the file take to print, in seconds
- * ``filament``
* Substructure describing estimated filament usage. Keys are ``tool0`` for the first extruder, ``tool1`` for
the second and so on. For each tool extruded length and volume (based on diameter) are provided.
- * ``filament.toolX.length``
* The extruded length in mm
- * ``filament.toolX.volume``
* The extruded volume in cm³
- * ``printingArea``
* Bounding box of the printed object in the print volume (minimum and maximum coordinates)
- * ``printingArea.minX``
* Minimum X coordinate of the printed object
- * ``printingArea.maxX``
* Maximum X coordinate of the printed object
- * ``printingArea.minY``
* Minimum Y coordinate of the printed object
- * ``printingArea.maxY``
* Maximum Y coordinate of the printed object
- * ``printingArea.minZ``
* Minimum Z coordinate of the printed object
- * ``printingArea.maxZ``
* Maximum Z coordinate of the printed object
- * ``dimensions``
* Dimensions of the printed object in X, Y, Z
- * ``dimensions.width``
* Width of the printed model along the X axis, in mm
- * ``dimensions.depth``
* Depth of the printed model along the Y axis, in mm
- * ``dimensions.height``
* Height of the printed model along the Z axis, in mm
"""
- * **Key**
* **Description**
- * ``estimatedPrintTime``
* Estimated time the file take to print, in seconds
- * ``filament``
* Substructure describing estimated filament usage. Keys are ``tool0`` for the first extruder, ``tool1`` for
the second and so on. For each tool extruded length and volume (based on diameter) are provided.
- * ``filament.toolX.length``
* The extruded length in mm
- * ``filament.toolX.volume``
* The extruded volume in cm³
- * ``printingArea``
* Bounding box of the printed object in the print volume (minimum and maximum coordinates)
- * ``printingArea.minX``
* Minimum X coordinate of the printed object
- * ``printingArea.maxX``
* Maximum X coordinate of the printed object
- * ``printingArea.minY``
* Minimum Y coordinate of the printed object
- * ``printingArea.maxY``
* Maximum Y coordinate of the printed object
- * ``printingArea.minZ``
* Minimum Z coordinate of the printed object
- * ``printingArea.maxZ``
* Maximum Z coordinate of the printed object
- * ``dimensions``
* Dimensions of the printed object in X, Y, Z
- * ``dimensions.width``
* Width of the printed model along the X axis, in mm
- * ``dimensions.depth``
* Depth of the printed model along the Y axis, in mm
- * ``dimensions.height``
* Height of the printed model along the Z axis, in mm
"""
def __init__(self, finished_callback):
AbstractAnalysisQueue.__init__(self, finished_callback)
def __init__(self, finished_callback):
AbstractAnalysisQueue.__init__(self, finished_callback)
self._aborted = False
self._reenqueue = False
self._aborted = False
self._reenqueue = False
def _do_analysis(self, high_priority=False):
import sarge
import sys
import yaml
def _do_analysis(self, high_priority=False):
import sarge
import sys
import yaml
if self._current.analysis and all(map(lambda x: x in self._current.analysis, ("printingArea",
"dimensions",
"estimatedPrintTime",
"filament"))):
return self._current.analysis
if self._current.analysis and all(
map(
lambda x: x in self._current.analysis,
("printingArea", "dimensions", "estimatedPrintTime", "filament"),
)
):
return self._current.analysis
try:
throttle = settings().getFloat(["gcodeAnalysis", "throttle_highprio"]) if high_priority \
else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"])
max_extruders = settings().getInt(["gcodeAnalysis", "maxExtruders"])
g90_extruder = settings().getBoolean(["feature", "g90InfluencesExtruder"])
speedx = self._current.printer_profile["axes"]["x"]["speed"]
speedy = self._current.printer_profile["axes"]["y"]["speed"]
offsets = self._current.printer_profile["extruder"]["offsets"]
try:
throttle = (
settings().getFloat(["gcodeAnalysis", "throttle_highprio"])
if high_priority
else settings().getFloat(["gcodeAnalysis", "throttle_normalprio"])
)
throttle_lines = settings().getInt(["gcodeAnalysis", "throttle_lines"])
max_extruders = settings().getInt(["gcodeAnalysis", "maxExtruders"])
g90_extruder = settings().getBoolean(["feature", "g90InfluencesExtruder"])
speedx = self._current.printer_profile["axes"]["x"]["speed"]
speedy = self._current.printer_profile["axes"]["y"]["speed"]
offsets = self._current.printer_profile["extruder"]["offsets"]
command = [sys.executable, "-m", "octoprint", "analysis", "gcode",
"--speed-x={}".format(speedx), "--speed-y={}".format(speedy),
"--max-t={}".format(max_extruders), "--throttle={}".format(throttle),
"--throttle-lines={}".format(throttle_lines)]
for offset in offsets[1:]:
command += ["--offset", str(offset[0]), str(offset[1])]
if g90_extruder:
command += ["--g90-extruder"]
command.append(self._current.absolute_path)
command = [
sys.executable,
"-m",
"octoprint",
"analysis",
"gcode",
"--speed-x={}".format(speedx),
"--speed-y={}".format(speedy),
"--max-t={}".format(max_extruders),
"--throttle={}".format(throttle),
"--throttle-lines={}".format(throttle_lines),
]
for offset in offsets[1:]:
command += ["--offset", str(offset[0]), str(offset[1])]
if g90_extruder:
command += ["--g90-extruder"]
command.append(self._current.absolute_path)
self._logger.info("Invoking analysis command: {}".format(" ".join(command)))
self._logger.info("Invoking analysis command: {}".format(" ".join(command)))
self._aborted = False
p = sarge.run(command, close_fds=CLOSE_FDS, async_=True, stdout=sarge.Capture())
self._aborted = False
p = sarge.run(
command, close_fds=CLOSE_FDS, async_=True, stdout=sarge.Capture()
)
while len(p.commands) == 0:
# somewhat ugly... we can't use wait_events because
# the events might not be all set if an exception
# by sarge is triggered within the async process
# thread
time.sleep(0.01)
while len(p.commands) == 0:
# somewhat ugly... we can't use wait_events because
# the events might not be all set if an exception
# by sarge is triggered within the async process
# thread
time.sleep(0.01)
# by now we should have a command, let's wait for its
# process to have been prepared
p.commands[0].process_ready.wait()
# by now we should have a command, let's wait for its
# process to have been prepared
p.commands[0].process_ready.wait()
if not p.commands[0].process:
# the process might have been set to None in case of any exception
raise RuntimeError("Error while trying to run command {}".format(" ".join(command)))
if not p.commands[0].process:
# the process might have been set to None in case of any exception
raise RuntimeError(
"Error while trying to run command {}".format(" ".join(command))
)
try:
# let's wait for stuff to finish
while p.returncode is None:
if self._aborted:
# oh, we shall abort, let's do so!
p.commands[0].terminate()
raise AnalysisAborted(reenqueue=self._reenqueue)
try:
# let's wait for stuff to finish
while p.returncode is None:
if self._aborted:
# oh, we shall abort, let's do so!
p.commands[0].terminate()
raise AnalysisAborted(reenqueue=self._reenqueue)
# else continue
p.commands[0].poll()
finally:
p.close()
# else continue
p.commands[0].poll()
finally:
p.close()
output = p.stdout.text
self._logger.debug("Got output: {!r}".format(output))
output = p.stdout.text
self._logger.debug("Got output: {!r}".format(output))
if not "RESULTS:" in output:
raise RuntimeError("No analysis result found")
if not "RESULTS:" in output:
raise RuntimeError("No analysis result found")
_, output = output.split("RESULTS:")
analysis = yaml.safe_load(output)
_, output = output.split("RESULTS:")
analysis = yaml.safe_load(output)
result = {}
result["printingArea"] = analysis["printing_area"]
result["dimensions"] = analysis["dimensions"]
if analysis["total_time"]:
result["estimatedPrintTime"] = analysis["total_time"] * 60
if analysis["extrusion_length"]:
result["filament"] = {}
for i in range(len(analysis["extrusion_length"])):
result["filament"]["tool%d" % i] = {
"length": analysis["extrusion_length"][i],
"volume": analysis["extrusion_volume"][i]
}
result = {}
result["printingArea"] = analysis["printing_area"]
result["dimensions"] = analysis["dimensions"]
if analysis["total_time"]:
result["estimatedPrintTime"] = analysis["total_time"] * 60
if analysis["extrusion_length"]:
result["filament"] = {}
for i in range(len(analysis["extrusion_length"])):
result["filament"]["tool%d" % i] = {
"length": analysis["extrusion_length"][i],
"volume": analysis["extrusion_volume"][i],
}
if self._current.analysis and isinstance(self._current.analysis, dict):
return dict_merge(result, self._current.analysis)
else:
return result
finally:
self._gcode = None
if self._current.analysis and isinstance(self._current.analysis, dict):
return dict_merge(result, self._current.analysis)
else:
return result
finally:
self._gcode = None
def _do_abort(self, reenqueue=True):
self._aborted = True
self._reenqueue = reenqueue
def _do_abort(self, reenqueue=True):
self._aborted = True
self._reenqueue = reenqueue
+4 -3
View File
@@ -1,9 +1,10 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
class FileDestinations(object):
SDCARD = "sdcard"
LOCAL = "local"
SDCARD = "sdcard"
LOCAL = "local"
File diff suppressed because it is too large. Load diff
+197 -190
View File
@@ -2,7 +2,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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 io
@@ -11,247 +11,254 @@ import os
from octoprint import UMASK
from octoprint.util import atomic_write
class AbstractFileWrapper(object):
"""
Wrapper for file representations to save to storages.
"""
Wrapper for file representations to save to storages.
Arguments:
filename (str): The file's name
"""
Arguments:
filename (str): The file's name
"""
DEFAULT_PERMISSIONS = 0o664
DEFAULT_PERMISSIONS = 0o664
def __init__(self, filename):
self.filename = filename
def __init__(self, filename):
self.filename = filename
def save(self, path, permissions=None):
"""
Saves the file's content to the given absolute path.
def save(self, path, permissions=None):
"""
Saves the file's content to the given absolute path.
Arguments:
path (str): The absolute path to where to save the file
permissions (int): The permissions to set on the file
"""
raise NotImplementedError()
Arguments:
path (str): The absolute path to where to save the file
permissions (int): The permissions to set on the file
"""
raise NotImplementedError()
def stream(self):
"""
Returns a Python stream object (subclass of io.IOBase) representing the file's contents.
def stream(self):
"""
Returns a Python stream object (subclass of io.IOBase) representing the file's contents.
Returns:
io.IOBase: The file's contents as a stream.
"""
raise NotImplementedError()
Returns:
io.IOBase: The file's contents as a stream.
"""
raise NotImplementedError()
class DiskFileWrapper(AbstractFileWrapper):
"""
An implementation of :class:`.AbstractFileWrapper` that wraps an actual file on disk. The `save` implementations
will either copy the file to the new path (preserving file attributes) or -- if `move` is `True` (the default) --
move the file.
"""
An implementation of :class:`.AbstractFileWrapper` that wraps an actual file on disk. The `save` implementations
will either copy the file to the new path (preserving file attributes) or -- if `move` is `True` (the default) --
move the file.
Arguments:
filename (str): The file's name
path (str): The file's absolute path
move (boolean): Whether to move the file upon saving (True, default) or copying.
"""
Arguments:
filename (str): The file's name
path (str): The file's absolute path
move (boolean): Whether to move the file upon saving (True, default) or copying.
"""
def __init__(self, filename, path, move=True):
AbstractFileWrapper.__init__(self, filename)
self.path = path
self.move = move
def __init__(self, filename, path, move=True):
AbstractFileWrapper.__init__(self, filename)
self.path = path
self.move = move
def save(self, path, permissions=None):
import shutil
def save(self, path, permissions=None):
import shutil
if self.move:
shutil.move(self.path, path)
else:
shutil.copy2(self.path, path)
if self.move:
shutil.move(self.path, path)
else:
shutil.copy2(self.path, path)
if permissions is None:
permissions = self.DEFAULT_PERMISSIONS & ~UMASK
os.chmod(path, permissions)
if permissions is None:
permissions = self.DEFAULT_PERMISSIONS & ~UMASK
os.chmod(path, permissions)
def stream(self):
return io.open(self.path, "rb")
def stream(self):
return io.open(self.path, 'rb')
class StreamWrapper(AbstractFileWrapper):
"""
A wrapper allowing processing of one or more consecutive streams.
"""
A wrapper allowing processing of one or more consecutive streams.
Arguments:
*streams: One or more :py:`io.IOBase` streams to process one after another to save to storage.
"""
def __init__(self, filename, *streams):
if not len(streams) > 0:
raise ValueError("Need at least one stream to wrap")
Arguments:
*streams: One or more :py:`io.IOBase` streams to process one after another to save to storage.
"""
AbstractFileWrapper.__init__(self, filename)
self.streams = streams
def __init__(self, filename, *streams):
if not len(streams) > 0:
raise ValueError("Need at least one stream to wrap")
def save(self, path, permissions=None):
"""
Will dump the contents of all streams provided during construction into the target file, in the order they were
provided.
"""
import shutil
AbstractFileWrapper.__init__(self, filename)
self.streams = streams
with atomic_write(path, mode='wb') as dest:
for source in self.streams:
shutil.copyfileobj(source, dest)
if permissions is None:
permissions = self.DEFAULT_PERMISSIONS & ~UMASK
os.chmod(path, permissions)
def save(self, path, permissions=None):
"""
Will dump the contents of all streams provided during construction into the target file, in the order they were
provided.
"""
import shutil
with atomic_write(path, mode="wb") as dest:
for source in self.streams:
shutil.copyfileobj(source, dest)
if permissions is None:
permissions = self.DEFAULT_PERMISSIONS & ~UMASK
os.chmod(path, permissions)
def stream(self):
"""
If more than one stream was provided to the constructor, will return a :class:`.MultiStream` wrapping all
provided streams in the order they were provided, else the first and only stream is returned directly.
"""
if len(self.streams) > 1:
return MultiStream(*self.streams)
else:
return self.streams[0]
def stream(self):
"""
If more than one stream was provided to the constructor, will return a :class:`.MultiStream` wrapping all
provided streams in the order they were provided, else the first and only stream is returned directly.
"""
if len(self.streams) > 1:
return MultiStream(*self.streams)
else:
return self.streams[0]
class MultiStream(io.RawIOBase):
"""
A stream implementation which when read reads from multiple streams, one after the other, basically concatenating
their contents in the order they are provided to the constructor.
"""
A stream implementation which when read reads from multiple streams, one after the other, basically concatenating
their contents in the order they are provided to the constructor.
Arguments:
*streams: One or more :py:`io.IOBase` streams to concatenate.
"""
def __init__(self, *streams):
io.RawIOBase.__init__(self)
self.streams = streams
self.current_stream = 0
Arguments:
*streams: One or more :py:`io.IOBase` streams to concatenate.
"""
def read(self, n=-1):
if n == 0:
return b''
def __init__(self, *streams):
io.RawIOBase.__init__(self)
self.streams = streams
self.current_stream = 0
if len(self.streams) == 0:
return b''
def read(self, n=-1):
if n == 0:
return b""
while self.current_stream < len(self.streams):
stream = self.streams[self.current_stream]
if len(self.streams) == 0:
return b""
result = stream.read(n)
if result is None or len(result) != 0:
return result
else:
self.current_stream += 1
while self.current_stream < len(self.streams):
stream = self.streams[self.current_stream]
return b''
result = stream.read(n)
if result is None or len(result) != 0:
return result
else:
self.current_stream += 1
def readinto(self, b):
n = len(b)
read = self.read(n)
b[:len(read)] = read
return len(read)
return b""
def close(self):
for stream in self.streams:
try:
stream.close()
except Exception:
pass
def readinto(self, b):
n = len(b)
read = self.read(n)
b[: len(read)] = read
return len(read)
def readable(self, *args, **kwargs):
return True
def close(self):
for stream in self.streams:
try:
stream.close()
except Exception:
pass
def seekable(self, *args, **kwargs):
return False
def readable(self, *args, **kwargs):
return True
def seekable(self, *args, **kwargs):
return False
def writable(self, *args, **kwargs):
return False
def writable(self, *args, **kwargs):
return False
class LineProcessorStream(io.RawIOBase):
"""
While reading from this stream the provided `input_stream` is read line by line, calling the (overridable) method
:meth:`.process_line` for each read line.
"""
While reading from this stream the provided `input_stream` is read line by line, calling the (overridable) method
:meth:`.process_line` for each read line.
Sub classes can thus modify the contents of the `input_stream` in line, while it is being read. Keep in mind that
``process_line`` will receive the line as a byte stream - if underlying code needs to operate on unicode you'll need
to do the decoding yourself.
Sub classes can thus modify the contents of the `input_stream` in line, while it is being read. Keep in mind that
``process_line`` will receive the line as a byte stream - if underlying code needs to operate on unicode you'll need
to do the decoding yourself.
Arguments:
input_stream (io.RawIOBase): The stream to process on the fly.
"""
Arguments:
input_stream (io.RawIOBase): The stream to process on the fly.
"""
def __init__(self, input_stream):
io.RawIOBase.__init__(self)
self.input_stream = io.BufferedReader(input_stream)
self.leftover = bytearray()
def __init__(self, input_stream):
io.RawIOBase.__init__(self)
self.input_stream = io.BufferedReader(input_stream)
self.leftover = bytearray()
def read(self, n=-1):
if n == 0:
return b''
def read(self, n=-1):
if n == 0:
return b""
result = bytearray()
while len(result) < n or n == -1:
# add left over from previous loop
bytes_left = (n - len(result)) if n != -1 else -1
if bytes_left != -1 and bytes_left < len(self.leftover):
# only s
result += self.leftover[:bytes_left]
self.leftover = self.leftover[bytes_left:]
break
else:
result += self.leftover
self.leftover = bytearray()
result = bytearray()
while len(result) < n or n == -1:
# add left over from previous loop
bytes_left = (n - len(result)) if n != -1 else -1
if bytes_left != -1 and bytes_left < len(self.leftover):
# only s
result += self.leftover[:bytes_left]
self.leftover = self.leftover[bytes_left:]
break
else:
result += self.leftover
self.leftover = bytearray()
# read one line from the underlying stream
processed_line = None
while processed_line is None:
line = self.input_stream.readline()
if not line:
break
processed_line = self.process_line(line)
if processed_line is None:
break
# read one line from the underlying stream
processed_line = None
while processed_line is None:
line = self.input_stream.readline()
if not line:
break
processed_line = self.process_line(line)
if processed_line is None:
break
bytes_left = (n - len(result)) if n != -1 else -1
if bytes_left != -1 and bytes_left < len(processed_line):
result += processed_line[:bytes_left]
self.leftover = processed_line[bytes_left:]
break
else:
result += processed_line
bytes_left = (n - len(result)) if n != -1 else -1
if bytes_left != -1 and bytes_left < len(processed_line):
result += processed_line[:bytes_left]
self.leftover = processed_line[bytes_left:]
break
else:
result += processed_line
return bytes(result)
return bytes(result)
def readinto(self, b):
n = len(b)
read = self.read(n)
b[:len(read)] = read
return len(read)
def readinto(self, b):
n = len(b)
read = self.read(n)
b[: len(read)] = read
return len(read)
def process_line(self, line):
"""
Called from the `read` Method of this stream with each line read from `self.input_stream`.
def process_line(self, line):
"""
Called from the `read` Method of this stream with each line read from `self.input_stream`.
By returning ``None`` the line will not be returned from the read stream, effectively being stripped from the
wrapper `input_stream`.
By returning ``None`` the line will not be returned from the read stream, effectively being stripped from the
wrapper `input_stream`.
Arguments:
line (bytes): The line as read from `self.input_stream` in byte representation (str under Python 2 and
bytes under Python 3)
Arguments:
line (bytes): The line as read from `self.input_stream` in byte representation (str under Python 2 and
bytes under Python 3)
Returns:
bytes or None: The processed version of the line (might also be multiple lines), or None if the line is to be
stripped from the processed stream.
"""
return line
Returns:
bytes or None: The processed version of the line (might also be multiple lines), or None if the line is to be
stripped from the processed stream.
"""
return line
def close(self):
self.input_stream.close()
def close(self):
self.input_stream.close()
def readable(self, *args, **kwargs):
return True
def readable(self, *args, **kwargs):
return True
def seekable(self, *args, **kwargs):
return False
def seekable(self, *args, **kwargs):
return False
def writable(self, *args, **kwargs):
return False
def writable(self, *args, **kwargs):
return False
+125 -118
View File
@@ -7,153 +7,160 @@ from octoprint.logging import handlers
from typing import Union
def log_to_handler(logger, handler, level, msg, exc_info=None, extra=None, *args):
"""
Logs to the provided handler only.
"""
Logs to the provided handler only.
Arguments:
logger: logger to log to
handler: handler to restrict logging to
level: level to log at
msg: message to log
exc_info: optional exception info
extra: optional extra data
*args: log args
"""
import sys
try:
from logging import _srcfile
except ImportError:
_srcfile = None
Arguments:
logger: logger to log to
handler: handler to restrict logging to
level: level to log at
msg: message to log
exc_info: optional exception info
extra: optional extra data
*args: log args
"""
import sys
# this is just the same as logging.Logger._log
try:
from logging import _srcfile
except ImportError:
_srcfile = None
if _srcfile:
# IronPython doesn't track Python frames, so findCaller raises an
# exception on some versions of IronPython. We trap it here so that
# IronPython can use logging.
try:
fn, lno, func = logger.findCaller()
except ValueError:
fn, lno, func = "(unknown file)", 0, "(unknown function)"
else:
fn, lno, func = "(unknown file)", 0, "(unknown function)"
if exc_info:
if not isinstance(exc_info, tuple):
exc_info = sys.exc_info()
# this is just the same as logging.Logger._log
record = logger.makeRecord(logger.name, level, fn, lno, msg, args, exc_info, func, extra)
if _srcfile:
# IronPython doesn't track Python frames, so findCaller raises an
# exception on some versions of IronPython. We trap it here so that
# IronPython can use logging.
try:
fn, lno, func = logger.findCaller()
except ValueError:
fn, lno, func = "(unknown file)", 0, "(unknown function)"
else:
fn, lno, func = "(unknown file)", 0, "(unknown function)"
if exc_info:
if not isinstance(exc_info, tuple):
exc_info = sys.exc_info()
# and this is a mixture of logging.Logger.handle and logging.Logger.callHandlers
record = logger.makeRecord(
logger.name, level, fn, lno, msg, args, exc_info, func, extra
)
if (not logger.disabled) and logger.filter(record):
if record.levelno >= handler.level:
handler.handle(record)
# and this is a mixture of logging.Logger.handle and logging.Logger.callHandlers
if (not logger.disabled) and logger.filter(record):
if record.levelno >= handler.level:
handler.handle(record)
def get_handler(name, logger=None):
"""
Retrieves the handler named ``name``.
"""
Retrieves the handler named ``name``.
If optional ``logger`` is provided, search will be
limited to that logger, otherwise the root logger will be
searched.
If optional ``logger`` is provided, search will be
limited to that logger, otherwise the root logger will be
searched.
Arguments:
name: the name of the handler to look for
logger: (optional) the logger to search in, root logger if not provided
Arguments:
name: the name of the handler to look for
logger: (optional) the logger to search in, root logger if not provided
Returns:
the handler if it could be found, None otherwise
"""
import logging
Returns:
the handler if it could be found, None otherwise
"""
import logging
if logger is None:
logger = logging.getLogger()
if logger is None:
logger = logging.getLogger()
for handler in logger.handlers:
if handler.get_name() == name:
return handler
for handler in logger.handlers:
if handler.get_name() == name:
return handler
return None
return None
def get_divider_line(c, message=None, length=78, indent=3):
"""
Generate a divider line for logging, optionally with included message.
"""
Generate a divider line for logging, optionally with included message.
Examples:
Examples:
>>> get_divider_line("-") # doctest: +ALLOW_UNICODE
'------------------------------------------------------------------------------'
>>> get_divider_line("=", length=10) # doctest: +ALLOW_UNICODE
'=========='
>>> get_divider_line("-", message="Hi", length=10) # doctest: +ALLOW_UNICODE
'--- Hi ---'
>>> get_divider_line("-", message="A slightly longer text") # doctest: +ALLOW_UNICODE
'--- A slightly longer text ---------------------------------------------------'
>>> get_divider_line("-", message="A slightly longer text", indent=5) # doctest: +ALLOW_UNICODE
'----- A slightly longer text -------------------------------------------------'
>>> get_divider_line("-", message="Hello World!", length=10) # doctest: +ALLOW_UNICODE
'--- Hello World!'
>>> get_divider_line(None)
Traceback (most recent call last):
...
AssertionError: c is not text
>>> get_divider_line("´`")
Traceback (most recent call last):
...
AssertionError: c is not a single character
>>> get_divider_line("-", message=3)
Traceback (most recent call last):
...
AssertionError: message is not text
>>> get_divider_line("-", length="hello")
Traceback (most recent call last):
...
AssertionError: length is not an int
>>> get_divider_line("-", indent="hi")
Traceback (most recent call last):
...
AssertionError: indent is not an int
>>> get_divider_line("-") # doctest: +ALLOW_UNICODE
'------------------------------------------------------------------------------'
>>> get_divider_line("=", length=10) # doctest: +ALLOW_UNICODE
'=========='
>>> get_divider_line("-", message="Hi", length=10) # doctest: +ALLOW_UNICODE
'--- Hi ---'
>>> get_divider_line("-", message="A slightly longer text") # doctest: +ALLOW_UNICODE
'--- A slightly longer text ---------------------------------------------------'
>>> get_divider_line("-", message="A slightly longer text", indent=5) # doctest: +ALLOW_UNICODE
'----- A slightly longer text -------------------------------------------------'
>>> get_divider_line("-", message="Hello World!", length=10) # doctest: +ALLOW_UNICODE
'--- Hello World!'
>>> get_divider_line(None)
Traceback (most recent call last):
...
AssertionError: c is not text
>>> get_divider_line("´`")
Traceback (most recent call last):
...
AssertionError: c is not a single character
>>> get_divider_line("-", message=3)
Traceback (most recent call last):
...
AssertionError: message is not text
>>> get_divider_line("-", length="hello")
Traceback (most recent call last):
...
AssertionError: length is not an int
>>> get_divider_line("-", indent="hi")
Traceback (most recent call last):
...
AssertionError: indent is not an int
Arguments:
c: character to use for the line
message: message to print in the line
length: length of the line
indent: indentation of message in line
Arguments:
c: character to use for the line
message: message to print in the line
length: length of the line
indent: indentation of message in line
Returns:
formatted divider line
"""
Returns:
formatted divider line
"""
assert isinstance(c, basestring), "c is not text"
assert len(c) == 1, "c is not a single character"
assert isinstance(length, int), "length is not an int"
assert isinstance(indent, int), "indent is not an int"
assert isinstance(c, basestring), "c is not text"
assert len(c) == 1, "c is not a single character"
assert isinstance(length, int), "length is not an int"
assert isinstance(indent, int), "indent is not an int"
if message is None:
return c * length
if message is None:
return c * length
assert isinstance(message, basestring), "message is not text"
assert isinstance(message, basestring), "message is not text"
space = length - 2 * (indent + 1)
if space >= len(message):
return c * indent + " " + message + " " + c * (length - indent - 2 - len(message))
else:
return c * indent + " " + message
space = length - 2 * (indent + 1)
if space >= len(message):
return c * indent + " " + message + " " + c * (length - indent - 2 - len(message))
else:
return c * indent + " " + message
def prefix_multilines(text, prefix=u": "):
# type: (Union[unicode, bytes], unicode) -> unicode
from octoprint.util import to_unicode
def prefix_multilines(text, prefix=": "):
# type: (Union[unicode, bytes], unicode) -> unicode
from octoprint.util import to_unicode
lines = text.splitlines()
if not lines:
return u""
lines = text.splitlines()
if not lines:
return ""
if len(lines) == 1:
return to_unicode(lines[0])
if len(lines) == 1:
return to_unicode(lines[0])
return to_unicode(lines[0]) + u"\n" + u"\n".join(map(lambda line: prefix + to_unicode(line),
lines[1:]))
return (
to_unicode(lines[0])
+ "\n"
+ "\n".join(map(lambda line: prefix + to_unicode(line), lines[1:]))
)
+132 -131
View File
@@ -11,186 +11,187 @@ import concurrent.futures
class AsyncLogHandlerMixin(logging.Handler):
def __init__(self, *args, **kwargs):
self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
super(AsyncLogHandlerMixin, self).__init__(*args, **kwargs)
def __init__(self, *args, **kwargs):
self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
super(AsyncLogHandlerMixin, self).__init__(*args, **kwargs)
def emit(self, record):
if getattr(self._executor, "_shutdown", False):
return
def emit(self, record):
if getattr(self._executor, "_shutdown", False):
return
try:
self._executor.submit(self._emit, record)
except Exception:
self.handleError(record)
try:
self._executor.submit(self._emit, record)
except Exception:
self.handleError(record)
def _emit(self, record):
# noinspection PyUnresolvedReferences
super(AsyncLogHandlerMixin, self).emit(record)
def _emit(self, record):
# noinspection PyUnresolvedReferences
super(AsyncLogHandlerMixin, self).emit(record)
def close(self):
self._executor.shutdown(wait=True)
super(AsyncLogHandlerMixin, self).close()
def close(self):
self._executor.shutdown(wait=True)
super(AsyncLogHandlerMixin, self).close()
class CleaningTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):
def __init__(self, *args, **kwargs):
kwargs["encoding"] = kwargs.get("encoding", "utf-8")
def __init__(self, *args, **kwargs):
kwargs["encoding"] = kwargs.get("encoding", "utf-8")
super(CleaningTimedRotatingFileHandler, self).__init__(*args, **kwargs)
super(CleaningTimedRotatingFileHandler, self).__init__(*args, **kwargs)
# clean up old files on handler start
if self.backupCount > 0:
for s in self.getFilesToDelete():
os.remove(s)
# clean up old files on handler start
if self.backupCount > 0:
for s in self.getFilesToDelete():
os.remove(s)
class OctoPrintLogHandler(AsyncLogHandlerMixin, CleaningTimedRotatingFileHandler):
rollover_callbacks = []
rollover_callbacks = []
def __init__(self, *args, **kwargs):
kwargs["encoding"] = kwargs.get("encoding", "utf-8")
super(OctoPrintLogHandler, self).__init__(*args, **kwargs)
def __init__(self, *args, **kwargs):
kwargs["encoding"] = kwargs.get("encoding", "utf-8")
super(OctoPrintLogHandler, self).__init__(*args, **kwargs)
@classmethod
def registerRolloverCallback(cls, callback, *args, **kwargs):
cls.rollover_callbacks.append((callback, args, kwargs))
@classmethod
def registerRolloverCallback(cls, callback, *args, **kwargs):
cls.rollover_callbacks.append((callback, args, kwargs))
def doRollover(self):
super(OctoPrintLogHandler, self).doRollover()
def doRollover(self):
super(OctoPrintLogHandler, self).doRollover()
for rcb in self.rollover_callbacks:
callback, args, kwargs = rcb
callback(*args, **kwargs)
for rcb in self.rollover_callbacks:
callback, args, kwargs = rcb
callback(*args, **kwargs)
class OctoPrintStreamHandler(AsyncLogHandlerMixin, logging.StreamHandler):
pass
pass
class TriggeredRolloverLogHandler(AsyncLogHandlerMixin, logging.handlers.RotatingFileHandler):
class TriggeredRolloverLogHandler(
AsyncLogHandlerMixin, logging.handlers.RotatingFileHandler
):
do_rollover = False
suffix_template = "%Y-%m-%d_%H-%M-%S"
file_pattern = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$")
do_rollover = False
suffix_template = "%Y-%m-%d_%H-%M-%S"
file_pattern = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}$")
@classmethod
def arm_rollover(cls):
cls.do_rollover = True
@classmethod
def arm_rollover(cls):
cls.do_rollover = True
def __init__(self, *args, **kwargs):
kwargs["encoding"] = kwargs.get("encoding", "utf-8")
super(TriggeredRolloverLogHandler, self).__init__(*args, **kwargs)
self.cleanupFiles()
def __init__(self, *args, **kwargs):
kwargs["encoding"] = kwargs.get("encoding", "utf-8")
super(TriggeredRolloverLogHandler, self).__init__(*args, **kwargs)
self.cleanupFiles()
def shouldRollover(self, record):
return self.do_rollover
def shouldRollover(self, record):
return self.do_rollover
def getFilesToDelete(self):
"""
Determine the files to delete when rolling over.
"""
dirName, baseName = os.path.split(self.baseFilename)
fileNames = os.listdir(dirName)
result = []
prefix = baseName + "."
plen = len(prefix)
for fileName in fileNames:
if fileName[:plen] == prefix:
suffix = fileName[plen:]
if type(self).file_pattern.match(suffix):
result.append(os.path.join(dirName, fileName))
result.sort()
if len(result) < self.backupCount:
result = []
else:
result = result[:len(result) - self.backupCount]
return result
def getFilesToDelete(self):
"""
Determine the files to delete when rolling over.
"""
dirName, baseName = os.path.split(self.baseFilename)
fileNames = os.listdir(dirName)
result = []
prefix = baseName + "."
plen = len(prefix)
for fileName in fileNames:
if fileName[:plen] == prefix:
suffix = fileName[plen:]
if type(self).file_pattern.match(suffix):
result.append(os.path.join(dirName, fileName))
result.sort()
if len(result) < self.backupCount:
result = []
else:
result = result[: len(result) - self.backupCount]
return result
def cleanupFiles(self):
if self.backupCount > 0:
for path in self.getFilesToDelete():
os.remove(path)
def cleanupFiles(self):
if self.backupCount > 0:
for path in self.getFilesToDelete():
os.remove(path)
def doRollover(self):
self.do_rollover = False
def doRollover(self):
self.do_rollover = False
if self.stream:
self.stream.close()
self.stream = None
if self.stream:
self.stream.close()
self.stream = None
if os.path.exists(self.baseFilename):
# figure out creation date/time to use for file suffix
t = time.localtime(os.stat(self.baseFilename).st_mtime)
dfn = self.baseFilename + "." + time.strftime(type(self).suffix_template, t)
if os.path.exists(dfn):
os.remove(dfn)
os.rename(self.baseFilename, dfn)
if os.path.exists(self.baseFilename):
# figure out creation date/time to use for file suffix
t = time.localtime(os.stat(self.baseFilename).st_mtime)
dfn = self.baseFilename + "." + time.strftime(type(self).suffix_template, t)
if os.path.exists(dfn):
os.remove(dfn)
os.rename(self.baseFilename, dfn)
self.cleanupFiles()
if not self.delay:
self.stream = self._open()
self.cleanupFiles()
if not self.delay:
self.stream = self._open()
class SerialLogHandler(TriggeredRolloverLogHandler):
pass
pass
class PluginTimingsLogHandler(TriggeredRolloverLogHandler):
pass
pass
class RecordingLogHandler(logging.Handler):
def __init__(self, target=None, *args, **kwargs):
super(RecordingLogHandler, self).__init__(*args, **kwargs)
self._buffer = []
self._target = target
def __init__(self, target=None, *args, **kwargs):
super(RecordingLogHandler, self).__init__(*args, **kwargs)
self._buffer = []
self._target = target
def emit(self, record):
self._buffer.append(record)
def emit(self, record):
self._buffer.append(record)
def setTarget(self, target):
self._target = target
def setTarget(self, target):
self._target = target
def flush(self):
if not self._target:
return
def flush(self):
if not self._target:
return
self.acquire()
try:
for record in self._buffer:
self._target.handle(record)
self._buffer = []
finally:
self.release()
self.acquire()
try:
for record in self._buffer:
self._target.handle(record)
self._buffer = []
finally:
self.release()
def close(self):
self.flush()
self.acquire()
try:
self._buffer = []
finally:
self.release()
def close(self):
self.flush()
self.acquire()
try:
self._buffer = []
finally:
self.release()
def __len__(self):
return len(self._buffer)
def __len__(self):
return len(self._buffer)
# noinspection PyAbstractClass
class CombinedLogHandler(logging.Handler):
def __init__(self, *handlers):
logging.Handler.__init__(self)
self._handlers = handlers
def __init__(self, *handlers):
logging.Handler.__init__(self)
self._handlers = handlers
def setHandlers(self, *handlers):
self._handlers = handlers
def setHandlers(self, *handlers):
self._handlers = handlers
def handle(self, record):
self.acquire()
try:
if self._handlers:
for handler in self._handlers:
handler.handle(record)
finally:
self.release()
def handle(self, record):
self.acquire()
try:
if self._handlers:
for handler in self._handlers:
handler.handle(record)
finally:
self.release()
File diff suppressed because it is too large. Load diff
+2291 -1833
View File
File diff suppressed because it is too large. Load diff
+1843 -1780
View File
File diff suppressed because it is too large. Load diff
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License"
import octoprint.plugin
@@ -15,118 +15,138 @@ from flask_babel import gettext
import time
class ActionCommandNotificationPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.EventHandlerPlugin):
def __init__(self):
self._notifications = []
class ActionCommandNotificationPlugin(
octoprint.plugin.AssetPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.EventHandlerPlugin,
):
def __init__(self):
self._notifications = []
# Additional permissions hook
# Additional permissions hook
def get_additional_permissions(self):
return [
{"key": "SHOW",
"name": "Show printer notifications",
"description": gettext("Allows to see printer notifications"),
"default_groups": [USER_GROUP],
"roles": ["show"]},
{"key": "CLEAR",
"name": "Clear printer notifications",
"description": gettext("Allows to clear printer notifications"),
"default_groups": [USER_GROUP],
"roles": ["clear"]}
]
def get_additional_permissions(self):
return [
{
"key": "SHOW",
"name": "Show printer notifications",
"description": gettext("Allows to see printer notifications"),
"default_groups": [USER_GROUP],
"roles": ["show"],
},
{
"key": "CLEAR",
"name": "Clear printer notifications",
"description": gettext("Allows to clear printer notifications"),
"default_groups": [USER_GROUP],
"roles": ["clear"],
},
]
#~ AssetPlugin
# ~ AssetPlugin
def get_assets(self):
return {"js": ["js/action_command_notification.js"],
"clientjs": ["clientjs/action_command_notification.js"],
"css": ["css/action_command_notification.css"]}
def get_assets(self):
return {
"js": ["js/action_command_notification.js"],
"clientjs": ["clientjs/action_command_notification.js"],
"css": ["css/action_command_notification.css"],
}
#~ EventHandlerPlugin
# ~ EventHandlerPlugin
def on_event(self, event, payload):
if event == Events.DISCONNECTED:
self._clear_notifications()
def on_event(self, event, payload):
if event == Events.DISCONNECTED:
self._clear_notifications()
#~ SettingsPlugin
# ~ SettingsPlugin
def get_settings_defaults(self):
return {"enable": True,
"enable_popups": False}
def get_settings_defaults(self):
return {"enable": True, "enable_popups": False}
#~ SimpleApiPlugin
# ~ SimpleApiPlugin
def on_api_get(self, request):
if not Permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW.can():
return flask.abort(403, "Insufficient permissions")
return flask.jsonify(notifications=[{"timestamp": notification[0],
"message": notification[1]} for notification in self._notifications])
def on_api_get(self, request):
if not Permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW.can():
return flask.abort(403, "Insufficient permissions")
return flask.jsonify(
notifications=[
{"timestamp": notification[0], "message": notification[1]}
for notification in self._notifications
]
)
def get_api_commands(self):
return {"clear": []}
def get_api_commands(self):
return {"clear": []}
def on_api_command(self, command, data):
if command == "clear":
if not Permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_CLEAR.can():
return flask.abort(403, "Insufficient permissions")
self._clear_notifications()
def on_api_command(self, command, data):
if command == "clear":
if not Permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_CLEAR.can():
return flask.abort(403, "Insufficient permissions")
self._clear_notifications()
#~ TemplatePlugin
# ~ TemplatePlugin
def get_template_configs(self):
return [
{"type": "settings",
"name": gettext("Printer Notifications"),
"custom_bindings": False},
{"type": "sidebar",
"name": gettext("Printer Notifications"),
"icon": "bell-o",
"styles_wrapper": ["display: none"],
"data_bind": "visible: loginState.hasPermissionKo(access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW)"
" && settings.settings.plugins.action_command_notification.enable()"}
]
def get_template_configs(self):
return [
{
"type": "settings",
"name": gettext("Printer Notifications"),
"custom_bindings": False,
},
{
"type": "sidebar",
"name": gettext("Printer Notifications"),
"icon": "bell-o",
"styles_wrapper": ["display: none"],
"data_bind": "visible: loginState.hasPermissionKo(access.permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW)"
" && settings.settings.plugins.action_command_notification.enable()",
},
]
#~ action command handler
# ~ action command handler
def action_command_handler(self, comm, line, action, *args, **kwargs):
if not self._settings.get_boolean(["enable"]):
return
def action_command_handler(self, comm, line, action, *args, **kwargs):
if not self._settings.get_boolean(["enable"]):
return
parts = action.split(None, 1)
if len(parts) == 1:
action = parts[0]
parameter = ""
else:
action, parameter = parts
parts = action.split(None, 1)
if len(parts) == 1:
action = parts[0]
parameter = ""
else:
action, parameter = parts
if action != "notification":
return
if action != "notification":
return
message = parameter.strip()
self._notifications.append((time.time(), message))
self._plugin_manager.send_plugin_message(self._identifier, {"message": message})
message = parameter.strip()
self._notifications.append((time.time(), message))
self._plugin_manager.send_plugin_message(self._identifier, {"message": message})
self._logger.info("Got a notification: {}".format(message))
self._logger.info("Got a notification: {}".format(message))
def _clear_notifications(self):
self._notifications = []
self._plugin_manager.send_plugin_message(self._identifier, {})
self._logger.info("Notifications cleared")
def _clear_notifications(self):
self._notifications = []
self._plugin_manager.send_plugin_message(self._identifier, {})
self._logger.info("Notifications cleared")
__plugin_name__ = "Action Command Notification Support"
__plugin_description__ = "Allows your printer to trigger notifications via action commands on the connection"
__plugin_description__ = (
"Allows your printer to trigger notifications via action commands on the connection"
)
__plugin_author__ = "Gina Häußge"
__plugin_disabling_discouraged__ = gettext("Without this plugin your printer will no longer be able to trigger"
" notifications in OctoPrint")
__plugin_disabling_discouraged__ = gettext(
"Without this plugin your printer will no longer be able to trigger"
" notifications in OctoPrint"
)
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = ActionCommandNotificationPlugin()
__plugin_hooks__ = {
"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions,
}
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import octoprint.plugin
@@ -14,232 +14,294 @@ from octoprint.events import Events
import flask
from flask_babel import gettext
class Prompt(object):
def __init__(self, text):
self.text = text
self.choices = []
def __init__(self, text):
self.text = text
self.choices = []
self._active = False
self._active = False
@property
def active(self):
return self._active
@property
def active(self):
return self._active
def add_choice(self, text):
self.choices.append(text)
def add_choice(self, text):
self.choices.append(text)
def activate(self):
self._active = True
def activate(self):
self._active = True
def validate_choice(self, choice):
return 0 <= choice < len(self.choices)
def validate_choice(self, choice):
return 0 <= choice < len(self.choices)
class ActionCommandPromptPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.EventHandlerPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin):
class ActionCommandPromptPlugin(
octoprint.plugin.AssetPlugin,
octoprint.plugin.EventHandlerPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin,
):
COMMAND = "M876"
CAP_PROMPT_SUPPORT = "PROMPT_SUPPORT"
COMMAND = "M876"
CAP_PROMPT_SUPPORT = "PROMPT_SUPPORT"
# noinspection PyMissingConstructor
def __init__(self):
self._prompt = None
self._enable = "detected"
self._command = None
self._enable_emergency_sending = True
self._enable_signal_support = True
self._cap_prompt_support = False
# noinspection PyMissingConstructor
def __init__(self):
self._prompt = None
self._enable = "detected"
self._command = None
self._enable_emergency_sending = True
self._enable_signal_support = True
self._cap_prompt_support = False
def initialize(self):
self._enable = self._settings.get(["enable"])
self._command = self._settings.get(["command"])
self._enable_emergency_sending = self._settings.get_boolean(["enable_emergency_sending"])
self._enable_signal_support = self._settings.get_boolean(["enable_signal_support"])
def initialize(self):
self._enable = self._settings.get(["enable"])
self._command = self._settings.get(["command"])
self._enable_emergency_sending = self._settings.get_boolean(
["enable_emergency_sending"]
)
self._enable_signal_support = self._settings.get_boolean(
["enable_signal_support"]
)
# Additional permissions hook
# Additional permissions hook
def get_additional_permissions(self):
return [
{"key": "INTERACT",
"name": "Interact with printer prompts",
"description": gettext("Allows to see and interact with printer prompts"),
"default_groups": [USER_GROUP],
"roles": ["interact"]}
]
def get_additional_permissions(self):
return [
{
"key": "INTERACT",
"name": "Interact with printer prompts",
"description": gettext("Allows to see and interact with printer prompts"),
"default_groups": [USER_GROUP],
"roles": ["interact"],
}
]
#~ AssetPlugin
# ~ AssetPlugin
def get_assets(self):
return {"js": ["js/action_command_prompt.js"],
"clientjs": ["clientjs/action_command_prompt.js"]}
def get_assets(self):
return {
"js": ["js/action_command_prompt.js"],
"clientjs": ["clientjs/action_command_prompt.js"],
}
#~ EventHandlerPlugin
# ~ EventHandlerPlugin
def on_event(self, event, payload):
if event == Events.CONNECTED and self._enable == "always" and self._enable_signal_support:
self._printer.commands(["{command} P1".format(command=self._command)])
elif event == Events.DISCONNECTED:
self._close_prompt()
def on_event(self, event, payload):
if (
event == Events.CONNECTED
and self._enable == "always"
and self._enable_signal_support
):
self._printer.commands(["{command} P1".format(command=self._command)])
elif event == Events.DISCONNECTED:
self._close_prompt()
#~ SettingsPlugin
# ~ SettingsPlugin
def get_settings_defaults(self):
return {"enable": "detected",
"command": self.COMMAND,
"enable_emergency_sending": True,
"enable_signal_support": True}
def get_settings_defaults(self):
return {
"enable": "detected",
"command": self.COMMAND,
"enable_emergency_sending": True,
"enable_signal_support": True,
}
def on_settings_save(self, data):
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
self._enable = self._settings.get(["enable"])
self._command = self._settings.get(["command"])
self._enable_emergency_sending = self._settings.get_boolean(["enable_emergency_sending"])
self._enable_signal_support = self._settings.get_boolean(["enable_signal_support"])
def on_settings_save(self, data):
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
self._enable = self._settings.get(["enable"])
self._command = self._settings.get(["command"])
self._enable_emergency_sending = self._settings.get_boolean(
["enable_emergency_sending"]
)
self._enable_signal_support = self._settings.get_boolean(
["enable_signal_support"]
)
#~ SimpleApiPlugin
# ~ SimpleApiPlugin
def get_api_commands(self):
return {"select": ["choice"]}
def get_api_commands(self):
return {"select": ["choice"]}
def on_api_command(self, command, data):
if command == "select":
if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can():
return flask.abort(403, "Insufficient permissions")
def on_api_command(self, command, data):
if command == "select":
if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can():
return flask.abort(403, "Insufficient permissions")
if self._prompt is None:
return flask.abort(409, "No active prompt")
if self._prompt is None:
return flask.abort(409, "No active prompt")
choice = data["choice"]
if not isinstance(choice, int) or not self._prompt.validate_choice(choice):
return flask.abort(400, "{!r} is not a valid value for choice".format(choice))
choice = data["choice"]
if not isinstance(choice, int) or not self._prompt.validate_choice(choice):
return flask.abort(
400, "{!r} is not a valid value for choice".format(choice)
)
self._answer_prompt(choice)
self._answer_prompt(choice)
def on_api_get(self, request):
if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can():
return flask.abort(403, "Insufficient permissions")
if self._prompt is None:
return flask.jsonify()
else:
return flask.jsonify(text=self._prompt.text, choices=self._prompt.choices)
def on_api_get(self, request):
if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can():
return flask.abort(403, "Insufficient permissions")
if self._prompt is None:
return flask.jsonify()
else:
return flask.jsonify(text=self._prompt.text, choices=self._prompt.choices)
#~ TemplatePlugin
# ~ TemplatePlugin
def get_template_configs(self):
return [{"type": "settings", "name": gettext("Printer Dialogs"), "custom_bindings": False}]
def get_template_configs(self):
return [
{
"type": "settings",
"name": gettext("Printer Dialogs"),
"custom_bindings": False,
}
]
#~ action command handler
# ~ action command handler
def action_command_handler(self, comm, line, action, *args, **kwargs):
if not action.startswith("prompt_"):
return
def action_command_handler(self, comm, line, action, *args, **kwargs):
if not action.startswith("prompt_"):
return
parts = action.split(None, 1)
if len(parts) == 1:
action = parts[0]
parameter = ""
else:
action, parameter = parts
parts = action.split(None, 1)
if len(parts) == 1:
action = parts[0]
parameter = ""
else:
action, parameter = parts
if action == "prompt_begin":
if self._prompt is not None and self._prompt.active:
self._logger.warning("Prompt is already defined")
return
self._prompt = Prompt(parameter.strip())
if action == "prompt_begin":
if self._prompt is not None and self._prompt.active:
self._logger.warning("Prompt is already defined")
return
self._prompt = Prompt(parameter.strip())
elif action == "prompt_choice" or action == "prompt_button":
if self._prompt is None:
return
if self._prompt.active:
self._logger.warning("Prompt is already active")
return
self._prompt.add_choice(parameter.strip())
elif action == "prompt_choice" or action == "prompt_button":
if self._prompt is None:
return
if self._prompt.active:
self._logger.warning("Prompt is already active")
return
self._prompt.add_choice(parameter.strip())
elif action == "prompt_show":
if self._prompt is None:
return
if self._prompt.active:
self._logger.warning("Prompt is already active")
return
self._show_prompt()
elif action == "prompt_show":
if self._prompt is None:
return
if self._prompt.active:
self._logger.warning("Prompt is already active")
return
self._show_prompt()
elif action == "prompt_end":
if self._prompt is None:
return
self._close_prompt()
self._prompt = None
elif action == "prompt_end":
if self._prompt is None:
return
self._close_prompt()
self._prompt = None
#~ queuing handling
# ~ queuing handling
def gcode_queuing_handler(self, comm_instance, phase, cmd, cmd_type, gcode, subcode=None, tags=None, *args, **kwargs):
if gcode != self._command:
return
def gcode_queuing_handler(
self,
comm_instance,
phase,
cmd,
cmd_type,
gcode,
subcode=None,
tags=None,
*args,
**kwargs
):
if gcode != self._command:
return
if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support) or not self._enable_emergency_sending:
return
if (
self._enable == "never"
or (self._enable == "detected" and not self._cap_prompt_support)
or not self._enable_emergency_sending
):
return
if not "S" in cmd:
# we only force-send M876 Sx
return
if not "S" in cmd:
# we only force-send M876 Sx
return
# noinspection PyProtectedMember
return comm_instance._emergency_force_send(cmd, "Force-sending {} to the printer".format(self._command), gcode=gcode)
# noinspection PyProtectedMember
return comm_instance._emergency_force_send(
cmd, "Force-sending {} to the printer".format(self._command), gcode=gcode
)
#~ capability reporting
# ~ capability reporting
def firmware_capability_handler(self, comm_instance, capability, enabled, already_defined, *args, **kwargs):
if capability == self.CAP_PROMPT_SUPPORT and enabled:
self._cap_prompt_support = True
if self._enable == "detected" and self._enable_signal_support:
self._printer.commands(["{command} P1".format(command=self._command)])
def firmware_capability_handler(
self, comm_instance, capability, enabled, already_defined, *args, **kwargs
):
if capability == self.CAP_PROMPT_SUPPORT and enabled:
self._cap_prompt_support = True
if self._enable == "detected" and self._enable_signal_support:
self._printer.commands(["{command} P1".format(command=self._command)])
#~ prompt handling
# ~ prompt handling
def _show_prompt(self):
if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support):
return
def _show_prompt(self):
if self._enable == "never" or (
self._enable == "detected" and not self._cap_prompt_support
):
return
self._prompt.activate()
self._plugin_manager.send_plugin_message(self._identifier, {"action": "show",
"text": self._prompt.text,
"choices": self._prompt.choices})
self._prompt.activate()
self._plugin_manager.send_plugin_message(
self._identifier,
{
"action": "show",
"text": self._prompt.text,
"choices": self._prompt.choices,
},
)
def _close_prompt(self):
if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support):
return
def _close_prompt(self):
if self._enable == "never" or (
self._enable == "detected" and not self._cap_prompt_support
):
return
self._prompt = None
self._plugin_manager.send_plugin_message(self._identifier, {"action": "close"})
self._prompt = None
self._plugin_manager.send_plugin_message(self._identifier, {"action": "close"})
def _answer_prompt(self, choice):
if self._enable == "never" or (self._enable == "detected" and not self._cap_prompt_support):
return
def _answer_prompt(self, choice):
if self._enable == "never" or (
self._enable == "detected" and not self._cap_prompt_support
):
return
self._close_prompt()
if "{choice}" in self._command:
self._printer.commands([self._command.format(choice=choice)],
force=True)
else:
self._printer.commands(["{command} S{choice}".format(command=self._command,
choice=choice)],
force=True)
self._close_prompt()
if "{choice}" in self._command:
self._printer.commands([self._command.format(choice=choice)], force=True)
else:
self._printer.commands(
["{command} S{choice}".format(command=self._command, choice=choice)],
force=True,
)
__plugin_name__ = "Action Command Prompt Support"
__plugin_description__ = "Allows your printer to trigger prompts via action commands on the connection"
__plugin_description__ = (
"Allows your printer to trigger prompts via action commands on the connection"
)
__plugin_author__ = "Gina Häußge"
__plugin_disabling_discouraged__ = gettext("Without this plugin your printer will no longer be able to trigger"
" confirmation or selection prompts in OctoPrint")
__plugin_disabling_discouraged__ = gettext(
"Without this plugin your printer will no longer be able to trigger"
" confirmation or selection prompts in OctoPrint"
)
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = ActionCommandPromptPlugin()
__plugin_hooks__ = {
"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler,
"octoprint.comm.protocol.gcode.queuing": __plugin_implementation__.gcode_queuing_handler,
"octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.firmware_capability_handler,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
"octoprint.comm.protocol.action": __plugin_implementation__.action_command_handler,
"octoprint.comm.protocol.gcode.queuing": __plugin_implementation__.gcode_queuing_handler,
"octoprint.comm.protocol.firmware.capabilities": __plugin_implementation__.firmware_capability_handler,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions,
}
File diff suppressed because it is too large. Load diff
+454 -400
View File
@@ -20,428 +20,482 @@ from octoprint.util import atomic_write, monotonic_time, ResettableTimer, genera
from octoprint.access import ADMIN_GROUP
from octoprint.access.permissions import Permissions
CUTOFF_TIME = 10 * 60 # 10min
POLL_TIMEOUT = 5 # 5 seconds
CUTOFF_TIME = 10 * 60 # 10min
POLL_TIMEOUT = 5 # 5 seconds
class AppAlreadyExists(Exception):
pass
pass
class PendingDecision(object):
def __init__(self, app_id, app_token, user_id, user_token, timeout_callback=None):
self.app_id = app_id
self.app_token = app_token
self.user_id = user_id
self.user_token = user_token
self.created = monotonic_time()
def __init__(self, app_id, app_token, user_id, user_token, timeout_callback=None):
self.app_id = app_id
self.app_token = app_token
self.user_id = user_id
self.user_token = user_token
self.created = monotonic_time()
if callable(timeout_callback):
self.poll_timeout = ResettableTimer(POLL_TIMEOUT, timeout_callback, [user_token])
self.poll_timeout.start()
if callable(timeout_callback):
self.poll_timeout = ResettableTimer(
POLL_TIMEOUT, timeout_callback, [user_token]
)
self.poll_timeout.start()
def external(self):
return {"app_id": self.app_id,
"user_id": self.user_id,
"user_token": self.user_token}
def external(self):
return {
"app_id": self.app_id,
"user_id": self.user_id,
"user_token": self.user_token,
}
def __repr__(self):
return u"PendingDecision({!r}, {!r}, {!r}, {!r}, timeout_callback=...)".format(self.app_id,
self.app_token,
self.user_id,
self.user_token)
def __repr__(self):
return "PendingDecision({!r}, {!r}, {!r}, {!r}, timeout_callback=...)".format(
self.app_id, self.app_token, self.user_id, self.user_token
)
class ReadyDecision(object):
def __init__(self, app_id, app_token, user_id):
self.app_id = app_id
self.app_token = app_token
self.user_id = user_id
def __init__(self, app_id, app_token, user_id):
self.app_id = app_id
self.app_token = app_token
self.user_id = user_id
@classmethod
def for_pending(cls, pending, user_id):
return cls(pending.app_id, pending.app_token, user_id)
@classmethod
def for_pending(cls, pending, user_id):
return cls(pending.app_id, pending.app_token, user_id)
def __repr__(self):
return u"ReadyDecision({!r}, {!r}, {!r})".format(self.app_id,
self.app_token,
self.user_id)
def __repr__(self):
return "ReadyDecision({!r}, {!r}, {!r})".format(
self.app_id, self.app_token, self.user_id
)
class ActiveKey(object):
def __init__(self, app_id, api_key, user_id):
self.app_id = app_id
self.api_key = api_key
self.user_id = user_id
def external(self):
return {"app_id": self.app_id,
"api_key": self.api_key,
"user_id": self.user_id}
def internal(self):
return {"app_id": self.app_id,
"api_key": self.api_key}
@classmethod
def for_internal(cls, internal, user_id):
return cls(internal["app_id"], internal["api_key"], user_id)
def __repr__(self):
return u"ActiveKey({!r}, {!r}, {!r})".format(self.app_id,
self.api_key,
self.user_id)
class AppKeysPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin):
def __init__(self):
self._pending_decisions = []
self._pending_lock = threading.RLock()
self._ready_decisions = []
self._ready_lock = threading.RLock()
self._keys = defaultdict(list)
self._keys_lock = threading.RLock()
self._key_path = None
def initialize(self):
self._key_path = os.path.join(self.get_plugin_data_folder(), "keys.yaml")
self._load_keys()
# Additional permissions hook
def get_additional_permissions(self):
return [
{"key": "ADMIN",
"name": "Admin access",
"description": gettext("Allows administrating all application keys"),
"roles": ["admin"],
"dangerous": True,
"default_groups": [ADMIN_GROUP]}
]
##~~ TemplatePlugin
def get_template_configs(self):
return [{"type": "usersettings", "name": gettext("Application Keys")},
{"type": "settings", "name": gettext("Application Keys")}]
##~~ AssetPlugin
def get_assets(self):
return {"js": ["js/appkeys.js"],
"clientjs": ["clientjs/appkeys.js"],
"less": ["less/appkeys.less"],
"css": ["css/appkeys.css"]}
##~~ BlueprintPlugin mixin
@octoprint.plugin.BlueprintPlugin.route("/probe", methods=["GET"])
@no_firstrun_access
def handle_probe(self):
return NO_CONTENT
@octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"])
@no_firstrun_access
def handle_request(self):
data = flask.request.json
if data is None:
return flask.make_response("Missing key request", 400)
if not "app" in data:
return flask.make_response("No app name provided", 400)
app_name = data["app"]
user_id = None
if "user" in data and data["user"]:
user_id = data["user"]
app_token, user_token = self._add_pending_decision(app_name, user_id=user_id)
self._plugin_manager.send_plugin_message(self._identifier, {"type": "request_access",
"app_name": app_name,
"user_token": user_token,
"user_id": user_id})
response = flask.jsonify(app_token=app_token)
response.status_code = 201
response.headers["Location"] = flask.url_for(".handle_decision_poll", app_token=app_token, _external=True)
return response
def __init__(self, app_id, api_key, user_id):
self.app_id = app_id
self.api_key = api_key
self.user_id = user_id
def external(self):
return {"app_id": self.app_id, "api_key": self.api_key, "user_id": self.user_id}
def internal(self):
return {"app_id": self.app_id, "api_key": self.api_key}
@classmethod
def for_internal(cls, internal, user_id):
return cls(internal["app_id"], internal["api_key"], user_id)
def __repr__(self):
return "ActiveKey({!r}, {!r}, {!r})".format(
self.app_id, self.api_key, self.user_id
)
class AppKeysPlugin(
octoprint.plugin.AssetPlugin,
octoprint.plugin.BlueprintPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.TemplatePlugin,
):
def __init__(self):
self._pending_decisions = []
self._pending_lock = threading.RLock()
self._ready_decisions = []
self._ready_lock = threading.RLock()
self._keys = defaultdict(list)
self._keys_lock = threading.RLock()
self._key_path = None
def initialize(self):
self._key_path = os.path.join(self.get_plugin_data_folder(), "keys.yaml")
self._load_keys()
# Additional permissions hook
def get_additional_permissions(self):
return [
{
"key": "ADMIN",
"name": "Admin access",
"description": gettext("Allows administrating all application keys"),
"roles": ["admin"],
"dangerous": True,
"default_groups": [ADMIN_GROUP],
}
]
##~~ TemplatePlugin
def get_template_configs(self):
return [
{"type": "usersettings", "name": gettext("Application Keys")},
{"type": "settings", "name": gettext("Application Keys")},
]
##~~ AssetPlugin
def get_assets(self):
return {
"js": ["js/appkeys.js"],
"clientjs": ["clientjs/appkeys.js"],
"less": ["less/appkeys.less"],
"css": ["css/appkeys.css"],
}
##~~ BlueprintPlugin mixin
@octoprint.plugin.BlueprintPlugin.route("/probe", methods=["GET"])
@no_firstrun_access
def handle_probe(self):
return NO_CONTENT
@octoprint.plugin.BlueprintPlugin.route("/request", methods=["POST"])
@no_firstrun_access
def handle_request(self):
data = flask.request.json
if data is None:
return flask.make_response("Missing key request", 400)
if not "app" in data:
return flask.make_response("No app name provided", 400)
app_name = data["app"]
user_id = None
if "user" in data and data["user"]:
user_id = data["user"]
app_token, user_token = self._add_pending_decision(app_name, user_id=user_id)
self._plugin_manager.send_plugin_message(
self._identifier,
{
"type": "request_access",
"app_name": app_name,
"user_token": user_token,
"user_id": user_id,
},
)
response = flask.jsonify(app_token=app_token)
response.status_code = 201
response.headers["Location"] = flask.url_for(
".handle_decision_poll", app_token=app_token, _external=True
)
return response
@octoprint.plugin.BlueprintPlugin.route("/request/<app_token>")
@no_firstrun_access
def handle_decision_poll(self, app_token):
result = self._get_pending_by_app_token(app_token)
if result:
for pending_decision in result:
pending_decision.poll_timeout.reset()
response = flask.jsonify(message="Awaiting decision")
response.status_code = 202
return response
result = self._get_decision(app_token)
if result:
return flask.jsonify(api_key=result)
return flask.abort(404)
@octoprint.plugin.BlueprintPlugin.route("/decision/<user_token>", methods=["POST"])
@restricted_access
def handle_decision(self, user_token):
data = flask.request.json
if not "decision" in data:
return flask.make_response("No decision provided", 400)
decision = data["decision"] in valid_boolean_trues
user_id = current_user.get_name()
result = self._set_decision(user_token, decision, user_id)
if not result:
return flask.abort(404)
# Close access_request dialog for this request on all open OctoPrint connections
self._plugin_manager.send_plugin_message(
self._identifier, {"type": "end_request", "user_token": user_token}
)
return NO_CONTENT
def is_blueprint_protected(self):
return False # No API key required to request API access
##~~ SimpleApiPlugin mixin
def get_api_commands(self):
return {"generate": ["app"], "revoke": ["key"]}
def on_api_get(self, request):
user_id = current_user.get_name()
if not user_id:
return flask.abort(403)
if (
request.values.get("all") in valid_boolean_trues
and Permissions.PLUGIN_APPKEYS_ADMIN.can()
):
keys = self._all_api_keys()
else:
keys = self._api_keys_for_user(user_id)
return flask.jsonify(
keys=list(map(lambda x: x.external(), keys)),
pending=dict(
(x.user_token, x.external())
for x in self._get_pending_by_user_id(user_id)
),
)
def on_api_command(self, command, data):
user_id = current_user.get_name()
if not user_id:
return flask.abort(403)
if command == "revoke":
api_key = data.get("key")
if not api_key:
return flask.abort(400)
if not admin_permission.can():
user_for_key = self._user_for_api_key(api_key)
if user_for_key is None or user_for_key.user_id != user_id:
return flask.abort(403)
self._delete_api_key(api_key)
elif command == "generate":
# manual generateKey
app_name = data.get("app")
if not app_name:
return flask.abort(400)
selected_user_id = data.get("user", user_id)
if selected_user_id != user_id and not Permissions.PLUGIN_APPKEYS_ADMIN.can():
return flask.abort(403)
key = self._add_api_key(selected_user_id, app_name.strip())
return flask.jsonify(user_id=selected_user_id, app_id=app_name, api_key=key)
return NO_CONTENT
##~~ key validator hook
def validate_api_key(self, api_key, *args, **kwargs):
return self._user_for_api_key(api_key)
##~~ Helpers
def _add_pending_decision(self, app_name, user_id=None):
app_token = self._generate_key()
user_token = self._generate_key()
with self._pending_lock:
self._remove_stale_pending()
self._pending_decisions.append(
PendingDecision(
app_name,
app_token,
user_id,
user_token,
timeout_callback=self._expire_pending,
)
)
return app_token, user_token
def _get_pending_by_app_token(self, app_token):
result = []
with self._pending_lock:
self._remove_stale_pending()
for data in self._pending_decisions:
if data.app_token == app_token:
result.append(data)
return result
def _get_pending_by_user_id(self, user_id):
result = []
with self._pending_lock:
self._remove_stale_pending()
for data in self._pending_decisions:
if data.user_id == user_id or data.user_id is None:
result.append(data)
return result
def _expire_pending(self, user_token):
with self._pending_lock:
len_before = len(self._pending_decisions)
self._pending_decisions = list(
filter(lambda x: x.user_token != user_token, self._pending_decisions)
)
len_after = len(self._pending_decisions)
if len_after < len_before:
self._plugin_manager.send_plugin_message(
self._identifier, {"type": "end_request", "user_token": user_token}
)
def _remove_stale_pending(self):
with self._pending_lock:
cutoff = monotonic_time() - CUTOFF_TIME
len_before = len(self._pending_decisions)
self._pending_decisions = list(
filter(lambda x: x.created >= cutoff, self._pending_decisions)
)
len_after = len(self._pending_decisions)
if len_after < len_before:
self._logger.info(
"Deleted {} stale pending authorization requests".format(
len_before - len_after
)
)
def _set_decision(self, user_token, decision, user_id):
with self._pending_lock:
self._remove_stale_pending()
for data in self._pending_decisions:
if data.user_token == user_token and (
data.user_id == user_id or data.user_id is None
):
pending = data
break
else:
return False # not found
if decision:
with self._ready_lock:
self._ready_decisions.append(ReadyDecision.for_pending(pending, user_id))
with self._pending_lock:
self._pending_decisions = list(
filter(lambda x: x.user_token != user_token, self._pending_decisions)
)
return True
def _get_decision(self, app_token):
self._remove_stale_pending()
with self._ready_lock:
for data in self._ready_decisions:
if data.app_token == app_token:
decision = data
break
else:
return False # not found
api_key = self._add_api_key(decision.user_id, decision.app_id)
with self._ready_lock:
self._ready_decisions = list(
filter(lambda x: x.app_token != app_token, self._ready_decisions)
)
return api_key
def _add_api_key(self, user_id, app_name):
with self._keys_lock:
for key in self._keys[user_id]:
if key.app_id.lower() == app_name.lower():
return key.api_key
key = ActiveKey(app_name, self._generate_key(), user_id)
self._keys[user_id].append(key)
self._save_keys()
return key.api_key
def _delete_api_key(self, api_key):
with self._keys_lock:
for user_id, data in self._keys.items():
self._keys[user_id] = list(filter(lambda x: x.api_key != api_key, data))
self._save_keys()
def _user_for_api_key(self, api_key):
with self._keys_lock:
for user_id, data in self._keys.items():
if any(filter(lambda x: x.api_key == api_key, data)):
if self._user_manager.enabled:
return self._user_manager.find_user(userid=user_id)
elif user_id == "_admin" or user_id == "dummy":
# dummy = backwards compatible
return self._user_manager.anonymous_user_factory()
return None
def _api_keys_for_user(self, user_id):
with self._keys_lock:
return self._keys[user_id]
def _all_api_keys(self):
with self._keys_lock:
result = []
for user_id, keys in self._keys.items():
result += keys
return result
def _generate_key(self):
return generate_api_key()
def _load_keys(self):
with self._keys_lock:
if not os.path.exists(self._key_path):
return
try:
with io.open(
self._key_path, "rt", encoding="utf-8", errors="strict"
) as f:
persisted = yaml.safe_load(f)
except Exception:
self._logger.exception(
"Could not load application keys from {}".format(self._key_path)
)
return
if not isinstance(persisted, dict):
return
keys = defaultdict(list)
for user_id, persisted_keys in persisted.items():
keys[user_id] = [
ActiveKey.for_internal(x, user_id) for x in persisted_keys
]
self._keys = keys
def _save_keys(self):
with self._keys_lock:
to_persist = {}
for user_id, keys in self._keys.items():
to_persist[user_id] = [x.internal() for x in keys]
try:
with atomic_write(self._key_path, mode="wt") as f:
yaml.safe_dump(to_persist, f, allow_unicode=True)
except Exception:
self._logger.exception(
"Could not write application keys to {}".format(self._key_path)
)
@octoprint.plugin.BlueprintPlugin.route("/request/<app_token>")
@no_firstrun_access
def handle_decision_poll(self, app_token):
result = self._get_pending_by_app_token(app_token)
if result:
for pending_decision in result:
pending_decision.poll_timeout.reset()
response = flask.jsonify(message="Awaiting decision")
response.status_code = 202
return response
result = self._get_decision(app_token)
if result:
return flask.jsonify(api_key=result)
return flask.abort(404)
@octoprint.plugin.BlueprintPlugin.route("/decision/<user_token>", methods=["POST"])
@restricted_access
def handle_decision(self, user_token):
data = flask.request.json
if not "decision" in data:
return flask.make_response("No decision provided", 400)
decision = data["decision"] in valid_boolean_trues
user_id = current_user.get_name()
result = self._set_decision(user_token, decision, user_id)
if not result:
return flask.abort(404)
# Close access_request dialog for this request on all open OctoPrint connections
self._plugin_manager.send_plugin_message(self._identifier, {"type": "end_request",
"user_token": user_token})
return NO_CONTENT
def is_blueprint_protected(self):
return False # No API key required to request API access
##~~ SimpleApiPlugin mixin
def get_api_commands(self):
return {"generate": ["app"],
"revoke": ["key"]}
def on_api_get(self, request):
user_id = current_user.get_name()
if not user_id:
return flask.abort(403)
if request.values.get("all") in valid_boolean_trues and Permissions.PLUGIN_APPKEYS_ADMIN.can():
keys = self._all_api_keys()
else:
keys = self._api_keys_for_user(user_id)
return flask.jsonify(keys=list(map(lambda x: x.external(), keys)),
pending=dict((x.user_token, x.external()) for x in self._get_pending_by_user_id(user_id)))
def on_api_command(self, command, data):
user_id = current_user.get_name()
if not user_id:
return flask.abort(403)
if command == "revoke":
api_key = data.get("key")
if not api_key:
return flask.abort(400)
if not admin_permission.can():
user_for_key = self._user_for_api_key(api_key)
if user_for_key is None or user_for_key.user_id != user_id:
return flask.abort(403)
self._delete_api_key(api_key)
elif command == "generate":
# manual generateKey
app_name = data.get("app")
if not app_name:
return flask.abort(400)
selected_user_id = data.get("user", user_id)
if selected_user_id != user_id and not Permissions.PLUGIN_APPKEYS_ADMIN.can():
return flask.abort(403)
key = self._add_api_key(selected_user_id, app_name.strip())
return flask.jsonify(user_id=selected_user_id, app_id=app_name, api_key=key)
return NO_CONTENT
##~~ key validator hook
def validate_api_key(self, api_key, *args, **kwargs):
return self._user_for_api_key(api_key)
##~~ Helpers
def _add_pending_decision(self, app_name, user_id=None):
app_token = self._generate_key()
user_token = self._generate_key()
with self._pending_lock:
self._remove_stale_pending()
self._pending_decisions.append(PendingDecision(app_name, app_token, user_id, user_token,
timeout_callback=self._expire_pending))
return app_token, user_token
def _get_pending_by_app_token(self, app_token):
result = []
with self._pending_lock:
self._remove_stale_pending()
for data in self._pending_decisions:
if data.app_token == app_token:
result.append(data)
return result
def _get_pending_by_user_id(self, user_id):
result = []
with self._pending_lock:
self._remove_stale_pending()
for data in self._pending_decisions:
if data.user_id == user_id or data.user_id is None:
result.append(data)
return result
def _expire_pending(self, user_token):
with self._pending_lock:
len_before = len(self._pending_decisions)
self._pending_decisions = list(filter(lambda x: x.user_token != user_token,
self._pending_decisions))
len_after = len(self._pending_decisions)
if len_after < len_before:
self._plugin_manager.send_plugin_message(self._identifier, {"type": "end_request",
"user_token": user_token})
def _remove_stale_pending(self):
with self._pending_lock:
cutoff = monotonic_time() - CUTOFF_TIME
len_before = len(self._pending_decisions)
self._pending_decisions = list(filter(lambda x: x.created >= cutoff,
self._pending_decisions))
len_after = len(self._pending_decisions)
if len_after < len_before:
self._logger.info("Deleted {} stale pending authorization requests".format(len_before - len_after))
def _set_decision(self, user_token, decision, user_id):
with self._pending_lock:
self._remove_stale_pending()
for data in self._pending_decisions:
if data.user_token == user_token and (data.user_id == user_id or data.user_id is None):
pending = data
break
else:
return False # not found
if decision:
with self._ready_lock:
self._ready_decisions.append(ReadyDecision.for_pending(pending, user_id))
with self._pending_lock:
self._pending_decisions = list(filter(lambda x: x.user_token != user_token,
self._pending_decisions))
return True
def _get_decision(self, app_token):
self._remove_stale_pending()
with self._ready_lock:
for data in self._ready_decisions:
if data.app_token == app_token:
decision = data
break
else:
return False # not found
api_key = self._add_api_key(decision.user_id, decision.app_id)
with self._ready_lock:
self._ready_decisions = list(filter(lambda x: x.app_token != app_token,
self._ready_decisions))
return api_key
def _add_api_key(self, user_id, app_name):
with self._keys_lock:
for key in self._keys[user_id]:
if key.app_id.lower() == app_name.lower():
return key.api_key
key = ActiveKey(app_name, self._generate_key(), user_id)
self._keys[user_id].append(key)
self._save_keys()
return key.api_key
def _delete_api_key(self, api_key):
with self._keys_lock:
for user_id, data in self._keys.items():
self._keys[user_id] = list(filter(lambda x: x.api_key != api_key, data))
self._save_keys()
def _user_for_api_key(self, api_key):
with self._keys_lock:
for user_id, data in self._keys.items():
if any(filter(lambda x: x.api_key == api_key, data)):
if self._user_manager.enabled:
return self._user_manager.find_user(userid=user_id)
elif user_id == "_admin" or user_id == "dummy":
# dummy = backwards compatible
return self._user_manager.anonymous_user_factory()
return None
def _api_keys_for_user(self, user_id):
with self._keys_lock:
return self._keys[user_id]
def _all_api_keys(self):
with self._keys_lock:
result = []
for user_id, keys in self._keys.items():
result += keys
return result
def _generate_key(self):
return generate_api_key()
def _load_keys(self):
with self._keys_lock:
if not os.path.exists(self._key_path):
return
try:
with io.open(self._key_path, 'rt', encoding="utf-8", errors="strict") as f:
persisted = yaml.safe_load(f)
except Exception:
self._logger.exception("Could not load application keys from {}".format(self._key_path))
return
if not isinstance(persisted, dict):
return
keys = defaultdict(list)
for user_id, persisted_keys in persisted.items():
keys[user_id] = [ActiveKey.for_internal(x, user_id) for x in persisted_keys]
self._keys = keys
def _save_keys(self):
with self._keys_lock:
to_persist = {}
for user_id, keys in self._keys.items():
to_persist[user_id] = [x.internal() for x in keys]
try:
with atomic_write(self._key_path, mode='wt') as f:
yaml.safe_dump(to_persist, f, allow_unicode=True)
except Exception:
self._logger.exception("Could not write application keys to {}".format(self._key_path))
__plugin_name__ = "Application Keys Plugin"
__plugin_description__ = "Implements a workflow for third party clients to obtain API keys"
__plugin_description__ = (
"Implements a workflow for third party clients to obtain API keys"
)
__plugin_author__ = "Gina Häußge, Aldo Hoeben"
__plugin_disabling_discouraged__ = gettext("Without this plugin third party clients will no longer be able to "
"obtain an API key without you manually copy-pasting it.")
__plugin_disabling_discouraged__ = gettext(
"Without this plugin third party clients will no longer be able to "
"obtain an API key without you manually copy-pasting it."
)
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = AppKeysPlugin()
__plugin_hooks__ = {
"octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
"octoprint.accesscontrol.keyvalidator": __plugin_implementation__.validate_api_key,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions,
}
File diff suppressed because it is too large. Load diff
+94 -80
View File
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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 octoprint.plugin
@@ -10,116 +10,130 @@ from flask_babel import gettext
from .subwizards import Subwizards
class CoreWizardPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.WizardPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.BlueprintPlugin,
Subwizards):
class CoreWizardPlugin(
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.WizardPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.BlueprintPlugin,
Subwizards,
):
#~~ TemplatePlugin API
# ~~ TemplatePlugin API
def get_template_configs(self):
required = self._get_subwizard_attrs("_is_", "_wizard_required")
names = self._get_subwizard_attrs("_get_", "_wizard_name")
additional = self._get_subwizard_attrs("_get_", "_additional_wizard_template_data")
def get_template_configs(self):
required = self._get_subwizard_attrs("_is_", "_wizard_required")
names = self._get_subwizard_attrs("_get_", "_wizard_name")
additional = self._get_subwizard_attrs(
"_get_", "_additional_wizard_template_data"
)
firstrunonly = self._get_subwizard_attrs("_is_", "_wizard_firstrunonly")
firstrun = self._settings.global_get(["server", "firstRun"])
firstrunonly = self._get_subwizard_attrs("_is_", "_wizard_firstrunonly")
firstrun = self._settings.global_get(["server", "firstRun"])
if not firstrun:
required = dict((key, value) for key, value in required.items()
if not firstrunonly.get(key, lambda: False)())
if not firstrun:
required = dict(
(key, value)
for key, value in required.items()
if not firstrunonly.get(key, lambda: False)()
)
result = list()
for key, method in required.items():
if not callable(method):
continue
result = list()
for key, method in required.items():
if not callable(method):
continue
if not method():
continue
if not method():
continue
if not key in names:
continue
if not key in names:
continue
name = names[key]()
if not name:
continue
name = names[key]()
if not name:
continue
config = {"type": "wizard",
"name": name,
"template": "corewizard_{}_wizard.jinja2".format(key),
"div": "wizard_plugin_corewizard_{}".format(key),
"suffix": "_{}".format(key)}
if key in additional:
additional_result = additional[key]()
if additional_result:
config.update(additional_result)
result.append(config)
config = {
"type": "wizard",
"name": name,
"template": "corewizard_{}_wizard.jinja2".format(key),
"div": "wizard_plugin_corewizard_{}".format(key),
"suffix": "_{}".format(key),
}
if key in additional:
additional_result = additional[key]()
if additional_result:
config.update(additional_result)
result.append(config)
return result
return result
#~~ AssetPlugin API
# ~~ AssetPlugin API
def get_assets(self):
if self.is_wizard_required():
return {"js": ["js/corewizard.js"],
"css": ["css/corewizard.css"]}
else:
return {}
def get_assets(self):
if self.is_wizard_required():
return {"js": ["js/corewizard.js"], "css": ["css/corewizard.css"]}
else:
return {}
#~~ WizardPlugin API
# ~~ WizardPlugin API
def is_wizard_required(self):
required = self._get_subwizard_attrs("_is_", "_wizard_required")
firstrunonly = self._get_subwizard_attrs("_is_", "_wizard_firstrunonly")
firstrun = self._settings.global_get(["server", "firstRun"])
def is_wizard_required(self):
required = self._get_subwizard_attrs("_is_", "_wizard_required")
firstrunonly = self._get_subwizard_attrs("_is_", "_wizard_firstrunonly")
firstrun = self._settings.global_get(["server", "firstRun"])
if not firstrun:
required = dict((key, value) for key, value in required.items()
if not firstrunonly.get(key, lambda: False)())
any_required = any(map(lambda m: m(), required.values()))
if not firstrun:
required = dict(
(key, value)
for key, value in required.items()
if not firstrunonly.get(key, lambda: False)()
)
any_required = any(map(lambda m: m(), required.values()))
return any_required
return any_required
def get_wizard_details(self):
result = {}
def get_wizard_details(self):
result = {}
def add_result(key, method):
result[key] = method()
self._get_subwizard_attrs("_get_", "_wizard_details", add_result)
def add_result(key, method):
result[key] = method()
return result
self._get_subwizard_attrs("_get_", "_wizard_details", add_result)
def get_wizard_version(self):
return 3
return result
#~~ helpers
def get_wizard_version(self):
return 3
def _get_subwizard_attrs(self, start, end, callback=None):
result = {}
# ~~ helpers
for item in dir(self):
if not item.startswith(start) or not item.endswith(end):
continue
def _get_subwizard_attrs(self, start, end, callback=None):
result = {}
key = item[len(start):-len(end)]
if not key:
continue
for item in dir(self):
if not item.startswith(start) or not item.endswith(end):
continue
attr = getattr(self, item)
if callable(callback):
callback(key, attr)
result[key] = attr
key = item[len(start) : -len(end)]
if not key:
continue
return result
attr = getattr(self, item)
if callable(callback):
callback(key, attr)
result[key] = attr
return result
__plugin_name__ = "Core Wizard"
__plugin_author__ = "Gina Häußge"
__plugin_description__ = "Provides wizard dialogs for core components and functionality"
__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to perform "
"setup steps that might be required after an update.")
__plugin_disabling_discouraged__ = gettext(
"Without this plugin OctoPrint will no longer be able to perform "
"setup steps that might be required after an update."
)
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = CoreWizardPlugin()
+118 -87
View File
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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 octoprint.plugin
@@ -14,139 +14,170 @@ from octoprint.util import to_native_str
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class ServerCommandsSubwizard(object):
def _is_servercommands_wizard_firstrunonly(self):
return True
def _is_servercommands_wizard_firstrunonly(self):
return True
def _is_servercommands_wizard_required(self):
system_shutdown_command = self._settings.global_get(["server", "commands", "systemShutdownCommand"])
system_restart_command = self._settings.global_get(["server", "commands", "systemRestartCommand"])
server_restart_command = self._settings.global_get(["server", "commands", "serverRestartCommand"])
def _is_servercommands_wizard_required(self):
system_shutdown_command = self._settings.global_get(
["server", "commands", "systemShutdownCommand"]
)
system_restart_command = self._settings.global_get(
["server", "commands", "systemRestartCommand"]
)
server_restart_command = self._settings.global_get(
["server", "commands", "serverRestartCommand"]
)
return not (system_shutdown_command and system_restart_command and server_restart_command)
return not (
system_shutdown_command and system_restart_command and server_restart_command
)
def _get_servercommands_wizard_details(self):
return {"required": self._is_servercommands_wizard_required()}
def _get_servercommands_wizard_details(self):
return {"required": self._is_servercommands_wizard_required()}
def _get_servercommands_wizard_name(self):
return gettext("Server Commands")
def _get_servercommands_wizard_name(self):
return gettext("Server Commands")
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class WebcamSubwizard(object):
def _is_webcam_wizard_firstrunonly(self):
return True
def _is_webcam_wizard_firstrunonly(self):
return True
def _is_webcam_wizard_required(self):
webcam_snapshot_url = self._settings.global_get(["webcam", "snapshot"])
webcam_stream_url = self._settings.global_get(["webcam", "stream"])
ffmpeg_path = self._settings.global_get(["webcam", "ffmpeg"])
def _is_webcam_wizard_required(self):
webcam_snapshot_url = self._settings.global_get(["webcam", "snapshot"])
webcam_stream_url = self._settings.global_get(["webcam", "stream"])
ffmpeg_path = self._settings.global_get(["webcam", "ffmpeg"])
return not (webcam_snapshot_url and webcam_stream_url and ffmpeg_path)
return not (webcam_snapshot_url and webcam_stream_url and ffmpeg_path)
def _get_webcam_wizard_details(self):
return {"required": self._is_webcam_wizard_required()}
def _get_webcam_wizard_details(self):
return {"required": self._is_webcam_wizard_required()}
def _get_webcam_wizard_name(self):
return gettext("Webcam & Timelapse")
def _get_webcam_wizard_name(self):
return gettext("Webcam & Timelapse")
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class AclSubwizard(object):
def _is_acl_wizard_firstrunonly(self):
return True
def _is_acl_wizard_firstrunonly(self):
return True
def _is_acl_wizard_required(self):
return self._user_manager.enabled and not self._user_manager.has_been_customized()
def _is_acl_wizard_required(self):
return self._user_manager.enabled and not self._user_manager.has_been_customized()
def _get_acl_wizard_details(self):
return {"required": self._is_acl_wizard_required()}
def _get_acl_wizard_details(self):
return {"required": self._is_acl_wizard_required()}
def _get_acl_wizard_name(self):
return gettext("Access Control")
def _get_acl_wizard_name(self):
return gettext("Access Control")
def _get_acl_additional_wizard_template_data(self):
return {"mandatory": self._is_acl_wizard_required()}
def _get_acl_additional_wizard_template_data(self):
return {"mandatory": self._is_acl_wizard_required()}
@octoprint.plugin.BlueprintPlugin.route("/acl", methods=["POST"])
def acl_wizard_api(self):
from flask import request, abort
from octoprint.server.api import valid_boolean_trues, NO_CONTENT
@octoprint.plugin.BlueprintPlugin.route("/acl", methods=["POST"])
def acl_wizard_api(self):
from flask import request, abort
from octoprint.server.api import valid_boolean_trues, NO_CONTENT
if not self._settings.global_get(["server", "firstRun"]) or self._user_manager.has_been_customized():
abort(404)
if (
not self._settings.global_get(["server", "firstRun"])
or self._user_manager.has_been_customized()
):
abort(404)
data = request.get_json()
if data is None:
data = request.values
data = request.get_json()
if data is None:
data = request.values
if "ac" in data and data["ac"] in valid_boolean_trues and \
"user" in data and "pass1" in data and \
"pass2" in data and data["pass1"] == data["pass2"]:
# configure access control
self._settings.global_set_boolean(["accessControl", "enabled"], True)
self._user_manager.enable()
if (
"ac" in data
and data["ac"] in valid_boolean_trues
and "user" in data
and "pass1" in data
and "pass2" in data
and data["pass1"] == data["pass2"]
):
# configure access control
self._settings.global_set_boolean(["accessControl", "enabled"], True)
self._user_manager.enable()
self._user_manager.add_user(data["user"], data["pass1"], True, [], [USER_GROUP, ADMIN_GROUP], overwrite=True)
elif "ac" in data and not data["ac"] in valid_boolean_trues:
# disable access control
self._settings.global_set_boolean(["accessControl", "enabled"], False)
self._user_manager.disable()
self._settings.save()
return NO_CONTENT
self._user_manager.add_user(
data["user"],
data["pass1"],
True,
[],
[USER_GROUP, ADMIN_GROUP],
overwrite=True,
)
elif "ac" in data and not data["ac"] in valid_boolean_trues:
# disable access control
self._settings.global_set_boolean(["accessControl", "enabled"], False)
self._user_manager.disable()
self._settings.save()
return NO_CONTENT
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class OnlineCheckSubwizard(object):
def _is_onlinecheck_wizard_firstrunonly(self):
return False
def _is_onlinecheck_wizard_firstrunonly(self):
return False
def _is_onlinecheck_wizard_required(self):
return self._settings.global_get(["server", "onlineCheck", "enabled"]) is None
def _is_onlinecheck_wizard_required(self):
return self._settings.global_get(["server", "onlineCheck", "enabled"]) is None
def _get_onlinecheck_wizard_details(self):
return {"required": self._is_onlinecheck_wizard_required()}
def _get_onlinecheck_wizard_details(self):
return {"required": self._is_onlinecheck_wizard_required()}
def _get_onlinecheck_wizard_name(self):
return gettext("Online Connectivity Check")
def _get_onlinecheck_wizard_name(self):
return gettext("Online Connectivity Check")
def _get_onlinecheck_additional_wizard_template_data(self):
return {"mandatory": self._is_onlinecheck_wizard_required()}
def _get_onlinecheck_additional_wizard_template_data(self):
return {"mandatory": self._is_onlinecheck_wizard_required()}
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class PluginBlacklistSubwizard(object):
def _is_pluginblacklist_wizard_firstrunonly(self):
return False
def _is_pluginblacklist_wizard_firstrunonly(self):
return False
def _is_pluginblacklist_wizard_required(self):
return self._settings.global_get(["server", "pluginBlacklist", "enabled"]) is None
def _is_pluginblacklist_wizard_required(self):
return self._settings.global_get(["server", "pluginBlacklist", "enabled"]) is None
def _get_pluginblacklist_wizard_details(self):
return {"required": self._is_pluginblacklist_wizard_required()}
def _get_pluginblacklist_wizard_details(self):
return {"required": self._is_pluginblacklist_wizard_required()}
def _get_pluginblacklist_wizard_name(self):
return gettext("Plugin Blacklist")
def _get_pluginblacklist_wizard_name(self):
return gettext("Plugin Blacklist")
def _get_pluginblacklist_additional_wizard_template_data(self):
return {"mandatory": self._is_pluginblacklist_wizard_required()}
def _get_pluginblacklist_additional_wizard_template_data(self):
return {"mandatory": self._is_pluginblacklist_wizard_required()}
# noinspection PyUnresolvedReferences,PyMethodMayBeStatic
class PrinterProfileSubwizard(object):
def _is_printerprofile_wizard_firstrunonly(self):
return True
def _is_printerprofile_wizard_firstrunonly(self):
return True
def _is_printerprofile_wizard_required(self):
return self._printer_profile_manager.is_default_unmodified() and self._printer_profile_manager.profile_count == 1
def _is_printerprofile_wizard_required(self):
return (
self._printer_profile_manager.is_default_unmodified()
and self._printer_profile_manager.profile_count == 1
)
def _get_printerprofile_wizard_details(self):
return {"required": self._is_printerprofile_wizard_required()}
def _get_printerprofile_wizard_details(self):
return {"required": self._is_printerprofile_wizard_required()}
def _get_printerprofile_wizard_name(self):
return gettext("Default Printer Profile")
def _get_printerprofile_wizard_name(self):
return gettext("Default Printer Profile")
Subwizards = type(to_native_str("Subwizards"),
tuple(cls for clsname, cls in inspect.getmembers(sys.modules[__name__], inspect.isclass)
if clsname.endswith("Subwizard")),
{})
Subwizards = type(
to_native_str("Subwizards"),
tuple(
cls
for clsname, cls in inspect.getmembers(sys.modules[__name__], inspect.isclass)
if clsname.endswith("Subwizard")
),
{},
)
File diff suppressed because it is too large. Load diff
+183 -138
View File
@@ -1,26 +1,35 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License"
import octoprint.plugin
import logging
from octoprint.util import get_fully_qualified_classname as fqcn
from octoprint.util.version import get_octoprint_version_string, is_released_octoprint_version
from octoprint.util.version import (
get_octoprint_version_string,
is_released_octoprint_version,
)
from flask import jsonify
from flask_babel import gettext
SENTRY_URL_SERVER = "https://d479a74f172d4ac2b959a9a7d0536a82@o118517.ingest.sentry.io/1373987"
SENTRY_URL_COREUI = "https://040577fb88b241ff985e408c11775720@o118517.ingest.sentry.io/1374096"
SENTRY_URL_SERVER = (
"https://d479a74f172d4ac2b959a9a7d0536a82@o118517.ingest.sentry.io/1373987"
)
SENTRY_URL_COREUI = (
"https://040577fb88b241ff985e408c11775720@o118517.ingest.sentry.io/1374096"
)
SETTINGS_DEFAULTS = {"enabled": False,
"enabled_unreleased": False,
"unique_id": None,
"url_server": SENTRY_URL_SERVER,
"url_coreui": SENTRY_URL_COREUI}
SETTINGS_DEFAULTS = {
"enabled": False,
"enabled_unreleased": False,
"unique_id": None,
"url_server": SENTRY_URL_SERVER,
"url_coreui": SENTRY_URL_COREUI,
}
import serial
import requests.exceptions
@@ -28,181 +37,217 @@ import errno
import tornado.websocket
IGNORED_EXCEPTIONS = [
# serial exceptions in octoprint.util.comm
(serial.SerialException, lambda exc, logger, plugin, cb: logger == "octoprint.util.comm"),
# KeyboardInterrupts
KeyboardInterrupt,
# IOErrors of any kind due to a full file system
(IOError, lambda exc, logger, plugin, cb: getattr(exc, "errno") and exc.errno in (getattr(errno, "ENOSPC"),)),
# RequestExceptions of any kind
requests.exceptions.RequestException,
# Tornado WebSocketErrors of any kind
tornado.websocket.WebSocketError,
# Anything triggered by or in third party plugin Astroprint
(Exception, lambda exc, logger, plugin, cb: logger.startswith("octoprint.plugins.astroprint")
or plugin == "astroprint"
or cb.startswith("octoprint_astroprint."))
# serial exceptions in octoprint.util.comm
(
serial.SerialException,
lambda exc, logger, plugin, cb: logger == "octoprint.util.comm",
),
# KeyboardInterrupts
KeyboardInterrupt,
# IOErrors of any kind due to a full file system
(
IOError,
lambda exc, logger, plugin, cb: getattr(exc, "errno")
and exc.errno in (getattr(errno, "ENOSPC"),),
),
# RequestExceptions of any kind
requests.exceptions.RequestException,
# Tornado WebSocketErrors of any kind
tornado.websocket.WebSocketError,
# Anything triggered by or in third party plugin Astroprint
(
Exception,
lambda exc, logger, plugin, cb: logger.startswith("octoprint.plugins.astroprint")
or plugin == "astroprint"
or cb.startswith("octoprint_astroprint."),
),
]
try:
# noinspection PyUnresolvedReferences
from octoprint.plugins.backup import InsufficientSpace
# noinspection PyUnresolvedReferences
from octoprint.plugins.backup import InsufficientSpace
# if the backup plugin is enabled, ignore InsufficientSpace errors from it as well
IGNORED_EXCEPTIONS.append(InsufficientSpace)
# if the backup plugin is enabled, ignore InsufficientSpace errors from it as well
IGNORED_EXCEPTIONS.append(InsufficientSpace)
del InsufficientSpace
del InsufficientSpace
except ImportError:
pass
pass
class ErrorTrackingPlugin(octoprint.plugin.SettingsPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.SimpleApiPlugin):
class ErrorTrackingPlugin(
octoprint.plugin.SettingsPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.SimpleApiPlugin,
):
def get_template_configs(self):
return [
{
"type": "settings",
"name": gettext("Error Tracking"),
"template": "errortracking_settings.jinja2",
"custom_bindings": False,
},
{"type": "generic", "template": "errortracking_javascripts.jinja2"},
]
def get_template_configs(self):
return [{"type": "settings",
"name": gettext("Error Tracking"),
"template": "errortracking_settings.jinja2",
"custom_bindings": False},
{"type": "generic",
"template": "errortracking_javascripts.jinja2"}]
def get_template_vars(self):
enabled = self._settings.get_boolean(["enabled"])
enabled_unreleased = self._settings.get_boolean(["enabled_unreleased"])
def get_template_vars(self):
enabled = self._settings.get_boolean(["enabled"])
enabled_unreleased = self._settings.get_boolean(["enabled_unreleased"])
return {
"enabled": _is_enabled(enabled, enabled_unreleased),
"unique_id": self._settings.get(["unique_id"]),
"url_coreui": self._settings.get(["url_coreui"]),
}
return {"enabled": _is_enabled(enabled, enabled_unreleased),
"unique_id": self._settings.get(["unique_id"]),
"url_coreui": self._settings.get(["url_coreui"])}
def get_assets(self):
return {"js": ["js/sentry.min.js", "js/errortracking.js"]}
def get_assets(self):
return {"js": ["js/sentry.min.js", "js/errortracking.js"]}
def get_settings_defaults(self):
return SETTINGS_DEFAULTS
def get_settings_defaults(self):
return SETTINGS_DEFAULTS
def on_settings_save(self, data):
old_enabled = _is_enabled(
self._settings.get_boolean(["enabled"]),
self._settings.get_boolean(["enabled_unreleased"]),
)
def on_settings_save(self, data):
old_enabled = _is_enabled(self._settings.get_boolean(["enabled"]),
self._settings.get_boolean(["enabled_unreleased"]))
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
enabled = _is_enabled(
self._settings.get_boolean(["enabled"]),
self._settings.get_boolean(["enabled_unreleased"]),
)
enabled = _is_enabled(self._settings.get_boolean(["enabled"]),
self._settings.get_boolean(["enabled_unreleased"]))
if old_enabled != enabled:
_enable_errortracking()
if old_enabled != enabled:
_enable_errortracking()
def on_api_get(self, request):
return jsonify(**self.get_template_vars())
def on_api_get(self, request):
return jsonify(**self.get_template_vars())
_enabled = False
def _enable_errortracking():
# this is a bit hackish, but we want to enable error tracking as early in the platform lifecycle as possible
# and hence can't wait until our implementation is initialized and injected with settings
# this is a bit hackish, but we want to enable error tracking as early in the platform lifecycle as possible
# and hence can't wait until our implementation is initialized and injected with settings
from octoprint.settings import settings
global _enabled
from octoprint.settings import settings
if _enabled:
return
global _enabled
version = get_octoprint_version_string()
if _enabled:
return
s = settings()
plugin_defaults = {"plugins": {"errortracking": SETTINGS_DEFAULTS}}
version = get_octoprint_version_string()
enabled = s.getBoolean(["plugins", "errortracking", "enabled"], defaults=plugin_defaults)
enabled_unreleased = s.getBoolean(["plugins", "errortracking", "enabled_unreleased"], defaults=plugin_defaults)
url_server = s.get(["plugins", "errortracking", "url_server"], defaults=plugin_defaults)
unique_id = s.get(["plugins", "errortracking", "unique_id"], defaults=plugin_defaults)
if unique_id is None:
import uuid
unique_id = str(uuid.uuid4())
s.set(["plugins", "errortracking", "unique_id"], unique_id, defaults=plugin_defaults)
s.save()
s = settings()
plugin_defaults = {"plugins": {"errortracking": SETTINGS_DEFAULTS}}
if _is_enabled(enabled, enabled_unreleased):
import sentry_sdk
from octoprint.plugin import plugin_manager
enabled = s.getBoolean(
["plugins", "errortracking", "enabled"], defaults=plugin_defaults
)
enabled_unreleased = s.getBoolean(
["plugins", "errortracking", "enabled_unreleased"], defaults=plugin_defaults
)
url_server = s.get(
["plugins", "errortracking", "url_server"], defaults=plugin_defaults
)
unique_id = s.get(["plugins", "errortracking", "unique_id"], defaults=plugin_defaults)
if unique_id is None:
import uuid
def _before_send(event, hint):
if not "exc_info" in hint:
# we only want exceptions
return None
unique_id = str(uuid.uuid4())
s.set(
["plugins", "errortracking", "unique_id"], unique_id, defaults=plugin_defaults
)
s.save()
handled = True
logger = event.get("logger", "")
plugin = event.get("extra", {}).get("plugin", None)
callback = event.get("extra", {}).get("callback", None)
if _is_enabled(enabled, enabled_unreleased):
import sentry_sdk
from octoprint.plugin import plugin_manager
for ignore in IGNORED_EXCEPTIONS:
if isinstance(ignore, tuple):
ignored_exc, matcher = ignore
else:
ignored_exc = ignore
matcher = lambda *args: True
def _before_send(event, hint):
if not "exc_info" in hint:
# we only want exceptions
return None
exc = hint["exc_info"][1]
if isinstance(exc, ignored_exc) and matcher(exc, logger, plugin, callback):
# exception ignored for logger, plugin and/or callback
return None
handled = True
logger = event.get("logger", "")
plugin = event.get("extra", {}).get("plugin", None)
callback = event.get("extra", {}).get("callback", None)
elif isinstance(ignore, type):
if isinstance(hint["exc_info"][1], ignore):
# exception ignored
return None
for ignore in IGNORED_EXCEPTIONS:
if isinstance(ignore, tuple):
ignored_exc, matcher = ignore
else:
ignored_exc = ignore
matcher = lambda *args: True
if event.get("exception") and event["exception"].get("values"):
handled = not any(map(lambda x: x.get("mechanism") and x["mechanism"].get("handled", True) == False,
event["exception"]["values"]))
exc = hint["exc_info"][1]
if isinstance(exc, ignored_exc) and matcher(
exc, logger, plugin, callback
):
# exception ignored for logger, plugin and/or callback
return None
if handled:
# error is handled, restrict further based on logger
if logger != "" and not (logger.startswith("octoprint.") or logger.startswith("tornado.")):
# we only want errors logged by loggers octoprint.* or tornado.*
return None
elif isinstance(ignore, type):
if isinstance(hint["exc_info"][1], ignore):
# exception ignored
return None
if logger.startswith("octoprint.plugins."):
plugin_id = logger.split(".")[2]
plugin_info = plugin_manager().get_plugin_info(plugin_id)
if plugin_info is None or not plugin_info.bundled:
# we only want our active bundled plugins
return None
if event.get("exception") and event["exception"].get("values"):
handled = not any(
map(
lambda x: x.get("mechanism")
and x["mechanism"].get("handled", True) == False,
event["exception"]["values"],
)
)
if plugin is not None:
plugin_info = plugin_manager().get_plugin_info(plugin)
if plugin_info is None or not plugin_info.bundled:
# we only want our active bundled plugins
return None
if handled:
# error is handled, restrict further based on logger
if logger != "" and not (
logger.startswith("octoprint.") or logger.startswith("tornado.")
):
# we only want errors logged by loggers octoprint.* or tornado.*
return None
return event
if logger.startswith("octoprint.plugins."):
plugin_id = logger.split(".")[2]
plugin_info = plugin_manager().get_plugin_info(plugin_id)
if plugin_info is None or not plugin_info.bundled:
# we only want our active bundled plugins
return None
sentry_sdk.init(url_server,
release=version,
before_send=_before_send)
if plugin is not None:
plugin_info = plugin_manager().get_plugin_info(plugin)
if plugin_info is None or not plugin_info.bundled:
# we only want our active bundled plugins
return None
with sentry_sdk.configure_scope() as scope:
scope.user = {"id": unique_id}
return event
logging.getLogger("octoprint.plugins.errortracking").info("Initialized error tracking")
_enabled = True
sentry_sdk.init(url_server, release=version, before_send=_before_send)
with sentry_sdk.configure_scope() as scope:
scope.user = {"id": unique_id}
logging.getLogger("octoprint.plugins.errortracking").info(
"Initialized error tracking"
)
_enabled = True
def _is_enabled(enabled, enabled_unreleased):
return enabled and (enabled_unreleased or is_released_octoprint_version())
return enabled and (enabled_unreleased or is_released_octoprint_version())
def __plugin_enable__():
_enable_errortracking()
_enable_errortracking()
__plugin_name__ = "Error Tracking"
+61 -46
View File
@@ -1,69 +1,84 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License"
import octoprint.plugin
from flask_babel import gettext
class GcodeviewerPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.SettingsPlugin):
def get_assets(self):
js = ["js/gcodeviewer.js",
"js/viewer/ui.js",
"js/viewer/reader.js",
"js/viewer/renderer.js"
]
class GcodeviewerPlugin(
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.SettingsPlugin,
):
def get_assets(self):
js = [
"js/gcodeviewer.js",
"js/viewer/ui.js",
"js/viewer/reader.js",
"js/viewer/renderer.js",
]
return {"js": js,
"less": ["less/gcodeviewer.less"],
"css": ["css/gcodeviewer.css"]}
return {
"js": js,
"less": ["less/gcodeviewer.less"],
"css": ["css/gcodeviewer.css"],
}
def get_template_configs(self):
return [
{"type": "tab",
"template": "gcodeviewer_tab.jinja2",
"div": "gcode",
"styles": ["display: none;"],
"data_bind": "visible: loginState.hasAllPermissionsKo(access.permissions.GCODE_VIEWER, access.permissions.FILES_DOWNLOAD)"},
{"type": "settings",
"template": "gcodeviewer_settings.jinja2",
"custom_bindings": True},
{"type": "generic",
"template": "gcodeviewer_initscript.jinja2"}
]
def get_template_configs(self):
return [
{
"type": "tab",
"template": "gcodeviewer_tab.jinja2",
"div": "gcode",
"styles": ["display: none;"],
"data_bind": "visible: loginState.hasAllPermissionsKo(access.permissions.GCODE_VIEWER, access.permissions.FILES_DOWNLOAD)",
},
{
"type": "settings",
"template": "gcodeviewer_settings.jinja2",
"custom_bindings": True,
},
{"type": "generic", "template": "gcodeviewer_initscript.jinja2"},
]
def get_settings_defaults(self):
return {"mobileSizeThreshold": 2 * 1024 * 1024, # 2MB
"sizeThreshold": 20 * 1024 * 1024} # 20MB
def get_settings_defaults(self):
return {
"mobileSizeThreshold": 2 * 1024 * 1024, # 2MB
"sizeThreshold": 20 * 1024 * 1024,
} # 20MB
def get_settings_version(self):
return 1
def get_settings_version(self):
return 1
def on_settings_migrate(self, target, current):
if current is None:
config = self._settings.global_get(["gcodeViewer"])
if config:
self._logger.info("Migrating settings from gcodeViewer to plugins.gcodeviewer...")
if "mobileSizeThreshold" in config:
self._settings.set_int(["mobileSizeThreshold"], config["mobileSizeThreshold"])
if "sizeThreshold" in config:
self._settings.set_int(["sizeThreshold"], config["sizeThreshold"])
self._settings.global_remove(["gcodeViewer"])
def on_settings_migrate(self, target, current):
if current is None:
config = self._settings.global_get(["gcodeViewer"])
if config:
self._logger.info(
"Migrating settings from gcodeViewer to plugins.gcodeviewer..."
)
if "mobileSizeThreshold" in config:
self._settings.set_int(
["mobileSizeThreshold"], config["mobileSizeThreshold"]
)
if "sizeThreshold" in config:
self._settings.set_int(["sizeThreshold"], config["sizeThreshold"])
self._settings.global_remove(["gcodeViewer"])
__plugin_name__ = gettext("GCode Viewer")
__plugin_author__ = "Gina Häußge"
__plugin_description__ = "Provides a GCODE viewer in OctoPrint's UI."
__plugin_disabling_discouraged__ = gettext("Without this plugin the GCode Viewer in OctoPrint will no longer be "
"available.")
__plugin_disabling_discouraged__ = gettext(
"Without this plugin the GCode Viewer in OctoPrint will no longer be " "available."
)
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = GcodeviewerPlugin()
#__plugin_hooks__ = {
# "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
#}
# __plugin_hooks__ = {
# "octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
# }
+215 -172
View File
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import octoprint.plugin
@@ -23,221 +23,264 @@ import io
import os
try:
from os import scandir
from os import scandir
except ImportError:
from scandir import scandir
from scandir import scandir
class LoggingPlugin(octoprint.plugin.AssetPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.BlueprintPlugin):
# Additional permissions hook
class LoggingPlugin(
octoprint.plugin.AssetPlugin,
octoprint.plugin.SettingsPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.BlueprintPlugin,
):
def get_additional_permissions(self):
return [
{"key": "MANAGE",
"name": "Logging management",
"description": gettext("Allows to download and delete log files and list and set log levels."),
"default_groups": [ADMIN_GROUP],
"roles": ["manage"]}
]
# Additional permissions hook
@octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def get_all(self):
files = self._getLogFiles()
free, total = self._get_usage()
loggers = self._get_available_loggers()
levels = self._get_logging_levels()
serial_log_enabled = self._settings.global_get_boolean(["serial", "log"])
plugintimings_log_enabled = self._settings.global_get_boolean(["devel", "pluginTimings"])
return jsonify(logs={"files": files, "free": free, "total": total},
setup={"loggers": loggers, "levels": levels},
serial_log={"enabled": serial_log_enabled},
plugintimings_log={"enabled": plugintimings_log_enabled})
def get_additional_permissions(self):
return [
{
"key": "MANAGE",
"name": "Logging management",
"description": gettext(
"Allows to download and delete log files and list and set log levels."
),
"default_groups": [ADMIN_GROUP],
"roles": ["manage"],
}
]
@octoprint.plugin.BlueprintPlugin.route("/logs", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def get_log_files(self):
files = self._getLogFiles()
free, total = self._get_usage()
return jsonify(files=files, free=free, total=total)
@octoprint.plugin.BlueprintPlugin.route("/", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def get_all(self):
files = self._getLogFiles()
free, total = self._get_usage()
loggers = self._get_available_loggers()
levels = self._get_logging_levels()
serial_log_enabled = self._settings.global_get_boolean(["serial", "log"])
plugintimings_log_enabled = self._settings.global_get_boolean(
["devel", "pluginTimings"]
)
return jsonify(
logs={"files": files, "free": free, "total": total},
setup={"loggers": loggers, "levels": levels},
serial_log={"enabled": serial_log_enabled},
plugintimings_log={"enabled": plugintimings_log_enabled},
)
@octoprint.plugin.BlueprintPlugin.route("/logs/<path:filename>", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def download_log(self, filename):
return redirect_to_tornado(request, url_for("index") + "downloads/logs/" + filename)
@octoprint.plugin.BlueprintPlugin.route("/logs", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def get_log_files(self):
files = self._getLogFiles()
free, total = self._get_usage()
return jsonify(files=files, free=free, total=total)
@octoprint.plugin.BlueprintPlugin.route("/logs/<path:filename>", methods=["DELETE"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def delete_log(self, filename):
secure = os.path.join(settings().getBaseFolder("logs"), secure_filename(filename))
if not os.path.exists(secure):
return make_response("File not found: %s" % filename, 404)
@octoprint.plugin.BlueprintPlugin.route("/logs/<path:filename>", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def download_log(self, filename):
return redirect_to_tornado(
request, url_for("index") + "downloads/logs/" + filename
)
os.remove(secure)
@octoprint.plugin.BlueprintPlugin.route("/logs/<path:filename>", methods=["DELETE"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def delete_log(self, filename):
secure = os.path.join(settings().getBaseFolder("logs"), secure_filename(filename))
if not os.path.exists(secure):
return make_response("File not found: %s" % filename, 404)
return NO_CONTENT
os.remove(secure)
@octoprint.plugin.BlueprintPlugin.route("/setup", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def get_logging_setup(self):
loggers = self._get_available_loggers()
levels = self._get_logging_levels()
return jsonify(loggers=loggers, levels=levels)
return NO_CONTENT
@octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def get_logging_levels_api(self):
return jsonify(self._get_logging_levels())
@octoprint.plugin.BlueprintPlugin.route("/setup", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def get_logging_setup(self):
loggers = self._get_available_loggers()
levels = self._get_logging_levels()
return jsonify(loggers=loggers, levels=levels)
@octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["PUT"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def set_logging_levels_api(self):
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
@octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["GET"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def get_logging_levels_api(self):
return jsonify(self._get_logging_levels())
try:
json_data = request.json
except BadRequest:
return make_response("Malformed JSON body in request", 400)
@octoprint.plugin.BlueprintPlugin.route("/setup/levels", methods=["PUT"])
@no_firstrun_access
@Permissions.PLUGIN_LOGGING_MANAGE.require(403)
def set_logging_levels_api(self):
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
if not isinstance(json_data, dict):
return make_response("Invalid log level configuration", 400)
try:
json_data = request.json
except BadRequest:
return make_response("Malformed JSON body in request", 400)
# TODO validate further
if not isinstance(json_data, dict):
return make_response("Invalid log level configuration", 400)
self._set_logging_levels(json_data)
return self.get_logging_levels_api()
# TODO validate further
def is_blueprint_protected(self):
return False
self._set_logging_levels(json_data)
return self.get_logging_levels_api()
def _get_usage(self):
import psutil
usage = psutil.disk_usage(settings().getBaseFolder("logs", check_writable=False))
return usage.free, usage.total
def is_blueprint_protected(self):
return False
def _getLogFiles(self):
files = []
basedir = settings().getBaseFolder("logs", check_writable=False)
for entry in scandir(basedir):
files.append({
"name": entry.name,
"date": int(entry.stat().st_mtime),
"size": entry.stat().st_size,
"refs": {
"resource": url_for(".download_log", filename=entry.name, _external=True),
"download": url_for("index", _external=True) + "downloads/logs/" + entry.name
}
})
def _get_usage(self):
import psutil
return files
usage = psutil.disk_usage(settings().getBaseFolder("logs", check_writable=False))
return usage.free, usage.total
def _get_available_loggers(self):
return list(filter(lambda x: self._is_managed_logger(x), self._logger.manager.loggerDict.keys()))
def _getLogFiles(self):
files = []
basedir = settings().getBaseFolder("logs", check_writable=False)
for entry in scandir(basedir):
files.append(
{
"name": entry.name,
"date": int(entry.stat().st_mtime),
"size": entry.stat().st_size,
"refs": {
"resource": url_for(
".download_log", filename=entry.name, _external=True
),
"download": url_for("index", _external=True)
+ "downloads/logs/"
+ entry.name,
},
}
)
def _get_logging_file(self):
# TODO this might not be the logging config we are actually using here (command line parameter...)
return os.path.join(self._settings.getBaseFolder("base"), "logging.yaml")
return files
def _get_logging_config(self):
logging_file = self._get_logging_file()
def _get_available_loggers(self):
return list(
filter(
lambda x: self._is_managed_logger(x),
self._logger.manager.loggerDict.keys(),
)
)
config_from_file = {}
if os.path.exists(logging_file) and os.path.isfile(logging_file):
import yaml
with io.open(logging_file, 'rt', encoding='utf-8') as f:
config_from_file = yaml.safe_load(f)
return config_from_file
def _get_logging_file(self):
# TODO this might not be the logging config we are actually using here (command line parameter...)
return os.path.join(self._settings.getBaseFolder("base"), "logging.yaml")
def _get_logging_levels(self):
config = self._get_logging_config()
if config is None or not isinstance(config, dict):
return {}
def _get_logging_config(self):
logging_file = self._get_logging_file()
return dict((key, value.get("level"))
for key, value in config.get("loggers", {}).items()
if isinstance(value, dict) and "level" in value)
config_from_file = {}
if os.path.exists(logging_file) and os.path.isfile(logging_file):
import yaml
def _set_logging_levels(self, new_levels):
import logging
with io.open(logging_file, "rt", encoding="utf-8") as f:
config_from_file = yaml.safe_load(f)
return config_from_file
config = self._get_logging_config()
def _get_logging_levels(self):
config = self._get_logging_config()
if config is None or not isinstance(config, dict):
return {}
# clear all configured logging levels
if "loggers" in config:
purge = []
for component, data in config["loggers"].items():
if not self._is_managed_logger(component): continue
try:
del data["level"]
self._logger.manager.loggerDict[component].setLevel(logging.INFO)
except KeyError:
pass
if len(data) == 0:
purge.append(component)
for component in purge:
del config["loggers"][component]
else:
config["loggers"] = {}
return dict(
(key, value.get("level"))
for key, value in config.get("loggers", {}).items()
if isinstance(value, dict) and "level" in value
)
# update all logging levels
for logger, level in new_levels.items():
if logger not in config["loggers"]:
config["loggers"][logger] = {}
config["loggers"][logger]["level"] = level
def _set_logging_levels(self, new_levels):
import logging
# delete empty entries
config["loggers"] = {k: v for k, v in config["loggers"].items() if len(v)}
config = self._get_logging_config()
# save
with octoprint.util.atomic_write(self._get_logging_file(), mode='wt', max_permissions=0o666) as f:
yaml.safe_dump(config, f, default_flow_style=False, indent=2, allow_unicode=True)
# clear all configured logging levels
if "loggers" in config:
purge = []
for component, data in config["loggers"].items():
if not self._is_managed_logger(component):
continue
try:
del data["level"]
self._logger.manager.loggerDict[component].setLevel(logging.INFO)
except KeyError:
pass
if len(data) == 0:
purge.append(component)
for component in purge:
del config["loggers"][component]
else:
config["loggers"] = {}
# set runtime logging levels now
for logger, level in new_levels.items():
level = logging.getLevelName(level)
# update all logging levels
for logger, level in new_levels.items():
if logger not in config["loggers"]:
config["loggers"][logger] = {}
config["loggers"][logger]["level"] = level
self._logger.info("Setting logger {} level to {}".format(logger, level))
self._logger.manager.loggerDict[logger].setLevel(level)
# delete empty entries
config["loggers"] = {k: v for k, v in config["loggers"].items() if len(v)}
def _is_managed_logger(self, logger):
return logger and (logger.startswith("octoprint") or logger.startswith("tornado"))
# save
with octoprint.util.atomic_write(
self._get_logging_file(), mode="wt", max_permissions=0o666
) as f:
yaml.safe_dump(
config, f, default_flow_style=False, indent=2, allow_unicode=True
)
def get_template_configs(self):
return [{"type": "navbar",
"template": "logging_navbar_seriallog.jinja2",
"suffix": "_seriallog"},
{"type": "navbar",
"template": "logging_navbar_plugintimingslog.jinja2",
"suffix": "_plugintimingslog"},
{"type": "settings",
"custom_bindings": True}]
# set runtime logging levels now
for logger, level in new_levels.items():
level = logging.getLevelName(level)
self._logger.info("Setting logger {} level to {}".format(logger, level))
self._logger.manager.loggerDict[logger].setLevel(level)
def _is_managed_logger(self, logger):
return logger and (logger.startswith("octoprint") or logger.startswith("tornado"))
def get_template_configs(self):
return [
{
"type": "navbar",
"template": "logging_navbar_seriallog.jinja2",
"suffix": "_seriallog",
},
{
"type": "navbar",
"template": "logging_navbar_plugintimingslog.jinja2",
"suffix": "_plugintimingslog",
},
{"type": "settings", "custom_bindings": True},
]
def get_assets(self):
return {
"js": ["js/logging.js"],
"clientjs": ["clientjs/logging.js"],
"less": ["less/logging.less"],
"css": ["css/logging.css"],
}
def get_assets(self):
return {"js": ["js/logging.js"],
"clientjs": ["clientjs/logging.js"],
"less": ["less/logging.less"],
"css": ["css/logging.css"]}
__plugin_name__ = "Logging"
__plugin_author__ = "Shawn Bruce, based on work by Gina Häußge and Marc Hannappel"
__plugin_description__ = "Provides access to OctoPrint's logs and logging configuration."
__plugin_disabling_discouraged__ = gettext("Without this plugin you will no longer be able to retrieve "
"OctoPrint's logs or modify the current logging levels through "
"the web interface.")
__plugin_disabling_discouraged__ = gettext(
"Without this plugin you will no longer be able to retrieve "
"OctoPrint's logs or modify the current logging levels through "
"the web interface."
)
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=2.7,<4"
__plugin_implementation__ = LoggingPlugin()
__plugin_hooks__ = {
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
}
+310 -231
View File
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
import flask
@@ -30,17 +30,35 @@ _CHECK_INTERVAL_THROTTLED = 30
__LOCAL_DEBUG = False
if __LOCAL_DEBUG:
### mocks & settings for local debugging
import sys
base = os.path.realpath(os.path.join(os.path.dirname(__file__), "..", "..", "..", "..", "tests", "plugins", "pi_support", "fakes"))
_PROC_DT_MODEL_PATH = os.path.join(base, "fake_model.txt")
_OCTOPI_VERSION_PATH = os.path.join(base, "fake_octopi.txt")
_VCGENCMD_THROTTLE = "{} {}".format(sys.executable, os.path.join(base, "fake_vcgencmd.py"))
import itertools
_VCGENCMD_OUTPUT = itertools.chain(iter(("0x0", "0x0", "0x50005", "0x50000", "0x70007")), itertools.repeat("0x70005"))
### mocks & settings for local debugging
import sys
_CHECK_INTERVAL_OK = 10
_CHECK_INTERVAL_THROTTLED = 5
base = os.path.realpath(
os.path.join(
os.path.dirname(__file__),
"..",
"..",
"..",
"..",
"tests",
"plugins",
"pi_support",
"fakes",
)
)
_PROC_DT_MODEL_PATH = os.path.join(base, "fake_model.txt")
_OCTOPI_VERSION_PATH = os.path.join(base, "fake_octopi.txt")
_VCGENCMD_THROTTLE = "{} {}".format(
sys.executable, os.path.join(base, "fake_vcgencmd.py")
)
import itertools
_VCGENCMD_OUTPUT = itertools.chain(
iter(("0x0", "0x0", "0x50005", "0x50000", "0x70007")), itertools.repeat("0x70005")
)
_CHECK_INTERVAL_OK = 10
_CHECK_INTERVAL_THROTTLED = 5
# see https://www.raspberrypi.org/forums/viewtopic.php?f=63&t=147781&start=50#p972790
@@ -51,314 +69,375 @@ _FLAG_PAST_UNDERVOLTAGE = 1 << 16
_FLAG_PAST_FREQ_CAPPED = 1 << 17
_FLAG_PAST_THROTTLED = 1 << 18
class ThrottleState(object):
@classmethod
def from_value(cls, value=0):
if value == 0:
return ThrottleState()
@classmethod
def from_value(cls, value=0):
if value == 0:
return ThrottleState()
kwargs = {"undervoltage": _FLAG_UNDERVOLTAGE & value == _FLAG_UNDERVOLTAGE,
"freq_capped": _FLAG_FREQ_CAPPED & value == _FLAG_FREQ_CAPPED,
"throttled": _FLAG_THROTTLED & value == _FLAG_THROTTLED,
"past_undervoltage": _FLAG_PAST_UNDERVOLTAGE & value == _FLAG_PAST_UNDERVOLTAGE,
"past_freq_capped": _FLAG_PAST_FREQ_CAPPED & value == _FLAG_PAST_FREQ_CAPPED,
"past_throttled": _FLAG_PAST_THROTTLED & value == _FLAG_PAST_THROTTLED,
"raw_value": value}
return ThrottleState(**kwargs)
kwargs = {
"undervoltage": _FLAG_UNDERVOLTAGE & value == _FLAG_UNDERVOLTAGE,
"freq_capped": _FLAG_FREQ_CAPPED & value == _FLAG_FREQ_CAPPED,
"throttled": _FLAG_THROTTLED & value == _FLAG_THROTTLED,
"past_undervoltage": _FLAG_PAST_UNDERVOLTAGE & value
== _FLAG_PAST_UNDERVOLTAGE,
"past_freq_capped": _FLAG_PAST_FREQ_CAPPED & value == _FLAG_PAST_FREQ_CAPPED,
"past_throttled": _FLAG_PAST_THROTTLED & value == _FLAG_PAST_THROTTLED,
"raw_value": value,
}
return ThrottleState(**kwargs)
def __init__(self, **kwargs):
self._raw_value = kwargs.get('raw_value', -1)
self._undervoltage = False
self._freq_capped = False
self._throttled = False
self._past_undervoltage = False
self._past_freq_capped = False
self._past_throttled = False
def __init__(self, **kwargs):
self._raw_value = kwargs.get("raw_value", -1)
self._undervoltage = False
self._freq_capped = False
self._throttled = False
self._past_undervoltage = False
self._past_freq_capped = False
self._past_throttled = False
for key, value in kwargs.items():
local_key = "_{}".format(key)
if hasattr(self, local_key) and isinstance(value, bool):
setattr(self, local_key, value)
for key, value in kwargs.items():
local_key = "_{}".format(key)
if hasattr(self, local_key) and isinstance(value, bool):
setattr(self, local_key, value)
@property
def undervoltage(self):
return self.current_undervoltage or self.past_undervoltage
@property
def undervoltage(self):
return self.current_undervoltage or self.past_undervoltage
@property
def current_undervoltage(self):
return self._undervoltage
@property
def current_undervoltage(self):
return self._undervoltage
@property
def past_undervoltage(self):
return self._past_undervoltage
@property
def past_undervoltage(self):
return self._past_undervoltage
@property
def overheat(self):
return self.current_overheat or self.past_overheat
@property
def overheat(self):
return self.current_overheat or self.past_overheat
@property
def current_overheat(self):
return self._freq_capped
@property
def current_overheat(self):
return self._freq_capped
@property
def past_overheat(self):
return self._past_freq_capped
@property
def past_overheat(self):
return self._past_freq_capped
@property
def issue(self):
return self.current_issue or self.past_issue
@property
def issue(self):
return self.current_issue or self.past_issue
@property
def current_issue(self):
return self._undervoltage or self._freq_capped or self._throttled
@property
def current_issue(self):
return self._undervoltage or self._freq_capped or self._throttled
@property
def past_issue(self):
return self._past_undervoltage or self._past_freq_capped or self._past_throttled
@property
def past_issue(self):
return self._past_undervoltage or self._past_freq_capped or self._past_throttled
def __eq__(self, other):
if not isinstance(other, ThrottleState):
return False
def __eq__(self, other):
if not isinstance(other, ThrottleState):
return False
return self._undervoltage == other._undervoltage \
and self._freq_capped == other._freq_capped \
and self._throttled == other._throttled \
and self._past_undervoltage == other._past_undervoltage \
and self._past_freq_capped == other._past_freq_capped \
and self._past_throttled == other._past_throttled
return (
self._undervoltage == other._undervoltage
and self._freq_capped == other._freq_capped
and self._throttled == other._throttled
and self._past_undervoltage == other._past_undervoltage
and self._past_freq_capped == other._past_freq_capped
and self._past_throttled == other._past_throttled
)
def as_dict(self):
return {"raw_value": self._raw_value,
"current_undervoltage": self.current_undervoltage,
"past_undervoltage": self.past_undervoltage,
"current_overheat": self.current_overheat,
"past_overheat": self.past_overheat,
"current_issue": self.current_issue,
"past_issue": self.past_issue}
def as_dict(self):
return {
"raw_value": self._raw_value,
"current_undervoltage": self.current_undervoltage,
"past_undervoltage": self.past_undervoltage,
"current_overheat": self.current_overheat,
"past_overheat": self.past_overheat,
"current_issue": self.current_issue,
"past_issue": self.past_issue,
}
_proc_dt_model = None
def get_proc_dt_model():
global _proc_dt_model
global _proc_dt_model
if _proc_dt_model is None:
with io.open(_PROC_DT_MODEL_PATH, 'rt', encoding='utf-8') as f:
_proc_dt_model = f.readline().strip(" \t\r\n\0")
if _proc_dt_model is None:
with io.open(_PROC_DT_MODEL_PATH, "rt", encoding="utf-8") as f:
_proc_dt_model = f.readline().strip(" \t\r\n\0")
return _proc_dt_model
return _proc_dt_model
def get_vcgencmd_throttled_state(command):
if __LOCAL_DEBUG:
output = "throttled={}".format(next(_VCGENCMD_OUTPUT)) # mock for local debugging
else:
output = sarge.get_stdout(command, close_fds=CLOSE_FDS)
if __LOCAL_DEBUG:
output = "throttled={}".format(next(_VCGENCMD_OUTPUT)) # mock for local debugging
else:
output = sarge.get_stdout(command, close_fds=CLOSE_FDS)
if not "throttled=0x" in output:
raise ValueError("cannot parse \"{}\" output: {}".format(command, output))
if not "throttled=0x" in output:
raise ValueError('cannot parse "{}" output: {}'.format(command, output))
value = output[len("throttled="):].strip(" \t\r\n\0")
value = int(value, 0)
return ThrottleState.from_value(value)
value = output[len("throttled=") :].strip(" \t\r\n\0")
value = int(value, 0)
return ThrottleState.from_value(value)
def is_octopi():
return os.path.exists(_OCTOPI_VERSION_PATH)
return os.path.exists(_OCTOPI_VERSION_PATH)
_octopi_version = None
def get_octopi_version():
global _octopi_version
global _octopi_version
if _octopi_version is None:
with io.open(_OCTOPI_VERSION_PATH, 'rt', encoding='utf-8') as f:
_octopi_version = f.readline().strip(" \t\r\n\0")
if _octopi_version is None:
with io.open(_OCTOPI_VERSION_PATH, "rt", encoding="utf-8") as f:
_octopi_version = f.readline().strip(" \t\r\n\0")
return _octopi_version
return _octopi_version
class PiSupportPlugin(octoprint.plugin.EnvironmentDetectionPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.SettingsPlugin):
class PiSupportPlugin(
octoprint.plugin.EnvironmentDetectionPlugin,
octoprint.plugin.SimpleApiPlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.SettingsPlugin,
):
# noinspection PyMissingConstructor
def __init__(self):
self._throttle_state = ThrottleState()
self._throttle_check = None
self._throttle_undervoltage = False
self._throttle_overheat = False
self._throttle_functional = True
# noinspection PyMissingConstructor
def __init__(self):
self._throttle_state = ThrottleState()
self._throttle_check = None
self._throttle_undervoltage = False
self._throttle_overheat = False
self._throttle_functional = True
# Additional permissions hook
# Additional permissions hook
def get_additional_permissions(self):
return [{"key": "STATUS",
"name": "Status",
"description": gettext("Allows to check for the Pi's throttling status and environment info"),
"roles": ["check"],
"default_groups": [USER_GROUP]}]
def get_additional_permissions(self):
return [
{
"key": "STATUS",
"name": "Status",
"description": gettext(
"Allows to check for the Pi's throttling status and environment info"
),
"roles": ["check"],
"default_groups": [USER_GROUP],
}
]
#~~ EnvironmentDetectionPlugin
# ~~ EnvironmentDetectionPlugin
def get_additional_environment(self):
result = {"model": get_proc_dt_model()}
def get_additional_environment(self):
result = {"model": get_proc_dt_model()}
if is_octopi():
result.update({"octopi_version": get_octopi_version()})
if is_octopi():
result.update({"octopi_version": get_octopi_version()})
return result
return result
#~~ SimpleApiPlugin
# ~~ SimpleApiPlugin
def on_api_get(self, request):
if not Permissions.PLUGIN_PI_SUPPORT_STATUS.can():
return flask.abort(403)
result = {"throttle_state": self._throttle_state.as_dict()}
result.update(self.get_additional_environment())
return flask.jsonify(**result)
def on_api_get(self, request):
if not Permissions.PLUGIN_PI_SUPPORT_STATUS.can():
return flask.abort(403)
result = {"throttle_state": self._throttle_state.as_dict()}
result.update(self.get_additional_environment())
return flask.jsonify(**result)
#~~ AssetPlugin
# ~~ AssetPlugin
def get_assets(self):
return {"js": ["js/pi_support.js"],
"clientjs": ["clientjs/pi_support.js"],
"css": ["css/pi_support.css"]}
def get_assets(self):
return {
"js": ["js/pi_support.js"],
"clientjs": ["clientjs/pi_support.js"],
"css": ["css/pi_support.css"],
}
#~~ TemplatePlugin
# ~~ TemplatePlugin
def get_template_configs(self):
configs = [{"type": "settings",
"name": gettext("Pi Support"),
"template": "pi_support_settings.jinja2",
"custom_bindings": False}]
def get_template_configs(self):
configs = [
{
"type": "settings",
"name": gettext("Pi Support"),
"template": "pi_support_settings.jinja2",
"custom_bindings": False,
}
]
if is_octopi():
configs.append({"type": "about",
"name": "About OctoPi",
"template": "pi_support_about_octopi.jinja2"})
if is_octopi():
configs.append(
{
"type": "about",
"name": "About OctoPi",
"template": "pi_support_about_octopi.jinja2",
}
)
return configs
return configs
def get_template_vars(self):
return self.get_additional_environment()
def get_template_vars(self):
return self.get_additional_environment()
#~~ StartupPlugin
# ~~ StartupPlugin
def on_startup(self, *args, **kwargs):
if self._settings.get_boolean(["vcgencmd_throttle_check_enabled"]):
self._check_throttled_state()
self._throttle_check = RepeatedTimer(self._check_throttled_state_interval,
self._check_throttled_state,
condition=self._check_throttled_state_condition)
self._throttle_check.start()
def on_startup(self, *args, **kwargs):
if self._settings.get_boolean(["vcgencmd_throttle_check_enabled"]):
self._check_throttled_state()
self._throttle_check = RepeatedTimer(
self._check_throttled_state_interval,
self._check_throttled_state,
condition=self._check_throttled_state_condition,
)
self._throttle_check.start()
#~~ SettingsPlugin
# ~~ SettingsPlugin
def get_settings_defaults(self):
return {"vcgencmd_throttle_check_enabled": True,
"vcgencmd_throttle_check_command": _VCGENCMD_THROTTLE}
def get_settings_defaults(self):
return {
"vcgencmd_throttle_check_enabled": True,
"vcgencmd_throttle_check_command": _VCGENCMD_THROTTLE,
}
def get_settings_restricted_paths(self):
return {"admin": [["vcgencmd_throttle_check_enabled"], ["vcgencmd_throttle_check_command"]]}
def get_settings_restricted_paths(self):
return {
"admin": [
["vcgencmd_throttle_check_enabled"],
["vcgencmd_throttle_check_command"],
]
}
#~~ Helpers
# ~~ Helpers
def _check_throttled_state_interval(self):
if self._throttle_state.current_issue:
return _CHECK_INTERVAL_THROTTLED
else:
return _CHECK_INTERVAL_OK
def _check_throttled_state_interval(self):
if self._throttle_state.current_issue:
return _CHECK_INTERVAL_THROTTLED
else:
return _CHECK_INTERVAL_OK
def _check_throttled_state_condition(self):
return self._throttle_functional
def _check_throttled_state_condition(self):
return self._throttle_functional
def get_throttle_state(self, run_now=False):
"""Exposed as public helper."""
if run_now:
self._check_throttled_state()
def get_throttle_state(self, run_now=False):
"""Exposed as public helper."""
if run_now:
self._check_throttled_state()
if not self._throttle_functional:
return False
if not self._throttle_functional:
return False
return self._throttle_state.as_dict()
return self._throttle_state.as_dict()
def _check_throttled_state(self):
command = self._settings.get(["vcgencmd_throttle_check_command"])
def _check_throttled_state(self):
command = self._settings.get(["vcgencmd_throttle_check_command"])
self._logger.debug("Retrieving throttle state via \"{}\"".format(command))
try:
state = get_vcgencmd_throttled_state(command)
except ValueError:
self._logger.warning("Fetching the current throttle state via \"{}\" doesn't work".format(command))
self._throttle_functional = False
return
self._logger.debug('Retrieving throttle state via "{}"'.format(command))
try:
state = get_vcgencmd_throttled_state(command)
except ValueError:
self._logger.warning(
'Fetching the current throttle state via "{}" doesn\'t work'.format(
command
)
)
self._throttle_functional = False
return
if self._throttle_state == state:
# no change
return
if self._throttle_state == state:
# no change
return
self._throttle_state = state
self._throttle_state = state
if (not self._throttle_undervoltage and self._throttle_state.undervoltage) \
or (not self._throttle_overheat and self._throttle_state.overheat):
message = "This Raspberry Pi is reporting problems that might lead to bad performance or errors caused " \
"by overheating or insufficient power."
if (not self._throttle_undervoltage and self._throttle_state.undervoltage) or (
not self._throttle_overheat and self._throttle_state.overheat
):
message = (
"This Raspberry Pi is reporting problems that might lead to bad performance or errors caused "
"by overheating or insufficient power."
)
if self._throttle_state.undervoltage:
self._throttle_undervoltage = True
message += "\n!!! UNDERVOLTAGE REPORTED !!! Make sure that the power supply and power cable are " \
"capable of supplying enough voltage and current to your Pi."
if self._throttle_state.undervoltage:
self._throttle_undervoltage = True
message += (
"\n!!! UNDERVOLTAGE REPORTED !!! Make sure that the power supply and power cable are "
"capable of supplying enough voltage and current to your Pi."
)
if self._throttle_state.overheat:
self._throttle_overheat = True
message += "\n!!! FREQUENCY CAPPING DUE TO OVERHEATING REPORTED !!! Improve cooling on the Pi's " \
"CPU and GPU."
if self._throttle_state.overheat:
self._throttle_overheat = True
message += (
"\n!!! FREQUENCY CAPPING DUE TO OVERHEATING REPORTED !!! Improve cooling on the Pi's "
"CPU and GPU."
)
self._logger.warning(message)
self._logger.warning(message)
self._plugin_manager.send_plugin_message(self._identifier, {"type": "throttle_state",
"state": self._throttle_state.as_dict()})
self._plugin_manager.send_plugin_message(
self._identifier,
{"type": "throttle_state", "state": self._throttle_state.as_dict()},
)
# noinspection PyUnresolvedReferences
self._event_bus.fire(octoprint.events.Events.PLUGIN_PI_SUPPORT_THROTTLE_STATE, self._throttle_state.as_dict())
# noinspection PyUnresolvedReferences
self._event_bus.fire(
octoprint.events.Events.PLUGIN_PI_SUPPORT_THROTTLE_STATE,
self._throttle_state.as_dict(),
)
def register_custom_events(*args, **kwargs):
return ["throttle_state",]
return [
"throttle_state",
]
__plugin_name__ = "Pi Support Plugin"
__plugin_author__ = "Gina Häußge"
__plugin_description__ = "Provides additional information about your Pi in the UI."
__plugin_disabling_discouraged__ = gettext("Without this plugin OctoPrint will no longer be able to "
"provide additional information about your Pi, "
"which will make it more tricky to help you if you need support.")
__plugin_disabling_discouraged__ = gettext(
"Without this plugin OctoPrint will no longer be able to "
"provide additional information about your Pi, "
"which will make it more tricky to help you if you need support."
)
__plugin_license__ = "AGPLv3"
__plugin_pythoncompat__ = ">=2.7,<4"
def __plugin_check__():
try:
proc_dt_model = get_proc_dt_model()
if proc_dt_model is None:
return False
except Exception:
return False
return "raspberry pi" in proc_dt_model.lower()
def __plugin_check__():
try:
proc_dt_model = get_proc_dt_model()
if proc_dt_model is None:
return False
except Exception:
return False
return "raspberry pi" in proc_dt_model.lower()
def __plugin_load__():
plugin = PiSupportPlugin()
global __plugin_implementation__
__plugin_implementation__ = plugin
plugin = PiSupportPlugin()
global __plugin_implementation__
__plugin_implementation__ = plugin
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.events.register_custom_events": register_custom_events,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions
}
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.events.register_custom_events": register_custom_events,
"octoprint.access.permissions": __plugin_implementation__.get_additional_permissions,
}
global __plugin_helpers__
__plugin_helpers__ = {"get_throttled": plugin.get_throttle_state}
global __plugin_helpers__
__plugin_helpers__ = {"get_throttled": plugin.get_throttle_state}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+210 -184
View File
@@ -1,229 +1,255 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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"
def commands(cli_group, pass_octoprint_ctx, *args, **kwargs):
import click
click.disable_unicode_literals_warning = True
import sys
import requests.exceptions
from octoprint.cli.client import create_client, client_options
import click
@click.command("check")
@click.option("--force", is_flag=True, help="Ignore the cache for the update check")
@click.option("--only-new", is_flag=True, help="Only show entries with updates available")
@client_options
@click.argument("targets", nargs=-1)
def check_command(force, only_new, apikey, host, port, httpuser, httppass, https, prefix, targets):
"""
Check for updates.
click.disable_unicode_literals_warning = True
import sys
import requests.exceptions
from octoprint.cli.client import create_client, client_options
If any TARGETs are provided, only those components will be checked.
@click.command("check")
@click.option("--force", is_flag=True, help="Ignore the cache for the update check")
@click.option(
"--only-new", is_flag=True, help="Only show entries with updates available"
)
@client_options
@click.argument("targets", nargs=-1)
def check_command(
force, only_new, apikey, host, port, httpuser, httppass, https, prefix, targets
):
"""
Check for updates.
\b
Examples:
- octoprint plugins softwareupdate:check
This will check all components for available updates,
utilizing cached version information.
- octoprint plugins softwareupdate:check --force
This will check all components for available updates,
ignoring any cached version information even if it's
still valid.
- octoprint plugins softwareupdate:check octoprint
This will only check OctoPrint itself for available
updates.
If any TARGETs are provided, only those components will be checked.
Note that the OctoPrint server needs to be running for this
command to work as it utilizes the server API.
"""
params = {"force": force}
if targets:
params["targets"] = ",".join(targets)
\b
Examples:
- octoprint plugins softwareupdate:check
This will check all components for available updates,
utilizing cached version information.
- octoprint plugins softwareupdate:check --force
This will check all components for available updates,
ignoring any cached version information even if it's
still valid.
- octoprint plugins softwareupdate:check octoprint
This will only check OctoPrint itself for available
updates.
client = create_client(settings=cli_group.settings,
apikey=apikey,
host=host,
port=port,
httpuser=httpuser,
httppass=httppass,
https=https,
prefix=prefix)
Note that the OctoPrint server needs to be running for this
command to work as it utilizes the server API.
"""
params = {"force": force}
if targets:
params["targets"] = ",".join(targets)
r = client.get("plugin/softwareupdate/check", params=params)
try:
r.raise_for_status()
except requests.exceptions.HTTPError as e:
click.echo("Could not get update information from server, got {}".format(e))
sys.exit(1)
client = create_client(
settings=cli_group.settings,
apikey=apikey,
host=host,
port=port,
httpuser=httpuser,
httppass=httppass,
https=https,
prefix=prefix,
)
data = r.json()
status = data["status"]
information = data["information"]
r = client.get("plugin/softwareupdate/check", params=params)
try:
r.raise_for_status()
except requests.exceptions.HTTPError as e:
click.echo("Could not get update information from server, got {}".format(e))
sys.exit(1)
lines = []
octoprint_line = None
for key, info in information.items():
status_text = "Up to date"
if info["updateAvailable"]:
if info["updatePossible"]:
status_text = "Update available"
else:
status_text = "Update available (manual)"
data = r.json()
status = data["status"]
information = data["information"]
elif only_new:
continue
lines = []
octoprint_line = None
for key, info in information.items():
status_text = "Up to date"
if info["updateAvailable"]:
if info["updatePossible"]:
status_text = "Update available"
else:
status_text = "Update available (manual)"
line = "{} (target: {})\n\tInstalled: {}\n\tAvailable: {}\n\t=> {}".format(info["displayName"],
key,
info["information"]["local"]["name"],
info["information"]["remote"]["name"],
status_text)
if key == "octoprint":
octoprint_line = line
else:
lines.append(line)
elif only_new:
continue
lines.sort()
if octoprint_line:
lines = [octoprint_line] + lines
line = "{} (target: {})\n\tInstalled: {}\n\tAvailable: {}\n\t=> {}".format(
info["displayName"],
key,
info["information"]["local"]["name"],
info["information"]["remote"]["name"],
status_text,
)
if key == "octoprint":
octoprint_line = line
else:
lines.append(line)
for line in lines:
click.echo(line)
lines.sort()
if octoprint_line:
lines = [octoprint_line] + lines
click.echo()
if status == "current":
click.echo("Everything is up to date")
else:
click.echo("There are updates available!")
for line in lines:
click.echo(line)
click.echo()
if status == "current":
click.echo("Everything is up to date")
else:
click.echo("There are updates available!")
@click.command("update")
@click.option("--force", is_flag=True, help="Update even if already up to date")
@client_options
@click.argument("targets", nargs=-1)
def update_command(force, apikey, host, port, httpuser, httppass, https, prefix, targets):
"""
Apply updates.
@click.command("update")
@click.option("--force", is_flag=True, help="Update even if already up to date")
@client_options
@click.argument("targets", nargs=-1)
def update_command(
force, apikey, host, port, httpuser, httppass, https, prefix, targets
):
"""
Apply updates.
If any TARGETs are provided, only those components will be updated.
If any TARGETs are provided, only those components will be updated.
\b
Examples:
- octoprint plugins softwareupdate:update
This will update all components with a pending update
that can be updated.
- octoprint plugins softwareupdate:update --force
This will force an update of all registered components
that can be updated, even if they don't have an updated
pending.
- octoprint plugins softwareupdate:update octoprint
This will only update OctoPrint and leave any further
components with pending updates at their current versions.
\b
Examples:
- octoprint plugins softwareupdate:update
This will update all components with a pending update
that can be updated.
- octoprint plugins softwareupdate:update --force
This will force an update of all registered components
that can be updated, even if they don't have an updated
pending.
- octoprint plugins softwareupdate:update octoprint
This will only update OctoPrint and leave any further
components with pending updates at their current versions.
Note that the OctoPrint server needs to be running for this
command to work as it utilizes the server API.
"""
Note that the OctoPrint server needs to be running for this
command to work as it utilizes the server API.
"""
data = {"force": force}
if targets:
data["targets"] = targets
data = {"force": force}
if targets:
data["targets"] = targets
client = create_client(settings=cli_group.settings,
apikey=apikey,
host=host,
port=port,
httpuser=httpuser,
httppass=httppass,
https=https,
prefix=prefix)
client = create_client(
settings=cli_group.settings,
apikey=apikey,
host=host,
port=port,
httpuser=httpuser,
httppass=httppass,
https=https,
prefix=prefix,
)
flags = {"waiting_for_restart": False,
"seen_close": False}
flags = {"waiting_for_restart": False, "seen_close": False}
def on_message(ws, msg_type, msg):
if msg_type != "plugin" or msg["plugin"] != "softwareupdate":
return
def on_message(ws, msg_type, msg):
if msg_type != "plugin" or msg["plugin"] != "softwareupdate":
return
plugin_message = msg["data"]
if not "type" in plugin_message:
return
plugin_message = msg["data"]
if not "type" in plugin_message:
return
plugin_message_type = plugin_message["type"]
plugin_message_data = plugin_message["data"]
plugin_message_type = plugin_message["type"]
plugin_message_data = plugin_message["data"]
if plugin_message_type == "updating":
click.echo("Updating {} to {}...".format(plugin_message_data.get("name", "unknown"), plugin_message_data.get("version", "n/a")))
if plugin_message_type == "updating":
click.echo(
"Updating {} to {}...".format(
plugin_message_data.get("name", "unknown"),
plugin_message_data.get("version", "n/a"),
)
)
elif plugin_message_type == "update_failed":
click.echo("\t... failed :(")
elif plugin_message_type == "update_failed":
click.echo("\t... failed :(")
elif plugin_message_type == "loglines" and "loglines" in plugin_message_data:
for entry in plugin_message_data["loglines"]:
prefix = ">>> " if entry["stream"] == "call" else ""
error = entry["stream"] == "stderr"
click.echo("\t{}{}".format(prefix, entry["line"].replace("\n", "\n\t")), err=error)
elif plugin_message_type == "loglines" and "loglines" in plugin_message_data:
for entry in plugin_message_data["loglines"]:
prefix = ">>> " if entry["stream"] == "call" else ""
error = entry["stream"] == "stderr"
click.echo(
"\t{}{}".format(prefix, entry["line"].replace("\n", "\n\t")),
err=error,
)
elif plugin_message_type == "success" or plugin_message_type == "restart_manually":
results = plugin_message_data["results"] if "results" in plugin_message_data else {}
if results:
click.echo("The update finished successfully.")
if plugin_message_type == "restart_manually":
click.echo("Please restart the OctoPrint server.")
else:
click.echo("No update necessary")
ws.close()
elif (
plugin_message_type == "success"
or plugin_message_type == "restart_manually"
):
results = (
plugin_message_data["results"]
if "results" in plugin_message_data
else {}
)
if results:
click.echo("The update finished successfully.")
if plugin_message_type == "restart_manually":
click.echo("Please restart the OctoPrint server.")
else:
click.echo("No update necessary")
ws.close()
elif plugin_message_type == "restarting":
flags["waiting_for_restart"] = True
click.echo("Restarting to apply changes...")
elif plugin_message_type == "restarting":
flags["waiting_for_restart"] = True
click.echo("Restarting to apply changes...")
elif plugin_message_type == "error":
click.echo("Error")
ws.close()
elif plugin_message_type == "error":
click.echo("Error")
ws.close()
def on_open(ws):
if flags["waiting_for_restart"] and flags["seen_close"]:
click.echo(" Reconnected!")
else:
click.echo("Connected to server...")
def on_open(ws):
if flags["waiting_for_restart"] and flags["seen_close"]:
click.echo(" Reconnected!")
else:
click.echo("Connected to server...")
def on_close(ws):
if flags["waiting_for_restart"] and flags["seen_close"]:
click.echo(".", nl=False)
else:
flags["seen_close"] = True
click.echo("Disconnected from server...")
def on_close(ws):
if flags["waiting_for_restart"] and flags["seen_close"]:
click.echo(".", nl=False)
else:
flags["seen_close"] = True
click.echo("Disconnected from server...")
socket = client.create_socket(on_message=on_message,
on_open=on_open,
on_close=on_close)
socket = client.create_socket(
on_message=on_message, on_open=on_open, on_close=on_close
)
r = client.post_json("plugin/softwareupdate/update", data=data)
try:
r.raise_for_status()
except requests.exceptions.HTTPError as e:
click.echo("Could not get update information from server, got {}".format(e))
sys.exit(1)
r = client.post_json("plugin/softwareupdate/update", data=data)
try:
r.raise_for_status()
except requests.exceptions.HTTPError as e:
click.echo("Could not get update information from server, got {}".format(e))
sys.exit(1)
data = r.json()
to_be_updated = data["order"]
checks = data["checks"]
click.echo("Update in progress, updating:")
for name in to_be_updated:
click.echo("\t{}".format(name if not name in checks else checks[name]))
data = r.json()
to_be_updated = data["order"]
checks = data["checks"]
click.echo("Update in progress, updating:")
for name in to_be_updated:
click.echo("\t{}".format(name if not name in checks else checks[name]))
socket.wait()
if flags["waiting_for_restart"]:
if socket.reconnect(timeout=60):
click.echo("The update finished successfully.")
else:
click.echo("The update finished successfully but the server apparently didn't restart as expected.")
click.echo("Please restart the OctoPrint server.")
return [check_command, update_command]
socket.wait()
if flags["waiting_for_restart"]:
if socket.reconnect(timeout=60):
click.echo("The update finished successfully.")
else:
click.echo(
"The update finished successfully but the server apparently didn't restart as expected."
)
click.echo("Please restart the OctoPrint server.")
return [check_command, update_command]
@@ -2,55 +2,65 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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"
class NoUpdateAvailable(Exception):
pass
pass
class UpdateAlreadyInProgress(Exception):
pass
pass
class UnknownUpdateType(Exception):
pass
pass
class UnknownCheckType(Exception):
pass
pass
class NetworkError(Exception):
def __init__(self, message=None, cause=None):
Exception.__init__(self)
self.message = message
self.cause = cause
def __init__(self, message=None, cause=None):
Exception.__init__(self)
self.message = message
self.cause = cause
def __str__(self):
if self.message is not None:
return self.message
elif self.cause is not None:
return "NetworkError caused by {}".format(self.cause)
else:
return "NetworkError"
def __str__(self):
if self.message is not None:
return self.message
elif self.cause is not None:
return "NetworkError caused by {}".format(self.cause)
else:
return "NetworkError"
class UpdateError(Exception):
def __init__(self, message, data):
self.message = message
self.data = data
def __init__(self, message, data):
self.message = message
self.data = data
class ScriptError(Exception):
def __init__(self, returncode, stdout, stderr):
self.returncode = returncode
self.stdout = stdout
self.stderr = stderr
def __init__(self, returncode, stdout, stderr):
self.returncode = returncode
self.stdout = stdout
self.stderr = stderr
class RestartFailed(Exception):
pass
pass
class ConfigurationInvalid(Exception):
pass
pass
class CannotCheckOffline(Exception):
pass
pass
class CannotUpdateOffline(Exception):
pass
pass
@@ -3,7 +3,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Haeussge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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"
@@ -16,310 +16,416 @@ from past.builtins import unicode
# default close_fds settings
if sys.platform == "win32" and sys.version_info < (3, 7):
CLOSE_FDS = False
CLOSE_FDS = False
else:
CLOSE_FDS = True
CLOSE_FDS = True
def _log_call(*lines):
_log(lines, prefix=">", stream="call")
_log(lines, prefix=">", stream="call")
def _log_stdout(*lines):
_log(lines, prefix=" ", stream="stdout")
_log(lines, prefix=" ", stream="stdout")
def _log_stderr(*lines):
_log(lines, prefix=" ", stream="stderr")
_log(lines, prefix=" ", stream="stderr")
def _log(lines, prefix=None, stream=None):
output_stream = sys.stdout
if stream == "stderr":
output_stream = sys.stderr
output_stream = sys.stdout
if stream == "stderr":
output_stream = sys.stderr
for line in lines:
to_print = _to_bytes("{} {}".format(prefix, _to_unicode(line.rstrip(), errors="replace")),
errors="replace")
print(to_print, file=output_stream)
for line in lines:
to_print = _to_bytes(
"{} {}".format(prefix, _to_unicode(line.rstrip(), errors="replace")),
errors="replace",
)
print(to_print, file=output_stream)
def _to_unicode(s_or_u, encoding="utf-8", errors="strict"):
"""Make sure ``s_or_u`` is a unicode string."""
if isinstance(s_or_u, bytes):
return s_or_u.decode(encoding, errors=errors)
else:
return s_or_u
"""Make sure ``s_or_u`` is a unicode string."""
if isinstance(s_or_u, bytes):
return s_or_u.decode(encoding, errors=errors)
else:
return s_or_u
def _to_bytes(s_or_u, encoding="utf-8", errors="strict"):
"""Make sure ``s_or_u`` is a str."""
if isinstance(s_or_u, unicode):
return s_or_u.encode(encoding, errors=errors)
else:
return s_or_u
"""Make sure ``s_or_u`` is a str."""
if isinstance(s_or_u, unicode):
return s_or_u.encode(encoding, errors=errors)
else:
return s_or_u
def _execute(command, **kwargs):
import sarge
import sarge
if isinstance(command, (list, tuple)):
joined_command = " ".join(command)
else:
joined_command = command
_log_call(joined_command)
if isinstance(command, (list, tuple)):
joined_command = " ".join(command)
else:
joined_command = command
_log_call(joined_command)
kwargs.update({"close_fds": CLOSE_FDS,
"async_": True,
"stdout": sarge.Capture(),
"stderr": sarge.Capture()})
kwargs.update(
{
"close_fds": CLOSE_FDS,
"async_": True,
"stdout": sarge.Capture(),
"stderr": sarge.Capture(),
}
)
try:
p = sarge.run(command, **kwargs)
while len(p.commands) == 0:
# somewhat ugly... we can't use wait_events because
# the events might not be all set if an exception
# by sarge is triggered within the async process
# thread
time.sleep(0.01)
try:
p = sarge.run(command, **kwargs)
while len(p.commands) == 0:
# somewhat ugly... we can't use wait_events because
# the events might not be all set if an exception
# by sarge is triggered within the async process
# thread
time.sleep(0.01)
# by now we should have a command, let's wait for its
# process to have been prepared
p.commands[0].process_ready.wait()
# by now we should have a command, let's wait for its
# process to have been prepared
p.commands[0].process_ready.wait()
if not p.commands[0].process:
# the process might have been set to None in case of any exception
print("Error while trying to run command {}".format(joined_command), file=sys.stderr)
return None, [], []
except Exception:
print("Error while trying to run command {}".format(joined_command), file=sys.stderr)
traceback.print_exc(file=sys.stderr)
return None, [], []
if not p.commands[0].process:
# the process might have been set to None in case of any exception
print(
"Error while trying to run command {}".format(joined_command),
file=sys.stderr,
)
return None, [], []
except Exception:
print(
"Error while trying to run command {}".format(joined_command), file=sys.stderr
)
traceback.print_exc(file=sys.stderr)
return None, [], []
all_stdout = []
all_stderr = []
try:
while p.commands[0].poll() is None:
lines = p.stderr.readlines(timeout=0.5)
if lines:
lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines))
_log_stderr(*lines)
all_stderr += lines
all_stdout = []
all_stderr = []
try:
while p.commands[0].poll() is None:
lines = p.stderr.readlines(timeout=0.5)
if lines:
lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines))
_log_stderr(*lines)
all_stderr += lines
lines = p.stdout.readlines(timeout=0.5)
if lines:
lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines))
_log_stdout(*lines)
all_stdout += lines
lines = p.stdout.readlines(timeout=0.5)
if lines:
lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines))
_log_stdout(*lines)
all_stdout += lines
finally:
p.close()
finally:
p.close()
lines = p.stderr.readlines()
if lines:
lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines))
_log_stderr(*lines)
all_stderr += lines
lines = p.stderr.readlines()
if lines:
lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines))
_log_stderr(*lines)
all_stderr += lines
lines = p.stdout.readlines()
if lines:
lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines))
_log_stdout(*lines)
all_stdout += lines
lines = p.stdout.readlines()
if lines:
lines = list(map(lambda x: _to_unicode(x, errors="replace"), lines))
_log_stdout(*lines)
all_stdout += lines
return p.returncode, all_stdout, all_stderr
return p.returncode, all_stdout, all_stderr
def _get_git_executables():
GITS = ["git"]
if sys.platform == "win32":
GITS = ["git.cmd", "git.exe"]
return GITS
GITS = ["git"]
if sys.platform == "win32":
GITS = ["git.cmd", "git.exe"]
return GITS
def _git(args, cwd, git_executable=None):
if git_executable is not None:
commands = [git_executable]
else:
commands = _get_git_executables()
if git_executable is not None:
commands = [git_executable]
else:
commands = _get_git_executables()
for c in commands:
command = [c] + args
try:
return _execute(command, cwd=cwd)
except EnvironmentError:
e = sys.exc_info()[1]
if e.errno == errno.ENOENT:
continue
for c in commands:
command = [c] + args
try:
return _execute(command, cwd=cwd)
except EnvironmentError:
e = sys.exc_info()[1]
if e.errno == errno.ENOENT:
continue
print("Error while trying to run command {}".format(" ".join(command)), file=sys.stderr)
traceback.print_exc(file=sys.stderr)
return None, [], []
except Exception:
print("Error while trying to run command {}".format(" ".join(command)), file=sys.stderr)
traceback.print_exc(file=sys.stderr)
return None, [], []
else:
print("Unable to find git command, tried {}".format(", ".join(commands)), file=sys.stderr)
return None, [], []
print(
"Error while trying to run command {}".format(" ".join(command)),
file=sys.stderr,
)
traceback.print_exc(file=sys.stderr)
return None, [], []
except Exception:
print(
"Error while trying to run command {}".format(" ".join(command)),
file=sys.stderr,
)
traceback.print_exc(file=sys.stderr)
return None, [], []
else:
print(
"Unable to find git command, tried {}".format(", ".join(commands)),
file=sys.stderr,
)
return None, [], []
def _python(args, cwd, python_executable, sudo=False):
command = [python_executable] + args
if sudo:
command = ["sudo"] + command
try:
return _execute(command, cwd=cwd)
except Exception:
import traceback
print("Error while trying to run command {}".format(" ".join(command)), file=sys.stderr)
traceback.print_exc(file=sys.stderr)
return None, [], []
command = [python_executable] + args
if sudo:
command = ["sudo"] + command
try:
return _execute(command, cwd=cwd)
except Exception:
import traceback
print(
"Error while trying to run command {}".format(" ".join(command)),
file=sys.stderr,
)
traceback.print_exc(file=sys.stderr)
return None, [], []
def _to_error(*lines):
if len(lines) == 1:
if isinstance(lines[0], (list, tuple)):
lines = lines[0]
elif not isinstance(lines[0], (str, unicode)):
lines = [repr(lines[0]),]
return "\n".join(map(lambda x: _to_unicode(x, errors="replace"), lines))
if len(lines) == 1:
if isinstance(lines[0], (list, tuple)):
lines = lines[0]
elif not isinstance(lines[0], (str, unicode)):
lines = [
repr(lines[0]),
]
return "\n".join(map(lambda x: _to_unicode(x, errors="replace"), lines))
def _rescue_changes(git_executable, folder):
print(">>> Running: git diff --shortstat")
returncode, stdout, stderr = _git(["diff", "--shortstat"], folder, git_executable=git_executable)
if returncode is None or returncode != 0:
raise RuntimeError("Could not update, \"git diff\" failed with returncode {}".format(returncode))
if stdout and "".join(stdout).strip():
# we got changes in the working tree, maybe from the user, so we'll now rescue those into a patch
import time
import os
timestamp = time.strftime("%Y%m%d%H%M")
patch = os.path.join(folder, "{}-preupdate.patch".format(timestamp))
print(">>> Running: git diff --shortstat")
returncode, stdout, stderr = _git(
["diff", "--shortstat"], folder, git_executable=git_executable
)
if returncode is None or returncode != 0:
raise RuntimeError(
'Could not update, "git diff" failed with returncode {}'.format(returncode)
)
if stdout and "".join(stdout).strip():
# we got changes in the working tree, maybe from the user, so we'll now rescue those into a patch
import time
import os
print(">>> Running: git diff and saving output to {}".format(patch))
returncode, stdout, stderr = _git(["diff"], folder, git_executable=git_executable)
if returncode is None or returncode != 0:
raise RuntimeError("Could not update, installation directory was dirty and state could not be persisted as a patch to {}".format(patch))
timestamp = time.strftime("%Y%m%d%H%M")
patch = os.path.join(folder, "{}-preupdate.patch".format(timestamp))
import io
with io.open(patch, "wt", encoding="utf-8", errors="replace") as f:
for line in stdout:
f.write(line)
print(">>> Running: git diff and saving output to {}".format(patch))
returncode, stdout, stderr = _git(["diff"], folder, git_executable=git_executable)
if returncode is None or returncode != 0:
raise RuntimeError(
"Could not update, installation directory was dirty and state could not be persisted as a patch to {}".format(
patch
)
)
return True
import io
return False
with io.open(patch, "wt", encoding="utf-8", errors="replace") as f:
for line in stdout:
f.write(line)
return True
return False
def update_source(git_executable, folder, target, force=False, branch=None):
if _rescue_changes(git_executable, folder):
print(">>> Running: git reset --hard")
returncode, stdout, stderr = _git(["reset", "--hard"], folder, git_executable=git_executable)
if returncode is None or returncode != 0:
raise RuntimeError("Could not update, \"git reset --hard\" failed with returncode {}".format(returncode))
if _rescue_changes(git_executable, folder):
print(">>> Running: git reset --hard")
returncode, stdout, stderr = _git(
["reset", "--hard"], folder, git_executable=git_executable
)
if returncode is None or returncode != 0:
raise RuntimeError(
'Could not update, "git reset --hard" failed with returncode {}'.format(
returncode
)
)
print(">>> Running: git clean -f -d -e *-preupdate.patch")
returncode, stdout, stderr = _git(["clean", "-f", "-d", "-e", "*-preupdate.patch"], folder, git_executable=git_executable)
if returncode is None or returncode != 0:
raise RuntimeError("Could not update, \"git clean -f\" failed with returncode {}".format(returncode))
print(">>> Running: git clean -f -d -e *-preupdate.patch")
returncode, stdout, stderr = _git(
["clean", "-f", "-d", "-e", "*-preupdate.patch"],
folder,
git_executable=git_executable,
)
if returncode is None or returncode != 0:
raise RuntimeError(
'Could not update, "git clean -f" failed with returncode {}'.format(
returncode
)
)
print(">>> Running: git fetch")
returncode, stdout, stderr = _git(["fetch"], folder, git_executable=git_executable)
if returncode is None or returncode != 0:
raise RuntimeError("Could not update, \"git fetch\" failed with returncode {}".format(returncode))
print(">>> Running: git fetch")
returncode, stdout, stderr = _git(["fetch"], folder, git_executable=git_executable)
if returncode is None or returncode != 0:
raise RuntimeError(
'Could not update, "git fetch" failed with returncode {}'.format(returncode)
)
if branch is not None and branch.strip() != "":
print(">>> Running: git checkout {}".format(branch))
returncode, stdout, stderr = _git(["checkout", branch], folder, git_executable=git_executable)
if returncode is None or returncode != 0:
raise RuntimeError("Could not update, \"git checkout\" failed with returncode {}".format(returncode))
if branch is not None and branch.strip() != "":
print(">>> Running: git checkout {}".format(branch))
returncode, stdout, stderr = _git(
["checkout", branch], folder, git_executable=git_executable
)
if returncode is None or returncode != 0:
raise RuntimeError(
'Could not update, "git checkout" failed with returncode {}'.format(
returncode
)
)
print(">>> Running: git pull")
returncode, stdout, stderr = _git(["pull"], folder, git_executable=git_executable)
if returncode is None or returncode != 0:
raise RuntimeError("Could not update, \"git pull\" failed with returncode {}".format(returncode))
print(">>> Running: git pull")
returncode, stdout, stderr = _git(["pull"], folder, git_executable=git_executable)
if returncode is None or returncode != 0:
raise RuntimeError(
'Could not update, "git pull" failed with returncode {}'.format(returncode)
)
if force:
reset_command = ["reset", "--hard"]
reset_command += [target]
if force:
reset_command = ["reset", "--hard"]
reset_command += [target]
print(">>> Running: git {}".format(" ".join(reset_command)))
returncode, stdout, stderr = _git(reset_command, folder, git_executable=git_executable)
if returncode is None or returncode != 0:
raise RuntimeError("Error while updating, \"git {}\" failed with returncode {}".format(" ".join(reset_command), returncode))
print(">>> Running: git {}".format(" ".join(reset_command)))
returncode, stdout, stderr = _git(
reset_command, folder, git_executable=git_executable
)
if returncode is None or returncode != 0:
raise RuntimeError(
'Error while updating, "git {}" failed with returncode {}'.format(
" ".join(reset_command), returncode
)
)
def install_source(python_executable, folder, user=False, sudo=False):
print(">>> Running: python setup.py clean")
returncode, stdout, stderr = _python(["setup.py", "clean"], folder, python_executable)
if returncode is None or returncode != 0:
print("\"python setup.py clean\" failed with returncode {}".format(returncode))
print("Continuing anyways")
print(">>> Running: python setup.py clean")
returncode, stdout, stderr = _python(["setup.py", "clean"], folder, python_executable)
if returncode is None or returncode != 0:
print('"python setup.py clean" failed with returncode {}'.format(returncode))
print("Continuing anyways")
print(">>> Running: python setup.py install")
args = ["setup.py", "install"]
if user:
args.append("--user")
returncode, stdout, stderr = _python(args, folder, python_executable, sudo=sudo)
if returncode is None or returncode != 0:
raise RuntimeError("Could not update, \"python setup.py install\" failed with returncode {}".format(returncode))
print(">>> Running: python setup.py install")
args = ["setup.py", "install"]
if user:
args.append("--user")
returncode, stdout, stderr = _python(args, folder, python_executable, sudo=sudo)
if returncode is None or returncode != 0:
raise RuntimeError(
'Could not update, "python setup.py install" failed with returncode {}'.format(
returncode
)
)
def parse_arguments():
import argparse
import argparse
boolean_trues = ["true", "yes", "1"]
boolean_trues = ["true", "yes", "1"]
parser = argparse.ArgumentParser(prog="update-octoprint.py")
parser = argparse.ArgumentParser(prog="update-octoprint.py")
parser.add_argument("--git", action="store", type=str, dest="git_executable",
help="Specify git executable to use")
parser.add_argument("--python", action="store", type=str, dest="python_executable",
help="Specify python executable to use")
parser.add_argument("--force", action="store", type=lambda x: x in boolean_trues,
dest="force", default=False,
help="Set this to true to force the update to only the specified version (nothing newer, nothing older)")
parser.add_argument("--sudo", action="store_true", dest="sudo",
help="Install with sudo")
parser.add_argument("--user", action="store_true", dest="user",
help="Install to the user site directory instead of the general site directory")
parser.add_argument("--branch", action="store", type=str, dest="branch", default=None,
help="Specify the branch to make sure is checked out")
parser.add_argument("folder", type=str,
help="Specify the base folder of the OctoPrint installation to update")
parser.add_argument("target", type=str,
help="Specify the commit or tag to which to update")
parser.add_argument(
"--git",
action="store",
type=str,
dest="git_executable",
help="Specify git executable to use",
)
parser.add_argument(
"--python",
action="store",
type=str,
dest="python_executable",
help="Specify python executable to use",
)
parser.add_argument(
"--force",
action="store",
type=lambda x: x in boolean_trues,
dest="force",
default=False,
help="Set this to true to force the update to only the specified version (nothing newer, nothing older)",
)
parser.add_argument(
"--sudo", action="store_true", dest="sudo", help="Install with sudo"
)
parser.add_argument(
"--user",
action="store_true",
dest="user",
help="Install to the user site directory instead of the general site directory",
)
parser.add_argument(
"--branch",
action="store",
type=str,
dest="branch",
default=None,
help="Specify the branch to make sure is checked out",
)
parser.add_argument(
"folder",
type=str,
help="Specify the base folder of the OctoPrint installation to update",
)
parser.add_argument(
"target", type=str, help="Specify the commit or tag to which to update"
)
args = parser.parse_args()
args = parser.parse_args()
return args
return args
def main():
args = parse_arguments()
args = parse_arguments()
git_executable = None
if args.git_executable:
git_executable = args.git_executable
git_executable = None
if args.git_executable:
git_executable = args.git_executable
python_executable = sys.executable
if args.python_executable:
python_executable = args.python_executable
if python_executable.startswith('"'):
python_executable = python_executable[1:]
if python_executable.endswith('"'):
python_executable = python_executable[:-1]
python_executable = sys.executable
if args.python_executable:
python_executable = args.python_executable
if python_executable.startswith('"'):
python_executable = python_executable[1:]
if python_executable.endswith('"'):
python_executable = python_executable[:-1]
print("Python executable: {!r}".format(python_executable))
print("Python executable: {!r}".format(python_executable))
folder = args.folder
folder = args.folder
import os
if not os.access(folder, os.W_OK):
raise RuntimeError("Could not update, base folder is not writable")
import os
if not os.access(folder, os.W_OK):
raise RuntimeError("Could not update, base folder is not writable")
update_source(
git_executable, folder, args.target, force=args.force, branch=args.branch
)
install_source(python_executable, folder, user=args.user, sudo=args.sudo)
update_source(git_executable, folder, args.target, force=args.force, branch=args.branch)
install_source(python_executable, folder, user=args.user, sudo=args.sudo)
if __name__ == "__main__":
main()
main()
@@ -2,7 +2,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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"
from . import pip, python_updater, update_script, sleep_a_bit, single_file_plugin
@@ -2,7 +2,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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"
@@ -14,7 +14,9 @@ from octoprint.util.version import get_comparable_version
from .. import exceptions
logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip")
console_logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.pip.console")
console_logger = logging.getLogger(
"octoprint.plugins.softwareupdate.updaters.pip.console"
)
_ALREADY_INSTALLED = "Requirement already satisfied (use --upgrade to upgrade)"
_POTENTIAL_EGG_PROBLEM_POSIX = "No such file or directory"
@@ -23,108 +25,144 @@ _POTENTIAL_EGG_PROBLEM_WINDOWS = "The system cannot find the file specified"
_pip_callers = {}
_pip_version_dependency_links = pkg_resources.parse_version("1.5")
def can_perform_update(target, check, online=True):
from .. import MINIMUM_PIP
pip_caller = _get_pip_caller(command=check["pip_command"] if "pip_command" in check else None)
return "pip" in check \
and pip_caller is not None \
and pip_caller.available \
and pip_caller.version >= get_comparable_version(MINIMUM_PIP) \
and (online or check.get("offline", False))
from .. import MINIMUM_PIP
pip_caller = _get_pip_caller(
command=check["pip_command"] if "pip_command" in check else None
)
return (
"pip" in check
and pip_caller is not None
and pip_caller.available
and pip_caller.version >= get_comparable_version(MINIMUM_PIP)
and (online or check.get("offline", False))
)
def _get_pip_caller(command=None):
key = command
if command is None:
key = "__default"
key = command
if command is None:
key = "__default"
if not key in _pip_callers:
try:
_pip_callers[key] = PipCaller(configured=command)
except UnknownPip:
_pip_callers[key] = None
if not key in _pip_callers:
try:
_pip_callers[key] = PipCaller(configured=command)
except UnknownPip:
_pip_callers[key] = None
return _pip_callers[key]
return _pip_callers[key]
def perform_update(target, check, target_version, log_cb=None, online=True, force=False):
pip_command = None
if "pip_command" in check:
pip_command = check["pip_command"]
pip_command = None
if "pip_command" in check:
pip_command = check["pip_command"]
pip_working_directory = None
if "pip_cwd" in check:
pip_working_directory = check["pip_cwd"]
pip_working_directory = None
if "pip_cwd" in check:
pip_working_directory = check["pip_cwd"]
if not online and not check.get("offline", False):
raise exceptions.CannotUpdateOffline()
if not online and not check.get("offline", False):
raise exceptions.CannotUpdateOffline()
pip_caller = _get_pip_caller(command=pip_command)
if pip_caller is None:
raise exceptions.UpdateError("Can't run pip", None)
pip_caller = _get_pip_caller(command=pip_command)
if pip_caller is None:
raise exceptions.UpdateError("Can't run pip", None)
def _log_call(*lines):
_log(lines, prefix=" ", stream="call")
def _log_call(*lines):
_log(lines, prefix=" ", stream="call")
def _log_stdout(*lines):
_log(lines, prefix=">", stream="stdout")
def _log_stdout(*lines):
_log(lines, prefix=">", stream="stdout")
def _log_stderr(*lines):
_log(lines, prefix="!", stream="stderr")
def _log_stderr(*lines):
_log(lines, prefix="!", stream="stderr")
def _log_message(*lines):
_log(lines, prefix="#", stream="message")
def _log_message(*lines):
_log(lines, prefix="#", stream="message")
def _log(lines, prefix=None, stream=None):
if log_cb is None:
return
log_cb(lines, prefix=prefix, stream=stream)
def _log(lines, prefix=None, stream=None):
if log_cb is None:
return
log_cb(lines, prefix=prefix, stream=stream)
if log_cb is not None:
pip_caller.on_log_call = _log_call
pip_caller.on_log_stdout = _log_stdout
pip_caller.on_log_stderr = _log_stderr
if log_cb is not None:
pip_caller.on_log_call = _log_call
pip_caller.on_log_stdout = _log_stdout
pip_caller.on_log_stderr = _log_stderr
install_arg = check["pip"].format(target_version=target_version, target=target_version)
install_arg = check["pip"].format(
target_version=target_version, target=target_version
)
logger.debug("Target: %s, executing pip install %s" % (target, install_arg))
pip_args = ["--disable-pip-version-check", "install", install_arg, "--no-cache-dir"]
pip_kwargs = {"env": {"PYTHONWARNINGS": b"ignore:DEPRECATION::pip._internal.cli.base_command"}}
if pip_working_directory is not None:
pip_kwargs.update(cwd=pip_working_directory)
logger.debug("Target: %s, executing pip install %s" % (target, install_arg))
pip_args = ["--disable-pip-version-check", "install", install_arg, "--no-cache-dir"]
pip_kwargs = {
"env": {"PYTHONWARNINGS": b"ignore:DEPRECATION::pip._internal.cli.base_command"}
}
if pip_working_directory is not None:
pip_kwargs.update(cwd=pip_working_directory)
if "dependency_links" in check and check["dependency_links"]:
pip_args += ["--process-dependency-links"]
if "dependency_links" in check and check["dependency_links"]:
pip_args += ["--process-dependency-links"]
returncode, stdout, stderr = pip_caller.execute(*pip_args, **pip_kwargs)
if returncode != 0:
# This could be caused by an issue with pip/setuptools: If something (target or dependency of target) was
# installed as an egg at an earlier date (e.g. thanks to just running python setup.py install), pip install
# will throw an error after updating that something to a newer (non-egg) version since it will still have
# the egg on its sys.path and expect to read data from it. Running the exact same command a second time
# solved this during hunt for a workaround, so this is what we'll now do if it indeed looks like this
# specific problem
def is_egg_problem(line):
return (_POTENTIAL_EGG_PROBLEM_POSIX in line or _POTENTIAL_EGG_PROBLEM_WINDOWS in line) and ".egg" in line
returncode, stdout, stderr = pip_caller.execute(*pip_args, **pip_kwargs)
if returncode != 0:
# This could be caused by an issue with pip/setuptools: If something (target or dependency of target) was
# installed as an egg at an earlier date (e.g. thanks to just running python setup.py install), pip install
# will throw an error after updating that something to a newer (non-egg) version since it will still have
# the egg on its sys.path and expect to read data from it. Running the exact same command a second time
# solved this during hunt for a workaround, so this is what we'll now do if it indeed looks like this
# specific problem
def is_egg_problem(line):
return (
_POTENTIAL_EGG_PROBLEM_POSIX in line
or _POTENTIAL_EGG_PROBLEM_WINDOWS in line
) and ".egg" in line
if any(map(lambda x: is_egg_problem(x), stderr)) or any(map(lambda x: is_egg_problem(x), stdout)):
_log_message("This looks like an error caused by a specific issue in upgrading Python \"eggs\"",
"via current versions of pip.",
"Performing a second install attempt as a work around.")
returncode, stdout, stderr = pip_caller.execute(*pip_args, **pip_kwargs)
if returncode != 0:
raise exceptions.UpdateError("Error while executing pip install", (stdout, stderr))
else:
raise exceptions.UpdateError("Error while executing pip install", (stdout, stderr))
if any(map(lambda x: is_egg_problem(x), stderr)) or any(
map(lambda x: is_egg_problem(x), stdout)
):
_log_message(
'This looks like an error caused by a specific issue in upgrading Python "eggs"',
"via current versions of pip.",
"Performing a second install attempt as a work around.",
)
returncode, stdout, stderr = pip_caller.execute(*pip_args, **pip_kwargs)
if returncode != 0:
raise exceptions.UpdateError(
"Error while executing pip install", (stdout, stderr)
)
else:
raise exceptions.UpdateError(
"Error while executing pip install", (stdout, stderr)
)
if not force and any(map(lambda x: x.strip().startswith(_ALREADY_INSTALLED) and (install_arg in x or install_arg in x.lower()), stdout)):
_log_message("Looks like we were already installed in this version. Forcing a reinstall.")
force = True
if not force and any(
map(
lambda x: x.strip().startswith(_ALREADY_INSTALLED)
and (install_arg in x or install_arg in x.lower()),
stdout,
)
):
_log_message(
"Looks like we were already installed in this version. Forcing a reinstall."
)
force = True
if force:
logger.debug("Target: %s, executing pip install %s --ignore-reinstalled --force-reinstall --no-deps" % (target, install_arg))
pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"]
if force:
logger.debug(
"Target: %s, executing pip install %s --ignore-reinstalled --force-reinstall --no-deps"
% (target, install_arg)
)
pip_args += ["--ignore-installed", "--force-reinstall", "--no-deps"]
returncode, stdout, stderr = pip_caller.execute(*pip_args, **pip_kwargs)
if returncode != 0:
raise exceptions.UpdateError("Error while executing pip install --force-reinstall", (stdout, stderr))
returncode, stdout, stderr = pip_caller.execute(*pip_args, **pip_kwargs)
if returncode != 0:
raise exceptions.UpdateError(
"Error while executing pip install --force-reinstall", (stdout, stderr)
)
return "ok"
return "ok"
@@ -2,28 +2,38 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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"
def can_perform_update(target, check, online=True):
return "python_updater" in check and check["python_updater"] is not None and hasattr(check["python_updater"], "perform_update") and (online or check.get("offline", False))
return (
"python_updater" in check
and check["python_updater"] is not None
and hasattr(check["python_updater"], "perform_update")
and (online or check.get("offline", False))
)
def perform_update(target, check, target_version, log_cb=None, online=True):
from ..exceptions import CannotUpdateOffline
from ..exceptions import CannotUpdateOffline
if not online and not check("offline", False):
raise CannotUpdateOffline()
if not online and not check("offline", False):
raise CannotUpdateOffline()
try:
return check["python_updater"].perform_update(target, check, target_version, log_cb=log_cb, online=online)
except Exception:
import inspect
args, _, _, _ = inspect.getargspec(check["python_updater"].perform_update)
if "online" not in args:
# old python_updater footprint, simply leave out the online parameter
return check["python_updater"].perform_update(target, check, target_version, log_cb=log_cb)
try:
return check["python_updater"].perform_update(
target, check, target_version, log_cb=log_cb, online=online
)
except Exception:
import inspect
# some other error, raise again
raise
args, _, _, _ = inspect.getargspec(check["python_updater"].perform_update)
if "online" not in args:
# old python_updater footprint, simply leave out the online parameter
return check["python_updater"].perform_update(
target, check, target_version, log_cb=log_cb
)
# some other error, raise again
raise
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
@@ -15,61 +15,73 @@ from octoprint.util.net import download_file
from octoprint.settings import settings
from .. import exceptions
logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.download_single_file_plugin")
logger = logging.getLogger(
"octoprint.plugins.softwareupdate.updaters.download_single_file_plugin"
)
def can_perform_update(target, check, online=True):
return online or check.get("offline", False)
return online or check.get("offline", False)
def perform_update(target, check, target_version, log_cb=None, online=True, force=False):
if not online and not check.get("offline", False):
raise exceptions.CannotUpdateOffline()
if not online and not check.get("offline", False):
raise exceptions.CannotUpdateOffline()
url = check.get("url")
if url is None:
raise exceptions.ConfigurationInvalid("download_single_file_plugin updater needs url set")
url = check.get("url")
if url is None:
raise exceptions.ConfigurationInvalid(
"download_single_file_plugin updater needs url set"
)
def _log_call(*lines):
_log(lines, prefix=" ", stream="call")
def _log_call(*lines):
_log(lines, prefix=" ", stream="call")
def _log_message(*lines):
_log(lines, prefix="#", stream="message")
def _log_message(*lines):
_log(lines, prefix="#", stream="message")
def _log(lines, prefix=None, stream=None):
if log_cb is None:
return
log_cb(lines, prefix=prefix, stream=stream)
def _log(lines, prefix=None, stream=None):
if log_cb is None:
return
log_cb(lines, prefix=prefix, stream=stream)
folder = None
try:
try:
_log_message("Download file from {}".format(url))
folder = TemporaryDirectory()
path = download_file(url, folder.name)
except Exception as exc:
raise exceptions.NetworkError(cause=exc)
folder = None
try:
try:
_log_message("Download file from {}".format(url))
folder = TemporaryDirectory()
path = download_file(url, folder.name)
except Exception as exc:
raise exceptions.NetworkError(cause=exc)
filename = os.path.basename(path)
_, ext = os.path.splitext(filename)
if ext not in (".py",):
raise exceptions.UpdateError("File is not a python file: {}".format(filename), None)
filename = os.path.basename(path)
_, ext = os.path.splitext(filename)
if ext not in (".py",):
raise exceptions.UpdateError(
"File is not a python file: {}".format(filename), None
)
try:
with io.open(path, 'rb') as f:
ast.parse(f.read(), filename=path)
except Exception:
logger.exception("Could not parse {} as python file".format(path), None)
raise exceptions.UpdateError("Could not parse {} as python file.".format(filename), None)
try:
with io.open(path, "rb") as f:
ast.parse(f.read(), filename=path)
except Exception:
logger.exception("Could not parse {} as python file".format(path), None)
raise exceptions.UpdateError(
"Could not parse {} as python file.".format(filename), None
)
destination = os.path.join(settings().getBaseFolder("plugins"), filename)
destination = os.path.join(settings().getBaseFolder("plugins"), filename)
try:
_log_message("Copy {} to {}".format(path, destination))
shutil.copy(path, destination)
except Exception:
logger.exception("Could not copy {} to {}".format(path, destination))
raise exceptions.UpdateError("Could not copy {} to {}".format(path, destination), None)
try:
_log_message("Copy {} to {}".format(path, destination))
shutil.copy(path, destination)
except Exception:
logger.exception("Could not copy {} to {}".format(path, destination))
raise exceptions.UpdateError(
"Could not copy {} to {}".format(path, destination), None
)
return "ok"
finally:
if folder is not None:
folder.cleanup()
return "ok"
finally:
if folder is not None:
folder.cleanup()
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
@@ -9,16 +9,17 @@ import time
from octoprint.util import monotonic_time
def can_perform_update(target, check, online=True):
return True
return True
def perform_update(target, check, target_version, log_cb=None, online=True):
duration = check.get("duration", 30)
duration = check.get("duration", 30)
now = monotonic_time()
end = now + duration
while now < end:
log_cb(["{}s left...".format(end - now)], prefix=">", stream="output")
time.sleep(5)
now = monotonic_time()
now = monotonic_time()
end = now + duration
while now < end:
log_cb(["{}s left...".format(end - now)], prefix=">", stream="output")
time.sleep(5)
now = monotonic_time()
@@ -2,7 +2,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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"
import sys
@@ -14,92 +14,119 @@ from octoprint.util.commandline import CommandlineCaller, CommandlineError
def _get_caller(log_cb=None):
def _log_call(*lines):
_log(lines, prefix=" ", stream="call")
def _log_call(*lines):
_log(lines, prefix=" ", stream="call")
def _log_stdout(*lines):
_log(lines, prefix=">", stream="stdout")
def _log_stdout(*lines):
_log(lines, prefix=">", stream="stdout")
def _log_stderr(*lines):
_log(lines, prefix="!", stream="stderr")
def _log_stderr(*lines):
_log(lines, prefix="!", stream="stderr")
def _log(lines, prefix=None, stream=None):
if log_cb is None:
return
log_cb(lines, prefix=prefix, stream=stream)
def _log(lines, prefix=None, stream=None):
if log_cb is None:
return
log_cb(lines, prefix=prefix, stream=stream)
caller = CommandlineCaller()
if log_cb is not None:
caller.on_log_call = _log_call
caller.on_log_stdout = _log_stdout
caller.on_log_stderr = _log_stderr
return caller
caller = CommandlineCaller()
if log_cb is not None:
caller.on_log_call = _log_call
caller.on_log_stdout = _log_stdout
caller.on_log_stderr = _log_stderr
return caller
def can_perform_update(target, check, online=True):
import os
script_configured = bool("update_script" in check and check["update_script"])
import os
folder = None
if "update_folder" in check:
folder = check["update_folder"]
elif "checkout_folder" in check:
folder = check["checkout_folder"]
folder_configured = bool(folder and os.path.isdir(folder))
script_configured = bool("update_script" in check and check["update_script"])
return script_configured and folder_configured and (online or check.get("offline", False))
folder = None
if "update_folder" in check:
folder = check["update_folder"]
elif "checkout_folder" in check:
folder = check["checkout_folder"]
folder_configured = bool(folder and os.path.isdir(folder))
return (
script_configured
and folder_configured
and (online or check.get("offline", False))
)
def perform_update(target, check, target_version, log_cb=None, online=True):
logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.update_script")
logger = logging.getLogger("octoprint.plugins.softwareupdate.updaters.update_script")
if not online and not check("offline", False):
raise CannotUpdateOffline()
if not online and not check("offline", False):
raise CannotUpdateOffline()
if not can_perform_update(target, check):
raise ConfigurationInvalid("checkout_folder and update_folder are missing for update target %s, one is needed" % target)
if not can_perform_update(target, check):
raise ConfigurationInvalid(
"checkout_folder and update_folder are missing for update target %s, one is needed"
% target
)
update_script = check["update_script"]
update_branch = check.get("update_branch", "")
force_exact_version = check.get("force_exact_version", False)
folder = check.get("update_folder", check.get("checkout_folder")) # either should be set, tested above
pre_update_script = check.get("pre_update_script", None)
post_update_script = check.get("post_update_script", None)
update_script = check["update_script"]
update_branch = check.get("update_branch", "")
force_exact_version = check.get("force_exact_version", False)
folder = check.get(
"update_folder", check.get("checkout_folder")
) # either should be set, tested above
pre_update_script = check.get("pre_update_script", None)
post_update_script = check.get("post_update_script", None)
caller = _get_caller(log_cb=log_cb)
caller = _get_caller(log_cb=log_cb)
### pre update
### pre update
if pre_update_script is not None:
logger.debug("Target: %s, running pre-update script: %s" % (target, pre_update_script))
try:
caller.checked_call(pre_update_script, cwd=folder)
except CommandlineError as e:
logger.exception("Target: %s, error while executing pre update script, got returncode %r" % (target, e.returncode))
if pre_update_script is not None:
logger.debug(
"Target: %s, running pre-update script: %s" % (target, pre_update_script)
)
try:
caller.checked_call(pre_update_script, cwd=folder)
except CommandlineError as e:
logger.exception(
"Target: %s, error while executing pre update script, got returncode %r"
% (target, e.returncode)
)
### update
### update
try:
update_command = update_script.format(python=sys.executable,
folder=folder,
target=target_version,
branch=update_branch,
force="true" if force_exact_version else "false")
try:
update_command = update_script.format(
python=sys.executable,
folder=folder,
target=target_version,
branch=update_branch,
force="true" if force_exact_version else "false",
)
logger.debug("Target %s, running update script: %s" % (target, update_command))
logger.debug("Target %s, running update script: %s" % (target, update_command))
caller.checked_call(update_command, cwd=folder)
except CommandlineError as e:
logger.exception("Target: %s, error while executing update script, got returncode %r" % (target, e.returncode))
raise UpdateError("Error while executing update script for %s", (e.stdout, e.stderr))
caller.checked_call(update_command, cwd=folder)
except CommandlineError as e:
logger.exception(
"Target: %s, error while executing update script, got returncode %r"
% (target, e.returncode)
)
raise UpdateError(
"Error while executing update script for %s", (e.stdout, e.stderr)
)
### post update
### post update
if post_update_script is not None:
logger.debug("Target: %s, running post-update script %s..." % (target, post_update_script))
try:
caller.checked_call(post_update_script, cwd=folder)
except CommandlineError as e:
logger.exception("Target: %s, error while executing post update script, got returncode %r" % (target, e.returncode))
if post_update_script is not None:
logger.debug(
"Target: %s, running post-update script %s..." % (target, post_update_script)
)
try:
caller.checked_call(post_update_script, cwd=folder)
except CommandlineError as e:
logger.exception(
"Target: %s, error while executing post update script, got returncode %r"
% (target, e.returncode)
)
return "ok"
return "ok"
+27 -16
View File
@@ -2,7 +2,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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"
@@ -12,23 +12,34 @@ import logging
from octoprint.util.platform import CLOSE_FDS
def execute(command, cwd=None, evaluate_returncode=True, **kwargs):
do_async = kwargs.get("do_async", kwargs.get("async", False))
do_async = kwargs.get("do_async", kwargs.get("async", False))
import sarge
p = None
import sarge
try:
p = sarge.run(command, close_fds=CLOSE_FDS, cwd=cwd, stdout=sarge.Capture(), stderr=sarge.Capture(), async_=do_async)
except Exception:
logging.getLogger(__name__).exception("Error while executing command: {}".format(command))
returncode = p.returncode if p is not None else None
stdout = p.stdout.text if p is not None and p.stdout is not None else ""
stderr = p.stderr.text if p is not None and p.stderr is not None else ""
raise ScriptError(returncode, stdout, stderr)
p = None
if evaluate_returncode and p.returncode != 0:
raise ScriptError(p.returncode, p.stdout.text, p.stderr.text)
try:
p = sarge.run(
command,
close_fds=CLOSE_FDS,
cwd=cwd,
stdout=sarge.Capture(),
stderr=sarge.Capture(),
async_=do_async,
)
except Exception:
logging.getLogger(__name__).exception(
"Error while executing command: {}".format(command)
)
returncode = p.returncode if p is not None else None
stdout = p.stdout.text if p is not None and p.stdout is not None else ""
stderr = p.stderr.text if p is not None and p.stderr is not None else ""
raise ScriptError(returncode, stdout, stderr)
if not do_async:
return p.returncode, p.stdout.text, p.stderr.text
if evaluate_returncode and p.returncode != 0:
raise ScriptError(p.returncode, p.stdout.text, p.stderr.text)
if not do_async:
return p.returncode, p.stdout.text, p.stderr.text
@@ -2,20 +2,39 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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"
from . import commandline, git_commit, github_commit, github_release, bitbucket_commit, \
python_checker, never_current, always_current, pypi_release, httpheader, jsondata
from . import (
commandline,
git_commit,
github_commit,
github_release,
bitbucket_commit,
python_checker,
never_current,
always_current,
pypi_release,
httpheader,
jsondata,
)
def log_github_ratelimit(logger, r):
ratelimit = r.headers["X-RateLimit-Limit"] if "X-RateLimit-Limit" in r.headers else "?"
remaining = r.headers["X-RateLimit-Remaining"] if "X-RateLimit-Remaining" in r.headers else "?"
reset = r.headers["X-RateLimit-Reset"] if "X-RateLimit-Reset" in r.headers else None
try:
import time
reset = time.strftime("%Y-%m-%d %H:%M", time.gmtime(int(reset)))
except Exception:
reset = "?"
ratelimit = (
r.headers["X-RateLimit-Limit"] if "X-RateLimit-Limit" in r.headers else "?"
)
remaining = (
r.headers["X-RateLimit-Remaining"]
if "X-RateLimit-Remaining" in r.headers
else "?"
)
reset = r.headers["X-RateLimit-Reset"] if "X-RateLimit-Reset" in r.headers else None
try:
import time
logger.debug("Github rate limit: %s/%s, reset at %s" % (remaining, ratelimit, reset))
reset = time.strftime("%Y-%m-%d %H:%M", time.gmtime(int(reset)))
except Exception:
reset = "?"
logger.debug("Github rate limit: %s/%s, reset at %s" % (remaining, ratelimit, reset))
@@ -1,13 +1,16 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
def get_latest(target, check, online=True):
current_version = check.get("current_version", "1.0.0")
current_version = check.get("current_version", "1.0.0")
information = {"local": {"name": current_version, "value": current_version},
"remote": {"name": current_version, "value": current_version}}
information = {
"local": {"name": current_version, "value": current_version},
"remote": {"name": current_version, "value": current_version},
}
return information, True
return information, True
@@ -1,70 +1,93 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
import requests
import logging
import base64
BRANCH_HEAD_URL = "https://api.bitbucket.org/2.0/repositories/{user}/{repo}/commit/{branch}"
BRANCH_HEAD_URL = (
"https://api.bitbucket.org/2.0/repositories/{user}/{repo}/commit/{branch}"
)
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.bitbucket_commit")
logger = logging.getLogger(
"octoprint.plugins.softwareupdate.version_checks.bitbucket_commit"
)
def _get_latest_commit(user, repo, branch, api_user=None, api_password=None):
from ..exceptions import NetworkError
from ..exceptions import NetworkError
url = BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch)
headers = {}
if api_user is not None and api_password is not None:
auth_value = base64.b64encode(b"{user}:{pw}".format(user=api_user, pw=api_password))
headers["authorization"] = "Basic {}".format(auth_value)
url = BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch)
headers = {}
if api_user is not None and api_password is not None:
auth_value = base64.b64encode(
b"{user}:{pw}".format(user=api_user, pw=api_password)
)
headers["authorization"] = "Basic {}".format(auth_value)
try:
r = requests.get(url, headers=headers, timeout=(3.05, 30))
except requests.ConnectionError as exc:
raise NetworkError(cause=exc)
try:
r = requests.get(url, headers=headers, timeout=(3.05, 30))
except requests.ConnectionError as exc:
raise NetworkError(cause=exc)
if not r.status_code == requests.codes.ok:
return None
if not r.status_code == requests.codes.ok:
return None
reference = r.json()
if not "hash" in reference:
return None
reference = r.json()
if not "hash" in reference:
return None
return reference["hash"]
return reference["hash"]
def get_latest(target, check, online=True):
from ..exceptions import ConfigurationInvalid
from ..exceptions import ConfigurationInvalid
if "user" not in check or "repo" not in check:
raise ConfigurationInvalid("Update configuration for %s of type bitbucket_commit needs all of user and repo" % target)
if "user" not in check or "repo" not in check:
raise ConfigurationInvalid(
"Update configuration for %s of type bitbucket_commit needs all of user and repo"
% target
)
branch = "master"
if "branch" in check and check["branch"] is not None:
branch = check["branch"]
branch = "master"
if "branch" in check and check["branch"] is not None:
branch = check["branch"]
api_user = check.get("api_user")
api_password = check.get("api_password")
api_user = check.get("api_user")
api_password = check.get("api_password")
current = check.get("current")
current = check.get("current")
information = {"local": {"name": "Commit {commit}".format(commit=current if current is not None else "unknown"), "value": current},
"remote": {"name": "?", "value": "?"},
"needs_online": not check.get("offline", False)}
if not online and information["needs_online"]:
return information, True
information = {
"local": {
"name": "Commit {commit}".format(
commit=current if current is not None else "unknown"
),
"value": current,
},
"remote": {"name": "?", "value": "?"},
"needs_online": not check.get("offline", False),
}
if not online and information["needs_online"]:
return information, True
remote_commit = _get_latest_commit(check["user"], check["repo"], branch, api_user, api_password)
remote_name = "Commit {commit}".format(commit=remote_commit) if remote_commit is not None else "-"
remote_commit = _get_latest_commit(
check["user"], check["repo"], branch, api_user, api_password
)
remote_name = (
"Commit {commit}".format(commit=remote_commit)
if remote_commit is not None
else "-"
)
information["remote"] = {"name": remote_name, "value": remote_commit}
is_current = (current is not None and current == remote_commit) or remote_commit is None
information["remote"] = {"name": remote_name, "value": remote_commit}
is_current = (
current is not None and current == remote_commit
) or remote_commit is None
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit))
return information, is_current
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit))
return information, is_current
@@ -2,7 +2,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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"
@@ -11,38 +11,54 @@ import logging
from ..exceptions import ConfigurationInvalid, CannotCheckOffline
from ..util import execute
def get_latest(target, check, online=True):
command = check.get("command")
if command is None:
raise ConfigurationInvalid("Update configuration for {} of type commandline needs command set and not None".format(target))
command = check.get("command")
if command is None:
raise ConfigurationInvalid(
"Update configuration for {} of type commandline needs command set and not None".format(
target
)
)
if not online and not check.get("offline", False):
raise CannotCheckOffline("{} isn't marked as 'offline' capable, but we are apparently offline right now".format(target))
if not online and not check.get("offline", False):
raise CannotCheckOffline(
"{} isn't marked as 'offline' capable, but we are apparently offline right now".format(
target
)
)
returncode, stdout, stderr = execute(command, evaluate_returncode=False)
returncode, stdout, stderr = execute(command, evaluate_returncode=False)
# We expect command line check commands to
#
# * have a return code of 0 if an update is available, a value != 0 otherwise
# * return the display name of the new version as the final line on stdout
# * return the display name of the current version as the next to final line on stdout
#
# Example output:
# 1.1.0
# 1.1.1
#
# 1.1.0 is the current version, 1.1.1 is the remote version. If only one line is output, it's taken to be the
# display name of the new version
# We expect command line check commands to
#
# * have a return code of 0 if an update is available, a value != 0 otherwise
# * return the display name of the new version as the final line on stdout
# * return the display name of the current version as the next to final line on stdout
#
# Example output:
# 1.1.0
# 1.1.1
#
# 1.1.0 is the current version, 1.1.1 is the remote version. If only one line is output, it's taken to be the
# display name of the new version
stdout_lines = list(filter(lambda x: len(x.strip()), stdout.splitlines()))
local_name = stdout_lines[-2] if len(stdout_lines) >= 2 else "unknown"
remote_name = stdout_lines[-1] if len(stdout_lines) >= 1 else "unknown"
is_current = returncode != 0
stdout_lines = list(filter(lambda x: len(x.strip()), stdout.splitlines()))
local_name = stdout_lines[-2] if len(stdout_lines) >= 2 else "unknown"
remote_name = stdout_lines[-1] if len(stdout_lines) >= 1 else "unknown"
is_current = returncode != 0
information ={"local": {"name": local_name, "value": local_name,},
"remote": {"name": remote_name, "value": remote_name}}
information = {
"local": {
"name": local_name,
"value": local_name,
},
"remote": {"name": remote_name, "value": remote_name},
}
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.github_commit")
logger.debug("Target: %s, local: %s, remote: %s" % (target, local_name, remote_name))
logger = logging.getLogger(
"octoprint.plugins.softwareupdate.version_checks.github_commit"
)
logger.debug("Target: %s, local: %s, remote: %s" % (target, local_name, remote_name))
return information, is_current
return information, is_current
@@ -2,7 +2,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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"
@@ -13,75 +13,95 @@ import logging
from ..exceptions import ConfigurationInvalid
def _get_git_executables():
GITS = ["git"]
if sys.platform == "win32":
GITS = ["git.cmd", "git.exe"]
return GITS
GITS = ["git"]
if sys.platform == "win32":
GITS = ["git.cmd", "git.exe"]
return GITS
def _git(args, cwd, hide_stderr=False):
commands = _get_git_executables()
commands = _get_git_executables()
for c in commands:
try:
p = subprocess.Popen([c] + args, cwd=cwd, stdout=subprocess.PIPE,
stderr=(subprocess.PIPE if hide_stderr
else None))
break
except EnvironmentError:
e = sys.exc_info()[1]
if e.errno == errno.ENOENT:
continue
return None, None
else:
return None, None
for c in commands:
try:
p = subprocess.Popen(
[c] + args,
cwd=cwd,
stdout=subprocess.PIPE,
stderr=(subprocess.PIPE if hide_stderr else None),
)
break
except EnvironmentError:
e = sys.exc_info()[1]
if e.errno == errno.ENOENT:
continue
return None, None
else:
return None, None
stdout = p.communicate()[0].strip()
if sys.version >= '3':
stdout = stdout.decode()
stdout = p.communicate()[0].strip()
if sys.version >= "3":
stdout = stdout.decode()
if p.returncode != 0:
return p.returncode, None
if p.returncode != 0:
return p.returncode, None
return p.returncode, stdout
return p.returncode, stdout
def get_latest(target, check, online=True):
checkout_folder = check.get("checkout_folder")
if checkout_folder is None:
raise ConfigurationInvalid("Update configuration for {} of type git_commit needs checkout_folder set and not None".format(target))
checkout_folder = check.get("checkout_folder")
if checkout_folder is None:
raise ConfigurationInvalid(
"Update configuration for {} of type git_commit needs checkout_folder set and not None".format(
target
)
)
returncode, local_commit = _git(["rev-parse", "@{0}"], checkout_folder)
if returncode != 0:
return None, True
returncode, local_commit = _git(["rev-parse", "@{0}"], checkout_folder)
if returncode != 0:
return None, True
information = {"local": {"name": "Commit %s" % local_commit, "value": local_commit},
"remote": {"name": "?", "value": "?"},
"needs_online": not check.get("offline", False)}
if not online and information["needs_online"]:
return information, True
information = {
"local": {"name": "Commit %s" % local_commit, "value": local_commit},
"remote": {"name": "?", "value": "?"},
"needs_online": not check.get("offline", False),
}
if not online and information["needs_online"]:
return information, True
returncode, _ = _git(["fetch"], checkout_folder)
if returncode != 0:
return information, True
returncode, _ = _git(["fetch"], checkout_folder)
if returncode != 0:
return information, True
returncode, remote_commit = _git(["rev-parse", "@{u}"], checkout_folder)
if returncode != 0:
return information, True
returncode, remote_commit = _git(["rev-parse", "@{u}"], checkout_folder)
if returncode != 0:
return information, True
returncode, base = _git(["merge-base", "@{0}", "@{u}"], checkout_folder)
if returncode != 0:
return information, True
returncode, base = _git(["merge-base", "@{0}", "@{u}"], checkout_folder)
if returncode != 0:
return information, True
if local_commit == remote_commit or remote_commit == base:
information["remote"] = {"name": "Commit %s" % local_commit, "value": local_commit}
is_current = True
else:
information["remote"] = {"name": "Commit %s" % remote_commit, "value": remote_commit}
is_current = local_commit == remote_commit
if local_commit == remote_commit or remote_commit == base:
information["remote"] = {
"name": "Commit %s" % local_commit,
"value": local_commit,
}
is_current = True
else:
information["remote"] = {
"name": "Commit %s" % remote_commit,
"value": remote_commit,
}
is_current = local_commit == remote_commit
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.git_commit")
logger.debug("Target: %s, local: %s, remote: %s" % (target, local_commit, remote_commit))
logger = logging.getLogger(
"octoprint.plugins.softwareupdate.version_checks.git_commit"
)
logger.debug(
"Target: %s, local: %s, remote: %s" % (target, local_commit, remote_commit)
)
return information, is_current
return information, is_current
@@ -2,7 +2,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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"
import requests
@@ -10,57 +10,80 @@ import logging
BRANCH_HEAD_URL = "https://api.github.com/repos/{user}/{repo}/git/refs/heads/{branch}"
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.github_commit")
logger = logging.getLogger(
"octoprint.plugins.softwareupdate.version_checks.github_commit"
)
def _get_latest_commit(user, repo, branch):
from ..exceptions import NetworkError
from ..exceptions import NetworkError
try:
r = requests.get(BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch), timeout=(3.05, 30))
except requests.ConnectionError as exc:
raise NetworkError(cause=exc)
try:
r = requests.get(
BRANCH_HEAD_URL.format(user=user, repo=repo, branch=branch),
timeout=(3.05, 30),
)
except requests.ConnectionError as exc:
raise NetworkError(cause=exc)
from . import log_github_ratelimit
log_github_ratelimit(logger, r)
from . import log_github_ratelimit
if not r.status_code == requests.codes.ok:
return None
log_github_ratelimit(logger, r)
reference = r.json()
if not "object" in reference or not "sha" in reference["object"]:
return None
if not r.status_code == requests.codes.ok:
return None
return reference["object"]["sha"]
reference = r.json()
if not "object" in reference or not "sha" in reference["object"]:
return None
return reference["object"]["sha"]
def get_latest(target, check, online=True):
from ..exceptions import ConfigurationInvalid
from ..exceptions import ConfigurationInvalid
user = check.get("user")
repo = check.get("repo")
user = check.get("user")
repo = check.get("repo")
if user is None or repo is None:
raise ConfigurationInvalid("Update configuration for {} of type github_commit needs user and repo set and not None".format(target))
if user is None or repo is None:
raise ConfigurationInvalid(
"Update configuration for {} of type github_commit needs user and repo set and not None".format(
target
)
)
branch = "master"
if "branch" in check and check["branch"] is not None:
branch = check["branch"]
branch = "master"
if "branch" in check and check["branch"] is not None:
branch = check["branch"]
current = check.get("current")
current = check.get("current")
information = {"local": {"name": "Commit {commit}".format(commit=current if current is not None else "?"), "value": current},
"remote": {"name": "?", "value": "?"},
"needs_online": not check.get("offline", False)}
if not online and information["needs_online"]:
return information, True
information = {
"local": {
"name": "Commit {commit}".format(
commit=current if current is not None else "?"
),
"value": current,
},
"remote": {"name": "?", "value": "?"},
"needs_online": not check.get("offline", False),
}
if not online and information["needs_online"]:
return information, True
remote_commit = _get_latest_commit(check["user"], check["repo"], branch)
remote_name = "Commit {commit}".format(commit=remote_commit) if remote_commit is not None else "-"
remote_commit = _get_latest_commit(check["user"], check["repo"], branch)
remote_name = (
"Commit {commit}".format(commit=remote_commit)
if remote_commit is not None
else "-"
)
information["remote"] = {"name": remote_name, "value": remote_commit}
is_current = (current is not None and current == remote_commit) or remote_commit is None
information["remote"] = {"name": remote_name, "value": remote_commit}
is_current = (
current is not None and current == remote_commit
) or remote_commit is None
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit))
return information, is_current
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit))
return information, is_current
@@ -1,9 +1,10 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function
# MO unicode_literals because fixing all the doctests is too annoying :-P
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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"
import requests
@@ -14,289 +15,332 @@ from octoprint.util.version import get_comparable_version
RELEASE_URL = "https://api.github.com/repos/{user}/{repo}/releases"
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.github_release")
def _filter_out_latest(releases,
sort_key=None,
include_prerelease=False,
commitish=None):
"""
Filters out the newest of all matching releases.
Tests:
>>> release_1_2_15 = dict(name="1.2.15", tag_name="1.2.15", html_url="some_url", published_at="2016-07-29T19:53:29Z", prerelease=False, draft=False, target_commitish="prerelease")
>>> release_1_2_16rc1 = dict(name="1.2.16rc1", tag_name="1.2.16rc1", html_url="some_url", published_at="2016-08-29T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance")
>>> release_1_2_16rc2 = dict(name="1.2.16rc2", tag_name="1.2.16rc2", html_url="some_url", published_at="2016-08-30T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance")
>>> release_1_2_17rc1 = dict(name="1.2.17rc1", tag_name="1.2.17rc1", html_url="some_url", published_at="2016-08-31T12:00:00Z", prerelease=True, draft=True, target_commitish="rc/maintenance")
>>> release_1_3_0rc1 = dict(name="1.3.0rc1", tag_name="1.3.0rc1", html_url="some_url", published_at="2016-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/devel")
>>> release_1_3_5rc1 = dict(name="1.3.5rc1", tag_name="1.3.5rc1", html_url="some_url", published_at="2017-06-14T10:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance")
>>> release_1_2_18 = dict(name="1.2.18", tag_name="1.2.18", html_url="some_url", published_at="2016-12-13T12:00:00Z", prerelease=False, draft=False, target_commitish="master")
>>> release_1_4_0rc1 = dict(name="1.4.0rc1", tag_name="1.4.0rc1", html_url="some_url", published_at="2017-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/future")
>>> release_1_4_0rc1_devel = dict(name="1.4.0rc1", tag_name="1.4.0rc1", html_url="some_url", published_at="2017-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/devel")
>>> releases = [release_1_2_15, release_1_2_16rc1, release_1_2_16rc2, release_1_2_17rc1, release_1_3_0rc1, release_1_4_0rc1]
>>> _filter_out_latest(releases, include_prerelease=False, commitish=None)
('1.2.15', '1.2.15', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, commitish=["rc/maintenance"])
('1.2.16rc2', '1.2.16rc2', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, commitish=["rc/devel"])
('1.3.0rc1', '1.3.0rc1', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, commitish=None)
('1.4.0rc1', '1.4.0rc1', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, commitish=["rc/doesntexist"])
('1.2.15', '1.2.15', 'some_url')
>>> _filter_out_latest([release_1_2_17rc1])
(None, None, None)
>>> _filter_out_latest([release_1_2_16rc1, release_1_2_16rc2])
(None, None, None)
>>> comparable_factory = _get_comparable_factory("python", force_base=True)
>>> sort_key = lambda release: comparable_factory(_get_sanitized_version(release["tag_name"]))
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=False, commitish=None, sort_key=sort_key)
('1.2.18', '1.2.18', 'some_url')
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, commitish=["rc/maintenance"], sort_key=sort_key)
('1.2.18', '1.2.18', 'some_url')
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, commitish=["rc/devel"], sort_key=sort_key)
('1.3.0rc1', '1.3.0rc1', 'some_url')
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1], include_prerelease=True, commitish=["rc/maintenance"])
('1.3.5rc1', '1.3.5rc1', 'some_url')
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1], include_prerelease=True, commitish=["rc/maintenance", "rc/devel"])
('1.3.5rc1', '1.3.5rc1', 'some_url')
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1, release_1_4_0rc1_devel], include_prerelease=True, commitish=["rc/maintenance"])
('1.3.5rc1', '1.3.5rc1', 'some_url')
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1, release_1_4_0rc1_devel], include_prerelease=True, commitish=["rc/maintenance", "rc/devel"])
('1.4.0rc1', '1.4.0rc1', 'some_url')
"""
nothing = None, None, None
if sort_key is None:
sort_key = lambda release: sv(release.get("published_at", None))
# filter out prereleases and drafts
filter_function = lambda rel: not rel["prerelease"] and not rel["draft"]
if include_prerelease:
if commitish:
filter_function = lambda rel: not rel["draft"] and \
(not rel["prerelease"] or rel["target_commitish"] in commitish)
else:
filter_function = lambda rel: not rel["draft"]
releases = list(filter(filter_function, releases))
if not releases:
return nothing
# sort by sort_key
releases = sorted(releases, key=sort_key)
# latest release = last in list
latest = releases[-1]
return latest["name"], latest["tag_name"], latest.get("html_url", None)
logger = logging.getLogger(
"octoprint.plugins.softwareupdate.version_checks.github_release"
)
def _get_latest_release(user, repo, compare_type,
include_prerelease=False,
commitish=None,
force_base=True):
from ..exceptions import NetworkError
def _filter_out_latest(releases, sort_key=None, include_prerelease=False, commitish=None):
"""
Filters out the newest of all matching releases.
nothing = None, None, None
Tests:
try:
r = requests.get(RELEASE_URL.format(user=user, repo=repo), timeout=(3.05, 30))
except requests.ConnectionError as exc:
raise NetworkError(cause=exc)
>>> release_1_2_15 = dict(name="1.2.15", tag_name="1.2.15", html_url="some_url", published_at="2016-07-29T19:53:29Z", prerelease=False, draft=False, target_commitish="prerelease")
>>> release_1_2_16rc1 = dict(name="1.2.16rc1", tag_name="1.2.16rc1", html_url="some_url", published_at="2016-08-29T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance")
>>> release_1_2_16rc2 = dict(name="1.2.16rc2", tag_name="1.2.16rc2", html_url="some_url", published_at="2016-08-30T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance")
>>> release_1_2_17rc1 = dict(name="1.2.17rc1", tag_name="1.2.17rc1", html_url="some_url", published_at="2016-08-31T12:00:00Z", prerelease=True, draft=True, target_commitish="rc/maintenance")
>>> release_1_3_0rc1 = dict(name="1.3.0rc1", tag_name="1.3.0rc1", html_url="some_url", published_at="2016-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/devel")
>>> release_1_3_5rc1 = dict(name="1.3.5rc1", tag_name="1.3.5rc1", html_url="some_url", published_at="2017-06-14T10:00:00Z", prerelease=True, draft=False, target_commitish="rc/maintenance")
>>> release_1_2_18 = dict(name="1.2.18", tag_name="1.2.18", html_url="some_url", published_at="2016-12-13T12:00:00Z", prerelease=False, draft=False, target_commitish="master")
>>> release_1_4_0rc1 = dict(name="1.4.0rc1", tag_name="1.4.0rc1", html_url="some_url", published_at="2017-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/future")
>>> release_1_4_0rc1_devel = dict(name="1.4.0rc1", tag_name="1.4.0rc1", html_url="some_url", published_at="2017-12-12T12:00:00Z", prerelease=True, draft=False, target_commitish="rc/devel")
>>> releases = [release_1_2_15, release_1_2_16rc1, release_1_2_16rc2, release_1_2_17rc1, release_1_3_0rc1, release_1_4_0rc1]
>>> _filter_out_latest(releases, include_prerelease=False, commitish=None)
('1.2.15', '1.2.15', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, commitish=["rc/maintenance"])
('1.2.16rc2', '1.2.16rc2', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, commitish=["rc/devel"])
('1.3.0rc1', '1.3.0rc1', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, commitish=None)
('1.4.0rc1', '1.4.0rc1', 'some_url')
>>> _filter_out_latest(releases, include_prerelease=True, commitish=["rc/doesntexist"])
('1.2.15', '1.2.15', 'some_url')
>>> _filter_out_latest([release_1_2_17rc1])
(None, None, None)
>>> _filter_out_latest([release_1_2_16rc1, release_1_2_16rc2])
(None, None, None)
from . import log_github_ratelimit
log_github_ratelimit(logger, r)
>>> comparable_factory = _get_comparable_factory("python", force_base=True)
>>> sort_key = lambda release: comparable_factory(_get_sanitized_version(release["tag_name"]))
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=False, commitish=None, sort_key=sort_key)
('1.2.18', '1.2.18', 'some_url')
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, commitish=["rc/maintenance"], sort_key=sort_key)
('1.2.18', '1.2.18', 'some_url')
>>> _filter_out_latest(releases + [release_1_2_18], include_prerelease=True, commitish=["rc/devel"], sort_key=sort_key)
('1.3.0rc1', '1.3.0rc1', 'some_url')
if not r.status_code == requests.codes.ok:
return nothing
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1], include_prerelease=True, commitish=["rc/maintenance"])
('1.3.5rc1', '1.3.5rc1', 'some_url')
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1], include_prerelease=True, commitish=["rc/maintenance", "rc/devel"])
('1.3.5rc1', '1.3.5rc1', 'some_url')
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1, release_1_4_0rc1_devel], include_prerelease=True, commitish=["rc/maintenance"])
('1.3.5rc1', '1.3.5rc1', 'some_url')
>>> _filter_out_latest([release_1_2_18, release_1_3_5rc1, release_1_4_0rc1_devel], include_prerelease=True, commitish=["rc/maintenance", "rc/devel"])
('1.4.0rc1', '1.4.0rc1', 'some_url')
"""
releases = r.json()
nothing = None, None, None
# sanitize
required_fields = {"name", "tag_name", "html_url", "draft", "prerelease", "published_at", "target_commitish"}
releases = list(filter(lambda rel: set(rel.keys()) & required_fields == required_fields,
releases))
if sort_key is None:
sort_key = lambda release: sv(release.get("published_at", None))
comparable_factory = _get_comparable_factory(compare_type,
force_base=force_base)
sort_key = lambda release: comparable_factory(_get_sanitized_version(release["tag_name"]))
# filter out prereleases and drafts
filter_function = lambda rel: not rel["prerelease"] and not rel["draft"]
if include_prerelease:
if commitish:
filter_function = lambda rel: not rel["draft"] and (
not rel["prerelease"] or rel["target_commitish"] in commitish
)
else:
filter_function = lambda rel: not rel["draft"]
return _filter_out_latest(releases,
sort_key=sort_key,
include_prerelease=include_prerelease,
commitish=commitish)
releases = list(filter(filter_function, releases))
if not releases:
return nothing
# sort by sort_key
releases = sorted(releases, key=sort_key)
# latest release = last in list
latest = releases[-1]
return latest["name"], latest["tag_name"], latest.get("html_url", None)
def _get_latest_release(
user, repo, compare_type, include_prerelease=False, commitish=None, force_base=True
):
from ..exceptions import NetworkError
nothing = None, None, None
try:
r = requests.get(RELEASE_URL.format(user=user, repo=repo), timeout=(3.05, 30))
except requests.ConnectionError as exc:
raise NetworkError(cause=exc)
from . import log_github_ratelimit
log_github_ratelimit(logger, r)
if not r.status_code == requests.codes.ok:
return nothing
releases = r.json()
# sanitize
required_fields = {
"name",
"tag_name",
"html_url",
"draft",
"prerelease",
"published_at",
"target_commitish",
}
releases = list(
filter(lambda rel: set(rel.keys()) & required_fields == required_fields, releases)
)
comparable_factory = _get_comparable_factory(compare_type, force_base=force_base)
sort_key = lambda release: comparable_factory(
_get_sanitized_version(release["tag_name"])
)
return _filter_out_latest(
releases,
sort_key=sort_key,
include_prerelease=include_prerelease,
commitish=commitish,
)
def _get_sanitized_version(version_string):
"""
Removes "-..." prefix from version strings.
"""
Removes "-..." prefix from version strings.
Tests:
>>> _get_sanitized_version(None)
>>> _get_sanitized_version("1.2.15")
'1.2.15'
>>> _get_sanitized_version("1.2.15-dev12")
'1.2.15'
"""
Tests:
>>> _get_sanitized_version(None)
>>> _get_sanitized_version("1.2.15")
'1.2.15'
>>> _get_sanitized_version("1.2.15-dev12")
'1.2.15'
"""
if version_string is not None and "-" in version_string:
version_string = version_string[:version_string.find("-")]
return version_string
if version_string is not None and "-" in version_string:
version_string = version_string[: version_string.find("-")]
return version_string
def _get_base_from_version_tuple(version_tuple):
"""
Reduces version tuple to base version.
"""
Reduces version tuple to base version.
Tests:
Tests:
>>> _get_base_from_version_tuple(("1", "2", "15"))
('1', '2', '15')
>>> _get_base_from_version_tuple(("1", "2", "15", "*", "dev12"))
('1', '2', '15')
"""
>>> _get_base_from_version_tuple(("1", "2", "15"))
('1', '2', '15')
>>> _get_base_from_version_tuple(("1", "2", "15", "*", "dev12"))
('1', '2', '15')
"""
base_version = []
for part in version_tuple:
if part.startswith("*"):
break
base_version.append(part)
return tuple(base_version)
base_version = []
for part in version_tuple:
if part.startswith("*"):
break
base_version.append(part)
return tuple(base_version)
def _get_comparable_version_semantic(version_string, force_base=True):
import semantic_version
import semantic_version
version = semantic_version.Version.coerce(version_string, partial=False)
version = semantic_version.Version.coerce(version_string, partial=False)
if force_base:
version_string = "{}.{}.{}".format(version.major, version.minor, version.patch)
version = semantic_version.Version.coerce(version_string, partial=False)
if force_base:
version_string = "{}.{}.{}".format(version.major, version.minor, version.patch)
version = semantic_version.Version.coerce(version_string, partial=False)
return version
return version
def _get_sanitized_compare_type(compare_type, custom=None):
if not compare_type in ("python", "python_unequal",
"semantic", "semantic_unequal",
"unequal", "custom") or compare_type == "custom" and custom is None:
compare_type = "python"
return compare_type
if (
not compare_type
in (
"python",
"python_unequal",
"semantic",
"semantic_unequal",
"unequal",
"custom",
)
or compare_type == "custom"
and custom is None
):
compare_type = "python"
return compare_type
def _get_comparable_factory(compare_type, force_base=True):
if compare_type in ("python", "python_unequal"):
return lambda version: get_comparable_version(version, base=force_base)
elif compare_type in ("semantic", "semantic_unequal"):
return lambda version: _get_comparable_version_semantic(version, force_base=force_base)
else:
return lambda version: version
if compare_type in ("python", "python_unequal"):
return lambda version: get_comparable_version(version, base=force_base)
elif compare_type in ("semantic", "semantic_unequal"):
return lambda version: _get_comparable_version_semantic(
version, force_base=force_base
)
else:
return lambda version: version
def _get_comparator(compare_type, custom=None):
if compare_type in ("python", "semantic"):
return lambda a, b: a >= b
elif compare_type == "custom":
return custom
else:
return lambda a, b: a == b
if compare_type in ("python", "semantic"):
return lambda a, b: a >= b
elif compare_type == "custom":
return custom
else:
return lambda a, b: a == b
def _is_current(release_information, compare_type, custom=None, force_base=True):
"""
Checks if the provided release information indicates the version being the most current one.
"""
Checks if the provided release information indicates the version being the most current one.
Tests:
Tests:
>>> _is_current(dict(remote=dict(value=None)), "python")
True
>>> _is_current(dict(local=dict(value="1.2.15"), remote=dict(value="1.2.16")), "python")
False
>>> _is_current(dict(local=dict(value="1.2.16dev1"), remote=dict(value="1.2.16dev2")), "python")
True
>>> _is_current(dict(local=dict(value="1.2.16dev1"), remote=dict(value="1.2.16dev2")), "python", force_base=False)
False
>>> _is_current(dict(local=dict(value="1.2.16dev3"), remote=dict(value="1.2.16dev2")), "python", force_base=False)
True
>>> _is_current(dict(local=dict(value="1.2.16dev3"), remote=dict(value="1.2.16dev2")), "python_unequal", force_base=False)
False
>>> _is_current(dict(local=dict(value="1.3.0.post1+g1014712"), remote=dict(value="1.3.0")), "python")
True
>>> _is_current(dict(remote=dict(value=None)), "python")
True
>>> _is_current(dict(local=dict(value="1.2.15"), remote=dict(value="1.2.16")), "python")
False
>>> _is_current(dict(local=dict(value="1.2.16dev1"), remote=dict(value="1.2.16dev2")), "python")
True
>>> _is_current(dict(local=dict(value="1.2.16dev1"), remote=dict(value="1.2.16dev2")), "python", force_base=False)
False
>>> _is_current(dict(local=dict(value="1.2.16dev3"), remote=dict(value="1.2.16dev2")), "python", force_base=False)
True
>>> _is_current(dict(local=dict(value="1.2.16dev3"), remote=dict(value="1.2.16dev2")), "python_unequal", force_base=False)
False
>>> _is_current(dict(local=dict(value="1.3.0.post1+g1014712"), remote=dict(value="1.3.0")), "python")
True
"""
"""
if release_information["remote"]["value"] is None:
return True
if release_information["remote"]["value"] is None:
return True
compare_type = _get_sanitized_compare_type(compare_type, custom=custom)
comparable_factory = _get_comparable_factory(compare_type, force_base=force_base)
comparator = _get_comparator(compare_type, custom=custom)
compare_type = _get_sanitized_compare_type(compare_type, custom=custom)
comparable_factory = _get_comparable_factory(compare_type, force_base=force_base)
comparator = _get_comparator(compare_type, custom=custom)
sanitized_local = _get_sanitized_version(release_information["local"]["value"])
sanitized_remote = _get_sanitized_version(release_information["remote"]["value"])
sanitized_local = _get_sanitized_version(release_information["local"]["value"])
sanitized_remote = _get_sanitized_version(release_information["remote"]["value"])
try:
return comparator(comparable_factory(sanitized_local),
comparable_factory(sanitized_remote))
except Exception:
logger.exception("Could not check if version is current due to an error, assuming it is")
return True
try:
return comparator(
comparable_factory(sanitized_local), comparable_factory(sanitized_remote)
)
except Exception:
logger.exception(
"Could not check if version is current due to an error, assuming it is"
)
return True
def get_latest(target, check, custom_compare=None, online=True):
from ..exceptions import ConfigurationInvalid
from ..exceptions import ConfigurationInvalid
user = check.get("user", None)
repo = check.get("repo", None)
current = check.get("current", None)
if user is None or repo is None or current is None:
raise ConfigurationInvalid("Update configuration for {} of type github_release needs all of user, repo and current set and not None".format(target))
user = check.get("user", None)
repo = check.get("repo", None)
current = check.get("current", None)
if user is None or repo is None or current is None:
raise ConfigurationInvalid(
"Update configuration for {} of type github_release needs all of user, repo and current set and not None".format(
target
)
)
information ={"local": {"name": current, "value": current},
"remote": {"name": "?", "value": "?", "release_notes": None},
"needs_online": not check.get("offline", False)}
if not online and information["needs_online"]:
return information, True
information = {
"local": {"name": current, "value": current},
"remote": {"name": "?", "value": "?", "release_notes": None},
"needs_online": not check.get("offline", False),
}
if not online and information["needs_online"]:
return information, True
include_prerelease = check.get("prerelease", False)
prerelease_channel = check.get("prerelease_channel", None)
include_prerelease = check.get("prerelease", False)
prerelease_channel = check.get("prerelease_channel", None)
# determine valid "commitish" values in case we track prereleases
commitish = None
if include_prerelease and prerelease_channel:
prerelease_branches = check.get("prerelease_branches", None)
if prerelease_branches:
# fetch valid commitish list from configured prerelease_branches for selected channel
commitishes = dict((x["branch"], x.get("commitish", [x["branch"]])) for x in prerelease_branches)
commitish = commitishes.get(prerelease_channel, [prerelease_channel])
# determine valid "commitish" values in case we track prereleases
commitish = None
if include_prerelease and prerelease_channel:
prerelease_branches = check.get("prerelease_branches", None)
if prerelease_branches:
# fetch valid commitish list from configured prerelease_branches for selected channel
commitishes = dict(
(x["branch"], x.get("commitish", [x["branch"]]))
for x in prerelease_branches
)
commitish = commitishes.get(prerelease_channel, [prerelease_channel])
force_base = check.get("force_base", False)
compare_type = _get_sanitized_compare_type(check.get("release_compare", "python"),
custom=custom_compare)
force_base = check.get("force_base", False)
compare_type = _get_sanitized_compare_type(
check.get("release_compare", "python"), custom=custom_compare
)
remote_name, remote_tag, release_notes = _get_latest_release(check["user"],
check["repo"],
compare_type,
include_prerelease=include_prerelease,
commitish=commitish,
force_base=force_base)
remote_name, remote_tag, release_notes = _get_latest_release(
check["user"],
check["repo"],
compare_type,
include_prerelease=include_prerelease,
commitish=commitish,
force_base=force_base,
)
if not remote_name:
if remote_tag:
remote_name = remote_tag
else:
remote_name = "-"
if not remote_name:
if remote_tag:
remote_name = remote_tag
else:
remote_name = "-"
information["remote"] = {"name": remote_name, "value": remote_tag, "release_notes": release_notes}
information["remote"] = {
"name": remote_name,
"value": remote_tag,
"release_notes": release_notes,
}
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_tag))
logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_tag))
return information, _is_current(information,
compare_type,
custom=custom_compare,
force_base=force_base)
return information, _is_current(
information, compare_type, custom=custom_compare, force_base=force_base
)
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License"
import requests
@@ -11,31 +11,46 @@ from ..exceptions import ConfigurationInvalid, NetworkError, CannotCheckOffline
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.etag")
def get_latest(target, check, online=True):
if not online:
raise CannotCheckOffline()
if not online:
raise CannotCheckOffline()
url = check.get("header_url", check.get("url"))
header = check.get("header_name")
url = check.get("header_url", check.get("url"))
header = check.get("header_name")
if url is None or header is None:
raise ConfigurationInvalid("HTTP header version check needs header_url or url and header_name set")
if url is None or header is None:
raise ConfigurationInvalid(
"HTTP header version check needs header_url or url and header_name set"
)
current = check.get("current")
method = check.get("header_method", "head")
prefix = check.get("header_prefix", header)
if prefix:
prefix = "{} ".format(prefix)
current = check.get("current")
method = check.get("header_method", "head")
prefix = check.get("header_prefix", header)
if prefix:
prefix = "{} ".format(prefix)
try:
with requests.request(method, url) as r:
latest = r.headers.get(header)
except Exception as exc:
raise NetworkError(cause=exc)
try:
with requests.request(method, url) as r:
latest = r.headers.get(header)
except Exception as exc:
raise NetworkError(cause=exc)
information = {"local": {"name": "{}{}".format(prefix, current if current else "-"), "value": current},
"remote": {"name": "{}{}".format(prefix, latest if latest else "-"), "value": latest}}
information = {
"local": {
"name": "{}{}".format(prefix, current if current else "-"),
"value": current,
},
"remote": {
"name": "{}{}".format(prefix, latest if latest else "-"),
"value": latest,
},
}
logger.debug("Target: {}, local: {}, remote: {}".format(target, information["local"]["name"], information["remote"]["name"]))
logger.debug(
"Target: {}, local: {}, remote: {}".format(
target, information["local"]["name"], information["remote"]["name"]
)
)
return information, current is None or current == latest or latest is None
return information, current is None or current == latest or latest is None
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2020 The OctoPrint Project - Released under terms of the AGPLv3 License"
import requests
@@ -11,27 +11,34 @@ from ..exceptions import ConfigurationInvalid, NetworkError, CannotCheckOffline
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.jsondata")
def get_latest(target, check, online=True):
if not online:
raise CannotCheckOffline()
if not online:
raise CannotCheckOffline()
url = check.get("jsondata")
current = check.get("current")
url = check.get("jsondata")
current = check.get("current")
if url is None:
raise ConfigurationInvalid("jsondata version check needs jsondata set")
if url is None:
raise ConfigurationInvalid("jsondata version check needs jsondata set")
try:
with requests.get(url) as r:
data = r.json()
except Exception as exc:
raise NetworkError(cause=exc)
try:
with requests.get(url) as r:
data = r.json()
except Exception as exc:
raise NetworkError(cause=exc)
latest = data.get("version")
latest = data.get("version")
information = {"local": {"name": current if current else "-", "value": current},
"remote": {"name": latest if latest else "-", "value": latest}}
information = {
"local": {"name": current if current else "-", "value": current},
"remote": {"name": latest if latest else "-", "value": latest},
}
logger.debug("Target: {}, local: {}, remote: {}".format(target, information["local"]["name"], information["remote"]["name"]))
logger.debug(
"Target: {}, local: {}, remote: {}".format(
target, information["local"]["name"], information["remote"]["name"]
)
)
return information, current is None or current == latest or latest is None
return information, current is None or current == latest or latest is None
@@ -1,14 +1,17 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
def get_latest(target, check, online=True):
local_version = check.get("local_version", "1.0.0")
remote_version = check.get("remote_version", "1.0.1")
local_version = check.get("local_version", "1.0.0")
remote_version = check.get("remote_version", "1.0.1")
information = {"local": {"name": local_version, "value": local_version},
"remote": {"name": remote_version, "value": remote_version}}
information = {
"local": {"name": local_version, "value": local_version},
"remote": {"name": remote_version, "value": remote_version},
}
return information, False
return information, False
@@ -1,7 +1,7 @@
# coding=utf-8
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2019 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
@@ -9,100 +9,122 @@ import pkg_resources
import requests
from octoprint.util import to_native_str
from octoprint.util.version import is_python_compatible, get_comparable_version, is_prerelease
from octoprint.util.version import (
is_python_compatible,
get_comparable_version,
is_prerelease,
)
INFO_URL = "https://pypi.org/pypi/{package}/json"
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.pypi_release")
def _filter_out_latest(releases, include_prerelease=False, python_version=None):
"""
Filters out the newest of all matching releases.
"""
Filters out the newest of all matching releases.
Tests:
Tests:
>>> requires_py2 = ">=2.7.9,<3"
>>> requires_py23 = ">=2.7.9, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, <4"
>>> requires_py3 = ">=3.6, <4"
>>> releases = {"1.3.12": [dict(requires_python=requires_py2, upload_time_iso_8601="2019-10-22T10:06:03.190293Z")], "1.4.0rc1": [dict(requires_python=requires_py23, upload_time_iso_8601="2019-11-22T10:06:03.190293Z")], "2.0.0rc1": [dict(requires_python=requires_py3, upload_time_iso_8601="2020-10-22T10:06:03.190293Z")]}
>>> to_native_str(_filter_out_latest(releases, python_version="2.7.9"))
'1.3.12'
>>> to_native_str(_filter_out_latest(releases, include_prerelease=True, python_version="2.7.9"))
'1.4.0rc1'
>>> to_native_str(_filter_out_latest(releases, include_prerelease=True, python_version="3.6.0"))
'2.0.0rc1'
>>> to_native_str(_filter_out_latest(releases, python_version="3.6.0"))
"""
releases = [{"version": k, "data": v[0]} for k, v in releases.items()]
>>> requires_py2 = ">=2.7.9,<3"
>>> requires_py23 = ">=2.7.9, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*, <4"
>>> requires_py3 = ">=3.6, <4"
>>> releases = {"1.3.12": [dict(requires_python=requires_py2, upload_time_iso_8601="2019-10-22T10:06:03.190293Z")], "1.4.0rc1": [dict(requires_python=requires_py23, upload_time_iso_8601="2019-11-22T10:06:03.190293Z")], "2.0.0rc1": [dict(requires_python=requires_py3, upload_time_iso_8601="2020-10-22T10:06:03.190293Z")]}
>>> to_native_str(_filter_out_latest(releases, python_version="2.7.9"))
'1.3.12'
>>> to_native_str(_filter_out_latest(releases, include_prerelease=True, python_version="2.7.9"))
'1.4.0rc1'
>>> to_native_str(_filter_out_latest(releases, include_prerelease=True, python_version="3.6.0"))
'2.0.0rc1'
>>> to_native_str(_filter_out_latest(releases, python_version="3.6.0"))
"""
releases = [{"version": k, "data": v[0]} for k, v in releases.items()]
# filter out prereleases and versions incompatible to our python
filter_function = lambda release: not is_prerelease(release["version"]) and is_python_compatible(release["data"].get("requires_python", ""), python_version=python_version)
if include_prerelease:
filter_function = lambda release: is_python_compatible(release["data"].get("requires_python", ""), python_version=python_version)
# filter out prereleases and versions incompatible to our python
filter_function = lambda release: not is_prerelease(
release["version"]
) and is_python_compatible(
release["data"].get("requires_python", ""), python_version=python_version
)
if include_prerelease:
filter_function = lambda release: is_python_compatible(
release["data"].get("requires_python", ""), python_version=python_version
)
releases = list(filter(filter_function, releases))
if not releases:
return None
releases = list(filter(filter_function, releases))
if not releases:
return None
# sort by upload date
releases = sorted(releases, key=lambda release: release["data"].get("upload_time_iso_8601", ""))
# sort by upload date
releases = sorted(
releases, key=lambda release: release["data"].get("upload_time_iso_8601", "")
)
# latest release = last in list
latest = releases[-1]
# latest release = last in list
latest = releases[-1]
return latest["version"]
return latest["version"]
def _get_latest_release(package, include_prerelease):
from ..exceptions import NetworkError
from ..exceptions import NetworkError
try:
r = requests.get(INFO_URL.format(package=package), timeout=(3.05, 30))
except requests.ConnectionError as exc:
raise NetworkError(cause=exc)
try:
r = requests.get(INFO_URL.format(package=package), timeout=(3.05, 30))
except requests.ConnectionError as exc:
raise NetworkError(cause=exc)
if not r.status_code == requests.codes.ok:
return None
if not r.status_code == requests.codes.ok:
return None
data = r.json()
if not "info" in data or not "version" in data["info"]:
return None
data = r.json()
if not "info" in data or not "version" in data["info"]:
return None
requires_python = data["info"].get("requires_python")
if requires_python and not is_python_compatible(requires_python):
return None
requires_python = data["info"].get("requires_python")
if requires_python and not is_python_compatible(requires_python):
return None
return _filter_out_latest(data["releases"], include_prerelease=include_prerelease)
return _filter_out_latest(data["releases"],
include_prerelease=include_prerelease)
def _is_current(release_information):
if release_information["remote"]["value"] is None:
return True
if release_information["remote"]["value"] is None:
return True
local_version = get_comparable_version(release_information["local"]["value"])
remote_version = get_comparable_version(release_information["remote"]["value"])
local_version = get_comparable_version(release_information["local"]["value"])
remote_version = get_comparable_version(release_information["remote"]["value"])
return remote_version <= local_version
return remote_version <= local_version
def get_latest(target, check, online=True):
from ..exceptions import CannotUpdateOffline
from ..exceptions import CannotUpdateOffline
if not online and not check.get("offline", False):
raise CannotUpdateOffline()
if not online and not check.get("offline", False):
raise CannotUpdateOffline()
package = check.get("package")
package = check.get("package")
distribution = pkg_resources.get_distribution(package)
if distribution:
local_version = distribution.version
else:
local_version = None
distribution = pkg_resources.get_distribution(package)
if distribution:
local_version = distribution.version
else:
local_version = None
remote_version = _get_latest_release(package,
include_prerelease=check.get("prerelease", False))
remote_version = _get_latest_release(
package, include_prerelease=check.get("prerelease", False)
)
information = {"local": {"name": local_version, "value": local_version},
"remote": {"name": remote_version, "value": remote_version}}
information = {
"local": {"name": local_version, "value": local_version},
"remote": {"name": remote_version, "value": remote_version},
}
logger.debug("Target: {}, local: {}, remote: {}".format(target, information["local"]["name"], information["remote"]["name"]))
logger.debug(
"Target: {}, local: {}, remote: {}".format(
target, information["local"]["name"], information["remote"]["name"]
)
)
return information, _is_current(information)
return information, _is_current(information)
@@ -2,27 +2,39 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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"
from ..exceptions import ConfigurationInvalid, CannotCheckOffline
def get_latest(target, check, full_data=False, online=True):
python_checker = check.get("python_checker")
if python_checker is None or not hasattr(python_checker, "get_latest"):
raise ConfigurationInvalid("Update configuration for {} of type python_checker needs python_checker defined and have an attribute \"get_latest\"".format(target))
python_checker = check.get("python_checker")
if python_checker is None or not hasattr(python_checker, "get_latest"):
raise ConfigurationInvalid(
'Update configuration for {} of type python_checker needs python_checker defined and have an attribute "get_latest"'.format(
target
)
)
if not online and not check.get("offline", False):
raise CannotCheckOffline("{} isn't marked as 'offline' capable, but we are apparently offline right now".format(target))
if not online and not check.get("offline", False):
raise CannotCheckOffline(
"{} isn't marked as 'offline' capable, but we are apparently offline right now".format(
target
)
)
try:
return check["python_checker"].get_latest(target, check, full_data=full_data, online=online)
except Exception:
import inspect
args, _, _, _ = inspect.getargspec(check["python_checker"].get_latest)
if "online" not in args:
# old python_checker footprint, simply leave out the online parameter
return check["python_checker"].get_latest(target, check, full_data=full_data)
try:
return check["python_checker"].get_latest(
target, check, full_data=full_data, online=online
)
except Exception:
import inspect
# some other error, raise again
raise
args, _, _, _ = inspect.getargspec(check["python_checker"].get_latest)
if "online" not in args:
# old python_checker footprint, simply leave out the online parameter
return check["python_checker"].get_latest(target, check, full_data=full_data)
# some other error, raise again
raise
+509 -422
View File
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2018 The OctoPrint Project - Released under terms of the AGPLv3 License"
import octoprint.plugin
@@ -13,10 +13,10 @@ import hashlib
import logging
try:
# noinspection PyCompatibility
from urllib.parse import urlencode
# noinspection PyCompatibility
from urllib.parse import urlencode
except ImportError:
from urllib import urlencode
from urllib import urlencode
# noinspection PyCompatibility
import concurrent.futures
@@ -28,427 +28,514 @@ from octoprint.events import Events
TRACKING_URL = "https://tracking.octoprint.org/track/{id}/{event}/"
# noinspection PyMissingConstructor
class TrackingPlugin(octoprint.plugin.SettingsPlugin,
octoprint.plugin.EnvironmentDetectionPlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.ShutdownPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.WizardPlugin,
octoprint.plugin.EventHandlerPlugin):
def __init__(self):
self._environment = None
self._throttle_state = None
self._helpers_get_throttle_state = None
self._printer_connection_parameters = None
self._url = None
self._ping_worker = None
self._pong_worker = None
self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
class TrackingPlugin(
octoprint.plugin.SettingsPlugin,
octoprint.plugin.EnvironmentDetectionPlugin,
octoprint.plugin.StartupPlugin,
octoprint.plugin.ShutdownPlugin,
octoprint.plugin.TemplatePlugin,
octoprint.plugin.AssetPlugin,
octoprint.plugin.WizardPlugin,
octoprint.plugin.EventHandlerPlugin,
):
def __init__(self):
self._environment = None
self._throttle_state = None
self._helpers_get_throttle_state = None
self._printer_connection_parameters = None
self._url = None
self._ping_worker = None
self._pong_worker = None
self._executor = concurrent.futures.ThreadPoolExecutor(max_workers=1)
self._record_next_firmware_info = False
self._startup_time = monotonic_time()
def initialize(self):
self._init_id()
##~~ SettingsPlugin
def get_settings_defaults(self):
return {
"enabled": None,
"unique_id": None,
"server": TRACKING_URL,
"ping": 15 * 60,
"pong": 24 * 60 * 60,
"events": {
"pong": True,
"startup": True,
"printjob": True,
"commerror": True,
"plugin": True,
"update": True,
"printer": True,
"printer_safety_check": True,
"throttled": True,
"slicing": True,
},
}
def get_settings_restricted_paths(self):
return {
"admin": [["enabled"], ["unique_id"], ["events"]],
"never": [["server"], ["ping"]],
}
def on_settings_save(self, data):
enabled = self._settings.get(["enabled"])
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
if enabled is None and self._settings.get(["enabled"]):
# tracking was just enabled, let's start up tracking
self._start_tracking()
##~~ EnvironmentDetectionPlugin
def on_environment_detected(self, environment, *args, **kwargs):
self._environment = environment
##~~ StartupPlugin
def on_after_startup(self):
self._start_tracking()
##~~ ShutdownPlugin
def on_shutdown(self):
if not self._settings.get_boolean(["enabled"]):
return
self._track_shutdown()
self._executor.shutdown(wait=True)
##~~ EventHandlerPlugin
# noinspection PyUnresolvedReferences
def on_event(self, event, payload):
if not self._settings.get_boolean(["enabled"]):
return
if event in (
Events.PRINT_STARTED,
Events.PRINT_DONE,
Events.PRINT_FAILED,
Events.PRINT_CANCELLED,
):
self._track_printjob_event(event, payload)
elif event in (Events.ERROR,):
self._track_commerror_event(event, payload)
elif event in (Events.CONNECTED,):
self._printer_connection_parameters = {
"port": payload["port"],
"baudrate": payload["baudrate"],
}
self._record_next_firmware_info = True
elif event in (Events.FIRMWARE_DATA,) and self._record_next_firmware_info:
self._record_next_firmware_info = False
self._track_printer_event(event, payload)
elif event in (Events.SLICING_STARTED,):
self._track_slicing_event(event, payload)
elif hasattr(Events, "PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN") and event in (
Events.PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN,
Events.PLUGIN_PLUGINMANAGER_UNINSTALL_PLUGIN,
Events.PLUGIN_PLUGINMANAGER_ENABLE_PLUGIN,
Events.PLUGIN_PLUGINMANAGER_DISABLE_PLUGIN,
):
self._track_plugin_event(event, payload)
elif hasattr(Events, "PLUGIN_SOFTWAREUPDATE_UPDATE_SUCCEEDED") and event in (
Events.PLUGIN_SOFTWAREUPDATE_UPDATE_SUCCEEDED,
Events.PLUGIN_SOFTWAREUPDATE_UPDATE_FAILED,
):
self._track_update_event(event, payload)
elif hasattr(Events, "PLUGIN_PI_SUPPORT_THROTTLE_STATE") and event in (
Events.PLUGIN_PI_SUPPORT_THROTTLE_STATE,
):
self._throttle_state = payload
self._track_throttle_event(event, payload)
elif hasattr(Events, "PLUGIN_PRINTER_SAFETY_CHECK_WARNING") and event in (
Events.PLUGIN_PRINTER_SAFETY_CHECK_WARNING,
):
self._track_printer_safety_event(event, payload)
##~~ TemplatePlugin
def get_template_configs(self):
return [
{
"type": "settings",
"name": gettext("Anonymous Usage Tracking"),
"template": "tracking_settings.jinja2",
"custom_bindings": False,
},
{
"type": "wizard",
"name": gettext("Anonymous Usage Tracking"),
"template": "tracking_wizard.jinja2",
"custom_bindings": True,
"mandatory": True,
},
]
##~~ AssetPlugin
def get_assets(self):
return {"js": ["js/usage.js"]}
##~~ WizardPlugin
def is_wizard_required(self):
return self._settings.get(["enabled"]) is None
##~~ helpers
def _init_id(self):
if not self._settings.get(["unique_id"]):
import uuid
self._settings.set(["unique_id"], str(uuid.uuid4()))
self._settings.save()
def _start_tracking(self):
if not self._settings.get_boolean(["enabled"]):
return
if self._ping_worker is None:
ping_interval = self._settings.get_int(["ping"])
if ping_interval:
self._ping_worker = RepeatedTimer(
ping_interval, self._track_ping, run_first=True
)
self._ping_worker.start()
if self._pong_worker is None:
pong_interval = self._settings.get(["pong"])
if pong_interval:
self._pong_worker = RepeatedTimer(
pong_interval, self._track_pong, run_first=True
)
self._pong_worker.start()
if self._helpers_get_throttle_state is None:
# cautiously look for the get_throttled helper from pi_support
pi_helper = self._plugin_manager.get_helpers("pi_support", "get_throttled")
if pi_helper and "get_throttled" in pi_helper:
self._helpers_get_throttle_state = pi_helper["get_throttled"]
# now that we have everything set up, phone home.
self._track_startup()
def _track_ping(self):
if not self._settings.get_boolean(["enabled"]):
return
uptime = int(monotonic_time() - self._startup_time)
self._track("ping", octoprint_uptime=uptime)
def _track_pong(self):
if not self._settings.get_boolean(["events", "pong"]):
return
payload = self._get_environment_payload()
plugins = self._plugin_manager.enabled_plugins
plugins_thirdparty = [plugin for plugin in plugins.values() if not plugin.bundled]
payload["plugins"] = ",".join(
map(
lambda x: "{}:{}".format(
x.key.lower(), x.version.lower() if x.version else "?"
),
plugins_thirdparty,
)
)
self._track("pong", body=True, **payload)
def _track_startup(self):
if not self._settings.get_boolean(["events", "startup"]):
return
payload = self._get_environment_payload()
self._track("startup", **payload)
def _track_shutdown(self):
if not self._settings.get_boolean(["enabled"]):
return
if not self._settings.get_boolean(["events", "startup"]):
return
self._track("shutdown")
def _track_plugin_event(self, event, payload):
if not self._settings.get_boolean(["events", "plugin"]):
return
if event.endswith("_install_plugin"):
self._track(
"install_plugin",
plugin=payload.get("id"),
plugin_version=payload.get("version"),
)
elif event.endswith("_uninstall_plugin"):
self._track(
"uninstall_plugin",
plugin=payload.get("id"),
plugin_version=payload.get("version"),
)
elif event.endswith("_enable_plugin"):
self._track(
"enable_plugin",
plugin=payload.get("id"),
plugin_version=payload.get("version"),
)
elif event.endswith("_disable_plugin"):
self._track(
"disable_plugin",
plugin=payload.get("id"),
plugin_version=payload.get("version"),
)
def _track_update_event(self, event, payload):
if not self._settings.get_boolean(["events", "update"]):
return
if event.endswith("_update_succeeded"):
self._track(
"update_successful",
target=payload.get("target"),
from_version=payload.get("from_version"),
to_version=payload.get("to_version"),
)
elif event.endswith("_update_failed"):
self._track(
"update_failed",
target=payload.get("target"),
from_version=payload.get("from_version"),
to_version=payload.get("to_version"),
)
def _track_throttle_event(self, event, payload):
if not self._settings.get_boolean(["events", "throttled"]):
return
args = {
"throttled_now": payload["current_issue"],
"throttled_past": payload["past_issue"],
"throttled_mask": payload["raw_value"],
"throttled_voltage_now": payload["current_undervoltage"],
"throttled_voltage_past": payload["past_undervoltage"],
"throttled_overheat_now": payload["current_overheat"],
"throttled_overheat_past": payload["past_overheat"],
}
if payload["current_issue"]:
track_event = "system_throttled"
else:
track_event = "system_unthrottled"
if track_event is not None:
self._track(track_event, **args)
def _track_commerror_event(self, event, payload):
if not self._settings.get_boolean(["events", "commerror"]):
return
if not "reason" in payload or not "error" in payload:
return
track_event = "commerror_{}".format(payload["reason"])
args = {"commerror_text": payload["error"]}
if callable(self._helpers_get_throttle_state):
try:
throttle_state = self._helpers_get_throttle_state(run_now=True)
if throttle_state and (
throttle_state.get("current_issue", False)
or throttle_state.get("past_issue", False)
):
args["throttled_now"] = throttle_state["current_issue"]
args["throttled_past"] = throttle_state["past_issue"]
args["throttled_mask"] = throttle_state["raw_value"]
except Exception:
# ignored
pass
self._track(track_event, **args)
def _track_printjob_event(self, event, payload):
if not self._settings.get_boolean(["events", "printjob"]):
return
unique_id = self._settings.get(["unique_id"])
if not unique_id:
return
sha = hashlib.sha1()
sha.update(payload.get("path").encode("utf-8"))
sha.update(unique_id.encode("utf-8"))
track_event = None
args = {"origin": payload.get("origin"), "file": sha.hexdigest()}
if event == Events.PRINT_STARTED:
track_event = "print_started"
elif event == Events.PRINT_DONE:
try:
elapsed = int(payload.get("time", 0))
if elapsed:
args["elapsed"] = elapsed
except (ValueError, TypeError):
pass
track_event = "print_done"
elif event == Events.PRINT_FAILED:
try:
elapsed = int(payload.get("time", 0))
if elapsed:
args["elapsed"] = elapsed
except (ValueError, TypeError):
pass
args["reason"] = payload.get("reason", "unknown")
if "error" in payload and self._settings.get_boolean(["events", "commerror"]):
args["commerror_text"] = payload["error"]
track_event = "print_failed"
elif event == Events.PRINT_CANCELLED:
try:
elapsed = int(payload.get("time", 0))
if elapsed:
args["elapsed"] = elapsed
except (ValueError, TypeError):
pass
track_event = "print_cancelled"
if callable(self._helpers_get_throttle_state):
try:
throttle_state = self._helpers_get_throttle_state(run_now=True)
if throttle_state and (
throttle_state.get("current_issue", False)
or throttle_state.get("past_issue", False)
):
args["throttled_now"] = throttle_state["current_issue"]
args["throttled_past"] = throttle_state["past_issue"]
args["throttled_mask"] = throttle_state["raw_value"]
except Exception:
# ignored
pass
if track_event is not None:
self._track(track_event, **args)
def _track_printer_event(self, event, payload):
if not self._settings.get_boolean(["events", "printer"]):
return
if event in (Events.FIRMWARE_DATA,):
args = {"firmware_name": payload["name"]}
if self._printer_connection_parameters:
args["printer_port"] = self._printer_connection_parameters["port"]
args["printer_baudrate"] = self._printer_connection_parameters["baudrate"]
self._track("printer_connected", **args)
def _track_printer_safety_event(self, event, payload):
if not self._settings.get_boolean(["events", "printer_safety_check"]):
return
self._track(
"printer_safety_warning",
printer_safety_warning_type=payload.get("warning_type", "unknown"),
printer_safety_check_name=payload.get("check_name", "unknown"),
)
def _track_slicing_event(self, event, payload):
if not self._settings.get_boolean(["events", "slicing"]):
return
self._track("slicing_started", slicer=payload.get(b"slicer", "unknown"))
def _track(self, event, **kwargs):
if not self._settings.get_boolean(["enabled"]):
return
self._executor.submit(self._do_track, event, **kwargs)
def _do_track(self, event, body=False, **kwargs):
if not self._connectivity_checker.online:
return
if not self._settings.get_boolean(["enabled"]):
return
unique_id = self._settings.get(["unique_id"])
if not unique_id:
return
server = self._settings.get(["server"])
url = server.format(id=unique_id, event=event)
# Don't print the URL or UUID! That would expose the UUID in forums/tickets
# if pasted. It's okay for the user to know their uuid, but it shouldn't be shared.
headers = {"User-Agent": "OctoPrint/{}".format(get_octoprint_version_string())}
try:
params = urlencode(kwargs, doseq=True).replace("+", "%20")
if body:
requests.post(url, data=params, timeout=3.1, headers=headers)
else:
requests.get(url, params=params, timeout=3.1, headers=headers)
self._logger.info(
"Sent tracking event {}, payload: {!r}".format(event, kwargs)
)
except Exception:
if self._logger.isEnabledFor(logging.DEBUG):
self._logger.exception(
"Error while sending event to anonymous usage tracking"
)
else:
pass
def _get_environment_payload(self):
payload = {
"version": get_octoprint_version_string(),
"os": self._environment["os"]["id"],
"python": self._environment["python"]["version"],
"pip": self._environment["python"]["pip"],
"cores": self._environment["hardware"]["cores"],
"freq": self._environment["hardware"]["freq"],
"ram": self._environment["hardware"]["ram"],
}
if (
"plugins" in self._environment
and "pi_support" in self._environment["plugins"]
):
payload["pi_model"] = self._environment["plugins"]["pi_support"]["model"]
if "octopi_version" in self._environment["plugins"]["pi_support"]:
payload["octopi_version"] = self._environment["plugins"]["pi_support"][
"octopi_version"
]
return payload
self._record_next_firmware_info = False
self._startup_time = monotonic_time()
def initialize(self):
self._init_id()
##~~ SettingsPlugin
def get_settings_defaults(self):
return {"enabled": None,
"unique_id": None,
"server": TRACKING_URL,
"ping": 15*60,
"pong": 24*60*60,
"events": {"pong": True,
"startup": True,
"printjob": True,
"commerror": True,
"plugin": True,
"update": True,
"printer": True,
"printer_safety_check": True,
"throttled": True,
"slicing": True}}
def get_settings_restricted_paths(self):
return {"admin": [["enabled"], ["unique_id"], ["events"]],
"never": [["server"], ["ping"]]}
def on_settings_save(self, data):
enabled = self._settings.get(["enabled"])
octoprint.plugin.SettingsPlugin.on_settings_save(self, data)
if enabled is None and self._settings.get(["enabled"]):
# tracking was just enabled, let's start up tracking
self._start_tracking()
##~~ EnvironmentDetectionPlugin
def on_environment_detected(self, environment, *args, **kwargs):
self._environment = environment
##~~ StartupPlugin
def on_after_startup(self):
self._start_tracking()
##~~ ShutdownPlugin
def on_shutdown(self):
if not self._settings.get_boolean(["enabled"]):
return
self._track_shutdown()
self._executor.shutdown(wait=True)
##~~ EventHandlerPlugin
# noinspection PyUnresolvedReferences
def on_event(self, event, payload):
if not self._settings.get_boolean(["enabled"]):
return
if event in (Events.PRINT_STARTED, Events.PRINT_DONE, Events.PRINT_FAILED, Events.PRINT_CANCELLED):
self._track_printjob_event(event, payload)
elif event in (Events.ERROR,):
self._track_commerror_event(event, payload)
elif event in (Events.CONNECTED,):
self._printer_connection_parameters = {"port": payload["port"],
"baudrate": payload["baudrate"]}
self._record_next_firmware_info = True
elif event in (Events.FIRMWARE_DATA,) and self._record_next_firmware_info:
self._record_next_firmware_info = False
self._track_printer_event(event, payload)
elif event in (Events.SLICING_STARTED,):
self._track_slicing_event(event, payload)
elif hasattr(Events, "PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN") and \
event in (Events.PLUGIN_PLUGINMANAGER_INSTALL_PLUGIN, Events.PLUGIN_PLUGINMANAGER_UNINSTALL_PLUGIN,
Events.PLUGIN_PLUGINMANAGER_ENABLE_PLUGIN, Events.PLUGIN_PLUGINMANAGER_DISABLE_PLUGIN):
self._track_plugin_event(event, payload)
elif hasattr(Events, "PLUGIN_SOFTWAREUPDATE_UPDATE_SUCCEEDED") and \
event in (Events.PLUGIN_SOFTWAREUPDATE_UPDATE_SUCCEEDED, Events.PLUGIN_SOFTWAREUPDATE_UPDATE_FAILED):
self._track_update_event(event, payload)
elif hasattr(Events, "PLUGIN_PI_SUPPORT_THROTTLE_STATE") and event in (Events.PLUGIN_PI_SUPPORT_THROTTLE_STATE,):
self._throttle_state = payload
self._track_throttle_event(event, payload)
elif hasattr(Events, "PLUGIN_PRINTER_SAFETY_CHECK_WARNING") and event in (Events.PLUGIN_PRINTER_SAFETY_CHECK_WARNING,):
self._track_printer_safety_event(event, payload)
##~~ TemplatePlugin
def get_template_configs(self):
return [
{"type": "settings", "name": gettext("Anonymous Usage Tracking"), "template": "tracking_settings.jinja2", "custom_bindings": False},
{"type": "wizard", "name": gettext("Anonymous Usage Tracking"), "template": "tracking_wizard.jinja2", "custom_bindings": True, "mandatory": True}
]
##~~ AssetPlugin
def get_assets(self):
return {"js": ["js/usage.js"]}
##~~ WizardPlugin
def is_wizard_required(self):
return self._settings.get(["enabled"]) is None
##~~ helpers
def _init_id(self):
if not self._settings.get(["unique_id"]):
import uuid
self._settings.set(["unique_id"], str(uuid.uuid4()))
self._settings.save()
def _start_tracking(self):
if not self._settings.get_boolean(["enabled"]):
return
if self._ping_worker is None:
ping_interval = self._settings.get_int(["ping"])
if ping_interval:
self._ping_worker = RepeatedTimer(ping_interval, self._track_ping, run_first=True)
self._ping_worker.start()
if self._pong_worker is None:
pong_interval = self._settings.get(["pong"])
if pong_interval:
self._pong_worker = RepeatedTimer(pong_interval, self._track_pong, run_first=True)
self._pong_worker.start()
if self._helpers_get_throttle_state is None:
# cautiously look for the get_throttled helper from pi_support
pi_helper = self._plugin_manager.get_helpers("pi_support", "get_throttled")
if pi_helper and 'get_throttled' in pi_helper:
self._helpers_get_throttle_state = pi_helper['get_throttled']
# now that we have everything set up, phone home.
self._track_startup()
def _track_ping(self):
if not self._settings.get_boolean(["enabled"]):
return
uptime = int(monotonic_time() - self._startup_time)
self._track("ping", octoprint_uptime=uptime)
def _track_pong(self):
if not self._settings.get_boolean(["events", "pong"]):
return
payload = self._get_environment_payload()
plugins = self._plugin_manager.enabled_plugins
plugins_thirdparty = [plugin for plugin in plugins.values() if not plugin.bundled]
payload["plugins"] = ",".join(map(lambda x: "{}:{}".format(x.key.lower(),
x.version.lower() if x.version else "?"),
plugins_thirdparty))
self._track("pong", body=True, **payload)
def _track_startup(self):
if not self._settings.get_boolean(["events", "startup"]):
return
payload = self._get_environment_payload()
self._track("startup", **payload)
def _track_shutdown(self):
if not self._settings.get_boolean(["enabled"]):
return
if not self._settings.get_boolean(["events", "startup"]):
return
self._track("shutdown")
def _track_plugin_event(self, event, payload):
if not self._settings.get_boolean(["events", "plugin"]):
return
if event.endswith("_install_plugin"):
self._track("install_plugin", plugin=payload.get("id"), plugin_version=payload.get("version"))
elif event.endswith("_uninstall_plugin"):
self._track("uninstall_plugin", plugin=payload.get("id"), plugin_version=payload.get("version"))
elif event.endswith("_enable_plugin"):
self._track("enable_plugin", plugin=payload.get("id"), plugin_version=payload.get("version"))
elif event.endswith("_disable_plugin"):
self._track("disable_plugin", plugin=payload.get("id"), plugin_version=payload.get("version"))
def _track_update_event(self, event, payload):
if not self._settings.get_boolean(["events", "update"]):
return
if event.endswith("_update_succeeded"):
self._track("update_successful", target=payload.get("target"), from_version=payload.get("from_version"), to_version=payload.get("to_version"))
elif event.endswith("_update_failed"):
self._track("update_failed", target=payload.get("target"), from_version=payload.get("from_version"), to_version=payload.get("to_version"))
def _track_throttle_event(self, event, payload):
if not self._settings.get_boolean(["events", "throttled"]):
return
args = {"throttled_now": payload["current_issue"],
"throttled_past": payload["past_issue"],
"throttled_mask": payload["raw_value"],
"throttled_voltage_now": payload["current_undervoltage"],
"throttled_voltage_past": payload["past_undervoltage"],
"throttled_overheat_now": payload["current_overheat"],
"throttled_overheat_past": payload["past_overheat"]}
if payload["current_issue"]:
track_event = "system_throttled"
else:
track_event = "system_unthrottled"
if track_event is not None:
self._track(track_event, **args)
def _track_commerror_event(self, event, payload):
if not self._settings.get_boolean(["events", "commerror"]):
return
if not "reason" in payload or not "error" in payload:
return
track_event = "commerror_{}".format(payload["reason"])
args = {"commerror_text": payload["error"]}
if callable(self._helpers_get_throttle_state):
try:
throttle_state = self._helpers_get_throttle_state(run_now=True)
if throttle_state and (throttle_state.get("current_issue", False) or throttle_state.get("past_issue", False)):
args["throttled_now"] = throttle_state["current_issue"]
args["throttled_past"] = throttle_state["past_issue"]
args["throttled_mask"] = throttle_state["raw_value"]
except Exception:
# ignored
pass
self._track(track_event, **args)
def _track_printjob_event(self, event, payload):
if not self._settings.get_boolean(["events", "printjob"]):
return
unique_id = self._settings.get(["unique_id"])
if not unique_id:
return
sha = hashlib.sha1()
sha.update(payload.get("path").encode("utf-8"))
sha.update(unique_id.encode("utf-8"))
track_event = None
args = {"origin": payload.get("origin"), "file": sha.hexdigest()}
if event == Events.PRINT_STARTED:
track_event = "print_started"
elif event == Events.PRINT_DONE:
try:
elapsed = int(payload.get("time", 0))
if elapsed:
args["elapsed"] = elapsed
except (ValueError, TypeError):
pass
track_event = "print_done"
elif event == Events.PRINT_FAILED:
try:
elapsed = int(payload.get("time", 0))
if elapsed:
args["elapsed"] = elapsed
except (ValueError, TypeError):
pass
args["reason"] = payload.get("reason", "unknown")
if "error" in payload and self._settings.get_boolean(["events", "commerror"]):
args["commerror_text"] = payload["error"]
track_event = "print_failed"
elif event == Events.PRINT_CANCELLED:
try:
elapsed = int(payload.get("time", 0))
if elapsed:
args["elapsed"] = elapsed
except (ValueError, TypeError):
pass
track_event = "print_cancelled"
if callable(self._helpers_get_throttle_state):
try:
throttle_state = self._helpers_get_throttle_state(run_now=True)
if throttle_state and (throttle_state.get("current_issue", False) or throttle_state.get("past_issue", False)):
args["throttled_now"] = throttle_state["current_issue"]
args["throttled_past"] = throttle_state["past_issue"]
args["throttled_mask"] = throttle_state["raw_value"]
except Exception:
# ignored
pass
if track_event is not None:
self._track(track_event, **args)
def _track_printer_event(self, event, payload):
if not self._settings.get_boolean(["events", "printer"]):
return
if event in (Events.FIRMWARE_DATA,):
args = {"firmware_name": payload["name"]}
if self._printer_connection_parameters:
args["printer_port"] = self._printer_connection_parameters["port"]
args["printer_baudrate"] = self._printer_connection_parameters["baudrate"]
self._track("printer_connected", **args)
def _track_printer_safety_event(self, event, payload):
if not self._settings.get_boolean(["events", "printer_safety_check"]):
return
self._track("printer_safety_warning",
printer_safety_warning_type=payload.get("warning_type", "unknown"),
printer_safety_check_name=payload.get("check_name", "unknown"))
def _track_slicing_event(self, event, payload):
if not self._settings.get_boolean(["events", "slicing"]):
return
self._track("slicing_started",
slicer=payload.get(b"slicer", "unknown"))
def _track(self, event, **kwargs):
if not self._settings.get_boolean(["enabled"]):
return
self._executor.submit(self._do_track, event, **kwargs)
def _do_track(self, event, body=False, **kwargs):
if not self._connectivity_checker.online:
return
if not self._settings.get_boolean(["enabled"]):
return
unique_id = self._settings.get(["unique_id"])
if not unique_id:
return
server = self._settings.get(["server"])
url = server.format(id=unique_id, event=event)
# Don't print the URL or UUID! That would expose the UUID in forums/tickets
# if pasted. It's okay for the user to know their uuid, but it shouldn't be shared.
headers = {"User-Agent": "OctoPrint/{}".format(get_octoprint_version_string())}
try:
params = urlencode(kwargs, doseq=True).replace("+", "%20")
if body:
requests.post(url,
data=params,
timeout=3.1,
headers=headers)
else:
requests.get(url,
params=params,
timeout=3.1,
headers=headers)
self._logger.info("Sent tracking event {}, payload: {!r}".format(event, kwargs))
except Exception:
if self._logger.isEnabledFor(logging.DEBUG):
self._logger.exception("Error while sending event to anonymous usage tracking")
else:
pass
def _get_environment_payload(self):
payload = {"version": get_octoprint_version_string(),
"os": self._environment["os"]["id"],
"python": self._environment["python"]["version"],
"pip": self._environment["python"]["pip"],
"cores": self._environment["hardware"]["cores"],
"freq": self._environment["hardware"]["freq"],
"ram": self._environment["hardware"]["ram"]}
if "plugins" in self._environment and "pi_support" in self._environment["plugins"]:
payload["pi_model"] = self._environment["plugins"]["pi_support"]["model"]
if "octopi_version" in self._environment["plugins"]["pi_support"]:
payload["octopi_version"] = self._environment["plugins"]["pi_support"]["octopi_version"]
return payload
__plugin_name__ = "Anonymous Usage Tracking"
__plugin_description__ = "Anonymous version and usage tracking, see homepage for details on what gets tracked"
__plugin_description__ = (
"Anonymous version and usage tracking, see homepage for details on what gets tracked"
)
__plugin_url__ = "https://tracking.octoprint.org"
__plugin_author__ = "Gina Häußge"
__plugin_license__ = "AGPLv3"
+115 -107
View File
@@ -2,135 +2,143 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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 octoprint.plugin
class VirtualPrinterPlugin(octoprint.plugin.SettingsPlugin, octoprint.plugin.TemplatePlugin):
def get_template_configs(self):
return [
{"type": "settings", "custom_bindings": False}
]
class VirtualPrinterPlugin(
octoprint.plugin.SettingsPlugin, octoprint.plugin.TemplatePlugin
):
def get_template_configs(self):
return [{"type": "settings", "custom_bindings": False}]
def get_settings_defaults(self):
return {
"enabled": False,
"okAfterResend": False,
"forceChecksum": False,
"numExtruders": 1,
"pinnedExtruders": None,
"includeCurrentToolInTemps": True,
"includeFilenameInOpened": True,
"hasBed": True,
"hasChamber": False,
"repetierStyleTargetTemperature": False,
"okBeforeCommandOutput": False,
"smoothieTemperatureReporting": False,
"klipperTemperatureReporting": False,
"reprapfwM114": False,
"sdFiles": {
"size": True,
"longname": False
},
"throttle": 0.01,
"sendWait": True,
"waitInterval": 1.0,
"rxBuffer": 64,
"commandBuffer": 4,
"supportM112": True,
"echoOnM117": True,
"brokenM29": True,
"brokenResend": False,
"supportF": False,
"firmwareName": "Virtual Marlin 1.0",
"sharedNozzle": False,
"sendBusy": False,
"busyInterval": 2.0,
"simulateReset": True,
"resetLines": ['start', 'Marlin: Virtual Marlin!', '\x80', 'SD card ok'],
"preparedOks": [],
"okFormatString": "ok",
"m115FormatString": "FIRMWARE_NAME:{firmware_name} PROTOCOL_VERSION:1.0",
"m115ReportCapabilities": True,
"capabilities": {
"AUTOREPORT_TEMP": True,
"AUTOREPORT_SD_STATUS": True,
"EMERGENCY_PARSER": True
},
"m114FormatString": "X:{x} Y:{y} Z:{z} E:{e[current]} Count: A:{a} B:{b} C:{c}",
"m105TargetFormatString": "{heater}:{actual:.2f}/ {target:.2f}",
"m105NoTargetFormatString": "{heater}:{actual:.2f}",
"ambientTemperature": 21.3,
"errors": {
"checksum_mismatch": "Checksum mismatch",
"checksum_missing": "Missing checksum",
"lineno_mismatch": "expected line {} got {}",
"lineno_missing": "No Line Number with checksum, Last Line: {}",
"maxtemp": "MAXTEMP triggered!",
"mintemp": "MINTEMP triggered!",
"command_unknown": "Unknown command {}"
}
}
def get_settings_defaults(self):
return {
"enabled": False,
"okAfterResend": False,
"forceChecksum": False,
"numExtruders": 1,
"pinnedExtruders": None,
"includeCurrentToolInTemps": True,
"includeFilenameInOpened": True,
"hasBed": True,
"hasChamber": False,
"repetierStyleTargetTemperature": False,
"okBeforeCommandOutput": False,
"smoothieTemperatureReporting": False,
"klipperTemperatureReporting": False,
"reprapfwM114": False,
"sdFiles": {"size": True, "longname": False},
"throttle": 0.01,
"sendWait": True,
"waitInterval": 1.0,
"rxBuffer": 64,
"commandBuffer": 4,
"supportM112": True,
"echoOnM117": True,
"brokenM29": True,
"brokenResend": False,
"supportF": False,
"firmwareName": "Virtual Marlin 1.0",
"sharedNozzle": False,
"sendBusy": False,
"busyInterval": 2.0,
"simulateReset": True,
"resetLines": ["start", "Marlin: Virtual Marlin!", "\x80", "SD card ok"],
"preparedOks": [],
"okFormatString": "ok",
"m115FormatString": "FIRMWARE_NAME:{firmware_name} PROTOCOL_VERSION:1.0",
"m115ReportCapabilities": True,
"capabilities": {
"AUTOREPORT_TEMP": True,
"AUTOREPORT_SD_STATUS": True,
"EMERGENCY_PARSER": True,
},
"m114FormatString": "X:{x} Y:{y} Z:{z} E:{e[current]} Count: A:{a} B:{b} C:{c}",
"m105TargetFormatString": "{heater}:{actual:.2f}/ {target:.2f}",
"m105NoTargetFormatString": "{heater}:{actual:.2f}",
"ambientTemperature": 21.3,
"errors": {
"checksum_mismatch": "Checksum mismatch",
"checksum_missing": "Missing checksum",
"lineno_mismatch": "expected line {} got {}",
"lineno_missing": "No Line Number with checksum, Last Line: {}",
"maxtemp": "MAXTEMP triggered!",
"mintemp": "MINTEMP triggered!",
"command_unknown": "Unknown command {}",
},
}
def get_settings_version(self):
return 1
def get_settings_version(self):
return 1
def on_settings_migrate(self, target, current):
if current is None:
config = self._settings.global_get(["devel", "virtualPrinter"])
if config:
self._logger.info("Migrating settings from devel.virtualPrinter to plugins.virtual_printer...")
self._settings.global_set(["plugins", "virtual_printer"], config, force=True)
self._settings.global_remove(["devel", "virtualPrinter"])
def on_settings_migrate(self, target, current):
if current is None:
config = self._settings.global_get(["devel", "virtualPrinter"])
if config:
self._logger.info(
"Migrating settings from devel.virtualPrinter to plugins.virtual_printer..."
)
self._settings.global_set(
["plugins", "virtual_printer"], config, force=True
)
self._settings.global_remove(["devel", "virtualPrinter"])
def virtual_printer_factory(self, comm_instance, port, baudrate,
read_timeout):
if not port == "VIRTUAL":
return None
def virtual_printer_factory(self, comm_instance, port, baudrate, read_timeout):
if not port == "VIRTUAL":
return None
if not self._settings.get_boolean(["enabled"]):
return None
if not self._settings.get_boolean(["enabled"]):
return None
import logging.handlers
from octoprint.logging.handlers import CleaningTimedRotatingFileHandler
import logging.handlers
from octoprint.logging.handlers import CleaningTimedRotatingFileHandler
seriallog_handler = CleaningTimedRotatingFileHandler(self._settings.get_plugin_logfile_path(postfix="serial"),
when="D",
backupCount=3)
seriallog_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
seriallog_handler.setLevel(logging.DEBUG)
seriallog_handler = CleaningTimedRotatingFileHandler(
self._settings.get_plugin_logfile_path(postfix="serial"),
when="D",
backupCount=3,
)
seriallog_handler.setFormatter(logging.Formatter("%(asctime)s %(message)s"))
seriallog_handler.setLevel(logging.DEBUG)
from . import virtual
from . import virtual
serial_obj = virtual.VirtualPrinter(self._settings,
seriallog_handler=seriallog_handler,
read_timeout=float(read_timeout),
faked_baudrate=baudrate)
return serial_obj
serial_obj = virtual.VirtualPrinter(
self._settings,
seriallog_handler=seriallog_handler,
read_timeout=float(read_timeout),
faked_baudrate=baudrate,
)
return serial_obj
def get_additional_port_names(self, *args, **kwargs):
if self._settings.get_boolean(["enabled"]):
return ["VIRTUAL"]
else:
return []
def get_additional_port_names(self, *args, **kwargs):
if self._settings.get_boolean(["enabled"]):
return ["VIRTUAL"]
else:
return []
__plugin_name__ = "Virtual Printer"
__plugin_author__ = "Gina Häußge, based on work by Daid Braam"
__plugin_homepage__ = "https://docs.octoprint.org/en/master/development/virtual_printer.html"
__plugin_homepage__ = (
"https://docs.octoprint.org/en/master/development/virtual_printer.html"
)
__plugin_license__ = "AGPLv3"
__plugin_description__ = "Provides a virtual printer via a virtual serial port for development and testing purposes"
__plugin_pythoncompat__ = ">=2.7,<4"
def __plugin_load__():
plugin = VirtualPrinterPlugin()
plugin = VirtualPrinterPlugin()
global __plugin_implementation__
__plugin_implementation__ = plugin
global __plugin_implementation__
__plugin_implementation__ = plugin
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.comm.transport.serial.factory": plugin.virtual_printer_factory,
"octoprint.comm.transport.serial.additional_port_names": plugin.get_additional_port_names
}
global __plugin_hooks__
__plugin_hooks__ = {
"octoprint.comm.transport.serial.factory": plugin.virtual_printer_factory,
"octoprint.comm.transport.serial.additional_port_names": plugin.get_additional_port_names,
}
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+221 -185
View File
@@ -2,7 +2,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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"
@@ -10,229 +10,265 @@ from octoprint.settings import settings
class PrintTimeEstimator(object):
"""
Estimator implementation.
"""
Estimator implementation.
Subclass this and register via the octoprint.printer.estimation.factory hook to provide your own implementation.
"""
Subclass this and register via the octoprint.printer.estimation.factory hook to provide your own implementation.
"""
def __init__(self, job_type):
self.stats_weighing_until = settings().getFloat(["estimation", "printTime", "statsWeighingUntil"])
self.validity_range = settings().getFloat(["estimation", "printTime", "validityRange"])
self.force_dumb_from_percent = settings().getFloat(["estimation", "printTime", "forceDumbFromPercent"])
self.force_dumb_after_min = settings().getFloat(["estimation", "printTime", "forceDumbAfterMin"])
def __init__(self, job_type):
self.stats_weighing_until = settings().getFloat(
["estimation", "printTime", "statsWeighingUntil"]
)
self.validity_range = settings().getFloat(
["estimation", "printTime", "validityRange"]
)
self.force_dumb_from_percent = settings().getFloat(
["estimation", "printTime", "forceDumbFromPercent"]
)
self.force_dumb_after_min = settings().getFloat(
["estimation", "printTime", "forceDumbAfterMin"]
)
threshold = None
rolling_window = None
countdown = None
threshold = None
rolling_window = None
countdown = None
if job_type == "local" or job_type == "sdcard":
# we are happy if the average of the estimates stays within 60s of the prior one
threshold = settings().getFloat(["estimation", "printTime", "stableThreshold"])
if job_type == "local" or job_type == "sdcard":
# we are happy if the average of the estimates stays within 60s of the prior one
threshold = settings().getFloat(
["estimation", "printTime", "stableThreshold"]
)
if job_type == "sdcard":
# we are interesting in a rolling window of roughly the last 15s, so the number of entries has to be derived
# by that divided by the sd status polling interval
interval = settings().getFloat(["serial", "timeout", "sdStatus"])
if interval <= 0:
interval = 1.0
rolling_window = int(15 // interval)
if rolling_window < 1:
rolling_window = 1
if job_type == "sdcard":
# we are interesting in a rolling window of roughly the last 15s, so the number of entries has to be derived
# by that divided by the sd status polling interval
interval = settings().getFloat(["serial", "timeout", "sdStatus"])
if interval <= 0:
interval = 1.0
rolling_window = int(15 // interval)
if rolling_window < 1:
rolling_window = 1
# we are happy when one rolling window has been stable
countdown = rolling_window
# we are happy when one rolling window has been stable
countdown = rolling_window
self._data = TimeEstimationHelper(rolling_window=rolling_window, countdown=countdown, threshold=threshold)
self._data = TimeEstimationHelper(
rolling_window=rolling_window, countdown=countdown, threshold=threshold
)
def estimate(self, progress, printTime, cleanedPrintTime, statisticalTotalPrintTime, statisticalTotalPrintTimeType):
"""
Tries to estimate the print time left for the print job
def estimate(
self,
progress,
printTime,
cleanedPrintTime,
statisticalTotalPrintTime,
statisticalTotalPrintTimeType,
):
"""
Tries to estimate the print time left for the print job
This is somewhat horrible since accurate print time estimation is pretty much impossible to
achieve, considering that we basically have only two data points (current progress in file and
time needed for that so far - former prints or a file analysis might not have happened or simply
be completely impossible e.g. if the file is stored on the printer's SD card) and
hence can only do a linear estimation of a completely non-linear process. That's a recipe
for inaccurate predictions right there. Yay.
This is somewhat horrible since accurate print time estimation is pretty much impossible to
achieve, considering that we basically have only two data points (current progress in file and
time needed for that so far - former prints or a file analysis might not have happened or simply
be completely impossible e.g. if the file is stored on the printer's SD card) and
hence can only do a linear estimation of a completely non-linear process. That's a recipe
for inaccurate predictions right there. Yay.
Anyhow, here's how this implementation works. This method gets the current progress in the
printed file (percentage based on bytes read vs total bytes), the print time that elapsed,
the same print time with the heat up times subtracted (if possible) and if available also
some statistical total print time (former prints or a result from the GCODE analysis).
Anyhow, here's how this implementation works. This method gets the current progress in the
printed file (percentage based on bytes read vs total bytes), the print time that elapsed,
the same print time with the heat up times subtracted (if possible) and if available also
some statistical total print time (former prints or a result from the GCODE analysis).
1. First get an "intelligent" estimate based on the :class:`~octoprint.printer.estimation.TimeEstimationHelper`.
That thing tries to detect if the estimation based on our progress and time needed for that becomes
stable over time through a rolling window and only returns a result once that appears to be the
case.
2. If we have any statistical data (former prints or a result from the GCODE analysis)
but no intelligent estimate yet, we'll use that for the next step. Otherwise, up to a certain percentage
in the print we do a percentage based weighing of the statistical data and the intelligent
estimate - the closer to the beginning of the print, the more precedence for the statistical
data, the closer to the cut off point, the more precedence for the intelligent estimate. This
is our preliminary total print time.
3. If the total print time is set, we do a sanity check for it. Based on the total print time
estimate and the time we already spent printing, we calculate at what percentage we SHOULD be
and compare that to the percentage at which we actually ARE. If it's too far off, our total
can't be trusted and we fall back on the dumb estimate. Same if the time we spent printing is
already higher than our total estimate.
4. If we do NOT have a total print time estimate yet but we've been printing for longer than
a configured amount of minutes or are further in the file than a configured percentage, we
also use the dumb estimate for now.
1. First get an "intelligent" estimate based on the :class:`~octoprint.printer.estimation.TimeEstimationHelper`.
That thing tries to detect if the estimation based on our progress and time needed for that becomes
stable over time through a rolling window and only returns a result once that appears to be the
case.
2. If we have any statistical data (former prints or a result from the GCODE analysis)
but no intelligent estimate yet, we'll use that for the next step. Otherwise, up to a certain percentage
in the print we do a percentage based weighing of the statistical data and the intelligent
estimate - the closer to the beginning of the print, the more precedence for the statistical
data, the closer to the cut off point, the more precedence for the intelligent estimate. This
is our preliminary total print time.
3. If the total print time is set, we do a sanity check for it. Based on the total print time
estimate and the time we already spent printing, we calculate at what percentage we SHOULD be
and compare that to the percentage at which we actually ARE. If it's too far off, our total
can't be trusted and we fall back on the dumb estimate. Same if the time we spent printing is
already higher than our total estimate.
4. If we do NOT have a total print time estimate yet but we've been printing for longer than
a configured amount of minutes or are further in the file than a configured percentage, we
also use the dumb estimate for now.
Yes, all this still produces horribly inaccurate results. But we have to do this live during the print and
hence can't produce to much computational overhead, we do not have any insight into the firmware implementation
with regards to planner setup and acceleration settings, we might not even have access to the printed file's
contents and such we need to find something that works "mostly" all of the time without costing too many
resources. Feel free to propose a better solution within the above limitations (and I mean that, this solution
here makes me unhappy).
Yes, all this still produces horribly inaccurate results. But we have to do this live during the print and
hence can't produce to much computational overhead, we do not have any insight into the firmware implementation
with regards to planner setup and acceleration settings, we might not even have access to the printed file's
contents and such we need to find something that works "mostly" all of the time without costing too many
resources. Feel free to propose a better solution within the above limitations (and I mean that, this solution
here makes me unhappy).
Args:
progress (float or None): Current percentage in the printed file
printTime (float or None): Print time elapsed so far
cleanedPrintTime (float or None): Print time elapsed minus the time needed for getting up to temperature
(if detectable).
statisticalTotalPrintTime (float or None): Total print time of past prints against same printer profile,
or estimated total print time from GCODE analysis.
statisticalTotalPrintTimeType (str or None): Type of statistical print time, either "average" (total time
of former prints) or "analysis"
Args:
progress (float or None): Current percentage in the printed file
printTime (float or None): Print time elapsed so far
cleanedPrintTime (float or None): Print time elapsed minus the time needed for getting up to temperature
(if detectable).
statisticalTotalPrintTime (float or None): Total print time of past prints against same printer profile,
or estimated total print time from GCODE analysis.
statisticalTotalPrintTimeType (str or None): Type of statistical print time, either "average" (total time
of former prints) or "analysis"
Returns:
(2-tuple) estimated print time left or None if not proper estimate could be made at all, origin of estimation
"""
Returns:
(2-tuple) estimated print time left or None if not proper estimate could be made at all, origin of estimation
"""
if progress is None or progress == 0 or printTime is None or cleanedPrintTime is None:
return None, None
if (
progress is None
or progress == 0
or printTime is None
or cleanedPrintTime is None
):
return None, None
dumbTotalPrintTime = printTime / progress
estimatedTotalPrintTime = self.estimate_total(progress, cleanedPrintTime)
totalPrintTime = estimatedTotalPrintTime
dumbTotalPrintTime = printTime / progress
estimatedTotalPrintTime = self.estimate_total(progress, cleanedPrintTime)
totalPrintTime = estimatedTotalPrintTime
printTimeLeftOrigin = "estimate"
if statisticalTotalPrintTime is not None:
if estimatedTotalPrintTime is None:
# no estimate yet, we'll use the statistical total
totalPrintTime = statisticalTotalPrintTime
printTimeLeftOrigin = statisticalTotalPrintTimeType
printTimeLeftOrigin = "estimate"
if statisticalTotalPrintTime is not None:
if estimatedTotalPrintTime is None:
# no estimate yet, we'll use the statistical total
totalPrintTime = statisticalTotalPrintTime
printTimeLeftOrigin = statisticalTotalPrintTimeType
else:
if progress < self.stats_weighing_until:
# still inside weighing range, use part stats, part current estimate
sub_progress = progress * (1 / self.stats_weighing_until)
if sub_progress > 1.0:
sub_progress = 1.0
printTimeLeftOrigin = "mixed-" + statisticalTotalPrintTimeType
else:
# use only the current estimate
sub_progress = 1.0
printTimeLeftOrigin = "estimate"
else:
if progress < self.stats_weighing_until:
# still inside weighing range, use part stats, part current estimate
sub_progress = progress * (1 / self.stats_weighing_until)
if sub_progress > 1.0:
sub_progress = 1.0
printTimeLeftOrigin = "mixed-" + statisticalTotalPrintTimeType
else:
# use only the current estimate
sub_progress = 1.0
printTimeLeftOrigin = "estimate"
# combine
totalPrintTime = - sub_progress * statisticalTotalPrintTime \
+ sub_progress * estimatedTotalPrintTime
# combine
totalPrintTime = (
-sub_progress * statisticalTotalPrintTime
+ sub_progress * estimatedTotalPrintTime
)
printTimeLeft = None
if totalPrintTime is not None:
# sanity check current total print time estimate
assumed_progress = cleanedPrintTime / totalPrintTime
min_progress = progress - self.validity_range
max_progress = progress + self.validity_range
printTimeLeft = None
if totalPrintTime is not None:
# sanity check current total print time estimate
assumed_progress = cleanedPrintTime / totalPrintTime
min_progress = progress - self.validity_range
max_progress = progress + self.validity_range
if min_progress <= assumed_progress <= max_progress and totalPrintTime > cleanedPrintTime:
# appears sane, we'll use it
printTimeLeft = totalPrintTime - cleanedPrintTime
if (
min_progress <= assumed_progress <= max_progress
and totalPrintTime > cleanedPrintTime
):
# appears sane, we'll use it
printTimeLeft = totalPrintTime - cleanedPrintTime
else:
# too far from the actual progress or negative,
# we use the dumb print time instead
printTimeLeft = dumbTotalPrintTime - cleanedPrintTime
printTimeLeftOrigin = "linear"
else:
# too far from the actual progress or negative,
# we use the dumb print time instead
printTimeLeft = dumbTotalPrintTime - cleanedPrintTime
printTimeLeftOrigin = "linear"
else:
printTimeLeftOrigin = "linear"
if progress > self.force_dumb_from_percent or \
cleanedPrintTime >= self.force_dumb_after_min * 60:
# more than x% or y min printed and still no real estimate, ok, we'll use the dumb variant :/
printTimeLeft = dumbTotalPrintTime - cleanedPrintTime
else:
printTimeLeftOrigin = "linear"
if (
progress > self.force_dumb_from_percent
or cleanedPrintTime >= self.force_dumb_after_min * 60
):
# more than x% or y min printed and still no real estimate, ok, we'll use the dumb variant :/
printTimeLeft = dumbTotalPrintTime - cleanedPrintTime
if printTimeLeft is not None and printTimeLeft < 0:
# shouldn't actually happen, but let's make sure
printTimeLeft = None
if printTimeLeft is not None and printTimeLeft < 0:
# shouldn't actually happen, but let's make sure
printTimeLeft = None
return printTimeLeft, printTimeLeftOrigin
return printTimeLeft, printTimeLeftOrigin
def estimate_total(self, progress, printTime):
if not progress or not printTime or not self._data:
return None
else:
return self._data.update(printTime / progress)
def estimate_total(self, progress, printTime):
if not progress or not printTime or not self._data:
return None
else:
return self._data.update(printTime / progress)
class TimeEstimationHelper(object):
STABLE_THRESHOLD = 0.1
STABLE_COUNTDOWN = 250
STABLE_ROLLING_WINDOW = 250
STABLE_THRESHOLD = 0.1
STABLE_COUNTDOWN = 250
STABLE_ROLLING_WINDOW = 250
def __init__(self, rolling_window=None, countdown=None, threshold=None):
if rolling_window is None:
rolling_window = self.__class__.STABLE_ROLLING_WINDOW
if countdown is None:
countdown = self.__class__.STABLE_COUNTDOWN
if threshold is None:
threshold = self.__class__.STABLE_THRESHOLD
def __init__(self, rolling_window=None, countdown=None, threshold=None):
if rolling_window is None:
rolling_window = self.__class__.STABLE_ROLLING_WINDOW
if countdown is None:
countdown = self.__class__.STABLE_COUNTDOWN
if threshold is None:
threshold = self.__class__.STABLE_THRESHOLD
self._rolling_window = rolling_window
self._countdown = countdown
self._threshold = threshold
self._rolling_window = rolling_window
self._countdown = countdown
self._threshold = threshold
import collections
self._distances = collections.deque([], self._rolling_window)
self._totals = collections.deque([], self._rolling_window)
self._sum_total = 0
self._count = 0
self._stable_counter = -1
import collections
def is_stable(self):
return self._stable_counter >= self._countdown
self._distances = collections.deque([], self._rolling_window)
self._totals = collections.deque([], self._rolling_window)
self._sum_total = 0
self._count = 0
self._stable_counter = -1
def update(self, new_estimate):
old_average_total = self.average_total
def is_stable(self):
return self._stable_counter >= self._countdown
self._sum_total += new_estimate
self._totals.append(new_estimate)
self._count += 1
def update(self, new_estimate):
old_average_total = self.average_total
if old_average_total:
self._distances.append(abs(self.average_total - old_average_total))
self._sum_total += new_estimate
self._totals.append(new_estimate)
self._count += 1
if -self._threshold < self.average_distance < self._threshold:
self._stable_counter += 1
else:
self._stable_counter = -1
if old_average_total:
self._distances.append(abs(self.average_total - old_average_total))
if self.is_stable():
return self.average_total_rolling
else:
return None
if -self._threshold < self.average_distance < self._threshold:
self._stable_counter += 1
else:
self._stable_counter = -1
@property
def average_total(self):
if not self._count:
return 0
else:
return self._sum_total / self._count
if self.is_stable():
return self.average_total_rolling
else:
return None
@property
def average_total_rolling(self):
if not self._count or self._count < self._rolling_window or not len(self._totals):
return -1
else:
return sum(self._totals) / len(self._totals)
@property
def average_total(self):
if not self._count:
return 0
else:
return self._sum_total / self._count
@property
def average_distance(self):
if not self._count or self._count < self._rolling_window + 1 or not len(self._distances):
return -1
else:
return sum(self._distances) / len(self._distances)
@property
def average_total_rolling(self):
if not self._count or self._count < self._rolling_window or not len(self._totals):
return -1
else:
return sum(self._totals) / len(self._totals)
@property
def average_distance(self):
if (
not self._count
or self._count < self._rolling_window + 1
or not len(self._distances)
):
return -1
else:
return sum(self._distances) / len(self._distances)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+257 -201
View File
@@ -2,7 +2,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Marc Hannappel <salandora@gmail.com>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
from flask import request, jsonify, abort, make_response
@@ -17,335 +17,391 @@ from octoprint.server.api import api, valid_boolean_trues
from octoprint.server.util.flask import no_firstrun_access
from octoprint.access.permissions import Permissions
#~~ permission api
# ~~ permission api
@api.route("/access/permissions", methods=["GET"])
def get_permissions():
return jsonify(permissions=[permission.as_dict() for permission in Permissions.all()])
return jsonify(permissions=[permission.as_dict() for permission in Permissions.all()])
# ~~ group api
#~~ group api
@api.route("/access/groups", methods=["GET"])
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def get_groups():
return jsonify(groups=list(map(lambda g: g.as_dict(), groupManager.groups)))
return jsonify(groups=list(map(lambda g: g.as_dict(), groupManager.groups)))
@api.route("/access/groups", methods=["POST"])
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def add_group():
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
try:
data = request.get_json()
except BadRequest:
return make_response("Malformed JSON body in request", 400)
try:
data = request.get_json()
except BadRequest:
return make_response("Malformed JSON body in request", 400)
if not "key" in data:
return make_response("Missing mandatory key field", 400)
if not "name" in data:
return make_response("Missing mandatory name field", 400)
if not "permissions" in data:
return make_response("Missing mandatory permissions field", 400)
if not "key" in data:
return make_response("Missing mandatory key field", 400)
if not "name" in data:
return make_response("Missing mandatory name field", 400)
if not "permissions" in data:
return make_response("Missing mandatory permissions field", 400)
key = data["key"]
name = data["name"]
description = data.get("description", "")
permissions = data["permissions"]
subgroups = data["subgroups"]
default = data.get("default", False)
key = data["key"]
name = data["name"]
description = data.get("description", "")
permissions = data["permissions"]
subgroups = data["subgroups"]
default = data.get("default", False)
try:
groupManager.add_group(key, name, description=description, permissions=permissions, subgroups=subgroups, default=default)
except groups.GroupAlreadyExists:
abort(409)
return get_groups()
try:
groupManager.add_group(
key,
name,
description=description,
permissions=permissions,
subgroups=subgroups,
default=default,
)
except groups.GroupAlreadyExists:
abort(409)
return get_groups()
@api.route("/access/groups/<key>", methods=["GET"])
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def get_group(key):
group = groupManager.find_group(key)
if group is not None:
return jsonify(group)
else:
abort(404)
group = groupManager.find_group(key)
if group is not None:
return jsonify(group)
else:
abort(404)
@api.route("/access/groups/<key>", methods=["PUT"])
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def update_group(key):
if "application/json" not in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
if "application/json" not in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
try:
data = request.get_json()
except BadRequest:
return make_response("Malformed JSON body in request", 400)
try:
data = request.get_json()
except BadRequest:
return make_response("Malformed JSON body in request", 400)
try:
kwargs = {}
try:
kwargs = {}
if "permissions" in data:
kwargs["permissions"] = data["permissions"]
if "permissions" in data:
kwargs["permissions"] = data["permissions"]
if "subgroups" in data:
kwargs["subgroups"] = data["subgroups"]
if "subgroups" in data:
kwargs["subgroups"] = data["subgroups"]
if "default" in data:
kwargs["default"] = data["default"] in valid_boolean_trues
if "default" in data:
kwargs["default"] = data["default"] in valid_boolean_trues
if "description" in data:
kwargs["description"] = data["description"]
if "description" in data:
kwargs["description"] = data["description"]
groupManager.update_group(key, **kwargs)
groupManager.update_group(key, **kwargs)
return get_groups()
except groups.GroupCantBeChanged:
abort(403)
except groups.UnknownGroup:
abort(404)
return get_groups()
except groups.GroupCantBeChanged:
abort(403)
except groups.UnknownGroup:
abort(404)
@api.route("/access/groups/<key>", methods=["DELETE"])
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def remove_group(key):
try:
groupManager.remove_group(key)
return get_groups()
except groups.UnknownGroup:
abort(404)
except groups.GroupUnremovable:
abort(403)
try:
groupManager.remove_group(key)
return get_groups()
except groups.UnknownGroup:
abort(404)
except groups.GroupUnremovable:
abort(403)
# ~~ user api
#~~ user api
@api.route("/access/users", methods=["GET"])
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def get_users():
if not userManager.enabled:
return jsonify(SUCCESS)
if not userManager.enabled:
return jsonify(SUCCESS)
return jsonify(users=list(map(lambda u: u.as_dict(), userManager.get_all_users())))
return jsonify(users=list(map(lambda u: u.as_dict(), userManager.get_all_users())))
@api.route("/access/users", methods=["POST"])
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def add_user():
if not userManager.enabled:
return jsonify(SUCCESS)
if not userManager.enabled:
return jsonify(SUCCESS)
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
try:
data = request.get_json()
except BadRequest:
return make_response("Malformed JSON body in request", 400)
try:
data = request.get_json()
except BadRequest:
return make_response("Malformed JSON body in request", 400)
if data is None:
return make_response("Malformed JSON body in request", 400)
if data is None:
return make_response("Malformed JSON body in request", 400)
if not "name" in data:
return make_response("Missing mandatory name field", 400)
if not "password" in data:
return make_response("Missing mandatory password field", 400)
if not "active" in data:
return make_response("Missing mandatory active field", 400)
if not "name" in data:
return make_response("Missing mandatory name field", 400)
if not "password" in data:
return make_response("Missing mandatory password field", 400)
if not "active" in data:
return make_response("Missing mandatory active field", 400)
name = data["name"]
password = data["password"]
active = data["active"] in valid_boolean_trues
name = data["name"]
password = data["password"]
active = data["active"] in valid_boolean_trues
groups = data.get("groups", None)
permissions = data.get("permissions", None)
groups = data.get("groups", None)
permissions = data.get("permissions", None)
try:
userManager.add_user(name, password, active, permissions, groups)
except users.UserAlreadyExists:
abort(409)
return get_users()
try:
userManager.add_user(name, password, active, permissions, groups)
except users.UserAlreadyExists:
abort(409)
return get_users()
@api.route("/access/users/<username>", methods=["GET"])
@no_firstrun_access
def get_user(username):
if not userManager.enabled:
return jsonify(SUCCESS)
if not userManager.enabled:
return jsonify(SUCCESS)
if current_user is not None and not current_user.is_anonymous and (current_user.get_name() == username or current_user.has_permission(Permissions.ADMIN)):
user = userManager.find_user(username)
if user is not None:
return jsonify(user)
else:
abort(404)
else:
abort(403)
if (
current_user is not None
and not current_user.is_anonymous
and (
current_user.get_name() == username
or current_user.has_permission(Permissions.ADMIN)
)
):
user = userManager.find_user(username)
if user is not None:
return jsonify(user)
else:
abort(404)
else:
abort(403)
@api.route("/access/users/<username>", methods=["PUT"])
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def update_user(username):
if not userManager.enabled:
return jsonify(SUCCESS)
if not userManager.enabled:
return jsonify(SUCCESS)
user = userManager.find_user(username)
if user is not None:
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
user = userManager.find_user(username)
if user is not None:
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
try:
data = request.get_json()
except BadRequest:
return make_response("Malformed JSON body in request", 400)
try:
data = request.get_json()
except BadRequest:
return make_response("Malformed JSON body in request", 400)
# change groups
if "groups" in data:
groups = data["groups"]
userManager.change_user_groups(username, groups)
# change groups
if "groups" in data:
groups = data["groups"]
userManager.change_user_groups(username, groups)
# change permissions
if "permissions" in data:
permissions = data["permissions"]
userManager.change_user_permissions(username, permissions)
# change permissions
if "permissions" in data:
permissions = data["permissions"]
userManager.change_user_permissions(username, permissions)
if data is None:
return make_response("Malformed JSON body in request", 400)
if data is None:
return make_response("Malformed JSON body in request", 400)
# change activation
if "active" in data:
userManager.change_user_activation(
username, data["active"] in valid_boolean_trues
)
# change activation
if "active" in data:
userManager.change_user_activation(username, data["active"] in valid_boolean_trues)
return get_users()
else:
abort(404)
return get_users()
else:
abort(404)
@api.route("/access/users/<username>", methods=["DELETE"])
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def remove_user(username):
if not userManager.enabled:
return jsonify(SUCCESS)
if not userManager.enabled:
return jsonify(SUCCESS)
try:
userManager.remove_user(username)
return get_users()
except users.UnknownUser:
abort(404)
try:
userManager.remove_user(username)
return get_users()
except users.UnknownUser:
abort(404)
@api.route("/access/users/<username>/password", methods=["PUT"])
@no_firstrun_access
def change_password_for_user(username):
if not userManager.enabled:
return jsonify(SUCCESS)
if not userManager.enabled:
return jsonify(SUCCESS)
if current_user is not None and not current_user.is_anonymous and (current_user.get_name() == username or current_user.is_admin):
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
if (
current_user is not None
and not current_user.is_anonymous
and (current_user.get_name() == username or current_user.is_admin)
):
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
try:
data = request.get_json()
except BadRequest:
return make_response("Malformed JSON body in request", 400)
try:
data = request.get_json()
except BadRequest:
return make_response("Malformed JSON body in request", 400)
if data is None:
return make_response("Malformed JSON body in request", 400)
if data is None:
return make_response("Malformed JSON body in request", 400)
if not "password" in data or not data["password"]:
return make_response("password is missing from request", 400)
if not "password" in data or not data["password"]:
return make_response("password is missing from request", 400)
try:
userManager.change_user_password(username, data["password"])
except users.UnknownUser:
return make_response(("Unknown user: %s" % username, 404, []))
try:
userManager.change_user_password(username, data["password"])
except users.UnknownUser:
return make_response(("Unknown user: %s" % username, 404, []))
return jsonify(SUCCESS)
else:
return make_response(("Forbidden", 403, []))
return jsonify(SUCCESS)
else:
return make_response(("Forbidden", 403, []))
@api.route("/access/users/<username>/settings", methods=["GET"])
@no_firstrun_access
def get_settings_for_user(username):
if not userManager.enabled:
return jsonify(SUCCESS)
if not userManager.enabled:
return jsonify(SUCCESS)
if current_user is None or current_user.is_anonymous or (current_user.get_name() != username and not current_user.has_permission(Permissions.ADMIN)):
return make_response("Forbidden", 403)
if (
current_user is None
or current_user.is_anonymous
or (
current_user.get_name() != username
and not current_user.has_permission(Permissions.ADMIN)
)
):
return make_response("Forbidden", 403)
try:
return jsonify(userManager.get_all_user_settings(username))
except users.UnknownUser:
return make_response("Unknown user: %s" % username, 404)
try:
return jsonify(userManager.get_all_user_settings(username))
except users.UnknownUser:
return make_response("Unknown user: %s" % username, 404)
@api.route("/access/users/<username>/settings", methods=["PATCH"])
@no_firstrun_access
def change_settings_for_user(username):
if not userManager.enabled:
return jsonify(SUCCESS)
if not userManager.enabled:
return jsonify(SUCCESS)
if current_user is None or current_user.is_anonymous or (current_user.get_name() != username and not current_user.has_permission(Permissions.ADMIN)):
return make_response("Forbidden", 403)
if (
current_user is None
or current_user.is_anonymous
or (
current_user.get_name() != username
and not current_user.has_permission(Permissions.ADMIN)
)
):
return make_response("Forbidden", 403)
try:
data = request.get_json()
except BadRequest:
return make_response("Malformed JSON body in request", 400)
try:
data = request.get_json()
except BadRequest:
return make_response("Malformed JSON body in request", 400)
if data is None:
return make_response("Malformed JSON body in request", 400)
if data is None:
return make_response("Malformed JSON body in request", 400)
try:
userManager.change_user_settings(username, data)
return jsonify(SUCCESS)
except users.UnknownUser:
return make_response("Unknown user: %s" % username, 404)
try:
userManager.change_user_settings(username, data)
return jsonify(SUCCESS)
except users.UnknownUser:
return make_response("Unknown user: %s" % username, 404)
@api.route("/access/users/<username>/apikey", methods=["DELETE"])
@no_firstrun_access
def delete_apikey_for_user(username):
if not userManager.enabled:
return jsonify(SUCCESS)
if not userManager.enabled:
return jsonify(SUCCESS)
if current_user is not None and not current_user.is_anonymous and (current_user.get_name() == username or current_user.has_permission(Permissions.ADMIN)):
try:
userManager.delete_api_key(username)
except users.UnknownUser:
return make_response(("Unknown user: %s" % username, 404, []))
return jsonify(SUCCESS)
else:
return make_response(("Forbidden", 403, []))
if (
current_user is not None
and not current_user.is_anonymous
and (
current_user.get_name() == username
or current_user.has_permission(Permissions.ADMIN)
)
):
try:
userManager.delete_api_key(username)
except users.UnknownUser:
return make_response(("Unknown user: %s" % username, 404, []))
return jsonify(SUCCESS)
else:
return make_response(("Forbidden", 403, []))
@api.route("/access/users/<username>/apikey", methods=["POST"])
@no_firstrun_access
def generate_apikey_for_user(username):
if not userManager.enabled:
return jsonify(SUCCESS)
if not userManager.enabled:
return jsonify(SUCCESS)
if (
current_user is not None
and not current_user.is_anonymous
and (
current_user.get_name() == username
or current_user.has_permission(Permissions.ADMIN)
)
):
try:
apikey = userManager.generate_api_key(username)
except users.UnknownUser:
return make_response(("Unknown user: %s" % username, 404, []))
return jsonify({"apikey": apikey})
else:
return make_response(("Forbidden", 403, []))
if current_user is not None and not current_user.is_anonymous and (current_user.get_name() == username or current_user.has_permission(Permissions.ADMIN)):
try:
apikey = userManager.generate_api_key(username)
except users.UnknownUser:
return make_response(("Unknown user: %s" % username, 404, []))
return jsonify({"apikey": apikey})
else:
return make_response(("Forbidden", 403, []))
def _to_external_permissions(*permissions):
return list(map(lambda p: p.get_name(), permissions))
return list(map(lambda p: p.get_name(), permissions))
def _to_external_groups(*groups):
return list(map(lambda g: g.get_name(), groups))
return list(map(lambda g: g.get_name(), groups))
+70 -57
View File
@@ -2,7 +2,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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"
from flask import request, jsonify, make_response
@@ -13,77 +13,90 @@ from octoprint.server.api import api
from octoprint.server.util.flask import no_firstrun_access, get_json_command_from_request
from octoprint.access.permissions import Permissions
@api.route("/connection", methods=["GET"])
@Permissions.STATUS.require(403)
def connectionState():
state, port, baudrate, printer_profile = printer.get_current_connection()
current = {
"state": state,
"port": port,
"baudrate": baudrate,
"printerProfile": printer_profile["id"] if printer_profile is not None and "id" in printer_profile else "_default"
}
state, port, baudrate, printer_profile = printer.get_current_connection()
current = {
"state": state,
"port": port,
"baudrate": baudrate,
"printerProfile": printer_profile["id"]
if printer_profile is not None and "id" in printer_profile
else "_default",
}
return jsonify({"current": current, "options": _get_options()})
return jsonify({"current": current, "options": _get_options()})
@api.route("/connection", methods=["POST"])
@no_firstrun_access
@Permissions.CONNECTION.require(403)
def connectionCommand():
valid_commands = {
"connect": [],
"disconnect": [],
"fake_ack": []
}
valid_commands = {"connect": [], "disconnect": [], "fake_ack": []}
command, data, response = get_json_command_from_request(request, valid_commands)
if response is not None:
return response
command, data, response = get_json_command_from_request(request, valid_commands)
if response is not None:
return response
if command == "connect":
connection_options = printer.__class__.get_connection_options()
if command == "connect":
connection_options = printer.__class__.get_connection_options()
port = None
baudrate = None
printerProfile = None
if "port" in data:
port = data["port"]
if port not in connection_options["ports"] and port != "AUTO":
return make_response("Invalid port: %s" % port, 400)
if "baudrate" in data:
baudrate = data["baudrate"]
if baudrate not in connection_options["baudrates"] and baudrate != 0:
return make_response("Invalid baudrate: %d" % baudrate, 400)
if "printerProfile" in data:
printerProfile = data["printerProfile"]
if not printerProfileManager.exists(printerProfile):
return make_response("Invalid printer profile: %s" % printerProfile, 400)
if "save" in data and data["save"]:
settings().set(["serial", "port"], port)
settings().setInt(["serial", "baudrate"], baudrate)
printerProfileManager.set_default(printerProfile)
if "autoconnect" in data:
settings().setBoolean(["serial", "autoconnect"], data["autoconnect"])
settings().save()
printer.connect(port=port, baudrate=baudrate, profile=printerProfile)
elif command == "disconnect":
printer.disconnect()
elif command == "fake_ack":
printer.fake_ack()
port = None
baudrate = None
printerProfile = None
if "port" in data:
port = data["port"]
if port not in connection_options["ports"] and port != "AUTO":
return make_response("Invalid port: %s" % port, 400)
if "baudrate" in data:
baudrate = data["baudrate"]
if baudrate not in connection_options["baudrates"] and baudrate != 0:
return make_response("Invalid baudrate: %d" % baudrate, 400)
if "printerProfile" in data:
printerProfile = data["printerProfile"]
if not printerProfileManager.exists(printerProfile):
return make_response("Invalid printer profile: %s" % printerProfile, 400)
if "save" in data and data["save"]:
settings().set(["serial", "port"], port)
settings().setInt(["serial", "baudrate"], baudrate)
printerProfileManager.set_default(printerProfile)
if "autoconnect" in data:
settings().setBoolean(["serial", "autoconnect"], data["autoconnect"])
settings().save()
printer.connect(port=port, baudrate=baudrate, profile=printerProfile)
elif command == "disconnect":
printer.disconnect()
elif command == "fake_ack":
printer.fake_ack()
return NO_CONTENT
return NO_CONTENT
def _get_options():
connection_options = printer.__class__.get_connection_options()
profile_options = printerProfileManager.get_all()
default_profile = printerProfileManager.get_default()
connection_options = printer.__class__.get_connection_options()
profile_options = printerProfileManager.get_all()
default_profile = printerProfileManager.get_default()
options = {"ports": connection_options["ports"],
"baudrates": connection_options["baudrates"],
"printerProfiles": [{"id": printer_profile["id"], "name": printer_profile["name"] if "name" in printer_profile else printer_profile["id"]} for printer_profile in profile_options.values() if "id" in printer_profile],
"portPreference": connection_options["portPreference"],
"baudratePreference": connection_options["baudratePreference"],
"printerProfilePreference": default_profile["id"] if "id" in default_profile else None}
options = {
"ports": connection_options["ports"],
"baudrates": connection_options["baudrates"],
"printerProfiles": [
{
"id": printer_profile["id"],
"name": printer_profile["name"]
if "name" in printer_profile
else printer_profile["id"],
}
for printer_profile in profile_options.values()
if "id" in printer_profile
],
"portPreference": connection_options["portPreference"],
"baudratePreference": connection_options["baudratePreference"],
"printerProfilePreference": default_profile["id"]
if "id" in default_profile
else None,
}
return options
return options
File diff suppressed because it is too large. Load diff
+61 -47
View File
@@ -2,7 +2,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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"
from flask import request, make_response, jsonify
@@ -12,63 +12,77 @@ from octoprint.server.util.flask import no_firstrun_access, get_json_command_fro
from octoprint.server.api import api
from octoprint.access.permissions import Permissions
@api.route("/job", methods=["POST"])
@no_firstrun_access
def controlJob():
if not printer.is_operational():
return make_response("Printer is not operational", 409)
if not printer.is_operational():
return make_response("Printer is not operational", 409)
valid_commands = {
"start": [],
"restart": [],
"pause": [],
"cancel": []
}
valid_commands = {"start": [], "restart": [], "pause": [], "cancel": []}
command, data, response = get_json_command_from_request(request, valid_commands)
if response is not None:
return response
command, data, response = get_json_command_from_request(request, valid_commands)
if response is not None:
return response
activePrintjob = printer.is_printing() or printer.is_paused()
activePrintjob = printer.is_printing() or printer.is_paused()
tags = {"source:api", "api:job"}
tags = {"source:api", "api:job"}
user = current_user.get_name()
user = current_user.get_name()
with Permissions.PRINT.require(403):
if command == "start":
if activePrintjob:
return make_response("Printer already has an active print job, did you mean 'restart'?", 409)
printer.start_print(tags=tags, user=user)
elif command == "restart":
if not printer.is_paused():
return make_response("Printer does not have an active print job or is not paused", 409)
printer.start_print(tags=tags, user=user)
elif command == "pause":
if not activePrintjob:
return make_response("Printer is neither printing nor paused, 'pause' command cannot be performed", 409)
action = data.get("action", "toggle")
if action == "toggle":
printer.toggle_pause_print(tags=tags, user=user)
elif action == "pause":
printer.pause_print(tags=tags, user=user)
elif action == "resume":
printer.resume_print(tags=tags, user=user)
else:
return make_response("Unknown action '{}', allowed values for action parameter are 'pause', 'resume' and 'toggle'".format(action), 400)
elif command == "cancel":
if not activePrintjob:
return make_response("Printer is neither printing nor paused, 'cancel' command cannot be performed", 409)
printer.cancel_print(tags=tags, user=user)
return NO_CONTENT
with Permissions.PRINT.require(403):
if command == "start":
if activePrintjob:
return make_response(
"Printer already has an active print job, did you mean 'restart'?",
409,
)
printer.start_print(tags=tags, user=user)
elif command == "restart":
if not printer.is_paused():
return make_response(
"Printer does not have an active print job or is not paused", 409
)
printer.start_print(tags=tags, user=user)
elif command == "pause":
if not activePrintjob:
return make_response(
"Printer is neither printing nor paused, 'pause' command cannot be performed",
409,
)
action = data.get("action", "toggle")
if action == "toggle":
printer.toggle_pause_print(tags=tags, user=user)
elif action == "pause":
printer.pause_print(tags=tags, user=user)
elif action == "resume":
printer.resume_print(tags=tags, user=user)
else:
return make_response(
"Unknown action '{}', allowed values for action parameter are 'pause', 'resume' and 'toggle'".format(
action
),
400,
)
elif command == "cancel":
if not activePrintjob:
return make_response(
"Printer is neither printing nor paused, 'cancel' command cannot be performed",
409,
)
printer.cancel_print(tags=tags, user=user)
return NO_CONTENT
@api.route("/job", methods=["GET"])
@Permissions.STATUS.require(403)
def jobState():
currentData = printer.get_current_data()
return jsonify({
"job": currentData["job"],
"progress": currentData["progress"],
"state": currentData["state"]["text"]
})
currentData = printer.get_current_data()
return jsonify(
{
"job": currentData["job"],
"progress": currentData["progress"],
"state": currentData["state"]["text"],
}
)
+140 -98
View File
@@ -2,7 +2,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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 io
@@ -12,9 +12,9 @@ import zipfile
import logging
try:
from os import scandir
from os import scandir
except ImportError:
from scandir import scandir
from scandir import scandir
from collections import defaultdict
@@ -30,141 +30,183 @@ from octoprint.access.permissions import Permissions
from flask_babel import Locale
@api.route("/languages", methods=["GET"])
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def getInstalledLanguagePacks():
translation_folder = settings().getBaseFolder("translations", check_writable=False)
if not os.path.exists(translation_folder):
return jsonify(language_packs={"_core": []})
translation_folder = settings().getBaseFolder("translations", check_writable=False)
if not os.path.exists(translation_folder):
return jsonify(language_packs={"_core": []})
core_packs = []
plugin_packs = defaultdict(lambda: {"identifier": None, "display": None, "languages": []})
for entry in scandir(translation_folder):
if not entry.is_dir():
continue
core_packs = []
plugin_packs = defaultdict(
lambda: {"identifier": None, "display": None, "languages": []}
)
for entry in scandir(translation_folder):
if not entry.is_dir():
continue
def load_meta(path, locale):
meta = {}
def load_meta(path, locale):
meta = {}
meta_path = os.path.join(path, "meta.yaml")
if os.path.isfile(meta_path):
import yaml
try:
with io.open(meta_path, 'rt', encoding='utf-8') as f:
meta = yaml.safe_load(f)
except Exception:
logging.getLogger(__name__).exception("Could not load %s", meta_path)
pass
else:
import datetime
if "last_update" in meta and isinstance(meta["last_update"], datetime.datetime):
meta["last_update"] = (meta["last_update"] - datetime.datetime(1970,1,1)).total_seconds()
meta_path = os.path.join(path, "meta.yaml")
if os.path.isfile(meta_path):
import yaml
l = Locale.parse(locale)
meta["locale"] = locale
meta["locale_display"] = l.display_name
meta["locale_english"] = l.english_name
return meta
try:
with io.open(meta_path, "rt", encoding="utf-8") as f:
meta = yaml.safe_load(f)
except Exception:
logging.getLogger(__name__).exception("Could not load %s", meta_path)
pass
else:
import datetime
if entry.name == "_plugins":
for plugin_entry in scandir(entry.path):
if not plugin_entry.is_dir():
continue
if "last_update" in meta and isinstance(
meta["last_update"], datetime.datetime
):
meta["last_update"] = (
meta["last_update"] - datetime.datetime(1970, 1, 1)
).total_seconds()
if not plugin_entry.name in plugin_manager().plugins:
continue
l = Locale.parse(locale)
meta["locale"] = locale
meta["locale_display"] = l.display_name
meta["locale_english"] = l.english_name
return meta
plugin_info = plugin_manager().plugins[plugin_entry.name]
if entry.name == "_plugins":
for plugin_entry in scandir(entry.path):
if not plugin_entry.is_dir():
continue
plugin_packs[plugin_entry.name]["identifier"] = plugin_entry.name
plugin_packs[plugin_entry.name]["display"] = plugin_info.name
if not plugin_entry.name in plugin_manager().plugins:
continue
for language_entry in scandir(plugin_entry.path):
try:
plugin_packs[plugin_entry.name]["languages"].append(load_meta(language_entry.path, language_entry.name))
except Exception:
logging.getLogger(__name__).exception("Error while parsing metadata for language pack {} from {} for plugin {}".format(language_entry.name,
language_entry.path,
plugin_entry.name))
continue
else:
try:
core_packs.append(load_meta(entry.path, entry.name))
except ValueError:
logging.getLogger(__name__).exception("Core language pack {} doesn't appear to actually be one".format(entry.name))
except Exception:
logging.getLogger(__name__).exception("Error while parsing metadata for core language pack {} from {}".format(entry.name,
entry.path))
plugin_info = plugin_manager().plugins[plugin_entry.name]
plugin_packs[plugin_entry.name]["identifier"] = plugin_entry.name
plugin_packs[plugin_entry.name]["display"] = plugin_info.name
for language_entry in scandir(plugin_entry.path):
try:
plugin_packs[plugin_entry.name]["languages"].append(
load_meta(language_entry.path, language_entry.name)
)
except Exception:
logging.getLogger(__name__).exception(
"Error while parsing metadata for language pack {} from {} for plugin {}".format(
language_entry.name,
language_entry.path,
plugin_entry.name,
)
)
continue
else:
try:
core_packs.append(load_meta(entry.path, entry.name))
except ValueError:
logging.getLogger(__name__).exception(
"Core language pack {} doesn't appear to actually be one".format(
entry.name
)
)
except Exception:
logging.getLogger(__name__).exception(
"Error while parsing metadata for core language pack {} from {}".format(
entry.name, entry.path
)
)
result = {
"_core": {"identifier": "_core", "display": "Core", "languages": core_packs}
}
result.update(plugin_packs)
return jsonify(language_packs=result)
result = {"_core": {"identifier": "_core", "display": "Core", "languages": core_packs}}
result.update(plugin_packs)
return jsonify(language_packs=result)
@api.route("/languages", methods=["POST"])
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def uploadLanguagePack():
input_name = "file"
input_upload_path = input_name + "." + settings().get(["server", "uploads", "pathSuffix"])
input_upload_name = input_name + "." + settings().get(["server", "uploads", "nameSuffix"])
if not input_upload_path in request.values or not input_upload_name in request.values:
return make_response("No file included", 400)
input_name = "file"
input_upload_path = (
input_name + "." + settings().get(["server", "uploads", "pathSuffix"])
)
input_upload_name = (
input_name + "." + settings().get(["server", "uploads", "nameSuffix"])
)
if not input_upload_path in request.values or not input_upload_name in request.values:
return make_response("No file included", 400)
upload_name = request.values[input_upload_name]
upload_path = request.values[input_upload_path]
upload_name = request.values[input_upload_name]
upload_path = request.values[input_upload_path]
exts = filter(lambda x: upload_name.lower().endswith(x), (".zip", ".tar.gz", ".tgz", ".tar"))
if not len(exts):
return make_response("File doesn't have a valid extension for a language pack archive", 400)
exts = filter(
lambda x: upload_name.lower().endswith(x), (".zip", ".tar.gz", ".tgz", ".tar")
)
if not len(exts):
return make_response(
"File doesn't have a valid extension for a language pack archive", 400
)
target_path = settings().getBaseFolder("translations")
target_path = settings().getBaseFolder("translations")
if tarfile.is_tarfile(upload_path):
_unpack_uploaded_tarball(upload_path, target_path)
elif zipfile.is_zipfile(upload_path):
_unpack_uploaded_zipfile(upload_path, target_path)
else:
return make_response("Neither zip file nor tarball included", 400)
if tarfile.is_tarfile(upload_path):
_unpack_uploaded_tarball(upload_path, target_path)
elif zipfile.is_zipfile(upload_path):
_unpack_uploaded_zipfile(upload_path, target_path)
else:
return make_response("Neither zip file nor tarball included", 400)
return getInstalledLanguagePacks()
return getInstalledLanguagePacks()
@api.route("/languages/<string:locale>/<string:pack>", methods=["DELETE"])
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def deleteInstalledLanguagePack(locale, pack):
if pack == "_core":
target_path = os.path.join(settings().getBaseFolder("translations"), locale)
else:
target_path = os.path.join(settings().getBaseFolder("translations"), "_plugins", pack, locale)
if pack == "_core":
target_path = os.path.join(settings().getBaseFolder("translations"), locale)
else:
target_path = os.path.join(
settings().getBaseFolder("translations"), "_plugins", pack, locale
)
if os.path.isdir(target_path):
import shutil
shutil.rmtree(target_path)
if os.path.isdir(target_path):
import shutil
shutil.rmtree(target_path)
return getInstalledLanguagePacks()
return getInstalledLanguagePacks()
def _unpack_uploaded_zipfile(path, target):
with zipfile.ZipFile(path, "r") as zip:
# sanity check
map(_validate_archive_name, zip.namelist())
with zipfile.ZipFile(path, "r") as zip:
# sanity check
map(_validate_archive_name, zip.namelist())
# unpack everything
zip.extractall(target)
# unpack everything
zip.extractall(target)
def _unpack_uploaded_tarball(path, target):
with tarfile.open(path, "r") as tar:
# sanity check
map(_validate_archive_name, tar.getmembers())
with tarfile.open(path, "r") as tar:
# sanity check
map(_validate_archive_name, tar.getmembers())
# unpack everything
tar.extractall(target)
# unpack everything
tar.extractall(target)
def _validate_archive_name(name):
if name.startswith("/") or ".." in name:
raise InvalidLanguagePack("Provided language pack contains invalid name {name}".format(**locals()))
if name.startswith("/") or ".." in name:
raise InvalidLanguagePack(
"Provided language pack contains invalid name {name}".format(**locals())
)
class InvalidLanguagePack(Exception):
pass
pass
+331 -326
View File
@@ -2,7 +2,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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"
from flask import request, jsonify, make_response, Response
@@ -20,152 +20,163 @@ from octoprint.printer import UnknownScript
from octoprint.access.permissions import Permissions
#~~ Printer
# ~~ Printer
@api.route("/printer", methods=["GET"])
@Permissions.STATUS.require(403)
def printerState():
if not printer.is_operational():
return make_response("Printer is not operational", 409)
if not printer.is_operational():
return make_response("Printer is not operational", 409)
# process excludes
excludes = []
if "exclude" in request.values:
excludeStr = request.values["exclude"]
if len(excludeStr.strip()) > 0:
excludes = list(filter(lambda x: x in ["temperature", "sd", "state"], map(lambda x: x.strip(), excludeStr.split(","))))
# process excludes
excludes = []
if "exclude" in request.values:
excludeStr = request.values["exclude"]
if len(excludeStr.strip()) > 0:
excludes = list(
filter(
lambda x: x in ["temperature", "sd", "state"],
map(lambda x: x.strip(), excludeStr.split(",")),
)
)
result = {}
result = {}
# add temperature information
if not "temperature" in excludes:
processor = lambda x: x
heated_bed = printerProfileManager.get_current_or_default()["heatedBed"]
heated_chamber = printerProfileManager.get_current_or_default()["heatedChamber"]
if not heated_bed and not heated_chamber:
processor = _keep_tools
elif not heated_bed:
processor = _delete_bed
elif not heated_chamber:
processor = _delete_chamber
# add temperature information
if not "temperature" in excludes:
processor = lambda x: x
heated_bed = printerProfileManager.get_current_or_default()["heatedBed"]
heated_chamber = printerProfileManager.get_current_or_default()["heatedChamber"]
if not heated_bed and not heated_chamber:
processor = _keep_tools
elif not heated_bed:
processor = _delete_bed
elif not heated_chamber:
processor = _delete_chamber
result.update({"temperature": _get_temperature_data(processor)})
result.update({"temperature": _get_temperature_data(processor)})
# add sd information
if not "sd" in excludes and settings().getBoolean(["feature", "sdSupport"]):
result.update({"sd": {"ready": printer.is_sd_ready()}})
# add sd information
if not "sd" in excludes and settings().getBoolean(["feature", "sdSupport"]):
result.update({"sd": {"ready": printer.is_sd_ready()}})
# add state information
if not "state" in excludes:
state = printer.get_current_data()["state"]
result.update({"state": state})
# add state information
if not "state" in excludes:
state = printer.get_current_data()["state"]
result.update({"state": state})
return jsonify(result)
return jsonify(result)
#~~ Tool
# ~~ Tool
@api.route("/printer/tool", methods=["POST"])
@no_firstrun_access
@Permissions.CONTROL.require(403)
def printerToolCommand():
if not printer.is_operational():
return make_response("Printer is not operational", 409)
if not printer.is_operational():
return make_response("Printer is not operational", 409)
valid_commands = {
"select": ["tool"],
"target": ["targets"],
"offset": ["offsets"],
"extrude": ["amount"],
"flowrate": ["factor"]
}
command, data, response = get_json_command_from_request(request, valid_commands)
if response is not None:
return response
valid_commands = {
"select": ["tool"],
"target": ["targets"],
"offset": ["offsets"],
"extrude": ["amount"],
"flowrate": ["factor"],
}
command, data, response = get_json_command_from_request(request, valid_commands)
if response is not None:
return response
validation_regex = re.compile(r"tool\d+")
validation_regex = re.compile(r"tool\d+")
tags = {"source:api", "api:printer.tool"}
tags = {"source:api", "api:printer.tool"}
##~~ tool selection
if command == "select":
tool = data["tool"]
if not isinstance(tool, basestring) or re.match(validation_regex, tool) is None:
return make_response("Invalid tool: %s" % tool, 400)
if not tool.startswith("tool"):
return make_response("Invalid tool for selection: %s" % tool, 400)
##~~ tool selection
if command == "select":
tool = data["tool"]
if not isinstance(tool, basestring) or re.match(validation_regex, tool) is None:
return make_response("Invalid tool: %s" % tool, 400)
if not tool.startswith("tool"):
return make_response("Invalid tool for selection: %s" % tool, 400)
printer.change_tool(tool, tags=tags)
printer.change_tool(tool, tags=tags)
##~~ temperature
elif command == "target":
targets = data["targets"]
##~~ temperature
elif command == "target":
targets = data["targets"]
# make sure the targets are valid and the values are numbers
validated_values = {}
for tool, value in targets.items():
if re.match(validation_regex, tool) is None:
return make_response("Invalid target for setting temperature: %s" % tool, 400)
if not isinstance(value, (int, long, float)):
return make_response("Not a number for %s: %r" % (tool, value), 400)
validated_values[tool] = value
# make sure the targets are valid and the values are numbers
validated_values = {}
for tool, value in targets.items():
if re.match(validation_regex, tool) is None:
return make_response(
"Invalid target for setting temperature: %s" % tool, 400
)
if not isinstance(value, (int, long, float)):
return make_response("Not a number for %s: %r" % (tool, value), 400)
validated_values[tool] = value
# perform the actual temperature commands
for tool in validated_values.keys():
printer.set_temperature(tool, validated_values[tool], tags=tags)
# perform the actual temperature commands
for tool in validated_values.keys():
printer.set_temperature(tool, validated_values[tool], tags=tags)
##~~ temperature offset
elif command == "offset":
offsets = data["offsets"]
##~~ temperature offset
elif command == "offset":
offsets = data["offsets"]
# make sure the targets are valid, the values are numbers and in the range [-50, 50]
validated_values = {}
for tool, value in offsets.items():
if re.match(validation_regex, tool) is None:
return make_response("Invalid target for setting temperature: %s" % tool, 400)
if not isinstance(value, (int, long, float)):
return make_response("Not a number for %s: %r" % (tool, value), 400)
if not -50 <= value <= 50:
return make_response("Offset %s not in range [-50, 50]: %f" % (tool, value), 400)
validated_values[tool] = value
# make sure the targets are valid, the values are numbers and in the range [-50, 50]
validated_values = {}
for tool, value in offsets.items():
if re.match(validation_regex, tool) is None:
return make_response(
"Invalid target for setting temperature: %s" % tool, 400
)
if not isinstance(value, (int, long, float)):
return make_response("Not a number for %s: %r" % (tool, value), 400)
if not -50 <= value <= 50:
return make_response(
"Offset %s not in range [-50, 50]: %f" % (tool, value), 400
)
validated_values[tool] = value
# set the offsets
printer.set_temperature_offset(validated_values)
# set the offsets
printer.set_temperature_offset(validated_values)
##~~ extrusion
elif command == "extrude":
if printer.is_printing():
# do not extrude when a print job is running
return make_response("Printer is currently printing", 409)
##~~ extrusion
elif command == "extrude":
if printer.is_printing():
# do not extrude when a print job is running
return make_response("Printer is currently printing", 409)
amount = data["amount"]
speed = data.get("speed", None)
if not isinstance(amount, (int, long, float)):
return make_response("Not a number for extrusion amount: %r" % amount, 400)
printer.extrude(amount, speed=speed, tags=tags)
amount = data["amount"]
speed = data.get("speed", None)
if not isinstance(amount, (int, long, float)):
return make_response("Not a number for extrusion amount: %r" % amount, 400)
printer.extrude(amount, speed=speed, tags=tags)
elif command == "flowrate":
factor = data["factor"]
if not isinstance(factor, (int, long, float)):
return make_response("Not a number for flow rate: %r" % factor, 400)
try:
printer.flow_rate(factor, tags=tags)
except ValueError as e:
return make_response("Invalid value for flow rate: %s" % str(e), 400)
elif command == "flowrate":
factor = data["factor"]
if not isinstance(factor, (int, long, float)):
return make_response("Not a number for flow rate: %r" % factor, 400)
try:
printer.flow_rate(factor, tags=tags)
except ValueError as e:
return make_response("Invalid value for flow rate: %s" % str(e), 400)
return NO_CONTENT
return NO_CONTENT
@api.route("/printer/tool", methods=["GET"])
@no_firstrun_access
@Permissions.STATUS.require(403)
def printerToolState():
if not printer.is_operational():
return make_response("Printer is not operational", 409)
if not printer.is_operational():
return make_response("Printer is not operational", 409)
return jsonify(_get_temperature_data(_keep_tools))
return jsonify(_get_temperature_data(_keep_tools))
##~~ Heated bed
@@ -175,64 +186,61 @@ def printerToolState():
@no_firstrun_access
@Permissions.CONTROL.require(403)
def printerBedCommand():
if not printer.is_operational():
return make_response("Printer is not operational", 409)
if not printer.is_operational():
return make_response("Printer is not operational", 409)
if not printerProfileManager.get_current_or_default()["heatedBed"]:
return make_response("Printer does not have a heated bed", 409)
if not printerProfileManager.get_current_or_default()["heatedBed"]:
return make_response("Printer does not have a heated bed", 409)
valid_commands = {
"target": ["target"],
"offset": ["offset"]
}
command, data, response = get_json_command_from_request(request, valid_commands)
if response is not None:
return response
valid_commands = {"target": ["target"], "offset": ["offset"]}
command, data, response = get_json_command_from_request(request, valid_commands)
if response is not None:
return response
tags = {"source:api", "api:printer.bed"}
tags = {"source:api", "api:printer.bed"}
##~~ temperature
if command == "target":
target = data["target"]
##~~ temperature
if command == "target":
target = data["target"]
# make sure the target is a number
if not isinstance(target, (int, long, float)):
return make_response("Not a number: %r" % target, 400)
# make sure the target is a number
if not isinstance(target, (int, long, float)):
return make_response("Not a number: %r" % target, 400)
# perform the actual temperature command
printer.set_temperature("bed", target, tags=tags)
# perform the actual temperature command
printer.set_temperature("bed", target, tags=tags)
##~~ temperature offset
elif command == "offset":
offset = data["offset"]
##~~ temperature offset
elif command == "offset":
offset = data["offset"]
# make sure the offset is valid
if not isinstance(offset, (int, long, float)):
return make_response("Not a number: %r" % offset, 400)
if not -50 <= offset <= 50:
return make_response("Offset not in range [-50, 50]: %f" % offset, 400)
# make sure the offset is valid
if not isinstance(offset, (int, long, float)):
return make_response("Not a number: %r" % offset, 400)
if not -50 <= offset <= 50:
return make_response("Offset not in range [-50, 50]: %f" % offset, 400)
# set the offsets
printer.set_temperature_offset({"bed": offset})
# set the offsets
printer.set_temperature_offset({"bed": offset})
return NO_CONTENT
return NO_CONTENT
@api.route("/printer/bed", methods=["GET"])
@no_firstrun_access
@Permissions.STATUS.require(403)
def printerBedState():
if not printer.is_operational():
return make_response("Printer is not operational", 409)
if not printer.is_operational():
return make_response("Printer is not operational", 409)
if not printerProfileManager.get_current_or_default()["heatedBed"]:
return make_response("Printer does not have a heated bed", 409)
if not printerProfileManager.get_current_or_default()["heatedBed"]:
return make_response("Printer does not have a heated bed", 409)
data = _get_temperature_data(_keep_bed)
if isinstance(data, Response):
return data
else:
return jsonify(data)
data = _get_temperature_data(_keep_bed)
if isinstance(data, Response):
return data
else:
return jsonify(data)
##~~ Heated chamber
@@ -242,64 +250,61 @@ def printerBedState():
@no_firstrun_access
@Permissions.CONTROL.require(403)
def printerChamberCommand():
if not printer.is_operational():
return make_response("Printer is not operational", 409)
if not printer.is_operational():
return make_response("Printer is not operational", 409)
if not printerProfileManager.get_current_or_default()["heatedChamber"]:
return make_response("Printer does not have a heated chamber", 409)
if not printerProfileManager.get_current_or_default()["heatedChamber"]:
return make_response("Printer does not have a heated chamber", 409)
valid_commands = {
"target": ["target"],
"offset": ["offset"]
}
command, data, response = get_json_command_from_request(request, valid_commands)
if response is not None:
return response
valid_commands = {"target": ["target"], "offset": ["offset"]}
command, data, response = get_json_command_from_request(request, valid_commands)
if response is not None:
return response
tags = {"source:api", "api:printer.chamber"}
tags = {"source:api", "api:printer.chamber"}
##~~ temperature
if command == "target":
target = data["target"]
##~~ temperature
if command == "target":
target = data["target"]
# make sure the target is a number
if not isinstance(target, (int, long, float)):
return make_response("Not a number: %r" % target, 400)
# make sure the target is a number
if not isinstance(target, (int, long, float)):
return make_response("Not a number: %r" % target, 400)
# perform the actual temperature command
printer.set_temperature("chamber", target, tags=tags)
# perform the actual temperature command
printer.set_temperature("chamber", target, tags=tags)
##~~ temperature offset
elif command == "offset":
offset = data["offset"]
##~~ temperature offset
elif command == "offset":
offset = data["offset"]
# make sure the offset is valid
if not isinstance(offset, (int, long, float)):
return make_response("Not a number: %r" % offset, 400)
if not -50 <= offset <= 50:
return make_response("Offset not in range [-50, 50]: %f" % offset, 400)
# make sure the offset is valid
if not isinstance(offset, (int, long, float)):
return make_response("Not a number: %r" % offset, 400)
if not -50 <= offset <= 50:
return make_response("Offset not in range [-50, 50]: %f" % offset, 400)
# set the offsets
printer.set_temperature_offset({"chamber": offset})
# set the offsets
printer.set_temperature_offset({"chamber": offset})
return NO_CONTENT
return NO_CONTENT
@api.route("/printer/chamber", methods=["GET"])
@no_firstrun_access
@Permissions.STATUS.require(403)
def printerChamberState():
if not printer.is_operational():
return make_response("Printer is not operational", 409)
if not printer.is_operational():
return make_response("Printer is not operational", 409)
if not printerProfileManager.get_current_or_default()["heatedChamber"]:
return make_response("Printer does not have a heated chamber", 409)
if not printerProfileManager.get_current_or_default()["heatedChamber"]:
return make_response("Printer does not have a heated chamber", 409)
data = _get_temperature_data(_keep_chamber)
if isinstance(data, Response):
return data
else:
return jsonify(data)
data = _get_temperature_data(_keep_chamber)
if isinstance(data, Response):
return data
else:
return jsonify(data)
##~~ Print head
@@ -309,61 +314,59 @@ def printerChamberState():
@no_firstrun_access
@Permissions.CONTROL.require(403)
def printerPrintheadCommand():
valid_commands = {
"jog": [],
"home": ["axes"],
"feedrate": ["factor"]
}
command, data, response = get_json_command_from_request(request, valid_commands)
if response is not None:
return response
valid_commands = {"jog": [], "home": ["axes"], "feedrate": ["factor"]}
command, data, response = get_json_command_from_request(request, valid_commands)
if response is not None:
return response
if not printer.is_operational() or (printer.is_printing() and command != "feedrate"):
# do not jog when a print job is running or we don't have a connection
return make_response("Printer is not operational or currently printing", 409)
if not printer.is_operational() or (printer.is_printing() and command != "feedrate"):
# do not jog when a print job is running or we don't have a connection
return make_response("Printer is not operational or currently printing", 409)
tags = {"source:api", "api:printer.printhead"}
tags = {"source:api", "api:printer.printhead"}
valid_axes = ["x", "y", "z"]
##~~ jog command
if command == "jog":
# validate all jog instructions, make sure that the values are numbers
validated_values = {}
for axis in valid_axes:
if axis in data:
value = data[axis]
if not isinstance(value, (int, long, float)):
return make_response("Not a number for axis %s: %r" % (axis, value), 400)
validated_values[axis] = value
valid_axes = ["x", "y", "z"]
##~~ jog command
if command == "jog":
# validate all jog instructions, make sure that the values are numbers
validated_values = {}
for axis in valid_axes:
if axis in data:
value = data[axis]
if not isinstance(value, (int, long, float)):
return make_response(
"Not a number for axis %s: %r" % (axis, value), 400
)
validated_values[axis] = value
absolute = "absolute" in data and data["absolute"] in valid_boolean_trues
speed = data.get("speed", None)
absolute = "absolute" in data and data["absolute"] in valid_boolean_trues
speed = data.get("speed", None)
# execute the jog commands
printer.jog(validated_values, relative=not absolute, speed=speed, tags=tags)
# execute the jog commands
printer.jog(validated_values, relative=not absolute, speed=speed, tags=tags)
##~~ home command
elif command == "home":
validated_values = []
axes = data["axes"]
for axis in axes:
if not axis in valid_axes:
return make_response("Invalid axis: %s" % axis, 400)
validated_values.append(axis)
##~~ home command
elif command == "home":
validated_values = []
axes = data["axes"]
for axis in axes:
if not axis in valid_axes:
return make_response("Invalid axis: %s" % axis, 400)
validated_values.append(axis)
# execute the home command
printer.home(validated_values, tags=tags)
# execute the home command
printer.home(validated_values, tags=tags)
elif command == "feedrate":
factor = data["factor"]
if not isinstance(factor, (int, long, float)):
return make_response("Not a number for feed rate: %r" % factor, 400)
try:
printer.feed_rate(factor, tags=tags)
except ValueError as e:
return make_response("Invalid value for feed rate: %s" % str(e), 400)
elif command == "feedrate":
factor = data["factor"]
if not isinstance(factor, (int, long, float)):
return make_response("Not a number for feed rate: %r" % factor, 400)
try:
printer.feed_rate(factor, tags=tags)
except ValueError as e:
return make_response("Invalid value for feed rate: %s" % str(e), 400)
return NO_CONTENT
return NO_CONTENT
##~~ SD Card
@@ -373,41 +376,37 @@ def printerPrintheadCommand():
@no_firstrun_access
@Permissions.CONTROL.require(403)
def printerSdCommand():
if not settings().getBoolean(["feature", "sdSupport"]):
return make_response("SD support is disabled", 404)
if not settings().getBoolean(["feature", "sdSupport"]):
return make_response("SD support is disabled", 404)
if not printer.is_operational() or printer.is_printing() or printer.is_paused():
return make_response("Printer is not operational or currently busy", 409)
if not printer.is_operational() or printer.is_printing() or printer.is_paused():
return make_response("Printer is not operational or currently busy", 409)
valid_commands = {
"init": [],
"refresh": [],
"release": []
}
command, data, response = get_json_command_from_request(request, valid_commands)
if response is not None:
return response
valid_commands = {"init": [], "refresh": [], "release": []}
command, data, response = get_json_command_from_request(request, valid_commands)
if response is not None:
return response
tags = {"source:api", "api:printer.sd"}
tags = {"source:api", "api:printer.sd"}
if command == "init":
printer.init_sd_card(tags=tags)
elif command == "refresh":
printer.refresh_sd_files(tags=tags)
elif command == "release":
printer.release_sd_card(tags=tags)
if command == "init":
printer.init_sd_card(tags=tags)
elif command == "refresh":
printer.refresh_sd_files(tags=tags)
elif command == "release":
printer.release_sd_card(tags=tags)
return NO_CONTENT
return NO_CONTENT
@api.route("/printer/sd", methods=["GET"])
@no_firstrun_access
@Permissions.STATUS.require(403)
def printerSdState():
if not settings().getBoolean(["feature", "sdSupport"]):
return make_response("SD support is disabled", 404)
if not settings().getBoolean(["feature", "sdSupport"]):
return make_response("SD support is disabled", 404)
return jsonify(ready=printer.is_sd_ready())
return jsonify(ready=printer.is_sd_ready())
##~~ Commands
@@ -417,116 +416,122 @@ def printerSdState():
@no_firstrun_access
@Permissions.CONTROL.require(403)
def printerCommand():
if not printer.is_operational():
return make_response("Printer is not operational", 409)
if not printer.is_operational():
return make_response("Printer is not operational", 409)
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content type JSON", 400)
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content type JSON", 400)
try:
data = request.get_json()
except BadRequest:
return make_response("Malformed JSON body in request", 400)
try:
data = request.get_json()
except BadRequest:
return make_response("Malformed JSON body in request", 400)
if data is None:
return make_response("Malformed JSON body in request", 400)
if data is None:
return make_response("Malformed JSON body in request", 400)
if "command" in data and "commands" in data:
return make_response("'command' and 'commands' are mutually exclusive", 400)
elif ("command" in data or "commands" in data) and "script" in data:
return make_response("'command'/'commands' and 'script' are mutually exclusive", 400)
elif not ("command" in data or "commands" in data or "script" in data):
return make_response("Need one of 'command', 'commands' or 'script'", 400)
if "command" in data and "commands" in data:
return make_response("'command' and 'commands' are mutually exclusive", 400)
elif ("command" in data or "commands" in data) and "script" in data:
return make_response(
"'command'/'commands' and 'script' are mutually exclusive", 400
)
elif not ("command" in data or "commands" in data or "script" in data):
return make_response("Need one of 'command', 'commands' or 'script'", 400)
parameters = {}
if "parameters" in data:
parameters = data["parameters"]
parameters = {}
if "parameters" in data:
parameters = data["parameters"]
tags = {"source:api", "api:printer.command"}
tags = {"source:api", "api:printer.command"}
if "command" in data or "commands" in data:
if "command" in data:
commands = [data["command"]]
else:
if not isinstance(data["commands"], (list, tuple)):
return make_response("'commands' needs to be a list", 400)
commands = data["commands"]
if "command" in data or "commands" in data:
if "command" in data:
commands = [data["command"]]
else:
if not isinstance(data["commands"], (list, tuple)):
return make_response("'commands' needs to be a list", 400)
commands = data["commands"]
commandsToSend = []
for command in commands:
commandToSend = command
if len(parameters) > 0:
commandToSend = command % parameters
commandsToSend.append(commandToSend)
commandsToSend = []
for command in commands:
commandToSend = command
if len(parameters) > 0:
commandToSend = command % parameters
commandsToSend.append(commandToSend)
printer.commands(commandsToSend, tags=tags)
printer.commands(commandsToSend, tags=tags)
elif "script" in data:
script_name = data["script"]
context = {"parameters": parameters}
if "context" in data:
context["context"] = data["context"]
elif "script" in data:
script_name = data["script"]
context = {"parameters": parameters}
if "context" in data:
context["context"] = data["context"]
try:
printer.script(script_name, context=context, tags=tags)
except UnknownScript:
return make_response("Unknown script: {script_name}".format(**locals()), 404)
try:
printer.script(script_name, context=context, tags=tags)
except UnknownScript:
return make_response("Unknown script: {script_name}".format(**locals()), 404)
return NO_CONTENT
return NO_CONTENT
@api.route("/printer/command/custom", methods=["GET"])
@no_firstrun_access
@Permissions.CONTROL.require(403)
def getCustomControls():
customControls = settings().get(["controls"])
return jsonify(controls=customControls)
customControls = settings().get(["controls"])
return jsonify(controls=customControls)
def _get_temperature_data(preprocessor):
if not printer.is_operational():
return make_response("Printer is not operational", 409)
if not printer.is_operational():
return make_response("Printer is not operational", 409)
tempData = printer.get_current_temperatures()
tempData = printer.get_current_temperatures()
if "history" in request.values and request.values["history"] in valid_boolean_trues:
tempHistory = printer.get_temperature_history()
if "history" in request.values and request.values["history"] in valid_boolean_trues:
tempHistory = printer.get_temperature_history()
limit = 300
if "limit" in request.values and unicode(request.values["limit"]).isnumeric():
limit = int(request.values["limit"])
limit = 300
if "limit" in request.values and unicode(request.values["limit"]).isnumeric():
limit = int(request.values["limit"])
history = list(tempHistory)
limit = min(limit, len(history))
history = list(tempHistory)
limit = min(limit, len(history))
tempData.update({
"history": list(map(lambda x: preprocessor(x), history[-limit:]))
})
tempData.update(
{"history": list(map(lambda x: preprocessor(x), history[-limit:]))}
)
return preprocessor(tempData)
return preprocessor(tempData)
def _keep_tools(x):
return _delete_from_data(x, lambda k: not k.startswith("tool") and k != "history")
return _delete_from_data(x, lambda k: not k.startswith("tool") and k != "history")
def _keep_bed(x):
return _delete_from_data(x, lambda k: k != "bed" and k != "history")
return _delete_from_data(x, lambda k: k != "bed" and k != "history")
def _delete_bed(x):
return _delete_from_data(x, lambda k: k == "bed")
return _delete_from_data(x, lambda k: k == "bed")
def _keep_chamber(x):
return _delete_from_data(x, lambda k: k != "chamber" and k != "history")
return _delete_from_data(x, lambda k: k != "chamber" and k != "history")
def _delete_chamber(x):
return _delete_from_data(x, lambda k: k == "chamber")
return _delete_from_data(x, lambda k: k == "chamber")
def _delete_from_data(x, key_matcher):
data = dict(x)
# must make list of keys first to avoid
# RuntimeError: dictionary changed size during iteration
for k in list(data.keys()):
if key_matcher(k):
del data[k]
return data
data = dict(x)
# must make list of keys first to avoid
# RuntimeError: dictionary changed size during iteration
for k in list(data.keys()):
if key_matcher(k):
del data[k]
return data
+144 -115
View File
@@ -2,7 +2,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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"
@@ -21,171 +21,200 @@ from octoprint.server import printerProfileManager
from octoprint.printer.profile import InvalidProfileError, CouldNotOverwriteError
from octoprint.access.permissions import Permissions
def _lastmodified():
return printerProfileManager.last_modified
return printerProfileManager.last_modified
def _etag(lm=None):
if lm is None:
lm = _lastmodified()
if lm is None:
lm = _lastmodified()
import hashlib
hash = hashlib.sha1()
def hash_update(value):
value = value.encode('utf-8')
hash.update(value)
hash_update(str(lm))
hash_update(repr(printerProfileManager.get_default()))
hash_update(repr(printerProfileManager.get_current()))
return hash.hexdigest()
import hashlib
hash = hashlib.sha1()
def hash_update(value):
value = value.encode("utf-8")
hash.update(value)
hash_update(str(lm))
hash_update(repr(printerProfileManager.get_default()))
hash_update(repr(printerProfileManager.get_current()))
return hash.hexdigest()
@api.route("/printerprofiles", methods=["GET"])
@with_revalidation_checking(etag_factory=_etag,
lastmodified_factory=_lastmodified,
unless=lambda: request.values.get("force", "false") in valid_boolean_trues)
@with_revalidation_checking(
etag_factory=_etag,
lastmodified_factory=_lastmodified,
unless=lambda: request.values.get("force", "false") in valid_boolean_trues,
)
@no_firstrun_access
@Permissions.CONNECTION.require(403)
def printerProfilesList():
all_profiles = printerProfileManager.get_all()
return jsonify({"profiles": _convert_profiles(all_profiles)})
all_profiles = printerProfileManager.get_all()
return jsonify({"profiles": _convert_profiles(all_profiles)})
@api.route("/printerprofiles", methods=["POST"])
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def printerProfilesAdd():
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
try:
json_data = request.get_json()
except BadRequest:
return make_response("Malformed JSON body in request", 400)
try:
json_data = request.get_json()
except BadRequest:
return make_response("Malformed JSON body in request", 400)
if json_data is None:
return make_response("Malformed JSON body in request", 400)
if json_data is None:
return make_response("Malformed JSON body in request", 400)
if not "profile" in json_data:
return make_response("No profile included in request", 400)
if not "profile" in json_data:
return make_response("No profile included in request", 400)
base_profile = printerProfileManager.get_default()
if "basedOn" in json_data and isinstance(json_data["basedOn"], basestring):
other_profile = printerProfileManager.get(json_data["basedOn"])
if other_profile is not None:
base_profile = other_profile
base_profile = printerProfileManager.get_default()
if "basedOn" in json_data and isinstance(json_data["basedOn"], basestring):
other_profile = printerProfileManager.get(json_data["basedOn"])
if other_profile is not None:
base_profile = other_profile
if "id" in base_profile:
del base_profile["id"]
if "name" in base_profile:
del base_profile["name"]
if "default" in base_profile:
del base_profile["default"]
if "id" in base_profile:
del base_profile["id"]
if "name" in base_profile:
del base_profile["name"]
if "default" in base_profile:
del base_profile["default"]
new_profile = json_data["profile"]
make_default = False
if "default" in new_profile:
make_default = True
del new_profile["default"]
new_profile = json_data["profile"]
make_default = False
if "default" in new_profile:
make_default = True
del new_profile["default"]
profile = dict_merge(base_profile, new_profile)
profile = dict_merge(base_profile, new_profile)
if not "id" in profile:
return make_response("Profile does not contain mandatory 'id' field", 400)
if not "name" in profile:
return make_response("Profile does not contain mandatory 'name' field", 400)
if not "id" in profile:
return make_response("Profile does not contain mandatory 'id' field", 400)
if not "name" in profile:
return make_response("Profile does not contain mandatory 'name' field", 400)
try:
saved_profile = printerProfileManager.save(
profile, allow_overwrite=False, make_default=make_default, trigger_event=True
)
except InvalidProfileError:
return make_response("Profile is invalid", 400)
except CouldNotOverwriteError:
return make_response(
"Profile {} already exists and overwriting was not allowed".format(
profile["id"]
),
400,
)
except Exception as e:
return make_response("Could not save profile: %s" % str(e), 500)
else:
return jsonify({"profile": _convert_profile(saved_profile)})
try:
saved_profile = printerProfileManager.save(profile, allow_overwrite=False, make_default=make_default,
trigger_event=True)
except InvalidProfileError:
return make_response("Profile is invalid", 400)
except CouldNotOverwriteError:
return make_response("Profile {} already exists and overwriting was not allowed".format(profile["id"]), 400)
except Exception as e:
return make_response("Could not save profile: %s" % str(e), 500)
else:
return jsonify({"profile": _convert_profile(saved_profile)})
@api.route("/printerprofiles/<string:identifier>", methods=["GET"])
@no_firstrun_access
@Permissions.CONNECTION.require(403)
def printerProfilesGet(identifier):
profile = printerProfileManager.get(identifier)
if profile is None:
return make_response("Unknown profile: %s" % identifier, 404)
else:
return jsonify(_convert_profile(profile))
profile = printerProfileManager.get(identifier)
if profile is None:
return make_response("Unknown profile: %s" % identifier, 404)
else:
return jsonify(_convert_profile(profile))
@api.route("/printerprofiles/<string:identifier>", methods=["DELETE"])
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def printerProfilesDelete(identifier):
current_profile = printerProfileManager.get_current()
if current_profile and current_profile["id"] == identifier:
return make_response("Cannot delete currently selected profile: {}".format(identifier), 409)
current_profile = printerProfileManager.get_current()
if current_profile and current_profile["id"] == identifier:
return make_response(
"Cannot delete currently selected profile: {}".format(identifier), 409
)
default_profile = printerProfileManager.get_default()
if default_profile and default_profile["id"] == identifier:
return make_response("Cannot delete default profile: {}".format(identifier), 409)
default_profile = printerProfileManager.get_default()
if default_profile and default_profile["id"] == identifier:
return make_response("Cannot delete default profile: {}".format(identifier), 409)
printerProfileManager.remove(identifier, trigger_event=True)
return NO_CONTENT
printerProfileManager.remove(identifier, trigger_event=True)
return NO_CONTENT
@api.route("/printerprofiles/<string:identifier>", methods=["PATCH"])
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def printerProfilesUpdate(identifier):
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
try:
json_data = request.get_json()
except BadRequest:
return make_response("Malformed JSON body in request", 400)
try:
json_data = request.get_json()
except BadRequest:
return make_response("Malformed JSON body in request", 400)
if json_data is None:
return make_response("Malformed JSON body in request", 400)
if json_data is None:
return make_response("Malformed JSON body in request", 400)
if not "profile" in json_data:
return make_response("No profile included in request", 400)
if not "profile" in json_data:
return make_response("No profile included in request", 400)
profile = printerProfileManager.get(identifier)
if profile is None:
profile = printerProfileManager.get_default()
profile = printerProfileManager.get(identifier)
if profile is None:
profile = printerProfileManager.get_default()
new_profile = json_data["profile"]
merged_profile = dict_merge(profile, new_profile)
new_profile = json_data["profile"]
merged_profile = dict_merge(profile, new_profile)
make_default = False
if "default" in merged_profile:
make_default = True
del new_profile["default"]
make_default = False
if "default" in merged_profile:
make_default = True
del new_profile["default"]
merged_profile["id"] = identifier
merged_profile["id"] = identifier
try:
saved_profile = printerProfileManager.save(
merged_profile,
allow_overwrite=True,
make_default=make_default,
trigger_event=True,
)
except InvalidProfileError:
return make_response("Profile is invalid", 400)
except CouldNotOverwriteError:
return make_response(
"Profile already exists and overwriting was not allowed", 400
)
except Exception as e:
return make_response("Could not save profile: %s" % str(e), 500)
else:
return jsonify({"profile": _convert_profile(saved_profile)})
try:
saved_profile = printerProfileManager.save(merged_profile, allow_overwrite=True, make_default=make_default,
trigger_event=True)
except InvalidProfileError:
return make_response("Profile is invalid", 400)
except CouldNotOverwriteError:
return make_response("Profile already exists and overwriting was not allowed", 400)
except Exception as e:
return make_response("Could not save profile: %s" % str(e), 500)
else:
return jsonify({"profile": _convert_profile(saved_profile)})
def _convert_profiles(profiles):
result = {}
for identifier, profile in profiles.items():
result[identifier] = _convert_profile(profile)
return result
result = {}
for identifier, profile in profiles.items():
result[identifier] = _convert_profile(profile)
return result
def _convert_profile(profile):
default = printerProfileManager.get_default()["id"]
current = printerProfileManager.get_current_or_default()["id"]
default = printerProfileManager.get_default()["id"]
current = printerProfileManager.get_current_or_default()["id"]
converted = copy.deepcopy(profile)
converted["resource"] = url_for(".printerProfilesGet", identifier=profile["id"], _external=True)
converted["default"] = (profile["id"] == default)
converted["current"] = (profile["id"] == current)
return converted
converted = copy.deepcopy(profile)
converted["resource"] = url_for(
".printerProfilesGet", identifier=profile["id"], _external=True
)
converted["default"] = profile["id"] == default
converted["current"] = profile["id"] == current
return converted
File diff suppressed because it is too large. Load diff
+214 -153
View File
@@ -2,7 +2,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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"
from flask import request, jsonify, make_response, url_for
@@ -15,228 +15,289 @@ from octoprint.access.permissions import Permissions
from octoprint.settings import settings as s, valid_boolean_trues
from octoprint.slicing import UnknownSlicer, SlicerNotConfigured, UnknownProfile, CouldNotDeleteProfile
from octoprint.slicing import (
UnknownSlicer,
SlicerNotConfigured,
UnknownProfile,
CouldNotDeleteProfile,
)
_DATA_FORMAT_VERSION = "v2"
def _lastmodified(configured):
if configured:
slicers = slicingManager.configured_slicers
else:
slicers = slicingManager.registered_slicers
if configured:
slicers = slicingManager.configured_slicers
else:
slicers = slicingManager.registered_slicers
lms = [0]
for slicer in slicers:
lms.append(slicingManager.profiles_last_modified(slicer))
lms = [0]
for slicer in slicers:
lms.append(slicingManager.profiles_last_modified(slicer))
return max(lms)
return max(lms)
def _etag(configured, lm=None):
if lm is None:
lm = _lastmodified(configured)
if lm is None:
lm = _lastmodified(configured)
import hashlib
hash = hashlib.sha1()
def hash_update(value):
value = value.encode('utf-8')
hash.update(value)
hash_update(str(lm))
import hashlib
if configured:
slicers = slicingManager.configured_slicers
else:
slicers = slicingManager.registered_slicers
hash = hashlib.sha1()
default_slicer = s().get(["slicing", "defaultSlicer"])
def hash_update(value):
value = value.encode("utf-8")
hash.update(value)
for slicer in sorted(slicers):
slicer_impl = slicingManager.get_slicer(slicer, require_configured=False)
hash_update(slicer)
hash_update(str(slicer_impl.is_slicer_configured()))
hash_update(str(slicer == default_slicer))
hash_update(str(lm))
hash_update(_DATA_FORMAT_VERSION) # increment version if we change the API format
if configured:
slicers = slicingManager.configured_slicers
else:
slicers = slicingManager.registered_slicers
return hash.hexdigest()
default_slicer = s().get(["slicing", "defaultSlicer"])
for slicer in sorted(slicers):
slicer_impl = slicingManager.get_slicer(slicer, require_configured=False)
hash_update(slicer)
hash_update(str(slicer_impl.is_slicer_configured()))
hash_update(str(slicer == default_slicer))
hash_update(_DATA_FORMAT_VERSION) # increment version if we change the API format
return hash.hexdigest()
@api.route("/slicing", methods=["GET"])
@with_revalidation_checking(etag_factory=lambda lm=None: _etag(request.values.get("configured", "false") in valid_boolean_trues, lm=lm),
lastmodified_factory=lambda: _lastmodified(request.values.get("configured", "false") in valid_boolean_trues),
unless=lambda: request.values.get("force", "false") in valid_boolean_trues)
@with_revalidation_checking(
etag_factory=lambda lm=None: _etag(
request.values.get("configured", "false") in valid_boolean_trues, lm=lm
),
lastmodified_factory=lambda: _lastmodified(
request.values.get("configured", "false") in valid_boolean_trues
),
unless=lambda: request.values.get("force", "false") in valid_boolean_trues,
)
@Permissions.SLICE.require(403)
def slicingListAll():
from octoprint.filemanager import get_extensions
from octoprint.filemanager import get_extensions
default_slicer = s().get(["slicing", "defaultSlicer"])
default_slicer = s().get(["slicing", "defaultSlicer"])
if "configured" in request.values and request.values["configured"] in valid_boolean_trues:
slicers = slicingManager.configured_slicers
else:
slicers = slicingManager.registered_slicers
if (
"configured" in request.values
and request.values["configured"] in valid_boolean_trues
):
slicers = slicingManager.configured_slicers
else:
slicers = slicingManager.registered_slicers
result = {}
for slicer in slicers:
try:
slicer_impl = slicingManager.get_slicer(slicer, require_configured=False)
result = {}
for slicer in slicers:
try:
slicer_impl = slicingManager.get_slicer(slicer, require_configured=False)
extensions = set()
for source_file_type in slicer_impl.get_slicer_properties().get("source_file_types", ["model"]):
extensions = extensions.union(get_extensions(source_file_type))
extensions = set()
for source_file_type in slicer_impl.get_slicer_properties().get(
"source_file_types", ["model"]
):
extensions = extensions.union(get_extensions(source_file_type))
result[slicer] = {"key": slicer,
"displayName": slicer_impl.get_slicer_properties().get("name", "n/a"),
"sameDevice": slicer_impl.get_slicer_properties().get("same_device", True),
"default": default_slicer == slicer,
"configured": slicer_impl.is_slicer_configured(),
"profiles": _getSlicingProfilesData(slicer),
"extensions": {"source": list(extensions),
"destination": slicer_impl.get_slicer_properties().get("destination_extensions", ["gco", "gcode", "g"])}}
except (UnknownSlicer, SlicerNotConfigured):
# this should never happen
pass
result[slicer] = {
"key": slicer,
"displayName": slicer_impl.get_slicer_properties().get("name", "n/a"),
"sameDevice": slicer_impl.get_slicer_properties().get(
"same_device", True
),
"default": default_slicer == slicer,
"configured": slicer_impl.is_slicer_configured(),
"profiles": _getSlicingProfilesData(slicer),
"extensions": {
"source": list(extensions),
"destination": slicer_impl.get_slicer_properties().get(
"destination_extensions", ["gco", "gcode", "g"]
),
},
}
except (UnknownSlicer, SlicerNotConfigured):
# this should never happen
pass
return jsonify(result)
return jsonify(result)
@api.route("/slicing/<string:slicer>/profiles", methods=["GET"])
@no_firstrun_access
@Permissions.SLICE.require(403)
def slicingListSlicerProfiles(slicer):
configured = False
if "configured" in request.values and request.values["configured"] in valid_boolean_trues:
configured = True
configured = False
if (
"configured" in request.values
and request.values["configured"] in valid_boolean_trues
):
configured = True
try:
return jsonify(_getSlicingProfilesData(slicer, require_configured=configured))
except (UnknownSlicer, SlicerNotConfigured):
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
try:
return jsonify(_getSlicingProfilesData(slicer, require_configured=configured))
except (UnknownSlicer, SlicerNotConfigured):
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["GET"])
@no_firstrun_access
@Permissions.SLICE.require(403)
def slicingGetSlicerProfile(slicer, name):
try:
profile = slicingManager.load_profile(slicer, name, require_configured=False)
except UnknownSlicer:
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
except UnknownProfile:
return make_response("Profile not found", 404)
try:
profile = slicingManager.load_profile(slicer, name, require_configured=False)
except UnknownSlicer:
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
except UnknownProfile:
return make_response("Profile not found", 404)
result = _getSlicingProfileData(slicer, name, profile)
result["data"] = profile.data
return jsonify(result)
result = _getSlicingProfileData(slicer, name, profile)
result["data"] = profile.data
return jsonify(result)
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["PUT"])
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def slicingAddSlicerProfile(slicer, name):
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
try:
json_data = request.get_json()
except BadRequest:
return make_response("Malformed JSON body in request", 400)
try:
json_data = request.get_json()
except BadRequest:
return make_response("Malformed JSON body in request", 400)
if json_data is None:
return make_response("Malformed JSON body in request", 400)
if json_data is None:
return make_response("Malformed JSON body in request", 400)
data = {}
display_name = None
description = None
if "data" in json_data:
data = json_data["data"]
if "displayName" in json_data:
display_name = json_data["displayName"]
if "description" in json_data:
description = json_data["description"]
data = {}
display_name = None
description = None
if "data" in json_data:
data = json_data["data"]
if "displayName" in json_data:
display_name = json_data["displayName"]
if "description" in json_data:
description = json_data["description"]
try:
profile = slicingManager.save_profile(slicer, name, data,
allow_overwrite=True, display_name=display_name, description=description)
except UnknownSlicer:
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
try:
profile = slicingManager.save_profile(
slicer,
name,
data,
allow_overwrite=True,
display_name=display_name,
description=description,
)
except UnknownSlicer:
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
result = _getSlicingProfileData(slicer, name, profile)
r = make_response(jsonify(result), 201)
r.headers["Location"] = result["resource"]
return r
result = _getSlicingProfileData(slicer, name, profile)
r = make_response(jsonify(result), 201)
r.headers["Location"] = result["resource"]
return r
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["PATCH"])
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def slicingPatchSlicerProfile(slicer, name):
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
if not "application/json" in request.headers["Content-Type"]:
return make_response("Expected content-type JSON", 400)
try:
profile = slicingManager.load_profile(slicer, name, require_configured=False)
except UnknownSlicer:
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
except UnknownProfile:
return make_response("Profile {name} for slicer {slicer} not found".format(**locals()), 404)
try:
profile = slicingManager.load_profile(slicer, name, require_configured=False)
except UnknownSlicer:
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
except UnknownProfile:
return make_response(
"Profile {name} for slicer {slicer} not found".format(**locals()), 404
)
try:
json_data = request.get_json()
except BadRequest:
return make_response("Malformed JSON body in request", 400)
try:
json_data = request.get_json()
except BadRequest:
return make_response("Malformed JSON body in request", 400)
if json_data is None:
return make_response("Malformed JSON body in request", 400)
if json_data is None:
return make_response("Malformed JSON body in request", 400)
data = {}
display_name = None
description = None
if "data" in json_data:
data = json_data["data"]
if "displayName" in json_data:
display_name = json_data["displayName"]
if "description" in json_data:
description = json_data["description"]
data = {}
display_name = None
description = None
if "data" in json_data:
data = json_data["data"]
if "displayName" in json_data:
display_name = json_data["displayName"]
if "description" in json_data:
description = json_data["description"]
saved_profile = slicingManager.save_profile(slicer, name, profile,
allow_overwrite=True,
overrides=data,
display_name=display_name,
description=description)
saved_profile = slicingManager.save_profile(
slicer,
name,
profile,
allow_overwrite=True,
overrides=data,
display_name=display_name,
description=description,
)
from octoprint.server.api import valid_boolean_trues
if "default" in json_data and json_data["default"] in valid_boolean_trues:
slicingManager.set_default_profile(slicer, name, require_exists=False)
from octoprint.server.api import valid_boolean_trues
if "default" in json_data and json_data["default"] in valid_boolean_trues:
slicingManager.set_default_profile(slicer, name, require_exists=False)
return jsonify(_getSlicingProfileData(slicer, name, saved_profile))
return jsonify(_getSlicingProfileData(slicer, name, saved_profile))
@api.route("/slicing/<string:slicer>/profiles/<string:name>", methods=["DELETE"])
@no_firstrun_access
@Permissions.SETTINGS.require(403)
def slicingDelSlicerProfile(slicer, name):
try:
slicingManager.delete_profile(slicer, name)
except UnknownSlicer:
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
except CouldNotDeleteProfile as e:
return make_response("Could not delete profile {profile} for slicer {slicer}: {cause}".format(profile=name, slicer=slicer, cause=str(e.cause)), 500)
try:
slicingManager.delete_profile(slicer, name)
except UnknownSlicer:
return make_response("Unknown slicer {slicer}".format(**locals()), 404)
except CouldNotDeleteProfile as e:
return make_response(
"Could not delete profile {profile} for slicer {slicer}: {cause}".format(
profile=name, slicer=slicer, cause=str(e.cause)
),
500,
)
return NO_CONTENT
return NO_CONTENT
def _getSlicingProfilesData(slicer, require_configured=False):
profiles = slicingManager.all_profiles(slicer, require_configured=require_configured)
profiles = slicingManager.all_profiles(slicer, require_configured=require_configured)
result = {}
for name, profile in profiles.items():
result[name] = _getSlicingProfileData(slicer, name, profile)
return result
result = {}
for name, profile in profiles.items():
result[name] = _getSlicingProfileData(slicer, name, profile)
return result
def _getSlicingProfileData(slicer, name, profile):
defaultProfiles = s().get(["slicing", "defaultProfiles"])
result = {"key": name,
"default": defaultProfiles and slicer in defaultProfiles and defaultProfiles[slicer] == name,
"resource": url_for(".slicingGetSlicerProfile", slicer=slicer, name=name, _external=True)}
if profile.display_name is not None:
result["displayName"] = profile.display_name
if profile.description is not None:
result["description"] = profile.description
return result
defaultProfiles = s().get(["slicing", "defaultProfiles"])
result = {
"key": name,
"default": defaultProfiles
and slicer in defaultProfiles
and defaultProfiles[slicer] == name,
"resource": url_for(
".slicingGetSlicerProfile", slicer=slicer, name=name, _external=True
),
}
if profile.display_name is not None:
result["displayName"] = profile.display_name
if profile.description is not None:
result["description"] = profile.description
return result
+197 -150
View File
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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 collections
@@ -23,223 +23,270 @@ from octoprint.access.permissions import Permissions
from octoprint.logging import prefix_multilines
from octoprint.util.platform import CLOSE_FDS
@api.route("/system/usage", methods=["GET"])
@no_firstrun_access
@Permissions.SYSTEM.require(403)
def readUsageForFolders():
return jsonify(usage=_usageForFolders())
return jsonify(usage=_usageForFolders())
def _usageForFolders():
data = {}
for folder_name in s().get(['folder']).keys():
path = s().getBaseFolder(folder_name, check_writable=False)
if path is not None:
usage = psutil.disk_usage(path)
data[folder_name] = { 'free': usage.free, 'total': usage.total }
return data
data = {}
for folder_name in s().get(["folder"]).keys():
path = s().getBaseFolder(folder_name, check_writable=False)
if path is not None:
usage = psutil.disk_usage(path)
data[folder_name] = {"free": usage.free, "total": usage.total}
return data
@api.route("/system", methods=["POST"])
@no_firstrun_access
@Permissions.SYSTEM.require(403)
def performSystemAction():
logging.getLogger(__name__).warning("Deprecated API call to /api/system made by {}, should be migrated to use /system/commands/custom/<action>".format(get_remote_address(request)))
logging.getLogger(__name__).warning(
"Deprecated API call to /api/system made by {}, should be migrated to use /system/commands/custom/<action>".format(
get_remote_address(request)
)
)
data = request.get_json(silent=True)
if data is None:
data = request.values
data = request.get_json(silent=True)
if data is None:
data = request.values
if not "action" in data:
return make_response(u"action to perform is not defined", 400)
if not "action" in data:
return make_response("action to perform is not defined", 400)
return executeSystemCommand("custom", data["action"])
return executeSystemCommand("custom", data["action"])
@api.route("/system/commands", methods=["GET"])
@no_firstrun_access
@Permissions.SYSTEM.require(403)
def retrieveSystemCommands():
return jsonify(core=_to_client_specs(_get_core_command_specs()),
custom=_to_client_specs(_get_custom_command_specs()))
return jsonify(
core=_to_client_specs(_get_core_command_specs()),
custom=_to_client_specs(_get_custom_command_specs()),
)
@api.route("/system/commands/<string:source>", methods=["GET"])
@no_firstrun_access
@Permissions.SYSTEM.require(403)
def retrieveSystemCommandsForSource(source):
if source == "core":
specs = _get_core_command_specs()
elif source == "custom":
specs = _get_custom_command_specs()
else:
return make_response(u"Unknown system command source: {}".format(source), 404)
if source == "core":
specs = _get_core_command_specs()
elif source == "custom":
specs = _get_custom_command_specs()
else:
return make_response("Unknown system command source: {}".format(source), 404)
return jsonify(_to_client_specs(specs))
return jsonify(_to_client_specs(specs))
@api.route("/system/commands/<string:source>/<string:command>", methods=["POST"])
@no_firstrun_access
@Permissions.SYSTEM.require(403)
def executeSystemCommand(source, command):
logger = logging.getLogger(__name__)
logger = logging.getLogger(__name__)
if command == "divider":
return make_response("Dividers cannot be executed", 400)
if command == "divider":
return make_response("Dividers cannot be executed", 400)
command_spec = _get_command_spec(source, command)
if not command_spec:
return make_response(u"Command {}:{} not found".format(source, command), 404)
command_spec = _get_command_spec(source, command)
if not command_spec:
return make_response("Command {}:{} not found".format(source, command), 404)
if not "command" in command_spec:
return make_response(u"Command {}:{} does not define a command to execute, can't proceed".format(source, command), 500)
if not "command" in command_spec:
return make_response(
"Command {}:{} does not define a command to execute, can't proceed".format(
source, command
),
500,
)
do_async = command_spec.get("async", False)
do_ignore = command_spec.get("ignore", False)
debug = command_spec.get("debug", False)
do_async = command_spec.get("async", False)
do_ignore = command_spec.get("ignore", False)
debug = command_spec.get("debug", False)
if logger.isEnabledFor(logging.DEBUG) or debug:
logger.info(u"Performing command for {}:{}: {}".format(source, command, command_spec["command"]))
else:
logger.info(u"Performing command for {}:{}".format(source, command))
if logger.isEnabledFor(logging.DEBUG) or debug:
logger.info(
"Performing command for {}:{}: {}".format(
source, command, command_spec["command"]
)
)
else:
logger.info("Performing command for {}:{}".format(source, command))
try:
if "before" in command_spec and callable(command_spec["before"]):
command_spec["before"]()
except Exception as e:
if not do_ignore:
error = u"Command \"before\" for {}:{} failed: {}".format(source, command, e)
logger.warning(error)
return make_response(error, 500)
try:
if "before" in command_spec and callable(command_spec["before"]):
command_spec["before"]()
except Exception as e:
if not do_ignore:
error = 'Command "before" for {}:{} failed: {}'.format(source, command, e)
logger.warning(error)
return make_response(error, 500)
try:
def execute():
# we run this with shell=True since we have to trust whatever
# our admin configured as command and since we want to allow
# shell-alike handling here...
p = sarge.run(command_spec["command"],
close_fds=CLOSE_FDS,
stdout=sarge.Capture(),
stderr=sarge.Capture(),
shell=True)
try:
if not do_ignore and p.returncode != 0:
returncode = p.returncode
stdout_text = p.stdout.text
stderr_text = p.stderr.text
def execute():
# we run this with shell=True since we have to trust whatever
# our admin configured as command and since we want to allow
# shell-alike handling here...
p = sarge.run(
command_spec["command"],
close_fds=CLOSE_FDS,
stdout=sarge.Capture(),
stderr=sarge.Capture(),
shell=True,
)
error = "Command for {}:{} failed with return code {}:\nSTDOUT: {}\nSTDERR: {}".format(source, command,
returncode,
stdout_text,
stderr_text)
logger.warning(prefix_multilines(error, prefix="! "))
if not do_async:
raise CommandFailed(error)
if not do_ignore and p.returncode != 0:
returncode = p.returncode
stdout_text = p.stdout.text
stderr_text = p.stderr.text
if do_async:
thread = threading.Thread(target=execute)
thread.daemon = True
thread.start()
error = "Command for {}:{} failed with return code {}:\nSTDOUT: {}\nSTDERR: {}".format(
source, command, returncode, stdout_text, stderr_text
)
logger.warning(prefix_multilines(error, prefix="! "))
if not do_async:
raise CommandFailed(error)
else:
try:
execute()
except CommandFailed as exc:
return make_response(exc.error, 500)
if do_async:
thread = threading.Thread(target=execute)
thread.daemon = True
thread.start()
except Exception as e:
if not do_ignore:
error = "Command for {}:{} failed: {}".format(source, command, e)
logger.warning(error)
return make_response(error, 500)
else:
try:
execute()
except CommandFailed as exc:
return make_response(exc.error, 500)
except Exception as e:
if not do_ignore:
error = "Command for {}:{} failed: {}".format(source, command, e)
logger.warning(error)
return make_response(error, 500)
return NO_CONTENT
return NO_CONTENT
def _to_client_specs(specs):
result = list()
for spec in specs.values():
if not "action" in spec or not "source" in spec:
continue
copied = dict((k, v) for k, v in spec.items() if k in ("source", "action", "name", "confirm"))
copied["resource"] = url_for(".executeSystemCommand",
source=spec["source"],
command=spec["action"],
_external=True)
result.append(copied)
return result
result = list()
for spec in specs.values():
if not "action" in spec or not "source" in spec:
continue
copied = dict(
(k, v)
for k, v in spec.items()
if k in ("source", "action", "name", "confirm")
)
copied["resource"] = url_for(
".executeSystemCommand",
source=spec["source"],
command=spec["action"],
_external=True,
)
result.append(copied)
return result
def _get_command_spec(source, action):
if source == "core":
return _get_core_command_spec(action)
elif source == "custom":
return _get_custom_command_spec(action)
else:
return None
if source == "core":
return _get_core_command_spec(action)
elif source == "custom":
return _get_custom_command_spec(action)
else:
return None
def _get_core_command_specs():
def enable_safe_mode():
s().set(["server", "startOnceInSafeMode"], True)
s().save()
def enable_safe_mode():
s().set(["server", "startOnceInSafeMode"], True)
s().save()
commands = collections.OrderedDict(
shutdown={"command": s().get(["server", "commands", "systemShutdownCommand"]),
"name": gettext("Shutdown system"),
"confirm": gettext(u"<strong>You are about to shutdown the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).")},
reboot={"command": s().get(["server", "commands", "systemRestartCommand"]),
"name": gettext("Reboot system"),
"confirm": gettext(u"<strong>You are about to reboot the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).")},
restart={"command": s().get(["server", "commands", "serverRestartCommand"]),
"name": gettext("Restart OctoPrint"),
"confirm": gettext(u"<strong>You are about to restart the OctoPrint server.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage).")},
restart_safe={"command": s().get(["server", "commands", "serverRestartCommand"]),
"name": gettext("Restart OctoPrint in safe mode"),
"confirm": gettext(u"<strong>You are about to restart the OctoPrint server in safe mode.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."),
"before": enable_safe_mode}
)
commands = collections.OrderedDict(
shutdown={
"command": s().get(["server", "commands", "systemShutdownCommand"]),
"name": gettext("Shutdown system"),
"confirm": gettext(
"<strong>You are about to shutdown the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."
),
},
reboot={
"command": s().get(["server", "commands", "systemRestartCommand"]),
"name": gettext("Reboot system"),
"confirm": gettext(
"<strong>You are about to reboot the system.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."
),
},
restart={
"command": s().get(["server", "commands", "serverRestartCommand"]),
"name": gettext("Restart OctoPrint"),
"confirm": gettext(
"<strong>You are about to restart the OctoPrint server.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."
),
},
restart_safe={
"command": s().get(["server", "commands", "serverRestartCommand"]),
"name": gettext("Restart OctoPrint in safe mode"),
"confirm": gettext(
"<strong>You are about to restart the OctoPrint server in safe mode.</strong></p><p>This action may disrupt any ongoing print jobs (depending on your printer's controller and general setup that might also apply to prints run directly from your printer's internal storage)."
),
"before": enable_safe_mode,
},
)
available_commands = collections.OrderedDict()
for action, spec in commands.items():
if not spec["command"]:
continue
spec.update({'action': action, 'source': 'core', 'async': True, 'debug': True})
available_commands[action] = spec
return available_commands
available_commands = collections.OrderedDict()
for action, spec in commands.items():
if not spec["command"]:
continue
spec.update({"action": action, "source": "core", "async": True, "debug": True})
available_commands[action] = spec
return available_commands
def _get_core_command_spec(action):
available_actions = _get_core_command_specs()
if not action in available_actions:
logging.getLogger(__name__).warning(u"Command for core action {} is not configured, you need to configure the command before it can be used".format(action))
return None
available_actions = _get_core_command_specs()
if not action in available_actions:
logging.getLogger(__name__).warning(
"Command for core action {} is not configured, you need to configure the command before it can be used".format(
action
)
)
return None
return available_actions[action]
return available_actions[action]
def _get_custom_command_specs():
specs = collections.OrderedDict()
dividers = 0
for spec in s().get(["system", "actions"]):
if not "action" in spec:
continue
copied = dict(spec)
copied["source"] = "custom"
specs = collections.OrderedDict()
dividers = 0
for spec in s().get(["system", "actions"]):
if not "action" in spec:
continue
copied = dict(spec)
copied["source"] = "custom"
action = spec["action"]
if action == "divider":
dividers += 1
action = "divider_{}".format(dividers)
specs[action] = copied
return specs
action = spec["action"]
if action == "divider":
dividers += 1
action = "divider_{}".format(dividers)
specs[action] = copied
return specs
def _get_custom_command_spec(action):
available_actions = _get_custom_command_specs()
if not action in available_actions:
return None
available_actions = _get_custom_command_specs()
if not action in available_actions:
return None
return available_actions[action]
return available_actions[action]
class CommandFailed(Exception):
def __init__(self, error):
self.error = error
def __init__(self, error):
self.error = error
+214 -165
View File
@@ -2,7 +2,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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"
import os
@@ -16,7 +16,12 @@ import octoprint.util as util
from octoprint.settings import settings, valid_boolean_trues
from octoprint.server import admin_permission, printer
from octoprint.server.util.flask import redirect_to_tornado, no_firstrun_access, get_json_command_from_request, with_revalidation_checking
from octoprint.server.util.flask import (
redirect_to_tornado,
no_firstrun_access,
get_json_command_from_request,
with_revalidation_checking,
)
from octoprint.server.api import api
from octoprint.server import NO_CONTENT
@@ -24,7 +29,7 @@ from octoprint.access.permissions import Permissions
_DATA_FORMAT_VERSION = "v2"
#~~ timelapse handling
# ~~ timelapse handling
_timelapse_cache_finished = []
_timelapse_cache_finished_lastmodified = None
@@ -32,229 +37,273 @@ _timelapse_cache_unrendered = []
_timelapse_cache_unrendered_lastmodified = None
_timelapse_cache_mutex = threading.RLock()
def _config_for_timelapse(timelapse):
if timelapse is not None and isinstance(timelapse, octoprint.timelapse.ZTimelapse):
return {"type": "zchange",
"postRoll": timelapse.post_roll,
"fps": timelapse.fps,
"retractionZHop": timelapse.retraction_zhop,
"minDelay": timelapse.min_delay}
elif timelapse is not None and isinstance(timelapse, octoprint.timelapse.TimedTimelapse):
return {"type": "timed",
"postRoll": timelapse.post_roll,
"fps": timelapse.fps,
"interval": timelapse.interval}
else:
return {"type": "off"}
if timelapse is not None and isinstance(timelapse, octoprint.timelapse.ZTimelapse):
return {
"type": "zchange",
"postRoll": timelapse.post_roll,
"fps": timelapse.fps,
"retractionZHop": timelapse.retraction_zhop,
"minDelay": timelapse.min_delay,
}
elif timelapse is not None and isinstance(
timelapse, octoprint.timelapse.TimedTimelapse
):
return {
"type": "timed",
"postRoll": timelapse.post_roll,
"fps": timelapse.fps,
"interval": timelapse.interval,
}
else:
return {"type": "off"}
def _lastmodified(unrendered):
lm_finished = octoprint.timelapse.last_modified_finished()
if unrendered:
lm_unrendered = octoprint.timelapse.last_modified_unrendered()
lm_finished = octoprint.timelapse.last_modified_finished()
if unrendered:
lm_unrendered = octoprint.timelapse.last_modified_unrendered()
if lm_finished is None or lm_unrendered is None:
return None
return max(lm_finished, lm_unrendered)
return lm_finished
if lm_finished is None or lm_unrendered is None:
return None
return max(lm_finished, lm_unrendered)
return lm_finished
def _etag(unrendered, lm=None):
if lm is None:
lm = _lastmodified(unrendered)
if lm is None:
lm = _lastmodified(unrendered)
timelapse = octoprint.timelapse.current
config = _config_for_timelapse(timelapse)
timelapse = octoprint.timelapse.current
config = _config_for_timelapse(timelapse)
import hashlib
hash = hashlib.sha1()
def hash_update(value):
value = value.encode('utf-8')
hash.update(value)
hash_update(str(lm))
hash_update(repr(config))
hash_update(repr(_DATA_FORMAT_VERSION))
import hashlib
hash = hashlib.sha1()
def hash_update(value):
value = value.encode("utf-8")
hash.update(value)
hash_update(str(lm))
hash_update(repr(config))
hash_update(repr(_DATA_FORMAT_VERSION))
return hash.hexdigest()
return hash.hexdigest()
@api.route("/timelapse", methods=["GET"])
@with_revalidation_checking(etag_factory=lambda lm=None: _etag(request.values.get("unrendered", "false") in valid_boolean_trues, lm=lm),
lastmodified_factory=lambda: _lastmodified(request.values.get("unrendered", "false") in valid_boolean_trues),
unless=lambda: request.values.get("force", "false") in valid_boolean_trues)
@with_revalidation_checking(
etag_factory=lambda lm=None: _etag(
request.values.get("unrendered", "false") in valid_boolean_trues, lm=lm
),
lastmodified_factory=lambda: _lastmodified(
request.values.get("unrendered", "false") in valid_boolean_trues
),
unless=lambda: request.values.get("force", "false") in valid_boolean_trues,
)
@no_firstrun_access
@Permissions.TIMELAPSE_LIST.require(403)
def getTimelapseData():
timelapse = octoprint.timelapse.current
config = _config_for_timelapse(timelapse)
timelapse = octoprint.timelapse.current
config = _config_for_timelapse(timelapse)
force = request.values.get("force", "false") in valid_boolean_trues
unrendered = request.values.get("unrendered", "false") in valid_boolean_trues
force = request.values.get("force", "false") in valid_boolean_trues
unrendered = request.values.get("unrendered", "false") in valid_boolean_trues
global _timelapse_cache_finished_lastmodified, _timelapse_cache_finished, _timelapse_cache_unrendered_lastmodified, _timelapse_cache_unrendered
with _timelapse_cache_mutex:
current_lastmodified_finished = octoprint.timelapse.last_modified_finished()
current_lastmodified_unrendered = octoprint.timelapse.last_modified_unrendered()
global _timelapse_cache_finished_lastmodified, _timelapse_cache_finished, _timelapse_cache_unrendered_lastmodified, _timelapse_cache_unrendered
with _timelapse_cache_mutex:
current_lastmodified_finished = octoprint.timelapse.last_modified_finished()
current_lastmodified_unrendered = octoprint.timelapse.last_modified_unrendered()
if not force and _timelapse_cache_finished_lastmodified == current_lastmodified_finished:
files = _timelapse_cache_finished
else:
files = octoprint.timelapse.get_finished_timelapses()
_timelapse_cache_finished = files
_timelapse_cache_finished_lastmodified = current_lastmodified_finished
if (
not force
and _timelapse_cache_finished_lastmodified == current_lastmodified_finished
):
files = _timelapse_cache_finished
else:
files = octoprint.timelapse.get_finished_timelapses()
_timelapse_cache_finished = files
_timelapse_cache_finished_lastmodified = current_lastmodified_finished
unrendered_files = []
if unrendered:
if not force and _timelapse_cache_unrendered_lastmodified == current_lastmodified_unrendered:
unrendered_files = _timelapse_cache_unrendered
else:
unrendered_files = octoprint.timelapse.get_unrendered_timelapses()
_timelapse_cache_unrendered = unrendered_files
_timelapse_cache_unrendered_lastmodified = current_lastmodified_unrendered
unrendered_files = []
if unrendered:
if (
not force
and _timelapse_cache_unrendered_lastmodified
== current_lastmodified_unrendered
):
unrendered_files = _timelapse_cache_unrendered
else:
unrendered_files = octoprint.timelapse.get_unrendered_timelapses()
_timelapse_cache_unrendered = unrendered_files
_timelapse_cache_unrendered_lastmodified = current_lastmodified_unrendered
finished_list = []
for f in files:
output = dict(f)
output["url"] = url_for("index") + "downloads/timelapse/" + f["name"]
finished_list.append(output)
finished_list = []
for f in files:
output = dict(f)
output["url"] = url_for("index") + "downloads/timelapse/" + f["name"]
finished_list.append(output)
result = {"config": config,
"enabled": settings().getBoolean(["webcam", "timelapseEnabled"]),
"files": finished_list}
result = {
"config": config,
"enabled": settings().getBoolean(["webcam", "timelapseEnabled"]),
"files": finished_list,
}
if unrendered:
result.update(unrendered=unrendered_files)
if unrendered:
result.update(unrendered=unrendered_files)
return jsonify(result)
return jsonify(result)
@api.route("/timelapse/<filename>", methods=["GET"])
@no_firstrun_access
@Permissions.TIMELAPSE_DOWNLOAD.require(403)
def downloadTimelapse(filename):
return redirect_to_tornado(request, url_for("index") + "downloads/timelapse/" + filename)
return redirect_to_tornado(
request, url_for("index") + "downloads/timelapse/" + filename
)
@api.route("/timelapse/<filename>", methods=["DELETE"])
@no_firstrun_access
@Permissions.TIMELAPSE_DELETE.require(403)
def deleteTimelapse(filename):
timelapse_folder = settings().getBaseFolder("timelapse")
full_path = os.path.realpath(os.path.join(timelapse_folder, filename))
if octoprint.timelapse.valid_timelapse(full_path) \
and full_path.startswith(timelapse_folder) \
and os.path.exists(full_path) \
and not util.is_hidden_path(full_path):
try:
os.remove(full_path)
except Exception as ex:
logging.getLogger(__file__).exception("Error deleting timelapse file {}".format(full_path))
return make_response("Unexpected error: {}".format(ex), 500)
timelapse_folder = settings().getBaseFolder("timelapse")
full_path = os.path.realpath(os.path.join(timelapse_folder, filename))
if (
octoprint.timelapse.valid_timelapse(full_path)
and full_path.startswith(timelapse_folder)
and os.path.exists(full_path)
and not util.is_hidden_path(full_path)
):
try:
os.remove(full_path)
except Exception as ex:
logging.getLogger(__file__).exception(
"Error deleting timelapse file {}".format(full_path)
)
return make_response("Unexpected error: {}".format(ex), 500)
return getTimelapseData()
return getTimelapseData()
@api.route("/timelapse/unrendered/<name>", methods=["DELETE"])
@no_firstrun_access
@Permissions.TIMELAPSE_DELETE.require(403)
def deleteUnrenderedTimelapse(name):
octoprint.timelapse.delete_unrendered_timelapse(name)
return NO_CONTENT
octoprint.timelapse.delete_unrendered_timelapse(name)
return NO_CONTENT
@api.route("/timelapse/unrendered/<name>", methods=["POST"])
@no_firstrun_access
@Permissions.TIMELAPSE_ADMIN.require(403)
def processUnrenderedTimelapseCommand(name):
# valid file commands, dict mapping command name to mandatory parameters
valid_commands = {
"render": []
}
# valid file commands, dict mapping command name to mandatory parameters
valid_commands = {"render": []}
command, data, response = get_json_command_from_request(request, valid_commands)
if response is not None:
return response
command, data, response = get_json_command_from_request(request, valid_commands)
if response is not None:
return response
if command == "render":
if printer.is_printing() or printer.is_paused():
return make_response("Printer is currently printing, cannot render timelapse", 409)
octoprint.timelapse.render_unrendered_timelapse(name)
if command == "render":
if printer.is_printing() or printer.is_paused():
return make_response(
"Printer is currently printing, cannot render timelapse", 409
)
octoprint.timelapse.render_unrendered_timelapse(name)
return NO_CONTENT
return NO_CONTENT
@api.route("/timelapse", methods=["POST"])
@no_firstrun_access
@Permissions.TIMELAPSE_ADMIN.require(403)
def setTimelapseConfig():
data = request.get_json(silent=True)
if data is None:
data = request.values
data = request.get_json(silent=True)
if data is None:
data = request.values
if "type" in data:
config = {
"type": data["type"],
"postRoll": 0,
"fps": 25,
"options": {}
}
if "type" in data:
config = {"type": data["type"], "postRoll": 0, "fps": 25, "options": {}}
if "postRoll" in data:
try:
postRoll = int(data["postRoll"])
except ValueError:
return make_response("Invalid value for postRoll: %r" % data["postRoll"], 400)
else:
if postRoll >= 0:
config["postRoll"] = postRoll
else:
return make_response("Invalid value for postRoll: %d" % postRoll, 400)
if "postRoll" in data:
try:
postRoll = int(data["postRoll"])
except ValueError:
return make_response(
"Invalid value for postRoll: %r" % data["postRoll"], 400
)
else:
if postRoll >= 0:
config["postRoll"] = postRoll
else:
return make_response("Invalid value for postRoll: %d" % postRoll, 400)
if "fps" in data:
try:
fps = int(data["fps"])
except ValueError:
return make_response("Invalid value for fps: %r" % data["fps"], 400)
else:
if fps > 0:
config["fps"] = fps
else:
return make_response("Invalid value for fps: %d" % fps, 400)
if "fps" in data:
try:
fps = int(data["fps"])
except ValueError:
return make_response("Invalid value for fps: %r" % data["fps"], 400)
else:
if fps > 0:
config["fps"] = fps
else:
return make_response("Invalid value for fps: %d" % fps, 400)
if "interval" in data:
try:
interval = int(data["interval"])
except ValueError:
return make_response("Invalid value for interval: %r" % data["interval"], 400)
else:
if interval > 0:
config["options"]["interval"] = interval
else:
return make_response("Invalid value for interval: %d" % interval, 400)
if "interval" in data:
try:
interval = int(data["interval"])
except ValueError:
return make_response(
"Invalid value for interval: %r" % data["interval"], 400
)
else:
if interval > 0:
config["options"]["interval"] = interval
else:
return make_response("Invalid value for interval: %d" % interval, 400)
if "retractionZHop" in data:
try:
retractionZHop = float(data["retractionZHop"])
except ValueError:
return make_response("Invalid value for retraction Z-Hop: %r" % data["retractionZHop"], 400)
else:
if retractionZHop >= 0:
config["options"]["retractionZHop"] = retractionZHop
else:
return make_response("Invalid value for retraction Z-Hop: %f" % retractionZHop, 400)
if "retractionZHop" in data:
try:
retractionZHop = float(data["retractionZHop"])
except ValueError:
return make_response(
"Invalid value for retraction Z-Hop: %r" % data["retractionZHop"], 400
)
else:
if retractionZHop >= 0:
config["options"]["retractionZHop"] = retractionZHop
else:
return make_response(
"Invalid value for retraction Z-Hop: %f" % retractionZHop, 400
)
if "minDelay" in data:
try:
minDelay = float(data["minDelay"])
except ValueError:
return make_response("Invalid value for minimum delay: %r" % data["minDelay"], 400)
else:
if minDelay > 0:
config["options"]["minDelay"] = minDelay
else:
return make_response("Invalid value for minimum delay: %f" % minDelay, 400)
if "minDelay" in data:
try:
minDelay = float(data["minDelay"])
except ValueError:
return make_response(
"Invalid value for minimum delay: %r" % data["minDelay"], 400
)
else:
if minDelay > 0:
config["options"]["minDelay"] = minDelay
else:
return make_response(
"Invalid value for minimum delay: %f" % minDelay, 400
)
if admin_permission.can() and "save" in data and data["save"] in valid_boolean_trues:
octoprint.timelapse.configure_timelapse(config, True)
else:
octoprint.timelapse.configure_timelapse(config)
return getTimelapseData()
if (
admin_permission.can()
and "save" in data
and data["save"] in valid_boolean_trues
):
octoprint.timelapse.configure_timelapse(config, True)
else:
octoprint.timelapse.configure_timelapse(config)
return getTimelapseData()
+12 -11
View File
@@ -1,7 +1,7 @@
# -*- coding: utf-8 -*-
from __future__ import absolute_import, division, print_function, unicode_literals
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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"
from octoprint.server.api import api
@@ -11,51 +11,52 @@ from flask import redirect, url_for
# by all browsers yet. So we stick to 307 TEMPORARY REDIRECT as defined in RFC7231 although it's definitely not a
# temporary redirect we have here.
@api.route("/users", methods=["GET"])
def deprecated_get_users():
return redirect(url_for("api.get_users"), code=307)
return redirect(url_for("api.get_users"), code=307)
@api.route("/users", methods=["POST"])
def addUser():
return redirect(url_for("api.add_user"), code=307)
return redirect(url_for("api.add_user"), code=307)
@api.route("/users/<username>", methods=["GET"])
def getUser(username):
return redirect(url_for("api.get_user", username=username), code=307)
return redirect(url_for("api.get_user", username=username), code=307)
@api.route("/users/<username>", methods=["PUT"])
def updateUser(username):
return redirect(url_for("api.update_user", username=username), code=307)
return redirect(url_for("api.update_user", username=username), code=307)
@api.route("/users/<username>", methods=["DELETE"])
def removeUser(username):
return redirect(url_for("api.remove_user", username=username), code=307)
return redirect(url_for("api.remove_user", username=username), code=307)
@api.route("/users/<username>/password", methods=["PUT"])
def changePasswordForUser(username):
return redirect(url_for("api.change_password_for_user", username=username), code=307)
return redirect(url_for("api.change_password_for_user", username=username), code=307)
@api.route("/users/<username>/settings", methods=["GET"])
def getSettingsForUser(username):
return redirect(url_for("api.get_settings_for_user", username=username), code=307)
return redirect(url_for("api.get_settings_for_user", username=username), code=307)
@api.route("/users/<username>/settings", methods=["PATCH"])
def changeSettingsForUser(username):
return redirect(url_for("api.change_settings_for_user", username=username), code=307)
return redirect(url_for("api.change_settings_for_user", username=username), code=307)
@api.route("/users/<username>/apikey", methods=["DELETE"])
def deleteApikeyForUser(username):
return redirect(url_for("api.delete_apikey_for_user", username=username), code=307)
return redirect(url_for("api.delete_apikey_for_user", username=username), code=307)
@api.route("/users/<username>/apikey", methods=["POST"])
def generateApikeyForUser(username):
return redirect(url_for("api.generate_apikey_for_user", username=username), code=307)
return redirect(url_for("api.generate_apikey_for_user", username=username), code=307)
+226 -182
View File
@@ -2,11 +2,12 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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"
import base64
import sys
PY3 = sys.version_info[0] == 3
from octoprint.settings import settings
@@ -27,277 +28,320 @@ from . import tornado
from . import watchdog
@deprecated("API keys are no longer needed for anonymous access and thus this is now obsolete")
@deprecated(
"API keys are no longer needed for anonymous access and thus this is now obsolete"
)
def enforceApiKeyRequestHandler():
pass
pass
apiKeyRequestHandler = deprecated("apiKeyRequestHandler has been renamed to enforceApiKeyRequestHandler")(enforceApiKeyRequestHandler)
apiKeyRequestHandler = deprecated(
"apiKeyRequestHandler has been renamed to enforceApiKeyRequestHandler"
)(enforceApiKeyRequestHandler)
def loginFromApiKeyRequestHandler():
"""
``before_request`` handler for blueprints which creates a login session for the provided api key (if available)
"""
``before_request`` handler for blueprints which creates a login session for the provided api key (if available)
App session keys are handled as anonymous keys here and ignored.
"""
try:
if loginUserFromApiKey():
_flask.g.login_via_apikey = True
except InvalidApiKeyException:
return _flask.make_response("Invalid API key", 403)
App session keys are handled as anonymous keys here and ignored.
"""
try:
if loginUserFromApiKey():
_flask.g.login_via_apikey = True
except InvalidApiKeyException:
return _flask.make_response("Invalid API key", 403)
def loginFromAuthorizationHeaderRequestHandler():
"""
``before_request`` handler for creating login sessions based on the Authorization header.
"""
try:
if loginUserFromAuthorizationHeader():
_flask.g.login_via_header = True
except InvalidApiKeyException:
return _flask.make_response("Invalid API key", 403)
"""
``before_request`` handler for creating login sessions based on the Authorization header.
"""
try:
if loginUserFromAuthorizationHeader():
_flask.g.login_via_header = True
except InvalidApiKeyException:
return _flask.make_response("Invalid API key", 403)
class InvalidApiKeyException(Exception): pass
class InvalidApiKeyException(Exception):
pass
def loginUserFromApiKey():
apikey = get_api_key(_flask.request)
if not apikey:
return False
apikey = get_api_key(_flask.request)
if not apikey:
return False
user = get_user_for_apikey(apikey)
if user is None:
# invalid API key = no API key
return False
user = get_user_for_apikey(apikey)
if user is None:
# invalid API key = no API key
return False
return loginUser(user, login_mechanism="apikey")
return loginUser(user, login_mechanism="apikey")
def loginUserFromAuthorizationHeader():
authorization_header = get_authorization_header(_flask.request)
user = get_user_for_authorization_header(authorization_header)
return loginUser(user, login_mechanism="authheader")
authorization_header = get_authorization_header(_flask.request)
user = get_user_for_authorization_header(authorization_header)
return loginUser(user, login_mechanism="authheader")
def loginUser(user, remember=False, login_mechanism=None):
"""
Logs the provided ``user`` into Flask Login and Principal if not None and active
"""
Logs the provided ``user`` into Flask Login and Principal if not None and active
Args:
user: the User to login. May be None in which case the login will fail
remember: Whether to set the ``remember`` flag on the Flask Login operation
Args:
user: the User to login. May be None in which case the login will fail
remember: Whether to set the ``remember`` flag on the Flask Login operation
Returns: (bool) True if the login succeeded, False otherwise
Returns: (bool) True if the login succeeded, False otherwise
"""
if user is not None and user.is_active and flask_login.login_user(user, remember=remember):
flask_principal.identity_changed.send(_flask.current_app._get_current_object(),
identity=flask_principal.Identity(user.get_id()))
if login_mechanism:
_flask.session["login_mechanism"] = login_mechanism
return True
return False
"""
if (
user is not None
and user.is_active
and flask_login.login_user(user, remember=remember)
):
flask_principal.identity_changed.send(
_flask.current_app._get_current_object(),
identity=flask_principal.Identity(user.get_id()),
)
if login_mechanism:
_flask.session["login_mechanism"] = login_mechanism
return True
return False
def requireLoginRequestHandler():
if _flask.request.endpoint.endswith(".static"):
return
if _flask.request.endpoint.endswith(".static"):
return
if not (octoprint.server.userManager.enabled and octoprint.server.userManager.has_been_customized()):
return
if not (
octoprint.server.userManager.enabled
and octoprint.server.userManager.has_been_customized()
):
return
user = flask_login.current_user
if user is None or user.is_anonymous or not user.is_active:
return flask.make_response("Forbidden", 403)
user = flask_login.current_user
if user is None or user.is_anonymous or not user.is_active:
return flask.make_response("Forbidden", 403)
def corsRequestHandler():
"""
``before_request`` handler for blueprints which sets CORS headers for OPTIONS requests if enabled
"""
if _flask.request.method == 'OPTIONS' and settings().getBoolean(["api", "allowCrossOrigin"]):
# reply to OPTIONS request for CORS headers
return optionsAllowOrigin(_flask.request)
"""
``before_request`` handler for blueprints which sets CORS headers for OPTIONS requests if enabled
"""
if _flask.request.method == "OPTIONS" and settings().getBoolean(
["api", "allowCrossOrigin"]
):
# reply to OPTIONS request for CORS headers
return optionsAllowOrigin(_flask.request)
def corsResponseHandler(resp):
"""
``after_request`` handler for blueprints for which CORS is supported.
"""
``after_request`` handler for blueprints for which CORS is supported.
Sets ``Access-Control-Allow-Origin`` headers for ``Origin`` request header on response.
"""
Sets ``Access-Control-Allow-Origin`` headers for ``Origin`` request header on response.
"""
# Allow crossdomain
allowCrossOrigin = settings().getBoolean(["api", "allowCrossOrigin"])
if _flask.request.method != 'OPTIONS' and 'Origin' in _flask.request.headers and allowCrossOrigin:
resp.headers['Access-Control-Allow-Origin'] = _flask.request.headers['Origin']
# Allow crossdomain
allowCrossOrigin = settings().getBoolean(["api", "allowCrossOrigin"])
if (
_flask.request.method != "OPTIONS"
and "Origin" in _flask.request.headers
and allowCrossOrigin
):
resp.headers["Access-Control-Allow-Origin"] = _flask.request.headers["Origin"]
return resp
return resp
def noCachingResponseHandler(resp):
"""
``after_request`` handler for blueprints which shall set no caching headers
on their responses.
"""
``after_request`` handler for blueprints which shall set no caching headers
on their responses.
Sets ``Cache-Control``, ``Pragma`` and ``Expires`` headers accordingly
to prevent all client side caching from taking place.
"""
Sets ``Cache-Control``, ``Pragma`` and ``Expires`` headers accordingly
to prevent all client side caching from taking place.
"""
return flask.add_non_caching_response_headers(resp)
return flask.add_non_caching_response_headers(resp)
def noCachingExceptGetResponseHandler(resp):
"""
``after_request`` handler for blueprints which shall set no caching headers
on their responses to any requests that are not sent with method ``GET``.
"""
``after_request`` handler for blueprints which shall set no caching headers
on their responses to any requests that are not sent with method ``GET``.
See :func:`noCachingResponseHandler`.
"""
See :func:`noCachingResponseHandler`.
"""
if _flask.request.method == "GET":
return flask.add_no_max_age_response_headers(resp)
else:
return flask.add_non_caching_response_headers(resp)
if _flask.request.method == "GET":
return flask.add_no_max_age_response_headers(resp)
else:
return flask.add_non_caching_response_headers(resp)
def optionsAllowOrigin(request):
"""
Shortcut for request handling for CORS OPTIONS requests to set CORS headers.
"""
"""
Shortcut for request handling for CORS OPTIONS requests to set CORS headers.
"""
resp = _flask.current_app.make_default_options_response()
resp = _flask.current_app.make_default_options_response()
# Allow the origin which made the XHR
resp.headers['Access-Control-Allow-Origin'] = request.headers['Origin']
# Allow the actual method
resp.headers['Access-Control-Allow-Methods'] = request.headers['Access-Control-Request-Method']
# Allow for 10 seconds
resp.headers['Access-Control-Max-Age'] = "10"
# Allow the origin which made the XHR
resp.headers["Access-Control-Allow-Origin"] = request.headers["Origin"]
# Allow the actual method
resp.headers["Access-Control-Allow-Methods"] = request.headers[
"Access-Control-Request-Method"
]
# Allow for 10 seconds
resp.headers["Access-Control-Max-Age"] = "10"
# 'preflight' request contains the non-standard headers the real request will have (like X-Api-Key)
customRequestHeaders = request.headers.get('Access-Control-Request-Headers', None)
if customRequestHeaders is not None:
# If present => allow them all
resp.headers['Access-Control-Allow-Headers'] = customRequestHeaders
# 'preflight' request contains the non-standard headers the real request will have (like X-Api-Key)
customRequestHeaders = request.headers.get("Access-Control-Request-Headers", None)
if customRequestHeaders is not None:
# If present => allow them all
resp.headers["Access-Control-Allow-Headers"] = customRequestHeaders
return resp
return resp
def get_user_for_apikey(apikey):
if apikey is not None:
if apikey == settings().get(["api", "key"]):
# master key was used
return octoprint.server.userManager.api_user_factory()
if apikey is not None:
if apikey == settings().get(["api", "key"]):
# master key was used
return octoprint.server.userManager.api_user_factory()
if octoprint.server.userManager.enabled:
user = octoprint.server.userManager.find_user(apikey=apikey)
if user is not None:
# user key was used
return user
if octoprint.server.userManager.enabled:
user = octoprint.server.userManager.find_user(apikey=apikey)
if user is not None:
# user key was used
return user
apikey_hooks = plugin_manager().get_hooks("octoprint.accesscontrol.keyvalidator")
for name, hook in apikey_hooks.items():
try:
user = hook(apikey)
if user is not None:
return user
except Exception:
logging.getLogger(__name__).exception("Error running api key validator "
"for plugin {} and key {}".format(name, apikey),
extra={"plugin": name})
return None
apikey_hooks = plugin_manager().get_hooks("octoprint.accesscontrol.keyvalidator")
for name, hook in apikey_hooks.items():
try:
user = hook(apikey)
if user is not None:
return user
except Exception:
logging.getLogger(__name__).exception(
"Error running api key validator "
"for plugin {} and key {}".format(name, apikey),
extra={"plugin": name},
)
return None
def get_user_for_remote_user_header(request):
if not octoprint.server.userManager.enabled:
return None
if not octoprint.server.userManager.enabled:
return None
if not settings().getBoolean(["accessControl", "trustRemoteUser"]):
return None
if not settings().getBoolean(["accessControl", "trustRemoteUser"]):
return None
header = request.headers.get(settings().get(["accessControl", "remoteUserHeader"]))
if header is None:
return None
header = request.headers.get(settings().get(["accessControl", "remoteUserHeader"]))
if header is None:
return None
user = octoprint.server.userManager.findUser(userid=header)
user = octoprint.server.userManager.findUser(userid=header)
if user is None and settings().getBoolean(["accessControl", "addRemoteUsers"]):
octoprint.server.userManager.addUser(header, settings().generateApiKey(), active=True)
user = octoprint.server.userManager.findUser(userid=header)
if user is None and settings().getBoolean(["accessControl", "addRemoteUsers"]):
octoprint.server.userManager.addUser(
header, settings().generateApiKey(), active=True
)
user = octoprint.server.userManager.findUser(userid=header)
return user
return user
def get_user_for_authorization_header(header):
if not settings().getBoolean(["accessControl", "trustBasicAuthentication"]):
return None
if not settings().getBoolean(["accessControl", "trustBasicAuthentication"]):
return None
if header is None:
return None
if header is None:
return None
if not header.startswith("Basic "):
# we currently only support Basic Authentication
return None
if not header.startswith("Basic "):
# we currently only support Basic Authentication
return None
header = header.replace('Basic ', '', 1)
try:
header = to_unicode(base64.b64decode(header))
except TypeError:
return None
header = header.replace("Basic ", "", 1)
try:
header = to_unicode(base64.b64decode(header))
except TypeError:
return None
name, password = header.split(':', 1)
if not octoprint.server.userManager.enabled:
return None
name, password = header.split(":", 1)
if not octoprint.server.userManager.enabled:
return None
user = octoprint.server.userManager.find_user(userid=name)
if settings().getBoolean(["accessControl", "checkBasicAuthenticationPassword"]) \
and not octoprint.server.userManager.check_password(name, password):
# password check enabled and password don't match
return None
user = octoprint.server.userManager.find_user(userid=name)
if settings().getBoolean(
["accessControl", "checkBasicAuthenticationPassword"]
) and not octoprint.server.userManager.check_password(name, password):
# password check enabled and password don't match
return None
return user
return user
def get_api_key(request):
# Check Flask GET/POST arguments
if hasattr(request, "values") and "apikey" in request.values:
return request.values["apikey"]
# Check Flask GET/POST arguments
if hasattr(request, "values") and "apikey" in request.values:
return request.values["apikey"]
# Check Tornado GET/POST arguments
if hasattr(request, "arguments") and "apikey" in request.arguments \
and len(request.arguments["apikey"]) > 0 and len(request.arguments["apikey"].strip()) > 0:
return request.arguments["apikey"]
# Check Tornado GET/POST arguments
if (
hasattr(request, "arguments")
and "apikey" in request.arguments
and len(request.arguments["apikey"]) > 0
and len(request.arguments["apikey"].strip()) > 0
):
return request.arguments["apikey"]
# Check Tornado and Flask headers
if "X-Api-Key" in request.headers:
return request.headers.get("X-Api-Key")
# Check Tornado and Flask headers
if "X-Api-Key" in request.headers:
return request.headers.get("X-Api-Key")
# Check Tornado and Flask headers
if "Authorization" in request.headers:
header = request.headers.get("Authorization")
if header.startswith("Bearer "):
token = header.replace("Bearer ", "", 1)
return token
# Check Tornado and Flask headers
if "Authorization" in request.headers:
header = request.headers.get("Authorization")
if header.startswith("Bearer "):
token = header.replace("Bearer ", "", 1)
return token
return None
return None
def get_authorization_header(request):
# Tornado and Flask headers
return request.headers.get("Authorization")
# Tornado and Flask headers
return request.headers.get("Authorization")
def get_plugin_hash():
from octoprint.plugin import plugin_manager
from octoprint.plugin import plugin_manager
plugin_signature = lambda impl: "{}:{}".format(impl._identifier, impl._plugin_version)
template_plugins = list(map(plugin_signature, plugin_manager().get_implementations(octoprint.plugin.TemplatePlugin)))
asset_plugins = list(map(plugin_signature, plugin_manager().get_implementations(octoprint.plugin.AssetPlugin)))
ui_plugins = sorted(set(template_plugins + asset_plugins))
plugin_signature = lambda impl: "{}:{}".format(impl._identifier, impl._plugin_version)
template_plugins = list(
map(
plugin_signature,
plugin_manager().get_implementations(octoprint.plugin.TemplatePlugin),
)
)
asset_plugins = list(
map(
plugin_signature,
plugin_manager().get_implementations(octoprint.plugin.AssetPlugin),
)
)
ui_plugins = sorted(set(template_plugins + asset_plugins))
import hashlib
plugin_hash = hashlib.sha1()
plugin_hash.update(",".join(ui_plugins).encode('utf-8'))
return plugin_hash.hexdigest()
import hashlib
plugin_hash = hashlib.sha1()
plugin_hash.update(",".join(ui_plugins).encode("utf-8"))
return plugin_hash.hexdigest()
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+185 -136
View File
@@ -2,7 +2,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <osd@foosel.net>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__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"
import logging
@@ -18,174 +18,223 @@ import octoprint.util
def fix_scandir():
try:
from os import scandir
# nothing to fix, natively available, return
return
try:
from os import scandir
except ImportError:
# not natively available, use backport
from scandir import scandir
# nothing to fix, natively available, return
return
import watchdog.utils.dirsnapshot
OriginalDirectorySnapshot = watchdog.utils.dirsnapshot.DirectorySnapshot
class FixedDirectorySnapshot(OriginalDirectorySnapshot):
def __init__(self, listdir=scandir, *args, **kwargs):
OriginalDirectorySnapshot.__init__(self, listdir=listdir, *args, **kwargs)
watchdog.utils.dirsnapshot.DirectorySnapshot = FixedDirectorySnapshot
except ImportError:
# not natively available, use backport
from scandir import scandir
import watchdog.utils.dirsnapshot
OriginalDirectorySnapshot = watchdog.utils.dirsnapshot.DirectorySnapshot
class FixedDirectorySnapshot(OriginalDirectorySnapshot):
def __init__(self, listdir=scandir, *args, **kwargs):
OriginalDirectorySnapshot.__init__(self, listdir=listdir, *args, **kwargs)
watchdog.utils.dirsnapshot.DirectorySnapshot = FixedDirectorySnapshot
import watchdog.observers.polling
OriginalPollingEmitter = watchdog.observers.polling.PollingEmitter
class FixedPollingEmitter(OriginalPollingEmitter):
def __init__(self, listdir=scandir, *args, **kwargs):
OriginalPollingEmitter.__init__(self, listdir=listdir, *args, **kwargs)
watchdog.observers.polling.PollingEmitter = FixedPollingEmitter
import watchdog.observers.polling
OriginalPollingEmitter = watchdog.observers.polling.PollingEmitter
class FixedPollingEmitter(OriginalPollingEmitter):
def __init__(self, listdir=scandir, *args, **kwargs):
OriginalPollingEmitter.__init__(self, listdir=listdir, *args, **kwargs)
watchdog.observers.polling.PollingEmitter = FixedPollingEmitter
class GcodeWatchdogHandler(watchdog.events.PatternMatchingEventHandler):
"""
Takes care of automatically "uploading" files that get added to the watched folder.
"""
"""
Takes care of automatically "uploading" files that get added to the watched folder.
"""
def __init__(self, file_manager, printer):
watchdog.events.PatternMatchingEventHandler.__init__(self, patterns=list(map(lambda x: "*.%s" % x, octoprint.filemanager.get_all_extensions())))
def __init__(self, file_manager, printer):
watchdog.events.PatternMatchingEventHandler.__init__(
self,
patterns=list(
map(lambda x: "*.%s" % x, octoprint.filemanager.get_all_extensions())
),
)
self._logger = logging.getLogger(__name__)
self._logger = logging.getLogger(__name__)
self._file_manager = file_manager
self._printer = printer
self._file_manager = file_manager
self._printer = printer
self._watched_folder = None
self._watched_folder = None
def initial_scan(self, folder):
try:
from os import scandir
except ImportError:
from scandir import scandir
def initial_scan(self, folder):
try:
from os import scandir
except ImportError:
from scandir import scandir
def _recursive_scandir(path):
"""Recursively yield DirEntry objects for given directory."""
for entry in scandir(path):
if entry.is_dir(follow_symlinks=False):
for entry in _recursive_scandir(entry.path):
yield entry
else:
yield entry
def _recursive_scandir(path):
"""Recursively yield DirEntry objects for given directory."""
for entry in scandir(path):
if entry.is_dir(follow_symlinks=False):
for entry in _recursive_scandir(entry.path):
yield entry
else:
yield entry
def run_scan():
self._logger.info("Running initial scan on watched folder...")
self._watched_folder = folder
def run_scan():
self._logger.info("Running initial scan on watched folder...")
self._watched_folder = folder
for entry in _recursive_scandir(folder):
path = entry.path
for entry in _recursive_scandir(folder):
path = entry.path
if not self._valid_path(path):
continue
if not self._valid_path(path):
continue
self._logger.info("Found {}, trying to add it".format(path))
self._upload(path)
self._logger.info("... initial scan done.")
self._logger.info("Found {}, trying to add it".format(path))
self._upload(path)
self._logger.info("... initial scan done.")
thread = threading.Thread(target=run_scan)
thread.daemon = True
thread.start()
thread = threading.Thread(target=run_scan)
thread.daemon = True
thread.start()
def on_created(self, event):
self._start_check(event.src_path)
def on_created(self, event):
self._start_check(event.src_path)
def on_moved(self, event):
# for move/rename we are only interested in the dest_path
self._start_check(event.dest_path)
def on_moved(self, event):
# for move/rename we are only interested in the dest_path
self._start_check(event.dest_path)
def _start_check(self, path):
if not self._valid_path(path):
return
def _start_check(self, path):
if not self._valid_path(path):
return
thread = threading.Thread(target=self._repeatedly_check, args=(path,))
thread.daemon = True
thread.start()
thread = threading.Thread(target=self._repeatedly_check, args=(path,))
thread.daemon = True
thread.start()
def _upload(self, path):
# noinspection PyBroadException
try:
file_wrapper = octoprint.filemanager.util.DiskFileWrapper(os.path.basename(path), path)
relative_path = os.path.relpath(path, self._watched_folder)
def _upload(self, path):
# noinspection PyBroadException
try:
file_wrapper = octoprint.filemanager.util.DiskFileWrapper(
os.path.basename(path), path
)
relative_path = os.path.relpath(path, self._watched_folder)
# determine future filename of file to be uploaded, abort if it can't be uploaded
try:
futurePath, futureFilename = self._file_manager.sanitize(octoprint.filemanager.FileDestinations.LOCAL, relative_path)
except Exception:
self._logger.exception("Could not wrap %s", path)
futurePath = None
futureFilename = None
# determine future filename of file to be uploaded, abort if it can't be uploaded
try:
futurePath, futureFilename = self._file_manager.sanitize(
octoprint.filemanager.FileDestinations.LOCAL, relative_path
)
except Exception:
self._logger.exception("Could not wrap %s", path)
futurePath = None
futureFilename = None
if futureFilename is None or (len(self._file_manager.registered_slicers) == 0 and not octoprint.filemanager.valid_file_type(futureFilename)):
return
if futureFilename is None or (
len(self._file_manager.registered_slicers) == 0
and not octoprint.filemanager.valid_file_type(futureFilename)
):
return
# prohibit overwriting currently selected file while it's being printed
futureFullPath = self._file_manager.join_path(octoprint.filemanager.FileDestinations.LOCAL, futurePath, futureFilename)
futureFullPathInStorage = self._file_manager.path_in_storage(octoprint.filemanager.FileDestinations.LOCAL, futureFullPath)
# prohibit overwriting currently selected file while it's being printed
futureFullPath = self._file_manager.join_path(
octoprint.filemanager.FileDestinations.LOCAL, futurePath, futureFilename
)
futureFullPathInStorage = self._file_manager.path_in_storage(
octoprint.filemanager.FileDestinations.LOCAL, futureFullPath
)
if not self._printer.can_modify_file(futureFullPathInStorage, False):
return
if not self._printer.can_modify_file(futureFullPathInStorage, False):
return
reselect = self._printer.is_current_file(futureFullPathInStorage, False)
reselect = self._printer.is_current_file(futureFullPathInStorage, False)
added_file = self._file_manager.add_file(octoprint.filemanager.FileDestinations.LOCAL,
relative_path,
file_wrapper,
allow_overwrite=True)
if os.path.exists(path):
try:
os.remove(path)
except Exception:
pass
added_file = self._file_manager.add_file(
octoprint.filemanager.FileDestinations.LOCAL,
relative_path,
file_wrapper,
allow_overwrite=True,
)
if os.path.exists(path):
try:
os.remove(path)
except Exception:
pass
if reselect:
self._printer.select_file(self._file_manager.path_on_disk(octoprint.filemanager.FileDestinations.LOCAL,
added_file),
False)
except Exception:
self._logger.exception("There was an error while processing the file {} in the watched folder".format(path))
finally:
if os.path.exists(path):
# file is still there - that should only happen if something went wrong, so mark it as failed
# noinspection PyBroadException
try:
shutil.move(path, "{}.failed".format(path))
except:
# something went really wrong here.... but we can't do anything about it, so just log it
self._logger.exception("There was an error while trying to mark {} as failed in the watched folder".format(path))
if reselect:
self._printer.select_file(
self._file_manager.path_on_disk(
octoprint.filemanager.FileDestinations.LOCAL, added_file
),
False,
)
except Exception:
self._logger.exception(
"There was an error while processing the file {} in the watched folder".format(
path
)
)
finally:
if os.path.exists(path):
# file is still there - that should only happen if something went wrong, so mark it as failed
# noinspection PyBroadException
try:
shutil.move(path, "{}.failed".format(path))
except:
# something went really wrong here.... but we can't do anything about it, so just log it
self._logger.exception(
"There was an error while trying to mark {} as failed in the watched folder".format(
path
)
)
def _repeatedly_check(self, path, interval=1, stable=5):
try:
last_size = os.stat(path).st_size
except Exception:
return
def _repeatedly_check(self, path, interval=1, stable=5):
try:
last_size = os.stat(path).st_size
except Exception:
return
countdown = stable
countdown = stable
while True:
try:
new_size = os.stat(path).st_size
except Exception:
return
while True:
try:
new_size = os.stat(path).st_size
except Exception:
return
if new_size == last_size:
self._logger.debug("File at {} is no longer growing, counting down: {}".format(path, countdown))
countdown -= 1
if countdown <= 0:
break
else:
self._logger.debug("File at {} is still growing (last: {}, new: {}), waiting...".format(path, last_size, new_size))
countdown = stable
if new_size == last_size:
self._logger.debug(
"File at {} is no longer growing, counting down: {}".format(
path, countdown
)
)
countdown -= 1
if countdown <= 0:
break
else:
self._logger.debug(
"File at {} is still growing (last: {}, new: {}), waiting...".format(
path, last_size, new_size
)
)
countdown = stable
last_size = new_size
time.sleep(interval)
last_size = new_size
time.sleep(interval)
self._logger.debug("File at {} is stable, moving it".format(path))
self._upload(path)
self._logger.debug("File at {} is stable, moving it".format(path))
self._upload(path)
def _valid_path(self, path):
_, ext = os.path.splitext(path)
return octoprint.filemanager.valid_file_type(path) and not octoprint.util.is_hidden_path(path) and ext != "failed"
def _valid_path(self, path):
_, ext = os.path.splitext(path)
return (
octoprint.filemanager.valid_file_type(path)
and not octoprint.util.is_hidden_path(path)
and ext != "failed"
)
+124 -109
View File
@@ -2,7 +2,7 @@
from __future__ import absolute_import, division, print_function, unicode_literals
__author__ = "Gina Häußge <gina@octoprint.org>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
import logging
@@ -11,9 +11,9 @@ import os
import re
try:
from urllib import parse as urlparse
from urllib import parse as urlparse
except ImportError:
import urlparse
import urlparse
from webassets.bundle import Bundle
from webassets.merge import MemoryHunk, BaseHunk
@@ -23,162 +23,177 @@ import webassets.filter.cssrewrite.urlpath as urlpath
def replace_url(source_url, output_url, url):
# If path is an absolute one, keep it
parsed = urlparse.urlparse(url)
# If path is an absolute one, keep it
parsed = urlparse.urlparse(url)
if not parsed.scheme and not parsed.path.startswith('/'):
abs_source_url = urlparse.urljoin(source_url, url)
if not parsed.scheme and not parsed.path.startswith("/"):
abs_source_url = urlparse.urljoin(source_url, url)
# relpath() will not detect this case
if urlparse.urlparse(abs_source_url).scheme:
return abs_source_url
# relpath() will not detect this case
if urlparse.urlparse(abs_source_url).scheme:
return abs_source_url
# rewritten url: relative path from new location (output)
# to location of referenced file (source + current url)
url = urlpath.relpath(output_url, abs_source_url)
# rewritten url: relative path from new location (output)
# to location of referenced file (source + current url)
url = urlpath.relpath(output_url, abs_source_url)
return url
return url
class UrlRewriter(PatternRewriter):
def input(self, _in, out, **kw):
source, source_path, output, output_path = (
kw["source"],
kw["source_path"],
kw["output"],
kw["output_path"],
)
def input(self, _in, out, **kw):
source, source_path, output, output_path = \
kw['source'], kw['source_path'], kw['output'], kw['output_path']
self.source_path = source_path
self.output_path = output_path
self.source_url = self.ctx.resolver.resolve_source_to_url(
self.ctx, source_path, source
)
self.output_url = self.ctx.resolver.resolve_output_to_url(self.ctx, output)
self.source_path = source_path
self.output_path = output_path
self.source_url = self.ctx.resolver.resolve_source_to_url(
self.ctx, source_path, source)
self.output_url = self.ctx.resolver.resolve_output_to_url(
self.ctx, output)
return super(UrlRewriter, self).input(_in, out, **kw)
return super(UrlRewriter, self).input(_in, out, **kw)
def replace_url(self, url):
return replace_url(self.source_url, self.output_url, url)
def replace_url(self, url):
return replace_url(self.source_url, self.output_url, url)
class LessImportRewrite(UrlRewriter):
name = "less_importrewrite"
name = "less_importrewrite"
patterns = {
"import_rewrite": re.compile(r"(@import(\s+\(.*\))?\s+)\"(.*)\";")
}
patterns = {"import_rewrite": re.compile(r"(@import(\s+\(.*\))?\s+)\"(.*)\";")}
def import_rewrite(self, m):
import_with_options = m.group(1)
import_url = self.replace_url(m.group(3))
return "{import_with_options}\"{import_url}\";".format(**locals())
def import_rewrite(self, m):
import_with_options = m.group(1)
import_url = self.replace_url(m.group(3))
return '{import_with_options}"{import_url}";'.format(**locals())
class SourceMapRewrite(UrlRewriter):
name = "sourcemap_urlrewrite"
name = "sourcemap_urlrewrite"
patterns = {
"url_rewrite": re.compile(r"(//#\s+sourceMappingURL=)(.*)")
}
patterns = {"url_rewrite": re.compile(r"(//#\s+sourceMappingURL=)(.*)")}
def url_rewrite(self, m):
mapping = m.group(1)
source_url = self.replace_url(m.group(2))
return "{mapping}{source_url}".format(**locals())
def url_rewrite(self, m):
mapping = m.group(1)
source_url = self.replace_url(m.group(2))
return "{mapping}{source_url}".format(**locals())
class SourceMapRemove(PatternRewriter):
name = "sourcemap_remove"
name = "sourcemap_remove"
patterns = {
"sourcemap_remove": re.compile(r"(//#\s+sourceMappingURL=)(.*)")
}
patterns = {"sourcemap_remove": re.compile(r"(//#\s+sourceMappingURL=)(.*)")}
def sourcemap_remove(self, m):
return ""
def sourcemap_remove(self, m):
return ""
class JsDelimiterBundler(Filter):
name = "js_delimiter_bundler"
options = {}
name = "js_delimiter_bundler"
options = {}
def input(self, _in, out, **kwargs):
source = kwargs.get("source", "n/a")
def input(self, _in, out, **kwargs):
source = kwargs.get("source", "n/a")
out.write("// source: " + source + "\n")
out.write(_in.read())
out.write("\n;\n")
out.write("// source: " + source + "\n")
out.write(_in.read())
out.write("\n;\n")
class GzipFile(Filter):
name = "gzip"
options = {}
name = "gzip"
options = {}
def output(self, _in, out, **kwargs):
data = _in.read()
out.write(data)
def output(self, _in, out, **kwargs):
data = _in.read()
out.write(data)
# webassets requires us to output a "str", but we can't do that since gzip
# provides binary outputs.
#
# We work around that by outputting the gzipped file to another path
output_path = kwargs.get("output_path", None)
if output_path:
gzipped_output_path = output_path + ".gz"
try:
with gzip.open(gzipped_output_path, "wb", 9) as f:
f.write(data.encode("utf8"))
except Exception:
logging.getLogger(__name__).exception("Error writing gzipped "
"output of {} to {}".format(output_path,
gzipped_output_path))
try:
os.remove(gzipped_output_path)
except Exception:
logging.getLogger(__name__).exception("Error removing broken "
".gz from {}".format(gzipped_output_path))
# webassets requires us to output a "str", but we can't do that since gzip
# provides binary outputs.
#
# We work around that by outputting the gzipped file to another path
output_path = kwargs.get("output_path", None)
if output_path:
gzipped_output_path = output_path + ".gz"
try:
with gzip.open(gzipped_output_path, "wb", 9) as f:
f.write(data.encode("utf8"))
except Exception:
logging.getLogger(__name__).exception(
"Error writing gzipped "
"output of {} to {}".format(output_path, gzipped_output_path)
)
try:
os.remove(gzipped_output_path)
except Exception:
logging.getLogger(__name__).exception(
"Error removing broken " ".gz from {}".format(gzipped_output_path)
)
class ChainedHunk(BaseHunk):
def __init__(self, *hunks):
self._hunks = hunks
def __init__(self, *hunks):
self._hunks = hunks
def mtime(self):
pass
def mtime(self):
pass
def data(self):
result = ""
for hunk in self._hunks:
if isinstance(hunk, tuple) and len(hunk) == 2:
hunk, f = hunk
else:
f = lambda x: x
result += f(hunk.data())
return result
def data(self):
result = ""
for hunk in self._hunks:
if isinstance(hunk, tuple) and len(hunk) == 2:
hunk, f = hunk
else:
f = lambda x: x
result += f(hunk.data())
return result
_PLUGIN_BUNDLE_WRAPPER_PREFIX = \
"""// JS assets for plugin {plugin}
_PLUGIN_BUNDLE_WRAPPER_PREFIX = """// JS assets for plugin {plugin}
(function () {{
try {{
"""
_PLUGIN_BUNDLE_WRAPPER_SUFFIX = \
"""
_PLUGIN_BUNDLE_WRAPPER_SUFFIX = """
}} catch (error) {{
log.error("Error in JS assets for plugin {plugin}:", (error.stack || error));
}}
}})();
"""
class JsPluginBundle(Bundle):
def __init__(self, plugin, *args, **kwargs):
Bundle.__init__(self, *args, **kwargs)
self.plugin = plugin
def __init__(self, plugin, *args, **kwargs):
Bundle.__init__(self, *args, **kwargs)
self.plugin = plugin
def _merge_and_apply(self, ctx, output, force, parent_debug=None,
parent_filters=None, extra_filters=None,
disable_cache=None):
hunk = Bundle._merge_and_apply(self, ctx, output, force, parent_debug=parent_debug,
parent_filters=parent_filters, extra_filters=extra_filters,
disable_cache=disable_cache)
def _merge_and_apply(
self,
ctx,
output,
force,
parent_debug=None,
parent_filters=None,
extra_filters=None,
disable_cache=None,
):
hunk = Bundle._merge_and_apply(
self,
ctx,
output,
force,
parent_debug=parent_debug,
parent_filters=parent_filters,
extra_filters=extra_filters,
disable_cache=disable_cache,
)
return ChainedHunk(MemoryHunk(_PLUGIN_BUNDLE_WRAPPER_PREFIX.format(plugin=self.plugin)),
(hunk, lambda x: x.replace("\n", "\n ")),
MemoryHunk(_PLUGIN_BUNDLE_WRAPPER_SUFFIX.format(plugin=self.plugin)))
return ChainedHunk(
MemoryHunk(_PLUGIN_BUNDLE_WRAPPER_PREFIX.format(plugin=self.plugin)),
(hunk, lambda x: x.replace("\n", "\n ")),
MemoryHunk(_PLUGIN_BUNDLE_WRAPPER_SUFFIX.format(plugin=self.plugin)),
)
File diff suppressed because it is too large. Load diff
+2060 -1785
View File
File diff suppressed because it is too large. Load diff
Loaded 100 of 184 files, more files were not shown because too many files have changed in this diff. Show more