✨ Add cli to generate system info bundle

To print the system info:

    octoprint systeminfo

To export a system info bundle:

    octoprint systeminfo <targetpath>

e.g.

    octoprint systeminfo .
This commit is contained in:
Gina Häußge committed 2021-01-29 15:37:24 +01:00
1 parent 3fc21fae75
commit 55291b6bfd
3 files changed
+140 -57

No files matched your search

+101 -5
View File
@@ -6,18 +6,23 @@ __copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms
import logging
import os
import click
import zipstream
from octoprint.cli import init_platform_for_cli, standard_options
click.disable_unicode_literals_warning = True
def get_systeminfo(environment_detector, connectivity_checker):
def get_systeminfo(environment_detector, connectivity_checker, additional_fields=None):
from octoprint import __version__
from octoprint.util import dict_flatten
if additional_fields is None:
additional_fields = {}
environment_detector.run_detection(notify_plugins=False)
systeminfo = {
@@ -30,9 +35,70 @@ def get_systeminfo(environment_detector, connectivity_checker):
flattened = dict_flatten(systeminfo)
flattened["env.python.virtualenv"] = "env.python.virtualenv" in flattened
for k, v in additional_fields.items():
if k not in flattened:
flattened[k] = v
return flattened
def get_systeminfo_bundle(systeminfo, logbase, printer=None):
from octoprint.util import to_bytes
systeminfotxt = []
for k in sorted(systeminfo.keys()):
systeminfotxt.append("{}: {}".format(k, systeminfo[k]))
terminaltxt = None
if printer and printer.is_operational():
firmware_info = printer.firmware_info
if firmware_info:
systeminfo["printer.firmware"] = firmware_info["name"]
if hasattr(printer, "_log"):
terminaltxt = list(printer._log)
try:
import zlib # noqa: F401
compress_type = zipstream.ZIP_DEFLATED
except ImportError:
# no zlib, no compression
compress_type = zipstream.ZIP_STORED
z = zipstream.ZipFile()
# add systeminfo
z.writestr(
"systeminfo.txt", to_bytes("\n".join(systeminfotxt)), compress_type=compress_type
)
# add terminal.txt, if available
if terminaltxt:
z.writestr(
"terminal.txt", to_bytes("\n".join(terminaltxt)), compress_type=compress_type
)
# add logs
for log in (
"octoprint.log",
"serial.log",
"plugin_softwareupdate_console.log",
"plugin_pluginmanager_console.log",
):
logpath = os.path.join(logbase, log)
if os.path.exists(logpath):
z.write(logpath, arcname=log, compress_type=compress_type)
return z
def get_systeminfo_bundle_name():
import time
return "octoprint-systeminfo-{}.zip".format(time.strftime("%Y%m%d%H%M%S"))
@click.group()
def systeminfo_commands():
pass
@@ -40,8 +106,14 @@ def systeminfo_commands():
@systeminfo_commands.command(name="systeminfo")
@standard_options()
@click.argument(
"path",
nargs=1,
required=False,
type=click.Path(writable=True, dir_okay=True, resolve_path=True),
)
@click.pass_context
def systeminfo_command(ctx, **kwargs):
def systeminfo_command(ctx, path, **kwargs):
"""Retrieves and prints the system info."""
logging.disable(logging.ERROR)
try:
@@ -59,8 +131,32 @@ def systeminfo_command(ctx, **kwargs):
click.echo("There was a fatal error initializing the platform.", err=True)
ctx.exit(-1)
else:
systeminfo = get_systeminfo(environment_detector, connectivity_checker)
systeminfo = get_systeminfo(
environment_detector, connectivity_checker, {"systeminfo.generator": "cli"}
)
for k in sorted(systeminfo.keys()):
click.echo("{}: {}".format(k, systeminfo[k]))
if path:
# create zip at path
zipfilename = os.path.join(path, get_systeminfo_bundle_name())
click.echo("Writing systeminfo bundle to {}...".format(zipfilename))
z = get_systeminfo_bundle(systeminfo, settings.getBaseFolder("logs"))
try:
with open(zipfilename, "wb") as f:
for data in z:
f.write(data)
except Exception as e:
click.echo(str(e), err=True)
click.echo(
"There was an error writing to {}.".format(zipfilename), err=True
)
ctx.exit(-1)
click.echo("Done!")
click.echo(zipfilename)
else:
# output systeminfo to console
for k in sorted(systeminfo.keys()):
click.echo("{}: {}".format(k, systeminfo[k]))
ctx.exit(0)
+9 -3
View File
@@ -42,9 +42,15 @@ def getSystemInfo():
)
from octoprint.util import dict_flatten
systeminfo = get_systeminfo(environmentDetector, connectivityChecker)
systeminfo["browser.user_agent"] = request.headers.get("User-Agent")
systeminfo["octoprint.safe_mode"] = safe_mode is not None
systeminfo = get_systeminfo(
environmentDetector,
connectivityChecker,
{
"browser.user_agent": request.headers.get("User-Agent"),
"octoprint.safe_mode": safe_mode is not None,
"systeminfo.generator": "systemapi",
},
)
if printer and printer.is_operational():
firmware_info = printer.firmware_info
+30 -49
View File
@@ -1551,19 +1551,21 @@ class DynamicZipBundleHandler(StaticZipBundleHandler):
return self.stream_zip(files)
class SystemInfoBundleHandler(StaticZipBundleHandler):
class SystemInfoBundleHandler(CorsSupportMixin, tornado.web.RequestHandler):
# noinspection PyMethodOverriding
def initialize(self, access_validation=None):
self._as_attachment = True
self._attachment_name = "octoprint-systeminfo-{datetime}.zip"
self._access_validator = access_validation
self._compress = True
@tornado.gen.coroutine
def get(self, *args, **kwargs):
if self._access_validator is not None:
self._access_validator(self.request)
from octoprint.cli.systeminfo import get_systeminfo
from octoprint.cli.systeminfo import (
get_systeminfo,
get_systeminfo_bundle,
get_systeminfo_bundle_name,
)
from octoprint.server import (
connectivityChecker,
environmentDetector,
@@ -1571,54 +1573,33 @@ class SystemInfoBundleHandler(StaticZipBundleHandler):
safe_mode,
)
from octoprint.settings import settings
from octoprint.util import dict_flatten
systeminfo = get_systeminfo(environmentDetector, connectivityChecker)
systeminfo["browser.user_agent"] = self.request.headers.get("User-Agent")
systeminfo["octoprint.safe_mode"] = safe_mode is not None
terminaltxt = None
if printer and printer.is_operational():
firmware_info = printer.firmware_info
if firmware_info:
systeminfo.update(
dict_flatten({"firmware": firmware_info["name"]}, prefix="printer")
)
if hasattr(printer, "_log"):
terminaltxt = list(printer._log)
logbase = settings().getBaseFolder("logs")
systeminfotxt = []
for k in sorted(systeminfo.keys()):
systeminfotxt.append("{}: {}".format(k, systeminfo[k]))
files = [
systeminfo = get_systeminfo(
environmentDetector,
connectivityChecker,
{
"name": "systeminfo.txt",
"content": octoprint.util.to_bytes("\n".join(systeminfotxt)),
"browser.user_agent": self.request.headers.get("User-Agent"),
"octoprint.safe_mode": safe_mode is not None,
"systeminfo.generator": "zipapi",
},
{"path": os.path.join(logbase, "octoprint.log"), "name": "octoprint.log"},
{"path": os.path.join(logbase, "serial.log"), "name": "serial.log"},
{
"path": os.path.join(logbase, "plugin_softwareupdate_console.log"),
"name": "plugin_softwareupdate_console.log",
},
{
"path": os.path.join(logbase, "plugin_pluginmanager_console.log"),
"name": "plugin_pluginmanager_console.log",
},
]
if terminaltxt is not None:
files.append(
{
"name": "terminal.txt",
"content": octoprint.util.to_bytes("\n".join(terminaltxt)),
}
)
)
return self.stream_zip(files)
z = get_systeminfo_bundle(
systeminfo, settings().getBaseFolder("logs"), printer=printer
)
self.set_header("Content-Type", "application/zip")
self.set_header(
"Content-Disposition",
'attachment; filename="{}"'.format(get_systeminfo_bundle_name()),
)
for chunk in z:
try:
self.write(chunk)
yield self.flush()
except tornado.iostream.StreamClosedError:
return
def get_attachment_name(self):
import time