1168 Commits
Author SHA1 Message Date
Eric Callahan d549af915f docs: update changelog
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 19:56:30 -05:00
Eric Callahan 672c223cc6 docs: update README with a link to the changelog
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 19:55:37 -05:00
Eric Callahan 68c5fb6f6b git_deploy: strip comments when parsing python reqs
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 18:08:52 -05:00
Eric Callahan fce056e481 file_manager: fix notification sync on fast machines
Desktop class PCs may exit the request before the inotify observer
gains control of the loop.  When the observer does gain control
it will immediately notify as the sync mutex is no longer held,
this can result in sending  the websocket notification before
the response has returned.  Delay all notifications by 5ms to prevent
this.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 18:08:51 -05:00
Eric Callahan a02209443e server: remove duplicates when loading components
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 18:08:51 -05:00
Eric Callahan 2cda75ff2c utils: simplify sentinel object
Use an enum to represent the sentinel rather than a singleton object.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 18:08:50 -05:00
Eric Callahan 0e80e301f0 button: remove stale sentinel import
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 18:08:50 -05:00
Eric Callahan e32fd688e4 moonraker: correct stale annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 18:08:50 -05:00
Eric Callahan 5a504243df app: use Jinja2 to render the welcome landing page
Read the template using the "source_info" utility, which
uses a zip-safe method to read a file.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2023-02-22 18:08:49 -05:00
Eric Callahan 7520d0e7b1 install: update script to set PYTHONPATH env var
This is preferable to setting the WorkingDirectory item in
the systemd unit, as its possible to switch between git repos
and installed wheels without requiring root.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 18:08:49 -05:00
Eric Callahan 5ffd18d132 machine: update install validation to use package
If the "moonraker" entry point is available use it as an executable.  Otherwise
launch the module through the "-m" switch.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 18:08:48 -05:00
Eric Callahan 79467e6484 utils: add source_info utility module
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 18:08:48 -05:00
Eric Callahan 277aecd305 moonraker: convert utils.py to a package
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 18:08:47 -05:00
Eric Callahan f48c18bfda utils: add support for package version retreival
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 18:08:47 -05:00
Eric Callahan a3121775fc build: add initial support for pdm build
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 18:08:46 -05:00
Eric Callahan a5790d4b84 install: add moonraker system deps json file
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 12:41:57 -05:00
Eric Callahan b50057c3ba install: remove dependency on pycurl
Moonraker no longer uses the curl http client backend.  The curl
commandline client is still used in some scripts and thus has been
retained.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 12:16:28 -05:00
Eric Callahan 15f37827a1 test: fix imports
The tests are stale and will not run successfully against the current
code.  This will be addressed in a future series of patches.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 12:16:27 -05:00
Eric Callahan 0f8638fec7 components: correct imports
All imports must now be relative to work correctly with the
moonraker parent package.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 12:16:27 -05:00
Eric Callahan b9a17e07e9 moonraker: convert code to a package
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-22 12:16:26 -05:00
Eric Callahan a5d63db9a6 server: rename moonraker.py to server.py
Signed-off-by:  Eric Callahan <arksiine.code@gmail.com>
2023-02-21 18:05:01 -05:00
Eric Callahan 1e7be4598c docs: add a changelog
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-21 16:54:29 -05:00
Eric Callahan 833519ecc3 docs: update file_manager documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-21 12:24:54 -05:00
Eric Callahan dce3b9eaf5 file_manager: add metadata scan endpoint
Support manual scan requests for systems where inotify
does not function correctlly (network shares).  This endpoint
may also be used to force a rescan of files that have already
had an initial scan.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-21 12:10:56 -05:00
Eric Callahan 9178b3833c file_manager: improve observer log message
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-21 07:33:45 -05:00
Eric Callahan 522fdab63d metadata: simplify the S3Dv5 temp regex
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-21 06:24:17 -05:00
Eric Callahan 7845390dd1 file_manager: support uploading to symlinks
Previously Moonraker disabled writing to symbolic links, as
doing so would overwrite the link.  Moonraker now resolves
the link, overwrites the file, and manually emits a websocket
notification.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2023-02-20 20:42:19 -05:00
Eric Callahan 0f7b781f57 file_manager: process metadata changes when no observer is configured
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-20 19:49:48 -05:00
Eric Callahan 347c9f4d2b file_manager: improve duplicate notifcation detection
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-20 19:36:58 -05:00
Eric Callahan 2fd668bf0d file_manager: implement configurable fs observer
Currently the choices are "none" and "inotify".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-20 19:36:58 -05:00
Eric Callahan 1e97571aa8 file_manager: refactor attribute names
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-20 19:36:57 -05:00
Eric Callahan 7330c2c123 file_manager: add request notifcation fallback
Schedule fallback websocket notifications in the event that
inotify is unable to watch a file system.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-20 19:36:57 -05:00
Eric Callahan 51e307dbd6 file_manager: don't queue "create from move" events
Treat these events as if they were actual file write events.  They
will reset the node completion time and suppress the notifcation.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-20 19:36:56 -05:00
Christian Speich 45506647a7 metadata: Add support for Simplify3D v5
Signed-off-by: Christian Speich <christian@spei.ch>
2023-02-20 19:35:37 -05:00
Eric Callahan 3917c9cd56 docs: fix minor typos
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-20 17:47:39 -05:00
Morton Jonuschat b2ba52ce3d sensor: add support to track generic single value sensors
This feature implements a sensor component that can be used to
track/log generic sensors from multiple sources. Each sensor
can have properties like unit of measurement, accuracy and a
display name that help frontends display the tracked measurements.


Signed-off-by: Morton Jonuschat <mjonuschat+moonraker@gmail.com>
2023-02-20 17:43:41 -05:00
Eric Callahan 0a811b9e44 file_manager: cleanup coroutines on close
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-17 16:40:31 -05:00
Eric Callahan 36de982692 docs: document file manager API fix
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-17 15:04:04 -05:00
Eric Callahan a8c82b4560 moonraker: bump API version for patch
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-17 14:28:18 -05:00
Eric Callahan 7dac9c3961 file_manager: queue move event notifications
It is possible for a move event to occur shortly after a directory
is created.  These events are not bundled as part of an operation
like "copy", so they should not be suppressed, however the
notification should be emitted after the "create_dir" from its
parent is emitted.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-17 12:29:10 -05:00
Eric Callahan d39792b84e file_manager: allow concurrent inotify processing
All of the awaitable calls in the inotify loop only block to
postpone notifications.  Only gcode notifications require async
processing due to metadata analysis.  Queue these notifications
while allowing inotify events to be received concurrently.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>

fix
2023-02-17 08:24:55 -05:00
Eric Callahan 9f08aad6f6 file_manager: improve notification sync
Most requests do not require waiting for inotify to process the
file event before exiting.  Rework the NotifySyncLock to make this
optional.  Replace the write mutex with the sync lock itself,
a guarantee that the synchronization state is cleaned up when
a request is complete.

This implementation avoids potential deadlocks or long wait times
when inotify is not enabled on a file system.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2023-02-16 19:37:34 -05:00
Eric Callahan 87dba2f2e2 template: handle render exceptions
Re-raise as either a ServerError or ConfigError as appropriate.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-14 14:13:06 -05:00
Eric Callahan a40dae2bc8 file_manager: improve klipper config detection
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-13 15:33:04 -05:00
Eric Callahan bec9a66411 klippy_connection: fix regression in state reporting
Moonraker should only force the state to report as "startup"
when Klippy is connected and it hasn't detected a transition
to startup.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-11 11:43:18 -05:00
Eric Callahan dbd1b4ac1b github: increase the max line length to 88 characters
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-11 11:43:17 -05:00
Eric Callahan 9b9a6d0646 http_client: remove escape_url method
This method will not work correctly if any individual part contains
a special character.  For example, if an item in the path contains
a "#", the regex will return an incorrect result.  Likewise, if any item
in a query string contains an "&" the query string will be correctly
escaped.

All urls supplied to the http client must be escaped by the consumer.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-11 11:43:17 -05:00
Eric Callahan 0b4e604c95 webcam: remove call to escape_url
The configured url should already be escaped.  It isn't possible to
reliably quote a full url if any of the parts contain special characters.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-11 11:43:16 -05:00
Eric Callahan 5661b0216c simplyprint: remove call to escape_url
The url received from SimplyPrint should already be escaped.  It
isn't possibly to reliably quote a full url if any of the parts contain
special characters.

This commit also corrects some minor type checking issues.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-11 11:43:16 -05:00
Eric Callahan 55ebe120c5 power: resolve url encoding issues
Dynamic parts of the url must be encoded individually to
guarantee correct url generation.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-11 11:43:15 -05:00
cmerkle 0de712e822 power: add support for Hue device groups
Signed-off-by: Clayton Merkle <clay.merkle@gmail.com>
2023-02-09 11:15:27 -05:00
Eric Callahan 5325693ed6 machine: report provider in system_info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-08 17:44:57 -05:00
Eric Callahan 8c7b93c6dd machine: fix supervisord active state reporting
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-08 17:00:39 -05:00
Eric Callahan 25d2ad4af6 docs: update SimplyPrint documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-08 16:34:18 -05:00
Eric Callahan 3710d49f46 docs: various small updates
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-08 16:32:45 -05:00
Eric Callahan c5c6366a84 docs: document shutdown_action option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-08 11:11:35 -05:00
Eric Callahan ea4ec1f424 scripts: add halt polkit rules
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-08 11:11:34 -05:00
Eric Callahan 8010f1dda2 machine: add shutdown action option
Signed-off-by:  Eric Callahan <arkisne.code@gmail.com>
2023-02-08 11:11:34 -05:00
Eric Callahan f0b82afde4 machine: remove unnecessary supervisord handlers
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-08 06:02:25 -05:00
Eric Callahan 645f0c9acf machine: add container detection logging
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-08 06:00:01 -05:00
Eric Callahan d70dfaeebd docs: update machine config documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-08 05:42:30 -05:00
Eric Callahan b02224485e machine: rename supervisord provider
This is a cli providers, so rename it to supervisord_cli.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-08 05:36:57 -05:00
Eric Callahan d9579c9374 shell_command: allow optional success codes
Some commands may return codes other than zero on a successful
return.  Allow callers to specify an optional list of return codes that
will return success without raising an exception.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-07 19:10:18 -05:00
Eric Callahan c69441955a machine: support supervisord service info extraction
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-07 19:10:17 -05:00
Eric Callahan 5aa645f974 machine: simplify extract_service_info() call
Don't require the caller to specifiy properties, use the default
property list if not specified.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-07 19:10:17 -05:00
Eric Callahan 2fb136449a machine: fix supervisorctl command arguments
According to the supervisord documentation the `-c` option is used to
specify the configuraiton file.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-07 19:10:17 -05:00
Eric Callahan 8335906443 machine: automate supervisord process init
Don't hardcode klipper and moonraker, detect them along with all other
allowed services.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-07 19:10:16 -05:00
Eric Callahan 5807757efa Revert "announcements: enable dev_mode when the debug flag is set"
This reverts commit 83e0947d31.
2023-02-07 19:09:14 -05:00
Eric Callahan 0db655b9d6 github: update lint workflow
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-07 11:29:37 -05:00
Eric Callahan 385b9a1b7a update_manager: handle rev-list on tagless repos
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-07 11:20:08 -05:00
Eric Callahan d75831f10a update_manager: require at least two parts in a tag
Allowing only a single part in the regex resulted in repos
without tags being assigned erronous version info.  With
this change, the following tags can be parsed:

v1.0
v1.0.2
1.0
1.0.2

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-07 11:09:50 -05:00
Eric Callahan c331c5a7d7 update_manager: fix semver conversion
When converting a semantic version to a list for comparisons
guarantee that the base version has 3 parts.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-07 10:28:36 -05:00
Eric Callahan 4ff7a50821 update_manager: relax semantic tag requirement
Allow tags versions with one, two, or three parts.  The following
examples are now valid:

v1
v1.3
v1.0,10

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-07 08:06:13 -05:00
Eric Callahan 90c7b80f37 docs: add bridge socket documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-06 19:55:36 -05:00
Eric Callahan 83e0947d31 announcements: enable dev_mode when the debug flag is set
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2023-02-06 18:12:29 -05:00
Eric Callahan 4af483c786 database: remove unnecessary BytesIO conversion
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-06 15:22:46 -05:00
Eric Callahan 559df5aea1 websockets: implement websocket-klippy bridge
Provide a new websocket implementation that creates a near one to one
bridge with a Unix Socket connection to Klippy.  This may be used to
access Klippy APIs not otherwise available over the primary websocket,
such as the various "dump" commands.

Unlike the primary websocket Moonraker does not decode or inspect
data that passes through the bridge.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-06 15:22:45 -05:00
Eric Callahan f9086181b8 moonraker: bump API version to 1.2.0
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-06 11:24:17 -05:00
Eric Callahan 198bff6aba docs: update_manger documenation change
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-06 11:17:26 -05:00
Eric Callahan 01977c8775 update_manager: refactoring
Code style and naming convention improvements.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-06 07:50:08 -05:00
Eric Callahan c8ad69b902 update_manager: add individual refresh endpoint
This endpoint allows clients to refresh items on an individual basis
when the "name" parameter is specified.  This endpoint replaces

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-06 06:42:56 -05:00
Eric Callahan f50fa3c5e7 update_manager: add package resolution check to apt backend
Make sure packages within the package list exist prior to installation.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-05 19:25:54 -05:00
Eric Callahan 21a7928ea2 update_manager: pip improvements
Re-implement pip updates using a pinned version.  A version
check is now always done prior to installing python requirements,
updating when necessary.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-05 19:25:54 -05:00
Eric Callahan 76500fe9f9 update_manager: improve dependency detection
Parse system packages and python requirements prior to and after each
updating, using the difference to determine if an update is necessary.
Only the new detected packages are installed unless the "force" variable
is set.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-05 19:25:53 -05:00
Eric Callahan a413f4e4cd websockets: guarantee subscription removal
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-04 16:46:03 -05:00
Eric Callahan 1be19be747 klippy_connection: rework klippy initialization
Handle a race condition where a shutdown event could be received
from the webhooks subscription during initialization.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-02-04 16:43:35 -05:00
Quinn Damerell babf97be3b Adding OctoEverywhere to the default service list
module: Adding OctoEverywhere to the default service list.

Adding OctoEverywhere to the default service list in machine.py so future installs of moonraker will allow the octoeverywhere service to be managed from frontends.

Signed-off-by: Quinn Damerell <quinnd@outlook.com>
2023-02-03 19:09:34 -05:00
Eric Callahan 61d3182bea docs: add thumbnail request documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-31 14:00:55 -05:00
Eric Callahan c1e4142a40 update_manager: add arch filter
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-31 14:00:54 -05:00
Eric Callahan b02e766a4d update_manager: log detected packages
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-31 14:00:54 -05:00
Eric Callahan fb618a46fd file_manager: fix thumbnails endpoint registration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-31 14:00:33 -05:00
Eric Callahan 55e852cd87 file_manager: add thumbnail request endpoint
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-31 06:13:44 -05:00
Eric Callahan 1bad68cb66 dbtool: improve encoded line regex
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-28 12:09:36 -05:00
Eric Callahan 6c4c7a00cf docs: add database backup/recovery
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-28 08:04:13 -05:00
Eric Callahan 50d22a2dff scripts: add database backup and restore scripts
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-27 19:25:09 -05:00
Eric Callahan 46a92e1900 dbtool: update backup location
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-27 07:57:51 -05:00
Eric Callahan 2392ccd719 scripts: update default database path for fetch-apikey.sh
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-27 06:10:16 -05:00
Eric Callahan 12b1befcbc authorizaton: type checking fix
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-24 07:08:23 -05:00
Eric Callahan 3dbc99fd84 docs: update authorization documentation
Authorization APIs are a now available over the websocket.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-24 06:20:02 -05:00
Eric Callahan d8941b3fb2 websockets: sanitize verbose logging
When verbose logging is enabled sanitize credentials from JSON-RPC
requests and responses.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-24 06:13:54 -05:00
Eric Callahan a5161816a7 websockets: decode jwts on authorized connections
Unix sockets never require authentication and it is possible for
Websocket connections to authenticate with the request itself.
In these cases the `identify` endpoint must still process an
access_token if provided, as it allows the front end to assign
the desired user to the connection.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-24 06:13:54 -05:00
Eric Callahan 80862799ed websockets: require re-auth on user logout
Propagate user state changes to open websockets and unix sockets.
If a websocket's user is logged out require re-authentication.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-24 06:13:53 -05:00
Eric Callahan 06ec5541e3 websockets: add support for API Key authentication
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-24 06:13:53 -05:00
Eric Callahan eca4c7e438 authorization: limit failed login attempts
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-24 06:13:52 -05:00
Eric Callahan 9d6719ed31 websockets: set a websocket connection limit
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-24 06:13:52 -05:00
Eric Callahan 5a22b21a40 authorization: relax auth header requirements
Don't raise an exception if the authorization header contains an
invalid value, such as Basic auth.  Ignore it and move on to the
next step in authentication.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-24 06:13:52 -05:00
Eric Callahan 4ca39bec0a authorization: authenticate over websocket
Register all of the "access" endpoints with the websocket.  Front
ends may now connect to the websocket without an oneshot token
and login.  If the front end already has a JWT for the user it
can be passed to the "identify" endpoint to authenticate directly.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2023-01-24 06:13:51 -05:00
Eric Callahan c83714bfe8 authorization: make api key authentication optional
Signed-off-by;  Eric Callahan <arksine.code@gmail.com>
2023-01-24 06:13:51 -05:00
pataar d4378eb051 notify: bump apprise to v1.2.1
Signed-off-by: Pieter Willekens<git@pataar.me>
2023-01-23 17:50:29 -05:00
Eric Callahan c964e68bc8 docs: fix erroneous note in secrets section
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2023-01-18 19:47:52 -05:00
Eric Callahan 2ad7a6a087 power: log the traceback on device init errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-18 19:31:47 -05:00
Eric Callahan db81607370 machine: use direct systemctl commands for reboot/shutdown
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-16 12:42:21 -05:00
Eric Callahan a154c5fa51 machine: add moonraker-obico to default services
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-12 18:10:30 -05:00
Eric Callahan c9a1d0f3bb server: bump API version to 1.1.0
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-10 06:12:45 -05:00
Eric Callahan bf63798bb1 simplyprint: fix queue handler import
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-09 07:12:08 -05:00
Eric Callahan 3400094881 klippy_connection: minor change to is_ready() method
Use attribute to check the condition rather than the property.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-09 07:11:33 -05:00
Eric Callahan 486f659d20 docs: add new endpoints
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-08 13:50:09 -05:00
Eric Callahan a4b496d135 file_manager: fix internal access check
Include the reserved file check in the `can_access_path()` method.  This
fixes a potential vulnerability in the notifier where it may be possible
to attach a reserved file to a notification.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-08 13:50:08 -05:00
Eric Callahan fe9a9899e3 file_manager: reserved path fix
Raise an exception if an attempt is made to access .git folders.

Signed-off-by:  Eric Callahan <arksine.cde@gmail.com>
2023-01-08 13:50:08 -05:00
Eric Callahan 6021b39234 file_manager: implement zip endpoint
Provides an API for front ends to archive a list of files and/or
folders into a single zipped file.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-08 13:49:32 -05:00
Eric Callahan 53eda78b11 loghelper: moonraker log management
Move logger initialization out of the utils module into its own
module, loghelper.py.  This manager class simplifies access to the
underlying logger implementation and the queue listener.  Additionally
it allows for endpoint registration.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-06 12:20:54 -05:00
Eric Callahan 24dc8914d0 klippy_connection: implement manual log rollover
On systems where Klipper is installed as a service allow a
manual log rollover.  The rollover cannot be called while printing.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-06 12:20:53 -05:00
Eric Callahan ecf7fb9267 klippy_connection: add is_printing() and is_ready() methods
Several components throughout Moonraker determine whether or not
Klipper is printing or is ready before taking action.  This centralizes
queries in one area.  The checks do not query Klipper directly but
rather rely on subscriptions to push state to Moonraker.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-06 12:20:52 -05:00
Eric Callahan 019c5fc416 app: move reserved endpoints to klippy_connection
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-06 06:14:45 -05:00
Eric Callahan 225ec588eb docs: document allowed services
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-02 07:46:44 -05:00
Eric Callahan 690f841768 machine: introduce custom allow list for service control
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-02 07:46:43 -05:00
Eric Callahan b3a9447392 power: add support for multiple bound services
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2023-01-02 06:30:18 -05:00
Matt White e3bcfb5ea0 mqtt: add option to publish states to individual mqtt topics
This change allows the user to choose the strategy for publishing
klipper states to MQTT.  The original strategy where all state
updates are published to a common topic is still the default, but
can be turned off using the "publish_combined_status" config option.

The newly added strategy is publishing individual state updates to
separate mqtt topics.  It is disabled by default, and can be enabled
with the "publish_split_status" config option.

Signed-off-by: Matt White <m.w.white@gmail.com>
2022-12-30 06:13:25 -05:00
Eric Callahan 358aee956b docs: clarify power on start usage
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-12-27 10:37:10 -05:00
Eric Callahan 1999b82a86 docs: update power documentation
Note how to override SDCARD_PRINT_FILE to power on
a device before a print starts.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-12-26 08:29:24 -05:00
Eric Callahan d6b1a724a8 eventloop: improve callback handling
Wrap all callbacks in a coroutine that handles exceptions.  This
should eliminate "task not retreived" errors.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-12-24 08:07:45 -05:00
Eric Callahan 3d3911d4fd docs: document the "force" power option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-12-24 06:37:18 -05:00
Eric Callahan aeea9a2efd power: introduce "force" argument for remote method calls
The "force" argument may be used turn on a device during a print
that is otherwise locked for normal requests.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-12-23 19:13:11 -05:00
Pedro Lamas a6b8a8a3e9 docs: add "reset" parameter to post endpoint
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2022-12-23 08:07:04 -05:00
Pedro Lamas 51fee3e7a1 job_queue: add "reset" parameter to post endpoint
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2022-12-23 08:07:04 -05:00
Eric Callahan f7d8af6e12 docs: add the "jump queue" API
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-12-22 14:09:15 -05:00
Eric Callahan 129b0feb81 job_queue: add "jump" endpoint
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-12-22 12:48:23 -05:00
Eric Callahan f296c6fadd update_manager: allow old application naming convention
While the [update_manager client ...] naming convention is
deprecated it should not be disallowed.  This fixes service restart
issues using the old naming convention.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-12-12 16:59:22 -05:00
Eric Callahan dde9bcc752 metadata: add object detection logging
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-30 16:40:36 -05:00
Eric Callahan 1cb46a8f8f metadata: fix check for existing objects
Don't process files with EXCLUDE_OBJECT_DEFINE gcode
commands.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-30 13:43:39 -05:00
Eric Callahan f3f39b7ab0 metadata: handle object processing identity
This allows object processing for slicers with aliases.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-28 10:50:40 -05:00
Eric Callahan f3e13faf19 file_manager: validate Klipper config path
Warn when Klipper's configuration file is not located in
the "config" subfolder of the datapath.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-26 19:30:59 -05:00
Eric Callahan 7b8c2c3409 metadata: add support for A3dp Slicer
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-26 06:22:27 -05:00
Pedro Lamas b67a08a65b machine: use virtualization.virt_identifier property
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2022-11-22 05:59:18 -05:00
Albert Møller Nielsen c61ff8b252 simplyprint: preprare for release
Signed-off-by: Albert Møller Nielsen <albert@simplyprint.io>
2022-11-20 19:16:08 -05:00
Eric Callahan 362bc1a3d3 machine: fix typos and clarify supervisord docs
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-18 10:42:44 -05:00
mirokymac 48f3bb2189 machine.py: add support for supervisord service management
Signed-off-by: mirokymac <toufubomb@gmail.com>
2022-11-18 10:37:33 -05:00
Eric Callahan e628b243c2 docs: add canbus to /machine/system_info result
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-16 16:52:20 -05:00
Eric Callahan 88ebc21318 requirements: update distro 1.8.0
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-16 14:33:47 -05:00
Eric Callahan 68f5de6d2d machine: report canbus info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-16 14:20:07 -05:00
Eric Callahan bfe20433f9 mqtt: update compatibility with latest client
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-16 10:11:59 -05:00
Eric Callahan bd1fd63b14 requirements: update python dependencies
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-16 10:11:59 -05:00
pataar 7afd556c21 notify: upgrade apprise to version 1.2.0
Signed-off-by: Pieter Willekens <me@pataar.nl>
2022-11-16 10:10:50 -05:00
Markus Küffner 8b2e8c2a4e scripts: update streaming-form-data dependency
Updates streaming-form-data to Version 1.11.0 to be compatible with Python 3.11.0

Signed-off-by: Markus Küffner <kueffner.markus@gmail.com>
2022-11-16 10:09:23 -05:00
Eric Callahan 490d27b7de extensions; type checking fix take two
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-13 14:30:24 -05:00
Eric Callahan 0c6e860534 extensions: fix type checking for Python 3.7
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-13 14:16:59 -05:00
Eric Callahan 7f58f2274e docs: add unix socket documentation 2022-11-13 12:32:07 -05:00
Eric Callahan b2d109a840 extensions: serve JSON-RPC API over a unix socket
Support unix connections with full access to all JSON-RPC APIs.
Internally these connections are treated as websocket connections,
however the underlying transport protocol is simplfied.  Packets
are JSON encoded objects terminated with an ETX character.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-10 11:57:21 -05:00
Eric Callahan 53129bef7e utils: add method for retrieving unix socket peercred
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-09 07:15:33 -05:00
Eric Callahan f089794adc websockets: create a client base class
Separate out code that applies to both standard websockets and the
future unix socket implementation.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-09 07:15:33 -05:00
Eric Callahan 5a3b1b6e5c docs: fix list roots endpoint
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-11-07 07:54:43 -05:00
Eric Callahan ddf3325dae docs: document list roots
Update documentation to note that the uds now supports
templates.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-06 11:48:00 -05:00
Eric Callahan bb7cd27be5 machine: fix typo in sudo access request
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-06 11:43:52 -05:00
Eric Callahan a8018afd46 file_manager: always deny access to .git folders
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-06 10:51:32 -05:00
Eric Callahan d490796da9 file_manager: fix permission reporting
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-06 10:51:32 -05:00
Eric Callahan 36536535bc klippy_connection: update configuration
Use the ConfigHelper's getpath() method to configure the
unix socket.  The option may now be a template where the
datapath is passed into the context.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-06 10:51:31 -05:00
Eric Callahan b291d94596 file_manager: implement additional reserved path filters
Do not add inotify watches for reserved paths that exclude
write acccess.  Do not return include reserved paths in
file list requests without read access.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-06 10:51:31 -05:00
Eric Callahan 484950cb40 confighelper: implement getpath
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-06 10:51:30 -05:00
Eric Callahan e8dad1c8c0 file_manager: add list roots endpoint
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-11-06 10:51:30 -05:00
Misterke 130c2a48f0 file_manager: disallow drilling down protected folders
Signed-off-by:  Kurt Haenen <kurt.haenen@gmail.com>
2022-11-05 10:45:46 -04:00
pataar 6f43940270 docs: improve notifier reference when using the action
This was unclear for users.

Signed-off-by: Pieter Willekens <me@pataar.nl
2022-11-04 16:20:37 -04:00
Eric Callahan 779997c2b8 git_deploy: refresh previously corrupt repos
It is possible that the user manually corrected a corrupt repo.
If a repo makes it past initialization reset the corrupt flag.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-10-22 19:03:48 -04:00
Eric Callahan 1a3689cb7d klippy_connect: resolve the uds path
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-22 16:45:16 -04:00
Eric Callahan 1ef34b8b60 machine: improve default database handling
Don't force a symlink to the default database if
the subfolder exits.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-22 16:44:51 -04:00
Eric Callahan 80a7d461ed data-path-fix: correct moonraker.conf typo
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-22 11:21:17 -04:00
Eric Callahan 4c963de0fc data-path-fix: add gcode path option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-21 19:25:15 -04:00
Nick Douma 6afa664ac9 ldap: Add option to use a customer LDAP query for looking up the user logging in
This allows for more advanced integration of LDAP databases that are not
covered by the default behaviour of is_active_directory.

Signed-off-by: Nick Douma <n.douma@nekoconeko.nl>
2022-10-21 19:24:35 -04:00
Eric Callahan 379bcb10f9 data-path-fix: add missing alias
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-21 15:23:45 -04:00
Eric Callahan 8540f5a794 data-path-fix: add command line arguments
Give the script flexibility for use on installs with multiple instances.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-21 14:26:03 -04:00
Eric Callahan 1f86943cbb gpio: relax error handling
Increase the error threshold to 50 and reset within a 5 second threshold.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-21 14:13:17 -04:00
Eric Callahan 4df0b4d532 machine: abort validation if the backup config is loaded
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-21 10:26:25 -04:00
Eric Callahan 1190aba4b7 machine: add logging to validation init
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-21 10:26:25 -04:00
Jim C K Flaten 25adba0bf6 docs: Correct minimum_event_time example
The internal variable is called `min_`, but the config option is called `miniumum_`.
2022-10-21 10:23:29 -04:00
Eric Callahan 974b37dad8 machine: improve multi-instance validation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-20 20:27:02 -04:00
Eric Callahan 8f444a908e shell_command: error message fix
Use the original command in the message rather than the
list generated by shlex.split().

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-20 16:54:35 -04:00
Eric Callahan 59cc8c6c7b update_manager: report errors in update response
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-20 16:54:35 -04:00
Eric Callahan e4a670a380 update_manager: improve corrupt repo detection
It that "git status" will not detect some repo issues, these are only
found after a fetch.  When this condition is detected save the repo
state and report that the repo is corrupt and invalid.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-20 16:54:34 -04:00
Eric Callahan 74f43cad6e git_deploy: notify attempts to fix loose objects
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-19 19:32:54 -04:00
Eric Callahan c7e290a3cd update_manager: improve web client error handling
Singed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-19 17:58:58 -04:00
Eric Callahan 38b035389d power: improve logging
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-19 16:35:49 -04:00
Eric Callahan 1f1c590409 power: add initial state support for all devices
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-10-19 13:43:14 -04:00
Franklyn Tackitt 6131c7afc1 Git submodules use a .git file instead of a directory
I'm playing with using git submodules to track my entire printer config,
 and moonraker only works with separate clones as is. Using `.exists()`
 instead of `.is_dir()` allows moonraker to control the submodules.

Signed-off-by: Franklyn Tackitt <git@frank.af>
2022-10-19 13:41:35 -04:00
Eric Callahan 4954cc74cd machine: change sudo folder access test
The previous "/lost+found" is not available on all systems.  Change to
"/root", which should be available.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-19 06:21:18 -04:00
Eric Callahan f745c2ce17 database: remove legacy database warning
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-18 14:13:25 -04:00
Eric Callahan d6bdad3a9d machine: announce required update via gcode terminal
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-18 14:07:27 -04:00
Eric Callahan 9a466f3b22 server: improve warning formatting
Introduce a "raw" parameter for /server/info that defaults to False.
Front ends that do not wish to recieve warnings with html line breaks
may set this parameter to True, otherwise newlines will be replaced
with "<br/>".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-18 07:23:25 -04:00
Eric Callahan a8cbfe6345 file_manager: improve gcode path warning
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-10-18 07:23:25 -04:00
Eric Callahan 6b3c78da71 docs: fix notifier debug endpoint
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-10-18 05:20:39 -04:00
pataar b981dc109d notify: add server endpoints for notifier to list and test them
Signed-off-by: Pieter Willekens <me@pataar.nl>
2022-10-18 05:18:30 -04:00
Eric Callahan f1c4d6b143 machine: validation fix for new installs
Add a missing return statement to _link_data_subfolder.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-17 06:30:54 -04:00
alfrix 7552631b65 update_manager: fix error message displaying the wrong option
Signed-off-by: Alfredo Monclus <alfredomonclus@gmail.com>
2022-10-16 10:31:15 -04:00
Eric Callahan 06279d0e10 data-path-fix: update for fresh installs
Don't require the database and gcode paths to exist.  Fall back on the
default location if they do not.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-16 07:53:51 -04:00
Eric Callahan 7e35e54a71 machine: increase timeout for sudo access check
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-15 20:01:19 -04:00
Eric Callahan 05ca71f5a8 machine: relax config validation
Don't raise an exception if the option in a path does not exist.  Remove
the option and fall back to the default path location

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-15 19:58:34 -04:00
Eric Callahan 3ad7d0668a scripts: add data-path-fix script
This script can be used to fix broken installations on
MainsailOS and FluiddPi distributions running a
single instance of Moonraker.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-15 11:42:43 -04:00
Eric Callahan b9cac62db8 update_manager: log when refresh is bypassed
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-15 11:07:31 -04:00
Eric Callahan 65e24a14dc update_manager: do not refresh when install validation is pending
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-15 10:52:05 -04:00
Eric Callahan 53fcc7386f machine: increase timeouts for sudo commands
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-15 10:52:04 -04:00
Eric Callahan 00c4846d11 machine: validation fixes
Protect the sudo request with a lock.  Add retries to the sudo
commands.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-15 08:37:45 -04:00
th33xitus f0e4678fab docs: use term "sudo" instead of "root"
Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2022-10-15 06:11:14 -04:00
th33xitus fb327a6ca9 machine: use term "sudo" instead of "root"
Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2022-10-15 06:11:14 -04:00
Eric Callahan 500e8f3b68 machine: disable file write access when validation fails
Prevent users from uploading files before validation is complete, as
this can populate one of the subfolders resulting in a failure when
attempting to symlink the original path.

When validating the config symlink the database first.  This should
allow Moonraker to correctly move the database should an error
be encountered when validating the other config options.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-15 06:01:36 -04:00
Eric Callahan fb679aa056 database: minor fallback fix
Fallback if not using the default path and the database has not been created.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 19:25:47 -04:00
Eric Callahan 2603cc2e8f docs: update deprecations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 485b29490a update_manager: deprecate repo debug option
Use the "debug" command line option to enable debug
features for the update manager.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 1e8c7f0915 database: register debug endpoints
Allow full database access to registered debug endpoints.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 30e2ec04b7 app: add support for debug endpoints
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 86fc1057f7 server: deprecate debug logging option
Add a debug option to the command line to enable
debug features.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan d2cbd1d0a0 finish-upgrade: helper for finishing updates
This script provides a method for users to complete an upgrade
that requires elevated privileges via ssh.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 485c723a3c install: only write initial config for first time installs
This prevents an upgrade from unintentionally populating
the config directory when a legacy install exists.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 9021fbea48 machine: use default password for validation
For legacy Raspberry Pi installations attempt to automate
the update using the default password.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan be9aff8b5e power: loosen bound service requirement
Specifically check against the detected service unit, otherwise
allow a power device to bind to any available service.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan f22b859a0f docs: update install documentation
Moonraker no longer takes an `alias` command line option.  Use `printer_data`
as a placeholder for the default data folder.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 26088cdfff install: change env location and rework default datapath
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 41ea45a486 moonraker: remove alias option
Differentiate instances based on the data path provided.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan c3cd24b3bf docs: add "instance_ids" field to system_info response
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 266c5b53d1 machine: extend system info request with unit names
Report the unit names for both Moonarker and Klipper.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan d3484e8c13 klippy_connection: report systemd service info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 59471a7959 docs: update machine documentation
Add documentation for the new validation options, and document
changes to the sudo APIs.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan dd7e480cdd docs: update documentation reflected new folder structure
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 577f55306e install: add data path and alias options to the script
Additionally, rework the systemd unit so it is not necessary to
overwrite and reload systemd when changes are made to Moonraker's
arguments.  Use a symbolic link for the executable and an environment
flle to supply the arguments.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 636aca6cbd app: add sudo request form to welcome page
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 5259a6fd0a moonraker: perform install validation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 6e56815b42 machine: implement install validation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 7004722499 app: report if https is enabled
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 7217b36f9b file_manager: handle overlapped inotify watches
Handle exceptions raised when adding a new watch.  Warn
the user and skip adding the node to the watched tree.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 069a655df8 file_manager: update reserved path handling
Allow components to register reserved paths, then perform reserved
path validation it upon request.  Reserved paths may be registered as
read-only or no access.  Any request to modify an file/folder that is
either reserved or a child of a reserved path is rejected.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 4df6aba6c0 app: use datapath for ssl certificate storage
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 1327602ec3 secrets: add support for the data folder
The secrets module will now look for "moonraker.secrets"
in the data folder.  If the file does not exist the deprecated
"secrets_path" option will be used as a fallback.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 524552eb84 database: add support for the data folder
Deprecate the "database_path" option.  If the database
does not exist, however the "database_path" does, it
will be used as a fallback.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan 480ebfac8e file_manager: add support for new "data_path"
The config and logs paths are no longer configurable,
they all exist as folders or symbolic links within the primary
data folder.  The gcode path no longer relies on Klipper to
specify the location, instead Klipper's virtual_sdcard path
shold be configured to the location of the "gcodes" folder
in the data path.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan b78cdf9660 moonraker: add data_path and alias command line arguments
Prepare to move away from configurable paths.  This will
resolve potential security vulnerabilities in the event that
a user's access is compromised.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-14 15:15:41 -04:00
Eric Callahan edaeb17f38 docs: update simplyprint documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-12 11:14:12 -04:00
Eric Callahan 91e48200d6 simplyprint: implement direct layer detection
Klipper now has the ability to report the current layer on
properly configured slicers.  Prefer this value if available,
otherwise fall back to layer detection.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-11 19:29:36 -04:00
Eric Callahan c48fe7307a job_state: add layer_changed event
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-11 19:29:36 -04:00
Eric Callahan 48674a46e1 simplyprint: add support for configured ambient sensors
Users may specify a dedicated ambient sensor in the
[simplyprint] configuration.  If the specified sensor is
invalid or no sensor is specified ambient detection
will fall back to an estimate using the extruder.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-11 19:29:36 -04:00
Eric Callahan 785213b2b3 simplyprint: bring up AI stream to correct state
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-11 18:01:57 -04:00
Eric Callahan 6e121c2221 simplyprint: implement "webcam_stream" demand
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-11 06:07:32 -04:00
Eric Callahan d5fa40df87 simplyprint: implement ping timer
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-11 06:07:32 -04:00
Eric Callahan f8d15d3baa simplyprint: remove keepalive
This will be replaced by a custom ping timer to the backend.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-11 06:07:31 -04:00
Eric Callahan 2e3188a48b klippy_connection: socket credential fix
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-10-11 06:06:19 -04:00
Mathis Mensing cd19b51117 app: add jpg files to AUTHORIZED_EXTS
Signed-off-by: Mathis Mensing <github@matmen.dev>
2022-10-10 19:41:30 -04:00
Pedro Lamas 60b871adbe metadata: strip delimiting quotes in strings
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2022-09-27 06:08:34 -04:00
SoftFever df24e3ea77 metadata: Add support to extract metadata from g-code files generated by Bambu Studio
Signed-off-by: Li Jiang <softfeverever@gmail.com>
2022-09-22 06:00:45 -04:00
Andrew Basson 07f4643070 docs(api-changes): fix method typo
Signed-off-by: Andrew Basson <andrew.basson@gmail.com>
2022-09-21 05:48:07 -04:00
alfrix 621739bb2b docs: web_api: update allowed system services 2022-09-21 05:40:34 -04:00
Rogerio Goncalves 4806ffd2ae proc_stats: expose network packets, errors and drops
Signed-off-by: Rogerio Goncalves <rogerlz@gmail.com>
2022-09-21 05:38:06 -04:00
pataar 21bb17743f notify: add ability to notify using a remote action
Signed-off-by: Pieter Willekens <me@pataar.nl>
2022-09-21 05:36:55 -04:00
Eric Callahan 5d856b9c49 simplyprint: suppress write exceptions
Its possible for the websocket client to disconnect before
read_message() returns None.   Await all calls to write_message()
to handle websocket closed exceptions.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-09-05 05:59:02 -04:00
pataar f047167b3b notify: upgrade apprise to version 1.0.0
Signed-off-by: Pieter Willekens <me@pataar.nl>
2022-08-30 10:19:41 -04:00
Eric Callahan d04e99a8ec simplyprint: automated file reset bugfix
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-28 13:45:21 -04:00
Eric Callahan 7f2d43de3d simplyprint: automate file reset for sp uploads
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-28 12:23:03 -04:00
Eric Callahan 3a03f48e0f simplyprint: report error messages
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-28 11:16:52 -04:00
Eric Callahan 25e79c78b2 klippy_connection: report Klippy's state message
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-28 11:16:52 -04:00
Eric Callahan b52b0bd98a webcam: improve default host handling
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-28 11:16:51 -04:00
Eric Callahan e8999363ed confighelper: raise duplicate exceptions
Moonraker requires that the configuration be parsed in 'strict' mode,
ie: duplicate sections are not allowed within the same file and duplicate
options are not allowed within the same section.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-28 11:16:51 -04:00
Grant Harding 78605db001 webcam: fixed rotation param
Signed-off-by: Grant Harding gharding@gmail.com
2022-08-28 11:16:02 -04:00
Eric Callahan e3cafb58bc docs: update "machine" component documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 07:16:15 -04:00
Eric Callahan db7474aa88 machine: use sudo password for commands if available
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 06:30:28 -04:00
Eric Callahan 272f7b946d machine: add endpoint to check sudo access
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:59:38 -04:00
Eric Callahan 59403e226b git_deploy: line length fix
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:54:48 -04:00
Eric Callahan 25d99207f0 authorization: implement permitted path registration
Allow components to register paths that bypass authentication
requirements.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:25:20 -04:00
Eric Callahan fd5053ecac app: improve debug logging
Dont log the full response when html is requested.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:22:23 -04:00
Eric Callahan 2314ea74c2 app: report asset path location
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:22:18 -04:00
Eric Callahan 942d595bc2 websockets: static type fix
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:21:56 -04:00
Eric Callahan e82fe46c11 moonraker: provide startup warnings as a list
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:20:58 -04:00
Eric Callahan 0d936d5af0 moonraker: track warnings by id
This makes it possible to remove warnings and prevent duplicates.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:20:33 -04:00
Eric Callahan 0dd8eee034 confighelper: add method to write the config to any folder
Signed-off-by:  Eric Callahan <arksine.cod@gmail.com>
2022-08-21 05:19:27 -04:00
Eric Callahan a4f9fbe298 confighelper: support config modification
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:19:12 -04:00
Eric Callahan a776f1f6dc git_deploy: improved moved origin handling
Query the detected url and make sure it redirects to the
expected url.  This closes a security vulnerability
where a remote could be changed to an arbitrary repo's url.

The `moved_origin` option is no longer necessary, however it
is currently used as an additional check.  In the future it will be
deprecated.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:18:44 -04:00
Eric Callahan 4b25b04c4f git_deploy: refuse recovery if repo is not verified
Close a security hole where an attacker could overwrite an existing repo
with any remote and run malicious code through an update.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:18:38 -04:00
Eric Callahan b5e7a5ba5a update_manager: resolve pip location issues
If the supplied python executable is a symbolic link attempt
to read the location at which it points.   If this is a virtualenv
this should give us the correct pip location.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:18:16 -04:00
Eric Callahan c24fd7d11c template: add support for UI templates
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:17:57 -04:00
Eric Callahan b7768671aa http_client: report final resolved url in response
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:17:36 -04:00
Eric Callahan 12161d12f5 machine: improve private ip detection
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:16:06 -04:00
Eric Callahan 4efb6575b7 machine: report provider type and container info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:15:19 -04:00
Eric Callahan c154d92499 machine: add support for setting a sudo password
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:13:44 -04:00
Eric Callahan a7b50a8068 machine: extract moonraker systemd unit info
This allows moonraker to validate and log the current unit file.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:13:31 -04:00
Eric Callahan cd24b116c6 utils: resolve the moonraker path to an absolute path
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-21 05:13:04 -04:00
Eric Callahan 66f9184c74 zeroconf: support binding to all interfaces
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-19 17:38:22 -04:00
Eric Callahan 49b3f78f20 docs: note how to bind to all interfaces
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-19 12:24:10 -04:00
Eric Callahan 97c8b05eee app: support binding to all interfaces
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-19 12:21:41 -04:00
Eric Callahan 853de9e8cb update_manager: resolve potential deadlocks on startup
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-18 07:17:54 -04:00
Eric Callahan 413e3b2f4f simplyprint: add power device fallback
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-08 19:48:13 -04:00
Eric Callahan 3424f1b3e2 machine: fix IP detection broadcast setting
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-08 19:26:19 -04:00
Eric Callahan c4e370fcff machine: improve LAN IP detection
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-08 19:20:56 -04:00
Pedro Lamas 8bbd269084 metadata: adds chamber temp support
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2022-08-08 17:56:27 -04:00
Eric Callahan a9345d19fa simplyprint: fix incorrect directive
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-08 17:37:35 -04:00
Eric Callahan 71e9085778 install: add wireless-tools dependency
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-08 17:03:09 -04:00
Eric Callahan 39f26dc31a simplyprint: silence stream errors
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-08-08 17:02:20 -04:00
Eric Callahan 6e253b0d42 webcam: fix default host fallback
Fallback to the loopback if unable to determine the
local ip address.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-08-08 16:55:59 -04:00
Eric Callahan 0188b81d4a dbus_manager: verify stat path exists
Signed-off-by:  Eric Callahan  <arksine.code@gmail.com>
2022-08-01 10:22:16 -04:00
Eric Callahan e0cf635d34 simplyprint: websocket write fix
Gracefully handle websocket closed conditions.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-30 15:16:52 -04:00
Eric Callahan ea29788ab1 docs: add simplyprint documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-28 10:57:25 -04:00
Eric Callahan c251a9d7ed simplyprint: initial implementation
This adds initial support for connecting Moonraker to the SimplyPrint
service.  Currently the connection defaults to SimplyPrint's dev/test
endpoint, this will be changed prior to official release.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-28 08:06:49 -04:00
Eric Callahan cd8954e36c metadata: Add support for Kiri:Moto and SimplyPrint
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-27 07:59:07 -04:00
Eric Callahan 5d4db16fd6 docs: update configuration documention
Note support for inline comments and the current behavior
for include directives.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-27 07:41:07 -04:00
Eric Callahan e264fa82b2 confighelper: don't overwrite option tracking
Its possible for any component to request a configuration
option from another component.  Don't overwrite the
inital value stored.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-26 19:34:40 -04:00
Eric Callahan a178a6cd01 confighelper: improve file parsing
Process included files in the order they are added.  This changes how
duplicate sections throughout included files are merged, options in
the last section to be parsed will take precedent.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-26 19:34:39 -04:00
Eric Callahan bdd0222a1c machine: handle exception if iwgetid fails
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-24 17:16:34 -04:00
Eric Callahan d713076947 docs: add webcam documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-24 12:05:54 -04:00
Eric Callahan 6b4020a6e9 moonraker: load webcam as a core component
This makes sure that the webcam APIs are always available.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-24 11:27:30 -04:00
Eric Callahan a3cae26e33 webcam: initial implememtation
The webcam module allows users to enter webcam configuration through
moonraker.conf while keeping compatibility with frontends that
store webcam data in the database.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-24 11:27:29 -04:00
Attila BODY cd6db1ee75 scripts: Following polkit versioning scheme change
Signed-off-by:  Attila Body <attila.body@gmail.com>
2022-07-19 17:35:30 -04:00
Frank Tackitt 16327ff551 install-moonraker: allow configurable virtualenv location
Signed-off-by: Franklyn Tackitt <git@frank.af>
2022-07-19 14:51:06 -04:00
Frank Tackitt 7cd29c068d authorization: set private network CORS header
In the future, an `Access-Control-Request-Private-Network` header will be sent with
 these requests, and servers must respond with `Access-Control-Allow-Private-Network`.

This will start with the next Chrome version (104), and Mozilla has marked the
 standard as "worth prototyping", which often leads to final implementation.

Signed-off-by: Franklyn Tackitt <git@frank.af>
2022-07-19 14:25:18 -04:00
olli-t 9fea1634b1 power: fix Hue implementation
Signed-off-by: Oliver Tetz olli.codes.some.lines@gmail.com
2022-07-18 08:17:16 -04:00
Eric Callahan bcb7a55996 power: fix type/checking formatting for Hue device
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-17 06:38:38 -04:00
lie_ink 4d803ec9e5 power: add support for hue devices
Signed-off-by: Oliver Tetz <olli.codes.some.lines@gmail.com>
2022-07-17 06:26:26 -04:00
Eric Callahan 3080885257 update_manager: change default refresh interval
Check for updates every 7 days rather than every 28 days.  This
is in preparation of an upcoming beta release.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-17 06:13:50 -04:00
Eric Callahan 53a3c64186 moonraker: move loop creation to the eventloop module
Python 3.10 deprecates "get_event_loop()", so it is necessary to
create a new loop and set it as active at startup.  Previously
Moonraker only did this after a soft restart.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-07-16 19:41:09 -04:00
Eric Callahan d37f91c9c8 power: type checking fix
For legacy purposes its possible that "initialize()" may be an
awaitable.   Ignore the type as it consues mypy.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-29 12:06:36 -04:00
Eric Callahan 31d4335e3e power: allow indefinite remote device init
Remote devices, such as the tplink smartplug and http
based devices, may not be immediately available when
Moonraker starts.  Previously this would result in an error.

Remote switches that requiring polling for state will now
reattempt initialization indefinitely.  This behavior brings
them in line with devices that are updated asynchronously.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-29 08:07:46 -04:00
Eric Callahan 835e49c10e klippy_connection: log raw peercred data on error
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-29 06:01:48 -04:00
Eric Callahan 0a0993f9e0 server: sleep 1ms after calling component close methods
This allows any cancelled tasks to run through the eventloop
before loop.stop() is called.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-06-28 19:21:21 -04:00
Eric Callahan 09550af466 mqtt: resolve connection blocking issues
Override the paho-mqtt client "reconnect()" method with
a method capable of taking a connected socket.  This allows
Moonraker to connect the socket asynchronously, then finish
establishing the connection.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-28 19:21:21 -04:00
Eric Callahan 0b31d7d0b2 eventloop: add async create socket method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-28 18:25:16 -04:00
Eric Callahan 371840a988 klippy_connection: increase the read buffer limit
Allow a buffer of up to 20 MiB to cover the reception of
a very large request.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-27 10:51:56 -04:00
Eric Callahan 1eaead1073 server: handle event exceptions
Don't allow exceptions to propagate beyond a call to
_process_event().  Make sure the future is not marked
as done prior to setting the result.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-27 10:51:49 -04:00
Eric Callahan 4bed314b0a authorizaton: fix static type checks
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-17 17:56:47 -04:00
Eric Callahan 8266376f46 authorization: fix minor typing issues
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-17 17:07:58 -04:00
Luca Schöneberg 58fa361c8c authorization: implement /access/info endpoint
Signed-off-by: Luca Schöneberg <luca-schoeneberg@outlook.com>
2022-06-17 11:19:12 -04:00
Eric Callahan a8b9fc0017 docs: document list feeds api
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-12 06:20:55 -04:00
Eric Callahan d19471fd4d announcements: implement list feeds endpoint
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-12 06:10:29 -04:00
Eric Callahan 14ec8472ef ldap: fix group validation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-11 17:06:54 -04:00
Eric Callahan a492ae983c docs: add ldap documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-10 11:19:53 -04:00
Eric Callahan 65d532a6cf reqs: add ldap3 python requirement
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-10 11:19:53 -04:00
Eric Callahan 7780a8a09e authorization: add ldap support
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-10 11:19:52 -04:00
Eric Callahan f52df8c7ed ldap: initial implementation
Introduce an ldap component that can be used authenticate
Moonraker users over ldap connections.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-10 11:19:52 -04:00
Eric Callahan 5081321a32 Revert "authorization: add LDAP support"
This reverts commit a86cbc77f6.
2022-06-08 06:23:19 -04:00
Eric Callahan d0cdd76bed Revert "install: add ldap requirements"
This reverts commit 7af8a03129.
2022-06-08 06:23:14 -04:00
Eric Callahan 250b93e89c git_deploy: fix install script parsing
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-08 06:13:17 -04:00
Eric Callahan 3b76d81155 machine: add sonar and crowsnest to allowed services
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-07 06:51:40 -04:00
Luca Schöneberg a86cbc77f6 authorization: add LDAP support
Signed-off-by: Luca Schöneberg luca-schoeneberg@outlook.com
2022-06-07 06:46:08 -04:00
Eric Callahan 7af8a03129 install: add ldap requirements
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-06-07 06:38:04 -04:00
Eric Callahan 74d6e35166 Revert "job_queue: always initialize state to "ready""
This reverts commit d53cf27264.
2022-06-01 17:37:03 -04:00
Eric Callahan d53cf27264 job_queue: always initialize state to "ready"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-05-22 06:02:46 -04:00
Eric Callahan f15ec23c3a http_client: increase max body size
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-05-21 06:27:56 -04:00
Eric Callahan 0164bb239e klippy_connection: fix bug during initialization
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-05-13 05:23:06 -04:00
Eric Callahan babfba1686 mqtt: allow unlimited connection attempts
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-05-12 19:37:33 -04:00
Eric Callahan 09ac00ce2e klippy_connection: request endpoints before setting the state
All of Klipper's endpoints should be available before Moonraker
reports the "ready" state.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-05-12 19:22:56 -04:00
Pierre Bedell 3d9f5dc6d9 metadata: expanded IceSL's support
Signed-off-by: Pierre Bedell pierre.bedell@gmail.com
2022-05-09 12:22:20 -04:00
Richard Mitchell 56097a35ad wled: Add extra control for wled effects
For the "Percent" preset the intensity controls the amount of the bar lit up 0-100
Work around issue when preset is re-enabled if sending intensity or speed while no preset is active

Removed control endpoint
Added missed toggle endpoint
Transition time to 0 for control changes

Signed-off-by:  Richard Mitchell <richardjm+moonraker@gmail.com>
2022-05-09 06:32:14 -04:00
Eric Callahan fcfa563d02 docs: fix minor typo
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-05-04 05:28:20 -04:00
Eric Callahan 59f2736bb6 docs: clarify location of moonraker.conf
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-05-04 05:25:40 -04:00
David Smith 2f09b74dc1 docs: correct flip_v for webcam vertical flip
Signed-off-by: David Smith <davidosmith@gmail.com>
2022-05-03 06:32:53 -04:00
Eric Callahan cd520ba917 http_client: immediately raise cancelled errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-23 14:55:49 -04:00
Eric Callahan 94a11ff291 docs: add repo recovery documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-21 17:56:29 -04:00
Eric Callahan 11beaa7076 metadata: read metadata after object processing
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-21 10:28:45 -04:00
Eric Callahan 6f2ce72b4c metadata: add a UUID to extracted metadata
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-21 06:47:31 -04:00
Eric Callahan c1eda1ef3d http_client: modify download progress reporting
Report progress for each percentage change.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-21 06:37:52 -04:00
Eric Callahan f8a38abc89 confighelper: Update the help url for moved options
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-20 07:13:26 -04:00
Eric Callahan 985760c584 docs: add clarification to option deprecations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-20 07:08:29 -04:00
Eric Callahan d84f93d381 polkit: add flag to disable systemctl
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-19 14:46:15 -04:00
Eric Callahan 3ddbb9553d docs: note the "-z" option of the install script
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-19 14:18:16 -04:00
Eric Callahan b06f782665 install: add flag to disable systemctl
The "-z" flag will run the install script without running the
systemctl command.  This is useful for installations which
are done outside of the normal "boot" process.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-19 14:11:04 -04:00
Eric Callahan 4be8e2e72f database: fix decode exception handler
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-19 10:59:38 -04:00
Eric Callahan 65946ef857 job_queue: increase ready job delay
Delay for a full second before processing a job after
Klippy reports ready.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-19 06:23:02 -04:00
Eric Callahan bbd5d8a1a1 history: add logging
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-19 06:22:58 -04:00
Eric Callahan 430c2550c5 job_state: add logging
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-19 06:18:42 -04:00
Eric Callahan fe84226908 klippy_connection: log klippy version as received
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-19 06:18:32 -04:00
Eric Callahan d3003a1584 machine: return default values for find public interface
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-15 17:27:36 -04:00
Eric Callahan 47c6245c3f docs: spelling fixes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-10 14:17:27 -04:00
Eric Callahan e0eded70e8 docs: document extension APIs
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-10 14:17:27 -04:00
Eric Callahan 4666458793 websockets: simplify JSON-RPC execution
To accommodate access to multiple protocols Moonraker will always
require that the "params" field contain a dictionary, so reject any
other type as invalid.  There is no need to expand keyword arguments,
simply pass the params dict to the callback.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-10 14:17:27 -04:00
Eric Callahan da864ab391 websockets: only allow connections to identify once
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-10 14:17:26 -04:00
Eric Callahan cbc02d625c websockets: add agent registration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-10 14:17:26 -04:00
Eric Callahan a79e0eeef2 moonraker: add extensions to core components
Bump the API patch version with the addition of the extension
APIs.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-10 14:17:26 -04:00
Eric Callahan 236a7a7736 extensions: initial implementation
Add basic support "agents", ie: unmanaged extensions.  Connected
agents are granted a limited ability to emit websocket notifications
and process rpc requests from Moonraker.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-10 14:17:25 -04:00
Eric Callahan 1133c296b1 websockets: implement notification masking
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-10 14:17:25 -04:00
Eric Callahan d5a55047ab websockets: fix status codes
HTTP 404 and JSON-RPC -32601 are equivalent, so translate
where necessary.  Any other JRPC code received outside of the
HTTP error range should be assigned a 500.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-10 14:17:25 -04:00
Eric Callahan f6876c15e4 websockets: add ability to call ws client methods
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-10 14:17:24 -04:00
Eric Callahan 3a21e9d6f0 websockets: add default values for client data
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-10 14:17:24 -04:00
Eric Callahan b296444091 github: create a pull request template
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-10 06:13:53 -04:00
Eric Callahan 7631999c8f klippy_connection: handle credential exceptions
Handle exceptions should the attempt to fetch peer
credentials on the unix socket fail.  This isn't a hard
requirement for connection and should not cause
the connection to abort.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-08 14:37:11 -04:00
Eric Callahan b21f909705 klippy_connection: get unix socket peer credentials
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-08 14:21:17 -04:00
Eric Callahan eb6aeddf78 update_manager: detect divergent remotes
If a repo's remote has diverged then a reset is necessary as the
attempt to pull will fail.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-07 08:25:26 -04:00
Eric Callahan 2096c380c4 tests: update confighelper tests
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-06 17:02:22 -04:00
Eric Callahan 0f70037ffc docs: update documentation for config changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-06 08:41:19 -04:00
Eric Callahan 536871ad18 moonraker: bump API Version to 1.0.4
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-06 08:26:33 -04:00
Eric Callahan 77027d252e moonraker: always log configuration exceptions
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-06 08:26:32 -04:00
Eric Callahan bf19bcecae moonraker: report additional configuration info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-06 08:26:32 -04:00
Eric Callahan fc6714b30d confighelper: backup the entire configuraiton
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-06 08:26:32 -04:00
Eric Callahan ad00e08d11 confighelper: add support for include directives
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-06 08:26:31 -04:00
Eric Callahan 2e4814978f app: shallow copy arguments before passing to a request
This prevents a scenario where a request handler mutates
the arguments of a WebRequest, which could result in
changing the default "request_arguments" in
"InternalTransport.call_method()".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-05 15:48:36 -04:00
Eric Callahan fb2eacf702 confighelper: make parsed a required argument
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-05 15:48:36 -04:00
Eric Callahan ea25cce38f confighelper: require core component sections
This is a reimplementation of commit d61540cad5,
however this attempt provides a fallback for legacy configurations
that still have configuration in the server section.

This will change how `/server/config` reports configuration.  Options
will always be reported in their respective component's field, even if
they are currently configured in the `[server]` section.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-05 15:48:34 -04:00
Eric Callahan f27daac4f4 confighelper: remove "orig section" tracking
This isn't necessary as we don't add new sections to the
original config object when parsing supplemental data.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 20:45:17 -04:00
Eric Callahan 5f5f40293e Revert "docs: update user changes"
This reverts commit 82a22b287f.
2022-04-04 20:31:35 -04:00
Eric Callahan ac6cf0fac7 Revert "confighelper: match core components to their configuration"
This reverts commit d61540cad5.
2022-04-04 20:31:23 -04:00
Eric Callahan 7692197678 Revert "confighelper: remove "orig section" tracking"
This reverts commit 9c33eb225c.
2022-04-04 20:31:06 -04:00
Eric Callahan a706d23cfa docs: update mkdocs version
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 20:13:01 -04:00
Eric Callahan 82a22b287f docs: update user changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 19:40:50 -04:00
Eric Callahan 366e68c8f4 klippy_connection: send an event when gcode commands are received
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 17:18:54 -04:00
Eric Callahan fe3b7456f6 klippy_apis: add pause, resume and cancel print method
These methods may be called internally, which invoke the associated
events.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 17:18:54 -04:00
Eric Callahan e05aeac884 proc_stats: report system memory usage
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 17:18:50 -04:00
Eric Callahan 071a430159 klippy_apis: send events on pause, resume, and cancel requests
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 17:18:04 -04:00
Eric Callahan 7c1d6a8f24 websockets: emit added, removed, and identified events
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 17:18:03 -04:00
Eric Callahan 18169f279e file_manager: add get_directory method
This replaces the previous "get_sd_directory()" method, allowing
consumers to get any registered root path.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 17:18:03 -04:00
Eric Callahan 393cfa2a0e machine: implement get_public_network method
This allows components to determine the current local
ip address that routes to the internet.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 17:18:02 -04:00
Eric Callahan 9c33eb225c confighelper: remove "orig section" tracking
This isn't necessary as we don't add new sections to the
original config object when parsing supplemental data.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 15:26:16 -04:00
Eric Callahan d61540cad5 confighelper: match core components to their configuration
Most core components have default options that allow them to
load without a section specified in moonraker.conf.  This resulted
in those options showing up in the [server] section in the
"/server/config" response.  These changes will make sure that those
values show up in the correct section.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 15:16:25 -04:00
Eric Callahan 58228ec161 docs: bring up the update_manager documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:24 -04:00
Eric Callahan 5c9409c28d scripts: add a helper for tagging releases
The tag-release.sh script creates an annotated tag containing
Klipper's current state.  Moonraker's update manager parses
this annotation to bind the available Klipper version to this
release of Moonraker.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:24 -04:00
Eric Callahan 72a85e08d4 update_manager: refactor extension instantation
Don't allow extension errors to propagate, warn and continue
loading the module instead.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:24 -04:00
Eric Callahan 238b08ea1f update_manager: bind Klipper beta updates to Moonraker
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:23 -04:00
Eric Callahan 6afc70a9f5 update_manager: add support for beta git updates
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:23 -04:00
Eric Callahan 03934d8d81 update_manager: deprecate web_beta type
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:23 -04:00
Eric Callahan 58ea3cfdc7 update_manager: deprecate zip beta type
Use the "channel" option to specify a beta.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:22 -04:00
Eric Callahan f965ce8fd8 git_deploy: refactor tag retrieval
Use git for-each-ref to retreive tags and their associated commit
hashes.  This allows us to limit the amount of tags to 10 and
simplifies the code as the returned objects are already dereferenced.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:22 -04:00
Eric Callahan e9e86c3042 update_manager: refactor AppDeloy class
Don't require the `app_params` argument, instead dynamically
generate the configuration from a dict.  This simiplifies AppDeploy
initialization as the internally generated configurations can be
read in the same way as those supplied in moonraker.conf.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:21 -04:00
Eric Callahan 54081612ca confighelper: add a setoption method
This should only be used for internally generated configuration
that may change during runtime.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:21 -04:00
Eric Callahan 93b62236de update_manager: reorder update instances
Instantiate the moonraker instance first, then Klipper.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:21 -04:00
Eric Callahan c8042a5700 update_manager: add support for extensions
While use of "unofficial" klippy extras an moonraker components
is not officially supported, there is no harm in facilitating
updates for these extensions in the update manager.  This adds
configuration which will restart either moonraker or klipper
after an extension is updated.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:20 -04:00
Eric Callahan 16737d086d update_manager: add full update tracking
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:20 -04:00
Eric Callahan a4019bce8e confighelper: add support for optional separators
If "None" is specified as a separator for getdict and the getlist
variants then strings will split along any whitespace character.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:46:20 -04:00
Eric Callahan f3b0fbaa34 github: add an announcement issue template
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-04 11:39:49 -04:00
Eric Callahan 5643c0ffbe assets: show announcements on welcome page
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-03 12:17:08 -04:00
Eric Callahan 13bb624bd7 app: include announcements in welcome page context
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-03 08:58:31 -04:00
Eric Callahan 156e9652e1 announcements: add internal access methods
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-03 08:37:42 -04:00
Eric Callahan 2edbba3b53 assets: improve welcome page style
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-04-03 08:37:42 -04:00
Eric Callahan 8d49a5d5ee docs: update proc_stats documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-31 16:46:56 -04:00
Eric Callahan 9b5b3cc506 proc_stats: report system uptime in API request
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-31 16:44:39 -04:00
Eric Callahan 1968beaa0d app: add a welcome handler
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-30 19:59:27 -04:00
Eric Callahan d11357e5f2 authorization: add status methods
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-30 14:35:39 -04:00
Eric Callahan 8bb020edc6 moonraker: add method to retreive warnings
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-30 14:35:07 -04:00
Eric Callahan b85f3081ab power: add retries to custom http requests
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-29 15:39:04 -04:00
Eric Callahan 8c7247acbb announcements: add retries to http request
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-29 15:37:24 -04:00
Brian 'Redbeard' Harrington be2e8623b9 docs: Remove ambiguity from documentation index
Presently the index page of the documentation makes no attempt to
clarify what Moonraker is or even that it has anything to do with 3D
printing or CNC machine control.  This attempts to add a basic
clarification by using the top level description from README.md.

Additionally this adds a second clarification that Klipper is a "3D
printer firmware" (as referenced in the Klipper `README.md`) in this
projects `README.md`.

Signed-off-by: Brian 'Redbeard' Harrington <redbeard@dead-city.org>
2022-03-29 15:20:41 -04:00
Eric Callahan 060ca56fae docs: fix malformed post requests
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-27 10:33:51 -04:00
Eric Callahan 384ab71d72 docs: update announcement APIs
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-25 17:26:58 -04:00
Eric Callahan 242fabe7ad announcements: don't capitalize the feed
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-25 15:48:15 -04:00
Eric Callahan d74d1e7612 moonraker: bump the API version
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-25 15:41:49 -04:00
Eric Callahan 829b3b5c98 announcements: refactor RssFeed class
Don't require a config object to instantiate and don't attempt
to wrap database namespace.  These changes allow instantation
after the server has started.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-25 15:08:54 -04:00
Eric Callahan 5757347994 http_client: use the simple client
While the curl based client is better in most respects, it requires
that libcurl be against with an asynchronous DNS resolver, such
as c-ares, in order to prevent blocking.  As of now it Debian does
not ship with a version of curl with ares enabled.  Fall back to the
simple client until this can be resolved.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-25 12:45:46 -04:00
Eric Callahan 81a482f83d announcements: add support for temporary dismissals
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-25 12:45:46 -04:00
Eric Callahan 64b6029559 announcements: remove warnings on failure
Its possible for users to have an unstable internet connection.  Log
connection errors rather than warn.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-25 12:45:46 -04:00
Eric Callahan cd03b91f87 announcements: add support for dynamic feed registration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-25 12:45:42 -04:00
Eric Callahan 88b0282900 announcements: dont cache feeds
The parsed feeds are stored in the DB, so there is no
need to cache the result when 304 is returned.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-24 19:15:13 -04:00
Eric Callahan 561f5f4230 http client: minor logging fix
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-24 18:21:48 -04:00
Eric Callahan 4b0685852e announcements: remove stale code
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-24 17:40:15 -04:00
Eric Callahan 1bdedd009f power: fix tasmota command encoding
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-24 14:46:46 -04:00
Eric Callahan ac8c44095a docs: add announcement documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-24 12:08:24 -04:00
Eric Callahan 209ace4728 gitignore: ignore .devel and .venv folders
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-23 10:37:13 -04:00
Eric Callahan 3b208c6889 moonraker: add announcements to core components
Bump Moonraker's the API version to 1.0.2 with the addition of new
endpoints.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-23 10:37:13 -04:00
Eric Callahan b1cc766576 announcements: initial implementation
This adds support for announcements retreived via RSS feed from
the "moonlight" GitHub repo.  Announcements may also be procedurally
generated internally.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-23 10:37:12 -04:00
Eric Callahan 4a6732f13a confighelper: implement method to read a dictionary
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-23 10:37:12 -04:00
Eric Callahan 790d77756e app: fix blocking I/O
Open and close static files to be read using the default
thread pool executor.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-23 10:37:11 -04:00
Eric Callahan 27466984df update_manager: fix blocking I/O
When using tempfile.TemporaryDirectory it is possible that
exiting the context will block when attempting to delete
the temporary directory.  Don't use the context manager,
instead create and cleanup the temp dir using the default
threadpoolexecutor.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-23 10:37:11 -04:00
Eric Callahan faf956c65d update_manager: use the http_client component
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-23 10:37:11 -04:00
Eric Callahan 5bf112bcbc power: use the http_client component
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-23 10:37:10 -04:00
Eric Callahan 0abb831ea0 moonraker: remove references to Tornado's http client
Add the http client wrapper to core components.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-23 07:07:11 -04:00
Eric Callahan 43b19d8a83 http_client: shared client implementation
This abstracts the tornado http client from the rest of Moonraker,
allowing all components to access the client's most used functionality
without importing tornado modules.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-23 07:07:10 -04:00
Eric Callahan 4b27e5e41d scripts: pin pyserial to version 3.4
The pyserial-asyncio dependency pins pyserial to any version
greater than 3.4.  Currently pip is distributing version 3.5,
which is not an official stable release.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-23 07:06:15 -04:00
dependabot[bot] d20d2fd07e build(deps): bump pillow from 9.0.0 to 9.0.1 in /scripts
Bumps [pillow](https://github.com/python-pillow/Pillow) from 9.0.0 to 9.0.1.
- [Release notes](https://github.com/python-pillow/Pillow/releases)
- [Changelog](https://github.com/python-pillow/Pillow/blob/main/CHANGES.rst)
- [Commits](https://github.com/python-pillow/Pillow/compare/9.0.0...9.0.1)

---
updated-dependencies:
- dependency-name: pillow
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-03-23 06:48:07 -04:00
Mathis Mensing ee312ee9c6 docs: fix incorrect identify method
Signed-off-by: Mathis Mensing <matmen@dreadful.tech>
2022-03-10 13:57:43 -05:00
pataar a700725681 docs: fix an incorrection in the notifier example
Signed-off-by: Pieter Willekens <me@pataar.nl>
2022-03-08 10:45:25 -05:00
Eric Callahan efeea0d8e1 docs: document connection identify endpoint
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-04 19:56:13 -05:00
Eric Callahan 052dd5e338 moonraker: bump API Version
Addition of a  the "server.connection.identify" API warrants a bump in th
micro version.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-04 19:42:27 -05:00
Eric Callahan 3667e0d41f websockets: implement server.connection.identify method
Provide a remote method by which clients may identify their
name, version, and type.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>

fix

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-04 19:42:27 -05:00
Eric Callahan b86e86aff2 websockets: report hostname and connected time
By retreiving and storing the hostname in the websocket
header, it is possible to determine a fully qualified domain
used to reach the instance.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-04 14:20:06 -05:00
Eric Callahan 221df0937d machine: fix typo in cpu description parser
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-02 19:25:53 -05:00
vertigo235 26d6ca009a notifier: Add paused and resumed events to notifier
So we can tell when our printers need our attention. 

Signed-off-by: Josh Jones (vertigo235) <jbjonesclt@gmail.com>
2022-03-02 16:48:06 -05:00
Eric Callahan 94c51c9412 scripts: bump preprocess-cancellation to 0.2.0
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-03-01 15:45:28 -05:00
pataar 9d49659884 notifier: add support for 'attach' property
Signed-off-by: Pieter Willekens <me@pataar.nl>
2022-03-01 11:13:32 -05:00
Gregor Majcen 553f8862b5 notifier: typo at job_state:completed
Signed-off-by: Gregor Majcen <majcn.m@gmail.com>
2022-03-01 08:56:47 -05:00
Eric Callahan b6fc692500 dbus_manager: clarify warnings
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-28 06:57:38 -05:00
Eric Callahan 6065e9a0fe docs: add tip to resolve additional polkit warnings
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-28 06:32:04 -05:00
Eric Callahan c87d8d2e51 docs: fix reference to the test client
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-27 20:55:03 -05:00
Eric Callahan f93fed62ae docs: update power documentation
If the "restart_klipper_when_powered" option is set Moonraker will
always abort if Klippy's current state is "ready".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-27 08:39:28 -05:00
Eric Callahan c165c40146 power: improve device initialization
Refactor the PowerDevice initialize() method so that it acquires the
request lock. Always register the "klippy_started" event if the
"restart_klipper" option is set, and always check if Klipper is is
 the ready state before performing the restart.  Remove stale
 PowerDevice methods no longer used.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-27 07:47:12 -05:00
Eric Callahan 970c8a4181 power: move process_request to the device class
Perform the entire request within a lock to prevent rentry until
the request completes.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-26 20:10:27 -05:00
Eric Callahan 0d93cf2c39 docs: respect OctoPrint's case
Make sure that all references capitalize the "P" in OctoPrint.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-26 10:48:53 -05:00
Eric Callahan 8f7f824a47 octoprint_compat: respect OctoPrint's case
Make sure that the "P" in Print is capitalized when referencing
OctoPrint.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-26 10:48:52 -05:00
Eric Callahan 65e76aeec8 docs: document remote methods registered by machine
The "reboot_machine" and "shutdown_machine" remote methods may
be called from a Klipper gcode macro to accomplish their respective
tasks.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-26 10:48:52 -05:00
Eric Callahan ab09364a98 docs: provide additional context for the secrets module
Advise users to use unique credentials, and warn them that unattended
clients can be configured to steal credentials.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-26 10:48:51 -05:00
Eric Callahan 2bc43ec3df docs: warn users about overlapping folders
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-26 10:48:51 -05:00
Eric Callahan fd8bde7185 file_manager: implement access check method
This method can be used by other components to check if Moonraker has
access to a particular file or folder.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-26 10:48:51 -05:00
Eric Callahan a32bf4a47a file_manager: allow server to start with invalid paths
Don't raise an exeption if the config or log paths are invalid,
add warnings instead.  This allows the user to see what is wrong
and resolve this issue.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-26 10:48:50 -05:00
Eric Callahan 3a384e62dd file_manager: add registered directory validation
Make sure that paths registered with full access do not overlap one
another, nor that they overlap sensitive folders such as the database,
Moonraker's source, or Klipper's source.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-26 10:48:48 -05:00
Eric Callahan ed20223614 docs: update database config documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-25 14:05:26 -05:00
Eric Callahan 79f867ba83 database: remove debug option
This option was intended for Moonraker developers to live test
changes to write protected namespaces.   This can be accomplished
locally with other methods, thus this option has been removed to
prevent users from compromising sections of the database.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-25 12:38:36 -05:00
Eric Callahan 0a2c1904c0 docs: fix typo in [secrets] json example
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-02-24 17:05:09 -05:00
pataar 71de8def8e notifier: create the new notifier module
This component will be a bridge between moonraker and https://github.com/caronc/apprise. This way users can easily add all kind of notification services to their printer.

Signed-off-by: Pieter Willekens <me@pataar.nl>
2022-02-23 17:05:55 -05:00
Eric Callahan 501af62018 docs: update /server/info and /machine/system_info docs
These endpoints now return additional values.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-23 12:25:52 -05:00
Eric Callahan 1fbfb90500 tests: update test_server for changes to moonraker
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-23 12:01:50 -05:00
Eric Callahan 54f2ee61d0 machine: report the python version in system_info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-23 12:01:50 -05:00
Eric Callahan 7679f8063f moonraker: remove the python version check
Moonraker depends on "future" annotations and uses fstrings, so
 versions of Python older than 3.7 will fail to load and never make
 it to the version check.

 Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-23 12:01:10 -05:00
Eric Callahan f83f476f81 moonraker: report the api version
Start tracking the Remote API version separately from the application
version.  This allows the API to stick to semantic versioning while
and track the application version separately.  This is necessary as
we prepare to release a beta.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-23 12:01:07 -05:00
th33xitus 8b8cb66481 readme: fix link for MainsailOS
readme: replace `Meteyou` with `Mainsail-Crew`

docs: replace `meteyou` with `mainsail-crew` in web_api.md

Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2022-02-23 10:24:39 -05:00
Eric Callahan 8ff54e2372 docs: update documenation for "power on queued" changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-23 09:13:54 -05:00
Eric Callahan 7ab1dda772 power: change behavior of "on when queued"
Rename the "on_when_upload_queued" option to "on_when_job_queued",
deprecate the former.  This option now applies to any queued job while
the device is off.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 14:36:46 -05:00
Eric Callahan 2b1a3e5603 klippy_apis: fix blocking issue in start_print and do_restart
The "wait_connected" method would block indefinitely until a klippy
connection is established.  This isn't the behavior we want, we only
want to wait "if" a connection has been established until Klippy
reports that its startup sequence is complete.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 14:34:14 -05:00
Eric Callahan 86469903f3 tests: add database tests
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 3edb4b1bad tests: add support for loading a database
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan f2f1d413d4 scripts: introduce dbtool
This tool may be used to backup and restore Moonraker's lmdb
database without depending on the "lmdb-utils" package.  The
backup is done to a plain text file in cdb format, so a backup
may be restored on any platform.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 55baad1ad0 tests: rework path_args and klippy fixtures
Initialize the temporary directory in a "session_args" fixture that is session
scoped.  Move the Klippy process to a session scope, restarting the process
only when necessary.  This combination speeds up tests as it reduces disk
I/O and the overhead of starting the Klippy process for each test.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 81f2418d78 tests: fix error in websocket_client fixture
A jsonrpc request is a notification when no ID is present.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 348d45e87c tests: increase the timeout to 60 seconds
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan e6b4e54bea tests: fix the server pending tasks tests
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 6946f67dbf tests: increase the klippy process timeout to 2.5 seconds
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan f7f487ac18 database: sort protected namespaces before storing them
This makes the order in which they are reported consistent,
as the namespaces are stored in a set.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 888fb58c4f database: sync namespace bugfix
Use the transaction object to overwrite keys so that we don't
move the cursor.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 2b7a5ff035 tests: assign the WebsocketError to an static variable
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan d630b79e8b tests: http client fixes
Correctly encode the query string.  Use the query string for DELETE
requests in addition to GET requests.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 5f96822c90 database: don't overwrite "get" server errors
Make sure the correct exception is raised when "get_item" fails.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 2d28a3eeff database: fix typo in http exception
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 96b00549cf database: validate that namespace exists in ns_contains
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 0bd12c8dec database: don't allow sync against an empty dict
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan f3cd177a02 database: move_batch() fix
Raise an exception if the key lengths for the source and destination
keys do not match.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 11e299558d database: fix insert_batch()
If a namespace does not exist insert batch must create a new one rather
than raise an exception.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan bb39a3c1b2 database: handle invalid reduce results
It is possible to reduce to a value that is not a dict in "insert_item()"
and "update_item()".  Raise a ServerError with a clear description of
what went wrong in these situations.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 89e78b9a00 database: fix type reported in overwrite warning
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan c1104617b6 database: fix typo in sync implementation
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 3c92f42d49 database: allow synchronous calls before the server starts
It is possible that Moonraker can be instantiated while the eventloop
is running during tests.  To avoid errors allow synchronous calls until
the server starts.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:38 -05:00
Eric Callahan 9ab6d0e83d update_manager: support database changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-22 07:47:34 -05:00
Eric Callahan c081fa49a1 history: update for database changes
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan 9e57db0611 file_manager: add method to retreive the metadata storage object
This allows other components to synchronously access and update
metadata if necessary.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan 0dd10ce116 file_manager: update for changes in the database
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan b43f4623fc authorization: update for changes in the database
Since the User DB is not going to be large cache the users
in local memory and sync with the DB when changes are
made to the local user store.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan 46f74329d3 database: reduce duplicate code
Add a _get_db() method that perform the check for existance.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan e2a62f80d4 database: introduce record based operations
Now that all transactions run in a thread it is possible for them to
interleave.  The record based operations allow for batch operations
within a single transaction.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan e029b6c582 database: refactor to remove duplicate code
Wrap command implementations in with a _run_command() method.  All
database commands now return a Future object.  If the command was
run before the eventloop starts its possible to immediately query
the Future's result.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan 65d1f23352 database: add a sync method
Similar to the update method, however sync will remove any
keys in the database not in the new value.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan 781e3e6250 database: combine namespace wrappers
Rather than creating two wrappers, use a single wrapper whose methods
always return a future or awaitable.  If the operation occurs during
the __init__() method of a component it will be syncrhonous, and the
result from the future can be immediately queried.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan 4d0a43cb25 database: refactor initial check for empty keys
Rather than reading out the entire database, attempt to pop off
empty keys in each database.  This should should speed up
init on platforms with slow disk I/O and prevents reading
large namespaces in memory.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan e754d123dd database: improve ns_contains method
It isn't necessary to read out the entire namespace, just attempt
to fetch the record and reduce the key list.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan 43c1b998b0 database: add methods to clear and update a namespace
Since transactions are now threaded we need updating
and clearing a namespace needs to be performed within
one transaction.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan e895b10ac3 database: run transactions in a thread after the eventloop starts
Database transactions can perform disk I/O tasks, which at times will
block the eventloop.  Run all transactions in threads to prevent this
from occuring.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan 1be639b99a eventloop: use the default executor for run_in_thread()
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan ac55b95c1d database: Add unsafe shutdowns to the log rollover
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:57 -05:00
Eric Callahan 5f9706f6be test: initial testing framework
This adds the framework for unit testing Moonraker via pytest.
Initally only moonraker.py, klippy_connection.py, and confighelper.py
have acceptable coverage.  Coverage for other modules will be added on
an incremental basis, when most of Moonraker's source is covered tests
will be conducted via GitHub actions.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-17 11:19:41 -05:00
Lars Pöpperl 34f607c061 docs: add alternative sample file for home assistant
Signed-off-by: Lars Pöpperl  <lars.poepperl@gmail.com>
2022-02-17 11:03:30 -05:00
Simon Germain 11f4ae75cc octoprint_compat: add webcam settings
Signed-off-by: Simon Germain <sgermain06@gmail.com>
2022-02-17 10:46:05 -05:00
Eric Callahan f79439aedd funding: add a ko-fi button
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-16 05:44:10 -05:00
Eric Callahan c2861a1391 app: correct location header encoding
SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-15 14:39:33 -05:00
Eric Callahan e2d92b5575 confighelper: use read_file() rather than read()
The read() method will return an empty list if the file specified
does not exist or if the read failed in some fashion.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-15 11:42:50 -05:00
Eric Callahan 0e27a949af docs: update power documentation for "smartthings" devices
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-14 06:26:34 -05:00
Eric Callahan 10703321b0 power: fetch the Smart Things token option as a template
This allows users to store their token in a "secrets" file

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-14 06:19:37 -05:00
Mitch Gallman 0dc05eac76 docs: add smartthings power documentation
docs: add smartthings power documentation

Signed-off-by: Mitch Gallman <mitchell.gallman@gmail.com>
2022-02-14 06:12:52 -05:00
Mitch Gallman d01b8a9763 power: add support for smartthings switch
power: add support for smartthings switch

Signed-off-by: Mitch Gallman <mitchell.gallman@gmail.com>
2022-02-14 06:12:52 -05:00
Eric Callahan b60153c919 workflows: disable blank issues
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-02-13 20:50:22 -05:00
Eric Callahan ee11ed2a15 confighelper: fix the get_hash() method
Include the option's values in the hash.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-13 20:48:27 -05:00
Eric Callahan 9be93ff445 docs: add "info_tags" to update manager status
This also fixes some stale documentation.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-13 11:32:32 -05:00
Eric Callahan ecfad5cff1 update_manager: add support for application tags
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-13 10:50:28 -05:00
Eric Callahan 92eda982ce docs: clarify contributing documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-10 16:53:11 -05:00
Pedro Lamas cb5ac86af7 metadata: add support for parsing layer count in Cura
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2022-02-10 12:11:20 -05:00
Eric Callahan 94a2949c00 moonraker: report missing klippy requirements
Moonraker requires that some Klipper objects be configured
and loaded.  This check has always been performed and logged,
now track and report missing requirements.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-02-10 08:28:51 -05:00
Eric Callahan b4ddffd5d1 moonraker: refactor KlippyConnection
Move the KlippyConnection class into its own module.  Refactor
init to use loops rather than callbacks, this reduces complexity
of tracking and cancelling callback handles.

All Klippy state previously tracked by the Server is now in the
KlippyConnection.  This improves testing and makes the code
less ambiguous, ie: the `server.make_request()` method is not
as clear as `klippy.request()`.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-09 19:15:11 -05:00
Eric Callahan 737cf8a2cb mooraker: refactor main entry point
Move the version check to the top of the module.   An older version
of python is unlikely to make it beyond the initial import statements,
so print a message to stdout and stderr.

Move argument parsing out of the main method.  This makes it possible
to invoke main without parsing command line arguments, which is useful
for tests.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-02-09 07:35:01 -05:00
Eric Callahan 6efcffa028 moonraker: perform error checking when registering remote methods
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-09 06:48:23 -05:00
Eric Callahan a04e91c046 proc_stats: track the loop blocked count
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-05 20:24:00 -05:00
Eric Callahan 9e9f9ee0fd moonraker: add the SIGTERM handler in server_init()
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-05 06:56:29 -05:00
Eric Callahan 1072958534 authorization: start the prune timer in component_init()
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-05 06:56:29 -05:00
Eric Callahan a5eff12131 proc_stats: start timers in component init
Avoid adding  event loop callbacks in a component's "__init__()" method.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-05 06:56:29 -05:00
Eric Callahan 0f7af929f1 file_manager: suppress "root_update" notifications during init
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-05 06:56:29 -05:00
Eric Callahan 47f0437973 eventloop: add a reset method
Rather than instantiate a new version of the event loop wrapper
we can simply reset the internal event loop.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-04 18:14:46 -05:00
Eric Callahan a5c49e8742 moonraker: refactor init sequence
Don't load components and start the server from within the
__init__() method.  Break those out and call them in __main__().
This makes unit testing individual components possible.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-04 11:54:39 -05:00
Eric Callahan 35d8d88855 confighelper: remove direct component imports
Dont directly import components for instance checks.  Instead
check to see if the type is serializable, if not store the string
representation.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-04 11:20:31 -05:00
Eric Callahan f6d8de2cee utils: move config backup methods to confighelper
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-04 10:58:00 -05:00
pznamenskii 6749d3836e docs: add Home Assistant camera example
Signed-off-by: Pavel Znamenskiy <[pznamenskii@gmail.com](mailto:pznamenskii@gmail.com)>
2022-02-03 19:17:11 -05:00
Eric Callahan 509759ba0d secrets: fix ConfigParser to Dict conversion
The result should be a dictionary of dictionaries rather than a
dictionary of SectionProxy objects.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-03 17:57:50 -05:00
Eric Callahan 5a966836b5 moonraker: backup the most recent working config
Attempt to take a backup of the configuration file if Moonraker
loads successfully and has not seen a config change.

If Moonraker fails to load due to a config error, attempt to fallback
to the backup configuration.  If that fails, exit the server.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-03 17:19:17 -05:00
Eric Callahan 4ec781d66b confighelper: minor cleanup in get_configuration
Its safer to let the attempt to read fail before additional error
checking.  Also there is no need to remove DEFAULT from
config.sections(), as it can't be there per the Python docs.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-03 12:19:29 -05:00
Eric Callahan ae8cab356b moonraker: gracefully handle invalid log paths
Don't exit the server if the log path is invalid.  Instead start
logging to stdout and add a warning for the user to
resolve.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-03 11:21:34 -05:00
Eric Callahan 305e002f8c docs: update docs for "klipper_device" power types
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-03 08:38:44 -05:00
Eric Callahan 0b13e2da44 power: add support for gcode_macro Klipper devices
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-02-03 08:14:48 -05:00
Matthew Humphrey aca7cb78b9 module: power
Add separate output_id configuration attribute for TPLink Smartplug device.

Signed-off-by:  Matthew Humphrey <mhumphrey@gmail.com>
2022-02-02 17:35:18 -05:00
Eric Callahan 10ac044485 scripts: add a --root argument to set-policykit-rules.sh
If a user specifies this then root is allowed to run the script.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-30 15:20:49 -05:00
Eric Callahan f616c83ebc docs: clarify PackageKit documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-30 14:12:03 -05:00
Eric Callahan 5ec98cf0ba scripts: workaround pip 22.0 issues
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-30 14:08:13 -05:00
Eric Callahan de796a9ec7 app_deploy: don't update pip
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-30 12:14:09 -05:00
Eric Callahan 13591d0a5b scripts: do not allow set-policykit-rules.sh to run as root
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-29 14:07:15 -05:00
Eric Callahan b4ad6692e3 update_manager: fix klipper path regression
Commit 7401192 introduced a regression where the saved klipper
paths were not loaded into the Update object.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-29 11:03:08 -05:00
Pedro Lamas 287982acdd power: initial support for Klipper Devices
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2022-01-29 07:53:30 -05:00
Eric Callahan 7c8c0e715f scripts: update set-policykit-rules.sh
Check for the moonraker-admin Supplementary group
in the moonraker service file and add it if necessary.

For PolKit versions > 0.106 make sure that the process
is launched with the moonraker-admin group before
granting any polkit permissions.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 468ea36bba scripts: update install-moonraker.sh
Add the "moonraker-admin" supplementary group to the service unit
file.  Check if polkit rules are available after installation, if not
advise the user that they may wish to run set-polkit-rules.sh.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan d396dbd2cb utils: add support for versioning shallow clones
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 471885c3a2 git_deploy: add support for shallow clone tags
Shallow clones don't report the tag in git describe, so use
git rev-list to extract the tag and prepend it to the version
string.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 7401192478 update_manager: store klipper paths in the database
If Klipper or its python executable is located at a custom path
this allows moonraker to instantiate its update on startup
rather than wait for Klipper to connect.  This also resolves an
issue where Klipper's update state is always refreshed on startup
when its located in a non-default path.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan ede671f0df app_deploy: handle exceptions in same path check
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 14f1b6f936 docs: update documentation for dbus additions
Signed-off-by:  Eric Callahan <arksine.code@gmail.com
2022-01-28 18:00:21 -05:00
Eric Callahan 6aecd7b26d machine: add "none" provider
When the "none"  provider is set service action APIs will be disabled
and return an error when called.  Service state tracking is also
disabled.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan b1a232efce update_manager: remove redundant locks
All requests to update, refresh, recover, or reinstall must acquire
the command lock. Given that the individual Deployment implementations
are not (and should not be) called from outside of a request the locks they
use to prevent unwanted re-entry are redundant, confusing, and could
potential result in a deadlock if used improperly.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 4d473969db scripts: add packagekit dependency to install script
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan a92847771d scripts: add set-policykit-rules.sh
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 0e6fbb12b0 update_manager: add support for PackageKit updates
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 744f14d6f9 scripts: add pk-enum-converter.py
This is added to distrubute the changes made to "enum-converter.py"
taken from the original PackageKit repo.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 0dbb6d51a8 moonraker: introduce thirdparty package
This allows for the inclusion of 3rd party Python Source
within the Moonraker package.  Initially this includes
a python source file containing PackageKit enumerations.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 4ddd77430a update_manager: move low level package methods to a provider class
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 3b27ab49f1 update_manager: use the machine component to restart services
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan be338ad039 machine: add systemd dbus provider implmentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 73f0d5503d dbus_manager: add initial implementation
The DBus manager is a core component that connects to the
system bus, providing resources used to communicate with other
processes on the the system through the DBus interface.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 0d6791a320 machine: refactor systemd cli implementation
Move all systemd cli calls to its own provider class, inherted from
a base provider class.  This is in preparation for multiple provider
implementations.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 9b6161a6b0 proc_stats: add stat callback registration
This allows other components to be register callbacks that will
be executed in the stat update timer. This is useful for methods
that wish to poll subprocess commands, as its desireable to
prevent multiple subprocesses from running simultaneously.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan f4c5e808c3 shell_command: add exec_cmd method to factory
This allows for users to execute a method directly rather than
create a command.  This is useful for fire once commands that
do not need to inspect the return code unless there is an error.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 89d0bbdb63 shell_command: add support for sending data to a process
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 8546cd6ac5 shell_command: use a custom protocol for callbacks
Rather than override the Process class instead create a custom
protocol that forwards data over callbacks.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 18:00:21 -05:00
Eric Callahan 9911b5c7dd app: don't allow open redirects in '/server/redirect'
Validate that the URL argument against the `cors_domains` option.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 14:05:48 -05:00
Eric Callahan 41c19e4b9a github: modify issue templates
Add some additional required fields that are helpful in diagnosing
issues, and remove the "what did you expect to happen", as that
tends to be implied in the issue.  Also allow blank issues so
announcements can be made.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 12:07:23 -05:00
Eric Callahan 0c5a0fd979 wled: add retries to http request
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-28 06:16:54 -05:00
Eric Callahan 209bdc18da power: sleep for 1 second between failed retries
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-01-28 06:12:56 -05:00
Eric Callahan 04477705b0 app: content disposition fix for file names containing commas
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-27 19:21:25 -05:00
Eric Callahan 7fcd84bbe4 power: add retries to http requests
This is an attempt to mitigate 599 errors raised by tornado's
curl based http client.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-27 17:00:08 -05:00
Richard Mitchell 1cac7399f9 wled: deprecate color_order option
Support more synonym strings for colors
Case insensitive string type checks
Show errors in UI if e.g. wrong color was selected
Public color_config not color_order as it has confused users
Fix documentation for white stealthburner example

Signed-off-by:  Richard Mitchell <richardjm+moonraker@gmail.com>
2022-01-25 06:02:36 -05:00
Eric Callahan f5ceefbb8d websockets: log if the connection is proxied
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-21 06:57:52 -05:00
Eric Callahan e103accdfb websockets: refactor open/close logging
Log the User Agent when a websocket is opened.
When a websocket is closed log the close code, close Reason, and
time elapsed since the last pong was recieved from the client.
When Moonraker shuts down send a 1001 Code with Server Shutdown
as the reason.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-20 14:20:23 -05:00
Eric Callahan 09689143b5 shell_command: python 3.10 fix
Remove the deprecated "loop" parameter in asyncio.gather().

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-19 15:18:36 -05:00
Richard Mitchell 5f54a23f3e Richardjm/wled serial asyncio (#332)
wled: Use pyserial-asyncio for wled

Signed-off-by:  Richard Mitchell <richardjm+moonraker@gmail.com>
2022-01-15 14:22:49 -05:00
dependabot[bot] 60f2e3e1c7 build(deps): bump pillow from 8.3.2 to 9.0.0 in /scripts
Bumps [pillow](https://github.com/python-pillow/Pillow) from 8.3.2 to 9.0.0.
- [Release notes](https://github.com/python-pillow/Pillow/releases)
- [Changelog](https://github.com/python-pillow/Pillow/blob/main/CHANGES.rst)
- [Commits](https://github.com/python-pillow/Pillow/compare/8.3.2...9.0.0)

---
updated-dependencies:
- dependency-name: pillow
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2022-01-13 05:53:30 -05:00
Eric Callahan dd6a06e9de docs: update proc_stats documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-12 19:58:49 -05:00
Eric Callahan 4c99f99cf0 proc_stats: report system cpu usage
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-12 19:58:49 -05:00
Lukas Fink 693a34d562 docs: add 'off_when_shutdown_delay' documentation
Signed-off-by: Lukas Fink <lukas.fink1@gmail.com>
2022-01-12 19:58:25 -05:00
Lukas Fink 3cbc2c2ca8 power: add 'off_when_shutdown_delay' option
This option allows to delay switching off a power source after klippy
shuts down.

Signed-off-by: Lukas Fink <lukas.fink1@gmail.com>
2022-01-12 19:58:25 -05:00
Richard Mitchell cfd3d63a0d wled: Add serial support for direct communication (#325)
wled: Add serial support for direct communication

Signed-off-by:  Richard Mitchell <richardjm+moonraker@gmail.com>
2022-01-12 19:56:14 -05:00
Eric Callahan 59fd35827e docs: add button documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-12 08:05:17 -05:00
Eric Callahan 4c087612d8 mqtt: allow internal access to API endpoints
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-12 08:05:17 -05:00
Eric Callahan 2025332e6f button: initial implementation
Adds support for GPIO buttons.  Each button is configured to render
a template when pressed and/or released.  The button event
templates recieve a context with  a "call_method" field, allowing
them to call nearly all Moonraker APIs.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-12 08:05:17 -05:00
Eric Callahan a652845843 moonraker: add register_component() method
Allow base modules to register themselves as components during
initialization.  This makes them accessible via lookup_component()
across the entire application.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-12 08:05:17 -05:00
Eric Callahan 27c65e0a64 application: support internal API consumption
Track registered endpoints and allow internal APIs calls through
their JSON-RPC method names.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-01-12 08:05:17 -05:00
Eric Callahan 3bd5f7edbd template: add support for async rendering
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-12 08:05:17 -05:00
Eric Callahan fc5e34096a gpio: add support for line events
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2022-01-12 08:05:17 -05:00
Eric Callahan 9346186337 gpio: refactor pin parsing
Return a dictionary of pin params rather than a tuple

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2022-01-06 11:56:41 -05:00
th33xitus 505c1bfdba metadata.py: fix parsing of IdeaMaker nozzle_diameter
Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2022-01-06 11:55:52 -05:00
th33xitus 6c8e3690a7 chore: remove unused import
Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2022-01-05 06:32:09 -05:00
th33xitus 2c732b7afa metadata.py: add parsing of filament name
This commit will add parsing of optional filament name metadata for:
- PrusaSlicer and it's derivatives
- Simplify3D
- Cura
- IdeaMaker

For Cura and IdeaMaker it is necessary to add a custom start g-code comment.
Cura:
;Filament name = {material_name}
IdeaMaker:
;Filament name = {filament_name1}

Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2022-01-05 06:32:09 -05:00
th33xitus d145442d4b metadata.py: add parsing of filament type
This commit will add parsing of optional filament type metadata for:
- PrusaSlicer and it's derivatives
- Cura
- IdeaMaker

For Cura and IdeaMaker it is necessary to add a custom start g-code comment.
Cura:
;Filament type = {material_type}
IdeaMaker:
;Filament type = {filament_name_abbreviation1}

Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2022-01-05 06:32:09 -05:00
th33xitus 20d3c9961d metadata.py: add parsing of nozzle diameter
This commit will add parsing of optional nozzle diameter metadata for:
- PrusaSlicer and it's derivatives
- Simplify3D
- Cura
- IdeaMaker

For Cura and IdeaMaker it is necessary to add a custom start g-code comment.
Cura:
;Nozzle diameter = {machine_nozzle_size}
IdeaMaker:
;Nozzle diameter = {machine_nozzle_diameter1}

Signed-off-by: Dominik Willner <th33xitus@gmail.com>
2022-01-05 06:32:09 -05:00
Pedro Lamas 9d7baa1eb6 utils: fixes minor typo
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-12-28 14:13:27 -05:00
Pedro Lamas d997fd637a moonraker: fixes minor typo
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-12-28 14:13:27 -05:00
Pedro Lamas 05af4babb9 mqtt: fixes minor typo
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-12-28 14:13:27 -05:00
Pedro Lamas 7c5d840c1b zip_deploy: fixes minor typo
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-12-28 14:13:27 -05:00
Pedro Lamas 5f20dafadb docs: fixes minor typo
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-12-28 14:13:27 -05:00
Eric Callahan 1d1ce0671d docs: fix jinja2 example
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-12-28 11:05:15 -05:00
Eric Callahan adfe8a67b6 docs: fix error in mqtt power device documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-28 10:49:27 -05:00
Eric Callahan 0a541bbea1 docs: add documentation for the secrets module
Update the documentation for all relevant options that may
be resolved from secrets.

Signed-off-by:  Eric Calalahan <arksine.code@gmail.com>
2021-12-24 14:44:48 -05:00
Eric Callahan 1e440741da mqtt: add support for "secret" credentials
Deprecate the "password_file" option in favor of "password".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-24 14:23:05 -05:00
Eric Callahan c5fd863bb7 power: add support for secrets
The "user", "password", and "token" options are templates
that can resolve items stored in the secrets file.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-12-24 14:23:05 -05:00
Eric Callahan a269de5dc0 confighelper: add load_template method
This is an alternative to gettemplate that always returns a
template.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-24 14:23:05 -05:00
Eric Callahan a4f960d40c confighelper: implement deprecation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-24 14:23:05 -05:00
Eric Callahan 9dadf50ac6 templates: add support for secrets
Add the secrets module as a Jinja2 Environment global.
All templates will be able to access secrets as if it were
a dictionary.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-24 12:41:28 -05:00
Eric Callahan d498eefd13 secrets: initial implmentation
Add support for an external "secrets" file that may contain
usernames, passwords, and tokens.  This file may be in
"ini" or "json" format.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-24 12:41:28 -05:00
Eric Callahan f4e3803647 metadata: refactor thumbnail parsing
Check for "Prusa" style embedded thumbnails by default for
all slicers.  This is becoming a standard, as it is now available
in Cura, Ideamaker, and Simplify3D via plugins.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-23 06:38:13 -05:00
Eric Callahan 51ca383591 docs: add missing headers to config examples
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-12-22 19:50:25 -05:00
Eric Callahan 01245ea8a1 docs: document the publish_mqtt_topic remote method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-22 19:31:00 -05:00
Eric Callahan 92954245fa mqtt: implement a "publish_mqtt_topic" remote method
Allow Klipper to publish MQTT topics from gcode macros.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-12-22 19:31:00 -05:00
Eric Callahan 57b00cb33a docs: add a warning for tplink devices
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-22 12:46:54 -05:00
Eric Callahan 5f7c6d623c docs: update "octoprint_compat" documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-22 07:49:41 -05:00
Eric Callahan cc1a55a871 metadata: always create a miniature thumbnail
Don't require that gcode files embed two thumbnails.  When
a single large thumbnail is parsed use pillow to create a
small one.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-22 07:29:16 -05:00
Eric Callahan 5766d16edc octoprint_compat: default printer profile fix
Cura's Octoprint plugin expects an "axes" field for each profile.
Report these values to match the default values used by the
plugin.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-22 05:41:00 -05:00
Eric Callahan ec43f5e9b6 octoprint_compat: make UFP uploads optional
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-22 05:41:00 -05:00
Eric Callahan e2fb1cc931 octoprint_compat: add support for "print on start"
Cura's Octoprint plugin does not set the 'start' flag on uploads
when UFP is enabled.  Instead it waits for the upload to
finish then issues Octoprint's "file command" request.  Add
limited support for this API, mimicing how uploads are normally
handled.

Singed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-22 05:41:00 -05:00
Eric Callahan e46b4994d4 app: add support for empty responses
If a dynamic request handler returns None with "wrap_result"
disabled, set the return status to 204.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-21 18:12:27 -05:00
Eric Callahan b369173f94 app: refactor upload handler registration
Move upload handler registration out of the file manager.
Register the primary hander in the app module, and the
Octoprint Comptaiblity handler in octoprint_compat.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-21 16:53:33 -05:00
Eric Callahan ac9eaa7681 app: set the status to 201 for uploads
Set the location header when the upload returns a valid result.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-21 15:32:28 -05:00
Eric Callahan 3e70e4b4ce machine: report additional release info
Report information contained within a linux distribution's
release file if it exists.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-20 16:58:21 -05:00
Eric Callahan 1333413db7 update_manager: fix pip location resolution
When creating a virtualenv, some operating systems provide
symbolic links back to /usr/bin/python3 rather than copy
the python exectuable over.  Previously Moonraker resolved
this symbolic link, resulting in a failure  to locate pip.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-20 12:30:26 -05:00
Eric Callahan 7d1cf435f7 authorization: report invalid "trusted_clients"
Add warnings that are reported to clients and logged if an
invalid trusted client is detected.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-20 08:37:54 -05:00
Eric Callahan 828be30466 docs: refactor [power] documentation
Separate the configuration for each device type, making it
easier for users to identify options specific for each
device.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-20 08:00:53 -05:00
Eric Callahan d7bfb7744a docs: document mqtt power device configuration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-19 12:35:14 -05:00
Eric Callahan d0b1621bd5 power: add mqtt device support
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-19 08:00:13 -05:00
Eric Callahan f57bddfe4a mqtt: send connect and disconnect events
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-14 17:51:12 -05:00
Eric Callahan 3ac8f8cd81 mqtt: add method to report instance name
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-14 17:51:12 -05:00
Eric Callahan e2b821e90c confighelper: add gettemplate method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-14 17:51:12 -05:00
Eric Callahan 2142d344dd template: add support for Jinja2 template evaluation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-14 17:51:12 -05:00
Eric Callahan 3f7cc53baa moonraker: don't allow a unix socket to open while closing
Hold the closed mutex in the "connect()" method.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-12 10:24:19 -05:00
Eric Callahan 31dd758d52 moonraker: unix socket fix
Handle connection errors in the read loop.  Set a maximum number
of consecutive errors encountered during a read before aborting.
Resolves #309.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-12-12 06:40:53 -05:00
Eric Callahan a4abec43d5 mqtt: fix non-threadsafe on_socket_open callback
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-11 14:31:10 -05:00
Eric Callahan c6cddf4b05 moonraker: logging improvements
Move logging setup to the Server class and enable asyncio debugging.
Sanitize debug logging for all "/access" endpoints so tokens and
passwords are not logged.

SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-11 14:16:15 -05:00
Eric Callahan c69ded21b0 job_state: initialize in "klippy_started" event
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-11 08:44:55 -05:00
Eric Callahan 08111415be update_manager: auto-refresh fix
Only refresh a provider when the update interval has expired.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-10 11:37:51 -05:00
Eric Callahan 56a98aa8ed update_manager: replace PeriodicCallback
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-10 11:37:51 -05:00
Eric Callahan 511c91829a power: use native asyncio socket streams
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-10 11:37:51 -05:00
Eric Callahan ae4c4ad678 moonraker: use native asyncio unix streams
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-10 11:37:51 -05:00
Eric Callahan df674ae476 proc_stats: replace PeriodicCallback
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-12-10 11:37:51 -05:00
Eric Callahan 5dadc2067d data_store: replace PeriodicCallback
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-10 11:32:52 -05:00
Eric Callahan 4e625aef37 authorization: replace PeriodicCallback
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-10 11:32:52 -05:00
Eric Callahan 69a06dd12a eventloop: add a timer class
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-09 14:38:32 -05:00
Frank Tackitt 2216e85fef Bump preprocess-cancellation to 0.1.6
This fixes a bug that caused retraction moves to be included in bounding box calculations.
2021-12-09 14:26:45 -05:00
Eric Callahan 54abd27486 paneldue: multi-extruder fixes
Sort heater response so that the bed is displayed first, followed
by extruders in ascending order.  Set inactive extruders to
"standby" if they are on rather than "active".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-08 19:31:41 -05:00
Eric Callahan f5f87bf08c file_manager: metadata move fix
If the destination exits in the metadata database it is necessary
to either overwrite it with the source metadata or delete it
so that the new metadata can be rescanned.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-08 15:26:45 -05:00
Eric Callahan 18b84b8d9f file_manager: don't request metadata from non-gcode files
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-08 15:26:45 -05:00
Eric Callahan ec29787edd file_manager: inotify timing fix
Flush pending delete events when move and create events are detected.  This resolves timing issues with rapidfire create/delete events.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-08 15:26:45 -05:00
Eric Callahan 1ad83cec97 mqtt: fix connect/reconnect issues
Handle all potential exceptions.  Run the connect/disconnect
in another thread, as its possible for some calls to block
the event loop.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-06 08:38:27 -05:00
Eric Callahan ac73036857 machine: fix issues with network interface parsing
Don't parse non "ether" types.  Don't add interfaces that don't
have mac addresses and at least one IP address.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 17:12:21 -05:00
Eric Callahan c0c34ea045 file_manager: fix object processing option name
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 14:08:41 -05:00
Eric Callahan 7b9c6c5e77 Merge branch 'master' of https://github.com/Arksine/moonraker 2021-12-05 09:14:54 -05:00
Eric Callahan 6a90bfa480 update_manager: prevent apt from fetching updates on startup
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 09:14:49 -05:00
Pedro Lamas 8c12c137d0 moonraker: move GitHub issue templates to correct folder
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-12-05 07:01:28 -05:00
Stephan Wendel f22e16d8cc FIX: sudo_fix.sh not working on armbian
According to https://github.com/Arksine/moonraker/issues/241

Signed-off-by: Stephan Wendel <me@stephanwe.de>
2021-12-05 06:51:30 -05:00
Rafael 6852982406 Add API key info to example-home-assistant.yaml
Currently the file makes no mention of any type of auth, so I've added a short example with an explanation of when you should use it.

Signed-off-by:  Rafael Schridi <r.schridi@gmail.com>
2021-12-05 06:49:26 -05:00
Pedro Lamas d884e5288c moonraker: adds GitHub issue templates
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-12-05 06:48:21 -05:00
Eric Callahan b1c9a96040 metadata: add support for parsing layer count
Currently this is only supported in SuperSlicer.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:45:06 -05:00
Eric Callahan cfa5f4a432 file_manager: don't emit events when a node is processing metadata
When a folder is copied processing can take several minutes, depending on the size and number of gcode files in the
path.  Suppress all file events on a node until processing
is complete.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:45:06 -05:00
Eric Callahan b3d2307d36 docs: document object processing
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:45:06 -05:00
Eric Callahan 9dd0797f49 file_manager: ignore duplicate "create_file" notifications for gcode files
The the cancel object post processor results in an additional
"create_file" notification when the old file is replaced.
Track previous "create_file" notifications for valid gcode
files so the dups can be suppressed.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:45:06 -05:00
Eric Callahan ea6c78773e scripts: add preprocess-cancellation dependency
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:45:06 -05:00
Eric Callahan b7c64443db file_manager: refactor metadata processing
When destructively iterating over pending metdata requests
don't pop the pending item until metadata processing is
complete.  If a call to `parse_metadata()` has a request
pending, return the asyncio Event associated with that
request.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:45:06 -05:00
Eric Callahan 88137d5898 file_manager: add option to enable object postprocessing
Signed-off-by:  Eric Callahan <arksine.code@gmail.com
2021-12-05 06:45:06 -05:00
Eric Callahan 6bd46a4433 metadata: add support for object postprocessing
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:45:06 -05:00
Eric Callahan f00263b782 docs: document the refresh_interval option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:41:18 -05:00
Eric Callahan 13bc4c5b9b update_manager: handle system package init
Force refresh requests after server initializaton.  Update
package state after installation.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:26:34 -05:00
Eric Callahan e8c1798a13 update_manager: Prune stale data in the database
SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:26:34 -05:00
Eric Callahan 3203950ca9 update_manager: prevent refresh requests from spamming
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:26:34 -05:00
Eric Callahan 4c68086798 zip_deploy: add support for persistent state
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:26:34 -05:00
Eric Callahan bb87917c97 git_deploy: add support for persistent state
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:26:34 -05:00
Eric Callahan 74a03fca59 app_deploy: add support for persistent state
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:26:34 -05:00
Eric Callahan eb8f1e2526 update_manager: add support for persistent state
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:26:31 -05:00
Eric Callahan 3a547fb530 base_deploy: add support for persistent state
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:25:24 -05:00
Eric Callahan d23f72d232 database: increase max namespaces to 100
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:25:24 -05:00
Eric Callahan c4fa76f217 update_manager: remove refresh time tracking
This is preparation for moving refresh time tracking to the deployment
provider class.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-12-05 06:25:20 -05:00
Eric Callahan d8a31fc249 update_manager: remove init success check
Now that the update manager doesn't rely on the rate
limit it should always initialize successfully.  An individual
updater may still fail to initialize, however this does
not prevent the update manager from loading.

Singed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-28 11:15:23 -05:00
Eric Callahan 7f0712183d update_manager: remove GitHub rate limit initialization
The rate limit fields can be extracted from the response
to an API request, even if that request fails with 403.  This speeds up update manager initialization and reduces
failures if github is unreachable.

SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-28 11:15:23 -05:00
Eric Callahan f7bdfb4d6b confighelper: add get_hash method
This returns the checksum of a config section and can be used to check
if the section has changed.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-28 11:15:23 -05:00
Eric Callahan eda5623b2e database: fix invalid key handling
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-11-28 11:10:42 -05:00
Eric Callahan 3df0f3ffe4 job_queue: add websocket notification
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-27 10:23:04 -05:00
Eric Callahan 269897bef7 job_queue: rename "resume" api to "start"
Given the changes to the job queue, "start" is a more
appropriate API call than "resume".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-27 06:04:47 -05:00
Eric Callahan 4837ea56cb job_queue: register remote method to control the queue
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-26 20:35:10 -05:00
Eric Callahan e9b3d8e7ae docs: update job_queue documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-26 20:01:16 -05:00
Eric Callahan 28e88b1363 job_queue: dont attempt to start a print when empty
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-11-26 19:53:57 -05:00
Eric Callahan 784b8b9b18 file_manager: attempt to start gcode uploads prior to queueing
Only attempt to queue the upload if the job failed to start.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-26 19:46:59 -05:00
Eric Callahan f09c313c5b job_queue: fix resume request
Make sure that the queue is set to ready after resuming,
even if the next job is unable to be loaded.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-26 18:11:11 -05:00
Eric Callahan d25c3c1d49 job_queue: queue state fix
When not in automatic mode make sure the queue
state is paused after adding a job to the queue.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-26 17:19:44 -05:00
Eric Callahan 0f428acd07 docs: update job_queue documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-26 17:00:42 -05:00
Eric Callahan e8cdd8a928 job_queue: add "automatic_transition" option
When set to true, the queue will automatically transition
to the next job in the queue upon completion of the
current job.  When false the queue will pause between
jobs, requiring that the user manually resume.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-26 17:00:42 -05:00
Eric Callahan 0b9fa7d87e zeroconf: more refactoring
Resolve issues with ipv6 addresses.  Only register the
net_state_changed event handler if Moonraker is bound
to all interfaces.  Build a new instance of ServiceInfo
for each update rather than attempt to modify the
existing object.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-26 15:51:49 -05:00
Eric Callahan c89a9152b5 moonraker: log exceptions when a component_init fails
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-26 14:39:01 -05:00
Eric Callahan b70254feed zeroconf: minor formatting fix
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-26 14:30:47 -05:00
Clifford Roche 513a122290 zeroconf: Don't close on update
Signed-off-by: Clifford Roche <clifford.roche@gmail.com>
2021-11-26 14:28:06 -05:00
Clifford Roche 6258082d70 zeroconf: Implement new approach for ip detection
Signed-off-by: Clifford Roche <clifford.roche@gmail.com>
2021-11-26 14:28:06 -05:00
Eric Callahan 76e431330c machine: service unit detection fix
Add `--plain` and `--no-legend` to the command to list service units.
This fixes a bug where  a service could be prefixed with a unique
character, resulting undetected services.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-26 09:02:05 -05:00
Eric Callahan 685bd72274 app: add request debug logging
This mimics the logging available over JSON-RPC requests.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-26 06:11:13 -05:00
TravisTX d020dc81db docs: document the protocol config option
Signed-off-by:  Travis Collins <travistx@gmail.com>
2021-11-25 19:22:52 -05:00
Eric Callahan f0831cbe3c moonraker: prevent duplicate failed components
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-25 17:16:09 -05:00
Eric Callahan 2a0be55a8d power: remove has_gpio check
This prevents loading the gpio module unless a gpio
device is configured.  Resolves #283.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-25 17:16:09 -05:00
Eric Callahan ccb86ea039 proc_stats: check for network updates every 10 seconds
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-25 08:18:24 -05:00
Eric Callahan b33183f60f machine: add support for parsing network info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-25 07:58:25 -05:00
Eric Callahan 7a99f83396 server: refactor get_host_info method
Return a dict with the host name, server address, server port, and ssl port.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-25 05:43:49 -05:00
Pedro Lamas 16c8063900 docs: fixes minor typos
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-11-24 11:33:23 -05:00
Eric Callahan 50fd8c9cc4 confighelper: track default values
This restores the behavior before commit 5b4de64.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-11-23 13:55:24 -05:00
Eric Callahan 0a1367744f confighelper: fix json parsing error for gpios
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-11-23 08:21:56 -05:00
Clifford Roche 4e8e4f7d14 zeroconf: add module for zeroconf discovery
Signed-off-by: Clifford Roche <clifford.roche@gmail.com>
2021-11-22 15:03:33 -05:00
Clifford Roche 44abc64533 machine: add serial number attribute for cpu
Adds the property "serial_number" to the process info structure.

Signed-off-by:  Clifford Roche <clifford.roche@gmail.com>
2021-11-22 14:00:34 -05:00
Eric Callahan 97e27661d7 gpio: remove get_gpio_out_from_config method
The confighelper object now can setup  gpios directly.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-21 06:26:09 -05:00
Eric Callahan 0e4e3383e3 update_manager: node update fix
Use "getboolean" rather than "get" to fetch this option.

SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-20 11:40:57 -05:00
Eric Callahan fd6d318f0a power: use extended confighelper methods
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-20 11:40:57 -05:00
Eric Callahan 69e2fb810f update_mananger: use extended confighelper methods
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-20 11:40:57 -05:00
Eric Callahan 4572bd955e paneldue: use extended confighelper methods
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-20 11:40:57 -05:00
Eric Callahan 9ebae5fd5a mqtt: use extended confighelper methods
SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-20 11:40:57 -05:00
Eric Callahan 22807ee393 authorization: use extended confighelper methods
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-11-20 11:40:57 -05:00
Eric Callahan 845689fde1 confighelper: add getgpioout method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-20 11:40:55 -05:00
Eric Callahan 0b25350ebc confighelper: add support for getlist and getdict
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-20 11:40:07 -05:00
Eric Callahan c0ae10bef6 confighelper: add has_option method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-20 11:38:37 -05:00
Eric Callahan 5b4de64709 confighelper: add support for conditionals
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-20 11:38:34 -05:00
Pedro Lamas d51d65ef30 mqtt: retry connection if failed to resolve hostname
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-11-18 06:00:51 -05:00
Richard Mitchell 93299658fb wled: fix index for wled
Comparing to mqtt I think it should be H3 to appear in the index

Signed-off-by:  Richard Mitchell <richardjm+moonraker@gmail.com>
2021-11-18 05:17:36 -05:00
Eric Callahan df1892801f docs: refactor the "power" configuration docs
Add the "status_delay" option for Home Assistant and refactor to clarify what each option does for each device type.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-15 11:01:03 -05:00
Eric Callahan 1caaebe03f power: implement workaround for Homeassistant devices
Some devices on the Home Assistant server do not update their internal state immediately after a request returns.  Introduce a configurable delay to work around this issue.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-15 10:59:46 -05:00
Eric Callahan c3400bd237 power: add timer support to the RFDevice
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-15 08:11:08 -05:00
Eric Callahan 18c6ff5a99 power: refactor gpio device to use gpio component
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-15 08:11:08 -05:00
Eric Callahan 83901b1896 gpio: helper component for managing system gpios
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-11-15 08:10:29 -05:00
Eric Callahan dfa11f0f3e utils: add method to load system level modules
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-11-15 06:41:38 -05:00
Eric Callahan adb88fd8cf authorization: validate user data on startup
This provides corrective action in the event that an
invalid user entry makes its way into the database.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-15 06:00:59 -05:00
Richard Mitchell 389e9c7e62 wled: support for remote neopixel control
Signed-off-by:  Richard Mitchell <richardjm+moonraker@gmail.com>
2021-11-14 07:16:20 -05:00
FrYakaTKoP 79b1c071ad docs: change repository links from meteyou to mainsail-crew
Signed-off-by:  Christoph Frei <fryakatkop@gmail.com>
2021-11-14 06:47:17 -05:00
Pedro Lamas bed239c90a mqtt: implements last will and testament
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-11-13 11:00:26 -05:00
Eric Callahan ca27c2cf10 power: change gpiod line request based on version
For gpiod versions 1.3 or greater use the "default_val" keyword argument to set the default, otherwise use
"default_vals".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 9789b3d999 docs: update user changes
Note that core components should now be configured in their own config section.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan a9e865eb54 docs: update documenation with API and configuration changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 6d458125a1 power: fix scheduled firmware restarts
Determine if a firmware restart should be postponed by checking Klippy's state.  This should correctly schedule the restart regardless of whether or not the device is bound to Klipper.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 7f11214609 power: abort a scheduled firmware restart if klipper reports ready
This handles a specific scenario where a power device is bound to the Klipper service and is configured to perform a firmware restart after power on.  In this case, we can detect if the firmware restart is required and abort it if necessary.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 739af51904 power: add "on_when_upload_queued" option
When this option is set to "True", the device will power on after the file manager queues an upload for printing.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 484c4aea59 eventloop: fix FlexCallback annotation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan ac23f00d1f update_manager: remove initialized lock
Now that init occurs before the server starts there is no need to block requests until post initialization.

Signed-off-buy:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 2d5914b358 moonraker: attempt to resolve "event loop closed" errors on restart
Occasionally a server restart will fail as the new loop instantiates as closed.  This seems to be an issue with asyncio, attempt to work around by retyring to create a new loop.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan c718e9d1c3 moonraker: don't use a set to load initial components
Previously a set was used to remove duplicate components, however this is unnecessary as the `load_component` method immediately returns dups.  Using a list should preserve the load order based on the configuration, making it more predictable.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 76731b673b moonraker: refactor klipper initialization
The `send_event()` method now returns a future that can be awaited until all callbacks are complete.  All events emitted during Klipper init are now awaited, and a Lock is used to prevent re-entry.  This resolves potential timing issues with commands sent during the init sequence.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan c2bf9bf551 event_loop: add create_future method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 9854fd36cf power: use component_init for post initialization
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan e6bedd1ffe paneldue: use component_init for post initialization
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 799e763050 mqtt: use component_init for post initalization
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan fd59ace4f8 machine: use component_init for post initialization
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 15d99be9f0 update_manager: use component_init method for post initialzation
Clean up retry functionality to use for loops rather than while loops.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan cbdbe83bbd moonraker: refactor component initialization
Components may call a "component_init" method for initialization that requires async calls.  This allows moonraker to track init progress and guarantee init order.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 7a8aeae673 file_manager: use the job queue to start gcode uploads
If a print cannot be started then it will be queued.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan b135f48867 moonraker: add job queue to core components
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 0f1aea8df8 moonraker: refactor component loading
Remove the "load_component_multi" method as it is not
necessary.  Components are responsible for loading
"child" sections as required.  Core components can
now have their own config section.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan ec12a187fc job_queue: initial implementation
Add support for holding multiple printer jobs in a queue.
When a job successfully completes Moonraker will load
the next job in the queue.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 358fe9733f history: implement reset totals endpoint
This allows clients to request that job totals are reset to 0.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 21ee446509 history: use the job_state module to manage job events
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan d0c104aceb job_state: initial implementation
This module adds a helper to track Klippy's "print_stats" module.  It
stores the current stats and emits events for changes in job state.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-12 10:11:39 -05:00
Eric Callahan 53291f6887 power: use the default_vals keyword to init gpios
The "default_val" keyword argument is not available in libgpiod version 1.2.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-11 19:35:34 -05:00
Pedro Lamas a3ba4b4169 power: improves GPIO initial_state handling
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-11-11 19:09:06 -05:00
Pedro Lamas 7ff126a56e docs: updates to new Fluidd repo address
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-11-07 07:00:12 -05:00
Eric Callahan 4e567d72a9 readme: add links for Docker Images
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-11-05 15:35:54 -04:00
Eric Callahan 78af774413 readme: add links for Pi images
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-11-05 15:26:41 -04:00
Eric Callahan 800816055e readme: add a clients header
Also update the link to Fluidd.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-05 15:21:18 -04:00
Eric Callahan 61fab42281 moonraker: log unix socket permission errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-04 11:03:53 -04:00
FrY Sennberg 780279d261 docs: fix typo
Signed-off-by: Christoph Frei <fryakatkop@gmail.com>
2021-11-04 08:40:14 -04:00
Eric Callahan 105858b0c7 machine: fix perfomance regression
The `update_service_status()` method could result in the creation of multiple subprocesses for each update, resulting in a performance hit as subprocesses are inherently expensive.

Fetch the state for all detected services in a single subprocess.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-03 09:10:12 -04:00
Eric Callahan 6a39bbd0c3 mqtt: don't publish status updates when disconnected
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-03 08:49:40 -04:00
FrY Sennberg eec60a760b git_deploy: report git repository name
Signed-off-by: Christoph Frei <fryakatkop@gmail.com>
2021-11-01 19:10:35 -04:00
Eric Callahan 9f89b03aa3 docs: update /server/info documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-01 11:24:31 -04:00
Eric Callahan 86ac019572 moonraker: report software version in server.info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-01 11:24:31 -04:00
Eric Callahan 4f43cf3a9f shell_command: handle ProcessLookupError when cancelling
This suggests that the process has previously exited.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-11-01 08:25:28 -04:00
Eric Callahan e71e723f89 confighelper: attempt to clarify unparsed config warnings
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-31 19:17:25 -04:00
Eric Callahan 8e33698e23 power: improve logging when the gpiod module fails to load
Log all import errors other than ModuleNotFound errors.  Add a server warning if a gpio type is configured and the gpiod module is not loaded.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-31 19:12:20 -04:00
Eric Callahan 2addf845d3 machine: add PNY to the list of known SD manufacturers
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-31 19:12:00 -04:00
Eric Callahan f9372f3638 scripts: remove Klipper check in install script
Moonraker no longer requires that Klipper be installed and started prior to launch.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-31 06:11:06 -04:00
Eric Callahan 21305853ce scripts: add liblmdb-dev and libjpeg-dev to dependencies
These packages can be required on systems that need to build python wheels.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-31 06:03:56 -04:00
Eric Callahan 504d87831d docs: document "root_info" filed reported by get_directory
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-30 17:06:14 -04:00
Eric Callahan b55b21921a file_manager: report additional info in response to get_directory
Include the root's name and its permissions.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-30 16:49:41 -04:00
Eric Callahan e9b06472c1 file_manager: minor refactoring in _list_directory method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-30 16:46:40 -04:00
Eric Callahan aa608b4c29 metadata: support extracting thumbnails from footer
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-30 11:01:27 -04:00
Eric Callahan 4e262dfa14 file_manager: remove redundant code in delete_file method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-30 07:34:40 -04:00
Eric Callahan 538c68fc8b file_manager: normalize path requests
This resolves an issue where a path is containter two slashes as a separator reports as outside of the root.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-30 07:28:55 -04:00
Eric Callahan 28c8bf61da machine: add a more robust container check
Most containers do not have access to systemd, so using
systemd-detect-virt will fail.  We can check the cgroup
and sched files of the first process to reliably determine
if Moonraker is running within a container.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-28 19:38:15 -04:00
Eric Callahan 179e9428c5 docs: add 'virtualization' to the return value of system_info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-28 11:45:13 -04:00
Eric Callahan f35bceb309 machine: detect virtualized envronment
It isn't valid to run some commands from within containers.  Use systmd-detect-virt to detect a virtualized environment and report the type and id via the system_info endpoint.

If Moonraker is running from within a container do not allow access to the reboot and shutdown endpoints.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-28 11:45:13 -04:00
Eric Callahan 7890753d9f docs: update documentation to reflect api changes
The file list and directory list endpoints now report file
permissions.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-27 12:02:06 -04:00
Eric Callahan de8c0fc871 file_manager: fix inotify symlink handling
When a symbolic link is created there is no completion event, so immediately fire the notification.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-27 11:24:57 -04:00
Eric Callahan e33962fdd4 file_manager: check write permissions for uploads
If the specified path is a symbolic link do not proceed with the upload, raise an exception.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-27 08:55:44 -04:00
Eric Callahan 734f295822 file_manager: allow registration of full access directories
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-27 08:55:44 -04:00
Eric Callahan 4c42b8d072 file_manager: report file and directory permissions
Signed-off-by: Eric Callahan <arksine.code@gmail.com>

fix
2021-10-27 08:55:19 -04:00
Eric Callahan 1dd89bac4b docs: bump mkdocs requirement to 1.2.3
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-24 12:46:56 -04:00
Eric Callahan f086f75c07 docs: Add documentation for new service and power features
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-24 12:46:56 -04:00
Eric Callahan 47999e24c4 power: add support for bound services
A bound service is stopped when a device powers off and started when a device is powered on.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-24 12:39:52 -04:00
Eric Callahan 12e035b6eb machine: list all active units
This resolves an issue where an allowed service is not
tagged as available if it is not loaded when moonraker
starts.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-10-24 08:45:28 -04:00
Eric Callahan 9d7dac3425 moonraker: rework Klippy init sequence
Stop polling Klippy after it it has exited the "startup" state.
When this has been detected, emit a "klippy_startup"
event.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-24 08:45:28 -04:00
Eric Callahan a0b5275cc9 machine: add method to wait for service init
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-10-23 10:20:07 -04:00
Eric Callahan 97522947ec proc_stats: update service state in the proc_stat timer
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-23 10:20:07 -04:00
Eric Callahan 8126a73663 machine: report active status of available services
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-23 10:20:07 -04:00
th33xitus 6a6422c16e metadata: add IdeaMaker thumbnail parsing
This commit allows Moonraker to parse thumbnails from g-code files generated by IdeaMaker.

Signed-off-by:  Dominik Willner <th33xitus@gmail.com>
2021-10-14 14:23:00 -04:00
Eric Callahan 8b510d9b03 docs: document the "timer" option for the power component
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-14 08:03:13 -04:00
Eric Callahan 838b25d288 power: implement timer functionality for gpio devices
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-14 08:03:13 -04:00
crashmaxx 2836600857 power: add timer option to tplink-smartplug devices
Signed-off-by: Andrew Stowell crashmaxx@gmail.com
2021-10-12 06:35:32 -04:00
Eric Callahan 562f971c3d docs: update the mqtt documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-10 18:08:25 -04:00
Eric Callahan 25f9800f77 moonraker: don't send status updates for empty objects
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-10 17:58:43 -04:00
Eric Callahan 0ed367d734 mqtt: support specifying fields in "status_objects" option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-10 12:21:27 -04:00
Eric Callahan 070e03d741 file_manager: Don't filter inotify events on the gcodes root
Broadcast events for all files and let clients determine
what should be shown.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-10 11:33:33 -04:00
Eric Callahan 7f1c327f02 file_manager: hidden folder bugfix
Since inotify supports hidden folders we shouldn't skip them when scanning for nodes.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-10 11:04:59 -04:00
Eric Callahan c631bff0c9 docs: Document MQTT support for printer objects
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-08 15:33:11 -04:00
Eric Callahan 0c311aeef4 mqtt: add support for publishing klipper status updates
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-08 14:17:13 -04:00
Eric Callahan b1f122beec scripts: update service to start after the network is brought online
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-10-08 08:07:03 -04:00
danijoo c3f1b290f8 power: add RF transmitter support
Signed-off: Daniel Bauer <github@dbauer.me>
2021-10-03 09:05:12 -04:00
Eric Callahan 86764657cf machine: add moonraker-telegram-bot to list of allowed services
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-29 18:08:08 -04:00
Eric Callahan 4df93481ec docs: add note about nginx to installation.md
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-29 17:22:58 -04:00
Eric Callahan 4e2bbde829 scripts: remove nginx dependency
Moonraker itself does not depend on nginx and it
is no longer required to install clients on the host.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-09-29 17:22:26 -04:00
Eric Callahan fdfab66951 metadata: add PrusaSlicer aliases
The varous forks of PrusaSlicer are processed identically
outside of their identifier, so there is no need to
implement new classes for each fork.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-28 06:14:24 -04:00
Eric Callahan 81b0c0a581 docs: minor API change reflecting new owner of Klipper repo
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-24 12:22:45 -04:00
Eric Callahan 00c6072274 workflows: update Klipper's repo location
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-24 12:22:45 -04:00
Eric Callahan 9c09ca2ed5 update_manager: add support for moved git repos
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-24 12:22:45 -04:00
Eric Callahan 2447ccab62 docs: update proc_stats documentation
The "websocket_connections" is now reported by proc_stats.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-21 14:22:19 -04:00
Eric Callahan d6fafef902 proc_stats: report websocket connection count
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-21 14:19:01 -04:00
Eric Callahan 46a8723566 scripts: add libcurl4-openssl-dev dependency
This dependency is also require to build the pycurl wheel.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-21 14:02:09 -04:00
Eric Callahan 233be2e889 scripts: add libssl-dev dependency
This is required for operating systems that need to build
the pycurl wheel

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-21 13:08:27 -04:00
Eric Callahan 83eddf5e7d docs: update /server/info documentation
Note the addition of the "websocket_count" field.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-21 11:35:58 -04:00
Eric Callahan b1d739e032 moonraker: report websocket connection via /server/info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-21 11:30:25 -04:00
Eric Callahan e76e83d8c1 moonraker: configure the tornado http client to use the curl backend
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-21 08:32:24 -04:00
Eric Callahan 73d3eae8ae scripts: add pycurl dependency
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-21 08:23:32 -04:00
Eric Callahan e92da4c82c power: add gpiod support for Arch Linux
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-15 18:09:20 -04:00
Eric Callahan 776e0d6c90 file_manager: strip leading slashes supplied in the upload path argument
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-14 14:43:00 -04:00
dependabot[bot] 8ca953f55c build(deps): bump pillow from 8.2.0 to 8.3.2 in /scripts
Bumps [pillow](https://github.com/python-pillow/Pillow) from 8.2.0 to 8.3.2.
- [Release notes](https://github.com/python-pillow/Pillow/releases)
- [Changelog](https://github.com/python-pillow/Pillow/blob/master/CHANGES.rst)
- [Commits](https://github.com/python-pillow/Pillow/compare/8.2.0...8.3.2)

---
updated-dependencies:
- dependency-name: pillow
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-09-13 05:34:32 -04:00
Pedro Lamas db3f69e0dd Improves Home Assistant failure handling
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-09-04 05:39:55 -04:00
Pedro Lamas 183f4a75e5 Adds Home Assistant power switch example
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-09-04 05:39:55 -04:00
Eric Callahan 628c7e2e4d docs: fix typos
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-09-04 05:38:03 -04:00
Stefan Dej 81176a6d31 confighelper: update 'Invalid config option' warning for better understanding
Signed-off-by: Stefan Dej <meteyou@gmail.com>
2021-08-29 14:15:12 -04:00
Eric Callahan 245053434f authorization: specifically identify basic auth
Raise an exception when a request with Basic Auth is received, however do not log the username/password.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-08-28 08:54:40 -04:00
Eric Callahan dfb8da6e3e authorization: improve error message for invalid auth headers
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-08-27 06:11:55 -04:00
Eric Callahan b040640813 update_manager: broadcast update_refreshed notification in the status refresh handler
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-08-26 15:44:26 -04:00
Eric Callahan a1cf02231a scripts: add --allow-releaseinfo-change option to apt-get in install-moonraker.sh
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-08-24 06:41:45 -04:00
Eric Callahan 8a7b348899 update_manager: fix apt-get issue with changed release info
Add --allow-releaseinfo-change to the call to apt-get.  This resolves an issue where the repos are chaning their "Suite" value from stable to oldstable with the release of Debian Bullseye.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-08-24 06:39:54 -04:00
Pedro Lamas f1523ef5f8 Fixes rounding issue in home assistant sensor
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-08-21 18:05:06 -04:00
Eric Callahan 5204fe3e08 metadata: fix est time parsing for Simplify3D
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-08-07 11:45:44 -04:00
Pedro Lamas 5522e150b7 docs: Refactors the Home Assistant example
Signed-off-by: Pedro Lamas <pedrolamas@gmail.com>
2021-07-28 15:47:26 -04:00
Eric Callahan 86e0ef0d5e git_deploy: use "git pull --rebase" when repo debug is enabled
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-27 05:52:56 -04:00
Eric Callahan 42f61ceafa power: attempt to retry failed device init for 120 seconds
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-18 14:26:10 -04:00
Eric Callahan 2f95b0f426 docs: add network reporting to proc_stats documetation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-18 09:06:03 -04:00
Eric Callahan c684b063b2 proc_stats: report network stats for all interfaces
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-18 08:49:38 -04:00
Eric Callahan 8f8d780c72 proc_stats: fix stat logging when the event loop is blocked
Convert the deque to a list before slicing.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-15 11:03:07 -04:00
Eric Callahan 91f264bdaf update_manager: fix unbound variable error
Signed-off-by:  Eric Callahan <arksine.code
2021-07-15 08:14:18 -04:00
Eric Callahan 1fdfb5299e moonraker: create a new asyncio event loop on restart
This should guarantee that no dangliing callbacks are leftover on a soft restart.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-15 06:57:54 -04:00
Eric Callahan 0d1431395e update_manager: fix potential race condition with auto_refresh
Wait until update manager init is complete before attempting starting the auto refresh periodic callback.  This prevents an auto refresh from blocking init if Moonraker is started during the auto refresh window.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-07-15 06:52:04 -04:00
Eric Callahan 7f740ccb5a authorization: add warning if a domian in "cors_domains" contains a trailing slash
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 15:47:38 -04:00
Eric Callahan f94a27c8e4 docs: add documentation for "is_system_service" option 2021-07-12 15:37:31 -04:00
Eric Callahan cb8d5ecb35 app_deploy: add "is_system_service" configuration option
This allows users to add update manager "clients" that don't have systemd services registered.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 07:47:43 -04:00
Eric Callahan a921b4269e test: remove test client files
The test client has been moved to its own repository, Arksine/moontest.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 07:47:43 -04:00
Eric Callahan 87444f5bcb zip_deploy: allow updates to stable releases when on the "beta" channel
Users on the "beta" channel should be updated to the latest release, including stable releases.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 07:47:43 -04:00
Eric Callahan 2ceafb0ff5 git_deploy: replace references to ioloop with eventloop
Wrap some additional system calls that could potentially block in "run_in_thread".

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:34:15 -04:00
Eric Callahan 912840bbcd zip_deploy: replace references to ioloop with eventloop
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan d52554231a app_deploy: replace reference to ioloop with eventloop
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan c4796ee321 update_manager: replace references to ioloop with eventloop
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan 13a85fe9e0 file_manager: replace references to ioloop with eventloop
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan e4ecc1febe authorization: replace references to ioloop with eventloop
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan 646e97ad55 machine: replace reference to ioloop with eventloop
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan 05e2389dc1 mqtt: replace references to ioloop with eventloop
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan 8382b90682 paneldue: replace reference to ioloop with eventloop
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan c61cfa325f power: replace references of ioloop with EventLoop
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan 78e10cf7f8 proc_stats: Use the EventLoop to run blocking calls in in a background thread
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan 85d12da18d shell_command: replace tornado lock with asyncio lock
Also use asyncio's sleep method in place of tornado's wrapper around it.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan 4430d564fe websockets: replace references to ioloop with event loop
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan 8a3ff7a54a app: replace refrences to ioloop with eventloop
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan d224536552 moonraker: replace calls to ioloop with eventloop wrapper
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan 07cb64a191 eventloop: initial implementation
This adds a thin wrapper around asyncio's eventloop.  Generally it is similar to Tornado's IOLoop, however without the need to support all awaitables.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-12 06:16:18 -04:00
Eric Callahan 1ce8af18ec docs: add "web_beta" documentation for the update_manager
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-09 18:06:07 -04:00
Eric Callahan fddc67db93 update_manager: add support for web betas
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-09 18:06:07 -04:00
Eric Callahan df43aca222 proc_stats: fix erroneous timer handle assignment
The delayed callback to "log_last_stats()" in the Watchdog shold not have its return value assigned to the watchdog handle.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-09 08:01:27 -04:00
Eric Callahan fb9206aa8f proc_stats: read system files in another thread
This should prevent the event loop from getting blocked by a system call.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-09 05:53:11 -04:00
Eric Callahan e20c12619b git_deploy: compare upstream url to lowercase url during validation
SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-08 12:09:17 -04:00
Eric Callahan 211c7e70e1 app_deploy: fix typo preventing repo clients from loading
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-08 11:58:11 -04:00
Eric Callahan d60b852b27 docs: add documentation for latest changes to the update manager
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-07-08 10:52:56 -04:00
Eric Callahan dacd9f7565 update_manager: report detected_type and configured_type for applications
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-08 09:02:08 -04:00
Eric Callahan d76abe019f update_manager: return True when on update success
All calls to update now return a boolean value.  When performing a full upate this return value is used to
check if Moonraker should wait for Klippy to reconnect.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-08 07:55:50 -04:00
Eric Callahan b6cd19d6ef update_manager: make application package updates generic
This ignores an attempt to update packages if system updates are disabled and opens the possibility for supporting updates for other linux distributions.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-07 18:27:12 -04:00
Eric Callahan 74630f933a update_manager: use asyncio locks
Transion away from Tornado's wrappers, as their implementation of
"wait()" can be confusing.  Some of tornado's methods require that
you specify a delay in seconds, others requrire that you specify a
timeout relative to the Unix epoch.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-07 18:27:07 -04:00
Eric Callahan 9133b59dbf update_manager: add "full" update endpoint
This endpoint will perform a full system update.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-07 18:26:30 -04:00
Eric Callahan 10da7b714f update_manager: add support for zip deployment
This adds support for updating packaged applications from GitHub.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 908501cbc8 update_manager: remove unnecessary Is_refreshing check
The underlying deployment implementations use locks to prevent concurrent attempts at refeshing state, thus the "is_refreshing" check is redundant.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 5d35cc0d10 update_manager: Implement async streaming downloads
This allows Moonraker to report download progress.  This also resolves potential issues with I/O blocking the event loop.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan f2b48d0f1a update_manager: refactor github API requests
Save a request cache in the CommandHelper that stores the etag and value for each URL requested.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 88ee83c7d8 update_manager: use pathlib to represent file system paths
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan d3ec2dbae2 update_manager: refactor application deployment
This is the first step toward creating mutliple methods for deployment.  This patch creates a base class for all deployment objects and a base class for application deployment.  The git functionality has moved to its own module.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 78edcab86e confighelper: don't add supplemental configs to the original
Create a new ConfigParser that reads the supplemental and return a new ConfigWrapper.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 627db24c63 update_manager: make system updates optional
Remove the "distro" config option as it is not necessary.  If there is a need to identify the linux distribution that can now be done through the distro dependency.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 7c56a8fa74 utils: add method to validate packaged applications
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 0527904c48 moonraker: remove references to "system_args"
Rather than add these arguments to the config, use a method to access them from the server object.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 3642003dd2 workflows: add workflow to publish assets for a new release
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 2c47064d79 scripts: add release build scripts
Add a script that can build zipped releases to be distributed by Moonraker's Update Manager.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 39a532cf87 utils: move git version parsing into its own method
This creates a generic utility for retreiving the git version.  Moonraker will now attempt to parse basic version info from a ".version" file if git describe fails.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan ebaac290e7 utils: add a method to calculate the hash of a directory
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 5379e4b4bd scripts: remove version.txt
This file is no longer required for moonraker, the version info will either be stored in the pex file or retreived from git.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 6b03c4600d scripts: minor install script fixes
Fix the systemd unit description.  Make the launch command variable.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 7ed54a166b scripts: provide a log path option in install-moonraker.sh
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Arksine 2ab63d75fc moonraker: fix imports for type checking
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Arksine 1c248d1de8 moonraker: remove check for component existence in "load_component()"
The importlib module will raise an exception if the component does not exist, so the check is redundant.  This allow allows packages to be loaded.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Arksine 261fbbc867 file_manager: move modules to its own package
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Arksine 346015e528 update_manager: move the "rebuild env" functionality
Initially rebuilding the venv was required to change env options to include dist packages.  This is no longer necessary so we can remove detection for it.  Building a venv could still be necessary, so move this functionality to its own method.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Arksine 8b8d538a9c update_manager: remove dist package options
These options are no longer necessary, as we now apply the dist path before the import in modules that require dist packages.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Arksine 5b260a5ba6 update_manager: correct relative paths
Update the paths to Moonraker and the supplemental configuration file.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>

Update update_manager.py
2021-07-06 19:25:10 -04:00
Arksine 03892a517e update_manger: move module into its own package
This includes its specific configuration file.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Arksine 30155c4a8c power: add special handling for gpiod import
Rather than symlink the gpiod dependency in a virtualenv, temporarily add the dist-package to sys.path then import gpiod.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Arksine bfef2eb98e file_manager: update location of metadata script
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Arksine 7ccb455174 metadata: move extract_metadata.py to components
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:25:10 -04:00
Eric Callahan 80df137437 websockets: fix call to wait() in WebsocketHandler.close()
The wait timeout must be relative to the current time.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:24:52 -04:00
Eric Callahan a605cd3048 file_manager: NotifySyncLock bugfix
The time() method must be called on the current IOLoop.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 19:22:46 -04:00
Eric Callahan c7f8689bfe docs: fix incorrect documentation on eventtime
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 15:54:29 -04:00
Eric Callahan 12a7f957c3 docs: note addition of the "eventtime" param to "notify_status_update"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 15:43:02 -04:00
Eric Callahan c6fee3c1f4 moonraker: send status eventtime as a second parameter to "notify_status_update"
This resolves a potential issue where clients could anticipate that all items in the status parameter are objects.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 14:56:18 -04:00
Eric Callahan 81854d1daf moonraker: report Klipper event time with status subscriptions
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-07-06 14:35:09 -04:00
Eric Callahan 4836f52a5d shell_command: ignore utf8 decode errors
Also catch a potential KeyError when removing running commands.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-07-06 07:26:09 -04:00
Eric Callahan 5c05afae42 docs: Update mkdocs version
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-28 20:27:40 -04:00
Eric Callahan 77052e15b0 docs: update MQTT documentation
Reflect the new behavior of wait_connection()

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-28 20:27:40 -04:00
Eric Callahan ecc0fbdae9 mqtt: return a boolean in the wait_connection method
Rather than require consumers handle the TimeoutError, handle it directly and return the connection state.

SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-28 12:45:50 -04:00
Eric Callahan 00f4bd594f app: prevent static file reads from blocking the event loop
Perform reads in a thread so File I/O does not block.

This patch also disables ETags for static files.  Tornado's default behavior of caching file hashes will not work as many of Moonraker's can be updated.  The previous workaround to this was to recalculate the checksum if the modified date changed.  This is inefficient  as its behavior is not much different than using "If-Modified-Since".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-28 07:31:40 -04:00
Eric Callahan 3529acfeec proc_stats: report a blocked event loop
Use the PeriodicCallback in proc_stats to check if the event loop was blocked for a More than 5 seconds.  If this is detected, log
Moonraker's CPU usage over that time.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-27 17:10:49 -04:00
Eric Callahan 1510f66121 app: Process file uploads in a thread pool executor
This should prevent large file uploads from blocking the asyncio event loop for a long period of time.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-27 12:33:52 -04:00
Eric Callahan c22dcc18dc docs: Remove unreferenced macro
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-26 20:12:10 -04:00
Eric Callahan b6f9769488 websockets: refactor message handling
Implement a write buffer so that all calls to "write_message" are awaited.  This allows for more graceful shutdown if the websocket is closed.

When Moonraker shuts down, attempt to wait for all websockets to close before exiting.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-26 15:33:35 -04:00
Eric Callahan 188dc4c782 docs: add MQTT documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-26 11:44:29 -04:00
Eric Callahan 0126aa794f mqtt: initial support for mqtt connections
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-26 08:10:32 -04:00
Eric Callahan 2bc7efd20e octoprint_compat: only register endpoints with the http transport
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-25 17:46:43 -04:00
Eric Callahan 566df69ca5 moonraker: expose additional app methods
Add references to the application's "get_websocket_manager" and "register_api_transport" methods.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-25 17:46:43 -04:00
Eric Callahan 40f21b10cd app: allow transport registration
This allows eligible components to register themselves as API transports.  By default the WebsocketManager is registered.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-25 17:46:43 -04:00
Eric Callahan a7801db6e7 websockets: Make the JsonRPC class more generic
Allow JsonRPC to be used with transports other than the websocket.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-25 17:46:43 -04:00
Eric Callahan 06bbca7ae3 moonraker: add method to set a component as failed
Some components require post-load initialization after the IOLoop has started.  Provide a method for these components to register a failure with the server.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-22 19:38:09 -04:00
Eric Callahan 331be63c9e scripts: add paho-mqtt dependency
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-22 08:21:26 -04:00
Eric Callahan d3df568aec extract_metadata: don't remove ufp files after failed extraction
Cura writes ufp files in chunks, closing the file after each chunk is written.  This will result in a failed extraction, and removing the file will result in corruption.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-18 06:15:54 -04:00
Eric Callahan 9e909e8532 docs: add "cancelled" state to print_stats documentation
Refactor the available values so that they are more readable.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-16 15:50:04 -04:00
Eric Callahan 1b2fa4924b docs: fix typo in metadata return value
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-15 15:25:40 -04:00
Kamil Trzcinski 20673b9edd pause_resume: Make Moonraker to use pause_resume/* API
This switches Moonraker from calling `CANCEL_PRINT` and alikes
to rather use `pause_resume/` API that underneath calls
the relevant G-Codes.

This done, this way, allows Klipper to be able to interrupt
blocking operations gracefully.

Signed-off-by: Kamil Trzcinski <ayufan@ayufan.eu>
2021-06-15 12:22:43 -04:00
Rafael Schridi 3b4bfba85e Add variable domain support for Home Assistant
Defaults to the hard-coded "switch" domain used before

Signed-off-by:  Rafael Schridi <r.schridi@gmail.com>
2021-06-13 18:17:08 -04:00
Eric Callahan 42bdb42573 database: read out all namespaces on init
If a namespace contains an invalid key reading out the namespace should correct the issue.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-13 11:04:44 -04:00
Eric Callahan c9a958f861 database: track unsafe shutdowns
Keep track of the number of unsafe shutdowns a machine experiences.  This data is useful in diagnosing potential file system issues and issues with the datbase itself.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-13 09:15:09 -04:00
Eric Callahan 9a316fe84a database: check for invalid keys
It is invalid for a namespace to contain a top level key represented as an empty bytestring.  If this is detected, log the result and drop the invalid key.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-13 08:18:12 -04:00
Eric Callahan 92423911a9 file_manager: upload request fix
Make sure that inotify watches are added for new directories created via the upload endpoint.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-12 17:22:01 -04:00
Kamil Trzcinski 6770a965a6 history: add support for cancelled state
Signed-off-by: Kamil Trzcinski <ayufan@ayufan.eu>
2021-06-12 11:35:35 -04:00
Eric Callahan 33cb18517a docs: update response to "/machine/system_info"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-10 19:58:11 -04:00
Eric Callahan 9ea91f4f5d machine: report total memory from /proc/meminfo
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-10 19:58:11 -04:00
dependabot[bot] d9d3739118 build(deps): bump pillow from 8.1.2 to 8.2.0 in /scripts
Bumps [pillow](https://github.com/python-pillow/Pillow) from 8.1.2 to 8.2.0.
- [Release notes](https://github.com/python-pillow/Pillow/releases)
- [Changelog](https://github.com/python-pillow/Pillow/blob/master/CHANGES.rst)
- [Commits](https://github.com/python-pillow/Pillow/compare/8.1.2...8.2.0)

---
updated-dependencies:
- dependency-name: pillow
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2021-06-08 19:20:15 -04:00
Eric Callahan 0b885ec5ec file_manager: scan metadata for renamed gcode files
Some slicers create a temporary file during export, then rename the file with gcode extension after completion.  If file metadata does not exist during an attempt to move metadata, scan the file.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-08 16:55:04 -04:00
Eric Callahan b16110bcd0 mooraker: refactor stop_server()
Shutdown the websocket and http server before doing final component cleanup.  This prevents clients from making a request after components have been closed.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-07 11:17:52 -04:00
Eric Callahan 936d766cae authorization: correctly handle the transition from a deprecated signature algorithm
SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-04 14:48:21 -04:00
Eric Callahan 108d0578a2 scripts: update moonraker python requirements
Remove python jose and cryptography.  Add pynacl.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-03 05:46:14 -04:00
Eric Callahan 39343f984a authorization: switch to EdDSA signatures
This removes the cryptography dependency in favor of libsodium.  Also removed is python-jose, as we must generate our own JWTs for use with EdDSA.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>

use libnacl instead of pynacl
2021-06-03 05:45:56 -04:00
Eric Callahan 628c0193f3 machine: extend allowed services
Allow all services that start with a match.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-06-02 17:46:34 -04:00
Eric Callahan def6b365fa machine: fix service case sensitivity bug
Systemd units are case sensitive, do not convert the "name" argument for service requests to lower case.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-31 07:34:16 -04:00
Eric Callahan 0ab9ffdc93 docs: add machine API changes
MoonCord and KlipperScreen have been added to supported services.  The "/machine/system_info" endpoint now returns a list of available services that moonraker may control.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-30 14:36:28 -04:00
Eric Callahan 1b3efb1a78 machine: add support for controlling MoonCord and KlipperScreen services
Provide a list of available services in the `/machine/system_info` endpoint.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-30 14:21:07 -04:00
Alan Harper d6156dee68 power: Fix Home Assistant exception
Home Assistant returns an empty response when switching a switch
on or off. Will now requery the switch status and return it's result

Signed-off-by:  Alan Harper <alan@aussiegeek.net>
2021-05-29 14:12:20 -04:00
Alan Harper 541f5e54dc power: Add https support for Home Assistant
Signed-off-by:  Alan Harper <alan@aussiegeek.net>
2021-05-29 14:12:20 -04:00
Eric Callahan 793ab6b24b app: add a redirect endpoint
Clients can use this in situations where a browser may
prompt the user to take action prior to sending the
request.  After the user accepts, Moonraker will redirect the user to the url provided in the request.

SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-28 21:03:03 -04:00
Eric Callahan 082134b9a0 authorization: raise a 401 error in the event that a JWT failes decoding
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-28 18:26:32 -04:00
Arksine 2db727e40f file_manager: handle situations where file transfer is corrupt
The addition of inotify can introduce scenarios where file transfers complete abruptly, resulting in a corrupt/incomplete file.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-26 06:41:59 -04:00
Arksine fc5420db27 file_manager: filter out websocket notifcations in the gcodes root
Only push notifications for files with valid gcode extensions.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-26 06:32:31 -04:00
Arksine aeb24dabdb file_manager: add watches for hidden directories
The logic used to sync requests to modify contents in hidden directories is no longer necessary, thus removed.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-26 06:32:31 -04:00
Arksine 3d0d1e1dcb file_manager: disallow requests for paths outside of a root
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-26 06:31:47 -04:00
Arksine 5f7cff9af8 authorization: attempt to resolve cryptography import issues
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-24 07:25:31 -04:00
Arksine d7c367f095 update_manager: update pip before installing new python deps
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-24 06:38:10 -04:00
Arksine aa9641024a authorization: restrict CORS headers on non-options requests
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-23 20:36:26 -04:00
Arksine 60d6c748ef moonraker: rename deprecated "logging.warn"
Python uses "logging.warning" to log warning level methods.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-23 14:46:46 -04:00
Arksine dc4da6087f authorization: rename the oneshot request handler
Naming the method "_handle_oneshot_request" is less ambiguous than "_handle_token_request".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-23 14:46:46 -04:00
Arksine 8a3b885eca authorization: use ES256 algorithm for JWT signatures
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-23 14:46:46 -04:00
Arksine ce7f659a32 authorization: use python_jose dependency for jwt management
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-23 09:09:53 -04:00
Arksine e4e58f6d97 scripts: add python-jose python dependency
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-23 09:09:53 -04:00
Arksine a18987aa59 app: raise an exception if configured ssl cert or key files do not exist
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-22 08:22:46 -04:00
Arksine 5db74b724e docs: document https configuration options
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-21 20:00:41 -04:00
Arksine aba3e374c3 test client: fix mixed content issues with https
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-21 15:25:26 -04:00
Arksine dcf1cdf526 moonraker: add support for serving https with self signed certs
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-21 12:45:45 -04:00
Arksine 68b9a073af update_manager: compare file hashes rather than modified times
The metadata won't always depict an actual change to the content of a file.  Compare a hash of the file content rather than retrieve modified times to determine if it is necessary to install dependencies.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-21 08:58:40 -04:00
Arksine f1ba8e3d9b shell_command: Use a lock to prevent re-entrant calls
Re-entrant calls to "run" and "run_with_response" would poison the process state resulting in unexpected behavior.  Use a lock to prevent this.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-21 08:54:48 -04:00
Arksine e7193dbb5f shell_command: track running commands and cancel them prior to moonraker exit
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-21 08:54:48 -04:00
Arksine e15ef345bc shell_command: run_with_response fixes
Reset the command tracking data before each retry.  If the command is cancelled by the user immediately break.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-21 08:54:48 -04:00
Arksine 564e33bc18 update_manager: enhance attempt to recover from loose object errors
Attempt to recover from "loose object" error in git status and git fetch commands.   It is no longer necessary to run git fsck on every refresh attempt, only run it after a recovery attempt.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-21 08:54:48 -04:00
Arksine daa7b5edd4 update_manager: allow the remote method to run a generic command
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-21 08:54:48 -04:00
Arksine a012c4b772 update_manager: remove unused rsync methods
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-21 08:54:48 -04:00
Arksine 58f7aa0a57 update_manager: Implement clone method for GitRepo class
Replace the existing rsync "hard" recovery method with a call to git clone.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-21 08:54:48 -04:00
Arksine 81f2393b46 update_manager: Don't set the std_err_callback for async git commands
When no callback is set for stderr, the outputfrom stderr is piped to stdout.  This makes setting the callback redundant.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-21 08:54:48 -04:00
Arksine 5d783a743a app: re-enable authorization checks on static files
Image files (.png) are still granted unauthorized access, however all other files require that the request be authorized.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-20 17:07:48 -04:00
Arksine c335b62d26 file_manager: fix sync issues with hidden directories
While inotify watches are not applied to hidden directories it is still valid to use Moonraker's endpoints to perform operations on them.  When performing an operation on an item within a hidden directory, or on a hidden directory itself,  do not sync the request with inotify.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-20 08:35:26 -04:00
Arksine e7ca2d6adc docs: add 'warnings' field to "/server/info" response
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 20:42:44 -04:00
Arksine ceae5bb88b moonraker: report a 'warnings' field in "/server/info"
This allows clients to display a list of warnings that Moonraker detects.   Previously this info was only logged.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 20:37:36 -04:00
Arksine 36aec50bce docs: update authorization documentation
Document the "force_logins" option and the ability to accept JSON Web Tokens via the query string.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 19:59:06 -04:00
Arksine b8cf0d7fd2 authorization: check the query string for jwts
Clients may pass a json web token via the query string's "access_token" argument to authorize requests that do not allow modified headers.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 19:18:23 -04:00
Arksine dca7bd51cd authorization: add 'force_logins' option
When "force_logins" is enabled a user login is required if at least one user is registered, overriding the "trusted_clients" configuration.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 19:05:48 -04:00
Vladimir Poleh 6b9a3c656d app: Fixed download for the files with non-ASCII characters in name.
Replace non-ASCII characters with "?" and add escaped unicode version of the file name to the "Content-Disposition" header to fix problems with thumbnails and downloading for the gcode file with non-ASCII characters in filename.

Signed-off-by: Uladzimir Palekh <visor.rti@gmail.com>
2021-05-19 17:43:49 -04:00
Arksine 829b3a4ee8 docs: document log path for the file manager
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 08:26:30 -04:00
Arksine f5ccddb52b file_manager: add support for an optional "logs" root
This root may be used to store log files for Klipper, Moonraker, and other applications as necessary.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 08:23:24 -04:00
Arksine 94e1dcf2cb docs: update contributing doc
Update the code style guidelines informing contributors that they should validate their code with pycodestyle and mypy before submission.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 08:19:21 -04:00
Arksine 7465de389f gh-actions: enable mypy static type checking
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 07:34:05 -04:00
Arksine c83d91eea7 extract_metadata: add annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 06:59:38 -04:00
Arksine dbe28751df file_manager: add annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 06:59:38 -04:00
Arksine d392a895d9 update_manager: add annotations
USER CHANGE:  The deprecated "client_repo" and "client_path" options have been removed in this commit.  Use [update_manger client client_name] to configure clients.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 06:59:38 -04:00
Arksine 1026d59cad paneldue: add annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 06:59:38 -04:00
Arksine 1ada457364 power: add annotiations
This includes a refactoring of the PowerDevice base class so that it defines some abstract methods that its children must implement.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-19 06:54:57 -04:00
Arksine 12246029ef proc_stats: add annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:49 -04:00
Arksine c977948c2c octoprint_compat: add annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:49 -04:00
Arksine 9994e1eb84 machine: Add annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:49 -04:00
Arksine 1755d0f970 history: add annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:49 -04:00
Arksine f5010e960b data_store: add annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:49 -04:00
Arksine 9bf4ade35b klippy_apis: Add annotiations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:49 -04:00
Arksine ce7495ecce shell_command: add annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:49 -04:00
Arksine 41ddbb16a8 authorization: add annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:49 -04:00
Arksine 410db750c6 database: add annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:49 -04:00
Arksine b91df6642d app: add annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:49 -04:00
Arksine 420ba065da confighelper: add annotations
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:48 -04:00
Arksine ca69a10838 moonraker: add annotations
Annotate function definitions, class attributes, and local variables as necessary for type hinting.  This is useful for IDEs with linters that support type hints and also can be used by GitHub Actions to detect erroneous code.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:48 -04:00
Arksine 9c76dbef7a websockets: add annotations
Implement a "Subscribable" base class for objects that can maintain a status subscription.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:48 -04:00
Arksine 96e69240ca utils: add annotations
Add a SentinelClass singleton.  This can be used to generate Sentinels by
modules that need to use the Sentinel pattern for default values.  This
allows for more robust type checking, as the Sentinel type should not be
included as a return value.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:16:48 -04:00
Arksine 6c27885702 file_manager: send "root_update" notification for all registered directories
This includes non mutable directories such as "config_examples" and "docs".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 5a2e2b1f3f docs: update return value for "/server/files/list"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 316c6b5fa1 file_manager: rename "filename" field to "path" in "/server/files/list" request
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine b2f8413057 docs: update documentation for changes to file_manager
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 17a436bc27 file_manager: validate file extension before attempting to parse metadata
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 93a29e0e34 file_manager: return more descriptive responses for op requests
File manager operations now return values similar to that of file change notifications.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine d46f04de0b file_manager: delete file trees in another thread
On slower platforms it is possible for this to take time and block the event loop.   Run shutil.rmtree in another thread to prevent this from occuring.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 55941b106b file_manager: only run the operation check for files in the "gcodes" root
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine ebaf355878 file_manager: synchronize inotify events with api requests
If an inotify event is generated as the result of an API request, the notifications are synchronized so that they occur after the request returns.  Use a mutex to prevent multiple "write" requests processing concurrently.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 21d290beb7 file_manager: implement metadata "move" functionality
If a file is moved from one location to another in the "gcodes" root it isn't necessary to rescan the file metadata as the underlying file information does not change.   Add the ability to change the metadata's key and move associated thumbnails when a file is moved.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine a9f1a98fa2 file_manager: remove metadata_update notifications
Since filelist_changed notifications are now delayed until after metadata is processed there is no need to send an additional metadata notification.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 5fe9f1a217 file_manager: don't send filelist notifications until metadata is processed
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 9da74f7bc6 file_manager: implement inotify using a bidirectional tree
Rather than tracking watch paths directly, wrap each watch in a node.  This makes makes it a bit easier to handle move and delete changes, as we don't have to manage several different dicts to store the information we need.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine e4d61de406 file_manager: bundle directory creation events
When a directory is created, attempt to suppress notifications generated as its children are created.
Wait until all items are copied before notifying clients and scanning metadata.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 93fcd1ae86 file_manager: process copy requests in another thread
The copy methods are blocking and will block the asyncio event loop.  Run them in a  ThreadPoolExecutor to keep the event loop free.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 43fcca5ffa scripts: add inotify-simple dependency
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 9c31a360ee file_manager: remove child watches when a directory is stale
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine bb00825cd2 file_manager: bundle inotify delete events
When a directory is deleted this attempts to suppress delete events for all children.  Clients only need to be notified of the parent node, as its deletion implies all children have been deleted.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine db0eb8f22b extract_metadata: remove base64 data from metadata
The previously deprecated "data" field has now been removed. The "size" field now reports the size of the png.  Clients may use the "relative_path" field to retrieve thumbnail png files.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine c40c202220 file_manager: allow extract_metadata to unzip ufp files
This guarantees that .ufps will not be unzipped in parallel and offloads a potential blocking operation to another process.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine eaf35ded0c extract_metadata: add support for ufp file extraction
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine ecbf663b18 file_manager: make the thumbs directory hidden
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 23dd001a9b file_manager: don't add inotify watches for hidden directories
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 48607f8ab3 file_manager: allow inotify to exclusively handle gcode metadata and ufp files
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine c2871d94ed file_manager: remove gcode metadata prune callback
Inotify keeps metadata in sync with the file system.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 7744b1fd8a test_client: update file list changed notification
Handle the new action nomenclature correctly.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 5756e27711 file_manager: exclusively manage websocket notifications using inotify
This removes all calls to "notify_filelist_changed" in the FileManager class.  This also simplfies the previous `_convert_path()` method, as it is no longer necessary to return the path relative to the root.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine fbb1fcf500 file_manager: add support for inotify event based monitoring
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-18 19:12:54 -04:00
Arksine 5f9b0e9b86 app: don't require authorization to retreive static files
Generally speaking static files do not require authorization, so there should be little harm in bypassing auth checks.  This allows clients to retrieve assets without XHRs or requesting tokens.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-17 17:52:47 -04:00
Arksine 9fe6ef82a5 power: Don't query a gpio line in "refresh_status"
On some devices gpiod does not report the correct state.  Since Moonraker maintains exclusive control over GPIO lines, its unnecessary to query the line itself for state, as we can maintain it ourselves.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-17 16:53:28 -04:00
Arksine fd07b077b9 update_manager: increase fetch timeout to 5 minutes
This should allow git's internal timeout mechanisms to trigger at the expense of potentially delaying response time if a fetch or pull hangs.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-15 07:14:17 -04:00
Arksine 158f92f17f docs: Update the delete user documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-14 12:59:30 -04:00
Arksine e73f9b7bf5 test: add a delete user form to the test client
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-14 12:59:30 -04:00
Arksine 2ba85533c2 authorization: refactor user delete API
It is now possible for any authorized request to delete a user, however a logged in user cannot delete its own account.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-14 12:59:30 -04:00
Arksine 490e66fe07 authorization: bypass authorization check when the request method is OPTIONS
If CORS is enabled then then OPTIONS should always return 204.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-13 19:33:42 -04:00
Arksine 4a61bf21de docs: update "/access/users/list" documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-13 18:01:18 -04:00
Arksine b3187710d0 authorization: Return more detail in "/access/users/list"
Return a list of objects with username and creation date fields.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-13 17:58:07 -04:00
Arksine e472fb6c1e docs: update authorization documentation
Add documentation for the "/access/users/list" endpoint.  Document the "notify_user_created" and "notify_user_deleted" websocket notifications.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-13 15:38:41 -04:00
Arksine 1af7f7d550 authorization: send websocket notifications when a user is created or deleted
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-13 15:24:41 -04:00
Arksine 400cefebc8 authorization: add '/access/users/list' API request
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-13 14:58:22 -04:00
Arksine d3c251bc52 docs: update power module documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-10 08:42:08 -04:00
Arksine 0274a641b2 power: add LoxoneV1 support
This is a refactored version of loxone V1 support submitted by EraserFX.  Closes PR #94.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-10 07:50:23 -04:00
Arksine 0917536ccc power: use a mutex to prevent concurrent device requests
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-10 07:50:23 -04:00
Arksine 724c29c4a7 power: implement an HTTPDevice base class
This allows for some additional code reuse that is duplicated amongst several HTTP Device implementations.
2021-05-10 07:50:23 -04:00
Arksine 8e6bb34d1b power: remove unnecessary calls to get_server()
The server attribute for these classes is already assigned by their parent.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-10 07:50:23 -04:00
Arksine c02964e95c power: add endpoint for toggling a single device
A single endpoint that can be used to both toggle and retrieve device state is useful for interoperability with home automation software.  The previous endpoints will remain as they are still useful for batch operations.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-10 07:50:23 -04:00
Arksine cb8e5af8f7 power: always refresh status prior to processing a request
Make sure that the current device state is correct in the event that a device is toggled by an external source.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-09 19:36:58 -04:00
Arksine 06bea715a3 power: store device classes in a dict
This provides a cleaner way of adding new types.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-09 17:28:33 -04:00
Arksine 3d01b0b9da update_manager: attempt to handle empty git objects
Always run git fsck when initializing a repo.  If a loose object error is detected when running git pull or git fetch, attempt to remove  loose objects and retry.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-09 14:53:56 -04:00
Arksine f339aa7454 update_manager: don't allow repo init waiters to return success on a failure
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-09 12:47:33 -04:00
Arksine e69ac489c7 gh_actions: fix broken yaml
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-05-09 08:56:15 -04:00
Arksine 52f08eda08 extract_metdata: fix whitespace errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-09 08:17:24 -04:00
Arksine a746019790 power: fix whitespace errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-09 08:16:14 -04:00
Arksine efdcc263dd shell_command: fix typo
The trailing underscore in IDX_SIGKILL is not correct.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-09 08:15:20 -04:00
Arksine 4ee32ebaf3 history: minor codestyle change
Use the accepted "not in"  test for membership.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-09 08:13:18 -04:00
Arksine acd3b3c064 gh_actions: add initial test workflow
The intial test uses the python-lint action to validate code style
according to the preferences used for Python code in the Moonraker
repo.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-09 08:10:28 -04:00
Sébastien Jousse c53b95aa93 power: Add Home Assistant switch support
* power: Add Home Assistant switch support

Signed-off-by:  Sébastien Jousse <s.jousse@gmail.com>
2021-05-05 07:14:25 -04:00
Arksine 40d4daa96b docs: update proc_stats API documentation
Document the "cpu_temp" field in the "/machine/proc_stats" request along with the new "notify_proc_stat_update" websocket notification.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-03 08:59:19 -04:00
Arksine 68b793f059 test: register proc stat json-rpc notifications in client
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-02 20:48:29 -04:00
Arksine f705f1145a proc_stats: add notify_proc_stat_update websocket notifcation
Report CPU temp in addition to moonraker stats in this notification and the proc_stat request.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-05-02 20:42:19 -04:00
Arksine 5321a8a558 docs: update authorization documentation
The "trusted_clients" option now supports fqdns (full qualified domain names).

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-29 19:40:06 -04:00
Arksine 46e1d7b66b authorization: support fqdns as "trusted_clients"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-29 19:16:57 -04:00
Arksine 497423ddc2 confighelper: log detailed parsing errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-27 08:52:34 -04:00
Arksine 80707d1734 proc_stats: send cpu_throttled event when throttled state changes
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-04-26 12:35:40 -04:00
Arksine 275bcde081 docs: add documentation for /machine/system_info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-26 12:08:52 -04:00
Arksine 24eaff6951 machine: add distribution to system info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-26 12:08:52 -04:00
Arksine 5e87d8793d machine: add support for retrieving CPU and SDCard info
Add this info to the log rollover so it is always visible.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-26 12:08:52 -04:00
Stefan Dej 0791c658ad fix moonraker process stats link
Signed-off-by: Stefan Dej <meteyou@gmail.com>
2021-04-25 11:30:37 -04:00
Arksine 37615d4790 proc_stats: add CPU throttled flags to log rollover
Don't continuously log a change in throttled state, only log when a new throttled flag is detected.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-23 07:03:17 -04:00
Maciej Rutkowski b9487276e9 power: Fix Shelly behavior when a timer is configured (#149)
* power: Fix Shelly behavior when a timer is configured

Signed-off-by:  Maciej Rutkowski <dev@nomadic.works>
2021-04-22 08:47:40 -04:00
Arksine 46dea00b2f docs: Document "Kasa Power Strip" configuration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-20 19:59:59 -04:00
Arksine 85be5cbfc1 docs: add "checksum" option to file upload documentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-20 18:12:30 -04:00
Arksine 2b79a129aa app: fix unauthorized file upload access
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-20 18:12:30 -04:00
Arksine d42fd3b095 docs: fix accidental removal of trusted_clients option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-20 18:12:30 -04:00
Arksine 25b6f6fb34 test: add checksum calculation to client upload
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-20 18:12:30 -04:00
Arksine 9478678ea0 app: Add sha256 checksum validation to file uploads
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-20 18:12:30 -04:00
Arksine 2c078cbc7c database: don't return forbidden namespaces in the list request
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-20 06:34:46 -04:00
Arksine 3627331527 scripts: update to lmdb 1.2.1
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-20 06:03:42 -04:00
Arksine f4ebb93546 docs: update documentation for the Authorization component
USER_CHANGE:  The "enable" and "api_key_file" options in the [authorizaton] section are now deprecated.  A new API Key will be generated.  Use the "fetch-apikey.sh" script to retrieve the new key.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-19 20:46:17 -04:00
Arksine 64e794f1b5 scripts: add fetch-apikey helper script
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-19 20:46:17 -04:00
Arksine 5bba0fc2fa scripts: bump lmdb version to 1.2.0
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-19 20:46:17 -04:00
Arksine a4273d2d0a test: implement JWT Authorization for test client
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-19 20:46:17 -04:00
Arksine 0c765f7b71 app: improve http request logging
Log the current user for each request.   Dont' log requests that return with 200, 204, 206, or 304 in release mode.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-19 20:46:17 -04:00
Arksine 4e0e223599 authorization: allow auth related CORS Headers
Allow Authorization, X-Api-Key, and X-Access-Token headers when CORS is enabled.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-19 20:46:17 -04:00
Arksine 7eba8e58e3 authorization: add support for JWT User Authorizaton
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-19 20:46:17 -04:00
Arksine 43a8d25619 websockets: Store IP Address in WebRequest object
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-18 07:25:12 -04:00
Arksine 24e6fded91 authorization: use database to store API Key
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-18 07:25:12 -04:00
Arksine dee9055347 database: introduce forbidden namespaces
A Moonraker component may now register a namespace as "forbidden".   API requests have no read/write access to forbidden namespaces and this cannot be overridden by the database debug option.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-18 07:25:12 -04:00
Arksine 0ce53bd98f app: return HTTP errors in json format
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-18 07:25:12 -04:00
Arksine 14991ac3b9 authorization: convert module to component
CONFIG CHANGE:  This deprecates the "enabled" option in the [authorization] section.  Authorization will be enabled if the section is included in moonraker.conf,  otherwise it will be disabled.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-18 07:25:12 -04:00
Arksine 57836047f6 octoprint compat: use subscriptions to update printer data
This tends to be more efficient than polling, particularly on slower machines.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-18 07:12:26 -04:00
Arksine 9873084667 octoprint_compat: correctly report printer state
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-18 06:20:27 -04:00
Arksine e8f6862fd2 app: cache modified time in static file handler
Force an update to cached file hashes should the modified time change.  Re-enable the "should_return_304" check so clients can re-implement caching.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-17 07:05:31 -04:00
th33xitus 4d69a1f1c6 extract_metadata: parse filament_total and filament_total_weight for Slic3r
Signed-off-by:  Dominik Willner <th33xitus@gmail.com>
2021-04-17 06:06:53 -04:00
th33xitus f203567381 extract_metadata: add Cura filament weight parsing
Adds a simple implementation for parsing filament weight from Cura g-code with help of a custom start-g-code comment.

Signed-off-by:  Dominik Willner <th33xitus@gmail.com>
2021-04-17 06:06:53 -04:00
th33xitus 0d601073a6 extract_metadata: add parsing of filament weight
This will parse the total used filament weight of g-code files created by Simplify3D, PrusaSlicer, SuperSlicer and ideaMaker

Signed-off-by:  Dominik Willner <th33xitus@gmail.com>
2021-04-17 06:06:53 -04:00
Arksine daf3b202c3 app: restrict static file size to the detected content length
Some static files, such as logs, can change size during a request.  This results in a content length mismatch and error.   Cap the amount read based on the original content length.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-16 07:49:44 -04:00
Arksine 087240aa67 app: don't return 304 for static files
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-16 07:29:18 -04:00
Arksine 210cae2736 file_manager: check for broken symlinks in "get_file_list()"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-13 15:26:32 -04:00
th33xitus dae0f05378 extract_metadata: assign correct data parameter
This fix will now correctly parse the used filament from g-code generated by ideaMaker. The used filament is located in the footer of the g-code file.

Signed-off-by:  Dominik Willner <th33xitus@gmail.com>
2021-04-11 11:36:06 -04:00
Arksine 4d1a2668f5 docs: add notes about sending M112 gcodes
Also  document the new "full_version_string" field reported by the update_manager.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-09 14:59:39 -04:00
Arksine 7d3bba75e1 update_manager: report full version string for git repos
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-09 14:59:39 -04:00
fsironman b111e3d6c7 power.py add parameter timer
Add a timer parameter to shelly and tasmota integration.

Use case: 3D printer mains power is connected to one of these devices. Just turning off the smart switch will just kill power to the RaspberryPI. Adding a timer will allow the PI to shutdown cleanly before killing the power

Signed-off-by: Dominik Weis fsironman@gmail.com
2021-04-06 17:58:51 -04:00
Kamil Trzciński 6cc11276c8 Extend history API with reverse order
Signed-off-by: Kamil Trzciński <ayufan@ayufan.eu>
2021-04-05 11:41:14 -04:00
Arksine 5db596f0a5 docs: Add database debugging option to configuration.md
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-02 11:58:43 -04:00
Arksine aa3ffdbaaf power: fix whitespace issues
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-02 11:37:21 -04:00
Arksine 8724d5e9ed database: add "enable_database_debug" option
This allows protected namespaces to be modified externally.  This is for dev use only, modifying protected namespaces can potentially corrupt the database.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-02 11:37:21 -04:00
Arksine da9401dd1a database: make protected namespaces persistent
This fixes a bug where it is protected namespace can be modified in an optional component if that component is disabled.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-04-02 08:25:40 -04:00
Arnaud Schaer 85b1b44e20 power.py: fix issue with single relay tasmota
add a check and handle consequently in case tasmota device is only one relay and would return a power value when asked a power1 value

Signed-off-by:  Arnaud Schaer <arnaud.schaer@wanadoo.fr>
2021-04-02 08:24:32 -04:00
Michael Kreitzer c36f989c52 power: Adding TPLinkSmartPlug multi plug support (clean-up and sign off)
Signed-off-by:  Michael Kreitzer <reztierk@gmail.com>
2021-03-31 06:55:32 -04:00
147 changed files with 41236 additions and 19333 deletions

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
# These are supported funding model platforms
ko_fi: arksine
+10
View File
@@ -0,0 +1,10 @@
---
name: Announcement
about: Create a Moonraker Announcement. For dev use only.
title: ''
labels: announcement
assignees: ''
---
+66
View File
@@ -0,0 +1,66 @@
name: Bug report
description: Create a report to help us improve
labels: ["bug", "triage"]
body:
- type: markdown
attributes:
value: |
This issue form is for reporting bugs only!
If you have a feature request, please use [Feature Request](/new?template=feature_request.yml)
- type: textarea
id: what-happened
attributes:
label: What happened
description: >-
A clear and concise description of what the bug is.
validations:
required: true
- type: dropdown
id: client
attributes:
label: Client
multiple: true
description: On what clients are you seeing the problem?
options:
- Mainsail
- Fluidd
- MoonCord
- KlipperScreen
- MobileRaker
- Other
validations:
required: true
- type: dropdown
id: browser
attributes:
label: Browser
multiple: true
description: On what browsers are you seeing the problem?
options:
- Chrome
- Firefox
- Safari
- Microsoft Edge
- Brave
- Other or N/A
validations:
required: true
- type: textarea
id: repro-steps
attributes:
label: How to reproduce
description: >-
Minimal and precise steps to reproduce this bug.
validations:
required: true
- type: textarea
id: additional-info
attributes:
label: Additional information
description: |
Please attach moonraker.log using the field below. If you are using
a Browser or Client not provided in the options above please specify
them here.
You may also include any additional information, screenshots, or files
that helpful in describing the issue.
+5
View File
@@ -0,0 +1,5 @@
blank_issues_enabled: false
contact_links:
- name: Klipper Discord
url: https://discord.klipper3d.org/
about: Quickest way to get in contact
@@ -0,0 +1,40 @@
name: Feature request
description: Suggest an idea for this project
labels: ["enhancement"]
body:
- type: markdown
attributes:
value: |
This issue form is for feature requests only!
If you've found a bug, please use [bug_report](/new?template=bug_report.yml)
- type: textarea
id: problem-description
attributes:
label: Is your feature request related to a problem? Please describe
description: >-
A clear and concise description of what the problem is.
validations:
required: true
- type: textarea
id: solution-description
attributes:
label: Describe the solution you'd like
description: >-
A clear and concise description of what you want to happen.
validations:
required: true
- type: textarea
id: possible-alternatives
attributes:
label: Describe alternatives you've considered
description: >-
A clear and concise description of any alternative solutions or features you've considered.
- type: textarea
id: additional-info
attributes:
label: Additional information
description: |
If you have any additional information for us, use the field below.
Please note, you can attach screenshots or screen recordings here, by
dragging and dropping files in the field below.
@@ -0,0 +1,7 @@
<!---
Thank you for contributing to Moonraker. Before creating your pull request please
review the [contributing documentation](https://moonraker.readthedocs.io/en/latest/contributing/).
Be sure that each commit message is formatted as described, with a signature containing
your real name and a reachable email address. Your signature acknowledges that you accept the
[developer certificate of origin](https://github.com/Arksine/moonraker/blob/master/docs/developer-certificate-of-origin).
--->
+51
View File
@@ -0,0 +1,51 @@
# CI Code for generating and publishing beta assets
name: publish_assets
on:
release:
types: [published]
jobs:
generate_assets:
runs-on: ubuntu-latest
steps:
- name: Checkout Moonraker
uses: actions/checkout@v2
with:
fetch-depth: 0
ref: ${{ github.ref }}
path: moonraker
- name: Checkout Klipper
uses: actions/checkout@v2
with:
fetch-depth: 0
repository: Klipper3d/klipper
path: klipper
- name: Build Beta Assets
if: ${{ github.event.release.prerelease }}
run: >
./moonraker/scripts/build-zip-release.sh -b
-o ${{ github.workspace }}
-k ${{ github.workspace }}/klipper
- name: Build Stable Assets
if: ${{ !github.event.release.prerelease }}
run: >
./moonraker/scripts/build-zip-release.sh
-o ${{ github.workspace }}
-k ${{ github.workspace }}/klipper
- name: Upload assets
run: |
cd moonraker
gh release upload ${{ env.TAG }} ${{ env.FILES }}
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
FILES: >
${{ github.workspace }}/moonraker.zip
${{ github.workspace }}/klipper.zip
${{ github.workspace }}/RELEASE_INFO
${{ github.workspace }}/COMMIT_LOG
TAG: ${{ github.event.release.tag_name }}
+20
View File
@@ -0,0 +1,20 @@
# CI for code style and application tests
name: test-code
on: [push, pull_request]
jobs:
lint-python-code:
runs-on: ubuntu-22.04
steps:
- uses: actions/checkout@v3
- uses: ricardochaves/python-lint@v1.4.0
with:
python-root-list: "moonraker scripts"
use-pylint: false
use-pycodestyle: true
use-flake8: false
use-black: false
use-mypy: true
use-isort: false
extra-pycodestyle-options: "--ignore=E226,E301,E302,E303,W503,W504 --max-line-length=88 --max-doc-length=88"
extra-mypy-options: "--ignore-missing-imports --follow-imports=silent"
+9
View File
@@ -2,3 +2,12 @@
__pycache__/
*.py[cod]
*$py.class
.devel
.venv
venv
start_moonraker
*.env
.pdm.toml
build
dist
+26 -12
View File
@@ -1,7 +1,9 @@
[![pdm-managed](https://img.shields.io/badge/pdm-managed-blueviolet)](https://pdm.fming.dev)
# Moonraker - API Web Server for Klipper
Moonraker is a Python 3 based web server that exposes APIs with which
client applications may use to interact with
client applications may use to interact with the 3D printing firmware
[Klipper](https://github.com/KevinOConnor/klipper). Communcation between
the Klippy host and Moonraker is done over a Unix Domain Socket. Tornado
is used to provide Moonraker's server functionality.
@@ -9,22 +11,34 @@ is used to provide Moonraker's server functionality.
Documentation for users and developers can be found on
[Read the Docs](https://moonraker.readthedocs.io/en/latest/).
### Clients
Note that Moonraker does not come bundled with a client, you will need to
install one. The following clients are currently available:
- [Mainsail](https://github.com/meteyou/mainsail) by Meteyou
- [Fluidd](https://github.com/cadriel/fluidd) by Cadriel
- [Mainsail](https://github.com/mainsail-crew/mainsail) by [Mainsail-Crew](https://github.com/mainsail-crew)
- [Fluidd](https://github.com/fluidd-core/fluidd) by Cadriel
- [KlipperScreen](https://github.com/jordanruthe/KlipperScreen) by jordanruthe
- [mooncord](https://github.com/eliteSchwein/mooncord) by eliteSchwein
### Raspberry Pi Images
Moonraker is available pre-installed with the following Raspberry Pi images:
- [MainsailOS](https://github.com/mainsail-crew/MainsailOS) by [Mainsail-Crew](https://github.com/mainsail-crew)
- Includes Klipper, Moonraker, and Mainsail
- [FluiddPi](https://github.com/fluidd-core/FluiddPi) by Cadriel
- Includes Klipper, Moonraker, and Fluidd
### Docker Containers
The following projects deploy Moonraker via Docker:
- [prind](https://github.com/mkuf/prind) by mkuf
- A suite of containers which allow you to run Klipper in
Docker. Includes support for OctoPrint and Moonraker.
### Changes
This section contains changelogs that users and developers may reference
to see if any action is necessary on their part. The date of the most
recent change is included.
Users:\
[user_changes.md](https://moonraker.readthedocs.io/en/latest/user_changes/) - March 10th 2021
Developers:\
[api_changes.md](https://moonraker.readthedocs.io/en/latest/api_changes/) - March 15th 2021
Please refer to the [changelog](https://moonraker.readthedocs.io/en/latest/changelog)
for a list of notable changes to Moonraker.
+76
View File
@@ -1,6 +1,82 @@
##
This document keeps a record of all changes to Moonraker's web APIs.
### February 20th 2023
- The following new endpoints are available when at least one `[sensor]`
section has been configured:
- `GET /server/sensors/list`
- `GET /server/sensors/sensor`
- `GET /server/sensors/measurements`
See [web_api.md](web_api.md) for details on these new endpoints.
- A `sensors:sensor_update` notification has been added. When at least one
monitored sensor is reporting a changed value Moonraker will broadcast this
notification.
See [web_api.md](web_api.md) for details on this new notification.
### February 17 2023
- Moonraker API Version 1.2.1
- An error in the return value for some file manager endpoints has
been corrected. Specifically, the returned result contains an `item` object
with a `path` field that was prefixed with the root (ie: "gcodes").
This is inconsistent with the websocket notification and has been corrected
to remove the prefix. This affects the following endpoints:
- `POST /server/files/directory` | `server.files.post_directory`
- `DELETE /server/files/directory` | `server.files.delete_directory`
- `POST /server/files/move` | `server.files.move`
- `POST /server/files/copy` | `server.files.copy`
### March 4th 2022
- Moonraker API Version 1.0.1
- The `server.websocket.id` endpoint has been deprecated. It is
recommended to use `server.connection.identify` method to identify
your client. This method returns a `connection_id` which is
the websocket's unique id. See
[the documentation](web_api.md#identify-connection) for details.
### May 8th 2021
- The `file_manager` has been refactored to support system file
file events through `inotify`. Only mutable `roots` are monitored,
(currently `gcodes` and `config`). Subfolders within these
these roots are also monitored, however hidden folders are not.
The following changes API changes have been made to acccommodate
this functionality:
- The `notify_filelist_changed` actions have changed. The new
actions are as follows:
- `create_file`: sent when a new file has been created. This
includes file uploads and copied files.
- `create_dir`: sent when a new directory has been created.
- `delete_file`: sent when a file has been deleted.
- `delete_dir`: sent when a directory has been deleted.
- `move_file`: sent when a file has moved.
- `move_dir`: sent when a directory has moved.
- `modify_file`: sent when an existing file has been modified
- `root_update`: sent when a root directory location has been set.
For example, if a user changes the gcode path in Klipper, this
action is sent with a `notify_filelist_changed` notification.
- File list notifications for gcode files are now only sent after
all metadata has been processed. Likewise, requests to copy,
move, or upload a file will only return after metadata has been
processed. Notifications are synced with requests so that the
request should always return before the notification is sent.
- Thumbnails are now stored in the `.thumbs` directory to prevent
changes to thumbnails from emitting filelist notications. This
change will be reflected in the metadata's `relative_path` field,
so clients that use this field should not need to take additional
action. Note that existing thumbnails will remain in the `thumbs`
directory and filelist notifications will be sent for changes to
these thumbnails.
- The `notify_metadata_update` notification has been removed Clients
- can reliably expect metadata to be available for new or moved gcode
files when a request returns.
- The return values for several endpoints have been updated. They
now contain information similar to that which is pushed by the
`notify_filelist_changed` notification.
- The deprecated `data` field in gcode metadata has been removed.
The `size` field now returns the size of the `.png` file.
### March 15th 2021
- The `data` field for gcode thumbnails is now deprecated and will
be removed in the near future. Thumbnails are now saved to png
+85
View File
@@ -0,0 +1,85 @@
# Changelog
All notable changes to this project will be documented in this file.
Notable changes prior to 2023-02-01 may be found in [user_changes.md] and
[api_changes.md].
The format is based on [Keep a Changelog].
## [Unreleased]
### Added
- Added this changelog!
- Added pyproject.toml with support for builds through [pdm](https://pdm.fming.dev/latest/).
- **sensor**: New component for generic sensor configuration.
- [Configuration Docs](configuration.md#sensor)
- [API Docs](web_api.md#sensor-apis)
- [Websocket Notification Docs](web_api.md#sensor-events)
- **file_manager**: Added new [scan metadata](web_api.md#scan-gcode-metadata) endpoint.
- **file_manager**: Added new [thumbnails](web_api.md#get-gcode-thumbnails) endpoint.
- **file_manager**: Added [file_system_observer](configuration.md#file_manager)
configuration option.
- **file_manager**: Added [enable_observer_warnings](configuration.md#file_manager)
configuration option.
- **file_manager**: Added ability to upload to symbolic links.
- **metadata**: Added support for Simplify3D V5 metadata parsing
- **machine**: Added [shutdown_action](configuration.md#machine) configuration
option.
- **machine**: Added service detection to the `supervisord_cli` provider.
- **machine**: Added `octoeverywhere` to the list of default allowed service.
- **power**: Added support for "Hue" device groups.
- **websockets**: Added support for [direct bridge](web_api.md#bridge-websocket)
connections.
- **update_manager**: Added new [refresh](web_api.md#refresh-update-status) endpoint.
- **update_manager**: Added support for pinned pip upgrades.
- **websockets**: Added support for post connection authentication over the websocket.
- **scripts**: Added database backup and restore scripts.
### Changed
- Converted Moonraker source into a Python package.
- The source from `moonraker.py` has been moved to `server.py`. The remaining code in
`moonraker.py` serves as a legacy entry point for launching Moonraker.
- **file_manager**: Improved inotify synchronization with API requests.
- **file_manager**: Endpoint return values are now consistent with their
respective websocket notifications.
- **machine**: The [provider](configuration.md#machine) configuration option
now expects `supervisord_cli` instead of `supervisord`.
- **update_manager**: Relaxed requirement for git repo tag detection. Now only two
parts are required (ie: v1.5 and v1.5.0 are acceptable).
### Deprecated
- **file_manager**: The `enable_inotify_warnings` configuration option has been
deprecated in favor of `enable_observer_warnings`.
### Fixed
- **file_manager**: Fix edge condition where `create_file` notifications
may be sent before a `create_dir` notification.
- **power** - Fixed URL encoding issues for http devices.
- **template**: A ConfigError is now raised when a template fails to
render during configuration.
- **machine**: Fixed support for Supervisord Version 4 and above.
- **update_manager**: Added package resolution step to the APT backend.
- **update_manger**: Fixed PackageKit resolution step for 64-bit systems.
- **update_manager**: Fixed Python requirements file parsing. Comments are now ignored.
### Removed
- Pycurl dependency. Moonraker no longer uses Tornado's curl based http client.
## [0.7.1] - 2021-07-08
- Experimental pre-release
<!-- Links -->
[keep a changelog]: https://keepachangelog.com/en/1.0.0/
[semantic versioning]: https://semver.org/spec/v2.0.0.html
[user_changes.md]: user_changes.md
[api_changes.md]: api_changes.md
<!-- Versions -->
[unreleased]: https://github.com/Arksine/moonraker/compare/v0.7.1...HEAD
[0.7.1]: https://github.com/Arksine/moonraker/releases/tag/v0.7.1
+73 -12
View File
@@ -40,7 +40,7 @@ class Example:
self.example_float_opt = config.getfloat("example_float_option", None)
self.server.register_endpoint("/server/example", ['GET'],
self._handle_example request)
self._handle_example_request)
async def request_some_klippy_state(self):
klippy_apis = self.server.lookup_component('klippy_apis')
@@ -153,7 +153,7 @@ when it needs a reference to core component.
If the component fails to load `default` will be returned. If `default`
is not provided a `ServerError` will be raised.
#### *Server.register_endpoint(uri, request_methods, callback, protocol=["http", "websocket"], wrap_result=True)*
#### *Server.register_endpoint(uri, request_methods, callback, transports=["http", "websocket", "mqtt"], wrap_result=True)*
Registers the supplied `uri` with the server.
@@ -166,10 +166,11 @@ The `callback` is executed when a request matching the `uri` and a
should be able of handling each registered `request_method`. The
provided callback must be a coroutine.
The `protocol` is a list containing any combination of `http` and `websocket`.
If `websocket` is selected associated JSON-RPC methods will be generated based
on what is supplied by the `uri` and `request_methods` argument. A unique
JSON_RPC method is generated for each request method. For example:
The `transports` argument is a list containing any combination of
`http`, `websocket` and `mqtt`. JSON-RPC methods for `websocket` and `mqtt`
will be generated based on what is supplied by the `uri` and
request_methods` argument. A unique JSON_RPC method is generated for each
request method. For example:
```python
self.server.register_endpoint("/server/example", ["POST"], self._handle_request)
```
@@ -200,7 +201,7 @@ by a `callback` is wrapped in a dict:
It is only necessary to set this to false if you need to return a body that
does not match this result. For example, the `[octoprint_compat]` component
uses this functionality to return results in a format that match what
Octoprint itself would return.
OctoPrint itself would return.
#### *Server.register_event_handler(event, callback)*
@@ -273,32 +274,92 @@ passing the WebRequest on to another request handler.
Returns the request argument at the provided `key`. If the key is not
present `default` will be returned. If `default` is not provided a
`SeverError` will be raised.
`ServerError` will be raised.
#### *WebRequest.get_str(key, default=Sentinel)*
Retrieves the request argument at the provided `key` and converts it
to a string, returning the result. If the key is not present the `default`
value will be returned. If `default` is not provided or if the attempt at
type conversion fails a `SeverError` will be raised.
type conversion fails a `ServerError` will be raised.
#### *WebRequest.get_int(key, default=Sentinel)*
Retrieves the request argument at the provided `key` and converts it
to an integer, returning the result. If the key is not present the `default`
value will be returned. If `default` is not provided or if the attempt at
type conversion fails a `SeverError` will be raised.
type conversion fails a `ServerError` will be raised.
#### *WebRequest.get_float(key, default=Sentinel)*
Retrieves the request argument at the provided `key` and converts it
to a float, returning the result. If the key is not present the `default`
value will be returned. If `default` is not provided or if the attempt at
type conversion fails a `SeverError` will be raised.
type conversion fails a `ServerError` will be raised.
#### *WebRequest.get_boolean(key, default=Sentinel)*
Retrieves the request argument at the provided `key` and converts it
to a boolean, returning the result. If the key is not present the `default`
value will be returned. If `default` is not provided or if the attempt at
type conversion fails a `SeverError` will be raised.
type conversion fails a `ServerError` will be raised.
### MQTT
If configured by the user the MQTT component is available for lookup.
Developers may use this to subscribe and publish topics.
#### *MQTTClient.is_connected()*
Returns true if Moonraker is currently connected to the Broker, false
otherwise.
#### *MQTTClient.wait_connection(timeout=None)*
Blocks until a connection with the broker has been successfully established
or until the specified timeout has exceeded. Returns true if the connection
was successful established, or False on timeout. If no timeout is specified
then this method will block indefinitely until a connection has been
established.
#### *MQTTClient.publish_topic(topic, payload=None, qos=None, retain=False)*
Attempts to publish a topic to the Broker. The `payload` may be a bool, int,
float, string, or json encodable (Dict or List). If omitted then an empty
payload is sent. The `qos` may be an integer from 0 to 2. If not specifed
then the QOS level will use the configured default. If `retain` is set to
`True` then the retain flag for the payload will be set.
Returns a Future that will block until topic is confirmed as published.
For QOS level 0 an exception will be raised if the broker is not connected.
#### *MQTTClient.publish_topic_with_response(topic, response_topic, payload=None, qos=None, retain=False, timeout=None)*
Publishes the supplied `topic` with the arguments specified by `payload`,
`qos`, and `retain`, then subscribes to the `response_topic`. The payload
delivered by the response topic is returned. Note that this method is
a coroutine, it must always be awaited. The call will block until the
entire process has completed unless a `timeout` (in seconds) is specifed.
The `timeout` is applied to both the attempt to publish and the pending
response, so the maximum waiting time would be approximately 2*timeout.
!!! warning
This should only be used when it is guaranteed that the `response_topic`
does not have a retained value. Otherwise the returned response will
be the retained value.
#### *MQTTClient.subscribe_topic(topic, callback, qos=None)*
Subscibes to the supplied `topic` with the specified `qos`. If `qos` is not
supplied the configured default will be used. The `callback` should be a
callable that accepts a `payload` argument of a `bytes` type. The callable
may be a coroutine. The callback will be run each time the subscribed topic
is published by another client.
Returns a `SubscriptionHandle` that may be used to unsubscribe the topic.
#### *MQTTClinet.unsubscribe(hdl)*
Unsubscribes the callback associated with `hdl`. If no outstanding callbacks
exist for the topic then the topic is unsubscribed from the broker.
+2131 -137
View File
File diff suppressed because it is too large. Load diff
+74 -17
View File
@@ -6,29 +6,63 @@ the Moonraker application into the Klipper repo after Moonraker matures,
at which point this repo will be archived. As such, contibuting guidelines
are near those of Klipper:
- All source files should begin with a copyright notice in the following
format:
#### New Module Contributions
# Module name and brief description of module
#
# Copyright (C) 2021 YOUR NAME <YOUR EMAIL ADDRESS>
#
# This file may be distributed under the terms of the GNU GPLv3 license
All source files should begin with a copyright notice in the following format:
- No line in the source code or documentation should exceed 80 characters.
Be sure there is no trailing whitespace.
- Each Commit message should be in the following format:
```python
# Module name and brief description of module
#
# Copyright (C) 2021 YOUR NAME <YOUR EMAIL ADDRESS>
#
# This file may be distributed under the terms of the GNU GPLv3 license
```
module name: brief description of commit
#### Git Commit Format
More detailed explanation if necessary.
Commits should be contain one functional change. Changes that are unrelated
or independent should be broken up into multiple commits. It is acceptable
for a commit to contain multiple files if a change to one module depends on a
change to another (ie: changing the name of a method).
Signed-off-by: Your Name <your email address>
Avoid merge commits. If it is necessary to update a Pull Request from the
master branch use git's interactive rebase and force push.
- By signing off on commits, you acknowledge that you agree to the
[developer certificate of origin](../developer-certificate-of-origin)
shown below. Your signature must contain your real name and a current
email address.
Each Commit message should be in the following format:
```text
module: brief description of commit
More detailed explanation of the change if required
Signed-off-by: Your Name <your email address>
```
Where:
- `module`: is the name of the Python module you are changing or parent
folder if not applicable
- `Your Name`: Your real first and last name
- `<your email address>`: A real, reachable email address
For example, the git log of a new `power.py` device implementation might look
like the following:
```git
power: add support for mqtt devices
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
```
```git
docs: add mqtt power device documentation
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
```
By signing off on commits, you acknowledge that you agree to the
[developer certificate of origin](../developer-certificate-of-origin)
shown below. As mentioned above, your signature must contain your
real name and a current email address.
```text
Developer Certificate of Origin
@@ -69,3 +103,26 @@ By making a contribution to this project, I certify that:
maintained indefinitely and may be redistributed consistent with
this project or the open source license(s) involved.
```
#### Code Style
Python methods should be fully annotated. Variables should be annotated where
the type cannot be inferred. Moonraker uses the `mypy` static type checker for
code validation with the following options:
- `--ignore-missing-imports`
- `--follow-imports=silent`
No line in the source code should exceed 80 characters. Be sure there is no
trailing whitespace. To validate code before submission one may use
`pycodestyle` with the following options:
- `--ignore=E226,E301,E302,E303,W503,W504`
- `--max-line-length=80`
- `--max-doc-length=80`
Generally speaking, each line in submitted documentation should also be no
longer than 80 characters, however there are situations where this isn't
possible, such as long hyperlinks or example return values. Documentation
isn't linted, so it
Don't peek into the member variables of another class. Use getters or
properties to access object state.
+2 -2
View File
@@ -181,7 +181,7 @@
metadata from gcode files.
- Clean up API registration. All endpoints are now registered by Klippy
host modules outside of static files and `/api/version`, which is used for
compatibility with Octoprint's legacy file upload API.
compatibility with OctoPrint's file upload API.
- The server now runs in its own process. Communication between the Host and
the server is done over a duplex pipe. Currently this results in a second
log file being generated specifically for the server at
@@ -277,7 +277,7 @@
/printer/extras/endstops` to `GET /printer/endstops`
- Serveral API changes have been made to accomodate the addition of webhooks:
- `GET /printer/klippy_info` is now `GET /printer/info`. This endpoint no
longer returns host information, as that can be retreived direct via the
longer returns host information, as that can be retrieved direct via the
`location` object in javascript. Instead it returns CPU information.
- `GET /printer/objects` is no longer used to accomodate multiple request
types by modifying the "Accept" headers. Each request has been broken
+2 -1
View File
@@ -1 +1,2 @@
mkdocs==1.1.2
mkdocs==1.3.0
pymdown-extensions==9.1
+106
View File
@@ -0,0 +1,106 @@
# Example Home Assistant configuration file for a Artillery Sidewinder X1
# Credit to GitHub users @Kruppes and @pedrolamas
# extended by @tispokes
camera:
- platform: generic
still_image_url: http://192.168.178.66/webcam/?action=snapshot
stream_source: http://192.168.178.66/webcam/?action=stream
framerate: 10
sensor:
- platform: rest
name: SWX1_sensor
resource: "http://192.168.178.66:7125/printer/objects/query?heater_bed&extruder&print_stats&toolhead&display_status&virtual_sdcard"
json_attributes_path: "$.result.status"
json_attributes:
- heater_bed
- extruder
- print_stats
- toolhead
- display_status
- virtual_sdcard
value_template: >-
{{ "OK" if ("result" in value_json) else "offline" }}
# Adding an API key is only necessary while using the [authorization] component
# and if Home Assistant is not a trusted client
headers:
x-api-key: 123456789abcdefghijklmno
- platform: template
sensors:
swx1_state:
unique_id: sensor.swx1_state
friendly_name: "Status"
icon_template: mdi:printer-3d
value_template: >-
{{ states.sensor.swx1_sensor.attributes['print_stats']['state'] if is_state('sensor.swx1_sensor', 'OK') else None }}
swx1_current_print:
unique_id: sensor.swx1_current_print
friendly_name: >-
{{ "Printed" if states.sensor.swx1_sensor.attributes['display_status']['progress'] == 1 else "Printing..." }}
icon_template: mdi:video-3d
value_template: >-
{{ states.sensor.swx1_sensor.attributes['print_stats']['filename'].split(".")[0] if is_state('sensor.swx1_sensor', 'OK') else None }}
swx1_current_progress:
unique_id: sensor.swx1_current_progress
friendly_name: "Progress"
unit_of_measurement: '%'
icon_template: mdi:file-percent
value_template: >-
{{ (states.sensor.swx1_sensor.attributes['display_status']['progress'] * 100) | round(1) if is_state('sensor.swx1_sensor', 'OK') else None }}
swx1_print_time:
unique_id: sensor.swx1_print_time
friendly_name: "T-elapsed"
icon_template: mdi:clock-start
value_template: >-
{{ states.sensor.swx1_sensor.attributes['print_stats']['print_duration'] | timestamp_custom("%H:%M:%S", 0) if is_state('sensor.swx1_sensor', 'OK') else None }}
swx1_time_remaining:
unique_id: sensor.swx1_time_remaining
friendly_name: "T-remaining"
icon_template: mdi:clock-end
value_template: >-
{{ (((states.sensor.swx1_sensor.attributes['print_stats']['print_duration'] / states.sensor.swx1_sensor.attributes['display_status']['progress'] - states.sensor.swx1_sensor.attributes['print_stats']['print_duration']) if states.sensor.swx1_sensor.attributes['display_status']['progress'] > 0 else 0) | timestamp_custom('%H:%M:%S', 0)) if is_state('sensor.swx1_sensor', 'OK') else None }}
swx1_eta:
unique_id: sensor.swx1_eta
friendly_name: "T-ETA"
icon_template: mdi:clock-outline
value_template: >-
{{ (as_timestamp(now()) + 2 * 60 * 60 + ((states.sensor.swx1_sensor.attributes['print_stats']['print_duration'] / states.sensor.swx1_sensor.attributes['display_status']['progress'] - states.sensor.swx1_sensor.attributes['print_stats']['print_duration']) if states.sensor.swx1_sensor.attributes['display_status']['progress'] > 0 else 0)) | timestamp_custom("%H:%M:%S", 0) if is_state('sensor.swx1_sensor', 'OK') else None }}
swx1_nozzletemp:
unique_id: sensor.swx1_nozzletemp
friendly_name: >-
Nozzle
{{ ["(shall ", (states.sensor.swx1_sensor.attributes['extruder']['target'] | float | round(1)), "°C)"] | join if states.sensor.swx1_sensor.attributes['display_status']['progress'] < 1 }}
icon_template: >-
{{ "mdi:printer-3d-nozzle-heat" if states.sensor.swx1_sensor.attributes['extruder']['target'] > 0 else "mdi:printer-3d-nozzle-heat-outline" }}
value_template: >-
{{ states.sensor.swx1_sensor.attributes['extruder']['temperature'] | float | round(1) if is_state('sensor.swx1_sensor', 'OK') else None }}
swx1_bedtemp:
unique_id: sensor.swx1_bedtemp
friendly_name: >-
Bed
{{ ["(shall ", (states.sensor.swx1_sensor.attributes['heater_bed']['target'] | float | round(1)), "°C)"] | join if states.sensor.swx1_sensor.attributes['display_status']['progress'] < 1 }}
icon_template: >-
{{ "mdi:radiator" if states.sensor.swx1_sensor.attributes['extruder']['target'] > 0 else "mdi:radiator-off" }}
value_template: >-
{{ states.sensor.swx1_sensor.attributes['heater_bed']['temperature'] | float | round(1) if is_state('sensor.swx1_sensor', 'OK') else None }}
# The following will allow you to control the power of devices configured in the "[power]" sections of moonraker
# Make sure to change the `Printer` name below to the device name on your configuration
#
switch:
- platform: rest
name: SWX1_power
resource: "http://192.168.178.66:7125/machine/device_power/device?device=SWX1"
body_on: '{"action": "on"}'
body_off: '{"action": "off"}'
headers:
Content-Type: 'application/json'
is_on_template: >-
{{ 'result' in value_json and (value_json.result.values() | list | first == "on") }}
+73 -14
View File
@@ -1,5 +1,5 @@
# Example Home Assistant configuration file for a Voron V0.
# Credit to GitHub user @Kruppes
# Credit to GitHub users @Kruppes and @pedrolamas
#
sensor:
- platform: rest
@@ -13,40 +13,99 @@ sensor:
- toolhead
- display_status
- virtual_sdcard
value_template: 'OK'
value_template: >-
{{ 'OK' if ('result' in value_json) else None }}
# Adding an API key is only necessary while using the [authorization] component
# and if Home Assistant is not a trusted client
headers:
x-api-key: 123456789abcdefghijklmno
- platform: template
sensors:
vzero_hotend_target:
friendly_name: 'V0.126 Hotend Target'
value_template: '{{ states.sensor.voron_v0_sensor.attributes["extruder"]["target"] | float | round(1) }}'
device_class: temperature
unit_of_measurement: '°C'
value_template: >-
{{ states.sensor.voron_v0_sensor.attributes['extruder']['target'] | float | round(1) if is_state('sensor.voron_v0_sensor', 'OK') else None }}
vzero_hotend_actual:
value_template: '{{ states.sensor.voron_v0_sensor.attributes["extruder"]["temperature"] | float | round(1) }}'
device_class: temperature
unit_of_measurement: '°C'
value_template: >-
{{ states.sensor.voron_v0_sensor.attributes['extruder']['temperature'] | float | round(1) if is_state('sensor.voron_v0_sensor', 'OK') else None }}
vzero_bed_target:
value_template: '{{ states.sensor.voron_v0_sensor.attributes["heater_bed"]["target"] | float | round(1) }}'
device_class: temperature
unit_of_measurement: '°C'
value_template: >-
{{ states.sensor.voron_v0_sensor.attributes['heater_bed']['target'] | float | round(1) if is_state('sensor.voron_v0_sensor', 'OK') else None }}
vzero_bed_actual:
value_template: '{{ states.sensor.voron_v0_sensor.attributes["heater_bed"]["temperature"] | float | round(1) }}'
device_class: temperature
unit_of_measurement: '°C'
value_template: >-
{{ states.sensor.voron_v0_sensor.attributes['heater_bed']['temperature'] | float | round(1) if is_state('sensor.voron_v0_sensor', 'OK') else None }}
vzero_state:
value_template: '{{ states.sensor.voron_v0_sensor.attributes["print_stats"]["state"]}}'
icon_template: mdi:printer-3d
value_template: >-
{{ states.sensor.voron_v0_sensor.attributes['print_stats']['state'] if is_state('sensor.voron_v0_sensor', 'OK') else None }}
vzero_current_print:
value_template: '{{ states.sensor.voron_v0_sensor.attributes["print_stats"]["filename"]}}'
value_template: >-
{{ states.sensor.voron_v0_sensor.attributes['print_stats']['filename'] if is_state('sensor.voron_v0_sensor', 'OK') else None }}
vzero_current_progress:
value_template: '{{ (states.sensor.voron_v0_sensor.attributes["display_status"]["progress"])*100 | round(1) }}'
unit_of_measurement: '%'
icon_template: mdi:file-percent
value_template: >-
{{ (states.sensor.voron_v0_sensor.attributes['display_status']['progress'] * 100) | round(1) if is_state('sensor.voron_v0_sensor', 'OK') else None }}
vzero_print_time:
value_template: '{{ states.sensor.voron_v0_sensor.attributes["print_stats"]["print_duration"] |timestamp_custom("%H:%M:%S", 0)}}'
icon_template: mdi:clock-start
value_template: >-
{{ states.sensor.voron_v0_sensor.attributes['print_stats']['print_duration'] | timestamp_custom("%H:%M:%S", 0) if is_state('sensor.voron_v0_sensor', 'OK') else None }}
vzero_time_remaining:
value_template: '{{ (((states.sensor.voron_v0_sensor.attributes["print_stats"]["print_duration"]/states.sensor.voron_v0_sensor.attributes["display_status"]["progress"]- states.sensor.voron_v0_sensor.attributes["print_stats"]["print_duration"]) if states.sensor.voron_v0_sensor.attributes["display_status"]["progress"]>0 else 0)) | timestamp_custom("%H:%M:%S", 0)}}'
icon_template: mdi:clock-end
value_template: >-
{{ (((states.sensor.voron_v0_sensor.attributes['print_stats']['print_duration'] / states.sensor.voron_v0_sensor.attributes['display_status']['progress'] - states.sensor.voron_v0_sensor.attributes['print_stats']['print_duration']) if states.sensor.voron_v0_sensor.attributes['display_status']['progress'] > 0 else 0) | timestamp_custom('%H:%M:%S', 0)) if is_state('sensor.voron_v0_sensor', 'OK') else None }}
vzero_eta:
value_template: '{{ (as_timestamp(now())+2*60*60+((states.sensor.voron_v0_sensor.attributes["print_stats"]["print_duration"]/states.sensor.voron_v0_sensor.attributes["display_status"]["progress"]- states.sensor.voron_v0_sensor.attributes["print_stats"]["print_duration"]) if states.sensor.voron_v0_sensor.attributes["display_status"]["progress"]>0 else 0)) | timestamp_custom("%H:%M:%S", 0)}}'
icon_template: mdi:clock-outline
value_template: >-
{{ (as_timestamp(now()) + 2 * 60 * 60 + ((states.sensor.voron_v0_sensor.attributes['print_stats']['print_duration'] / states.sensor.voron_v0_sensor.attributes['display_status']['progress'] - states.sensor.voron_v0_sensor.attributes['print_stats']['print_duration']) if states.sensor.voron_v0_sensor.attributes['display_status']['progress'] > 0 else 0)) | timestamp_custom("%H:%M:%S", 0) if is_state('sensor.voron_v0_sensor', 'OK') else None }}
vzero_nozzletemp:
value_template: '{{[( states.sensor.voron_v0_sensor.attributes["extruder"]["temperature"] | float | round(1)| string)," / ",( states.sensor.voron_v0_sensor.attributes["extruder"]["target"] | float | round(1)| string)]|join}}'
icon_template: mdi:thermometer
value_template: >-
{{ [(states.sensor.voron_v0_sensor.attributes['extruder']['temperature'] | float | round(1) | string), " / ", (states.sensor.voron_v0_sensor.attributes['extruder']['target'] | float | round(1) | string)] | join if is_state('sensor.voron_v0_sensor', 'OK') else None }}
vzero_bedtemp:
value_template: '{{[( states.sensor.voron_v0_sensor.attributes["heater_bed"]["temperature"] | float | round(1)| string)," / ",( states.sensor.voron_v0_sensor.attributes["heater_bed"]["target"] | float | round(1)| string)]|join}}'
icon_template: mdi:thermometer
value_template: >-
{{ [(states.sensor.voron_v0_sensor.attributes['heater_bed']['temperature'] | float | round(1) | string), " / ", (states.sensor.voron_v0_sensor.attributes['heater_bed']['target'] | float | round(1) | string)] | join if is_state('sensor.voron_v0_sensor', 'OK') else None }}
# The following will allow you to control the power of devices configured in the "[power]" sections of moonraker
# Make sure to change the `Printer` name below to the device name on your configuration
#
switch:
- platform: rest
name: Voron_V0_power
resource: "http://192.168.178.56:7125/machine/device_power/device?device=Printer"
body_on: '{"action": "on"}'
body_off: '{"action": "off"}'
headers:
Content-Type: 'application/json'
is_on_template: >-
{{ 'result' in value_json and (value_json.result.values() | list | first == "on") }}
# MJPEG camera can be exposed to HA
#
camera:
- platform: mjpeg
name: Voron_V0_camera
still_image_url: http://192.168.178.56/webcam/?action=snapshot
mjpeg_url: http://192.168.178.56/webcam/?action=stream
+6
View File
@@ -1,5 +1,11 @@
# Welcome to Moonraker Documentation
Moonraker is a Python 3 based web server that exposes APIs with which
client applications may use to interact with the 3D printing firmware
[Klipper](https://github.com/Klipper3d/klipper). Communcation between
the Klippy host and Moonraker is done over a Unix Domain Socket. Tornado
is used to provide Moonraker's server functionality.
Users should refer to the [Installation](installation.md) and
[Configuration](configuration.md) sections for documentation on how
to install and configure Moonraker.
+499 -55
View File
@@ -31,7 +31,7 @@ missing one or both, you can simply add the bare sections to `printer.cfg`:
[display_status]
[virtual_sdcard]
path: ~/gcode_files
path: ~/printer_data/gcodes
```
### Enabling the Unix Socket
@@ -69,12 +69,9 @@ KLIPPY_ARGS="/home/pi/klipper/klippy/klippy.py /home/pi/printer.cfg -l /tmp/klip
the default LSB script. In this case, you need to modify the
klipper.service file.
You may also want to take this opportunity to change the location of
printer.cfg to match Moonraker's `config_path` option (see the
[configuration document](configuration.md#primary-configuration)
for more information on the config_path). For example, if the `config_path`
is set to `~/printer_config`, your klipper defaults file might look
like the following:
You may also want to take this opportunity to configure `printer.cfg` and
`klippy.log` so they are located in Moonraker's `data_path`, for example:
```
# Configuration for /etc/init.d/klipper
@@ -82,14 +79,17 @@ KLIPPY_USER=pi
KLIPPY_EXEC=/home/pi/klippy-env/bin/python
KLIPPY_ARGS="/home/pi/klipper/klippy/klippy.py /home/pi/printer_config/printer.cfg -l /tmp/klippy.log -a /tmp/klippy_uds"
KLIPPY_ARGS="/home/pi/klipper/klippy/klippy.py /home/pi/printer_data/config/printer.cfg -l /home/pi/printer_data/logs/klippy.log -a /tmp/klippy_uds"
```
If necessary, create the config directory and move printer.cfg to it:
Moonraker's install script will create the data folder, however you
may wish to create it now and move `printer.cfg` to the correct
location, ie:
```
cd ~
mkdir printer_config
mv printer.cfg printer_config
mkdir ~/printer_data
mkdir ~/printer_data/logs
mkdir ~/printer_data/config
mv printer.cfg ~/printer_data/config
```
### Installing Moonraker
@@ -101,10 +101,15 @@ cd ~
git clone https://github.com/Arksine/moonraker.git
```
Now is a good time to create [moonraker.conf](configuration.md). If you are
using the `config_path`, create it in the specified directory otherwise create
it in the HOME directory. The [sample moonraker.conf](./moonraker.conf) in
the `docs` directory may be used as a starting point.
The install script will attempt to create a basic configuration if
`moonraker.conf` does not exist at the expected location, however if you
prefer to have Moonraker start with a robust configuration you may create
it now. By default the configuration file should be located at
`$HOME/printer_data/config/moonraker.conf`, however the location of the
data path may be configured using the script's command line options.
The [sample moonraker.conf](./moonraker.conf) may be used as a starting
point, full details can be found in the
[confguration documentation](./configuration.md).
For a default installation run the following commands:
```
@@ -112,34 +117,208 @@ cd ~/moonraker/scripts
./install-moonraker.sh
```
Or to install with `moonraker.conf` in the `config_path`:
```
cd ~/moonraker/scripts
./install-moonraker.sh -f -c /home/pi/printer_config/moonraker.conf
```
The install script has a few command line options that may be useful,
particularly for those upgrading:
- `-r`:
Rebuilds the virtual environment for existing installations.
Sometimes this is necessary when a dependency has been added.
- `-f`:
Force an overwrite of Moonraker's systemd script. By default the
the systemd script will not be modified if it exists.
- `-c /home/pi/moonraker.conf`:
Specifies the path to Moonraker's config file. The default location
is `/home/<user>/moonraker.conf`. When using this option to modify
an existing installation it is necessary to add `-f` as well.
- `-a <alias>`:
The installer uses this option to determine the name of the service
to install. If `-d` is not provided then this options will also be
used to determine the name of the data path folder. If omitted this
defaults to `moonraker`.
- `-d <path to data folder>`:
Specifies the path to Moonraker's data folder. This folder organizes
files and directories used by moonraker. See the `Data Folder Structure`
section for details. If omitted this defaults to `$HOME/printer_data`.
- `-c <path to configuration file>`
Specifies the path to Moonraker's configuation file. By default the
configuration is expected at `<data_folder>/config/moonraker.conf`. ie:
`/home/pi/printer_data/config/moonraker.conf`.
- `-l <path to log file>`
Specifies the path to Moonraker's log file. By default Moonraker logs
to `<data_folder>/logs/moonraker.log`. ie:
`/home/pi/printer_data/logs/moonraker.log`.
- `-z`:
Disables `systemctl` commands during install (ie: daemon-reload, restart).
This is useful for installations that occur outside of a standard environment
where systemd is not running.
- `-x`:
Skips installation of [polkit rules](#policykit-permissions). This may be
necessary to install Moonraker on systems that do not have policykit
installed.
Additionally, installation may be customized with the following environment
variables:
- `MOONRAKER_VENV`
- `MOONRAKER_REBUILD_ENV`
- `MOONRAKER_FORCE_DEFAULTS`
- `MOONRAKER_DISABLE_SYSTEMCTL`
- `MOONRAKER_SKIP_POLKIT`
- `MOONRAKER_CONFIG_PATH`
- `MOONAKER_LOG_PATH`
- `MOONRAKER_DATA_PATH`
When the script completes it should start both Moonraker and Klipper. In
`/tmp/klippy.log` you should find the following entry:
`klippy.log` you should find the following entry:
`webhooks client <uid>: Client info {'program': 'Moonraker', 'version': '<version>'}`
Now you may install a client, such as
[Mainsail](https://github.com/meteyou/mainsail) or
[Fluidd](https://github.com/cadriel/fluidd)
[Mainsail](https://github.com/mainsail-crew/mainsail) or
[Fluidd](https://github.com/cadriel/fluidd).
!!! Note
Moonraker's install script no longer includes the nginx dependency.
If you want to install one of the above clients on the local machine,
you may want to first install nginx (`sudo apt install nginx` on
debian/ubuntu distros).
### Data Folder Structure
As mentioned previously, files and folders used by Moonraker are organized
in a primary data folder. The example below illustrates the folder
structure using the default data path of `$HOME/printer_data`.
```
/home/pi/printer_data
├── backup
│   └── 20220822T202419Z
│   ├── config
│   │   └── moonraker.conf
│   └── service
│   └── moonraker.service
├── certs
│   ├── moonraker.cert (optional)
│   └── moonraker.key (optional)
├── config
│   ├── moonraker.conf
│   └── printer.cfg
├── database
│   ├── data.mdb
│   └── lock.mdb
├── gcodes
│   ├── test_gcode_one.gcode
│   └── test_gcode_two.gcode
├── logs
│   ├── klippy.log
│   └── moonraker.log
├── systemd
│ └── moonraker.env
├── moonraker.secrets (optional)
└── moonraker.asvc
```
If it is not desirible for the files and folders to exist in these specific
locations it is acceptable to use symbolic links. For example, it is common
for the gcode folder to be located at `$HOME/gcode_files`. Rather than
reconfigure Klipper's `virtual_sdcard` it may be desirable to create a
`gcodes` symbolic link in the data path pointing to this location.
!!! Note
It is still possible to directly configure the paths to the configuration
and log files if you do not wish to use the default file names of
`moonraker.conf` and `moonraker.log`
When Moonraker attempts to update legacy installations symbolic links
are used to avoid an unrecoverable error. Additionally a `backup`
folder is created which contains the prior configuration and/or
systemd service unit, ie:
```
/home/pi/printer_data
├── backup
│   └── 20220822T202419Z
│   ├── config
│   │   ├── include
│   │   │   ├── extras.conf
│   │   │   ├── power.conf
│   │   │   └── updates.conf
│   │   └── moonraker.conf
│   └── service
│   └── moonraker.service
├── certs
│   ├── moonraker.cert -> /home/pi/certs/certificate.pem
│   └── moonraker.key -> /home/pi/certs/key.pem
├── config -> /home/pi/klipper_config
├── database -> /home/pi/.moonraker_database
├── gcodes -> /home/pi/gcode_files
├── logs -> /home/pi/logs
├── systemd
│ └── moonraker.env
└── moonraker.secrets -> /home/pi/moonraker_secrets.ini
```
!!! Warning
The gcode and config paths should not contain symbolic links
that result in an "overlap" of on another. Moonraker uses
inotify to watch files in each of these folders and takes action
when a file change is detected. The action taken depends on the
"root" folder, thus it is important that they be distinct.
### The systemd service file
The default installation will create `/etc/systemd/system/moonraker.service`.
Below is a common example of service file, installed on a Raspberry Pi:
```ini
# systemd service file for moonraker
[Unit]
Description=API Server for Klipper SV1
Requires=network-online.target
After=network-online.target
[Install]
WantedBy=multi-user.target
[Service]
Type=simple
User=pi
SupplementaryGroups=moonraker-admin
RemainAfterExit=yes
WorkingDirectory=/home/pi/moonraker
EnvironmentFile=/home/pi/printer_data/systemd/moonraker.env
ExecStart=/home/pi/moonraker-env/bin/python $MOONRAKER_ARGS
Restart=always
RestartSec=10
```
Following are some items to take note of:
- The `Description` contains a string that Moonraker uses to validate
the version of the service file, (notice `SV1` at the end, ie: Service
Version 1).
- The `moonraker-admin` supplementary group is used to grant policykit
permissions.
- The `EnvironmentFile` field contains Moonraker's arguments. More on this
below.
- The `ExecStart` field begins with the python executable, followed by
by the enviroment variable `MOONRAKER_ARGS`. This variable is set in
the environment file.
#### The Environment File
The environment file, `moonraker.env`. is created in the data path during
installation. A default installation's environment file will contain the path
to `moonraker.py` and the data path option, ie:
```
MOONRAKER_ARGS="/home/pi/moonraker/moonraker/moonraker.py -d /home/pi/printer_data"
```
A legacy installation converted to the updated flexible service unit
might contain the following:
```
MOONRAKER_ARGS="/home/pi/moonraker/moonraker/moonraker.py -d /home/pi/printer_data -c /home/pi/klipper_config/moonraker.conf -l /home/pi/klipper_logs/moonraker.log"
```
Post installation it is simple to customize the [arguments](#command-line-usage)
supplied to Moonraker by editing this file and restarting the service.
### Command line usage
@@ -147,47 +326,312 @@ This section is intended for users that need to write their own
installation script. Detailed are the command line arguments
available to Moonraker:
```
usage: moonraker.py [-h] [-c <configfile>] [-l <logfile>] [-n]
usage: moonraker.py [-h]p [-d <data path>] [-c <configfile>] [-l <logfile>] [-n]
Moonraker - Klipper API Server
optional arguments:
options:
-h, --help show this help message and exit
-d <data path>, --datapath <data path>
Location of Moonraker Data File Path
-c <configfile>, --configfile <configfile>
Location of moonraker configuration file
-l <logfile>, --logfile <logfile>
log file name and location
-n, --nologfile disable logging to a file
-v, --verbose Enable verbose logging
-g, --debug Enable Moonraker debug features
-o, --asyncio-debug Enable asyncio debug flag
```
The default configuration is:
- config file path- `~/moonraker.conf`
- log file path - `/tmp/moonraker.log`
- `data path`: `$HOME/printer_data`
- `config file`: `$HOME/printer_data/config/moonraker.conf`
- `log file`: `$HOME/printer_data/logs/moonraker.log`
- logging to a file is enabled
- Verbose logging is disabled
- Moonraker's debug features are disabled
- The asyncio debug flag is set to false
If one needs to start moonraker without generating a log file, the
!!! Tip
While the `data path` option may be omitted it is recommended that it
always be included for new installations. This allows Moonraker
to differentiate between new and legacy installations.
If is necessary to run Moonraker without logging to a file the
`-n` option may be used, for example:
```
~/moonraker-env/bin/python ~/moonraker/moonraker/moonraker.py -n -c /path/to/moonraker.conf
~/moonraker-env/bin/python ~/moonraker/moonraker/moonraker.py -d ~/printer_data -n
```
In general it is not recommended to install moonraker with this option.
While moonraker will still log to stdout, all requests for support must
be accompanied by moonraker.log.
These options may be changed by editing
`/etc/systemd/system/moonraker.service`. The `install-moonraker.sh` script
may also be used to modify the config file location.
In general it is not recommended to install Moonraker with file logging
disabled. While moonraker will still log to stdout, all requests for support
must be accompanied by moonraker.log.
### Additional Notes
These options may be changed by editing `moonraker.env`.
- Make sure that Moonraker and Klipper both have read and write access to the
directory set in the `path` option for the `[virtual_sdcard]` in
`printer.cfg`.
- Upon first starting Moonraker is not aware of the gcode file path, thus
it cannot serve gcode files, add directories, etc. After Klippy enters
the "ready" state it sends Moonraker the gcode file path.
Once Moonraker receives the path it will retain it regardless of Klippy's
state, and update it if the path is changed in printer.cfg.
### PolicyKit Permissions
Please see [configuration.md](configuration.md) for details on how to
configure moonraker.conf.
Some of Moonraker's components require elevated privileges to perform actions.
Previously these actions could only be run via commandline programs launched
with the `sudo` prefix. This has significant downsides:
- The user must be granted `NOPASSWD` sudo access. Raspberry Pi OS
grants the Pi user this access by default, however most other distros
require that this be enabled through editing `visudo` or adding files
in `/etc/sudoers.d/`.
- Some linux distributions require additional steps such as those taken
in `sudo_fix.sh`.
- Running CLI programs is relatively expensive. This isn't an issue for
programs that are run once at startup, but is undesirable if Moonraker
wants to poll information about the system.
Moonraker now supports communicating with system services via D-Bus.
Operations that require elevated privileges are authrorized through
PolicyKit. On startup Moonraker will check for the necessary privileges
and warn users if they are not available. Warnings are presented in
`moonraker.log` and directly to the user through some clients.
To resolve these warnings users have two options:
1) Install the PolicyKit permissions with the `set-policykit-rules.sh` script,
for example:
```shell
cd ~/moonraker/scripts
./set-policykit-rules.sh
sudo service moonraker restart
```
!!! tip
If you still get warnings after installing the PolKit rules, run the
install script with no options to make sure that all new dependencies
are installed.
```shell
cd ~/moonraker/scripts
./install-moonraker.sh
```
2) Configure Moonraker to use the legacy backend implementations for
the `machine` and/or `update_manager` components, ie:
```ini
# Use the systemd CLI provider rather than the DBus Provider
[machine]
provider: systemd_cli
# Edit your existing [update_manager] section to disable
# PackageKit. This will fallback to the APT CLI Package Update
# implementation.
[update_manager]
#..other update manager options
enable_packagekit: False
# Alternatively system updates can be disabled
[update_manager]
#..other update manager options
enable_system_updates: False
```
!!! Note
Previously installed PolicyKit rules can be removed by running
`set-policykit-rules.sh -c`
### Completing Privileged Upgrades
At times an update to Moonraker may require a change to the systemd service
file, which requires sudo permission to complete. Moonraker will present
an announcement when it need's the user's password and the process can
be completed by entering the password through Moonraker's landing page.
Some users prefer not to provide these credentials via the web browser and
instead would like to do so over ssh. These users may run
`scripts/finish-upgrade.sh` to provide Moonraker the necessary credentials
via ssh:
```
Utility to complete privileged upgrades for Moonraker
usage: finish-upgrade.sh [-h] [-a <address>] [-p <port>] [-k <api_key>]
optional arguments:
-h show this message
-a <address> address for Moonraker instance
-p <port> port for Moonraker instance
-k <api_key> API Key for authorization
```
By default the script will connect to a Moonraker instances on the local
machine at port 7125. If the instance is not bound to localhost or is
bound to another port the user may specify a custom address and port.
The API Key (`-k`) option is only necessary if the localhost is not authorized
to access Moonraker's API.
### Retrieving the API Key
Some clients may require an API Key to connect to Moonraker. After the
`[authorization]` component is first configured Moonraker will automatically
generate an API Key. There are two ways in which the key may be retrieved
by the user:
Retrieve the API Key via the command line (SSH):
```
cd ~/moonraker/scripts
./fetch-apikey.sh
```
Retrieve the API Key via the browser from a trusted client:
- Navigate to `http://{moonraker-host}/access/api_key`, where
`{moonraker-host}` is the host name or ip address of the desired
moonraker instance.
- The result will appear in the browser window in JSON format. Copy
The API Key without the quotes.
{"result": "8ce6ae5d354a4365812b83140ed62e4b"}
### LMDB Database Backup and Restore
Moonraker uses a [LMDB Database](http://www.lmdb.tech/doc/) for persistent
storage of procedurally generated data. LMDB database files are platform
dependent, and thus cannot be easily transferred between different machines.
A file generated on a Raspberry Pi cannot be directly transferred to an x86
machine. Likewise, a file generated on a 32-bit version of Linux cannot
be transferred to a 64-bit machine.
Moonraker includes two scripts, `backup-database.sh` and `restore-database.sh`
to help facilitate database backups and transfers.
```shell
~/moonraker/scripts/backup-database.sh -h
Moonraker Database Backup Utility
usage: backup-database.sh [-h] [-e <python env path>] [-d <database path>] [-o <output file>]
optional arguments:
-h show this message
-e <env path> Moonraker Python Environment
-d <database path> Moonraker LMDB database to backup
-o <output file> backup file to save to
```
```shell
~/moonraker/scripts/restore-database.sh -h
Moonraker Database Restore Utility
usage: restore-database.sh [-h] [-e <python env path>] [-d <database path>] [-i <input file>]
optional arguments:
-h show this message
-e <env path> Moonraker Python Environment
-d <database path> Moonraker LMDB database path to restore to
-i <input file> backup file to restore from
```
Both scripts include default values for the Moonraker Environment and Database
Path. These are `$HOME/moonraker-env` and `$HOME/printer_data/database`
respectively. The `backup` script defaults the output value to
`$HOME/database.backup`. The `restore` script requires that the user specify
the input file using the `-i` option.
To backup a database for a default Moonraker installation the user may ssh into
the machine and run the following command:
```shell
~/moonraker/scripts/backup-database.sh -o ~/moonraker-database.backup
```
And to restore the database:
```shell
sudo service moonraker stop
~/moonraker/scripts/restore-database.sh -i ~/moonraker-database.backup
sudo service moonraker start
```
The backup file contains [cdb like](https://manpages.org/cdb/5) entries
for each key/value pair in the database. All keys and values are base64
encoded, however the data is not encrypted. Moonraker's database may
contain credentials and other sensitive information, so users should treat
this file accordingly. It is not recommended to keep backups in any folder
served by Moonraker.
### Recovering a broken repo
Currently Moonraker is deployed using `git`. Without going into the gritty
details,`git` is effectively a file system, and as such is subject to
file system corruption in the event of a loss of power, bad sdcard, etc.
If this occurs, updates using the `[update_manager]` may fail. In most
cases Moonraker provides an automated method to recover, however in some
edge cases this is not possible and the user will need to do so manually.
This requires that you `ssh` into your machine. The example below assumes
the following:
- You are using a Raspberry Pi
- Moonraker and Klipper are installed at the default locations in the `home`
directory
- Both Moonraker and Klipper have been corrupted and need to be restored
The following commands may be used to restore Moonraker:
```shell
cd ~
rm -rf moonraker
git clone https://github.com/Arksine/moonraker.git
cd moonraker/scripts
./install-moonraker.sh
./set-policykit-rules.sh
sudo systemctl restart moonraker
```
And for Klipper:
```shell
cd ~
rm -rf klipper
git clone https://github.com/Klipper3d/klipper.git
sudo systemctl restart klipper
```
### Debug options for developers
Moonraker accepts several command line arguments that can be used to
assist both front end developers and developers interested in extending
Moonraker.
- The `-v` (`--verbose`) argument enables verbose logging. This includes
logging that reports information on all requests received and responses.
- The `-g` (`--debug`) argument enables Moonraker's debug features,
including:
- Debug endpoints
- The `update_manager` will bypass strict git repo validation, allowing
updates from unofficial remotes and repos in a `detached HEAD` state.
- The `-o` (`--asyncio-debug`) argument enables the asyncio debug flag. This
will substantially increase logging and is intended for low level debugging
of the asyncio event loop.
!!! Warning
The debug option should not be enabled in production environments. The
database debug endpoints grant read/write access to all namespaces,
including those typically exclusive to Moonraker. Items such as user
credentials are exposed.
Installations using systemd can enable debug options by editing `moonraker.env`
via ssh:
```
nano ~/printer_data/systemd/moonraker.env
```
Once the file is open, append the debug option(s) (`-v` and `-g` in this example) to the
value of `MOONRAKER_ARGS`:
```
MOONRAKER_ARGS="/home/pi/moonraker/moonraker/moonraker.py -d /home/pi/printer_data -c /home/pi/klipper_config/moonraker.conf -l /home/pi/klipper_logs/moonraker.log -v -g"
```
Save the file, exit the text editor, and restart the Moonraker service:
```
sudo systemctl restart moonraker
```
+12 -3
View File
@@ -1,9 +1,12 @@
# Sample Moonraker Configuration File
#
# !!! Moonraker does not load this file. See configuration.md !!!
# !!! for details on path to Moonraker's configuration. !!!
#
[server]
# Bind server defaults of 0.0.0.0, port 7125
enable_debug_logging: True
config_path: ~/printer_config
enable_debug_logging: False
[authorization]
enabled: True
@@ -14,7 +17,13 @@ cors_domains:
# Allow CORS requests for Fluidd
http://app.fluidd.xyz
# Enable Octoprint compatibility for Slicer uploads
# Enable OctoPrint compatibility for Slicer uploads
# Supports Cura, Slic3r, and Slic3r dervivatives
# (PrusaSlicer, SuperSlicer)
[octoprint_compat]
# Default webcam config values:
# flip_h = false
# flip_v = false
# rotate_90 = false
# stream_url = /webcam/?action=stream
# webcam_enabled = true
+9 -4
View File
@@ -4,13 +4,13 @@ As mentioned in the API documentation, it is possible to
[subscribe](web_api.md#subscribe-to-printer-object-status)
to "Klipper Printer Objects." There are numerous printer objects in
Klipper, many of which are optional and only report status if they are
enabled by Klipper's configuration. Client's may retreive a list of
enabled by Klipper's configuration. Client's may retrieve a list of
available printer objects via the
[list objects endpoint](web_api.md#list-available-printer-objects). This
should be done after Klipper reports its state as "ready".
This section will provide an overview of the most useful printer objects.
If a developer is interested in retreiving state for an object not listed here,
If a developer is interested in retrieving state for an object not listed here,
look in Klipper's source code for module you wish to query. If the module
contains a "get_status()" method, its return value will contain a dictionary
that reports state which can be queried.
@@ -251,8 +251,13 @@ The `print_stats` object reports `virtual_sdcard` print state:
equivalent to `total_duration` - time paused.
- `filament_used`: The amount of filament used during the current print
(in mm). Any extrusion during a pause is excluded.
- `state`: Current print state. Can be "standby", "printing", "paused",
"complete", or "error". If an error is detected the print will abort.
- `state`: Current print state. Can be one of the following values:
- `"standby"`
- `"printing"`
- `"paused"`
- `"complete"`
- `"cancelled"`
- `"error"` - Note that if an error is detected the print will abort
- `message`: If an error is detected, this field contains the error
message generated. Otherwise it will be a null string.
+105 -1
View File
@@ -2,6 +2,110 @@
This file will track changes that require user intervention,
such as a configuration change or a reinstallation.
### Februrary 8th 2023
- The `provider` option in the `[machine]` section no longer accepts
`supervisord` as an option. It has been renamed to `supervisord_cli`.
### January 2nd 2023
- The `bound_service` option for `[power]` devices has been deprecated in
favor of `bound_services`. Currently this change does not generate a
warning as it can be reliably resolved internally.
### October 14th 2022
- The systemd service file is now versioned. Moonraker can now detect when
the file is out of date and automate corrections as necessary.
- Moonraker's command line options are now specified in an environment file,
making it possible to change these options without modifying the service file
and reloading the systemd daemon. The default location of the environment
file is `~/printer_data/systemd/moonraker.env`.
- Moonraker now manages files and folders in a primary data folder supplied
by the `-d` (`--data-path`) command line option. As a result, the following
options have been deprecated:
- `ssl_certificate_path` in `[server]`
- `ssl_key_path` in `[server]`
- `database_path` in `[database]`
- `config_path` in `[file_manager]`
- `log_path` in `[file_manager]`
- `secrets_path` in `[secrets]`
- Debugging options are now supplied to Moonraker via the command line.
The `-v` (`--verbose`) option enables verbose logging, while the `-g`
(`--debug`) option enables debug features, including access to debug
endpoints and the repo debug feature in `update_manager`. As a result,
the following options are deprecated:
- `enable_debug_logging` in `[server]`
- `enable_repo_debug` in `[update_manager]`
### July 27th 2022
- The behavior of `[include]` directives has changed. Included files
are now parsed as they are encountered. If sections are duplicated
options in the last section parsed take precendence. If you are
using include directives to override configuration in `moonraker.conf`
the directives should be moved to the bottom of the file.
- Configuration files now support inline comments.
### April 6th 2022
- The ability to configure core components in the `[server]`section
is now deprecated. When legacy items are detected in `[server]` a
warning will be generated. It is crucially important to move configuration
to the correct section as in the future it will be a hard requirement.
### Feburary 22nd 2022
- The `on_when_upload_queued` option for [power] devices has been
deprecated in favor of `on_when_job_queued`. As the new option
name implies, this option will power on the device when any new
job is queued, not only when its sourced from an upload. The
`on_when_upload_queued` option will be treated as an alias to
`on_when_job_queued` until its removal.
### February 16th 2022
- Webcam settings can now be defined in the `moonraker.conf` file, under
the `[octoprint_compat]` section. The default values are being used as
default values.
Default values:
| Setting | Default value |
|---------|---------------|
| flip_h | False |
| flip_v | False |
| rotate_90 | False |
| stream_url | /webcam/?action=stream |
| webcam_enabled | True |
### January 22th 2022
- The `color_order` option in the `[wled]` section has been deprecated.
This is configured in wled directly. This is not a breaking change,
the setting will simply be ignored not affecting functionality.
### December 24th 2021
- The `password_file` option in the `[mqtt]` section has been deprecated.
Use the `password` option instead. This option may be a template, thus
can resolve secrets stored in the `[secrets]` module.
### November 7th 2021
- Previously all core components received configuration through
the `[server]` config section. As Moonraker's core functionality
has expanded this is becoming unsustainable, thus core components
should now be configured in their own section. For example, the
`config_path` and `log_path` should now be configured in the
`[file_manager]` section of `moonraker.conf`. See the
[configuration documentation](https://moonraker.readthedocs.io/en/latest/configuration/)
for details. This is not a breaking change, core components
will still fall back to checking the `[server]` section for
configuration.
### April 19th 2021
- The `[authorization]` module is now a component, thus is only
loaded if the user has it configured in `moonraker.conf`. This
deprecates the previous `enable` option, as it is enabled
if configured and disabled otherwise.
- The API Key is now stored in the database. This deprecates the
`api_key_file` option in the `[authorization]` module. Users can
no longer read the contents of the API Key file to retrieve the
API Key. Instead, users can run `scripts/fetch-apikey.sh` to
print the API Key. Alternative a user can navigate to
`http://{moonraker-host}/access/api_key` from a trusted client
to retrieve the API Key.
### March 10th 2021
- The `cors_domain` option in the `[authoriztion]` section is now
checked for dangerous entries. If a domain entry contains a
@@ -15,7 +119,7 @@ such as a configuration change or a reinstallation.
by Moonraker for the typical user.
### March 4th 2021
- To enable Octoprint compatibility with slicer uploads it is now
- To enable OctoPrint compatibility with slicer uploads it is now
required to add `[octoprint_compat]` to `moonraker.conf`. After
making this change it is necessary to restart the Moonraker service
so the module is loaded.
+4664 -501
View File
File diff suppressed because it is too large. Load diff
+10 -7
View File
@@ -1,21 +1,24 @@
site_name: Moonraker
site_url: https://moonraker.readthedocs.io
repo_url: https://github.com/Arksine/moonraker
nav:
- 'User Documentation':
- Installation: installation.md
- Configuration : configuration.md
- User Changes: user_changes.md
- 'Client Developers':
- Client API: web_api.md
- 'Developer Documenation':
- Remote API: web_api.md
- Printer Objects: printer_objects.md
- API Changes: api_changes.md
- 'Backend Developers':
- Contributing: contributing.md
- Components: components.md
- 'Miscellaneous':
- Contributing: contributing.md
- Changelog: changelog.md
theme:
name: readthedocs
plugins:
- search
markdown_extensions:
- codehilite
- admonition
- pymdownx.superfences
- pymdownx.highlight:
use_pygments: false
- pymdownx.inlinehilite
+5
View File
@@ -0,0 +1,5 @@
# Top level package definition for Moonraker
#
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
+9
View File
@@ -0,0 +1,9 @@
# Package entry point for Moonraker
#
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from .server import main
main()
+787 -131
View File
File diff suppressed because it is too large. Load diff
+1
View File
@@ -0,0 +1 @@
# Assets Package Definition
+500
View File
@@ -0,0 +1,500 @@
<html>
<head>
<title>Moonraker {{ version }}</title>
<style>
body {
background-color: rgb(48, 48, 48);
color: rgb(230, 230, 230);
font-family: Arial, Helvetica, sans-serif;
margin: 0px;
}
.nav-bar {
width: 100%;
overflow: hidden;
}
.nav-bar a {
float: right;
text-align: center;
padding: .5em .75em;
font-size: 1.2em;
text-decoration: none;
color: rgb(230, 230, 230);
}
.intro {
font-size: 1.1em;
margin-top: 7rem;
margin-left: auto;
margin-right: auto;
width: 60%;
}
.intro h1 {
font-size: 2.2rem;
text-align: center;
}
.status {
display: flex;
margin-top: 2rem;
margin-left: auto;
margin-right: auto;
width: 80%;
align-items: baseline;
justify-content: center;
column-gap: 1.5rem;
row-gap: 1.5rem;
flex-wrap: wrap;
}
.card {
background:none;
border: 0px;
border-radius: .75rem;
width: 25rem;
}
.card h1 {
background-color: #225353;
text-align: center;
line-height: 2.2rem;
font-size: 1.1rem;
height: 2.2rem;
margin: 0;
border-top-left-radius: .75rem;
border-top-right-radius: .75rem;
}
.card .content{
background-color: #1a1a1a;
border-bottom-left-radius: .75rem;
border-bottom-right-radius: .75rem;
padding: .5rem;
}
.card .entry {
display: inline-block;
width: 100%;
}
.card .entry:not(:last-child) {
margin-bottom: .4rem;
}
.card .value {
float: right;
display: inline;
}
.messages {
margin-top: 2rem;
width: 51.5rem;
padding: .5rem;
}
.messages .item {
padding: .5rem;
background: #242424;
border-radius: .4rem;
}
.messages .announcement {
cursor: pointer;
}
.messages .item:not(:last-child) {
margin-bottom: .5rem;
}
.messages .item a {
font-size: 1.2rem;
margin: 0;
font-weight: 600;
padding: 0rem;
margin-bottom: .1rem;
text-decoration: None;
color: rgb(230, 230, 230);
}
.messages .item:hover {
background-color: #3f3f3f;
}
.messages .item:hover a,
.messages .item a:hover {
color: rgb(235, 199, 0);
}
.messages .item p {
font-size: 1rem;
}
.warning h1 {
animation: glow 1s ease-in-out infinite alternate;
}
@keyframes glow {
from {
background-color: #225353;
}
to {
background-color: rgb(160, 64, 8);
}
}
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}
.modal-card {
background: none;
position: relative;
border: 0px;
border-radius: 1rem;
background-color: #1a1a1a;
margin: 20% auto 2rem auto;
padding: 0rem;
border: 0px;
width: 50%;
animation-name: fadein;
animation-duration: .5s;
}
.modal-card h1 {
background-color: #006f7e;
text-align: center;
line-height: 3rem;
font-size: 1.1rem;
height: 3rem;
margin: 0;
border-top-left-radius: 1rem;
border-top-right-radius: 1rem;
}
.modal-content {
background-color: #3e3e3e;
padding: 1rem;
margin: 0;
height: auto
}
.modal-content .entry {
display: inline-block;
width: 100%;
}
.modal-content .entry:not(:last-child) {
margin-bottom: .5rem;
}
.modal-content .value {
float: right;
display: inline;
}
.modal-content input {
width: 100%;
padding: 8px;
border-radius: 4px;
-moz-border-radius: 4px;
-webkit-border-radius: 4px;
font-size: 1rem; color: #222;
background: #F7F7F7;
}
.modal-footer {
display: inline-block;
background-color: #3e3e3e;
margin: 0;
height: auto;
width: 100%;
border-bottom-left-radius: 1rem;
border-bottom-right-radius: 1rem;
}
.modal-button {
float: right;
background: #cecece;
border: none;
width: auto;
overflow: visible;
font-size: 1rem;
font-weight: bold;
color: rgb(0, 0, 0);
padding: .4rem .5rem;
margin: 0rem .5rem .5rem 0rem;
border-radius: .5rem;
-webkit-border-radius: .5rem;
-moz-border-radius: .5rem;
}
.modal-button:hover {
color: rgb(8, 154, 45);
text-decoration: none;
cursor: pointer;
}
.modal-status {
display: none;
position: relative;
border: 0;
border-radius: 1rem;
background-color: #3e3e3e;
margin: auto;
padding: 0rem;
width: 50%;
animation-name: fadebottom;
animation-duration: .5s;
}
.modal-status:hover {
cursor: pointer;
}
.modal-status .content {
display: inline-block;
margin: 1rem;
}
@keyframes fadebottom {
from {top: 10em; opacity: 0}
to {top: 0em; opacity: 1}
}
@keyframes fadein {
from {opacity: 0}
to {opacity: 1}
}
</style>
<script>
function setClickable(id) {
const item = document.querySelector(`#${id}`);
const primary_link = item.querySelector("a");
const clickable = Array.from(item.querySelectorAll(".clickable"));
clickable.forEach((element) => {
element.addEventListener("click", (evt) => {
evt.stopPropagation();
})
});
function onItemClicked(evt) {
const noTextSelected = !window.getSelection().toString();
if (noTextSelected)
primary_link.click();
}
item.addEventListener("click", onItemClicked);
}
</script>
</head>
<body>
<main>
<div class="nav-bar">
<a href="https://github.com/Arksine/moonraker">GitHub</a>
<a href="https://moonraker.readthedocs.io">Documentation</a>
</div>
<div class="intro">
<h1>Welcome to Moonraker</h1>
<p>You may have intended
to navigate to one of Moonraker's front ends, if so check
that you entered the correct port in the address bar.
</p>
</div>
<div class="status">
<article class="card">
<h1>Authorization</h1>
<div class="content">
<div class="entry">
Request IP:
<div class="value">{{ remote_ip }}</div>
</div>
<div class="entry">
Authorized:
<div class="value">{{ authorized }}</div>
</div>
<div class="entry">
CORS Enabled:
<div class="value">{{ cors_enabled }}</div>
</div>
</div>
</article>
<article class="card">
<h1>Status</h1>
<div class="content">
<div class="entry">
Version:
<div class="value">{{ version }}</div>
</div>
<div class="entry">
Websocket Count:
<div class="value">{{ ws_count }}</div>
</div>
<div class="entry">
Klipper State:
<div class="value">{{ klippy_state }}</div>
</div>
</div>
</article>
{% if summary %}
<article class="card messages">
<h1>Summary</h1>
<div class="content">
{% for item in summary %}
<article class="item">{{ item }}</article>
{% endfor %}
</div>
</article>
{% endif %}
{% if announcements %}
<article class="card messages">
<h1>Announcements</h1>
<div class="content">
{% for item in announcements %}
{% set id = "announcement-" + item["entry_id"].replace("/", "-") %}
<article class="item announcement" id="{{ id }}">
{% set url = item["url"] %}
<a href="{{ url }}" class="clickable">{{ item["title"] }}</a>
<p>{{ item["description"] }}</p>
</article>
<script>
setClickable("{{ id }}");
</script>
{% endfor %}
</div>
</article>
{% endif %}
{% if warnings %}
<article class="card messages warning">
<h1>Warnings</h1>
<div class="content">
{% for warn in warnings %}
<article class="item">{{ warn }}</article>
{% endfor %}
</div>
</article>
{% endif %}
</div>
<div id="update_modal" class="modal">
<div class="modal-card">
<h1 id="modal_header_msg">
Moonraker Sudo Password Request
</h1>
<div id="modal_body" class="modal-content">
<div id="main_form">
<div class="entry">
Service Name:
<div class="value">
{{ service_name }}
</div>
</div>
<div class="entry">
Host Name:
<div class="value">
{{ hostname }}
</div>
</div>
<div class="entry">
Host IP Address:
<div class="value">
{{ local_ip }}
</div>
</div>
<div class="entry">
{{ sudo_request_message }}
Please enter the password for linux user <b>{{ linux_user }}</b>:
</div>
<div class="entry">
<input id="sudo_passwd" name="sudo_passwd" type="password" />
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" id="modal_close" class="modal-button">Cancel</button>
<button type="button" id="modal_submit" class="modal-button">Submit</button>
</div>
</div>
<div id="modal_status" class="modal-status">
<div id="status_msg" class="content">
Status Text
</div>
</div>
</div>
<script>
const modal = document.getElementById("update_modal");
{% if sudo_requested %}
modal.style.display = "block";
{% endif %}
const main_form = document.getElementById("main_form")
const status_item = document.getElementById("modal_status");
const status_div = document.getElementById("status_msg");
function update_modal(status_msg) {
status_div.innerHTML = status_msg
status_item.style.display = "block";
}
function dismiss_status() {
status_item.style.display = "none";
}
function check_success(req) {
return (req.status < 205 || req.status == 304);
}
function post_machine_password(passwd) {
let pwd_req = new XMLHttpRequest();
pwd_req.onload = () => {
if (check_success(pwd_req)) {
console.log("Successfully Set Sudo Password");
let resp = JSON.parse(pwd_req.responseText)
let msg = resp.result.sudo_responses.join("<br/>")
msg += "<br/><br/>You may close this window and return to the front end.";
update_modal(msg);
} else {
console.log("Password Request Error");
let err_msg = `Code ${pwd_req.status}: `;
let response = pwd_req.responseText;
try {
let json_resp = JSON.parse(response);
err_msg = json_resp.error.message;
} catch (error) {}
update_modal(
"Request failed with error:<br/><br/>" + err_msg +
"<br/><br/>You may need to manually update your installation."
);
}
};
pwd_req.onerror = () => {
console.log("Error setting password");
update_modal(
"Request to set sudo password failed with " +
"a network error."
)
};
pwd_req.open("POST", "/machine/sudo/password");
pwd_req.setRequestHeader("Content-Type", "application/json");
pwd_req.send(JSON.stringify({"password": passwd}));
}
const modal_submit = document.getElementById("modal_submit");
const pwd_input = document.getElementById("sudo_passwd");
const modal_close = document.getElementById("modal_close");
modal_submit.onclick = () => {
let val = pwd_input.value;
pwd_input.value = "";
dismiss_status();
post_machine_password(val);
};
pwd_input.addEventListener("keypress", (event) => {
if (event.key === "Enter") {
event.preventDefault();
modal_submit.click();
}
});
modal_close.onclick = () => {
modal.style.display = "none";
};
status_item.onclick = () => {
dismiss_status();
}
window.onclick = (event) => {
if (event.target == modal) {
modal.style.display = "none";
}
};
</script>
</main>
</body>
</html>
-307
View File
@@ -1,307 +0,0 @@
# API Key Based Authorization
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
import base64
import uuid
import os
import time
import ipaddress
import re
import logging
import tornado
from tornado.ioloop import IOLoop, PeriodicCallback
from utils import ServerError
TOKEN_TIMEOUT = 5
CONNECTION_TIMEOUT = 3600
PRUNE_CHECK_TIME = 300 * 1000
class Authorization:
def __init__(self, config):
api_key_file = config.get('api_key_file', "~/.moonraker_api_key")
self.api_key_file = os.path.expanduser(api_key_file)
self.api_key = self._read_api_key()
self.auth_enabled = config.getboolean('enabled', True)
self.trusted_connections = {}
self.access_tokens = {}
# Get allowed cors domains
self.cors_domains = []
cors_cfg = config.get('cors_domains', "").strip()
cds = [d.strip() for d in cors_cfg.split('\n')if d.strip()]
for domain in cds:
bad_match = re.search(r"^.+\.[^:]*\*", domain)
if bad_match is not None:
raise config.error(
f"Unsafe CORS Domain '{domain}'. Wildcards are not"
" permitted in the top level domain.")
self.cors_domains.append(
domain.replace(".", "\\.").replace("*", ".*"))
# Get Trusted Clients
self.trusted_ips = []
self.trusted_ranges = []
trusted_clients = config.get('trusted_clients', "")
trusted_clients = [c.strip() for c in trusted_clients.split('\n')
if c.strip()]
for ip in trusted_clients:
# Check IP address
try:
tc = ipaddress.ip_address(ip)
except ValueError:
tc = None
if tc is None:
# Check ip network
try:
tc = ipaddress.ip_network(ip)
except ValueError:
raise ServerError(
f"Invalid option in trusted_clients: {ip}")
self.trusted_ranges.append(tc)
else:
self.trusted_ips.append(tc)
t_clients = "\n".join(
[str(ip) for ip in self.trusted_ips] +
[str(rng) for rng in self.trusted_ranges])
c_domains = "\n".join(self.cors_domains)
logging.info(
f"Authorization Configuration Loaded\n"
f"Auth Enabled: {self.auth_enabled}\n"
f"Trusted Clients:\n{t_clients}\n"
f"CORS Domains:\n{c_domains}")
self.prune_handler = PeriodicCallback(
self._prune_conn_handler, PRUNE_CHECK_TIME)
self.prune_handler.start()
def register_handlers(self, app):
# Register Authorization Endpoints
app.register_local_handler(
"/access/api_key", ['GET', 'POST'],
self._handle_apikey_request, protocol=['http'])
app.register_local_handler(
"/access/oneshot_token", ['GET'],
self._handle_token_request, protocol=['http'])
async def _handle_apikey_request(self, web_request):
action = web_request.get_action()
if action.upper() == 'POST':
self.api_key = self._create_api_key()
return self.api_key
async def _handle_token_request(self, web_request):
return self.get_access_token()
def _read_api_key(self):
if os.path.exists(self.api_key_file):
with open(self.api_key_file, 'r') as f:
api_key = f.read()
return api_key
# API Key file doesn't exist. Generate
# a new api key and create the file.
logging.info(
f"No API Key file found, creating new one at:"
f"\n{self.api_key_file}")
return self._create_api_key()
def _create_api_key(self):
api_key = uuid.uuid4().hex
with open(self.api_key_file, 'w') as f:
f.write(api_key)
return api_key
def _check_authorized_ip(self, ip):
if ip in self.trusted_ips:
return True
for rng in self.trusted_ranges:
if ip in rng:
return True
return False
def _prune_conn_handler(self):
cur_time = time.time()
expired_conns = []
for ip, access_time in self.trusted_connections.items():
if cur_time - access_time > CONNECTION_TIMEOUT:
expired_conns.append(ip)
for ip in expired_conns:
self.trusted_connections.pop(ip, None)
logging.info(
f"Trusted Connection Expired, IP: {ip}")
def _token_expire_handler(self, token):
self.access_tokens.pop(token, None)
def is_enabled(self):
return self.auth_enabled
def get_access_token(self):
token = base64.b32encode(os.urandom(20)).decode()
ioloop = IOLoop.current()
self.access_tokens[token] = ioloop.call_later(
TOKEN_TIMEOUT, self._token_expire_handler, token)
return token
def _check_trusted_connection(self, ip):
if ip is not None:
if ip in self.trusted_connections:
self.trusted_connections[ip] = time.time()
return True
elif self._check_authorized_ip(ip):
logging.info(
f"Trusted Connection Detected, IP: {ip}")
self.trusted_connections[ip] = time.time()
return True
return False
def _check_access_token(self, token):
if token in self.access_tokens:
token_handler = self.access_tokens.pop(token, None)
IOLoop.current().remove_timeout(token_handler)
return True
else:
return False
def check_authorized(self, request):
# Authorization is disabled, request may pass
if not self.auth_enabled:
return True
# Check if IP is trusted
try:
ip = ipaddress.ip_address(request.remote_ip)
except ValueError:
logging.exception(
f"Unable to Create IP Address {request.remote_ip}")
ip = None
if self._check_trusted_connection(ip):
return True
# Check API Key Header
key = request.headers.get("X-Api-Key")
if key and key == self.api_key:
return True
# Check one-shot access token
token = request.arguments.get('token', [b""])[0].decode()
if self._check_access_token(token):
return True
return False
def check_cors(self, origin, request=None):
if origin is None or not self.cors_domains:
return False
for regex in self.cors_domains:
match = re.match(regex, origin)
if match is not None:
if match.group() == origin:
logging.debug(f"CORS Pattern Matched, origin: {origin} "
f" | pattern: {regex}")
self._set_cors_headers(origin, request)
return True
else:
logging.debug(f"Partial Cors Match: {match.group()}")
else:
# Check to see if the origin contains an IP that matches a
# current trusted connection
match = re.search(r"^https?://([^/:]+)", origin)
if match is not None:
ip = match.group(1)
try:
ipaddr = ipaddress.ip_address(ip)
except ValueError:
pass
else:
if self._check_authorized_ip(ipaddr):
logging.debug(
f"Cors request matched trusted IP: {ip}")
self._set_cors_headers(origin, request)
return True
logging.debug(f"No CORS match for origin: {origin}\n"
f"Patterns: {self.cors_domains}")
return False
def _set_cors_headers(self, origin, request):
if request is None:
return
request.set_header("Access-Control-Allow-Origin", origin)
request.set_header(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS")
request.set_header(
"Access-Control-Allow-Headers",
"Origin, Accept, Content-Type, X-Requested-With, "
"X-CRSF-Token")
def close(self):
self.prune_handler.stop()
class AuthorizedRequestHandler(tornado.web.RequestHandler):
def initialize(self):
app = self.settings['parent']
self.server = app.get_server()
self.auth = app.get_auth()
self.wsm = app.get_websocket_manager()
def set_default_headers(self):
origin = self.request.headers.get("Origin")
# it is necessary to look up the parent app here,
# as initialize() may not yet be called
auth = self.settings['parent'].get_auth()
self.cors_enabled = auth.check_cors(origin, self)
def prepare(self):
if not self.auth.check_authorized(self.request):
raise tornado.web.HTTPError(401, "Unauthorized")
def options(self, *args, **kwargs):
# Enable CORS if configured
if self.cors_enabled:
self.set_status(204)
self.finish()
else:
super(AuthorizedRequestHandler, self).options()
def get_associated_websocket(self):
# Return associated websocket connection if an id
# was provided by the request
conn = None
conn_id = self.get_argument('connection_id', None)
if conn_id is not None:
try:
conn_id = int(conn_id)
except Exception:
pass
else:
conn = self.wsm.get_websocket(conn_id)
return conn
# Due to the way Python treats multiple inheritance its best
# to create a separate authorized handler for serving files
class AuthorizedFileHandler(tornado.web.StaticFileHandler):
def initialize(self, path, default_filename=None):
super(AuthorizedFileHandler, self).initialize(path, default_filename)
app = self.settings['parent']
self.server = app.get_server()
self.auth = app.get_auth()
def set_default_headers(self):
origin = self.request.headers.get("Origin")
auth = self.settings['parent'].get_auth()
self.cors_enabled = auth.check_cors(origin, self)
def prepare(self):
if not self.auth.check_authorized(self.request):
raise tornado.web.HTTPError(401, "Unauthorized")
def options(self, *args, **kwargs):
# Enable CORS if configured
if self.cors_enabled:
self.set_status(204)
self.finish()
else:
super(AuthorizedFileHandler, self).options()
+541
View File
@@ -0,0 +1,541 @@
# Support for Moonraker/Klipper/Client announcements
#
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import datetime
import pathlib
import asyncio
import logging
import email.utils
import xml.etree.ElementTree as etree
from typing import (
TYPE_CHECKING,
Awaitable,
List,
Dict,
Any,
Optional,
Union
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..websockets import WebRequest
from .http_client import HttpClient
from .database import MoonrakerDatabase
MOONLIGHT_URL = "https://arksine.github.io/moonlight"
UPDATE_CHECK_TIME = 1800.
etree.register_namespace("moonlight", MOONLIGHT_URL)
class Announcements:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.entry_mgr = EntryManager(config)
self.eventloop = self.server.get_event_loop()
self.update_timer = self.eventloop.register_timer(
self._handle_update_timer
)
self.request_lock = asyncio.Lock()
self.dev_mode = config.getboolean("dev_mode", False)
self.subscriptions: Dict[str, RssFeed] = {
"moonraker": RssFeed("moonraker", self.entry_mgr, self.dev_mode),
"klipper": RssFeed("klipper", self.entry_mgr, self.dev_mode)
}
self.stored_feeds: List[str] = []
sub_list: List[str] = config.getlist("subscriptions", [])
self.configured_feeds: List[str] = ["moonraker", "klipper"]
for sub in sub_list:
sub = sub.lower()
if sub in self.subscriptions:
continue
self.configured_feeds.append(sub)
self.subscriptions[sub] = RssFeed(
sub, self.entry_mgr, self.dev_mode
)
self.server.register_endpoint(
"/server/announcements/list", ["GET"],
self._list_announcements
)
self.server.register_endpoint(
"/server/announcements/dismiss", ["POST"],
self._handle_dismiss_request
)
self.server.register_endpoint(
"/server/announcements/update", ["POST"],
self._handle_update_request
)
self.server.register_endpoint(
"/server/announcements/feed", ["POST", "DELETE"],
self._handle_feed_request
)
self.server.register_endpoint(
"/server/announcements/feeds", ["GET"],
self._handle_list_feeds
)
self.server.register_notification(
"announcements:dismissed", "announcement_dismissed"
)
self.server.register_notification(
"announcements:entries_updated", "announcement_update"
)
self.server.register_notification(
"announcements:dismiss_wake", "announcement_wake"
)
async def component_init(self) -> None:
db: MoonrakerDatabase = self.server.lookup_component("database")
stored_feeds: List[str] = await db.get_item(
"moonraker", "announcements.stored_feeds", []
)
self.stored_feeds = stored_feeds
for name in stored_feeds:
if name in self.subscriptions:
continue
feed = RssFeed(name, self.entry_mgr, self.dev_mode)
self.subscriptions[name] = feed
async with self.request_lock:
await self.entry_mgr.initialize()
for sub in self.subscriptions.values():
await sub.initialize()
self.update_timer.start()
async def _handle_update_timer(self, eventtime: float) -> float:
changed = False
entries: List[Dict[str, Any]] = []
async with self.request_lock:
for sub in self.subscriptions.values():
ret = await sub.update_entries()
changed |= ret
if changed:
entries = await self.entry_mgr.list_entries()
self.server.send_event(
"announcements:entries_updated", {"entries": entries}
)
return eventtime + UPDATE_CHECK_TIME
async def _handle_dismiss_request(
self, web_request: WebRequest
) -> Dict[str, Any]:
async with self.request_lock:
entry_id: str = web_request.get_str("entry_id")
wake_time: Optional[int] = web_request.get_int("wake_time", None)
await self.entry_mgr.dismiss_entry(entry_id, wake_time)
return {
"entry_id": entry_id
}
async def _list_announcements(
self, web_request: WebRequest
) -> Dict[str, Any]:
async with self.request_lock:
incl_dsm = web_request.get_boolean("include_dismissed", True)
entries = await self.entry_mgr.list_entries(incl_dsm)
return {
"entries": entries,
"feeds": list(self.subscriptions.keys())
}
async def _handle_update_request(
self, web_request: WebRequest
) -> Dict[str, Any]:
subs: Optional[Union[str, List[str]]]
subs = web_request.get("subscriptions", None)
if isinstance(subs, str):
subs = [sub.strip() for sub in subs.split(",") if sub.strip()]
elif subs is None:
subs = list(self.subscriptions.keys())
for sub in subs:
if sub not in self.subscriptions:
raise self.server.error(f"No subscription for {sub}")
async with self.request_lock:
changed = False
for sub in subs:
ret = await self.subscriptions[sub].update_entries()
changed |= ret
entries = await self.entry_mgr.list_entries()
if changed:
self.eventloop.delay_callback(
.05, self.server.send_event,
"announcements:entries_updated",
{"entries": entries})
return {
"entries": entries,
"modified": changed
}
async def _handle_list_feeds(
self, web_request: WebRequest
) -> Dict[str, Any]:
return {"feeds": list(self.subscriptions.keys())}
async def _handle_feed_request(
self, web_request: WebRequest
) -> Dict[str, Any]:
action = web_request.get_action()
name: str = web_request.get("name")
name = name.lower()
changed: bool = False
db: MoonrakerDatabase = self.server.lookup_component("database")
result = "skipped"
if action == "POST":
if name not in self.subscriptions:
feed = RssFeed(name, self.entry_mgr, self.dev_mode)
self.subscriptions[name] = feed
await feed.initialize()
changed = await feed.update_entries()
self.stored_feeds.append(name)
db.insert_item(
"moonraker", "announcements.stored_feeds", self.stored_feeds
)
result = "added"
elif action == "DELETE":
if name not in self.stored_feeds:
raise self.server.error(f"Feed '{name}' not stored")
if name in self.configured_feeds:
raise self.server.error(
f"Feed '{name}' exists in the configuration, cannot remove"
)
self.stored_feeds.remove(name)
db.insert_item(
"moonraker", "announcements.stored_feeds", self.stored_feeds
)
if name in self.subscriptions:
del self.subscriptions[name]
changed = await self.entry_mgr.prune_by_feed(name)
logging.info(f"Removed Announcement Feed: {name}")
result = "removed"
else:
raise self.server.error(f"Feed does not exist: {name}")
if changed:
entries = await self.entry_mgr.list_entries()
self.eventloop.delay_callback(
.05, self.server.send_event, "announcements:entries_updated",
{"entries": entries}
)
return {
"feed": name,
"action": result
}
def add_internal_announcement(
self, title: str, desc: str, url: str, priority: str, feed: str
) -> Dict[str, Any]:
date = datetime.datetime.utcnow()
entry_id: str = f"{feed}/{date.isoformat(timespec='seconds')}"
entry = {
"entry_id": entry_id,
"url": url,
"title": title,
"description": desc,
"priority": priority,
"date": date.timestamp(),
"dismissed": False,
"date_dismissed": None,
"dismiss_wake": None,
"source": "internal",
"feed": feed
}
self.entry_mgr.add_entry(entry)
return entry
async def remove_announcement(self, entry_id: str) -> None:
ret = await self.entry_mgr.remove_entry(entry_id)
if ret is not None:
entries = await self.entry_mgr.list_entries()
self.server.send_event(
"announcements:entries_updated", {"entries": entries}
)
async def dismiss_announcement(
self, entry_id, wake_time: Optional[int] = None
) -> None:
await self.entry_mgr.dismiss_entry(entry_id, wake_time)
async def get_announcements(
self, include_dismissed: bool = False
) -> List[Dict[str, Any]]:
return await self.entry_mgr.list_entries(include_dismissed)
def close(self):
self.entry_mgr.close()
class EntryManager:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
database: MoonrakerDatabase
database = self.server.lookup_component("database")
database.register_local_namespace("announcements")
self.announce_db = database.wrap_namespace("announcements")
self.entry_id_map: Dict[str, str] = {}
self.next_key = 0
self.dismiss_handles: Dict[str, asyncio.TimerHandle] = {}
async def initialize(self) -> None:
last_key = ""
eventloop = self.server.get_event_loop()
curtime = datetime.datetime.utcnow().timestamp()
for key, entry in await self.announce_db.items():
last_key = key
aid = entry["entry_id"]
self.entry_id_map[aid] = key
if entry["dismissed"]:
wake_time: Optional[float] = entry.get("dismiss_wake")
if wake_time is not None:
time_diff = wake_time - curtime
if time_diff - 10. < 0.:
# announcement is near or past wake time
entry["dismissed"] = False
entry["date_dismissed"] = None
entry["dismiss_wake"] = None
self.announce_db[key] = entry
else:
self.dismiss_handles[key] = eventloop.delay_callback(
time_diff, self._wake_dismissed, key
)
if last_key:
self.next_key = int(last_key, 16) + 1
async def list_entries(
self, include_dismissed: bool = True
) -> List[Dict[str, Any]]:
vals: List[Dict[str, Any]] = await self.announce_db.values()
vals = sorted(vals, key=lambda x: x["date"], reverse=True)
if include_dismissed:
return vals
return [val for val in vals if not val["dismissed"]]
def has_entry(self, entry_id: str) -> bool:
return entry_id in self.entry_id_map
def add_entry(self, entry: Dict[str, Any]) -> Awaitable[None]:
aid = entry["entry_id"]
key = f"{self.next_key:06X}"
self.next_key += 1
self.entry_id_map[aid] = key
return self.announce_db.insert(key, entry)
def remove_entry(self, entry_id: str) -> Awaitable[Any]:
key = self.entry_id_map.pop(entry_id, None)
if key is None:
raise self.server.error(f"No key matching entry id: {entry_id}")
return self.announce_db.pop(key, None)
async def dismiss_entry(
self, entry_id: str, wake_time: Optional[int] = None
) -> None:
key = self.entry_id_map.get(entry_id)
if key is None:
raise self.server.error(f"No key matching entry id: {entry_id}")
entry = await self.announce_db[key]
is_dismissed = entry["dismissed"]
if is_dismissed:
return
entry["dismissed"] = True
eventloop = self.server.get_event_loop()
curtime = datetime.datetime.utcnow().timestamp()
entry["date_dismissed"] = curtime
if wake_time is not None:
entry["dismiss_wake"] = curtime + wake_time
self.dismiss_handles[key] = eventloop.delay_callback(
wake_time, self._wake_dismissed, key
)
self.announce_db[key] = entry
eventloop.delay_callback(
.05, self.server.send_event, "announcements:dismissed",
{"entry_id": entry_id}
)
async def _wake_dismissed(self, key: str) -> None:
self.dismiss_handles.pop(key, None)
entry = await self.announce_db.get(key, None)
if entry is None:
return
if not entry["dismissed"]:
return
entry["dismissed"] = False
entry["date_dismissed"] = None
entry["dismiss_wake"] = None
self.announce_db[key] = entry
self.server.send_event(
"announcements:dismiss_wake", {"entry_id": entry["entry_id"]}
)
def prune_by_prefix(self, prefix: str, valid_ids: List[str]) -> bool:
del_keys: List[str] = []
for entry_id in list(self.entry_id_map.keys()):
if not entry_id.startswith(prefix) or entry_id in valid_ids:
continue
# Entry is no longer valid and should be removed
key = self.entry_id_map.pop(entry_id, None)
if key is not None:
del_keys.append(key)
if del_keys:
self.announce_db.delete_batch(del_keys)
return True
return False
async def prune_by_feed(self, feed: str) -> bool:
entries = await self.list_entries()
del_keys: List[str] = []
for entry in entries:
if entry["feed"].lower() == feed:
key = self.entry_id_map.pop(entry["entry_id"], None)
if key is not None:
del_keys.append(key)
if del_keys:
self.announce_db.delete_batch(del_keys)
return True
return False
def close(self):
for handle in self.dismiss_handles.values():
handle.cancel()
class RssFeed:
def __init__(
self, name: str, entry_mgr: EntryManager, dev_mode: bool
) -> None:
self.server = entry_mgr.server
self.name = name
self.entry_mgr = entry_mgr
self.client: HttpClient = self.server.lookup_component("http_client")
self.database: MoonrakerDatabase
self.database = self.server.lookup_component("database")
self.xml_file = f"{self.name}.xml"
self.asset_url = f"{MOONLIGHT_URL}/assets/{self.xml_file}"
self.last_modified: int = 0
self.etag: Optional[str] = None
self.dev_xml_path: Optional[pathlib.Path] = None
if dev_mode:
res_dir = pathlib.Path(__file__).parent.parent.parent.resolve()
res_path = res_dir.joinpath(".devel/announcement_xml")
self.dev_xml_path = res_path.joinpath(self.xml_file)
async def initialize(self) -> None:
self.etag = await self.database.get_item(
"moonraker", f"announcements.{self.name}.etag", None
)
async def update_entries(self) -> bool:
if self.dev_xml_path is None:
xml_data = await self._fetch_moonlight()
else:
xml_data = await self._fetch_local_folder()
if not xml_data:
return False
return self._parse_xml(xml_data)
async def _fetch_moonlight(self) -> str:
headers = {"Accept": "application/xml"}
if self.etag is not None:
headers["If-None-Match"] = self.etag
resp = await self.client.get(
self.asset_url, headers, attempts=5,
retry_pause_time=.5, enable_cache=False,
)
if resp.has_error():
logging.info(
f"Failed to update subscription '{self.name}': {resp.error}"
)
return ""
if resp.status_code == 304:
logging.debug(f"Content at {self.xml_file} not modified")
return ""
# update etag
self.etag = resp.etag
try:
if self.etag is not None:
self.database.insert_item(
"moonraker", f"announcements.{self.name}.etag", resp.etag
)
else:
self.database.delete_item(
"moonraker", f"announcements.{self.name}.etag",
)
except self.server.error:
pass
return resp.text
async def _fetch_local_folder(self) -> str:
if self.dev_xml_path is None:
return ""
if not self.dev_xml_path.is_file():
logging.info(f"No file at path {self.dev_xml_path}")
return ""
mtime = self.dev_xml_path.stat().st_mtime_ns
if mtime <= self.last_modified:
logging.debug(f"Content at {self.xml_file} not modified")
return ""
try:
eventloop = self.server.get_event_loop()
xml_data = await eventloop.run_in_thread(
self.dev_xml_path.read_text)
except Exception:
logging.exception(f"Unable read xml file {self.dev_xml_path}")
return ""
self.last_modified = mtime
return xml_data
def _parse_xml(self, xml_data: str) -> bool:
root = etree.fromstring(xml_data)
channel = root.find("channel")
if channel is None:
root_str = etree.tostring(root, encoding="unicode")
logging.debug(f"Feed {self.name}: no channel found\n{root_str}")
return False
# extract prefix
prefix = channel.findtext("title", "").lower()
if not prefix:
logging.info(f"Feed {self.name}: No prefix found")
items = channel.findall("item")
valid_ids: List[str] = []
changed: bool = False
for item in items:
guid = item.findtext("guid")
if guid is None:
item_str = etree.tostring(item, encoding="unicode")
logging.debug(f"Feed {self.name}: Invalid Item\n{item_str}")
continue
if not prefix:
# fall back to first guid prefix
prefix = "/".join(guid.split("/")[:2])
elif not guid.startswith(prefix):
logging.debug(
f"Feed {self.name}: Guid {guid} is not "
f"prefixed with {prefix}")
valid_ids.append(guid)
if self.entry_mgr.has_entry(guid):
continue
try:
rfc_date = item.findtext("pubDate", "")
dt = email.utils.parsedate_to_datetime(rfc_date)
except Exception:
dt = datetime.datetime.utcnow()
entry: Dict[str, Any] = {
"entry_id": guid,
"url": item.findtext("link"),
"title": item.findtext("title"),
"description": item.findtext("description"),
"priority": item.findtext("category"),
"date": dt.timestamp(),
"dismissed": False,
"date_dismissed": None,
"dismiss_wake": None,
"source": "moonlight",
"feed": self.name
}
changed = True
self.entry_mgr.add_entry(entry)
logging.debug(f"Feed {self.name}: found entries {valid_ids}")
if prefix:
pruned = self.entry_mgr.prune_by_prefix(prefix, valid_ids)
changed = changed or pruned
return changed
def load_component(config: ConfigHelper) -> Announcements:
return Announcements(config)
+874
View File
@@ -0,0 +1,874 @@
# API Key Based Authorization
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import asyncio
import base64
import uuid
import hashlib
import secrets
import os
import time
import datetime
import ipaddress
import re
import socket
import logging
import json
from tornado.web import HTTPError
from libnacl.sign import Signer, Verifier
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Tuple,
Set,
Optional,
Union,
Dict,
List,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..websockets import WebRequest, WebsocketManager
from tornado.httputil import HTTPServerRequest
from tornado.web import RequestHandler
from .database import MoonrakerDatabase as DBComp
from .ldap import MoonrakerLDAP
IPAddr = Union[ipaddress.IPv4Address, ipaddress.IPv6Address]
IPNetwork = Union[ipaddress.IPv4Network, ipaddress.IPv6Network]
OneshotToken = Tuple[IPAddr, Optional[Dict[str, Any]], asyncio.Handle]
# Helpers for base64url encoding and decoding
def base64url_encode(data: bytes) -> bytes:
return base64.urlsafe_b64encode(data).rstrip(b"=")
def base64url_decode(data: str) -> bytes:
pad_cnt = len(data) % 4
if pad_cnt:
data += "=" * (4 - pad_cnt)
return base64.urlsafe_b64decode(data)
ONESHOT_TIMEOUT = 5
TRUSTED_CONNECTION_TIMEOUT = 3600
PRUNE_CHECK_TIME = 300.
AUTH_SOURCES = ["moonraker", "ldap"]
HASH_ITER = 100000
API_USER = "_API_KEY_USER_"
TRUSTED_USER = "_TRUSTED_USER_"
RESERVED_USERS = [API_USER, TRUSTED_USER]
JWT_EXP_TIME = datetime.timedelta(hours=1)
JWT_HEADER = {
'alg': "EdDSA",
'typ': "JWT"
}
class Authorization:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.login_timeout = config.getint('login_timeout', 90)
self.force_logins = config.getboolean('force_logins', False)
self.default_source = config.get('default_source', "moonraker").lower()
self.enable_api_key = config.getboolean('enable_api_key', True)
self.max_logins = config.getint("max_login_attempts", None, above=0)
self.failed_logins: Dict[IPAddr, int] = {}
if self.default_source not in AUTH_SOURCES:
raise config.error(
"[authorization]: option 'default_source' - Invalid "
f"value '{self.default_source}'"
)
self.ldap: Optional[MoonrakerLDAP] = None
if config.has_section("ldap"):
self.ldap = self.server.load_component(config, "ldap", None)
if self.default_source == "ldap" and self.ldap is None:
self.server.add_warning(
"[authorization]: Option 'default_source' set to 'ldap',"
" however [ldap] section failed to load or not configured"
)
database: DBComp = self.server.lookup_component('database')
database.register_local_namespace('authorized_users', forbidden=True)
self.user_db = database.wrap_namespace('authorized_users')
self.users: Dict[str, Dict[str, Any]] = self.user_db.as_dict()
api_user: Optional[Dict[str, Any]] = self.users.get(API_USER, None)
if api_user is None:
self.api_key = uuid.uuid4().hex
self.users[API_USER] = {
'username': API_USER,
'api_key': self.api_key,
'created_on': time.time()
}
else:
self.api_key = api_user['api_key']
hi = self.server.get_host_info()
self.issuer = f"http://{hi['hostname']}:{hi['port']}"
self.public_jwks: Dict[str, Dict[str, Any]] = {}
for username, user_info in list(self.users.items()):
if username == API_USER:
# Validate the API User
for item in ["username", "api_key", "created_on"]:
if item not in user_info:
self.users[API_USER] = {
'username': API_USER,
'api_key': self.api_key,
'created_on': time.time()
}
break
continue
else:
# validate created users
valid = True
for item in ["username", "password", "salt", "created_on"]:
if item not in user_info:
logging.info(
f"Authorization: User {username} does not "
f"contain field {item}, removing")
del self.users[username]
valid = False
break
if not valid:
continue
# generate jwks for valid users
if 'jwt_secret' in user_info:
try:
priv_key = self._load_private_key(user_info['jwt_secret'])
jwk_id = user_info['jwk_id']
except (self.server.error, KeyError):
logging.info("Invalid key found for user, removing")
user_info.pop('jwt_secret', None)
user_info.pop('jwk_id', None)
self.users[username] = user_info
continue
self.public_jwks[jwk_id] = self._generate_public_jwk(priv_key)
# sync user changes to the database
self.user_db.sync(self.users)
self.trusted_users: Dict[IPAddr, Any] = {}
self.oneshot_tokens: Dict[str, OneshotToken] = {}
self.permitted_paths: Set[str] = set()
# Get allowed cors domains
self.cors_domains: List[str] = []
for domain in config.getlist('cors_domains', []):
bad_match = re.search(r"^.+\.[^:]*\*", domain)
if bad_match is not None:
raise config.error(
f"Unsafe CORS Domain '{domain}'. Wildcards are not"
" permitted in the top level domain.")
if domain.endswith("/"):
self.server.add_warning(
f"[authorization]: Invalid domain '{domain}' in option "
"'cors_domains'. Domain's cannot contain a trailing "
"slash.")
else:
self.cors_domains.append(
domain.replace(".", "\\.").replace("*", ".*"))
# Get Trusted Clients
self.trusted_ips: List[IPAddr] = []
self.trusted_ranges: List[IPNetwork] = []
self.trusted_domains: List[str] = []
for val in config.getlist('trusted_clients', []):
# Check IP address
try:
tc = ipaddress.ip_address(val)
except ValueError:
pass
else:
self.trusted_ips.append(tc)
continue
# Check ip network
try:
tn = ipaddress.ip_network(val)
except ValueError as e:
if "has host bits set" in str(e):
self.server.add_warning(
f"[authorization]: Invalid CIDR expression '{val}' "
"in option 'trusted_clients'")
continue
pass
else:
self.trusted_ranges.append(tn)
continue
# Check hostname
match = re.match(r"([a-z0-9]+(-[a-z0-9]+)*\.?)+[a-z]{2,}$", val)
if match is not None:
self.trusted_domains.append(val.lower())
else:
self.server.add_warning(
f"[authorization]: Invalid domain name '{val}' "
"in option 'trusted_clients'")
t_clients = "\n".join(
[str(ip) for ip in self.trusted_ips] +
[str(rng) for rng in self.trusted_ranges] +
self.trusted_domains)
c_domains = "\n".join(self.cors_domains)
logging.info(
f"Authorization Configuration Loaded\n"
f"Trusted Clients:\n{t_clients}\n"
f"CORS Domains:\n{c_domains}")
eventloop = self.server.get_event_loop()
self.prune_timer = eventloop.register_timer(
self._prune_conn_handler)
# Register Authorization Endpoints
self.permitted_paths.add("/server/redirect")
self.permitted_paths.add("/access/login")
self.permitted_paths.add("/access/refresh_jwt")
self.permitted_paths.add("/access/info")
self.server.register_endpoint(
"/access/login", ['POST'], self._handle_login,
transports=['http', 'websocket'])
self.server.register_endpoint(
"/access/logout", ['POST'], self._handle_logout,
transports=['http', 'websocket'])
self.server.register_endpoint(
"/access/refresh_jwt", ['POST'], self._handle_refresh_jwt,
transports=['http', 'websocket'])
self.server.register_endpoint(
"/access/user", ['GET', 'POST', 'DELETE'],
self._handle_user_request, transports=['http', 'websocket'])
self.server.register_endpoint(
"/access/users/list", ['GET'], self._handle_list_request,
transports=['http', 'websocket'])
self.server.register_endpoint(
"/access/user/password", ['POST'], self._handle_password_reset,
transports=['http', 'websocket'])
self.server.register_endpoint(
"/access/api_key", ['GET', 'POST'],
self._handle_apikey_request, transports=['http', 'websocket'])
self.server.register_endpoint(
"/access/oneshot_token", ['GET'],
self._handle_oneshot_request, transports=['http', 'websocket'])
self.server.register_endpoint(
"/access/info", ['GET'],
self._handle_info_request, transports=['http', 'websocket'])
wsm: WebsocketManager = self.server.lookup_component("websockets")
wsm.register_notification("authorization:user_created")
wsm.register_notification(
"authorization:user_deleted", event_type="logout"
)
wsm.register_notification(
"authorization:user_logged_out", event_type="logout"
)
def register_permited_path(self, path: str) -> None:
self.permitted_paths.add(path)
def is_path_permitted(self, path: str) -> bool:
return path in self.permitted_paths
def _sync_user(self, username: str) -> None:
self.user_db[username] = self.users[username]
async def component_init(self) -> None:
self.prune_timer.start(delay=PRUNE_CHECK_TIME)
async def _handle_apikey_request(self, web_request: WebRequest) -> str:
action = web_request.get_action()
if action.upper() == 'POST':
self.api_key = uuid.uuid4().hex
self.users[API_USER]['api_key'] = self.api_key
self._sync_user(API_USER)
return self.api_key
async def _handle_oneshot_request(self, web_request: WebRequest) -> str:
ip = web_request.get_ip_address()
assert ip is not None
user_info = web_request.get_current_user()
return self.get_oneshot_token(ip, user_info)
async def _handle_login(self, web_request: WebRequest) -> Dict[str, Any]:
ip = web_request.get_ip_address()
if ip is not None and self.check_logins_maxed(ip):
raise HTTPError(
401, "Unauthorized, Maximum Login Attempts Reached"
)
try:
ret = await self._login_jwt_user(web_request)
except asyncio.CancelledError:
raise
except Exception:
if ip is not None:
failed = self.failed_logins.get(ip, 0)
self.failed_logins[ip] = failed + 1
raise
if ip is not None:
self.failed_logins.pop(ip, None)
return ret
async def _handle_logout(self, web_request: WebRequest) -> Dict[str, str]:
user_info = web_request.get_current_user()
if user_info is None:
raise self.server.error("No user logged in")
username: str = user_info['username']
if username in RESERVED_USERS:
raise self.server.error(
f"Invalid log out request for user {username}")
self.users[username].pop("jwt_secret", None)
jwk_id: str = self.users[username].pop("jwk_id", None)
self._sync_user(username)
self.public_jwks.pop(jwk_id, None)
eventloop = self.server.get_event_loop()
eventloop.delay_callback(
.005, self.server.send_event, "authorization:user_logged_out",
{'username': username}
)
return {
"username": username,
"action": "user_logged_out"
}
async def _handle_info_request(
self, web_request: WebRequest
) -> Dict[str, Any]:
sources = ["moonraker"]
if self.ldap is not None:
sources.append("ldap")
return {
"default_source": self.default_source,
"available_sources": sources
}
async def _handle_refresh_jwt(self,
web_request: WebRequest
) -> Dict[str, str]:
refresh_token: str = web_request.get_str('refresh_token')
try:
user_info = self.decode_jwt(refresh_token, token_type="refresh")
except Exception:
raise self.server.error("Invalid Refresh Token", 401)
username: str = user_info['username']
if 'jwt_secret' not in user_info or "jwk_id" not in user_info:
raise self.server.error("User not logged in", 401)
private_key = self._load_private_key(user_info['jwt_secret'])
jwk_id: str = user_info['jwk_id']
token = self._generate_jwt(username, jwk_id, private_key)
return {
'username': username,
'token': token,
'source': user_info.get("source", "moonraker"),
'action': 'user_jwt_refresh'
}
async def _handle_user_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
action = web_request.get_action()
if action == "GET":
user = web_request.get_current_user()
if user is None:
return {
'username': None,
'source': None,
'created_on': None,
}
else:
return {
'username': user['username'],
'source': user.get("source", "moonraker"),
'created_on': user.get('created_on')
}
elif action == "POST":
# Create User
return await self._login_jwt_user(web_request, create=True)
elif action == "DELETE":
# Delete User
return self._delete_jwt_user(web_request)
raise self.server.error("Invalid Request Method")
async def _handle_list_request(self,
web_request: WebRequest
) -> Dict[str, List[Dict[str, Any]]]:
user_list = []
for user in self.users.values():
if user['username'] == API_USER:
continue
user_list.append({
'username': user['username'],
'source': user.get("source", "moonraker"),
'created_on': user['created_on']
})
return {
'users': user_list
}
async def _handle_password_reset(self,
web_request: WebRequest
) -> Dict[str, str]:
password: str = web_request.get_str('password')
new_pass: str = web_request.get_str('new_password')
user_info = web_request.get_current_user()
if user_info is None:
raise self.server.error("No Current User")
username = user_info['username']
if user_info.get("source", "moonraker") == "ldap":
raise self.server.error(
f"Can´t Reset password for ldap user {username}")
if username in RESERVED_USERS:
raise self.server.error(
f"Invalid Reset Request for user {username}")
salt = bytes.fromhex(user_info['salt'])
hashed_pass = hashlib.pbkdf2_hmac(
'sha256', password.encode(), salt, HASH_ITER).hex()
if hashed_pass != user_info['password']:
raise self.server.error("Invalid Password")
new_hashed_pass = hashlib.pbkdf2_hmac(
'sha256', new_pass.encode(), salt, HASH_ITER).hex()
self.users[username]['password'] = new_hashed_pass
self._sync_user(username)
return {
'username': username,
'action': "user_password_reset"
}
async def _login_jwt_user(
self, web_request: WebRequest, create: bool = False
) -> Dict[str, Any]:
username: str = web_request.get_str('username')
password: str = web_request.get_str('password')
source: str = web_request.get_str(
'source', self.default_source
).lower()
if source not in AUTH_SOURCES:
raise self.server.error(f"Invalid 'source': {source}")
user_info: Dict[str, Any]
if username in RESERVED_USERS:
raise self.server.error(
f"Invalid Request for user {username}")
if source == "ldap":
if create:
raise self.server.error("Cannot Create LDAP User")
if self.ldap is None:
raise self.server.error(
"LDAP authentication not available", 401
)
await self.ldap.authenticate_ldap_user(username, password)
if username not in self.users:
create = True
if create:
if username in self.users:
raise self.server.error(f"User {username} already exists")
salt = secrets.token_bytes(32)
hashed_pass = hashlib.pbkdf2_hmac(
'sha256', password.encode(), salt, HASH_ITER).hex()
user_info = {
'username': username,
'password': hashed_pass,
'salt': salt.hex(),
'source': source,
'created_on': time.time()
}
self.users[username] = user_info
self._sync_user(username)
action = "user_created"
if source == "ldap":
# Dont notify user created
action = "user_logged_in"
create = False
else:
if username not in self.users:
raise self.server.error(f"Unregistered User: {username}")
user_info = self.users[username]
auth_src = user_info.get("source", "moonraker")
if auth_src != source:
raise self.server.error(
f"Moonraker cannot authenticate user '{username}', must "
f"specify source '{auth_src}'", 401
)
salt = bytes.fromhex(user_info['salt'])
hashed_pass = hashlib.pbkdf2_hmac(
'sha256', password.encode(), salt, HASH_ITER).hex()
action = "user_logged_in"
if hashed_pass != user_info['password']:
raise self.server.error("Invalid Password")
jwt_secret_hex: Optional[str] = user_info.get('jwt_secret', None)
if jwt_secret_hex is None:
private_key = Signer()
jwk_id = base64url_encode(secrets.token_bytes()).decode()
user_info['jwt_secret'] = private_key.hex_seed().decode()
user_info['jwk_id'] = jwk_id
self.users[username] = user_info
self._sync_user(username)
self.public_jwks[jwk_id] = self._generate_public_jwk(private_key)
else:
private_key = self._load_private_key(jwt_secret_hex)
jwk_id = user_info['jwk_id']
token = self._generate_jwt(username, jwk_id, private_key)
refresh_token = self._generate_jwt(
username, jwk_id, private_key, token_type="refresh",
exp_time=datetime.timedelta(days=self.login_timeout))
conn = web_request.get_client_connection()
if create:
event_loop = self.server.get_event_loop()
event_loop.delay_callback(
.005, self.server.send_event,
"authorization:user_created",
{'username': username})
elif conn is not None:
conn.user_info = user_info
return {
'username': username,
'token': token,
'source': user_info.get("source", "moonraker"),
'refresh_token': refresh_token,
'action': action
}
def _delete_jwt_user(self, web_request: WebRequest) -> Dict[str, str]:
username: str = web_request.get_str('username')
current_user = web_request.get_current_user()
if current_user is not None:
curname = current_user.get('username', None)
if curname is not None and curname == username:
raise self.server.error(
f"Cannot delete logged in user {curname}")
if username in RESERVED_USERS:
raise self.server.error(
f"Invalid Request for reserved user {username}")
user_info: Optional[Dict[str, Any]] = self.users.get(username)
if user_info is None:
raise self.server.error(f"No registered user: {username}")
if 'jwk_id' in user_info:
self.public_jwks.pop(user_info['jwk_id'], None)
del self.users[username]
del self.user_db[username]
event_loop = self.server.get_event_loop()
event_loop.delay_callback(
.005, self.server.send_event,
"authorization:user_deleted",
{'username': username})
return {
"username": username,
"action": "user_deleted"
}
def _generate_jwt(self,
username: str,
jwk_id: str,
private_key: Signer,
token_type: str = "access",
exp_time: datetime.timedelta = JWT_EXP_TIME
) -> str:
curtime = int(time.time())
payload = {
'iss': self.issuer,
'aud': "Moonraker",
'iat': curtime,
'exp': curtime + int(exp_time.total_seconds()),
'username': username,
'token_type': token_type
}
header = {'kid': jwk_id}
header.update(JWT_HEADER)
jwt_header = base64url_encode(json.dumps(header).encode())
jwt_payload = base64url_encode(json.dumps(payload).encode())
jwt_msg = b".".join([jwt_header, jwt_payload])
sig = private_key.signature(jwt_msg)
jwt_sig = base64url_encode(sig)
return b".".join([jwt_msg, jwt_sig]).decode()
def decode_jwt(
self, token: str, token_type: str = "access"
) -> Dict[str, Any]:
message, sig = token.rsplit('.', maxsplit=1)
enc_header, enc_payload = message.split('.')
header: Dict[str, Any] = json.loads(base64url_decode(enc_header))
sig_bytes = base64url_decode(sig)
# verify header
if header.get('typ') != "JWT" or header.get('alg') != "EdDSA":
raise self.server.error("Invalid JWT header")
jwk_id = header.get('kid')
if jwk_id not in self.public_jwks:
raise self.server.error("Invalid key ID")
# validate signature
public_key = self._public_key_from_jwk(self.public_jwks[jwk_id])
public_key.verify(sig_bytes + message.encode())
# validate claims
payload: Dict[str, Any] = json.loads(base64url_decode(enc_payload))
if payload['token_type'] != token_type:
raise self.server.error(
f"JWT Token type mismatch: Expected {token_type}, "
f"Recd: {payload['token_type']}", 401)
if payload['iss'] != self.issuer:
raise self.server.error("Invalid JWT Issuer", 401)
if payload['aud'] != "Moonraker":
raise self.server.error("Invalid JWT Audience", 401)
if payload['exp'] < int(time.time()):
raise self.server.error("JWT Expired", 401)
# get user
user_info: Optional[Dict[str, Any]] = self.users.get(
payload.get('username', ""), None)
if user_info is None:
raise self.server.error("Unknown user", 401)
return user_info
def validate_jwt(self, token: str) -> Dict[str, Any]:
try:
user_info = self.decode_jwt(token)
except Exception as e:
if isinstance(e, self.server.error):
raise
raise self.server.error(
f"Failed to decode JWT: {e}", 401
) from e
return user_info
def validate_api_key(self, api_key: str) -> Dict[str, Any]:
if not self.enable_api_key:
raise self.server.error("API Key authentication is disabled", 401)
if api_key and api_key == self.api_key:
return self.users[API_USER]
raise self.server.error("Invalid API Key", 401)
def _load_private_key(self, secret: str) -> Signer:
try:
key = Signer(bytes.fromhex(secret))
except Exception:
raise self.server.error(
"Error decoding private key, user data may"
" be corrupt", 500) from None
return key
def _generate_public_jwk(self, private_key: Signer) -> Dict[str, Any]:
public_key = private_key.vk
return {
'x': base64url_encode(public_key).decode(),
'kty': "OKP",
'crv': "Ed25519",
'use': "sig"
}
def _public_key_from_jwk(self, jwk: Dict[str, Any]) -> Verifier:
if jwk.get('kty') != "OKP":
raise self.server.error("Not an Octet Key Pair")
if jwk.get('crv') != "Ed25519":
raise self.server.error("Invalid Curve")
if 'x' not in jwk:
raise self.server.error("No 'x' argument in jwk")
key = base64url_decode(jwk['x'])
return Verifier(key.hex().encode())
def _prune_conn_handler(self, eventtime: float) -> float:
cur_time = time.time()
for ip, user_info in list(self.trusted_users.items()):
exp_time: float = user_info['expires_at']
if cur_time >= exp_time:
self.trusted_users.pop(ip, None)
logging.info(
f"Trusted Connection Expired, IP: {ip}")
return eventtime + PRUNE_CHECK_TIME
def _oneshot_token_expire_handler(self, token):
self.oneshot_tokens.pop(token, None)
def get_oneshot_token(self,
ip_addr: IPAddr,
user: Optional[Dict[str, Any]]
) -> str:
token = base64.b32encode(os.urandom(20)).decode()
event_loop = self.server.get_event_loop()
hdl = event_loop.delay_callback(
ONESHOT_TIMEOUT, self._oneshot_token_expire_handler, token)
self.oneshot_tokens[token] = (ip_addr, user, hdl)
return token
def _check_json_web_token(self,
request: HTTPServerRequest
) -> Optional[Dict[str, Any]]:
auth_token: Optional[str] = request.headers.get("Authorization")
if auth_token is None:
auth_token = request.headers.get("X-Access-Token")
if auth_token is None:
qtoken = request.query_arguments.get('access_token', None)
if qtoken is not None:
auth_token = qtoken[-1].decode()
elif auth_token.startswith("Bearer "):
auth_token = auth_token[7:]
else:
return None
if auth_token:
try:
return self.decode_jwt(auth_token)
except Exception:
logging.exception(f"JWT Decode Error {auth_token}")
raise HTTPError(401, "JWT Decode Error")
return None
def _check_authorized_ip(self, ip: IPAddr) -> bool:
if ip in self.trusted_ips:
return True
for rng in self.trusted_ranges:
if ip in rng:
return True
fqdn = socket.getfqdn(str(ip)).lower()
if fqdn in self.trusted_domains:
return True
return False
def _check_trusted_connection(self,
ip: Optional[IPAddr]
) -> Optional[Dict[str, Any]]:
if ip is not None:
curtime = time.time()
exp_time = curtime + TRUSTED_CONNECTION_TIMEOUT
if ip in self.trusted_users:
self.trusted_users[ip]['expires_at'] = exp_time
return self.trusted_users[ip]
elif self._check_authorized_ip(ip):
logging.info(
f"Trusted Connection Detected, IP: {ip}")
self.trusted_users[ip] = {
'username': TRUSTED_USER,
'password': None,
'created_on': curtime,
'expires_at': exp_time
}
return self.trusted_users[ip]
return None
def _check_oneshot_token(self,
token: str,
cur_ip: Optional[IPAddr]
) -> Optional[Dict[str, Any]]:
if token in self.oneshot_tokens:
ip_addr, user, hdl = self.oneshot_tokens.pop(token)
hdl.cancel()
if cur_ip != ip_addr:
logging.info(f"Oneshot Token IP Mismatch: expected{ip_addr}"
f", Recd: {cur_ip}")
return None
return user
else:
return None
def check_logins_maxed(self, ip_addr: IPAddr) -> bool:
if self.max_logins is None:
return False
return self.failed_logins.get(ip_addr, 0) >= self.max_logins
def check_authorized(self,
request: HTTPServerRequest
) -> Optional[Dict[str, Any]]:
if (
request.path in self.permitted_paths
or request.method == "OPTIONS"
):
return None
# Check JSON Web Token
jwt_user = self._check_json_web_token(request)
if jwt_user is not None:
return jwt_user
try:
ip = ipaddress.ip_address(request.remote_ip) # type: ignore
except ValueError:
logging.exception(
f"Unable to Create IP Address {request.remote_ip}")
ip = None
# Check oneshot access token
ost: Optional[List[bytes]] = request.arguments.get('token', None)
if ost is not None:
ost_user = self._check_oneshot_token(ost[-1].decode(), ip)
if ost_user is not None:
return ost_user
# Check API Key Header
if self.enable_api_key:
key: Optional[str] = request.headers.get("X-Api-Key")
if key and key == self.api_key:
return self.users[API_USER]
# If the force_logins option is enabled and at least one
# user is created this is an unauthorized request
if self.force_logins and len(self.users) > 1:
raise HTTPError(401, "Unauthorized, Force Logins Enabled")
# Check if IP is trusted
trusted_user = self._check_trusted_connection(ip)
if trusted_user is not None:
return trusted_user
raise HTTPError(401, "Unauthorized")
def check_cors(self,
origin: Optional[str],
req_hdlr: Optional[RequestHandler] = None
) -> bool:
if origin is None or not self.cors_domains:
return False
for regex in self.cors_domains:
match = re.match(regex, origin)
if match is not None:
if match.group() == origin:
logging.debug(f"CORS Pattern Matched, origin: {origin} "
f" | pattern: {regex}")
self._set_cors_headers(origin, req_hdlr)
return True
else:
logging.debug(f"Partial Cors Match: {match.group()}")
else:
# Check to see if the origin contains an IP that matches a
# current trusted connection
match = re.search(r"^https?://([^/:]+)", origin)
if match is not None:
ip = match.group(1)
try:
ipaddr = ipaddress.ip_address(ip)
except ValueError:
pass
else:
if self._check_authorized_ip(ipaddr):
logging.debug(
f"Cors request matched trusted IP: {ip}")
self._set_cors_headers(origin, req_hdlr)
return True
logging.debug(f"No CORS match for origin: {origin}\n"
f"Patterns: {self.cors_domains}")
return False
def _set_cors_headers(self,
origin: str,
req_hdlr: Optional[RequestHandler]
) -> None:
if req_hdlr is None:
return
req_hdlr.set_header("Access-Control-Allow-Origin", origin)
if req_hdlr.request.method == "OPTIONS":
req_hdlr.set_header(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, OPTIONS")
req_hdlr.set_header(
"Access-Control-Allow-Headers",
"Origin, Accept, Content-Type, X-Requested-With, "
"X-CRSF-Token, Authorization, X-Access-Token, "
"X-Api-Key")
if req_hdlr.request.headers.get(
"Access-Control-Request-Private-Network", None) == "true":
req_hdlr.set_header(
"Access-Control-Allow-Private-Network",
"true")
def cors_enabled(self) -> bool:
return self.cors_domains is not None
def close(self) -> None:
self.prune_timer.stop()
def load_component(config: ConfigHelper) -> Authorization:
return Authorization(config)
+130
View File
@@ -0,0 +1,130 @@
# Support for GPIO Button actions
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import asyncio
import logging
from typing import (
TYPE_CHECKING,
Any,
Dict
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from .gpio import GpioFactory
from ..app import InternalTransport as ITransport
class ButtonManager:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.buttons: Dict[str, GpioButton] = {}
prefix_sections = config.get_prefix_sections("button")
logging.info(f"Loading Buttons: {prefix_sections}")
for section in prefix_sections:
cfg = config[section]
# Reserve the "type" option for future use
btn_type = cfg.get('type', "gpio")
try:
btn = GpioButton(cfg)
except Exception as e:
msg = f"Failed to load button [{cfg.get_name()}]\n{e}"
self.server.add_warning(msg)
continue
self.buttons[btn.name] = btn
self.server.register_notification("button:button_event")
def component_init(self) -> None:
for btn in self.buttons.values():
btn.initialize()
class GpioButton:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.eventloop = self.server.get_event_loop()
self.name = config.get_name().split()[-1]
self.itransport: ITransport = self.server.lookup_component(
'internal_transport')
self.mutex = asyncio.Lock()
gpio: GpioFactory = self.server.load_component(config, 'gpio')
self.gpio_event = gpio.register_gpio_event(
config.get('pin'), self._on_gpio_event)
min_event_time = config.getfloat(
'minimum_event_time', .05, minval=.010)
self.gpio_event.setup_debounce(min_event_time, self._on_gpio_error)
self.press_template = config.gettemplate(
"on_press", None, is_async=True)
self.release_template = config.gettemplate(
"on_release", None, is_async=True)
if (
self.press_template is None and
self.release_template is None
):
raise config.error(
f"[{config.get_name()}]: No template option configured")
self.notification_sent: bool = False
self.user_data: Dict[str, Any] = {}
self.context: Dict[str, Any] = {
'call_method': self.itransport.call_method,
'send_notification': self._send_notification,
'event': {
'elapsed_time': 0.,
'received_time': 0.,
'render_time': 0.,
'pressed': False,
},
'user_data': self.user_data
}
def initialize(self) -> None:
self.gpio_event.start()
self.context['event']['pressed'] = bool(self.gpio_event.get_value())
def get_status(self) -> Dict[str, Any]:
return {
'name': self.name,
'type': "gpio",
'event': self.context['event'],
}
def _send_notification(self, result: Any = None) -> None:
if self.notification_sent:
# Only allow execution once per template
return
self.notification_sent = True
data = self.get_status()
data['aux'] = result
self.server.send_event("button:button_event", data)
async def _on_gpio_event(self,
eventtime: float,
elapsed_time: float,
pressed: int
) -> None:
template = self.press_template if pressed else self.release_template
if template is None:
return
async with self.mutex:
self.notification_sent = False
event_info: Dict[str, Any] = {
'elapsed_time': elapsed_time,
'received_time': eventtime,
'render_time': self.eventloop.get_loop_time(),
'pressed': bool(pressed)
}
self.context['event'] = event_info
try:
await template.render_async(self.context)
except Exception:
action = "on_press" if pressed else "on_release"
logging.exception(
f"Button {self.name}: '{action}' template error")
def _on_gpio_error(self, message: str) -> None:
self.server.add_warning(f"Button {self.name}: {message}")
def load_component(config: ConfigHelper) -> ButtonManager:
return ButtonManager(config)
+53 -23
View File
@@ -3,25 +3,44 @@
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import logging
import time
from collections import deque
from tornado.ioloop import IOLoop, PeriodicCallback
TEMPERATURE_UPDATE_MS = 1000
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Optional,
Dict,
List,
Tuple,
Deque,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..websockets import WebRequest
from .klippy_apis import KlippyAPI as APIComp
GCQueue = Deque[Dict[str, Any]]
TempStore = Dict[str, Dict[str, Deque[float]]]
TEMP_UPDATE_TIME = 1.
class DataStore:
def __init__(self, config):
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.temp_store_size = config.getint('temperature_store_size', 1200)
self.gcode_store_size = config.getint('gcode_store_size', 1000)
# Temperature Store Tracking
self.last_temps = {}
self.gcode_queue = deque(maxlen=self.gcode_store_size)
self.temperature_store = {}
self.temp_update_cb = PeriodicCallback(
self._update_temperature_store, TEMPERATURE_UPDATE_MS)
self.last_temps: Dict[str, Tuple[float, ...]] = {}
self.gcode_queue: GCQueue = deque(maxlen=self.gcode_store_size)
self.temperature_store: TempStore = {}
eventloop = self.server.get_event_loop()
self.temp_update_timer = eventloop.register_timer(
self._update_temperature_store)
# Register status update event
self.server.register_event_handler(
@@ -30,6 +49,9 @@ class DataStore:
"server:gcode_response", self._update_gcode_store)
self.server.register_event_handler(
"server:klippy_ready", self._init_sensors)
self.server.register_event_handler(
"klippy_connection:gcode_received", self._store_gcode_command
)
# Register endpoints
self.server.register_endpoint(
@@ -39,26 +61,29 @@ class DataStore:
"/server/gcode_store", ['GET'],
self._handle_gcode_store_request)
async def _init_sensors(self):
klippy_apis = self.server.lookup_component('klippy_apis')
async def _init_sensors(self) -> None:
klippy_apis: APIComp = self.server.lookup_component('klippy_apis')
# Fetch sensors
try:
result: Dict[str, Any]
result = await klippy_apis.query_objects({'heaters': None})
except self.server.error as e:
logging.info(f"Error Configuring Sensors: {e}")
return
sensors: List[str]
sensors = result.get("heaters", {}).get("available_sensors", [])
if sensors:
# Add Subscription
sub = {s: None for s in sensors}
sub: Dict[str, Optional[List[str]]] = {s: None for s in sensors}
try:
status: Dict[str, Any]
status = await klippy_apis.subscribe_objects(sub)
except self.server.error as e:
logging.info(f"Error subscribing to sensors: {e}")
return
logging.info(f"Configuring available sensors: {sensors}")
new_store = {}
new_store: TempStore = {}
for sensor in sensors:
fields = list(status.get(sensor, {}).keys())
if sensor in self.temperature_store:
@@ -79,14 +104,14 @@ class DataStore:
del self.last_temps[sensor]
# Update initial temperatures
self._set_current_temps(status)
self.temp_update_cb.start()
self.temp_update_timer.start()
else:
logging.info("No sensors found")
self.last_temps = {}
self.temperature_store = {}
self.temp_update_cb.stop()
self.temp_update_timer.stop()
def _set_current_temps(self, data):
def _set_current_temps(self, data: Dict[str, Any]) -> None:
for sensor in self.temperature_store:
if sensor in data:
last_val = self.last_temps[sensor]
@@ -96,7 +121,7 @@ class DataStore:
data[sensor].get('power', last_val[2]),
data[sensor].get('speed', last_val[3]))
def _update_temperature_store(self):
def _update_temperature_store(self, eventtime: float) -> float:
# XXX - If klippy is not connected, set values to zero
# as they are unknown?
for sensor, vals in self.last_temps.items():
@@ -104,22 +129,25 @@ class DataStore:
for val, item in zip(vals[1:], ["targets", "powers", "speeds"]):
if item in self.temperature_store[sensor]:
self.temperature_store[sensor][item].append(val)
return eventtime + TEMP_UPDATE_TIME
async def _handle_temp_store_request(self, web_request):
async def _handle_temp_store_request(self,
web_request: WebRequest
) -> Dict[str, Dict[str, List[float]]]:
store = {}
for name, sensor in self.temperature_store.items():
store[name] = {k: list(v) for k, v in sensor.items()}
return store
async def close(self):
self.temp_update_cb.stop()
async def close(self) -> None:
self.temp_update_timer.stop()
def _update_gcode_store(self, response):
def _update_gcode_store(self, response: str) -> None:
curtime = time.time()
self.gcode_queue.append(
{'message': response, 'time': curtime, 'type': "response"})
def store_gcode_command(self, script):
def _store_gcode_command(self, script: str) -> None:
curtime = time.time()
for cmd in script.split('\n'):
cmd = cmd.strip()
@@ -128,7 +156,9 @@ class DataStore:
self.gcode_queue.append(
{'message': script, 'time': curtime, 'type': "command"})
async def _handle_gcode_store_request(self, web_request):
async def _handle_gcode_store_request(self,
web_request: WebRequest
) -> Dict[str, List[Dict[str, Any]]]:
count = web_request.get_int("count", None)
if count is not None:
gc_responses = list(self.gcode_queue)[-count:]
@@ -136,5 +166,5 @@ class DataStore:
gc_responses = list(self.gcode_queue)
return {'gcode_store': gc_responses}
def load_component(config):
def load_component(config: ConfigHelper) -> DataStore:
return DataStore(config)
File diff suppressed because it is too large. Load diff
+136
View File
@@ -0,0 +1,136 @@
# DBus Connection Management
#
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import os
import pathlib
import logging
import dbus_next
from dbus_next.aio import MessageBus, ProxyInterface
from dbus_next.constants import BusType
# Annotation imports
from typing import (
TYPE_CHECKING,
List,
Optional,
Any,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
STAT_PATH = "/proc/self/stat"
DOC_URL = (
"https://moonraker.readthedocs.io/en/latest/"
"installation/#policykit-permissions"
)
class DbusManager:
Variant = dbus_next.Variant
DbusError = dbus_next.errors.DBusError
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.bus: Optional[MessageBus] = None
self.polkit: Optional[ProxyInterface] = None
self.warned: bool = False
st_path = pathlib.Path(STAT_PATH)
self.polkit_subject: List[Any] = []
if not st_path.is_file():
return
proc_data = st_path.read_text()
start_clk_ticks = int(proc_data.split()[21])
self.polkit_subject = [
"unix-process",
{
"pid": dbus_next.Variant("u", os.getpid()),
"start-time": dbus_next.Variant("t", start_clk_ticks)
}
]
def is_connected(self) -> bool:
return self.bus is not None and self.bus.connected
async def component_init(self) -> None:
try:
self.bus = MessageBus(bus_type=BusType.SYSTEM)
await self.bus.connect()
except Exception:
logging.info("Unable to Connect to D-Bus")
return
# Make sure that all required actions are register
try:
self.polkit = await self.get_interface(
"org.freedesktop.PolicyKit1",
"/org/freedesktop/PolicyKit1/Authority",
"org.freedesktop.PolicyKit1.Authority")
except self.DbusError:
self.server.add_warning(
"Unable to find DBus PolKit Interface, this suggests PolKit "
"is not installed on your OS.")
async def check_permission(self,
action: str,
err_msg: str = ""
) -> bool:
if self.polkit is None:
return False
try:
ret = await self.polkit.call_check_authorization( # type: ignore
self.polkit_subject, action, {}, 0, "")
except Exception as e:
self._check_warned()
self.server.add_warning(
f"Error checking authorization for action [{action}]: {e}. "
"This suggests that a dependency is not installed or "
f"up to date. {err_msg}.")
return False
if not ret[0]:
self._check_warned()
self.server.add_warning(
"Moonraker not authorized for PolicyKit action: "
f"[{action}], {err_msg}")
return ret[0]
def _check_warned(self):
if not self.warned:
self.server.add_warning(
f"PolKit warnings detected. See {DOC_URL} for instructions "
"on how to resolve.")
self.warned = True
async def get_interface(self,
bus_name: str,
bus_path: str,
interface_name: str
) -> ProxyInterface:
ret = await self.get_interfaces(bus_name, bus_path,
[interface_name])
return ret[0]
async def get_interfaces(self,
bus_name: str,
bus_path: str,
interface_names: List[str]
) -> List[ProxyInterface]:
if self.bus is None:
raise self.server.error("Bus not avaialable")
interfaces: List[ProxyInterface] = []
introspection = await self.bus.introspect(bus_name, bus_path)
proxy_obj = self.bus.get_proxy_object(bus_name, bus_path,
introspection)
for ifname in interface_names:
intf = proxy_obj.get_interface(ifname)
interfaces.append(intf)
return interfaces
async def close(self):
if self.bus is not None and self.bus.connected:
self.bus.disconnect()
await self.bus.wait_for_disconnect()
def load_component(config: ConfigHelper) -> DbusManager:
return DbusManager(config)
+237
View File
@@ -0,0 +1,237 @@
# Moonraker extension management
#
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import asyncio
import pathlib
import logging
import json
from ..websockets import BaseSocketClient
from ..utils import get_unix_peer_credentials
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
Optional,
Union,
)
if TYPE_CHECKING:
from ..server import Server
from ..confighelper import ConfigHelper
from ..websockets import WebRequest
from ..klippy_connection import KlippyConnection as Klippy
UNIX_BUFFER_LIMIT = 20 * 1024 * 1024
class ExtensionManager:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.agents: Dict[str, BaseSocketClient] = {}
self.uds_server: Optional[asyncio.AbstractServer] = None
self.server.register_endpoint(
"/connection/send_event", ["POST"], self._handle_agent_event,
transports=["websocket"]
)
self.server.register_endpoint(
"/server/extensions/list", ["GET"], self._handle_list_extensions
)
self.server.register_endpoint(
"/server/extensions/request", ["POST"], self._handle_call_agent
)
def register_agent(self, connection: BaseSocketClient) -> None:
data = connection.client_data
name = data["name"]
client_type = data["type"]
if client_type != "agent":
raise self.server.error(
f"Cannot register client type '{client_type}' as an agent"
)
if name in self.agents:
raise self.server.error(
f"Agent '{name}' already registered and connected'"
)
self.agents[name] = connection
data = connection.client_data
evt: Dict[str, Any] = {
"agent": name, "event": "connected", "data": data
}
connection.send_notification("agent_event", [evt])
def remove_agent(self, connection: BaseSocketClient) -> None:
name = connection.client_data["name"]
if name in self.agents:
del self.agents[name]
evt: Dict[str, Any] = {"agent": name, "event": "disconnected"}
connection.send_notification("agent_event", [evt])
async def _handle_agent_event(self, web_request: WebRequest) -> str:
conn = web_request.get_client_connection()
if conn is None:
raise self.server.error("No connection detected")
if conn.client_data["type"] != "agent":
raise self.server.error(
"Only connections of the 'agent' type can send events"
)
name = conn.client_data["name"]
evt_name = web_request.get_str("event")
if evt_name in ["connected", "disconnected"]:
raise self.server.error(f"Event '{evt_name}' is reserved")
data: Optional[Union[List, Dict[str, Any]]]
data = web_request.get("data", None)
evt: Dict[str, Any] = {"agent": name, "event": evt_name}
if data is not None:
evt["data"] = data
conn.send_notification("agent_event", [evt])
return "ok"
async def _handle_list_extensions(
self, web_request: WebRequest
) -> Dict[str, List[Dict[str, Any]]]:
agents: List[Dict[str, Any]]
agents = [agt.client_data for agt in self.agents.values()]
return {"agents": agents}
async def _handle_call_agent(self, web_request: WebRequest) -> Any:
agent = web_request.get_str("agent")
method: str = web_request.get_str("method")
args: Optional[Union[List, Dict[str, Any]]]
args = web_request.get("arguments", None)
if args is not None and not isinstance(args, (list, dict)):
raise self.server.error(
"The 'arguments' field must contain an object or a list"
)
if agent not in self.agents:
raise self.server.error(f"Agent {agent} not connected")
conn = self.agents[agent]
return await conn.call_method(method, args)
async def start_unix_server(self) -> None:
data_path = pathlib.Path(self.server.get_app_args()["data_path"])
comms_path = data_path.joinpath("comms")
if not comms_path.exists():
comms_path.mkdir()
sock_path = comms_path.joinpath("moonraker.sock")
logging.info(f"Creating Unix Domain Socket at '{sock_path}'")
self.uds_server = await asyncio.start_unix_server(
self.on_unix_socket_connected, sock_path, limit=UNIX_BUFFER_LIMIT
)
def on_unix_socket_connected(
self, reader: asyncio.StreamReader, writer: asyncio.StreamWriter
) -> None:
peercred = get_unix_peer_credentials(writer, "Unix Client Connection")
UnixSocketClient(self.server, reader, writer, peercred)
async def close(self) -> None:
if self.uds_server is not None:
self.uds_server.close()
await self.uds_server.wait_closed()
self.uds_server = None
class UnixSocketClient(BaseSocketClient):
def __init__(
self,
server: Server,
reader: asyncio.StreamReader,
writer: asyncio.StreamWriter,
peercred: Dict[str, int]
) -> None:
self.on_create(server)
self.writer = writer
self._peer_cred = peercred
self._connected_time = self.eventloop.get_loop_time()
pid = self._peer_cred.get("process_id")
uid = self._peer_cred.get("user_id")
gid = self._peer_cred.get("group_id")
self.wsm.add_client(self)
logging.info(
f"Unix Socket Opened - Client ID: {self.uid}, "
f"Process ID: {pid}, User ID: {uid}, Group ID: {gid}"
)
self.eventloop.register_callback(self._read_messages, reader)
async def _read_messages(self, reader: asyncio.StreamReader) -> None:
errors_remaining: int = 10
while not reader.at_eof():
try:
data = await reader.readuntil(b'\x03')
decoded = data[:-1].decode(encoding="utf-8")
except (ConnectionError, asyncio.IncompleteReadError):
break
except asyncio.CancelledError:
logging.exception("Unix Client Stream Read Cancelled")
raise
except Exception:
logging.exception("Unix Client Stream Read Error")
errors_remaining -= 1
if not errors_remaining or self.is_closed:
break
continue
errors_remaining = 10
self.eventloop.register_callback(self._process_message, decoded)
logging.debug("Unix Socket Disconnection From _read_messages()")
await self._on_close(reason="Read Exit")
async def write_to_socket(
self, message: Union[str, Dict[str, Any]]
) -> None:
if isinstance(message, dict):
data = json.dumps(message).encode() + b"\x03"
else:
data = message.encode() + b"\x03"
try:
self.writer.write(data)
await self.writer.drain()
except asyncio.CancelledError:
raise
except Exception:
logging.debug("Unix Socket Disconnection From write_to_socket()")
await self._on_close(reason="Write Exception")
async def _on_close(
self,
code: Optional[int] = None,
reason: Optional[str] = None
) -> None:
if self.is_closed:
return
self.is_closed = True
kconn: Klippy = self.server.lookup_component("klippy_connection")
kconn.remove_subscription(self)
if not self.writer.is_closing():
self.writer.close()
try:
await self.writer.wait_closed()
except Exception:
pass
self.message_buf = []
for resp in self.pending_responses.values():
resp.set_exception(
self.server.error("Client Socket Disconnected", 500)
)
self.pending_responses = {}
logging.info(
f"Unix Socket Closed: ID: {self.uid}, "
f"Close Code: {code}, "
f"Close Reason: {reason}"
)
if self._client_data["type"] == "agent":
extensions: ExtensionManager
extensions = self.server.lookup_component("extensions")
extensions.remove_agent(self)
self.wsm.remove_client(self)
def close_socket(self, code: int, reason: str) -> None:
if not self.is_closed:
self.eventloop.register_callback(self._on_close, code, reason)
def load_component(config: ConfigHelper) -> ExtensionManager:
return ExtensionManager(config)
-768
View File
@@ -1,768 +0,0 @@
# Enhanced gcode file management and analysis
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import os
import sys
import shutil
import zipfile
import logging
import json
import tempfile
from concurrent.futures import ThreadPoolExecutor
from tornado.ioloop import IOLoop, PeriodicCallback
from tornado.locks import Event
VALID_GCODE_EXTS = ['.gcode', '.g', '.gco', '.ufp', '.nc']
FULL_ACCESS_ROOTS = ["gcodes", "config"]
METADATA_SCRIPT = os.path.abspath(os.path.join(
os.path.dirname(__file__), "../../scripts/extract_metadata.py"))
UFP_MODEL_PATH = "/3D/model.gcode"
UFP_THUMB_PATH = "/Metadata/thumbnail.png"
class FileManager:
def __init__(self, config):
self.server = config.get_server()
self.file_paths = {}
database = self.server.load_component(config, "database")
gc_path = database.get_item("moonraker", "file_manager.gcode_path", "")
self.gcode_metadata = MetadataStorage(self.server, gc_path, database)
self.fixed_path_args = {}
# Register file management endpoints
self.server.register_endpoint(
"/server/files/list", ['GET'], self._handle_filelist_request)
self.server.register_endpoint(
"/server/files/metadata", ['GET'], self._handle_metadata_request)
self.server.register_endpoint(
"/server/files/directory", ['GET', 'POST', 'DELETE'],
self._handle_directory_request)
self.server.register_endpoint(
"/server/files/move", ['POST'], self._handle_file_move_copy)
self.server.register_endpoint(
"/server/files/copy", ['POST'], self._handle_file_move_copy)
self.server.register_endpoint(
"/server/files/delete_file", ['DELETE'], self._handle_file_delete,
protocol=["websocket"])
# register client notificaitons
self.server.register_notification("file_manager:filelist_changed")
self.server.register_notification("file_manager:metadata_update")
# Register APIs to handle file uploads
self.server.register_upload_handler("/server/files/upload")
self.server.register_upload_handler("/api/files/local")
self.server.register_event_handler(
"server:klippy_identified", self._update_fixed_paths)
# Register Klippy Configuration Path
config_path = config.get('config_path', None)
if config_path is not None:
ret = self.register_directory('config', config_path)
if not ret:
raise config.error(
"Option 'config_path' is not a valid directory")
# If gcode path is in the database, register it
if gc_path:
self.register_directory('gcodes', gc_path)
def _update_fixed_paths(self):
kinfo = self.server.get_klippy_info()
paths = {k: kinfo.get(k) for k in
['klipper_path', 'python_path',
'log_file', 'config_file']}
if paths == self.fixed_path_args:
# No change in fixed paths
return
self.fixed_path_args = paths
str_paths = "\n".join([f"{k}: {v}" for k, v in paths.items()])
logging.debug(f"\nUpdating Fixed Paths:\n{str_paths}")
# Register path for example configs
klipper_path = paths.get('klipper_path', None)
if klipper_path is not None:
example_cfg_path = os.path.join(klipper_path, "config")
self.register_directory("config_examples", example_cfg_path)
docs_path = os.path.join(klipper_path, "docs")
self.register_directory("docs", docs_path)
# Register log path
log_file = paths.get('log_file')
if log_file is not None:
log_path = os.path.abspath(os.path.expanduser(log_file))
self.server.register_static_file_handler(
"klippy.log", log_path, force=True)
def register_directory(self, root, path):
if path is None:
return False
path = os.path.abspath(os.path.expanduser(path))
if os.path.islink(path):
path = os.path.realpath(path)
if not os.path.isdir(path) or path == "/":
logging.info(
f"\nSupplied path ({path}) for ({root}) a valid. Make sure\n"
"that the path exists and is not the file system root.")
return False
permissions = os.R_OK
if root in FULL_ACCESS_ROOTS:
permissions |= os.W_OK
if not os.access(path, permissions):
logging.info(
f"\nMoonraker does not have permission to access path "
f"({path}) for ({root}).")
return False
if path != self.file_paths.get(root, ""):
self.file_paths[root] = path
self.server.register_static_file_handler(root, path)
if root == "gcodes":
database = self.server.lookup_component(
"database").wrap_namespace("moonraker")
database["file_manager.gcode_path"] = path
# scan for metadata changes
self.gcode_metadata.update_gcode_path(path)
try:
self.get_file_list("gcodes")
except Exception:
logging.exception(
f"Unable to initialize gcode metadata")
return True
def get_sd_directory(self):
return self.file_paths.get('gcodes', "")
def get_registered_dirs(self):
return list(self.file_paths.keys())
def get_fixed_path_args(self):
return dict(self.fixed_path_args)
def check_file_exists(self, root, filename):
root_dir = self.file_paths.get(root, "")
file_path = os.path.join(root_dir, filename)
return os.path.exists(file_path)
async def _handle_filelist_request(self, web_request):
root = web_request.get_str('root', "gcodes")
return self.get_file_list(root, list_format=True, notify=True)
async def _handle_metadata_request(self, web_request):
requested_file = web_request.get_str('filename')
metadata = self.gcode_metadata.get(requested_file, None)
if metadata is None:
raise self.server.error(
f"Metadata not available for <{requested_file}>", 404)
metadata['filename'] = requested_file
return metadata
async def _handle_directory_request(self, web_request):
directory = web_request.get_str('path', "gcodes")
root, rel_path, dir_path = self._convert_path(directory)
action = web_request.get_action()
if action == 'GET':
is_extended = web_request.get_boolean('extended', False)
# Get list of files and subdirectories for this target
dir_info = self._list_directory(dir_path, is_extended)
return dir_info
elif action == 'POST' and root in FULL_ACCESS_ROOTS:
# Create a new directory
try:
os.mkdir(dir_path)
except Exception as e:
raise self.server.error(str(e))
self.notify_filelist_changed("create_dir", rel_path, root)
elif action == 'DELETE' and root in FULL_ACCESS_ROOTS:
# Remove a directory
if directory.strip("/") == root:
raise self.server.error(
"Cannot delete root directory")
if not os.path.isdir(dir_path):
raise self.server.error(
f"Directory does not exist ({directory})")
force = web_request.get_boolean('force', False)
if force:
# Make sure that the directory does not contain a file
# loaded by the virtual_sdcard
await self._handle_operation_check(dir_path)
shutil.rmtree(dir_path)
if root == "gcodes":
self.gcode_metadata.prune_metadata()
else:
try:
os.rmdir(dir_path)
except Exception as e:
raise self.server.error(str(e))
self.notify_filelist_changed("delete_dir", rel_path, root)
else:
raise self.server.error("Operation Not Supported", 405)
return "ok"
async def _handle_operation_check(self, requested_path):
# Get virtual_sdcard status
klippy_apis = self.server.lookup_component('klippy_apis')
result = await klippy_apis.query_objects({'print_stats': None})
pstats = result.get('print_stats', {})
loaded_file = pstats.get('filename', "")
state = pstats.get('state', "")
gc_path = self.file_paths.get('gcodes', "")
full_path = os.path.join(gc_path, loaded_file)
if loaded_file and state != "complete":
if os.path.isdir(requested_path):
# Check to see of the loaded file is in the request
if full_path.startswith(requested_path):
raise self.server.error("File currently in use", 403)
elif full_path == requested_path:
raise self.server.error("File currently in use", 403)
ongoing = state in ["printing", "paused"]
return ongoing
def _convert_path(self, request_path):
# Parse the root, relative path, and disk path from a remote request
parts = request_path.strip("/").split("/")
if not parts:
raise self.server.error(f"Invalid path: {request_path}")
root = parts[0]
if root not in self.file_paths:
raise self.server.error(f"Invalid root path ({root})")
disk_path = self.file_paths[root]
rel_path = ""
if len(parts) > 1:
rel_path = "/".join(parts[1:])
disk_path = os.path.join(disk_path, rel_path)
return root, rel_path, disk_path
async def _handle_file_move_copy(self, web_request):
source = web_request.get_str("source")
destination = web_request.get_str("dest")
ep = web_request.get_endpoint()
if source is None:
raise self.server.error("File move/copy request issing source")
if destination is None:
raise self.server.error(
"File move/copy request missing destination")
source_root, src_rel_path, source_path = self._convert_path(source)
dest_root, dst_rel_path, dest_path = self._convert_path(destination)
if dest_root not in FULL_ACCESS_ROOTS:
raise self.server.error(
f"Destination path is read-only: {dest_root}")
if not os.path.exists(source_path):
raise self.server.error(f"File {source_path} does not exist")
# make sure the destination is not in use
if os.path.exists(dest_path):
await self._handle_operation_check(dest_path)
action = op_result = ""
if ep == "/server/files/move":
if source_root not in FULL_ACCESS_ROOTS:
raise self.server.error(
f"Source path is read-only, cannot move: {source_root}")
# if moving the file, make sure the source is not in use
await self._handle_operation_check(source_path)
try:
op_result = shutil.move(source_path, dest_path)
except Exception as e:
raise self.server.error(str(e))
if source_root == "gcodes":
if os.path.isdir(op_result):
self.gcode_metadata.prune_metadata()
else:
self.gcode_metadata.remove_file(src_rel_path)
action = "move_item"
elif ep == "/server/files/copy":
try:
if os.path.isdir(source_path):
op_result = shutil.copytree(source_path, dest_path)
else:
op_result = shutil.copy2(source_path, dest_path)
except Exception as e:
raise self.server.error(str(e))
action = "copy_item"
if op_result != dest_path:
dst_rel_path = os.path.join(
dst_rel_path, os.path.basename(op_result))
self.notify_filelist_changed(
action, dst_rel_path, dest_root,
{'path': src_rel_path, 'root': source_root})
return "ok"
def _list_directory(self, path, is_extended=False):
if not os.path.isdir(path):
raise self.server.error(
f"Directory does not exist ({path})")
flist = {'dirs': [], 'files': []}
for fname in os.listdir(path):
full_path = os.path.join(path, fname)
if not os.path.exists(full_path):
continue
path_info = self._get_path_info(full_path)
if os.path.isdir(full_path):
path_info['dirname'] = fname
flist['dirs'].append(path_info)
elif os.path.isfile(full_path):
path_info['filename'] = fname
# Check to see if a filelist update is necessary
ext = os.path.splitext(fname)[-1].lower()
gc_path = self.file_paths.get('gcodes', None)
if gc_path is not None and full_path.startswith(gc_path) and \
ext in VALID_GCODE_EXTS:
if ext == ".ufp":
try:
full_path = self._process_ufp_from_refresh(
full_path)
except Exception:
logging.exception("Error processing ufp file")
continue
path_info = self._get_path_info(full_path)
path_info['filename'] = os.path.split(full_path)[-1]
rel_path = os.path.relpath(full_path, start=gc_path)
self.gcode_metadata.parse_metadata(
rel_path, path_info['size'], path_info['modified'],
notify=True)
metadata = self.gcode_metadata.get(rel_path, None)
if metadata is not None and is_extended:
path_info.update(metadata)
flist['files'].append(path_info)
usage = shutil.disk_usage(path)
flist['disk_usage'] = usage._asdict()
return flist
def _get_path_info(self, path):
modified = os.path.getmtime(path)
size = os.path.getsize(path)
path_info = {'modified': modified, 'size': size}
return path_info
def gen_temp_upload_path(self):
ioloop = IOLoop.current()
return os.path.join(
tempfile.gettempdir(),
f"moonraker.upload-{int(ioloop.time())}.mru")
async def finalize_upload(self, form_args):
# lookup root file path
try:
upload_info = self._parse_upload_args(form_args)
root = upload_info['root']
if root == "gcodes":
result = await self._finish_gcode_upload(upload_info)
elif root in FULL_ACCESS_ROOTS:
result = await self._finish_standard_upload(upload_info)
else:
raise self.server.error(f"Invalid root request: {root}")
except Exception:
try:
os.remove(form_args['tmp_file_path'])
except Exception:
pass
raise
return result
def _parse_upload_args(self, upload_args):
if 'filename' not in upload_args:
raise self.server.error(
"No file name specifed in upload form")
# check relative path
root = upload_args.get('root', "gcodes").lower()
if root not in self.file_paths:
raise self.server.error(f"Root {root} not available")
root_path = self.file_paths[root]
dir_path = upload_args.get('path', "")
if os.path.isfile(root_path):
filename = os.path.basename(root_path)
dest_path = root_path
dir_path = ""
else:
filename = upload_args['filename'].strip().lstrip("/")
if dir_path:
filename = os.path.join(dir_path, filename)
dest_path = os.path.abspath(os.path.join(root_path, filename))
# Validate the path. Don't allow uploads to a parent of the root
if not dest_path.startswith(root_path):
raise self.server.error(
f"Cannot write to path: {dest_path}")
start_print = upload_args.get('print', "false") == "true"
f_ext = os.path.splitext(dest_path)[-1].lower()
unzip_ufp = f_ext == ".ufp" and root == "gcodes"
if unzip_ufp:
filename = os.path.splitext(filename)[0] + ".gcode"
dest_path = os.path.splitext(dest_path)[0] + ".gcode"
return {
'root': root,
'filename': filename,
'dir_path': dir_path,
'dest_path': dest_path,
'tmp_file_path': upload_args['tmp_file_path'],
'start_print': start_print,
'unzip_ufp': unzip_ufp
}
async def _finish_gcode_upload(self, upload_info):
print_ongoing = False
start_print = upload_info['start_print']
# Verify that the operation can be done if attempting to upload a gcode
try:
check_path = upload_info['dest_path']
print_ongoing = await self._handle_operation_check(
check_path)
except self.server.error as e:
if e.status_code == 403:
raise self.server.error(
"File is loaded, upload not permitted", 403)
else:
# Couldn't reach Klippy, so it should be safe
# to permit the upload but not start
start_print = False
# Don't start if another print is currently in progress
start_print = start_print and not print_ongoing
ioloop = IOLoop.current()
with ThreadPoolExecutor(max_workers=1) as tpe:
await ioloop.run_in_executor(
tpe, self._process_uploaded_file, upload_info)
# Fetch Metadata
finfo = self._get_path_info(upload_info['dest_path'])
evt = self.gcode_metadata.parse_metadata(
upload_info['filename'], finfo['size'], finfo['modified'])
await evt.wait()
if start_print:
# Make a Klippy Request to "Start Print"
klippy_apis = self.server.lookup_component('klippy_apis')
try:
await klippy_apis.start_print(upload_info['filename'])
except self.server.error:
# Attempt to start print failed
start_print = False
self.notify_filelist_changed(
'upload_file', upload_info['filename'], "gcodes")
return {
'result': upload_info['filename'],
'print_started': start_print
}
async def _finish_standard_upload(self, upload_info):
ioloop = IOLoop.current()
with ThreadPoolExecutor(max_workers=1) as tpe:
await ioloop.run_in_executor(
tpe, self._process_uploaded_file, upload_info)
self.notify_filelist_changed(
'upload_file', upload_info['filename'], upload_info['root'])
return {'result': upload_info['filename']}
def _process_uploaded_file(self, upload_info):
try:
if upload_info['dir_path']:
os.makedirs(os.path.dirname(
upload_info['dest_path']), exist_ok=True)
if upload_info['unzip_ufp']:
self._unzip_ufp(upload_info['tmp_file_path'],
upload_info['dest_path'])
else:
shutil.move(upload_info['tmp_file_path'],
upload_info['dest_path'])
except Exception:
logging.exception("Upload Write Error")
raise self.server.error("Unable to save file", 500)
# UFP Extraction Implementation inspired by GitHub user @cdkeito
def _unzip_ufp(self, ufp_path, dest_path):
thumb_name = os.path.splitext(
os.path.basename(dest_path))[0] + ".png"
dest_thumb_dir = os.path.join(os.path.dirname(dest_path), "thumbs")
dest_thumb_path = os.path.join(dest_thumb_dir, thumb_name)
try:
with tempfile.TemporaryDirectory() as tmp_dir_name:
tmp_thumb_path = ""
with zipfile.ZipFile(ufp_path) as zf:
tmp_model_path = zf.extract(
UFP_MODEL_PATH, path=tmp_dir_name)
if UFP_THUMB_PATH in zf.namelist():
tmp_thumb_path = zf.extract(
UFP_THUMB_PATH, path=tmp_dir_name)
shutil.move(tmp_model_path, dest_path)
if tmp_thumb_path:
if not os.path.exists(dest_thumb_dir):
os.mkdir(dest_thumb_dir)
shutil.move(tmp_thumb_path, dest_thumb_path)
finally:
try:
os.remove(ufp_path)
except Exception:
logging.exception(f"Error removing ufp file: {ufp_path}")
def _process_ufp_from_refresh(self, ufp_path):
dest_path = os.path.splitext(ufp_path)[0] + ".gcode"
self._unzip_ufp(ufp_path, dest_path)
return dest_path
def get_file_list(self, root, list_format=False, notify=False):
# Use os.walk find files in sd path and subdirs
filelist = {}
path = self.file_paths.get(root, None)
if path is None or not os.path.isdir(path):
msg = f"Failed to build file list, invalid path: {root}: {path}"
logging.info(msg)
raise self.server.error(msg)
logging.info(f"Updating File List <{root}>...")
st = os.stat(path)
visited_dirs = {(st.st_dev, st.st_ino)}
for dir_path, dir_names, files in os.walk(path, followlinks=True):
scan_dirs = []
# Filter out directories that have already been visted. This
# prevents infinite recrusion "followlinks" is set to True
for dname in dir_names:
st = os.stat(os.path.join(dir_path, dname))
key = (st.st_dev, st.st_ino)
if key not in visited_dirs:
visited_dirs.add(key)
scan_dirs.append(dname)
dir_names[:] = scan_dirs
for name in files:
ext = os.path.splitext(name)[-1].lower()
if root == 'gcodes' and ext not in VALID_GCODE_EXTS:
continue
full_path = os.path.join(dir_path, name)
if ext == ".ufp":
try:
full_path = self._process_ufp_from_refresh(full_path)
except Exception:
logging.exception("Error processing ufp file")
continue
fname = full_path[len(path) + 1:]
finfo = self._get_path_info(full_path)
filelist[fname] = finfo
if root == 'gcodes':
self.gcode_metadata.parse_metadata(
fname, finfo['size'], finfo['modified'], notify)
if list_format:
flist = []
for fname in sorted(filelist, key=str.lower):
fdict = {'filename': fname}
fdict.update(filelist[fname])
flist.append(fdict)
return flist
return filelist
def get_file_metadata(self, filename):
if filename[0] == '/':
filename = filename[1:]
# Remove "gcodes" of its added. It is valid for a request to
# include to the root or assume the root is gcodes
if filename.startswith('gcodes/'):
filename = filename[7:]
return self.gcode_metadata.get(filename, {})
def list_dir(self, directory, simple_format=False):
# List a directory relative to its root.
if directory[0] == "/":
directory = directory[1:]
parts = directory.split("/", 1)
root = parts[0]
if root not in self.file_paths:
raise self.server.error(
f"Invalid Directory Request: {directory}")
path = self.file_paths[root]
if len(parts) == 1:
dir_path = path
else:
dir_path = os.path.join(path, parts[1])
if not os.path.isdir(dir_path):
raise self.server.error(
f"Directory does not exist ({dir_path})")
flist = self._list_directory(dir_path)
if simple_format:
simple_list = []
for dirobj in flist['dirs']:
simple_list.append("*" + dirobj['dirname'])
for fileobj in flist['files']:
fname = fileobj['filename']
ext = os.path.splitext(fname)[-1].lower()
if root == "gcodes" and ext in VALID_GCODE_EXTS:
simple_list.append(fname)
return simple_list
return flist
async def _handle_file_delete(self, web_request):
file_path = web_request.get_str("path")
return await self.delete_file(file_path)
async def delete_file(self, path):
parts = path.lstrip("/").split("/", 1)
if len(parts) != 2:
raise self.server.error(
f"Path not available for DELETE: {path}", 405)
root = parts[0]
filename = parts[1]
if root not in self.file_paths or root not in FULL_ACCESS_ROOTS:
raise self.server.error(
f"Path not available for DELETE: {path}", 405)
root_path = self.file_paths[root]
full_path = os.path.join(root_path, filename)
if not os.path.isfile(full_path):
raise self.server.error(f"Invalid file path: {path}")
if root == "gcodes":
try:
await self._handle_operation_check(full_path)
except self.server.error as e:
if e.status_code == 403:
raise
self.gcode_metadata.remove_file(filename)
os.remove(full_path)
self.notify_filelist_changed('delete_file', filename, root)
return filename
def notify_filelist_changed(self, action, fname, root, source_item={}):
flist = self.get_file_list(root, notify=True)
file_info = flist.get(fname, {'size': 0, 'modified': 0})
file_info.update({'path': fname, 'root': root})
result = {'action': action, 'item': file_info}
if source_item:
result.update({'source_item': source_item})
self.server.send_event("file_manager:filelist_changed", result)
def close(self):
self.gcode_metadata.close()
METADATA_PRUNE_TIME = 600000
METADATA_NAMESPACE = "gcode_metadata"
METADATA_VERSION = 3
class MetadataStorage:
def __init__(self, server, gc_path, database):
self.server = server
database.register_local_namespace(METADATA_NAMESPACE)
self.mddb = database.wrap_namespace(
METADATA_NAMESPACE, parse_keys=False)
version = database.get_item(
"moonraker", "file_manager.metadata_version", 0)
if version != METADATA_VERSION:
# Clear existing metadata when version is bumped
self.mddb.clear()
database.insert_item(
"moonraker", "file_manager.metadata_version",
METADATA_VERSION)
self.pending_requests = {}
self.events = {}
self.busy = False
self.gc_path = gc_path
self.prune_cb = PeriodicCallback(
self.prune_metadata, METADATA_PRUNE_TIME)
def update_gcode_path(self, path):
if path == self.gc_path:
return
self.mddb.clear()
self.gc_path = path
if not self.prune_cb.is_running():
self.prune_cb.start()
def close(self):
self.prune_cb.stop()
def get(self, key, default=None):
return self.mddb.get(key, default)
def __getitem__(self, key):
return self.mddb[key]
def prune_metadata(self):
for fname in list(self.mddb.keys()):
fpath = os.path.join(self.gc_path, fname)
if not os.path.exists(fpath):
self.remove_file(fname)
logging.info(f"Pruned file: {fname}")
continue
def _has_valid_data(self, fname, fsize, modified):
mdata = self.mddb.get(fname, {'size': "", 'modified': 0})
return mdata['size'] == fsize and mdata['modified'] == modified
def remove_file(self, fname):
metadata = self.mddb.pop(fname, None)
if metadata is None:
return
# Delete associated thumbnails
fdir = os.path.dirname(os.path.join(self.gc_path, fname))
if "thumbnails" in metadata:
for thumb in metadata["thumbnails"]:
path = thumb.get("relative_path", None)
if path is None:
continue
thumb_path = os.path.join(fdir, path)
try:
os.remove(thumb_path)
except Exception:
logging.debug(f"Error removing thumb at {thumb_path}")
def parse_metadata(self, fname, fsize, modified, notify=False):
evt = Event()
if fname in self.pending_requests or \
self._has_valid_data(fname, fsize, modified):
# request already pending or not necessary
evt.set()
return evt
self.pending_requests[fname] = (fsize, modified, notify, evt)
if self.busy:
return evt
self.busy = True
IOLoop.current().spawn_callback(self._process_metadata_update)
return evt
async def _process_metadata_update(self):
while self.pending_requests:
fname, (fsize, modified, notify, evt) = \
self.pending_requests.popitem()
if self._has_valid_data(fname, fsize, modified):
evt.set()
continue
retries = 3
while retries:
try:
await self._run_extract_metadata(fname, notify)
except Exception:
logging.exception("Error running extract_metadata.py")
retries -= 1
else:
break
else:
self.mddb[fname] = {
'size': fsize,
'modified': modified,
'print_start_time': None,
'job_id': None
}
logging.info(
f"Unable to extract medatadata from file: {fname}")
evt.set()
self.busy = False
async def _run_extract_metadata(self, filename, notify):
# Escape single quotes in the file name so that it may be
# properly loaded
filename = filename.replace("\"", "\\\"")
cmd = " ".join([sys.executable, METADATA_SCRIPT, "-p",
self.gc_path, "-f", f"\"{filename}\""])
shell_command = self.server.lookup_component('shell_command')
scmd = shell_command.build_shell_command(cmd, log_stderr=True)
result = await scmd.run_with_response(timeout=10.)
try:
decoded_resp = json.loads(result.strip())
except Exception:
logging.debug(f"Invalid metadata response:\n{result}")
raise
path = decoded_resp['file']
metadata = decoded_resp['metadata']
if not metadata:
# This indicates an error, do not add metadata for this
raise self.server.error("Unable to extract metadata")
metadata.update({'print_start_time': None, 'job_id': None})
self.mddb[path] = dict(metadata)
metadata['filename'] = path
if notify:
self.server.send_event(
"file_manager:metadata_update", metadata)
def load_component(config):
return FileManager(config)
@@ -0,0 +1,15 @@
# Package definition for the file_manager
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
from . import file_manager as fm
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ...confighelper import ConfigHelper
def load_component(config: ConfigHelper) -> fm.FileManager:
return fm.load_component(config)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+285
View File
@@ -0,0 +1,285 @@
# GPIO Factory helper
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import logging
from ..utils import load_system_module
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Callable,
Dict,
Optional
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..eventloop import EventLoop
GPIO_CALLBACK = Callable[[float, float, int], Optional[Awaitable[None]]]
class GpioFactory:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.gpiod: Any = load_system_module("gpiod")
GpioEvent.init_constants(self.gpiod)
self.chips: Dict[str, Any] = {}
self.reserved_gpios: Dict[str, GpioBase] = {}
version: str = self.gpiod.version_string()
self.gpiod_version = tuple(int(v) for v in version.split('.'))
self.server.add_log_rollover_item(
"gpiod_version", f"libgpiod version: {version}")
def _get_gpio_chip(self, chip_name) -> Any:
if chip_name in self.chips:
return self.chips[chip_name]
chip = self.gpiod.Chip(chip_name, self.gpiod.Chip.OPEN_BY_NAME)
self.chips[chip_name] = chip
return chip
def setup_gpio_out(self,
pin_name: str,
initial_value: int = 0
) -> GpioOutputPin:
initial_value = int(not not initial_value)
pparams = self._parse_pin(pin_name)
pparams['initial_value'] = initial_value
line = self._request_gpio(pparams)
try:
gpio_out = GpioOutputPin(line, pparams)
except Exception:
logging.exception("Error Instantiating GpioOutputPin")
line.release()
raise
full_name = pparams['full_name']
self.reserved_gpios[full_name] = gpio_out
return gpio_out
def register_gpio_event(self,
pin_name: str,
callback: GPIO_CALLBACK
) -> GpioEvent:
pin_params = self._parse_pin(pin_name, type="event")
line = self._request_gpio(pin_params)
event_loop = self.server.get_event_loop()
try:
gpio_event = GpioEvent(event_loop, line, pin_params, callback)
except Exception:
logging.exception("Error Instantiating GpioEvent")
line.release()
raise
full_name = pin_params['full_name']
self.reserved_gpios[full_name] = gpio_event
return gpio_event
def _request_gpio(self, pin_params: Dict[str, Any]) -> Any:
full_name = pin_params['full_name']
if full_name in self.reserved_gpios:
raise self.server.error(f"GPIO {full_name} already reserved")
try:
chip = self._get_gpio_chip(pin_params['chip_id'])
line = chip.get_line(pin_params['pin_id'])
args: Dict[str, Any] = {
'consumer': "moonraker",
'type': pin_params['request_type']
}
if 'flags' in pin_params:
args['flags'] = pin_params['flags']
if 'initial_value' in pin_params:
if self.gpiod_version < (1, 3):
args['default_vals'] = [pin_params['initial_value']]
else:
args['default_val'] = pin_params['initial_value']
line.request(**args)
except Exception:
logging.exception(
f"Unable to init {full_name}. Make sure the gpio is not in "
"use by another program or exported by sysfs.")
raise
return line
def _parse_pin(self,
pin_name: str,
type: str = "out"
) -> Dict[str, Any]:
params: Dict[str, Any] = {
'orig': pin_name,
'invert': False,
}
pin = pin_name
if type == "event":
params['request_type'] = self.gpiod.LINE_REQ_EV_BOTH_EDGES
flag: str = "disable"
if pin[0] == "^":
pin = pin[1:]
flag = "pullup"
elif pin[0] == "~":
pin = pin[1:]
flag = "pulldown"
if self.gpiod_version >= (1, 5):
flag_to_enum = {
"disable": self.gpiod.LINE_REQ_FLAG_BIAS_DISABLE,
"pullup": self.gpiod.LINE_REQ_FLAG_BIAS_PULL_UP,
"pulldown": self.gpiod.LINE_REQ_FLAG_BIAS_PULL_DOWN
}
params['flags'] = flag_to_enum[flag]
elif flag != "disable":
raise self.server.error(
f"Flag {flag} configured for event GPIO '{pin_name}'"
" requires libgpiod version 1.5 or later. "
f"Current Version: {self.gpiod.version_string()}")
elif type == "out":
params['request_type'] = self.gpiod.LINE_REQ_DIR_OUT
if pin[0] == "!":
pin = pin[1:]
params['invert'] = True
if 'flags' in params:
params['flags'] |= self.gpiod.LINE_REQ_FLAG_ACTIVE_LOW
else:
params['flags'] = self.gpiod.LINE_REQ_FLAG_ACTIVE_LOW
chip_id: str = "gpiochip0"
pin_parts = pin.split("/")
if len(pin_parts) == 2:
chip_id, pin = pin_parts
elif len(pin_parts) == 1:
pin = pin_parts[0]
# Verify pin
if not chip_id.startswith("gpiochip") or \
not chip_id[-1].isdigit() or \
not pin.startswith("gpio") or \
not pin[4:].isdigit():
raise self.server.error(
f"Invalid Gpio Pin: {pin_name}")
pin_id = int(pin[4:])
params['pin_id'] = pin_id
params['chip_id'] = chip_id
params['full_name'] = f"{chip_id}:{pin}"
return params
def close(self) -> None:
for line in self.reserved_gpios.values():
line.release()
for chip in self.chips.values():
chip.close()
class GpioBase:
def __init__(self,
line: Any,
pin_params: Dict[str, Any]
) -> None:
self.orig: str = pin_params['orig']
self.name: str = pin_params['full_name']
self.inverted: bool = pin_params['invert']
self.line: Any = line
self.value: int = pin_params.get('initial_value', 0)
def release(self) -> None:
self.line.release()
def is_inverted(self) -> bool:
return self.inverted
def get_value(self) -> int:
return self.value
def get_name(self) -> str:
return self.name
def __str__(self) -> str:
return self.orig
class GpioOutputPin(GpioBase):
def write(self, value: int) -> None:
self.value = int(not not value)
self.line.set_value(self.value)
MAX_ERRORS = 50
ERROR_RESET_TIME = 5.
class GpioEvent(GpioBase):
EVENT_FALLING_EDGE = 0
EVENT_RISING_EDGE = 1
def __init__(self,
event_loop: EventLoop,
line: Any,
pin_params: Dict[str, Any],
callback: GPIO_CALLBACK
) -> None:
super().__init__(line, pin_params)
self.event_loop = event_loop
self.fd = line.event_get_fd()
self.callback = callback
self.on_error: Optional[Callable[[str], None]] = None
self.min_evt_time = 0.
self.last_event_time = 0.
self.error_count = 0
self.last_error_reset = 0.
self.started = False
@classmethod
def init_constants(cls, gpiod: Any) -> None:
cls.EVENT_RISING_EDGE = gpiod.LineEvent.RISING_EDGE
cls.EVENT_FALLING_EDGE = gpiod.LineEvent.FALLING_EDGE
def setup_debounce(self,
min_evt_time: float,
err_callback: Optional[Callable[[str], None]]
) -> None:
self.min_evt_time = max(min_evt_time, 0.)
self.on_error = err_callback
def start(self) -> None:
if not self.started:
self.value = self.line.get_value()
self.last_event_time = self.event_loop.get_loop_time()
self.event_loop.add_reader(self.fd, self._on_event_trigger)
self.started = True
logging.debug(f"GPIO {self.name}: Listening for events, "
f"current state: {self.value}")
def stop(self) -> None:
if self.started:
self.event_loop.remove_reader(self.fd)
self.started = False
def release(self) -> None:
self.stop()
self.line.release()
def _on_event_trigger(self) -> None:
evt = self.line.event_read()
last_val = self.value
if evt.type == self.EVENT_RISING_EDGE:
self.value = 1
elif evt.type == self.EVENT_FALLING_EDGE:
self.value = 0
eventtime = self.event_loop.get_loop_time()
evt_duration = eventtime - self.last_event_time
if last_val == self.value or evt_duration < self.min_evt_time:
self._increment_error(eventtime)
return
self.last_event_time = eventtime
self.error_count = 0
ret = self.callback(eventtime, evt_duration, self.value)
if ret is not None:
self.event_loop.create_task(ret) # type: ignore
def _increment_error(self, eventtime: float) -> None:
if eventtime - self.last_error_reset > ERROR_RESET_TIME:
self.error_count = 0
self.last_error_reset = eventtime
self.error_count += 1
if self.error_count >= MAX_ERRORS:
self.stop()
if self.on_error is not None:
self.on_error("Too Many Consecutive Errors, "
f"GPIO Event Disabled on {self.name}")
def load_component(config: ConfigHelper) -> GpioFactory:
return GpioFactory(config)
+245 -138
View File
@@ -1,19 +1,39 @@
# History cache for printer jobs
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging
from __future__ import annotations
import time
import logging
from asyncio import Lock
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Union,
Optional,
Dict,
List,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..websockets import WebRequest
from .database import MoonrakerDatabase as DBComp
from .job_state import JobState
from .file_manager.file_manager import FileManager
HIST_NAMESPACE = "history"
MAX_JOBS = 10000
class History:
def __init__(self, config):
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.file_manager = self.server.lookup_component('file_manager')
database = self.server.lookup_component("database")
self.gcdb = database.wrap_namespace("gcode_metadata", parse_keys=False)
self.job_totals = database.get_item(
self.file_manager: FileManager = self.server.lookup_component(
'file_manager')
self.request_lock = Lock()
database: DBComp = self.server.lookup_component("database")
self.job_totals: Dict[str, float] = database.get_item(
"moonraker", "history.job_totals",
{
'total_jobs': 0,
@@ -22,16 +42,22 @@ class History:
'total_filament_used': 0.,
'longest_job': 0.,
'longest_print': 0.
})
}).result()
self.server.register_event_handler(
"server:klippy_ready", self._init_ready)
self.server.register_event_handler(
"server:status_update", self._status_update)
self.server.register_event_handler(
"server:klippy_disconnect", self._handle_disconnect)
self.server.register_event_handler(
"server:klippy_shutdown", self._handle_shutdown)
self.server.register_event_handler(
"job_state:started", self._on_job_started)
self.server.register_event_handler(
"job_state:complete", self._on_job_complete)
self.server.register_event_handler(
"job_state:cancelled", self._on_job_cancelled)
self.server.register_event_handler(
"job_state:standby", self._on_job_standby)
self.server.register_event_handler(
"job_state:error", self._on_job_error)
self.server.register_notification("history:history_changed")
self.server.register_endpoint(
@@ -40,128 +66,178 @@ class History:
"/server/history/list", ['GET'], self._handle_jobs_list)
self.server.register_endpoint(
"/server/history/totals", ['GET'], self._handle_job_totals)
self.server.register_endpoint(
"/server/history/reset_totals", ['POST'],
self._handle_job_total_reset)
database.register_local_namespace(HIST_NAMESPACE)
self.history_ns = database.wrap_namespace(HIST_NAMESPACE,
parse_keys=False)
self.current_job = None
self.current_job_id = None
self.print_stats = {}
self.next_job_id = 0
self.cached_job_ids = self.history_ns.keys()
self.current_job: Optional[PrinterJob] = None
self.current_job_id: Optional[str] = None
self.next_job_id: int = 0
self.cached_job_ids = self.history_ns.keys().result()
if self.cached_job_ids:
self.next_job_id = int(self.cached_job_ids[-1], 16) + 1
async def _init_ready(self):
klippy_apis = self.server.lookup_component('klippy_apis')
sub = {"print_stats": None}
try:
result = await klippy_apis.subscribe_objects(sub)
except self.server.error as e:
logging.info(f"Error subscribing to print_stats")
self.print_stats = result.get("print_stats", {})
async def _handle_job_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
async with self.request_lock:
action = web_request.get_action()
if action == "GET":
job_id = web_request.get_str("uid")
if job_id not in self.cached_job_ids:
raise self.server.error(f"Invalid job uid: {job_id}", 404)
job = await self.history_ns[job_id]
return {"job": self._prep_requested_job(job, job_id)}
if action == "DELETE":
all = web_request.get_boolean("all", False)
if all:
deljobs = self.cached_job_ids
self.history_ns.clear()
self.cached_job_ids = []
self.next_job_id = 0
return {'deleted_jobs': deljobs}
async def _handle_job_request(self, web_request):
action = web_request.get_action()
if action == "GET":
job_id = web_request.get_str("uid")
if job_id not in self.cached_job_ids:
raise self.server.error(f"Invalid job uid: {job_id}", 404)
job = self.history_ns[job_id]
return {"job": self._prep_requested_job(job, job_id)}
if action == "DELETE":
all = web_request.get_boolean("all", False)
if all:
deljobs = self.cached_job_ids
self.history_ns.clear()
self.cached_job_ids = []
self.next_job_id = 0
return {'deleted_jobs': deljobs}
job_id = web_request.get_str("uid")
if job_id not in self.cached_job_ids:
raise self.server.error(f"Invalid job uid: {job_id}", 404)
job_id = web_request.get_str("uid")
if job_id not in self.cached_job_ids:
raise self.server.error(f"Invalid job uid: {job_id}", 404)
self.delete_job(job_id)
return {'deleted_jobs': [job_id]}
raise self.server.error("Invalid Request Method")
self.delete_job(job_id)
return {'deleted_jobs': [job_id]}
async def _handle_jobs_list(self,
web_request: WebRequest
) -> Dict[str, Any]:
async with self.request_lock:
i = 0
count = 0
end_num = len(self.cached_job_ids)
jobs: List[Dict[str, Any]] = []
start_num = 0
async def _handle_jobs_list(self, web_request):
i = 0
end_num = len(self.history_ns)
jobs = []
start_num = 0
before = web_request.get_float("before", -1)
since = web_request.get_float("since", -1)
limit = web_request.get_int("limit", 50)
start = web_request.get_int("start", 0)
order = web_request.get_str("order", "desc")
before = web_request.get_float("before", -1)
since = web_request.get_float("since", -1)
limit = web_request.get_int("limit", 50)
start = web_request.get_int("start", 0)
if start >= end_num or end_num == 0:
return {"count": 0, "jobs": []}
if order not in ["asc", "desc"]:
raise self.server.error(f"Invalid `order` value: {order}", 400)
for job_id in self.cached_job_ids:
job = self.history_ns[job_id]
if since != -1 and since > job.get('start_time'):
start_num += 1
continue
if before != -1 and before < job.get('end_time'):
end_num -= 1
continue
if limit != 0 and i >= limit:
continue
if start != 0:
start -= 1
continue
jobs.append(self._prep_requested_job(job, job_id))
i += 1
reverse_order = (order == "desc")
return {"count": end_num - start_num, "jobs": jobs}
# cached jobs is asc order, find lower and upper boundary
if since != -1:
while start_num < end_num:
job_id = self.cached_job_ids[start_num]
job: Dict[str, Any] = await self.history_ns[job_id]
if job['start_time'] > since:
break
start_num += 1
async def _handle_job_totals(self, web_request):
if before != -1:
while end_num > 0:
job_id = self.cached_job_ids[end_num-1]
job = await self.history_ns[job_id]
if job['end_time'] < before:
break
end_num -= 1
if start_num >= end_num or end_num == 0:
return {"count": 0, "jobs": []}
i = start
count = end_num - start_num
if limit == 0:
limit = MAX_JOBS
while i < count and len(jobs) < limit:
if reverse_order:
job_id = self.cached_job_ids[end_num - i - 1]
else:
job_id = self.cached_job_ids[start_num + i]
job = await self.history_ns[job_id]
jobs.append(self._prep_requested_job(job, job_id))
i += 1
return {"count": count, "jobs": jobs}
async def _handle_job_totals(self,
web_request: WebRequest
) -> Dict[str, Dict[str, float]]:
return {'job_totals': self.job_totals}
async def _status_update(self, data):
ps = data.get("print_stats", {})
if "state" in ps:
old_state = self.print_stats['state']
new_state = ps['state']
new_ps = dict(self.print_stats)
new_ps.update(ps)
async def _handle_job_total_reset(self,
web_request: WebRequest,
) -> Dict[str, Dict[str, float]]:
if self.current_job is not None:
raise self.server.error(
"Job in progress, cannot reset totals")
last_totals = dict(self.job_totals)
self.job_totals = {
'total_jobs': 0,
'total_time': 0.,
'total_print_time': 0.,
'total_filament_used': 0.,
'longest_job': 0.,
'longest_print': 0.
}
database: DBComp = self.server.lookup_component("database")
await database.insert_item(
"moonraker", "history.job_totals", self.job_totals)
return {'last_totals': last_totals}
if new_state is not old_state:
if new_state == "printing" and self.current_job is None:
# always add new job if no existing job is present
self.add_job(PrinterJob(new_ps))
elif self.current_job is not None:
if new_state == "complete":
self.finish_job("completed", new_ps)
if new_state == "standby":
self.finish_job("cancelled", self.print_stats)
elif new_state == "error":
self.finish_job("error", new_ps)
elif new_state == "printing" and \
self._check_need_cancel(new_ps):
# Finish with the previous state
self.finish_job("cancelled", self.print_stats)
self.add_job(PrinterJob(new_ps))
def _on_job_started(self,
prev_stats: Dict[str, Any],
new_stats: Dict[str, Any]
) -> None:
if self.current_job is not None:
# Finish with the previous state
self.finish_job("cancelled", prev_stats)
self.add_job(PrinterJob(new_stats))
self.print_stats.update(ps)
def _on_job_complete(self,
prev_stats: Dict[str, Any],
new_stats: Dict[str, Any]
) -> None:
self.finish_job("completed", new_stats)
def _handle_shutdown(self):
self.finish_job("klippy_shutdown", self.print_stats)
def _on_job_cancelled(self,
prev_stats: Dict[str, Any],
new_stats: Dict[str, Any]
) -> None:
self.finish_job("cancelled", new_stats)
def _handle_disconnect(self):
self.finish_job("klippy_disconnect", self.print_stats)
def _on_job_error(self,
prev_stats: Dict[str, Any],
new_stats: Dict[str, Any]
) -> None:
self.finish_job("error", new_stats)
def _check_need_cancel(self, new_stats):
# Cancel if the file name has changed, total duration has
# decreased, or if job is not resuming from a pause
ps = self.print_stats
return ps['filename'] != new_stats['filename'] or \
ps['total_duration'] > new_stats['total_duration'] or \
ps['state'] != "paused"
def _on_job_standby(self,
prev_stats: Dict[str, Any],
new_stats: Dict[str, Any]
) -> None:
# Backward compatibility with
# `CLEAR_PAUSE/SDCARD_RESET_FILE` workflow
self.finish_job("cancelled", prev_stats)
def add_job(self, job):
def _handle_shutdown(self) -> None:
jstate: JobState = self.server.lookup_component("job_state")
last_ps = jstate.get_last_stats()
self.finish_job("klippy_shutdown", last_ps)
def _handle_disconnect(self) -> None:
jstate: JobState = self.server.lookup_component("job_state")
last_ps = jstate.get_last_stats()
self.finish_job("klippy_disconnect", last_ps)
def add_job(self, job: PrinterJob) -> None:
if len(self.cached_job_ids) >= MAX_JOBS:
self.delete_job(self.cached_job_ids[0])
job_id = f"{self.next_job_id:06X}"
@@ -171,9 +247,12 @@ class History:
self.history_ns[job_id] = job.get_stats()
self.cached_job_ids.append(job_id)
self.next_job_id += 1
logging.debug(
f"History Job Added - Id: {job_id}, File: {job.filename}"
)
self.send_history_event("added")
def delete_job(self, job_id):
def delete_job(self, job_id: Union[int, str]) -> None:
if isinstance(job_id, int):
job_id = f"{job_id:06X}"
@@ -181,29 +260,44 @@ class History:
del self.history_ns[job_id]
self.cached_job_ids.remove(job_id)
def finish_job(self, status, pstats):
def finish_job(self, status: str, pstats: Dict[str, Any]) -> None:
if self.current_job is None:
return
cj = self.current_job
if (
pstats.get('filename') != cj.get('filename') or
pstats.get('total_duration', 0.) < cj.get('total_duration')
):
# Print stats have been reset, do not update this job with them
pstats = {}
self.current_job.finish(status, pstats)
# Regrab metadata incase metadata wasn't parsed yet due to file upload
self.grab_job_metadata()
self.save_current_job()
self._update_job_totals()
logging.debug(
f"History Job Finished - Id: {self.current_job_id}, "
f"File: {self.current_job.filename}, "
f"Status: {status}"
)
self.send_history_event("finished")
self.current_job = None
self.current_job_id = None
def get_job(self, job_id):
async def get_job(self,
job_id: Union[int, str]
) -> Optional[Dict[str, Any]]:
if isinstance(job_id, int):
job_id = f"{job_id:06X}"
return self.history_ns.get(job_id, None)
return await self.history_ns.get(job_id, None)
def grab_job_metadata(self):
def grab_job_metadata(self) -> None:
if self.current_job is None:
return
filename = self.current_job.get("filename")
metadata = self.gcdb.get(filename, {})
filename: str = self.current_job.get("filename")
mdst = self.file_manager.get_metadata_storage()
metadata: Dict[str, Any] = mdst.get(filename, {})
if metadata:
# Add the start time and job id to the
# persistent metadata storage
@@ -211,20 +305,23 @@ class History:
'print_start_time': self.current_job.get('start_time'),
'job_id': self.current_job_id
})
self.gcdb[filename] = metadata
mdst.insert(filename, metadata.copy())
# We don't need to store these fields in the
# job metadata, as they are redundant
metadata.pop('print_start_time', None)
metadata.pop('job_id', None)
if "thumbnails" in metadata:
thumb: Dict[str, Any]
for thumb in metadata['thumbnails']:
thumb.pop('data', None)
self.current_job.set("metadata", metadata)
def save_current_job(self):
def save_current_job(self) -> None:
if self.current_job is None or self.current_job_id is None:
return
self.history_ns[self.current_job_id] = self.current_job.get_stats()
def _update_job_totals(self):
def _update_job_totals(self) -> None:
if self.current_job is None:
return
job = self.current_job
@@ -236,59 +333,69 @@ class History:
self.job_totals['longest_job'], job.get('total_duration'))
self.job_totals['longest_print'] = max(
self.job_totals['longest_print'], job.get('print_duration'))
database = self.server.lookup_component("database")
database: DBComp = self.server.lookup_component("database")
database.insert_item(
"moonraker", "history.job_totals", self.job_totals)
def send_history_event(self, evt_action):
def send_history_event(self, evt_action: str) -> None:
if self.current_job is None or self.current_job_id is None:
return
job = self._prep_requested_job(
self.current_job.get_stats(), self.current_job_id)
self.server.send_event("history:history_changed",
{'action': evt_action, 'job': job})
def _prep_requested_job(self, job, job_id):
def _prep_requested_job(self,
job: Dict[str, Any],
job_id: str
) -> Dict[str, Any]:
job['job_id'] = job_id
job['exists'] = self.file_manager.check_file_exists(
"gcodes", job['filename'])
return job
def on_exit(self):
self.finish_job("server_exit", self.print_stats)
def on_exit(self) -> None:
jstate: JobState = self.server.lookup_component("job_state")
last_ps = jstate.get_last_stats()
self.finish_job("server_exit", last_ps)
class PrinterJob:
def __init__(self, data={}):
self.end_time = None
self.filament_used = 0
self.filename = None
self.metadata = None
self.print_duration = 0
self.status = "in_progress"
def __init__(self, data: Dict[str, Any] = {}) -> None:
self.end_time: Optional[float] = None
self.filament_used: float = 0
self.filename: Optional[str] = None
self.metadata: Optional[Dict[str, Any]] = None
self.print_duration: float = 0.
self.status: str = "in_progress"
self.start_time = time.time()
self.total_duration = 0
self.total_duration: float = 0.
self.update_from_ps(data)
def finish(self, status, print_stats={}):
def finish(self,
status: str,
print_stats: Dict[str, Any] = {}
) -> None:
self.end_time = time.time()
self.status = status
self.update_from_ps(print_stats)
def get(self, name):
def get(self, name: str) -> Any:
if not hasattr(self, name):
return None
return getattr(self, name)
def get_stats(self):
def get_stats(self) -> Dict[str, Any]:
return self.__dict__.copy()
def set(self, name, val):
def set(self, name: str, val: Any) -> None:
if not hasattr(self, name):
return
setattr(self, name, val)
def update_from_ps(self, data):
def update_from_ps(self, data: Dict[str, Any]) -> None:
for i in data:
if hasattr(self, i):
setattr(self, i, data[i])
def load_component(config):
def load_component(config: ConfigHelper) -> History:
return History(config)
+470
View File
@@ -0,0 +1,470 @@
# Wrapper around Tornado's HTTP Client with a "requests-like" interface
#
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import re
import json
import time
import asyncio
import pathlib
import tempfile
import logging
from ..utils import ServerError
from tornado.escape import url_escape, url_unescape
from tornado.httpclient import AsyncHTTPClient, HTTPRequest, HTTPError
from tornado.httputil import HTTPHeaders
from typing import (
TYPE_CHECKING,
Callable,
Optional,
Tuple,
Union,
Dict,
List,
Any
)
if TYPE_CHECKING:
from ..server import Server
from ..confighelper import ConfigHelper
from io import BufferedWriter
StrOrPath = Union[str, pathlib.Path]
MAX_BODY_SIZE = 512 * 1024 * 1024
AsyncHTTPClient.configure(
None, defaults=dict(user_agent="Moonraker"),
max_body_size=MAX_BODY_SIZE
)
GITHUB_PREFIX = "https://api.github.com/"
class HttpClient:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.client = AsyncHTTPClient()
self.response_cache: Dict[str, HttpResponse] = {}
self.gh_rate_limit: Optional[int] = None
self.gh_limit_remaining: Optional[int] = None
self.gh_limit_reset_time: Optional[float] = None
def register_cached_url(
self,
url: str,
etag: Optional[str] = None,
last_modified: Optional[str] = None
) -> None:
headers = HTTPHeaders()
if etag is not None:
headers["etag"] = etag
if last_modified is not None:
headers["last-modified"] = last_modified
if len(headers) == 0:
raise self.server.error(
"Either an Etag or Last Modified Date must be specified")
empty_resp = HttpResponse(url, url, 200, b"", headers, None)
self.response_cache[url] = empty_resp
async def request(
self,
method: str,
url: str,
body: Optional[Union[str, List[Any], Dict[str, Any]]] = None,
headers: Optional[Dict[str, Any]] = None,
connect_timeout: float = 5.,
request_timeout: float = 10.,
attempts: int = 1,
retry_pause_time: float = .1,
enable_cache: bool = False,
send_etag: bool = True,
send_if_modified_since: bool = True
) -> HttpResponse:
cache_key = url.split("?", 1)[0]
method = method.upper()
# prepare the body if required
req_headers: Dict[str, Any] = {}
if isinstance(body, (list, dict)):
body = json.dumps(body)
req_headers["Content-Type"] = "application/json"
cached: Optional[HttpResponse] = None
if enable_cache:
cached = self.response_cache.get(cache_key)
if cached is not None and send_etag:
if cached.etag is not None and send_etag:
req_headers["If-None-Match"] = cached.etag
if cached.last_modified and send_if_modified_since:
req_headers["If-Modified-Since"] = cached.last_modified
if headers is not None:
headers.update(req_headers)
elif req_headers:
headers = req_headers
timeout = 1 + connect_timeout + request_timeout
request = HTTPRequest(url, method, headers, body=body,
request_timeout=request_timeout,
connect_timeout=connect_timeout)
err: Optional[BaseException] = None
for i in range(attempts):
if i:
await asyncio.sleep(retry_pause_time)
try:
fut = self.client.fetch(request, raise_error=False)
resp = await asyncio.wait_for(fut, timeout)
except asyncio.CancelledError:
raise
except Exception as e:
err = e
else:
err = resp.error
if resp.code == 304:
err = None
if cached is None:
if enable_cache:
logging.info(
"Request returned 304, however no cached "
"item was found")
result = b""
else:
logging.debug(f"Request returned from cache: {url}")
result = cached.content
elif resp.error is not None and attempts - i != 1:
continue
else:
result = resp.body
ret = HttpResponse(
url, resp.effective_url, resp.code, result,
resp.headers, err
)
break
else:
ret = HttpResponse(url, url, 500, b"", HTTPHeaders(), err)
if enable_cache and ret.is_cachable():
logging.debug(f"Caching HTTP Response: {url}")
self.response_cache[cache_key] = ret
else:
self.response_cache.pop(cache_key, None)
return ret
async def get(
self, url: str, headers: Optional[Dict[str, Any]] = None, **kwargs
) -> HttpResponse:
if "enable_cache" not in kwargs:
kwargs["enable_cache"] = True
return await self.request("GET", url, None, headers, **kwargs)
async def post(
self,
url: str,
body: Union[str, List[Any], Dict[str, Any]] = "",
headers: Optional[Dict[str, Any]] = None,
**kwargs
) -> HttpResponse:
return await self.request("POST", url, body, headers, **kwargs)
async def delete(
self,
url: str,
headers: Optional[Dict[str, Any]] = None,
**kwargs
) -> HttpResponse:
return await self.request("DELETE", url, None, headers, **kwargs)
async def github_api_request(
self,
resource: str,
attempts: int = 1,
retry_pause_time: float = .1
) -> HttpResponse:
url = f"{GITHUB_PREFIX}{resource.strip('/')}"
if (
self.gh_limit_reset_time is not None and
self.gh_limit_remaining == 0
):
curtime = time.time()
if curtime < self.gh_limit_reset_time:
reset_time = time.ctime(self.gh_limit_reset_time)
raise self.server.error(
f"GitHub Rate Limit Reached\n"
f"Request: {url}\n"
f"Limit Reset Time: {reset_time}"
)
headers = {"Accept": "application/vnd.github.v3+json"}
resp = await self.get(
url, headers, attempts=attempts,
retry_pause_time=retry_pause_time)
resp_hdrs = resp.headers
if 'X-Ratelimit-Limit' in resp_hdrs:
self.gh_rate_limit = int(resp_hdrs['X-Ratelimit-Limit'])
self.gh_limit_remaining = int(
resp_hdrs['X-Ratelimit-Remaining'])
self.gh_limit_reset_time = float(
resp_hdrs['X-Ratelimit-Reset'])
return resp
def github_api_stats(self) -> Dict[str, Any]:
return {
'github_rate_limit': self.gh_rate_limit,
'github_requests_remaining': self.gh_limit_remaining,
'github_limit_reset_time': self.gh_limit_reset_time,
}
async def get_file(
self,
url: str,
content_type: str,
connect_timeout: float = 5.,
request_timeout: float = 180.,
attempts: int = 1,
retry_pause_time: float = .1,
enable_cache: bool = False,
) -> bytes:
headers = {"Accept": content_type}
resp = await self.get(
url, headers, connect_timeout=connect_timeout,
request_timeout=request_timeout, attempts=attempts,
retry_pause_time=retry_pause_time, enable_cache=enable_cache
)
resp.raise_for_status()
return resp.content
async def download_file(
self,
url: str,
content_type: str,
destination_path: Optional[StrOrPath] = None,
download_size: int = -1,
progress_callback: Optional[Callable[[int, int, int], None]] = None,
connect_timeout: float = 5.,
request_timeout: float = 180.,
attempts: int = 1,
retry_pause_time: float = 1.
) -> pathlib.Path:
for i in range(attempts):
dl = StreamingDownload(
self.server, destination_path, download_size,
progress_callback)
try:
fut = self.client.fetch(
url, headers={"Accept": content_type},
connect_timeout=connect_timeout,
request_timeout=request_timeout,
streaming_callback=dl.on_chunk_recd,
header_callback=dl.on_headers_recd)
timeout = connect_timeout + request_timeout + 1.
resp = await asyncio.wait_for(fut, timeout)
except asyncio.CancelledError:
raise
except Exception:
if i + 1 == attempts:
raise
await asyncio.sleep(retry_pause_time)
continue
finally:
await dl.close()
if resp.code < 400:
return dl.dest_file
raise self.server.error(f"Retries exceeded for request: {url}")
def close(self):
self.client.close()
class HttpResponse:
def __init__(self,
url: str,
final_url: str,
code: int,
result: bytes,
response_headers: HTTPHeaders,
error: Optional[BaseException]
) -> None:
self._url = url
self._final_url = final_url
self._code = code
self._result: bytes = result
self._encoding: str = "utf-8"
self._response_headers: HTTPHeaders = response_headers
self._etag: Optional[str] = response_headers.get("etag", None)
self._error = error
self._last_modified: Optional[str] = response_headers.get(
"last-modified", None)
def json(self, **kwargs) -> Union[List[Any], Dict[str, Any]]:
return json.loads(self._result, **kwargs)
def is_cachable(self) -> bool:
return self._last_modified is not None or self._etag is not None
def has_error(self) -> bool:
return self._error is not None
def raise_for_status(self, message: Optional[str] = None) -> None:
if self._error is not None:
code = 500
msg = f"HTTP Request Error: {self.url}"
if isinstance(self._error, HTTPError):
code = self._code
if self._error.message is not None:
msg = self._error.message
if message is not None:
msg = message
raise ServerError(msg, code) from self._error
@property
def encoding(self) -> str:
return self._encoding
@encoding.setter
def encoding(self, new_enc: str) -> None:
self._encoding = new_enc
@property
def text(self) -> str:
return self._result.decode(encoding=self._encoding)
@property
def content(self) -> bytes:
return self._result
@property
def url(self) -> str:
return self._url
@property
def final_url(self) -> str:
return self._final_url
@property
def status_code(self) -> int:
return self._code
@property
def headers(self) -> HTTPHeaders:
return self._response_headers
@property
def last_modified(self) -> Optional[str]:
return self._last_modified
@property
def etag(self) -> Optional[str]:
return self._etag
@property
def error(self) -> Optional[BaseException]:
return self._error
class StreamingDownload:
def __init__(
self,
server: Server,
dest_path: Optional[StrOrPath],
download_size: int,
progress_callback: Optional[Callable[[int, int, int], None]]
) -> None:
self.server = server
self.event_loop = server.get_event_loop()
self.need_content_length: bool = True
self.need_content_disposition: bool = False
self.request_ok: bool = False
if dest_path is None:
# If no destination is provided initialize to a procedurally
# generated temp file. We will attempt to extract the filename
# from the Content-Disposition Header
tmp_dir = tempfile.gettempdir()
loop_time = int(self.event_loop.get_loop_time())
tmp_fname = f"moonraker.download-{loop_time}.mrd"
self.dest_file = pathlib.Path(tmp_dir).joinpath(tmp_fname)
self.need_content_disposition = True
elif isinstance(dest_path, str):
self.dest_file = pathlib.Path(dest_path)
else:
self.dest_file = dest_path
self.filename = self.dest_file.name
self.file_hdl: Optional[BufferedWriter] = None
self.total_recd: int = 0
self.download_size: int = download_size
self.pct_done: int = 0
self.chunk_buffer: List[bytes] = []
self.progress_callback = progress_callback
self.busy_evt: asyncio.Event = asyncio.Event()
self.busy_evt.set()
def on_headers_recd(self, line: str) -> None:
if not self.need_content_length and not self.need_content_disposition:
return
line = line.strip()
rc_match = re.match(r"HTTP/\d.?\d? (\d+)", line)
if rc_match is not None:
self.request_ok = rc_match.group(1) == "200"
return
if not self.request_ok:
return
parts = line.split(":", 1)
if len(parts) < 2:
return
hname = parts[0].strip().lower()
hval = parts[1].strip()
if hname == "content-length" and self.need_content_length:
self.download_size = int(hval)
self.need_content_length = False
logging.debug(
f"Content-Length header received: "
f"size = {self.download_size}")
elif (
hname == "content-disposition" and
self.need_content_disposition
):
fnr = r"filename[^;\n=]*=(['\"])?(utf-8\'\')?([^\n;]*)(?(1)\1|)"
matches: List[Tuple[str, str, str]] = re.findall(fnr, hval)
is_utf8 = False
for (_, encoding, fname) in matches:
if encoding.startswith("utf-8"):
# Prefer the utf8 filename if included
self.filename = url_unescape(
fname, encoding="utf-8", plus=False)
is_utf8 = True
break
self.filename = fname
self.need_content_disposition = False
# Use the filename extracted from the content-disposition header
self.dest_file = self.dest_file.parent.joinpath(self.filename)
logging.debug(
"Content-Disposition header received: filename = "
f"{self.filename}, utf8: {is_utf8}")
def on_chunk_recd(self, chunk: bytes) -> None:
if not chunk:
return
self.chunk_buffer.append(chunk)
if not self.busy_evt.is_set():
return
self.busy_evt.clear()
self.event_loop.register_callback(self._process_buffer)
async def close(self):
await self.busy_evt.wait()
if self.file_hdl is not None:
await self.event_loop.run_in_thread(self.file_hdl.close)
async def _process_buffer(self):
if self.file_hdl is None:
self.file_hdl = await self.event_loop.run_in_thread(
self.dest_file.open, "wb")
while self.chunk_buffer:
chunk = self.chunk_buffer.pop(0)
await self.event_loop.run_in_thread(self.file_hdl.write, chunk)
self.total_recd += len(chunk)
if self.download_size > 0 and self.progress_callback is not None:
pct = int(self.total_recd / self.download_size * 100 + .5)
pct = min(100, pct)
if pct != self.pct_done:
self.pct_done = pct
self.progress_callback(
pct, self.download_size, self.total_recd)
self.busy_evt.set()
def load_component(config: ConfigHelper) -> HttpClient:
return HttpClient(config)
+337
View File
@@ -0,0 +1,337 @@
# Print Job Queue Implementation
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import asyncio
import time
import logging
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Optional,
Dict,
List,
Union,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..websockets import WebRequest
from .klippy_apis import KlippyAPI
from .file_manager.file_manager import FileManager
class JobQueue:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.queued_jobs: Dict[str, QueuedJob] = {}
self.lock = asyncio.Lock()
self.load_on_start = config.getboolean("load_on_startup", False)
self.automatic = config.getboolean("automatic_transition", False)
self.queue_state: str = "ready" if self.automatic else "paused"
self.job_delay = config.getfloat("job_transition_delay", 0.01)
if self.job_delay <= 0.:
raise config.error(
"Value for option 'job_transition_delay' in section [job_queue]"
" must be above 0.0")
self.job_transition_gcode = config.get(
"job_transition_gcode", "").strip()
self.pop_queue_handle: Optional[asyncio.TimerHandle] = None
self.server.register_event_handler(
"server:klippy_ready", self._handle_ready)
self.server.register_event_handler(
"server:klippy_shutdown", self._handle_shutdown)
self.server.register_event_handler(
"job_state:complete", self._on_job_complete)
self.server.register_event_handler(
"job_state:error", self._on_job_abort)
self.server.register_event_handler(
"job_state:cancelled", self._on_job_abort)
self.server.register_notification("job_queue:job_queue_changed")
self.server.register_remote_method("pause_job_queue", self.pause_queue)
self.server.register_remote_method("start_job_queue",
self.start_queue)
self.server.register_endpoint(
"/server/job_queue/job", ['POST', 'DELETE'],
self._handle_job_request)
self.server.register_endpoint(
"/server/job_queue/pause", ['POST'], self._handle_pause_queue)
self.server.register_endpoint(
"/server/job_queue/start", ['POST'], self._handle_start_queue)
self.server.register_endpoint(
"/server/job_queue/status", ['GET'], self._handle_queue_status)
self.server.register_endpoint(
"/server/job_queue/jump", ['POST'], self._handle_jump)
async def _handle_ready(self) -> None:
async with self.lock:
if not self.load_on_start or not self.queued_jobs:
return
# start a queued print
if self.queue_state in ['ready', 'paused']:
event_loop = self.server.get_event_loop()
self._set_queue_state("loading")
self.pop_queue_handle = event_loop.delay_callback(
1., self._pop_job, False)
async def _handle_shutdown(self) -> None:
await self.pause_queue()
if not self.queued_jobs and self.automatic:
self._set_queue_state("ready")
async def _on_job_complete(self,
prev_stats: Dict[str, Any],
new_stats: Dict[str, Any]
) -> None:
async with self.lock:
# Transition to the next job in the queue
if self.queue_state == "ready" and self.queued_jobs:
event_loop = self.server.get_event_loop()
self._set_queue_state("loading")
self.pop_queue_handle = event_loop.delay_callback(
self.job_delay, self._pop_job)
async def _on_job_abort(self,
prev_stats: Dict[str, Any],
new_stats: Dict[str, Any]
) -> None:
async with self.lock:
if self.queued_jobs:
self._set_queue_state("paused")
async def _pop_job(self, need_transition: bool = True) -> None:
self.pop_queue_handle = None
async with self.lock:
if self.queue_state == "paused":
return
if not self.queued_jobs:
qs = "ready" if self.automatic else "paused"
self._set_queue_state(qs)
return
kapis: KlippyAPI = self.server.lookup_component('klippy_apis')
uid, job = list(self.queued_jobs.items())[0]
filename = str(job)
can_print = await self._check_can_print()
if not can_print or self.queue_state != "loading":
self._set_queue_state("paused")
return
try:
if self.job_transition_gcode and need_transition:
await kapis.run_gcode(self.job_transition_gcode)
# Check to see if the queue was paused while running
# the job transition gcode
if self.queue_state != "loading":
raise self.server.error(
"Queue State Changed during Transition Gcode")
self._set_queue_state("starting")
await kapis.start_print(filename, wait_klippy_started=True)
except self.server.error:
logging.exception(f"Error Loading print: {filename}")
self._set_queue_state("paused")
else:
self.queued_jobs.pop(uid, None)
if self.queue_state == "starting":
# If the queue was not paused while starting the print,
set_ready = not self.queued_jobs or self.automatic
self.queue_state = "ready" if set_ready else "paused"
self._send_queue_event(action="job_loaded")
async def _check_can_print(self) -> bool:
# Query the latest stats
kapis: KlippyAPI = self.server.lookup_component('klippy_apis')
try:
result = await kapis.query_objects({"print_stats": None})
except Exception:
# Klippy not connected
return False
if 'print_stats' not in result:
return False
state: str = result['print_stats']['state']
if state in ["printing", "paused"]:
return False
return True
async def queue_job(self,
filenames: Union[str, List[str]],
check_exists: bool = True,
reset: bool = False
) -> None:
async with self.lock:
# Make sure that the file exists
if isinstance(filenames, str):
filenames = [filenames]
if check_exists:
# Make sure all files exist before adding them to the queue
for fname in filenames:
self._check_job_file(fname)
if reset:
self.queued_jobs.clear()
for fname in filenames:
queued_job = QueuedJob(fname)
self.queued_jobs[queued_job.job_id] = queued_job
self._send_queue_event(action="jobs_added")
async def delete_job(self,
job_ids: Union[str, List[str]],
all: bool = False
) -> None:
async with self.lock:
if not self.queued_jobs:
# No jobs in queue, nothing to delete
return
if all:
self.queued_jobs.clear()
elif job_ids:
if isinstance(job_ids, str):
job_ids = [job_ids]
for uid in job_ids:
self.queued_jobs.pop(uid, None)
else:
# Don't notify, nothing was deleted
return
self._send_queue_event(action="jobs_removed")
async def pause_queue(self) -> None:
self._set_queue_state("paused")
if self.pop_queue_handle is not None:
self.pop_queue_handle.cancel()
self.pop_queue_handle = None
# Acquire the lock to wait for any pending operations to
# complete
await self.lock.acquire()
self.lock.release()
async def start_queue(self) -> None:
async with self.lock:
if self.queue_state != "loading":
if self.queued_jobs and await self._check_can_print():
self._set_queue_state("loading")
event_loop = self.server.get_event_loop()
self.pop_queue_handle = event_loop.delay_callback(
0.01, self._pop_job)
else:
self._set_queue_state("ready")
def _job_map_to_list(self) -> List[Dict[str, Any]]:
cur_time = time.time()
return [job.as_dict(cur_time) for
job in self.queued_jobs.values()]
def _check_job_file(self, job_name: str) -> None:
fm: FileManager = self.server.lookup_component('file_manager')
if not fm.check_file_exists("gcodes", job_name):
raise self.server.error(
f"G-Code File {job_name} does not exist")
def _set_queue_state(self, new_state: str) -> None:
if new_state != self.queue_state:
self.queue_state = new_state
self._send_queue_event()
def _send_queue_event(self, action: str = "state_changed"):
updated_queue: Optional[List[Dict[str, Any]]] = None
if action != "state_changed":
updated_queue = self._job_map_to_list()
event_loop = self.server.get_event_loop()
event_loop.delay_callback(
.05, self.server.send_event, "job_queue:job_queue_changed",
{
'action': action,
'updated_queue': updated_queue,
'queue_state': self.queue_state
})
async def _handle_job_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
action = web_request.get_action()
if action == "POST":
files: Union[List[str], str] = web_request.get('filenames')
reset = web_request.get_boolean("reset", False)
if isinstance(files, str):
files = [f.strip() for f in files.split(',') if f.strip()]
# Validate that all files exist before queueing
await self.queue_job(files, reset=reset)
elif action == "DELETE":
if web_request.get_boolean("all", False):
await self.delete_job([], all=True)
else:
job_ids: Union[List[str], str] = web_request.get('job_ids')
if isinstance(job_ids, str):
job_ids = [f.strip() for f in job_ids.split(',')
if f.strip()]
await self.delete_job(job_ids)
else:
raise self.server.error(f"Invalid action: {action}")
return {
'queued_jobs': self._job_map_to_list(),
'queue_state': self.queue_state
}
async def _handle_pause_queue(self,
web_request: WebRequest
) -> Dict[str, Any]:
await self.pause_queue()
return {
'queued_jobs': self._job_map_to_list(),
'queue_state': self.queue_state
}
async def _handle_start_queue(self,
web_request: WebRequest
) -> Dict[str, Any]:
await self.start_queue()
return {
'queued_jobs': self._job_map_to_list(),
'queue_state': self.queue_state
}
async def _handle_queue_status(self,
web_request: WebRequest
) -> Dict[str, Any]:
return {
'queued_jobs': self._job_map_to_list(),
'queue_state': self.queue_state
}
async def _handle_jump(self, web_request: WebRequest) -> Dict[str, Any]:
job_id: str = web_request.get("job_id")
async with self.lock:
job = self.queued_jobs.pop(job_id, None)
if job is None:
raise self.server.error(f"Invalid job id: {job_id}")
new_queue = {job_id: job}
new_queue.update(self.queued_jobs)
self.queued_jobs = new_queue
return {
'queued_jobs': self._job_map_to_list(),
'queue_state': self.queue_state
}
async def close(self):
await self.pause_queue()
class QueuedJob:
def __init__(self, filename: str) -> None:
self.filename = filename
self.job_id = f"{id(self):016X}"
self.time_added = time.time()
def __str__(self) -> str:
return self.filename
def as_dict(self, cur_time: float) -> Dict[str, Any]:
return {
'filename': self.filename,
'job_id': self.job_id,
'time_added': self.time_added,
'time_in_queue': cur_time - self.time_added
}
def load_component(config: ConfigHelper) -> JobQueue:
return JobQueue(config)
+95
View File
@@ -0,0 +1,95 @@
# Klippy job state event handlers
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import logging
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Optional,
Dict,
List,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from .klippy_apis import KlippyAPI
class JobState:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.last_print_stats: Dict[str, Any] = {}
self.server.register_event_handler(
"server:klippy_started", self._handle_started)
self.server.register_event_handler(
"server:status_update", self._status_update)
async def _handle_started(self, state: str) -> None:
if state != "ready":
return
kapis: KlippyAPI = self.server.lookup_component('klippy_apis')
sub: Dict[str, Optional[List[str]]] = {"print_stats": None}
try:
result = await kapis.subscribe_objects(sub)
except self.server.error as e:
logging.info(f"Error subscribing to print_stats")
self.last_print_stats = result.get("print_stats", {})
if "state" in self.last_print_stats:
state = self.last_print_stats["state"]
logging.info(f"Job state initialized: {state}")
async def _status_update(self, data: Dict[str, Any]) -> None:
if 'print_stats' not in data:
return
ps = data['print_stats']
if "state" in ps:
prev_ps = dict(self.last_print_stats)
old_state: str = prev_ps['state']
new_state: str = ps['state']
new_ps = dict(self.last_print_stats)
new_ps.update(ps)
if new_state is not old_state:
if new_state == "printing":
# The "printing" state needs some special handling
# to detect "resets" and a transition from pause to resume
if self._check_resumed(prev_ps, new_ps):
new_state = "resumed"
else:
logging.info(
f"Job Started: {new_ps['filename']}"
)
new_state = "started"
logging.debug(
f"Job State Changed - Prev State: {old_state}, "
f"New State: {new_state}"
)
self.server.send_event(
f"job_state:{new_state}", prev_ps, new_ps)
if "info" in ps:
cur_layer: Optional[int] = ps["info"].get("current_layer")
if cur_layer is not None:
total: int = ps["info"].get("total_layer", 0)
self.server.send_event(
"job_state:layer_changed", cur_layer, total
)
self.last_print_stats.update(ps)
def _check_resumed(self,
prev_ps: Dict[str, Any],
new_ps: Dict[str, Any]
) -> bool:
return (
prev_ps['state'] == "paused" and
prev_ps['filename'] == new_ps['filename'] and
prev_ps['total_duration'] < new_ps['total_duration']
)
def get_last_stats(self) -> Dict[str, Any]:
return dict(self.last_print_stats)
def load_component(config: ConfigHelper) -> JobState:
return JobState(config)
+122 -41
View File
@@ -3,8 +3,28 @@
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import utils
from websockets import WebRequest
from __future__ import annotations
from ..utils import Sentinel
from ..websockets import WebRequest, Subscribable
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Union,
Optional,
Dict,
List,
TypeVar,
Mapping,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..websockets import WebRequest
from ..klippy_connection import KlippyConnection as Klippy
Subscription = Dict[str, Optional[List[Any]]]
_T = TypeVar("_T")
INFO_ENDPOINT = "info"
ESTOP_ENDPOINT = "emergency_stop"
@@ -16,16 +36,15 @@ STATUS_ENDPOINT = "objects/query"
OBJ_LIST_ENDPOINT = "objects/list"
REG_METHOD_ENDPOINT = "register_remote_method"
class Sentinel:
pass
class KlippyAPI:
def __init__(self, config):
class KlippyAPI(Subscribable):
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.klippy: Klippy = self.server.lookup_component("klippy_connection")
app_args = self.server.get_app_args()
self.version = app_args.get('software_version')
# Maintain a subscription for all moonraker requests, as
# we do not want to overwrite them
self.host_subscription = {}
self.host_subscription: Subscription = {}
# Register GCode Aliases
self.server.register_endpoint(
@@ -41,51 +60,98 @@ class KlippyAPI:
self.server.register_endpoint(
"/printer/firmware_restart", ['POST'], self._gcode_firmware_restart)
async def _gcode_pause(self, web_request):
return await self.run_gcode("PAUSE")
async def _gcode_pause(self, web_request: WebRequest) -> str:
return await self.pause_print()
async def _gcode_resume(self, web_request):
return await self.run_gcode("RESUME")
async def _gcode_resume(self, web_request: WebRequest) -> str:
return await self.resume_print()
async def _gcode_cancel(self, web_request):
return await self.run_gcode("CANCEL_PRINT")
async def _gcode_cancel(self, web_request: WebRequest) -> str:
return await self.cancel_print()
async def _gcode_start_print(self, web_request):
filename = web_request.get_str('filename')
async def _gcode_start_print(self, web_request: WebRequest) -> str:
filename: str = web_request.get_str('filename')
return await self.start_print(filename)
async def _gcode_restart(self, web_request):
async def _gcode_restart(self, web_request: WebRequest) -> str:
return await self.do_restart("RESTART")
async def _gcode_firmware_restart(self, web_request):
async def _gcode_firmware_restart(self, web_request: WebRequest) -> str:
return await self.do_restart("FIRMWARE_RESTART")
async def _send_klippy_request(self, method, params, default=Sentinel):
async def _send_klippy_request(
self,
method: str,
params: Dict[str, Any],
default: Any = Sentinel.MISSING
) -> Any:
try:
result = await self.server.make_request(
WebRequest(method, params, conn=self))
except self.server.error as e:
if default == Sentinel:
req = WebRequest(method, params, conn=self)
result = await self.klippy.request(req)
except self.server.error:
if default is Sentinel.MISSING:
raise
result = default
return result
async def run_gcode(self, script, default=Sentinel):
async def run_gcode(self,
script: str,
default: Any = Sentinel.MISSING
) -> str:
params = {'script': script}
result = await self._send_klippy_request(
GCODE_ENDPOINT, params, default)
return result
async def start_print(self, filename):
async def start_print(
self, filename: str, wait_klippy_started: bool = False
) -> str:
# WARNING: Do not call this method from within the following
# event handlers when "wait_klippy_started" is set to True:
# klippy_identified, klippy_started, klippy_ready, klippy_disconnect
# Doing so will result in "wait_started" blocking for the specifed
# timeout (default 20s) and returning False.
# XXX - validate that file is on disk
if filename[0] == '/':
filename = filename[1:]
# Escape existing double quotes in the file name
filename = filename.replace("\"", "\\\"")
script = f'SDCARD_PRINT_FILE FILENAME="{filename}"'
if wait_klippy_started:
await self.klippy.wait_started()
return await self.run_gcode(script)
async def do_restart(self, gc):
async def pause_print(
self, default: Union[Sentinel, _T] = Sentinel.MISSING
) -> Union[_T, str]:
self.server.send_event("klippy_apis:pause_requested")
return await self._send_klippy_request(
"pause_resume/pause", {}, default)
async def resume_print(
self, default: Union[Sentinel, _T] = Sentinel.MISSING
) -> Union[_T, str]:
self.server.send_event("klippy_apis:resume_requested")
return await self._send_klippy_request(
"pause_resume/resume", {}, default)
async def cancel_print(
self, default: Union[Sentinel, _T] = Sentinel.MISSING
) -> Union[_T, str]:
self.server.send_event("klippy_apis:cancel_requested")
return await self._send_klippy_request(
"pause_resume/cancel", {}, default)
async def do_restart(
self, gc: str, wait_klippy_started: bool = False
) -> str:
# WARNING: Do not call this method from within the following
# event handlers when "wait_klippy_started" is set to True:
# klippy_identified, klippy_started, klippy_ready, klippy_disconnect
# Doing so will result in "wait_started" blocking for the specifed
# timeout (default 20s) and returning False.
if wait_klippy_started:
await self.klippy.wait_started()
try:
result = await self.run_gcode(gc)
except self.server.error as e:
@@ -95,28 +161,38 @@ class KlippyAPI:
raise
return result
async def list_endpoints(self, default=Sentinel):
async def list_endpoints(self,
default: Union[Sentinel, _T] = Sentinel.MISSING
) -> Union[_T, Dict[str, List[str]]]:
return await self._send_klippy_request(
LIST_EPS_ENDPOINT, {}, default)
async def emergency_stop(self, default=Sentinel):
return await self._send_klippy_request(ESTOP_ENDPOINT, {}, default)
async def emergency_stop(self) -> str:
return await self._send_klippy_request(ESTOP_ENDPOINT, {})
async def get_klippy_info(self, send_id=False, default=Sentinel):
async def get_klippy_info(self,
send_id: bool = False,
default: Union[Sentinel, _T] = Sentinel.MISSING
) -> Union[_T, Dict[str, Any]]:
params = {}
if send_id:
ver = utils.get_software_version()
ver = self.version
params = {'client_info': {'program': "Moonraker", 'version': ver}}
return await self._send_klippy_request(INFO_ENDPOINT, params, default)
async def get_object_list(self, default=Sentinel):
async def get_object_list(self,
default: Union[Sentinel, _T] = Sentinel.MISSING
) -> Union[_T, List[str]]:
result = await self._send_klippy_request(
OBJ_LIST_ENDPOINT, {}, default)
if isinstance(result, dict) and 'objects' in result:
return result['objects']
return result
async def query_objects(self, objects, default=Sentinel):
async def query_objects(self,
objects: Mapping[str, Optional[List[str]]],
default: Union[Sentinel, _T] = Sentinel.MISSING
) -> Union[_T, Dict[str, Any]]:
params = {'objects': objects}
result = await self._send_klippy_request(
STATUS_ENDPOINT, params, default)
@@ -124,7 +200,10 @@ class KlippyAPI:
return result['status']
return result
async def subscribe_objects(self, objects, default=Sentinel):
async def subscribe_objects(self,
objects: Mapping[str, Optional[List[str]]],
default: Union[Sentinel, _T] = Sentinel.MISSING
) -> Union[_T, Dict[str, Any]]:
for obj, items in objects.items():
if obj in self.host_subscription:
prev = self.host_subscription[obj]
@@ -142,20 +221,22 @@ class KlippyAPI:
return result['status']
return result
async def subscribe_gcode_output(self, default=Sentinel):
async def subscribe_gcode_output(self) -> str:
template = {'response_template':
{'method': "process_gcode_response"}}
return await self._send_klippy_request(
GC_OUTPUT_ENDPOINT, template, default)
return await self._send_klippy_request(GC_OUTPUT_ENDPOINT, template)
async def register_method(self, method_name):
async def register_method(self, method_name: str) -> str:
return await self._send_klippy_request(
REG_METHOD_ENDPOINT,
{'response_template': {"method": method_name},
'remote_method': method_name})
def send_status(self, status):
def send_status(self,
status: Dict[str, Any],
eventtime: float
) -> None:
self.server.send_event("server:status_update", status)
def load_component(config):
def load_component(config: ConfigHelper) -> KlippyAPI:
return KlippyAPI(config)
+129
View File
@@ -0,0 +1,129 @@
# LDAP authentication for Moonraker
#
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
# Copyright (C) 2022 Luca Schöneberg <luca-schoeneberg@outlook.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import asyncio
import logging
import ldap3
from ldap3.core.exceptions import LDAPExceptionError
# Annotation imports
from typing import (
TYPE_CHECKING,
Optional
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ldap3.abstract.entry import Entry
class MoonrakerLDAP:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.ldap_host = config.get('ldap_host')
self.ldap_port = config.getint("ldap_port", None)
self.ldap_secure = config.getboolean("ldap_secure", False)
base_dn_template = config.gettemplate('base_dn')
self.base_dn = base_dn_template.render()
self.group_dn: Optional[str] = None
group_dn_template = config.gettemplate("group_dn", None)
if group_dn_template is not None:
self.group_dn = group_dn_template.render()
self.active_directory = config.getboolean('is_active_directory', False)
self.bind_dn: Optional[str] = None
self.bind_password: Optional[str] = None
bind_dn_template = config.gettemplate('bind_dn', None)
bind_pass_template = config.gettemplate('bind_password', None)
if bind_dn_template is not None:
self.bind_dn = bind_dn_template.render()
if bind_pass_template is None:
raise config.error(
"Section [ldap]: Option 'bind_password' is "
"required when 'bind_dn' is provided"
)
self.bind_password = bind_pass_template.render()
self.user_filter: Optional[str] = None
user_filter_template = config.gettemplate('user_filter', None)
if user_filter_template is not None:
self.user_filter = user_filter_template.render()
if "USERNAME" not in self.user_filter:
raise config.error(
"Section [ldap]: Option 'user_filter' is "
"is missing required token USERNAME"
)
self.lock = asyncio.Lock()
async def authenticate_ldap_user(self, username, password) -> None:
eventloop = self.server.get_event_loop()
async with self.lock:
await eventloop.run_in_thread(
self._perform_ldap_auth, username, password
)
def _perform_ldap_auth(self, username, password) -> None:
server = ldap3.Server(
self.ldap_host, self.ldap_port, use_ssl=self.ldap_secure,
connect_timeout=10.
)
conn_args = {
"user": self.bind_dn,
"password": self.bind_password,
"auto_bind": ldap3.AUTO_BIND_NO_TLS,
}
attr_name = "sAMAccountName" if self.active_directory else "uid"
ldfilt = f"(&(objectClass=Person)({attr_name}={username}))"
if self.user_filter:
ldfilt = self.user_filter.replace("USERNAME", username)
try:
with ldap3.Connection(server, **conn_args) as conn:
ret = conn.search(
self.base_dn, ldfilt, attributes=["memberOf"]
)
if not ret:
raise self.server.error(
f"LDAP User '{username}' Not Found", 401
)
user: Entry = conn.entries[0]
rebind_success = conn.rebind(user.entry_dn, password)
if not rebind_success:
# Server may not allow rebinding, attempt to start
# a new connection to validate credentials
logging.debug(
"LDAP Rebind failed, attempting to validate credentials "
"with new connection."
)
conn_args["user"] = user.entry_dn
conn_args["password"] = password
with ldap3.Connection(server, **conn_args) as conn:
if self._validate_group(username, user):
return
elif self._validate_group(username, user):
return
except LDAPExceptionError:
err_msg = "LDAP authentication failed"
else:
err_msg = "Invalid LDAP Username or Password"
raise self.server.error(err_msg, 401)
def _validate_group(self, username: str, user: Entry) -> bool:
if self.group_dn is None:
logging.debug(f"LDAP User {username} login successful")
return True
if not hasattr(user, "memberOf"):
return False
for group in user.memberOf.values:
if group == self.group_dn:
logging.debug(
f"LDAP User {username} group match success, "
"login successful"
)
return True
return False
def load_component(config: ConfigHelper) -> MoonrakerLDAP:
return MoonrakerLDAP(config)
File diff suppressed because it is too large. Load diff
+786
View File
@@ -0,0 +1,786 @@
# MQTT client implementation for Moonraker
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import socket
import asyncio
import logging
import json
import pathlib
import ssl
from collections import deque
import paho.mqtt.client as paho_mqtt
from ..websockets import Subscribable, WebRequest, JsonRPC, APITransport
# Annotation imports
from typing import (
List,
Optional,
TYPE_CHECKING,
Any,
Callable,
Coroutine,
Dict,
Union,
Tuple,
Awaitable,
Deque,
)
if TYPE_CHECKING:
from ..app import APIDefinition
from ..confighelper import ConfigHelper
from ..klippy_connection import KlippyConnection as Klippy
FlexCallback = Callable[[bytes], Optional[Coroutine]]
RPCCallback = Callable[..., Coroutine]
DUP_API_REQ_CODE = -10000
MQTT_PROTOCOLS = {
'v3.1': paho_mqtt.MQTTv31,
'v3.1.1': paho_mqtt.MQTTv311,
'v5': paho_mqtt.MQTTv5
}
class ExtPahoClient(paho_mqtt.Client):
# Override reconnection to take a connected socket. This allows Moonraker
# create the socket connection asynchronously
def reconnect(self, sock: Optional[socket.socket] = None):
"""Reconnect the client after a disconnect. Can only be called after
connect()/connect_async()."""
if len(self._host) == 0:
raise ValueError('Invalid host.')
if self._port <= 0:
raise ValueError('Invalid port number.')
if hasattr(self, "_out_packet_mutex"):
# Paho Mqtt Version < 1.6.x
self._in_packet = {
"command": 0,
"have_remaining": 0,
"remaining_count": [],
"remaining_mult": 1,
"remaining_length": 0,
"packet": b"",
"to_process": 0,
"pos": 0
}
with self._out_packet_mutex:
self._out_packet = deque() # type: ignore
with self._current_out_packet_mutex:
self._current_out_packet = None
else:
self._in_packet = {
"command": 0,
"have_remaining": 0,
"remaining_count": [],
"remaining_mult": 1,
"remaining_length": 0,
"packet": bytearray(b""),
"to_process": 0,
"pos": 0
}
self._out_packet = deque() # type: ignore
with self._msgtime_mutex:
self._last_msg_in = paho_mqtt.time_func()
self._last_msg_out = paho_mqtt.time_func()
self._ping_t = 0
self._state = paho_mqtt.mqtt_cs_new
self._sock_close()
# Put messages in progress in a valid state.
self._messages_reconnect_reset()
if sock is None:
sock = self._create_socket_connection()
if self._ssl:
# SSL is only supported when SSLContext is available
# (implies Python >= 2.7.9 or >= 3.2)
verify_host = not self._tls_insecure
try:
# Try with server_hostname, even it's not supported in
# certain scenarios
sock = self._ssl_context.wrap_socket(
sock,
server_hostname=self._host,
do_handshake_on_connect=False,
)
except ssl.CertificateError:
# CertificateError is derived from ValueError
raise
except ValueError:
# Python version requires SNI in order to handle
# server_hostname, but SNI is not available
sock = self._ssl_context.wrap_socket(
sock,
do_handshake_on_connect=False,
)
else:
# If SSL context has already checked hostname, then don't need
# to do it again
if (hasattr(self._ssl_context, 'check_hostname') and
self._ssl_context.check_hostname):
verify_host = False
assert isinstance(sock, ssl.SSLSocket)
sock.settimeout(self._keepalive)
sock.do_handshake()
if verify_host:
ssl.match_hostname(sock.getpeercert(), self._host)
if self._transport == "websockets":
sock.settimeout(self._keepalive)
sock = paho_mqtt.WebsocketWrapper(
sock, self._host, self._port, self._ssl,
self._websocket_path, self._websocket_extra_headers
)
self._sock = sock
assert self._sock is not None
self._sock.setblocking(False)
self._registered_write = False
self._call_socket_open()
return self._send_connect(self._keepalive)
class SubscriptionHandle:
def __init__(self, topic: str, callback: FlexCallback) -> None:
self.callback = callback
self.topic = topic
class BrokerAckLogger:
def __init__(self, topics: List[str], action: str) -> None:
self.topics = topics
self.action = action
def __call__(self, fut: asyncio.Future) -> None:
if self.action == "subscribe":
res: Union[List[int], List[paho_mqtt.ReasonCodes]]
res = fut.result()
log_msg = "MQTT Subscriptions Acknowledged"
if len(res) != len(self.topics):
log_msg += "\nTopic / QOS count mismatch, " \
f"\nTopics: {self.topics} " \
f"\nQoS responses: {res}"
else:
for topic, qos in zip(self.topics, res):
log_msg += f"\n Topic: {topic} | "
if isinstance(qos, paho_mqtt.ReasonCodes):
log_msg += qos.getName()
else:
log_msg += f"Granted QoS {qos}"
elif self.action == "unsubscribe":
log_msg = "MQTT Unsubscribe Acknowledged"
for topic in self.topics:
log_msg += f"\n Topic: {topic}"
else:
log_msg = f"Unknown action: {self.action}"
logging.debug(log_msg)
SubscribedDict = Dict[str, Tuple[int, List[SubscriptionHandle]]]
class AIOHelper:
def __init__(self, client: paho_mqtt.Client) -> None:
self.loop = asyncio.get_running_loop()
self.client = client
self.client.on_socket_open = self._on_socket_open
self.client.on_socket_close = self._on_socket_close
self.client._on_socket_register_write = self._on_socket_register_write
self.client._on_socket_unregister_write = \
self._on_socket_unregister_write
self.misc_task: Optional[asyncio.Task] = None
def _on_socket_open(self,
client: paho_mqtt.Client,
userdata: Any,
sock: socket.socket
) -> None:
logging.info("MQTT Socket Opened")
self.loop.add_reader(sock, client.loop_read)
self.misc_task = self.loop.create_task(self.misc_loop())
def _on_socket_close(self,
client: paho_mqtt.Client,
userdata: Any,
sock: socket.socket
) -> None:
logging.info("MQTT Socket Closed")
self.loop.remove_reader(sock)
if self.misc_task is not None:
self.misc_task.cancel()
def _on_socket_register_write(self,
client: paho_mqtt.Client,
userdata: Any,
sock: socket.socket
) -> None:
self.loop.add_writer(sock, client.loop_write)
def _on_socket_unregister_write(self,
client: paho_mqtt.Client,
userdata: Any,
sock: socket.socket
) -> None:
self.loop.remove_writer(sock)
async def misc_loop(self) -> None:
while self.client.loop_misc() == paho_mqtt.MQTT_ERR_SUCCESS:
try:
await asyncio.sleep(1)
except asyncio.CancelledError:
break
logging.info("MQTT Misc Loop Complete")
class MQTTClient(APITransport, Subscribable):
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.event_loop = self.server.get_event_loop()
self.klippy: Klippy = self.server.lookup_component("klippy_connection")
self.address: str = config.get('address')
self.port: int = config.getint('port', 1883)
user = config.gettemplate('username', None)
self.user_name: Optional[str] = None
if user:
self.user_name = user.render()
pw_file_path = config.get('password_file', None, deprecate=True)
pw_template = config.gettemplate('password', None)
self.password: Optional[str] = None
if pw_file_path is not None:
pw_file = pathlib.Path(pw_file_path).expanduser().absolute()
if not pw_file.exists():
raise config.error(
f"Password file '{pw_file}' does not exist")
self.password = pw_file.read_text().strip()
if pw_template is not None:
self.password = pw_template.render()
protocol = config.get('mqtt_protocol', "v3.1.1")
self.protocol = MQTT_PROTOCOLS.get(protocol, None)
if self.protocol is None:
raise config.error(
f"Invalid value '{protocol}' for option 'mqtt_protocol' "
"in section [mqtt]. Must be one of "
f"{MQTT_PROTOCOLS.values()}")
self.instance_name = config.get('instance_name', socket.gethostname())
if '+' in self.instance_name or '#' in self.instance_name:
raise config.error(
"Option 'instance_name' in section [mqtt] cannot "
"contain a wildcard.")
self.qos = config.getint("default_qos", 0)
if self.qos > 2 or self.qos < 0:
raise config.error(
"Option 'default_qos' in section [mqtt] must be "
"between 0 and 2")
self.publish_split_status = \
config.getboolean("publish_split_status", False)
self.client = ExtPahoClient(protocol=self.protocol)
self.client.on_connect = self._on_connect
self.client.on_message = self._on_message
self.client.on_disconnect = self._on_disconnect
self.client.on_publish = self._on_publish
self.client.on_subscribe = self._on_subscribe
self.client.on_unsubscribe = self._on_unsubscribe
self.connect_evt: asyncio.Event = asyncio.Event()
self.disconnect_evt: Optional[asyncio.Event] = None
self.connect_task: Optional[asyncio.Task] = None
self.subscribed_topics: SubscribedDict = {}
self.pending_responses: List[asyncio.Future] = []
self.pending_acks: Dict[int, asyncio.Future] = {}
self.server.register_endpoint(
"/server/mqtt/publish", ["POST"],
self._handle_publish_request,
transports=["http", "websocket", "internal"])
self.server.register_endpoint(
"/server/mqtt/subscribe", ["POST"],
self._handle_subscription_request,
transports=["http", "websocket", "internal"])
# Subscribe to API requests
self.json_rpc = JsonRPC(self.server, transport="MQTT")
self.api_request_topic = f"{self.instance_name}/moonraker/api/request"
self.api_resp_topic = f"{self.instance_name}/moonraker/api/response"
self.klipper_status_topic = f"{self.instance_name}/klipper/status"
self.klipper_state_prefix = f"{self.instance_name}/klipper/state"
self.moonraker_status_topic = f"{self.instance_name}/moonraker/status"
status_cfg: Dict[str, Any] = config.getdict("status_objects", {},
allow_empty_fields=True)
self.status_objs: Dict[str, Any] = {}
for key, val in status_cfg.items():
if val is not None:
self.status_objs[key] = [v.strip() for v in val.split(',')
if v.strip()]
else:
self.status_objs[key] = None
if status_cfg:
logging.debug(f"MQTT: Status Objects Set: {self.status_objs}")
self.server.register_event_handler(
"server:klippy_started", self._handle_klippy_started
)
self.timestamp_deque: Deque = deque(maxlen=20)
self.api_qos = config.getint('api_qos', self.qos)
if config.getboolean("enable_moonraker_api", True):
api_cache = self.server.register_api_transport("mqtt", self)
for api_def in api_cache.values():
if "mqtt" in api_def.supported_transports:
self.register_api_handler(api_def)
self.subscribe_topic(self.api_request_topic,
self._process_api_request,
self.api_qos)
self.server.register_remote_method("publish_mqtt_topic",
self._publish_from_klipper)
logging.info(
f"\nReserved MQTT topics:\n"
f"API Request: {self.api_request_topic}\n"
f"API Response: {self.api_resp_topic}\n"
f"Moonraker Status: {self.moonraker_status_topic}\n"
f"Klipper Status: {self.klipper_status_topic}")
async def component_init(self) -> None:
# We must wait for the IOLoop (asyncio event loop) to start
# prior to retrieving it
self.helper = AIOHelper(self.client)
if self.user_name is not None:
self.client.username_pw_set(self.user_name, self.password)
self.client.will_set(self.moonraker_status_topic,
payload=json.dumps({'server': 'offline'}),
qos=self.qos, retain=True)
self.client.connect_async(self.address, self.port)
self.connect_task = self.event_loop.create_task(
self._do_reconnect(first=True)
)
async def _handle_klippy_started(self, state: str) -> None:
if self.status_objs:
args = {'objects': self.status_objs}
try:
await self.klippy.request(
WebRequest("objects/subscribe", args, conn=self))
except self.server.error:
pass
def _on_message(self,
client: str,
user_data: Any,
message: paho_mqtt.MQTTMessage
) -> None:
topic = message.topic
if topic in self.subscribed_topics:
cb_hdls = self.subscribed_topics[topic][1]
for hdl in cb_hdls:
self.event_loop.register_callback(
hdl.callback, message.payload)
else:
logging.debug(
f"Unregistered MQTT Topic Received: {topic}, "
f"payload: {message.payload.decode()}")
def _on_connect(self,
client: paho_mqtt.Client,
user_data: Any,
flags: Dict[str, Any],
reason_code: Union[int, paho_mqtt.ReasonCodes],
properties: Optional[paho_mqtt.Properties] = None
) -> None:
logging.info("MQTT Client Connected")
if reason_code == 0:
self.publish_topic(self.moonraker_status_topic,
{'server': 'online'}, retain=True)
subs = [(k, v[0]) for k, v in self.subscribed_topics.items()]
if subs:
res, msg_id = client.subscribe(subs)
if msg_id is not None:
sub_fut: asyncio.Future = asyncio.Future()
topics = list(self.subscribed_topics.keys())
sub_fut.add_done_callback(
BrokerAckLogger(topics, "subscribe"))
self.pending_acks[msg_id] = sub_fut
self.connect_evt.set()
self.server.send_event("mqtt:connected")
else:
if isinstance(reason_code, int):
err_str = paho_mqtt.connack_string(reason_code)
else:
err_str = reason_code.getName()
self.server.set_failed_component("mqtt")
self.server.add_warning(f"MQTT Connection Failed: {err_str}")
def _on_disconnect(self,
client: paho_mqtt.Client,
user_data: Any,
reason_code: int,
properties: Optional[paho_mqtt.Properties] = None
) -> None:
if self.disconnect_evt is not None:
self.disconnect_evt.set()
elif self.is_connected():
# The server connection was dropped, attempt to reconnect
logging.info("MQTT Server Disconnected, reason: "
f"{paho_mqtt.error_string(reason_code)}")
if self.connect_task is None:
self.connect_task = asyncio.create_task(self._do_reconnect())
self.server.send_event("mqtt:disconnected")
self.connect_evt.clear()
def _on_publish(self,
client: paho_mqtt.Client,
user_data: Any,
msg_id: int
) -> None:
pub_fut = self.pending_acks.pop(msg_id, None)
if pub_fut is not None and not pub_fut.done():
pub_fut.set_result(None)
def _on_subscribe(self,
client: paho_mqtt.Client,
user_data: Any,
msg_id: int,
flex: Union[List[int], List[paho_mqtt.ReasonCodes]],
properties: Optional[paho_mqtt.Properties] = None
) -> None:
sub_fut = self.pending_acks.pop(msg_id, None)
if sub_fut is not None and not sub_fut.done():
sub_fut.set_result(flex)
def _on_unsubscribe(self,
client: paho_mqtt.Client,
user_data: Any,
msg_id: int,
properties: Optional[paho_mqtt.Properties] = None,
reasoncodes: Optional[paho_mqtt.ReasonCodes] = None
) -> None:
unsub_fut = self.pending_acks.pop(msg_id, None)
if unsub_fut is not None and not unsub_fut.done():
unsub_fut.set_result(None)
async def _do_reconnect(self, first: bool = False) -> None:
logging.info("Attempting MQTT Connect/Reconnect")
last_err: Exception = Exception()
while True:
if not first:
try:
await asyncio.sleep(2.)
except asyncio.CancelledError:
raise
first = False
try:
sock = await self.event_loop.create_socket_connection(
(self.address, self.port), timeout=10
)
self.client.reconnect(sock)
except asyncio.CancelledError:
raise
except Exception as e:
if type(last_err) != type(e) or last_err.args != e.args:
logging.exception("MQTT Connection Error")
last_err = e
continue
self.client.socket().setsockopt(
socket.SOL_SOCKET, socket.SO_SNDBUF, 2048)
break
self.connect_task = None
async def wait_connection(self, timeout: Optional[float] = None) -> bool:
try:
await asyncio.wait_for(self.connect_evt.wait(), timeout)
except asyncio.TimeoutError:
return False
return True
def is_connected(self) -> bool:
return self.connect_evt.is_set()
def subscribe_topic(self,
topic: str,
callback: FlexCallback,
qos: Optional[int] = None
) -> SubscriptionHandle:
if '#' in topic or '+' in topic:
raise self.server.error("Wildcards may not be used")
qos = qos or self.qos
if qos > 2 or qos < 0:
raise self.server.error("QOS must be between 0 and 2")
hdl = SubscriptionHandle(topic, callback)
sub_handles = [hdl]
need_sub = True
if topic in self.subscribed_topics:
prev_qos, sub_handles = self.subscribed_topics[topic]
qos = max(qos, prev_qos)
sub_handles.append(hdl)
need_sub = qos != prev_qos
self.subscribed_topics[topic] = (qos, sub_handles)
if self.is_connected() and need_sub:
res, msg_id = self.client.subscribe(topic, qos)
if msg_id is not None:
sub_fut: asyncio.Future = asyncio.Future()
sub_fut.add_done_callback(
BrokerAckLogger([topic], "subscribe"))
self.pending_acks[msg_id] = sub_fut
return hdl
def unsubscribe(self, hdl: SubscriptionHandle) -> None:
topic = hdl.topic
if topic in self.subscribed_topics:
sub_hdls = self.subscribed_topics[topic][1]
try:
sub_hdls.remove(hdl)
except Exception:
pass
if not sub_hdls:
del self.subscribed_topics[topic]
res, msg_id = self.client.unsubscribe(topic)
if msg_id is not None:
unsub_fut: asyncio.Future = asyncio.Future()
unsub_fut.add_done_callback(
BrokerAckLogger([topic], "unsubscribe"))
self.pending_acks[msg_id] = unsub_fut
def publish_topic(self,
topic: str,
payload: Any = None,
qos: Optional[int] = None,
retain: bool = False
) -> Awaitable[None]:
qos = qos or self.qos
if qos > 2 or qos < 0:
raise self.server.error("QOS must be between 0 and 2")
pub_fut: asyncio.Future = asyncio.Future()
if isinstance(payload, (dict, list)):
try:
payload = json.dumps(payload)
except json.JSONDecodeError:
raise self.server.error(
"Dict or List is not json encodable") from None
elif isinstance(payload, bool):
payload = str(payload).lower()
try:
msg_info = self.client.publish(topic, payload, qos, retain)
if msg_info.is_published():
pub_fut.set_result(None)
else:
if qos == 0:
# There is no delivery guarantee for qos == 0, so
# it is possible that the on_publish event will
# not be called if paho mqtt encounters an error
# during publication. Return immediately as
# a workaround.
if msg_info.rc != paho_mqtt.MQTT_ERR_SUCCESS:
err_str = paho_mqtt.error_string(msg_info.rc)
pub_fut.set_exception(self.server.error(
f"MQTT Publish Error: {err_str}", 503))
else:
pub_fut.set_result(None)
return pub_fut
self.pending_acks[msg_info.mid] = pub_fut
except ValueError:
pub_fut.set_exception(self.server.error(
"MQTT Message Queue Full", 529))
except Exception as e:
pub_fut.set_exception(self.server.error(
f"MQTT Publish Error: {e}", 503))
return pub_fut
async def publish_topic_with_response(self,
topic: str,
response_topic: str,
payload: Any = None,
qos: Optional[int] = None,
retain: bool = False,
timeout: Optional[float] = None
) -> bytes:
qos = qos or self.qos
if qos > 2 or qos < 0:
raise self.server.error("QOS must be between 0 and 2")
resp_fut: asyncio.Future = asyncio.Future()
resp_hdl = self.subscribe_topic(
response_topic, resp_fut.set_result, qos)
self.pending_responses.append(resp_fut)
try:
await asyncio.wait_for(self.publish_topic(
topic, payload, qos, retain), timeout)
await asyncio.wait_for(resp_fut, timeout)
except asyncio.TimeoutError:
logging.info(f"Response to request {topic} timed out")
raise self.server.error("MQTT Request Timed Out", 504)
finally:
try:
self.pending_responses.remove(resp_fut)
except Exception:
pass
self.unsubscribe(resp_hdl)
return resp_fut.result()
async def _handle_publish_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
topic: str = web_request.get_str("topic")
payload: Any = web_request.get("payload", None)
qos: int = web_request.get_int("qos", self.qos)
retain: bool = web_request.get_boolean("retain", False)
timeout: Optional[float] = web_request.get_float('timeout', None)
try:
await asyncio.wait_for(self.publish_topic(
topic, payload, qos, retain), timeout)
except asyncio.TimeoutError:
raise self.server.error("MQTT Publish Timed Out", 504)
return {
"topic": topic
}
async def _handle_subscription_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
topic: str = web_request.get_str("topic")
qos: int = web_request.get_int("qos", self.qos)
timeout: Optional[float] = web_request.get_float('timeout', None)
resp: asyncio.Future = asyncio.Future()
hdl: Optional[SubscriptionHandle] = None
try:
hdl = self.subscribe_topic(topic, resp.set_result, qos)
self.pending_responses.append(resp)
await asyncio.wait_for(resp, timeout)
ret: bytes = resp.result()
except asyncio.TimeoutError:
raise self.server.error("MQTT Subscribe Timed Out", 504)
finally:
try:
self.pending_responses.remove(resp)
except Exception:
pass
if hdl is not None:
self.unsubscribe(hdl)
try:
payload = json.loads(ret)
except json.JSONDecodeError:
payload = ret.decode()
return {
'topic': topic,
'payload': payload
}
async def _process_api_request(self, payload: bytes) -> None:
response = await self.json_rpc.dispatch(payload.decode())
if response is not None:
await self.publish_topic(self.api_resp_topic, response,
self.api_qos)
def register_api_handler(self, api_def: APIDefinition) -> None:
if api_def.callback is None:
# Remote API, uses RPC to reach out to Klippy
mqtt_method = api_def.jrpc_methods[0]
rpc_cb = self._generate_remote_callback(api_def.endpoint)
self.json_rpc.register_method(mqtt_method, rpc_cb)
else:
# Local API, uses local callback
for mqtt_method, req_method in \
zip(api_def.jrpc_methods, api_def.request_methods):
rpc_cb = self._generate_local_callback(
api_def.endpoint, req_method, api_def.callback)
self.json_rpc.register_method(mqtt_method, rpc_cb)
logging.info(
"Registering MQTT JSON-RPC methods: "
f"{', '.join(api_def.jrpc_methods)}")
def remove_api_handler(self, api_def: APIDefinition) -> None:
for jrpc_method in api_def.jrpc_methods:
self.json_rpc.remove_method(jrpc_method)
def _generate_local_callback(self,
endpoint: str,
request_method: str,
callback: Callable[[WebRequest], Coroutine]
) -> RPCCallback:
async def func(args: Dict[str, Any]) -> Any:
self._check_timestamp(args)
result = await callback(WebRequest(endpoint, args, request_method))
return result
return func
def _generate_remote_callback(self, endpoint: str) -> RPCCallback:
async def func(args: Dict[str, Any]) -> Any:
self._check_timestamp(args)
result = await self.klippy.request(WebRequest(endpoint, args))
return result
return func
def _check_timestamp(self, args: Dict[str, Any]) -> None:
ts = args.pop("mqtt_timestamp", None)
if ts is not None:
if ts in self.timestamp_deque:
logging.debug("Duplicate MQTT API request received")
raise self.server.error(
"Duplicate MQTT Request", DUP_API_REQ_CODE)
else:
self.timestamp_deque.append(ts)
def send_status(self,
status: Dict[str, Any],
eventtime: float
) -> None:
if not status or not self.is_connected():
return
if self.publish_split_status:
for objkey in status:
objval = status[objkey]
for statekey in objval:
payload = {'eventtime': eventtime,
'value': objval[statekey]}
self.publish_topic(
f"{self.klipper_state_prefix}/{objkey}/{statekey}",
payload, retain=True)
else:
payload = {'eventtime': eventtime, 'status': status}
self.publish_topic(self.klipper_status_topic, payload)
def get_instance_name(self) -> str:
return self.instance_name
async def close(self) -> None:
if self.connect_task is not None:
self.connect_task.cancel()
self.connect_task = None
if not self.is_connected():
return
await self.publish_topic(self.moonraker_status_topic,
{'server': 'offline'},
retain=True)
self.disconnect_evt = asyncio.Event()
self.client.disconnect()
try:
await asyncio.wait_for(self.disconnect_evt.wait(), 2.)
except asyncio.TimeoutError:
logging.info("MQTT Disconnect Timeout")
futs = list(self.pending_acks.values())
futs.extend(self.pending_responses)
for fut in futs:
if fut.done():
continue
fut.set_exception(
self.server.error("Moonraker Shutdown", 503))
async def _publish_from_klipper(self,
topic: str,
payload: Any = None,
qos: Optional[int] = None,
retain: bool = False,
use_prefix: bool = False
) -> None:
if use_prefix:
topic = f"{self.instance_name}/{topic.lstrip('/')}"
await self.publish_topic(topic, payload, qos, retain)
def load_component(config: ConfigHelper) -> MQTTClient:
return MQTTClient(config)
+247
View File
@@ -0,0 +1,247 @@
# Notifier
#
# Copyright (C) 2022 Pataar <me@pataar.nl>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import apprise
import logging
# Annotation imports
from typing import (
TYPE_CHECKING,
Dict,
Any,
List,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..websockets import WebRequest
from .http_client import HttpClient
from .klippy_apis import KlippyAPI as APIComp
class Notifier:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.notifiers: Dict[str, NotifierInstance] = {}
self.events: Dict[str, NotifierEvent] = {}
prefix_sections = config.get_prefix_sections("notifier")
self.register_events(config)
self.register_remote_actions()
for section in prefix_sections:
cfg = config[section]
try:
notifier = NotifierInstance(cfg)
for event in self.events:
if event in notifier.events or "*" in notifier.events:
self.events[event].register_notifier(notifier)
logging.info(f"Registered notifier: '{notifier.get_name()}'")
except Exception as e:
msg = f"Failed to load notifier[{cfg.get_name()}]\n{e}"
self.server.add_warning(msg)
continue
self.notifiers[notifier.get_name()] = notifier
self.register_endpoints(config)
def register_remote_actions(self):
self.server.register_remote_method("notify", self.notify_action)
async def notify_action(self, name: str, message: str = ""):
if name not in self.notifiers:
raise self.server.error(f"Notifier '{name}' not found", 404)
notifier = self.notifiers[name]
await notifier.notify("remote_action", [], message)
def register_events(self, config: ConfigHelper):
self.events["started"] = NotifierEvent(
"started",
"job_state:started",
config)
self.events["complete"] = NotifierEvent(
"complete",
"job_state:complete",
config)
self.events["error"] = NotifierEvent(
"error",
"job_state:error",
config)
self.events["cancelled"] = NotifierEvent(
"cancelled",
"job_state:cancelled",
config)
self.events["paused"] = NotifierEvent(
"paused",
"job_state:paused",
config)
self.events["resumed"] = NotifierEvent(
"resumed",
"job_state:resumed",
config)
def register_endpoints(self, config: ConfigHelper):
self.server.register_endpoint(
"/server/notifiers/list", ["GET"], self._handle_notifier_list
)
self.server.register_debug_endpoint(
"/debug/notifiers/test", ["POST"], self._handle_notifier_test
)
async def _handle_notifier_list(
self, web_request: WebRequest
) -> Dict[str, Any]:
return {"notifiers": self._list_notifiers()}
def _list_notifiers(self) -> List[Dict[str, Any]]:
return [notifier.as_dict() for notifier in self.notifiers.values()]
async def _handle_notifier_test(
self, web_request: WebRequest
) -> Dict[str, Any]:
name = web_request.get_str("name")
if name not in self.notifiers:
raise self.server.error(f"Notifier '{name}' not found", 404)
client: HttpClient = self.server.lookup_component("http_client")
notifier = self.notifiers[name]
kapis: APIComp = self.server.lookup_component('klippy_apis')
result: Dict[str, Any] = await kapis.query_objects(
{'print_stats': None}, default={})
print_stats = result.get('print_stats', {})
print_stats["filename"] = "notifier_test.gcode" # Mock the filename
await notifier.notify(notifier.events[0], [print_stats, print_stats])
return {
"status": "success",
"stats": print_stats
}
class NotifierEvent:
def __init__(self, identifier: str, event_name: str, config: ConfigHelper):
self.identifier = identifier
self.event_name = event_name
self.server = config.get_server()
self.notifiers: Dict[str, NotifierInstance] = {}
self.config = config
self.server.register_event_handler(self.event_name, self._handle)
def register_notifier(self, notifier: NotifierInstance):
self.notifiers[notifier.get_name()] = notifier
async def _handle(self, *args) -> None:
logging.info(f"'{self.identifier}' notifier event triggered'")
await self.invoke_notifiers(args)
async def invoke_notifiers(self, args):
for notifier_name in self.notifiers:
try:
notifier = self.notifiers[notifier_name]
await notifier.notify(self.identifier, args)
except Exception as e:
logging.info(f"Failed to notify [{notifier_name}]\n{e}")
continue
class NotifierInstance:
def __init__(self, config: ConfigHelper) -> None:
self.config = config
name_parts = config.get_name().split(maxsplit=1)
if len(name_parts) != 2:
raise config.error(f"Invalid Section Name: {config.get_name()}")
self.server = config.get_server()
self.name = name_parts[1]
self.apprise = apprise.Apprise()
self.warned = False
self.attach_requires_file_system_check = True
self.attach = config.get("attach", None)
if self.attach is None or \
(self.attach.startswith("http://") or
self.attach.startswith("https://")):
self.attach_requires_file_system_check = False
url_template = config.gettemplate('url')
self.url = url_template.render()
if len(self.url) < 2:
raise config.error(f"Invalid url for: {config.get_name()}")
self.title = config.gettemplate('title', None)
self.body = config.gettemplate("body", None)
self.events: List[str] = config.getlist("events", separator=",")
self.apprise.add(self.url)
def as_dict(self):
return {
"name": self.name,
"url": self.config.get("url"),
"title": self.config.get("title", None),
"body": self.config.get("body", None),
"events": self.events,
"attach": self.attach
}
async def notify(
self, event_name: str, event_args: List, message: str = ""
) -> None:
context = {
"event_name": event_name,
"event_args": event_args,
"event_message": message
}
rendered_title = (
'' if self.title is None else self.title.render(context)
)
rendered_body = (
event_name if self.body is None else self.body.render(context)
)
# Verify the attachment
if self.attach_requires_file_system_check and self.attach is not None:
fm = self.server.lookup_component("file_manager")
if not fm.can_access_path(self.attach):
if not self.warned:
self.server.add_warning(
f"Attachment of notifier '{self.name}' is not "
"valid. The location of the "
"attachment is not "
"accessible.")
self.warned = True
self.attach = None
await self.apprise.async_notify(
rendered_body.strip(),
rendered_title.strip(),
attach=self.attach
)
def get_name(self) -> str:
return self.name
def load_component(config: ConfigHelper) -> Notifier:
return Notifier(config)
+206 -87
View File
@@ -1,21 +1,35 @@
# Octoprint API compatibility
# OctoPrint API compatibility
#
# Copyright (C) 2021 Nickolas Grigoriadis <nagrigoriadis@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import logging
import utils
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Dict,
List,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..websockets import WebRequest
from .klippy_apis import KlippyAPI as APIComp
from .file_manager.file_manager import FileManager
from .job_queue import JobQueue
OCTO_VERSION = '1.5.0'
class OctoprintCompat:
class OctoPrintCompat:
"""
Minimal implementation of the REST API as described here:
https://docs.octoprint.org/en/master/api/index.html
So that Cura Octoprint plugin will function for:
So that Cura OctoPrint plugin will function for:
* Handshake
* Upload gcode/ufp
* Webcam config
@@ -23,32 +37,50 @@ class OctoprintCompat:
* Heater temperatures
"""
def __init__(self, config):
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.software_version = config['system_args'].get('software_version')
self.software_version = self.server.get_app_args().get(
'software_version')
self.enable_ufp: bool = config.getboolean('enable_ufp', True)
# Get webcam settings from config
self.webcam: Dict[str, Any] = {
'flipH': config.getboolean('flip_h', False),
'flipV': config.getboolean('flip_v', False),
'rotate90': config.getboolean('rotate_90', False),
'streamUrl': config.get('stream_url', '/webcam/?action=stream'),
'webcamEnabled': config.getboolean('webcam_enabled', True),
}
# Local variables
self.klippy_apis = None
self.heaters = []
self.klippy_apis: APIComp = self.server.lookup_component('klippy_apis')
self.heaters: Dict[str, Dict[str, Any]] = {}
self.last_print_stats: Dict[str, Any] = {}
# Register status update event
self.server.register_event_handler(
'server:klippy_ready', self._init)
self.server.register_event_handler(
'server:status_update', self._handle_status_update)
# Version & Server information
self.server.register_endpoint(
'/api/version', ['GET'], self._get_version, wrap_result=False)
'/api/version', ['GET'], self._get_version,
transports=['http'], wrap_result=False)
self.server.register_endpoint(
'/api/server', ['GET'], self._get_server, wrap_result=False)
'/api/server', ['GET'], self._get_server,
transports=['http'], wrap_result=False)
# Login, User & Settings
self.server.register_endpoint(
'/api/login', ['POST'], self._post_login_user, wrap_result=False)
'/api/login', ['POST'], self._post_login_user,
transports=['http'], wrap_result=False)
self.server.register_endpoint(
'/api/currentuser', ['GET'], self._post_login_user,
wrap_result=False)
transports=['http'], wrap_result=False)
self.server.register_endpoint(
'/api/settings', ['GET'], self._get_settings, wrap_result=False)
'/api/settings', ['GET'], self._get_settings,
transports=['http'], wrap_result=False)
# File operations
# Note that file upload is handled in file_manager.py
@@ -56,76 +88,95 @@ class OctoprintCompat:
# Job operations
self.server.register_endpoint(
'/api/job', ['GET'], self._get_job, wrap_result=False)
'/api/job', ['GET'], self._get_job,
transports=['http'], wrap_result=False)
# TODO: start/cancel/restart/pause jobs
# Printer operations
self.server.register_endpoint(
'/api/printer', ['GET'], self._get_printer, wrap_result=False)
'/api/printer', ['GET'], self._get_printer,
transports=['http'], wrap_result=False)
self.server.register_endpoint(
'/api/printer/command', ['POST'], self._post_command,
wrap_result=False)
transports=['http'], wrap_result=False)
# TODO: head/tool/bed/chamber specific read/issue
# Printer profiles
self.server.register_endpoint(
'/api/printerprofiles', ['GET'], self._get_printerprofiles,
wrap_result=False)
transports=['http'], wrap_result=False)
# Upload Handlers
self.server.register_upload_handler(
"/api/files/local", location_prefix="api/files/moonraker")
self.server.register_endpoint(
"/api/files/moonraker/(?P<relative_path>.+)", ['POST'],
self._select_file, transports=['http'], wrap_result=False)
# System
# TODO: shutdown/reboot/restart operations
async def _init(self):
self.klippy_apis = self.server.lookup_component('klippy_apis')
async def _init(self) -> None:
self.heaters = {}
# Fetch heaters
try:
result: Dict[str, Any]
sensors: List[str]
result = await self.klippy_apis.query_objects({'heaters': None})
sensors = result.get('heaters', {}).get('available_sensors', [])
except self.server.error as e:
logging.info(f'Error Configuring heaters: {e}')
return
self.heaters = result.get('heaters', {}).get('available_sensors', [])
sensors = []
# subscribe objects
sub: Dict[str, Any] = {s: None for s in sensors}
sub['print_stats'] = None
result = await self.klippy_apis.subscribe_objects(sub)
self.last_print_stats = result.get('print_stats', {})
if sensors:
self.heaters = {name: result.get(name, {}) for name in sensors}
async def printer_state(self):
if not self.klippy_apis:
def _handle_status_update(self, status: Dict[str, Any]) -> None:
if 'print_stats' in status:
self.last_print_stats.update(status['print_stats'])
for heater_name, data in self.heaters.items():
if heater_name in status:
data.update(status[heater_name])
def printer_state(self) -> str:
klippy_state = self.server.get_klippy_state()
if klippy_state in ["disconnected", "startup"]:
return 'Offline'
if self.server.klippy_state != 'ready':
elif klippy_state != 'ready':
return 'Error'
result = await self.klippy_apis.query_objects({'print_stats': None})
return {
'standby': 'Operational',
'printing': 'Printing',
'paused': 'Paused',
'complete': 'Operational'
}.get(result.get('state', 'standby'), 'Error')
}.get(self.last_print_stats.get('state', 'standby'), 'Error')
async def printer_temps(self):
temps = {}
if not self.klippy_apis:
return temps
if self.heaters:
result = await self.klippy_apis.query_objects(
{heater: None for heater in self.heaters})
for heater in self.heaters:
if heater not in result:
continue
data = result[heater]
name = 'bed'
if heater.startswith('extruder'):
try:
tool_no = int(heater[8:])
except ValueError:
tool_no = 0
name = f'tool{tool_no}'
elif heater != "heater_bed":
continue
temps[name] = {
'actual': round(data.get('temperature', 0.), 2),
'offset': 0,
'target': data.get('target', 0.),
}
def printer_temps(self) -> Dict[str, Any]:
temps: Dict[str, Any] = {}
for heater, data in self.heaters.items():
name = 'bed'
if heater.startswith('extruder'):
try:
tool_no = int(heater[8:])
except ValueError:
tool_no = 0
name = f'tool{tool_no}'
elif heater != "heater_bed":
continue
temps[name] = {
'actual': round(data.get('temperature', 0.), 2),
'offset': 0,
'target': data.get('target', 0.),
}
return temps
async def _get_version(self, web_request):
async def _get_version(self,
web_request: WebRequest
) -> Dict[str, str]:
"""
Version information
"""
@@ -135,17 +186,22 @@ class OctoprintCompat:
'text': f'OctoPrint (Moonraker {self.software_version})',
}
async def _get_server(self, web_request):
async def _get_server(self,
web_request: WebRequest
) -> Dict[str, Any]:
"""
Server status
"""
klippy_state = self.server.get_klippy_state()
return {
'server': OCTO_VERSION,
'safemode': (
None if self.server.klippy_state == 'ready' else 'settings')
None if klippy_state == 'ready' else 'settings')
}
async def _post_login_user(self, web_request):
async def _post_login_user(self,
web_request: WebRequest
) -> Dict[str, Any]:
"""
Confirm session login.
@@ -164,15 +220,22 @@ class OctoprintCompat:
'groups': ['admins', 'users'],
}
async def _get_settings(self, web_request):
async def _get_settings(self,
web_request: WebRequest
) -> Dict[str, Any]:
"""
Used to parse Octoprint capabilities
Hardcode capabilities to be basically there and use default
fluid/mainsail webcam path.
Used to parse OctoPrint capabilities
"""
return {
'plugins': {
settings = {
'plugins': {},
'feature': {
'sdSupport': False,
'temperatureGraph': False
},
'webcam': self.webcam,
}
if self.enable_ufp:
settings['plugins'] = {
'UltimakerFormatPackage': {
'align_inline_thumbnail': False,
'inline_thumbnail': False,
@@ -183,23 +246,12 @@ class OctoprintCompat:
'scale_inline_thumbnail': False,
'state_panel_thumbnail': True,
},
},
'feature': {
'sdSupport': False,
'temperatureGraph': False
},
# TODO: Get webcam settings from config file to allow user
# to customise this.
'webcam': {
'flipH': False,
'flipV': False,
'rotate90': False,
'streamUrl': '/webcam/?action=stream',
'webcamEnabled': True,
},
}
}
return settings
async def _get_job(self, web_request):
async def _get_job(self,
web_request: WebRequest
) -> Dict[str, Any]:
"""
Get current job status
"""
@@ -217,16 +269,18 @@ class OctoprintCompat:
'printTimeLeft': None,
'printTimeOrigin': None,
},
'state': await self.printer_state()
'state': self.printer_state()
}
async def _get_printer(self, web_request):
async def _get_printer(self,
web_request: WebRequest
) -> Dict[str, Any]:
"""
Get Printer status
"""
state = await self.printer_state()
state = self.printer_state()
return {
'temperature': await self.printer_temps(),
'temperature': self.printer_temps(),
'state': {
'text': state,
'flags': {
@@ -242,11 +296,13 @@ class OctoprintCompat:
},
}
async def _post_command(self, web_request):
async def _post_command(self,
web_request: WebRequest
) -> Dict:
"""
Request to run some gcode command
"""
commands = web_request.get('commands', [])
commands: List[str] = web_request.get('commands', [])
for command in commands:
logging.info(f'Executing GCode: {command}')
try:
@@ -257,7 +313,9 @@ class OctoprintCompat:
return {}
async def _get_printerprofiles(self, web_request):
async def _get_printerprofiles(self,
web_request: WebRequest
) -> Dict[str, Any]:
"""
Get Printer profiles
"""
@@ -272,10 +330,71 @@ class OctoprintCompat:
'current': True,
'heatedBed': 'heater_bed' in self.heaters,
'heatedChamber': 'chamber' in self.heaters,
'axes': {
'x': {
'speed': 6000.,
'inverted': False
},
'y': {
'speed': 6000.,
'inverted': False
},
'z': {
'speed': 6000.,
'inverted': False
},
'e': {
'speed': 300.,
'inverted': False
}
}
}
}
}
async def _select_file(self,
web_request: WebRequest
) -> None:
command: str = web_request.get('command')
rel_path: str = web_request.get('relative_path')
root, filename = rel_path.strip("/").split("/", 1)
fmgr: FileManager = self.server.lookup_component('file_manager')
if command == "select":
start_print: bool = web_request.get('print', False)
if not start_print:
# No-op, selecting a file has no meaning in Moonraker
return
if root != "gcodes":
raise self.server.error(
"File must be located in the 'gcodes' root", 400)
if not fmgr.check_file_exists(root, filename):
raise self.server.error("File does not exist")
try:
ret = await self.klippy_apis.query_objects(
{'print_stats': None})
pstate: str = ret['print_stats']['state']
except self.server.error:
pstate = "not_avail"
started: bool = False
if pstate not in ["printing", "paused", "not_avail"]:
try:
await self.klippy_apis.start_print(filename)
except self.server.error:
started = False
else:
logging.debug(f"Job '{filename}' started via OctoPrint API")
started = True
if not started:
if fmgr.upload_queue_enabled():
job_queue: JobQueue = self.server.lookup_component(
'job_queue')
await job_queue.queue_job(filename, check_exists=False)
logging.debug(f"Job '{filename}' queued via OctoPrint API")
else:
raise self.server.error("Conflict", 409)
else:
raise self.server.error(f"Unsupported Command: {command}")
def load_component(config):
return OctoprintCompat(config)
def load_component(config: ConfigHelper) -> OctoPrintCompat:
return OctoPrintCompat(config)
+182 -135
View File
@@ -3,6 +3,8 @@
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import serial
import os
import time
@@ -11,9 +13,25 @@ import errno
import logging
import asyncio
from collections import deque
from utils import ServerError
from tornado import gen
from tornado.ioloop import IOLoop
from ..utils import ServerError
# Annotation imports
from typing import (
TYPE_CHECKING,
Deque,
Any,
Tuple,
Optional,
Dict,
List,
Callable,
Coroutine,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from .klippy_apis import KlippyAPI as APIComp
from .file_manager.file_manager import FileManager as FMComp
FlexCallback = Callable[..., Optional[Coroutine]]
MIN_EST_TIME = 10.
INITIALIZE_TIMEOUT = 10.
@@ -25,26 +43,30 @@ class PanelDueError(ServerError):
RESTART_GCODES = ["RESTART", "FIRMWARE_RESTART"]
class SerialConnection:
def __init__(self, config, paneldue):
self.ioloop = IOLoop.current()
def __init__(self,
config: ConfigHelper,
paneldue: PanelDue
) -> None:
self.event_loop = config.get_server().get_event_loop()
self.paneldue = paneldue
self.port = config.get('serial')
self.port: str = config.get('serial')
self.baud = config.getint('baud', 57600)
self.partial_input = b""
self.ser = self.fd = None
self.connected = False
self.send_busy = False
self.send_buffer = b""
self.attempting_connect = True
self.ioloop.spawn_callback(self._connect)
self.partial_input: bytes = b""
self.ser: Optional[serial.Serial] = None
self.fd: Optional[int] = None
self.connected: bool = False
self.send_busy: bool = False
self.send_buffer: bytes = b""
self.attempting_connect: bool = True
def disconnect(self, reconnect=False):
def disconnect(self, reconnect: bool = False) -> None:
if self.connected:
if self.fd is not None:
self.ioloop.remove_handler(self.fd)
self.event_loop.remove_reader(self.fd)
self.fd = None
self.connected = False
self.ser.close()
if self.ser is not None:
self.ser.close()
self.ser = None
self.partial_input = b""
self.send_buffer = b""
@@ -52,9 +74,10 @@ class SerialConnection:
logging.info("PanelDue Disconnected")
if reconnect and not self.attempting_connect:
self.attempting_connect = True
self.ioloop.call_later(1., self._connect)
self.event_loop.delay_callback(1., self.connect)
async def _connect(self):
async def connect(self) -> None:
self.attempting_connect = True
start_time = connect_time = time.time()
while not self.connected:
if connect_time > start_time + 30.:
@@ -69,25 +92,23 @@ class SerialConnection:
self.port, self.baud, timeout=0, exclusive=True)
except (OSError, IOError, serial.SerialException):
logging.exception(f"Unable to open port: {self.port}")
await gen.sleep(2.)
await asyncio.sleep(2.)
connect_time += time.time()
continue
self.fd = self.ser.fileno()
os.set_blocking(self.fd, False)
self.ioloop.add_handler(
self.fd, self._handle_incoming, IOLoop.READ | IOLoop.ERROR)
fd = self.fd = self.ser.fileno()
os.set_blocking(fd, False)
self.event_loop.add_reader(fd, self._handle_incoming)
self.connected = True
logging.info("PanelDue Connected")
self.attempting_connect = False
def _handle_incoming(self, fd, events):
if events & IOLoop.ERROR:
logging.info("PanelDue Connection Error")
self.disconnect(reconnect=True)
return
def _handle_incoming(self) -> None:
# Process incoming data using same method as gcode.py
if self.fd is None:
return
try:
data = os.read(fd, 4096)
data = os.read(self.fd, 4096)
except os.error:
return
@@ -104,23 +125,24 @@ class SerialConnection:
self.partial_input = lines.pop()
for line in lines:
try:
line = line.strip().decode('utf-8', 'ignore')
self.paneldue.process_line(line)
decoded_line = line.strip().decode('utf-8', 'ignore')
self.paneldue.process_line(decoded_line)
except ServerError:
logging.exception(
f"GCode Processing Error: {line}")
f"GCode Processing Error: {decoded_line}")
self.paneldue.handle_gcode_response(
f"!! GCode Processing Error: {line}")
f"!! GCode Processing Error: {decoded_line}")
except Exception:
logging.exception("Error during gcode processing")
def send(self, data):
def send(self, data: bytes) -> None:
self.send_buffer += data
if not self.send_busy:
self.send_busy = True
self.ioloop.spawn_callback(self._do_send)
self.event_loop.register_callback(self._do_send)
async def _do_send(self):
async def _do_send(self) -> None:
assert self.fd is not None
while self.send_buffer:
if not self.connected:
break
@@ -130,7 +152,7 @@ class SerialConnection:
if e.errno == errno.EBADF or e.errno == errno.EPIPE:
sent = 0
else:
await gen.sleep(.001)
await asyncio.sleep(.001)
continue
if sent:
self.send_buffer = self.send_buffer[sent:]
@@ -142,60 +164,61 @@ class SerialConnection:
self.send_busy = False
class PanelDue:
def __init__(self, config):
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.ioloop = IOLoop.current()
self.file_manager = self.server.lookup_component('file_manager')
self.klippy_apis = self.server.lookup_component('klippy_apis')
self.kinematics = "none"
self.event_loop = self.server.get_event_loop()
self.file_manager: FMComp = \
self.server.lookup_component('file_manager')
self.klippy_apis: APIComp = \
self.server.lookup_component('klippy_apis')
self.kinematics: str = "none"
self.machine_name = config.get('machine_name', "Klipper")
self.firmware_name = "Repetier | Klipper"
self.last_message = None
self.last_gcode_response = None
self.current_file = ""
self.file_metadata = {}
self.firmware_name: str = "Repetier | Klipper"
self.last_message: Optional[str] = None
self.last_gcode_response: Optional[str] = None
self.current_file: str = ""
self.file_metadata: Dict[str, Any] = {}
self.enable_checksum = config.getboolean('enable_checksum', True)
self.debug_queue = deque(maxlen=100)
self.debug_queue: Deque[str] = deque(maxlen=100)
# Initialize tracked state.
self.printer_state = {
self.printer_state: Dict[str, Dict[str, Any]] = {
'gcode_move': {}, 'toolhead': {}, 'virtual_sdcard': {},
'fan': {}, 'display_status': {}, 'print_stats': {},
'idle_timeout': {}, 'gcode_macro PANELDUE_BEEP': {}}
self.extruder_count = 0
self.heaters = []
self.is_ready = False
self.is_shutdown = False
self.initialized = False
self.cq_busy = self.gq_busy = False
self.command_queue = []
self.gc_queue = []
self.last_printer_state = 'O'
self.last_update_time = 0.
self.extruder_count: int = 0
self.heaters: List[str] = []
self.is_ready: bool = False
self.is_shutdown: bool = False
self.initialized: bool = False
self.cq_busy: bool = False
self.gq_busy: bool = False
self.command_queue: List[Tuple[FlexCallback, Any, Any]] = []
self.gc_queue: List[str] = []
self.last_printer_state: str = 'O'
self.last_update_time: float = 0.
# Set up macros
self.confirmed_gcode = ""
self.mbox_sequence = 0
self.available_macros = {}
self.confirmed_gcode: str = ""
self.mbox_sequence: int = 0
self.available_macros: Dict[str, str] = {}
self.confirmed_macros = {
"RESTART": "RESTART",
"FIRMWARE_RESTART": "FIRMWARE_RESTART"}
macros = config.get('macros', None)
macros = config.getlist('macros', None)
if macros is not None:
# The macro's configuration name is the key, whereas the full
# command is the value
macros = [m for m in macros.split('\n') if m.strip()]
self.available_macros = {m.split()[0]: m for m in macros}
conf_macros = config.get('confirmed_macros', None)
conf_macros = config.getlist('confirmed_macros', None)
if conf_macros is not None:
# The macro's configuration name is the key, whereas the full
# command is the value
conf_macros = [m for m in conf_macros.split('\n') if m.strip()]
self.confirmed_macros = {m.split()[0]: m for m in conf_macros}
self.available_macros.update(self.confirmed_macros)
ntkeys = config.get('non_trivial_keys', "Klipper state")
self.non_trivial_keys = [k for k in ntkeys.split('\n') if k.strip()]
self.non_trivial_keys = config.getlist('non_trivial_keys',
["Klipper state"])
self.ser_conn = SerialConnection(config, self)
logging.info("PanelDue Configured")
@@ -216,7 +239,7 @@ class PanelDue:
# These commands are directly executued on the server and do not to
# make a request to Klippy
self.direct_gcodes = {
self.direct_gcodes: Dict[str, FlexCallback] = {
'M20': self._run_paneldue_M20,
'M30': self._run_paneldue_M30,
'M36': self._run_paneldue_M36,
@@ -225,7 +248,7 @@ class PanelDue:
# These gcodes require special parsing or handling prior to being
# sent via Klippy's "gcode/script" api command.
self.special_gcodes = {
self.special_gcodes: Dict[str, Callable[[List[str]], str]] = {
'M0': lambda args: "CANCEL_PRINT",
'M23': self._prepare_M23,
'M24': lambda args: "RESUME",
@@ -239,10 +262,14 @@ class PanelDue:
'M999': lambda args: "FIRMWARE_RESTART"
}
async def _process_klippy_ready(self):
async def component_init(self) -> None:
await self.ser_conn.connect()
async def _process_klippy_ready(self) -> None:
# Request "info" and "configfile" status
retries = 10
printer_info = cfg_status = {}
printer_info: Dict[str, Any] = {}
cfg_status: Dict[str, Any] = {}
while retries:
try:
printer_info = await self.klippy_apis.get_klippy_info()
@@ -253,14 +280,15 @@ class PanelDue:
retries -= 1
if not retries:
raise
await gen.sleep(1.)
await asyncio.sleep(1.)
continue
break
self.firmware_name = "Repetier | Klipper " + \
printer_info['software_version']
config = cfg_status.get('configfile', {}).get('config', {})
printer_cfg = config.get('printer', {})
config: Dict[str, Any] = cfg_status.get(
'configfile', {}).get('config', {})
printer_cfg: Dict[str, Any] = config.get('printer', {})
self.kinematics = printer_cfg.get('kinematics', "none")
logging.info(
@@ -277,17 +305,21 @@ class PanelDue:
sub_args = {k: None for k in self.printer_state.keys()}
self.extruder_count = 0
self.heaters = []
extruders = []
for cfg in config:
if cfg.startswith("extruder"):
self.extruder_count += 1
self.printer_state[cfg] = {}
self.heaters.append(cfg)
extruders.append(cfg)
sub_args[cfg] = None
elif cfg == "heater_bed":
self.printer_state[cfg] = {}
self.heaters.append(cfg)
sub_args[cfg] = None
extruders.sort()
self.heaters.extend(extruders)
try:
status: Dict[str, Any]
status = await self.klippy_apis.subscribe_objects(sub_args)
except self.server.error:
logging.exception("Unable to complete subscription request")
@@ -296,39 +328,39 @@ class PanelDue:
self.is_shutdown = False
self.is_ready = True
def _process_klippy_shutdown(self):
def _process_klippy_shutdown(self) -> None:
self.is_shutdown = True
def _process_klippy_disconnect(self):
def _process_klippy_disconnect(self) -> None:
# Tell the PD that the printer is "off"
self.write_response({'status': 'O'})
self.last_printer_state = 'O'
self.is_shutdown = self.is_shutdown = False
def handle_status_update(self, status):
def handle_status_update(self, status: Dict[str, Any]) -> None:
for obj, items in status.items():
if obj in self.printer_state:
self.printer_state[obj].update(items)
else:
self.printer_state[obj] = items
def paneldue_beep(self, frequency, duration):
def paneldue_beep(self, frequency: int, duration: float) -> None:
duration = int(duration * 1000.)
self.write_response(
{'beep_freq': frequency, 'beep_length': duration})
def process_line(self, line):
def process_line(self, line: str) -> None:
self.debug_queue.append(line)
# If we find M112 in the line then skip verification
if "M112" in line.upper():
self.ioloop.spawn_callback(self.klippy_apis.emergency_stop)
self.event_loop.register_callback(self.klippy_apis.emergency_stop)
return
if self.enable_checksum:
# Get line number
line_index = line.find(' ')
try:
line_no = int(line[1:line_index])
line_no: Optional[int] = int(line[1:line_index])
except Exception:
line_index = -1
line_no = None
@@ -370,7 +402,7 @@ class PanelDue:
# Check for commands that query state and require immediate response
if cmd in self.direct_gcodes:
params = {}
params: Dict[str, Any] = {}
for p in parts[1:]:
if p[0] not in "PSR":
params["arg_p"] = p.strip(" \"\t\n")
@@ -391,20 +423,20 @@ class PanelDue:
# Prepare GCodes that require special handling
if cmd in self.special_gcodes:
func = self.special_gcodes[cmd]
script = func(parts[1:])
sgc_func = self.special_gcodes[cmd]
script = sgc_func(parts[1:])
if not script:
return
self.queue_gcode(script)
def queue_gcode(self, script):
def queue_gcode(self, script: str) -> None:
self.gc_queue.append(script)
if not self.gq_busy:
self.gq_busy = True
self.ioloop.spawn_callback(self._process_gcode_queue)
self.event_loop.register_callback(self._process_gcode_queue)
async def _process_gcode_queue(self):
async def _process_gcode_queue(self) -> None:
while self.gc_queue:
script = self.gc_queue.pop(0)
try:
@@ -418,24 +450,24 @@ class PanelDue:
logging.exception(msg)
self.gq_busy = False
def queue_command(self, cmd, *args, **kwargs):
def queue_command(self, cmd: FlexCallback, *args, **kwargs) -> None:
self.command_queue.append((cmd, args, kwargs))
if not self.cq_busy:
self.cq_busy = True
self.ioloop.spawn_callback(self._process_command_queue)
self.event_loop.register_callback(self._process_command_queue)
async def _process_command_queue(self):
async def _process_command_queue(self) -> None:
while self.command_queue:
cmd, args, kwargs = self.command_queue.pop(0)
try:
ret = cmd(*args, **kwargs)
if asyncio.iscoroutine(ret):
if ret is not None:
await ret
except Exception:
logging.exception("Error processing command")
self.cq_busy = False
def _clean_filename(self, filename):
def _clean_filename(self, filename: str) -> str:
# Remove quotes and whitespace
filename.strip(" \"\t\n")
# Remove drive number
@@ -453,17 +485,17 @@ class PanelDue:
filename = "/" + filename
return filename
def _prepare_M23(self, args):
def _prepare_M23(self, args: List[str]) -> str:
filename = self._clean_filename(args[0])
return f"M23 {filename}"
def _prepare_M32(self, args):
def _prepare_M32(self, args: List[str]) -> str:
filename = self._clean_filename(args[0])
# Escape existing double quotes in the file name
filename = filename.replace("\"", "\\\"")
return f"SDCARD_PRINT_FILE FILENAME=\"{filename}\""
def _prepare_M98(self, args):
def _prepare_M98(self, args: List[str]) -> str:
macro = args[0][1:].strip(" \"\t\n")
name_start = macro.rfind('/') + 1
macro = macro[name_start:]
@@ -475,12 +507,12 @@ class PanelDue:
cmd = ""
return cmd
def _prepare_M290(self, args):
def _prepare_M290(self, args: List[str]) -> str:
# args should in in the format Z0.02
offset = args[0][1:].strip()
return f"SET_GCODE_OFFSET Z_ADJUST={offset} MOVE=1"
def _prepare_M292(self, args):
def _prepare_M292(self, args: List[str]) -> str:
p_val = int(args[0][1])
if p_val == 0:
cmd = self.confirmed_gcode
@@ -488,13 +520,13 @@ class PanelDue:
return cmd
return ""
def _create_confirmation(self, name, gcode):
def _create_confirmation(self, name: str, gcode: str) -> None:
self.mbox_sequence += 1
self.confirmed_gcode = gcode
title = "Confirmation Dialog"
msg = f"Please confirm your intent to run {name}." \
" Press OK to continue, or CANCEL to abort."
mbox = {}
mbox: Dict[str, Any] = {}
mbox['msgBox.mode'] = 3
mbox['msgBox.msg'] = msg
mbox['msgBox.seq'] = self.mbox_sequence
@@ -504,7 +536,7 @@ class PanelDue:
logging.debug(f"Creating PanelDue Confirmation: {mbox}")
self.write_response(mbox)
def handle_gcode_response(self, response):
def handle_gcode_response(self, response: str) -> None:
# Only queue up "non-trivial" gcode responses. At the
# moment we'll handle state changes and errors
if "Klipper state" in response \
@@ -516,11 +548,11 @@ class PanelDue:
self.last_gcode_response = response
return
def write_response(self, response):
def write_response(self, response: Dict[str, Any]) -> None:
byte_resp = json.dumps(response) + "\r\n"
self.ser_conn.send(byte_resp.encode())
def _get_printer_status(self):
def _get_printer_status(self) -> str:
# PanelDue States applicable to Klipper:
# I = idle, P = printing from SD, S = stopped (shutdown),
# C = starting up (not ready), A = paused, D = pausing,
@@ -529,6 +561,7 @@ class PanelDue:
return 'S'
printer_state = self.printer_state
sd_state: str
sd_state = printer_state['print_stats'].get('state', "standby")
if sd_state == "printing":
if self.last_printer_state == 'A':
@@ -548,12 +581,15 @@ class PanelDue:
return 'I'
def _run_paneldue_M408(self, arg_r=None, arg_s=1):
response = {}
def _run_paneldue_M408(self,
arg_r: Optional[int] = None,
arg_s: int = 1
) -> None:
response: Dict[str, Any] = {}
sequence = arg_r
response_type = arg_s
curtime = self.ioloop.time()
curtime = self.event_loop.get_loop_time()
if curtime - self.last_update_time > INITIALIZE_TIMEOUT:
self.initialized = False
self.last_update_time = curtime
@@ -587,6 +623,9 @@ class PanelDue:
'homing_origin', [0., 0., 0., 0.])[2], 3)
# Current position
pos: List[float]
homed_pos: str
sfactor: float
pos = p_state['toolhead'].get('position', [0., 0., 0., 0.])
response['pos'] = [round(p, 2) for p in pos[:3]]
homed_pos = p_state['toolhead'].get('homed_axes', "")
@@ -597,38 +636,41 @@ class PanelDue:
# Print Progress Tracking
sd_status = p_state['virtual_sdcard']
print_stats = p_state['print_stats']
fname = print_stats.get('filename', "")
sd_print_state = print_stats.get('state')
fname: str = print_stats.get('filename', "")
sd_print_state: Optional[str] = print_stats.get('state')
if sd_print_state in ['printing', 'paused']:
# We know a file has been loaded, initialize metadata
if self.current_file != fname:
self.current_file = fname
self.file_metadata = self.file_manager.get_file_metadata(fname)
progress = sd_status.get('progress', 0)
progress: float = sd_status.get('progress', 0)
# progress and print tracking
if progress:
response['fraction_printed'] = round(progress, 3)
est_time = self.file_metadata.get('estimated_time', 0)
est_time: float = self.file_metadata.get('estimated_time', 0)
if est_time > MIN_EST_TIME:
# file read estimate
times_left = [int(est_time - est_time * progress)]
# filament estimate
est_total_fil: Optional[float]
est_total_fil = self.file_metadata.get('filament_total')
if est_total_fil:
cur_filament = print_stats.get('filament_used', 0.)
cur_filament: float = print_stats.get(
'filament_used', 0.)
fpct = min(1., cur_filament / est_total_fil)
times_left.append(int(est_time - est_time * fpct))
# object height estimate
obj_height: Optional[float]
obj_height = self.file_metadata.get('object_height')
if obj_height:
cur_height = p_state['gcode_move'].get(
cur_height: float = p_state['gcode_move'].get(
'gcode_position', [0., 0., 0., 0.])[2]
hpct = min(1., cur_height / obj_height)
times_left.append(int(est_time - est_time * hpct))
else:
# The estimated time is not in the metadata, however we
# can still provide an estimate based on file progress
duration = print_stats.get('print_duration', 0.)
duration: float = print_stats.get('print_duration', 0.)
times_left = [int(duration / progress - duration)]
response['timesLeft'] = times_left
else:
@@ -636,35 +678,39 @@ class PanelDue:
self.current_file = ""
self.file_metadata = {}
fan_speed = p_state['fan'].get('speed')
fan_speed: Optional[float] = p_state['fan'].get('speed')
if fan_speed is not None:
response['fanPercent'] = [round(fan_speed * 100, 1)]
extruder_name: str = ""
if self.extruder_count > 0:
extruder_name = p_state['toolhead'].get('extruder')
if extruder_name is not None:
extruder_name = p_state['toolhead'].get('extruder', "")
if extruder_name:
tool = 0
if extruder_name != "extruder":
tool = int(extruder_name[-1])
response['tool'] = tool
# Report Heater Status
efactor = round(p_state['gcode_move'].get(
efactor: float = round(p_state['gcode_move'].get(
'extrude_factor', 1.) * 100., 2)
for name in self.heaters:
temp = round(p_state[name].get('temperature', 0.0), 1)
target = round(p_state[name].get('target', 0.0), 1)
temp: float = round(p_state[name].get('temperature', 0.0), 1)
target: float = round(p_state[name].get('target', 0.0), 1)
response.setdefault('heaters', []).append(temp)
response.setdefault('active', []).append(target)
response.setdefault('standby', []).append(target)
response.setdefault('hstat', []).append(2 if target else 0)
if name.startswith('extruder'):
a_stat = 2 if name == extruder_name else 1
response.setdefault('hstat', []).append(a_stat if target else 0)
response.setdefault('efactor', []).append(efactor)
response.setdefault('extr', []).append(round(pos[3], 2))
else:
response.setdefault('hstat', []).append(2 if target else 0)
# Display message (via M117)
msg = p_state['display_status'].get('message')
msg: str = p_state['display_status'].get('message', "")
if msg and msg != self.last_message:
response['message'] = msg
# reset the message so it only shows once. The paneldue
@@ -673,7 +719,7 @@ class PanelDue:
self.last_message = msg
self.write_response(response)
def _run_paneldue_M20(self, arg_p, arg_s=0):
def _run_paneldue_M20(self, arg_p: str, arg_s: int = 0) -> None:
response_type = arg_s
if response_type != 2:
logging.info(
@@ -689,7 +735,7 @@ class PanelDue:
# ie. "0:/"
if path.startswith("0:/"):
path = path[2:]
response = {'dir': path}
response: Dict[str, Any] = {'dir': path}
response['files'] = []
if path == "/macros":
@@ -713,7 +759,7 @@ class PanelDue:
response['files'] = flist
self.write_response(response)
async def _run_paneldue_M30(self, arg_p=None):
async def _run_paneldue_M30(self, arg_p: str = "") -> None:
# Delete a file. Clean up the file name and make sure
# it is relative to the "gcodes" root.
path = arg_p
@@ -727,9 +773,9 @@ class PanelDue:
path = "gcodes/" + path
await self.file_manager.delete_file(path)
def _run_paneldue_M36(self, arg_p=None):
response = {}
filename = arg_p
def _run_paneldue_M36(self, arg_p: Optional[str] = None) -> None:
response: Dict[str, Any] = {}
filename: Optional[str] = arg_p
sd_status = self.printer_state.get('virtual_sdcard', {})
print_stats = self.printer_state.get('print_stats', {})
if filename is None:
@@ -756,37 +802,38 @@ class PanelDue:
if not filename.startswith("gcodes/"):
filename = "gcodes/" + filename
metadata = self.file_manager.get_file_metadata(filename)
metadata: Dict[str, Any] = \
self.file_manager.get_file_metadata(filename)
if metadata:
response['err'] = 0
response['size'] = metadata['size']
# workaround for PanelDue replacing the first "T" found
response['lastModified'] = "T" + time.ctime(metadata['modified'])
slicer = metadata.get('slicer')
slicer: Optional[str] = metadata.get('slicer')
if slicer is not None:
response['generatedBy'] = slicer
height = metadata.get('object_height')
height: Optional[float] = metadata.get('object_height')
if height is not None:
response['height'] = round(height, 2)
layer_height = metadata.get('layer_height')
layer_height: Optional[float] = metadata.get('layer_height')
if layer_height is not None:
response['layerHeight'] = round(layer_height, 2)
filament = metadata.get('filament_total')
filament: Optional[float] = metadata.get('filament_total')
if filament is not None:
response['filament'] = [round(filament, 1)]
est_time = metadata.get('estimated_time')
est_time: Optional[float] = metadata.get('estimated_time')
if est_time is not None:
response['printTime'] = int(est_time + .5)
else:
response['err'] = 1
self.write_response(response)
def close(self):
def close(self) -> None:
self.ser_conn.disconnect()
msg = "\nPanelDue GCode Dump:"
for i, gc in enumerate(self.debug_queue):
msg += f"\nSequence {i}: {gc}"
logging.debug(msg)
def load_component(config):
def load_component(config: ConfigHelper) -> PanelDue:
return PanelDue(config)
File diff suppressed because it is too large. Load diff
+257 -52
View File
@@ -3,19 +3,45 @@
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import asyncio
import time
import re
import os
import pathlib
import logging
from collections import deque
from tornado.ioloop import IOLoop, PeriodicCallback
# Annotation imports
from typing import (
TYPE_CHECKING,
Awaitable,
Callable,
Deque,
Any,
List,
Tuple,
Optional,
Dict,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..websockets import WebRequest, WebsocketManager
from . import shell_command
STAT_CALLBACK = Callable[[int], Optional[Awaitable]]
VC_GEN_CMD_FILE = "/usr/bin/vcgencmd"
STATM_FILE_PATH = "/proc/self/smaps_rollup"
STAT_UPDATE_TIME_MS = 1000
NET_DEV_PATH = "/proc/net/dev"
TEMPERATURE_PATH = "/sys/class/thermal/thermal_zone0/temp"
CPU_STAT_PATH = "/proc/stat"
MEM_AVAIL_PATH = "/proc/meminfo"
STAT_UPDATE_TIME = 1.
REPORT_QUEUE_SIZE = 30
THROTTLE_CHECK_INTERVAL = 10
WATCHDOG_REFRESH_TIME = 2.
REPORT_BLOCKED_TIME = 4.
THROTTLED_FLAGS = {
1: "Under-Voltage Detected",
@@ -29,91 +55,165 @@ THROTTLED_FLAGS = {
}
class ProcStats:
def __init__(self, config):
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.ioloop = IOLoop.current()
self.stat_update_cb = PeriodicCallback(
self._handle_stat_update, STAT_UPDATE_TIME_MS)
self.vcgencmd = None
self.event_loop = self.server.get_event_loop()
self.watchdog = Watchdog(self)
self.stat_update_timer = self.event_loop.register_timer(
self._handle_stat_update)
self.vcgencmd: Optional[shell_command.ShellCommand] = None
if os.path.exists(VC_GEN_CMD_FILE):
logging.info("Detected 'vcgencmd', throttle checking enabled")
shell_command = self.server.load_component(config, "shell_command")
self.vcgencmd = shell_command.build_shell_command(
shell_cmd: shell_command.ShellCommandFactory
shell_cmd = self.server.load_component(config, "shell_command")
self.vcgencmd = shell_cmd.build_shell_command(
"vcgencmd get_throttled")
self.server.register_notification("proc_stats:cpu_throttled")
else:
logging.info("Unable to find 'vcgencmd', throttle checking "
"disabled")
self.temp_file = pathlib.Path(TEMPERATURE_PATH)
self.smaps = pathlib.Path(STATM_FILE_PATH)
self.netdev_file = pathlib.Path(NET_DEV_PATH)
self.cpu_stats_file = pathlib.Path(CPU_STAT_PATH)
self.meminfo_file = pathlib.Path(MEM_AVAIL_PATH)
self.server.register_endpoint(
"/machine/proc_stats", ["GET"], self._handle_stat_request)
self.server.register_event_handler(
"server:klippy_shutdown", self._handle_shutdown)
self.proc_stat_queue = deque(maxlen=30)
self.server.register_notification("proc_stats:proc_stat_update")
self.proc_stat_queue: Deque[Dict[str, Any]] = deque(maxlen=30)
self.last_update_time = time.time()
self.last_proc_time = time.process_time()
self.throttled = False
self.update_sequence = 0
self.stat_update_cb.start()
self.throttle_check_lock = asyncio.Lock()
self.total_throttled: int = 0
self.last_throttled: int = 0
self.update_sequence: int = 0
self.last_net_stats: Dict[str, Dict[str, Any]] = {}
self.last_cpu_stats: Dict[str, Tuple[int, int]] = {}
self.cpu_usage: Dict[str, float] = {}
self.memory_usage: Dict[str, int] = {}
self.stat_callbacks: List[STAT_CALLBACK] = []
async def _handle_stat_request(self, web_request):
ts = None
async def component_init(self) -> None:
self.stat_update_timer.start()
self.watchdog.start()
def register_stat_callback(self, callback: STAT_CALLBACK) -> None:
self.stat_callbacks.append(callback)
async def _handle_stat_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
ts: Optional[Dict[str, Any]] = None
if self.vcgencmd is not None:
ts = await self._check_throttled_state()
cpu_temp = await self.event_loop.run_in_thread(
self._get_cpu_temperature)
wsm: WebsocketManager = self.server.lookup_component("websockets")
websocket_count = wsm.get_count()
return {
'moonraker_stats': list(self.proc_stat_queue),
'throttled_state': ts
'throttled_state': ts,
'cpu_temp': cpu_temp,
'network': self.last_net_stats,
'system_cpu_usage': self.cpu_usage,
'system_uptime': time.clock_gettime(time.CLOCK_BOOTTIME),
'system_memory': self.memory_usage,
'websocket_connections': websocket_count
}
async def _handle_shutdown(self):
async def _handle_shutdown(self) -> None:
msg = "\nMoonraker System Usage Statistics:"
for stats in self.proc_stat_queue:
msg += f"\n{self._format_stats(stats)}"
cpu_temp = await self.event_loop.run_in_thread(
self._get_cpu_temperature)
msg += f"\nCPU Temperature: {cpu_temp}"
logging.info(msg)
if self.vcgencmd is not None:
ts = await self._check_throttled_state()
logging.info(f"Throttled Flags: {' '.join(ts['flags'])}")
async def _handle_stat_update(self):
update_time = time.time()
async def _handle_stat_update(self, eventtime: float) -> float:
update_time = eventtime
proc_time = time.process_time()
time_diff = update_time - self.last_update_time
usage = round((proc_time - self.last_proc_time) / time_diff * 100, 2)
mem, mem_units = self._get_memory_usage()
self.proc_stat_queue.append({
"time": update_time,
"cpu_usage": usage,
"memory": mem,
"mem_units": mem_units
cpu_temp, mem, mem_units, net = (
await self.event_loop.run_in_thread(self._read_system_files)
)
for dev in net:
bytes_sec = 0.
if dev in self.last_net_stats:
last_dev_stats = self.last_net_stats[dev]
cur_total: int = net[dev]['rx_bytes'] + net[dev]['tx_bytes']
last_total: int = last_dev_stats['rx_bytes'] + \
last_dev_stats['tx_bytes']
bytes_sec = round((cur_total - last_total) / time_diff, 2)
net[dev]['bandwidth'] = bytes_sec
self.last_net_stats = net
result = {
'time': time.time(),
'cpu_usage': usage,
'memory': mem,
'mem_units': mem_units
}
self.proc_stat_queue.append(result)
wsm: WebsocketManager = self.server.lookup_component("websockets")
websocket_count = wsm.get_count()
self.server.send_event("proc_stats:proc_stat_update", {
'moonraker_stats': result,
'cpu_temp': cpu_temp,
'network': net,
'system_cpu_usage': self.cpu_usage,
'system_memory': self.memory_usage,
'websocket_connections': websocket_count
})
if not self.update_sequence % THROTTLE_CHECK_INTERVAL:
if self.vcgencmd is not None:
ts = await self._check_throttled_state()
cur_throttled = ts['bits']
if cur_throttled & ~self.total_throttled:
self.server.add_log_rollover_item(
'throttled', f"CPU Throttled Flags: {ts['flags']}")
if cur_throttled != self.last_throttled:
self.server.send_event("proc_stats:cpu_throttled", ts)
self.last_throttled = cur_throttled
self.total_throttled |= cur_throttled
for cb in self.stat_callbacks:
ret = cb(self.update_sequence)
if ret is not None:
await ret
self.last_update_time = update_time
self.last_proc_time = proc_time
self.update_sequence += 1
if self.update_sequence == THROTTLE_CHECK_INTERVAL:
self.update_sequence = 0
if self.vcgencmd is not None:
ts = await self._check_throttled_state()
cur_throttled = ts['bits'] & 0xF
if cur_throttled and not self.throttled:
logging.info(
f"CPU Throttled State Detected: {ts['flags']}")
self.server.send_event("proc_stats:cpu_throttled", ts)
self.throttled = cur_throttled
return eventtime + STAT_UPDATE_TIME
async def _check_throttled_state(self):
try:
resp = await self.vcgencmd.run_with_response(
timeout=.5, log_complete=False)
ts = int(resp.strip().split("=")[-1], 16)
except Exception:
return {'bits': 0, 'flags': ["?"]}
flags = []
for flag, desc in THROTTLED_FLAGS.items():
if flag & ts:
flags.append(desc)
return {'bits': ts, 'flags': flags}
async def _check_throttled_state(self) -> Dict[str, Any]:
async with self.throttle_check_lock:
assert self.vcgencmd is not None
try:
resp = await self.vcgencmd.run_with_response(
timeout=.5, log_complete=False)
ts = int(resp.strip().split("=")[-1], 16)
except Exception:
return {'bits': 0, 'flags': ["?"]}
flags = []
for flag, desc in THROTTLED_FLAGS.items():
if flag & ts:
flags.append(desc)
return {'bits': ts, 'flags': flags}
def _get_memory_usage(self):
def _read_system_files(self) -> Tuple:
mem, units = self._get_memory_usage()
temp = self._get_cpu_temperature()
net_stats = self._get_net_stats()
self._update_cpu_stats()
self._update_system_memory()
return temp, mem, units, net_stats
def _get_memory_usage(self) -> Tuple[Optional[int], Optional[str]]:
try:
mem_data = self.smaps.read_text()
rss_match = re.search(r"Rss:\s+(\d+)\s+(\w+)", mem_data)
@@ -125,13 +225,118 @@ class ProcStats:
return None, None
return mem, units
def _format_stats(self, stats):
def _get_cpu_temperature(self) -> Optional[float]:
try:
res = int(self.temp_file.read_text().strip())
temp = res / 1000.
except Exception:
return None
return temp
def _get_net_stats(self) -> Dict[str, Any]:
net_stats: Dict[str, Any] = {}
try:
ret = self.netdev_file.read_text()
dev_info = re.findall(r"([\w]+):(.+)", ret)
for (dev_name, stats) in dev_info:
parsed_stats = stats.strip().split()
net_stats[dev_name] = {
'rx_bytes': int(parsed_stats[0]),
'tx_bytes': int(parsed_stats[8]),
'rx_packets': int(parsed_stats[1]),
'tx_packets': int(parsed_stats[9]),
'rx_errs': int(parsed_stats[2]),
'tx_errs': int(parsed_stats[10]),
'rx_drop': int(parsed_stats[3]),
'tx_drop': int(parsed_stats[11])
}
return net_stats
except Exception:
return {}
def _update_system_memory(self) -> None:
mem_stats: Dict[str, Any] = {}
try:
ret = self.meminfo_file.read_text()
total_match = re.search(r"MemTotal:\s+(\d+)", ret)
avail_match = re.search(r"MemAvailable:\s+(\d+)", ret)
if total_match is not None and avail_match is not None:
mem_stats["total"] = int(total_match.group(1))
mem_stats["available"] = int(avail_match.group(1))
mem_stats["used"] = mem_stats["total"] - mem_stats["available"]
self.memory_usage.update(mem_stats)
except Exception:
pass
def _update_cpu_stats(self) -> None:
try:
cpu_usage: Dict[str, Any] = {}
ret = self.cpu_stats_file.read_text()
usage_info: List[str] = re.findall(r"cpu[^\n]+", ret)
for cpu in usage_info:
parts = cpu.split()
name = parts[0]
cpu_sum = sum([int(t) for t in parts[1:]])
cpu_idle = int(parts[4])
if name in self.last_cpu_stats:
last_sum, last_idle = self.last_cpu_stats[name]
cpu_delta = cpu_sum - last_sum
idle_delta = cpu_idle - last_idle
cpu_used = cpu_delta - idle_delta
cpu_usage[name] = round(
100 * (cpu_used / cpu_delta), 2)
self.cpu_usage = cpu_usage
self.last_cpu_stats[name] = (cpu_sum, cpu_idle)
except Exception:
pass
def _format_stats(self, stats: Dict[str, Any]) -> str:
return f"System Time: {stats['time']:2f}, " \
f"Usage: {stats['cpu_usage']}%, " \
f"Memory: {stats['memory']} {stats['mem_units']}"
def close(self):
self.stat_update_cb.stop()
def log_last_stats(self, count: int = 1):
count = min(len(self.proc_stat_queue), count)
msg = ""
for stats in list(self.proc_stat_queue)[-count:]:
msg += f"\n{self._format_stats(stats)}"
logging.info(msg)
def load_component(config):
def close(self) -> None:
self.stat_update_timer.stop()
self.watchdog.stop()
class Watchdog:
def __init__(self, proc_stats: ProcStats) -> None:
self.proc_stats = proc_stats
self.event_loop = proc_stats.event_loop
self.blocked_count: int = 0
self.last_watch_time: float = 0.
self.watchdog_timer = self.event_loop.register_timer(
self._watchdog_callback
)
def _watchdog_callback(self, eventtime: float) -> float:
time_diff = eventtime - self.last_watch_time
if time_diff > REPORT_BLOCKED_TIME:
self.blocked_count += 1
logging.info(
f"EVENT LOOP BLOCKED: {round(time_diff, 2)} seconds"
f", total blocked count: {self.blocked_count}")
# delay the stat logging so we capture the CPU percentage after
# the next cycle
self.event_loop.delay_callback(
.2, self.proc_stats.log_last_stats, 5)
self.last_watch_time = eventtime
return eventtime + WATCHDOG_REFRESH_TIME
def start(self):
if not self.watchdog_timer.is_running():
self.last_watch_time = self.event_loop.get_loop_time()
self.watchdog_timer.start()
def stop(self):
self.watchdog_timer.stop()
def load_component(config: ConfigHelper) -> ProcStats:
return ProcStats(config)
+91
View File
@@ -0,0 +1,91 @@
# Support for password/token secrets
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import pathlib
import logging
import configparser
import json
from typing import (
TYPE_CHECKING,
Dict,
Optional,
Any
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from .file_manager.file_manager import FileManager
class Secrets:
def __init__(self, config: ConfigHelper) -> None:
server = config.get_server()
self.secrets_file: Optional[pathlib.Path] = None
path: Optional[str] = config.get("secrets_path", None, deprecate=True)
app_args = server.get_app_args()
data_path = app_args["data_path"]
fpath = pathlib.Path(data_path).joinpath("moonraker.secrets")
if not fpath.is_file() and path is not None:
fpath = pathlib.Path(path).expanduser().resolve()
self.type = "invalid"
self.values: Dict[str, Any] = {}
fm: FileManager = server.lookup_component("file_manager")
fm.add_reserved_path("secrets", fpath, False)
if fpath.is_file():
self.secrets_file = fpath
data = self.secrets_file.read_text()
vals = self._parse_json(data)
if vals is not None:
if not isinstance(vals, dict):
server.add_warning(
f"[secrets]: option 'secrets_path', top level item in"
f" json file '{self.secrets_file}' must be an Object.")
return
self.values = vals
self.type = "json"
else:
vals = self._parse_ini(data)
if vals is None:
server.add_warning(
"[secrets]: option 'secrets_path', invalid file "
f"format, must be json or ini: '{self.secrets_file}'")
return
self.values = vals
self.type = "ini"
logging.debug(f"[secrets]: Loaded {self.type} file: "
f"{self.secrets_file}")
elif path is not None:
server.add_warning(
"[secrets]: option 'secrets_path', file does not exist: "
f"'{self.secrets_file}'")
else:
logging.debug(
"[secrets]: Option `secrets_path` not supplied")
def _parse_ini(self, data: str) -> Optional[Dict[str, Any]]:
try:
cfg = configparser.ConfigParser(interpolation=None)
cfg.read_string(data)
return {sec: dict(cfg.items(sec)) for sec in cfg.sections()}
except Exception:
return None
def _parse_json(self, data: str) -> Optional[Dict[str, Any]]:
try:
return json.loads(data)
except json.JSONDecodeError:
return None
def get_type(self) -> str:
return self.type
def __getitem__(self, key: str) -> Any:
return self.values[key]
def get(self, key: str, default: Any = None) -> Any:
return self.values.get(key, default)
def load_component(config: ConfigHelper) -> Secrets:
return Secrets(config)
+304
View File
@@ -0,0 +1,304 @@
# Generic sensor support
#
# Copyright (C) 2022 Morton Jonuschat <mjonuschat+moonraker@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
# Component to read additional generic sensor data and make it
# available to clients
from __future__ import annotations
import logging
from collections import defaultdict, deque
from dataclasses import dataclass, replace
from functools import partial
# Annotation imports
from typing import (
Any,
DefaultDict,
Deque,
Dict,
List,
Optional,
Type,
TYPE_CHECKING,
Union,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..websockets import WebRequest
from .mqtt import MQTTClient
SENSOR_UPDATE_TIME = 1.0
SENSOR_EVENT_NAME = "sensors:sensor_update"
@dataclass(frozen=True)
class SensorConfiguration:
id: str
name: str
type: str
source: str = ""
def _set_result(
name: str, value: Union[int, float], store: Dict[str, Union[int, float]]
) -> None:
if not isinstance(value, (int, float)):
store[name] = float(value)
else:
store[name] = value
@dataclass(frozen=True)
class Sensor:
config: SensorConfiguration
values: Dict[str, Deque[Union[int, float]]]
class BaseSensor:
def __init__(self, name: str, cfg: ConfigHelper, store_size: int = 1200) -> None:
self.server = cfg.get_server()
self.error_state: Optional[str] = None
self.config = SensorConfiguration(
id=name,
type=cfg.get("type"),
name=cfg.get("name", name),
)
self.last_measurements: Dict[str, Union[int, float]] = {}
self.last_value: Dict[str, Union[int, float]] = {}
self.values: DefaultDict[str, Deque[Union[int, float]]] = defaultdict(
lambda: deque(maxlen=store_size)
)
def _update_sensor_value(self, eventtime: float) -> None:
"""
Append the last updated value to the store.
"""
for key, value in self.last_measurements.items():
self.values[key].append(value)
# Copy the last measurements data
self.last_value = {**self.last_measurements}
async def initialize(self) -> bool:
"""
Sensor initialization executed on Moonraker startup.
"""
logging.info("Registered sensor '%s'", self.config.name)
return True
def get_sensor_info(self) -> Dict[str, Any]:
return {
"id": self.config.id,
"friendly_name": self.config.name,
"type": self.config.type,
"values": self.last_measurements,
}
def get_sensor_measurements(self) -> Dict[str, List[Union[int, float]]]:
return {key: list(values) for key, values in self.values.items()}
def get_name(self) -> str:
return self.config.name
def close(self) -> None:
pass
class MQTTSensor(BaseSensor):
def __init__(self, name: str, cfg: ConfigHelper, store_size: int = 1200):
super().__init__(name=name, cfg=cfg)
self.mqtt: MQTTClient = self.server.load_component(cfg, "mqtt")
self.state_topic: str = cfg.get("state_topic")
self.state_response = cfg.load_template("state_response_template", "{payload}")
self.config = replace(self.config, source=self.state_topic)
self.qos: Optional[int] = cfg.getint("qos", None, minval=0, maxval=2)
self.server.register_event_handler(
"mqtt:disconnected", self._on_mqtt_disconnected
)
def _on_state_update(self, payload: bytes) -> None:
measurements: Dict[str, Union[int, float]] = {}
context = {
"payload": payload.decode(),
"set_result": partial(_set_result, store=measurements),
}
try:
self.state_response.render(context)
except Exception as e:
logging.error("Error updating sensor results: %s", e)
self.error_state = str(e)
else:
self.error_state = None
self.last_measurements = measurements
logging.debug(
"Received updated sensor value for %s: %s",
self.config.name,
self.last_measurements,
)
async def _on_mqtt_disconnected(self):
self.error_state = "MQTT Disconnected"
self.last_measurements = {}
async def initialize(self) -> bool:
await super().initialize()
try:
self.mqtt.subscribe_topic(
self.state_topic,
self._on_state_update,
self.qos,
)
self.error_state = None
return True
except Exception as e:
self.error_state = str(e)
return False
class Sensors:
__sensor_types: Dict[str, Type[BaseSensor]] = {"MQTT": MQTTSensor}
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.store_size = config.getint("sensor_store_size", 1200)
prefix_sections = config.get_prefix_sections("sensor")
self.sensors: Dict[str, BaseSensor] = {}
# Register timer to update sensor values in store
self.sensors_update_timer = self.server.get_event_loop().register_timer(
self._update_sensor_values
)
# Register endpoints
self.server.register_endpoint(
"/server/sensors/list",
["GET"],
self._handle_sensor_list_request,
)
self.server.register_endpoint(
"/server/sensors/info",
["GET"],
self._handle_sensor_info_request,
)
self.server.register_endpoint(
"/server/sensors/measurements",
["GET"],
self._handle_sensor_measurements_request,
)
# Register notifications
self.server.register_notification(SENSOR_EVENT_NAME)
for section in prefix_sections:
cfg = config[section]
try:
try:
_, name = cfg.get_name().split(maxsplit=1)
except ValueError:
raise cfg.error(f"Invalid section name: {cfg.get_name()}")
logging.info(f"Configuring sensor: {name}")
sensor_type: str = cfg.get("type")
sensor_class: Optional[Type[BaseSensor]] = self.__sensor_types.get(
sensor_type.upper(), None
)
if sensor_class is None:
raise config.error(f"Unsupported sensor type: {sensor_type}")
self.sensors[name] = sensor_class(
name=name,
cfg=cfg,
store_size=self.store_size,
)
except Exception as e:
# Ensures that configuration errors are shown to the user
self.server.add_warning(
f"Failed to configure sensor [{cfg.get_name()}]\n{e}"
)
continue
def _update_sensor_values(self, eventtime: float) -> float:
"""
Iterate through the sensors and store the last updated value.
"""
changed_data: Dict[str, Dict[str, Union[int, float]]] = {}
for sensor_name, sensor in self.sensors.items():
base_value = sensor.last_value
sensor._update_sensor_value(eventtime=eventtime)
# Notify if a change in sensor values was detected
if base_value != sensor.last_value:
changed_data[sensor_name] = sensor.last_value
if changed_data:
self.server.send_event(SENSOR_EVENT_NAME, changed_data)
return eventtime + SENSOR_UPDATE_TIME
async def component_init(self) -> None:
try:
logging.debug("Initializing sensor component")
for sensor in self.sensors.values():
if not await sensor.initialize():
self.server.add_warning(
f"Sensor '{sensor.get_name()}' failed to initialize"
)
self.sensors_update_timer.start()
except Exception as e:
logging.exception(e)
async def _handle_sensor_list_request(
self, web_request: WebRequest
) -> Dict[str, Dict[str, Any]]:
output = {
"sensors": {
key: sensor.get_sensor_info() for key, sensor in self.sensors.items()
}
}
return output
async def _handle_sensor_info_request(
self, web_request: WebRequest
) -> Dict[str, Any]:
sensor_name: str = web_request.get_str("sensor")
if sensor_name not in self.sensors:
raise self.server.error(f"No valid sensor named {sensor_name}")
sensor = self.sensors[sensor_name]
return sensor.get_sensor_info()
async def _handle_sensor_measurements_request(
self, web_request: WebRequest
) -> Dict[str, Dict[str, Any]]:
sensor_name: str = web_request.get_str("sensor", "")
if sensor_name and sensor_name not in self.sensors:
raise self.server.error(f"No valid sensor named {sensor_name}")
output = {
key: sensor.get_sensor_measurements()
for key, sensor in self.sensors.items()
if sensor_name is "" or key == sensor_name
}
return output
def close(self) -> None:
self.sensors_update_timer.stop()
for sensor in self.sensors.values():
sensor.close()
def load_component(config: ConfigHelper) -> Sensors:
return Sensors(config)
+318 -148
View File
@@ -3,100 +3,140 @@
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import os
import shlex
import logging
import signal
import asyncio
from tornado import gen
from utils import ServerError
from ..utils import ServerError
# Annotation imports
from typing import (
TYPE_CHECKING,
Awaitable,
List,
Optional,
Callable,
Coroutine,
Dict,
Set,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
OutputCallback = Optional[Callable[[bytes], None]]
class ShellCommandError(ServerError):
def __init__(self, message, return_code, stdout=b"",
stderr=b"", status_code=500):
def __init__(
self,
message: str,
return_code: Optional[int],
stdout: Optional[bytes] = b"",
stderr: Optional[bytes] = b"",
status_code: int = 500
) -> None:
super().__init__(message, status_code=status_code)
self.stdout = stdout or b""
self.stderr = stderr or b""
self.return_code = return_code
class SCProcess(asyncio.subprocess.Process):
def initialize(self, program_name, std_out_cb, std_err_cb, log_stderr):
class ShellCommandProtocol(asyncio.subprocess.SubprocessStreamProtocol):
def __init__(
self,
limit: int,
loop: asyncio.events.AbstractEventLoop,
program_name: str = "",
std_out_cb: OutputCallback = None,
std_err_cb: OutputCallback = None,
log_stderr: bool = False
) -> None:
self._loop = loop
self._pipe_fds: List[int] = []
super().__init__(limit, loop)
self.program_name = program_name
self.std_out_cb = std_out_cb
self.std_err_cb = std_err_cb
self.log_stderr = log_stderr
self.cancel_requested = False
self.pending_data: List[bytes] = [b"", b""]
async def _read_stream_with_cb(self, fd):
transport = self._transport.get_pipe_transport(fd)
if fd == 2:
stream = self.stderr
cb = self.std_err_cb
else:
assert fd == 1
stream = self.stdout
def connection_made(
self, transport: asyncio.transports.BaseTransport
) -> None:
self._transport = transport
assert isinstance(transport, asyncio.SubprocessTransport)
stdout_transport = transport.get_pipe_transport(1)
if stdout_transport is not None:
self._pipe_fds.append(1)
stderr_transport = transport.get_pipe_transport(2)
if stderr_transport is not None:
self._pipe_fds.append(2)
stdin_transport = transport.get_pipe_transport(0)
if stdin_transport is not None:
self.stdin = asyncio.streams.StreamWriter(
stdin_transport, # type: ignore
protocol=self,
reader=None,
loop=self._loop
)
def pipe_data_received(self, fd: int, data: bytes | str) -> None:
cb = None
data_idx = fd - 1
if fd == 1:
cb = self.std_out_cb
while not stream.at_eof():
output = await stream.readline()
if not output:
break
if fd == 2 and self.log_stderr:
logging.info(f"{self.program_name}: {output.decode()}")
output = output.rstrip(b'\n')
if output and cb is not None:
cb(output)
transport.close()
return output
elif fd == 2:
cb = self.std_err_cb
if self.log_stderr:
if isinstance(data, bytes):
msg = data.decode(errors='ignore')
else:
msg = data
logging.info(f"{self.program_name}: {msg}")
if cb is not None:
if isinstance(data, str):
data = data.encode()
lines = data.split(b'\n')
lines[0] = self.pending_data[data_idx] + lines[0]
self.pending_data[data_idx] = lines.pop()
for line in lines:
if not line:
continue
cb(line)
async def cancel(self, sig_idx=1):
if self.cancel_requested:
return
self.cancel_requested = True
exit_success = False
sig_idx = min(2, max(0, sig_idx))
sigs = [signal.SIGINT, signal.SIGTERM, signal.SIGKILL][sig_idx:]
for sig in sigs:
self.send_signal(sig)
try:
ret = self.wait()
await asyncio.wait_for(ret, timeout=2.)
except asyncio.TimeoutError:
continue
logging.debug(f"Command '{self.program_name}' exited with "
f"signal: {sig.name}")
exit_success = True
break
if not exit_success:
logging.info(f"WARNING: {self.program_name} did not cleanly exit")
if self.stdout is not None:
self.stdout.feed_eof()
if self.stderr is not None:
self.stderr.feed_eof()
def pipe_connection_lost(
self, fd: int, exc: Exception | None
) -> None:
cb = None
pending = b""
if fd == 1:
cb = self.std_out_cb
pending = self.pending_data[0]
elif fd == 2:
cb = self.std_err_cb
pending = self.pending_data[1]
if pending and cb is not None:
cb(pending)
super().pipe_connection_lost(fd, exc)
async def communicate_with_cb(self, input=None):
if input is not None:
stdin = self._feed_stdin(input)
else:
stdin = self._noop()
if self.stdout is not None and self.std_out_cb is not None:
stdout = self._read_stream_with_cb(1)
else:
stdout = self._noop()
has_err_output = self.std_err_cb is not None or self.log_stderr
if self.stderr is not None and has_err_output:
stderr = self._read_stream_with_cb(2)
else:
stderr = self._noop()
stdin, stdout, stderr = await asyncio.tasks.gather(
stdin, stdout, stderr, loop=self._loop)
await self.wait()
class ShellCommand:
IDX_SIGINT = 0
IDX_SIGTERM = 1
IDX_SIGKILL_= 2
def __init__(self, cmd, std_out_callback, std_err_callback,
env=None, log_stderr=False, cwd=None):
IDX_SIGKILL = 2
def __init__(
self,
factory: ShellCommandFactory,
cmd: str,
std_out_callback: OutputCallback,
std_err_callback: OutputCallback,
env: Optional[Dict[str, str]] = None,
log_stderr: bool = False,
cwd: Optional[str] = None
) -> None:
self.factory = factory
self.name = cmd
self.std_out_cb = std_out_callback
self.std_err_cb = std_err_callback
@@ -105,104 +145,189 @@ class ShellCommand:
self.log_stderr = log_stderr
self.env = env
self.cwd = cwd
self.proc = None
self.proc: Optional[asyncio.subprocess.Process] = None
self.cancelled = False
self.return_code = None
self.return_code: Optional[int] = None
self.run_lock = asyncio.Lock()
async def cancel(self, sig_idx=1):
async def cancel(self, sig_idx: int = 1) -> None:
if self.cancelled:
return
self.cancelled = True
if self.proc is not None:
await self.proc.cancel(sig_idx)
exit_success = False
sig_idx = min(2, max(0, sig_idx))
sigs = [signal.SIGINT, signal.SIGTERM, signal.SIGKILL][sig_idx:]
for sig in sigs:
try:
self.proc.send_signal(sig)
ret = self.proc.wait()
await asyncio.wait_for(ret, timeout=2.)
except asyncio.TimeoutError:
continue
except ProcessLookupError:
pass
logging.debug(f"Command '{self.name}' exited with "
f"signal: {sig.name}")
exit_success = True
break
if not exit_success:
logging.info(f"WARNING: {self.name} did not cleanly exit")
def get_return_code(self):
def get_return_code(self) -> Optional[int]:
return self.return_code
def _reset_command_data(self):
def _reset_command_data(self) -> None:
self.return_code = self.proc = None
self.cancelled = False
async def run(self, timeout=2., verbose=True, log_complete=True,
sig_idx=1):
self._reset_command_data()
if not timeout:
# Never timeout
timeout = 9999999999999999.
if self.std_out_cb is None and self.std_err_cb is None and \
not self.log_stderr:
# No callbacks set so output cannot be verbose
verbose = False
if not await self._create_subprocess():
return False
try:
if verbose:
ret = self.proc.communicate_with_cb()
else:
ret = self.proc.wait()
await asyncio.wait_for(ret, timeout=timeout)
except asyncio.TimeoutError:
complete = False
await self.proc.cancel(sig_idx)
else:
complete = not self.cancelled
return self._check_proc_success(complete, log_complete)
async def run_with_response(self, timeout=2., retries=1,
log_complete=True, sig_idx=1):
self._reset_command_data()
retries = max(1, retries)
while retries > 0:
stdout = stderr = b""
if await self._create_subprocess():
try:
ret = self.proc.communicate()
stdout, stderr = await asyncio.wait_for(
ret, timeout=timeout)
except asyncio.TimeoutError:
complete = False
await self.proc.cancel(sig_idx)
async def run(
self,
timeout: float = 2.,
verbose: bool = True,
log_complete: bool = True,
sig_idx: int = 1,
proc_input: Optional[str] = None,
success_codes: Optional[List[int]] = None
) -> bool:
async with self.run_lock:
self.factory.add_running_command(self)
self._reset_command_data()
if not timeout:
# Never timeout
timeout = 9999999999999999.
if (
self.std_out_cb is None
and self.std_err_cb is None and
not self.log_stderr
):
# No callbacks set so output cannot be verbose
verbose = False
created = await self._create_subprocess(
verbose, proc_input is not None)
if not created:
self.factory.remove_running_command(self)
return False
assert self.proc is not None
try:
if proc_input is not None:
ret: Coroutine = self.proc.communicate(
input=proc_input.encode())
else:
complete = not self.cancelled
if self.log_stderr and stderr:
logging.info(f"{self.command[0]}: {stderr.decode()}")
if self._check_proc_success(complete, log_complete):
return stdout.decode().rstrip("\n")
elif stdout:
logging.debug(
f"Shell command '{self.name}' output:"
f"\n{stdout.decode()}")
retries -= 1
await gen.sleep(.5)
raise ShellCommandError(
f"Error running shell command: '{self.command}'",
self.return_code, stdout, stderr)
ret = self.proc.wait()
await asyncio.wait_for(ret, timeout=timeout)
except asyncio.TimeoutError:
complete = False
await self.cancel(sig_idx)
else:
complete = not self.cancelled
self.factory.remove_running_command(self)
return self._check_proc_success(
complete, log_complete, success_codes
)
async def _create_subprocess(self):
loop = asyncio.get_event_loop()
async def run_with_response(
self,
timeout: float = 2.,
retries: int = 1,
log_complete: bool = True,
sig_idx: int = 1,
proc_input: Optional[str] = None,
success_codes: Optional[List[int]] = None
) -> str:
async with self.run_lock:
self.factory.add_running_command(self)
retries = max(1, retries)
stdin: Optional[bytes] = None
if proc_input is not None:
stdin = proc_input.encode()
while retries > 0:
self._reset_command_data()
timed_out = False
stdout = stderr = b""
if await self._create_subprocess(has_input=stdin is not None):
assert self.proc is not None
try:
ret = self.proc.communicate(input=stdin)
stdout, stderr = await asyncio.wait_for(
ret, timeout=timeout)
except asyncio.TimeoutError:
complete = False
timed_out = True
await self.cancel(sig_idx)
else:
complete = not self.cancelled
if self.log_stderr and stderr:
logging.info(
f"{self.command[0]}: "
f"{stderr.decode(errors='ignore')}")
if self._check_proc_success(
complete, log_complete, success_codes
):
self.factory.remove_running_command(self)
return stdout.decode(errors='ignore').rstrip("\n")
if stdout:
logging.debug(
f"Shell command '{self.name}' output:"
f"\n{stdout.decode(errors='ignore')}")
if self.cancelled and not timed_out:
break
retries -= 1
await asyncio.sleep(.5)
self.factory.remove_running_command(self)
raise ShellCommandError(
f"Error running shell command: '{self.name}'",
self.return_code, stdout, stderr)
async def _create_subprocess(
self,
use_callbacks: bool = False,
has_input: bool = False
) -> bool:
loop = asyncio.get_running_loop()
def protocol_factory():
return asyncio.subprocess.SubprocessStreamProtocol(
limit=2**20, loop=loop)
return ShellCommandProtocol(
limit=2**20, loop=loop, program_name=self.command[0],
std_out_cb=self.std_out_cb, std_err_cb=self.std_err_cb,
log_stderr=self.log_stderr)
try:
stdpipe: Optional[int] = None
if has_input:
stdpipe = asyncio.subprocess.PIPE
if self.std_err_cb is not None or self.log_stderr:
errpipe = asyncio.subprocess.PIPE
else:
errpipe = asyncio.subprocess.STDOUT
transport, protocol = await loop.subprocess_exec(
protocol_factory, *self.command,
stdout=asyncio.subprocess.PIPE,
stderr=errpipe, env=self.env, cwd=self.cwd)
self.proc = SCProcess(transport, protocol, loop)
self.proc.initialize(self.command[0], self.std_out_cb,
self.std_err_cb, self.log_stderr)
if use_callbacks:
transport, protocol = await loop.subprocess_exec(
protocol_factory, *self.command, stdin=stdpipe,
stdout=asyncio.subprocess.PIPE,
stderr=errpipe, env=self.env, cwd=self.cwd)
self.proc = asyncio.subprocess.Process(
transport, protocol, loop)
else:
self.proc = await asyncio.create_subprocess_exec(
*self.command, stdin=stdpipe,
stdout=asyncio.subprocess.PIPE,
stderr=errpipe, env=self.env, cwd=self.cwd)
except Exception:
logging.exception(
f"shell_command: Command ({self.name}) failed")
return False
return True
def _check_proc_success(self, complete, log_complete):
def _check_proc_success(
self,
complete: bool,
log_complete: bool,
success_codes: Optional[List[int]] = None
) -> bool:
assert self.proc is not None
if success_codes is None:
success_codes = [0]
self.return_code = self.proc.returncode
success = self.return_code == 0 and complete
success = self.return_code in success_codes and complete
if success:
msg = f"Command ({self.name}) successfully finished"
elif self.cancelled:
@@ -218,10 +343,55 @@ class ShellCommand:
class ShellCommandFactory:
error = ShellCommandError
def build_shell_command(self, cmd, callback=None, std_err_callback=None,
env=None, log_stderr=False, cwd=None):
return ShellCommand(cmd, callback, std_err_callback, env,
log_stderr, cwd)
def __init__(self, config: ConfigHelper) -> None:
self.running_commands: Set[ShellCommand] = set()
def load_component(config):
return ShellCommandFactory()
def add_running_command(self, cmd: ShellCommand) -> None:
self.running_commands.add(cmd)
def remove_running_command(self, cmd: ShellCommand) -> None:
try:
self.running_commands.remove(cmd)
except KeyError:
pass
def build_shell_command(
self,
cmd: str,
callback: OutputCallback = None,
std_err_callback: OutputCallback = None,
env: Optional[Dict[str, str]] = None,
log_stderr: bool = False,
cwd: Optional[str] = None
) -> ShellCommand:
return ShellCommand(
self, cmd, callback, std_err_callback, env, log_stderr, cwd
)
def exec_cmd(
self,
cmd: str,
timeout: float = 2.,
retries: int = 1,
sig_idx: int = 1,
proc_input: Optional[str] = None,
log_complete: bool = True,
log_stderr: bool = False,
env: Optional[Dict[str, str]] = None,
cwd: Optional[str] = None,
success_codes: Optional[List[int]] = None
) -> Awaitable:
scmd = ShellCommand(self, cmd, None, None, env,
log_stderr, cwd)
coro = scmd.run_with_response(
timeout, retries, log_complete, sig_idx,
proc_input, success_codes
)
return asyncio.create_task(coro)
async def close(self) -> None:
for cmd in self.running_commands:
await cmd.cancel()
def load_component(config: ConfigHelper) -> ShellCommandFactory:
return ShellCommandFactory(config)
File diff suppressed because it is too large. Load diff
+111
View File
@@ -0,0 +1,111 @@
# Template Factory helper
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import logging
import asyncio
import jinja2
import json
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Dict
)
if TYPE_CHECKING:
from ..server import Server
from ..confighelper import ConfigHelper
from .secrets import Secrets
class TemplateFactory:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
secrets: Secrets = self.server.load_component(config, 'secrets')
self.jenv = jinja2.Environment('{%', '%}', '{', '}')
self.async_env = jinja2.Environment(
'{%', '%}', '{', '}', enable_async=True
)
self.ui_env = jinja2.Environment(enable_async=True)
self.jenv.add_extension("jinja2.ext.do")
self.jenv.filters['fromjson'] = json.loads
self.async_env.add_extension("jinja2.ext.do")
self.async_env.filters['fromjson'] = json.loads
self.ui_env.add_extension("jinja2.ext.do")
self.ui_env.filters['fromjson'] = json.loads
self.add_environment_global('raise_error', self._raise_error)
self.add_environment_global('secrets', secrets)
def add_environment_global(self, name: str, value: Any):
if name in self.jenv.globals:
raise self.server.error(
f"Jinja 2 environment already contains global {name}")
self.jenv.globals[name] = value
self.async_env.globals[name] = value
def _raise_error(self, err_msg: str, err_code: int = 400) -> None:
raise self.server.error(err_msg, err_code)
def create_template(self,
source: str,
is_async: bool = False
) -> JinjaTemplate:
env = self.async_env if is_async else self.jenv
try:
template = env.from_string(source)
except Exception:
logging.exception(f"Error creating template from source:\n{source}")
raise
return JinjaTemplate(source, self.server, template, is_async)
def create_ui_template(self, source: str) -> JinjaTemplate:
try:
template = self.ui_env.from_string(source)
except Exception:
logging.exception(f"Error creating template from source:\n{source}")
raise
return JinjaTemplate(source, self.server, template, True)
class JinjaTemplate:
def __init__(self,
source: str,
server: Server,
template: jinja2.Template,
is_async: bool
) -> None:
self.server = server
self.orig_source = source
self.template = template
self.is_async = is_async
def __str__(self) -> str:
return self.orig_source
def render(self, context: Dict[str, Any] = {}) -> str:
if self.is_async:
raise self.server.error(
"Cannot render async templates with the render() method"
", use render_async()")
try:
return self.template.render(context).strip()
except Exception as e:
msg = "Error rending Jinja2 Template"
if self.server.is_configured():
raise self.server.error(msg, 500) from e
raise self.server.config_error(msg) from e
async def render_async(self, context: Dict[str, Any] = {}) -> str:
try:
ret = await self.template.render_async(context)
except asyncio.CancelledError:
raise
except Exception as e:
raise self.server.error("Error rending Jinja2 Template", 500) from e
return ret.strip()
def load_component(config: ConfigHelper) -> TemplateFactory:
return TemplateFactory(config)
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,15 @@
# Package definition for the update_manager
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
from . import update_manager as um
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from ...confighelper import ConfigHelper
def load_component(config: ConfigHelper) -> um.UpdateManager:
return um.load_component(config)
@@ -0,0 +1,391 @@
# Deploy updates for applications managed by Moonraker
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import os
import pathlib
import shutil
import hashlib
import logging
import re
from .base_deploy import BaseDeploy
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Optional,
Union,
Dict,
List,
Tuple
)
if TYPE_CHECKING:
from ...confighelper import ConfigHelper
from .update_manager import CommandHelper
from ..machine import Machine
from ..file_manager.file_manager import FileManager
MIN_PIP_VERSION = (23, 0)
SUPPORTED_CHANNELS = {
"zip": ["stable", "beta"],
"git_repo": ["dev", "beta"]
}
TYPE_TO_CHANNEL = {
"zip": "stable",
"zip_beta": "beta",
"git_repo": "dev"
}
class AppDeploy(BaseDeploy):
def __init__(self, config: ConfigHelper, cmd_helper: CommandHelper) -> None:
super().__init__(config, cmd_helper, prefix="Application")
self.config = config
type_choices = list(TYPE_TO_CHANNEL.keys())
self.type = config.get('type').lower()
if self.type not in type_choices:
raise config.error(
f"Config Error: Section [{config.get_name()}], Option "
f"'type: {self.type}': value must be one "
f"of the following choices: {type_choices}"
)
self.channel = config.get(
"channel", TYPE_TO_CHANNEL[self.type]
)
if self.type == "zip_beta":
self.server.add_warning(
f"Config Section [{config.get_name()}], Option 'type: "
"zip_beta', value 'zip_beta' is deprecated. Set 'type' "
"to zip and 'channel' to 'beta'")
self.type = "zip"
self.path = pathlib.Path(
config.get('path')).expanduser().resolve()
if (
self.name not in ["moonraker", "klipper"]
and not self.path.joinpath(".writeable").is_file()
):
fm: FileManager = self.server.lookup_component("file_manager")
fm.add_reserved_path(f"update_manager {self.name}", self.path)
executable = config.get('env', None)
if self.channel not in SUPPORTED_CHANNELS[self.type]:
raise config.error(
f"Invalid Channel '{self.channel}' for config "
f"section [{config.get_name()}], type: {self.type}")
self._verify_path(config, 'path', self.path, check_file=False)
self.executable: Optional[pathlib.Path] = None
self.pip_cmd: Optional[str] = None
self.pip_version: Tuple[int, ...] = tuple()
self.venv_args: Optional[str] = None
if executable is not None:
self.executable = pathlib.Path(executable).expanduser()
self._verify_path(config, 'env', self.executable, check_exe=True)
# Detect if executable is actually located in a virtualenv
# by checking the parent for the activation script
act_path = self.executable.parent.joinpath("activate")
while not act_path.is_file():
if self.executable.is_symlink():
self.executable = pathlib.Path(os.readlink(self.executable))
act_path = self.executable.parent.joinpath("activate")
else:
break
if act_path.is_file():
venv_dir = self.executable.parent.parent
self.log_info(f"Detected virtualenv: {venv_dir}")
pip_exe = self.executable.parent.joinpath("pip")
if pip_exe.is_file():
self.pip_cmd = f"{self.executable} -m pip"
else:
self.log_info("Unable to locate pip executable")
else:
self.log_info(
f"Unable to detect virtualenv at: {executable}"
)
self.executable = pathlib.Path(executable).expanduser()
self.venv_args = config.get('venv_args', None)
self.info_tags: List[str] = config.getlist("info_tags", [])
self.managed_services: List[str] = []
svc_default = []
if config.getboolean("is_system_service", True):
svc_default.append(self.name)
svc_choices = [self.name, "klipper", "moonraker"]
services: List[str] = config.getlist(
"managed_services", svc_default, separator=None
)
for svc in services:
if svc not in svc_choices:
raw = " ".join(services)
self.server.add_warning(
f"[{config.get_name()}]: Option 'managed_services: {raw}' "
f"contains an invalid value '{svc}'. All values must be "
f"one of the following choices: {svc_choices}"
)
break
for svc in svc_choices:
if svc in services and svc not in self.managed_services:
self.managed_services.append(svc)
logging.debug(
f"Extension {self.name} managed services: {self.managed_services}"
)
# We need to fetch all potential options for an Application. Not
# all options apply to each subtype, however we can't limit the
# options in children if we want to switch between channels and
# satisfy the confighelper's requirements.
self.moved_origin: Optional[str] = config.get('moved_origin', None)
self.origin: str = config.get('origin')
self.primary_branch = config.get("primary_branch", "master")
self.npm_pkg_json: Optional[pathlib.Path] = None
if config.getboolean("enable_node_updates", False):
self.npm_pkg_json = self.path.joinpath("package-lock.json")
self._verify_path(config, 'enable_node_updates', self.npm_pkg_json)
self.python_reqs: Optional[pathlib.Path] = None
if self.executable is not None:
self.python_reqs = self.path.joinpath(config.get("requirements"))
self._verify_path(config, 'requirements', self.python_reqs)
self.install_script: Optional[pathlib.Path] = None
install_script = config.get('install_script', None)
if install_script is not None:
self.install_script = self.path.joinpath(install_script).resolve()
self._verify_path(config, 'install_script', self.install_script)
@staticmethod
def _is_git_repo(app_path: Union[str, pathlib.Path]) -> bool:
if isinstance(app_path, str):
app_path = pathlib.Path(app_path).expanduser()
return app_path.joinpath('.git').exists()
async def initialize(self) -> Dict[str, Any]:
storage = await super().initialize()
self.need_channel_update = storage.get("need_channel_update", False)
self._is_valid = storage.get("is_valid", False)
self.pip_version = tuple(storage.get("pip_version", []))
if self.pip_version:
ver_str = ".".join([str(part) for part in self.pip_version])
self.log_info(f"Stored pip version: {ver_str}")
return storage
def _verify_path(
self,
config: ConfigHelper,
option: str,
path: pathlib.Path,
check_file: bool = True,
check_exe: bool = False
) -> None:
base_msg = (
f"Invalid path for option `{option}` in section "
f"[{config.get_name()}]: Path `{path}`"
)
if not path.exists():
raise config.error(f"{base_msg} does not exist")
if check_file and not path.is_file():
raise config.error(f"{base_msg} is not a file")
if check_exe and not os.access(path, os.X_OK):
raise config.error(f"{base_msg} is not executable")
def check_need_channel_swap(self) -> bool:
return self.need_channel_update
def get_configured_type(self) -> str:
return self.type
def check_same_paths(self,
app_path: Union[str, pathlib.Path],
executable: Union[str, pathlib.Path]
) -> bool:
if isinstance(app_path, str):
app_path = pathlib.Path(app_path)
if isinstance(executable, str):
executable = pathlib.Path(executable)
app_path = app_path.expanduser()
executable = executable.expanduser()
if self.executable is None:
return False
try:
return self.path.samefile(app_path) and \
self.executable.samefile(executable)
except Exception:
return False
async def recover(self,
hard: bool = False,
force_dep_update: bool = False
) -> None:
raise NotImplementedError
async def reinstall(self):
raise NotImplementedError
async def restart_service(self):
if not self.managed_services:
return
is_full = self.cmd_helper.is_full_update()
for svc in self.managed_services:
if is_full and svc != self.name:
self.notify_status(f"Service {svc} restart postponed...")
self.cmd_helper.add_pending_restart(svc)
continue
self.cmd_helper.remove_pending_restart(svc)
self.notify_status(f"Restarting service {svc}...")
if svc == "moonraker":
# Launch restart async so the request can return
# before the server restarts
event_loop = self.server.get_event_loop()
event_loop.delay_callback(.1, self._do_restart, svc)
else:
await self._do_restart(svc)
async def _do_restart(self, svc_name: str) -> None:
machine: Machine = self.server.lookup_component("machine")
try:
await machine.do_service_action("restart", svc_name)
except Exception:
if svc_name == "moonraker":
# We will always get an error when restarting moonraker
# from within the child process, so ignore it
return
raise self.log_exc("Error restarting service")
def get_update_status(self) -> Dict[str, Any]:
return {
'channel': self.channel,
'debug_enabled': self.server.is_debug_enabled(),
'need_channel_update': self.need_channel_update,
'is_valid': self._is_valid,
'configured_type': self.type,
'info_tags': self.info_tags
}
def get_persistent_data(self) -> Dict[str, Any]:
storage = super().get_persistent_data()
storage['is_valid'] = self._is_valid
storage['need_channel_update'] = self.need_channel_update
storage['pip_version'] = list(self.pip_version)
return storage
async def _get_file_hash(self,
filename: Optional[pathlib.Path]
) -> Optional[str]:
if filename is None or not filename.is_file():
return None
def hash_func(f: pathlib.Path) -> str:
return hashlib.sha256(f.read_bytes()).hexdigest()
try:
event_loop = self.server.get_event_loop()
return await event_loop.run_in_thread(hash_func, filename)
except Exception:
return None
async def _check_need_update(self,
prev_hash: Optional[str],
filename: Optional[pathlib.Path]
) -> bool:
cur_hash = await self._get_file_hash(filename)
if prev_hash is None or cur_hash is None:
return False
return prev_hash != cur_hash
async def _install_packages(self, package_list: List[str]) -> None:
self.notify_status("Installing system dependencies...")
# Install packages with apt-get
try:
await self.cmd_helper.install_packages(
package_list, timeout=3600., notify=True)
except Exception:
self.log_exc("Error updating packages")
return
async def _update_python_requirements(
self, requirements: Union[pathlib.Path, List[str]]
) -> None:
if self.pip_cmd is None:
return
await self._update_pip()
# Update python dependencies
if isinstance(requirements, pathlib.Path):
if not requirements.is_file():
self.log_info(
f"Invalid path to requirements_file '{requirements}'")
return
args = f"-r {requirements}"
else:
args = " ".join(requirements)
self.notify_status("Updating python packages...")
try:
await self.cmd_helper.run_cmd(
f"{self.pip_cmd} install {args}", timeout=1200., notify=True,
retries=3
)
except Exception:
self.log_exc("Error updating python requirements")
async def _update_pip(self) -> None:
if self.pip_cmd is None:
return
update_ver = await self._check_pip_version()
if update_ver is None:
return
cur_vstr = ".".join([str(part) for part in self.pip_version])
self.notify_status(
f"Updating pip from version {cur_vstr} to {update_ver}..."
)
try:
await self.cmd_helper.run_cmd(
f"{self.pip_cmd} install pip=={update_ver}",
timeout=1200., notify=True, retries=3
)
except Exception:
self.log_exc("Error updating python pip")
async def _check_pip_version(self) -> Optional[str]:
if self.pip_cmd is None:
return None
self.notify_status("Checking pip version...")
try:
data: str = await self.cmd_helper.run_cmd_with_response(
f"{self.pip_cmd} --version", timeout=30., retries=3
)
match = re.match(
r"^pip ([0-9.]+) from .+? \(python ([0-9.]+)\)$", data.strip()
)
if match is None:
return None
pipver_str: str = match.group(1)
pyver_str: str = match.group(2)
pipver = tuple([int(part) for part in pipver_str.split(".")])
pyver = tuple([int(part) for part in pyver_str.split(".")])
except Exception:
self.log_exc("Error Getting Pip Version")
return None
self.pip_version = pipver
if not self.pip_version:
return None
self.log_info(
f"Dectected pip version: {pipver_str}, Python {pyver_str}"
)
if pyver < (3, 7):
return None
if self.pip_version < MIN_PIP_VERSION:
return ".".join([str(ver) for ver in MIN_PIP_VERSION])
return None
async def _build_virtualenv(self) -> None:
if self.executable is None or self.venv_args is None:
return
bin_dir = self.executable.parent
env_path = bin_dir.parent.resolve()
self.notify_status(f"Creating virtualenv at: {env_path}...")
if env_path.exists():
shutil.rmtree(env_path)
try:
await self.cmd_helper.run_cmd(
f"virtualenv {self.venv_args} {env_path}", timeout=300.)
except Exception:
self.log_exc(f"Error creating virtualenv")
return
if not self.executable.exists():
raise self.log_exc("Failed to create new virtualenv", False)
@@ -0,0 +1,61 @@
# Moonraker/Klipper update configuration
#
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import os
import sys
import copy
from ...utils import source_info
from typing import (
TYPE_CHECKING,
Dict
)
if TYPE_CHECKING:
from ...confighelper import ConfigHelper
from ..database import MoonrakerDatabase
KLIPPER_DEFAULT_PATH = os.path.expanduser("~/klipper")
KLIPPER_DEFAULT_EXEC = os.path.expanduser("~/klippy-env/bin/python")
BASE_CONFIG: Dict[str, Dict[str, str]] = {
"moonraker": {
"origin": "https://github.com/arksine/moonraker.git",
"requirements": "scripts/moonraker-requirements.txt",
"venv_args": "-p python3",
"install_script": "scripts/install-moonraker.sh",
"host_repo": "arksine/moonraker",
"env": sys.executable,
"path": str(source_info.source_path()),
"managed_services": "moonraker"
},
"klipper": {
"moved_origin": "https://github.com/kevinoconnor/klipper.git",
"origin": "https://github.com/Klipper3d/klipper.git",
"requirements": "scripts/klippy-requirements.txt",
"venv_args": "-p python2",
"install_script": "scripts/install-octopi.sh",
"host_repo": "arksine/moonraker",
"managed_services": "klipper"
}
}
def get_base_configuration(config: ConfigHelper, channel: str) -> ConfigHelper:
server = config.get_server()
base_cfg = copy.deepcopy(BASE_CONFIG)
app_type = "zip" if channel == "stable" else "git_repo"
base_cfg["moonraker"]["channel"] = channel
base_cfg["moonraker"]["type"] = app_type
base_cfg["klipper"]["channel"] = channel
base_cfg["klipper"]["type"] = app_type
db: MoonrakerDatabase = server.lookup_component('database')
base_cfg["klipper"]["path"] = db.get_item(
"moonraker", "update_manager.klipper_path", KLIPPER_DEFAULT_PATH
).result()
base_cfg["klipper"]["env"] = db.get_item(
"moonraker", "update_manager.klipper_exec", KLIPPER_DEFAULT_EXEC
).result()
return config.read_supplemental_dict(base_cfg)
@@ -0,0 +1,97 @@
# Base Deployment Interface
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import logging
import time
from typing import TYPE_CHECKING, Dict, Any, Optional
if TYPE_CHECKING:
from ...confighelper import ConfigHelper
from ...utils import ServerError
from .update_manager import CommandHelper
class BaseDeploy:
def __init__(self,
config: ConfigHelper,
cmd_helper: CommandHelper,
name: Optional[str] = None,
prefix: str = "",
cfg_hash: Optional[str] = None
) -> None:
if name is None:
name = config.get_name().split(maxsplit=1)[-1]
if name.startswith("client "):
# allow deprecated [update_manager client app] style names
name = name[7:]
self.name = name
if prefix:
prefix = f"{prefix} {self.name}: "
self.prefix = prefix
self.server = config.get_server()
self.cmd_helper = cmd_helper
self.refresh_interval = cmd_helper.get_refresh_interval()
refresh_interval = config.getint('refresh_interval', None)
if refresh_interval is not None:
self.refresh_interval = refresh_interval * 60 * 60
if cfg_hash is None:
cfg_hash = config.get_hash().hexdigest()
self.cfg_hash = cfg_hash
async def initialize(self) -> Dict[str, Any]:
umdb = self.cmd_helper.get_umdb()
storage: Dict[str, Any] = await umdb.get(self.name, {})
self.last_refresh_time: float = storage.get('last_refresh_time', 0.0)
self.last_cfg_hash: str = storage.get('last_config_hash', "")
return storage
def needs_refresh(self) -> bool:
next_refresh_time = self.last_refresh_time + self.refresh_interval
return (
self.cfg_hash != self.last_cfg_hash or
time.time() > next_refresh_time
)
def get_last_refresh_time(self) -> float:
return self.last_refresh_time
async def refresh(self) -> None:
pass
async def update(self) -> bool:
return False
def get_update_status(self) -> Dict[str, Any]:
return {}
def get_persistent_data(self) -> Dict[str, Any]:
return {
'last_config_hash': self.cfg_hash,
'last_refresh_time': self.last_refresh_time
}
def _save_state(self) -> None:
umdb = self.cmd_helper.get_umdb()
self.last_refresh_time = time.time()
self.last_cfg_hash = self.cfg_hash
umdb[self.name] = self.get_persistent_data()
def log_exc(self, msg: str, traceback: bool = True) -> ServerError:
log_msg = f"{self.prefix}{msg}"
if traceback:
logging.exception(log_msg)
else:
logging.info(log_msg)
return self.server.error(msg)
def log_info(self, msg: str) -> None:
log_msg = f"{self.prefix}{msg}"
logging.info(log_msg)
def notify_status(self, msg: str, is_complete: bool = False) -> None:
log_msg = f"{self.prefix}{msg}"
logging.debug(log_msg)
self.cmd_helper.notify_update_response(log_msg, is_complete)
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,431 @@
# Zip Application Deployment implementation
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import os
import pathlib
import json
import shutil
import re
import time
import zipfile
from .app_deploy import AppDeploy
from ...utils import verify_source
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Tuple,
Optional,
Dict,
List,
)
if TYPE_CHECKING:
from ...confighelper import ConfigHelper
from .update_manager import CommandHelper
RINFO_KEYS = [
"git_version", "long_version", "commit_hash", "source_checksum",
"ignored_exts", "ignored_dirs", "build_date", "channel",
"owner_repo", "host_repo", "release_tag"
]
class ZipDeploy(AppDeploy):
def __init__(self, config: ConfigHelper, cmd_helper: CommandHelper) -> None:
super().__init__(config, cmd_helper)
self.need_channel_update = self.type != "zip"
self.official_repo: str = "?"
self.owner: str = "?"
# Extract repo from origin for validation
match = re.match(r"https?://(?:www\.)?github.com/([^/]+/[^.]+)",
self.origin)
if match is not None:
self.official_repo = match.group(1)
self.owner = self.official_repo.split('/')[0]
else:
raise config.error(
"Invalid url set for 'origin' option in section "
f"[{config.get_name()}]. Unable to extract owner/repo.")
self.host_repo: str = config.get('host_repo', self.official_repo)
self.package_list: List[str] = []
self.python_pkg_list: List[str] = []
self.release_download_info: Tuple[str, str, int] = ("?", "?", 0)
@staticmethod
async def from_application(app: AppDeploy) -> ZipDeploy:
new_app = ZipDeploy(app.config, app.cmd_helper)
await new_app.reinstall()
return new_app
async def initialize(self) -> Dict[str, Any]:
storage = await super().initialize()
self.source_checksum: str = storage.get("source_checksum", "?")
self.pristine = storage.get('pristine', False)
self.verified = storage.get('verified', False)
self.build_date: int = storage.get('build_date', 0)
self.full_version: str = storage.get('full_version', "?")
self.short_version: str = storage.get('short_version', "?")
self.commit_hash: str = storage.get('commit_hash', "?")
self.lastest_hash: str = storage.get('latest_hash', "?")
self.latest_version: str = storage.get('latest_version', "?")
self.latest_checksum: str = storage.get('latest_checksum', "?")
self.latest_build_date: int = storage.get('latest_build_date', 0)
self.errors: List[str] = storage.get('errors', [])
self.commit_log: List[Dict[str, Any]] = storage.get('commit_log', [])
return storage
def get_persistent_data(self) -> Dict[str, Any]:
storage = super().get_persistent_data()
storage.update({
'source_checksum': self.source_checksum,
'pristine': self.pristine,
'verified': self.verified,
'build_date': self.build_date,
'full_version': self.full_version,
'short_version': self.short_version,
'commit_hash': self.commit_hash,
'latest_hash': self.lastest_hash,
'latest_version': self.latest_version,
'latest_checksum': self.latest_checksum,
'latest_build_date': self.latest_build_date,
'commit_log': self.commit_log,
'errors': self.errors
})
return storage
async def _parse_info_file(self, file_name: str) -> Dict[str, Any]:
info_file = self.path.joinpath(file_name)
if not info_file.exists():
self.log_info(f"Unable to locate file '{info_file}'")
return {}
try:
event_loop = self.server.get_event_loop()
info_bytes = await event_loop.run_in_thread(info_file.read_text)
info: Dict[str, Any] = json.loads(info_bytes)
except Exception:
self.log_exc(f"Unable to parse info file {file_name}")
info = {}
return info
def _get_tag_version(self, version_string: str) -> str:
tag_version: str = "?"
ver_match = re.match(r"v\d+\.\d+\.\d-\d+", version_string)
if ver_match:
tag_version = ver_match.group()
return tag_version
async def refresh(self) -> None:
try:
await self._update_repo_state()
except Exception:
self.verified = False
self.log_exc("Error refreshing application state")
async def _update_repo_state(self) -> None:
self.errors = []
self._is_valid = False
self.verified = False
release_info = await self._parse_info_file(".release_info")
dep_info = await self._parse_info_file(".dependencies")
for key in RINFO_KEYS:
if key not in release_info:
self._add_error(f"Missing release info item: {key}")
if 'channel' in release_info:
local_channel = release_info['channel']
if self.channel == "stable" and local_channel == "beta":
self.need_channel_update = True
self.full_version = release_info.get('long_version', "?")
self.short_version = self._get_tag_version(
release_info.get('git_version', ""))
self.commit_hash = release_info.get('commit_hash', "?")
self.build_date = release_info.get('build_date', 0)
owner_repo = release_info.get('owner_repo', "?")
if self.official_repo != owner_repo:
self._add_error(
f"Owner repo mismatch. Received {owner_repo}, "
f"official: {self.official_repo}")
# validate the local source code
event_loop = self.server.get_event_loop()
res = await event_loop.run_in_thread(verify_source, self.path)
if res is not None:
self.source_checksum, self.pristine = res
if self.name in ["moonraker", "klipper"]:
self.server.add_log_rollover_item(
f"{self.name}_validation",
f"{self.name} checksum: {self.source_checksum}, "
f"pristine: {self.pristine}")
else:
self._add_error("Unable to validate source checksum")
self.source_checksum = ""
self.pristine = False
self.package_list = sorted(dep_info.get(
'debian', {}).get('packages', []))
self.python_pkg_list = sorted(dep_info.get('python', []))
# Retrieve version info from github to check for updates and
# validate local release info
host_repo = release_info.get('host_repo', "?")
release_tag = release_info.get('release_tag', "?")
if host_repo != self.host_repo:
self._add_error(
f"Host repo mismatch, received: {host_repo}, "
f"expected: {self.host_repo}. This could result in "
" a failed update.")
resource = f"repos/{self.host_repo}/releases"
current_release, latest_release = await self._fetch_github_releases(
resource, release_tag)
await self._validate_current_release(release_info, current_release)
if not self.errors:
self.verified = True
await self._process_latest_release(latest_release)
self._save_state()
self._log_zipapp_info()
async def _fetch_github_releases(self,
resource: str,
current_tag: Optional[str] = None
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
try:
client = self.cmd_helper.get_http_client()
resp = await client.github_api_request(resource, attempts=3)
resp.raise_for_status()
releases = resp.json()
assert isinstance(releases, list)
except Exception:
self.log_exc("Error fetching releases from GitHub")
return {}, {}
release: Dict[str, Any]
latest_release: Dict[str, Any] = {}
current_release: Dict[str, Any] = {}
for release in releases:
if not latest_release:
if self.channel != "stable":
# Allow the beta channel to update regardless
latest_release = release
elif not release['prerelease']:
# This is a stable release on the stable channle
latest_release = release
if current_tag is not None:
if not current_release and release['tag_name'] == current_tag:
current_release = release
if latest_release and current_release:
break
elif latest_release:
break
return current_release, latest_release
async def _validate_current_release(self,
release_info: Dict[str, Any],
release: Dict[str, Any]
) -> None:
if not release:
self._add_error("Unable to find current release on GitHub")
return
asset_info = self._get_asset_urls(release, ["RELEASE_INFO"])
if "RELEASE_INFO" not in asset_info:
self._add_error(
"RELEASE_INFO not found in current release assets")
info_url, content_type, size = asset_info['RELEASE_INFO']
client = self.cmd_helper.get_http_client()
rinfo_bytes = await client.get_file(info_url, content_type)
github_rinfo: Dict[str, Any] = json.loads(rinfo_bytes)
if github_rinfo.get(self.name, {}) != release_info:
self._add_error(
"Local release info does not match the remote")
else:
self.log_info("Current Release Info Validated")
async def _process_latest_release(self, release: Dict[str, Any]):
if not release:
self._add_error("Unable to find latest release on GitHub")
return
zip_file_name = f"{self.name}.zip"
asset_names = ["RELEASE_INFO", "COMMIT_LOG", zip_file_name]
asset_info = self._get_asset_urls(release, asset_names)
if "RELEASE_INFO" in asset_info:
asset_url, content_type, size = asset_info['RELEASE_INFO']
client = self.cmd_helper.get_http_client()
rinfo_bytes = await client.get_file(asset_url, content_type)
update_release_info: Dict[str, Any] = json.loads(rinfo_bytes)
update_info = update_release_info.get(self.name, {})
self.lastest_hash = update_info.get('commit_hash', "?")
self.latest_checksum = update_info.get('source_checksum', "?")
self.latest_version = self._get_tag_version(
update_info.get('git_version', "?"))
self.latest_build_date = update_info.get('build_date', 0)
else:
self._add_error(
"RELEASE_INFO not found in latest release assets")
self.commit_log = []
if self.short_version != self.latest_version:
# Only report commit log if versions change
if "COMMIT_LOG" in asset_info:
asset_url, content_type, size = asset_info['COMMIT_LOG']
client = self.cmd_helper.get_http_client()
commit_bytes = await client.get_file(asset_url, content_type)
commit_info: Dict[str, Any] = json.loads(commit_bytes)
self.commit_log = commit_info.get(self.name, [])
if zip_file_name in asset_info:
self.release_download_info = asset_info[zip_file_name]
self._is_valid = True
else:
self.release_download_info = ("?", "?", 0)
self._add_error(f"Release asset {zip_file_name} not found")
def _get_asset_urls(self,
release: Dict[str, Any],
filenames: List[str]
) -> Dict[str, Tuple[str, str, int]]:
asset_info: Dict[str, Tuple[str, str, int]] = {}
asset: Dict[str, Any]
for asset in release.get('assets', []):
name = asset['name']
if name in filenames:
rinfo_url = asset['browser_download_url']
content_type = asset['content_type']
size = asset['size']
asset_info[name] = (rinfo_url, content_type, size)
filenames.remove(name)
if not filenames:
break
return asset_info
def _add_error(self, warning: str):
self.log_info(warning)
self.errors.append(warning)
def _log_zipapp_info(self):
self.log_info(
"\nZip Application Distribution Detected\n"
f" Valid: {self._is_valid}\n"
f" Verified: {self.verified}\n"
f" Channel: {self.channel}\n"
f" Repo: {self.official_repo}\n"
f" Path: {self.path}\n"
f" Pristine: {self.pristine}\n"
f" Need Channel Update: {self.need_channel_update}\n"
f" Commits Behind: {len(self.commit_log)}\n"
f"Current Release Info:\n"
f" Source Checksum: {self.source_checksum}\n"
f" Commit SHA: {self.commit_hash}\n"
f" Long Version: {self.full_version}\n"
f" Short Version: {self.short_version}\n"
f" Build Date: {time.ctime(self.build_date)}\n"
f"Latest Available Release Info:\n"
f" Source Checksum: {self.latest_checksum}\n"
f" Commit SHA: {self.lastest_hash}\n"
f" Version: {self.latest_version}\n"
f" Build Date: {time.ctime(self.latest_build_date)}\n"
f" Download URL: {self.release_download_info[0]}\n"
f" Content Type: {self.release_download_info[1]}\n"
f" Download Size: {self.release_download_info[2]}"
)
async def _update_dependencies(self,
npm_hash,
force: bool = False
) -> None:
new_deps = await self._parse_info_file('.dependencies')
system_pkgs = sorted(
new_deps.get('debian', {}).get('packages', []))
python_pkgs = sorted(new_deps.get('python', []))
if system_pkgs:
if force or system_pkgs != self.package_list:
await self._install_packages(system_pkgs)
if python_pkgs:
if force or python_pkgs != self.python_pkg_list:
await self._update_python_requirements(python_pkgs)
ret = await self._check_need_update(npm_hash, self.npm_pkg_json)
if force or ret:
if self.npm_pkg_json is not None:
self.notify_status("Updating Node Packages...")
try:
await self.cmd_helper.run_cmd(
"npm ci --only=prod", notify=True, timeout=600.,
cwd=str(self.path))
except Exception:
self.notify_status("Node Package Update failed")
def _extract_release(self, release_zip: pathlib.Path) -> None:
if self.path.is_dir():
shutil.rmtree(self.path)
os.mkdir(self.path)
with zipfile.ZipFile(release_zip) as zf:
zf.extractall(self.path)
async def update(self, force_dep_update: bool = False) -> bool:
if not self._is_valid:
raise self.log_exc("Update aborted, repo not valid", False)
if self.short_version == self.latest_version:
# already up to date
return False
self.cmd_helper.notify_update_response(
f"Updating Application {self.name}...")
npm_hash = await self._get_file_hash(self.npm_pkg_json)
dl_url, content_type, size = self.release_download_info
self.notify_status("Starting Download...")
td = await self.cmd_helper.create_tempdir(self.name, "app")
try:
tempdir = pathlib.Path(td.name)
temp_download_file = tempdir.joinpath(f"{self.name}.zip")
client = self.cmd_helper.get_http_client()
await client.download_file(
dl_url, content_type, temp_download_file, size,
self.cmd_helper.on_download_progress)
self.notify_status(
f"Download Complete, extracting release to '{self.path}'")
event_loop = self.server.get_event_loop()
await event_loop.run_in_thread(
self._extract_release, temp_download_file)
finally:
await event_loop.run_in_thread(td.cleanup)
await self._update_dependencies(npm_hash, force=force_dep_update)
await self._update_repo_state()
await self.restart_service()
self.notify_status("Update Finished...", is_complete=True)
return True
async def recover(self,
hard: bool = False,
force_dep_update: bool = False
) -> None:
res = f"repos/{self.host_repo}/releases"
releases = await self._fetch_github_releases(res)
await self._process_latest_release(releases[1])
await self.update(force_dep_update=force_dep_update)
async def reinstall(self) -> None:
# Clear the persistent storage prior to a channel swap.
# After the next update is complete new data will be
# restored.
umdb = self.cmd_helper.get_umdb()
await umdb.pop(self.name, None)
await self.initialize()
await self.recover(force_dep_update=True)
def get_update_status(self) -> Dict[str, Any]:
status = super().get_update_status()
# XXX - Currently this reports status matching
# that of the git repo so as to not break existing
# client functionality. In the future it would be
# good to report values that are specifc
status.update({
'detected_type': "zip",
'remote_alias': "origin",
'branch': "master",
'owner': self.owner,
'version': self.short_version,
'remote_version': self.latest_version,
'current_hash': self.commit_hash,
'remote_hash': self.lastest_hash,
'is_dirty': False,
'detached': not self.verified,
'commits_behind': self.commit_log,
'git_messages': self.errors,
'full_version_string': self.full_version,
'pristine': self.pristine,
})
return status
+373
View File
@@ -0,0 +1,373 @@
# Centralized webcam configuration
#
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import re
import ipaddress
import socket
import uuid
import logging
from typing import (
TYPE_CHECKING,
Optional,
Dict,
List,
Any,
Tuple
)
if TYPE_CHECKING:
from ..server import Server
from ..confighelper import ConfigHelper
from ..websockets import WebRequest
from .database import MoonrakerDatabase
from .machine import Machine
from .shell_command import ShellCommandFactory
from .http_client import HttpClient
# This provides a mapping of fields defined by Moonraker to fields
# defined by the database.
CAM_FIELDS = {
"name": "name", "service": "service", "target_fps": "targetFps",
"stream_url": "urlStream", "snapshot_url": "urlSnapshot",
"flip_horizontal": "flipX", "flip_vertical": "flipY"
}
class WebcamManager:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.webcams: Dict[str, WebCam] = {}
# parse user configured webcams
prefix_sections = config.get_prefix_sections("webcam ")
for section in prefix_sections:
cam_cfg = config[section]
webcam = WebCam.from_config(cam_cfg)
self.webcams[webcam.name] = webcam
self.server.register_endpoint(
"/server/webcams/list", ["GET"], self._handle_webcam_list
)
self.server.register_endpoint(
"/server/webcams/item", ["GET", "POST", "DELETE"],
self._handle_webcam_request
)
self.server.register_endpoint(
"/server/webcams/test", ["POST"], self._handle_webcam_test
)
self.server.register_notification("webcam:webcams_changed")
self.server.register_event_handler(
"machine:public_ip_changed", self._set_default_host_ip
)
async def component_init(self) -> None:
machine: Machine = self.server.lookup_component("machine")
if machine.public_ip:
self._set_default_host_ip(machine.public_ip)
db: MoonrakerDatabase = self.server.lookup_component("database")
saved_cams: Dict[str, Any] = await db.get_item("webcams", default={})
for cam_data in saved_cams.values():
try:
webcam = WebCam.from_database(self.server, cam_data)
if webcam.name in self.webcams:
continue
self.webcams[webcam.name] = webcam
except Exception:
logging.exception("Failed to process webcam from db")
continue
def _set_default_host_ip(self, ip: str) -> None:
default_host = "http://127.0.0.1"
if ip:
try:
addr = ipaddress.ip_address(ip)
except Exception:
logging.debug(f"Invalid IP Recd: {ip}")
else:
if addr.version == 6:
default_host = f"http://[{addr}]"
else:
default_host = f"http://{addr}"
WebCam.set_default_host(default_host)
logging.info(f"Default public webcam address set: {default_host}")
def get_webcams(self) -> Dict[str, WebCam]:
return self.webcams
def _list_webcams(self) -> List[Dict[str, Any]]:
return [wc.as_dict() for wc in self.webcams.values()]
async def _find_dbcam_by_uuid(
self, name: str
) -> Tuple[str, Dict[str, Any]]:
db: MoonrakerDatabase = self.server.lookup_component("database")
saved_cams: Dict[str, Dict[str, Any]]
saved_cams = await db.get_item("webcams", default={})
for uid, cam_data in saved_cams.items():
if name == cam_data["name"]:
return uid, cam_data
return "", {}
async def _save_cam(self, webcam: WebCam) -> None:
uid, cam_data = await self._find_dbcam_by_uuid(webcam.name)
if not uid:
uid = str(uuid.uuid4())
for mfield, dbfield in CAM_FIELDS.items():
cam_data[dbfield] = getattr(webcam, mfield)
cam_data["location"] = webcam.location
cam_data["rotation"] = webcam.rotation
if "icon" not in cam_data:
cam_data["icon"] = "mdi-webcam"
db: MoonrakerDatabase = self.server.lookup_component("database")
db.insert_item("webcams", uid, cam_data)
async def _delete_cam(self, webcam: WebCam) -> None:
uid, cam = await self._find_dbcam_by_uuid(webcam.name)
if not uid:
return
db: MoonrakerDatabase = self.server.lookup_component("database")
db.delete_item("webcams", uid)
async def _handle_webcam_request(
self, web_request: WebRequest
) -> Dict[str, Any]:
action = web_request.get_action()
name = web_request.get_str("name")
webcam_data: Dict[str, Any] = {}
if action == "GET":
if name not in self.webcams:
raise self.server.error(f"Webcam {name} not found", 404)
webcam_data = self.webcams[name].as_dict()
elif action == "POST":
if (
name in self.webcams and
self.webcams[name].source == "config"
):
raise self.server.error(
f"Cannot overwrite webcam '{name}' sourced from "
"Moonraker configuration"
)
webcam = WebCam.from_web_request(self.server, web_request)
self.webcams[name] = webcam
webcam_data = webcam.as_dict()
await self._save_cam(webcam)
elif action == "DELETE":
if name not in self.webcams:
raise self.server.error(f"Webcam {name} not found", 404)
elif self.webcams[name].source == "config":
raise self.server.error(
f"Cannot delete webcam '{name}' sourced from "
"Moonraker configuration"
)
webcam = self.webcams.pop(name)
webcam_data = webcam.as_dict()
await self._delete_cam(webcam)
if action != "GET":
self.server.send_event(
"webcam:webcams_changed", {"webcams": self._list_webcams()}
)
return {"webcam": webcam_data}
async def _handle_webcam_list(
self, web_request: WebRequest
) -> Dict[str, Any]:
return {"webcams": self._list_webcams()}
async def _handle_webcam_test(
self, web_request: WebRequest
) -> Dict[str, Any]:
name = web_request.get_str("name")
if name not in self.webcams:
raise self.server.error(f"Webcam '{name}' not found", 404)
client: HttpClient = self.server.lookup_component("http_client")
cam = self.webcams[name]
result: Dict[str, Any] = {
"name": name,
"snapshot_reachable": False
}
for img_type in ["snapshot", "stream"]:
try:
func = getattr(cam, f"get_{img_type}_url")
result[f"{img_type}_url"] = await func(True)
except Exception:
logging.exception(f"Error Processing {img_type} url")
result[f"{img_type}_url"] = ""
url: str = result["snapshot_url"]
if result.get("snapshot_url", "").startswith("http"):
ret = await client.get(url, connect_timeout=1., request_timeout=1.)
result["snapshot_reachable"] = not ret.has_error()
return result
class WebCam:
_default_host: str = "http://127.0.0.1"
def __init__(self, server: Server, **kwargs) -> None:
self._server = server
self.name: str = kwargs["name"]
self.location: str = kwargs["location"]
self.service: str = kwargs["service"]
self.target_fps: int = kwargs["target_fps"]
self.stream_url: str = kwargs["stream_url"]
self.snapshot_url: str = kwargs["snapshot_url"]
self.flip_horizontal: bool = kwargs["flip_horizontal"]
self.flip_vertical: bool = kwargs["flip_vertical"]
self.rotation: int = kwargs["rotation"]
self.source: str = kwargs["source"]
def as_dict(self):
return {k: v for k, v in self.__dict__.items() if k[0] != "_"}
async def get_stream_url(self, convert_local: bool = False) -> str:
return await self._get_url(self.stream_url, convert_local)
async def get_snapshot_url(self, convert_local: bool = False) -> str:
return await self._get_url(self.snapshot_url, convert_local)
async def _get_url(self, url: str, convert_local: bool) -> str:
if not url:
raise self._server.error("Empty URL Provided")
match = re.match(r"\w+://[^/]+", url)
if match is None:
# assume a partial URL on the default host
url = f"{self._default_host}/{url.lstrip('/')}"
if not convert_local:
return url
return await self.convert_local(url)
def _get_local_ips(self) -> List[str]:
all_ips: List[str] = []
machine: Machine = self._server.lookup_component("machine")
sys_info = machine.get_system_info()
network = sys_info.get("network", {})
iface: Dict[str, Any]
for iface in network.values():
addresses: List[Dict[str, Any]] = iface["ip_addresses"]
for addr_info in addresses:
all_ips.append(addr_info["address"])
return all_ips
async def convert_local(self, url: str) -> str:
match = re.match(r"(\w+)://([^/]+)(/.*)?", url)
if match is None:
return url
scheme = match.group(1)
addr = match.group(2)
fragment = match.group(3)
if fragment is None:
fragment = ""
if addr[0] == "[":
# ipv6 address
addr_match = re.match(r"\[(.+)\](:\d+)?", addr)
else:
# ipv4 address or hostname
addr_match = re.match(r"([^:]+)(:\d+)?", addr)
if addr_match is None:
return url
addr = addr_match.group(1)
port: Optional[str] = addr_match.group(2)
default_ports = {"http": "80", "https": "443", "rtsp": "554"}
if port is None:
if scheme not in default_ports:
return url
port = default_ports[scheme]
else:
port = port.lstrip(":")
# attempt to convert hostname to IP
try:
eventloop = self._server.get_event_loop()
addr_info = await eventloop.run_in_thread(
socket.getaddrinfo, addr, int(port)
)
if addr_info:
addr = addr_info[0][4][0]
except Exception:
pass
try:
ip = ipaddress.ip_address(addr)
except Exception:
# Invalid IP, can't convert.
return url
else:
if ip.is_loopback:
return url
# Check to see if this ip address is on the local machine
if addr not in self._get_local_ips():
return url
scmd: ShellCommandFactory
scmd = self._server.lookup_component("shell_command")
try:
# Use the ss command to list all tcp ports
resp: str = await scmd.exec_cmd("ss -ltn")
lines = resp.split("\n")[1:]
for line in lines:
parts = line.strip().split()
if len(parts) < 5:
continue
laddr, lport = parts[3].split(":")
if lport == port:
if laddr == "[::]":
return f"{scheme}://[::1]:{port}{fragment}"
elif laddr == "0.0.0.0":
return f"{scheme}://127.0.0.1:{port}{fragment}"
except scmd.error:
pass
return url
@staticmethod
def set_default_host(host: str) -> None:
WebCam._default_host = host
@classmethod
def from_config(cls, config: ConfigHelper) -> WebCam:
webcam: Dict[str, Any] = {}
webcam["name"] = config.get_name().split(maxsplit=1)[-1]
webcam["location"] = config.get("location", "printer")
webcam["service"] = config.get("service", "mjpegstreamer")
webcam["target_fps"] = config.getint("target_fps", 15)
webcam["stream_url"] = config.get("stream_url")
webcam["snapshot_url"] = config.get("snapshot_url")
webcam["flip_horizontal"] = config.getboolean("flip_horizontal", False)
webcam["flip_vertical"] = config.getboolean("flip_vertical", False)
webcam["rotation"] = config.getint("rotation", 0)
if webcam["rotation"] not in [0, 90, 180, 270]:
raise config.error("Invalid value for option 'rotation'")
webcam["source"] = "config"
return cls(config.get_server(), **webcam)
@classmethod
def from_web_request(
cls, server: Server, web_request: WebRequest
) -> WebCam:
webcam: Dict[str, Any] = {}
webcam["name"] = web_request.get_str("name")
webcam["location"] = web_request.get_str("location", "printer")
webcam["service"] = web_request.get_str("service", "mjpegstreamer")
webcam["target_fps"] = web_request.get_int("target_fps", 15)
webcam["stream_url"] = web_request.get_str("stream_url")
webcam["snapshot_url"] = web_request.get_str("snapshot_url")
webcam["flip_horizontal"] = web_request.get_boolean(
"flip_horizontal", False
)
webcam["flip_vertical"] = web_request.get_boolean(
"flip_vertical", False
)
webcam["rotation"] = web_request.get_int("rotation", 0)
if webcam["rotation"] not in [0, 90, 180, 270]:
raise server.error("Invalid value for parameter 'rotation'")
webcam["source"] = "database"
return cls(server, **webcam)
@classmethod
def from_database(cls, server: Server, cam_data: Dict[str, Any]) -> WebCam:
webcam: Dict[str, Any] = {}
for mfield, dbfield in CAM_FIELDS.items():
webcam[mfield] = cam_data[dbfield]
webcam["location"] = webcam.get("location", "printer")
webcam["rotation"] = webcam.get("rotation", 0)
webcam["source"] = "database"
return cls(server, **webcam)
def load_component(config: ConfigHelper) -> WebcamManager:
return WebcamManager(config)
+594
View File
@@ -0,0 +1,594 @@
# WLED neopixel support
#
# Copyright (C) 2021-2022 Richard Mitchell <richardjm+moonraker@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
# Component to control the wled neopixel home system from AirCookie
# Github at https://github.com/Aircoookie/WLED
# Wiki at https://kno.wled.ge/
from __future__ import annotations
from enum import Enum
import logging
import json
import asyncio
import serial_asyncio
from tornado.httpclient import AsyncHTTPClient
from tornado.httpclient import HTTPRequest
# Annotation imports
from typing import (
TYPE_CHECKING,
Type,
List,
Any,
Optional,
Dict,
)
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from ..websockets import WebRequest
class OnOff(str, Enum):
on: str = "on"
off: str = "off"
class Strip():
_COLORSIZE: int = 4
def __init__(self: Strip,
name: str,
cfg: ConfigHelper):
self.server = cfg.get_server()
self.request_mutex = asyncio.Lock()
self.name = name
self.initial_preset: int = cfg.getint("initial_preset", -1)
self.initial_red: float = cfg.getfloat("initial_red", 0.5)
self.initial_green: float = cfg.getfloat("initial_green", 0.5)
self.initial_blue: float = cfg.getfloat("initial_blue", 0.5)
self.initial_white: float = cfg.getfloat("initial_white", 0.5)
self.chain_count: int = cfg.getint("chain_count", 1)
# Supports rgbw always
self._chain_data = bytearray(
self.chain_count * self._COLORSIZE)
self.onoff = OnOff.off
self.preset = self.initial_preset
def get_strip_info(self: Strip) -> Dict[str, Any]:
return {
"strip": self.name,
"status": self.onoff.value,
"chain_count": self.chain_count,
"preset": self.preset,
"brightness": self.brightness,
"intensity": self.intensity,
"speed": self.speed,
"error": self.error_state
}
async def initialize(self: Strip) -> None:
self.send_full_chain_data = True
self.onoff = OnOff.on
self.preset = self.initial_preset
self.brightness = 255
self.intensity = -1
self.speed = -1
if self.initial_preset >= 0:
self._update_color_data(self.initial_red,
self.initial_green,
self.initial_blue,
self.initial_white,
None)
await self.wled_on(self.initial_preset)
else:
await self.set_wled(self.initial_red,
self.initial_green,
self.initial_blue,
self.initial_white,
None,
True)
def _update_color_data(self: Strip,
red: float, green: float, blue: float, white: float,
index: Optional[int]) -> None:
red = int(red * 255. + .5)
blue = int(blue * 255. + .5)
green = int(green * 255. + .5)
white = int(white * 255. + .5)
led_data = [red, green, blue, white]
if index is None:
self._chain_data[:] = led_data * self.chain_count
else:
elem_size = len(led_data)
self._chain_data[(index-1)*elem_size:index*elem_size] = led_data
async def send_wled_command_impl(self: Strip,
state: Dict[str, Any]) -> None:
pass
def close(self: Strip):
pass
async def _send_wled_command(self: Strip,
state: Dict[str, Any]) -> None:
try:
await self.send_wled_command_impl(state)
self.error_state = None
except Exception as e:
msg = f"WLED: Error {e}"
self.error_state = msg
logging.exception(msg)
raise self.server.error(msg)
async def wled_on(self: Strip, preset: int) -> None:
self.onoff = OnOff.on
logging.debug(f"WLED: {self.name} on PRESET={preset}")
if preset < 0:
# WLED_ON STRIP=strip (no args) - reset to default
await self.initialize()
else:
self.send_full_chain_data = True
self.preset = preset
# Without reading the data back from wled we don't know the values
self.brightness = -1
self.intensity = -1
self.speed = -1
await self._send_wled_command({"on": True, "ps": preset})
async def wled_off(self: Strip) -> None:
logging.debug(f"WLED: {self.name} off")
self.onoff = OnOff.off
# Without this calling SET_WLED for a single pixel after WLED_OFF
# would send just that pixel
self.send_full_chain_data = True
await self._send_wled_command({"on": False})
async def wled_control(self: Strip, brightness: int, intensity: int,
speed: int) -> None:
logging.debug(
f"WLED: {self.name} control {self.onoff} BRIGHTNESS={brightness} "
f"INTENSITY={intensity} SPEED={speed} CURRENTPRESET={self.preset}")
if self.onoff == OnOff.off:
logging.info("wled control only permitted when strip is on")
return
# Even if a preset is not activated sending seg {} information will
# turn it back on
control: Dict[str, Any]
if self.preset != -1:
control = {"tt": 0, "seg": {}}
else:
control = {"tt": 0}
shouldSend: bool = False
# Using 0 is not recommended in wled docs
if brightness > 0:
if brightness > 255:
logging.info("BRIGHTNESS should be between 1 and 255")
else:
shouldSend = True
self.brightness = brightness
control["bri"] = self.brightness
# Brightness in seg {} - only if a preset is on
if self.preset != -1:
control["seg"]["bri"] = self.brightness
# Intensity - only if a preset is on
if intensity > -1 and self.preset != -1:
if intensity > 255:
logging.info("INTENSITY should be between 0 and 255")
else:
shouldSend = True
self.intensity = intensity
control["seg"]["ix"] = self.intensity
# Speed - only if a preset is on
if speed > -1 and self.preset != -1:
if speed > 255:
logging.info("SPEED should be between 0 and 255")
else:
shouldSend = True
self.speed = speed
control["seg"]["sx"] = self.speed
# Control brightness, intensity, and speed for segment
# This will allow full control for effects such as "Percent"
if shouldSend:
await self._send_wled_command(control)
def _wled_pixel(self: Strip, index: int) -> List[int]:
led_color_data: List[int] = []
for p in self._chain_data[(index-1)*self._COLORSIZE:
(index)*self._COLORSIZE]:
led_color_data.append(p)
return led_color_data
async def set_wled(self: Strip,
red: float, green: float, blue: float, white: float,
index: Optional[int], transmit: bool) -> None:
logging.debug(
f"WLED: {self.name} R={red} G={green} B={blue} W={white} "
f"INDEX={index} TRANSMIT={transmit}")
self._update_color_data(red, green, blue, white, index)
if transmit:
# Clear preset (issues with sending seg{} will revert to preset)
self.preset = -1
# If we are coming from a preset without a wled_control
# we don't know a brightness, this will also ensure
# behaviour is consistent prior to introduction of wled_control
if self.brightness == -1:
self.brightness = 255
# Base command for setting an led (for all active segments)
# See https://kno.wled.ge/interfaces/json-api/
state: Dict[str, Any] = {"on": True,
"tt": 0,
"bri": self.brightness,
"seg": {"bri": self.brightness, "i": []}}
if index is None:
# All pixels same color only send range command of first color
self.send_full_chain_data = False
state["seg"]["i"] = [0, self.chain_count, self._wled_pixel(1)]
elif self.send_full_chain_data:
# Send a full set of color data (e.g. previous preset)
self.send_full_chain_data = False
cdata = []
for i in range(self.chain_count):
cdata.append(self._wled_pixel(i+1))
state["seg"]["i"] = cdata
else:
# Only one pixel has changed since last full data sent
# so send just that one
state["seg"]["i"] = [index-1, self._wled_pixel(index)]
# Send wled control command
await self._send_wled_command(state)
if self.onoff == OnOff.off:
# Without a repeated call individual led control doesn't
# turn the led strip back on or doesn't set brightness
# correctly from off
# Confirmed as a bug:
# https://discord.com/channels/473448917040758787/757254961640898622/934135556370202645
self.onoff = OnOff.on
await self._send_wled_command(state)
else:
# If not transmitting this time easiest just to send all data when
# next transmitting
self.send_full_chain_data = True
class StripHttp(Strip):
def __init__(self: StripHttp,
name: str,
cfg: ConfigHelper):
super().__init__(name, cfg)
# Read the uri information
addr: str = cfg.get("address")
port: int = cfg.getint("port", 80)
protocol: str = cfg.get("protocol", "http")
self.url = f"{protocol}://{addr}:{port}/json"
self.timeout: float = cfg.getfloat("timeout", 2.)
self.client = AsyncHTTPClient()
async def send_wled_command_impl(self: StripHttp,
state: Dict[str, Any],
retries: int = 3
) -> None:
async with self.request_mutex:
logging.debug(f"WLED: url:{self.url} json:{state}")
headers = {"Content-Type": "application/json"}
request = HTTPRequest(url=self.url,
method="POST",
headers=headers,
body=json.dumps(state),
connect_timeout=self.timeout,
request_timeout=self.timeout)
for i in range(retries):
try:
response = await self.client.fetch(request)
except Exception:
if i == retries - 1:
raise
await asyncio.sleep(1.0)
else:
break
logging.debug(
f"WLED: url:{self.url} status:{response.code} "
f"response:{response.body.decode()}")
class StripSerial(Strip):
def __init__(self: StripSerial,
name: str,
cfg: ConfigHelper):
super().__init__(name, cfg)
# Read the serial information (requires wled 0.13 2108250 or greater)
self.serialport: str = cfg.get("serial")
self.baud: int = cfg.getint("baud", 115200, above=49)
async def send_wled_command_impl(self: StripSerial,
state: Dict[str, Any]) -> None:
async with self.request_mutex:
if not hasattr(self, 'ser'):
_, self.ser = await serial_asyncio.open_serial_connection(
url=self.serialport, baudrate=self.baud)
logging.debug(f"WLED: serial:{self.serialport} json:{state}")
self.ser.write(json.dumps(state).encode())
def close(self: StripSerial):
if hasattr(self, 'ser'):
self.ser.close()
logging.info(f"WLED: Closing serial {self.serialport}")
class WLED:
def __init__(self: WLED, config: ConfigHelper) -> None:
# root_logger = logging.getLogger()
# root_logger.setLevel(logging.DEBUG)
self.server = config.get_server()
prefix_sections = config.get_prefix_sections("wled")
logging.info(f"WLED component loading strips: {prefix_sections}")
strip_types = {
"HTTP": StripHttp,
"SERIAL": StripSerial
}
self.strips = {}
for section in prefix_sections:
cfg = config[section]
try:
name_parts = cfg.get_name().split(maxsplit=1)
if len(name_parts) != 2:
raise cfg.error(
f"Invalid Section Name: {cfg.get_name()}")
name: str = name_parts[1]
logging.info(f"WLED strip: {name}")
# Discard old color_order setting, always support 4 color strips
_ = cfg.get("color_order", "", deprecate=True)
strip_type: str = cfg.get("type", "http")
strip_class: Optional[Type[Strip]]
strip_class = strip_types.get(strip_type.upper())
if strip_class is None:
raise config.error(f"Unsupported Strip Type: {strip_type}")
self.strips[name] = strip_class(name, cfg)
except Exception as e:
# Ensures errors such as "Color not supported" are visible
msg = f"Failed to initialise strip [{cfg.get_name()}]\n{e}"
self.server.add_warning(msg)
continue
# Register two remote methods for GCODE
self.server.register_remote_method(
"set_wled_state", self.set_wled_state)
self.server.register_remote_method(
"set_wled", self.set_wled)
# As moonraker is about making things a web api, let's try it
# Yes, this is largely a cut-n-paste from power.py
self.server.register_endpoint(
"/machine/wled/strips", ["GET"],
self._handle_list_strips)
self.server.register_endpoint(
"/machine/wled/status", ["GET"],
self._handle_batch_wled_request)
self.server.register_endpoint(
"/machine/wled/on", ["POST"],
self._handle_batch_wled_request)
self.server.register_endpoint(
"/machine/wled/off", ["POST"],
self._handle_batch_wled_request)
self.server.register_endpoint(
"/machine/wled/toggle", ["POST"],
self._handle_batch_wled_request)
self.server.register_endpoint(
"/machine/wled/strip", ["GET", "POST"],
self._handle_single_wled_request)
async def component_init(self) -> None:
try:
logging.debug("Initializing wled")
event_loop = self.server.get_event_loop()
cur_time = event_loop.get_loop_time()
endtime = cur_time + 120.
query_strips = list(self.strips.values())
failed_strips: List[Strip] = []
while cur_time < endtime:
for strip in query_strips:
ret = strip.initialize()
if ret is not None:
await ret
if strip.error_state is not None:
failed_strips.append(strip)
if not failed_strips:
logging.debug("All wled strips initialized")
return
query_strips = failed_strips
failed_strips = []
await asyncio.sleep(2.)
cur_time = event_loop.get_loop_time()
if failed_strips:
failed_names = [s.name for s in failed_strips]
self.server.add_warning(
"The following wled strips failed init:"
f" {failed_names}")
except Exception as e:
logging.exception(e)
async def wled_on(self: WLED, strip: str, preset: int) -> None:
if strip not in self.strips:
logging.info(f"Unknown WLED strip: {strip}")
return
await self.strips[strip].wled_on(preset)
# Full control of wled
# state: True, False, "on", "off"
# preset: wled preset (int) to use (ignored if state False or "Off")
async def set_wled_state(
self: WLED,
strip: str,
state: Optional[str] = None,
preset: int = -1,
brightness: int = -1,
intensity: int = -1,
speed: int = -1
) -> None:
status = None
if isinstance(state, bool):
status = OnOff.on if state else OnOff.off
elif isinstance(state, str):
status = state.lower()
if status in ["true", "false"]:
status = OnOff.on if status == "true" else OnOff.off
if status is None and preset == -1 and brightness == -1 and \
intensity == -1 and speed == -1:
logging.info(
f"Invalid state received but no control or preset data passed")
return
if strip not in self.strips:
logging.info(f"Unknown WLED strip: {strip}")
return
# All other arguments are ignored
if status == OnOff.off:
await self.strips[strip].wled_off()
# Turn on if on or a preset is specified
if status == OnOff.on or preset != -1:
await self.strips[strip].wled_on(preset)
# Control
if brightness != -1 or intensity != -1 or speed != -1:
await self.strips[strip].wled_control(brightness, intensity, speed)
# Individual pixel control, for compatibility with SET_LED
async def set_wled(self: WLED,
strip: str,
red: float = 0.,
green: float = 0.,
blue: float = 0.,
white: float = 0.,
index: Optional[int] = None,
transmit: int = 1) -> None:
if strip not in self.strips:
logging.info(f"Unknown WLED strip: {strip}")
return
if isinstance(index, int) and index < 0:
index = None
await self.strips[strip].set_wled(red, green, blue, white,
index,
True if transmit == 1 else False)
async def _handle_list_strips(self,
web_request: WebRequest
) -> Dict[str, Any]:
strips = {name: strip.get_strip_info()
for name, strip in self.strips.items()}
output = {"strips": strips}
return output
async def _handle_single_wled_request(self: WLED,
web_request: WebRequest
) -> Dict[str, Any]:
strip_name: str = web_request.get_str('strip')
preset: int = web_request.get_int('preset', -1)
brightness: int = web_request.get_int('brightness', -1)
intensity: int = web_request.get_int('intensity', -1)
speed: int = web_request.get_int('speed', -1)
req_action = web_request.get_action()
if strip_name not in self.strips:
raise self.server.error(f"No valid strip named {strip_name}")
strip = self.strips[strip_name]
if req_action == 'GET':
return {strip_name: strip.get_strip_info()}
elif req_action == "POST":
action = web_request.get_str('action').lower()
if action not in ["on", "off", "toggle", "control"]:
raise self.server.error(
f"Invalid requested action '{action}'")
result = await self._process_request(strip, action, preset,
brightness, intensity, speed)
return {strip_name: result}
async def _handle_batch_wled_request(self: WLED,
web_request: WebRequest
) -> Dict[str, Any]:
args = web_request.get_args()
ep = web_request.get_endpoint()
if not args:
raise self.server.error("No arguments provided")
requested_strips = {k: self.strips.get(k, None) for k in args}
result = {}
req = ep.split("/")[-1]
for name, strip in requested_strips.items():
if strip is not None:
result[name] = await self._process_request(strip, req, -1,
-1, -1, -1)
else:
result[name] = {"error": "strip_not_found"}
return result
async def _process_request(self: WLED,
strip: Strip,
req: str,
preset: int,
brightness: int,
intensity: int,
speed: int
) -> Dict[str, Any]:
strip_onoff = strip.onoff
if req == "status":
return strip.get_strip_info()
if req == "toggle":
req = "on" if strip_onoff == OnOff.off else "off"
if req in ["on", "off", "control"]:
# Always do something, could be turning off colors, or changing
# preset, easier not to have to worry
if req == "on" or req == "control":
if req == "on":
strip_onoff = OnOff.on
await strip.wled_on(preset)
if brightness != -1 or intensity != -1 or speed != -1:
await strip.wled_control(brightness, intensity, speed)
else:
strip_onoff = OnOff.off
await strip.wled_off()
return strip.get_strip_info()
raise self.server.error(f"Unsupported wled request: {req}")
def close(self) -> None:
for strip in self.strips.values():
strip.close()
def load_component(config: ConfigHelper) -> WLED:
return WLED(config)
+108
View File
@@ -0,0 +1,108 @@
# Zeroconf registration implementation for Moonraker
#
# Copyright (C) 2021 Clifford Roche <clifford.roche@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import socket
import asyncio
import logging
import ipaddress
from zeroconf import IPVersion
from zeroconf.asyncio import AsyncServiceInfo, AsyncZeroconf
from typing import TYPE_CHECKING, Any, Dict, Iterator, List, Optional
if TYPE_CHECKING:
from ..confighelper import ConfigHelper
from .machine import Machine
class AsyncRunner:
def __init__(self, ip_version: IPVersion) -> None:
self.ip_version = ip_version
self.aiozc: Optional[AsyncZeroconf] = None
async def register_services(self, infos: List[AsyncServiceInfo]) -> None:
self.aiozc = AsyncZeroconf(ip_version=self.ip_version)
tasks = [
self.aiozc.async_register_service(info, allow_name_change=True)
for info in infos
]
background_tasks = await asyncio.gather(*tasks)
await asyncio.gather(*background_tasks)
async def unregister_services(self, infos: List[AsyncServiceInfo]) -> None:
assert self.aiozc is not None
tasks = [self.aiozc.async_unregister_service(info) for info in infos]
background_tasks = await asyncio.gather(*tasks)
await asyncio.gather(*background_tasks)
await self.aiozc.async_close()
async def update_services(self, infos: List[AsyncServiceInfo]) -> None:
assert self.aiozc is not None
tasks = [self.aiozc.async_update_service(info) for info in infos]
background_tasks = await asyncio.gather(*tasks)
await asyncio.gather(*background_tasks)
class ZeroconfRegistrar:
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.runner = AsyncRunner(IPVersion.All)
hi = self.server.get_host_info()
addr: str = hi["address"]
if addr.lower() == "all":
addr = "::"
host_ip = ipaddress.ip_address(addr)
fam = socket.AF_INET6 if host_ip.version == 6 else socket.AF_INET
addresses: List[bytes] = [(socket.inet_pton(fam, addr))]
self.bound_all = addr in ["0.0.0.0", "::"]
self.service_info = self._build_service_info(addresses)
if self.bound_all:
self.server.register_event_handler(
"machine:net_state_changed", self._update_service)
async def component_init(self) -> None:
logging.info("Starting Zeroconf services")
if self.bound_all:
machine: Machine = self.server.lookup_component("machine")
network = machine.get_system_info()["network"]
addresses = [x for x in self._extract_ip_addresses(network)]
self.service_info = self._build_service_info(addresses)
await self.runner.register_services([self.service_info])
async def close(self) -> None:
await self.runner.unregister_services([self.service_info])
async def _update_service(self, network: Dict[str, Any]) -> None:
if self.bound_all:
addresses = [x for x in self._extract_ip_addresses(network)]
self.service_info = self._build_service_info(addresses)
await self.runner.update_services([self.service_info])
def _build_service_info(self,
addresses: Optional[List[bytes]] = None
) -> AsyncServiceInfo:
hi = self.server.get_host_info()
return AsyncServiceInfo(
"_moonraker._tcp.local.",
f"Moonraker Instance on {hi['hostname']}._moonraker._tcp.local.",
addresses=addresses,
port=hi["port"],
properties={"path": "/"},
server=f"{hi['hostname']}.local.",
)
def _extract_ip_addresses(self, network: Dict[str, Any]) -> Iterator[bytes]:
for ifname, ifinfo in network.items():
for addr_info in ifinfo["ip_addresses"]:
if addr_info["is_link_local"]:
continue
is_ipv6 = addr_info['family'] == "ipv6"
family = socket.AF_INET6 if is_ipv6 else socket.AF_INET
yield socket.inet_pton(family, addr_info["address"])
def load_component(config: ConfigHelper) -> ZeroconfRegistrar:
return ZeroconfRegistrar(config)
+999 -78
View File
File diff suppressed because it is too large. Load diff
+188
View File
@@ -0,0 +1,188 @@
# Wrapper around the asyncio eventloop
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import asyncio
import inspect
import functools
import socket
import time
import logging
from typing import (
TYPE_CHECKING,
Awaitable,
Callable,
Optional,
Tuple,
TypeVar,
Union
)
if TYPE_CHECKING:
_T = TypeVar("_T")
FlexCallback = Callable[..., Optional[Awaitable]]
TimerCallback = Callable[[float], Union[float, Awaitable[float]]]
class EventLoop:
TimeoutError = asyncio.TimeoutError
def __init__(self) -> None:
self.reset()
def reset(self) -> None:
self.aioloop = self._create_new_loop()
self.add_signal_handler = self.aioloop.add_signal_handler
self.remove_signal_handler = self.aioloop.remove_signal_handler
self.add_reader = self.aioloop.add_reader
self.add_writer = self.aioloop.add_writer
self.remove_reader = self.aioloop.remove_reader
self.remove_writer = self.aioloop.remove_writer
self.get_loop_time = self.aioloop.time
self.create_future = self.aioloop.create_future
self.create_task = self.aioloop.create_task
self.call_at = self.aioloop.call_at
self.set_debug = self.aioloop.set_debug
self.is_running = self.aioloop.is_running
def _create_new_loop(self) -> asyncio.AbstractEventLoop:
for _ in range(5):
# Sometimes the new loop does not properly instantiate.
# Give 5 attempts before raising an exception
new_loop = asyncio.new_event_loop()
if not new_loop.is_closed():
break
logging.info("Failed to create open eventloop, "
"retyring in .5 seconds...")
time.sleep(.5)
else:
raise RuntimeError("Unable to create new open eventloop")
asyncio.set_event_loop(new_loop)
return new_loop
def register_callback(self,
callback: FlexCallback,
*args,
**kwargs
) -> None:
async def _wrapper():
try:
ret = callback(*args, **kwargs)
if inspect.isawaitable(ret):
await ret
except asyncio.CancelledError:
raise
except Exception:
logging.exception("Error Running Callback")
self.aioloop.create_task(_wrapper())
def delay_callback(self,
delay: float,
callback: FlexCallback,
*args,
**kwargs
) -> asyncio.TimerHandle:
return self.aioloop.call_later(
delay, self.register_callback,
functools.partial(callback, *args, **kwargs)
)
def register_timer(self, callback: TimerCallback):
return FlexTimer(self, callback)
def run_in_thread(self,
callback: Callable[..., _T],
*args
) -> Awaitable[_T]:
return self.aioloop.run_in_executor(None, callback, *args)
async def create_socket_connection(
self, address: Tuple[str, int], timeout: Optional[float] = None
) -> socket.socket:
host, port = address
"""
async port of socket.create_connection()
"""
loop = self.aioloop
err = None
ainfo = await loop.getaddrinfo(
host, port, family=0, type=socket.SOCK_STREAM
)
for res in ainfo:
af, socktype, proto, canonname, sa = res
sock = None
try:
sock = socket.socket(af, socktype, proto)
sock.settimeout(0)
sock.setblocking(False)
await asyncio.wait_for(
loop.sock_connect(sock, (host, port)), timeout
)
# Break explicitly a reference cycle
err = None
return sock
except (socket.error, asyncio.TimeoutError) as _:
err = _
if sock is not None:
loop.remove_writer(sock.fileno())
sock.close()
if err is not None:
try:
raise err
finally:
# Break explicitly a reference cycle
err = None
else:
raise socket.error("getaddrinfo returns an empty list")
def start(self):
self.aioloop.run_forever()
def stop(self):
self.aioloop.stop()
def close(self):
self.aioloop.close()
class FlexTimer:
def __init__(self,
eventloop: EventLoop,
callback: TimerCallback
) -> None:
self.eventloop = eventloop
self.callback = callback
self.timer_handle: Optional[asyncio.TimerHandle] = None
self.running: bool = False
def start(self, delay: float = 0.):
if self.running:
return
self.running = True
call_time = self.eventloop.get_loop_time() + delay
self.timer_handle = self.eventloop.call_at(
call_time, self._schedule_task)
def stop(self):
if not self.running:
return
self.running = False
if self.timer_handle is not None:
self.timer_handle.cancel()
self.timer_handle = None
def _schedule_task(self):
self.timer_handle = None
self.eventloop.create_task(self._call_wrapper())
def is_running(self) -> bool:
return self.running
async def _call_wrapper(self):
if not self.running:
return
ret = self.callback(self.eventloop.get_loop_time())
if isinstance(ret, Awaitable):
ret = await ret
if self.running:
self.timer_handle = self.eventloop.call_at(ret, self._schedule_task)
+692
View File
@@ -0,0 +1,692 @@
# KlippyConnection - manage unix socket connection to Klipper
#
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import os
import time
import logging
import json
import getpass
import asyncio
import pathlib
from .utils import ServerError, get_unix_peer_credentials
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Awaitable,
Optional,
Callable,
Coroutine,
Dict,
List,
Set,
Tuple
)
if TYPE_CHECKING:
from .server import Server
from .app import MoonrakerApp
from .websockets import WebRequest, Subscribable
from .confighelper import ConfigHelper
from .components.klippy_apis import KlippyAPI
from .components.file_manager.file_manager import FileManager
from .components.machine import Machine
from .components.job_state import JobState
FlexCallback = Callable[..., Optional[Coroutine]]
# These endpoints are reserved for klippy/moonraker communication only and are
# not exposed via http or the websocket
RESERVED_ENDPOINTS = [
"list_endpoints",
"gcode/subscribe_output",
"register_remote_method",
]
INIT_TIME = .25
LOG_ATTEMPT_INTERVAL = int(2. / INIT_TIME + .5)
MAX_LOG_ATTEMPTS = 10 * LOG_ATTEMPT_INTERVAL
UNIX_BUFFER_LIMIT = 20 * 1024 * 1024
class KlippyConnection:
def __init__(self, server: Server) -> None:
self.server = server
self.uds_address = pathlib.Path("/tmp/klippy_uds")
self.writer: Optional[asyncio.StreamWriter] = None
self.connection_mutex: asyncio.Lock = asyncio.Lock()
self.event_loop = self.server.get_event_loop()
self.log_no_access = True
# Connection State
self.connection_task: Optional[asyncio.Task] = None
self.closing: bool = False
self._klippy_info: Dict[str, Any] = {}
self._klippy_identified: bool = False
self._klippy_initializing: bool = False
self._klippy_started: bool = False
self._klipper_version: str = ""
self._missing_reqs: Set[str] = set()
self._peer_cred: Dict[str, int] = {}
self._service_info: Dict[str, Any] = {}
self.init_attempts: int = 0
self._state: str = "disconnected"
self._state_message: str = "Klippy Disconnected"
self.subscriptions: Dict[Subscribable, Dict[str, Any]] = {}
# Setup remote methods accessable to Klippy. Note that all
# registered remote methods should be of the notification type,
# they do not return a response to Klippy after execution
self.pending_requests: Dict[int, KlippyRequest] = {}
self.remote_methods: Dict[str, FlexCallback] = {}
self.klippy_reg_methods: List[str] = []
self.register_remote_method(
'process_gcode_response', self._process_gcode_response,
need_klippy_reg=False)
self.register_remote_method(
'process_status_update', self._process_status_update,
need_klippy_reg=False)
self.server.register_component("klippy_connection", self)
def configure(self, config: ConfigHelper):
self.uds_address = config.getpath(
"klippy_uds_address", self.uds_address
)
@property
def klippy_apis(self) -> KlippyAPI:
return self.server.lookup_component("klippy_apis")
@property
def state(self) -> str:
if self.is_connected() and not self._klippy_started:
return "startup"
return self._state
@property
def state_message(self) -> str:
return self._state_message
@property
def klippy_info(self) -> Dict[str, Any]:
return self._klippy_info
@property
def missing_requirements(self) -> List[str]:
return list(self._missing_reqs)
@property
def peer_credentials(self) -> Dict[str, int]:
return dict(self._peer_cred)
@property
def service_info(self) -> Dict[str, Any]:
return self._service_info
@property
def unit_name(self) -> str:
svc_info = self._service_info
unit_name = svc_info.get("unit_name", "klipper.service")
return unit_name.split(".", 1)[0]
async def wait_connected(self) -> bool:
if (
self.connection_task is None or
self.connection_task.done()
):
return self.is_connected()
try:
await self.connection_task
except Exception:
pass
return self.is_connected()
async def wait_started(self, timeout: float = 20.) -> bool:
if self.connection_task is None or not self.is_connected():
return False
if not self.connection_task.done():
await asyncio.wait_for(
asyncio.shield(self.connection_task), timeout=timeout)
return self.is_connected()
async def _read_stream(self, reader: asyncio.StreamReader) -> None:
errors_remaining: int = 10
while not reader.at_eof():
try:
data = await reader.readuntil(b'\x03')
except (ConnectionError, asyncio.IncompleteReadError):
break
except asyncio.CancelledError:
logging.exception("Klippy Stream Read Cancelled")
raise
except Exception:
logging.exception("Klippy Stream Read Error")
errors_remaining -= 1
if not errors_remaining or not self.is_connected():
break
continue
errors_remaining = 10
try:
decoded_cmd = json.loads(data[:-1])
self._process_command(decoded_cmd)
except Exception:
logging.exception(
f"Error processing Klippy Host Response: {data.decode()}")
if not self.closing:
logging.debug("Klippy Disconnection From _read_stream()")
await self.close()
async def _write_request(self, request: KlippyRequest) -> None:
if self.writer is None or self.closing:
self.pending_requests.pop(request.id, None)
request.notify(ServerError("Klippy Host not connected", 503))
return
data = json.dumps(request.to_dict()).encode() + b"\x03"
try:
self.writer.write(data)
await self.writer.drain()
except asyncio.CancelledError:
self.pending_requests.pop(request.id, None)
request.notify(ServerError("Klippy Write Request Cancelled", 503))
raise
except Exception:
self.pending_requests.pop(request.id, None)
request.notify(ServerError("Klippy Write Request Error", 503))
if not self.closing:
logging.debug("Klippy Disconnection From _write_request()")
await self.close()
def register_remote_method(self,
method_name: str,
cb: FlexCallback,
need_klippy_reg: bool = True
) -> None:
if method_name in self.remote_methods:
raise self.server.error(
f"Remote method ({method_name}) already registered")
if self.server.is_running():
raise self.server.error(
f"Failed to register remote method {method_name}, "
"methods must be registered during initialization")
self.remote_methods[method_name] = cb
if need_klippy_reg:
# These methods need to be registered with Klippy
self.klippy_reg_methods.append(method_name)
def connect(self) -> Awaitable[bool]:
if (
self.is_connected() or
not self.server.is_running() or
(self.connection_task is not None and
not self.connection_task.done())
):
# already connecting
fut = self.event_loop.create_future()
fut.set_result(self.is_connected())
return fut
self.connection_task = self.event_loop.create_task(self._do_connect())
return self.connection_task
async def _do_connect(self) -> bool:
async with self.connection_mutex:
while self.writer is None:
await asyncio.sleep(INIT_TIME)
if self.closing or not self.server.is_running():
return False
if not self.uds_address.exists():
continue
if not os.access(str(self.uds_address), os.R_OK | os.W_OK):
if self.log_no_access:
user = getpass.getuser()
logging.info(
f"Cannot connect to Klippy, Linux user '{user}' "
"lacks permission to open Unix Domain Socket: "
f"{self.uds_address}")
self.log_no_access = False
continue
self.log_no_access = True
try:
reader, writer = await self.open_klippy_connection(True)
except asyncio.CancelledError:
raise
except Exception:
continue
logging.info("Klippy Connection Established")
self.writer = writer
if self._get_peer_credentials(writer):
machine: Machine = self.server.lookup_component("machine")
provider = machine.get_system_provider()
svc_info = await provider.extract_service_info(
"klipper", self._peer_cred["process_id"]
)
if svc_info != self._service_info:
self._service_info = svc_info
machine.log_service_info(svc_info)
self.event_loop.create_task(self._read_stream(reader))
return await self._init_klippy_connection()
async def open_klippy_connection(
self, primary: bool = False
) -> Tuple[asyncio.StreamReader, asyncio.StreamWriter]:
if not primary and not self.is_connected():
raise ServerError("Klippy Unix Connection Not Available", 503)
return await asyncio.open_unix_connection(
str(self.uds_address), limit=UNIX_BUFFER_LIMIT)
def _get_peer_credentials(self, writer: asyncio.StreamWriter) -> bool:
self._peer_cred = get_unix_peer_credentials(writer, "Klippy")
if not self._peer_cred:
return False
logging.debug(
f"Klippy Connection: Received Peer Credentials: {self._peer_cred}"
)
return True
async def _init_klippy_connection(self) -> bool:
self._klippy_identified = False
self._klippy_started = False
self._klippy_initializing = True
self._missing_reqs.clear()
self.init_attempts = 0
self._state = "startup"
while self.server.is_running():
await asyncio.sleep(INIT_TIME)
await self._check_ready()
if not self._klippy_initializing:
logging.debug("Klippy Connection Initialized")
return True
if not self.is_connected():
self._klippy_initializing = False
break
else:
self.init_attempts += 1
logging.debug("Klippy Connection Failed to Init")
return False
async def _request_endpoints(self) -> None:
result = await self.klippy_apis.list_endpoints(default=None)
if result is None:
return
endpoints = result.get('endpoints', [])
app: MoonrakerApp = self.server.lookup_component("application")
for ep in endpoints:
if ep not in RESERVED_ENDPOINTS:
app.register_remote_handler(ep)
async def _request_initial_subscriptions(self) -> None:
try:
await self.klippy_apis.subscribe_objects({'webhooks': None})
except ServerError as e:
logging.exception("Unable to subscribe to webhooks object")
else:
logging.info("Webhooks Subscribed")
try:
await self.klippy_apis.subscribe_gcode_output()
except ServerError as e:
logging.exception(
"Unable to register gcode output subscription"
)
else:
logging.info("GCode Output Subscribed")
async def _check_ready(self) -> None:
send_id = not self._klippy_identified
result: Dict[str, Any]
try:
result = await self.klippy_apis.get_klippy_info(send_id)
except ServerError as e:
if self.init_attempts % LOG_ATTEMPT_INTERVAL == 0 and \
self.init_attempts <= MAX_LOG_ATTEMPTS:
logging.info(
f"{e}\nKlippy info request error. This indicates that\n"
f"Klippy may have experienced an error during startup.\n"
f"Please check klippy.log for more information")
return
version = result.get("software_version", "")
if version != self._klipper_version:
self._klipper_version = version
msg = f"Klipper Version: {version}"
self.server.add_log_rollover_item("klipper_version", msg)
self._klippy_info = dict(result)
if "state_message" in self._klippy_info:
self._state_message = self._klippy_info["state_message"]
if "state" not in result:
return
if send_id:
self._klippy_identified = True
await self.server.send_event("server:klippy_identified")
# Request initial endpoints to register info, emergency stop APIs
await self._request_endpoints()
self._state = result["state"]
if self._state != "startup":
await self._request_initial_subscriptions()
# Register remaining endpoints available
await self._request_endpoints()
startup_state = self._state
await self.server.send_event(
"server:klippy_started", startup_state
)
self._klippy_started = True
if self._state != "ready":
logging.info("\n" + self._state_message)
if self._state == "shutdown" and startup_state != "shutdown":
# Klippy shutdown during startup event
self.server.send_event("server:klippy_shutdown")
else:
await self._verify_klippy_requirements()
# register methods with klippy
for method in self.klippy_reg_methods:
try:
await self.klippy_apis.register_method(method)
except ServerError:
logging.exception(
f"Unable to register method '{method}'")
if self._state == "ready":
logging.info("Klippy ready")
await self.server.send_event("server:klippy_ready")
if self._state == "shutdown":
# Klippy shutdown during ready event
self.server.send_event("server:klippy_shutdown")
else:
logging.info(
"Klippy state transition from ready during init, "
f"new state: {self._state}"
)
self._klippy_initializing = False
async def _verify_klippy_requirements(self) -> None:
result = await self.klippy_apis.get_object_list(default=None)
if result is None:
logging.info(
f"Unable to retrieve Klipper Object List")
return
req_objs = set(["virtual_sdcard", "display_status", "pause_resume"])
self._missing_reqs = req_objs - set(result)
if self._missing_reqs:
err_str = ", ".join([f"[{o}]" for o in self._missing_reqs])
logging.info(
f"\nWarning, unable to detect the following printer "
f"objects:\n{err_str}\nPlease add the the above sections "
f"to printer.cfg for full Moonraker functionality.")
if "virtual_sdcard" not in self._missing_reqs:
# Update the gcode path
query_res = await self.klippy_apis.query_objects(
{'configfile': None}, default=None)
if query_res is None:
logging.info(f"Unable to set SD Card path")
else:
config = query_res.get('configfile', {}).get('config', {})
vsd_config = config.get('virtual_sdcard', {})
vsd_path = vsd_config.get('path', None)
if vsd_path is not None:
file_manager: FileManager = self.server.lookup_component(
'file_manager')
file_manager.validate_gcode_path(vsd_path)
else:
logging.info(
"Configuration for [virtual_sdcard] not found,"
" unable to set SD Card path")
def _process_command(self, cmd: Dict[str, Any]) -> None:
method = cmd.get('method', None)
if method is not None:
# This is a remote method called from klippy
if method in self.remote_methods:
params = cmd.get('params', {})
self.event_loop.register_callback(
self._execute_method, method, **params)
else:
logging.info(f"Unknown method received: {method}")
return
# This is a response to a request, process
req_id = cmd.get('id', None)
request: Optional[KlippyRequest]
request = self.pending_requests.pop(req_id, None)
if request is None:
logging.info(
f"No request matching request ID: {req_id}, "
f"response: {cmd}")
return
if 'result' in cmd:
result = cmd['result']
if not result:
result = "ok"
else:
err = cmd.get('error', "Malformed Klippy Response")
result = ServerError(err, 400)
request.notify(result)
async def _execute_method(self, method_name: str, **kwargs) -> None:
try:
ret = self.remote_methods[method_name](**kwargs)
if ret is not None:
await ret
except Exception:
logging.exception(f"Error running remote method: {method_name}")
def _process_gcode_response(self, response: str) -> None:
self.server.send_event("server:gcode_response", response)
def _process_status_update(self,
eventtime: float,
status: Dict[str, Any]
) -> None:
if 'webhooks' in status:
wh: Dict[str, str] = status['webhooks']
if "state_message" in wh:
self._state_message = wh["state_message"]
# XXX - process other states (startup, ready, error, etc)?
if "state" in wh:
state = wh["state"]
if state == "shutdown" and not self._klippy_initializing:
# If the shutdown state is received during initialization
# defer the event, the init routine will handle it.
logging.info("Klippy has shutdown")
self.server.send_event("server:klippy_shutdown")
self._state = state
for conn, sub in self.subscriptions.items():
conn_status: Dict[str, Any] = {}
for name, fields in sub.items():
if name in status:
val: Dict[str, Any] = dict(status[name])
if fields is not None:
val = {k: v for k, v in val.items() if k in fields}
if val:
conn_status[name] = val
conn.send_status(conn_status, eventtime)
async def request(self, web_request: WebRequest) -> Any:
if not self.is_connected():
raise ServerError("Klippy Host not connected", 503)
rpc_method = web_request.get_endpoint()
if rpc_method == "objects/subscribe":
return await self._request_subscripton(web_request)
else:
if rpc_method == "gcode/script":
script = web_request.get_str('script', "")
if script:
self.server.send_event(
"klippy_connection:gcode_received", script)
return await self._request_standard(web_request)
async def _request_subscripton(self,
web_request: WebRequest
) -> Dict[str, Any]:
args = web_request.get_args()
conn = web_request.get_subscribable()
# Build the subscription request from a superset of all client
# subscriptions
sub = args.get('objects', {})
if conn is None:
raise self.server.error(
"No connection associated with subscription request")
self.subscriptions[conn] = sub
all_subs: Dict[str, Any] = {}
# request superset of all client subscriptions
for sub in self.subscriptions.values():
for obj, items in sub.items():
if obj in all_subs:
pi = all_subs[obj]
if items is None or pi is None:
all_subs[obj] = None
else:
uitems = list(set(pi) | set(items))
all_subs[obj] = uitems
else:
all_subs[obj] = items
args['objects'] = all_subs
args['response_template'] = {'method': "process_status_update"}
result = await self._request_standard(web_request)
# prune the status response
pruned_status = {}
all_status = result['status']
sub = self.subscriptions.get(conn, {})
for obj, fields in all_status.items():
if obj in sub:
valid_fields = sub[obj]
if valid_fields is None:
pruned_status[obj] = fields
else:
pruned_status[obj] = {k: v for k, v in fields.items()
if k in valid_fields}
result['status'] = pruned_status
return result
async def _request_standard(self, web_request: WebRequest) -> Any:
rpc_method = web_request.get_endpoint()
args = web_request.get_args()
# Create a base klippy request
base_request = KlippyRequest(rpc_method, args)
self.pending_requests[base_request.id] = base_request
self.event_loop.register_callback(self._write_request, base_request)
return await base_request.wait()
def remove_subscription(self, conn: Subscribable) -> None:
self.subscriptions.pop(conn, None)
def is_connected(self) -> bool:
return self.writer is not None and not self.closing
def is_ready(self) -> bool:
return self._state == "ready"
def is_printing(self) -> bool:
if not self.is_ready():
return False
job_state: JobState = self.server.lookup_component("job_state")
stats = job_state.get_last_stats()
return stats.get("state", "") == "printing"
async def rollover_log(self) -> None:
if "unit_name" not in self._service_info:
raise self.server.error(
"Unable to detect Klipper Service, cannot perform "
"manual rollover"
)
logfile: Optional[str] = self._klippy_info.get("log_file", None)
if logfile is None:
raise self.server.error(
"Unable to detect path to Klipper log file"
)
if self.is_printing():
raise self.server.error("Cannot rollover log while printing")
logpath = pathlib.Path(logfile).expanduser().resolve()
if not logpath.is_file():
raise self.server.error(
f"No file at {logpath} exists, cannot perform rollover"
)
machine: Machine = self.server.lookup_component("machine")
await machine.do_service_action("stop", self.unit_name)
suffix = time.strftime("%Y-%m-%d_%H-%M-%S", time.localtime())
new_path = pathlib.Path(f"{logpath}.{suffix}")
def _do_file_op() -> None:
if new_path.exists():
new_path.unlink()
logpath.rename(new_path)
await self.event_loop.run_in_thread(_do_file_op)
await machine.do_service_action("start", self.unit_name)
async def _on_connection_closed(self) -> None:
self._klippy_identified = False
self._klippy_initializing = False
self._klippy_started = False
self._state = "disconnected"
self._state_message = "Klippy Disconnected"
for request in self.pending_requests.values():
request.notify(ServerError("Klippy Disconnected", 503))
self.pending_requests = {}
self.subscriptions = {}
self._peer_cred = {}
self._missing_reqs.clear()
logging.info("Klippy Connection Removed")
await self.server.send_event("server:klippy_disconnect")
if self.server.is_running():
# Reconnect if server is running
loop = self.event_loop
self.connection_task = loop.create_task(self._do_connect())
async def close(self, wait_closed: bool = False) -> None:
if self.closing:
if wait_closed:
await self.connection_mutex.acquire()
self.connection_mutex.release()
return
self.closing = True
if (
self.connection_task is not None and
not self.connection_task.done()
):
self.connection_task.cancel()
async with self.connection_mutex:
if self.writer is not None:
try:
self.writer.close()
await self.writer.wait_closed()
except Exception:
logging.exception("Error closing Klippy Unix Socket")
self.writer = None
await self._on_connection_closed()
self.closing = False
# Basic KlippyRequest class, easily converted to dict for json encoding
class KlippyRequest:
def __init__(self, rpc_method: str, params: Dict[str, Any]) -> None:
self.id = id(self)
self.rpc_method = rpc_method
self.params = params
self._event = asyncio.Event()
self.response: Any = None
async def wait(self) -> Any:
# Log pending requests every 60 seconds
start_time = time.time()
while True:
try:
await asyncio.wait_for(self._event.wait(), 60.)
except asyncio.TimeoutError:
pending_time = time.time() - start_time
logging.info(
f"Request '{self.rpc_method}' pending: "
f"{pending_time:.2f} seconds")
self._event.clear()
continue
break
if isinstance(self.response, ServerError):
raise self.response
return self.response
def notify(self, response: Any) -> None:
if self._event.is_set():
return
self.response = response
self._event.set()
def to_dict(self) -> Dict[str, Any]:
return {'id': self.id, 'method': self.rpc_method,
'params': self.params}
+153
View File
@@ -0,0 +1,153 @@
# Log Management
#
# Copyright (C) 2023 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import logging
import logging.handlers
import os
import sys
import asyncio
from queue import SimpleQueue as Queue
# Annotation imports
from typing import (
TYPE_CHECKING,
Optional,
Awaitable,
Dict,
List,
Any,
)
if TYPE_CHECKING:
from .server import Server
from .websockets import WebRequest
from .klippy_connection import KlippyConnection
# Coroutine friendly QueueHandler courtesy of Martjin Pieters:
# https://www.zopatista.com/python/2019/05/11/asyncio-logging/
class LocalQueueHandler(logging.handlers.QueueHandler):
def emit(self, record: logging.LogRecord) -> None:
# Removed the call to self.prepare(), handle task cancellation
try:
self.enqueue(record)
except asyncio.CancelledError:
raise
except Exception:
self.handleError(record)
# Timed Rotating File Handler, based on Klipper's implementation
class MoonrakerLoggingHandler(logging.handlers.TimedRotatingFileHandler):
def __init__(self, app_args: Dict[str, Any], **kwargs) -> None:
super().__init__(app_args['log_file'], **kwargs)
self.rollover_info: Dict[str, str] = {
'header': f"{'-'*20}Moonraker Log Start{'-'*20}"
}
self.rollover_info['application_args'] = "\n".join(
[f"{k}: {v}" for k, v in app_args.items()])
lines = [line for line in self.rollover_info.values() if line]
if self.stream is not None:
self.stream.write("\n".join(lines) + "\n")
def set_rollover_info(self, name: str, item: str) -> None:
self.rollover_info[name] = item
def doRollover(self) -> None:
super().doRollover()
lines = [line for line in self.rollover_info.values() if line]
if self.stream is not None:
self.stream.write("\n".join(lines) + "\n")
class LogManager:
def __init__(
self, app_args: Dict[str, Any], startup_warnings: List[str]
) -> None:
root_logger = logging.getLogger()
queue: Queue = Queue()
queue_handler = LocalQueueHandler(queue)
root_logger.addHandler(queue_handler)
root_logger.setLevel(logging.INFO)
stdout_hdlr = logging.StreamHandler(sys.stdout)
stdout_fmt = logging.Formatter(
'[%(filename)s:%(funcName)s()] - %(message)s')
stdout_hdlr.setFormatter(stdout_fmt)
for name, val in app_args.items():
logging.info(f"{name}: {val}")
self.file_hdlr: Optional[MoonrakerLoggingHandler] = None
self.listener: Optional[logging.handlers.QueueListener] = None
log_file: str = app_args.get('log_file', "")
if log_file:
try:
self.file_hdlr = MoonrakerLoggingHandler(
app_args, when='midnight', backupCount=2)
formatter = logging.Formatter(
'%(asctime)s [%(filename)s:%(funcName)s()] - %(message)s')
self.file_hdlr.setFormatter(formatter)
self.listener = logging.handlers.QueueListener(
queue, self.file_hdlr, stdout_hdlr)
except Exception:
log_file = os.path.normpath(log_file)
dir_name = os.path.dirname(log_file)
startup_warnings.append(
f"Unable to create log file at '{log_file}'. "
f"Make sure that the folder '{dir_name}' exists "
"and Moonraker has Read/Write access to the folder. "
)
if self.listener is None:
self.listener = logging.handlers.QueueListener(
queue, stdout_hdlr)
self.listener.start()
def set_server(self, server: Server) -> None:
self.server = server
self.server.register_endpoint(
"/server/logs/rollover", ['POST'], self._handle_log_rollover
)
def set_rollover_info(self, name: str, item: str) -> None:
if self.file_hdlr is not None:
self.file_hdlr.set_rollover_info(name, item)
def rollover_log(self) -> Awaitable[None]:
if self.file_hdlr is None:
raise self.server.error("File Logging Disabled")
eventloop = self.server.get_event_loop()
return eventloop.run_in_thread(self.file_hdlr.doRollover)
def stop_logging(self):
self.listener.stop()
async def _handle_log_rollover(
self, web_request: WebRequest
) -> Dict[str, Any]:
log_apps = ["moonraker", "klipper"]
app = web_request.get_str("application", None)
result: Dict[str, Any] = {"rolled_over": [], "failed": {}}
if app is not None:
if app not in log_apps:
raise self.server.error(f"Unknown application {app}")
log_apps = [app]
if "moonraker" in log_apps:
try:
ret = self.rollover_log()
if ret is not None:
await ret
except asyncio.CancelledError:
raise
except Exception as e:
result["failed"]["moonraker"] = str(e)
else:
result["rolled_over"].append("moonraker")
if "klipper" in log_apps:
kconn: KlippyConnection
kconn = self.server.lookup_component("klippy_connection")
try:
await kconn.rollover_log()
except self.server.error as e:
result["failed"]["klipper"] = str(e)
else:
result["rolled_over"].append("klipper")
return result
+11 -689
View File
@@ -1,695 +1,17 @@
#!/usr/bin/env python3
# Moonraker - HTTP/Websocket API Server for Klipper
# Legacy entry point for Moonraker
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
import argparse
import sys
import importlib
import os
import io
import time
import socket
import logging
import json
import signal
import confighelper
import utils
import asyncio
from tornado import iostream, gen
from tornado.ioloop import IOLoop
from tornado.util import TimeoutError
from tornado.locks import Event
from app import MoonrakerApp
from utils import ServerError
INIT_TIME = .25
LOG_ATTEMPT_INTERVAL = int(2. / INIT_TIME + .5)
MAX_LOG_ATTEMPTS = 10 * LOG_ATTEMPT_INTERVAL
CORE_COMPONENTS = [
'database', 'file_manager', 'klippy_apis', 'machine',
'data_store', 'shell_command', 'proc_stats']
class Sentinel:
pass
class Server:
error = ServerError
def __init__(self, args, file_logger):
self.file_logger = file_logger
self.config = config = confighelper.get_configuration(self, args)
# log config file
strio = io.StringIO()
config.write_config(strio)
cfg_item = f"\n{'#'*20} Moonraker Configuration {'#'*20}\n\n"
cfg_item += strio.getvalue()
cfg_item += "#"*65
strio.close()
self.add_log_rollover_item('config', cfg_item)
self.host = config.get('host', "0.0.0.0")
self.port = config.getint('port', 7125)
self.exit_reason = ""
# Event initialization
self.events = {}
# Klippy Connection Handling
self.klippy_address = config.get(
'klippy_uds_address', "/tmp/klippy_uds")
self.klippy_connection = KlippyConnection(
self.process_command, self.on_connection_closed)
self.klippy_info = {}
self.init_list = []
self.init_handle = None
self.init_attempts = 0
self.klippy_state = "disconnected"
self.klippy_disconnect_evt = None
self.subscriptions = {}
self.failed_components = []
# Server/IOLoop
self.server_running = False
self.moonraker_app = app = MoonrakerApp(config)
self.register_endpoint = app.register_local_handler
self.register_static_file_handler = app.register_static_file_handler
self.register_upload_handler = app.register_upload_handler
self.ioloop = IOLoop.current()
self.register_endpoint(
"/server/info", ['GET'], self._handle_info_request)
self.register_endpoint(
"/server/config", ['GET'], self._handle_config_request)
self.register_endpoint(
"/server/restart", ['POST'], self._handle_server_restart)
self.register_notification("server:klippy_ready")
self.register_notification("server:klippy_shutdown")
self.register_notification("server:klippy_disconnect",
"klippy_disconnected")
self.register_notification("server:gcode_response")
# Setup remote methods accessable to Klippy. Note that all
# registered remote methods should be of the notification type,
# they do not return a response to Klippy after execution
self.pending_requests = {}
self.remote_methods = {}
self.klippy_reg_methods = []
self.register_remote_method(
'process_gcode_response', self._process_gcode_response,
need_klippy_reg=False)
self.register_remote_method(
'process_status_update', self._process_status_update,
need_klippy_reg=False)
# Component initialization
self.components = {}
self._load_components(config)
self.klippy_apis = self.lookup_component('klippy_apis')
config.validate_config()
def start(self):
hostname, hostport = self.get_host_info()
logging.info(
f"Starting Moonraker on ({self.host}, {hostport}), "
f"Hostname: {hostname}")
self.moonraker_app.listen(self.host, self.port)
self.server_running = True
self.ioloop.spawn_callback(self._init_signals)
self.ioloop.spawn_callback(self._connect_klippy)
def _init_signals(self):
aioloop = asyncio.get_event_loop()
aioloop.add_signal_handler(
signal.SIGTERM, self._handle_term_signal)
def add_log_rollover_item(self, name, item, log=True):
if self.file_logger is not None:
self.file_logger.set_rollover_info(name, item)
if log and item is not None:
logging.info(item)
# ***** Component Management *****
def _load_components(self, config):
# load core components
for component in CORE_COMPONENTS:
self.load_component(config, component)
# check for optional components
opt_sections = set([s.split()[0] for s in config.sections()]) - \
set(['server', 'authorization', 'system_args'])
for section in opt_sections:
self.load_component(config, section, None)
def load_component(self, config, component_name, default=Sentinel):
if component_name in self.components:
return self.components[component_name]
# Make sure component exists
mod_path = os.path.join(
os.path.dirname(__file__), 'components', component_name + '.py')
if not os.path.exists(mod_path):
msg = f"Component ({component_name}) does not exist"
logging.info(msg)
self.failed_components.append(component_name)
if default == Sentinel:
raise ServerError(msg)
return default
try:
module = importlib.import_module("components." + component_name)
func_name = "load_component"
if hasattr(module, "load_component_multi"):
func_name = "load_component_multi"
if component_name not in CORE_COMPONENTS and \
func_name == "load_component":
config = config[component_name]
load_func = getattr(module, func_name)
component = load_func(config)
except Exception:
msg = f"Unable to load component: ({component_name})"
logging.exception(msg)
self.failed_components.append(component_name)
if default == Sentinel:
raise ServerError(msg)
return default
self.components[component_name] = component
logging.info(f"Component ({component_name}) loaded")
return component
def lookup_component(self, component_name, default=Sentinel):
component = self.components.get(component_name, default)
if component == Sentinel:
raise ServerError(f"Component ({component_name}) not found")
return component
def register_notification(self, event_name, notify_name=None):
wsm = self.moonraker_app.get_websocket_manager()
wsm.register_notification(event_name, notify_name)
def register_event_handler(self, event, callback):
self.events.setdefault(event, []).append(callback)
def send_event(self, event, *args):
events = self.events.get(event, [])
for evt in events:
self.ioloop.spawn_callback(evt, *args)
def register_remote_method(self, method_name, cb, need_klippy_reg=True):
if method_name in self.remote_methods:
# XXX - may want to raise an exception here
logging.info(f"Remote method ({method_name}) already registered")
return
self.remote_methods[method_name] = cb
if need_klippy_reg:
# These methods need to be registered with Klippy
self.klippy_reg_methods.append(method_name)
def get_host_info(self):
hostname = socket.gethostname()
return hostname, self.port
def get_klippy_info(self):
return dict(self.klippy_info)
# ***** Klippy Connection *****
async def _connect_klippy(self):
if not self.server_running:
return
ret = await self.klippy_connection.connect(self.klippy_address)
if not ret:
self.ioloop.call_later(.25, self._connect_klippy)
return
# begin server iniialization
self.ioloop.spawn_callback(self._initialize)
def process_command(self, cmd):
method = cmd.get('method', None)
if method is not None:
# This is a remote method called from klippy
if method in self.remote_methods:
params = cmd.get('params', {})
self.ioloop.spawn_callback(
self._execute_method, method, **params)
else:
logging.info(f"Unknown method received: {method}")
return
# This is a response to a request, process
req_id = cmd.get('id', None)
request = self.pending_requests.pop(req_id, None)
if request is None:
logging.info(
f"No request matching request ID: {req_id}, "
f"response: {cmd}")
return
if 'result' in cmd:
result = cmd['result']
if not result:
result = "ok"
else:
err = cmd.get('error', "Malformed Klippy Response")
result = ServerError(err, 400)
request.notify(result)
async def _execute_method(self, method_name, **kwargs):
try:
ret = self.remote_methods[method_name](**kwargs)
if asyncio.iscoroutine(ret):
await ret
except Exception:
logging.exception(f"Error running remote method: {method_name}")
def on_connection_closed(self):
self.init_list = []
self.klippy_state = "disconnected"
for request in self.pending_requests.values():
request.notify(ServerError("Klippy Disconnected", 503))
self.pending_requests = {}
self.subscriptions = {}
logging.info("Klippy Connection Removed")
self.send_event("server:klippy_disconnect")
if self.init_handle is not None:
self.ioloop.remove_timeout(self.init_handle)
if self.server_running:
self.ioloop.call_later(.25, self._connect_klippy)
if self.klippy_disconnect_evt is not None:
self.klippy_disconnect_evt.set()
async def _initialize(self):
if not self.server_running:
return
await self._check_ready()
await self._request_endpoints()
# Subscribe to "webhooks"
# Register "webhooks" subscription
if "webhooks_sub" not in self.init_list:
try:
await self.klippy_apis.subscribe_objects({'webhooks': None})
except ServerError as e:
logging.info(f"{e}\nUnable to subscribe to webhooks object")
else:
logging.info("Webhooks Subscribed")
self.init_list.append("webhooks_sub")
# Subscribe to Gcode Output
if "gcode_output_sub" not in self.init_list:
try:
await self.klippy_apis.subscribe_gcode_output()
except ServerError as e:
logging.info(
f"{e}\nUnable to register gcode output subscription")
else:
logging.info("GCode Output Subscribed")
self.init_list.append("gcode_output_sub")
if "klippy_ready" in self.init_list or \
not self.klippy_connection.is_connected():
# Either Klippy is ready or the connection dropped
# during initialization. Exit initialization
self.init_attempts = 0
self.init_handle = None
else:
self.init_attempts += 1
self.init_handle = self.ioloop.call_later(
INIT_TIME, self._initialize)
async def _request_endpoints(self):
result = await self.klippy_apis.list_endpoints(default=None)
if result is None:
return
endpoints = result.get('endpoints', {})
for ep in endpoints:
self.moonraker_app.register_remote_handler(ep)
async def _check_ready(self):
send_id = "identified" not in self.init_list
try:
result = await self.klippy_apis.get_klippy_info(send_id)
except ServerError as e:
if self.init_attempts % LOG_ATTEMPT_INTERVAL == 0 and \
self.init_attempts <= MAX_LOG_ATTEMPTS:
logging.info(
f"{e}\nKlippy info request error. This indicates that\n"
f"Klippy may have experienced an error during startup.\n"
f"Please check klippy.log for more information")
return
self.klippy_info = dict(result)
self.klippy_state = result.get('state', "unknown")
if send_id:
self.init_list.append("identified")
self.send_event("server:klippy_identified")
if self.klippy_state == "ready":
await self._verify_klippy_requirements()
logging.info("Klippy ready")
self.init_list.append('klippy_ready')
# register methods with klippy
for method in self.klippy_reg_methods:
try:
await self.klippy_apis.register_method(method)
except ServerError:
logging.exception(f"Unable to register method '{method}'")
self.send_event("server:klippy_ready")
elif self.init_attempts % LOG_ATTEMPT_INTERVAL == 0 and \
self.init_attempts <= MAX_LOG_ATTEMPTS:
msg = result.get('state_message', "Klippy Not Ready")
logging.info("\n" + msg)
async def _verify_klippy_requirements(self):
result = await self.klippy_apis.get_object_list(default=None)
if result is None:
logging.info(
f"Unable to retreive Klipper Object List")
return
req_objs = set(["virtual_sdcard", "display_status", "pause_resume"])
missing_objs = req_objs - set(result)
if missing_objs:
err_str = ", ".join([f"[{o}]" for o in missing_objs])
logging.info(
f"\nWarning, unable to detect the following printer "
f"objects:\n{err_str}\nPlease add the the above sections "
f"to printer.cfg for full Moonraker functionality.")
if "virtual_sdcard" not in missing_objs:
# Update the gcode path
result = await self.klippy_apis.query_objects(
{'configfile': None}, default=None)
if result is None:
logging.info(f"Unable to set SD Card path")
else:
config = result.get('configfile', {}).get('config', {})
vsd_config = config.get('virtual_sdcard', {})
vsd_path = vsd_config.get('path', None)
if vsd_path is not None:
file_manager = self.lookup_component('file_manager')
file_manager.register_directory('gcodes', vsd_path)
else:
logging.info(
"Configuration for [virtual_sdcard] not found,"
" unable to set SD Card path")
def _process_gcode_response(self, response):
self.send_event("server:gcode_response", response)
def _process_status_update(self, eventtime, status):
if 'webhooks' in status:
# XXX - process other states (startup, ready, error, etc)?
state = status['webhooks'].get('state', None)
if state is not None:
if state == "shutdown":
logging.info("Klippy has shutdown")
self.send_event("server:klippy_shutdown")
self.klippy_state = state
for conn, sub in self.subscriptions.items():
conn_status = {}
for name, fields in sub.items():
if name in status:
val = status[name]
if fields is None:
conn_status[name] = dict(val)
else:
conn_status[name] = {
k: v for k, v in val.items() if k in fields}
conn.send_status(conn_status)
async def make_request(self, web_request):
rpc_method = web_request.get_endpoint()
if rpc_method == "objects/subscribe":
return await self._request_subscripton(web_request)
else:
if rpc_method == "gcode/script":
script = web_request.get_str('script', "")
data_store = self.lookup_component('data_store')
data_store.store_gcode_command(script)
return await self._request_standard(web_request)
async def _request_subscripton(self, web_request):
args = web_request.get_args()
conn = web_request.get_connection()
# Build the subscription request from a superset of all client
# subscriptions
sub = args.get('objects', {})
if conn is None:
raise self.error(
"No connection associated with subscription request")
self.subscriptions[conn] = sub
all_subs = {}
# request superset of all client subscriptions
for sub in self.subscriptions.values():
for obj, items in sub.items():
if obj in all_subs:
pi = all_subs[obj]
if items is None or pi is None:
all_subs[obj] = None
else:
uitems = list(set(pi) | set(items))
all_subs[obj] = uitems
else:
all_subs[obj] = items
args['objects'] = all_subs
args['response_template'] = {'method': "process_status_update"}
result = await self._request_standard(web_request)
# prune the status response
pruned_status = {}
all_status = result['status']
sub = self.subscriptions.get(conn, {})
for obj, fields in all_status.items():
if obj in sub:
valid_fields = sub[obj]
if valid_fields is None:
pruned_status[obj] = fields
else:
pruned_status[obj] = {k: v for k, v in fields.items()
if k in valid_fields}
result['status'] = pruned_status
return result
async def _request_standard(self, web_request):
rpc_method = web_request.get_endpoint()
args = web_request.get_args()
# Create a base klippy request
base_request = BaseRequest(rpc_method, args)
self.pending_requests[base_request.id] = base_request
self.ioloop.spawn_callback(
self.klippy_connection.send_request, base_request)
return await base_request.wait()
def remove_subscription(self, conn):
self.subscriptions.pop(conn, None)
def _handle_term_signal(self):
logging.info(f"Exiting with signal SIGTERM")
self.ioloop.spawn_callback(self._stop_server, "terminate")
async def _stop_server(self, exit_reason="restart"):
self.server_running = False
for method in ["on_exit", "close"]:
for name, component in self.components.items():
if not hasattr(component, method):
continue
func = getattr(component, method)
try:
ret = func()
if asyncio.iscoroutine(ret):
await ret
except Exception:
logging.exception(
f"Error executing '{method}()' for component: {name}")
try:
if self.klippy_connection.is_connected():
self.klippy_disconnect_evt = Event()
self.klippy_connection.close()
timeout = time.time() + 2.
await self.klippy_disconnect_evt.wait(timeout)
self.klippy_disconnect_evt = None
except Exception:
logging.exception("Klippy Disconnect Error")
# Sleep for 100ms to allow connected websockets
# to write out remaining data
await gen.sleep(.1)
try:
await self.moonraker_app.close()
except Exception:
logging.exception("Error Closing App")
self.exit_reason = exit_reason
aioloop = asyncio.get_event_loop()
aioloop.remove_signal_handler(signal.SIGTERM)
self.ioloop.stop()
async def _handle_server_restart(self, web_request):
self.ioloop.spawn_callback(self._stop_server)
return "ok"
async def _handle_info_request(self, web_request):
file_manager = self.lookup_component('file_manager', None)
reg_dirs = []
if file_manager is not None:
reg_dirs = file_manager.get_registered_dirs()
return {
'klippy_connected': self.klippy_connection.is_connected(),
'klippy_state': self.klippy_state,
'components': list(self.components.keys()),
'failed_components': self.failed_components,
'plugins': list(self.components.keys()),
'failed_plugins': self.failed_components,
'registered_directories': reg_dirs}
async def _handle_config_request(self, web_request):
return {
'config': self.config.get_parsed_config()
}
class KlippyConnection:
def __init__(self, on_recd, on_close):
self.ioloop = IOLoop.current()
self.iostream = None
self.on_recd = on_recd
self.on_close = on_close
async def connect(self, address):
ksock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
kstream = iostream.IOStream(ksock)
try:
await kstream.connect(address)
except iostream.StreamClosedError:
return False
logging.info("Klippy Connection Established")
self.iostream = kstream
self.iostream.set_close_callback(self.on_close)
self.ioloop.spawn_callback(self._read_stream, self.iostream)
return True
async def _read_stream(self, stream):
while not stream.closed():
try:
data = await stream.read_until(b'\x03')
except iostream.StreamClosedError as e:
return
except Exception:
logging.exception("Klippy Stream Read Error")
continue
try:
decoded_cmd = json.loads(data[:-1])
self.on_recd(decoded_cmd)
except Exception:
logging.exception(
f"Error processing Klippy Host Response: {data.decode()}")
async def send_request(self, request):
if self.iostream is None:
request.notify(ServerError("Klippy Host not connected", 503))
return
data = json.dumps(request.to_dict()).encode() + b"\x03"
try:
await self.iostream.write(data)
except iostream.StreamClosedError:
request.notify(ServerError("Klippy Host not connected", 503))
def is_connected(self):
return self.iostream is not None and not self.iostream.closed()
def close(self):
if self.iostream is not None and \
not self.iostream.closed():
self.iostream.close()
# Basic WebRequest class, easily converted to dict for json encoding
class BaseRequest:
def __init__(self, rpc_method, params):
self.id = id(self)
self.rpc_method = rpc_method
self.params = params
self._event = Event()
self.response = None
async def wait(self):
# Log pending requests every 60 seconds
start_time = time.time()
while True:
timeout = time.time() + 60.
try:
await self._event.wait(timeout=timeout)
except TimeoutError:
pending_time = time.time() - start_time
logging.info(
f"Request '{self.rpc_method}' pending: "
f"{pending_time:.2f} seconds")
self._event.clear()
continue
break
if isinstance(self.response, ServerError):
raise self.response
return self.response
def notify(self, response):
self.response = response
self._event.set()
def to_dict(self):
return {'id': self.id, 'method': self.rpc_method,
'params': self.params}
def main():
# Parse start arguments
parser = argparse.ArgumentParser(
description="Moonraker - Klipper API Server")
parser.add_argument(
"-c", "--configfile", default="~/moonraker.conf",
metavar='<configfile>',
help="Location of moonraker configuration file")
parser.add_argument(
"-l", "--logfile", default="/tmp/moonraker.log", metavar='<logfile>',
help="log file name and location")
parser.add_argument(
"-n", "--nologfile", action='store_true',
help="disable logging to a file")
system_args = parser.parse_args()
# Setup Logging
version = utils.get_software_version()
if system_args.nologfile:
log_file = ""
else:
log_file = os.path.normpath(os.path.expanduser(
system_args.logfile))
system_args.logfile = log_file
system_args.software_version = version
ql, file_logger = utils.setup_logging(log_file, version)
if sys.version_info < (3, 7):
msg = f"Moonraker requires Python 3.7 or above. " \
f"Detected Version: {sys.version}"
logging.info(msg)
print(msg)
ql.stop()
exit(1)
# Start IOLoop and Server
io_loop = IOLoop.current()
estatus = 0
while True:
try:
server = Server(system_args, file_logger)
except Exception:
logging.exception("Moonraker Error")
estatus = 1
break
try:
server.start()
io_loop.start()
except Exception:
logging.exception("Server Running Error")
estatus = 1
break
if server.exit_reason == "terminate":
break
# Since we are running outside of the the server
# it is ok to use a blocking sleep here
time.sleep(.5)
logging.info("Attempting Server Restart...")
io_loop.close(True)
logging.info("Server Shutdown")
ql.stop()
exit(estatus)
if __name__ == '__main__':
main()
if __name__ == "__main__":
import sys
import importlib
import pathlib
pkg_parent = pathlib.Path(__file__).parent.parent
sys.path.pop(0)
sys.path.insert(0, str(pkg_parent))
svr = importlib.import_module(".server", "moonraker")
svr.main(False) # type: ignore
+596
View File
@@ -0,0 +1,596 @@
#!/usr/bin/env python3
# Moonraker - HTTP/Websocket API Server for Klipper
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import pathlib
import sys
import argparse
import importlib
import os
import io
import time
import socket
import logging
import signal
import asyncio
from . import confighelper
from .eventloop import EventLoop
from .app import MoonrakerApp
from .klippy_connection import KlippyConnection
from .utils import ServerError, Sentinel, get_software_version
from .loghelper import LogManager
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Optional,
Callable,
Coroutine,
Dict,
List,
Tuple,
Union,
TypeVar,
)
if TYPE_CHECKING:
from .websockets import WebRequest, WebsocketManager
from .components.file_manager.file_manager import FileManager
from .components.machine import Machine
from .components.extensions import ExtensionManager
FlexCallback = Callable[..., Optional[Coroutine]]
_T = TypeVar("_T", Sentinel, Any)
API_VERSION = (1, 2, 1)
CORE_COMPONENTS = [
'dbus_manager', 'database', 'file_manager', 'klippy_apis',
'machine', 'data_store', 'shell_command', 'proc_stats',
'job_state', 'job_queue', 'http_client', 'announcements',
'webcam', 'extensions',
]
class Server:
error = ServerError
config_error = confighelper.ConfigError
def __init__(self,
args: Dict[str, Any],
log_manager: LogManager,
event_loop: EventLoop
) -> None:
self.event_loop = event_loop
self.log_manager = log_manager
self.app_args = args
self.events: Dict[str, List[FlexCallback]] = {}
self.components: Dict[str, Any] = {}
self.failed_components: List[str] = []
self.warnings: Dict[str, str] = {}
self._is_configured: bool = False
self.config = config = self._parse_config()
self.host: str = config.get('host', "0.0.0.0")
self.port: int = config.getint('port', 7125)
self.ssl_port: int = config.getint('ssl_port', 7130)
self.exit_reason: str = ""
self.server_running: bool = False
# Configure Debug Logging
config.getboolean('enable_debug_logging', False, deprecate=True)
self.debug = args["debug"]
log_level = logging.DEBUG if args["verbose"] else logging.INFO
logging.getLogger().setLevel(log_level)
self.event_loop.set_debug(args["asyncio_debug"])
self.klippy_connection = KlippyConnection(self)
# Tornado Application/Server
self.moonraker_app = app = MoonrakerApp(config)
self.register_endpoint = app.register_local_handler
self.register_debug_endpoint = app.register_debug_handler
self.register_static_file_handler = app.register_static_file_handler
self.register_upload_handler = app.register_upload_handler
self.register_api_transport = app.register_api_transport
self.log_manager.set_server(self)
for warning in args.get("startup_warnings", []):
self.add_warning(warning)
self.register_endpoint(
"/server/info", ['GET'], self._handle_info_request)
self.register_endpoint(
"/server/config", ['GET'], self._handle_config_request)
self.register_endpoint(
"/server/restart", ['POST'], self._handle_server_restart)
self.register_notification("server:klippy_ready")
self.register_notification("server:klippy_shutdown")
self.register_notification("server:klippy_disconnect",
"klippy_disconnected")
self.register_notification("server:gcode_response")
def get_app_args(self) -> Dict[str, Any]:
return dict(self.app_args)
def get_event_loop(self) -> EventLoop:
return self.event_loop
def get_api_version(self) -> Tuple[int, int, int]:
return API_VERSION
def get_warnings(self) -> List[str]:
return list(self.warnings.values())
def is_running(self) -> bool:
return self.server_running
def is_configured(self) -> bool:
return self._is_configured
def is_debug_enabled(self) -> bool:
return self.debug
def is_verbose_enabled(self) -> bool:
return self.app_args["verbose"]
def _parse_config(self) -> confighelper.ConfigHelper:
config = confighelper.get_configuration(self, self.app_args)
# log config file
cfg_files = "\n".join(config.get_config_files())
strio = io.StringIO()
config.write_config(strio)
cfg_item = f"\n{'#'*20} Moonraker Configuration {'#'*20}\n\n"
cfg_item += strio.getvalue()
cfg_item += "#"*65
cfg_item += f"\nAll Configuration Files:\n{cfg_files}\n"
cfg_item += "#"*65
strio.close()
self.add_log_rollover_item('config', cfg_item)
return config
async def server_init(self, start_server: bool = True) -> None:
self.event_loop.add_signal_handler(
signal.SIGTERM, self._handle_term_signal)
# Perform asynchronous init after the event loop starts
optional_comps: List[Coroutine] = []
for name, component in self.components.items():
if not hasattr(component, "component_init"):
continue
if name in CORE_COMPONENTS:
# Process core components in order synchronously
await self._initialize_component(name, component)
else:
optional_comps.append(
self._initialize_component(name, component))
# Asynchronous Optional Component Initialization
if optional_comps:
await asyncio.gather(*optional_comps)
if not self.warnings:
await self.event_loop.run_in_thread(self.config.create_backup)
machine: Machine = self.lookup_component("machine")
if await machine.validate_installation():
return
if start_server:
await self.start_server()
async def start_server(self, connect_to_klippy: bool = True) -> None:
# Open Unix Socket Server
extm: ExtensionManager = self.lookup_component("extensions")
await extm.start_unix_server()
# Start HTTP Server
logging.info(
f"Starting Moonraker on ({self.host}, {self.port}), "
f"Hostname: {socket.gethostname()}")
self.moonraker_app.listen(self.host, self.port, self.ssl_port)
self.server_running = True
if connect_to_klippy:
self.klippy_connection.connect()
def add_log_rollover_item(self, name: str, item: str,
log: bool = True) -> None:
self.log_manager.set_rollover_info(name, item)
if log and item is not None:
logging.info(item)
def add_warning(
self, warning: str, warn_id: Optional[str] = None, log: bool = True
) -> str:
if warn_id is None:
warn_id = str(id(warning))
self.warnings[warn_id] = warning
if log:
logging.warning(warning)
return warn_id
def remove_warning(self, warn_id: str) -> None:
self.warnings.pop(warn_id, None)
# ***** Component Management *****
async def _initialize_component(self, name: str, component: Any) -> None:
logging.info(f"Performing Component Post Init: [{name}]")
try:
ret = component.component_init()
if ret is not None:
await ret
except Exception as e:
logging.exception(f"Component [{name}] failed post init")
self.add_warning(f"Component '{name}' failed to load with "
f"error: {e}")
self.set_failed_component(name)
def load_components(self) -> None:
config = self.config
cfg_sections = set([s.split()[0] for s in config.sections()])
cfg_sections.remove('server')
# load core components
for component in CORE_COMPONENTS:
self.load_component(config, component)
if component in cfg_sections:
cfg_sections.remove(component)
# load remaining optional components
for section in cfg_sections:
self.load_component(config, section, None)
self.klippy_connection.configure(config)
config.validate_config()
self._is_configured = True
def load_component(
self,
config: confighelper.ConfigHelper,
component_name: str,
default: _T = Sentinel.MISSING
) -> Union[_T, Any]:
if component_name in self.components:
return self.components[component_name]
if self.is_configured():
raise self.error(
"Cannot load components after configuration", 500
)
if component_name in self.failed_components:
raise self.error(
f"Component {component_name} previously failed to load", 500
)
try:
full_name = f"moonraker.components.{component_name}"
module = importlib.import_module(full_name)
is_core = component_name in CORE_COMPONENTS
fallback: Optional[str] = "server" if is_core else None
config = config.getsection(component_name, fallback)
load_func = getattr(module, "load_component")
component = load_func(config)
except Exception:
msg = f"Unable to load component: ({component_name})"
logging.exception(msg)
if component_name not in self.failed_components:
self.failed_components.append(component_name)
if default is Sentinel.MISSING:
raise
return default
self.components[component_name] = component
logging.info(f"Component ({component_name}) loaded")
return component
def lookup_component(
self, component_name: str, default: _T = Sentinel.MISSING
) -> Union[_T, Any]:
component = self.components.get(component_name, default)
if component is Sentinel.MISSING:
raise ServerError(f"Component ({component_name}) not found")
return component
def set_failed_component(self, component_name: str) -> None:
if component_name not in self.failed_components:
self.failed_components.append(component_name)
def register_component(self, component_name: str, component: Any) -> None:
if component_name in self.components:
raise self.error(
f"Component '{component_name}' already registered")
self.components[component_name] = component
def register_notification(self,
event_name: str,
notify_name: Optional[str] = None
) -> None:
wsm: WebsocketManager = self.lookup_component("websockets")
wsm.register_notification(event_name, notify_name)
def register_event_handler(self,
event: str,
callback: FlexCallback
) -> None:
self.events.setdefault(event, []).append(callback)
def send_event(self, event: str, *args) -> asyncio.Future:
fut = self.event_loop.create_future()
self.event_loop.register_callback(
self._process_event, fut, event, *args)
return fut
async def _process_event(self,
fut: asyncio.Future,
event: str,
*args
) -> None:
events = self.events.get(event, [])
coroutines: List[Coroutine] = []
try:
for func in events:
ret = func(*args)
if ret is not None:
coroutines.append(ret)
if coroutines:
await asyncio.gather(*coroutines)
except ServerError as e:
logging.exception(f"Error Processing Event: {fut}")
if not fut.done():
fut.set_result(None)
def register_remote_method(self,
method_name: str,
cb: FlexCallback
) -> None:
self.klippy_connection.register_remote_method(method_name, cb)
def get_host_info(self) -> Dict[str, Any]:
return {
'hostname': socket.gethostname(),
'address': self.host,
'port': self.port,
'ssl_port': self.ssl_port
}
def get_klippy_info(self) -> Dict[str, Any]:
return self.klippy_connection.klippy_info
def get_klippy_state(self) -> str:
return self.klippy_connection.state
def _handle_term_signal(self) -> None:
logging.info(f"Exiting with signal SIGTERM")
self.event_loop.register_callback(self._stop_server, "terminate")
async def _stop_server(self, exit_reason: str = "restart") -> None:
self.server_running = False
# Call each component's "on_exit" method
for name, component in self.components.items():
if hasattr(component, "on_exit"):
func: FlexCallback = getattr(component, "on_exit")
try:
ret = func()
if ret is not None:
await ret
except Exception:
logging.exception(
f"Error executing 'on_exit()' for component: {name}")
# Sleep for 100ms to allow connected websockets to write out
# remaining data
await asyncio.sleep(.1)
try:
await self.moonraker_app.close()
except Exception:
logging.exception("Error Closing App")
# Disconnect from Klippy
try:
await asyncio.wait_for(
asyncio.shield(self.klippy_connection.close(
wait_closed=True)), 2.)
except Exception:
logging.exception("Klippy Disconnect Error")
# Close all components
for name, component in self.components.items():
if name in ["application", "websockets", "klippy_connection"]:
# These components have already been closed
continue
if hasattr(component, "close"):
func = getattr(component, "close")
try:
ret = func()
if ret is not None:
await ret
except Exception:
logging.exception(
f"Error executing 'close()' for component: {name}")
# Allow cancelled tasks a chance to run in the eventloop
await asyncio.sleep(.001)
self.exit_reason = exit_reason
self.event_loop.remove_signal_handler(signal.SIGTERM)
self.event_loop.stop()
async def _handle_server_restart(self, web_request: WebRequest) -> str:
self.event_loop.register_callback(self._stop_server)
return "ok"
async def _handle_info_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
raw = web_request.get_boolean("raw", False)
file_manager: Optional[FileManager] = self.lookup_component(
'file_manager', None)
reg_dirs = []
if file_manager is not None:
reg_dirs = file_manager.get_registered_dirs()
wsm: WebsocketManager = self.lookup_component('websockets')
mreqs = self.klippy_connection.missing_requirements
if raw:
warnings = list(self.warnings.values())
else:
warnings = [
w.replace("\n", "<br/>") for w in self.warnings.values()
]
return {
'klippy_connected': self.klippy_connection.is_connected(),
'klippy_state': self.klippy_connection.state,
'components': list(self.components.keys()),
'failed_components': self.failed_components,
'registered_directories': reg_dirs,
'warnings': warnings,
'websocket_count': wsm.get_count(),
'moonraker_version': self.app_args['software_version'],
'missing_klippy_requirements': mreqs,
'api_version': API_VERSION,
'api_version_string': ".".join([str(v) for v in API_VERSION])
}
async def _handle_config_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
cfg_file_list: List[Dict[str, Any]] = []
cfg_parent = pathlib.Path(
self.app_args["config_file"]
).expanduser().resolve().parent
for fname, sections in self.config.get_file_sections().items():
path = pathlib.Path(fname)
try:
rel_path = str(path.relative_to(str(cfg_parent)))
except ValueError:
rel_path = fname
cfg_file_list.append({"filename": rel_path, "sections": sections})
return {
'config': self.config.get_parsed_config(),
'orig': self.config.get_orig_config(),
'files': cfg_file_list
}
def main(from_package: bool = True) -> None:
# Parse start arguments
parser = argparse.ArgumentParser(
description="Moonraker - Klipper API Server")
parser.add_argument(
"-d", "--datapath", default=None,
metavar='<data path>',
help="Location of Moonraker Data File Path"
)
parser.add_argument(
"-c", "--configfile", default=None, metavar='<configfile>',
help="Location of moonraker configuration file")
parser.add_argument(
"-l", "--logfile", default=None, metavar='<logfile>',
help="log file name and location")
parser.add_argument(
"-n", "--nologfile", action='store_true',
help="disable logging to a file")
parser.add_argument(
"-v", "--verbose", action="store_true",
help="Enable verbose logging"
)
parser.add_argument(
"-g", "--debug", action="store_true",
help="Enable Moonraker debug features"
)
parser.add_argument(
"-o", "--asyncio-debug", action="store_true",
help="Enable asyncio debug flag"
)
cmd_line_args = parser.parse_args()
startup_warnings: List[str] = []
dp: str = cmd_line_args.datapath or "~/printer_data"
data_path = pathlib.Path(dp).expanduser().resolve()
if not data_path.exists():
try:
data_path.mkdir()
except Exception:
startup_warnings.append(
f"Unable to create data path folder at {data_path}"
)
if cmd_line_args.configfile is not None:
cfg_file: str = cmd_line_args.configfile
else:
cfg_file = str(data_path.joinpath("config/moonraker.conf"))
app_args = {
"data_path": str(data_path),
"is_default_data_path": cmd_line_args.datapath is None,
"config_file": cfg_file,
"startup_warnings": startup_warnings,
"verbose": cmd_line_args.verbose,
"debug": cmd_line_args.debug,
"asyncio_debug": cmd_line_args.asyncio_debug,
"is_backup_config": False,
"is_python_package": from_package
}
# Setup Logging
version = get_software_version()
if cmd_line_args.nologfile:
app_args["log_file"] = ""
elif cmd_line_args.logfile:
app_args["log_file"] = os.path.normpath(
os.path.expanduser(cmd_line_args.logfile))
else:
app_args["log_file"] = str(data_path.joinpath("logs/moonraker.log"))
app_args["software_version"] = version
app_args["python_version"] = sys.version.replace("\n", " ")
log_manager = LogManager(app_args, startup_warnings)
# Start asyncio event loop and server
event_loop = EventLoop()
alt_config_loaded = False
estatus = 0
while True:
try:
server = Server(app_args, log_manager, event_loop)
server.load_components()
except confighelper.ConfigError as e:
backup_cfg = confighelper.find_config_backup(cfg_file)
logging.exception("Server Config Error")
if alt_config_loaded or backup_cfg is None:
estatus = 1
break
app_args["config_file"] = backup_cfg
app_args["is_backup_config"] = True
warn_list = list(startup_warnings)
app_args["startup_warnings"] = warn_list
warn_list.append(
f"Server configuration error: {e}\n"
f"Loaded server from most recent working configuration:"
f" '{app_args['config_file']}'\n"
f"Please fix the issue in moonraker.conf and restart "
f"the server."
)
alt_config_loaded = True
continue
except Exception:
logging.exception("Moonraker Error")
estatus = 1
break
try:
event_loop.register_callback(server.server_init)
event_loop.start()
except Exception:
logging.exception("Server Running Error")
estatus = 1
break
if server.exit_reason == "terminate":
break
# Restore the original config and clear the warning
# before the server restarts
if alt_config_loaded:
app_args["config_file"] = cfg_file
app_args["startup_warnings"] = startup_warnings
app_args["is_backup_config"] = False
alt_config_loaded = False
event_loop.close()
# Since we are running outside of the the server
# it is ok to use a blocking sleep here
time.sleep(.5)
logging.info("Attempting Server Restart...")
event_loop.reset()
event_loop.close()
logging.info("Server Shutdown")
log_manager.stop_logging()
exit(estatus)
+1
View File
@@ -0,0 +1 @@
# package definition for thirdparty package
+1
View File
@@ -0,0 +1 @@
# package definition for packagekit thirdparty files
+768
View File
@@ -0,0 +1,768 @@
# This file was autogenerated from pk-enum.h by pk-enum-converter.py
# on Fri Jan 21 16:01:47 2022 UTC
#
# License for original source:
#
# Copyright (C) 2007-2014 Richard Hughes <richard@hughsie.com>
#
# Licensed under the GNU Lesser General Public License Version 2.1
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
#
from __future__ import annotations
import sys
from enum import Flag, auto
class PkFlag(Flag):
@classmethod
def from_pkstring(cls, pkstring: str):
for name, member in cls.__members__.items():
if member.pkstring == pkstring:
return cls(member.value)
# Return "unknown" flag
return cls(1)
@classmethod
def from_index(cls, index: int):
return cls(1 << index)
@property
def pkstring(self) -> str:
if self.name is None:
return " | ".join([f.pkstring for f in self])
return self.name.lower().replace("_", "-")
@property
def desc(self) -> str:
if self.name is None:
return ", ".join([f.desc for f in self])
description = self.name.lower().replace("_", " ")
return description.capitalize()
@property
def index(self) -> int:
return self.value.bit_length() - 1
if sys.version_info < (3, 11):
def __iter__(self):
for i in range(self._value_.bit_length()):
val = 1 << i
if val & self._value_ == val:
yield self.__class__(val)
class Role(PkFlag):
"""
What we were asked to do, this never changes for the lifetime of the
transaction.
Icons that have to represent the whole "aim" of the transaction will use
these constants
* Role.UNKNOWN: Unknow request
* Role.CANCEL: Cancel transaction
* Role.DEPENDS_ON: Get package dependencies
* Role.GET_DETAILS: Get package details
* Role.GET_FILES:
* Role.GET_PACKAGES: Get available packages
* Role.GET_REPO_LIST: Get repository list
* Role.REQUIRED_BY: Get packages required by given package
* Role.GET_UPDATE_DETAIL: Get update details
* Role.GET_UPDATES: Get available updates
* Role.INSTALL_FILES: Install package files
* Role.INSTALL_PACKAGES: Install packages
* Role.INSTALL_SIGNATURE: Install signature
* Role.REFRESH_CACHE: Refresh cache
* Role.REMOVE_PACKAGES: Remove packages
* Role.REPO_ENABLE: Enable repository
* Role.REPO_SET_DATA:
* Role.RESOLVE: Resolve depdencies
* Role.SEARCH_DETAILS: Search for details
* Role.SEARCH_FILE: Search for file
* Role.SEARCH_GROUP: Search for group
* Role.SEARCH_NAME: Search for package name
* Role.UPDATE_PACKAGES: Update packages
* Role.WHAT_PROVIDES: Get what a package provides
* Role.ACCEPT_EULA: Accept an EULA
* Role.DOWNLOAD_PACKAGES: Download packages
* Role.GET_DISTRO_UPGRADES: Get available distribution upgrades
* Role.GET_CATEGORIES: Get available categories
* Role.GET_OLD_TRANSACTIONS: Get old transation information
* Role.REPAIR_SYSTEM: Repair system
* Role.GET_DETAILS_LOCAL: Get details on local package
* Role.GET_FILES_LOCAL: Get files provided by local package
* Role.REPO_REMOVE: Remove repository
* Role.UPGRADE_SYSTEM: Upgrade system
"""
UNKNOWN = auto()
CANCEL = auto()
DEPENDS_ON = auto()
GET_DETAILS = auto()
GET_FILES = auto()
GET_PACKAGES = auto()
GET_REPO_LIST = auto()
REQUIRED_BY = auto()
GET_UPDATE_DETAIL = auto()
GET_UPDATES = auto()
INSTALL_FILES = auto()
INSTALL_PACKAGES = auto()
INSTALL_SIGNATURE = auto()
REFRESH_CACHE = auto()
REMOVE_PACKAGES = auto()
REPO_ENABLE = auto()
REPO_SET_DATA = auto()
RESOLVE = auto()
SEARCH_DETAILS = auto()
SEARCH_FILE = auto()
SEARCH_GROUP = auto()
SEARCH_NAME = auto()
UPDATE_PACKAGES = auto()
WHAT_PROVIDES = auto()
ACCEPT_EULA = auto()
DOWNLOAD_PACKAGES = auto()
GET_DISTRO_UPGRADES = auto()
GET_CATEGORIES = auto()
GET_OLD_TRANSACTIONS = auto()
REPAIR_SYSTEM = auto()
GET_DETAILS_LOCAL = auto()
GET_FILES_LOCAL = auto()
REPO_REMOVE = auto()
UPGRADE_SYSTEM = auto()
class Status(PkFlag):
"""
What status we are now; this can change for each transaction giving a
status of what sort of thing is happening
Icons that change to represent the current status of the transaction will
use these constants
If you add to these, make sure you add filenames in gpk-watch.c also
A typical transaction will do:
- schedule task
WAIT
- run task
SETUP
- wait for lock
RUNNING
This means that backends should run pk_backend_set_status (backend,
PK_STATUS_ENUM_RUNNING)
when they are ready to start running the transaction and after a lock has
been got.
* Status.UNKNOWN: Unknown status
* Status.WAIT: Waiting
* Status.SETUP: Setting up
* Status.RUNNING: Running
* Status.QUERY:
* Status.INFO:
* Status.REMOVE: Removing
* Status.REFRESH_CACHE: Refreshing cache
* Status.DOWNLOAD: Downloading
* Status.INSTALL: Installing
* Status.UPDATE: Updating
* Status.CLEANUP: Cleaning up
* Status.OBSOLETE:
* Status.DEP_RESOLVE: Resolving dependencies
* Status.SIG_CHECK: Checking signatures
* Status.TEST_COMMIT: Testing commit
* Status.COMMIT: Committing
* Status.REQUEST:
* Status.FINISHED: Finished
* Status.CANCEL: Cancelling
* Status.DOWNLOAD_REPOSITORY: Downloading respository
* Status.DOWNLOAD_PACKAGELIST: Donwloading package list
* Status.DOWNLOAD_FILELIST: Downloading file list
* Status.DOWNLOAD_CHANGELOG: Downloading changelog information
* Status.DOWNLOAD_GROUP: Downloading group information
* Status.DOWNLOAD_UPDATEINFO: Downloading update information
* Status.REPACKAGING: Repackaging
* Status.LOADING_CACHE: Loading cache
* Status.SCAN_APPLICATIONS: Scanning for applications
* Status.GENERATE_PACKAGE_LIST: Generating package list
* Status.WAITING_FOR_LOCK: Waiting for lock
* Status.WAITING_FOR_AUTH: Waiting for authentication/authorization
* Status.SCAN_PROCESS_LIST: Scanning running processes
* Status.CHECK_EXECUTABLE_FILES: Checking executable files
* Status.CHECK_LIBRARIES: Checking libraries
* Status.COPY_FILES: Copying files
* Status.RUN_HOOK: Running package hook
"""
UNKNOWN = auto()
WAIT = auto()
SETUP = auto()
RUNNING = auto()
QUERY = auto()
INFO = auto()
REMOVE = auto()
REFRESH_CACHE = auto()
DOWNLOAD = auto()
INSTALL = auto()
UPDATE = auto()
CLEANUP = auto()
OBSOLETE = auto()
DEP_RESOLVE = auto()
SIG_CHECK = auto()
TEST_COMMIT = auto()
COMMIT = auto()
REQUEST = auto()
FINISHED = auto()
CANCEL = auto()
DOWNLOAD_REPOSITORY = auto()
DOWNLOAD_PACKAGELIST = auto()
DOWNLOAD_FILELIST = auto()
DOWNLOAD_CHANGELOG = auto()
DOWNLOAD_GROUP = auto()
DOWNLOAD_UPDATEINFO = auto()
REPACKAGING = auto()
LOADING_CACHE = auto()
SCAN_APPLICATIONS = auto()
GENERATE_PACKAGE_LIST = auto()
WAITING_FOR_LOCK = auto()
WAITING_FOR_AUTH = auto()
SCAN_PROCESS_LIST = auto()
CHECK_EXECUTABLE_FILES = auto()
CHECK_LIBRARIES = auto()
COPY_FILES = auto()
RUN_HOOK = auto()
class Exit(PkFlag):
"""
How the backend exited
* Exit.UNKNOWN: Unknown exit status
* Exit.SUCCESS: Backend exited successfully
* Exit.FAILED: Backend failed
* Exit.CANCELLED: Backend was cancelled
* Exit.KEY_REQUIRED: A repository encryption key needs installing
* Exit.EULA_REQUIRED: A EULA is required to be accepted
* Exit.KILLED: Backend was killed
* Exit.MEDIA_CHANGE_REQUIRED: Media change required
* Exit.NEED_UNTRUSTED:
* Exit.CANCELLED_PRIORITY: Cancelled due to higher priority task
* Exit.SKIP_TRANSACTION:
* Exit.REPAIR_REQUIRED: Package database requires repairing
"""
UNKNOWN = auto()
SUCCESS = auto()
FAILED = auto()
CANCELLED = auto()
KEY_REQUIRED = auto()
EULA_REQUIRED = auto()
KILLED = auto()
MEDIA_CHANGE_REQUIRED = auto()
NEED_UNTRUSTED = auto()
CANCELLED_PRIORITY = auto()
SKIP_TRANSACTION = auto()
REPAIR_REQUIRED = auto()
class Network(PkFlag):
"""
Network type
* Network.UNKNOWN: Unknown network
* Network.OFFLINE: Offline (no network)
* Network.ONLINE: Online (network type unknown)
* Network.WIRED: Wired network
* Network.WIFI: WiFi network
* Network.MOBILE: Mobile network
"""
UNKNOWN = auto()
OFFLINE = auto()
ONLINE = auto()
WIRED = auto()
WIFI = auto()
MOBILE = auto()
class Filter(PkFlag):
"""
The filter types
* Filter.UNKNOWN: Unknown filter
* Filter.NONE: No filter
* Filter.INSTALLED: Filter for installed packages
* Filter.NOT_INSTALLED: Filter for not installed packages
* Filter.DEVELOPMENT: Filter for development packages
* Filter.NOT_DEVELOPMENT: Filter for non-development packages
* Filter.GUI: Filter for GUI packages
* Filter.NOT_GUI: Filter for non-GUI packages
* Filter.FREE: Filter for free packages
* Filter.NOT_FREE: Filter for non-free packages
* Filter.VISIBLE: Filter for visible packages
* Filter.NOT_VISIBLE: Filter for invisible packages
* Filter.SUPPORTED: Filter for supported packages
* Filter.NOT_SUPPORTED: Filter for not supported packages
* Filter.BASENAME: Filter for packages that match basename
* Filter.NOT_BASENAME: Filter for packages that don't match basename
* Filter.NEWEST: Filter for newest packages
* Filter.NOT_NEWEST: Filter for not newest packages
* Filter.ARCH: Filter for packages that match architecture
* Filter.NOT_ARCH: Filter for packages that don't match architecture
* Filter.SOURCE: Filter for source packages
* Filter.NOT_SOURCE: Filter for non-source packages
* Filter.COLLECTIONS: Filter for collections
* Filter.NOT_COLLECTIONS: Filter for not collections
* Filter.APPLICATION: Filter for application packages
* Filter.NOT_APPLICATION: Filter for non-application packages
* Filter.DOWNLOADED: Filter for downloaded packages
* Filter.NOT_DOWNLOADED: Filter for not downloaded packages
"""
@property
def pkstring(self) -> str:
pks = self.name
if pks is None:
return " | ".join([f.pkstring for f in self])
if pks in ["DEVELOPMENT", "NOT_DEVELOPMENT"]:
pks = pks[:-6]
if pks[:4] == "NOT_":
pks = "~" + pks[4:]
return pks.lower().replace("_", "-")
UNKNOWN = auto()
NONE = auto()
INSTALLED = auto()
NOT_INSTALLED = auto()
DEVELOPMENT = auto()
NOT_DEVELOPMENT = auto()
GUI = auto()
NOT_GUI = auto()
FREE = auto()
NOT_FREE = auto()
VISIBLE = auto()
NOT_VISIBLE = auto()
SUPPORTED = auto()
NOT_SUPPORTED = auto()
BASENAME = auto()
NOT_BASENAME = auto()
NEWEST = auto()
NOT_NEWEST = auto()
ARCH = auto()
NOT_ARCH = auto()
SOURCE = auto()
NOT_SOURCE = auto()
COLLECTIONS = auto()
NOT_COLLECTIONS = auto()
APPLICATION = auto()
NOT_APPLICATION = auto()
DOWNLOADED = auto()
NOT_DOWNLOADED = auto()
class Restart(PkFlag):
"""
What restart we need to after a transaction, ordered by severity
* Restart.UNKNOWN: Unknown restart state
* Restart.NONE: No restart required
* Restart.APPLICATION: Need to restart the application
* Restart.SESSION: Need to restart the session
* Restart.SYSTEM: Need to restart the system
* Restart.SECURITY_SESSION:
* Restart.SECURITY_SYSTEM:
"""
UNKNOWN = auto()
NONE = auto()
APPLICATION = auto()
SESSION = auto()
SYSTEM = auto()
SECURITY_SESSION = auto()
SECURITY_SYSTEM = auto()
class Error(PkFlag):
"""
The error type
* Error.UNKNOWN:
* Error.OOM: Out of memory
* Error.NO_NETWORK: No network access available
* Error.NOT_SUPPORTED: Request not supported
* Error.INTERNAL_ERROR: Undefined internal error
* Error.GPG_FAILURE: GPG encryption failure
* Error.PACKAGE_ID_INVALID: Invalid package ID provided
* Error.PACKAGE_NOT_INSTALLED: Requested package not installed
* Error.PACKAGE_NOT_FOUND: Requested package not found
* Error.PACKAGE_ALREADY_INSTALLED: Requested package already installed
* Error.PACKAGE_DOWNLOAD_FAILED: Failed to download package
* Error.GROUP_NOT_FOUND: Requested group not gound
* Error.GROUP_LIST_INVALID: Invalid group list provided
* Error.DEP_RESOLUTION_FAILED: Failed to resolve dependencies
* Error.FILTER_INVALID: Invalid filter provides
* Error.CREATE_THREAD_FAILED: Failed to create thread
* Error.TRANSACTION_ERROR: Error occurred during transaction
* Error.TRANSACTION_CANCELLED: Transaction was cancelled
* Error.NO_CACHE: No cache available
* Error.REPO_NOT_FOUND: Requested repository not found
* Error.CANNOT_REMOVE_SYSTEM_PACKAGE: Not allowed to remove system package
* Error.PROCESS_KILL: Process killed
* Error.FAILED_INITIALIZATION:
* Error.FAILED_FINALISE:
* Error.FAILED_CONFIG_PARSING: Configuration is not valid
* Error.CANNOT_CANCEL:
* Error.CANNOT_GET_LOCK: Cannot get lock
* Error.NO_PACKAGES_TO_UPDATE: No packages to update
* Error.CANNOT_WRITE_REPO_CONFIG: Cannot write repository configuration
* Error.LOCAL_INSTALL_FAILED:
* Error.BAD_GPG_SIGNATURE: Bad GPG signature found
* Error.MISSING_GPG_SIGNATURE: Required GPG signature not found
* Error.CANNOT_INSTALL_SOURCE_PACKAGE: Cannot install source package
* Error.REPO_CONFIGURATION_ERROR:
* Error.NO_LICENSE_AGREEMENT:
* Error.FILE_CONFLICTS: File conflicts detected
* Error.PACKAGE_CONFLICTS: Package conflict
* Error.REPO_NOT_AVAILABLE: Repository not available
* Error.INVALID_PACKAGE_FILE:
* Error.PACKAGE_INSTALL_BLOCKED: Package installation blocked
* Error.PACKAGE_CORRUPT: Package corruption occurred
* Error.ALL_PACKAGES_ALREADY_INSTALLED: All packages already installed
* Error.FILE_NOT_FOUND: Required file not found
* Error.NO_MORE_MIRRORS_TO_TRY: Out of repository mirrors to try
* Error.NO_DISTRO_UPGRADE_DATA: No distribution upgrade path found
* Error.INCOMPATIBLE_ARCHITECTURE: Incompatible architecture found
* Error.NO_SPACE_ON_DEVICE: Out of required disk space
* Error.MEDIA_CHANGE_REQUIRED: Need to change media
* Error.NOT_AUTHORIZED: Authorization failed
* Error.UPDATE_NOT_FOUND: Update not found
* Error.CANNOT_INSTALL_REPO_UNSIGNED:
Installation repository missing signature
* Error.CANNOT_UPDATE_REPO_UNSIGNED: Update repository missing signature
* Error.CANNOT_GET_FILELIST: Cannot get file list
* Error.CANNOT_GET_REQUIRES: Cannot get package requirements
* Error.CANNOT_DISABLE_REPOSITORY: Cannot disable reposoitory
* Error.RESTRICTED_DOWNLOAD:
* Error.PACKAGE_FAILED_TO_CONFIGURE: Package failed to configure
* Error.PACKAGE_FAILED_TO_BUILD: Package failed to build
* Error.PACKAGE_FAILED_TO_INSTALL: Package failed to install
* Error.PACKAGE_FAILED_TO_REMOVE: Package failed to remove
* Error.UPDATE_FAILED_DUE_TO_RUNNING_PROCESS:
* Error.PACKAGE_DATABASE_CHANGED:
* Error.PROVIDE_TYPE_NOT_SUPPORTED:
* Error.INSTALL_ROOT_INVALID: Installtion root not suitable
* Error.CANNOT_FETCH_SOURCES: Cannot fetch sources
* Error.CANCELLED_PRIORITY: Cancelled due to higher priority task
* Error.UNFINISHED_TRANSACTION: Transaction unfinished
* Error.LOCK_REQUIRED: Required lock not available
* Error.REPO_ALREADY_SET:
"""
@property
def pkstring(self) -> str:
if self == Error.UPDATE_FAILED_DUE_TO_RUNNING_PROCESS:
return "failed-due-to-running-process"
return super().pkstring
UNKNOWN = auto()
OUT_OF_MEMORY = auto()
NO_NETWORK = auto()
NOT_SUPPORTED = auto()
INTERNAL_ERROR = auto()
GPG_FAILURE = auto()
PACKAGE_ID_INVALID = auto()
PACKAGE_NOT_INSTALLED = auto()
PACKAGE_NOT_FOUND = auto()
PACKAGE_ALREADY_INSTALLED = auto()
PACKAGE_DOWNLOAD_FAILED = auto()
GROUP_NOT_FOUND = auto()
GROUP_LIST_INVALID = auto()
DEP_RESOLUTION_FAILED = auto()
FILTER_INVALID = auto()
CREATE_THREAD_FAILED = auto()
TRANSACTION_ERROR = auto()
TRANSACTION_CANCELLED = auto()
NO_CACHE = auto()
REPO_NOT_FOUND = auto()
CANNOT_REMOVE_SYSTEM_PACKAGE = auto()
PROCESS_KILL = auto()
FAILED_INITIALIZATION = auto()
FAILED_FINALISE = auto()
FAILED_CONFIG_PARSING = auto()
CANNOT_CANCEL = auto()
CANNOT_GET_LOCK = auto()
NO_PACKAGES_TO_UPDATE = auto()
CANNOT_WRITE_REPO_CONFIG = auto()
LOCAL_INSTALL_FAILED = auto()
BAD_GPG_SIGNATURE = auto()
MISSING_GPG_SIGNATURE = auto()
CANNOT_INSTALL_SOURCE_PACKAGE = auto()
REPO_CONFIGURATION_ERROR = auto()
NO_LICENSE_AGREEMENT = auto()
FILE_CONFLICTS = auto()
PACKAGE_CONFLICTS = auto()
REPO_NOT_AVAILABLE = auto()
INVALID_PACKAGE_FILE = auto()
PACKAGE_INSTALL_BLOCKED = auto()
PACKAGE_CORRUPT = auto()
ALL_PACKAGES_ALREADY_INSTALLED = auto()
FILE_NOT_FOUND = auto()
NO_MORE_MIRRORS_TO_TRY = auto()
NO_DISTRO_UPGRADE_DATA = auto()
INCOMPATIBLE_ARCHITECTURE = auto()
NO_SPACE_ON_DEVICE = auto()
MEDIA_CHANGE_REQUIRED = auto()
NOT_AUTHORIZED = auto()
UPDATE_NOT_FOUND = auto()
CANNOT_INSTALL_REPO_UNSIGNED = auto()
CANNOT_UPDATE_REPO_UNSIGNED = auto()
CANNOT_GET_FILELIST = auto()
CANNOT_GET_REQUIRES = auto()
CANNOT_DISABLE_REPOSITORY = auto()
RESTRICTED_DOWNLOAD = auto()
PACKAGE_FAILED_TO_CONFIGURE = auto()
PACKAGE_FAILED_TO_BUILD = auto()
PACKAGE_FAILED_TO_INSTALL = auto()
PACKAGE_FAILED_TO_REMOVE = auto()
UPDATE_FAILED_DUE_TO_RUNNING_PROCESS = auto()
PACKAGE_DATABASE_CHANGED = auto()
PROVIDE_TYPE_NOT_SUPPORTED = auto()
INSTALL_ROOT_INVALID = auto()
CANNOT_FETCH_SOURCES = auto()
CANCELLED_PRIORITY = auto()
UNFINISHED_TRANSACTION = auto()
LOCK_REQUIRED = auto()
REPO_ALREADY_SET = auto()
OOM = OUT_OF_MEMORY
class Group(PkFlag):
"""
The group type
* Group.UNKNOWN: Unknown group
* Group.ACCESSIBILITY: Accessibility related packages
* Group.ACCESSORIES: Accessory packages
* Group.ADMIN_TOOLS: Administration tools packages
* Group.COMMUNICATION: Communication packages
* Group.DESKTOP_GNOME: GNOME packages
* Group.DESKTOP_KDE: KDE packages
* Group.DESKTOP_OTHER: Other desktop packages
* Group.DESKTOP_XFCE: XFCE packages
* Group.EDUCATION: Education packages
* Group.FONTS: Fonts
* Group.GAMES: Games
* Group.GRAPHICS: Graphics related packages
* Group.INTERNET: Internet related packages
* Group.LEGACY: Legacy packages
* Group.LOCALIZATION: Localization related packages
* Group.MAPS: Map related packages
* Group.MULTIMEDIA: Multimedia packages
* Group.NETWORK: Network related packages
* Group.OFFICE: Office packages
* Group.OTHER:
* Group.POWER_MANAGEMENT: Power-management related packages
* Group.PROGRAMMING: Programming packages
* Group.PUBLISHING: Publishing related packages
* Group.REPOS:
* Group.SECURITY: Security packages
* Group.SERVERS: Server related packages
* Group.SYSTEM: System packages
* Group.VIRTUALIZATION: Virtualization packages
* Group.SCIENCE: Science related packages
* Group.DOCUMENTATION: Documentation
* Group.ELECTRONICS: Electronics package
* Group.COLLECTIONS:
* Group.VENDOR: Vendor defined group
* Group.NEWEST: Special group for recently updated packages
"""
UNKNOWN = auto()
ACCESSIBILITY = auto()
ACCESSORIES = auto()
ADMIN_TOOLS = auto()
COMMUNICATION = auto()
DESKTOP_GNOME = auto()
DESKTOP_KDE = auto()
DESKTOP_OTHER = auto()
DESKTOP_XFCE = auto()
EDUCATION = auto()
FONTS = auto()
GAMES = auto()
GRAPHICS = auto()
INTERNET = auto()
LEGACY = auto()
LOCALIZATION = auto()
MAPS = auto()
MULTIMEDIA = auto()
NETWORK = auto()
OFFICE = auto()
OTHER = auto()
POWER_MANAGEMENT = auto()
PROGRAMMING = auto()
PUBLISHING = auto()
REPOS = auto()
SECURITY = auto()
SERVERS = auto()
SYSTEM = auto()
VIRTUALIZATION = auto()
SCIENCE = auto()
DOCUMENTATION = auto()
ELECTRONICS = auto()
COLLECTIONS = auto()
VENDOR = auto()
NEWEST = auto()
class UpdateState(PkFlag):
"""
What state the update is in
* UpdateState.UNKNOWN: Update stability unknown
* UpdateState.STABLE: Update is a stable release
* UpdateState.UNSTABLE: Update is an unstable release
* UpdateState.TESTING: Update is a testing release
"""
UNKNOWN = auto()
STABLE = auto()
UNSTABLE = auto()
TESTING = auto()
class Info(PkFlag):
"""
The enumerated types used in Package() - these have to refer to a specific
package action, rather than a general state
* Info.UNKNOWN: Package status is unknown
* Info.INSTALLED: Package is installed
* Info.AVAILABLE: Package is available to be installed
* Info.LOW:
* Info.ENHANCEMENT:
* Info.NORMAL:
* Info.BUGFIX:
* Info.IMPORTANT:
* Info.SECURITY:
* Info.BLOCKED: Package is blocked
* Info.DOWNLOADING: Package is downloading
* Info.UPDATING: Package is updating
* Info.INSTALLING: Package is being installed
* Info.REMOVING: Package is being removed
* Info.CLEANUP: Package is running cleanup
* Info.OBSOLETING:
* Info.COLLECTION_INSTALLED:
* Info.COLLECTION_AVAILABLE:
* Info.FINISHED:
* Info.REINSTALLING: Package is being reinstalled
* Info.DOWNGRADING: Package is being downgraded
* Info.PREPARING: Package is preparing for installation/removal
* Info.DECOMPRESSING: Package is decompressing
* Info.UNTRUSTED:
* Info.TRUSTED:
* Info.UNAVAILABLE: Package is unavailable
* Info.CRITICAL: Update severity is critical; Since: 1.2.4
"""
UNKNOWN = auto()
INSTALLED = auto()
AVAILABLE = auto()
LOW = auto()
ENHANCEMENT = auto()
NORMAL = auto()
BUGFIX = auto()
IMPORTANT = auto()
SECURITY = auto()
BLOCKED = auto()
DOWNLOADING = auto()
UPDATING = auto()
INSTALLING = auto()
REMOVING = auto()
CLEANUP = auto()
OBSOLETING = auto()
COLLECTION_INSTALLED = auto()
COLLECTION_AVAILABLE = auto()
FINISHED = auto()
REINSTALLING = auto()
DOWNGRADING = auto()
PREPARING = auto()
DECOMPRESSING = auto()
UNTRUSTED = auto()
TRUSTED = auto()
UNAVAILABLE = auto()
CRITICAL = auto()
class DistroUpgrade(PkFlag):
"""
The distro upgrade status
* DistroUpgrade.UNKNOWN: Unknown disto upgrade state
* DistroUpgrade.STABLE: Upgraded to stable release
* DistroUpgrade.UNSTABLE: Upgraded to unstable release
"""
UNKNOWN = auto()
STABLE = auto()
UNSTABLE = auto()
class SigType(PkFlag):
"""
The signature type type
* SigType.UNKNOWN: Unkwown signature type
* SigType.GPG: GPG signature
"""
UNKNOWN = auto()
GPG = auto()
class MediaType(PkFlag):
"""
The media type
* MediaType.UNKNOWN: Unknown media type
* MediaType.CD: Media is a CD
* MediaType.DVD: Media is a DVD
* MediaType.DISC: Media is a disc (not CD or DVD)
"""
UNKNOWN = auto()
CD = auto()
DVD = auto()
DISC = auto()
class Authorize(PkFlag):
"""
The authorization result
* Authorize.UNKNOWN: Unknown authorization status
* Authorize.YES: Authorized
* Authorize.NO: Not authorized
* Authorize.INTERACTIVE: Interaction required for authorization
"""
UNKNOWN = auto()
YES = auto()
NO = auto()
INTERACTIVE = auto()
class UpgradeKind(PkFlag):
"""
The type of distribution upgrade to perform
* UpgradeKind.UNKNOWN:
* UpgradeKind.MINIMAL: Perform minimal upgrade
* UpgradeKind.DEFAULT: Perform default upgrade
* UpgradeKind.COMPLETE: Perform complete upgrade
"""
UNKNOWN = auto()
MINIMAL = auto()
DEFAULT = auto()
COMPLETE = auto()
class TransactionFlag(PkFlag):
"""
The transaction flags that alter how the transaction is handled
* TransactionFlag.NONE: No transaction flag
* TransactionFlag.ONLY_TRUSTED: Only allow trusted packages
* TransactionFlag.SIMULATE: Simulate transaction
* TransactionFlag.ONLY_DOWNLOAD: Only download packages
* TransactionFlag.ALLOW_REINSTALL: Allow package reinstallation
* TransactionFlag.JUST_REINSTALL: Only allow package reinstallation
* TransactionFlag.ALLOW_DOWNGRADE: Allow packages to be downgraded
"""
NONE = auto()
ONLY_TRUSTED = auto()
SIMULATE = auto()
ONLY_DOWNLOAD = auto()
ALLOW_REINSTALL = auto()
JUST_REINSTALL = auto()
ALLOW_DOWNGRADE = auto()
-101
View File
@@ -1,101 +0,0 @@
# General Server Utilities
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
import logging
import logging.handlers
import os
import sys
import subprocess
import asyncio
from queue import SimpleQueue as Queue
class ServerError(Exception):
def __init__(self, message, status_code=400):
Exception.__init__(self, message)
self.status_code = status_code
# Coroutine friendly QueueHandler courtesy of Martjin Pieters:
# https://www.zopatista.com/python/2019/05/11/asyncio-logging/
class LocalQueueHandler(logging.handlers.QueueHandler):
def emit(self, record: logging.LogRecord) -> None:
# Removed the call to self.prepare(), handle task cancellation
try:
self.enqueue(record)
except asyncio.CancelledError:
raise
except Exception:
self.handleError(record)
# Timed Rotating File Handler, based on Klipper's implementation
class MoonrakerLoggingHandler(logging.handlers.TimedRotatingFileHandler):
def __init__(self, software_version, filename, **kwargs):
super(MoonrakerLoggingHandler, self).__init__(filename, **kwargs)
self.rollover_info = {
'header': f"{'-'*20}Moonraker Log Start{'-'*20}",
'version': f"Git Version: {software_version}",
}
lines = [line for line in self.rollover_info.values() if line]
if self.stream is not None:
self.stream.write("\n".join(lines) + "\n")
def set_rollover_info(self, name, item):
self.rollover_info[name] = item
def doRollover(self):
super(MoonrakerLoggingHandler, self).doRollover()
lines = [line for line in self.rollover_info.values() if line]
if self.stream is not None:
self.stream.write("\n".join(lines) + "\n")
# Parse the git version from the command line. This code
# is borrowed from Klipper.
def get_software_version():
moonraker_path = os.path.join(
os.path.dirname(__file__), '..')
# Obtain version info from "git" program
prog = ('git', '-C', moonraker_path, 'describe', '--always',
'--tags', '--long', '--dirty')
try:
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
ver, err = process.communicate()
retcode = process.wait()
if retcode == 0:
version = ver.strip()
if isinstance(version, bytes):
version = version.decode()
return version
else:
logging.debug(f"Error getting git version: {err}")
except OSError:
logging.exception("Error runing git describe")
return "?"
def setup_logging(log_file, software_version):
root_logger = logging.getLogger()
queue = Queue()
queue_handler = LocalQueueHandler(queue)
root_logger.addHandler(queue_handler)
root_logger.setLevel(logging.INFO)
stdout_hdlr = logging.StreamHandler(sys.stdout)
stdout_fmt = logging.Formatter(
'[%(filename)s:%(funcName)s()] - %(message)s')
stdout_hdlr.setFormatter(stdout_fmt)
file_hdlr = None
if log_file:
file_hdlr = MoonrakerLoggingHandler(
software_version, log_file, when='midnight', backupCount=2)
formatter = logging.Formatter(
'%(asctime)s [%(filename)s:%(funcName)s()] - %(message)s')
file_hdlr.setFormatter(formatter)
listener = logging.handlers.QueueListener(
queue, file_hdlr, stdout_hdlr)
else:
listener = logging.handlers.QueueListener(
queue, stdout_hdlr)
listener.start()
return listener, file_hdlr
+196
View File
@@ -0,0 +1,196 @@
# General Server Utilities
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import logging
import os
import glob
import importlib
import pathlib
import sys
import subprocess
import asyncio
import hashlib
import json
import shlex
import re
import struct
import socket
import enum
from . import source_info
# Annotation imports
from typing import (
TYPE_CHECKING,
List,
Optional,
ClassVar,
Tuple,
Dict,
Union
)
if TYPE_CHECKING:
from types import ModuleType
from asyncio.trsock import TransportSocket
SYS_MOD_PATHS = glob.glob("/usr/lib/python3*/dist-packages")
SYS_MOD_PATHS += glob.glob("/usr/lib/python3*/site-packages")
class ServerError(Exception):
def __init__(self, message: str, status_code: int = 400) -> None:
Exception.__init__(self, message)
self.status_code = status_code
class Sentinel(enum.Enum):
MISSING = object()
def _run_git_command(cmd: str) -> str:
prog = shlex.split(cmd)
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
ret, err = process.communicate()
retcode = process.wait()
if retcode == 0:
return ret.strip().decode()
raise Exception(f"Failed to run git command: {cmd}")
def _retrieve_git_tag(source_path: str) -> str:
cmd = f"git -C {source_path} rev-list --tags --max-count=1"
hash = _run_git_command(cmd)
cmd = f"git -C {source_path} describe --tags {hash}"
tag = _run_git_command(cmd)
cmd = f"git -C {source_path} rev-list {tag}..HEAD --count"
count = _run_git_command(cmd)
return f"{tag}-{count}"
# Parse the git version from the command line. This code
# is borrowed from Klipper.
def retrieve_git_version(source_path: str) -> str:
# Obtain version info from "git" program
cmd = f"git -C {source_path} describe --always --tags --long --dirty"
ver = _run_git_command(cmd)
tag_match = re.match(r"v\d+\.\d+\.\d+", ver)
if tag_match is not None:
return ver
# This is likely a shallow clone. Resolve the tag and manually create
# the version string
tag = _retrieve_git_tag(source_path)
return f"t{tag}-g{ver}-shallow"
def get_software_version() -> str:
pkg_ver = source_info.package_version()
if pkg_ver is not None:
return pkg_ver
version: str = "?"
src_path = source_info.source_path()
try:
version = retrieve_git_version(str(src_path))
except Exception:
vfile = src_path.joinpath("moonraker/.version")
if vfile.exists():
try:
version = vfile.read_text().strip()
except Exception:
logging.exception("Unable to extract version from file")
version = "?"
return version
def hash_directory(
dir_path: Union[str, pathlib.Path],
ignore_exts: List[str],
ignore_dirs: List[str]
) -> str:
if isinstance(dir_path, str):
dir_path = pathlib.Path(dir_path)
checksum = hashlib.blake2s()
if not dir_path.exists():
return ""
for dpath, dnames, fnames in os.walk(dir_path):
valid_dirs: List[str] = []
for dname in sorted(dnames):
if dname[0] == '.' or dname in ignore_dirs:
continue
valid_dirs.append(dname)
dnames[:] = valid_dirs
for fname in sorted(fnames):
ext = os.path.splitext(fname)[-1].lower()
if fname[0] == '.' or ext in ignore_exts:
continue
fpath = pathlib.Path(os.path.join(dpath, fname))
try:
checksum.update(fpath.read_bytes())
except Exception:
pass
return checksum.hexdigest()
def verify_source(
path: Optional[Union[str, pathlib.Path]] = None
) -> Optional[Tuple[str, bool]]:
if path is None:
path = source_info.source_path()
elif isinstance(path, str):
path = pathlib.Path(path)
rfile = path.joinpath(".release_info")
if not rfile.exists():
return None
try:
rinfo = json.loads(rfile.read_text())
except Exception:
return None
orig_chksum = rinfo['source_checksum']
ign_dirs = rinfo['ignored_dirs']
ign_exts = rinfo['ignored_exts']
checksum = hash_directory(path, ign_exts, ign_dirs)
return checksum, checksum == orig_chksum
def load_system_module(name: str) -> ModuleType:
for module_path in SYS_MOD_PATHS:
sys.path.insert(0, module_path)
try:
module = importlib.import_module(name)
except ImportError as e:
if not isinstance(e, ModuleNotFoundError):
logging.exception(f"Failed to load {name} module")
sys.path.pop(0)
else:
sys.path.pop(0)
break
else:
raise ServerError(f"Unable to import module {name}")
return module
def get_unix_peer_credentials(
writer: asyncio.StreamWriter, name: str
) -> Dict[str, int]:
sock: TransportSocket
sock = writer.get_extra_info("socket", None)
if sock is None:
logging.debug(
f"Unable to get underlying Unix Socket for {name}, "
"cant fetch peer credentials"
)
return {}
data: bytes = b""
try:
size = struct.calcsize("3I")
data = sock.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, size)
pid, uid, gid = struct.unpack("3I", data)
except asyncio.CancelledError:
raise
except Exception:
logging.exception(
f"Failed to get Unix Socket Peer Credentials for {name}"
f", raw: 0x{data.hex()}"
)
return {}
return {
"process_id": pid,
"user_id": uid,
"group_id": gid
}
+77
View File
@@ -0,0 +1,77 @@
# General Server Utilities
#
# Copyright (C) 2023 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import importlib.resources as ilr
import pathlib
import sys
import site
# Annotation imports
from typing import (
Optional,
)
def package_path() -> pathlib.Path:
return pathlib.Path(__file__).parent.parent
def source_path() -> pathlib.Path:
return package_path().parent
def is_git_repo(src_path: Optional[pathlib.Path] = None) -> bool:
if src_path is None:
return source_path().joinpath(".git").is_dir()
return src_path.joinpath(".git").is_dir()
def is_dist_package(src_path: Optional[pathlib.Path] = None) -> bool:
if src_path is None:
# Fetch dist info for moonraker. This should be the most reliable
# method
src_path = source_path()
site_dirs = site.getsitepackages()
return str(src_path) in site_dirs
else:
# Make an assumption based on the source path. If its name is
# site-packages or dist-packages then presumably it is an
# installed package
return src_path.name in ["dist-packages", "site-packages"]
def package_version() -> Optional[str]:
try:
import moonraker.__version__ as ver # type: ignore
version = ver.__version__
except Exception:
pass
else:
if version:
return version
return None
def read_asset(asset_name: str) -> Optional[str]:
if sys.version_info < (3, 10):
with ilr.path("moonraker.assets", asset_name) as p:
if not p.is_file():
return None
return p.read_text()
else:
files = ilr.files("moonraker.assets")
with ilr.as_file(files.joinpath(asset_name)) as p:
if not p.is_file():
return None
return p.read_text()
def get_asset_path() -> Optional[pathlib.Path]:
if sys.version_info < (3, 10):
with ilr.path("moonraker.assets", "__init__.py") as p:
asset_path = p.parent
else:
files = ilr.files("moonraker.assets")
with ilr.as_file(files.joinpath("__init__.py")) as p:
asset_path = p.parent
if not asset_path.is_dir():
# Somehow running in a zipapp. This is an error.
return None
return asset_path
+847 -169
View File
File diff suppressed because it is too large. Load diff
Generated
+674
View File
@@ -0,0 +1,674 @@
# This file is @generated by PDM.
# It is not intended for manual editing.
[[package]]
name = "apprise"
version = "1.2.1"
requires_python = ">=3.6"
summary = "Push Notifications that work with just about every platform!"
dependencies = [
"PyYAML",
"certifi",
"click>=5.0",
"markdown",
"requests",
"requests-oauthlib",
]
[[package]]
name = "async-timeout"
version = "4.0.2"
requires_python = ">=3.6"
summary = "Timeout context manager for asyncio programs"
dependencies = [
"typing-extensions>=3.6.5; python_version < \"3.8\"",
]
[[package]]
name = "certifi"
version = "2022.12.7"
requires_python = ">=3.6"
summary = "Python package for providing Mozilla's CA Bundle."
[[package]]
name = "charset-normalizer"
version = "3.0.1"
summary = "The Real First Universal Charset Detector. Open, modern and actively maintained alternative to Chardet."
[[package]]
name = "click"
version = "8.1.3"
requires_python = ">=3.7"
summary = "Composable command line interface toolkit"
dependencies = [
"colorama; platform_system == \"Windows\"",
"importlib-metadata; python_version < \"3.8\"",
]
[[package]]
name = "colorama"
version = "0.4.6"
requires_python = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7"
summary = "Cross-platform colored terminal text."
[[package]]
name = "dbus-next"
version = "0.2.3"
requires_python = ">=3.6.0"
summary = "A zero-dependency DBus library for Python with asyncio support"
[[package]]
name = "distro"
version = "1.8.0"
requires_python = ">=3.6"
summary = "Distro - an OS platform information API"
[[package]]
name = "idna"
version = "3.4"
requires_python = ">=3.5"
summary = "Internationalized Domain Names in Applications (IDNA)"
[[package]]
name = "ifaddr"
version = "0.2.0"
summary = "Cross-platform network interface and IP address enumeration library"
[[package]]
name = "importlib-metadata"
version = "6.0.0"
requires_python = ">=3.7"
summary = "Read metadata from Python packages"
dependencies = [
"typing-extensions>=3.6.4; python_version < \"3.8\"",
"zipp>=0.5",
]
[[package]]
name = "inotify-simple"
version = "1.3.5"
requires_python = ">=2.7, !=3.0.*, !=3.1.*"
summary = "A simple wrapper around inotify. No fancy bells and whistles, just a literal wrapper with ctypes. Under 100 lines of code!"
[[package]]
name = "jinja2"
version = "3.1.2"
requires_python = ">=3.7"
summary = "A very fast and expressive template engine."
dependencies = [
"MarkupSafe>=2.0",
]
[[package]]
name = "ldap3"
version = "2.9.1"
summary = "A strictly RFC 4510 conforming LDAP V3 pure Python client library"
dependencies = [
"pyasn1>=0.4.6",
]
[[package]]
name = "libnacl"
version = "1.8.0"
summary = "Python bindings for libsodium based on ctypes"
[[package]]
name = "lmdb"
version = "1.3.0"
summary = "Universal Python binding for the LMDB 'Lightning' Database"
[[package]]
name = "markdown"
version = "3.4.1"
requires_python = ">=3.7"
summary = "Python implementation of Markdown."
dependencies = [
"importlib-metadata>=4.4; python_version < \"3.10\"",
]
[[package]]
name = "markupsafe"
version = "2.1.2"
requires_python = ">=3.7"
summary = "Safely add untrusted strings to HTML/XML markup."
[[package]]
name = "oauthlib"
version = "3.2.2"
requires_python = ">=3.6"
summary = "A generic, spec-compliant, thorough implementation of the OAuth request-signing logic"
[[package]]
name = "paho-mqtt"
version = "1.6.1"
summary = "MQTT version 5.0/3.1.1 client class"
[[package]]
name = "pillow"
version = "9.3.0"
requires_python = ">=3.7"
summary = "Python Imaging Library (Fork)"
[[package]]
name = "preprocess-cancellation"
version = "0.2.0"
requires_python = ">=3.6.2"
summary = "GCode processor to add klipper cancel-object markers"
[[package]]
name = "pyasn1"
version = "0.4.8"
summary = "ASN.1 types and codecs"
[[package]]
name = "pyserial"
version = "3.4"
summary = "Python Serial Port Extension"
[[package]]
name = "pyserial-asyncio"
version = "0.6"
summary = "Python Serial Port Extension - Asynchronous I/O support"
dependencies = [
"pyserial",
]
[[package]]
name = "pyyaml"
version = "6.0"
requires_python = ">=3.6"
summary = "YAML parser and emitter for Python"
[[package]]
name = "requests"
version = "2.28.2"
requires_python = ">=3.7, <4"
summary = "Python HTTP for Humans."
dependencies = [
"certifi>=2017.4.17",
"charset-normalizer<4,>=2",
"idna<4,>=2.5",
"urllib3<1.27,>=1.21.1",
]
[[package]]
name = "requests-oauthlib"
version = "1.3.1"
requires_python = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*"
summary = "OAuthlib authentication support for Requests."
dependencies = [
"oauthlib>=3.0.0",
"requests>=2.0.0",
]
[[package]]
name = "streaming-form-data"
version = "1.11.0"
requires_python = ">=3.6"
summary = "Streaming parser for multipart/form-data"
[[package]]
name = "tornado"
version = "6.2"
requires_python = ">= 3.7"
summary = "Tornado is a Python web framework and asynchronous networking library, originally developed at FriendFeed."
[[package]]
name = "typing-extensions"
version = "4.4.0"
requires_python = ">=3.7"
summary = "Backported and Experimental Type Hints for Python 3.7+"
[[package]]
name = "urllib3"
version = "1.26.14"
requires_python = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*, !=3.5.*"
summary = "HTTP library with thread-safe connection pooling, file post, and more."
[[package]]
name = "zeroconf"
version = "0.39.4"
requires_python = ">=3.7"
summary = "Pure Python Multicast DNS Service Discovery Library (Bonjour/Avahi compatible)"
dependencies = [
"async-timeout>=4.0.1",
"ifaddr>=0.1.7",
]
[[package]]
name = "zipp"
version = "3.13.0"
requires_python = ">=3.7"
summary = "Backport of pathlib-compatible object wrapper for zip files"
[metadata]
lock_version = "4.1"
content_hash = "sha256:0e54d8cb135fb11f1588c0d0208221cfcdbae6d54ed3ffa43012ec460bae6b34"
[metadata.files]
"apprise 1.2.1" = [
{url = "https://files.pythonhosted.org/packages/a4/3a/52ec5cf9ed71e3a068a208603e38471b686a59b548dda771f2975166e4a9/apprise-1.2.1-py2.py3-none-any.whl", hash = "sha256:679fb5d6232ec7748eef308bda9fe0f0707fa5e48eab247bfde83c3a024a21d1"},
{url = "https://files.pythonhosted.org/packages/d2/04/4285d864569dde4eece4b0e7bfa447a68e99240898537b10926cb5a53145/apprise-1.2.1.tar.gz", hash = "sha256:67e0c227eecee260000980dbbf8ba1e5eebdbe494f4730808297c9e645c03579"},
]
"async-timeout 4.0.2" = [
{url = "https://files.pythonhosted.org/packages/54/6e/9678f7b2993537452710ffb1750c62d2c26df438aa621ad5fa9d1507a43a/async-timeout-4.0.2.tar.gz", hash = "sha256:2163e1640ddb52b7a8c80d0a67a08587e5d245cc9c553a74a847056bc2976b15"},
{url = "https://files.pythonhosted.org/packages/d6/c1/8991e7c5385b897b8c020cdaad718c5b087a6626d1d11a23e1ea87e325a7/async_timeout-4.0.2-py3-none-any.whl", hash = "sha256:8ca1e4fcf50d07413d66d1a5e416e42cfdf5851c981d679a09851a6853383b3c"},
]
"certifi 2022.12.7" = [
{url = "https://files.pythonhosted.org/packages/37/f7/2b1b0ec44fdc30a3d31dfebe52226be9ddc40cd6c0f34ffc8923ba423b69/certifi-2022.12.7.tar.gz", hash = "sha256:35824b4c3a97115964b408844d64aa14db1cc518f6562e8d7261699d1350a9e3"},
{url = "https://files.pythonhosted.org/packages/71/4c/3db2b8021bd6f2f0ceb0e088d6b2d49147671f25832fb17970e9b583d742/certifi-2022.12.7-py3-none-any.whl", hash = "sha256:4ad3232f5e926d6718ec31cfc1fcadfde020920e278684144551c91769c7bc18"},
]
"charset-normalizer 3.0.1" = [
{url = "https://files.pythonhosted.org/packages/00/35/830c29e5dab61932224c7a6c89427090164a3e425cf03486ce7a3ce60623/charset_normalizer-3.0.1-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:9d9153257a3f70d5f69edf2325357251ed20f772b12e593f3b3377b5f78e7ef8"},
{url = "https://files.pythonhosted.org/packages/01/ff/9ee4a44e8c32fe96dfc12daa42f29294608a55eadc88f327939327fb20fb/charset_normalizer-3.0.1-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:72966d1b297c741541ca8cf1223ff262a6febe52481af742036a0b296e35fa5a"},
{url = "https://files.pythonhosted.org/packages/02/49/78b4c1bc8b1b0e0fc66fb31ce30d8302f10a1412ba75de72c57532f0beb0/charset_normalizer-3.0.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:87701167f2a5c930b403e9756fab1d31d4d4da52856143b609e30a1ce7160f3c"},
{url = "https://files.pythonhosted.org/packages/03/5e/e81488c74e86eef85cf085417ed945da2dcca87ed22d76202680c16bd3c3/charset_normalizer-3.0.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:39049da0ffb96c8cbb65cbf5c5f3ca3168990adf3551bd1dee10c48fce8ae820"},
{url = "https://files.pythonhosted.org/packages/0b/8b/3cf0eff3c8b6734cd4336c23a3141846d579931a31e6476c8091961f1e25/charset_normalizer-3.0.1-cp36-cp36m-win_amd64.whl", hash = "sha256:eaa379fcd227ca235d04152ca6704c7cb55564116f8bc52545ff357628e10602"},
{url = "https://files.pythonhosted.org/packages/0e/d3/c5fa421dc69bb77c581ed561f1ec6656109c97731ad1128aa93d8bad3053/charset_normalizer-3.0.1-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:024e606be3ed92216e2b6952ed859d86b4cfa52cd5bc5f050e7dc28f9b43ec42"},
{url = "https://files.pythonhosted.org/packages/0e/fd/0d099502582af039ef8a8c954d69d7dadbe5f425cb1b24d175eb0034ea9e/charset_normalizer-3.0.1-cp37-cp37m-win32.whl", hash = "sha256:0bf2dae5291758b6f84cf923bfaa285632816007db0330002fa1de38bfcb7154"},
{url = "https://files.pythonhosted.org/packages/0f/45/f462f534dd2853ebbc186ed859661db454665b1dc9ae6c690d982153cda9/charset_normalizer-3.0.1-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:503e65837c71b875ecdd733877d852adbc465bd82c768a067badd953bf1bc5a3"},
{url = "https://files.pythonhosted.org/packages/12/e5/aa09a1c39c3e444dd223d63e2c816c18ed78d035cff954143b2a539bdc9e/charset_normalizer-3.0.1-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:0c0a590235ccd933d9892c627dec5bc7511ce6ad6c1011fdf5b11363022746c1"},
{url = "https://files.pythonhosted.org/packages/16/bd/671f11f920dfb46de848e9176d84ddb25b3bbdffac6751cbbf691c0b5b17/charset_normalizer-3.0.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:3e45867f1f2ab0711d60c6c71746ac53537f1684baa699f4f668d4c6f6ce8e14"},
{url = "https://files.pythonhosted.org/packages/17/67/4b25c0358a2e812312b551e734d58855d58f47d0e0e9d1573930003910cb/charset_normalizer-3.0.1-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:8eade758719add78ec36dc13201483f8e9b5d940329285edcd5f70c0a9edbd7f"},
{url = "https://files.pythonhosted.org/packages/17/da/fdf8ffc33716c82cae06008159a55a581fa515e8dd02e3395dcad42ff83d/charset_normalizer-3.0.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:81d6741ab457d14fdedc215516665050f3822d3e56508921cc7239f8c8e66a58"},
{url = "https://files.pythonhosted.org/packages/20/a2/16b2cbf5f73bdd10624b94647b85c008ba25059792a5c7b4fdb8358bceeb/charset_normalizer-3.0.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e696f0dd336161fca9adbb846875d40752e6eba585843c768935ba5c9960722b"},
{url = "https://files.pythonhosted.org/packages/25/19/298089cef2eb82fd3810d982aa239d4226594f99e1fe78494cb9b47b03c9/charset_normalizer-3.0.1-cp39-cp39-musllinux_1_1_s390x.whl", hash = "sha256:0f438ae3532723fb6ead77e7c604be7c8374094ef4ee2c5e03a3a17f1fca256c"},
{url = "https://files.pythonhosted.org/packages/25/b5/f477e419b06e49f3bae446cbdc1fd71d2599be8b12b4d45c641c5a4495b1/charset_normalizer-3.0.1-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:911d8a40b2bef5b8bbae2e36a0b103f142ac53557ab421dc16ac4aafee6f53dc"},
{url = "https://files.pythonhosted.org/packages/27/b1/8dfcfa5d9978b845466cd41973b3d714eba3926fcb50f6fcddd45cfb75a2/charset_normalizer-3.0.1-cp36-cp36m-musllinux_1_1_ppc64le.whl", hash = "sha256:083c8d17153ecb403e5e1eb76a7ef4babfc2c48d58899c98fcaa04833e7a2f9a"},
{url = "https://files.pythonhosted.org/packages/2d/02/0f875eb6a1cf347bd3a6098f458f79796aafa3b51090fd7b2784736dc67d/charset_normalizer-3.0.1-cp310-cp310-musllinux_1_1_ppc64le.whl", hash = "sha256:44ba614de5361b3e5278e1241fda3dc1838deed864b50a10d7ce92983797fa76"},
{url = "https://files.pythonhosted.org/packages/2e/7b/5053a4a46fac017fd2aea3dc9abdd9983fd4cef153b6eb6aedcb0d7cb6e3/charset_normalizer-3.0.1-cp311-cp311-win_amd64.whl", hash = "sha256:9ab77acb98eba3fd2a85cd160851816bfce6871d944d885febf012713f06659c"},
{url = "https://files.pythonhosted.org/packages/31/06/f6330ee70c041a032ee1a5d32785d69748cfa41f64b6d327cc08cae51de9/charset_normalizer-3.0.1-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:ab5de034a886f616a5668aa5d098af2b5385ed70142090e2a31bcbd0af0fdb3d"},
{url = "https://files.pythonhosted.org/packages/31/af/67b7653a35dbd56f6bb9ff54652a551eae8420d1d0545f0042c5bdb15fb0/charset_normalizer-3.0.1-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f6f45710b4459401609ebebdbcfb34515da4fc2aa886f95107f556ac69a9147e"},
{url = "https://files.pythonhosted.org/packages/35/86/d85885ed7ac236a297b0b8beab5f0703fc0516f803ddf7b1910f255b83f3/charset_normalizer-3.0.1-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:7eb33a30d75562222b64f569c642ff3dc6689e09adda43a082208397f016c39a"},
{url = "https://files.pythonhosted.org/packages/37/00/ca188e0a2b3cd3184cdd2521b8765cf579327d128caa8aedc3dc7614020a/charset_normalizer-3.0.1-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:0298eafff88c99982a4cf66ba2efa1128e4ddaca0b05eec4c456bbc7db691d8d"},
{url = "https://files.pythonhosted.org/packages/37/60/7a01f3a129d1af1f26ab2c56aae89a72dbf33fd46a467c1aa994ec62b90b/charset_normalizer-3.0.1-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:8b8af03d2e37866d023ad0ddea594edefc31e827fee64f8de5611a1dbc373174"},
{url = "https://files.pythonhosted.org/packages/3a/91/a233f06d33dc3ac90a9991d238fbc68c59615d9f71be1801e14ac4e42d7f/charset_normalizer-3.0.1-cp38-cp38-win32.whl", hash = "sha256:4457ea6774b5611f4bed5eaa5df55f70abde42364d498c5134b7ef4c6958e20e"},
{url = "https://files.pythonhosted.org/packages/46/69/9f42514a9f58c602ab89a2af89081a475dccd959f9bc01ba7e61372d31bd/charset_normalizer-3.0.1-cp36-cp36m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c95a03c79bbe30eec3ec2b7f076074f4281526724c8685a42872974ef4d36b72"},
{url = "https://files.pythonhosted.org/packages/55/2b/35619e03725bfa4af4a902e1996c9ee8052d6bce005ff79c9bd988820cb4/charset_normalizer-3.0.1-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:31a9ddf4718d10ae04d9b18801bd776693487cbb57d74cc3458a7673f6f34639"},
{url = "https://files.pythonhosted.org/packages/56/5d/275fb120957dfe5a2262d04f28bc742fd4bcc2bd270d19bb8757e09737ef/charset_normalizer-3.0.1-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9cf4e8ad252f7c38dd1f676b46514f92dc0ebeb0db5552f5f403509705e24753"},
{url = "https://files.pythonhosted.org/packages/5a/d8/9e76846e70e729de85ecc6af21edc584a2adfef202dc5f5ae00a02622e3d/charset_normalizer-3.0.1-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:11b53acf2411c3b09e6af37e4b9005cba376c872503c8f28218c7243582df45d"},
{url = "https://files.pythonhosted.org/packages/5b/e7/5527effca09d873e07e128d3daac7c531203b5105cb4e2956c2b7a8cc41c/charset_normalizer-3.0.1-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:109487860ef6a328f3eec66f2bf78b0b72400280d8f8ea05f69c51644ba6521a"},
{url = "https://files.pythonhosted.org/packages/67/c6/cf4e8a8f41201284bdf200f764b29a87f6f7d22fe3c9eddab602af489acc/charset_normalizer-3.0.1-cp36-cp36m-musllinux_1_1_i686.whl", hash = "sha256:cd6056167405314a4dc3c173943f11249fa0f1b204f8b51ed4bde1a9cd1834dc"},
{url = "https://files.pythonhosted.org/packages/68/2b/02e9d6a98ddb73fa238d559a9edcc30b247b8dc4ee848b6184c936e99dc0/charset_normalizer-3.0.1-py3-none-any.whl", hash = "sha256:7e189e2e1d3ed2f4aebabd2d5b0f931e883676e51c7624826e0a4e5fe8a0bf24"},
{url = "https://files.pythonhosted.org/packages/6a/ab/3a00ecbddabe25132c20c1bd45e6f90c537b5f7a0b5bcaba094c4922928c/charset_normalizer-3.0.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:8499ca8f4502af841f68135133d8258f7b32a53a1d594aa98cc52013fff55678"},
{url = "https://files.pythonhosted.org/packages/6e/a3/997ff79260f76210b1d73463b9081ae7edbf16ff3d611b67f5e72c685cab/charset_normalizer-3.0.1-cp39-cp39-win32.whl", hash = "sha256:39cf9ed17fe3b1bc81f33c9ceb6ce67683ee7526e65fde1447c772afc54a1bb8"},
{url = "https://files.pythonhosted.org/packages/6e/d7/1d4035fcbf7d0f2e89588a142628355d8d1cd652a227acefb9ec85908cd4/charset_normalizer-3.0.1-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:772b87914ff1152b92a197ef4ea40efe27a378606c39446ded52c8f80f79702e"},
{url = "https://files.pythonhosted.org/packages/71/67/79be03bf7ab4198d994c2e8da869ca354487bfa25656b95cf289cf6338a2/charset_normalizer-3.0.1-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:16a8663d6e281208d78806dbe14ee9903715361cf81f6d4309944e4d1e59ac5b"},
{url = "https://files.pythonhosted.org/packages/80/54/183163f9910936e57a60ee618f4f5cc91c2f8333ee2d4ebc6c50f6c8684d/charset_normalizer-3.0.1-cp311-cp311-musllinux_1_1_s390x.whl", hash = "sha256:4a8fcf28c05c1f6d7e177a9a46a1c52798bfe2ad80681d275b10dcf317deaf0b"},
{url = "https://files.pythonhosted.org/packages/82/49/ab81421d5aa25bc8535896a017c93204cb4051f2a4e72b1ad8f3b594e072/charset_normalizer-3.0.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:761e8904c07ad053d285670f36dd94e1b6ab7f16ce62b9805c475b7aa1cffde6"},
{url = "https://files.pythonhosted.org/packages/84/0e/5965dd90991e4f2588718b865115a78c8b040193ac3676f757b7fb6af9d0/charset_normalizer-3.0.1-cp311-cp311-win32.whl", hash = "sha256:71140351489970dfe5e60fc621ada3e0f41104a5eddaca47a7acb3c1b851d6d3"},
{url = "https://files.pythonhosted.org/packages/84/ff/78a4942ef1ea4d1c464cc9a132122b36c5390c5cf6301ed0f9e3e6e24bd9/charset_normalizer-3.0.1-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:8ac7b6a045b814cf0c47f3623d21ebd88b3e8cf216a14790b455ea7ff0135d18"},
{url = "https://files.pythonhosted.org/packages/86/eb/31c9025b4ed7eddd930c5f2ac269efb953de33140608c7539675d74a2081/charset_normalizer-3.0.1-cp311-cp311-musllinux_1_1_ppc64le.whl", hash = "sha256:5995f0164fa7df59db4746112fec3f49c461dd6b31b841873443bdb077c13cfc"},
{url = "https://files.pythonhosted.org/packages/87/5d/0ebaee2249a04fd20bb4baeb9ea2c29dee17317175d9d67b4f5f34cf048d/charset_normalizer-3.0.1-cp38-cp38-win_amd64.whl", hash = "sha256:e62164b50f84e20601c1ff8eb55620d2ad25fb81b59e3cd776a1902527a788af"},
{url = "https://files.pythonhosted.org/packages/89/87/c237a299a658b35d19fd531eeb8247480627fc2fb4b7a471334b48850f45/charset_normalizer-3.0.1-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:f9d0c5c045a3ca9bedfc35dca8526798eb91a07aa7a2c0fee134c6c6f321cbd7"},
{url = "https://files.pythonhosted.org/packages/8f/e2/73ea48d2608f71a879588b607e093d550b8eaa177eb31bbdf1c01e515818/charset_normalizer-3.0.1-cp36-cp36m-musllinux_1_1_s390x.whl", hash = "sha256:f5057856d21e7586765171eac8b9fc3f7d44ef39425f85dbcccb13b3ebea806c"},
{url = "https://files.pythonhosted.org/packages/90/2c/bb5e4f7e2e9871793b5c0fb5c6c4056458a148a05143143320f2d4a410a9/charset_normalizer-3.0.1-cp36-cp36m-musllinux_1_1_aarch64.whl", hash = "sha256:59e5686dd847347e55dffcc191a96622f016bc0ad89105e24c14e0d6305acbc6"},
{url = "https://files.pythonhosted.org/packages/90/59/941e2e5ae6828a688c6437ad16e026eb3606d0cfdd13ea5c9090980f3ffd/charset_normalizer-3.0.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:a8d0fc946c784ff7f7c3742310cc8a57c5c6dc31631269876a88b809dbeff3d3"},
{url = "https://files.pythonhosted.org/packages/92/00/b8dc8dd725297b05f1ab4929c9d7e879f31746131534221c5c8948bc7563/charset_normalizer-3.0.1-cp310-cp310-musllinux_1_1_s390x.whl", hash = "sha256:12db3b2c533c23ab812c2b25934f60383361f8a376ae272665f8e48b88e8e1c6"},
{url = "https://files.pythonhosted.org/packages/93/d1/569445a704414e150f198737c245ab96b40d28d5b68045a62c414a5157de/charset_normalizer-3.0.1-cp37-cp37m-musllinux_1_1_ppc64le.whl", hash = "sha256:02a51034802cbf38db3f89c66fb5d2ec57e6fe7ef2f4a44d070a593c3688667b"},
{url = "https://files.pythonhosted.org/packages/96/d7/1675d9089a1f4677df5eb29c3f8b064aa1e70c1251a0a8a127803158942d/charset-normalizer-3.0.1.tar.gz", hash = "sha256:ebea339af930f8ca5d7a699b921106c6e29c617fe9606fa7baa043c1cdae326f"},
{url = "https://files.pythonhosted.org/packages/97/f9/366db2d2cf69d641159d6448b813ac9b1b5f9807a46fde6c50b36c1387f8/charset_normalizer-3.0.1-cp36-cp36m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:93ad6d87ac18e2a90b0fe89df7c65263b9a99a0eb98f0a3d2e079f12a0735837"},
{url = "https://files.pythonhosted.org/packages/98/e4/d4685870fda1cc7c5e29899ec329500460418e54f4f5df76ee520e30689a/charset_normalizer-3.0.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:c512accbd6ff0270939b9ac214b84fb5ada5f0409c44298361b2f5e13f9aed9e"},
{url = "https://files.pythonhosted.org/packages/98/f4/5ca33ee1e0b3412cbd13eae230321a9fe819acf1a99ad6482420fb97cc6b/charset_normalizer-3.0.1-cp310-cp310-win_amd64.whl", hash = "sha256:601f36512f9e28f029d9481bdaf8e89e5148ac5d89cffd3b05cd533eeb423b59"},
{url = "https://files.pythonhosted.org/packages/99/24/eb846dc9a797da58e6e5b3b5a71d3ff17264de3f424fb29aaa5d27173b55/charset_normalizer-3.0.1-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:3b590df687e3c5ee0deef9fc8c547d81986d9a1b56073d82de008744452d6541"},
{url = "https://files.pythonhosted.org/packages/9a/bf/c9fa15ccf216a69aaaa735c961d7fac2a2801a1b01023fe05d194bf076b4/charset_normalizer-3.0.1-cp36-cp36m-win32.whl", hash = "sha256:95dea361dd73757c6f1c0a1480ac499952c16ac83f7f5f4f84f0658a01b8ef41"},
{url = "https://files.pythonhosted.org/packages/9c/42/c1ebc736c57459aab28bfb8aa28c6a047796f2ea46050a3b129b4920dbe4/charset_normalizer-3.0.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:4b0d02d7102dd0f997580b51edc4cebcf2ab6397a7edf89f1c73b586c614272c"},
{url = "https://files.pythonhosted.org/packages/9c/94/1725fc3e0dbe8918a4ec6dd317ec1ef388e701bdfb5053e1f34f5c6d5a8e/charset_normalizer-3.0.1-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:df2c707231459e8a4028eabcd3cfc827befd635b3ef72eada84ab13b52e1574d"},
{url = "https://files.pythonhosted.org/packages/9f/5a/9dc8932d1e5f8eeaa502e3c3fce91c86be20c04eb3ec202d2b7d74b567e5/charset_normalizer-3.0.1-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:2edb64ee7bf1ed524a1da60cdcd2e1f6e2b4f66ef7c077680739f1641f62f555"},
{url = "https://files.pythonhosted.org/packages/a0/98/7b0d3a853af59e092cdd77c7e1c67ca92fd6acc126285240dbb552b4162f/charset_normalizer-3.0.1-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:74292fc76c905c0ef095fe11e188a32ebd03bc38f3f3e9bcb85e4e6db177b7ea"},
{url = "https://files.pythonhosted.org/packages/a2/93/0b1aa4dbc0ae2aa2e1b2e6d037ab8984dc09912d6b26d63ced14da07e3a7/charset_normalizer-3.0.1-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:a16418ecf1329f71df119e8a65f3aa68004a3f9383821edcb20f0702934d8087"},
{url = "https://files.pythonhosted.org/packages/a2/a7/adc963ad8f8fddadd6be088e636972705ec9d1d92d1b45e6119eb02b7e9e/charset_normalizer-3.0.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:358a7c4cb8ba9b46c453b1dd8d9e431452d5249072e4f56cfda3149f6ab1405e"},
{url = "https://files.pythonhosted.org/packages/a3/09/a837b27b122e710dfad15b0b5df04cd0623c8d8d3382e4298f50798fb84a/charset_normalizer-3.0.1-cp37-cp37m-musllinux_1_1_s390x.whl", hash = "sha256:2e396d70bc4ef5325b72b593a72c8979999aa52fb8bcf03f701c1b03e1166918"},
{url = "https://files.pythonhosted.org/packages/a3/4b/f565c852163312a0991c30598f403fd06796a12e408d7839cc46ca8d7f4a/charset_normalizer-3.0.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:62595ab75873d50d57323a91dd03e6966eb79c41fa834b7a1661ed043b2d404d"},
{url = "https://files.pythonhosted.org/packages/aa/a4/2d6255d4db5d4558a92458fd8dacddfdda2fb4ad9c0a87db6f6034aded34/charset_normalizer-3.0.1-cp38-cp38-musllinux_1_1_ppc64le.whl", hash = "sha256:f97e83fa6c25693c7a35de154681fcc257c1c41b38beb0304b9c4d2d9e164479"},
{url = "https://files.pythonhosted.org/packages/af/63/2c00ff4e657fb9bb76306ffbc7878fd52067e39716f5e8b0dd5582caf1fa/charset_normalizer-3.0.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:70990b9c51340e4044cfc394a81f614f3f90d41397104d226f21e66de668730d"},
{url = "https://files.pythonhosted.org/packages/b2/4c/9a4f30042bfee22d34d80daf75f51817cdd23180d718e0160aab235c4faf/charset_normalizer-3.0.1-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:88600c72ef7587fe1708fd242b385b6ed4b8904976d5da0893e31df8b3480cb6"},
{url = "https://files.pythonhosted.org/packages/b5/1a/932d86fde86bb0d2992c74552c9a422883fe0890132bbc9a5e2211f03318/charset_normalizer-3.0.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:00d3ffdaafe92a5dc603cb9bd5111aaa36dfa187c8285c543be562e61b755f6b"},
{url = "https://files.pythonhosted.org/packages/b6/c2/da108d835354b49aa5c738906e9b6a197b071bc5d77d223f6cd98119172a/charset_normalizer-3.0.1-cp310-cp310-win32.whl", hash = "sha256:502218f52498a36d6bf5ea77081844017bf7982cdbe521ad85e64cabee1b608b"},
{url = "https://files.pythonhosted.org/packages/c0/4d/6b82099e3f25a9ed87431e2f51156c14f3a9ce8fad73880a3856cd95f1d5/charset_normalizer-3.0.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:14e76c0f23218b8f46c4d87018ca2e441535aed3632ca134b10239dfb6dadd6b"},
{url = "https://files.pythonhosted.org/packages/c1/06/b7b1d3d186e0f288500b8a1161ede6b38a0abbf878c2033d667e815e6bd7/charset_normalizer-3.0.1-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:292d5e8ba896bbfd6334b096e34bffb56161c81408d6d036a7dfa6929cff8783"},
{url = "https://files.pythonhosted.org/packages/c1/b2/d81606aebeb7e9a33dc877ff3a206c9946f5bb374c99d22d4a28825aa270/charset_normalizer-3.0.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a60332922359f920193b1d4826953c507a877b523b2395ad7bc716ddd386d866"},
{url = "https://files.pythonhosted.org/packages/c4/d4/94f1ea460cce04483d2460efba6fd4d66e6f60ad6fc6075dba13e3501e48/charset_normalizer-3.0.1-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:9cb3032517f1627cc012dbc80a8ec976ae76d93ea2b5feaa9d2a5b8882597579"},
{url = "https://files.pythonhosted.org/packages/c8/a2/8f873138c99423de3b402daf8ccd7a538632c83d0c129444a6a18ef34e03/charset_normalizer-3.0.1-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c22d3fe05ce11d3671297dc8973267daa0f938b93ec716e12e0f6dee81591dc1"},
{url = "https://files.pythonhosted.org/packages/c9/dd/80a5e8c080b7e1cc2b0ca35f0d6aeedafd7bbd06d25031ac20868b1366d6/charset_normalizer-3.0.1-cp39-cp39-musllinux_1_1_ppc64le.whl", hash = "sha256:608862a7bf6957f2333fc54ab4399e405baad0163dc9f8d99cb236816db169d4"},
{url = "https://files.pythonhosted.org/packages/d2/7f/3c8a6db3eda16ce79a01552ec85ac8fd0ea6265976eb4db250a60b7416ab/charset_normalizer-3.0.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:84c3990934bae40ea69a82034912ffe5a62c60bbf6ec5bc9691419641d7d5c9a"},
{url = "https://files.pythonhosted.org/packages/d3/5b/4031145fcfb9ceaf49dad2fbf9a44e062eb2c08aff36f71d8aafbecf4567/charset_normalizer-3.0.1-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:ff6f3db31555657f3163b15a6b7c6938d08df7adbfc9dd13d9d19edad678f1e8"},
{url = "https://files.pythonhosted.org/packages/d9/7a/60d45c9453212b30eebbf8b5cddbdef330eebddfcf335bce7920c43fb72e/charset_normalizer-3.0.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:79909e27e8e4fcc9db4addea88aa63f6423ebb171db091fb4373e3312cb6d603"},
{url = "https://files.pythonhosted.org/packages/dc/ff/2c7655d83b1d6d6a0e132d50d54131fcb8da763b417ccc6c4a506aa0e08c/charset_normalizer-3.0.1-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:c2ac1b08635a8cd4e0cbeaf6f5e922085908d48eb05d44c5ae9eabab148512ca"},
{url = "https://files.pythonhosted.org/packages/df/2f/4806e155191f75e720aca98a969581c6b2676f0379dd315c34c388bbf8b5/charset_normalizer-3.0.1-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cadaeaba78750d58d3cc6ac4d1fd867da6fc73c88156b7a3212a3cd4819d679d"},
{url = "https://files.pythonhosted.org/packages/df/c5/dd3a17a615775d0ffc3e12b0e47833d8b7e0a4871431dad87a3f92382a19/charset_normalizer-3.0.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:8c7fe7afa480e3e82eed58e0ca89f751cd14d767638e2550c77a92a9e749c317"},
{url = "https://files.pythonhosted.org/packages/e1/7f/64b51f144fa9e74da63fa690d9563eae627f4df6cc6ae5185a781e1912e5/charset_normalizer-3.0.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:c75ffc45f25324e68ab238cb4b5c0a38cd1c3d7f1fb1f72b5541de469e2247db"},
{url = "https://files.pythonhosted.org/packages/e3/96/8cdbce165c96cce5f2c9c7748f7ed8e0cf0c5d03e213bbc90b7c3e918bf5/charset_normalizer-3.0.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:3ae1de54a77dc0d6d5fcf623290af4266412a7c4be0b1ff7444394f03f5c54e3"},
{url = "https://files.pythonhosted.org/packages/e7/0d/5eaceb5abfc000cca204af9f50e9839462dc0bb1c4e0f4b14ed370e3febd/charset_normalizer-3.0.1-cp39-cp39-win_amd64.whl", hash = "sha256:0a11e971ed097d24c534c037d298ad32c6ce81a45736d31e0ff0ad37ab437d59"},
{url = "https://files.pythonhosted.org/packages/e8/80/141f6af05332cbb811ab469f64deb1e1d4cc9e8b0c003aa8a38d689ce84a/charset_normalizer-3.0.1-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:37f8febc8ec50c14f3ec9637505f28e58d4f66752207ea177c1d67df25da5aed"},
{url = "https://files.pythonhosted.org/packages/f0/78/30d853a3073c866b47abede6d86b5532aa99ac67a95e86077d20be1ce481/charset_normalizer-3.0.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:db72b07027db150f468fbada4d85b3b2729a3db39178abf5c543b784c1254539"},
{url = "https://files.pythonhosted.org/packages/f1/14/ed5990189a6a25ae9f8d63e74cd0336189f9ad7e51f066ba2f6cb73e8126/charset_normalizer-3.0.1-cp36-cp36m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:f4c39b0e3eac288fedc2b43055cfc2ca7a60362d0e5e87a637beac5d801ef478"},
{url = "https://files.pythonhosted.org/packages/f1/ff/9a1c65d8c44958f45ae40cd558ab63bd499a35198a2014e13c0887c07ed1/charset_normalizer-3.0.1-cp38-cp38-musllinux_1_1_s390x.whl", hash = "sha256:a152f5f33d64a6be73f1d30c9cc82dfc73cec6477ec268e7c6e4c7d23c2d2291"},
{url = "https://files.pythonhosted.org/packages/f5/84/cac681144a28114bd9e40d3cdbfd961c14ecc2b56f1baec2094afd6744c7/charset_normalizer-3.0.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:3fc1c4a2ffd64890aebdb3f97e1278b0cc72579a08ca4de8cd2c04799a3a22be"},
{url = "https://files.pythonhosted.org/packages/f5/ec/a9bed59079bd0267d34ada58a4048c96a59b3621e7f586ea85840d41831d/charset_normalizer-3.0.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:356541bf4381fa35856dafa6a965916e54bed415ad8a24ee6de6e37deccf2786"},
{url = "https://files.pythonhosted.org/packages/fc/64/443267b7824283b3e0e33cee4240c079939a970c2c9a5a3164fc988d690b/charset_normalizer-3.0.1-cp37-cp37m-win_amd64.whl", hash = "sha256:2c03cc56021a4bd59be889c2b9257dae13bf55041a3372d3295416f86b295fb5"},
]
"click 8.1.3" = [
{url = "https://files.pythonhosted.org/packages/59/87/84326af34517fca8c58418d148f2403df25303e02736832403587318e9e8/click-8.1.3.tar.gz", hash = "sha256:7682dc8afb30297001674575ea00d1814d808d6a36af415a82bd481d37ba7b8e"},
{url = "https://files.pythonhosted.org/packages/c2/f1/df59e28c642d583f7dacffb1e0965d0e00b218e0186d7858ac5233dce840/click-8.1.3-py3-none-any.whl", hash = "sha256:bb4d8133cb15a609f44e8213d9b391b0809795062913b383c62be0ee95b1db48"},
]
"colorama 0.4.6" = [
{url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6"},
{url = "https://files.pythonhosted.org/packages/d8/53/6f443c9a4a8358a93a6792e2acffb9d9d5cb0a5cfd8802644b7b1c9a02e4/colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"},
]
"dbus-next 0.2.3" = [
{url = "https://files.pythonhosted.org/packages/ce/45/6a40fbe886d60a8c26f480e7d12535502b5ba123814b3b9a0b002ebca198/dbus_next-0.2.3.tar.gz", hash = "sha256:f4eae26909332ada528c0a3549dda8d4f088f9b365153952a408e28023a626a5"},
{url = "https://files.pythonhosted.org/packages/d2/fc/c0a3f4c4eaa5a22fbef91713474666e13d0ea2a69c84532579490a9f2cc8/dbus_next-0.2.3-py3-none-any.whl", hash = "sha256:58948f9aff9db08316734c0be2a120f6dc502124d9642f55e90ac82ffb16a18b"},
]
"distro 1.8.0" = [
{url = "https://files.pythonhosted.org/packages/4b/89/eaa3a3587ebf8bed93e45aa79be8c2af77d50790d15b53f6dfc85b57f398/distro-1.8.0.tar.gz", hash = "sha256:02e111d1dc6a50abb8eed6bf31c3e48ed8b0830d1ea2a1b78c61765c2513fdd8"},
{url = "https://files.pythonhosted.org/packages/f4/2c/c90a3adaf0ddb70afe193f5ebfb539612af57cffe677c3126be533df3098/distro-1.8.0-py3-none-any.whl", hash = "sha256:99522ca3e365cac527b44bde033f64c6945d90eb9f769703caaec52b09bbd3ff"},
]
"idna 3.4" = [
{url = "https://files.pythonhosted.org/packages/8b/e1/43beb3d38dba6cb420cefa297822eac205a277ab43e5ba5d5c46faf96438/idna-3.4.tar.gz", hash = "sha256:814f528e8dead7d329833b91c5faa87d60bf71824cd12a7530b5526063d02cb4"},
{url = "https://files.pythonhosted.org/packages/fc/34/3030de6f1370931b9dbb4dad48f6ab1015ab1d32447850b9fc94e60097be/idna-3.4-py3-none-any.whl", hash = "sha256:90b77e79eaa3eba6de819a0c442c0b4ceefc341a7a2ab77d7562bf49f425c5c2"},
]
"ifaddr 0.2.0" = [
{url = "https://files.pythonhosted.org/packages/9c/1f/19ebc343cc71a7ffa78f17018535adc5cbdd87afb31d7c34874680148b32/ifaddr-0.2.0-py3-none-any.whl", hash = "sha256:085e0305cfe6f16ab12d72e2024030f5d52674afad6911bb1eee207177b8a748"},
{url = "https://files.pythonhosted.org/packages/e8/ac/fb4c578f4a3256561548cd825646680edcadb9440f3f68add95ade1eb791/ifaddr-0.2.0.tar.gz", hash = "sha256:cc0cbfcaabf765d44595825fb96a99bb12c79716b73b44330ea38ee2b0c4aed4"},
]
"importlib-metadata 6.0.0" = [
{url = "https://files.pythonhosted.org/packages/26/a7/9da7d5b23fc98ab3d424ac2c65613d63c1f401efb84ad50f2fa27b2caab4/importlib_metadata-6.0.0-py3-none-any.whl", hash = "sha256:7efb448ec9a5e313a57655d35aa54cd3e01b7e1fbcf72dce1bf06119420f5bad"},
{url = "https://files.pythonhosted.org/packages/90/07/6397ad02d31bddf1841c9ad3ec30a693a3ff208e09c2ef45c9a8a5f85156/importlib_metadata-6.0.0.tar.gz", hash = "sha256:e354bedeb60efa6affdcc8ae121b73544a7aa74156d047311948f6d711cd378d"},
]
"inotify-simple 1.3.5" = [
{url = "https://files.pythonhosted.org/packages/51/41/59ca6011f5463d5e5eefcfed2e7fe470922d3a958b7f3aad95eda208d7d3/inotify_simple-1.3.5.tar.gz", hash = "sha256:8440ffe49c4ae81a8df57c1ae1eb4b6bfa7acb830099bfb3e305b383005cc128"},
]
"jinja2 3.1.2" = [
{url = "https://files.pythonhosted.org/packages/7a/ff/75c28576a1d900e87eb6335b063fab47a8ef3c8b4d88524c4bf78f670cce/Jinja2-3.1.2.tar.gz", hash = "sha256:31351a702a408a9e7595a8fc6150fc3f43bb6bf7e319770cbc0db9df9437e852"},
{url = "https://files.pythonhosted.org/packages/bc/c3/f068337a370801f372f2f8f6bad74a5c140f6fda3d9de154052708dd3c65/Jinja2-3.1.2-py3-none-any.whl", hash = "sha256:6088930bfe239f0e6710546ab9c19c9ef35e29792895fed6e6e31a023a182a61"},
]
"ldap3 2.9.1" = [
{url = "https://files.pythonhosted.org/packages/43/ac/96bd5464e3edbc61595d0d69989f5d9969ae411866427b2500a8e5b812c0/ldap3-2.9.1.tar.gz", hash = "sha256:f3e7fc4718e3f09dda568b57100095e0ce58633bcabbed8667ce3f8fbaa4229f"},
{url = "https://files.pythonhosted.org/packages/4e/f6/71d6ec9f18da0b2201287ce9db6afb1a1f637dedb3f0703409558981c723/ldap3-2.9.1-py2.py3-none-any.whl", hash = "sha256:5869596fc4948797020d3f03b7939da938778a0f9e2009f7a072ccf92b8e8d70"},
]
"libnacl 1.8.0" = [
{url = "https://files.pythonhosted.org/packages/9b/dd/395854871aa26b2d082d9c583a5ec807e26132029b0a5a935510b6ae515b/libnacl-1.8.0-py2.py3-none-any.whl", hash = "sha256:a2a4721e9d3d65a2630f9f904ab6624bb6f9e57ab0574244f666d1b58cea0f33"},
{url = "https://files.pythonhosted.org/packages/db/ab/1111466244a682121a86cf5360fb7c804e6c21edaf0b439bfd898f4a11fe/libnacl-1.8.0.tar.gz", hash = "sha256:f1037b85ca31fd8b02c43d66f78c2049bc58480e6a395dc9d27e6821b5fe185d"},
]
"lmdb 1.3.0" = [
{url = "https://files.pythonhosted.org/packages/19/78/bf28525ae03487162cee2e013cec3aeced349c3c2a8325a7dbfdcd61e680/lmdb-1.3.0-cp38-cp38-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:df2724bad7820114a205472994091097d0fa65a3e5fff5a8e688d123fb8c6326"},
{url = "https://files.pythonhosted.org/packages/2b/50/47b7cfe3973f787d2dc47ff3c41aac3dc37d0a10994ccd1129b18b64af68/lmdb-1.3.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5ddd590e1c7fcb395931aa3782fb89b9db4550ab2d81d006ecd239e0d462bc41"},
{url = "https://files.pythonhosted.org/packages/3c/4e/bf7177e502593ac31a6a9fd05db2d767474483cde8a1702189f9e271ffb3/lmdb-1.3.0-cp36-cp36m-macosx_10_14_x86_64.whl", hash = "sha256:eefb392f6b5cd43aada49258c5a79be11cb2c8cd3fc3e2d9319a1e0b9f906458"},
{url = "https://files.pythonhosted.org/packages/3f/31/fcdaedcbfdee59fc2a5643ced9c5af59ef54b8b11d8b40f3f420719c2b33/lmdb-1.3.0-cp310-cp310-win_amd64.whl", hash = "sha256:d6a816954d212f40fd15007cd81ab7a6bebb77436d949a6a9ae04af57fc127f3"},
{url = "https://files.pythonhosted.org/packages/4c/e2/fb76e5f8bd60fda8d6672c921fc3f024542720bc0f35fa5e1f541f00c006/lmdb-1.3.0-cp37-cp37m-macosx_10_14_x86_64.whl", hash = "sha256:008243762decf8f6c90430a9bced56290ebbcdb5e877d90e42343bb97033e494"},
{url = "https://files.pythonhosted.org/packages/4d/cf/3230b1c9b0bec406abb85a9332ba5805bdd03a1d24025c6bbcfb8ed71539/lmdb-1.3.0-cp37-cp37m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:17215a42a4b9814c383deabecb160581e4fb75d00198eef0e3cea54f230ffbea"},
{url = "https://files.pythonhosted.org/packages/50/e7/fb9f704d7db6fe10315ce22d173e2307565b62ee81df34079ca7f23d8b60/lmdb-1.3.0-cp37-cp37m-win_amd64.whl", hash = "sha256:18c69fabdaf04efaf246587739cc1062b3e57c6ef0743f5c418df89e5e7e7b9b"},
{url = "https://files.pythonhosted.org/packages/57/cc/36832bc3e04fa3a4cb61f02db0641b245d94b205ab215b967448ee36e3c9/lmdb-1.3.0-cp38-cp38-win_amd64.whl", hash = "sha256:4172fba19417d7b29409beca7d73c067b54e5d8ab1fb9b51d7b4c1445d20a167"},
{url = "https://files.pythonhosted.org/packages/5b/f5/a20bb77dced2aadc7bd45cb7a136dc748119d78d405e2bf5746ed1325fc6/lmdb-1.3.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:65334eafa5d430b18d81ebd5362559a41483c362e1931f6e1b15bab2ecb7d75d"},
{url = "https://files.pythonhosted.org/packages/60/af/f84c4dd2953e757701e2f027bc0637cce7f2784ea47297bd4d5ee98a14c9/lmdb-1.3.0-cp310-cp310-macosx_10_14_x86_64.whl", hash = "sha256:abbc439cd9fe60ffd6197009087ea885ac150017dc85384093b1d376f83f0ec4"},
{url = "https://files.pythonhosted.org/packages/62/66/764b581d5568d3f31340e970d8abc5a1c93cb65d1d0f3dd59f606bff6817/lmdb-1.3.0-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2cfa4aa9c67f8aee89b23005e98d1f3f32490b6b905fd1cb604b207cbd5755ab"},
{url = "https://files.pythonhosted.org/packages/62/b1/b53765aafa2d508285718cdc7088332d3093ce36a8c989a224413783bdd8/lmdb-1.3.0-cp35-cp35m-macosx_10_14_x86_64.whl", hash = "sha256:fa6439356e591d3249ab0e1778a6f8d8408e993f66dc911914c78208f5310309"},
{url = "https://files.pythonhosted.org/packages/65/01/ee604f15c55d72eb1216ab27eb36ca613a967ab05d6f83b44b7a36d73f29/lmdb-1.3.0-cp310-cp310-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:6260a526e4ad85b1f374a5ba9475bf369fb07e7728ea6ec57226b02c40d1976b"},
{url = "https://files.pythonhosted.org/packages/79/fb/36d8a180284d8967be737b68ef1ae163f00be8a38c1a77b840de8d6306fb/lmdb-1.3.0-pp27-pypy_73-win_amd64.whl", hash = "sha256:08f4b5129f4683802569b02581142e415c8dcc0ff07605983ec1b07804cecbad"},
{url = "https://files.pythonhosted.org/packages/7d/7d/9f45a8b64b398d0acedcfd5fe0049286b7488bf7d34a6a710520cff26d0c/lmdb-1.3.0-cp36-cp36m-win_amd64.whl", hash = "sha256:7da05d70fcc6561ac6b09e9fb1bf64b7ca294652c64c8a2889273970cee796b9"},
{url = "https://files.pythonhosted.org/packages/90/fd/788b49864b367199fe5ae97d391617b0d520645e65c9903884c10f89be2f/lmdb-1.3.0-cp39-cp39-win_amd64.whl", hash = "sha256:62ab28e3593bdc318ea2f2fa1574e5fca3b6d1f264686d773ba54a637d4f563b"},
{url = "https://files.pythonhosted.org/packages/97/47/1e73bc4b4879d1be8dfed4d1dcd139d2f8dfd0c6f63ef4ff5e132b8890e9/lmdb-1.3.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e568ae0887ae196340947d9800136e90feaed6b86a261ef01f01b2ba65fc8106"},
{url = "https://files.pythonhosted.org/packages/a3/c8/832b2310460d1eeee9d51410dcb4ce41cbe17a9eeb8eba7c4f5eb9cf8beb/lmdb-1.3.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:394df860c3f93cfd92b6f4caba785f38208cc9614c18b3803f83a2cc1695042f"},
{url = "https://files.pythonhosted.org/packages/a4/8d/e27d341de15eb9cc3755d38542cc448ced1037e0eb641e38ad66a564ff6a/lmdb-1.3.0-pp27-pypy_73-macosx_10_7_x86_64.whl", hash = "sha256:e6a704b3baced9182836c7f77b769f23856f3a8f62d0282b1bc1feaf81a86712"},
{url = "https://files.pythonhosted.org/packages/aa/4a/a404ce11f448c424994096dc7c8a85c5e317cfaec98afc6f90a814e7c706/lmdb-1.3.0-cp35-cp35m-win_amd64.whl", hash = "sha256:c6adbd6f7f9048e97f31a069e652eb51020a81e80a0ce92dbb9810d21da2409a"},
{url = "https://files.pythonhosted.org/packages/af/ad/092d8863b765ccac995ce799c725d340d81b225e50c950d3cf801dba49ef/lmdb-1.3.0-pp36-pypy36_pp73-win32.whl", hash = "sha256:f291e3f561f58dddf63a92a5a6a4b8af3a0920b6705d35e2f80e52e86ee238a2"},
{url = "https://files.pythonhosted.org/packages/bb/6b/3cec989d03e31f4b7eac453de8ab394df24eb2ee75114b9135f0e2cd9e2a/lmdb-1.3.0-cp38-cp38-macosx_10_14_x86_64.whl", hash = "sha256:41318717ab5d15ad2d6d263d34fbf614a045210f64b25e59ce734bb2105e421f"},
{url = "https://files.pythonhosted.org/packages/c5/72/109e7264a6441b4d9d0031be67776d9ef5cf69448ebec71d00a877a2babd/lmdb-1.3.0-cp27-cp27m-macosx_10_14_x86_64.whl", hash = "sha256:63cb73fe7ce9eb93d992d632c85a0476b4332670d9e6a2802b5062f603b7809f"},
{url = "https://files.pythonhosted.org/packages/d0/5b/8147d8ab13bfa57c5175803fd8796479da27298b828c95aa1d05e4b60c20/lmdb-1.3.0-cp39-cp39-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:d9103aa4908f0bca43c5911ca067d4e3d01f682dff0c0381a1239bd2bd757984"},
{url = "https://files.pythonhosted.org/packages/db/bf/1fa60f5893263ef4d0a74994104650a002d2a970b183608e5b7497836bfc/lmdb-1.3.0-cp36-cp36m-manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:5a14aca2651c3af6f0d0a6b9168200eea0c8f2d27c40b01a442f33329a6e8dff"},
{url = "https://files.pythonhosted.org/packages/ed/61/41f3c7cbd8a67202ef24fad3375ed936093a0547dc645581dd11c09581b7/lmdb-1.3.0.tar.gz", hash = "sha256:60a11efc21aaf009d06518996360eed346f6000bfc9de05114374230879f992e"},
{url = "https://files.pythonhosted.org/packages/f8/f7/4a889009d678cf7ce4e2349ed48a4f7c97c380018246e4f68b373192da75/lmdb-1.3.0-cp39-cp39-macosx_10_14_x86_64.whl", hash = "sha256:2df38115dd9428a54d59ae7c712a4c7cce0d6b1d66056de4b1a8c38718066106"},
]
"markdown 3.4.1" = [
{url = "https://files.pythonhosted.org/packages/85/7e/133e943e97a943d2f1d8bae0c5060f8ac50e6691754eb9dbe036b047a9bb/Markdown-3.4.1.tar.gz", hash = "sha256:3b809086bb6efad416156e00a0da66fe47618a5d6918dd688f53f40c8e4cfeff"},
{url = "https://files.pythonhosted.org/packages/86/be/ad281f7a3686b38dd8a307fa33210cdf2130404dfef668a37a4166d737ca/Markdown-3.4.1-py3-none-any.whl", hash = "sha256:08fb8465cffd03d10b9dd34a5c3fea908e20391a2a90b88d66362cb05beed186"},
]
"markupsafe 2.1.2" = [
{url = "https://files.pythonhosted.org/packages/02/2c/18d55e5df6a9ea33709d6c33e08cb2e07d39e20ad05d8c6fbf9c9bcafd54/MarkupSafe-2.1.2-cp310-cp310-win_amd64.whl", hash = "sha256:835fb5e38fd89328e9c81067fd642b3593c33e1e17e2fdbf77f5676abb14a156"},
{url = "https://files.pythonhosted.org/packages/04/cf/9464c3c41b7cdb8df660cda75676697e7fb49ce1be7691a1162fc88da078/MarkupSafe-2.1.2-cp311-cp311-musllinux_1_1_i686.whl", hash = "sha256:085fd3201e7b12809f9e6e9bc1e5c96a368c8523fad5afb02afe3c051ae4afcc"},
{url = "https://files.pythonhosted.org/packages/06/3b/d026c21cd1dbee89f41127e93113dcf5fa85c6660d108847760b59b3a66d/MarkupSafe-2.1.2-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:40dfd3fefbef579ee058f139733ac336312663c6706d1163b82b3003fb1925c4"},
{url = "https://files.pythonhosted.org/packages/0a/88/78cb3d95afebd183d8b04442685ab4c70cfc1138b850ba20e2a07aff2f53/MarkupSafe-2.1.2-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:65608c35bfb8a76763f37036547f7adfd09270fbdbf96608be2bead319728fcd"},
{url = "https://files.pythonhosted.org/packages/0d/15/82b108c697bec4c26c00aed6975b778cf0eac6cbb77598862b10550b7fcc/MarkupSafe-2.1.2-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:2298c859cfc5463f1b64bd55cb3e602528db6fa0f3cfd568d3605c50678f8f03"},
{url = "https://files.pythonhosted.org/packages/19/00/3b8eb0093c885576a1ce7f2263e7b8c01e55b9977433f8246f57cd81b0be/MarkupSafe-2.1.2-cp311-cp311-win32.whl", hash = "sha256:7df70907e00c970c60b9ef2938d894a9381f38e6b9db73c5be35e59d92e06625"},
{url = "https://files.pythonhosted.org/packages/1f/20/76f6337f1e7238a626ab34405ddd634636011b2ff947dcbd8995f16a7776/MarkupSafe-2.1.2-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:1bea30e9bf331f3fef67e0a3877b2288593c98a21ccb2cf29b74c581a4eb3af0"},
{url = "https://files.pythonhosted.org/packages/22/88/9c0cae2f5ada778182f2842b377dd273d6be689953345c10b165478831eb/MarkupSafe-2.1.2-cp39-cp39-win32.whl", hash = "sha256:137678c63c977754abe9086a3ec011e8fd985ab90631145dfb9294ad09c102a7"},
{url = "https://files.pythonhosted.org/packages/29/d2/243e6b860d97c18d848fc2bee2f39d102755a2b04a5ce4d018d839711b46/MarkupSafe-2.1.2-cp38-cp38-musllinux_1_1_i686.whl", hash = "sha256:8db032bf0ce9022a8e41a22598eefc802314e81b879ae093f36ce9ddf39ab1ba"},
{url = "https://files.pythonhosted.org/packages/30/3e/0a69a24adb38df83e2f6989c38d68627a5f27181c82ecaa1fd03d1236dca/MarkupSafe-2.1.2-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:ca244fa73f50a800cf8c3ebf7fd93149ec37f5cb9596aa8873ae2c1d23498601"},
{url = "https://files.pythonhosted.org/packages/34/19/64b0abc021b22766e86efee32b0e2af684c4b731ce8ac1d519c791800c13/MarkupSafe-2.1.2-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:340bea174e9761308703ae988e982005aedf427de816d1afe98147668cc03036"},
{url = "https://files.pythonhosted.org/packages/37/b2/6f4d5cac75ba6fe9f17671304fe339ea45a73c5609b5f5e652aa79c915c8/MarkupSafe-2.1.2-cp310-cp310-macosx_10_9_universal2.whl", hash = "sha256:665a36ae6f8f20a4676b53224e33d456a6f5a72657d9c83c2aa00765072f31f7"},
{url = "https://files.pythonhosted.org/packages/39/8d/5c5ce72deb8567ab48a18fbd99dc0af3dd651b6691b8570947e54a28e0f3/MarkupSafe-2.1.2-cp37-cp37m-win_amd64.whl", hash = "sha256:6d6607f98fcf17e534162f0709aaad3ab7a96032723d8ac8750ffe17ae5a0666"},
{url = "https://files.pythonhosted.org/packages/3d/66/2f636ba803fd6eb4cee7b3106ae02538d1e84a7fb7f4f8775c6528a87d31/MarkupSafe-2.1.2-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:28057e985dace2f478e042eaa15606c7efccb700797660629da387eb289b9323"},
{url = "https://files.pythonhosted.org/packages/41/54/6e88795c64ab5dcda31b06406c062c2740d1a64db18219d4e21fc90928c1/MarkupSafe-2.1.2-cp39-cp39-musllinux_1_1_i686.whl", hash = "sha256:c0a33bc9f02c2b17c3ea382f91b4db0e6cde90b63b296422a939886a7a80de1c"},
{url = "https://files.pythonhosted.org/packages/46/0c/10ee33673c5e36fa3809cf136971f81d951ca38516188ee11a965d9b2fe9/MarkupSafe-2.1.2-cp39-cp39-win_amd64.whl", hash = "sha256:0576fe974b40a400449768941d5d0858cc624e3249dfd1e0c33674e5c7ca7aed"},
{url = "https://files.pythonhosted.org/packages/48/cc/d027612e17b56088cfccd2c8e083518995fcb25a7b4f17fc146362a0499d/MarkupSafe-2.1.2-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:f8ffb705ffcf5ddd0e80b65ddf7bed7ee4f5a441ea7d3419e861a12eaf41af58"},
{url = "https://files.pythonhosted.org/packages/4b/34/dc837e5ad9e14634aac4342eb8b12a9be20a4f74f50cc0d765f7aa2fc1e3/MarkupSafe-2.1.2-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:a4abaec6ca3ad8660690236d11bfe28dfd707778e2442b45addd2f086d6ef094"},
{url = "https://files.pythonhosted.org/packages/50/41/1442b693a40eb76d835ca2016e86a01479f17d7fd8288f9830f6790e366a/MarkupSafe-2.1.2-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:b8526c6d437855442cdd3d87eede9c425c4445ea011ca38d937db299382e6fa3"},
{url = "https://files.pythonhosted.org/packages/52/36/b35c577c884ea352fc0c1eaed9ca4946ffc22cc9c3527a70408bfa9e9496/MarkupSafe-2.1.2-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:40627dcf047dadb22cd25ea7ecfe9cbf3bbbad0482ee5920b582f3809c97654f"},
{url = "https://files.pythonhosted.org/packages/56/0d/c9818629672a3368b773fa94597d79da77bdacc3186f097bb85023f785f6/MarkupSafe-2.1.2-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:0b462104ba25f1ac006fdab8b6a01ebbfbce9ed37fd37fd4acd70c67c973e460"},
{url = "https://files.pythonhosted.org/packages/5a/94/d056bf5dbadf7f4b193ee2a132b3d49ffa1602371e3847518b2982045425/MarkupSafe-2.1.2-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f2bfb563d0211ce16b63c7cb9395d2c682a23187f54c3d79bfec33e6705473c6"},
{url = "https://files.pythonhosted.org/packages/5e/f6/8eb8a5692c1986b6e863877b0b8a83628aff14e5fbfaf11d9522b532bd9d/MarkupSafe-2.1.2-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:22152d00bf4a9c7c83960521fc558f55a1adbc0631fbb00a9471e097b19d72e1"},
{url = "https://files.pythonhosted.org/packages/66/21/dadb671aade8eb67ef96e0d8f90b1bd5e8cfb6ad9d8c7fa2c870ec0c257b/MarkupSafe-2.1.2-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:55f44b440d491028addb3b88f72207d71eeebfb7b5dbf0643f7c023ae1fba619"},
{url = "https://files.pythonhosted.org/packages/76/b5/05ce70a3e31ecebcd3628cd180dc4761293aa496db85170fdc085ed2d79a/MarkupSafe-2.1.2-cp38-cp38-win32.whl", hash = "sha256:50c42830a633fa0cf9e7d27664637532791bfc31c731a87b202d2d8ac40c3ea2"},
{url = "https://files.pythonhosted.org/packages/77/26/af46880038c6eac3832e751298f1965f3a550f38d1e9ddaabd674860076b/MarkupSafe-2.1.2-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:8bca7e26c1dd751236cfb0c6c72d4ad61d986e9a41bbf76cb445f69488b2a2bd"},
{url = "https://files.pythonhosted.org/packages/78/e6/91c9a20a943ea231c59024e181c4c5480097daf132428f2272670974637f/MarkupSafe-2.1.2-cp310-cp310-win32.whl", hash = "sha256:c4a549890a45f57f1ebf99c067a4ad0cb423a05544accaf2b065246827ed9603"},
{url = "https://files.pythonhosted.org/packages/79/e2/b818bf277fa6b01244943498cb2127372c01dde5eff7682837cc72740618/MarkupSafe-2.1.2-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:da25303d91526aac3672ee6d49a2f3db2d9502a4a60b55519feb1a4c7714e07d"},
{url = "https://files.pythonhosted.org/packages/7b/0f/0e99c2f342933c43af69849a6ba63f2eef54e14c6d0e10a26470fb6b40a9/MarkupSafe-2.1.2-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:a6e40afa7f45939ca356f348c8e23048e02cb109ced1eb8420961b2f40fb373a"},
{url = "https://files.pythonhosted.org/packages/7c/e6/454df09f18e0ea34d189b447a9e1a9f66c2aa332b77fd5577ebc7ca14d42/MarkupSafe-2.1.2-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:090376d812fb6ac5f171e5938e82e7f2d7adc2b629101cec0db8b267815c85e2"},
{url = "https://files.pythonhosted.org/packages/80/64/ccb65aadd71e7685caa69a885885a673e8748525a243fb26acea37201b44/MarkupSafe-2.1.2-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:f03a532d7dee1bed20bc4884194a16160a2de9ffc6354b3878ec9682bb623c54"},
{url = "https://files.pythonhosted.org/packages/82/70/b3978786c7b576c25d84b009d2a20a11b5300d252fc3ce984e37b932e97c/MarkupSafe-2.1.2-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:2e7821bffe00aa6bd07a23913b7f4e01328c3d5cc0b40b36c0bd81d362faeb65"},
{url = "https://files.pythonhosted.org/packages/82/e3/4efcd74f10a7999783955aec36386f71082e6d7dafcc06b77b9df72b325a/MarkupSafe-2.1.2-cp39-cp39-macosx_10_9_universal2.whl", hash = "sha256:99625a92da8229df6d44335e6fcc558a5037dd0a760e11d84be2260e6f37002f"},
{url = "https://files.pythonhosted.org/packages/87/a1/d0f05a09c6c1aef89d1eea0ab0ff1ea897d4117d27f1571034a7e3ff515b/MarkupSafe-2.1.2-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cf877ab4ed6e302ec1d04952ca358b381a882fbd9d1b07cccbfd61783561f98a"},
{url = "https://files.pythonhosted.org/packages/93/ca/1c3ae0c6a5712d4ba98610cada03781ea0448436b17d1dcd4759115b15a1/MarkupSafe-2.1.2-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:d9d971ec1e79906046aa3ca266de79eac42f1dbf3612a05dc9368125952bd1a1"},
{url = "https://files.pythonhosted.org/packages/93/fa/d72f68f84f8537ee8aa3e0764d1eb11e5e025a5ca90c16e94a40f894c2fc/MarkupSafe-2.1.2-cp38-cp38-win_amd64.whl", hash = "sha256:bb06feb762bade6bf3c8b844462274db0c76acc95c52abe8dbed28ae3d44a147"},
{url = "https://files.pythonhosted.org/packages/95/7e/68018b70268fb4a2a605e2be44ab7b4dd7ce7808adae6c5ef32e34f4b55a/MarkupSafe-2.1.2.tar.gz", hash = "sha256:abcabc8c2b26036d62d4c746381a6f7cf60aafcc653198ad678306986b09450d"},
{url = "https://files.pythonhosted.org/packages/95/88/8c8cce021ac1b1eedde349c6a41f6c256da60babf95e572071361ff3f66b/MarkupSafe-2.1.2-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:63ba06c9941e46fa389d389644e2d8225e0e3e5ebcc4ff1ea8506dce646f8c8a"},
{url = "https://files.pythonhosted.org/packages/96/92/a873b4a7fa20c2e30bffe883bb560330f3b6ce03aaf278f75f96d161935b/MarkupSafe-2.1.2-cp310-cp310-musllinux_1_1_i686.whl", hash = "sha256:7e007132af78ea9df29495dbf7b5824cb71648d7133cf7848a2a5dd00d36f9ff"},
{url = "https://files.pythonhosted.org/packages/9d/80/8320f182d06a9b289b1a9f266f593feb91d3781c7e104bbe09e0c4c11439/MarkupSafe-2.1.2-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:4cf06cdc1dda95223e9d2d3c58d3b178aa5dacb35ee7e3bbac10e4e1faacb419"},
{url = "https://files.pythonhosted.org/packages/be/18/988e1913a40cc8eb725b1e073eacc130f7803a061577bdc0b9343eb3c696/MarkupSafe-2.1.2-cp37-cp37m-win32.whl", hash = "sha256:7668b52e102d0ed87cb082380a7e2e1e78737ddecdde129acadb0eccc5423859"},
{url = "https://files.pythonhosted.org/packages/c3/e5/42842a44bfd9ba2955c562b1139334a2f64cedb687e8969777fd07de42a9/MarkupSafe-2.1.2-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:f1cd098434e83e656abf198f103a8207a8187c0fc110306691a2e94a78d0abb2"},
{url = "https://files.pythonhosted.org/packages/c7/0e/22d0c8e6ee84414e251bd1bc555b2705af6b3fb99f0ba1ead2a0f51d423b/MarkupSafe-2.1.2-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:22731d79ed2eb25059ae3df1dfc9cb1546691cc41f4e3130fe6bfbc3ecbbecfa"},
{url = "https://files.pythonhosted.org/packages/cf/c1/d7596976a868fe3487212a382cc121358a53dc8e8d85ff2ee2c3d3b40f04/MarkupSafe-2.1.2-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:9cad97ab29dfc3f0249b483412c85c8ef4766d96cdf9dcf5a1e3caa3f3661cf1"},
{url = "https://files.pythonhosted.org/packages/d1/10/ff89b23d4a24051c4e4f689b79ee06f230d7e9431445e24f5dd9d9a89730/MarkupSafe-2.1.2-cp38-cp38-macosx_10_9_universal2.whl", hash = "sha256:a806db027852538d2ad7555b203300173dd1b77ba116de92da9afbc3a3be3eed"},
{url = "https://files.pythonhosted.org/packages/e3/a9/e366665c7eae59c9c9d34b747cd5a3994847719a2304e0c8dec8b604dd98/MarkupSafe-2.1.2-cp311-cp311-macosx_10_9_universal2.whl", hash = "sha256:2ec4f2d48ae59bbb9d1f9d7efb9236ab81429a764dedca114f5fdabbc3788013"},
{url = "https://files.pythonhosted.org/packages/e6/ff/d2378ca3cb3ac4a37af767b820b0f0bf3f5e9193a6acce0eefc379425c1c/MarkupSafe-2.1.2-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:608e7073dfa9e38a85d38474c082d4281f4ce276ac0010224eaba11e929dd53a"},
{url = "https://files.pythonhosted.org/packages/e9/c6/2da36728c1310f141395176556500aeedfdea8c2b02a3b72ba61b69280e8/MarkupSafe-2.1.2-cp37-cp37m-musllinux_1_1_i686.whl", hash = "sha256:a6f2fcca746e8d5910e18782f976489939d54a91f9411c32051b4aab2bd7c513"},
{url = "https://files.pythonhosted.org/packages/ea/60/2400ba59cf2465fa136487ee7299f52121a9d04b2cf8539ad43ad10e70e8/MarkupSafe-2.1.2-cp311-cp311-win_amd64.whl", hash = "sha256:e55e40ff0cc8cc5c07996915ad367fa47da6b3fc091fdadca7f5403239c5fec3"},
{url = "https://files.pythonhosted.org/packages/f9/aa/ebcd114deab08f892b1d70badda4436dbad1747f9e5b72cffb3de4c7129d/MarkupSafe-2.1.2-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:7313ce6a199651c4ed9d7e4cfb4aa56fe923b1adf9af3b420ee14e6d9a73df65"},
]
"oauthlib 3.2.2" = [
{url = "https://files.pythonhosted.org/packages/6d/fa/fbf4001037904031639e6bfbfc02badfc7e12f137a8afa254df6c4c8a670/oauthlib-3.2.2.tar.gz", hash = "sha256:9859c40929662bec5d64f34d01c99e093149682a3f38915dc0655d5a633dd918"},
{url = "https://files.pythonhosted.org/packages/7e/80/cab10959dc1faead58dc8384a781dfbf93cb4d33d50988f7a69f1b7c9bbe/oauthlib-3.2.2-py3-none-any.whl", hash = "sha256:8139f29aac13e25d502680e9e19963e83f16838d48a0d71c287fe40e7067fbca"},
]
"paho-mqtt 1.6.1" = [
{url = "https://files.pythonhosted.org/packages/f8/dd/4b75dcba025f8647bc9862ac17299e0d7d12d3beadbf026d8c8d74215c12/paho-mqtt-1.6.1.tar.gz", hash = "sha256:2a8291c81623aec00372b5a85558a372c747cbca8e9934dfe218638b8eefc26f"},
]
"pillow 9.3.0" = [
{url = "https://files.pythonhosted.org/packages/00/73/000575ca7b7635ecd4075e71925b71f2648300d725b6c9a1f969fe2d5a87/Pillow-9.3.0-cp37-cp37m-macosx_10_10_x86_64.whl", hash = "sha256:772a91fc0e03eaf922c63badeca75e91baa80fe2f5f87bdaed4280662aad25c9"},
{url = "https://files.pythonhosted.org/packages/06/2f/c17a2d559009b875f7da804a3a4e0f47baca6df2dfedb29a1df641c51e1a/Pillow-9.3.0-pp38-pypy38_pp73-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:12ce4932caf2ddf3e41d17fc9c02d67126935a44b86df6a206cf0d7161548627"},
{url = "https://files.pythonhosted.org/packages/0d/87/f696d8464c949c5a7ac133c8b7297a4243e0319fd29ae3a90b4ac90f0a5b/Pillow-9.3.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:7db8b751ad307d7cf238f02101e8e36a128a6cb199326e867d1398067381bff4"},
{url = "https://files.pythonhosted.org/packages/15/13/232be66adb8482f0636b3f3e254d9e18d7093bd1848b3610ffaf72717924/Pillow-9.3.0-cp310-cp310-manylinux_2_28_aarch64.whl", hash = "sha256:829f97c8e258593b9daa80638aee3789b7df9da5cf1336035016d76f03b8860c"},
{url = "https://files.pythonhosted.org/packages/16/11/da8d395299ca166aa56d9436e26fe8440e5443471de16ccd9a1d06f5993a/Pillow-9.3.0.tar.gz", hash = "sha256:c935a22a557a560108d780f9a0fc426dd7459940dc54faa49d83249c8d3e760f"},
{url = "https://files.pythonhosted.org/packages/1d/15/054644ecbed79d3af017a56eaabd13bf712b21c3a667b8a67a335174f4b7/Pillow-9.3.0-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:89dca0ce00a2b49024df6325925555d406b14aa3efc2f752dbb5940c52c56b11"},
{url = "https://files.pythonhosted.org/packages/23/b3/20f97e1bacd02b89953b50b2502be1b10e01d36a0618fb197e4a055e50f4/Pillow-9.3.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:68943d632f1f9e3dce98908e873b3a090f6cba1cbb1b892a9e8d97c938871fbe"},
{url = "https://files.pythonhosted.org/packages/26/d6/9355d59a2ee9406e4d5129ff0ff99835e7f6adb6133815fab2099e1879b5/Pillow-9.3.0-cp310-cp310-macosx_10_10_x86_64.whl", hash = "sha256:0b7257127d646ff8676ec8a15520013a698d1fdc48bc2a79ba4e53df792526f2"},
{url = "https://files.pythonhosted.org/packages/2c/3d/36cd1f6c04ab30ab7e6bc8d17a4337fc29fa5b35ebd4c520d916ce7e39e6/Pillow-9.3.0-cp38-cp38-macosx_10_10_x86_64.whl", hash = "sha256:b03ae6f1a1878233ac620c98f3459f79fd77c7e3c2b20d460284e1fb370557d4"},
{url = "https://files.pythonhosted.org/packages/2c/74/109e3d1fd2847c19c556fe4ce9b3f4aac2147b56c7b5d0924ae9586d2a47/Pillow-9.3.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b9a65733d103311331875c1dca05cb4606997fd33d6acfed695b1232ba1df193"},
{url = "https://files.pythonhosted.org/packages/2e/c8/03495501bb9beabf34979781b14cc625f39cbd8ff5310a93a85e45987590/Pillow-9.3.0-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:4390e9ce199fc1951fcfa65795f239a8a4944117b5935a9317fb320e7767b40f"},
{url = "https://files.pythonhosted.org/packages/2f/73/ec6b3e3f6b311cf1468eafc92a890f690a2cacac0cfd0f1bcc2b891d1334/Pillow-9.3.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:af0372acb5d3598f36ec0914deed2a63f6bcdb7b606da04dc19a88d31bf0c05b"},
{url = "https://files.pythonhosted.org/packages/39/5e/585dfbe0eb4660ea3ee082289625f94e402239282458c4bf78ecc84fbb93/Pillow-9.3.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:40e1ce476a7804b0fb74bcfa80b0a2206ea6a882938eaba917f7a0f004b42502"},
{url = "https://files.pythonhosted.org/packages/40/57/c8695a77561a83bd39eba30daf4d894b0b910aad55e2b60f0ef1b1b5205c/Pillow-9.3.0-cp310-cp310-win_amd64.whl", hash = "sha256:9f47eabcd2ded7698106b05c2c338672d16a6f2a485e74481f524e2a23c2794b"},
{url = "https://files.pythonhosted.org/packages/41/e9/7bae68c360de8d1e7e32aeab252c6dc9336c0d779c9ad5e24ce475d523fd/Pillow-9.3.0-pp37-pypy37_pp73-macosx_10_10_x86_64.whl", hash = "sha256:ab388aaa3f6ce52ac1cb8e122c4bd46657c15905904b3120a6248b5b8b0bc228"},
{url = "https://files.pythonhosted.org/packages/47/b2/6e5fc952713bfee71c5e25e7917b18207b6f445d81746008b14d9c80a91b/Pillow-9.3.0-cp38-cp38-manylinux_2_28_aarch64.whl", hash = "sha256:15c42fb9dea42465dfd902fb0ecf584b8848ceb28b41ee2b58f866411be33f07"},
{url = "https://files.pythonhosted.org/packages/48/92/820b43fcb333fe7f4cf726ed3c0cfcfd062f65b8fd23c0e6972a6107f440/Pillow-9.3.0-pp38-pypy38_pp73-macosx_10_10_x86_64.whl", hash = "sha256:b59430236b8e58840a0dfb4099a0e8717ffb779c952426a69ae435ca1f57210c"},
{url = "https://files.pythonhosted.org/packages/4b/f9/2fa7d6cce0b9867ec3917878d03d5298d7a88522ed7dadc6cac4642bce8b/Pillow-9.3.0-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bca31dd6014cb8b0b2db1e46081b0ca7d936f856da3b39744aef499db5d84d02"},
{url = "https://files.pythonhosted.org/packages/4e/8c/84131e85d4ebd600a823fad1707157d55055a7ea80ce6c8c2f6e2de93f2c/Pillow-9.3.0-cp38-cp38-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a0a06a052c5f37b4ed81c613a455a81f9a3a69429b4fd7bb913c3fa98abefc20"},
{url = "https://files.pythonhosted.org/packages/56/02/2c8fde18b251c6ce2061b23b4fa04f3e71d386c725a09753bad19649e1b1/Pillow-9.3.0-cp38-cp38-manylinux_2_28_x86_64.whl", hash = "sha256:51e0e543a33ed92db9f5ef69a0356e0b1a7a6b6a71b80df99f1d181ae5875636"},
{url = "https://files.pythonhosted.org/packages/5b/48/1e4437f90c0531c0a8f5c5b1e793e0f234fe8203019de04001213b4fb38e/Pillow-9.3.0-cp311-cp311-manylinux_2_28_x86_64.whl", hash = "sha256:90fb88843d3902fe7c9586d439d1e8c05258f41da473952aa8b328d8b907498c"},
{url = "https://files.pythonhosted.org/packages/5f/1e/8a26e1ff2064b665f3923a727cb9240919cdcdce303e4800729635aefc40/Pillow-9.3.0-cp39-cp39-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b0915e734b33a474d76c28e07292f196cdf2a590a0d25bcc06e64e545f2d146c"},
{url = "https://files.pythonhosted.org/packages/5f/71/ad106c6e3a28f7ff81b2e172a05c158181b61de2a6292896355f0e50f46c/Pillow-9.3.0-pp37-pypy37_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:c7025dce65566eb6e89f56c9509d4f628fddcedb131d9465cacd3d8bac337e7e"},
{url = "https://files.pythonhosted.org/packages/6c/a8/3cb2d902c4094b6ad06f069b937c2696fd47c5fc02da107e33470f468534/Pillow-9.3.0-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:3dd6caf940756101205dffc5367babf288a30043d35f80936f9bfb37f8355b32"},
{url = "https://files.pythonhosted.org/packages/6d/d2/610687610050eb3ce0ebdd0a3f87d4bb3f1637a89f9fe00060a080a167da/Pillow-9.3.0-1-cp37-cp37m-win32.whl", hash = "sha256:e6ea6b856a74d560d9326c0f5895ef8050126acfdc7ca08ad703eb0081e82b74"},
{url = "https://files.pythonhosted.org/packages/6f/64/3acfbffd532ec2e82f69d4f22de9c29197540ae61926f5b7072654281e91/Pillow-9.3.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:afa4107d1b306cdf8953edde0534562607fe8811b6c4d9a486298ad31de733b2"},
{url = "https://files.pythonhosted.org/packages/77/56/bb8dc927b3c44df0ca938b4a17b08c59ef5e1e7cc06300bddf20d4e2935f/Pillow-9.3.0-cp38-cp38-win_amd64.whl", hash = "sha256:276a5ca930c913f714e372b2591a22c4bd3b81a418c0f6635ba832daec1cbcfc"},
{url = "https://files.pythonhosted.org/packages/78/8c/ae0c7cfb6cae4eb0946b7369258f78e3104c22eeffda45ad6228bc0838f5/Pillow-9.3.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:3033fbe1feb1b59394615a1cafaee85e49d01b51d54de0cbf6aa8e64182518a1"},
{url = "https://files.pythonhosted.org/packages/88/9f/012551c5a9d8b4d0304b66d16119b9c79bac052e0b0bd37de29b64c1bf0c/Pillow-9.3.0-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:073adb2ae23431d3b9bcbcff3fe698b62ed47211d0716b067385538a1b0f28b8"},
{url = "https://files.pythonhosted.org/packages/8a/e8/124718316b3f4f9fa24e4b7e915d8e02d58d43a5e3c44fcbceef17d60647/Pillow-9.3.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:b90f7616ea170e92820775ed47e136208e04c967271c9ef615b6fbd08d9af0e3"},
{url = "https://files.pythonhosted.org/packages/a0/6c/6e11abff7f944b51dbeea1bdfe14ad21976858e822ef667fa4eb82ec6f7c/Pillow-9.3.0-cp37-cp37m-win_amd64.whl", hash = "sha256:41e0051336807468be450d52b8edd12ac60bebaa97fe10c8b660f116e50b30e4"},
{url = "https://files.pythonhosted.org/packages/a1/81/10f4f9665ce366c7501141c973c755cd5c9ebe577886ebfa7ca3e9a115f0/Pillow-9.3.0-cp38-cp38-win32.whl", hash = "sha256:f1ff2ee69f10f13a9596480335f406dd1f70c3650349e2be67ca3139280cade0"},
{url = "https://files.pythonhosted.org/packages/a7/9e/8acd4d170596fa876b0baaae3542de3b6d0a709b4652ce78285aff59e849/Pillow-9.3.0-cp37-cp37m-win32.whl", hash = "sha256:82409ffe29d70fd733ff3c1025a602abb3e67405d41b9403b00b01debc4c9a29"},
{url = "https://files.pythonhosted.org/packages/ac/0b/cb7ecd88cea2422818057db720966bbb56bbcec3b359f4a5cafdf737d9e5/Pillow-9.3.0-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:9aaa107275d8527e9d6e7670b64aabaaa36e5b6bd71a1015ddd21da0d4e06448"},
{url = "https://files.pythonhosted.org/packages/af/7f/c5f7a35fd7053a4aee79c41fc4b125281745577c6ce3445e57ed8b4eff56/Pillow-9.3.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2e0918e03aa0c72ea56edbb00d4d664294815aa11291a11504a377ea018330d3"},
{url = "https://files.pythonhosted.org/packages/b7/34/7a88f5ec5f26ac68d3d7a158c67c0a610a4e6b6d22c35266d0e715485b09/Pillow-9.3.0-cp37-cp37m-manylinux_2_28_aarch64.whl", hash = "sha256:6c738585d7a9961d8c2821a1eb3dcb978d14e238be3d70f0a706f7fa9316946b"},
{url = "https://files.pythonhosted.org/packages/b9/b8/3e2c23766019a9a03ee26ac6b7af9392aba8574806ce10e5074733987240/Pillow-9.3.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:1c7c8ae3864846fc95f4611c78129301e203aaa2af813b703c55d10cc1628535"},
{url = "https://files.pythonhosted.org/packages/bb/0e/83dd785dff8d62b4d663391ac62390ffadfcdfa4bd11959742f90d02127c/Pillow-9.3.0-cp39-cp39-win32.whl", hash = "sha256:bac18ab8d2d1e6b4ce25e3424f709aceef668347db8637c2296bcf41acb7cf48"},
{url = "https://files.pythonhosted.org/packages/bc/28/0bcf18f0c22cd89626ee2e071edbe5736d54f9031fe986ae94389776864b/Pillow-9.3.0-cp310-cp310-win32.whl", hash = "sha256:655a83b0058ba47c7c52e4e2df5ecf484c1b0b0349805896dd350cbc416bdd91"},
{url = "https://files.pythonhosted.org/packages/be/3e/a757fd2fdd5814aa0e9e1e838f79d33e0098e10a2e3afb7acdcb72278290/Pillow-9.3.0-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:03150abd92771742d4a8cd6f2fa6246d847dcd2e332a18d0c15cc75bf6703040"},
{url = "https://files.pythonhosted.org/packages/c0/47/4023dab2d77ea3f687939770b06e0c191b4a5a20590f158a6e8dbb03e357/Pillow-9.3.0-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:77ec3e7be99629898c9a6d24a09de089fa5356ee408cdffffe62d67bb75fdd72"},
{url = "https://files.pythonhosted.org/packages/c0/8f/dfa473f3a6241bff91ae8bb905bd0afceb827f37de2917a94b5c4b1112bf/Pillow-9.3.0-cp39-cp39-win_amd64.whl", hash = "sha256:b472b5ea442148d1c3e2209f20f1e0bb0eb556538690fa70b5e1f79fa0ba8dc2"},
{url = "https://files.pythonhosted.org/packages/c1/c3/be8222fce0553e05264bfe66f2cc73483567b961f144acef88753fba9c6c/Pillow-9.3.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:5d77adcd56a42d00cc1be30843d3426aa4e660cab4a61021dc84467123f7a00c"},
{url = "https://files.pythonhosted.org/packages/c2/1d/5d0fd887bb790a42a9efb7fe742358f1eae332ee3120a7d4f79ee37358c9/Pillow-9.3.0-cp311-cp311-macosx_10_10_x86_64.whl", hash = "sha256:57751894f6618fd4308ed8e0c36c333e2f5469744c34729a27532b3db106ee20"},
{url = "https://files.pythonhosted.org/packages/c8/7c/f5fe5b37b6a8f2218db98f33d2278f2900e0fc4ef019cd4d9e522d6e3206/Pillow-9.3.0-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ae5331c23ce118c53b172fa64a4c037eb83c9165aba3a7ba9ddd3ec9fa64a699"},
{url = "https://files.pythonhosted.org/packages/c9/b8/27c526c45f482450a53c0faab6c0c4baf9cddee0a8f879a8526f7dd8adf0/Pillow-9.3.0-cp37-cp37m-manylinux_2_28_x86_64.whl", hash = "sha256:828989c45c245518065a110434246c44a56a8b2b2f6347d1409c787e6e4651ee"},
{url = "https://files.pythonhosted.org/packages/ca/97/9677bf1d97c408779e5940b89675e38a8ebe8bcc9dbae8adfc9e7080a314/Pillow-9.3.0-cp39-cp39-macosx_10_10_x86_64.whl", hash = "sha256:73bd195e43f3fadecfc50c682f5055ec32ee2c933243cafbfdec69ab1aa87cad"},
{url = "https://files.pythonhosted.org/packages/cf/22/fed65d07e5e7b19cc608754e940a9b101bebe78cb6cd9d764639717848a4/Pillow-9.3.0-pp37-pypy37_pp73-win_amd64.whl", hash = "sha256:ebf2029c1f464c59b8bdbe5143c79fa2045a581ac53679733d3a91d400ff9efb"},
{url = "https://files.pythonhosted.org/packages/d0/ae/b5e8750a7e745926e2227a43766d905c8c6a0f03739c7aec5aea9e975355/Pillow-9.3.0-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:871b72c3643e516db4ecf20efe735deb27fe30ca17800e661d769faab45a18d7"},
{url = "https://files.pythonhosted.org/packages/d1/6f/b5e87428a5566563b6d661824c694bbc4b0386aed1c939b9aec47d9ee573/Pillow-9.3.0-cp311-cp311-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:22b012ea2d065fd163ca096f4e37e47cd8b59cf4b0fd47bfca6abb93df70b34c"},
{url = "https://files.pythonhosted.org/packages/d4/0d/e8f6ed8e2328007020bb242a0443d925f23ee06d059486c5f1308f2a5e26/Pillow-9.3.0-cp311-cp311-win_amd64.whl", hash = "sha256:18498994b29e1cf86d505edcb7edbe814d133d2232d256db8c7a8ceb34d18cef"},
{url = "https://files.pythonhosted.org/packages/d5/31/b026f9f7c87adf8027f51f98f392f6558982485b7202af5f9276492b2141/Pillow-9.3.0-1-cp37-cp37m-win_amd64.whl", hash = "sha256:32a44128c4bdca7f31de5be641187367fe2a450ad83b833ef78910397db491aa"},
{url = "https://files.pythonhosted.org/packages/d5/79/191ea841f818aba4eb9783b9f91a3c16c51deff7326f5a2f47de54959a28/Pillow-9.3.0-pp37-pypy37_pp73-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:dbb8e7f2abee51cef77673be97760abff1674ed32847ce04b4af90f610144c7b"},
{url = "https://files.pythonhosted.org/packages/d6/be/996d629efd03aa305472a17183fcdfe2dd8529acea767d0ba2242d90cbfa/Pillow-9.3.0-cp310-cp310-manylinux_2_28_x86_64.whl", hash = "sha256:801ec82e4188e935c7f5e22e006d01611d6b41661bba9fe45b60e7ac1a8f84de"},
{url = "https://files.pythonhosted.org/packages/db/b0/6438c96e80d4cad5b6381ba774018de9d8eae591d65bdfd80e3ad630928a/Pillow-9.3.0-cp39-cp39-manylinux_2_28_x86_64.whl", hash = "sha256:97aabc5c50312afa5e0a2b07c17d4ac5e865b250986f8afe2b02d772567a380c"},
{url = "https://files.pythonhosted.org/packages/dc/20/30e5ea4ecb35b36d9bc4ff4e8edc048e017a8e3d2e087a512b0622bfdde3/Pillow-9.3.0-cp311-cp311-win32.whl", hash = "sha256:3168434d303babf495d4ba58fc22d6604f6e2afb97adc6a423e917dab828939c"},
{url = "https://files.pythonhosted.org/packages/e0/59/74d88751801101259abd695f77c44b97a828b6a4e7981a79a75d2c3379ae/Pillow-9.3.0-cp311-cp311-manylinux_2_28_aarch64.whl", hash = "sha256:502526a2cbfa431d9fc2a079bdd9061a2397b842bb6bc4239bb176da00993812"},
{url = "https://files.pythonhosted.org/packages/ec/4f/bc65f543b4d774d6c888cb0936a8b91cf7c5fbb25e16f923e332822b279b/Pillow-9.3.0-cp37-cp37m-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b4012d06c846dc2b80651b120e2cdd787b013deb39c09f407727ba90015c684f"},
{url = "https://files.pythonhosted.org/packages/f1/e4/2f7e4efeb79ab0a2c5ecba320b2e5a3aad7a49cc543407f4c1268ed804bb/Pillow-9.3.0-pp38-pypy38_pp73-manylinux_2_28_x86_64.whl", hash = "sha256:0b07fffc13f474264c336298d1b4ce01d9c5a011415b79d4ee5527bb69ae6f65"},
{url = "https://files.pythonhosted.org/packages/f7/11/763c3992c3e6d00e9f6de81b0d721306757bb7201155d135a16032460943/Pillow-9.3.0-cp39-cp39-manylinux_2_28_aarch64.whl", hash = "sha256:ad58d27a5b0262c0c19b47d54c5802db9b34d38bbf886665b626aff83c74bacd"},
{url = "https://files.pythonhosted.org/packages/fc/12/32101461796addca02fd14dc4d2b76068a2cbf895002ed668550caf3fcc1/Pillow-9.3.0-cp310-cp310-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:be55f8457cd1eac957af0c3f5ece7bc3f033f89b114ef30f710882717670b2a8"},
]
"preprocess-cancellation 0.2.0" = [
{url = "https://files.pythonhosted.org/packages/64/45/8043211de9ecddf6c25fdd743abb168b198a4ee5e417012ec8f10c6ac91f/preprocess_cancellation-0.2.0-py3-none-any.whl", hash = "sha256:936e2d6f95eaf1c0dd8a00d4c9a0663fbb3ea9a6504bde36aa63509e079d9ee7"},
{url = "https://files.pythonhosted.org/packages/96/02/c8bd237196ca3ec99b0757744e591b3d7c64d7269c991bb7ca50008b6f8d/preprocess_cancellation-0.2.0.tar.gz", hash = "sha256:eb68494e35c0a1fe83716f2a14e12b3e1cdedf9458752be1cace00f944d90760"},
]
"pyasn1 0.4.8" = [
{url = "https://files.pythonhosted.org/packages/62/1e/a94a8d635fa3ce4cfc7f506003548d0a2447ae76fd5ca53932970fe3053f/pyasn1-0.4.8-py2.py3-none-any.whl", hash = "sha256:39c7e2ec30515947ff4e87fb6f456dfc6e84857d34be479c9d4a4ba4bf46aa5d"},
{url = "https://files.pythonhosted.org/packages/a4/db/fffec68299e6d7bad3d504147f9094830b704527a7fc098b721d38cc7fa7/pyasn1-0.4.8.tar.gz", hash = "sha256:aef77c9fb94a3ac588e87841208bdec464471d9871bd5050a287cc9a475cd0ba"},
]
"pyserial 3.4" = [
{url = "https://files.pythonhosted.org/packages/0d/e4/2a744dd9e3be04a0c0907414e2a01a7c88bb3915cbe3c8cc06e209f59c30/pyserial-3.4-py2.py3-none-any.whl", hash = "sha256:e0770fadba80c31013896c7e6ef703f72e7834965954a78e71a3049488d4d7d8"},
{url = "https://files.pythonhosted.org/packages/cc/74/11b04703ec416717b247d789103277269d567db575d2fd88f25d9767fe3d/pyserial-3.4.tar.gz", hash = "sha256:6e2d401fdee0eab996cf734e67773a0143b932772ca8b42451440cfed942c627"},
]
"pyserial-asyncio 0.6" = [
{url = "https://files.pythonhosted.org/packages/27/24/c820cf15f87f7b164e83710c1852d4f900d9793961579e5ef64189bc0c10/pyserial_asyncio-0.6-py3-none-any.whl", hash = "sha256:de9337922619421b62b9b1a84048634b3ac520e1d690a674ed246a2af7ce1fc5"},
{url = "https://files.pythonhosted.org/packages/4a/9a/8477699dcbc1882ea51dcff4d3c25aa3f2063ed8f7d7a849fd8f610506b6/pyserial-asyncio-0.6.tar.gz", hash = "sha256:b6032923e05e9d75ec17a5af9a98429c46d2839adfaf80604d52e0faacd7a32f"},
]
"pyyaml 6.0" = [
{url = "https://files.pythonhosted.org/packages/02/25/6ba9f6bb50a3d4fbe22c1a02554dc670682a07c8701d1716d19ddea2c940/PyYAML-6.0-cp310-cp310-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:f84fbc98b019fef2ee9a1cb3ce93e3187a6df0b2538a651bfb890254ba9f90b5"},
{url = "https://files.pythonhosted.org/packages/08/f4/ffa743f860f34a5e8c60abaaa686f82c9ac7a2b50e5a1c3b1eb564d59159/PyYAML-6.0-cp39-cp39-win_amd64.whl", hash = "sha256:b3d267842bf12586ba6c734f89d1f5b871df0273157918b0ccefa29deb05c21c"},
{url = "https://files.pythonhosted.org/packages/0f/93/5f81d1925ce3b531f5ff215376445ec220887cd1c9a8bde23759554dbdfd/PyYAML-6.0-cp310-cp310-win32.whl", hash = "sha256:2cd5df3de48857ed0544b34e2d40e9fac445930039f3cfe4bcc592a1f836d513"},
{url = "https://files.pythonhosted.org/packages/12/fc/a4d5a7554e0067677823f7265cb3ae22aed8a238560b5133b58cda252dad/PyYAML-6.0-cp39-cp39-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:40527857252b61eacd1d9af500c3337ba8deb8fc298940291486c465c8b46ec0"},
{url = "https://files.pythonhosted.org/packages/21/67/b42191239c5650c9e419c4a08a7a022bbf1abf55b0391c380a72c3af5462/PyYAML-6.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:d67d839ede4ed1b28a4e8909735fc992a923cdb84e618544973d7dfc71540803"},
{url = "https://files.pythonhosted.org/packages/2e/b3/13dfd4eeb5e4b2d686b6d1822b40702e991bf3a4194ca5cbcce8d43749db/PyYAML-6.0-cp39-cp39-win32.whl", hash = "sha256:b5b9eccad747aabaaffbc6064800670f0c297e52c12754eb1d976c57e4f74dcb"},
{url = "https://files.pythonhosted.org/packages/36/2b/61d51a2c4f25ef062ae3f74576b01638bebad5e045f747ff12643df63844/PyYAML-6.0.tar.gz", hash = "sha256:68fb519c14306fec9720a2a5b45bc9f0c8d1b9c72adf45c37baedfcd949c35a2"},
{url = "https://files.pythonhosted.org/packages/44/e5/4fea13230bcebf24b28c0efd774a2dd65a0937a2d39e94a4503438b078ed/PyYAML-6.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:d4db7c7aef085872ef65a8fd7d6d09a14ae91f691dec3e87ee5ee0539d516f53"},
{url = "https://files.pythonhosted.org/packages/4d/7d/c2ab8da648cd2b937de11fb35649b127adab4851cbeaf5fd9b60a2dab0f7/PyYAML-6.0-cp36-cp36m-win32.whl", hash = "sha256:0283c35a6a9fbf047493e3a0ce8d79ef5030852c51e9d911a27badfde0605293"},
{url = "https://files.pythonhosted.org/packages/55/e3/507a92589994a5b3c3d7f2a7a066339d6ff61c5c839bae56f7eff03d9c7b/PyYAML-6.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:897b80890765f037df3403d22bab41627ca8811ae55e9a722fd0392850ec4d86"},
{url = "https://files.pythonhosted.org/packages/56/8f/e8b49ad21d26111493dc2d5cae4d7efbd0e2e065440665f5023515f87f64/PyYAML-6.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:432557aa2c09802be39460360ddffd48156e30721f5e8d917f01d31694216782"},
{url = "https://files.pythonhosted.org/packages/59/00/30e33fcd2a4562cd40c49c7740881009240c5cbbc0e41ca79ca4bba7c24b/PyYAML-6.0-cp311-cp311-win_amd64.whl", hash = "sha256:01b45c0191e6d66c470b6cf1b9531a771a83c1c4208272ead47a3ae4f2f603bf"},
{url = "https://files.pythonhosted.org/packages/5e/f4/7b4bb01873be78fc9fde307f38f62e380b7111862c165372cf094ca2b093/PyYAML-6.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:77f396e6ef4c73fdc33a9157446466f1cff553d979bd00ecb64385760c6babdc"},
{url = "https://files.pythonhosted.org/packages/63/6b/f5dc7942bac17192f4ef00b2d0cdd1ae45eea453d05c1944c0573debe945/PyYAML-6.0-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9fa600030013c4de8165339db93d182b9431076eb98eb40ee068700c9c813e34"},
{url = "https://files.pythonhosted.org/packages/67/d4/b95266228a25ef5bd70984c08b4efce2c035a4baa5ccafa827b266e3dc36/PyYAML-6.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:e61ceaab6f49fb8bdfaa0f92c4b57bcfbea54c09277b1b4f7ac376bfb7a7c174"},
{url = "https://files.pythonhosted.org/packages/68/3f/c027422e49433239267c62323fbc6320d6ac8d7d50cf0cb2a376260dad5f/PyYAML-6.0-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:dbad0e9d368bb989f4515da330b88a057617d16b6a8245084f1b05400f24609f"},
{url = "https://files.pythonhosted.org/packages/6c/3d/524c642f3db37e7e7ab8d13a3f8b0c72d04a619abc19100097d987378fc6/PyYAML-6.0-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:213c60cd50106436cc818accf5baa1aba61c0189ff610f64f4a3e8c6726218ba"},
{url = "https://files.pythonhosted.org/packages/74/68/3c13deaa496c14a030c431b7b828d6b343f79eb241b4848c7918091a64a2/PyYAML-6.0-cp36-cp36m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:48c346915c114f5fdb3ead70312bd042a953a8ce5c7106d5bfb1a5254e47da92"},
{url = "https://files.pythonhosted.org/packages/77/da/e845437ffe0dffae4e7562faf23a4f264d886431c5d2a2816c853288dc8e/PyYAML-6.0-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:cba8c411ef271aa037d7357a2bc8f9ee8b58b9965831d9e51baf703280dc73d3"},
{url = "https://files.pythonhosted.org/packages/7f/d9/6a0d14ac8d3b5605dc925d177c1d21ee9f0b7b39287799db1e50d197b2f4/PyYAML-6.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:afa17f5bc4d1b10afd4466fd3a44dc0e245382deca5b3c353d8b757f9e3ecb8d"},
{url = "https://files.pythonhosted.org/packages/81/59/561f7e46916b78f3c4cab8d0c307c81656f11e32c846c0c97fda0019ed76/PyYAML-6.0-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:0ce82d761c532fe4ec3f87fc45688bdd3a4c1dc5e0b4a19814b9009a29baefd4"},
{url = "https://files.pythonhosted.org/packages/89/26/0bfd7b756b34c68f8fd158b7bc762b6b1705fc1b3cebf4cdbb53fd9ea75b/PyYAML-6.0-cp36-cp36m-win_amd64.whl", hash = "sha256:07751360502caac1c067a8132d150cf3d61339af5691fe9e87803040dbc5db57"},
{url = "https://files.pythonhosted.org/packages/91/49/d46d7b15cddfa98533e89f3832f391aedf7e31f37b4d4df3a7a7855a7073/PyYAML-6.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:9df7ed3b3d2e0ecfe09e14741b857df43adb5a3ddadc919a2d94fbdf78fea53c"},
{url = "https://files.pythonhosted.org/packages/9d/f6/7e91fbb58c9ee528759aea5892e062cccb426720c5830ddcce92eba00ff1/PyYAML-6.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:819b3830a1543db06c4d4b865e70ded25be52a2e0631ccd2f6a47a2822f2fd7c"},
{url = "https://files.pythonhosted.org/packages/a4/ba/e508fc780e3c94c12753a54fe8f74de535741a10d33b29a576a9bec03500/PyYAML-6.0-cp38-cp38-win32.whl", hash = "sha256:d4eccecf9adf6fbcc6861a38015c2a64f38b9d94838ac1810a9023a0609e1b78"},
{url = "https://files.pythonhosted.org/packages/a4/e6/4d7a01bc0730c8f958a62d6a4c4f3df23b6139ad68c132b168970d84f192/PyYAML-6.0-cp37-cp37m-win32.whl", hash = "sha256:c5687b8d43cf58545ade1fe3e055f70eac7a5a1a0bf42824308d868289a95737"},
{url = "https://files.pythonhosted.org/packages/a8/32/1bbe38477fb23f1d83041fefeabf93ef1cd6f0efcf44c221519507315d92/PyYAML-6.0-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:50602afada6d6cbfad699b0c7bb50d5ccffa7e46a3d738092afddc1f9758427f"},
{url = "https://files.pythonhosted.org/packages/a8/5b/c4d674846ea4b07ee239fbf6010bcc427c4e4552ba5655b446e36b9a40a7/PyYAML-6.0-cp38-cp38-win_amd64.whl", hash = "sha256:1e4747bc279b4f613a09eb64bba2ba602d8a6664c6ce6396a4d0cd413a50ce07"},
{url = "https://files.pythonhosted.org/packages/b3/85/79b9e5b4e8d3c0ac657f4e8617713cca8408f6cdc65d2ee6554217cedff1/PyYAML-6.0-cp36-cp36m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:98c4d36e99714e55cfbaaee6dd5badbc9a1ec339ebfc3b1f52e293aee6bb71a4"},
{url = "https://files.pythonhosted.org/packages/b7/09/2f6f4851bbca08642fef087bade095edc3c47f28d1e7bff6b20de5262a77/PyYAML-6.0-cp310-cp310-win_amd64.whl", hash = "sha256:daf496c58a8c52083df09b80c860005194014c3698698d1a57cbcfa182142a3a"},
{url = "https://files.pythonhosted.org/packages/cb/5f/05dd91f5046e2256e35d885f3b8f0f280148568f08e1bf20421887523e9a/PyYAML-6.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:81957921f441d50af23654aa6c5e5eaf9b06aba7f0a19c18a538dc7ef291c5a1"},
{url = "https://files.pythonhosted.org/packages/d1/c0/4fe04181b0210ee2647cfbb89ecd10a36eef89f10d8aca6a192c201bbe58/PyYAML-6.0-cp37-cp37m-win_amd64.whl", hash = "sha256:d15a181d1ecd0d4270dc32edb46f7cb7733c7c508857278d3d378d14d606db2d"},
{url = "https://files.pythonhosted.org/packages/d7/42/7ad4b6d67a16229496d4f6e74201bdbebcf4bc1e87d5a70c9297d4961bd2/PyYAML-6.0-cp38-cp38-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:277a0ef2981ca40581a47093e9e2d13b3f1fbbeffae064c1d21bfceba2030287"},
{url = "https://files.pythonhosted.org/packages/db/4e/74bc723f2d22677387ab90cd9139e62874d14211be7172ed8c9f9a7c81a9/PyYAML-6.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:0b4624f379dab24d3725ffde76559cff63d9ec94e1736b556dacdfebe5ab6d4b"},
{url = "https://files.pythonhosted.org/packages/df/75/ee0565bbf65133e5b6ffa154db43544af96ea4c42439e6b58c1e0eb44b4e/PyYAML-6.0-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:473f9edb243cb1935ab5a084eb238d842fb8f404ed2193a915d1784b5a6b5fc0"},
{url = "https://files.pythonhosted.org/packages/eb/5f/6e6fe6904e1a9c67bc2ca5629a69e7a5a0b17f079da838bab98a1e548b25/PyYAML-6.0-cp37-cp37m-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_12_x86_64.manylinux2010_x86_64.whl", hash = "sha256:231710d57adfd809ef5d34183b8ed1eeae3f76459c18fb4a0b373ad56bedcdd9"},
{url = "https://files.pythonhosted.org/packages/ef/ad/b443cce94539e57e1a745a845f95c100ad7b97593d7e104051e43f730ecd/PyYAML-6.0-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:a80a78046a72361de73f8f395f1f1e49f956c6be882eed58505a15f3e430962b"},
{url = "https://files.pythonhosted.org/packages/f5/6f/b8b4515346af7c33d3b07cd8ca8ea0700ca72e8d7a750b2b87ac0268ca4e/PyYAML-6.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:055d937d65826939cb044fc8c9b08889e8c743fdc6a32b33e2390f66013e449b"},
{url = "https://files.pythonhosted.org/packages/f8/54/799b059314b13e1063473f76e908f44106014d18f54b16c83a16edccd5ec/PyYAML-6.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:d4b0ba9512519522b118090257be113b9468d804b19d63c71dbcf4a48fa32358"},
{url = "https://files.pythonhosted.org/packages/fc/48/531ecd926fe0a374346dd811bf1eda59a95583595bb80eadad511f3269b8/PyYAML-6.0-cp311-cp311-win32.whl", hash = "sha256:bfaef573a63ba8923503d27530362590ff4f576c626d86a9fed95822a8255fd7"},
]
"requests 2.28.2" = [
{url = "https://files.pythonhosted.org/packages/9d/ee/391076f5937f0a8cdf5e53b701ffc91753e87b07d66bae4a09aa671897bf/requests-2.28.2.tar.gz", hash = "sha256:98b1b2782e3c6c4904938b84c0eb932721069dfdb9134313beff7c83c2df24bf"},
{url = "https://files.pythonhosted.org/packages/d2/f4/274d1dbe96b41cf4e0efb70cbced278ffd61b5c7bb70338b62af94ccb25b/requests-2.28.2-py3-none-any.whl", hash = "sha256:64299f4909223da747622c030b781c0d7811e359c37124b4bd368fb8c6518baa"},
]
"requests-oauthlib 1.3.1" = [
{url = "https://files.pythonhosted.org/packages/6f/bb/5deac77a9af870143c684ab46a7934038a53eb4aa975bc0687ed6ca2c610/requests_oauthlib-1.3.1-py2.py3-none-any.whl", hash = "sha256:2577c501a2fb8d05a304c09d090d6e47c306fef15809d102b327cf8364bddab5"},
{url = "https://files.pythonhosted.org/packages/95/52/531ef197b426646f26b53815a7d2a67cb7a331ef098bb276db26a68ac49f/requests-oauthlib-1.3.1.tar.gz", hash = "sha256:75beac4a47881eeb94d5ea5d6ad31ef88856affe2332b9aafb52c6452ccf0d7a"},
]
"streaming-form-data 1.11.0" = [
{url = "https://files.pythonhosted.org/packages/04/2f/2f35fbb41fc402f379081cf32f78cd750304fcb801b01d1307831225222b/streaming_form_data-1.11.0-cp36-cp36m-manylinux1_i686.whl", hash = "sha256:fe46eff0cb5aebcc752c7ee3258bbeaa6aa9007bad9c32cfbd46d00df5c1f4d4"},
{url = "https://files.pythonhosted.org/packages/08/7f/dcffefffde61a3cdcac981a81ff57164c44b64c92154c69742bdc8a27a7d/streaming_form_data-1.11.0-cp39-cp39-manylinux2010_i686.whl", hash = "sha256:52fd1ea2a8c0b4ac56b99903214e239f0e8b9266f65c8cae6c00787aaf1f9cfe"},
{url = "https://files.pythonhosted.org/packages/0a/f1/a9f862f8d097371ca464ff723221568010762c55d2cdcc200821048d29e0/streaming_form_data-1.11.0-cp37-cp37m-manylinux2010_x86_64.whl", hash = "sha256:ab59d14825cb4ed9d96eb17a2f78f5a96935fb4e8e6b98fcae5ce07fcd6e0fa9"},
{url = "https://files.pythonhosted.org/packages/1d/cc/9110eaa9a045274d7ff48a66e9185af64ba42349ab7d9da0828606fa06bc/streaming_form_data-1.11.0-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:9ff76ec968a1c04dcc94fd66fae343b9fc576cb455fdd3f93370dad5fa1d8771"},
{url = "https://files.pythonhosted.org/packages/1f/55/d09ebcc68fc24c15bea4c119247f4da38afbaefc302bfc90f567e3ab8394/streaming_form_data-1.11.0-cp36-cp36m-win_amd64.whl", hash = "sha256:5dfb34b8e147c4f30ada3ab333b517cbc8c273e06a0f464c85f92e70647bbbd6"},
{url = "https://files.pythonhosted.org/packages/2c/6c/a6666cadf14b7bcb27f214a2325b9c72a35a0f3f34fbcda3890e53488468/streaming-form-data-1.11.0.tar.gz", hash = "sha256:202cea84200e8d412dd22b3ae522e1896a8a7d041aae809278b003b64ed1712b"},
{url = "https://files.pythonhosted.org/packages/39/0c/5f68bd2f004a66af88b1509d15e8aab121a83d94b15103eef347a8378953/streaming_form_data-1.11.0-cp38-cp38-manylinux1_x86_64.whl", hash = "sha256:e551dc5604af5b971224c5c82c132ec8d99bc3da627ad6228ff899f1b1043839"},
{url = "https://files.pythonhosted.org/packages/3c/3f/2a637fee6d3ec836a24d3deb0bad343aec76458b24aebf5599d7265e0255/streaming_form_data-1.11.0-cp37-cp37m-manylinux2010_i686.whl", hash = "sha256:5358cc32bf775944d366525c2854620e55548563f40868f01ea4af6f252b682b"},
{url = "https://files.pythonhosted.org/packages/3f/2c/120ddd55d727e63a93a05e5da17a9d54f26570bf6cb5353211a0191bd858/streaming_form_data-1.11.0-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:a780dc298ff4da1d20c9deae02f817c08de59e0094b591627727efe6e94574af"},
{url = "https://files.pythonhosted.org/packages/4b/70/7a372bddb2e413170fe3a2f90a4aef33efd8aa655b7dadf521d19512895e/streaming_form_data-1.11.0-cp37-cp37m-manylinux1_i686.whl", hash = "sha256:f7bf111cd071853089b3904ec9dd9250959a45e88ea05ce078b2632375597cef"},
{url = "https://files.pythonhosted.org/packages/57/66/82ac7a98357c2062890cd2c2a19d7081ab877808bc49f5e8da779e7c63be/streaming_form_data-1.11.0-cp37-cp37m-manylinux1_x86_64.whl", hash = "sha256:1eccecf020053de8bfba7844ac9e0ed2cb1ca2a3d39980aa9077ca3f31048b1f"},
{url = "https://files.pythonhosted.org/packages/63/6f/3df5b7b134c1d3e971a0319b9ffce963269cdab4810cd9977fff9fb22963/streaming_form_data-1.11.0-cp39-cp39-manylinux1_i686.whl", hash = "sha256:27a21a95d9d05448f638c049b2da1406a6d4ac357c6e8bec4268d9a2f99bdd76"},
{url = "https://files.pythonhosted.org/packages/6e/00/c562082e709b96c54956a8631dcf086895a2504f46c25bbc1fa60e1b961b/streaming_form_data-1.11.0-cp36-cp36m-manylinux1_x86_64.whl", hash = "sha256:1428e0fe38d7d5dea984a772a235955a4f4e6e846d2f377239b7b8a42b2ab455"},
{url = "https://files.pythonhosted.org/packages/89/59/632ec49c341df95597f291eb7e818749287089b7166823b1e5397d1e855a/streaming_form_data-1.11.0-cp39-cp39-manylinux2010_x86_64.whl", hash = "sha256:301dba4f0b634d4e7e632172cc9fb6e0db136ce6a12b0f5cf118d25f0aaa484e"},
{url = "https://files.pythonhosted.org/packages/9a/c5/4d6b7a2bc2b01c0f2085db522cb0c2785dd011e5d9f13c8b35c987a79e55/streaming_form_data-1.11.0-cp39-cp39-win_amd64.whl", hash = "sha256:d33096083ae86837b7f8dfd3653b7cf87044d7ffb6b52102114e46a74a3a1164"},
{url = "https://files.pythonhosted.org/packages/a3/64/efed10d21c999c79d87f7b187c861918c80af1e8243ab4f1d3fafcca0625/streaming_form_data-1.11.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:adc810f256214af1dc45b9351cca1f8e7af60fb9de07bb3ab9ba1379770c51f7"},
{url = "https://files.pythonhosted.org/packages/af/d7/da423d9a38e9459089155d8583e32e46ca61f6ae5f429022557603ff721d/streaming_form_data-1.11.0-cp39-cp39-manylinux1_x86_64.whl", hash = "sha256:1fbdd0df497465524e2010ae1465582663c9fb2a1f933075fddb6710a0cf9f17"},
{url = "https://files.pythonhosted.org/packages/b2/2e/1d6a4ffe8650af67f3dbd9b84d2d369df14edc4559f4afb53c72914a1010/streaming_form_data-1.11.0-cp37-cp37m-win_amd64.whl", hash = "sha256:cf8de78d747e95db780cd18672783735bcb811ea495b8e4546c8fa534829d90d"},
{url = "https://files.pythonhosted.org/packages/bc/f6/804ff40efb9de1f4256f60e3faa507058349bc9086c5adad568692216a28/streaming_form_data-1.11.0-cp38-cp38-win32.whl", hash = "sha256:70321f427e0600c7d5b74fd8f91a4478edb92143bd9fd051dd11a18c1e08a37c"},
{url = "https://files.pythonhosted.org/packages/be/b0/91c341a58ea61c12c56dfc9ab101e495c08632bb74b1e6247e32641aea55/streaming_form_data-1.11.0-cp39-cp39-win32.whl", hash = "sha256:b208c0918cdf2e274d286c78f3f6b1fd5e9c0cf35bc1dc33a60d1c3c4edf0b51"},
{url = "https://files.pythonhosted.org/packages/d0/5b/f7ab5b7357fa274ce76f159d67ca6e52103e626ff9bbc82fc55cfa172888/streaming_form_data-1.11.0-cp38-cp38-manylinux1_i686.whl", hash = "sha256:f348e67d55dcb60ce8571647dd0e18aa4205091c9c1d1f1b0ee2816e8f612421"},
{url = "https://files.pythonhosted.org/packages/d3/28/b6cabf9b1e0c50140162bc369ff65d3535cef459f0264822d77b72a80ada/streaming_form_data-1.11.0-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:b073baa08f349ab4737ebb673e8dc5c4cd19be6c8d18f43262e659d95b290733"},
{url = "https://files.pythonhosted.org/packages/d8/e9/79041e6ed6b2ed56d8928eabaa5943da273dea3caf7b2e628c4a8c8e9a03/streaming_form_data-1.11.0-cp36-cp36m-manylinux2010_i686.whl", hash = "sha256:5bffc52d57f6733c5462b8fb19b4d7ce54c2faea3c7d5b12725b86740be1c7c9"},
{url = "https://files.pythonhosted.org/packages/df/63/c4fc00a6b4808b97f1fc46c2682a5154b81b99d2d3f2f4cd8bc61190426d/streaming_form_data-1.11.0-cp36-cp36m-win32.whl", hash = "sha256:8db536c6387d27b2ce9b89e58269ff79d8da197f1f3c300f53dc130271bb5f78"},
{url = "https://files.pythonhosted.org/packages/e0/4c/99315996886639c3887d5030f172ec14b6ffe5c9fffc4386ffbca95f3eff/streaming_form_data-1.11.0-cp38-cp38-win_amd64.whl", hash = "sha256:406cd5a23eef77f360b549b93fa64a8ee724309063ab1dce528e1c8e397cb56f"},
{url = "https://files.pythonhosted.org/packages/e0/51/09006f1ec2b562e3ca6d6fe82f878d8b2c66cd0ef56ce85d6225b8a6acc6/streaming_form_data-1.11.0-cp38-cp38-manylinux2010_x86_64.whl", hash = "sha256:aa07f1c565436319862abb338e3a9ae68855b09fc5ceb83564c34a53af852c52"},
{url = "https://files.pythonhosted.org/packages/e2/91/a1172ef7d998efb97fe9fd5a56f13fad43d56bf7c53c87ec96c379654b53/streaming_form_data-1.11.0-cp37-cp37m-win32.whl", hash = "sha256:267a4921decbd3a800463d72b6a8df362e17cad7825924a5a61e3cbc7bacf96d"},
{url = "https://files.pythonhosted.org/packages/ee/1e/0c7f836410c809d9001c31fb2bf31bdc40a38671fc8e6820021e0f8cd878/streaming_form_data-1.11.0-cp38-cp38-manylinux2010_i686.whl", hash = "sha256:1d56ac0fb880cb8143cbfd5c67361fc6caa0ab5e9863074555304ad27c1d0e2b"},
{url = "https://files.pythonhosted.org/packages/f0/37/5f4162304049e1a25974de914c9e21543bafd2218b396c2c3a313d575126/streaming_form_data-1.11.0-cp36-cp36m-manylinux2010_x86_64.whl", hash = "sha256:89a20560924bbbd07fc51f3f7b6710744e8b845028a9af338b6caa9c2611f7bb"},
]
"tornado 6.2" = [
{url = "https://files.pythonhosted.org/packages/11/30/ac70f5c5f03cf1cd0ae8199c80382387a9fe57e8f68853d5c9527c0219e5/tornado-6.2-cp37-abi3-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:b8150f721c101abdef99073bf66d3903e292d851bee51910839831caba341a75"},
{url = "https://files.pythonhosted.org/packages/19/bb/b6c3d1668d2b10ad38a584f3a1ec9737984e274f8b708e09fcbb96427f5c/tornado-6.2-cp37-abi3-manylinux_2_5_x86_64.manylinux1_x86_64.manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d3a2f5999215a3a06a4fc218026cd84c61b8b2b40ac5296a6db1f1451ef04c1e"},
{url = "https://files.pythonhosted.org/packages/1c/26/cbfa1103e74a02e09dd53291e419da3ad4c5b948f52aea5800e6671b56e0/tornado-6.2-cp37-abi3-win_amd64.whl", hash = "sha256:e5f923aa6a47e133d1cf87d60700889d7eae68988704e20c75fb2d65677a8e4b"},
{url = "https://files.pythonhosted.org/packages/5c/0c/cbc0a98f7b8ef833bcb13c58d35d09e2c288ae67a35af4c8960b88f99ae9/tornado-6.2-cp37-abi3-macosx_10_9_x86_64.whl", hash = "sha256:87dcafae3e884462f90c90ecc200defe5e580a7fbbb4365eda7c7c1eb809ebc9"},
{url = "https://files.pythonhosted.org/packages/60/08/e630a348b34a9ddd640aed67dafc6f0df425d8ac07d2fa60288f38321c69/tornado-6.2-cp37-abi3-musllinux_1_1_i686.whl", hash = "sha256:6fdfabffd8dfcb6cf887428849d30cf19a3ea34c2c248461e1f7d718ad30b66b"},
{url = "https://files.pythonhosted.org/packages/71/cc/c1342382484d0178a79029109c433e406a60095da1c3605ca966775a70e5/tornado-6.2-cp37-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:ba09ef14ca9893954244fd872798b4ccb2367c165946ce2dd7376aebdde8e3ac"},
{url = "https://files.pythonhosted.org/packages/cd/a4/761e45cea12b2af076d36240d464b371ab1231272948cdc49b7d81855c5c/tornado-6.2-cp37-abi3-musllinux_1_1_aarch64.whl", hash = "sha256:5f8c52d219d4995388119af7ccaa0bcec289535747620116a58d830e7c25d8a8"},
{url = "https://files.pythonhosted.org/packages/ec/01/93e63530851ba8ef9685f1a9b91e324b28d28323a6b67400114ea65c5110/tornado-6.2-cp37-abi3-win32.whl", hash = "sha256:5c87076709343557ef8032934ce5f637dbb552efa7b21d08e89ae7619ed0eb23"},
{url = "https://files.pythonhosted.org/packages/f3/9e/225a41452f2d9418d89be5e32cf824c84fe1e639d350d6e8d49db5b7f73a/tornado-6.2.tar.gz", hash = "sha256:9b630419bde84ec666bfd7ea0a4cb2a8a651c2d5cccdbdd1972a0c859dfc3c13"},
{url = "https://files.pythonhosted.org/packages/f9/51/6f63a166d9a3077be100cbb13dcbce434e5654daaaa7003b0a045b9f6edf/tornado-6.2-cp37-abi3-musllinux_1_1_x86_64.whl", hash = "sha256:1d54d13ab8414ed44de07efecb97d4ef7c39f7438cf5e976ccd356bebb1b5fca"},
{url = "https://files.pythonhosted.org/packages/fb/bd/074254a55bfc82d7a1886abbd803600ef01cbd76ee66bc30307b2724130b/tornado-6.2-cp37-abi3-macosx_10_9_universal2.whl", hash = "sha256:20f638fd8cc85f3cbae3c732326e96addff0a15e22d80f049e00121651e82e72"},
]
"typing-extensions 4.4.0" = [
{url = "https://files.pythonhosted.org/packages/0b/8e/f1a0a5a76cfef77e1eb6004cb49e5f8d72634da638420b9ea492ce8305e8/typing_extensions-4.4.0-py3-none-any.whl", hash = "sha256:16fa4864408f655d35ec496218b85f79b3437c829e93320c7c9215ccfd92489e"},
{url = "https://files.pythonhosted.org/packages/e3/a7/8f4e456ef0adac43f452efc2d0e4b242ab831297f1bac60ac815d37eb9cf/typing_extensions-4.4.0.tar.gz", hash = "sha256:1511434bb92bf8dd198c12b1cc812e800d4181cfcb867674e0f8279cc93087aa"},
]
"urllib3 1.26.14" = [
{url = "https://files.pythonhosted.org/packages/c5/52/fe421fb7364aa738b3506a2d99e4f3a56e079c0a798e9f4fa5e14c60922f/urllib3-1.26.14.tar.gz", hash = "sha256:076907bf8fd355cde77728471316625a4d2f7e713c125f51953bb5b3eecf4f72"},
{url = "https://files.pythonhosted.org/packages/fe/ca/466766e20b767ddb9b951202542310cba37ea5f2d792dae7589f1741af58/urllib3-1.26.14-py2.py3-none-any.whl", hash = "sha256:75edcdc2f7d85b137124a6c3c9fc3933cdeaa12ecb9a6a959f22797a0feca7e1"},
]
"zeroconf 0.39.4" = [
{url = "https://files.pythonhosted.org/packages/3f/ff/a8d7faaa3573b6e4c775cacbf911a0afbcb4928ce71b3de43119227a396a/zeroconf-0.39.4-py3-none-any.whl", hash = "sha256:d60eae9e9c99d1a168ce9ff9de7e7398c23754a0c2004ded230f8d529c5260a0"},
{url = "https://files.pythonhosted.org/packages/f5/4f/c47cea73d7ae5467b63de3999d7207fd5b14d70cb2f35ce81c4ab7d7a52e/zeroconf-0.39.4.tar.gz", hash = "sha256:701e4d697f89fe952aa9c13a512ed6bf472dcf4f0a6d275e71085604b3882295"},
]
"zipp 3.13.0" = [
{url = "https://files.pythonhosted.org/packages/95/7b/1608a7344743f54a8c072d64d2a279934fd204d6d015278b0a0ed4ce104b/zipp-3.13.0-py3-none-any.whl", hash = "sha256:e8b2a36ea17df80ffe9e2c4fda3f693c3dad6df1697d3cd3af232db680950b0b"},
{url = "https://files.pythonhosted.org/packages/d1/2f/ba544a8a6ad5ad9dcec1b00f536bb9fb078f5f50d1a1408876de18a9151b/zipp-3.13.0.tar.gz", hash = "sha256:23f70e964bc11a34cef175bc90ba2914e1e4545ea1e3e2f67c079671883f9cb6"},
]
+64
View File
@@ -0,0 +1,64 @@
[project]
name = "moonraker"
dynamic = ["version"]
description = "API Server for Klipper"
authors = [
{name = "Eric Callahan"},
{email = "arksine.code@gmail.com"},
]
dependencies = [
"tornado==6.2.0",
"pyserial==3.4",
"pyserial-asyncio==0.6",
"pillow==9.3.0",
"lmdb==1.3.0",
"streaming-form-data==1.11.0",
"distro==1.8.0",
"inotify-simple==1.3.5",
"libnacl==1.8.0",
"paho-mqtt==1.6.1",
"zeroconf==0.39.4",
"preprocess-cancellation==0.2.0",
"jinja2==3.1.2",
"dbus-next==0.2.3",
"apprise==1.2.1",
"ldap3==2.9.1"
]
requires-python = ">=3.7"
readme = "README.md"
license = {text = "GPL-3.0-only"}
keywords = ["klipper", "3D printing", "server", "moonraker"]
classifiers = [
"Development Status :: 4 - Beta",
"Topic :: Internet :: WWW/HTTP :: HTTP Servers",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
]
[project.urls]
homepage = "https://github.com/Arksine/moonraker"
repository = "https://github.com/Arksine/moonraker"
documentation = "https://moonraker.readthedocs.io"
changelog = "https://moonraker.readthedocs.io/en/latest/changelog/"
[tool.pdm.version]
source = "scm"
write_to = "moonraker/__version__.py"
write_template = "__version__ = '{}'\n"
[tool.pdm.build]
excludes = ["./**/.git", "moonraker/moonraker.py"]
includes = ["moonraker"]
editable-backend = "path"
custom-hook = "scripts/pdm_build_dist.py"
[project.scripts]
moonraker = "moonraker.server:main"
[build-system]
requires = ["pdm-backend>=2.0.2"]
build-backend = "pdm.backend"
+13
View File
@@ -0,0 +1,13 @@
[pytest]
minversion = 7.0
pythonpath = moonraker scripts
testpaths = tests
required_plugins =
pytest-asyncio>=0.17.2
pytest-timeout>=2.1.0
asyncio_mode = strict
timeout = 60
timeout_method = signal
markers =
run_paths
no_ws_connect
+50
View File
@@ -0,0 +1,50 @@
#!/bin/bash
# LMDB Database backup utility
DATABASE_PATH="${HOME}/printer_data/database"
MOONRAKER_ENV="${HOME}/moonraker-env"
OUPUT_FILE="${HOME}/database.backup"
print_help()
{
echo "Moonraker Database Backup Utility"
echo
echo "usage: backup-database.sh [-h] [-e <python env path>] [-d <database path>] [-o <output file>]"
echo
echo "optional arguments:"
echo " -h show this message"
echo " -e <env path> Moonraker Python Environment"
echo " -d <database path> Moonraker LMDB database to backup"
echo " -o <output file> backup file to save to"
exit 0
}
# Parse command line arguments
while getopts "he:d:o:" arg; do
case $arg in
h) print_help;;
e) MOONRAKER_ENV=$OPTARG;;
d) DATABASE_PATH=$OPTARG;;
o) OUPUT_FILE=$OPTARG;;
esac
done
PYTHON_BIN="${MOONRAKER_ENV}/bin/python"
DB_TOOL="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )/dbtool.py"
if [ ! -f $PYTHON_BIN ]; then
echo "No Python binary found at '${PYTHON_BIN}'"
exit -1
fi
if [ ! -f "$DATABASE_PATH/data.mdb" ]; then
echo "No Moonraker database found at '${DATABASE_PATH}'"
exit -1
fi
if [ ! -f $DB_TOOL ]; then
echo "Unable to locate dbtool.py at '${DB_TOOL}'"
exit -1
fi
${PYTHON_BIN} ${DB_TOOL} backup ${DATABASE_PATH} ${OUPUT_FILE}
+64
View File
@@ -0,0 +1,64 @@
#!/bin/bash
# This script builds a zipped source release for Moonraker and Klipper.
install_packages()
{
PKGLIST="python3-dev curl"
# Update system package info
report_status "Running apt-get update..."
sudo apt-get update
# Install desired packages
report_status "Installing packages..."
sudo apt-get install --yes $PKGLIST
}
report_status()
{
echo -e "\n\n###### $1"
}
verify_ready()
{
if [ "$EUID" -eq 0 ]; then
echo "This script must not run as root"
exit -1
fi
if [ ! -d "$SRCDIR/.git" ]; then
echo "This script must be run from a git repo"
exit -1
fi
if [ ! -d "$KLIPPER_DIR/.git" ]; then
echo "This script must be run from a git repo"
exit -1
fi
}
# Force script to exit if an error occurs
set -e
SRCDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )"/.. && pwd )"
OUTPUT_DIR="$SRCDIR/.dist"
KLIPPER_DIR="$HOME/klipper"
BETA=""
# Parse command line arguments
while getopts "o:k:b" arg; do
case $arg in
o) OUTPUT_DIR=$OPTARG;;
k) KLIPPER_DIR=$OPTARG;;
b) BETA="-b";;
esac
done
[ ! -d $OUTPUT_DIR ] && mkdir $OUTPUT_DIR
verify_ready
if [ "$BETA" = "" ]; then
releaseTag=$( git -C $KLIPPER_DIR describe --tags `git -C $KLIPPER_DIR rev-list --tags --max-count=1` )
echo "Checking out Klipper release $releaseTag"
git -C $KLIPPER_DIR checkout $releaseTag
fi
python3 "$SRCDIR/scripts/build_release.py" -k $KLIPPER_DIR -o $OUTPUT_DIR $BETA
+338
View File
@@ -0,0 +1,338 @@
#!/usr/bin/python3
# Builds zip release files for Moonraker and Klipper
import os
import sys
import argparse
import shutil
import tempfile
import json
import pathlib
import time
import traceback
import subprocess
import re
from typing import Dict, Any, List, Set, Optional
MOONRAKER_PATH = os.path.abspath(
os.path.join(os.path.dirname(__file__), ".."))
sys.path.append(os.path.join(MOONRAKER_PATH, "moonraker"))
from utils import hash_directory, retrieve_git_version # noqa:E402
# Dirs and exts to ignore when calculating the repo hash
IGNORE_DIRS = ["out", "lib", "test", "docs", "__pycache__"]
IGNORE_EXTS = [".o", ".so", ".pyc", ".pyo", ".pyd", ".yml", ".yaml"]
# Files not to include in the source package
SKIP_FILES = [".gitignore", ".gitattributes", ".readthedocs.yaml",
"mkdocs.yml", "__pycache__"]
RELEASE_URL = "https://api.github.com/repos/Arksine/moonraker/releases"
GIT_MAX_LOG_CNT = 100
GIT_LOG_FMT = \
"sha:%H%x1Dauthor:%an%x1Ddate:%ct%x1Dsubject:%s%x1Dmessage:%b%x1E"
OWNER_REPOS = {
'moonraker': "arksine/moonraker",
'klippy': "klipper3d/klipper"
}
INSTALL_SCRIPTS = {
'klippy': {
'debian': "install-octopi.sh",
'arch': "install-arch.sh",
'centos': "install-centos.sh"
},
'moonraker': {
'debian': "install-moonraker.sh"
}
}
class CopyIgnore:
def __init__(self, root_dir: str) -> None:
self.root_dir = root_dir
def __call__(self, dir_path: str, dir_items: List[str]) -> List[str]:
ignored: List[str] = []
for item in dir_items:
if item in SKIP_FILES:
ignored.append(item)
elif dir_path == self.root_dir:
full_path = os.path.join(dir_path, item)
# Ignore all hidden directories in the root
if os.path.isdir(full_path) and item[0] == ".":
ignored.append(item)
return ignored
def search_install_script(data: str,
regex: str,
exclude: str
) -> List[str]:
items: Set[str] = set()
lines: List[str] = re.findall(regex, data)
for line in lines:
items.update(line.strip().split())
try:
items.remove(exclude)
except KeyError:
pass
return list(items)
def generate_dependency_info(repo_path: str, app_name: str) -> None:
inst_scripts = INSTALL_SCRIPTS[app_name]
package_info: Dict[str, Any] = {}
for distro, script_name in inst_scripts.items():
script_path = os.path.join(repo_path, "scripts", script_name)
script = pathlib.Path(script_path)
if not script.exists():
continue
data = script.read_text()
packages: List[str] = search_install_script(
data, r'PKGLIST="(.*)"', "${PKGLIST}")
package_info[distro] = {'packages': sorted(packages)}
if distro == "arch":
aur_packages: List[str] = search_install_script(
data, r'AURLIST="(.*)"', "${AURLIST}")
package_info[distro]['aur_packages'] = sorted(aur_packages)
req_file_name = os.path.join(repo_path, "scripts",
f"{app_name}-requirements.txt")
req_file = pathlib.Path(req_file_name)
python_reqs: List[str] = []
if req_file.exists():
req_data = req_file.read_text()
lines = [line.strip() for line in req_data.split('\n')
if line.strip()]
for line in lines:
comment_idx = line.find('#')
if comment_idx == 0:
continue
if comment_idx > 0:
line = line[:comment_idx].strip()
python_reqs.append(line)
package_info['python'] = sorted(python_reqs)
dep_file = pathlib.Path(os.path.join(repo_path, ".dependencies"))
dep_file.write_text(json.dumps(package_info))
def clean_repo(path: str) -> None:
# Obtain version info from "git" program
prog = ('git', '-C', path, 'clean', '-x', '-f', '-d')
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, cwd=path)
retcode = process.wait()
if retcode != 0:
print(f"Error running git clean: {path}")
def get_releases() -> List[Dict[str, Any]]:
print("Fetching Release List...")
prog = ('curl', '-H', "Accept: application/vnd.github.v3+json",
RELEASE_URL)
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
response, err = process.communicate()
retcode = process.wait()
if retcode != 0:
print(f"Release list request returned with code {retcode},"
f" response:\n{err.decode()}")
return []
releases = json.loads(response.decode().strip())
print(f"Found {len(releases)} releases")
return releases
def get_last_release_info(moonraker_version: str,
is_beta: bool,
releases: List[Dict[str, Any]]
) -> Dict[str, Any]:
print("Searching for previous release assets...")
cur_tag, commit_count = moonraker_version.split('-', 2)[:2]
release_assets = []
matched_tag: Optional[str] = None
for release in releases:
if int(commit_count) != 0:
# This is build is not being done against a fresh release,
# return release info from a matching tag
if release['tag_name'] == cur_tag:
release_assets = release['assets']
matched_tag = cur_tag
break
else:
# Get the most recent non-matching tag
if release['tag_name'] == cur_tag:
continue
if is_beta or not release['prerelease']:
# Get the last tagged release. If we are building a beta,
# that is the most recent release. Otherwise we should
# omit pre-releases
release_assets = release['assets']
matched_tag = release['tag_name']
break
if matched_tag is None:
print("No matching release found")
matched_tag = "No Tag"
else:
print(f"Found release: {matched_tag}")
asset_url: Optional[str] = None
content_type: str = ""
for asset in release_assets:
if asset['name'] == "RELEASE_INFO":
asset_url = asset['browser_download_url']
content_type = asset['content_type']
break
if asset_url is None:
print(f"RELEASE_INFO asset not found in release: {matched_tag}")
return {}
# This build is prior to a tagged release, so fetch the current tag
print(f"Release Info Download URL: {asset_url}")
prog = ('curl', '-L', '-H', f"Accept: {content_type}", asset_url)
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
response, err = process.communicate()
retcode = process.wait()
if retcode != 0:
print("Request for release info failed")
return {}
resp = response.decode().strip()
print(f"Found Info for release {matched_tag}")
return json.loads(resp)
def get_commit_log(path: str,
release_info: Dict[str, Any]
) -> List[Dict[str, Any]]:
print(f"Preparing commit log for {path.split('/')[-1]}")
start_sha = release_info.get('commit_hash', None)
prog = ['git', '-C', path, 'log', f'--format={GIT_LOG_FMT}',
f'--max-count={GIT_MAX_LOG_CNT}']
if start_sha is not None:
prog = ['git', '-C', path, 'log', f'{start_sha}..HEAD',
f'--format={GIT_LOG_FMT}', f'--max-count={GIT_MAX_LOG_CNT}']
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, cwd=path)
response, err = process.communicate()
retcode = process.wait()
if retcode != 0:
return []
resp = response.decode().strip()
commit_log: List[Dict[str, Any]] = []
for log_entry in resp.split('\x1E'):
log_entry = log_entry.strip()
if not log_entry:
continue
log_items = [li.strip() for li in log_entry.split('\x1D')
if li.strip()]
cbh = [li.split(':', 1) for li in log_items]
commit_log.append(dict(cbh)) # type: ignore
print(f"Found {len(commit_log)} commits")
return commit_log
def get_commit_hash(path: str) -> str:
prog = ('git', '-C', path, 'rev-parse', 'HEAD')
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, cwd=path)
commit_hash, err = process.communicate()
retcode = process.wait()
if retcode == 0:
return commit_hash.strip().decode()
raise Exception(f"Failed to get commit hash: {commit_hash.decode()}")
def generate_version_info(path: str,
source_dir: str,
channel: str,
release_tag: Optional[str] = None
) -> Dict[str, Any]:
print(f"Generating version info: {source_dir}")
clean_repo(path)
owner_repo = OWNER_REPOS[source_dir]
curtime = int(time.time())
date_str = time.strftime("%Y%m%d", time.gmtime(curtime))
version = retrieve_git_version(path)
if release_tag is None:
release_tag = version.split('-')[0]
source_hash = hash_directory(path, IGNORE_EXTS, IGNORE_DIRS)
long_version = f"{version}-moonraker-{date_str}"
release_info = {
'git_version': version,
'long_version': long_version,
'commit_hash': get_commit_hash(path),
'source_checksum': source_hash,
'ignored_exts': IGNORE_EXTS,
'ignored_dirs': IGNORE_DIRS,
'build_date': curtime,
'channel': channel,
'owner_repo': owner_repo,
'host_repo': OWNER_REPOS['moonraker'],
'release_tag': release_tag
}
vfile = pathlib.Path(os.path.join(path, source_dir, ".version"))
vfile.write_text(long_version)
rfile = pathlib.Path(os.path.join(path, ".release_info"))
rfile.write_text(json.dumps(release_info))
generate_dependency_info(path, source_dir)
return release_info
def create_zip(repo_path: str,
repo_name: str,
output_path: str
) -> None:
print(f"Creating Zip Release: {repo_name}")
zip_path = os.path.join(output_path, repo_name)
with tempfile.TemporaryDirectory() as tmp_dir:
dest_path = os.path.join(tmp_dir, repo_name)
ingore_cb = CopyIgnore(repo_path)
shutil.copytree(repo_path, dest_path, ignore=ingore_cb)
shutil.make_archive(zip_path, "zip", root_dir=dest_path)
def main() -> None:
# Parse start arguments
parser = argparse.ArgumentParser(
description="Generates zip releases for Moonraker and Klipper")
parser.add_argument(
"-k", "--klipper", default="~/klipper",
metavar='<klipper_path>',
help="Path to Klipper git repo")
parser.add_argument(
"-o", "--output", default=os.path.join(MOONRAKER_PATH, ".dist"),
metavar='<output_path>', help="Path to output directory")
parser.add_argument(
"-b", "--beta", action='store_true',
help="Tag release as beta")
args = parser.parse_args()
kpath: str = os.path.abspath(os.path.expanduser(args.klipper))
opath: str = os.path.abspath(os.path.expanduser(args.output))
is_beta: bool = args.beta
channel = "beta" if is_beta else "stable"
if not os.path.exists(kpath):
print(f"Invalid path to Klipper: {kpath}")
sys.exit(-1)
if not os.path.exists(opath):
print(f"Invalid output path: {opath}")
sys.exit(-1)
releases = get_releases()
all_info: Dict[str, Dict[str, Any]] = {}
try:
print("Generating Moonraker Zip Distribution...")
all_info['moonraker'] = generate_version_info(
MOONRAKER_PATH, "moonraker", channel)
create_zip(MOONRAKER_PATH, 'moonraker', opath)
rtag: str = all_info['moonraker']['release_tag']
print("Generating Klipper Zip Distribution...")
all_info['klipper'] = generate_version_info(
kpath, "klippy", channel, rtag)
create_zip(kpath, 'klipper', opath)
info_file = pathlib.Path(os.path.join(opath, "RELEASE_INFO"))
info_file.write_text(json.dumps(all_info))
last_rinfo = get_last_release_info(
all_info['moonraker']['git_version'], is_beta, releases)
commit_log = {}
commit_log['moonraker'] = get_commit_log(
MOONRAKER_PATH, last_rinfo.get('moonraker', {}))
commit_log['klipper'] = get_commit_log(
kpath, last_rinfo.get('klipper', {}))
clog_file = pathlib.Path(os.path.join(opath, "COMMIT_LOG"))
clog_file.write_text(json.dumps(commit_log))
except Exception:
print("Error Creating Zip Distribution")
traceback.print_exc(file=sys.stdout)
sys.exit(-1)
print(f"Build Complete. Files are located at '{opath}'")
if __name__ == "__main__":
main()
+65
View File
@@ -0,0 +1,65 @@
#!/bin/bash
# Data Path Fix for legacy MainsailOS and FluiddPi installations running
# a single instance of Moonraker with a default configuration
DATA_PATH="${HOME}/printer_data"
DATA_PATH_BKP="${HOME}/.broken_printer_data"
DB_PATH="${HOME}/.moonraker_database"
CONFIG_PATH="${HOME}/klipper_config"
LOG_PATH="${HOME}/klipper_logs"
GCODE_PATH="${HOME}/gcode_files"
MOONRAKER_CONF="${CONFIG_PATH}/moonraker.conf"
MOONRAKER_LOG="${LOG_PATH}/moonraker.log"
ALIAS="moonraker"
# Parse command line arguments
while getopts "c:l:d:a:m:g:" arg; do
case $arg in
c)
MOONRAKER_CONF=$OPTARG
CONFIG_PATH="$( dirname $OPTARG )"
;;
l)
MOONRAKER_LOG=$OPTARG
LOG_PATH="$( dirname $OPTARG )"
;;
d)
DATA_PATH=$OPTARG
dpbase="$( basename $OPTARG )"
DATA_PATH_BKP="${HOME}/.broken_${dpbase}"
;;
a)
ALIAS=$OPTARG
;;
m)
DB_PATH=$OPTARG
[ ! -f "${DB_PATH}/data.mdb" ] && echo "No valid database found at ${DB_PATH}" && exit 1
;;
g)
GCODE_PATH=$OPTARG
[ ! -d "${GCODE_PATH}" ] && echo "No GCode Path found at ${GCODE_PATH}" && exit 1
;;
esac
done
[ ! -f "${MOONRAKER_CONF}" ] && echo "Error: unable to find config: ${MOONRAKER_CONF}" && exit 1
[ ! -d "${LOG_PATH}" ] && echo "Error: unable to find log path: ${LOG_PATH}" && exit 1
sudo systemctl stop ${ALIAS}
[ -d "${DATA_PATH_BKP}" ] && rm -rf ${DATA_PATH_BKP}
[ -d "${DATA_PATH}" ] && echo "Moving broken datapath to ${DATA_PATH_BKP}" && mv ${DATA_PATH} ${DATA_PATH_BKP}
mkdir ${DATA_PATH}
echo "Creating symbolic links..."
[ -f "${DB_PATH}/data.mdb" ] && ln -s ${DB_PATH} "$DATA_PATH/database"
[ -d "${GCODE_PATH}" ] && ln -s ${GCODE_PATH} "$DATA_PATH/gcodes"
ln -s ${LOG_PATH} "$DATA_PATH/logs"
ln -s ${CONFIG_PATH} "$DATA_PATH/config"
[ -f "${DB_PATH}/data.mdb" ] && ~/moonraker-env/bin/python -mlmdb -e ${DB_PATH} -d moonraker edit --delete=validate_install
echo "Running Moonraker install script..."
~/moonraker/scripts/install-moonraker.sh -f -a ${ALIAS} -d ${DATA_PATH} -c ${MOONRAKER_CONF} -l ${MOONRAKER_LOG}
+239
View File
@@ -0,0 +1,239 @@
#! /usr/bin/python3
# Tool to backup and restore Moonraker's LMDB database
#
# Copyright (C) 2022 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
import argparse
import pathlib
import base64
import tempfile
import re
import time
from typing import Any, Dict, Optional, TextIO, Tuple
import lmdb
MAX_NAMESPACES = 100
MAX_DB_SIZE = 200 * 2**20
HEADER_KEY = b"MOONRAKER_DATABASE_START"
LINE_MATCH = re.compile(
r"^\+(\d+),(\d+):([A-Za-z0-9+/]+={0,2})->([A-Za-z0-9+/]+={0,2})$"
)
class DBToolError(Exception):
pass
# Use a modified CDBMake Format
# +keylen,datalen:namespace|key->data
# Key length includes the namespace, key and separator (a colon)
def open_db(db_path: str) -> lmdb.Environment:
return lmdb.open(db_path, map_size=MAX_DB_SIZE,
max_dbs=MAX_NAMESPACES)
def _do_dump(namespace: bytes,
db: object,
backup: TextIO,
txn: lmdb.Transaction
) -> None:
expected_key_count: int = txn.stat(db)["entries"]
# write the namespace header
ns_key = base64.b64encode(b"namespace_" + namespace).decode()
ns_str = f"entries={expected_key_count}"
ns_val = base64.b64encode(ns_str.encode()).decode()
out = f"+{len(ns_key)},{len(ns_val)}:{ns_key}->{ns_val}\n"
backup.write(out)
with txn.cursor(db=db) as cursor:
count = 0
remaining = cursor.first()
while remaining:
key, value = cursor.item()
keystr = base64.b64encode(key).decode()
valstr = base64.b64encode(value).decode()
out = f"+{len(keystr)},{len(valstr)}:{keystr}->{valstr}\n"
backup.write(out)
count += 1
remaining = cursor.next()
if expected_key_count != count:
print("Warning: Key count mismatch for namespace "
f"'{namespace.decode()}': expected {expected_key_count}"
f", wrote {count}")
def _write_header(ns_count: int, backup: TextIO):
val_str = f"namespace_count={ns_count}"
hkey = base64.b64encode(HEADER_KEY).decode()
hval = base64.b64encode(val_str.encode()).decode()
out = f"+{len(hkey)},{len(hval)}:{hkey}->{hval}\n"
backup.write(out)
def backup(args: Dict[str, Any]):
source_db = pathlib.Path(args["source"]).expanduser().resolve()
if not source_db.is_dir():
print(f"Source path not a folder: '{source_db}'")
exit(1)
if not source_db.joinpath("data.mdb").exists():
print(f"No database file found in source path: '{source_db}'")
exit(1)
bkp_dest = pathlib.Path(args["output"]).expanduser().resolve()
print(f"Backing up database at '{source_db}' to '{bkp_dest}'...")
if bkp_dest.exists():
print(f"Warning: file at '{bkp_dest}' exists, will be overwritten")
env = open_db(str(source_db))
expected_ns_cnt: int = env.stat()["entries"]
with bkp_dest.open("wt") as f:
_write_header(expected_ns_cnt, f)
with env.begin(buffers=True) as txn:
count = 0
with txn.cursor() as cursor:
remaining = cursor.first()
while remaining:
namespace = bytes(cursor.key())
db = env.open_db(namespace, txn=txn, create=False)
_do_dump(namespace, db, f, txn)
count += 1
remaining = cursor.next()
env.close()
if expected_ns_cnt != count:
print("Warning: namespace count mismatch: "
f"expected: {expected_ns_cnt}, wrote: {count}")
print("Backup complete!")
def _process_header(key: bytes, value: bytes) -> int:
if key != HEADER_KEY:
raise DBToolError(
"Database Backup does not contain a valid header key, "
f" got {key.decode()}")
val_parts = value.split(b"=", 1)
if val_parts[0] != b"namespace_count":
raise DBToolError(
"Database Backup has an invalid header value, got "
f"{value.decode()}")
return int(val_parts[1])
def _process_namespace(key: bytes, value: bytes) -> Tuple[bytes, int]:
key_parts = key.split(b"_", 1)
if key_parts[0] != b"namespace":
raise DBToolError(
f"Invalid Namespace Key '{key.decode()}', ID not prefixed")
namespace = key_parts[1]
val_parts = value.split(b"=", 1)
if val_parts[0] != b"entries":
raise DBToolError(
f"Invalid Namespace value '{value.decode()}', entry "
"count not present")
entries = int(val_parts[1])
return namespace, entries
def _process_line(line: str) -> Tuple[bytes, bytes]:
match = LINE_MATCH.match(line)
if match is None:
# TODO: use own exception
raise DBToolError(
f"Invalid DB Entry match: {line}")
parts = match.groups()
if len(parts) != 4:
raise DBToolError(
f"Invalid DB Entry, does not contain all data: {line}")
key_len, val_len, key, val = parts
if len(key) != int(key_len):
raise DBToolError(
f"Invalid DB Entry, key length mismatch. "
f"Got {len(key)}, expected {key_len}, line: {line}")
if len(val) != int(val_len):
raise DBToolError(
f"Invalid DB Entry, value length mismatch. "
f"Got {len(val)}, expected {val_len}, line: {line}")
decoded_key = base64.b64decode(key.encode())
decoded_val = base64.b64decode(val.encode())
return decoded_key, decoded_val
def restore(args: Dict[str, Any]):
dest_path = pathlib.Path(args["destination"]).expanduser().resolve()
input_db = pathlib.Path(args["input"]).expanduser().resolve()
if not input_db.is_file():
print(f"No backup found at path: {input_db}")
exit(1)
if not dest_path.exists():
print(f"Destination path '{dest_path}' does not exist, directory"
"will be created")
print(f"Restoring backup from '{input_db}' to '{dest_path}'...")
bkp_dir: Optional[pathlib.Path] = None
if dest_path.joinpath("data.mdb").exists():
bkp_dir = dest_path.parent.joinpath("backup")
if not bkp_dir.exists():
bkp_dir = pathlib.Path(tempfile.gettempdir())
str_time = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())
bkp_dir = bkp_dir.joinpath(f"{str_time}/database")
if not bkp_dir.is_dir():
bkp_dir.mkdir(parents=True)
print(f"Warning: database file at found in '{dest_path}', "
"all data will be overwritten. Copying existing DB "
f"to '{bkp_dir}'")
env = open_db(str(dest_path))
if bkp_dir is not None:
env.copy(str(bkp_dir))
expected_ns_count = -1
namespace_count = 0
keys_left = 0
namespace = b""
current_db = object()
with env.begin(write=True) as txn:
# clear all existing entries
dbs = []
with txn.cursor() as cursor:
remaining = cursor.first()
while remaining:
ns = cursor.key()
dbs.append(env.open_db(ns, txn=txn, create=False))
remaining = cursor.next()
for db in dbs:
txn.drop(db)
with input_db.open("rt") as f:
while True:
line = f.readline()
if not line:
break
key, val = _process_line(line)
if expected_ns_count < 0:
expected_ns_count = _process_header(key, val)
continue
if not keys_left:
namespace, keys_left = _process_namespace(key, val)
current_db = env.open_db(namespace, txn=txn)
namespace_count += 1
continue
txn.put(key, val, db=current_db)
keys_left -= 1
if expected_ns_count != namespace_count:
print("Warning: Namespace count mismatch, expected: "
f"{expected_ns_count}, processed {namespace_count}")
print("Restore Complete")
if __name__ == "__main__":
# Parse start arguments
parser = argparse.ArgumentParser(
description="dbtool - tool for backup/restore of Moonraker's database")
subparsers = parser.add_subparsers(
title="commands", description="valid commands", required=True,
metavar="<command>")
bkp_parser = subparsers.add_parser("backup", help="backup a database")
rst_parser = subparsers.add_parser("restore", help="restore a databse")
bkp_parser.add_argument(
"source", metavar="<source path>",
help="location of the folder containing the database to backup")
bkp_parser.add_argument(
"output", metavar="<output file>",
help="location of the backup file to write to",
default="~/moonraker_db.bkp")
bkp_parser.set_defaults(func=backup)
rst_parser.add_argument(
"destination", metavar="<destination>",
help="location of the folder where the database will be restored")
rst_parser.add_argument(
"input", metavar="<input file>",
help="location of the backup file to restore from")
rst_parser.set_defaults(func=restore)
args = parser.parse_args()
args.func(vars(args))
-653
View File
@@ -1,653 +0,0 @@
#!/usr/bin/env python3
# GCode metadata extraction utility
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import json
import argparse
import re
import os
import sys
import base64
import traceback
import io
from PIL import Image
def log_to_stderr(msg):
sys.stderr.write(f"{msg}\n")
sys.stderr.flush()
# regex helpers
def _regex_find_floats(pattern, data, strict=False):
# If strict is enabled, pattern requires a floating point
# value, otherwise it can be an integer value
fptrn = r'\d+\.\d*' if strict else r'\d+\.?\d*'
matches = re.findall(pattern, data)
if matches:
# return the maximum height value found
try:
return [float(h) for h in re.findall(
fptrn, " ".join(matches))]
except Exception:
pass
return []
def _regex_find_ints(pattern, data):
matches = re.findall(pattern, data)
if matches:
# return the maximum height value found
try:
return [int(h) for h in re.findall(
r'\d+', " ".join(matches))]
except Exception:
pass
return []
def _regex_find_first(pattern, data, cast=float):
match = re.search(pattern, data)
val = None
if match:
try:
val = cast(match.group(1))
except Exception:
return None
return val
# Slicer parsing implementations
class BaseSlicer(object):
def __init__(self, file_path):
self.path = file_path
self.header_data = self.footer_data = None
self.layer_height = None
def set_data(self, header_data, footer_data, fsize):
self.header_data = header_data
self.footer_data = footer_data
self.size = fsize
def _parse_min_float(self, pattern, data, strict=False):
result = _regex_find_floats(pattern, data, strict)
if result:
return min(result)
else:
return None
def _parse_max_float(self, pattern, data, strict=False):
result = _regex_find_floats(pattern, data, strict)
if result:
return max(result)
else:
return None
def check_identity(self, data):
return None
def parse_gcode_start_byte(self):
m = re.search(r"\n[MG]\d+\s.*\n", self.header_data)
if m is None:
return None
return m.start()
def parse_gcode_end_byte(self):
rev_data = self.footer_data[::-1]
m = re.search(r"\n.*\s\d+[MG]\n", rev_data)
if m is None:
return None
return self.size - m.start()
def parse_first_layer_height(self):
return None
def parse_layer_height(self):
return None
def parse_object_height(self):
return None
def parse_filament_total(self):
return None
def parse_estimated_time(self):
return None
def parse_first_layer_bed_temp(self):
return None
def parse_first_layer_extr_temp(self):
return None
def parse_thumbnails(self):
return None
class UnknownSlicer(BaseSlicer):
def check_identity(self, data):
return {'slicer': "Unknown"}
def parse_first_layer_height(self):
return self._parse_min_float(r"G1\sZ\d+\.\d*", self.header_data)
def parse_object_height(self):
return self._parse_max_float(r"G1\sZ\d+\.\d*", self.footer_data)
def parse_first_layer_extr_temp(self):
return _regex_find_first(
r"M109 S(\d+\.?\d*)", self.header_data)
def parse_first_layer_bed_temp(self):
return _regex_find_first(
r"M190 S(\d+\.?\d*)", self.header_data)
class PrusaSlicer(BaseSlicer):
def check_identity(self, data):
match = re.search(r"PrusaSlicer\s(.*)\son", data)
if match:
return {
'slicer': "PrusaSlicer",
'slicer_version': match.group(1)
}
return None
def parse_first_layer_height(self):
# Check percentage
pct = _regex_find_first(
r"; first_layer_height = (\d+)%", self.footer_data)
if pct is not None:
if self.layer_height is None:
# Failed to parse the original layer height, so it is not
# possible to calculate a percentage
return None
return round(pct / 100. * self.layer_height, 6)
return _regex_find_first(
r"; first_layer_height = (\d+\.?\d*)", self.footer_data)
def parse_layer_height(self):
self.layer_height = _regex_find_first(
r"; layer_height = (\d+\.?\d*)", self.footer_data)
return self.layer_height
def parse_object_height(self):
matches = re.findall(
r";BEFORE_LAYER_CHANGE\n(?:.*\n)?;(\d+\.?\d*)", self.footer_data)
if matches:
try:
matches = [float(m) for m in matches]
except Exception:
pass
else:
return max(matches)
return self._parse_max_float(r"G1\sZ\d+\.\d*\sF", self.footer_data)
def parse_filament_total(self):
return _regex_find_first(
r"filament\sused\s\[mm\]\s=\s(\d+\.\d*)", self.footer_data)
def parse_estimated_time(self):
time_match = re.search(
r';\sestimated\sprinting\stime.*', self.footer_data)
if not time_match:
return None
total_time = 0
time_match = time_match.group()
time_patterns = [(r"(\d+)d", 24*60*60), (r"(\d+)h", 60*60),
(r"(\d+)m", 60), (r"(\d+)s", 1)]
try:
for pattern, multiplier in time_patterns:
t = re.search(pattern, time_match)
if t:
total_time += int(t.group(1)) * multiplier
except Exception:
return None
return round(total_time, 2)
def parse_thumbnails(self):
thumb_matches = re.findall(
r"; thumbnail begin[;/\+=\w\s]+?; thumbnail end", self.header_data)
if not thumb_matches:
return None
thumb_dir = os.path.join(os.path.dirname(self.path), "thumbs")
if not os.path.exists(thumb_dir):
try:
os.mkdir(thumb_dir)
except Exception:
log_to_stderr(f"Unable to create thumb dir: {thumb_dir}")
return
thumb_base = os.path.splitext(os.path.basename(self.path))[0]
parsed_matches = []
for match in thumb_matches:
lines = re.split(r"\r?\n", match.replace('; ', ''))
info = _regex_find_ints(r".*", lines[0])
data = "".join(lines[1:-1])
if len(info) != 3:
log_to_stderr(
f"MetadataError: Error parsing thumbnail"
f" header: {lines[0]}")
continue
if len(data) != info[2]:
log_to_stderr(
f"MetadataError: Thumbnail Size Mismatch: "
f"detected {info[2]}, actual {len(data)}")
continue
thumb_name = f"{thumb_base}-{info[0]}x{info[1]}.png"
thumb_path = os.path.join(thumb_dir, thumb_name)
rel_thumb_path = os.path.join("thumbs", thumb_name)
with open(thumb_path, "wb") as f:
f.write(base64.b64decode(data.encode()))
parsed_matches.append({
'width': info[0], 'height': info[1],
'size': info[2], 'data': data,
'relative_path': rel_thumb_path})
return parsed_matches
def parse_first_layer_extr_temp(self):
return _regex_find_first(
r"; first_layer_temperature = (\d+\.?\d*)", self.footer_data)
def parse_first_layer_bed_temp(self):
return _regex_find_first(
r"; first_layer_bed_temperature = (\d+\.?\d*)", self.footer_data)
class Slic3rPE(PrusaSlicer):
def check_identity(self, data):
match = re.search(r"Slic3r\sPrusa\sEdition\s(.*)\son", data)
if match:
return {
'slicer': "Slic3r PE",
'slicer_version': match.group(1)
}
return None
def parse_filament_total(self):
return _regex_find_first(
r"filament\sused\s=\s(\d+\.\d+)mm", self.footer_data)
def parse_thumbnails(self):
return None
class Slic3r(Slic3rPE):
def check_identity(self, data):
match = re.search(r"Slic3r\s(\d.*)\son", data)
if match:
return {
'slicer': "Slic3r",
'slicer_version': match.group(1)
}
return None
def parse_estimated_time(self):
return None
class SuperSlicer(PrusaSlicer):
def check_identity(self, data):
match = re.search(r"SuperSlicer\s(.*)\son", data)
if match:
return {
'slicer': "SuperSlicer",
'slicer_version': match.group(1)
}
return None
class Cura(PrusaSlicer):
def check_identity(self, data):
match = re.search(r"Cura_SteamEngine\s(.*)", data)
if match:
return {
'slicer': "Cura",
'slicer_version': match.group(1)
}
return None
def parse_first_layer_height(self):
return _regex_find_first(r";MINZ:(\d+\.?\d*)", self.header_data)
def parse_layer_height(self):
self.layer_height = _regex_find_first(
r";Layer\sheight:\s(\d+\.?\d*)", self.header_data)
return self.layer_height
def parse_object_height(self):
return _regex_find_first(r";MAXZ:(\d+\.?\d*)", self.header_data)
def parse_filament_total(self):
filament = _regex_find_first(
r";Filament\sused:\s(\d+\.?\d*)m", self.header_data)
if filament is not None:
filament *= 1000
return filament
def parse_estimated_time(self):
return self._parse_max_float(r";TIME:.*", self.header_data)
def parse_first_layer_extr_temp(self):
return _regex_find_first(
r"M109 S(\d+\.?\d*)", self.header_data)
def parse_first_layer_bed_temp(self):
return _regex_find_first(
r"M190 S(\d+\.?\d*)", self.header_data)
def parse_thumbnails(self):
# Attempt to parse thumbnails from file metadata
thumbs = super().parse_thumbnails()
if thumbs is not None:
return thumbs
# Check for thumbnails extracted from the ufp
thumb_dir = os.path.join(os.path.dirname(self.path), "thumbs")
thumb_base = os.path.splitext(os.path.basename(self.path))[0]
thumb_path = os.path.join(thumb_dir, f"{thumb_base}.png")
rel_path_full = os.path.join("thumbs", f"{thumb_base}.png")
rel_path_small = os.path.join("thumbs", f"{thumb_base}-32x32.png")
thumb_path_small = os.path.join(thumb_dir, f"{thumb_base}-32x32.png")
if not os.path.isfile(thumb_path):
return None
# read file
thumbs = []
try:
with open(thumb_path, 'rb') as thumb_file:
fbytes = thumb_file.read()
with Image.open(io.BytesIO(fbytes)) as im:
thumb_full_b64 = base64.b64encode(fbytes).decode()
thumbs.append({
'width': im.width, 'height': im.height,
'size': len(thumb_full_b64), 'data': thumb_full_b64,
'relative_path': rel_path_full
})
# Create 32x32 thumbnail
im.thumbnail((32, 32), Image.ANTIALIAS)
tmp_thumb = io.BytesIO()
im.save(tmp_thumb, format="PNG")
im.save(thumb_path_small, format="PNG")
thumb_small_b64 = base64.b64encode(
tmp_thumb.getbuffer()).decode()
tmp_thumb.close()
thumbs.insert(0, {
'width': im.width, 'height': im.height,
'size': len(thumb_small_b64), 'data': thumb_small_b64,
'relative_path': rel_path_small
})
except Exception as e:
log_to_stderr(str(e))
return None
return thumbs
class Simplify3D(BaseSlicer):
def check_identity(self, data):
match = re.search(r"Simplify3D\(R\)\sVersion\s(.*)", data)
if match:
return {
'slicer': "Simplify3D",
'slicer_version': match.group(1)
}
return None
def parse_first_layer_height(self):
return self._parse_min_float(r"G1\sZ\d+\.\d*", self.header_data)
def parse_layer_height(self):
self.layer_height = _regex_find_first(
r";\s+layerHeight,(\d+\.?\d*)", self.header_data)
return self.layer_height
def parse_object_height(self):
return self._parse_max_float(r"G1\sZ\d+\.\d*", self.footer_data)
def parse_filament_total(self):
return _regex_find_first(
r";\s+Filament\slength:\s(\d+\.?\d*)\smm", self.footer_data)
def parse_estimated_time(self):
time_match = re.search(
r';\s+Build time:.*', self.footer_data)
if not time_match:
return None
total_time = 0
time_match = time_match.group()
time_patterns = [(r"(\d+)\shours", 60*60), (r"(\d+)\smin", 60),
(r"(\d+)\ssec", 1)]
try:
for pattern, multiplier in time_patterns:
t = re.search(pattern, time_match)
if t:
total_time += int(t.group(1)) * multiplier
except Exception:
return None
return round(total_time, 2)
def _get_temp_items(self, pattern):
match = re.search(pattern, self.header_data)
if match is None:
return []
return match.group().split(",")[1:]
def _get_first_layer_temp(self, heater):
heaters = self._get_temp_items(r"temperatureName.*")
temps = self._get_temp_items(r"temperatureSetpointTemperatures.*")
for h, temp in zip(heaters, temps):
if h == heater:
try:
return float(temp)
except Exception:
return None
return None
def parse_first_layer_extr_temp(self):
return self._get_first_layer_temp("Extruder 1")
def parse_first_layer_bed_temp(self):
return self._get_first_layer_temp("Heated Bed")
class KISSlicer(BaseSlicer):
def check_identity(self, data):
match = re.search(r";\sKISSlicer", data)
if match:
ident = {'slicer': "KISSlicer"}
vmatch = re.search(r";\sversion\s(.*)", data)
if vmatch:
version = vmatch.group(1).replace(" ", "-")
ident['slicer_version'] = version
return ident
return None
def parse_first_layer_height(self):
return _regex_find_first(
r";\s+first_layer_thickness_mm\s=\s(\d+\.?\d*)", self.header_data)
def parse_layer_height(self):
self.layer_height = _regex_find_first(
r";\s+max_layer_thickness_mm\s=\s(\d+\.?\d*)", self.header_data)
return self.layer_height
def parse_object_height(self):
return self._parse_max_float(
r";\sEND_LAYER_OBJECT\sz.*", self.footer_data)
def parse_filament_total(self):
filament = _regex_find_floats(
r";\s+Ext\s.*mm", self.footer_data, strict=True)
if filament:
return sum(filament)
return None
def parse_estimated_time(self):
time = _regex_find_first(
r";\sCalculated.*Build\sTime:\s(\d+\.?\d*)\sminutes",
self.footer_data)
if time is not None:
time *= 60
return round(time, 2)
return None
def parse_first_layer_extr_temp(self):
return _regex_find_first(
r"; first_layer_C = (\d+\.?\d*)", self.header_data)
def parse_first_layer_bed_temp(self):
return _regex_find_first(
r"; bed_C = (\d+\.?\d*)", self.header_data)
class IdeaMaker(BaseSlicer):
def check_identity(self, data):
match = re.search(r"\sideaMaker\s(.*),", data)
if match:
return {
'slicer': "IdeaMaker",
'slicer_version': match.group(1)
}
return None
def parse_first_layer_height(self):
layer_info = _regex_find_floats(
r";LAYER:0\s*.*\s*;HEIGHT.*", self.header_data)
if len(layer_info) >= 3:
return layer_info[2]
return None
def parse_layer_height(self):
layer_info = _regex_find_floats(
r";LAYER:1\s*.*\s*;HEIGHT.*", self.header_data)
if len(layer_info) >= 3:
self.layer_height = layer_info[2]
return self.layer_height
return None
def parse_object_height(self):
bounds = _regex_find_floats(
r";Bounding Box:.*", self.header_data)
if len(bounds) >= 6:
return bounds[5]
return None
def parse_filament_total(self):
filament = _regex_find_floats(
r";Material.\d\sUsed:.*", self.header_data, strict=True)
if filament:
return sum(filament)
return None
def parse_estimated_time(self):
return _regex_find_first(
r";Print\sTime:\s(\d+\.?\d*)", self.footer_data)
def parse_first_layer_extr_temp(self):
return _regex_find_first(
r"M109 T0 S(\d+\.?\d*)", self.header_data)
def parse_first_layer_bed_temp(self):
return _regex_find_first(
r"M190 S(\d+\.?\d*)", self.header_data)
class IceSL(BaseSlicer):
def check_identity(self, data):
match = re.search(r"; <IceSL.*>", data)
if match:
return {'slicer': "IceSL"}
return None
def parse_first_layer_height(self):
return _regex_find_first(
r"; z_layer_height_first_layer_mm :\s+(\d+\.\d+)",
self.header_data, float)
def parse_layer_height(self):
self.layer_height = _regex_find_first(
r"; z_layer_height_mm :\s+(\d+\.\d+)",
self.header_data, float)
return self.layer_height
def parse_object_height(self):
return self._parse_max_float(
r"G0 F\d+ Z\d+\.\d+", self.footer_data, strict=True)
def parse_first_layer_extr_temp(self):
return _regex_find_first(
r"; extruder_temp_degree_c_0 :\s+(\d+\.?\d*)", self.header_data)
def parse_first_layer_bed_temp(self):
return _regex_find_first(
r"; bed_temp_degree_c :\s+(\d+\.?\d*)", self.header_data)
READ_SIZE = 512 * 1024
SUPPORTED_SLICERS = [
PrusaSlicer, Slic3rPE, Slic3r, SuperSlicer,
Cura, Simplify3D, KISSlicer, IdeaMaker, IceSL]
SUPPORTED_DATA = [
'layer_height', 'first_layer_height', 'object_height',
'filament_total', 'estimated_time', 'thumbnails',
'first_layer_bed_temp', 'first_layer_extr_temp',
'gcode_start_byte', 'gcode_end_byte']
def extract_metadata(file_path):
metadata = {}
slicers = [s(file_path) for s in SUPPORTED_SLICERS]
header_data = footer_data = slicer = None
size = os.path.getsize(file_path)
metadata['size'] = size
metadata['modified'] = os.path.getmtime(file_path)
with open(file_path, 'r') as f:
# read the default size, which should be enough to
# identify the slicer
header_data = f.read(READ_SIZE)
for s in slicers:
ident = s.check_identity(header_data)
if ident is not None:
slicer = s
metadata.update(ident)
break
if slicer is None:
slicer = UnknownSlicer(file_path)
metadata['slicer'] = "Unknown"
if size > READ_SIZE * 2:
f.seek(size - READ_SIZE)
footer_data = f.read()
elif size > READ_SIZE:
remaining = size - READ_SIZE
footer_data = header_data[remaining - READ_SIZE:] + f.read()
else:
footer_data = header_data
slicer.set_data(header_data, footer_data, size)
for key in SUPPORTED_DATA:
func = getattr(slicer, "parse_" + key)
result = func()
if result is not None:
metadata[key] = result
return metadata
def main(path, filename):
file_path = os.path.join(path, filename)
metadata = {}
if not os.path.isfile(file_path):
log_to_stderr(f"File Not Found: {file_path}")
sys.exit(-1)
try:
metadata = extract_metadata(file_path)
except Exception:
log_to_stderr(traceback.format_exc())
sys.exit(-1)
fd = sys.stdout.fileno()
data = json.dumps(
{'file': filename, 'metadata': metadata}).encode()
while data:
try:
ret = os.write(fd, data)
except OSError:
continue
data = data[ret:]
if __name__ == "__main__":
# Parse start arguments
parser = argparse.ArgumentParser(
description="GCode Metadata Extraction Utility")
parser.add_argument(
"-f", "--filename", metavar='<filename>',
help="name gcode file to parse")
parser.add_argument(
"-p", "--path", default=os.path.abspath(os.path.dirname(__file__)),
metavar='<path>',
help="optional absolute path for file"
)
args = parser.parse_args()
main(args.path, args.filename)
+42
View File
@@ -0,0 +1,42 @@
#!/bin/bash
# Helper Script for fetching the API Key from a moonraker database
DATABASE_PATH="${HOME}/printer_data/database"
MOONRAKER_ENV="${HOME}/moonraker-env"
DB_ARGS="--read=READ --db=authorized_users get _API_KEY_USER_"
API_REGEX='(?<="api_key": ")([^"]+)'
print_help()
{
echo "Moonraker API Key Extraction Utility"
echo
echo "usage: fetch-apikey.sh [-h] [-e <python env path>] [-d <database path>]"
echo
echo "optional arguments:"
echo " -h show this message"
echo " -e <env path> path to Moonraker env folder"
echo " -d <database path> path to Moonraker LMDB database folder"
exit 0
}
# Parse command line arguments
while getopts "he:d:" arg; do
case $arg in
h) print_help;;
e) MOONRAKER_ENV=$OPTARG;;
d) DATABASE_PATH=$OPTARG;;
esac
done
PYTHON_BIN="${MOONRAKER_ENV}/bin/python"
if [ ! -f $PYTHON_BIN ]; then
echo "No Python binary found at '${PYTHON_BIN}'"
exit -1
fi
if [ ! -d $DATABASE_PATH ]; then
echo "No Moonraker database found at '${DATABASE_PATH}'"
exit -1
fi
${PYTHON_BIN} -mlmdb --env=${DATABASE_PATH} ${DB_ARGS} | grep -Po "${API_REGEX}"
+104
View File
@@ -0,0 +1,104 @@
#!/bin/bash
# Helper script for completing service upgrades via ssh
ADDRESS="localhost"
PORT="7125"
API_KEY=""
# Python Helper Scripts
check_sudo_request=$( cat << EOF
import sys
import json
try:
ret = json.load(sys.stdin)
except Exception:
exit(0)
entries = ret.get('result', {}).get('entries', [])
for item in entries:
if item['dismissed'] is False and item['title'] == 'Sudo Password Required':
sys.stdout.write('true')
exit(0)
sys.stdout.write('false')
EOF
)
check_pw_response=$( cat << EOF
import sys
import json
try:
ret = json.load(sys.stdin)
except Exception:
exit(0)
responses = ret.get('result', {}).get('sudo_responses', [])
if responses:
sys.stdout.write('\n'.join(responses))
EOF
)
print_help_message()
{
echo "Utility to complete privileged upgrades for Moonraker"
echo
echo "usage: finish-upgrade.sh [-h] [-a <address>] [-p <port>] [-k <api_key>]"
echo
echo "optional arguments:"
echo " -h show this message"
echo " -a <address> address for Moonraker instance"
echo " -p <port> port for Moonraker instance"
echo " -k <api_key> API Key for authorization"
}
while getopts "a:p:k:h" arg; do
case $arg in
a) ADDRESS=${OPTARG};;
b) PORT=${OPTARG};;
k) API_KEY=${OPTARG};;
h)
print_help_message
exit 0
;;
esac
done
base_url="http://${ADDRESS}:${PORT}"
echo "Completing Upgrade for Moonraker at ${base_url}"
echo "Requesting Announcements..."
ann_url="${base_url}/server/announcements/list"
curl_cmd=(curl -f -s -S "${ann_url}")
[ -n "${API_KEY}" ] && curl_cmd+=(-H "X-Api-Key: ${API_KEY}")
result="$( "${curl_cmd[@]}" 2>&1 )"
if [ $? -ne 0 ]; then
echo "Moonraker announcement request failed with error: ${result}"
echo "Make sure the address and port are correct. If authorization"
echo "is required supply the API Key with the -k option."
exit -1
fi
has_req="$( echo "$result" | python3 -c "${check_sudo_request}" )"
if [ "$has_req" != "true" ]; then
echo "No sudo request detected, aborting"
exit -1
fi
# Request Password, send to Moonraker
echo "Sudo request announcement found, please enter your password"
read -sp "Password: " passvar
echo -e "\n"
sudo_url="${base_url}/machine/sudo/password"
curl_cmd=(curl -f -s -S -X POST "${sudo_url}")
curl_cmd+=(-d "{\"password\": \"${passvar}\"}")
curl_cmd+=(-H "Content-Type: application/json")
[ -n "$API_KEY" ] && curl_cmd+=(-H "X-Api-Key: ${API_KEY}")
result="$( "${curl_cmd[@]}" 2>&1)"
if [ $? -ne 0 ]; then
echo "Moonraker password request failed with error: ${result}"
echo "Make sure you entered the correct password."
exit -1
fi
response="$( echo "$result" | python3 -c "${check_pw_response}" )"
if [ -n "${response}" ]; then
echo "${response}"
else
echo "Invalid response received from Moonraker. Raw result: ${result}"
fi
+168 -37
View File
@@ -2,23 +2,29 @@
# This script installs Moonraker on a Raspberry Pi machine running
# Raspbian/Raspberry Pi OS based distributions.
PYTHONDIR="${HOME}/moonraker-env"
PYTHONDIR="${MOONRAKER_VENV:-${HOME}/moonraker-env}"
SYSTEMDDIR="/etc/systemd/system"
REBUILD_ENV="n"
FORCE_DEFAULTS="n"
CONFIG_PATH="${HOME}/moonraker.conf"
REBUILD_ENV="${MOONRAKER_REBUILD_ENV:-n}"
FORCE_DEFAULTS="${MOONRAKER_FORCE_DEFAULTS:-n}"
DISABLE_SYSTEMCTL="${MOONRAKER_DISABLE_SYSTEMCTL:-n}"
SKIP_POLKIT="${MOONRAKER_SKIP_POLKIT:-n}"
CONFIG_PATH="${MOONRAKER_CONFIG_PATH}"
LOG_PATH="${MOONRAKER_LOG_PATH}"
DATA_PATH="${MOONRAKER_DATA_PATH}"
INSTANCE_ALIAS="${MOONRAKER_ALIAS:-moonraker}"
SERVICE_VERSION="1"
MACHINE_PROVIDER="systemd_cli"
# Step 1: Verify Klipper has been installed
check_klipper()
{
if [ "$(sudo systemctl list-units --full -all -t service --no-legend | grep -F "klipper.service")" ]; then
echo "Klipper service found!"
else
echo "Klipper service not found, please install Klipper first"
exit -1
fi
}
package_decode_script=$( cat << EOF
import sys
import json
try:
ret = json.load(sys.stdin)
except Exception:
exit(0)
sys.stdout.write(' '.join(ret['debian']))
EOF
)
# Step 2: Clean up legacy installation
cleanup_legacy() {
@@ -35,16 +41,30 @@ cleanup_legacy() {
# Step 3: Install packages
install_packages()
{
PKGLIST="python3-virtualenv python3-dev nginx libopenjp2-7 python3-libgpiod"
PKGLIST="${PKGLIST} liblmdb0 rsync zlib1g-dev"
# Update system package info
report_status "Running apt-get update..."
sudo apt-get update
sudo apt-get update --allow-releaseinfo-change
system_deps="${SRCDIR}/scripts/system-dependencies.json"
if [ -f "${system_deps}" ]; then
if [ ! -x "$(command -v python3)" ]; then
report_status "Installing python3 base package..."
sudo apt-get install --yes python3
fi
PKGS="$( cat ${system_deps} | python3 -c "${package_decode_script}" )"
else
echo "Error: system-dependencies.json not found, falling back to legacy pacakge list"
PKGLIST="${PKGLIST} python3-virtualenv python3-dev python3-libgpiod liblmdb-dev"
PKGLIST="${PKGLIST} libopenjp2-7 libsodium-dev zlib1g-dev libjpeg-dev packagekit"
PKGLIST="${PKGLIST} wireless-tools curl"
PKGS=${PKGLIST}
fi
# Install desired packages
report_status "Installing packages..."
sudo apt-get install --yes ${PKGLIST}
report_status "Installing Moonraker Dependencies:"
report_status "${PKGS}"
sudo apt-get install --yes ${PKGS}
}
# Step 4: Create python virtual environment
@@ -60,25 +80,74 @@ create_virtualenv()
if [ ! -d ${PYTHONDIR} ]; then
virtualenv -p /usr/bin/python3 ${PYTHONDIR}
ln -s /usr/lib/python3/dist-packages/gpiod* ${PYTHONDIR}/lib/python*/site-packages
#GET_PIP="${HOME}/get-pip.py"
#curl https://bootstrap.pypa.io/pip/3.6/get-pip.py -o ${GET_PIP}
#${PYTHONDIR}/bin/python ${GET_PIP}
#rm ${GET_PIP}
fi
# Install/update dependencies
${PYTHONDIR}/bin/pip install -r ${SRCDIR}/scripts/moonraker-requirements.txt
}
# Step 5: Install startup script
# Step 5: Initialize data folder
init_data_path()
{
report_status "Initializing Moonraker Data Path at ${DATA_PATH}"
config_dir="${DATA_PATH}/config"
logs_dir="${DATA_PATH}/logs"
env_dir="${DATA_PATH}/systemd"
config_file="${DATA_PATH}/config/moonraker.conf"
[ ! -e "${DATA_PATH}" ] && mkdir ${DATA_PATH}
[ ! -e "${config_dir}" ] && mkdir ${config_dir}
[ ! -e "${logs_dir}" ] && mkdir ${logs_dir}
[ ! -e "${env_dir}" ] && mkdir ${env_dir}
[ -n "${CONFIG_PATH}" ] && config_file=${CONFIG_PATH}
# Write initial configuration for first time installs
if [ ! -f $SERVICE_FILE ] && [ ! -e "${config_file}" ]; then
report_status "Writing Config File ${config_file}:\n"
/bin/sh -c "cat > ${config_file}" << EOF
# Moonraker Configuration File
[server]
host: 0.0.0.0
port: 7125
# Make sure the klippy_uds_address is correct. It is initialized
# to the default address.
klippy_uds_address: /tmp/klippy_uds
[machine]
provider: ${MACHINE_PROVIDER}
EOF
cat ${config_file}
fi
}
# Step 6: Install startup script
install_script()
{
# Create systemd service file
SERVICE_FILE="${SYSTEMDDIR}/moonraker.service"
# Create systemd service file
ENV_FILE="${DATA_PATH}/systemd/moonraker.env"
if [ ! -f $ENV_FILE ] || [ $FORCE_DEFAULTS = "y" ]; then
rm -f $ENV_FILE
args="MOONRAKER_ARGS=\"-m moonraker"
[ -n "${CONFIG_PATH}" ] && args="${args} -c ${CONFIG_PATH}"
[ -n "${LOG_PATH}" ] && args="${args} -l ${LOG_PATH}"
args="${args} -d ${DATA_PATH}"
args="${args}\""
args="${args}\nPYTHONPATH=\"${SRCDIR}\""
echo -e $args > $ENV_FILE
fi
[ -f $SERVICE_FILE ] && [ $FORCE_DEFAULTS = "n" ] && return
report_status "Installing system start script..."
sudo groupadd -f moonraker-admin
sudo /bin/sh -c "cat > ${SERVICE_FILE}" << EOF
#Systemd service file for moonraker
# systemd service file for moonraker
[Unit]
Description=Starts Moonraker on startup
After=network.target
Description=API Server for Klipper SV${SERVICE_VERSION}
Requires=network-online.target
After=network-online.target
[Install]
WantedBy=multi-user.target
@@ -86,23 +155,62 @@ WantedBy=multi-user.target
[Service]
Type=simple
User=$USER
SupplementaryGroups=moonraker-admin
RemainAfterExit=yes
ExecStart=${PYTHONDIR}/bin/python ${SRCDIR}/moonraker/moonraker.py -c ${CONFIG_PATH}
EnvironmentFile=${ENV_FILE}
ExecStart=${PYTHONDIR}/bin/python \$MOONRAKER_ARGS
Restart=always
RestartSec=10
EOF
# Use systemctl to enable the klipper systemd service script
sudo systemctl enable moonraker.service
if [ $DISABLE_SYSTEMCTL = "n" ]; then
sudo systemctl enable "${INSTANCE_ALIAS}.service"
sudo systemctl daemon-reload
fi
}
# Step 7: Validate/Install polkit rules
check_polkit_rules()
{
if [ ! -x "$(command -v pkaction)" ]; then
return
fi
POLKIT_VERSION="$( pkaction --version | grep -Po "(\d+\.?\d*)" )"
NEED_POLKIT_INSTALL="n"
if [ "$POLKIT_VERSION" = "0.105" ]; then
POLKIT_LEGACY_FILE="/etc/polkit-1/localauthority/50-local.d/10-moonraker.pkla"
# legacy policykit rules don't give users other than root read access
if sudo [ ! -f $POLKIT_LEGACY_FILE ]; then
NEED_POLKIT_INSTALL="y"
fi
else
POLKIT_FILE="/etc/polkit-1/rules.d/moonraker.rules"
POLKIT_USR_FILE="/usr/share/polkit-1/rules.d/moonraker.rules"
if [ ! -f $POLKIT_FILE ] && [ ! -f $POLKIT_USR_FILE ]; then
NEED_POLKIT_INSTALL="y"
fi
fi
if [ "${NEED_POLKIT_INSTALL}" = "y" ]; then
if [ "${SKIP_POLKIT}" = "y" ]; then
echo -e "\n*** No PolicyKit Rules detected, run 'set-policykit-rules.sh'"
echo "*** if you wish to grant Moonraker authorization to manage"
echo "*** system services, reboot/shutdown the system, and update"
echo "*** packages."
else
report_status "Installing PolKit Rules"
${SRCDIR}/scripts/set-policykit-rules.sh -z
MACHINE_PROVIDER="systemd_dbus"
fi
else
MACHINE_PROVIDER="systemd_dbus"
fi
}
# Step 6: Start server
# Step 8: Start server
start_software()
{
report_status "Launching Moonraker API Server..."
sudo systemctl stop klipper
sudo systemctl restart moonraker
sudo systemctl start klipper
sudo systemctl restart ${INSTANCE_ALIAS}
}
# Helper functions
@@ -126,19 +234,42 @@ set -e
SRCDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )"/.. && pwd )"
# Parse command line arguments
while getopts "rfc:" arg; do
while getopts "rfzxc:l:d:a:" arg; do
case $arg in
r) REBUILD_ENV="y";;
f) FORCE_DEFAULTS="y";;
z) DISABLE_SYSTEMCTL="y";;
x) SKIP_POLKIT="y";;
c) CONFIG_PATH=$OPTARG;;
l) LOG_PATH=$OPTARG;;
d) DATA_PATH=$OPTARG;;
a) INSTANCE_ALIAS=$OPTARG;;
esac
done
if [ -z "${DATA_PATH}" ]; then
if [ "${INSTANCE_ALIAS}" = "moonraker" ]; then
DATA_PATH="${HOME}/printer_data"
else
num="$( echo ${INSTANCE_ALIAS} | grep -Po "moonraker[-_]?\K\d+" || true )"
if [ -n "${num}" ]; then
DATA_PATH="${HOME}/printer_${num}_data"
else
DATA_PATH="${HOME}/${INSTANCE_ALIAS}_data"
fi
fi
fi
SERVICE_FILE="${SYSTEMDDIR}/${INSTANCE_ALIAS}.service"
# Run installation steps defined above
verify_ready
check_klipper
cleanup_legacy
install_packages
create_virtualenv
init_data_path
install_script
start_software
check_polkit_rules
if [ $DISABLE_SYSTEMCTL = "n" ]; then
start_software
fi
+57
View File
@@ -0,0 +1,57 @@
#! /usr/bin/python3
# Create system dependencies json file from the install script
#
# Copyright (C) 2023 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import argparse
import pathlib
import json
import re
from typing import List, Dict
def make_sysdeps(input: str, output: str, distro: str, truncate: bool) -> None:
sysdeps: Dict[str, List[str]] = {}
outpath = pathlib.Path(output).expanduser().resolve()
if outpath.is_file() and not truncate:
sysdeps = json.loads(outpath.read_bytes())
inst_path: pathlib.Path = pathlib.Path(input).expanduser().resolve()
if not inst_path.is_file():
raise Exception(f"Unable to locate install script: {inst_path}")
data = inst_path.read_text()
plines: List[str] = re.findall(r'PKGLIST="(.*)"', data)
plines = [p.lstrip("${PKGLIST}").strip() for p in plines]
packages: List[str] = []
for line in plines:
packages.extend(line.split())
sysdeps[distro] = packages
outpath.write_text(json.dumps(sysdeps, indent=4))
if __name__ == "__main__":
def_path = pathlib.Path(__file__).parent
desc = (
"make_sysdeps - generate system dependency json file from an install script"
)
parser = argparse.ArgumentParser(description=desc)
parser.add_argument(
"-i", "--input", metavar="<install script>",
help="path of the install script to read",
default=f"{def_path}/install-moonraker.sh"
)
parser.add_argument(
"-o", "--output", metavar="<output file>",
help="path of the system dependency file to write",
default=f"{def_path}/system-dependencies.json"
)
parser.add_argument(
"-d", "--distro", metavar="<linux distro>",
help="linux distro for dependencies", default="debian"
)
parser.add_argument(
"-t", "--truncate", action="store_true",
help="truncate output file"
)
args = parser.parse_args()
make_sysdeps(args.input, args.output, args.distro, args.truncate)
+15 -4
View File
@@ -1,6 +1,17 @@
# Python dependencies for Moonraker
tornado==6.1.0
tornado==6.2.0
pyserial==3.4
pillow==8.1.2
lmdb==1.1.1
streaming-form-data==1.8.1
pyserial-asyncio==0.6
pillow==9.3.0
lmdb==1.3.0
streaming-form-data==1.11.0
distro==1.8.0
inotify-simple==1.3.5
libnacl==1.8.0
paho-mqtt==1.6.1
zeroconf==0.39.4
preprocess-cancellation==0.2.0
jinja2==3.1.2
dbus-next==0.2.3
apprise==1.2.1
ldap3==2.9.1
Loaded 100 of 147 files, more files were not shown because too many files have changed in this diff. Show more