216 Commits
Author SHA1 Message Date
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
46 changed files with 9128 additions and 3920 deletions

No files matched your search

+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: KevinOConnor/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-18.04
steps:
- uses: actions/checkout@v1
- 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=80 --max-doc-length=80"
extra-mypy-options: "--ignore-missing-imports --follow-imports=silent"
+42
View File
@@ -1,6 +1,48 @@
##
This document keeps a record of all changes to Moonraker's web APIs.
### 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
+71 -10
View File
@@ -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)
```
@@ -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.
+165 -27
View File
@@ -20,6 +20,16 @@ host: 0.0.0.0
# to all interfaces
port: 7125
# The port the HTTP server will listen on. Default is 7125
ssl_port: 7130
# The port to listen on for SSS (HTTPS) connections. Note that the HTTPS
# server will only be started of the certificate and key options outlined
# below are provied. The default is 7130.
ssl_certificate_path:
# The path to a self signed ssl certificate. The default is no path, which
# disables HTTPS.
ssl_key_path:
# The path to the private key used to signed the certificate. The default
# is no path, which disables HTTPS.
klippy_uds_address: /tmp/klippy_uds
# The address of Unix Domain Socket used to communicate with Klippy. Default
# is /tmp/klippy_uds
@@ -41,6 +51,10 @@ database_path: ~/.moonraker_database
# Moonraker (such as the "config_path" or the location where gcode
# files are stored). If the folder does not exist an attempt will be made
# to create it. The default is ~/.moonraker_database.
log_path:
# An optional path to a directory where log files are located. Users may
# configure various applications to store logs here and Moonraker will serve
# them at "/server/files/logs/*". The default is no log paths.
enable_database_debug: False
# For developer use only. End users should leave this option set to False.
temperature_store_size: 1200
@@ -65,15 +79,17 @@ login_timeout:
# credentials to log in. This period begins when a logged out user
# first logs in. Successive logins without logging out will not
# renew the timeout. The default is 90 days.
trusted_clients:
192.168.1.30
192.168.1.0/24
# A list of newline separated ip addresses and/or ip ranges that are
# trusted. Trusted clients are given full access to the API. Both IPv4
# and IPv6 addresses and ranges are supported. Ranges must be expressed
# in CIDR notation (see http://ip.sb/cidr for more info). For example, an
# entry of 192.168.1.0/24 will authorize IPs in the range of 192.168.1.1 -
# 192.168.1.254. Note that when specifying IPv4 ranges the last segment
# of the ip address must be 0. The default is no clients or ranges are
my-printer.lan
# A list of newline separated ip addresses, ip ranges, or fully qualified
# domain names that are trusted. Trusted clients are given full access to
# the API. Both IPv4 and IPv6 addresses and ranges are supported. Ranges
# must be expressed in CIDR notation (see http://ip.sb/cidr for more info).
# For example, an entry of 192.168.1.0/24 will authorize IPs in the range of
# 192.168.1.1 - 192.168.1.254. Note that when specifying IPv4 ranges the
# last segment of the ip address must be 0. The default is no clients are
# trusted.
cors_domains:
http://klipper-printer.local
@@ -92,6 +108,11 @@ cors_domains:
# When CORS is enabled by adding an entry to this option, all origins
# matching the "trusted_clients" option will have CORS headers set as
# well. If this option is not specified then CORS is disabled.
force_logins: False
# When set to True a user login is required for authorization if at least
# one user has been created, overriding the "trusted_clients" configuration.
# If no users have been created then trusted client checks will apply.
# The default is False.
```
## `[octoprint_compat]`
@@ -170,7 +191,7 @@ gcode:
## `[power]`
Enables device power control. Currently GPIO (relays), TPLink Smartplug,
and Tasmota (via http) devices are supported.
and Tasmota (via http) devices, HomeAssistant switch are supported.
```ini
# moonraker.conf
@@ -178,7 +199,7 @@ and Tasmota (via http) devices are supported.
[power device_name]
type: gpio
# The type of device. Can be either gpio, tplink_smartplug, tasmota
# or homeseer.
# shelly, homeseer, homeassistant, or loxonev1.
# This parameter must be provided.
off_when_shutdown: False
# If set to True the device will be powered off when Klipper enters
@@ -212,8 +233,11 @@ address:
port:
# The above options are used for "tplink_smartplug" devices. The
# address should be a valid ip or hostname for the tplink device.
# The port should be the port the device is configured to use. The
# address must be provided. The port defaults to 9999.
# The port should be the port the device is configured to use.
# "Power Strips" can be controlled by including the socket index
# in the ip address. For example, to control socket index 1:
# 192.168.1.127/1
# The address must be provided. The port defaults to 9999.
address:
password:
output_id:
@@ -236,10 +260,10 @@ timer:
# Provide a user and password if configured in Shelly (default is empty).
# If password is set but user is empty the default user "admin" will be used
# Provided an output_id (relay id) if the Shelly device supports
# more than one (default is 0).
# When timer option is used to delay the turn off make sure to set
# the state to "on" in action call_remote_method.
# So we send a command to turn it on for x sec when its already on then it turns off.
# more than one (default is 0). When timer option is used to delay the turn
# off make sure to set the state to "on" in action call_remote_method.
# So we send a command to turn it on for x sec when its already on then
# it turns off.
address:
device:
user:
@@ -253,7 +277,26 @@ password:
# "ID" in the "advanced information" section.
# Provide a user and password with access to "device control"
# and at least the specific device you want to control
address:
port:
device:
token:
domain:
# The above options are used for "homeassistant" devices. The
# address should be a valid ip or hostname for the homeassistant controller.
# "device" should be the ID of the switch to control.
# "domain" is the class of device set managed by homeassistant, defaults to "switch".
address:
user:
password:
output_id:
# The above options are used for "loxone smart home miniserver v1 " devices.
# The address should be a valid ip or hostname for the loxone miniserver v1
# device. All entries must be configured in advance in the loxone config.
# Provide a user and password configured in loxone config.
# The output_id is the name of a programmed output, virtual input or virtual
# output in the loxone config his output_id (name) may only be used once in
# the loxone config
```
Below are some potential examples:
```ini
@@ -289,6 +332,14 @@ type: shelly
address: 192.168.1.125
user: user2
password: password2
[power homeassistant_switch]
type: homeassistant
address: 192.168.1.126
port: 8123
device: switch.1234567890abcdefghij
token: home-assistant-very-long-token
domain: switch
```
It is possible to toggle device power from the Klippy host, this can be done
@@ -317,7 +368,7 @@ gcode:
[idle_timeout]
gcode:
TURN_OFF_MOTORS
M84
TURN_OFF_HEATERS
UPDATE_DELAYED_GCODE ID=delayed_printer_off DURATION=60
```
@@ -343,10 +394,22 @@ enable_auto_refresh: False
# When set to False Moonraker will only fetch update state on startup
# and clients will need to request that Moonraker updates state. The
# default is False.
distro: debian
# The disto in which moonraker has been installed. Currently the
# update manager only supports "debian", which encompasses all of
# its derivatives. The default is debain.
enable_system_updates: True
# A boolean value that can be used to toggle system package updates.
# Currently Moonraker only supports updating packages via APT, so
# this option is useful for users that wish to experiment with linux
# distros that use other package management applications, or users
# that prefer to manage their packages directly. Note that if this
# is set to False users will be need to make sure that all system
# dependencies are up to date. The default is True.
channel: dev
# The update channel applied to Klipper and Moonraker. May be 'dev'
# which will fetch updates using git, or 'beta' which will fetch
# zipped beta releases. Note that this channel does not apply to
# client updates, a client's update channel is determined by its
# 'type' option. When this option is changed the next "update" will
# swap channels, any untracked files in the application's path will be
# removed during this process. The default is dev.
```
### Client Configuration
@@ -361,8 +424,9 @@ service restart such as Fluidd/Mainsail.
```ini
# moonraker.conf
[update_manager client client_name]
[update_manager client_name]
type: web
# Indicates that this is a web client.
repo:
# This is the GitHub repo of the client, in the format of user/client.
# For example, this could be set to cadriel/fluidd to update Fluidd or
@@ -375,21 +439,29 @@ persistent_files:
# themes. The default is no persistent files.
```
This second example is for git repositories that have a service that need
updating.
This second example is for "applications". These may be git repositories
or zipped distributions.
Note that git repos must have at least one tag for Moonraker
to identify its version.
```ini
# moonraker.conf
# service_name must be the name of the systemd service
[update_manager client service_name]
[update_manager service_name]
type: git_repo
# Can be git_repo, zip, or zip_beta. See your the client's documentation
# for recommendations on which value to use. Generally a git_repo is
# an applications "dev" channel, zip_beta is its "beta" channel, and zip
# is its "stable" channel. This parameter must be provided.
path:
# The absolute path to the client's files on disk. This parameter must be provided.
# The absolute path to the client's files on disk. This parameter must be
# provided.
# Example:
# path: ~/service_name
origin:
# The full GitHub URL of the "origin" remote for the repository. This can
# The full git URL of the "origin" remote for the repository. This can
# be be viewed by navigating to your repository and running:
# git remote -v
# This parameter must be provided.
@@ -416,4 +488,70 @@ enable_node_updates:
# to package-lock.json. Note that if your project does not have a
# package-lock.json in its root directory then the plugin will fail to load.
# Default is False.
host_repo:
# The GitHub repo in which zipped releases are hosted. Note that this does
# not need to match the repository in the "origin" option, as it is possible
# to use a central GitHub repository to host multiple client builds. As
# an example, Moonraker's repo hosts builds for both Moonraker and Klipper.
# This option defaults to the repo extracted from the "origin" option,
# however if the origin is not hosted on GitHub then this parameter must
# be provided.
```
## `[mqtt]`
Enables an MQTT Client. When configured most of Moonraker's APIs are availble
by publishing JSON-RPC requests to `{instance_name}/moonraker/api/request`.
Responses will be published to `{instance_name}/moonraker/api/response`. See
the [API Documentation](web_api.md#json-rpc-api-overview) for details on
on JSON-RPC.
It is also possible for other components within Moonraker to use MQTT to
publish and subscribe to topics.
```ini
[mqtt]
address:
# Address of the Broker. This may be a hostname or IP Address. This
# parameter must be provided.
port:
# Port the Broker is listening on. Default is 1883.
username:
# An optional username used to log in to the Broker. Default is no
# username (an anonymous login will be attempted)
password_file:
# An optional path to a text file containing a password used to log in
# to the broker. It is strongly recommended that this file be located
# in a folder not served by Moonraker. It is also recommended that the
# password be unique and not used for other logins, as it is stored in
# plain text. To create a password file, one may ssh in to the device
# and enter the following commands:
# cd ~
# echo mypassword > .mqttpass
# Then set this option to:
# ~/.mqttpass
# If this option is omitted no password will be used to login.
mqtt_protocol: v3.1.1
# The protocol to use when connecting to the Broker. May be v3.1,
# v3.1.1, and v5. The default is v3.1.1
enable_moonraker_api: True
# If set to true the MQTT client will subscribe to API topic, ie:
# {instance_name}/moonraker/api/request
# This can be set to False if the user does not wish to allow API
# requests over MQTT. The default is True.
instance_name:
# An identifer used to create unique API topics for each instance of
# Moonraker on network. This name cannot contain wildcards (+ or #).
# For example, if the instance name is set to my_printer, Moonraker
# will subscribe to the following topic for API requests:
# my_printer/moonraker/api/request
# Responses will be published to the following topic:
# my_printer/moonraker/api/response
# The default is the machine's hostname.
default_qos: 0
# The default QOS level used when publishing or subscribing to topics.
# Must be an integer value from 0 to 2. The default is 0.
api_qos:
# The QOS level to use for the API topics. If not provided, the
# value specified by "default_qos" will be used.
```
+13 -2
View File
@@ -15,8 +15,19 @@ are near those of Klipper:
#
# This file may be distributed under the terms of the GNU GPLv3 license
- No line in the source code or documentation should exceed 80 characters.
Be sure there is no trailing whitespace.
- 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.
- Python code should be fully annotated. Moonraker uses the `mypy` static
type checker for code validation with the following options:
- `--ignore-missing-imports`
- `--follow-imports=silent`
- Each Commit message should be in the following format:
module name: brief description of commit
+1 -1
View File
@@ -1 +1 @@
mkdocs==1.1.2
mkdocs==1.2.1
+7 -2
View File
@@ -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.
+554 -98
View File
@@ -1,10 +1,10 @@
#
Most API methods are supported over both the Websocket and HTTP transports.
File Transfer and `/access` requests are only available over HTTP. The
Websocket is required to receive server generated events such as gcode
responses. For information on how to set up the Websocket, please see the
Appendix at the end of this document.
Most API methods are supported over the Websocket, HTTP, and MQTT
(if configured) transports. File Transfer and `/access` requests are only
available over HTTP. The Websocket is required to receive server generated
events such as gcode responses. For information on how to set up the
Websocket, please see the Appendix at the end of this document.
### HTTP API Overview
@@ -71,10 +71,19 @@ thus using this functionality should be seen as a "last resort." If at
all possible clients should attempt to put these arguments in the body
of a request.
### Websocket API Overview
### JSON-RPC API Overview
The Websocket API is based on JSON-RPC, an encoded request should look
something like:
The Websocket and MQTT transports use the [JSON-RPC 2.0](https://jsonrpc.org)
protocol. The Websocket transmits objects in a text frame, whereas MQTT
transmits them in the payload of a topic. When MQTT is configured Moonraker
subscribes to an api request topic. After an api request is processed Moonraker
publishes the return value to a response topic. By default these topics are
`{instance_name}/moonraker/api/request` and
`{instance_name}/moonraker/api/response`. The `{instance_name}` should be a
unique identifier for each instance of Moonraker and defaults to the machine's
host name.
An encoded request should look something like:
```json
{
"jsonrpc": "2.0",
@@ -85,10 +94,19 @@ something like:
```
The `params` field may be left out if the API request takes no arguments.
The `id` should be a unique integer value that has no chance of colliding
The `id` should be a unique value that has no chance of colliding
with other JSON-RPC requests. The `method` is the API method, as defined
for each API in this document.
!!! tip
MQTT requests may provide an optional `mqtt_timestamp` keyword
argument in the `params` field of the JSON-RPC request. To avoid
potential collisions from time drift it is recommended to specify
the timestamp in microseconds since the Unix Epoch. If provided
Moonraker will use the timestamp to discard duplicate requests.
It is recommended to either provide a timestamp or publish API
requests at a QoS level of 0 or 2.
A successful request will return a response like the following:
```json
{
@@ -114,7 +132,7 @@ Some errors may not return a request ID, such as an improperly formatted request
The `test/client` folder includes a basic test interface with example usage for
most of the requests below. It also includes a basic JSON-RPC implementation
that uses promises to return responses and errors (see json-rcp.js).
that uses promises to return responses and errors (see json-rpc.js).
### Printer Administration
@@ -303,6 +321,9 @@ POST /printer/objects/subscribe?connection_id=123456789&gcode_move&extruder`
request that includes only the `connection_id` argument will cancel the
subscription on the specified websocket.
This request is not available over MQTT, as it is not possible to
associate a connected websocket with an MQTT client.
JSON-RPC request:
```json
{
@@ -415,7 +436,11 @@ An object containing various fields that report server state.
"power"
],
"failed_components": [],
"registered_directories": ["config", "gcodes", "config_examples", "docs"]
"registered_directories": ["config", "gcodes", "config_examples", "docs"],
"warnings": [
"Invalid config option 'api_key_path' detected in section [authorization]. Remove the option to resolve this issue. In the future this will result in a startup error.",
"Unparsed config section [fake_section] detected. This may be the result of a component that failed to load. In the future this will result in a startup error."
]
}
```
!!! warning
@@ -787,6 +812,64 @@ Returns:
### Machine Commands
#### Get System Info
HTTP request:
```http
GET /machine/system_info
```
JSON-RPC request:
```json
{
"jsonrpc": "2.0",
"method": "machine.system_info",
"id": 4665
}
```
Returns: Information about the host system in the following format:
```json
{
"system_info": {
"available_services": ["moonraker", "klipper"],
"cpu_info": {
"cpu_count": 1,
"bits": "32bit",
"processor": "armv6l",
"cpu_desc": "ARMv6-compatible processor rev 7 (v6l)",
"hardware_desc": "BCM2835",
"model": "Raspberry Pi Zero W Rev 1.1",
"total_memory": 439276,
"memory_units": "kB"
},
"sd_info": {
"manufacturer_id": "03",
"manufacturer": "Sandisk",
"oem_id": "5344",
"product_name": "SS08G",
"product_revision": "8.0",
"serial_number": "00112233",
"manufacturer_date": "9/2017",
"capacity": "7.4 GiB",
"total_bytes": 7948206080
},
"distribution": {
"name": "Raspbian GNU/Linux 10 (buster)",
"id": "raspbian",
"version": "10",
"version_parts": {
"major": "10",
"minor": "",
"build_number": ""
},
"like": "debian",
"codename": "buster"
}
}
}
```
!!! note
If no SD Card is detected the `sd_info` field will contain an empty object.
#### Shutdown the Operating System
HTTP request:
```http
@@ -825,7 +908,8 @@ and the socket connection will drop.
#### Restart a system service
Restarts a system service via `sudo systemctl restart {name}`. Currently
only the `moonraker`, `klipper`, and `webcamd` services are supported.
the `moonraker`, `klipper`, `MoonCord`, `KlipperScreen` and `webcamd`
services are supported.
HTTP request:
```http
@@ -934,7 +1018,8 @@ An object in the following format:
"throttled_state": {
"bits": 0,
"flags": []
}
},
"cpu_temp": 46.148
}
```
Process information is sampled every second. The `moonraker_stats` field
@@ -970,6 +1055,10 @@ whereas the last four indicate a previous condition (may or
may not still be active). If `vcgencmd` is not available
`throttled_state` will report `null`.
If the system reports CPU temp at `/sys/class/thermal/thermal_zone0`
then temperature will be supplied in the `cpu_temp` field. Otherwise
the field will be set to `null`.
### File Operations
Most file operations are available over both APIs, however file upload and
@@ -1022,27 +1111,27 @@ A list of objects, where each object contains file data.
```json
[
{
"filename": "3DBenchy_0.15mm_PLA_MK3S_2h6m.gcode",
"path": "3DBenchy_0.15mm_PLA_MK3S_2h6m.gcode",
"modified": 1615077020.2025201,
"size": 4926481
},
{
"filename": "Shape-Box_0.2mm_PLA_Ender2_20m.gcode",
"path": "Shape-Box_0.2mm_PLA_Ender2_20m.gcode",
"modified": 1614910966.946807,
"size": 324236
},
{
"filename": "test_dir/A-Wing.gcode",
"path": "test_dir/A-Wing.gcode",
"modified": 1605202259,
"size": 1687387
},
{
"filename": "test_dir/CE2_CubeTest.gcode",
"path": "test_dir/CE2_CubeTest.gcode",
"modified": 1614644445.4025,
"size": 1467339
},
{
"filename": "test_dir/V350_Engine_Block_-_2_-_Scaled.gcode",
"path": "test_dir/V350_Engine_Block_-_2_-_Scaled.gcode",
"modified": 1615768477.5133543,
"size": 189713016
},
@@ -1098,15 +1187,13 @@ modified time, and size.
"width": 32,
"height": 32,
"size": 2596,
"data": "{base64_data}"
"relative_path": "thumbs/3DBenchy_0.15mm_PLA_MK3S_2h6m-32x32.png"
"relative_path": ".thumbs/3DBenchy_0.15mm_PLA_MK3S_2h6m-32x32.png"
},
{
"width": 400,
"height": 300,
"size": 73308,
"data": "{base64_data}",
"relative_path": "thumbs/3DBenchy_0.15mm_PLA_MK3S_2h6m-400x300.png"
"relative_path": ".thumbs/3DBenchy_0.15mm_PLA_MK3S_2h6m-400x300.png"
}
],
"first_layer_bed_temp": 60,
@@ -1121,11 +1208,6 @@ modified time, and size.
`null`. They will be updated for each print job if the user has the
`[history]` component configured
!!! warning
The `data` field for each thumbnail is deprecated and will be removed
in a future release. Clients should retrieve the png directly using the
`relative_path` field.
#### Get directory information
Returns a list of files and subdirectories given a supplied path.
Unlike `/server/files/list`, this command does not walk through
@@ -1225,9 +1307,16 @@ JSON-RPC request:
}
```
Returns:
`ok`
Returns: Information about the created directory
```json
{
"item": {
"path": "gcodes/testdir",
"root": "gcodes"
},
"action": "create_dir"
}
```
#### Delete directory
Deletes a directory at the specified path.
@@ -1252,9 +1341,16 @@ JSON-RPC request:
If the specified directory contains files then the delete request
will fail unless the `force` argument is set to `true`.
Returns:
`ok`
Returns: Information about the deleted directory
```json
{
"item": {
"path": "gcodes/testdir",
"root": "gcodes"
},
"action": "delete_dir"
}
```
#### Move a file or directory
Moves a file or directory from one location to another. The following
@@ -1291,9 +1387,22 @@ JSON-RPC request:
}
```
Returns:
`ok`
Returns: Information about the moved file or directory
```json
{
"result": {
"item": {
"root": "gcodes",
"path": "test4/test3"
},
"source_item": {
"path": "gcodes/test4/test3",
"root": "gcodes"
},
"action": "move_dir"
}
}
```
#### Copy a file or directory
Copies a file or directory from one location to another. A successful copy has
@@ -1318,9 +1427,16 @@ JSON-RPC request:
}
```
Returns:
`ok`
Returns: Information about the copied file or directory
```json
{
"item": {
"root": "gcodes",
"path": "test4/Voron_v2_350_aferburner_Filament Cover_0.2mm_ABS.gcode"
},
"action": "create_file"
}
```
#### File download
Retreives file `filename` at root `root`. The `filename` must include
@@ -1347,40 +1463,48 @@ below.
HTTP request:
```http
POST /server/files/upload`
Content-Type: multipart/form-data
------FormBoundaryemap3PkuvKX0B3HH
Content-Disposition: form-data; name="file"; filename="myfile.gcode"
Content-Type: application/octet-stream
<binary data>
------FormBoundaryemap3PkuvKX0B3HH--
```
The file must be uploaded in the request's body `multipart/form-data` (ie:
`<input type="file">`). The following fields may also be added to the form:
`<input type="file">`). The following arguments may also be added to the
form-data:
- `root`: The root location in which to upload the file. Currently this may
be `gcodes` or `config`. If not specified the default is `gcodes`.
be `gcodes` or `config`. If not specified the default is `gcodes`.
- `path`: This argument may contain a path (relative to the root) indicating
a subdirectory to which the file is written. If a `path` is present the
server will attempt to create any subdirectories that do not exist.
a subdirectory to which the file is written. If a `path` is present the
server will attempt to create any subdirectories that do not exist.
- `checksum`: A SHA256 hex digest calculated by the client for the uploaded
file. If this argument is supplied the server will compare it to its own
checksum calculation after the upload has completed. A checksum mismatch
will result in a 422 error.
Arguments available only for the `gcodes` root:
- `print`: If set to "true", Klippy will attempt to start the print after
uploading. Note that this value should be a string type, not boolean. This
provides compatibility with Octoprint's legacy upload API.
uploading. Note that this value should be a string type, not boolean. This
provides compatibility with Octoprint's legacy upload API.
JSON-RPC request: Not Available
Returns:
The name of the uploaded file.
Returns: Information about the uploaded file. Note that `print_started`
is only included when the supplied root is set to `gcodes`.
```json
{
"result": "{file_name}"
}
```
If the supplied root is "gcodes", a "print_started" field is also
returned.
```json
{
"result": "{file_name}",
"print_started": false
"item": {
"path": "Lock Body Shim 1mm_0.2mm_FLEX_MK3S_2h30m.gcode",
"root": "gcodes"
},
"print_started": false,
"action": "create_file"
}
```
@@ -1403,9 +1527,16 @@ JSON-RPC request:
"id": 1323
}
```
Returns:
The name of the deleted file
Returns: Information about the deleted file
```json
{
"item": {
"path": "Lock Body Shim 1mm_0.2mm_FLEX_MK3S_2h30m.gcode",
"root": "gcodes"
},
"action": "delete_file"
}
```
#### Download klippy.log
HTTP request:
@@ -1439,10 +1570,15 @@ Moonraker's HTTP APIs. JWTs should be included in the `Authorization`
header as a `Bearer` type for each HTTP request. If using an API Key it
should be included in the `X-Api-Key` header for each HTTP Request.
!!! note
For requests in which clients cannot modify headers it is acceptable
to pass the JWT via the query string's `access_token` argument.
Alternatively client developers may request a `oneshot_token` and
send the result via the `token` query string argument.
!!! warning
Clients should not use the query string to pass arguments to these
APIs. Arguments may be passed as part of the body either in JSON
format or as form-data.
It is strongly recommended that arguments for the below APIs are
passed in the request's body.
#### Login User
HTTP Request:
@@ -1540,7 +1676,12 @@ logs the user in.
or be logged in as another user.
#### Delete User
Deletes the currently logged in user.
Deletes a registered user.
!!! note
A request to delete a user MUST come from an authorized source
other than the account to be deleted. This can be a "trusted user",
the "api key user", or any other user account.
HTTP Request:
```http
@@ -1548,13 +1689,13 @@ DELETE /access/user
Content-Type: application/json
{
"password": "my_password"
"username": "my_username"
}
```
JSON-RPC request: Not Available
Returns: The username of the deleted user and an action summary. This
effectively logs the user out.
effectively logs the user out, as all outstanding tokens will be invalid.
```json
{
"username": "my_user",
@@ -1562,6 +1703,29 @@ effectively logs the user out.
}
```
#### List Available Users
HTTP Request:
```http
GET /access/users/list
```
JSON-RPC request: Not Available
Returns: A list of created users on the system
```json
{
"users": [
{
"username": "testuser",
"created_on": 1618771331.1685035
},
{
"username": "testuser2",
"created_on": 1620943153.0191233
}
]
}
```
#### Reset User Password
HTTP Request:
```http
@@ -1893,6 +2057,10 @@ and `fluidd` are present as clients configured in `moonraker.conf`
]
},
"moonraker": {
"type": "zip_beta",
"channel": "beta",
"need_channel_update": false,
"pristine": true,
"remote_alias": "origin",
"branch": "master",
"owner": "Arksine",
@@ -1920,6 +2088,10 @@ and `fluidd` are present as clients configured in `moonraker.conf`
"remote_version": "v1.10.0"
},
"klipper": {
"type": "zip_beta",
"channel": "beta",
"need_channel_update": false,
"pristine": true,
"remote_alias": "origin",
"branch": "master",
"owner": "KevinOConnor",
@@ -1969,9 +2141,23 @@ Below is an explanation for each field:
reported as seconds since the epoch (aka Unix Time).
The `moonraker`, `klipper` packages, along with and clients configured
as git repos have the following fields:
as applications have the following fields:
- `owner`: the owner of the repo
- `configured_type`: the application type configured by the user
- `detected_type`: the applicaiton type as detected by Moonraker.
- `channel`: the currently configured update channel. For Moonraker
and Klipper this is set in the `[update_manager]` configuration.
For clients the channel is determined by the configured type
- `need_channel_update`: This will be set to `true` if Moonraker has
detected that a channel swap is necessary (ie: the configured type does
not match the detected type). The channel swap will be performed on the
next update.
- `pristine`: For `zip` and `zip_beta` types this is set to `true` if an
applications source checksum matches the one generated when the app was
built. This value will be set to the opposite of "dirty" for git repos.
Note that a zip application can still be updated if the repo is not
pristine.
- `owner`: the owner of the repo / application
- `branch`: the name of the current git branch. This should typically
be "master".
- `remote_alias`: the alias for the remote. This should typically be
@@ -1982,9 +2168,14 @@ as git repos have the following fields:
- `current_hash`: hash of the most recent commit on disk
- `remote_hash`: hash of the most recent commit pushed to the remote
- `is_valid`: true if installation is a valid git repo on the master branch
and an "origin" set to the official remote
- `is_dirty`: true if the repo has been modified
- `detached`: true if the repo is currently in a detached state
and an "origin" set to the official remote. For `zip` and `zip_beta`
types this will report false if Moonraker is unable to fetch the
current repo state from GitHub.
- `is_dirty`: true if the repo has been modified. This will always be false
for `zip` and `zip_beta` types.
- `detached`: true if the repo is currently in a detached state. For `zip`
and `zip_beta` types it is considered detached if the local release info
does not match what is present on the remote.
- `debug_enabled`: True when `enable_repo_debug` has been configured. This
will bypass repo validation allowing detached updates, and updates from
a remote/branch other than than the primary (typically origin/master).
@@ -2011,6 +2202,32 @@ The `system` package has the following fields:
- `package_list`: an array containing the names of packages available
for update
### Perform a full update
Attempts to update all configured items in Moonraker. Updates are
performed in the following order:
- `system` if enabled
- All configured clients
- Klipper
- Moonraker
HTTP request:
```http
POST /machine/update/full
```
JSON-RPC request:
```json
{
"jsonrpc": "2.0",
"method": "machine.update.full",
"id": 4645
}
```
Returns:
`ok` when complete
#### Update Moonraker
Pulls the most recent version of Moonraker from GitHub and restarts
the service. If an update is requested while a print is in progress then
@@ -2179,6 +2396,66 @@ An array of objects containing info for each configured device.
```
#### Get Device Status
Returns the status for a single configured device.
HTTP request:
```http
GET /machine/device_power/device?device=green_led
```
JSON-RPC request:
```json
{
"jsonrpc": "2.0",
"method": "machine.device_power.get_device",
"params": {
"device": "green_led"
},
"id": 4564
}
```
Returns:
An object containing power state for the requested device:
```json
{
"green_led": "off"
}
```
#### Set Device State
Toggle, turn on, or turn off a specified device.
HTTP request:
```http
POST /machine/device_power/device?device=green_led&action=on
```
JSON-RPC request:
```json
{
"jsonrpc": "2.0",
"method": "machine.device_power.post_device",
"params": {
"device": "green_led",
"action": "on"
},
"id": 4564
}
```
!!! note
The `action` argument may be `on`, `off`, or `toggle`. Any
other value will result in an error.
Returns:
An object containing new power state for the requested device:
```json
{
"green_led": "off"
}
```
#### Get Batch Device Status
Get power status for the requested devices. At least one device must be
specified.
@@ -2208,7 +2485,7 @@ An object containing power state for each requested device:
}
```
#### Power On Devices
#### Batch Power On Devices
Power on the requested devices. At least one device must be
specified.
@@ -2236,7 +2513,7 @@ An object containing power state for each requested device:
}
```
#### Power Off Devices
#### Batch Power Off Devices
Power off the requested devices. At least one device must be
specified.
@@ -2591,7 +2868,7 @@ JSON-RPC request:
"jsonrpc": "2.0",
"method":"server.history.get_job",
"params":{"uid": "{uid}"},
"id": 4564,
"id": 4564
}
```
Returns:
@@ -2646,6 +2923,133 @@ An array of deleted job ids
]
```
### MQTT APIs
The following API is available when `[mqtt]` has been configured.
!!! Note
These requests are not available over the `mqtt` transport as they
are redundant. MQTT clients can publish and subscribe to
topics directly.
#### Publish a topic
HTTP request:
```http
POST /server/mqtt/publish
Content-Type: application/json
{
"topic": "home/test/pub",
"payload": "hello",
"qos": 0,
"retain": false,
"timeout": 5
}
```
JSON-RPC request:
```json
{
"jsonrpc": "2.0",
"method":"server.mqtt.publish",
"params":{
"topic": "home/test/pub",
"payload": "hello",
"qos": 0,
"retain": false,
"timeout": 5
},
"id": 4564
}
```
Only the `topic` parameter is required. Below is an explanation for
each paramater:
- `topic`: The topic to publish.
- `payload`: Payload to send with the topic. May be a boolean, float,
integer, string, object, or array. All values are converted to strings prior
to publishing. Objects and Arrays are JSON encoded. If omitted an empty
payload is sent.
- `qos`: QOS level to use when publishing the topic. Must be an integer value
from 0 to 2. If omitted the system configured default is used.
- `retain`: If set to `true` the MQTT broker will retain the payload of this
request. Note that only the mostly recently tagged payload is retained.
When other clients first subscribe to the topic they immediately recieve the
retained message. The default is `false`.
- `timeout`: A float value in seconds. By default requests with QoS levels of
1 or 2 will block until the Broker acknowledges confirmation. This option
applies a timeout to the request, returning a 504 error if the timeout is
exceeded. Note that the topic will still be published if the QoS level is 1
or 2.
!!! tip
To clear a retained value of a topic, publish the topic with an empty
payload and `retain` set to `true`.
Returns:
The published topic:
```json
{
"topic": "home/test/pub"
}
```
#### Subscribe to a topic
HTTP request:
```http
POST /server/mqtt/subscribe
Content-Type: application/json
{
"topic": "home/test/sub",
"qos": 0,
"timeout": 5
}
```
JSON-RPC request:
```json
{
"jsonrpc": "2.0",
"method":"server.mqtt.subscribe",
"params":{
"topic": "home/test/sub",
"qos": 0,
"timeout": 5
},
"id": 4564
}
```
Only the `topic` parameter is required. Below is an explanation for
each paramater:
- `topic`: The topic to subscribe. Note that wildcards may not be used.
- `qos`: QOS level to use when subscribing to the topic. Must be an integer
value from 0 to 2. If omitted the system configured default is used.
- `timeout`: A float value in seconds. By default requests will block
indefinitely until a response is received. This option applies a timeout to
the request, returning a 504 error if the timeout is exceeded. The
subscription will be removed after a timeout.
!!! note
If the topic was previously published with a retained payload this request
will return with the retained value.
Returns:
The subscribed topic and its payload:
```json
{
"topic": "home/test/pub",
"payload": "test"
}
```
If the payload is json encodable it will be returned as an object or array.
Otherwise it will be a string.
### Websocket notifications
Printer generated events are sent over the websocket as JSON-RPC 2.0
notifications. These notifications are sent to all connected clients
@@ -2687,13 +3091,17 @@ Status Subscriptions arrive as a "notify_status_update" notification:
{
"jsonrpc": "2.0",
"method": "notify_status_update",
"params": [{<status object>}]
"params": [{<status object>}, <eventtime>]
}
```
The structure of the `status object` is identical to the structure that is
returned from an [object query's](#query-printer-object-status)
`status` field.
The `eventtime` is a timestamp generated by Klipper when
the update was originally pushed. This timestamp is a float value,
relative to Klipper's monotonic clock.
#### Klippy Ready
Notify clients when Klippy has reported a ready state
```json
@@ -2747,29 +3155,22 @@ to alert all connected clients of the change:
}
```
The `source_item` field is only present for `move_item` and
`copy_item` actions. The following `action` field will be set
`copy_item` actions. The `action` field will be set
to one of the following values:
- `upload_file`
- `delete_file`
- `create_file`
- `create_dir`
- `delete_file`
- `delete_dir`
- `move_item`
- `copy_item`
- `move_file`
- `move_dir`
- `modify_file`
- `root_update`
#### Metadata Update
When a new file is uploaded via the API a websocket notification is broadcast
to all connected clients after parsing is complete:
```json
{
"jsonrpc": "2.0",
"method": "notify_metadata_update",
"params": [{metadata}]
}
```
Where `metadata` is an object matching that returned from a
[gcode metadata request](#get-gcode-metadata).
Most of the above actions are self explanatory. The `root_update`
notification is sent when a `root` folder has changed its location,
for example when a user configures a different gcode file path
in Klipper.
#### Update Manager Response
The update manager will send asyncronous messages to the client during an
@@ -2816,7 +3217,8 @@ Where `update_info` is an object that matches the response from an
#### CPU Throttled
If the system supports throttled CPU monitoring Moonraker will send the
following notification when it detectes an active throttled condition.
following notification when it detects a change to the current throttled
state:
```json
{
"jsonrpc": "2.0",
@@ -2826,9 +3228,33 @@ following notification when it detectes an active throttled condition.
```
Where `throtled_state` is an object that matches the `throttled_state` field
in the response from a [process info](#get-process-info) request. It is
possible for clients to receive this notification multiple times if the system
repeatedly transitions between an active and inactive throttled condition.
in the response from a [Moonraker process stats](#get-moonraker-process-stats)
request. It is possible for clients to receive this notification multiple times
if the system repeatedly transitions between an active and inactive throttled
condition.
#### Moonraker Process Statistic Update
Moonraker will emit the following notification each time it samples its
process statistics:
```json
{
"jsonrpc": "2.0",
"method": "notify_proc_stat_update",
"params": [{
"moonraker_stats": {
"time": 1615837812.0894408,
"cpu_usage": 1.99,
"memory": 23636,
"mem_units": "kB"
},
"cpu_temp": 44.008
}]
}
```
As with the [proc_stats request](#get-moonraker-process-stats) the `cpu_temp`
field will be set to `null` if the host machine does not support retreiving CPU
temperatures at `/sys/class/thermal/thermal_zone0`.
#### History Changed
If the `[history]` module is enabled the following notification is sent when
@@ -2849,6 +3275,36 @@ The `action` field may be `added` or `finished`. The `job` field contains
an object matches the one returned when requesting
[job data](#get-a-single-job).
#### Authorized User Created
If the `[authorization]` module is enabled the following notification is
sent when a new user is created:
```json
{
"jsonrpc": "2.0",
"method": "notify_user_created",
"params": [
{
"username": "<username>"
}
]
}
```
#### Authorized User Deleted
If the `[authorization]` module is enabled the following notification is
sent when an existing user is deleted.
```json
{
"jsonrpc": "2.0",
"method": "notify_user_deleted",
"params": [
{
"username": "<username>"
}
]
}
```
### Appendix
#### Websocket setup
+1
View File
@@ -1,4 +1,5 @@
site_name: Moonraker
site_url: https://moonraker.readthedocs.io
repo_url: https://github.com/Arksine/moonraker
nav:
- 'User Documentation':
+325 -141
View File
@@ -4,23 +4,52 @@
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import os
import mimetypes
import logging
import json
import datetime
from concurrent.futures import ThreadPoolExecutor
import traceback
import ssl
import urllib.parse
import tornado
import tornado.iostream
import tornado.httputil
import tornado.web
from inspect import isclass
from tornado.escape import url_unescape
from tornado.routing import Rule, PathMatches, AnyMatches
from tornado.http1connection import HTTP1Connection
from tornado.log import access_log
from tornado.ioloop import IOLoop
from utils import ServerError
from websockets import WebRequest, WebsocketManager, WebSocket
from streaming_form_data import StreamingFormDataParser
from streaming_form_data.targets import FileTarget, ValueTarget
from streaming_form_data.targets import FileTarget, ValueTarget, SHA256Target
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Optional,
Callable,
Coroutine,
Union,
Dict,
List,
AsyncGenerator,
)
if TYPE_CHECKING:
from tornado.httpserver import HTTPServer
from moonraker import Server
from confighelper import ConfigHelper
from websockets import APITransport
from components.file_manager.file_manager import FileManager
import components.authorization
MessageDelgate = Optional[tornado.httputil.HTTPMessageDelegate]
AuthComp = Optional[components.authorization.Authorization]
APICallback = Callable[[WebRequest], Coroutine]
# These endpoints are reserved for klippy/server communication only and are
# not exposed via http or the websocket
@@ -31,16 +60,22 @@ RESERVED_ENDPOINTS = [
# 50 MiB Max Standard Body Size
MAX_BODY_SIZE = 50 * 1024 * 1024
EXCLUDED_ARGS = ["_", "token", "connection_id"]
EXCLUDED_ARGS = ["_", "token", "access_token", "connection_id"]
AUTHORIZED_EXTS = [".png"]
DEFAULT_KLIPPY_LOG_PATH = "/tmp/klippy.log"
ALL_TRANSPORTS = ["http", "websocket", "mqtt"]
class MutableRouter(tornado.web.ReversibleRuleRouter):
def __init__(self, application):
def __init__(self, application: MoonrakerApp) -> None:
self.application = application
self.pattern_to_rule = {}
self.pattern_to_rule: Dict[str, Rule] = {}
super(MutableRouter, self).__init__(None)
def get_target_delegate(self, target, request, **target_params):
def get_target_delegate(self,
target: Any,
request: tornado.httputil.HTTPServerRequest,
**target_params
) -> MessageDelgate:
if isclass(target) and issubclass(target, tornado.web.RequestHandler):
return self.application.get_handler_delegate(
request, target, **target_params)
@@ -48,17 +83,21 @@ class MutableRouter(tornado.web.ReversibleRuleRouter):
return super(MutableRouter, self).get_target_delegate(
target, request, **target_params)
def has_rule(self, pattern):
def has_rule(self, pattern: str) -> bool:
return pattern in self.pattern_to_rule
def add_handler(self, pattern, target, target_params):
def add_handler(self,
pattern: str,
target: Any,
target_params: Optional[Dict[str, Any]]
) -> None:
if pattern in self.pattern_to_rule:
self.remove_handler(pattern)
new_rule = Rule(PathMatches(pattern), target, target_params)
self.pattern_to_rule[pattern] = new_rule
self.rules.append(new_rule)
def remove_handler(self, pattern):
def remove_handler(self, pattern: str) -> None:
rule = self.pattern_to_rule.pop(pattern, None)
if rule is not None:
try:
@@ -67,27 +106,45 @@ class MutableRouter(tornado.web.ReversibleRuleRouter):
logging.exception(f"Unable to remove rule: {pattern}")
class APIDefinition:
def __init__(self, endpoint, http_uri, ws_methods,
request_methods, need_object_parser):
def __init__(self,
endpoint: str,
http_uri: str,
jrpc_methods: List[str],
request_methods: Union[str, List[str]],
transports: List[str],
callback: Optional[APICallback],
need_object_parser: bool):
self.endpoint = endpoint
self.uri = http_uri
self.ws_methods = ws_methods
self.jrpc_methods = jrpc_methods
if not isinstance(request_methods, list):
request_methods = [request_methods]
self.request_methods = request_methods
self.supported_transports = transports
self.callback = callback
self.need_object_parser = need_object_parser
class MoonrakerApp:
def __init__(self, config):
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.tornado_server = None
self.api_cache = {}
self.registered_base_handlers = []
self.http_server: Optional[HTTPServer] = None
self.secure_server: Optional[HTTPServer] = None
self.api_cache: Dict[str, APIDefinition] = {}
self.registered_base_handlers: List[str] = []
self.max_upload_size = config.getint('max_upload_size', 1024)
self.max_upload_size *= 1024 * 1024
# SSL config
self.cert_path: str = self._get_path_option(
config, 'ssl_certificate_path')
self.key_path: str = self._get_path_option(
config, 'ssl_key_path')
# Set Up Websocket and Authorization Managers
self.wsm = WebsocketManager(self.server)
self.api_transports: Dict[str, APITransport] = {
"websocket": self.wsm
}
mimetypes.add_type('text/plain', '.log')
mimetypes.add_type('text/plain', '.gcode')
@@ -96,7 +153,7 @@ class MoonrakerApp:
self.debug = config.getboolean('enable_debug_logging', False)
log_level = logging.DEBUG if self.debug else logging.INFO
logging.getLogger().setLevel(log_level)
app_args = {
app_args: Dict[str, Any] = {
'serve_traceback': self.debug,
'websocket_ping_interval': 10,
'websocket_ping_timeout': 30,
@@ -108,26 +165,48 @@ class MoonrakerApp:
# Set up HTTP only requests
self.mutable_router = MutableRouter(self)
app_handlers = [
app_handlers: List[Any] = [
(AnyMatches(), self.mutable_router),
(r"/websocket", WebSocket)]
(r"/websocket", WebSocket),
(r"/server/redirect", RedirectHandler)]
self.app = tornado.web.Application(app_handlers, **app_args)
self.get_handler_delegate = self.app.get_handler_delegate
# Register handlers
logfile = config['system_args'].get('logfile')
logfile = self.server.get_app_args().get('log_file')
if logfile:
self.register_static_file_handler(
"moonraker.log", logfile, force=True)
self.register_static_file_handler(
"klippy.log", DEFAULT_KLIPPY_LOG_PATH, force=True)
def listen(self, host, port):
self.tornado_server = self.app.listen(
def _get_path_option(self, config: ConfigHelper, option: str) -> str:
path: Optional[str] = config.get(option, None)
if path is None:
return ""
expanded = os.path.abspath(os.path.expanduser(path))
if not os.path.exists(expanded):
raise self.server.error(
f"Invalid path for option '{option}', "
f"{path} does not exist")
return expanded
def listen(self, host: str, port: int, ssl_port: int) -> None:
self.http_server = self.app.listen(
port, address=host, max_body_size=MAX_BODY_SIZE,
xheaders=True)
if os.path.exists(self.cert_path) and os.path.exists(self.key_path):
logging.info(f"Starting secure server on port {ssl_port}")
ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_ctx.load_cert_chain(self.cert_path, self.key_path)
self.secure_server = self.app.listen(
ssl_port, address=host, max_body_size=MAX_BODY_SIZE,
xheaders=True, ssl_options=ssl_ctx)
else:
logging.info("SSL Certificate/Key not configured, "
"aborting HTTPS Server startup")
def log_request(self, handler):
def log_request(self, handler: tornado.web.RequestHandler) -> None:
status_code = handler.get_status()
if not self.debug and status_code in [200, 204, 206, 304]:
# don't log successful requests in release mode
@@ -147,19 +226,29 @@ class MoonrakerApp:
f"{status_code} {handler._request_summary()} "
f"[{username}] {request_time:.2f}ms")
def get_server(self):
def get_server(self) -> Server:
return self.server
def get_websocket_manager(self):
def get_websocket_manager(self) -> WebsocketManager:
return self.wsm
async def close(self):
if self.tornado_server is not None:
self.tornado_server.stop()
await self.tornado_server.close_all_connections()
async def close(self) -> None:
if self.http_server is not None:
self.http_server.stop()
await self.http_server.close_all_connections()
if self.secure_server is not None:
self.secure_server.stop()
await self.secure_server.close_all_connections()
await self.wsm.close()
def register_remote_handler(self, endpoint):
def register_api_transport(self,
name: str,
transport: APITransport
) -> Dict[str, APIDefinition]:
self.api_transports[name] = transport
return self.api_cache
def register_remote_handler(self, endpoint: str) -> None:
if endpoint in RESERVED_ENDPOINTS:
return
api_def = self._create_api_definition(endpoint)
@@ -167,41 +256,49 @@ class MoonrakerApp:
# reserved handler or already registered
return
logging.info(
f"Registering remote endpoint - "
f"HTTP: ({' '.join(api_def.request_methods)}) {api_def.uri}; "
f"Websocket: {', '.join(api_def.ws_methods)}")
self.wsm.register_remote_handler(api_def)
params = {}
f"Registering HTTP endpoint: "
f"({' '.join(api_def.request_methods)}) {api_def.uri}")
params: Dict[str, Any] = {}
params['methods'] = api_def.request_methods
params['callback'] = api_def.endpoint
params['need_object_parser'] = api_def.need_object_parser
self.mutable_router.add_handler(
api_def.uri, DynamicRequestHandler, params)
self.registered_base_handlers.append(api_def.uri)
for name, transport in self.api_transports.items():
transport.register_api_handler(api_def)
def register_local_handler(self, uri, request_methods,
callback, protocol=["http", "websocket"],
wrap_result=True):
def register_local_handler(self,
uri: str,
request_methods: List[str],
callback: APICallback,
transports: List[str] = ALL_TRANSPORTS,
wrap_result: bool = True
) -> None:
if uri in self.registered_base_handlers:
return
api_def = self._create_api_definition(
uri, request_methods, is_remote=False)
msg = "Registering local endpoint"
if "http" in protocol:
msg += f" - HTTP: ({' '.join(request_methods)}) {uri}"
params = {}
uri, request_methods, callback, transports=transports)
if "http" in transports:
logging.info(
f"Registering HTTP Endpoint: "
f"({' '.join(request_methods)}) {uri}")
params: dict[str, Any] = {}
params['methods'] = request_methods
params['callback'] = callback
params['wrap_result'] = wrap_result
params['is_remote'] = False
self.mutable_router.add_handler(uri, DynamicRequestHandler, params)
self.registered_base_handlers.append(uri)
if "websocket" in protocol:
msg += f" - Websocket: {', '.join(api_def.ws_methods)}"
self.wsm.register_local_handler(api_def, callback)
logging.info(msg)
self.registered_base_handlers.append(uri)
for name, transport in self.api_transports.items():
if name in transports:
transport.register_api_handler(api_def)
def register_static_file_handler(self, pattern, file_path, force=False):
def register_static_file_handler(self,
pattern: str,
file_path: str,
force: bool = False
) -> None:
if pattern[0] != "/":
pattern = "/server/files/" + pattern
if os.path.isfile(file_path) or force:
@@ -217,19 +314,25 @@ class MoonrakerApp:
params = {'path': file_path}
self.mutable_router.add_handler(pattern, FileRequestHandler, params)
def register_upload_handler(self, pattern):
def register_upload_handler(self, pattern: str) -> None:
self.mutable_router.add_handler(
pattern, FileUploadHandler,
{'max_upload_size': self.max_upload_size})
def remove_handler(self, endpoint):
api_def = self.api_cache.get(endpoint)
def remove_handler(self, endpoint: str) -> None:
api_def = self.api_cache.pop(endpoint, None)
if api_def is not None:
self.wsm.remove_handler(api_def.uri)
self.mutable_router.remove_handler(api_def.ws_method)
self.mutable_router.remove_handler(api_def.uri)
for name, transport in self.api_transports.items():
transport.remove_api_handler(api_def)
def _create_api_definition(self, endpoint, request_methods=[],
is_remote=True):
def _create_api_definition(self,
endpoint: str,
request_methods: List[str] = [],
callback: Optional[APICallback] = None,
transports: List[str] = ALL_TRANSPORTS
) -> APIDefinition:
is_remote = callback is None
if endpoint in self.api_cache:
return self.api_cache[endpoint]
if endpoint[0] == '/':
@@ -238,51 +341,52 @@ class MoonrakerApp:
uri = "/printer/" + endpoint
else:
uri = "/server/" + endpoint
ws_methods = []
jrpc_methods = []
if is_remote:
# Remote requests accept both GET and POST requests. These
# requests execute the same callback, thus they resolve to
# only a single websocket method.
ws_methods.append(uri[1:].replace('/', '.'))
jrpc_methods.append(uri[1:].replace('/', '.'))
request_methods = ['GET', 'POST']
else:
name_parts = uri[1:].split('/')
if len(request_methods) > 1:
for req_mthd in request_methods:
func_name = req_mthd.lower() + "_" + name_parts[-1]
ws_methods.append(".".join(name_parts[:-1] + [func_name]))
jrpc_methods.append(".".join(
name_parts[:-1] + [func_name]))
else:
ws_methods.append(".".join(name_parts))
if not is_remote and len(request_methods) != len(ws_methods):
jrpc_methods.append(".".join(name_parts))
if not is_remote and len(request_methods) != len(jrpc_methods):
raise self.server.error(
"Invalid API definition. Number of websocket methods must "
"match the number of request methods")
need_object_parser = endpoint.startswith("objects/")
api_def = APIDefinition(endpoint, uri, ws_methods,
request_methods, need_object_parser)
api_def = APIDefinition(endpoint, uri, jrpc_methods, request_methods,
transports, callback, need_object_parser)
self.api_cache[endpoint] = api_def
return api_def
class AuthorizedRequestHandler(tornado.web.RequestHandler):
def initialize(self):
self.server = self.settings['parent'].get_server()
def initialize(self) -> None:
self.server: Server = self.settings['parent'].get_server()
def set_default_headers(self):
origin = self.request.headers.get("Origin")
def set_default_headers(self) -> None:
origin: Optional[str] = self.request.headers.get("Origin")
# it is necessary to look up the parent app here,
# as initialize() may not yet be called
server = self.settings['parent'].get_server()
auth = server.lookup_component('authorization', None)
server: Server = self.settings['parent'].get_server()
auth: AuthComp = server.lookup_component('authorization', None)
self.cors_enabled = False
if auth is not None:
self.cors_enabled = auth.check_cors(origin, self)
def prepare(self):
auth = self.server.lookup_component('authorization', None)
def prepare(self) -> None:
auth: AuthComp = self.server.lookup_component('authorization', None)
if auth is not None:
self.current_user = auth.check_authorized(self.request)
def options(self, *args, **kwargs):
def options(self, *args, **kwargs) -> None:
# Enable CORS if configured
if self.cors_enabled:
self.set_status(204)
@@ -290,22 +394,23 @@ class AuthorizedRequestHandler(tornado.web.RequestHandler):
else:
super(AuthorizedRequestHandler, self).options()
def get_associated_websocket(self):
def get_associated_websocket(self) -> Optional[WebSocket]:
# Return associated websocket connection if an id
# was provided by the request
conn = None
conn_id = self.get_argument('connection_id', None)
conn_id: Any = self.get_argument('connection_id', None)
if conn_id is not None:
try:
conn_id = int(conn_id)
except Exception:
pass
else:
wsm = self.settings['parent'].get_websocket_manager()
parent: MoonrakerApp = self.settings['parent']
wsm: WebsocketManager = parent.get_websocket_manager()
conn = wsm.get_websocket(conn_id)
return conn
def write_error(self, status_code, **kwargs):
def write_error(self, status_code: int, **kwargs) -> None:
err = {'code': status_code, 'message': self._reason}
if 'exc_info' in kwargs:
err['traceback'] = "\n".join(
@@ -315,26 +420,29 @@ class AuthorizedRequestHandler(tornado.web.RequestHandler):
# 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):
def initialize(self,
path: str,
default_filename: Optional[str] = None
) -> None:
super(AuthorizedFileHandler, self).initialize(path, default_filename)
self.server = self.settings['parent'].get_server()
self.server: Server = self.settings['parent'].get_server()
def set_default_headers(self):
origin = self.request.headers.get("Origin")
def set_default_headers(self) -> None:
origin: Optional[str] = self.request.headers.get("Origin")
# it is necessary to look up the parent app here,
# as initialize() may not yet be called
server = self.settings['parent'].get_server()
auth = server.lookup_component('authorization', None)
server: Server = self.settings['parent'].get_server()
auth: AuthComp = server.lookup_component('authorization', None)
self.cors_enabled = False
if auth is not None:
self.cors_enabled = auth.check_cors(origin, self)
def prepare(self):
auth = self.server.lookup_component('authorization', None)
if auth is not None:
def prepare(self) -> None:
auth: AuthComp = self.server.lookup_component('authorization', None)
if auth is not None and self._check_need_auth():
self.current_user = auth.check_authorized(self.request)
def options(self, *args, **kwargs):
def options(self, *args, **kwargs) -> None:
# Enable CORS if configured
if self.cors_enabled:
self.set_status(204)
@@ -342,16 +450,30 @@ class AuthorizedFileHandler(tornado.web.StaticFileHandler):
else:
super(AuthorizedFileHandler, self).options()
def write_error(self, status_code, **kwargs):
def write_error(self, status_code: int, **kwargs) -> None:
err = {'code': status_code, 'message': self._reason}
if 'exc_info' in kwargs:
err['traceback'] = "\n".join(
traceback.format_exception(*kwargs['exc_info']))
self.finish({'error': err})
def _check_need_auth(self) -> bool:
if self.request.method != "GET":
return True
ext = os.path.splitext(self.request.path)[-1].lower()
if ext in AUTHORIZED_EXTS:
return False
return True
class DynamicRequestHandler(AuthorizedRequestHandler):
def initialize(self, callback, methods, need_object_parser=False,
is_remote=True, wrap_result=True):
def initialize(
self,
callback: Union[str, Callable[[WebRequest], Coroutine]] = "",
methods: List[str] = [],
need_object_parser: bool = False,
is_remote: bool = True,
wrap_result: bool = True
) -> None:
super(DynamicRequestHandler, self).initialize()
self.callback = callback
self.methods = methods
@@ -362,8 +484,8 @@ class DynamicRequestHandler(AuthorizedRequestHandler):
else self._default_parser
# Converts query string values with type hints
def _convert_type(self, value, hint):
type_funcs = {
def _convert_type(self, value: str, hint: str) -> Any:
type_funcs: Dict[str, Callable] = {
"int": int, "float": float,
"bool": lambda x: x.lower() == "true",
"json": json.loads}
@@ -379,7 +501,7 @@ class DynamicRequestHandler(AuthorizedRequestHandler):
return value
return converted
def _default_parser(self):
def _default_parser(self) -> Dict[str, Any]:
args = {}
for key in self.request.arguments.keys():
if key in EXCLUDED_ARGS:
@@ -392,8 +514,8 @@ class DynamicRequestHandler(AuthorizedRequestHandler):
args[key_parts[0]] = self._convert_type(val, key_parts[1])
return args
def _object_parser(self):
args = {}
def _object_parser(self) -> Dict[str, Dict[str, Any]]:
args: Dict[str, Any] = {}
for key in self.request.arguments.keys():
if key in EXCLUDED_ARGS:
continue
@@ -405,7 +527,7 @@ class DynamicRequestHandler(AuthorizedRequestHandler):
logging.debug(f"Parsed Arguments: {args}")
return {'objects': args}
def parse_args(self):
def parse_args(self) -> Dict[str, Any]:
try:
args = self._parse_query()
except Exception:
@@ -423,28 +545,36 @@ class DynamicRequestHandler(AuthorizedRequestHandler):
args[key] = value
return args
async def get(self, *args, **kwargs):
async def get(self, *args, **kwargs) -> None:
await self._process_http_request()
async def post(self, *args, **kwargs):
async def post(self, *args, **kwargs) -> None:
await self._process_http_request()
async def delete(self, *args, **kwargs):
async def delete(self, *args, **kwargs) -> None:
await self._process_http_request()
async def _do_local_request(self, args, conn):
async def _do_local_request(self,
args: Dict[str, Any],
conn: Optional[WebSocket]
) -> Any:
assert callable(self.callback)
return await self.callback(
WebRequest(self.request.path, args, self.request.method,
conn=conn, ip_addr=self.request.remote_ip,
user=self.current_user))
async def _do_remote_request(self, args, conn):
async def _do_remote_request(self,
args: Dict[str, Any],
conn: Optional[WebSocket]
) -> Any:
assert isinstance(self.callback, str)
return await self.server.make_request(
WebRequest(self.callback, args, conn=conn,
ip_addr=self.request.remote_ip,
user=self.current_user))
async def _process_http_request(self):
async def _process_http_request(self) -> None:
if self.request.method not in self.methods:
raise tornado.web.HTTPError(405)
conn = self.get_associated_websocket()
@@ -459,15 +589,19 @@ class DynamicRequestHandler(AuthorizedRequestHandler):
self.finish(result)
class FileRequestHandler(AuthorizedFileHandler):
def set_extra_headers(self, path):
def set_extra_headers(self, path: str) -> None:
# The call below shold never return an empty string,
# as the path should have already been validated to be
# a file
assert isinstance(self.absolute_path, str)
basename = os.path.basename(self.absolute_path)
ascii_basename = self._escape_filename_to_ascii(basename)
utf8_basename = self._escape_filename_to_utf8(basename)
self.set_header(
"Content-Disposition", f"attachment; filename={basename}")
"Content-Disposition", f"attachment; filename={ascii_basename}; "
f"filename*=UTF-8\'\'{utf8_basename}")
async def delete(self, path):
async def delete(self, path: str) -> None:
path = self.request.path.lstrip("/").split("/", 2)[-1]
path = url_unescape(path, plus=False)
file_manager = self.server.lookup_component('file_manager')
@@ -494,6 +628,7 @@ class FileRequestHandler(AuthorizedFileHandler):
self.modified = self.get_modified_time()
self.set_headers()
self.request.headers.pop("If-None-Match", None)
if self.should_return_304():
self.set_status(304)
return
@@ -548,6 +683,7 @@ class FileRequestHandler(AuthorizedFileHandler):
elif end is not None:
content_length = end
elif start is not None:
end = size
content_length = size - start
else:
end = size
@@ -555,10 +691,8 @@ class FileRequestHandler(AuthorizedFileHandler):
self.set_header("Content-Length", content_length)
if include_body:
content = self.get_content(self.absolute_path, start, end)
if isinstance(content, bytes):
content = [content]
for chunk in content:
content = self.get_content_nonblock(self.absolute_path, start, end)
async for chunk in content:
try:
self.write(chunk)
await self.flush()
@@ -567,61 +701,95 @@ class FileRequestHandler(AuthorizedFileHandler):
else:
assert self.request.method == "HEAD"
def _escape_filename_to_ascii(self, basename: str) -> str:
return basename.encode("ascii", "replace").decode()
def _escape_filename_to_utf8(self, basename: str) -> str:
return urllib.parse.quote(basename, encoding="utf-8")
@classmethod
def _get_cached_version(cls, abs_path: str):
with cls._lock:
hashes = cls._static_hashes
try:
mtime = datetime.datetime.fromtimestamp(
os.path.getmtime(abs_path), tz=datetime.timezone.utc)
except Exception:
logging.exception(
f"Unable to get modified time for file: {abs_path}")
hashes.pop(abs_path, None)
return None
if abs_path not in hashes or mtime != hashes[abs_path]['modified']:
try:
hashes[abs_path] = {
'modified': mtime,
'hash': cls.get_content_version(abs_path)
}
except Exception:
logging.exception(f"Could not open static file {abs_path}")
hashes.pop(abs_path, None)
return None
hsh = hashes.get(abs_path, {}).get('hash')
if hsh:
return hsh
async def get_content_nonblock(
cls, abspath: str, start: Optional[int] = None,
end: Optional[int] = None
) -> AsyncGenerator[bytes, None]:
ioloop = IOLoop.current()
with open(abspath, "rb") as file:
if start is not None:
file.seek(start)
if end is not None:
remaining = end - (start or 0) # type: Optional[int]
else:
remaining = None
while True:
chunk_size = 64 * 1024
if remaining is not None and remaining < chunk_size:
chunk_size = remaining
with ThreadPoolExecutor(max_workers=1) as tpe:
chunk = await ioloop.run_in_executor(
tpe, file.read, chunk_size)
if chunk:
if remaining is not None:
remaining -= len(chunk)
yield chunk
else:
if remaining is not None:
assert remaining == 0
return
@classmethod
def _get_cached_version(cls, abs_path: str) -> Optional[str]:
return None
@tornado.web.stream_request_body
class FileUploadHandler(AuthorizedRequestHandler):
def initialize(self, max_upload_size):
def initialize(self, max_upload_size: int = MAX_BODY_SIZE) -> None:
super(FileUploadHandler, self).initialize()
self.file_manager = self.server.lookup_component('file_manager')
self.file_manager: FileManager = self.server.lookup_component(
'file_manager')
self.max_upload_size = max_upload_size
def prepare(self):
def prepare(self) -> None:
super(FileUploadHandler, self).prepare()
if self.request.method == "POST":
assert isinstance(self.request.connection, HTTP1Connection)
self.request.connection.set_max_body_size(self.max_upload_size)
tmpname = self.file_manager.gen_temp_upload_path()
self._targets = {
'root': ValueTarget(),
'print': ValueTarget(),
'path': ValueTarget(),
'checksum': ValueTarget(),
}
self._file = FileTarget(tmpname)
self._sha256_target = SHA256Target()
self._parser = StreamingFormDataParser(self.request.headers)
self._parser.register('file', self._file)
self._parser.register('file', self._sha256_target)
for name, target in self._targets.items():
self._parser.register(name, target)
def data_received(self, chunk):
async def data_received(self, chunk: bytes) -> None:
if self.request.method == "POST":
self._parser.data_received(chunk)
with ThreadPoolExecutor(max_workers=1) as tpe:
await IOLoop.current().run_in_executor(
tpe, self._parser.data_received, chunk)
async def post(self):
async def post(self) -> None:
form_args = {}
chk_target = self._targets.pop('checksum')
calc_chksum = self._sha256_target.value.lower()
if chk_target.value:
# Validate checksum
recd_cksum = chk_target.value.decode().lower()
if calc_chksum != recd_cksum:
# remove temporary file
try:
os.remove(self._file.filename)
except Exception:
pass
raise self.server.error(
f"File checksum mismatch: expected {recd_cksum}, "
f"calculated {calc_chksum}", 422)
for name, target in self._targets.items():
if target.value:
form_args[name] = target.value.decode()
@@ -630,6 +798,7 @@ class FileUploadHandler(AuthorizedRequestHandler):
debug_msg = "\nFile Upload Arguments:"
for name, value in form_args.items():
debug_msg += f"\n{name}: {value}"
debug_msg += f"\nChecksum: {calc_chksum}"
logging.debug(debug_msg)
try:
result = await self.file_manager.finalize_upload(form_args)
@@ -640,17 +809,32 @@ class FileUploadHandler(AuthorizedRequestHandler):
# Default Handler for unregistered endpoints
class AuthorizedErrorHandler(AuthorizedRequestHandler):
def prepare(self):
def prepare(self) -> None:
super(AuthorizedRequestHandler, self).prepare()
self.set_status(404)
raise tornado.web.HTTPError(404)
def check_xsrf_cookie(self):
def check_xsrf_cookie(self) -> None:
pass
def write_error(self, status_code, **kwargs):
def write_error(self, status_code: int, **kwargs) -> None:
err = {'code': status_code, 'message': self._reason}
if 'exc_info' in kwargs:
err['traceback'] = "\n".join(
traceback.format_exception(*kwargs['exc_info']))
self.finish({'error': err})
class RedirectHandler(AuthorizedRequestHandler):
def get(self, *args, **kwargs) -> None:
url: Optional[str] = self.get_argument('url', None)
if url is None:
try:
body_args: Dict[str, Any] = json.loads(self.request.body)
except json.JSONDecodeError:
body_args = {}
if 'url' not in body_args:
raise tornado.web.HTTPError(
400, "No url argument provided")
url = body_args['url']
assert url is not None
self.redirect(url)
+332 -149
View File
@@ -3,21 +3,56 @@
# 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 base64
import uuid
import hashlib
import hmac
import secrets
import os
import time
import datetime
import ipaddress
import json
import re
import socket
import logging
import json
from tornado.ioloop import IOLoop, PeriodicCallback
from tornado.web import HTTPError
from utils import ServerError
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
from tornado.httputil import HTTPServerRequest
from tornado.web import RequestHandler
from . import database
DBComp = database.MoonrakerDatabase
IPAddr = Union[ipaddress.IPv4Address, ipaddress.IPv6Address]
IPNetwork = Union[ipaddress.IPv4Network, ipaddress.IPv6Network]
OneshotToken = Tuple[IPAddr, Optional[Dict[str, Any]], object]
# 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
@@ -29,28 +64,19 @@ TRUSTED_USER = "_TRUSTED_USER_"
RESERVED_USERS = [API_USER, TRUSTED_USER]
JWT_EXP_TIME = datetime.timedelta(hours=1)
JWT_HEADER = {
'alg': "HS256",
'alg': "EdDSA",
'typ': "JWT"
}
# Helpers for base64url encoding and decoding
def base64url_encode(data):
return base64.urlsafe_b64encode(data).rstrip(b"=")
def base64url_decode(data):
pad_cnt = len(data) % 4
if pad_cnt:
data += b"=" * (4 - pad_cnt)
return base64.urlsafe_b64decode(data)
class Authorization:
def __init__(self, config):
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.login_timeout = config.getint('login_timeout', 90)
database = self.server.lookup_component('database')
self.force_logins = config.getboolean('force_logins', False)
database: DBComp = self.server.lookup_component('database')
database.register_local_namespace('authorized_users', forbidden=True)
self.users = database.wrap_namespace('authorized_users')
api_user = self.users.get(API_USER, None)
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] = {
@@ -60,14 +86,32 @@ class Authorization:
}
else:
self.api_key = api_user['api_key']
self.trusted_users = {}
self.oneshot_tokens = {}
self.permitted_paths = set()
host_name, port = self.server.get_host_info()
self.issuer = f"http://{host_name}:{port}"
self.public_jwks: Dict[str, Dict[str, Any]] = {}
for username, user_info in list(self.users.items()):
if username == API_USER:
continue
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)
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 = []
self.cors_domains: List[str] = []
cors_cfg = config.get('cors_domains', "").strip()
cds = [d.strip() for d in cors_cfg.split('\n')if d.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:
@@ -78,31 +122,35 @@ class Authorization:
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:
self.trusted_ips: List[IPAddr] = []
self.trusted_ranges: List[IPNetwork] = []
self.trusted_domains: List[str] = []
tcs = config.get('trusted_clients', "")
trusted_clients = [c.strip() for c in tcs.split('\n') if c.strip()]
for val in trusted_clients:
# Check IP address
try:
tc = ipaddress.ip_address(ip)
tc = ipaddress.ip_address(val)
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)
pass
else:
self.trusted_ips.append(tc)
continue
# Check ip network
try:
tc = ipaddress.ip_network(val)
except ValueError:
pass
else:
self.trusted_ranges.append(tc)
continue
# Check hostname
self.trusted_domains.append(val.lower())
t_clients = "\n".join(
[str(ip) for ip in self.trusted_ips] +
[str(rng) for rng in self.trusted_ranges])
[str(rng) for rng in self.trusted_ranges] +
self.trusted_domains)
c_domains = "\n".join(self.cors_domains)
logging.info(
@@ -115,68 +163,91 @@ class Authorization:
self.prune_handler.start()
# Register Authorization Endpoints
self.permitted_paths.add("/server/redirect")
self.permitted_paths.add("/access/login")
self.permitted_paths.add("/access/refresh_jwt")
self.server.register_endpoint(
"/access/login", ['POST'], self._handle_login)
"/access/login", ['POST'], self._handle_login,
transports=['http'])
self.server.register_endpoint(
"/access/logout", ['POST'], self._handle_logout)
"/access/logout", ['POST'], self._handle_logout,
transports=['http'])
self.server.register_endpoint(
"/access/refresh_jwt", ['POST'], self._handle_refresh_jwt)
"/access/refresh_jwt", ['POST'], self._handle_refresh_jwt,
transports=['http'])
self.server.register_endpoint(
"/access/user", ['GET', 'POST', 'DELETE'],
self._handle_user_request)
self._handle_user_request, transports=['http'])
self.server.register_endpoint(
"/access/user/password", ['POST'], self._handle_password_reset)
"/access/users/list", ['GET'], self._handle_list_request,
transports=['http'])
self.server.register_endpoint(
"/access/user/password", ['POST'], self._handle_password_reset,
transports=['http'])
self.server.register_endpoint(
"/access/api_key", ['GET', 'POST'],
self._handle_apikey_request, protocol=['http'])
self._handle_apikey_request, transports=['http'])
self.server.register_endpoint(
"/access/oneshot_token", ['GET'],
self._handle_token_request, protocol=['http'])
self._handle_oneshot_request, transports=['http'])
self.server.register_notification("authorization:user_created")
self.server.register_notification("authorization:user_deleted")
async def _handle_apikey_request(self, web_request):
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[f'{API_USER}.api_key'] = self.api_key
return self.api_key
async def _handle_token_request(self, web_request):
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):
async def _handle_login(self, web_request: WebRequest) -> Dict[str, Any]:
return self._login_jwt_user(web_request)
async def _handle_logout(self, web_request):
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 = user_info['username']
username: str = user_info['username']
if username in RESERVED_USERS:
raise self.server.error(
f"Invalid log out request for user {username}")
self.users.pop(f"{username}.jwt_secret", None)
jwk_id: str = self.users.pop(f"{username}.jwk_id", "")
self.public_jwks.pop(jwk_id, None)
return {
"username": username,
"action": "user_logged_out"
}
async def _handle_refresh_jwt(self, web_request):
refresh_token = web_request.get_str('refresh_token')
user_info = self._decode_jwt(refresh_token, token_type="refresh")
username = user_info['username']
secret = bytes.fromhex(user_info['jwt_secret'])
token = self._generate_jwt(username, secret)
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,
'action': 'user_jwt_refresh'
}
async def _handle_user_request(self, web_request):
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()
@@ -196,10 +267,28 @@ class Authorization:
elif action == "DELETE":
# Delete User
return self._delete_jwt_user(web_request)
raise self.server.error("Invalid Request Method")
async def _handle_password_reset(self, web_request):
password = web_request.get_str('password')
new_pass = web_request.get_str('new_password')
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'],
'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")
@@ -220,9 +309,13 @@ class Authorization:
'action': "user_password_reset"
}
def _login_jwt_user(self, web_request, create=False):
username = web_request.get_str('username')
password = web_request.get_str('password')
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')
user_info: Dict[str, Any]
if username in RESERVED_USERS:
raise self.server.error(
f"Invalid Request for user {username}")
@@ -250,17 +343,26 @@ class Authorization:
action = "user_logged_in"
if hashed_pass != user_info['password']:
raise self.server.error("Invalid Password")
jwt_secret = user_info.get('jwt_secret', None)
if jwt_secret is None:
jwt_secret = secrets.token_bytes(32)
user_info['jwt_secret'] = jwt_secret.hex()
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.public_jwks[jwk_id] = self._generate_public_jwk(private_key)
else:
jwt_secret = bytes.fromhex(jwt_secret)
token = self._generate_jwt(username, jwt_secret)
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, jwt_secret, token_type="refresh",
username, jwk_id, private_key, token_type="refresh",
exp_time=datetime.timedelta(days=self.login_timeout))
if create:
IOLoop.current().call_later(
.005, self.server.send_event,
"authorization:user_created",
{'username': username})
return {
'username': username,
'token': token,
@@ -268,80 +370,128 @@ class Authorization:
'action': action
}
def _delete_jwt_user(self, web_request):
password = web_request.get_str('password')
user_info = web_request.get_current_user()
if user_info is None:
raise self.server.error("No Current User")
username = user_info['username']
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 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")
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}")
self.public_jwks.pop(self.users.get(f"{username}.jwk_id"), None)
del self.users[username]
IOLoop.current().call_later(
.005, self.server.send_event,
"authorization:user_deleted",
{'username': username})
return {
"username": username,
"action": "user_deleted"
}
def _generate_jwt(self, username, secret, token_type="auth",
exp_time=JWT_EXP_TIME):
curtime = time.time()
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': "Moonraker",
'iss': self.issuer,
'aud': "Moonraker",
'iat': curtime,
'exp': curtime + exp_time.total_seconds(),
'exp': curtime + int(exp_time.total_seconds()),
'username': username,
'token_type': token_type
}
enc_header = base64url_encode(json.dumps(JWT_HEADER).encode())
enc_payload = base64url_encode(json.dumps(payload).encode())
message = enc_header + b"." + enc_payload
signature = base64url_encode(hmac.digest(secret, message, "sha256"))
message += b"." + signature
return message.decode()
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, jwt, token_type="auth"):
parts = jwt.encode().split(b".")
if len(parts) != 3:
raise self.server.error(f"Invalid JWT length of {len(parts)}")
header = json.loads(base64url_decode(parts[0]))
payload = json.loads(base64url_decode(parts[1]))
if header != JWT_HEADER:
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")
recd_type = payload.get('token_type', "")
if token_type != recd_type:
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: {recd_type}", 401)
if time.time() > payload['exp']:
raise self.server.error("JWT expired", 401)
username = payload.get('username')
user_info = self.users.get(username, None)
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(
f"Invalid JWT, no registered user {username}", 401)
jwt_secret = user_info.get('jwt_secret', None)
if jwt_secret is None:
raise self.server.error(
f"Invalid JWT, user {username} not logged in", 401)
secret = bytes.fromhex(jwt_secret)
# Decode and verify signature
signature = base64url_decode(parts[2])
calc_sig = hmac.digest(
secret, parts[0] + b"." + parts[1], "sha256")
if signature != calc_sig:
raise self.server.error("Invalid JWT signature")
raise self.server.error("Unknown user", 401)
return user_info
def _prune_conn_handler(self):
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) -> None:
cur_time = time.time()
for ip, user_info in list(self.trusted_users.items()):
exp_time = user_info['expires_at']
exp_time: float = user_info['expires_at']
if cur_time >= exp_time:
self.trusted_users.pop(ip, None)
logging.info(
@@ -350,7 +500,10 @@ class Authorization:
def _oneshot_token_expire_handler(self, token):
self.oneshot_tokens.pop(token, None)
def get_oneshot_token(self, ip_addr, user):
def get_oneshot_token(self,
ip_addr: IPAddr,
user: Optional[Dict[str, Any]]
) -> str:
token = base64.b32encode(os.urandom(20)).decode()
ioloop = IOLoop.current()
hdl = ioloop.call_later(
@@ -358,27 +511,39 @@ class Authorization:
self.oneshot_tokens[token] = (ip_addr, user, hdl)
return token
def _check_json_web_token(self, request):
auth_token = request.headers.get("Authorization")
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 and auth_token.startswith("Bearer "):
auth_token = auth_token[7:]
else:
qtoken = request.query_arguments.get('access_token', None)
if qtoken is not None:
auth_token = qtoken[-1].decode()
if auth_token:
try:
return self._decode_jwt(auth_token)
except Exception as e:
raise HTTPError(401, str(e))
return None
def _check_authorized_ip(self, ip):
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):
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
@@ -397,7 +562,10 @@ class Authorization:
return self.trusted_users[ip]
return None
def _check_oneshot_token(self, token, cur_ip):
def _check_oneshot_token(self,
token: str,
cur_ip: IPAddr
) -> Optional[Dict[str, Any]]:
if token in self.oneshot_tokens:
ip_addr, user, hdl = self.oneshot_tokens.pop(token)
IOLoop.current().remove_timeout(hdl)
@@ -409,8 +577,11 @@ class Authorization:
else:
return None
def check_authorized(self, request):
if request.path in self.permitted_paths:
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
@@ -426,17 +597,22 @@ class Authorization:
ip = None
# Check oneshot access token
ost = request.arguments.get('token', None)
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
key = request.headers.get("X-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")
# Check if IP is trusted
trusted_user = self._check_trusted_connection(ip)
if trusted_user is not None:
@@ -444,7 +620,10 @@ class Authorization:
raise HTTPError(401, "Unauthorized")
def check_cors(self, origin, request=None):
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:
@@ -453,7 +632,7 @@ class Authorization:
if match.group() == origin:
logging.debug(f"CORS Pattern Matched, origin: {origin} "
f" | pattern: {regex}")
self._set_cors_headers(origin, request)
self._set_cors_headers(origin, req_hdlr)
return True
else:
logging.debug(f"Partial Cors Match: {match.group()}")
@@ -471,28 +650,32 @@ class Authorization:
if self._check_authorized_ip(ipaddr):
logging.debug(
f"Cors request matched trusted IP: {ip}")
self._set_cors_headers(origin, request)
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, request):
if request is None:
def _set_cors_headers(self,
origin: str,
req_hdlr: Optional[RequestHandler]
) -> None:
if req_hdlr 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, Authorization, X-Access-Token, "
"X-Api-Key")
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")
def close(self):
def close(self) -> None:
self.prune_handler.stop()
def load_component(config):
def load_component(config: ConfigHelper) -> Authorization:
return Authorization(config)
+44 -17
View File
@@ -3,23 +3,43 @@
# 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
from tornado.ioloop import PeriodicCallback
# 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 . import klippy_apis
APIComp = klippy_apis.KlippyAPI
GCQueue = Deque[Dict[str, Any]]
TempStore = Dict[str, Dict[str, Deque[float]]]
TEMPERATURE_UPDATE_MS = 1000
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.last_temps: Dict[str, Tuple[float, ...]] = {}
self.gcode_queue: GCQueue = deque(maxlen=self.gcode_store_size)
self.temperature_store: TempStore = {}
self.temp_update_cb = PeriodicCallback(
self._update_temperature_store, TEMPERATURE_UPDATE_MS)
@@ -39,26 +59,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:
@@ -86,7 +109,7 @@ class DataStore:
self.temperature_store = {}
self.temp_update_cb.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 +119,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) -> None:
# XXX - If klippy is not connected, set values to zero
# as they are unknown?
for sensor, vals in self.last_temps.items():
@@ -105,21 +128,23 @@ class DataStore:
if item in self.temperature_store[sensor]:
self.temperature_store[sensor][item].append(val)
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):
async def close(self) -> None:
self.temp_update_cb.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 +153,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 +163,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)
+157 -54
View File
@@ -3,6 +3,8 @@
# 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 json
import struct
@@ -11,6 +13,25 @@ import logging
from io import BytesIO
from functools import reduce
import lmdb
from utils import SentinelClass
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
ItemsView,
ValuesView,
Tuple,
Optional,
Union,
Dict,
List,
)
if TYPE_CHECKING:
from confighelper import ConfigHelper
from websockets import WebRequest
DBRecord = Union[int, float, bool, str, List[Any], Dict[str, Any]]
DBType = Optional[DBRecord]
DATABASE_VERSION = 1
MAX_NAMESPACES = 50
@@ -34,19 +55,19 @@ RECORD_DECODE_FUNCS = {
ord("{"): lambda x: json.load(BytesIO(x)),
}
def getitem_with_default(item, field):
SENTINEL = SentinelClass.get_instance()
def getitem_with_default(item: Dict, field: Any) -> Any:
if field not in item:
item[field] = {}
return item[field]
class Sentinel:
pass
class MoonrakerDatabase:
def __init__(self, config):
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.namespaces = {}
self.enable_debug = config.get("enable_database_debug", False)
self.namespaces: Dict[str, object] = {}
self.enable_debug = config.getboolean("enable_database_debug", False)
self.database_path = os.path.expanduser(config.get(
'database_path', "~/.moonraker_database"))
if not os.path.isdir(self.database_path):
@@ -68,6 +89,9 @@ class MoonrakerDatabase:
txn.put(b'database_version',
self._encode_value(DATABASE_VERSION),
db=mrdb)
# Read out all namespaces to remove any invalid keys on init
for ns in self.namespaces.keys():
self._get_namespace(ns)
# Protected Namespaces have read-only API access. Write access can
# be granted by enabling the debug option. Forbidden namespaces
# have no API access. This cannot be overridden.
@@ -75,20 +99,34 @@ class MoonrakerDatabase:
"moonraker", "database.protected_namespaces", ["moonraker"]))
self.forbidden_namespaces = set(self.get_item(
"moonraker", "database.forbidden_namespaces", []))
debug_counter = self.get_item("moonraker", "database.debug_counter", 0)
debug_counter: int = self.get_item(
"moonraker", "database.debug_counter", 0)
if self.enable_debug:
debug_counter += 1
self.insert_item("moonraker", "database.debug_counter",
debug_counter)
if debug_counter:
logging.info(f"Database Debug Count: {debug_counter}")
# Track unsafe shutdowns
unsafe_shutdowns: int = self.get_item(
"moonraker", "database.unsafe_shutdowns", 0)
logging.info(f"Unsafe Shutdown Count: {unsafe_shutdowns}")
# Increment unsafe shutdown counter. This will be reset if
# moonraker is safely restarted
self.insert_item("moonraker", "database.unsafe_shutdowns",
unsafe_shutdowns + 1)
self.server.register_endpoint(
"/server/database/list", ['GET'], self._handle_list_request)
self.server.register_endpoint(
"/server/database/item", ["GET", "POST", "DELETE"],
self._handle_item_request)
def insert_item(self, namespace, key, value):
def insert_item(self,
namespace: str,
key: Union[List[str], str],
value: DBType
) -> None:
key_list = self._process_key(key)
if namespace not in self.namespaces:
self.namespaces[namespace] = self.lmdb_env.open_db(
@@ -101,23 +139,31 @@ class MoonrakerDatabase:
logging.info(
f"Warning: Key {key_list[0]} contains a value of type "
f"{type(record)}. Overwriting with an object.")
item = reduce(getitem_with_default, key_list[1:-1], record)
item: Dict[str, Any] = reduce(getitem_with_default, key_list[1:-1],
record)
item[key_list[-1]] = value
if not self._insert_record(namespace, key_list[0], record):
logging.info(
f"Error inserting key '{key}' in namespace '{namespace}'")
def update_item(self, namespace, key, value):
def update_item(self,
namespace: str,
key: Union[List[str], str],
value: DBType
) -> None:
key_list = self._process_key(key)
record = self._get_record(namespace, key_list[0])
if len(key_list) == 1:
if isinstance(record, dict) and isinstance(value, dict):
record.update(value)
else:
assert value is not None
record = value
else:
try:
item = reduce(operator.getitem, key_list[1:-1], record)
assert isinstance(record, dict)
item: Dict[str, Any] = reduce(
operator.getitem, key_list[1:-1], record)
except Exception:
raise self.server.error(
f"Key '{key}' in namespace '{namespace}' not found", 404)
@@ -130,13 +176,19 @@ class MoonrakerDatabase:
logging.info(
f"Error updating key '{key}' in namespace '{namespace}'")
def delete_item(self, namespace, key, drop_empty_db=False):
def delete_item(self,
namespace: str,
key: Union[List[str], str],
drop_empty_db: bool = False
) -> Any:
key_list = self._process_key(key)
val = record = self._get_record(namespace, key_list[0])
remove_record = True
if len(key_list) > 1:
try:
item = reduce(operator.getitem, key_list[1:-1], record)
assert isinstance(record, dict)
item: Dict[str, Any] = reduce(
operator.getitem, key_list[1:-1], record)
val = item.pop(key_list[-1])
except Exception:
raise self.server.error(
@@ -157,25 +209,29 @@ class MoonrakerDatabase:
f"Error deleting key '{key}' from namespace '{namespace}'")
return val
def get_item(self, namespace, key=None, default=Sentinel):
def get_item(self,
namespace: str,
key: Optional[Union[List[str], str]] = None,
default: Any = SENTINEL
) -> Any:
try:
if key is None:
return self._get_namespace(namespace)
key_list = self._process_key(key)
ns = self._get_record(namespace, key_list[0])
val = reduce(operator.getitem, key_list[1:], ns)
val = reduce(operator.getitem, key_list[1:], ns) # type: ignore
except Exception:
if default != Sentinel:
if not isinstance(default, SentinelClass):
return default
raise self.server.error(
f"Key '{key}' in namespace '{namespace}' not found", 404)
return val
def ns_length(self, namespace):
def ns_length(self, namespace: str) -> int:
return len(self.ns_keys(namespace))
def ns_keys(self, namespace):
keys = []
def ns_keys(self, namespace: str) -> List[str]:
keys: List[str] = []
db = self.namespaces[namespace]
with self.lmdb_env.begin(db=db) as txn:
cursor = txn.cursor()
@@ -185,15 +241,15 @@ class MoonrakerDatabase:
remaining = cursor.next()
return keys
def ns_values(self, namespace):
def ns_values(self, namespace: str) -> ValuesView:
ns = self._get_namespace(namespace)
return ns.values()
def ns_items(self, namespace):
def ns_items(self, namespace: str) -> ItemsView:
ns = self._get_namespace(namespace)
return ns.items()
def ns_contains(self, namespace, key):
def ns_contains(self, namespace: str, key: Union[List[str], str]) -> bool:
try:
key_list = self._process_key(key)
if len(key_list) == 1:
@@ -204,7 +260,10 @@ class MoonrakerDatabase:
return False
return True
def register_local_namespace(self, namespace, forbidden=False):
def register_local_namespace(self,
namespace: str,
forbidden: bool = False
) -> None:
if namespace not in self.namespaces:
self.namespaces[namespace] = self.lmdb_env.open_db(
namespace.encode())
@@ -219,13 +278,16 @@ class MoonrakerDatabase:
self.insert_item("moonraker", "database.protected_namespaces",
list(self.protected_namespaces))
def wrap_namespace(self, namespace, parse_keys=True):
def wrap_namespace(self,
namespace: str,
parse_keys: bool = True
) -> NamespaceWrapper:
if namespace not in self.namespaces:
raise self.server.error(
f"Namespace '{namespace}' not found", 404)
return NamespaceWrapper(namespace, self, parse_keys)
def _process_key(self, key):
def _process_key(self, key: Union[List[str], str]) -> List[str]:
try:
key_list = key if isinstance(key, list) else key.split('.')
except Exception:
@@ -234,13 +296,19 @@ class MoonrakerDatabase:
raise self.server.error(f"Invalid Key Format: '{key}'")
return key_list
def _insert_record(self, namespace, key, val):
def _insert_record(self, namespace: str, key: str, val: DBType) -> bool:
db = self.namespaces[namespace]
if val is None:
return False
with self.lmdb_env.begin(write=True, buffers=True, db=db) as txn:
ret = txn.put(key.encode(), self._encode_value(val))
return ret
def _get_record(self, namespace, key, force=False):
def _get_record(self,
namespace: str,
key: str,
force: bool = False
) -> DBRecord:
if namespace not in self.namespaces:
raise self.server.error(
f"Namespace '{namespace}' not found", 404)
@@ -254,21 +322,30 @@ class MoonrakerDatabase:
f"Key '{key}' in namespace '{namespace}' not found", 404)
return self._decode_value(value)
def _get_namespace(self, namespace):
def _get_namespace(self, namespace: str) -> Dict[str, Any]:
if namespace not in self.namespaces:
raise self.server.error(
f"Invalid database namespace '{namespace}'")
db = self.namespaces[namespace]
result = {}
invalid_key_result = None
with self.lmdb_env.begin(buffers=True, db=db) as txn:
cursor = txn.cursor()
cursor.first()
for db_key, value in cursor:
k = bytes(db_key).decode()
if not k:
invalid_key_result = self._decode_value(value)
continue
result[k] = self._decode_value(value)
if invalid_key_result:
logging.info(f"Invalid Key found in namespace '{namespace}', "
f"dropping value: {repr(invalid_key_result)}")
with self.lmdb_env.begin(write=True, buffers=True, db=db) as txn:
txn.delete(b"")
return result
def _encode_value(self, value):
def _encode_value(self, value: DBRecord) -> bytes:
try:
enc_func = RECORD_ENCODE_FUNCS[type(value)]
return enc_func(value)
@@ -276,25 +353,32 @@ class MoonrakerDatabase:
raise self.server.error(
f"Error encoding val: {value}, type: {type(value)}")
def _decode_value(self, bvalue):
def _decode_value(self, bvalue: bytes) -> DBRecord:
fmt = bvalue[0]
try:
decode_func = RECORD_DECODE_FUNCS[fmt]
return decode_func(bvalue)
except Exception:
raise self.server.error(
f"Error decoding value {bvalue}, format: {chr(fmt)}")
f"Error decoding value {bvalue.decode()}, format: {chr(fmt)}")
async def _handle_list_request(self, web_request):
return {'namespaces': list(self.namespaces.keys())}
async def _handle_list_request(self,
web_request: WebRequest
) -> Dict[str, List[str]]:
ns_list = set(self.namespaces.keys()) - self.forbidden_namespaces
return {'namespaces': list(ns_list)}
async def _handle_item_request(self, web_request):
async def _handle_item_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
action = web_request.get_action()
namespace = web_request.get_str("namespace")
if namespace in self.forbidden_namespaces:
raise self.server.error(
f"Read/Write access to namespace '{namespace}'"
" is forbidden", 403)
key: Any
valid_types: Tuple[type, ...]
if action != "GET":
if namespace in self.protected_namespaces and \
not self.enable_debug:
@@ -319,7 +403,13 @@ class MoonrakerDatabase:
val = self.delete_item(namespace, key, drop_empty_db=True)
return {'namespace': namespace, 'key': key, 'value': val}
def close(self):
def close(self) -> None:
# Decrement unsafe shutdown counter
unsafe_shutdowns: int = self.get_item(
"moonraker", "database.unsafe_shutdowns", 0)
self.insert_item("moonraker", "database.unsafe_shutdowns",
unsafe_shutdowns - 1)
# log db stats
msg = ""
with self.lmdb_env.begin() as txn:
@@ -332,24 +422,28 @@ class MoonrakerDatabase:
self.lmdb_env.close()
class NamespaceWrapper:
def __init__(self, namespace, database, parse_keys):
def __init__(self,
namespace: str,
database: MoonrakerDatabase,
parse_keys: bool
) -> None:
self.namespace = namespace
self.db = database
# If parse keys is true, keys of a string type
# will be passed straight to the DB methods.
self.parse_keys = parse_keys
def insert(self, key, value):
def insert(self, key: Union[List[str], str], value: DBType) -> None:
if isinstance(key, str) and not self.parse_keys:
key = [key]
self.db.insert_item(self.namespace, key, value)
def update_child(self, key, value):
def update_child(self, key: Union[List[str], str], value: DBType) -> None:
if isinstance(key, str) and not self.parse_keys:
key = [key]
self.db.update_item(self.namespace, key, value)
def update(self, value):
def update(self, value: Dict[str, Any]) -> None:
val_keys = set(value.keys())
new_keys = val_keys - set(self.keys())
update_keys = val_keys - new_keys
@@ -358,52 +452,61 @@ class NamespaceWrapper:
for key in new_keys:
self.insert([key], value[key])
def get(self, key, default=None):
def get(self,
key: Union[List[str], str],
default: Any = None
) -> Any:
if isinstance(key, str) and not self.parse_keys:
key = [key]
return self.db.get_item(self.namespace, key, default)
def delete(self, key):
def delete(self, key: Union[List[str], str]) -> Any:
if isinstance(key, str) and not self.parse_keys:
key = [key]
return self.db.delete_item(self.namespace, key)
def __len__(self):
def __len__(self) -> int:
return self.db.ns_length(self.namespace)
def __getitem__(self, key):
return self.get(key, default=Sentinel)
def __getitem__(self, key: Union[List[str], str]) -> Any:
return self.get(key, default=SENTINEL)
def __setitem__(self, key, value):
def __setitem__(self,
key: Union[List[str], str],
value: DBType
) -> None:
self.insert(key, value)
def __delitem__(self, key):
def __delitem__(self, key: Union[List[str], str]):
self.delete(key)
def __contains__(self, key):
def __contains__(self, key: Union[List[str], str]) -> bool:
if isinstance(key, str) and not self.parse_keys:
key = [key]
return self.db.ns_contains(self.namespace, key)
def keys(self):
def keys(self) -> List[str]:
return self.db.ns_keys(self.namespace)
def values(self):
def values(self) -> ValuesView:
return self.db.ns_values(self.namespace)
def items(self):
def items(self) -> ItemsView:
return self.db.ns_items(self.namespace)
def pop(self, key, default=Sentinel):
def pop(self,
key: Union[List[str], str],
default: Any = SENTINEL
) -> Any:
try:
val = self.delete(key)
except Exception:
if default == Sentinel:
if isinstance(default, SentinelClass):
raise
val = default
return val
def clear(self):
def clear(self) -> None:
keys = self.keys()
for k in keys:
try:
@@ -411,5 +514,5 @@ class NamespaceWrapper:
except Exception:
pass
def load_component(config):
def load_component(config: ConfigHelper) -> MoonrakerDatabase:
return MoonrakerDatabase(config)
-773
View File
@@ -1,773 +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:
full_path = os.path.join(dir_path, dname)
if not os.path.exists(full_path):
continue
st = os.stat(full_path)
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
if not os.path.exists(full_path):
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
@@ -5,6 +5,7 @@
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import json
import argparse
import re
@@ -12,15 +13,35 @@ import os
import sys
import base64
import traceback
import io
import tempfile
import zipfile
import shutil
from PIL import Image
def log_to_stderr(msg):
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Optional,
Dict,
List,
Type,
)
if TYPE_CHECKING:
pass
UFP_MODEL_PATH = "/3D/model.gcode"
UFP_THUMB_PATH = "/Metadata/thumbnail.png"
def log_to_stderr(msg: str) -> None:
sys.stderr.write(f"{msg}\n")
sys.stderr.flush()
# regex helpers
def _regex_find_floats(pattern, data, strict=False):
def _regex_find_floats(pattern: str,
data: str,
strict: bool = False
) -> List[float]:
# 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*'
@@ -29,121 +50,133 @@ def _regex_find_floats(pattern, data, strict=False):
# return the maximum height value found
try:
return [float(h) for h in re.findall(
fptrn, " ".join(matches))]
fptrn, " ".join(matches))]
except Exception:
pass
return []
def _regex_find_ints(pattern, data):
def _regex_find_ints(pattern: str, data: str) -> List[int]:
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))]
r'\d+', " ".join(matches))]
except Exception:
pass
return []
def _regex_find_first(pattern, data, cast=float):
def _regex_find_first(pattern: str, data: str) -> Optional[float]:
match = re.search(pattern, data)
val = None
val: Optional[float] = None
if match:
try:
val = cast(match.group(1))
val = float(match.group(1))
except Exception:
return None
return val
# Slicer parsing implementations
class BaseSlicer(object):
def __init__(self, file_path):
def __init__(self, file_path: str) -> None:
self.path = file_path
self.header_data = self.footer_data = None
self.layer_height = None
self.header_data: str = ""
self.footer_data: str = ""
self.layer_height: Optional[float] = None
def set_data(self, header_data, footer_data, fsize):
def set_data(self,
header_data: str,
footer_data: str,
fsize: int) -> None:
self.header_data = header_data
self.footer_data = footer_data
self.size = fsize
self.size: int = fsize
def _parse_min_float(self, pattern, data, strict=False):
def _parse_min_float(self,
pattern: str,
data: str,
strict: bool = False
) -> Optional[float]:
result = _regex_find_floats(pattern, data, strict)
if result:
return min(result)
else:
return None
def _parse_max_float(self, pattern, data, strict=False):
def _parse_max_float(self,
pattern: str,
data: str,
strict: bool = False
) -> Optional[float]:
result = _regex_find_floats(pattern, data, strict)
if result:
return max(result)
else:
return None
def check_identity(self, data):
def check_identity(self, data: str) -> Optional[Dict[str, str]]:
return None
def parse_gcode_start_byte(self):
def parse_gcode_start_byte(self) -> Optional[int]:
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):
def parse_gcode_end_byte(self) -> Optional[int]:
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):
def parse_first_layer_height(self) -> Optional[float]:
return None
def parse_layer_height(self):
def parse_layer_height(self) -> Optional[float]:
return None
def parse_object_height(self):
def parse_object_height(self) -> Optional[float]:
return None
def parse_filament_total(self):
def parse_filament_total(self) -> Optional[float]:
return None
def parse_filament_weight_total(self):
def parse_filament_weight_total(self) -> Optional[float]:
return None
def parse_estimated_time(self):
def parse_estimated_time(self) -> Optional[float]:
return None
def parse_first_layer_bed_temp(self):
def parse_first_layer_bed_temp(self) -> Optional[float]:
return None
def parse_first_layer_extr_temp(self):
def parse_first_layer_extr_temp(self) -> Optional[float]:
return None
def parse_thumbnails(self):
def parse_thumbnails(self) -> Optional[List[Dict[str, Any]]]:
return None
class UnknownSlicer(BaseSlicer):
def check_identity(self, data):
def check_identity(self, data: str) -> Optional[Dict[str, str]]:
return {'slicer': "Unknown"}
def parse_first_layer_height(self):
def parse_first_layer_height(self) -> Optional[float]:
return self._parse_min_float(r"G1\sZ\d+\.\d*", self.header_data)
def parse_object_height(self):
def parse_object_height(self) -> Optional[float]:
return self._parse_max_float(r"G1\sZ\d+\.\d*", self.footer_data)
def parse_first_layer_extr_temp(self):
def parse_first_layer_extr_temp(self) -> Optional[float]:
return _regex_find_first(
r"M109 S(\d+\.?\d*)", self.header_data)
def parse_first_layer_bed_temp(self):
def parse_first_layer_bed_temp(self) -> Optional[float]:
return _regex_find_first(
r"M190 S(\d+\.?\d*)", self.header_data)
class PrusaSlicer(BaseSlicer):
def check_identity(self, data):
def check_identity(self, data: str) -> Optional[Dict[str, str]]:
match = re.search(r"PrusaSlicer\s(.*)\son", data)
if match:
return {
@@ -152,7 +185,7 @@ class PrusaSlicer(BaseSlicer):
}
return None
def parse_first_layer_height(self):
def parse_first_layer_height(self) -> Optional[float]:
# Check percentage
pct = _regex_find_first(
r"; first_layer_height = (\d+)%", self.footer_data)
@@ -165,12 +198,12 @@ class PrusaSlicer(BaseSlicer):
return _regex_find_first(
r"; first_layer_height = (\d+\.?\d*)", self.footer_data)
def parse_layer_height(self):
def parse_layer_height(self) -> Optional[float]:
self.layer_height = _regex_find_first(
r"; layer_height = (\d+\.?\d*)", self.footer_data)
return self.layer_height
def parse_object_height(self):
def parse_object_height(self) -> Optional[float]:
matches = re.findall(
r";BEFORE_LAYER_CHANGE\n(?:.*\n)?;(\d+\.?\d*)", self.footer_data)
if matches:
@@ -182,46 +215,46 @@ class PrusaSlicer(BaseSlicer):
return max(matches)
return self._parse_max_float(r"G1\sZ\d+\.\d*\sF", self.footer_data)
def parse_filament_total(self):
def parse_filament_total(self) -> Optional[float]:
return _regex_find_first(
r"filament\sused\s\[mm\]\s=\s(\d+\.\d*)", self.footer_data)
def parse_filament_weight_total(self):
def parse_filament_weight_total(self) -> Optional[float]:
return _regex_find_first(
r"total\sfilament\sused\s\[g\]\s=\s(\d+\.\d*)", self.footer_data)
def parse_estimated_time(self):
def parse_estimated_time(self) -> Optional[float]:
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_group = 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)
t = re.search(pattern, time_group)
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(
def parse_thumbnails(self) -> Optional[List[Dict[str, Any]]]:
thumb_matches: List[str] = 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")
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
return None
thumb_base = os.path.splitext(os.path.basename(self.path))[0]
parsed_matches = []
parsed_matches: List[Dict[str, Any]] = []
for match in thumb_matches:
lines = re.split(r"\r?\n", match.replace('; ', ''))
info = _regex_find_ints(r".*", lines[0])
@@ -238,25 +271,25 @@ class PrusaSlicer(BaseSlicer):
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)
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,
'size': os.path.getsize(thumb_path),
'relative_path': rel_thumb_path})
return parsed_matches
def parse_first_layer_extr_temp(self):
def parse_first_layer_extr_temp(self) -> Optional[float]:
return _regex_find_first(
r"; first_layer_temperature = (\d+\.?\d*)", self.footer_data)
def parse_first_layer_bed_temp(self):
def parse_first_layer_bed_temp(self) -> Optional[float]:
return _regex_find_first(
r"; first_layer_bed_temperature = (\d+\.?\d*)", self.footer_data)
class Slic3rPE(PrusaSlicer):
def check_identity(self, data):
def check_identity(self, data: str) -> Optional[Dict[str, str]]:
match = re.search(r"Slic3r\sPrusa\sEdition\s(.*)\son", data)
if match:
return {
@@ -265,15 +298,15 @@ class Slic3rPE(PrusaSlicer):
}
return None
def parse_filament_total(self):
def parse_filament_total(self) -> Optional[float]:
return _regex_find_first(
r"filament\sused\s=\s(\d+\.\d+)mm", self.footer_data)
def parse_thumbnails(self):
def parse_thumbnails(self) -> Optional[List[Dict[str, Any]]]:
return None
class Slic3r(Slic3rPE):
def check_identity(self, data):
def check_identity(self, data: str) -> Optional[Dict[str, str]]:
match = re.search(r"Slic3r\s(\d.*)\son", data)
if match:
return {
@@ -282,22 +315,22 @@ class Slic3r(Slic3rPE):
}
return None
def parse_filament_total(self):
def parse_filament_total(self) -> Optional[float]:
filament = _regex_find_first(
r";\sfilament\_length\_m\s=\s(\d+\.\d*)", self.footer_data)
if filament is not None:
filament *= 1000
return filament
def parse_filament_weight_total(self):
def parse_filament_weight_total(self) -> Optional[float]:
return _regex_find_first(
r";\sfilament\smass\_g\s=\s(\d+\.\d*)", self.footer_data)
def parse_estimated_time(self):
def parse_estimated_time(self) -> Optional[float]:
return None
class SuperSlicer(PrusaSlicer):
def check_identity(self, data):
def check_identity(self, data: str) -> Optional[Dict[str, str]]:
match = re.search(r"SuperSlicer\s(.*)\son", data)
if match:
return {
@@ -307,7 +340,7 @@ class SuperSlicer(PrusaSlicer):
return None
class Cura(PrusaSlicer):
def check_identity(self, data):
def check_identity(self, data: str) -> Optional[Dict[str, str]]:
match = re.search(r"Cura_SteamEngine\s(.*)", data)
if match:
return {
@@ -316,85 +349,77 @@ class Cura(PrusaSlicer):
}
return None
def parse_first_layer_height(self):
def parse_first_layer_height(self) -> Optional[float]:
return _regex_find_first(r";MINZ:(\d+\.?\d*)", self.header_data)
def parse_layer_height(self):
def parse_layer_height(self) -> Optional[float]:
self.layer_height = _regex_find_first(
r";Layer\sheight:\s(\d+\.?\d*)", self.header_data)
return self.layer_height
def parse_object_height(self):
def parse_object_height(self) -> Optional[float]:
return _regex_find_first(r";MAXZ:(\d+\.?\d*)", self.header_data)
def parse_filament_total(self):
def parse_filament_total(self) -> Optional[float]:
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_filament_weight_total(self):
def parse_filament_weight_total(self) -> Optional[float]:
return _regex_find_first(
r";Filament\sweight\s=\s.(\d+\.\d+).", self.header_data)
def parse_estimated_time(self):
def parse_estimated_time(self) -> Optional[float]:
return self._parse_max_float(r";TIME:.*", self.header_data)
def parse_first_layer_extr_temp(self):
def parse_first_layer_extr_temp(self) -> Optional[float]:
return _regex_find_first(
r"M109 S(\d+\.?\d*)", self.header_data)
def parse_first_layer_bed_temp(self):
def parse_first_layer_bed_temp(self) -> Optional[float]:
return _regex_find_first(
r"M190 S(\d+\.?\d*)", self.header_data)
def parse_thumbnails(self):
def parse_thumbnails(self) -> Optional[List[Dict[str, Any]]]:
# 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_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")
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
})
with Image.open(thumb_path) as im:
thumbs.append({
'width': im.width, 'height': im.height,
'size': os.path.getsize(thumb_path),
'relative_path': rel_path_full
})
# Create 32x32 thumbnail
im.thumbnail((32, 32), Image.ANTIALIAS)
im.save(thumb_path_small, format="PNG")
thumbs.insert(0, {
'width': im.width, 'height': im.height,
'size': os.path.getsize(thumb_path_small),
'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):
def check_identity(self, data: str) -> Optional[Dict[str, str]]:
match = re.search(r"Simplify3D\(R\)\sVersion\s(.*)", data)
if match:
return {
@@ -403,50 +428,50 @@ class Simplify3D(BaseSlicer):
}
return None
def parse_first_layer_height(self):
def parse_first_layer_height(self) -> Optional[float]:
return self._parse_min_float(r"G1\sZ\d+\.\d*", self.header_data)
def parse_layer_height(self):
self.layer_height = _regex_find_first(
def parse_layer_height(self) -> Optional[float]:
self.layer_height = _regex_find_first(
r";\s+layerHeight,(\d+\.?\d*)", self.header_data)
return self.layer_height
def parse_object_height(self):
def parse_object_height(self) -> Optional[float]:
return self._parse_max_float(r"G1\sZ\d+\.\d*", self.footer_data)
def parse_filament_total(self):
def parse_filament_total(self) -> Optional[float]:
return _regex_find_first(
r";\s+Filament\slength:\s(\d+\.?\d*)\smm", self.footer_data)
def parse_filament_weight_total(self):
def parse_filament_weight_total(self) -> Optional[float]:
return _regex_find_first(
r";\s+Plastic\sweight:\s(\d+\.?\d*)\sg", self.footer_data)
def parse_estimated_time(self):
def parse_estimated_time(self) -> Optional[float]:
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_group = 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)
t = re.search(pattern, time_group)
if t:
total_time += int(t.group(1)) * multiplier
except Exception:
return None
return round(total_time, 2)
def _get_temp_items(self, pattern):
def _get_temp_items(self, pattern: str) -> List[str]:
match = re.search(pattern, self.header_data)
if match is None:
return []
return match.group().split(",")[1:]
def _get_first_layer_temp(self, heater):
def _get_first_layer_temp(self, heater: str) -> Optional[float]:
heaters = self._get_temp_items(r"temperatureName.*")
temps = self._get_temp_items(r"temperatureSetpointTemperatures.*")
for h, temp in zip(heaters, temps):
@@ -457,14 +482,14 @@ class Simplify3D(BaseSlicer):
return None
return None
def parse_first_layer_extr_temp(self):
def parse_first_layer_extr_temp(self) -> Optional[float]:
return self._get_first_layer_temp("Extruder 1")
def parse_first_layer_bed_temp(self):
def parse_first_layer_bed_temp(self) -> Optional[float]:
return self._get_first_layer_temp("Heated Bed")
class KISSlicer(BaseSlicer):
def check_identity(self, data):
def check_identity(self, data: str) -> Optional[Dict[str, Any]]:
match = re.search(r";\sKISSlicer", data)
if match:
ident = {'slicer': "KISSlicer"}
@@ -475,27 +500,27 @@ class KISSlicer(BaseSlicer):
return ident
return None
def parse_first_layer_height(self):
def parse_first_layer_height(self) -> Optional[float]:
return _regex_find_first(
r";\s+first_layer_thickness_mm\s=\s(\d+\.?\d*)", self.header_data)
def parse_layer_height(self):
def parse_layer_height(self) -> Optional[float]:
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):
def parse_object_height(self) -> Optional[float]:
return self._parse_max_float(
r";\sEND_LAYER_OBJECT\sz.*", self.footer_data)
def parse_filament_total(self):
def parse_filament_total(self) -> Optional[float]:
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):
def parse_estimated_time(self) -> Optional[float]:
time = _regex_find_first(
r";\sCalculated.*Build\sTime:\s(\d+\.?\d*)\sminutes",
self.footer_data)
@@ -504,17 +529,17 @@ class KISSlicer(BaseSlicer):
return round(time, 2)
return None
def parse_first_layer_extr_temp(self):
def parse_first_layer_extr_temp(self) -> Optional[float]:
return _regex_find_first(
r"; first_layer_C = (\d+\.?\d*)", self.header_data)
def parse_first_layer_bed_temp(self):
def parse_first_layer_bed_temp(self) -> Optional[float]:
return _regex_find_first(
r"; bed_C = (\d+\.?\d*)", self.header_data)
class IdeaMaker(BaseSlicer):
def check_identity(self, data):
def check_identity(self, data: str) -> Optional[Dict[str, str]]:
match = re.search(r"\sideaMaker\s(.*),", data)
if match:
return {
@@ -523,14 +548,14 @@ class IdeaMaker(BaseSlicer):
}
return None
def parse_first_layer_height(self):
def parse_first_layer_height(self) -> Optional[float]:
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):
def parse_layer_height(self) -> Optional[float]:
layer_info = _regex_find_floats(
r";LAYER:1\s*.*\s*;HEIGHT.*", self.header_data)
if len(layer_info) >= 3:
@@ -538,21 +563,21 @@ class IdeaMaker(BaseSlicer):
return self.layer_height
return None
def parse_object_height(self):
def parse_object_height(self) -> Optional[float]:
bounds = _regex_find_floats(
r";Bounding Box:.*", self.header_data)
if len(bounds) >= 6:
return bounds[5]
return None
def parse_filament_total(self):
def parse_filament_total(self) -> Optional[float]:
filament = _regex_find_floats(
r";Material.\d\sUsed:.*", self.footer_data, strict=True)
if filament:
return sum(filament)
return None
def parse_filament_weight_total(self):
def parse_filament_weight_total(self) -> Optional[float]:
pi = 3.141592653589793
length = _regex_find_floats(
r";Material.\d\sUsed:.*", self.footer_data, strict=True)
@@ -563,55 +588,55 @@ class IdeaMaker(BaseSlicer):
if len(length) == len(density) == len(diameter):
# calc individual weight for each filament with m=pi/4*d²*l*rho
weights = [(pi/4 * diameter[i]**2 * length[i] * density[i]/10**6)
for i in range(len(length))]
for i in range(len(length))]
return sum(weights)
return None
def parse_estimated_time(self):
def parse_estimated_time(self) -> Optional[float]:
return _regex_find_first(
r";Print\sTime:\s(\d+\.?\d*)", self.footer_data)
def parse_first_layer_extr_temp(self):
def parse_first_layer_extr_temp(self) -> Optional[float]:
return _regex_find_first(
r"M109 T0 S(\d+\.?\d*)", self.header_data)
def parse_first_layer_bed_temp(self):
def parse_first_layer_bed_temp(self) -> Optional[float]:
return _regex_find_first(
r"M190 S(\d+\.?\d*)", self.header_data)
class IceSL(BaseSlicer):
def check_identity(self, data):
def check_identity(self, data) -> Optional[Dict[str, Any]]:
match = re.search(r"; <IceSL.*>", data)
if match:
return {'slicer': "IceSL"}
return None
def parse_first_layer_height(self):
def parse_first_layer_height(self) -> Optional[float]:
return _regex_find_first(
r"; z_layer_height_first_layer_mm :\s+(\d+\.\d+)",
self.header_data, float)
self.header_data)
def parse_layer_height(self):
def parse_layer_height(self) -> Optional[float]:
self.layer_height = _regex_find_first(
r"; z_layer_height_mm :\s+(\d+\.\d+)",
self.header_data, float)
self.header_data)
return self.layer_height
def parse_object_height(self):
def parse_object_height(self) -> Optional[float]:
return self._parse_max_float(
r"G0 F\d+ Z\d+\.\d+", self.footer_data, strict=True)
def parse_first_layer_extr_temp(self):
def parse_first_layer_extr_temp(self) -> Optional[float]:
return _regex_find_first(
r"; extruder_temp_degree_c_0 :\s+(\d+\.?\d*)", self.header_data)
def parse_first_layer_bed_temp(self):
def parse_first_layer_bed_temp(self) -> Optional[float]:
return _regex_find_first(
r"; bed_temp_degree_c :\s+(\d+\.?\d*)", self.header_data)
READ_SIZE = 512 * 1024
SUPPORTED_SLICERS = [
SUPPORTED_SLICERS: List[Type[BaseSlicer]] = [
PrusaSlicer, Slic3rPE, Slic3r, SuperSlicer,
Cura, Simplify3D, KISSlicer, IdeaMaker, IceSL]
SUPPORTED_DATA = [
@@ -620,10 +645,11 @@ SUPPORTED_DATA = [
'thumbnails', 'first_layer_bed_temp', 'first_layer_extr_temp',
'gcode_start_byte', 'gcode_end_byte']
def extract_metadata(file_path):
metadata = {}
def extract_metadata(file_path: str) -> Dict[str, Any]:
metadata: Dict[str, Any] = {}
slicers = [s(file_path) for s in SUPPORTED_SLICERS]
header_data = footer_data = slicer = None
header_data = footer_data = ""
slicer: Optional[BaseSlicer] = None
size = os.path.getsize(file_path)
metadata['size'] = size
metadata['modified'] = os.path.getmtime(file_path)
@@ -656,9 +682,41 @@ def extract_metadata(file_path):
metadata[key] = result
return metadata
def main(path, filename):
def extract_ufp(ufp_path: str, dest_path: str) -> None:
if not os.path.isfile(ufp_path):
log_to_stderr(f"UFP file Not Found: {ufp_path}")
sys.exit(-1)
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)
except Exception:
log_to_stderr(traceback.format_exc())
sys.exit(-1)
try:
os.remove(ufp_path)
except Exception:
log_to_stderr(f"Error removing ufp file: {ufp_path}")
def main(path: str, filename: str, ufp: Optional[str]) -> None:
file_path = os.path.join(path, filename)
metadata = {}
if ufp is not None:
extract_ufp(ufp, file_path)
metadata: Dict[str, Any] = {}
if not os.path.isfile(file_path):
log_to_stderr(f"File Not Found: {file_path}")
sys.exit(-1)
@@ -690,5 +748,9 @@ if __name__ == "__main__":
metavar='<path>',
help="optional absolute path for file"
)
parser.add_argument(
"-u", "--ufp", metavar="<ufp file>", default=None,
help="optional path of ufp file to extract"
)
args = parser.parse_args()
main(args.path, args.filename)
main(args.path, args.filename, args.ufp)
+97 -53
View File
@@ -1,19 +1,41 @@
# History cache for printer jobs
#
# This file may be distributed under the terms of the GNU GPLv3 license.
from __future__ import annotations
import logging
import time
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Union,
Optional,
Dict,
List,
)
if TYPE_CHECKING:
from confighelper import ConfigHelper
from websockets import WebRequest
from . import database
from . import klippy_apis
from .file_manager import file_manager
DBComp = database.MoonrakerDatabase
APIComp = klippy_apis.KlippyAPI
FMComp = file_manager.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.file_manager: FMComp = self.server.lookup_component(
'file_manager')
database: DBComp = self.server.lookup_component("database")
self.gcdb = database.wrap_namespace("gcode_metadata", parse_keys=False)
self.job_totals = database.get_item(
self.job_totals: Dict[str, float] = database.get_item(
"moonraker", "history.job_totals",
{
'total_jobs': 0,
@@ -45,24 +67,26 @@ class History:
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.current_job: Optional[PrinterJob] = None
self.current_job_id: Optional[str] = None
self.print_stats: Dict[str, Any] = {}
self.next_job_id: int = 0
self.cached_job_ids = self.history_ns.keys()
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}
async def _init_ready(self) -> None:
klippy_apis: APIComp = self.server.lookup_component('klippy_apis')
sub: Dict[str, Optional[List[str]]] = {"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):
async def _handle_job_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
action = web_request.get_action()
if action == "GET":
job_id = web_request.get_str("uid")
@@ -85,12 +109,15 @@ class History:
self.delete_job(job_id)
return {'deleted_jobs': [job_id]}
raise self.server.error("Invalid Request Method")
async def _handle_jobs_list(self, web_request):
async def _handle_jobs_list(self,
web_request: WebRequest
) -> Dict[str, Any]:
i = 0
count = 0
end_num = len(self.cached_job_ids)
jobs = []
jobs: List[Dict[str, Any]] = []
start_num = 0
before = web_request.get_float("before", -1)
@@ -99,7 +126,7 @@ class History:
start = web_request.get_int("start", 0)
order = web_request.get_str("order", "desc")
if not order in ["asc", "desc"]:
if order not in ["asc", "desc"]:
raise self.server.error(f"Invalid `order` value: {order}", 400)
reverse_order = (order == "desc")
@@ -108,8 +135,8 @@ class History:
if since != -1:
while start_num < end_num:
job_id = self.cached_job_ids[start_num]
job = self.history_ns[job_id]
if job.get('start_time') > since:
job: Dict[str, Any] = self.history_ns[job_id]
if job['start_time'] > since:
break
start_num += 1
@@ -117,7 +144,7 @@ class History:
while end_num > 0:
job_id = self.cached_job_ids[end_num-1]
job = self.history_ns[job_id]
if job.get('end_time') < before:
if job['end_time'] < before:
break
end_num -= 1
@@ -141,14 +168,16 @@ class History:
return {"count": count, "jobs": jobs}
async def _handle_job_totals(self, web_request):
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):
async def _status_update(self, data: Dict[str, Any]) -> None:
ps = data.get("print_stats", {})
if "state" in ps:
old_state = self.print_stats['state']
new_state = ps['state']
old_state: str = self.print_stats['state']
new_state: str = ps['state']
new_ps = dict(self.print_stats)
new_ps.update(ps)
@@ -159,7 +188,11 @@ class History:
elif self.current_job is not None:
if new_state == "complete":
self.finish_job("completed", new_ps)
if new_state == "standby":
elif new_state == "cancelled":
self.finish_job("cancelled", new_ps)
elif new_state == "standby":
# Backward compatibility with
# `CLEAR_PAUSE/SDCARD_RESET_FILE` workflow
self.finish_job("cancelled", self.print_stats)
elif new_state == "error":
self.finish_job("error", new_ps)
@@ -171,13 +204,13 @@ class History:
self.print_stats.update(ps)
def _handle_shutdown(self):
def _handle_shutdown(self) -> None:
self.finish_job("klippy_shutdown", self.print_stats)
def _handle_disconnect(self):
def _handle_disconnect(self) -> None:
self.finish_job("klippy_disconnect", self.print_stats)
def _check_need_cancel(self, new_stats):
def _check_need_cancel(self, new_stats: Dict[str, Any]) -> bool:
# Cancel if the file name has changed, total duration has
# decreased, or if job is not resuming from a pause
ps = self.print_stats
@@ -185,7 +218,7 @@ class History:
ps['total_duration'] > new_stats['total_duration'] or \
ps['state'] != "paused"
def add_job(self, job):
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}"
@@ -197,7 +230,7 @@ class History:
self.next_job_id += 1
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}"
@@ -205,7 +238,7 @@ 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
@@ -218,16 +251,16 @@ class History:
self.current_job = None
self.current_job_id = None
def get_job(self, job_id):
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)
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")
metadata: Dict[str, Any] = self.gcdb.get(filename, {})
if metadata:
# Add the start time and job id to the
# persistent metadata storage
@@ -241,14 +274,17 @@ class History:
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
@@ -260,59 +296,67 @@ 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):
def on_exit(self) -> None:
self.finish_job("server_exit", self.print_stats)
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)
+79 -39
View File
@@ -3,8 +3,27 @@
# 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 SentinelClass
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
Subscription = Dict[str, Optional[List[Any]]]
_T = TypeVar("_T")
INFO_ENDPOINT = "info"
ESTOP_ENDPOINT = "emergency_stop"
@@ -15,17 +34,16 @@ SUBSCRIPTION_ENDPOINT = "objects/subscribe"
STATUS_ENDPOINT = "objects/query"
OBJ_LIST_ENDPOINT = "objects/list"
REG_METHOD_ENDPOINT = "register_remote_method"
SENTINEL = SentinelClass.get_instance()
class Sentinel:
pass
class KlippyAPI:
def __init__(self, config):
class KlippyAPI(Subscribable):
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
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,42 +59,49 @@ 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._send_klippy_request("pause_resume/pause", {})
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._send_klippy_request("pause_resume/resume", {})
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._send_klippy_request("pause_resume/cancel", {})
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
) -> Any:
try:
result = await self.server.make_request(
WebRequest(method, params, conn=self))
except self.server.error as e:
if default == Sentinel:
except self.server.error:
if isinstance(default, SentinelClass):
raise
result = default
return result
async def run_gcode(self, script, default=Sentinel):
async def run_gcode(self,
script: str,
default: Any = SENTINEL
) -> 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) -> str:
# XXX - validate that file is on disk
if filename[0] == '/':
filename = filename[1:]
@@ -85,7 +110,7 @@ class KlippyAPI:
script = f'SDCARD_PRINT_FILE FILENAME="{filename}"'
return await self.run_gcode(script)
async def do_restart(self, gc):
async def do_restart(self, gc: str) -> str:
try:
result = await self.run_gcode(gc)
except self.server.error as e:
@@ -95,28 +120,38 @@ class KlippyAPI:
raise
return result
async def list_endpoints(self, default=Sentinel):
async def list_endpoints(self,
default: Union[SentinelClass, _T] = SENTINEL
) -> 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[SentinelClass, _T] = SENTINEL
) -> 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[SentinelClass, _T] = SENTINEL
) -> 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[SentinelClass, _T] = SENTINEL
) -> Union[_T, Dict[str, Any]]:
params = {'objects': objects}
result = await self._send_klippy_request(
STATUS_ENDPOINT, params, default)
@@ -124,7 +159,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[SentinelClass, _T] = SENTINEL
) -> Union[_T, Dict[str, Any]]:
for obj, items in objects.items():
if obj in self.host_subscription:
prev = self.host_subscription[obj]
@@ -142,20 +180,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)
+203 -14
View File
@@ -3,14 +3,60 @@
# 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 re
import pathlib
import logging
import platform
import distro
from tornado.ioloop import IOLoop
ALLOWED_SERVICES = ["moonraker", "klipper", "webcamd"]
# Annotation imports
from typing import (
List,
TYPE_CHECKING,
Any,
Dict,
)
if TYPE_CHECKING:
from confighelper import ConfigHelper
from websockets import WebRequest
from . import shell_command
SCMDComp = shell_command.ShellCommandFactory
ALLOWED_SERVICES = [
"moonraker", "klipper", "webcamd", "MoonCord",
"KlipperScreen"]
SYSTEMD_PATH = "/etc/systemd/system"
SD_CID_PATH = "/sys/block/mmcblk0/device/cid"
SD_CSD_PATH = "/sys/block/mmcblk0/device/csd"
SD_MFGRS = {
'1b': "Samsung",
'03': "Sandisk"
}
class Machine:
def __init__(self, config):
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
dist_info: Dict[str, Any]
dist_info = {'name': distro.name(pretty=True)}
dist_info.update(distro.info())
self.system_info: Dict[str, Any] = {
'cpu_info': self._get_cpu_info(),
'sd_info': self._get_sdcard_info(),
'distribution': dist_info
}
# Add system info to log rollover
sys_info_msg = "\nSystem Info:"
for header, info in self.system_info.items():
sys_info_msg += f"\n\n***{header}***"
for key, val in info.items():
sys_info_msg += f"\n {key}: {val}"
self.server.add_log_rollover_item('system_info', sys_info_msg)
self.available_services: List[str] = []
self.server.register_endpoint(
"/machine/reboot", ['POST'], self._handle_machine_request)
self.server.register_endpoint(
@@ -24,6 +70,9 @@ class Machine:
self.server.register_endpoint(
"/machine/services/start", ['POST'],
self._handle_service_request)
self.server.register_endpoint(
"/machine/system_info", ['GET'],
self._handle_sysinfo_request)
# Register remote methods
self.server.register_remote_method(
@@ -31,7 +80,10 @@ class Machine:
self.server.register_remote_method(
"reboot_machine", self.reboot_machine)
async def _handle_machine_request(self, web_request):
# Retreive list of services
IOLoop.current().spawn_callback(self._find_active_services)
async def _handle_machine_request(self, web_request: WebRequest) -> str:
ep = web_request.get_endpoint()
if ep == "/machine/shutdown":
await self.shutdown_machine()
@@ -41,18 +93,21 @@ class Machine:
raise self.server.error("Unsupported machine request")
return "ok"
async def shutdown_machine(self):
async def shutdown_machine(self) -> None:
await self._execute_cmd("sudo shutdown now")
async def reboot_machine(self):
async def reboot_machine(self) -> None:
await self._execute_cmd("sudo shutdown -r now")
async def do_service_action(self, action, service_name):
async def do_service_action(self,
action: str,
service_name: str
) -> None:
await self._execute_cmd(
f'sudo systemctl {action} {service_name}')
async def _handle_service_request(self, web_request):
name = web_request.get('service').lower()
async def _handle_service_request(self, web_request: WebRequest) -> str:
name: str = web_request.get('service')
action = web_request.get_endpoint().split('/')[-1]
if name == "moonraker":
if action != "restart":
@@ -60,21 +115,155 @@ class Machine:
f"Service action '{action}' not available for moonraker")
IOLoop.current().spawn_callback(
self.do_service_action, action, name)
elif name in ALLOWED_SERVICES:
elif name in self.available_services:
await self.do_service_action(action, name)
else:
if name in ALLOWED_SERVICES and \
name not in self.available_services:
raise self.server.error(f"Service '{name}' not installed")
raise self.server.error(
f"Invalid argument recevied for 'name': {name}")
f"Service '{name}' not allowed")
return "ok"
async def _execute_cmd(self, cmd):
shell_command = self.server.lookup_component('shell_command')
scmd = shell_command.build_shell_command(cmd, None)
async def _handle_sysinfo_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
return {'system_info': self.system_info}
async def _execute_cmd(self, cmd: str) -> None:
shell_cmd: SCMDComp = self.server.lookup_component('shell_command')
scmd = shell_cmd.build_shell_command(cmd, None)
try:
await scmd.run(timeout=2., verbose=False)
except Exception:
logging.exception(f"Error running cmd '{cmd}'")
raise
def load_component(config):
def get_system_info(self) -> Dict[str, Dict[str, Any]]:
return self.system_info
def _get_sdcard_info(self) -> Dict[str, Any]:
sd_info: Dict[str, Any] = {}
cid_file = pathlib.Path(SD_CID_PATH)
if not cid_file.exists():
# No SDCard detected at mmcblk0
return {}
try:
cid_text = cid_file.read_text().strip().lower()
mid = cid_text[:2]
sd_info['manufacturer_id'] = mid
sd_info['manufacturer'] = SD_MFGRS.get(mid, "Unknown")
sd_info['oem_id'] = cid_text[2:6]
sd_info['product_name'] = bytes.fromhex(cid_text[6:16]).decode(
encoding="ascii", errors="ignore")
sd_info['product_revision'] = \
f"{int(cid_text[16], 16)}.{int(cid_text[17], 16)}"
sd_info['serial_number'] = cid_text[18:26]
mfg_year = int(cid_text[27:29], 16) + 2000
mfg_month = int(cid_text[29], 16)
sd_info['manufacturer_date'] = f"{mfg_month}/{mfg_year}"
except Exception:
logging.info("Error reading SDCard CID Register")
return {}
sd_info['capacity'] = "Unknown"
sd_info['total_bytes'] = 0
csd_file = pathlib.Path(SD_CSD_PATH)
# Read CSD Register
try:
csd_reg = bytes.fromhex(csd_file.read_text().strip())
csd_type = (csd_reg[0] >> 6) & 0x3
if csd_type == 0:
# Standard Capacity (CSD Version 1.0)
max_block_len: int = 2**(csd_reg[5] & 0xF)
c_size = ((csd_reg[6] & 0x3) << 10) | (csd_reg[7] << 2) | \
((csd_reg[8] >> 6) & 0x3)
c_mult_reg = ((csd_reg[9] & 0x3) << 1) | (csd_reg[10] >> 7)
c_mult = 2**(c_mult_reg + 2)
total_bytes: int = (c_size + 1) * c_mult * max_block_len
sd_info['capacity'] = f"{(total_bytes / (1024.0**2)):.1f} MiB"
elif csd_type == 1:
# High Capacity (CSD Version 2.0)
c_size = ((csd_reg[7] & 0x3F) << 16) | (csd_reg[8] << 8) | \
csd_reg[9]
total_bytes = (c_size + 1) * 512 * 1024
sd_info['capacity'] = f"{(total_bytes / (1024.0**3)):.1f} GiB"
elif csd_type == 2:
# Ultra Capacity (CSD Version 3.0)
c_size = ((csd_reg[6]) & 0xF) << 24 | (csd_reg[7] << 16) | \
(csd_reg[8] << 8) | csd_reg[9]
total_bytes = (c_size + 1) * 512 * 1024
sd_info['capacity'] = f"{(total_bytes / (1024.0**4)):.1f} TiB"
else:
# Invalid CSD, skip capacity check
return sd_info
sd_info['total_bytes'] = total_bytes
except Exception:
logging.info("Error Reading SDCard CSD Register")
return sd_info
def _get_cpu_info(self) -> Dict[str, Any]:
cpu_file = pathlib.Path("/proc/cpuinfo")
mem_file = pathlib.Path("/proc/meminfo")
cpu_info = {
'cpu_count': os.cpu_count(),
'bits': platform.architecture()[0],
'processor': platform.processor() or platform.machine(),
'cpu_desc': "",
'hardware_desc': "",
'model': "",
'total_memory': None,
'memory_units': ""
}
if cpu_file.exists():
try:
cpu_text = cpu_file.read_text().strip()
cpu_items = [item.strip() for item in cpu_text.split("\n\n")
if item.strip()]
for item in cpu_items:
cpu_desc_match = re.search(r"model name\s+:\s+(.+)", item)
if cpu_desc_match is not None:
cpu_info['cpu_desc'] = cpu_desc_match.group(1).strip()
continue
hw_match = re.search(r"Hardware\s+:\s+(.+)", cpu_items[-1])
if hw_match is not None:
cpu_info['hardware_desc'] = hw_match.group(1).strip()
model_match = re.search(r"Model\s+:\s+(.+)", cpu_items[-1])
if model_match is not None:
cpu_info['model'] = model_match.group(1).strip()
except Exception:
logging.info("Error Reading /proc/cpuinfo")
if mem_file.exists():
try:
mem_text = mem_file.read_text().strip()
for line in mem_text.split('\n'):
line = line.strip()
if line.startswith("MemTotal:"):
parts = line.split()
cpu_info['total_memory'] = int(parts[1])
cpu_info['memory_units'] = parts[2]
break
except Exception:
logging.info("Error Reading /proc/meminfo")
return cpu_info
async def _find_active_services(self):
shell_cmd: SCMDComp = self.server.lookup_component('shell_command')
scmd = shell_cmd.build_shell_command(
"systemctl list-units --type=service")
try:
resp = await scmd.run_with_response()
lines = resp.split('\n')
services = [line.split()[0].strip() for line in lines
if ".service" in line.strip()]
except Exception:
services = []
for svc in services:
sname = svc.rsplit('.', 1)[0]
for allowed in ALLOWED_SERVICES:
if sname.startswith(allowed):
self.available_services.append(sname)
self.system_info['available_services'] = self.available_services
def load_component(config: ConfigHelper) -> Machine:
return Machine(config)
+599
View File
@@ -0,0 +1,599 @@
# MQTT client implemenation 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
from collections import deque
import paho.mqtt.client as paho_mqtt
from tornado.ioloop import IOLoop
from websockets import 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
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 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):
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
self.address: str = config.get('address')
self.port: int = config.getint('port', 1883)
self.user_name = config.get('username', None)
pw_file_path = config.get('password_file', 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()
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.client = paho_mqtt.Client(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.reconnect_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"])
self.server.register_endpoint(
"/server/mqtt/subscribe", ["POST"],
self._handle_subscription_request,
transports=["http", "websocket"])
# Subscribe to API requests
self.json_rpc = JsonRPC(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.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)
logging.info(
f"Moonraker API topics - Request: {self.api_request_topic}, "
f"Response: {self.api_resp_topic}")
IOLoop.current().spawn_callback(self._initialize)
async def _initialize(self) -> None:
# We must wait for the IOLoop (asyncio event loop) to start
# prior to retreiving it
self.helper = AIOHelper(self.client)
if self.user_name is not None:
self.client.username_pw_set(self.user_name, self.password)
retries = 15
while retries:
try:
self.client.connect(self.address, self.port)
except ConnectionRefusedError:
retries -= 1
if retries:
logging.info("Unable to connect to MQTT broker, "
f"retries remaining: {retries}")
await asyncio.sleep(2.)
continue
self.server.set_failed_component("mqtt")
self.server.add_warning(
f"MQTT Broker Connection at ({self.address}, {self.port}) "
"refused. Check your client and broker configuration.")
return
break
self.client.socket().setsockopt(
socket.SOL_SOCKET, socket.SO_SNDBUF, 2048)
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:
IOLoop.current().spawn_callback(
hdl.callback, message.payload) # type: ignore
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:
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()
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.reconnect_task is None:
self.reconnect_task = asyncio.create_task(self._do_reconnect())
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) -> None:
logging.info("Attempting MQTT Reconnect")
while True:
try:
await asyncio.sleep(2.)
except asyncio.CancelledError:
break
try:
self.client.reconnect()
except ConnectionRefusedError:
continue
self.client.socket().setsockopt(
socket.SOL_SOCKET, socket.SO_SNDBUF, 2048)
break
self.reconnect_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(**kwargs) -> Any:
self._check_timestamp(kwargs)
result = await callback(
WebRequest(endpoint, kwargs, request_method))
return result
return func
def _generate_remote_callback(self, endpoint: str) -> RPCCallback:
async def func(**kwargs) -> Any:
self._check_timestamp(kwargs)
result = await self.server.make_request(
WebRequest(endpoint, kwargs))
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)
async def close(self) -> None:
if self.reconnect_task is not None:
self.reconnect_task.cancel()
self.reconnect_task = None
if not self.is_connected():
return
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))
def load_component(config: ConfigHelper) -> MQTTClient:
return MQTTClient(config)
+69 -31
View File
@@ -3,9 +3,22 @@
# 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 . import klippy_apis
APIComp = klippy_apis.KlippyAPI
OCTO_VERSION = '1.5.0'
@@ -23,14 +36,15 @@ 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')
# Local variables
self.klippy_apis = self.server.lookup_component('klippy_apis')
self.heaters = {}
self.last_print_stats = {}
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(
@@ -40,18 +54,22 @@ class OctoprintCompat:
# 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
@@ -59,50 +77,54 @@ 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)
# System
# TODO: shutdown/reboot/restart operations
async def _init(self):
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}')
sensors = []
# subscribe objects
sub = {s: None for s in sensors}
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}
def _handle_status_update(self, status):
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):
def printer_state(self) -> str:
klippy_state = self.server.get_klippy_state()
if klippy_state in ["disconnected", "startup"]:
return 'Offline'
@@ -115,8 +137,8 @@ class OctoprintCompat:
'complete': 'Operational'
}.get(self.last_print_stats.get('state', 'standby'), 'Error')
def printer_temps(self):
temps = {}
def printer_temps(self) -> Dict[str, Any]:
temps: Dict[str, Any] = {}
for heater, data in self.heaters.items():
name = 'bed'
if heater.startswith('extruder'):
@@ -134,7 +156,9 @@ class OctoprintCompat:
}
return temps
async def _get_version(self, web_request):
async def _get_version(self,
web_request: WebRequest
) -> Dict[str, str]:
"""
Version information
"""
@@ -144,7 +168,9 @@ 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
"""
@@ -155,7 +181,9 @@ class OctoprintCompat:
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.
@@ -174,7 +202,9 @@ 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
@@ -209,7 +239,9 @@ class OctoprintCompat:
},
}
async def _get_job(self, web_request):
async def _get_job(self,
web_request: WebRequest
) -> Dict[str, Any]:
"""
Get current job status
"""
@@ -230,7 +262,9 @@ class OctoprintCompat:
'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
"""
@@ -252,11 +286,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:
@@ -267,7 +303,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
"""
@@ -287,5 +325,5 @@ class OctoprintCompat:
}
def load_component(config):
def load_component(config: ConfigHelper) -> OctoprintCompat:
return OctoprintCompat(config)
+154 -109
View File
@@ -3,18 +3,39 @@
# 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
import json
import errno
import logging
import asyncio
from collections import deque
from utils import ServerError
from tornado import gen
from tornado.ioloop import IOLoop
# Annotation imports
from typing import (
TYPE_CHECKING,
Deque,
Any,
Tuple,
Optional,
Dict,
List,
Callable,
Coroutine,
)
if TYPE_CHECKING:
from confighelper import ConfigHelper
from . import klippy_apis
from .file_manager import file_manager
APIComp = klippy_apis.KlippyAPI
FMComp = file_manager.FileManager
FlexCallback = Callable[..., Optional[Coroutine]]
MIN_EST_TIME = 10.
INITIALIZE_TIMEOUT = 10.
@@ -25,26 +46,31 @@ class PanelDueError(ServerError):
RESTART_GCODES = ["RESTART", "FIRMWARE_RESTART"]
class SerialConnection:
def __init__(self, config, paneldue):
def __init__(self,
config: ConfigHelper,
paneldue: PanelDue
) -> None:
self.ioloop = IOLoop.current()
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.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
self.ioloop.spawn_callback(self._connect)
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.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 +78,9 @@ 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.ioloop.call_later(1., self._connect) # type: ignore
async def _connect(self):
async def _connect(self) -> None:
start_time = connect_time = time.time()
while not self.connected:
if connect_time > start_time + 30.:
@@ -73,14 +99,15 @@ class SerialConnection:
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.ioloop.add_handler(fd, self._handle_incoming,
IOLoop.READ | IOLoop.ERROR)
self.connected = True
logging.info("PanelDue Connected")
self.attempting_connect = False
def _handle_incoming(self, fd, events):
def _handle_incoming(self, fd: int, events: int) -> None:
if events & IOLoop.ERROR:
logging.info("PanelDue Connection Error")
self.disconnect(reconnect=True)
@@ -104,23 +131,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)
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
@@ -142,41 +170,44 @@ 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.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"}
@@ -184,14 +215,14 @@ class PanelDue:
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}
macro_list = [m for m in macros.split('\n') if m.strip()]
self.available_macros = {m.split()[0]: m for m in macro_list}
conf_macros = config.get('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}
macro_list = [m for m in conf_macros.split('\n') if m.strip()]
self.confirmed_macros = {m.split()[0]: m for m in macro_list}
self.available_macros.update(self.confirmed_macros)
ntkeys = config.get('non_trivial_keys', "Klipper state")
@@ -216,7 +247,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 +256,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,7 +270,7 @@ class PanelDue:
'M999': lambda args: "FIRMWARE_RESTART"
}
async def _process_klippy_ready(self):
async def _process_klippy_ready(self) -> None:
# Request "info" and "configfile" status
retries = 10
printer_info = cfg_status = {}
@@ -259,8 +290,9 @@ class PanelDue:
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(
@@ -288,6 +320,7 @@ class PanelDue:
self.heaters.append(cfg)
sub_args[cfg] = None
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,28 +329,28 @@ 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():
@@ -328,7 +361,7 @@ class PanelDue:
# 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 +403,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 +424,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)
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 +451,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)
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 +486,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 +508,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 +521,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 +537,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 +549,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 +562,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,8 +582,11 @@ 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
@@ -587,6 +624,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 +637,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,11 +679,12 @@ 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)]
if self.extruder_count > 0:
extruder_name: Optional[str]
extruder_name = p_state['toolhead'].get('extruder')
if extruder_name is not None:
tool = 0
@@ -649,12 +693,12 @@ class PanelDue:
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)
@@ -664,7 +708,7 @@ class PanelDue:
response.setdefault('extr', []).append(round(pos[3], 2))
# 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 +717,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 +733,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 +757,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 +771,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 +800,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)
+427 -287
View File
@@ -4,42 +4,84 @@
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging
from __future__ import annotations
import os
import asyncio
import sys
import logging
import json
import struct
import socket
import gpiod
from tornado.ioloop import IOLoop
from tornado.iostream import IOStream
from tornado import gen
from tornado.locks import Lock
from tornado.httpclient import AsyncHTTPClient
from tornado.escape import json_decode
# Annotation imports
from typing import (
TYPE_CHECKING,
Type,
List,
Any,
Optional,
Dict,
Coroutine,
Tuple,
Union,
)
# Special handling for gpiod import
HAS_GPIOD = True
DIST_PATH = "/usr/lib/python3/dist-packages"
if os.path.exists(DIST_PATH):
sys.path.insert(0, DIST_PATH)
try:
import gpiod
except ImportError:
HAS_GPIOD = False
sys.path.pop(0)
else:
HAS_GPIOD = False
if TYPE_CHECKING:
from confighelper import ConfigHelper
from websockets import WebRequest
from . import klippy_apis
APIComp = klippy_apis.KlippyAPI
class PrinterPower:
def __init__(self, config):
def __init__(self, config: ConfigHelper) -> None:
self.server = config.get_server()
if not HAS_GPIOD:
self.server.add_warning(
"Unable to load gpiod library, GPIO power "
"devices will not be loaded")
self.chip_factory = GpioChipFactory()
self.devices = {}
self.devices: Dict[str, PowerDevice] = {}
prefix_sections = config.get_prefix_sections("power")
logging.info(f"Power component loading devices: {prefix_sections}")
dev_types = {
"gpio": GpioDevice,
"tplink_smartplug": TPLinkSmartPlug,
"tasmota": Tasmota,
"shelly": Shelly,
"homeseer": HomeSeer,
"homeassistant": HomeAssistant,
"loxonev1": Loxonev1
}
try:
for section in prefix_sections:
cfg = config[section]
dev_type = cfg.get("type")
if dev_type == "gpio":
dev = GpioDevice(cfg, self.chip_factory)
elif dev_type == "tplink_smartplug":
dev = TPLinkSmartPlug(cfg)
elif dev_type == "tasmota":
dev = Tasmota(cfg)
elif dev_type == "shelly":
dev = Shelly(cfg)
elif dev_type == "homeseer":
dev = HomeSeer(cfg)
else:
dev_type: str = cfg.get("type")
dev_class: Optional[Type[PowerDevice]]
dev_class = dev_types.get(dev_type)
if dev_class is None:
raise config.error(f"Unsupported Device Type: {dev_type}")
dev = dev_class(cfg)
if isinstance(dev, GpioDevice):
if not HAS_GPIOD:
continue
dev.configure_line(cfg, self.chip_factory)
self.devices[dev.get_name()] = dev
except Exception:
self.chip_factory.close()
@@ -50,13 +92,16 @@ class PrinterPower:
self._handle_list_devices)
self.server.register_endpoint(
"/machine/device_power/status", ['GET'],
self._handle_power_request)
self._handle_batch_power_request)
self.server.register_endpoint(
"/machine/device_power/on", ['POST'],
self._handle_power_request)
self._handle_batch_power_request)
self.server.register_endpoint(
"/machine/device_power/off", ['POST'],
self._handle_power_request)
self._handle_batch_power_request)
self.server.register_endpoint(
"/machine/device_power/device", ['GET', 'POST'],
self._handle_single_power_request)
self.server.register_remote_method(
"set_device_power", self.set_device_power)
self.server.register_event_handler(
@@ -65,51 +110,83 @@ class PrinterPower:
IOLoop.current().spawn_callback(
self._initalize_devices, list(self.devices.values()))
async def _check_klippy_printing(self):
klippy_apis = self.server.lookup_component('klippy_apis')
result = await klippy_apis.query_objects(
async def _check_klippy_printing(self) -> bool:
kapis: APIComp = self.server.lookup_component('klippy_apis')
result: Dict[str, Any] = await kapis.query_objects(
{'print_stats': None}, default={})
pstate = result.get('print_stats', {}).get('state', "").lower()
return pstate == "printing"
async def _initalize_devices(self, inital_devs):
async def _initalize_devices(self,
inital_devs: List[PowerDevice]
) -> None:
for dev in inital_devs:
ret = dev.initialize()
if asyncio.iscoroutine(ret):
if ret is not None:
await ret
async def _handle_klippy_shutdown(self):
async def _handle_klippy_shutdown(self) -> None:
for name, dev in self.devices.items():
if hasattr(dev, "off_when_shutdown"):
if dev.off_when_shutdown:
logging.info(
f"Powering off device [{name}] due to"
" klippy shutdown")
await self._process_request(dev, "off")
if dev.has_off_when_shutdown():
logging.info(
f"Powering off device [{name}] due to"
" klippy shutdown")
await self._process_request(dev, "off")
async def _handle_list_devices(self, web_request):
async def _handle_list_devices(self,
web_request: WebRequest
) -> Dict[str, Any]:
dev_list = [d.get_device_info() for d in self.devices.values()]
output = {"devices": dev_list}
return output
async def _handle_power_request(self, web_request):
async def _handle_single_power_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
dev_name: str = web_request.get_str('device')
req_action = web_request.get_action()
if dev_name not in self.devices:
raise self.server.error(f"No valid device named {dev_name}")
dev = self.devices[dev_name]
if req_action == 'GET':
action = "status"
elif req_action == "POST":
action = web_request.get_str('action').lower()
if action not in ["on", "off", "toggle"]:
raise self.server.error(
f"Invalid requested action '{action}'")
result = await self._process_request(dev, action)
return {dev_name: result}
async def _handle_batch_power_request(self,
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")
requsted_devs = {k: self.devices.get(k, None) for k in args}
requested_devs = {k: self.devices.get(k, None) for k in args}
result = {}
req = ep.split("/")[-1]
for name, device in requsted_devs.items():
for name, device in requested_devs.items():
if device is not None:
result[name] = await self._process_request(device, req)
else:
result[name] = "device_not_found"
return result
async def _process_request(self, device, req):
async def _process_request(self,
device: PowerDevice,
req: str
) -> str:
ret = device.refresh_status()
if ret is not None:
await ret
dev_info = device.get_device_info()
if req == "toggle":
req = "on" if dev_info['status'] == "off" else "off"
if req in ["on", "off"]:
cur_state = device.get_device_info()['status']
cur_state: str = dev_info['status']
if req == cur_state:
# device is already in requested state, do nothing
return cur_state
@@ -119,22 +196,17 @@ class PrinterPower:
f"Unable to change power for {device.get_name()} "
"while printing")
ret = device.set_power(req)
if asyncio.iscoroutine(ret):
if ret is not None:
await ret
dev_info = device.get_device_info()
self.server.send_event("power:power_changed", dev_info)
device.run_power_changed_action()
elif req == "status":
ret = device.refresh_status()
if asyncio.iscoroutine(ret):
await ret
dev_info = device.get_device_info()
else:
elif req != "status":
raise self.server.error(f"Unsupported power request: {req}")
return dev_info['status']
def set_device_power(self, device, state):
status = None
def set_device_power(self, device: str, state: str) -> None:
status: Optional[str] = None
if isinstance(state, bool):
status = "on" if state else "off"
elif isinstance(state, str):
@@ -151,32 +223,32 @@ class PrinterPower:
ioloop.spawn_callback(
self._process_request, self.devices[device], status)
async def add_device(self, name, device):
async def add_device(self, name: str, device: PowerDevice) -> None:
if name in self.devices:
raise self.server.error(
f"Device [{name}] already configured")
ret = device.initialize()
if asyncio.iscoroutine(ret):
if ret is not None:
await ret
self.devices[name] = device
async def close(self):
async def close(self) -> None:
for device in self.devices.values():
if hasattr(device, "close"):
ret = device.close()
if asyncio.iscoroutine(ret):
await ret
ret = device.close()
if ret is not None:
await ret
self.chip_factory.close()
class PowerDevice:
def __init__(self, config):
def __init__(self, config: ConfigHelper) -> None:
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.state = "init"
self.type: str = config.get('type')
self.state: str = "init"
self.locked_while_printing = config.getboolean(
'locked_while_printing', False)
self.off_when_shutdown = config.getboolean('off_when_shutdown', False)
@@ -188,44 +260,131 @@ class PowerDevice:
if self.restart_delay < .000001:
raise config.error("Option 'restart_delay' must be above 0.0")
def get_name(self):
def get_name(self) -> str:
return self.name
def get_device_info(self):
def get_device_info(self) -> Dict[str, Any]:
return {
'device': self.name,
'status': self.state,
'locked_while_printing': self.locked_while_printing
'locked_while_printing': self.locked_while_printing,
'type': self.type
}
def get_locked_while_printing(self):
def get_locked_while_printing(self) -> bool:
return self.locked_while_printing
def run_power_changed_action(self):
def run_power_changed_action(self) -> None:
if self.state == "on" and self.klipper_restart:
ioloop = IOLoop.current()
klippy_apis = self.server.lookup_component("klippy_apis")
ioloop.call_later(self.restart_delay, klippy_apis.do_restart,
"FIRMWARE_RESTART")
kapis: APIComp = self.server.lookup_component("klippy_apis")
ioloop.call_later(
self.restart_delay, kapis.do_restart, # type:ignore
"FIRMWARE_RESTART")
def has_off_when_shutdown(self) -> bool:
return self.off_when_shutdown
def initialize(self) -> Optional[Coroutine]:
raise NotImplementedError
def refresh_status(self) -> Optional[Coroutine]:
raise NotImplementedError
def set_power(self, state: str) -> Optional[Coroutine]:
raise NotImplementedError
def close(self) -> Optional[Coroutine]:
pass
class HTTPDevice(PowerDevice):
def __init__(self,
config: ConfigHelper,
default_port: int = -1,
default_user: str = "",
default_password: str = "",
default_protocol: str = "http"
) -> None:
super().__init__(config)
self.client = AsyncHTTPClient()
self.request_mutex = Lock()
self.addr: str = config.get("address")
self.port = config.getint("port", default_port)
self.user = config.get("user", default_user)
self.password = config.get("password", default_password)
self.protocol = config.get("protocol", default_protocol)
async def initialize(self) -> None:
await self.refresh_status()
async def _send_http_command(self,
url: str,
command: str
) -> Dict[str, Any]:
try:
response = await self.client.fetch(url)
data = json_decode(response.body)
except Exception:
msg = f"Error sending '{self.type}' command: {command}"
logging.exception(msg)
raise self.server.error(msg)
return data
async def _send_power_request(self, state: str) -> str:
raise NotImplementedError(
"_send_power_request must be implemented by children")
async def _send_status_request(self) -> str:
raise NotImplementedError(
"_send_status_request must be implemented by children")
async def refresh_status(self) -> None:
async with self.request_mutex:
try:
state = await self._send_status_request()
except Exception:
self.state = "error"
msg = f"Error Refeshing Device Status: {self.name}"
logging.exception(msg)
raise self.server.error(msg) from None
self.state = state
async def set_power(self, state):
async with self.request_mutex:
try:
state = await self._send_power_request(state)
except Exception:
self.state = "error"
msg = f"Error Setting Device Status: {self.name} to {state}"
logging.exception(msg)
raise self.server.error(msg) from None
self.state = state
class GpioChipFactory:
def __init__(self):
self.chips = {}
def __init__(self) -> None:
self.chips: Dict[str, gpiod.Chip] = {}
def get_gpio_chip(self, chip_name):
def get_gpio_chip(self, chip_name) -> gpiod.Chip:
if chip_name in self.chips:
return self.chips[chip_name]
chip = gpiod.Chip(chip_name, gpiod.Chip.OPEN_BY_NAME)
self.chips[chip_name] = chip
return chip
def close(self):
def close(self) -> None:
for chip in self.chips.values():
chip.close()
class GpioDevice(PowerDevice):
def __init__(self, config, chip_factory):
def __init__(self, config: ConfigHelper):
super().__init__(config)
self.initial_state = config.getboolean('initial_state', False)
def configure_line(self,
config: ConfigHelper,
chip_factory: GpioChipFactory
) -> None:
pin, chip_id, invert = self._parse_pin(config)
try:
chip = chip_factory.get_gpio_chip(chip_id)
@@ -243,15 +402,15 @@ class GpioDevice(PowerDevice):
f"Unable to init {pin}. Make sure the gpio is not in "
"use by another program or exported by sysfs.")
raise config.error("Power GPIO Config Error")
self.initial_state = config.getboolean('initial_state', False)
def _parse_pin(self, config):
def _parse_pin(self, config: ConfigHelper) -> Tuple[int, str, bool]:
pin = cfg_pin = config.get("pin")
invert = False
if pin[0] == "!":
pin = pin[1:]
invert = True
chip_id = "gpiochip0"
chip_id: str = "gpiochip0"
pin_parts = pin.split("/")
if len(pin_parts) == 2:
chip_id, pin = pin_parts
@@ -264,29 +423,16 @@ class GpioDevice(PowerDevice):
not pin[4:].isdigit():
raise config.error(
f"Invalid Power Pin configuration: {cfg_pin}")
pin = int(pin[4:])
return pin, chip_id, invert
pin_id = int(pin[4:])
return pin_id, chip_id, invert
def initialize(self):
def initialize(self) -> None:
self.set_power("on" if self.initial_state else "off")
def get_device_info(self):
return {
**super().get_device_info(),
'type': "gpio"
}
def refresh_status(self) -> None:
pass
def refresh_status(self):
try:
val = self.line.get_value()
except Exception:
self.state = "error"
msg = f"Error Refeshing Device Status: {self.name}"
logging.exception(msg)
raise self.server.error(msg) from None
self.state = "on" if val else "off"
def set_power(self, state):
def set_power(self, state) -> None:
try:
self.line.set_value(int(state == "on"))
except Exception:
@@ -296,7 +442,7 @@ class GpioDevice(PowerDevice):
raise self.server.error(msg) from None
self.state = state
def close(self):
def close(self) -> None:
self.line.release()
@@ -308,14 +454,16 @@ class GpioDevice(PowerDevice):
# Copyright 2016 softScheck GmbH
class TPLinkSmartPlug(PowerDevice):
START_KEY = 0xAB
def __init__(self, config):
def __init__(self, config: ConfigHelper) -> None:
super().__init__(config)
self.server = config.get_server()
self.addr = config.get("address").split('/')
self.request_mutex = Lock()
self.addr: List[str] = config.get("address").split('/')
self.port = config.getint("port", 9999)
async def _send_tplink_command(self, command):
out_cmd = {}
async def _send_tplink_command(self,
command: str
) -> Dict[str, Any]:
out_cmd: Dict[str, Any] = {}
if command in ["on", "off"]:
out_cmd = {
'system': {'set_relay_state': {'state': int(command == "on")}}
@@ -337,7 +485,7 @@ class TPLinkSmartPlug(PowerDevice):
await stream.connect((self.addr[0], self.port))
await stream.write(self._encrypt(out_cmd))
data = await stream.read_bytes(2048, partial=True)
length = struct.unpack(">I", data[:4])[0]
length: int = struct.unpack(">I", data[:4])[0]
data = data[4:]
retries = 5
remaining = length - len(data)
@@ -355,8 +503,8 @@ class TPLinkSmartPlug(PowerDevice):
stream.close()
return json.loads(self._decrypt(data))
def _encrypt(self, data):
data = json.dumps(data)
def _encrypt(self, outdata: Dict[str, Any]) -> bytes:
data = json.dumps(outdata)
key = self.START_KEY
res = struct.pack(">I", len(data))
for c in data:
@@ -365,64 +513,63 @@ class TPLinkSmartPlug(PowerDevice):
res += bytes([val])
return res
def _decrypt(self, data):
key = self.START_KEY
res = ""
def _decrypt(self, data: bytes) -> str:
key: int = self.START_KEY
res: str = ""
for c in data:
val = key ^ c
key = c
res += chr(val)
return res
async def initialize(self):
async def initialize(self) -> None:
await self.refresh_status()
def get_device_info(self):
return {
**super().get_device_info(),
'type': "tplink_smartplug"
}
async def refresh_status(self) -> None:
async with self.request_mutex:
try:
state: str
res = await self._send_tplink_command("info")
if len(self.addr) == 2:
# TPLink device controls multiple devices
children: Dict[int, Any]
children = res['system']['get_sysinfo']['children']
state = children[int(self.addr[1])]['state']
else:
state = res['system']['get_sysinfo']['relay_state']
except Exception:
self.state = "error"
msg = f"Error Refeshing Device Status: {self.name}"
logging.exception(msg)
raise self.server.error(msg) from None
self.state = "on" if state else "off"
async def refresh_status(self):
try:
res = await self._send_tplink_command("info")
if len(self.addr) == 2:
# TPLink device controls multiple devices
children = res['system']['get_sysinfo']['children']
state = children[int(self.addr[1])]['state']
else:
state = res['system']['get_sysinfo']['relay_state']
except Exception:
self.state = "error"
msg = f"Error Refeshing Device Status: {self.name}"
logging.exception(msg)
raise self.server.error(msg) from None
self.state = "on" if state else "off"
async def set_power(self, state):
try:
res = await self._send_tplink_command(state)
err = res['system']['set_relay_state']['err_code']
except Exception:
err = 1
logging.exception(f"Power Toggle Error: {self.name}")
if err:
self.state = "error"
raise self.server.error(
f"Error Toggling Device Power: {self.name}")
self.state = state
async def set_power(self, state) -> None:
async with self.request_mutex:
err: int
try:
res = await self._send_tplink_command(state)
err = res['system']['set_relay_state']['err_code']
except Exception:
err = 1
logging.exception(f"Power Toggle Error: {self.name}")
if err:
self.state = "error"
raise self.server.error(
f"Error Toggling Device Power: {self.name}")
self.state = state
class Tasmota(PowerDevice):
def __init__(self, config):
super().__init__(config)
self.server = config.get_server()
self.addr = config.get("address")
class Tasmota(HTTPDevice):
def __init__(self, config: ConfigHelper) -> None:
super().__init__(config, default_password="")
self.output_id = config.getint("output_id", 1)
self.password = config.get("password", "")
self.timer = config.get("timer","")
self.timer = config.get("timer", "")
async def _send_tasmota_command(self, command, password=None):
async def _send_tasmota_command(self,
command: str,
password: Optional[str] = None
) -> Dict[str, Any]:
if command in ["on", "off"]:
out_cmd = f"Power{self.output_id}%20{command}"
if self.timer != "" and command == "off":
@@ -434,76 +581,44 @@ class Tasmota(PowerDevice):
url = f"http://{self.addr}/cm?user=admin&password=" \
f"{self.password}&cmnd={out_cmd}"
data = ""
http_client = AsyncHTTPClient()
return await self._send_http_command(url, command)
async def _send_status_request(self) -> str:
res = await self._send_tasmota_command("info")
try:
response = await http_client.fetch(url)
data = json_decode(response.body)
except Exception:
msg = f"Error sending tplink command: {command}"
logging.exception(msg)
raise self.server.error(msg)
return data
state: str = res[f"POWER{self.output_id}"].lower()
except KeyError as e:
if self.output_id == 1:
state = res[f"POWER"].lower()
else:
raise KeyError(e)
return state
async def initialize(self):
await self.refresh_status()
def get_device_info(self):
return {
**super().get_device_info(),
'type': "tasmota"
}
async def refresh_status(self):
try:
res = await self._send_tasmota_command("info")
try:
async def _send_power_request(self, state: str) -> str:
res = await self._send_tasmota_command(state)
if self.timer == "" or state != "off":
try:
state = res[f"POWER{self.output_id}"].lower()
except KeyError as e:
if self.output_id == 1 :
if self.output_id == 1:
state = res[f"POWER"].lower()
else:
raise KeyError(e)
except Exception:
self.state = "error"
msg = f"Error Refeshing Device Status: {self.name}"
logging.exception(msg)
raise self.server.error(msg) from None
self.state = state
async def set_power(self, state):
try:
res = await self._send_tasmota_command(state)
if self.timer == "" or state != "off":
try:
state = res[f"POWER{self.output_id}"].lower()
except KeyError as e:
if self.output_id == 1 :
state = res[f"POWER"].lower()
else:
raise KeyError(e)
except Exception:
self.state = "error"
msg = f"Error Setting Device Status: {self.name} to {state}"
logging.exception(msg)
raise self.server.error(msg) from None
self.state = state
return state
class Shelly(PowerDevice):
def __init__(self, config):
super().__init__(config)
self.server = config.get_server()
self.addr = config.get("address")
class Shelly(HTTPDevice):
def __init__(self, config: ConfigHelper) -> None:
super().__init__(config, default_user="admin", default_password="")
self.output_id = config.getint("output_id", 0)
self.user = config.get("user", "admin")
self.password = config.get("password", "")
self.timer = config.get("timer","")
self.timer = config.get("timer", "")
async def _send_shelly_command(self, command):
if command in ["on", "off"]:
async def _send_shelly_command(self, command: str) -> Dict[str, Any]:
if command == "on":
out_cmd = f"relay/{self.output_id}?turn={command}"
elif command == "off":
if self.timer != "":
out_cmd = f"relay/{self.output_id}?turn={command}&timer={self.timer}"
out_cmd = f"relay/{self.output_id}?turn=on&timer={self.timer}"
else:
out_cmd = f"relay/{self.output_id}?turn={command}"
elif command == "info":
@@ -515,107 +630,132 @@ class Shelly(PowerDevice):
else:
out_pwd = f""
url = f"http://{out_pwd}{self.addr}/{out_cmd}"
data = ""
http_client = AsyncHTTPClient()
try:
response = await http_client.fetch(url)
data = json_decode(response.body)
except Exception:
msg = f"Error sending shelly command: {command}"
logging.exception(msg)
raise self.server.error(msg)
return data
return await self._send_http_command(url, command)
async def initialize(self):
await self.refresh_status()
async def _send_status_request(self) -> str:
res = await self._send_shelly_command("info")
state: str = res[f"ison"]
timer_remaining = res[f"timer_remaining"] if self.timer != "" else 0
return "on" if state and timer_remaining == 0 else "off"
def get_device_info(self):
return {
**super().get_device_info(),
'type': "shelly"
}
async def _send_power_request(self, state: str) -> str:
res = await self._send_shelly_command(state)
state = res[f"ison"]
timer_remaining = res[f"timer_remaining"] if self.timer != "" else 0
return "on" if state and timer_remaining == 0 else "off"
async def refresh_status(self):
try:
res = await self._send_shelly_command("info")
state = res[f"ison"]
except Exception:
self.state = "error"
msg = f"Error Refeshing Device Status: {self.name}"
logging.exception(msg)
raise self.server.error(msg) from None
self.state = "on" if state else "off"
async def set_power(self, state):
try:
res = await self._send_shelly_command(state)
state = res[f"ison"]
except Exception:
self.state = "error"
msg = f"Error Setting Device Status: {self.name} to {state}"
logging.exception(msg)
raise self.server.error(msg) from None
self.state = "on" if state else "off"
class HomeSeer(PowerDevice):
def __init__(self, config):
super().__init__(config)
self.server = config.get_server()
self.addr = config.get("address")
class HomeSeer(HTTPDevice):
def __init__(self, config: ConfigHelper) -> None:
super().__init__(config, default_user="admin", default_password="")
self.device = config.getint("device")
self.user = config.get("user", "admin")
self.password = config.get("password", "")
async def _send_homeseer(self, request, additional=""):
async def _send_homeseer(self,
request: str,
additional: str = ""
) -> Dict[str, Any]:
url = (f"http://{self.user}:{self.password}@{self.addr}"
f"/JSON?user={self.user}&pass={self.password}"
f"&request={request}&ref={self.device}&{additional}")
data = ""
http_client = AsyncHTTPClient()
return await self._send_http_command(url, request)
async def _send_status_request(self) -> str:
res = await self._send_homeseer("getstatus")
return res[f"Devices"][0]["status"].lower()
async def _send_power_request(self, state: str) -> str:
if state == "on":
state_hs = "On"
elif state == "off":
state_hs = "Off"
res = await self._send_homeseer("controldevicebylabel",
f"label={state_hs}")
return state
class HomeAssistant(HTTPDevice):
def __init__(self, config: ConfigHelper) -> None:
super().__init__(config, default_port=8123)
self.device: str = config.get("device")
self.token: str = config.get("token")
self.domain: str = config.get("domain", "switch")
async def _send_homeassistant_command(self,
command: str
) -> Dict[Union[str, int], Any]:
if command == "on":
out_cmd = f"api/services/{self.domain}/turn_on"
body = {"entity_id": self.device}
method = "POST"
elif command == "off":
out_cmd = f"api/services/{self.domain}/turn_off"
body = {"entity_id": self.device}
method = "POST"
elif command == "info":
out_cmd = f"api/states/{self.device}"
method = "GET"
else:
raise self.server.error(
f"Invalid homeassistant command: {command}")
url = f"{self.protocol}://{self.addr}:{self.port}/{out_cmd}"
headers = {
'Authorization': f'Bearer {self.token}',
'Content-Type': 'application/json'
}
try:
response = await http_client.fetch(url)
data = json_decode(response.body)
if (method == "POST"):
response = await self.client.fetch(
url, method="POST", body=json.dumps(body), headers=headers)
else:
response = await self.client.fetch(
url, method="GET", headers=headers)
data: Dict[Union[str, int], Any] = json_decode(response.body)
except Exception:
msg = f"Error sending HomeSeer command: {request}"
msg = f"Error sending homeassistant command: {command}"
logging.exception(msg)
raise self.server.error(msg)
return data
async def initialize(self):
await self.refresh_status()
async def _send_status_request(self) -> str:
res = await self._send_homeassistant_command("info")
return res[f"state"]
def get_device_info(self):
return {
**super().get_device_info(),
'type': "homeseer"
}
async def _send_power_request(self, state: str) -> str:
await self._send_homeassistant_command(state)
res = await self._send_status_request()
return res
async def refresh_status(self):
try:
res = await self._send_homeseer("getstatus")
state = res[f"Devices"][0]["status"].lower()
except Exception:
self.state = "error"
msg = f"Error Refeshing Device Status: {self.name}"
logging.exception(msg)
raise self.server.error(msg) from None
self.state = state
class Loxonev1(HTTPDevice):
def __init__(self, config: ConfigHelper) -> None:
super().__init__(config, default_user="admin",
default_password="admin")
self.output_id = config.get("output_id", "")
async def _send_loxonev1_command(self, command: str) -> Dict[str, Any]:
if command in ["on", "off"]:
out_cmd = f"jdev/sps/io/{self.output_id}/{command}"
elif command == "info":
out_cmd = f"jdev/sps/io/{self.output_id}"
else:
raise self.server.error(f"Invalid loxonev1 command: {command}")
if self.password != "":
out_pwd = f"{self.user}:{self.password}@"
else:
out_pwd = f""
url = f"http://{out_pwd}{self.addr}/{out_cmd}"
return await self._send_http_command(url, command)
async def _send_status_request(self) -> str:
res = await self._send_loxonev1_command("info")
state = res[f"LL"][f"value"]
return "on" if int(state) == 1 else "off"
async def _send_power_request(self, state: str) -> str:
res = await self._send_loxonev1_command(state)
state = res[f"LL"][f"value"]
return "on" if int(state) == 1 else "off"
async def set_power(self, state):
try:
if state == "on":
state_hs = "On"
elif state == "off":
state_hs = "Off"
res = await self._send_homeseer("controldevicebylabel",
f"label={state_hs}")
except Exception:
self.state = "error"
msg = f"Error Setting Device Status: {self.name} to {state}"
logging.exception(msg)
raise self.server.error(msg) from None
self.state = state
# The power component has multiple configuration sections
def load_component_multi(config):
def load_component_multi(config: ConfigHelper) -> PrinterPower:
return PrinterPower(config)
+88 -36
View File
@@ -3,6 +3,8 @@
# 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 time
import re
import os
@@ -10,12 +12,29 @@ import pathlib
import logging
from collections import deque
from tornado.ioloop import IOLoop, PeriodicCallback
from tornado.locks import Lock
# Annotation imports
from typing import (
TYPE_CHECKING,
Deque,
Any,
Tuple,
Optional,
Dict,
)
if TYPE_CHECKING:
from confighelper import ConfigHelper
from websockets import WebRequest
from . import shell_command
VC_GEN_CMD_FILE = "/usr/bin/vcgencmd"
STATM_FILE_PATH = "/proc/self/smaps_rollup"
TEMPERATURE_PATH = "/sys/class/thermal/thermal_zone0/temp"
STAT_UPDATE_TIME_MS = 1000
REPORT_QUEUE_SIZE = 30
THROTTLE_CHECK_INTERVAL = 10
REPORT_BLOCKED_TIME = 5.
THROTTLED_FLAGS = {
1: "Under-Voltage Detected",
@@ -29,62 +48,81 @@ 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._handle_stat_update, STAT_UPDATE_TIME_MS) # type: ignore
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.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.throttle_check_lock = Lock()
self.total_throttled: int = 0
self.last_throttled: int = 0
self.update_sequence: int = 0
self.stat_update_cb.start()
async def _handle_stat_request(self, web_request):
ts = None
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()
return {
'moonraker_stats': list(self.proc_stat_queue),
'throttled_state': ts
'throttled_state': ts,
'cpu_temp': self._get_cpu_temperature()
}
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)}"
msg += f"\nCPU Temperature: {self._get_cpu_temperature()}"
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):
async def _handle_stat_update(self) -> None:
update_time = time.time()
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)
if time_diff > REPORT_BLOCKED_TIME:
logging.info(
f"EVENT LOOP BLOCKED: {round(time_diff, 2)} seconds, "
f"Moonraker Process Usage: {usage}%")
mem, mem_units = self._get_memory_usage()
self.proc_stat_queue.append({
cpu_temp = self._get_cpu_temperature()
result = {
"time": update_time,
"cpu_usage": usage,
"memory": mem,
"mem_units": mem_units
"mem_units": mem_units,
}
self.proc_stat_queue.append(result)
self.server.send_event("proc_stats:proc_stat_update", {
'moonraker_stats': result,
'cpu_temp': cpu_temp
})
self.last_update_time = update_time
self.last_proc_time = proc_time
@@ -93,27 +131,31 @@ class ProcStats:
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']}")
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.throttled = cur_throttled
self.last_throttled = cur_throttled
self.total_throttled |= cur_throttled
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 _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 +167,23 @@ class ProcStats:
return None, None
return mem, units
def _format_stats(self, stats):
def _get_cpu_temperature(self) -> Optional[float]:
temp = None
if self.temp_file.exists():
try:
res = int(self.temp_file.read_text().strip())
temp = res / 1000.
except Exception:
return None
return temp
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):
def close(self) -> None:
self.stat_update_cb.stop()
def load_component(config):
def load_component(config: ConfigHelper) -> ProcStats:
return ProcStats(config)
+175 -83
View File
@@ -3,32 +3,60 @@
# 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 tornado.locks import Lock
from utils import ServerError
# Annotation imports
from typing import (
TYPE_CHECKING,
Optional,
Callable,
Coroutine,
Dict,
Set,
)
if TYPE_CHECKING:
from confighelper import ConfigHelper
from asyncio import BaseTransport
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):
def initialize(self,
program_name: str,
std_out_cb: OutputCallback,
std_err_cb: OutputCallback,
log_stderr: bool
) -> None:
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
async def _read_stream_with_cb(self, fd):
transport = self._transport.get_pipe_transport(fd)
async def _read_stream_with_cb(self, fd: int) -> bytes:
transport: BaseTransport = \
self._transport.get_pipe_transport(fd) # type: ignore
if fd == 2:
stream = self.stderr
cb = self.std_err_cb
@@ -36,19 +64,22 @@ class SCProcess(asyncio.subprocess.Process):
assert fd == 1
stream = self.stdout
cb = self.std_out_cb
assert stream is not None
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()}")
logging.info(
f"{self.program_name}: "
f"{output.decode(errors='ignore')}")
output = output.rstrip(b'\n')
if output and cb is not None:
cb(output)
transport.close()
return output
async def cancel(self, sig_idx=1):
async def cancel(self, sig_idx: int = 1) -> None:
if self.cancel_requested:
return
self.cancel_requested = True
@@ -73,30 +104,40 @@ class SCProcess(asyncio.subprocess.Process):
if self.stderr is not None:
self.stderr.feed_eof()
async def communicate_with_cb(self, input=None):
async def communicate_with_cb(self,
input: Optional[bytes] = None
) -> None:
if input is not None:
stdin = self._feed_stdin(input)
stdin: Coroutine = self._feed_stdin(input) # type: ignore
else:
stdin = self._noop()
stdin = self._noop() # type: ignore
if self.stdout is not None and self.std_out_cb is not None:
stdout = self._read_stream_with_cb(1)
stdout: Coroutine = self._read_stream_with_cb(1)
else:
stdout = self._noop()
stdout = self._noop() # type: ignore
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)
stderr: Coroutine = self._read_stream_with_cb(2)
else:
stderr = self._noop()
stderr = self._noop() # type: ignore
stdin, stdout, stderr = await asyncio.tasks.gather(
stdin, stdout, stderr, loop=self._loop)
stdin, stdout, stderr, loop=self._loop) # type: ignore
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,78 +146,103 @@ class ShellCommand:
self.log_stderr = log_stderr
self.env = env
self.cwd = cwd
self.proc = None
self.proc: Optional[SCProcess] = None
self.cancelled = False
self.return_code = None
self.return_code: Optional[int] = None
self.run_lock = Lock()
async def cancel(self, sig_idx=1):
async def cancel(self, sig_idx: int = 1) -> None:
self.cancelled = True
if self.proc is not None:
await self.proc.cancel(sig_idx)
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
) -> 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
if not await self._create_subprocess():
self.factory.remove_running_command(self)
return False
assert self.proc is not None
try:
if verbose:
ret: Coroutine = self.proc.communicate_with_cb()
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.proc.cancel(sig_idx)
else:
complete = not self.cancelled
self.factory.remove_running_command(self)
return self._check_proc_success(complete, log_complete)
async def _create_subprocess(self):
async def run_with_response(self,
timeout: float = 2.,
retries: int = 1,
log_complete: bool = True,
sig_idx: int = 1
) -> str:
async with self.run_lock:
self.factory.add_running_command(self)
retries = max(1, retries)
while retries > 0:
self._reset_command_data()
timed_out = False
stdout = stderr = b""
if await self._create_subprocess():
assert self.proc is not None
try:
ret = self.proc.communicate()
stdout, stderr = await asyncio.wait_for(
ret, timeout=timeout)
except asyncio.TimeoutError:
complete = False
timed_out = True
await self.proc.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):
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 gen.sleep(.5)
self.factory.remove_running_command(self)
raise ShellCommandError(
f"Error running shell command: '{self.command}'",
self.return_code, stdout, stderr)
async def _create_subprocess(self) -> bool:
loop = asyncio.get_event_loop()
def protocol_factory():
@@ -200,7 +266,11 @@ class ShellCommand:
return False
return True
def _check_proc_success(self, complete, log_complete):
def _check_proc_success(self,
complete: bool,
log_complete: bool
) -> bool:
assert self.proc is not None
self.return_code = self.proc.returncode
success = self.return_code == 0 and complete
if success:
@@ -218,10 +288,32 @@ 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,
def __init__(self, config: ConfigHelper) -> None:
self.running_commands: Set[ShellCommand] = set()
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 load_component(config):
return ShellCommandFactory()
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
@@ -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,249 @@
# 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 pathlib
import shutil
import hashlib
from concurrent.futures.thread import ThreadPoolExecutor
from tornado.ioloop import IOLoop
from .base_deploy import BaseDeploy
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Optional,
Union,
Dict,
List,
)
if TYPE_CHECKING:
from confighelper import ConfigHelper
from .update_manager import CommandHelper
CHANNEL_TO_TYPE = {
"stable": "zip",
"beta": "zip_beta",
"dev": "git_repo"
}
TYPE_TO_CHANNEL = {
"zip": "stable",
"zip_beta": "beta",
"dev": "git_repo"
}
class AppDeploy(BaseDeploy):
def __init__(self,
config: ConfigHelper,
cmd_helper: CommandHelper,
app_params: Optional[Dict[str, Any]]
) -> None:
super().__init__(config, cmd_helper)
self.config = config
self.app_params = app_params
self.debug = self.cmd_helper.is_debug_enabled()
if app_params is not None:
self.channel: str = app_params['channel']
self.path: pathlib.Path = pathlib.Path(
app_params['path']).expanduser().resolve()
executable: Optional[str] = app_params['executable']
self.type = CHANNEL_TO_TYPE[self.channel]
else:
self.type = config.get('type')
self.channel = TYPE_TO_CHANNEL[self.type]
self.path = pathlib.Path(
config.get('path')).expanduser().resolve()
executable = config.get('env', None)
if self.channel not in CHANNEL_TO_TYPE.keys():
raise config.error(
f"Invalid Channel '{self.channel}' for config "
f"section [{config.get_name()}]")
self._verify_path(config, 'path', self.path)
self.executable: Optional[pathlib.Path] = None
self.venv_args: Optional[str] = None
if executable is not None:
self.executable = pathlib.Path(executable).expanduser().resolve()
self._verify_path(config, 'env', self.executable)
self.venv_args = config.get('venv_args', None)
self.need_channel_update = False
self._is_valid = False
# 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.origin: str = config.get('origin')
self.primary_branch = config.get("primary_branch", "master")
self.npm_pkg_json: Optional[pathlib.Path] = None
if config.get("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()
def _verify_path(self,
config: ConfigHelper,
option: str,
file_path: pathlib.Path
) -> None:
if not file_path.exists():
raise config.error(
f"Invalid path for option `{option}` in section "
f"[{config.get_name()}]: Path `{file_path}` does not exist")
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
return self.path.samefile(app_path) and \
self.executable.samefile(executable)
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 self.name == "moonraker":
# Launch restart async so the request can return
# before the server restarts
IOLoop.current().call_later(
.1, self._do_restart) # type: ignore
else:
await self._do_restart()
async def _do_restart(self) -> None:
self.notify_status("Restarting Service...")
try:
await self.cmd_helper.run_cmd(
f"sudo systemctl restart {self.name}")
except Exception:
if self.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.debug,
'need_channel_update': self.need_channel_update,
'is_valid': self._is_valid,
'configured_type': self.type
}
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:
with ThreadPoolExecutor(max_workers=1) as tpe:
return await IOLoop.current().run_in_executor(
tpe, 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_virtualenv(self,
requirements: Union[pathlib.Path, List[str]]
) -> None:
if self.executable is None:
return
# Update python dependencies
bin_dir = self.executable.parent
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)
pip = bin_dir.joinpath("pip")
self.notify_status("Updating python packages...")
try:
# First attempt to update pip
await self.cmd_helper.run_cmd(
f"{pip} install -U pip", timeout=1200., notify=True,
retries=3)
await self.cmd_helper.run_cmd(
f"{pip} install {args}", timeout=1200., notify=True,
retries=3)
except Exception:
self.log_exc("Error updating python requirements")
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.joinpath("..").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,56 @@
# 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
from typing import TYPE_CHECKING, Dict, Any
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
) -> None:
name_parts = config.get_name().split()
self.name = name_parts[-1]
self.server = config.get_server()
self.cmd_helper = cmd_helper
if name_parts == 1:
self.prefix: str = ""
if config.get('type', "") == "web":
self.prefix = f"Web Client {self.name}: "
else:
self.prefix = f"Application {self.name}: "
async def refresh(self) -> None:
pass
async def update(self) -> bool:
return False
def get_update_status(self) -> Dict[str, Any]:
return {}
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)
@@ -0,0 +1,747 @@
# Git 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 asyncio
import os
import pathlib
import shutil
import re
import logging
from concurrent.futures import ThreadPoolExecutor
from tornado.ioloop import IOLoop
from .app_deploy import AppDeploy
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Tuple,
Optional,
Dict,
List,
)
if TYPE_CHECKING:
from confighelper import ConfigHelper
from components import database
from components import shell_command
from .update_manager import CommandHelper
DBComp = database.MoonrakerDatabase
class GitDeploy(AppDeploy):
def __init__(self,
config: ConfigHelper,
cmd_helper: CommandHelper,
app_params: Optional[Dict[str, Any]] = None
) -> None:
super().__init__(config, cmd_helper, app_params)
self.repo = GitRepo(cmd_helper, self.path, self.name, self.origin)
if self.type != 'git_repo':
self.need_channel_update = True
@staticmethod
async def from_application(app: AppDeploy) -> GitDeploy:
new_app = GitDeploy(app.config, app.cmd_helper, app.app_params)
await new_app.reinstall()
return new_app
async def refresh(self) -> None:
try:
await self._update_repo_state()
except Exception:
logging.exception("Error Refreshing git state")
async def _update_repo_state(self, need_fetch: bool = True) -> None:
self._is_valid = False
await self.repo.initialize(need_fetch=need_fetch)
self.log_info(
f"Channel: {self.channel}, "
f"Need Channel Update: {self.need_channel_update}"
)
invalids = self.repo.report_invalids(self.primary_branch)
if invalids:
msgs = '\n'.join(invalids)
self.log_info(
f"Repo validation checks failed:\n{msgs}")
if self.debug:
self._is_valid = True
self.log_info(
"Repo debug enabled, overriding validity checks")
else:
self.log_info("Updates on repo disabled")
else:
self._is_valid = True
self.log_info("Validity check for git repo passed")
async def update(self) -> bool:
await self.repo.wait_for_init()
if not self._is_valid:
raise self.log_exc("Update aborted, repo not valid", False)
if self.repo.is_dirty():
raise self.log_exc(
"Update aborted, repo has been modified", False)
if self.repo.is_current():
# No need to update
return False
self.cmd_helper.notify_update_response(
f"Updating Application {self.name}...")
inst_hash = await self._get_file_hash(self.install_script)
pyreqs_hash = await self._get_file_hash(self.python_reqs)
npm_hash = await self._get_file_hash(self.npm_pkg_json)
await self._pull_repo()
# Check Semantic Versions
await self._update_dependencies(inst_hash, pyreqs_hash, npm_hash)
# Refresh local repo state
await self._update_repo_state(need_fetch=False)
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:
self.notify_status("Attempting Repo Recovery...")
inst_hash = await self._get_file_hash(self.install_script)
pyreqs_hash = await self._get_file_hash(self.python_reqs)
npm_hash = await self._get_file_hash(self.npm_pkg_json)
if hard:
await self.repo.clone()
await self._update_repo_state()
else:
self.notify_status("Resetting Git Repo...")
await self.repo.reset()
await self._update_repo_state()
if self.repo.is_dirty() or not self._is_valid:
raise self.server.error(
"Recovery attempt failed, repo state not pristine", 500)
await self._update_dependencies(inst_hash, pyreqs_hash, npm_hash,
force=force_dep_update)
await self.restart_service()
self.notify_status("Reinstall Complete", is_complete=True)
async def reinstall(self):
await self.recover(True, True)
def get_update_status(self) -> Dict[str, Any]:
status = super().get_update_status()
status.update(self.repo.get_repo_status())
return status
async def _pull_repo(self) -> None:
self.notify_status("Updating Repo...")
try:
if self.repo.is_detached():
await self.repo.fetch()
await self.repo.checkout()
else:
await self.repo.pull()
except Exception:
raise self.log_exc("Error running 'git pull'")
async def _update_dependencies(self,
inst_hash: Optional[str],
pyreqs_hash: Optional[str],
npm_hash: Optional[str],
force: bool = False
) -> None:
ret = await self._check_need_update(inst_hash, self.install_script)
if force or ret:
package_list = await self._parse_install_script()
if package_list is not None:
await self._install_packages(package_list)
ret = await self._check_need_update(pyreqs_hash, self.python_reqs)
if force or ret:
if self.python_reqs is not None:
await self._update_virtualenv(self.python_reqs)
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")
async def _parse_install_script(self) -> Optional[List[str]]:
if self.install_script is None:
return None
# Open install file file and read
inst_path: pathlib.Path = self.install_script
if not inst_path.is_file():
self.log_info(f"Unable to open install script: {inst_path}")
return None
with ThreadPoolExecutor(max_workers=1) as tpe:
data = await IOLoop.current().run_in_executor(
tpe, inst_path.read_text)
packages: List[str] = re.findall(r'PKGLIST="(.*)"', data)
packages = [p.lstrip("${PKGLIST}").strip() for p in packages]
if not packages:
self.log_info(f"No packages found in script: {inst_path}")
return None
logging.debug(f"Repo {self.name}: Detected Packages: {repr(packages)}")
return packages
GIT_ASYNC_TIMEOUT = 300.
GIT_ENV_VARS = {
'GIT_HTTP_LOW_SPEED_LIMIT': "1000",
'GIT_HTTP_LOW_SPEED_TIME ': "20"
}
GIT_MAX_LOG_CNT = 100
GIT_LOG_FMT = \
"\"sha:%H%x1Dauthor:%an%x1Ddate:%ct%x1Dsubject:%s%x1Dmessage:%b%x1E\""
GIT_OBJ_ERR = "fatal: loose object"
class GitRepo:
def __init__(self,
cmd_helper: CommandHelper,
git_path: pathlib.Path,
alias: str,
origin_url: str
) -> None:
self.server = cmd_helper.get_server()
self.cmd_helper = cmd_helper
self.alias = alias
self.git_path = git_path
git_dir = git_path.parent
git_base = git_path.name
self.backup_path = git_dir.joinpath(f".{git_base}_repo_backup")
self.origin_url = origin_url
self.valid_git_repo: bool = False
self.git_owner: str = "?"
self.git_remote: str = "?"
self.git_branch: str = "?"
self.current_version: str = "?"
self.upstream_version: str = "?"
self.current_commit: str = "?"
self.upstream_commit: str = "?"
self.upstream_url: str = "?"
self.full_version_string: str = "?"
self.branches: List[str] = []
self.dirty: bool = False
self.head_detached: bool = False
self.git_messages: List[str] = []
self.commits_behind: List[Dict[str, Any]] = []
self.recovery_message = \
f"""
Manually restore via SSH with the following commands:
sudo service {self.alias} stop
cd {git_dir}
rm -rf {git_base}
git clone {self.origin_url}
sudo service {self.alias} start
"""
self.init_evt: Optional[asyncio.Event] = None
self.initialized: bool = False
self.git_operation_lock = asyncio.Lock()
self.fetch_timeout_handle: Optional[object] = None
self.fetch_input_recd: bool = False
async def initialize(self, need_fetch: bool = True) -> None:
if self.init_evt is not None:
# No need to initialize multiple requests
await self.init_evt.wait()
if self.initialized:
return
self.initialized = False
self.init_evt = asyncio.Event()
self.git_messages.clear()
try:
await self.update_repo_status()
self._verify_repo()
if not self.head_detached:
# lookup remote via git config
self.git_remote = await self.get_config_item(
f"branch.{self.git_branch}.remote")
# Populate list of current branches
blist = await self.list_branches()
self.branches = []
for branch in blist:
branch = branch.strip()
if branch[0] == "*":
branch = branch[2:]
if branch[0] == "(":
continue
self.branches.append(branch)
if need_fetch:
await self.fetch()
self.upstream_url = await self.remote(f"get-url {self.git_remote}")
self.current_commit = await self.rev_parse("HEAD")
self.upstream_commit = await self.rev_parse(
f"{self.git_remote}/{self.git_branch}")
current_version = await self.describe(
"--always --tags --long --dirty")
self.full_version_string = current_version.strip()
upstream_version = await self.describe(
f"{self.git_remote}/{self.git_branch} "
"--always --tags --long")
# Store current remote in the database if in a detached state
if self.head_detached:
mrdb: DBComp = self.server.lookup_component("database")
db_key = f"update_manager.git_repo_{self.alias}" \
".detached_remote"
mrdb.insert_item(
"moonraker", db_key,
[self.current_commit, self.git_remote, self.git_branch])
# Parse GitHub Owner from URL
owner_match = re.match(r"https?://[^/]+/([^/]+)", self.upstream_url)
self.git_owner = "?"
if owner_match is not None:
self.git_owner = owner_match.group(1)
self.dirty = current_version.endswith("dirty")
# Parse Version Info
versions = []
for ver in [current_version, upstream_version]:
tag_version = "?"
ver_match = re.match(r"v\d+\.\d+\.\d-\d+", ver)
if ver_match:
tag_version = ver_match.group()
versions.append(tag_version)
self.current_version, self.upstream_version = versions
# Get Commits Behind
self.commits_behind = []
cbh = await self.get_commits_behind()
if cbh:
tagged_commits = await self.get_tagged_commits()
debug_msg = '\n'.join([f"{k}: {v}" for k, v in
tagged_commits.items()])
logging.debug(f"Git Repo {self.alias}: Tagged Commits\n"
f"{debug_msg}")
for i, commit in enumerate(cbh):
tag = tagged_commits.get(commit['sha'], None)
if i < 30 or tag is not None:
commit['tag'] = tag
self.commits_behind.append(commit)
self.log_repo_info()
except Exception:
logging.exception(f"Git Repo {self.alias}: Initialization failure")
raise
else:
self.initialized = True
finally:
self.init_evt.set()
self.init_evt = None
async def wait_for_init(self) -> None:
if self.init_evt is not None:
await self.init_evt.wait()
if not self.initialized:
raise self.server.error(
f"Git Repo {self.alias}: Initialization failure")
async def update_repo_status(self) -> bool:
async with self.git_operation_lock:
if not self.git_path.joinpath(".git").is_dir():
logging.info(
f"Git Repo {self.alias}: path '{self.git_path}'"
" is not a valid git repo")
return False
await self._wait_for_lock_release()
self.valid_git_repo = False
retries = 3
while retries:
self.git_messages.clear()
try:
resp: Optional[str] = await self._run_git_cmd(
"status -u no", retries=1)
except Exception:
retries -= 1
resp = None
# Attempt to recover from "loose object" error
if retries and GIT_OBJ_ERR in "\n".join(self.git_messages):
ret = await self._repair_loose_objects()
if not ret:
# Since we are unable to recover, immediately
# return
return False
else:
break
if resp is None:
return False
resp = resp.strip().split('\n', 1)[0]
self.head_detached = resp.startswith("HEAD detached")
branch_info = resp.split()[-1]
if self.head_detached:
bparts = branch_info.split("/", 1)
if len(bparts) == 2:
self.git_remote, self.git_branch = bparts
else:
mrdb: DBComp = self.server.lookup_component("database")
db_key = f"update_manager.git_repo_{self.alias}" \
".detached_remote"
detached_remote: List[str] = mrdb.get_item(
"moonraker", db_key, ["", "?", "?"])
if detached_remote[0].startswith(branch_info):
self.git_remote = detached_remote[1]
self.git_branch = detached_remote[2]
msg = "Using remote stored in database:"\
f" {self.git_remote}/{self.git_branch}"
elif self.git_remote == "?":
msg = "Resolve by manually checking out" \
" a branch via SSH."
else:
msg = "Defaulting to previously tracked " \
f"{self.git_remote}/{self.git_branch}."
logging.info(
f"Git Repo {self.alias}: HEAD detached on untracked "
f"commit {branch_info}. {msg}")
else:
self.git_branch = branch_info
self.valid_git_repo = True
return True
def log_repo_info(self) -> None:
logging.info(
f"Git Repo {self.alias} Detected:\n"
f"Owner: {self.git_owner}\n"
f"Path: {self.git_path}\n"
f"Remote: {self.git_remote}\n"
f"Branch: {self.git_branch}\n"
f"Remote URL: {self.upstream_url}\n"
f"Current Commit SHA: {self.current_commit}\n"
f"Upstream Commit SHA: {self.upstream_commit}\n"
f"Current Version: {self.current_version}\n"
f"Upstream Version: {self.upstream_version}\n"
f"Is Dirty: {self.dirty}\n"
f"Is Detached: {self.head_detached}\n"
f"Commits Behind: {len(self.commits_behind)}")
def report_invalids(self, primary_branch: str) -> List[str]:
invalids: List[str] = []
upstream_url = self.upstream_url.lower()
if upstream_url[-4:] != ".git":
upstream_url += ".git"
if upstream_url != self.origin_url:
invalids.append(f"Unofficial remote url: {self.upstream_url}")
if self.git_branch != primary_branch or self.git_remote != "origin":
invalids.append(
"Repo not on valid remote branch, expected: "
f"origin/{primary_branch}, detected: "
f"{self.git_remote}/{self.git_branch}")
if self.head_detached:
invalids.append("Detached HEAD detected")
return invalids
def _verify_repo(self, check_remote: bool = False) -> None:
if not self.valid_git_repo:
raise self.server.error(
f"Git Repo {self.alias}: repo not initialized")
if check_remote:
if self.git_remote == "?":
raise self.server.error(
f"Git Repo {self.alias}: No valid git remote detected")
async def reset(self) -> None:
if self.git_remote == "?" or self.git_branch == "?":
raise self.server.error("Cannot reset, unknown remote/branch")
async with self.git_operation_lock:
await self._run_git_cmd("clean -d -f", retries=2)
await self._run_git_cmd(
f"reset --hard {self.git_remote}/{self.git_branch}",
retries=2)
async def fetch(self) -> None:
self._verify_repo(check_remote=True)
async with self.git_operation_lock:
await self._run_git_cmd_async(
f"fetch {self.git_remote} --prune --progress")
async def pull(self) -> None:
self._verify_repo()
if self.head_detached:
raise self.server.error(
f"Git Repo {self.alias}: Cannot perform pull on a "
"detached HEAD")
async with self.git_operation_lock:
await self._run_git_cmd_async("pull --progress")
async def list_branches(self) -> List[str]:
self._verify_repo()
async with self.git_operation_lock:
resp = await self._run_git_cmd("branch --list")
return resp.strip().split("\n")
async def remote(self, command: str) -> str:
self._verify_repo(check_remote=True)
async with self.git_operation_lock:
resp = await self._run_git_cmd(
f"remote {command}")
return resp.strip()
async def describe(self, args: str = "") -> str:
self._verify_repo()
async with self.git_operation_lock:
resp = await self._run_git_cmd(f"describe {args}".strip())
return resp.strip()
async def rev_parse(self, args: str = "") -> str:
self._verify_repo()
async with self.git_operation_lock:
resp = await self._run_git_cmd(f"rev-parse {args}".strip())
return resp.strip()
async def get_config_item(self, item: str) -> str:
self._verify_repo()
async with self.git_operation_lock:
resp = await self._run_git_cmd(f"config --get {item}")
return resp.strip()
async def checkout(self, branch: Optional[str] = None) -> None:
self._verify_repo()
async with self.git_operation_lock:
branch = branch or f"{self.git_remote}/{self.git_branch}"
await self._run_git_cmd(f"checkout {branch} -q")
async def run_fsck(self) -> None:
async with self.git_operation_lock:
await self._run_git_cmd("fsck --full", timeout=300., retries=1)
async def clone(self) -> None:
async with self.git_operation_lock:
self.cmd_helper.notify_update_response(
f"Git Repo {self.alias}: Starting Clone Recovery...")
if self.backup_path.exists():
shutil.rmtree(self.backup_path)
self._check_lock_file_exists(remove=True)
git_cmd = f"clone {self.origin_url} {self.backup_path}"
try:
await self._run_git_cmd_async(git_cmd, 1, False, False)
except Exception as e:
self.cmd_helper.notify_update_response(
f"Git Repo {self.alias}: Git Clone Failed")
raise self.server.error("Git Clone Error") from e
if self.git_path.exists():
shutil.rmtree(self.git_path)
shutil.move(str(self.backup_path), str(self.git_path))
self.cmd_helper.notify_update_response(
f"Git Repo {self.alias}: Git Clone Complete")
async def get_commits_behind(self) -> List[Dict[str, Any]]:
self._verify_repo()
if self.is_current():
return []
async with self.git_operation_lock:
branch = f"{self.git_remote}/{self.git_branch}"
resp = await self._run_git_cmd(
f"log {self.current_commit}..{branch} "
f"--format={GIT_LOG_FMT} --max-count={GIT_MAX_LOG_CNT}")
commits_behind: 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]
commits_behind.append(dict(cbh)) # type: ignore
return commits_behind
async def get_tagged_commits(self) -> Dict[str, Any]:
self._verify_repo()
async with self.git_operation_lock:
resp = await self._run_git_cmd(f"show-ref --tags -d")
tagged_commits: Dict[str, Any] = {}
tags = [tag.strip() for tag in resp.split('\n') if tag.strip()]
for tag in tags:
sha, ref = tag.split(' ', 1)
ref = ref.split('/')[-1]
if ref[-3:] == "^{}":
# Dereference this commit and overwrite any existing tag
ref = ref[:-3]
tagged_commits[ref] = sha
elif ref not in tagged_commits:
# This could be a lightweight tag pointing to a commit. If
# it is an annotated tag it will be overwritten by the
# dereferenced tag
tagged_commits[ref] = sha
# Return tagged commits as SHA keys mapped to tag values
return {v: k for k, v in tagged_commits.items()}
def get_repo_status(self) -> Dict[str, Any]:
return {
'detected_type': "git_repo",
'remote_alias': self.git_remote,
'branch': self.git_branch,
'owner': self.git_owner,
'version': self.current_version,
'remote_version': self.upstream_version,
'current_hash': self.current_commit,
'remote_hash': self.upstream_commit,
'is_dirty': self.dirty,
'detached': self.head_detached,
'commits_behind': self.commits_behind,
'git_messages': self.git_messages,
'full_version_string': self.full_version_string,
'pristine': not self.dirty
}
def get_version(self, upstream: bool = False) -> Tuple[Any, ...]:
version = self.upstream_version if upstream else self.current_version
return tuple(re.findall(r"\d+", version))
def is_detached(self) -> bool:
return self.head_detached
def is_dirty(self) -> bool:
return self.dirty
def is_current(self) -> bool:
return self.current_commit == self.upstream_commit
def _check_lock_file_exists(self, remove: bool = False) -> bool:
lock_path = self.git_path.joinpath(".git/index.lock")
if lock_path.is_file():
if remove:
logging.info(f"Git Repo {self.alias}: Git lock file found "
"after git process exited, removing")
try:
os.remove(lock_path)
except Exception:
pass
return True
return False
async def _wait_for_lock_release(self, timeout: int = 60) -> None:
while timeout:
if self._check_lock_file_exists():
if not timeout % 10:
logging.info(f"Git Repo {self.alias}: Git lock file "
f"exists, {timeout} seconds remaining "
"before removal.")
await asyncio.sleep(1.)
timeout -= 1
else:
return
self._check_lock_file_exists(remove=True)
async def _repair_loose_objects(self) -> bool:
try:
await self.cmd_helper.run_cmd_with_response(
"find .git/objects/ -type f -empty | xargs rm",
timeout=10., retries=1, cwd=str(self.git_path))
await self._run_git_cmd_async(
"fetch --all -p", retries=1, fix_loose=False)
await self._run_git_cmd("fsck --full", timeout=300., retries=1)
except Exception:
logging.exception("Attempt to repair loose objects failed")
return False
return True
async def _run_git_cmd_async(self,
cmd: str,
retries: int = 5,
need_git_path: bool = True,
fix_loose: bool = True
) -> None:
# Fetch and pull require special handling. If the request
# gets delayed we do not want to terminate it while the command
# is processing.
await self._wait_for_lock_release()
env = os.environ.copy()
env.update(GIT_ENV_VARS)
if need_git_path:
git_cmd = f"git -C {self.git_path} {cmd}"
else:
git_cmd = f"git {cmd}"
scmd = self.cmd_helper.build_shell_command(
git_cmd, callback=self._handle_process_output,
env=env)
while retries:
self.git_messages.clear()
ioloop = IOLoop.current()
self.fetch_input_recd = False
self.fetch_timeout_handle = ioloop.call_later(
GIT_ASYNC_TIMEOUT, self._check_process_active, # type: ignore
scmd, cmd)
try:
await scmd.run(timeout=0)
except Exception:
pass
ioloop.remove_timeout(self.fetch_timeout_handle)
ret = scmd.get_return_code()
if ret == 0:
self.git_messages.clear()
return
elif fix_loose:
if GIT_OBJ_ERR in "\n".join(self.git_messages):
ret = await self._repair_loose_objects()
if ret:
break
# since the attept to repair failed, bypass retries
# and immediately raise an exception
raise self.server.error(
f"Unable to repair loose objects, use hard recovery")
retries -= 1
await asyncio.sleep(.5)
self._check_lock_file_exists(remove=True)
raise self.server.error(f"Git Command '{cmd}' failed")
def _handle_process_output(self, output: bytes) -> None:
self.fetch_input_recd = True
out = output.decode().strip()
if out:
self.git_messages.append(out)
self.cmd_helper.notify_update_response(out)
logging.debug(
f"Git Repo {self.alias}: {out}")
async def _check_process_active(self,
scmd: shell_command.ShellCommand,
cmd_name: str
) -> None:
ret = scmd.get_return_code()
if ret is not None:
logging.debug(f"Git Repo {self.alias}: {cmd_name} returned")
return
if self.fetch_input_recd:
# Received some input, reschedule timeout
logging.debug(
f"Git Repo {self.alias}: {cmd_name} active, rescheduling")
ioloop = IOLoop.current()
self.fetch_input_recd = False
self.fetch_timeout_handle = ioloop.call_later(
GIT_ASYNC_TIMEOUT, self._check_process_active, # type: ignore
scmd, cmd_name)
else:
# Request has timed out with no input, terminate it
logging.debug(f"Git Repo {self.alias}: {cmd_name} timed out")
# Cancel with SIGKILL
await scmd.cancel(2)
async def _run_git_cmd(self,
git_args: str,
timeout: float = 20.,
retries: int = 5,
env: Optional[Dict[str, str]] = None
) -> str:
try:
return await self.cmd_helper.run_cmd_with_response(
f"git -C {self.git_path} {git_args}",
timeout=timeout, retries=retries, env=env, sig_idx=2)
except self.cmd_helper.scmd_error as e:
stdout = e.stdout.decode().strip()
stderr = e.stderr.decode().strip()
if stdout:
self.git_messages.append(stdout)
if stderr:
self.git_messages.append(stderr)
raise
@@ -1,20 +1,16 @@
# Supplemental configuration for Moonraker's Update Manager
# component. This file should not be modified.
[update_manager static debian moonraker]
[update_manager moonraker]
origin: https://github.com/arksine/moonraker.git
requirements: scripts/moonraker-requirements.txt
venv_args: -p python3
install_script: scripts/install-moonraker.sh
python_dist_path: /usr/lib/python3/dist-packages
env_package_path: lib/python*/site-packages
python_dist_packages:
gpiod
host_repo: arksine/moonraker
[update_manager static debian klipper]
[update_manager klipper]
origin: https://github.com/kevinoconnor/klipper.git
requirements: scripts/klippy-requirements.txt
venv_args: -p python2
install_script: scripts/install-octopi.sh
python_dist_path: /usr/lib/python2.7/dist-packages
env_package_path: lib/python*/site-packages
host_repo: arksine/moonraker
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,416 @@
# 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 asyncio
import os
import pathlib
import json
import shutil
import re
import time
import tempfile
import zipfile
from concurrent.futures import ThreadPoolExecutor
from tornado.ioloop import IOLoop
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,
app_params: Optional[Dict[str, Any]]
) -> None:
super().__init__(config, cmd_helper, app_params)
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.detected_type: str = "?"
self.source_checksum: str = ""
self.pristine = False
self.verified = False
self.build_date: int = 0
self.full_version: str = "?"
self.short_version: str = "?"
self.commit_hash: str = "?"
self.lastest_hash: str = "?"
self.latest_version: str = "?"
self.latest_checksum: str = "?"
self.latest_build_date: int = 0
self.commit_log: List[Dict[str, Any]] = []
self.package_list: List[str] = []
self.python_pkg_list: List[str] = []
self.release_download_info: Tuple[str, str, int] = ("?", "?", 0)
self.errors: List[str] = []
self.mutex: asyncio.Lock = asyncio.Lock()
self.refresh_event: Optional[asyncio.Event] = None
@staticmethod
async def from_application(app: AppDeploy) -> ZipDeploy:
new_app = ZipDeploy(app.config, app.cmd_helper, app.app_params)
await new_app.reinstall()
return new_app
async def _parse_info_file(self, file_name: str) -> Dict[str, Any]:
try:
info_file = self.path.joinpath(file_name)
with ThreadPoolExecutor(max_workers=1) as tpe:
info_bytes = await IOLoop.current().run_in_executor(
tpe, 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:
if self.refresh_event is not None:
await self.refresh_event.wait()
return
async with self.mutex:
self.refresh_event = asyncio.Event()
try:
await self._update_repo_state()
except Exception:
self.verified = False
self.log_exc("Error refreshing application state")
self.refresh_event.set()
self.refresh_event = None
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}")
self.detected_type = "?"
self.need_channel_update = False
if 'channel' in release_info:
local_channel = release_info['channel']
self.need_channel_update = self.channel != local_channel
self.detected_type = "zip"
if local_channel == "beta":
self.detected_type = "zip_beta"
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
with ThreadPoolExecutor(max_workers=1) as tpe:
res = await IOLoop.current().run_in_executor(
tpe, 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', []))
# Retreive 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.")
url = f"https://api.github.com/repos/{self.host_repo}/releases"
current_release, latest_release = await self._fetch_github_releases(
url, 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._log_zipapp_info()
async def _fetch_github_releases(self,
release_url: str,
current_tag: Optional[str] = None
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
try:
releases = await self.cmd_helper.github_api_request(release_url)
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 release['prerelease']:
if self.channel != "stable":
latest_release = release
elif self.channel == "stable":
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']
rinfo_bytes = await self.cmd_helper.http_download_request(
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']
rinfo_bytes = await self.cmd_helper.http_download_request(
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:
# No need to report the commit log when versions match
return
if "COMMIT_LOG" in asset_info:
asset_url, content_type, size = asset_info['COMMIT_LOG']
commit_bytes = await self.cmd_helper.http_download_request(
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_virtualenv(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:
async with self.mutex:
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...")
with tempfile.TemporaryDirectory(
suffix=self.name, prefix="app") as tempdirname:
tempdir = pathlib.Path(tempdirname)
temp_download_file = tempdir.joinpath(f"{self.name}.zip")
await self.cmd_helper.streaming_download_request(
dl_url, temp_download_file, content_type, size)
self.notify_status(
f"Download Complete, extracting release to '{self.path}'")
with ThreadPoolExecutor(max_workers=1) as tpe:
await IOLoop.current().run_in_executor(
tpe, self._extract_release, temp_download_file)
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:
async with self.mutex:
url = f"https://api.github.com/repos/{self.host_repo}/releases"
releases = await self._fetch_github_releases(url)
await self._process_latest_release(releases[1])
await self.update(force_dep_update=force_dep_update)
async def reinstall(self) -> None:
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': self.detected_type,
'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
+87 -40
View File
@@ -3,19 +3,43 @@
# 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 configparser
import os
import logging
from utils import SentinelClass
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Callable,
IO,
TypeVar,
Union,
Dict,
List,
)
if TYPE_CHECKING:
from moonraker import Server
_T = TypeVar("_T")
ConfigVal = Union[None, int, float, bool, str]
SENTINEL = SentinelClass.get_instance()
class ConfigError(Exception):
pass
class Sentinel:
pass
class ConfigHelper:
error = ConfigError
def __init__(self, server, config, section, orig_sects, parsed={}):
def __init__(self,
server: Server,
config: configparser.ConfigParser,
section: str,
orig_sects: List[str],
parsed: Dict[str, Dict[str, ConfigVal]] = {}
) -> None:
self.server = server
self.config = config
self.section = section
@@ -26,38 +50,42 @@ class ConfigHelper:
self.sections = config.sections
self.has_section = config.has_section
def get_server(self):
def get_server(self) -> Server:
return self.server
def __getitem__(self, key):
def __getitem__(self, key: str) -> ConfigHelper:
return self.getsection(key)
def __contains__(self, key):
def __contains__(self, key: str) -> bool:
return key in self.config
def get_name(self):
def get_name(self) -> str:
return self.section
def get_options(self):
def get_options(self) -> Dict[str, str]:
return dict(self.config[self.section])
def get_prefix_sections(self, prefix):
def get_prefix_sections(self, prefix: str) -> List[str]:
return [s for s in self.sections() if s.startswith(prefix)]
def getsection(self, section):
def getsection(self, section: str) -> ConfigHelper:
if section not in self.config:
raise ConfigError(f"No section [{section}] in config")
return ConfigHelper(self.server, self.config, section,
self.orig_sections, self.parsed)
def _get_option(self, func, option, default):
def _get_option(self,
func: Callable[..., Any],
option: str,
default: Union[SentinelClass, _T]
) -> _T:
try:
val = func(option, default)
except Exception:
raise ConfigError(
f"Error parsing option ({option}) from "
f"section [{self.section}]")
if val == Sentinel:
if isinstance(val, SentinelClass):
raise ConfigError(
f"No option found ({option}) in section [{self.section}]")
if self.section in self.orig_sections:
@@ -65,64 +93,87 @@ class ConfigHelper:
self.parsed[self.section][option] = val
return val
def get(self, option, default=Sentinel):
def get(self,
option: str,
default: Union[SentinelClass, _T] = SENTINEL
) -> Union[str, _T]:
return self._get_option(
self.config[self.section].get, option, default)
def getint(self, option, default=Sentinel):
def getint(self,
option: str,
default: Union[SentinelClass, _T] = SENTINEL
) -> Union[int, _T]:
return self._get_option(
self.config[self.section].getint, option, default)
def getboolean(self, option, default=Sentinel):
def getboolean(self,
option: str,
default: Union[SentinelClass, _T] = SENTINEL
) -> Union[bool, _T]:
return self._get_option(
self.config[self.section].getboolean, option, default)
def getfloat(self, option, default=Sentinel):
def getfloat(self,
option: str,
default: Union[SentinelClass, _T] = SENTINEL
) -> Union[float, _T]:
return self._get_option(
self.config[self.section].getfloat, option, default)
def read_supplemental_config(self, file_name):
def read_supplemental_config(self, file_name: str) -> ConfigHelper:
cfg_file_path = os.path.normpath(os.path.expanduser(file_name))
if not os.path.isfile(cfg_file_path):
raise ConfigError(
f"Configuration File Not Found: '{cfg_file_path}''")
try:
self.config.read(cfg_file_path)
sup_cfg = configparser.ConfigParser(interpolation=None)
sup_cfg.read(cfg_file_path)
except Exception:
raise ConfigError(f"Error Reading Config: '{cfg_file_path}'")
sections = sup_cfg.sections()
return ConfigHelper(self.server, sup_cfg, sections[0], sections)
def write_config(self, file_obj):
def write_config(self, file_obj: IO[str]) -> None:
self.config.write(file_obj)
def get_parsed_config(self):
def get_parsed_config(self) -> Dict[str, Dict[str, ConfigVal]]:
return dict(self.parsed)
def validate_config(self):
def validate_config(self) -> None:
for sect in self.orig_sections:
if sect not in self.parsed:
logging.warn(
f"Invalid config section [{sect}] detected. In "
"the future this will result in a startup error")
self.server.add_warning(
f"Unparsed config section [{sect}] detected. This "
"may be the result of a component that failed to "
"load. In the future this will result in a startup "
"error.")
continue
parsed_opts = self.parsed[sect]
for opt, val in self.config.items(sect):
if opt not in parsed_opts:
logging.warn(
f"Invalid option '{opt}' detected in section "
f"[{sect}]. In the future this will result in a "
"startup error.")
self.server.add_warning(
f"Invalid config option '{opt}' detected in section "
f"[{sect}]. Remove the option to resolve this issue. "
"In the future this will result in a startup error.")
def get_configuration(server, system_args):
cfg_file_path = os.path.normpath(os.path.expanduser(
system_args.configfile))
def get_configuration(server: Server,
app_args: Dict[str, Any]
) -> ConfigHelper:
cfg_file_path: str = os.path.normpath(os.path.expanduser(
app_args['config_file']))
if not os.path.isfile(cfg_file_path):
raise ConfigError(f"Configuration File Not Found: '{cfg_file_path}''")
raise ConfigError(
f"Configuration File Not Found: '{cfg_file_path}''")
if not os.access(cfg_file_path, os.R_OK | os.W_OK):
raise ConfigError(
"Moonraker does not have Read/Write permission for "
f"config file at path '{cfg_file_path}'")
config = configparser.ConfigParser(interpolation=None)
try:
config.read(cfg_file_path)
except Exception:
raise ConfigError(f"Error Reading Config: '{cfg_file_path}'") from None
except Exception as e:
raise ConfigError(f"Error Reading Config: '{cfg_file_path}'") from e
try:
server_cfg = config['server']
except KeyError:
@@ -134,8 +185,4 @@ def get_configuration(server, system_args):
except Exception:
pass
config['system_args'] = {
'configfile': system_args.configfile,
'logfile': system_args.logfile,
'software_version': system_args.software_version}
return ConfigHelper(server, config, 'server', orig_sections)
+206 -124
View File
@@ -4,6 +4,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 argparse
import sys
import importlib
@@ -22,7 +24,28 @@ from tornado.ioloop import IOLoop
from tornado.util import TimeoutError
from tornado.locks import Event
from app import MoonrakerApp
from utils import ServerError
from utils import ServerError, SentinelClass
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Optional,
Callable,
Coroutine,
Tuple,
Dict,
List,
Union,
TypeVar,
)
if TYPE_CHECKING:
from websockets import WebRequest, Subscribable
from components.data_store import DataStore
from components.klippy_apis import KlippyAPI
from components.file_manager.file_manager import FileManager
FlexCallback = Callable[..., Optional[Coroutine]]
_T = TypeVar("_T")
INIT_TIME = .25
LOG_ATTEMPT_INTERVAL = int(2. / INIT_TIME + .5)
@@ -32,13 +55,16 @@ CORE_COMPONENTS = [
'database', 'file_manager', 'klippy_apis', 'machine',
'data_store', 'shell_command', 'proc_stats']
class Sentinel:
pass
SENTINEL = SentinelClass.get_instance()
class Server:
error = ServerError
def __init__(self, args, file_logger):
def __init__(self,
args: Dict[str, Any],
file_logger: Optional[utils.MoonrakerLoggingHandler]
) -> None:
self.file_logger = file_logger
self.app_args = args
self.config = config = confighelper.get_configuration(self, args)
# log config file
strio = io.StringIO()
@@ -48,33 +74,37 @@ class Server:
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 = ""
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 = ""
# Event initialization
self.events = {}
self.events: Dict[str, List[FlexCallback]] = {}
# Klippy Connection Handling
self.klippy_address = config.get(
self.klippy_address: str = 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 = []
self.klippy_info: Dict[str, Any] = {}
self.init_list: List[str] = []
self.init_handle: Optional[object] = None
self.init_attempts: int = 0
self.klippy_state: str = "disconnected"
self.klippy_disconnect_evt: Optional[Event] = None
self.subscriptions: Dict[Subscribable, Dict[str, Any]] = {}
self.failed_components: List[str] = []
self.warnings: List[str] = []
# Server/IOLoop
self.server_running = False
self.server_running: bool = 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.get_websocket_manager = app.get_websocket_manager
self.register_api_transport = app.register_api_transport
self.ioloop = IOLoop.current()
self.register_endpoint(
@@ -93,9 +123,9 @@ class Server:
# 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.pending_requests: Dict[int, BaseRequest] = {}
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)
@@ -104,57 +134,60 @@ class Server:
need_klippy_reg=False)
# Component initialization
self.components = {}
self.components: Dict[str, Any] = {}
self._load_components(config)
self.klippy_apis = self.lookup_component('klippy_apis')
self.klippy_apis: KlippyAPI = self.lookup_component('klippy_apis')
config.validate_config()
def start(self):
def get_app_args(self) -> Dict[str, Any]:
return dict(self.app_args)
def start(self) -> None:
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.moonraker_app.listen(self.host, self.port, self.ssl_port)
self.server_running = True
self.ioloop.spawn_callback(self._init_signals)
self.ioloop.spawn_callback(self._connect_klippy)
def _init_signals(self):
def _init_signals(self) -> None:
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):
def add_log_rollover_item(self, name: str, item: str,
log: bool = True) -> None:
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)
def add_warning(self, warning: str, log: bool = True) -> None:
self.warnings.append(warning)
if log:
logging.warning(warning)
# ***** Component Management *****
def _load_components(self, config):
def _load_components(self, config: confighelper.ConfigHelper) -> None:
# 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', 'system_args'])
opt_sections = set([s.split()[0] for s in config.sections()])
opt_sections.remove('server')
for section in opt_sections:
self.load_component(config, section, None)
def load_component(self, config, component_name, default=Sentinel):
def load_component(self,
config: confighelper.ConfigHelper,
component_name: str,
default: Union[SentinelClass, _T] = SENTINEL
) -> Union[_T, Any]:
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"
@@ -169,32 +202,49 @@ class Server:
msg = f"Unable to load component: ({component_name})"
logging.exception(msg)
self.failed_components.append(component_name)
if default == Sentinel:
if isinstance(default, SentinelClass):
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):
def lookup_component(self,
component_name: str,
default: Union[SentinelClass, _T] = SENTINEL
) -> Union[_T, Any]:
component = self.components.get(component_name, default)
if component == Sentinel:
if isinstance(component, SentinelClass):
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()
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_notification(self,
event_name: str,
notify_name: Optional[str] = None
) -> None:
wsm = self.get_websocket_manager()
wsm.register_notification(event_name, notify_name)
def register_event_handler(self, event, callback):
def register_event_handler(self,
event: str,
callback: FlexCallback
) -> None:
self.events.setdefault(event, []).append(callback)
def send_event(self, event, *args):
def send_event(self, event: str, *args) -> None:
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):
def register_remote_method(self,
method_name: str,
cb: FlexCallback,
need_klippy_reg: bool = True
) -> None:
if method_name in self.remote_methods:
# XXX - may want to raise an exception here
logging.info(f"Remote method ({method_name}) already registered")
@@ -204,28 +254,28 @@ class Server:
# These methods need to be registered with Klippy
self.klippy_reg_methods.append(method_name)
def get_host_info(self):
def get_host_info(self) -> Tuple[str, int]:
hostname = socket.gethostname()
return hostname, self.port
def get_klippy_info(self):
def get_klippy_info(self) -> Dict[str, Any]:
return dict(self.klippy_info)
def get_klippy_state(self):
def get_klippy_state(self) -> str:
return self.klippy_state
# ***** Klippy Connection *****
async def _connect_klippy(self):
async def _connect_klippy(self) -> None:
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)
self.ioloop.call_later(.25, self._connect_klippy) # type: ignore
return
# begin server iniialization
self.ioloop.spawn_callback(self._initialize)
def process_command(self, cmd):
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
@@ -253,15 +303,15 @@ class Server:
result = ServerError(err, 400)
request.notify(result)
async def _execute_method(self, method_name, **kwargs):
async def _execute_method(self, method_name: str, **kwargs) -> None:
try:
ret = self.remote_methods[method_name](**kwargs)
if asyncio.iscoroutine(ret):
if ret is not None:
await ret
except Exception:
logging.exception(f"Error running remote method: {method_name}")
def on_connection_closed(self):
def on_connection_closed(self) -> None:
self.init_list = []
self.klippy_state = "disconnected"
for request in self.pending_requests.values():
@@ -273,11 +323,11 @@ class Server:
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)
self.ioloop.call_later(.25, self._connect_klippy) # type: ignore
if self.klippy_disconnect_evt is not None:
self.klippy_disconnect_evt.set()
async def _initialize(self):
async def _initialize(self) -> None:
if not self.server_running:
return
await self._check_ready()
@@ -311,18 +361,19 @@ class Server:
else:
self.init_attempts += 1
self.init_handle = self.ioloop.call_later(
INIT_TIME, self._initialize)
INIT_TIME, self._initialize) # type: ignore
async def _request_endpoints(self):
async def _request_endpoints(self) -> None:
result = await self.klippy_apis.list_endpoints(default=None)
if result is None:
return
endpoints = result.get('endpoints', {})
endpoints = result.get('endpoints', [])
for ep in endpoints:
self.moonraker_app.register_remote_handler(ep)
async def _check_ready(self):
async def _check_ready(self) -> None:
send_id = "identified" not in self.init_list
result: Dict[str, Any]
try:
result = await self.klippy_apis.get_klippy_info(send_id)
except ServerError as e:
@@ -354,7 +405,7 @@ class Server:
msg = result.get('state_message', "Klippy Not Ready")
logging.info("\n" + msg)
async def _verify_klippy_requirements(self):
async def _verify_klippy_requirements(self) -> None:
result = await self.klippy_apis.get_object_list(default=None)
if result is None:
logging.info(
@@ -370,58 +421,64 @@ class Server:
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(
query_res = await self.klippy_apis.query_objects(
{'configfile': None}, default=None)
if result is None:
if query_res is None:
logging.info(f"Unable to set SD Card path")
else:
config = result.get('configfile', {}).get('config', {})
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 = self.lookup_component('file_manager')
file_manager: FileManager = 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):
def _process_gcode_response(self, response: str) -> None:
self.send_event("server:gcode_response", response)
def _process_status_update(self, eventtime, status):
def _process_status_update(self,
eventtime: float,
status: Dict[str, Any]
) -> None:
if 'webhooks' in status:
# XXX - process other states (startup, ready, error, etc)?
state = status['webhooks'].get('state', None)
state: Optional[str] = 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 = {}
conn_status: Dict[str, Any] = {}
for name, fields in sub.items():
if name in status:
val = status[name]
val: Dict[str, Any] = 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)
conn.send_status(conn_status, eventtime)
async def make_request(self, web_request):
async def make_request(self, web_request: WebRequest) -> Any:
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: DataStore = 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):
async def _request_subscripton(self,
web_request: WebRequest
) -> Dict[str, Any]:
args = web_request.get_args()
conn = web_request.get_connection()
@@ -432,7 +489,7 @@ class Server:
raise self.error(
"No connection associated with subscription request")
self.subscriptions[conn] = sub
all_subs = {}
all_subs: Dict[str, Any] = {}
# request superset of all client subscriptions
for sub in self.subscriptions.values():
for obj, items in sub.items():
@@ -465,7 +522,7 @@ class Server:
result['status'] = pruned_status
return result
async def _request_standard(self, web_request):
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
@@ -475,27 +532,36 @@ class Server:
self.klippy_connection.send_request, base_request)
return await base_request.wait()
def remove_subscription(self, conn):
def remove_subscription(self, conn: Subscribable) -> None:
self.subscriptions.pop(conn, None)
def _handle_term_signal(self):
def _handle_term_signal(self) -> None:
logging.info(f"Exiting with signal SIGTERM")
self.ioloop.spawn_callback(self._stop_server, "terminate")
async def _stop_server(self, exit_reason="restart"):
async def _stop_server(self, exit_reason: str = "restart") -> None:
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)
# 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 asyncio.iscoroutine(ret):
if ret is not None:
await ret
except Exception:
logging.exception(
f"Error executing '{method}()' for component: {name}")
f"Error executing 'on_exit()' for component: {name}")
# 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")
# Disconnect from Klippy
try:
if self.klippy_connection.is_connected():
self.klippy_disconnect_evt = Event()
@@ -505,24 +571,33 @@ class Server:
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")
# Close all components
for name, component in self.components.items():
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}")
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):
async def _handle_server_restart(self, web_request: WebRequest) -> str:
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)
async def _handle_info_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
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()
@@ -533,21 +608,28 @@ class Server:
'failed_components': self.failed_components,
'plugins': list(self.components.keys()),
'failed_plugins': self.failed_components,
'registered_directories': reg_dirs}
'registered_directories': reg_dirs,
'warnings': self.warnings
}
async def _handle_config_request(self, web_request):
async def _handle_config_request(self,
web_request: WebRequest
) -> Dict[str, Any]:
return {
'config': self.config.get_parsed_config()
}
class KlippyConnection:
def __init__(self, on_recd, on_close):
def __init__(self,
on_recd: Callable[[dict], None],
on_close: Callable[[], None]
) -> None:
self.ioloop = IOLoop.current()
self.iostream = None
self.iostream: Optional[iostream.IOStream] = None
self.on_recd = on_recd
self.on_close = on_close
async def connect(self, address):
async def connect(self, address: str) -> bool:
ksock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
kstream = iostream.IOStream(ksock)
try:
@@ -560,7 +642,7 @@ class KlippyConnection:
self.ioloop.spawn_callback(self._read_stream, self.iostream)
return True
async def _read_stream(self, stream):
async def _read_stream(self, stream: iostream.IOStream) -> None:
while not stream.closed():
try:
data = await stream.read_until(b'\x03')
@@ -576,7 +658,7 @@ class KlippyConnection:
logging.exception(
f"Error processing Klippy Host Response: {data.decode()}")
async def send_request(self, request):
async def send_request(self, request: BaseRequest) -> None:
if self.iostream is None:
request.notify(ServerError("Klippy Host not connected", 503))
return
@@ -586,24 +668,24 @@ class KlippyConnection:
except iostream.StreamClosedError:
request.notify(ServerError("Klippy Host not connected", 503))
def is_connected(self):
def is_connected(self) -> bool:
return self.iostream is not None and not self.iostream.closed()
def close(self):
def close(self) -> None:
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):
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 = Event()
self.response = None
self.response: Any = None
async def wait(self):
async def wait(self) -> Any:
# Log pending requests every 60 seconds
start_time = time.time()
while True:
@@ -622,15 +704,15 @@ class BaseRequest:
raise self.response
return self.response
def notify(self, response):
def notify(self, response: Any) -> None:
self.response = response
self._event.set()
def to_dict(self):
def to_dict(self) -> Dict[str, Any]:
return {'id': self.id, 'method': self.rpc_method,
'params': self.params}
def main():
def main() -> None:
# Parse start arguments
parser = argparse.ArgumentParser(
description="Moonraker - Klipper API Server")
@@ -644,18 +726,18 @@ def main():
parser.add_argument(
"-n", "--nologfile", action='store_true',
help="disable logging to a file")
system_args = parser.parse_args()
cmd_line_args = parser.parse_args()
app_args = {'config_file': cmd_line_args.configfile}
# Setup Logging
version = utils.get_software_version()
if system_args.nologfile:
log_file = ""
if cmd_line_args.nologfile:
app_args['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)
app_args['log_file'] = os.path.normpath(
os.path.expanduser(cmd_line_args.logfile))
app_args['software_version'] = version
ql, file_logger = utils.setup_logging(app_args)
if sys.version_info < (3, 7):
msg = f"Moonraker requires Python 3.7 or above. " \
@@ -670,7 +752,7 @@ def main():
estatus = 0
while True:
try:
server = Server(system_args, file_logger)
server = Server(app_args, file_logger)
except Exception:
logging.exception("Moonraker Error")
estatus = 1
+108 -33
View File
@@ -3,19 +3,46 @@
# 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 logging.handlers
import os
import pathlib
import sys
import subprocess
import asyncio
import hashlib
import json
from queue import SimpleQueue as Queue
# Annotation imports
from typing import (
List,
Optional,
ClassVar,
Tuple,
Dict,
Any,
)
MOONRAKER_PATH = os.path.join(os.path.dirname(__file__), '..')
class ServerError(Exception):
def __init__(self, message, status_code=400):
def __init__(self, message: str, status_code: int = 400) -> None:
Exception.__init__(self, message)
self.status_code = status_code
class SentinelClass:
_instance: ClassVar[Optional[SentinelClass]] = None
@staticmethod
def get_instance() -> SentinelClass:
if SentinelClass._instance is None:
SentinelClass._instance = SentinelClass()
return SentinelClass._instance
# Coroutine friendly QueueHandler courtesy of Martjin Pieters:
# https://www.zopatista.com/python/2019/05/11/asyncio-logging/
class LocalQueueHandler(logging.handlers.QueueHandler):
@@ -30,54 +57,61 @@ class LocalQueueHandler(logging.handlers.QueueHandler):
# 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}",
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, item):
def set_rollover_info(self, name: str, item: str) -> None:
self.rollover_info[name] = item
def doRollover(self):
super(MoonrakerLoggingHandler, self).doRollover()
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")
# 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__), '..')
def retreive_git_version(source_path: str) -> str:
# Obtain version info from "git" program
prog = ('git', '-C', moonraker_path, 'describe', '--always',
prog = ('git', '-C', source_path, 'describe', '--always',
'--tags', '--long', '--dirty')
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
ver, err = process.communicate()
retcode = process.wait()
if retcode == 0:
return ver.strip().decode()
raise Exception(f"Failed to retreive git version: {err.decode()}")
def get_software_version() -> str:
version = "?"
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")
version = retreive_git_version(MOONRAKER_PATH)
except Exception:
vfile = pathlib.Path(os.path.join(
MOONRAKER_PATH, "moonraker/.version"))
if vfile.exists():
try:
version = vfile.read_text().strip()
except Exception:
logging.exception("Unable to extract version from file")
version = "?"
return version
return "?"
def setup_logging(log_file, software_version):
def setup_logging(app_args: Dict[str, Any]
) -> Tuple[logging.handlers.QueueListener,
Optional[MoonrakerLoggingHandler]]:
root_logger = logging.getLogger()
queue = Queue()
queue: Queue = Queue()
queue_handler = LocalQueueHandler(queue)
root_logger.addHandler(queue_handler)
root_logger.setLevel(logging.INFO)
@@ -85,10 +119,12 @@ def setup_logging(log_file, software_version):
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}")
file_hdlr = None
if log_file:
if app_args.get('log_file', ""):
file_hdlr = MoonrakerLoggingHandler(
software_version, log_file, when='midnight', backupCount=2)
app_args, when='midnight', backupCount=2)
formatter = logging.Formatter(
'%(asctime)s [%(filename)s:%(funcName)s()] - %(message)s')
file_hdlr.setFormatter(formatter)
@@ -99,3 +135,42 @@ def setup_logging(log_file, software_version):
queue, stdout_hdlr)
listener.start()
return listener, file_hdlr
def hash_directory(dir_path: str,
ignore_exts: List[str],
ignore_dirs: List[str]
) -> str:
checksum = hashlib.blake2s()
if not os.path.exists(dir_path):
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: str = MOONRAKER_PATH) -> Optional[Tuple[str, bool]]:
rfile = pathlib.Path(os.path.join(path, ".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
+262 -132
View File
@@ -4,126 +4,195 @@
#
# This file may be distributed under the terms of the GNU GPLv3 license
from __future__ import annotations
import logging
import ipaddress
import tornado
import json
import tornado.util
from tornado.ioloop import IOLoop
from tornado.websocket import WebSocketHandler, WebSocketClosedError
from utils import ServerError
from tornado.locks import Event
from utils import ServerError, SentinelClass
class Sentinel:
pass
# Annotation imports
from typing import (
TYPE_CHECKING,
Any,
Optional,
Callable,
Coroutine,
Type,
TypeVar,
Union,
Dict,
List,
)
if TYPE_CHECKING:
from moonraker import Server
from app import APIDefinition, MoonrakerApp
import components.authorization
_T = TypeVar("_T")
_C = TypeVar("_C", str, bool, float, int)
IPUnion = Union[ipaddress.IPv4Address, ipaddress.IPv6Address]
ConvType = Union[str, bool, float, int]
ArgVal = Union[None, int, float, bool, str]
RPCCallback = Callable[..., Coroutine]
AuthComp = Optional[components.authorization.Authorization]
SENTINEL = SentinelClass.get_instance()
class Subscribable:
def send_status(self,
status: Dict[str, Any],
eventtime: float
) -> None:
raise NotImplementedError
class WebRequest:
def __init__(self, endpoint, args, action="",
conn=None, ip_addr="", user=None):
def __init__(self,
endpoint: str,
args: Dict[str, Any],
action: Optional[str] = "",
conn: Optional[Subscribable] = None,
ip_addr: str = "",
user: Optional[Dict[str, Any]] = None
) -> None:
self.endpoint = endpoint
self.action = action
self.action = action or ""
self.args = args
self.conn = conn
self.ip_addr: Optional[IPUnion] = None
try:
self.ip_addr = ipaddress.ip_address(ip_addr)
except Exception:
self.ip_addr = None
self.current_user = user
def get_endpoint(self):
def get_endpoint(self) -> str:
return self.endpoint
def get_action(self):
def get_action(self) -> str:
return self.action
def get_args(self):
def get_args(self) -> Dict[str, Any]:
return self.args
def get_connection(self):
def get_connection(self) -> Optional[Subscribable]:
return self.conn
def get_ip_address(self):
def get_ip_address(self) -> Optional[IPUnion]:
return self.ip_addr
def get_current_user(self):
def get_current_user(self) -> Optional[Dict[str, Any]]:
return self.current_user
def _get_converted_arg(self, key, default=Sentinel, dtype=str):
def _get_converted_arg(self,
key: str,
default: Union[SentinelClass, _T],
dtype: Type[_C]
) -> Union[_C, _T]:
if key not in self.args:
if default == Sentinel:
if isinstance(default, SentinelClass):
raise ServerError(f"No data for argument: {key}")
return default
val = self.args[key]
try:
if dtype != bool:
if dtype is not bool:
return dtype(val)
else:
if isinstance(val, str):
val = val.lower()
if val in ["true", "false"]:
return True if val == "true" else False
return True if val == "true" else False # type: ignore
elif isinstance(val, bool):
return val
return val # type: ignore
raise TypeError
except Exception:
raise ServerError(
f"Unable to convert argument [{key}] to {dtype}: "
f"value recieved: {val}")
def get(self, key, default=Sentinel):
def get(self,
key: str,
default: Union[SentinelClass, _T] = SENTINEL
) -> Union[_T, Any]:
val = self.args.get(key, default)
if val == Sentinel:
if isinstance(val, SentinelClass):
raise ServerError(f"No data for argument: {key}")
return val
def get_str(self, key, default=Sentinel):
return self._get_converted_arg(key, default)
def get_str(self,
key: str,
default: Union[SentinelClass, _T] = SENTINEL
) -> Union[str, _T]:
return self._get_converted_arg(key, default, str)
def get_int(self, key, default=Sentinel):
def get_int(self,
key: str,
default: Union[SentinelClass, _T] = SENTINEL
) -> Union[int, _T]:
return self._get_converted_arg(key, default, int)
def get_float(self, key, default=Sentinel):
def get_float(self,
key: str,
default: Union[SentinelClass, _T] = SENTINEL
) -> Union[float, _T]:
return self._get_converted_arg(key, default, float)
def get_boolean(self, key, default=Sentinel):
def get_boolean(self,
key: str,
default: Union[SentinelClass, _T] = SENTINEL
) -> Union[bool, _T]:
return self._get_converted_arg(key, default, bool)
class JsonRPC:
def __init__(self):
self.methods = {}
def __init__(self, transport: str = "Websocket") -> None:
self.methods: Dict[str, RPCCallback] = {}
self.transport = transport
def register_method(self, name, method):
def register_method(self,
name: str,
method: RPCCallback
) -> None:
self.methods[name] = method
def remove_method(self, name):
def remove_method(self, name: str) -> None:
self.methods.pop(name, None)
async def dispatch(self, data, ws):
response = None
async def dispatch(self,
data: str,
conn: Optional[WebSocket] = None
) -> Optional[str]:
response: Any = None
try:
request = json.loads(data)
request: Union[Dict[str, Any], List[dict]] = json.loads(data)
except Exception:
msg = f"Websocket data not json: {data}"
msg = f"{self.transport} data not json: {data}"
logging.exception(msg)
response = self.build_error(-32700, "Parse error")
return json.dumps(response)
logging.debug("Websocket Request::" + data)
logging.debug(f"{self.transport} Request::{data}")
if isinstance(request, list):
response = []
for req in request:
resp = await self.process_request(req, ws)
resp = await self.process_request(req, conn)
if resp is not None:
response.append(resp)
if not response:
response = None
else:
response = await self.process_request(request, ws)
response = await self.process_request(request, conn)
if response is not None:
response = json.dumps(response)
logging.debug("Websocket Response::" + response)
logging.debug(f"{self.transport} Response::{response}")
return response
async def process_request(self, request, ws):
req_id = request.get('id', None)
rpc_version = request.get('jsonrpc', "")
async def process_request(self,
request: Dict[str, Any],
conn: Optional[WebSocket]
) -> Optional[Dict[str, Any]]:
req_id: Optional[int] = request.get('id', None)
rpc_version: str = request.get('jsonrpc', "")
method_name = request.get('method', None)
if rpc_version != "2.0" or not isinstance(method_name, str):
return self.build_error(-32600, "Invalid Request", req_id)
@@ -134,19 +203,28 @@ class JsonRPC:
params = request['params']
if isinstance(params, list):
response = await self.execute_method(
method, req_id, ws, *params)
method, req_id, conn, *params)
elif isinstance(params, dict):
response = await self.execute_method(
method, req_id, ws, **params)
method, req_id, conn, **params)
else:
return self.build_error(-32600, "Invalid Request", req_id)
else:
response = await self.execute_method(method, req_id, ws)
response = await self.execute_method(method, req_id, conn)
return response
async def execute_method(self, method, req_id, ws, *args, **kwargs):
async def execute_method(self,
method: RPCCallback,
req_id: Optional[int],
conn: Optional[WebSocket],
*args,
**kwargs
) -> Optional[Dict[str, Any]]:
try:
result = await method(ws, *args, **kwargs)
if conn is not None:
result = await method(conn, *args, **kwargs)
else:
result = await method(*args, **kwargs)
except TypeError as e:
return self.build_error(
-32603, f"Invalid params:\n{e}", req_id, True)
@@ -160,14 +238,19 @@ class JsonRPC:
else:
return self.build_result(result, req_id)
def build_result(self, result, req_id):
def build_result(self, result: Any, req_id: int) -> Dict[str, Any]:
return {
'jsonrpc': "2.0",
'result': result,
'id': req_id
}
def build_error(self, code, msg, req_id=None, is_exc=False):
def build_error(self,
code: int,
msg: str,
req_id: Optional[int] = None,
is_exc: bool = False
) -> Dict[str, Any]:
log_msg = f"JSON-RPC Request Error: {code}\n{msg}"
if is_exc:
logging.exception(log_msg)
@@ -179,147 +262,194 @@ class JsonRPC:
'id': req_id
}
class WebsocketManager:
def __init__(self, server):
class APITransport:
def register_api_handler(self, api_def: APIDefinition) -> None:
raise NotImplementedError
def remove_api_handler(self, api_def: APIDefinition) -> None:
raise NotImplementedError
class WebsocketManager(APITransport):
def __init__(self, server: Server) -> None:
self.server = server
self.websockets = {}
self.ws_lock = tornado.locks.Lock()
self.websockets: Dict[int, WebSocket] = {}
self.rpc = JsonRPC()
self.closed_event: Optional[Event] = None
self.rpc.register_method("server.websocket.id", self._handle_id_request)
def register_notification(self, event_name, notify_name=None):
def register_notification(self,
event_name: str,
notify_name: Optional[str] = None
) -> None:
if notify_name is None:
notify_name = event_name.split(':')[-1]
async def notify_handler(*args):
await self.notify_websockets(notify_name, *args)
def notify_handler(*args):
self.notify_websockets(notify_name, *args)
self.server.register_event_handler(
event_name, notify_handler)
def register_local_handler(self, api_def, callback):
for ws_method, req_method in \
zip(api_def.ws_methods, api_def.request_methods):
rpc_cb = self._generate_local_callback(
api_def.endpoint, req_method, callback)
def register_api_handler(self, api_def: APIDefinition) -> None:
if api_def.callback is None:
# Remote API, uses RPC to reach out to Klippy
ws_method = api_def.jrpc_methods[0]
rpc_cb = self._generate_callback(api_def.endpoint)
self.rpc.register_method(ws_method, rpc_cb)
else:
# Local API, uses local callback
for ws_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.rpc.register_method(ws_method, rpc_cb)
logging.info(
"Registering Websocket JSON-RPC methods: "
f"{', '.join(api_def.jrpc_methods)}")
def register_remote_handler(self, api_def):
ws_method = api_def.ws_methods[0]
rpc_cb = self._generate_callback(api_def.endpoint)
self.rpc.register_method(ws_method, rpc_cb)
def remove_api_handler(self, api_def: APIDefinition) -> None:
for jrpc_method in api_def.jrpc_methods:
self.rpc.remove_method(jrpc_method)
def remove_handler(self, ws_method):
self.rpc.remove_method(ws_method)
def _generate_callback(self, endpoint):
async def func(ws, **kwargs):
def _generate_callback(self, endpoint: str) -> RPCCallback:
async def func(ws: WebSocket, **kwargs) -> Any:
result = await self.server.make_request(
WebRequest(endpoint, kwargs, conn=ws, ip_addr=ws.ip_addr,
user=ws.current_user))
return result
return func
def _generate_local_callback(self, endpoint, request_method, callback):
async def func(ws, **kwargs):
def _generate_local_callback(self,
endpoint: str,
request_method: str,
callback: Callable[[WebRequest], Coroutine]
) -> RPCCallback:
async def func(ws: WebSocket, **kwargs) -> Any:
result = await callback(
WebRequest(endpoint, kwargs, request_method, ws,
ip_addr=ws.ip_addr, user=ws.current_user))
return result
return func
async def _handle_id_request(self, ws, **kwargs):
async def _handle_id_request(self,
ws: WebSocket,
**kwargs
) -> Dict[str, int]:
return {'websocket_id': ws.uid}
def has_websocket(self, ws_id):
def has_websocket(self, ws_id: int) -> bool:
return ws_id in self.websockets
def get_websocket(self, ws_id):
def get_websocket(self, ws_id: int) -> Optional[WebSocket]:
return self.websockets.get(ws_id, None)
async def add_websocket(self, ws):
async with self.ws_lock:
self.websockets[ws.uid] = ws
logging.info(f"New Websocket Added: {ws.uid}")
def add_websocket(self, ws: WebSocket) -> None:
self.websockets[ws.uid] = ws
logging.info(f"New Websocket Added: {ws.uid}")
async def remove_websocket(self, ws):
async with self.ws_lock:
old_ws = self.websockets.pop(ws.uid, None)
if old_ws is not None:
self.server.remove_subscription(old_ws)
logging.info(f"Websocket Removed: {ws.uid}")
def remove_websocket(self, ws: WebSocket) -> None:
old_ws = self.websockets.pop(ws.uid, None)
if old_ws is not None:
self.server.remove_subscription(old_ws)
logging.info(f"Websocket Removed: {ws.uid}")
if self.closed_event is not None and not self.websockets:
self.closed_event.set()
async def notify_websockets(self, name, data=Sentinel):
msg = {'jsonrpc': "2.0", 'method': "notify_" + name}
if data != Sentinel:
def notify_websockets(self,
name: str,
data: Any = SENTINEL
) -> None:
msg: Dict[str, Any] = {'jsonrpc': "2.0", 'method': "notify_" + name}
if data != SENTINEL:
msg['params'] = [data]
async with self.ws_lock:
for ws in list(self.websockets.values()):
try:
ws.write_message(msg)
except WebSocketClosedError:
self.websockets.pop(ws.uid, None)
self.server.remove_subscription(ws)
logging.info(f"Websocket Removed: {ws.uid}")
except Exception:
logging.exception(
f"Error sending data over websocket: {ws.uid}")
for ws in list(self.websockets.values()):
ws.queue_message(msg)
async def close(self):
async with self.ws_lock:
for ws in list(self.websockets.values()):
ws.close()
self.websockets = {}
async def close(self) -> None:
if not self.websockets:
return
self.closed_event = Event()
for ws in list(self.websockets.values()):
ws.close()
try:
await self.closed_event.wait(IOLoop.current().time() + 2.)
except tornado.util.TimeoutError:
pass
self.closed_event = None
class WebSocket(WebSocketHandler):
def initialize(self):
app = self.settings['parent']
class WebSocket(WebSocketHandler, Subscribable):
def initialize(self) -> None:
app: MoonrakerApp = self.settings['parent']
self.server = app.get_server()
self.wsm = app.get_websocket_manager()
self.rpc = self.wsm.rpc
self.uid = id(self)
self.is_closed = False
self.ip_addr = self.request.remote_ip
self.is_closed: bool = False
self.ip_addr: str = self.request.remote_ip
self.queue_busy: bool = False
self.message_buf: List[Union[str, Dict[str, Any]]] = []
async def open(self):
await self.wsm.add_websocket(self)
def open(self, *args, **kwargs) -> None:
self.set_nodelay(True)
self.wsm.add_websocket(self)
def on_message(self, message):
def on_message(self, message: Union[bytes, str]) -> None:
io_loop = IOLoop.current()
io_loop.spawn_callback(self._process_message, message)
async def _process_message(self, message):
async def _process_message(self, message: str) -> None:
try:
response = await self.rpc.dispatch(message, self)
if response is not None:
self.write_message(response)
self.queue_message(response)
except Exception:
logging.exception("Websocket Command Error")
def send_status(self, status):
if not status or self.is_closed:
def queue_message(self, message: Union[str, Dict[str, Any]]):
self.message_buf.append(message)
if self.queue_busy:
return
try:
self.write_message({
'jsonrpc': "2.0",
'method': "notify_status_update",
'params': [status]})
except WebSocketClosedError:
self.is_closed = True
logging.info(
f"Websocket Closed During Status Update: {self.uid}")
except Exception:
logging.exception(
f"Error sending data over websocket: {self.uid}")
self.queue_busy = True
IOLoop.current().spawn_callback(self._process_messages)
def on_close(self):
async def _process_messages(self):
if self.is_closed:
self.message_buf = []
self.queue_busy = False
return
while self.message_buf:
msg = self.message_buf.pop(0)
try:
await self.write_message(msg)
except WebSocketClosedError:
self.is_closed = True
logging.info(
f"Websocket closed while writing: {self.uid}")
break
except Exception:
logging.exception(
f"Error sending data over websocket: {self.uid}")
self.queue_busy = False
def send_status(self,
status: Dict[str, Any],
eventtime: float
) -> None:
if not status:
return
self.queue_message({
'jsonrpc': "2.0",
'method': "notify_status_update",
'params': [status, eventtime]})
def on_close(self) -> None:
self.is_closed = True
io_loop = IOLoop.current()
io_loop.spawn_callback(self.wsm.remove_websocket, self)
self.message_buf = []
self.wsm.remove_websocket(self)
def check_origin(self, origin):
def check_origin(self, origin: str) -> bool:
if not super(WebSocket, self).check_origin(origin):
auth = self.server.lookup_component('authorization', None)
auth: AuthComp = self.server.lookup_component('authorization', None)
if auth is not None:
return auth.check_cors(origin)
return False
@@ -327,6 +457,6 @@ class WebSocket(WebSocketHandler):
# Check Authorized User
def prepare(self):
auth = self.server.lookup_component('authorization', None)
auth: AuthComp = self.server.lookup_component('authorization', None)
if auth is not None:
self.current_user = auth.check_authorized(self.request)
+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, retreive_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': "kevinoconnor/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 = retreive_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()
+9 -5
View File
@@ -7,6 +7,7 @@ SYSTEMDDIR="/etc/systemd/system"
REBUILD_ENV="n"
FORCE_DEFAULTS="n"
CONFIG_PATH="${HOME}/moonraker.conf"
LOG_PATH="/tmp/moonraker.log"
# Step 1: Verify Klipper has been installed
check_klipper()
@@ -36,7 +37,7 @@ cleanup_legacy() {
install_packages()
{
PKGLIST="python3-virtualenv python3-dev nginx libopenjp2-7 python3-libgpiod"
PKGLIST="${PKGLIST} liblmdb0 rsync zlib1g-dev"
PKGLIST="${PKGLIST} liblmdb0 libsodium-dev zlib1g-dev"
# Update system package info
report_status "Running apt-get update..."
@@ -60,7 +61,6 @@ 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
fi
# Install/update dependencies
@@ -77,7 +77,7 @@ install_script()
sudo /bin/sh -c "cat > ${SERVICE_FILE}" << EOF
#Systemd service file for moonraker
[Unit]
Description=Starts Moonraker on startup
Description=API Server for Klipper
After=network.target
[Install]
@@ -87,12 +87,14 @@ WantedBy=multi-user.target
Type=simple
User=$USER
RemainAfterExit=yes
ExecStart=${PYTHONDIR}/bin/python ${SRCDIR}/moonraker/moonraker.py -c ${CONFIG_PATH}
WorkingDirectory=${SRCDIR}
ExecStart=${LAUNCH_CMD} -c ${CONFIG_PATH} -l ${LOG_PATH}
Restart=always
RestartSec=10
EOF
# Use systemctl to enable the klipper systemd service script
sudo systemctl enable moonraker.service
sudo systemctl daemon-reload
}
@@ -124,13 +126,15 @@ set -e
# Find SRCDIR from the pathname of this script
SRCDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )"/.. && pwd )"
LAUNCH_CMD="${PYTHONDIR}/bin/python ${SRCDIR}/moonraker/moonraker.py"
# Parse command line arguments
while getopts "rfc:" arg; do
while getopts "rfc:l:" arg; do
case $arg in
r) REBUILD_ENV="y";;
f) FORCE_DEFAULTS="y";;
c) CONFIG_PATH=$OPTARG;;
l) LOG_PATH=$OPTARG;;
esac
done
+6 -2
View File
@@ -1,6 +1,10 @@
# Python dependencies for Moonraker
tornado==6.1.0
pyserial==3.4
pillow==8.1.2
lmdb==1.2.0
pillow==8.2.0
lmdb==1.2.1
streaming-form-data==1.8.1
distro==1.5.0
inotify-simple==1.3.5
libnacl==1.7.2
paho-mqtt==1.5.1
-2
View File
@@ -1,2 +0,0 @@
env_version=0.2.6
deps_version=0.4.1
+22 -1
View File
@@ -3,7 +3,8 @@
<head>
<link rel="stylesheet" href="dist/themes/default/style.min.css"/>
<link rel="stylesheet" href="css/login_dialog.css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="//cdn.jsdelivr.net/npm/sha256-uint8array/dist/sha256-uint8array.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="dist/jstree.min.js"></script>
<script src="dist/jquery.leanModal.min.js"></script>
<script src="/js/main.js?v=0.1.3" type="module"></script>
@@ -107,6 +108,26 @@ Progress: <progress id="progressbar" value="0" max="100"></progress>
</div>
</div>
<a id="do_deleteuser" rel="leanModal" name="deleteuser" href="#deleteuser" hidden>Hidden Delete</a>
<div id="deleteuser" class="user">
<div id="login-ct">
<div id="deleteuser-header" class="user-header">
<h2>Delete User</h2>
<button id="deleteuser_close" class="modal_close"></a>
</div>
<form id="deleteuser_form" class="user-form">
<div class="text-field">
<label for="deleteuser_username">Username</label>
<input id="deleteuser_username" class="good_input" name="deleteuser_username" type="text" />
</div>
<div class="button-field">
<button type="submit" class="user-button">Submit</button>
</div>
</form>
</div>
</div>
<a id="do_signup" rel="leanModal" name="signup" href="#signup" hidden>Hidden Signup</a>
<div id="signup" class="user">
<div id="signup-ct">
+72 -17
View File
@@ -7,7 +7,7 @@
import JsonRPC from "./json-rpc.js?v=0.1.2";
var origin = location.origin;
var ws_url = (window.location.protocol == "https" ? "wss://" : "ws://")
var ws_url = (window.location.protocol == "https:" ? "wss://" : "ws://")
+ location.host;
// API Definitions
@@ -300,6 +300,29 @@ function process_mesh(result) {
console.log("Processed Mesh Coordinates:");
console.log(coordinates);
}
async function calculate_checksum(file) {
let done_promise = new Promise((resolve, reject) => {
let reader = file.stream().getReader();
let hash = SHA256.createHash();
reader.read().then(function read_file({done, value}) {
if (done) {
resolve(hash.digest("hex"));
return;
}
hash.update(value);
return reader.read().then(read_file)
});
})
let checksum = await done_promise;
if (checksum == null) {
console.log("Unable to calculate checksum for file")
return null;
} else {
console.log(`Calculated Checksum: ${checksum}`)
return checksum;
}
}
//***********End UI Update Functions****************/
//***********Websocket-Klipper API Functions (JSON-RPC)************/
@@ -775,7 +798,7 @@ function handle_file_list_changed(file_info) {
// Update the jstree based on the action and info
let parent_node = parse_node_path(file_info.item.root, file_info.item.path);
$("#filelist").jstree('refresh_node', parent_node);
if (file_info.action == "move_item") {
if (file_info.action.startsWith("move_")) {
let src_parent_node = parse_node_path(
file_info.source_item.root, file_info.source_item.path)
if (src_parent_node != parent_node)
@@ -791,6 +814,18 @@ function handle_metadata_update(metadata) {
}
json_rpc.register_method("notify_metadata_update", handle_metadata_update);
function handle_cpu_throttled(tdata) {
console.log("CPU Throttled");
console.log(tdata);
}
json_rpc.register_method("notify_cpu_throttled", handle_cpu_throttled);
function handle_proc_stat_update(proc_stats) {
// TODO: Display Temp
return;
}
json_rpc.register_method("notify_proc_stat_update", handle_proc_stat_update);
//***********End Klipper Event Handlers (JSON-RPC)*****************/
//*****************Websocket Batch GCode Tests*********************/
@@ -1335,20 +1370,17 @@ function logout_jwt_user() {
});
}
function delete_jwt_user(pass) {
if (!pass) {
alert("Invalid Password, Cannot Delete User");
return;
}
if (auth_token == null) {
console.log("No User Logged In")
function delete_jwt_user(user) {
if (!user) {
alert("Invalid username or password, Cannot Delete User");
return;
}
let settings = {
method: 'DELETE',
url: origin + api.user.url,
contentType: "application/json",
data: JSON.stringify({password: pass}),
data: JSON.stringify({username: user}),
dataType: 'json',
headers: {
"Authorization": `Bearer ${auth_token}`
@@ -1357,16 +1389,15 @@ function delete_jwt_user(pass) {
let res = resp.result;
console.log("Delete User Response:");
console.log(res);
auth_token = null;
refresh_token = null;
window.localStorage.removeItem('refresh_token');
$('.req-login').prop('disabled', true);
$("#deleteuser_close").click()
}
}
$.ajax(settings)
.fail(() => {
console.log("Delete User Failed");
$("#deleteuser_close").click()
window.alert("Unable to delete user!")
});
}
@@ -1701,7 +1732,7 @@ window.onload = () => {
});
// Uploads a selected file to the server
$('#upload-file').change(() => {
$('#upload-file').change(async () => {
update_progress(0, 100);
let file = $('#upload-file').prop('files')[0];
let dir = get_selected_item("dir");
@@ -1712,6 +1743,8 @@ window.onload = () => {
let root = dir[0];
let directory = dir.slice(1).join("/");
console.log("Sending Upload Request...");
// First, calculate the file checksum
let chksum = await calculate_checksum(file);
// It might not be a bad idea to validate that this is
// a gcode file here, and reject and other files.
@@ -1723,6 +1756,8 @@ window.onload = () => {
fdata.append("file", file);
fdata.append("root", root);
fdata.append("path", directory);
if (chksum != null)
fdata.append("checksum", chksum);
let settings = {
url: origin + api.upload.url,
data: fdata,
@@ -1934,8 +1969,7 @@ window.onload = () => {
});
$('#btndeluser').click(() => {
let password = window.prompt("Verify your password:")
delete_jwt_user(password);
$("#do_deleteuser").click()
});
$('#btnchangepass').click(() => {
@@ -1972,6 +2006,13 @@ window.onload = () => {
closeButton: "#changepass_close"
});
$("#do_deleteuser").leanModal({
top : 200,
overlay : 0.4,
closeButton: "#deleteuser_close"
});
$("#login_close").click(() => {
//$("#login_username").val("");
$("#login_password").val("");
@@ -1992,6 +2033,11 @@ window.onload = () => {
$("#nav_home").click();
});
$("#deleteuser_close").click(() => {
$("#deleteuser_username").val("");
$("#nav_home").click();
});
$("#login_form").submit((evt)=> {
let user = $("#login_username").val()
let pass = $("#login_password").val()
@@ -2024,5 +2070,14 @@ window.onload = () => {
return false;
});
$("#deleteuser_form").submit((evt)=> {
let user = $("#deleteuser_username").val()
if (user != "")
delete_jwt_user(user);
else
alert("Invalid username/password");
return false;
});
check_authorization();
};