125 Commits
Author SHA1 Message Date
Arksine 4de33bae4a scripts: update dependency version to 0.4.1
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-05 13:00:10 -05:00
Arksine 316fac1e75 docs: update default for max_upload_size
We now default 1024 MiB.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-05 12:59:42 -05:00
Arksine d057795bee scripts: add streaming-form-data dependency
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-05 12:52:01 -05:00
Arksine 4efce1b868 file_manager: extract UFP files to disk rather than memory
The prior implementations assumed that uploaded files would be buffered in memory.
This is no longer the case, so UFP extraction is more efficient when done straight to disk.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-05 12:07:13 -05:00
Arksine db13827a48 shell_command: only log stderr if output was returned
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-05 12:07:13 -05:00
Arksine 4c914d7b4d file_manager: add support for streaming file uploads
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-05 12:07:13 -05:00
Arksine f1edaa1f61 app: add support for streaming file uploads
This should reduce issues with large file uploads.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-05 05:25:28 -05:00
th33xitus a111733431 docs: fix incorrect wording. 'mainsail' should correctly read 'moonraker'
Signed-off-by:  Dominik Willner <th33xitus@gmail.com>
2021-03-05 05:17:00 -05:00
Arksine c8a2aa7a6c confighelper: don't warn on valid sections without options
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-04 21:15:30 -05:00
Arksine 84f663e2bc docs: update user_changes with octoprint_compat requirement
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-04 20:59:27 -05:00
Grigi 6ba45f6e35 docs: Document simulated Octoprint API
Signed-off-by:  Nickolas Grigoriadis <nagrigoriadis@gmail.com>
2021-03-04 20:52:55 -05:00
Grigi 39ab419c1f octoprint_compat: Compatibility with Cura Octoprint plugin to upload UFP files.
This PR is a minimal implementation of the Octoprint REST API that is required
for Cura to be able to establish a connection and  send gcode/UFP files to
moonraker without errors.
Currently it only supports the "global apikey authentication" method.

Signed-off-by:  Nickolas Grigoriadis <nagrigoriadis@gmail.com>
2021-03-04 20:52:55 -05:00
Евгений Непомнящий 228ed34eb1 docs: add git_repo path example
Signed-off-by: Eugene Rush <rush.zlo@gmail.com>
2021-03-04 20:43:05 -05:00
Евгений Непомнящий 0fa3c14f51 update_manager: expand user on path
Signed-off-by: Eugene Rush <rush.zlo@gmail.com>
2021-03-04 20:41:48 -05:00
Arksine 46680f4cda docs: add documentation for new machine APIs
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-04 08:52:49 -05:00
Arksine e32c14b1a7 machine: add service "stop" and "start" endpoints
This allows clients to toggle specific services on/off.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-04 08:45:31 -05:00
Arksine 1f9d896e17 update_manager: attempt client archive download before removing old client files
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-04 08:45:31 -05:00
Arksine d9edcd9396 shell_command: Add "quiet" argument to run_with_response
This reduces logging when "run_with_response" is called from a loop or a timer.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-04 08:45:31 -05:00
Arksine 22a5f6720c shell_command: reset internal proc state in "run_with_response"
This sets a clean state should a shell command be run more than once.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-04 08:45:31 -05:00
Arksine cea9af1ef8 proc_stats: moonraker process tracking
Track Moonraker CPU Usage, Rss Memory Usage, and Raspberry Pi Throttled State.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-04 08:45:31 -05:00
Arksine 63c685e1c4 database: return 404 when a key or namespace is not found
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-03 19:23:18 -05:00
Arksine 84f46b1cb1 app: fix issue with json Content-Type checks
Allow the Content-Type header to specify a "charset" by only validating the start of the string.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-03 19:13:20 -05:00
Arksine d1dfa86081 docs: fix typos in last web_api update
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-01 15:53:35 -05:00
Arksine dbf5f93919 docs: add more detail to the API overview in web_api.md
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-01 15:49:52 -05:00
Arksine d878340a7a app: refactor the dynamic request handlers
Unify the Local and Remote request handlers into a single handler.  This reduces duplicated code.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-03-01 11:50:09 -05:00
Arksine fb24917f1a app: expand support for HTTP arguments
Request arguments may now be parsed from the path, body, and query string.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-02-28 19:45:11 -05:00
Arksine 62324650e5 update_manager: improve the git owner regex
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-28 17:51:12 -05:00
Arksine bf48744048 update_manager: report "owner" in update status
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 20:36:12 -05:00
Arksine 6c994f6c9c machine: add webcamd to the list of allowed services
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 20:05:22 -05:00
Arksine bb3eb27b3d scripts: bump dependency version to 0.4.0
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 17:29:09 -05:00
Arksine 94b690c2e9 docs: add database documentation
Also add documentation for query string type hints.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 17:29:09 -05:00
Arksine aa4c13742e app: add support for query string type hints
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 17:29:09 -05:00
Arksine 900345e2d9 scripts: add lmdb dependencies
Signed-off-by:  Eric Callahan arksine.code@gmail.com
2021-02-27 17:29:09 -05:00
Arksine ec85b31a62 paneldue: exit send loop when serial port is disconnected
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 12:55:48 -05:00
Arksine ab6ed40bcb websockets: minor fixes
When a websocket is closed, set "is_closed" to True in the on_closed handler.   When closing all websockets, iterate through a list of values.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 12:55:48 -05:00
Arksine 87e136003f file_manager: save metadata to the database
This allows gcode file metadata to persist through restarts, reducing the time spent parsing.  The gcode file path also persists, so it is available even when Klippy is not.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 12:55:48 -05:00
Arksine 7ff54d8f2f file_manager: use "run_with_response" to extract metadata
Enable logging to stderr so that it is not necessary to extract logged data from the command.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 12:55:18 -05:00
Arksine 9e41d9d84b extract_metadata: write log output to stderr
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 12:55:18 -05:00
Arksine 75dce0af1a shell_command: refactor using asyncio
At times a subprocess created by shell command fails.  Attempt to mitigate this by using asyncio's version of subprocess, which should be more stable when running via the event loop.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 12:55:18 -05:00
Arksine 4abfb886f5 moonraker: don't explictly load klippy_apis in init
Instead, look up klippy_apis after all plugins are loaded.  This allows the "CORE_PLUGINS" list to determine the exact order in which core plugins are loaded.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 12:55:18 -05:00
Arksine 979aef2903 websockets: explicitly log JSON-RPC errors
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 12:55:18 -05:00
Arksine 958a0f3270 moonraker: add handler for SIGTERM
This performs a graceful shutdown when SIGTERM is received.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 12:55:18 -05:00
Arksine 54b1bd8b04 database: initial implementation
This provides an lmdb database which can be used to keep persistent data.   This can be used by internal plugins or by clients.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-27 12:54:59 -05:00
Arksine 1f61357dd6 update_manager: register websocket notifications
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-17 08:33:00 -05:00
Arksine b89aa77bc9 power: register websocket notification
Change event prefix from "gpio_power" to "power".

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-17 08:33:00 -05:00
Arksine 537ba281ab file_manager: register websocket notifications
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-17 08:33:00 -05:00
Arksine 83c24ff765 moonraker: register notifications via the websocket's "register_notification" method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-17 08:27:59 -05:00
Arksine b726747261 websockets: implement "register_notification" method
Rather than require developers to add new notification handlers to websockets.py directly, implement a method that may be called to register websocket notifications during init.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-17 08:27:59 -05:00
Arksine eb37ce767d docs: add documentation for "/server/config" endpoint
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-16 11:43:31 -05:00
Arksine 60ba8ff1d5 moonraker: validate parsed configuration options after plugins are loaded
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-16 06:38:23 -05:00
Arksine 45557b8260 confighelper: add method to validate configuration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-16 06:38:23 -05:00
Arksine f229c3ec2c moonraker: add "GET /server/config" endpoint
Clients may call this method to retrieve moonraker's current configuration in json format.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-16 06:35:01 -05:00
Arksine 0e22a0cfe8 confighelper: track parsed configuration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-16 06:35:00 -05:00
Arksine f2135d7483 websockets: improve closed websocket handling
When a closed websocket is detected set a flag to prevent further status updates until the websocket is removed.

Also make sure that the associated subscriptions are removed if a closed websocket is detected during a notification.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-15 11:26:54 -05:00
Arksine baf97f8ea4 docs: document new "data_store" options.
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-14 17:50:45 -05:00
Arksine 29b89fb87d data_store: make the temperature and gcode store sizes configurable
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-14 17:46:05 -05:00
Arksine ec7936ee97 confighelper: fix bug that ignores enable_debug_logging option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-11 15:14:40 -05:00
Arksine ceaa4911bb scripts: revert the "remove_sudo_fix" addition
This causes the uninstallation script to fail if the user has not applied the patch.  It should be removed in a separate script.

Signed-off-by:  Eric Callahan <arksine.colde@gmail.com>
2021-02-08 06:48:19 -05:00
Arksine f9dcda7ba9 scripts: update uninstallation script
Remove the LSB or systemd service, depending on which is installed.

SIgned-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-08 06:45:01 -05:00
zellneralex 0fcae5b6e4 power: add Shelly device support
Signed-off-by: Alex Zellner <alexander.zellner@googlemali.com>
2021-02-07 07:31:04 -05:00
Arksine dd81beab47 extract_metadata: add support for metadata thumbnail extraction in Cura
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-02-06 08:39:41 -05:00
Arksine 9648630392 file_manager: process ufp files found when refreshing a directory
This allows users to manaully place ufp files in the gcode directory.  Resolves #81.

Signed-off-by:  Eric Callahan  <arskine.code@gmail.com>
2021-01-31 12:33:50 -05:00
Arksine fe2cec1087 update_manager: use glob pattern matching to find site package folder
This allows for python version flexibility.  Resolves #76.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-31 12:33:33 -05:00
Arksine 81104a6618 docs: update documentation for latest changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com
2021-01-31 07:41:16 -05:00
Arksine 980912270e data_store: store fan speed for temperature fans
Refactor the the temperature store to only store fields available to a sensor.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-01-31 06:52:42 -05:00
Arksine 39334d1098 update_manager: add "persistent_files" option to web clients
This allows clients to define files that will persist through an update, useful if the client has some sort of static configuration.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-31 06:52:42 -05:00
Arksine 943b78195b power: fix incorrect indentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-28 07:36:21 -05:00
Arksine 49c5583e95 machine: fix typo in service restart handler
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-28 07:35:33 -05:00
Arksine e8776a5d85 docs: fix incorrect wording for 'klipper_restart_when_powered'
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-27 07:12:19 -05:00
Arksine 9c385ce067 docs: document 'restart_klipper_when_powered' option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-27 06:58:27 -05:00
Arksine 9e240c3b86 power: add "klipper_restart_method" option
When this option is set Mooraker will restart Klipper after the device has been powered on.  An additional "restart_delay" option has been added to customize the delay in which the restart is executed.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-27 06:58:27 -05:00
Arksine c365de32cf machine: add "restart_service" method
Move the service restart functionality out of the "service restart" request into its own method.  This allows the "service restart" to be called internally by other modules.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-27 06:22:15 -05:00
Arksine aa9bf0fb9c docs: document the enable_auto_refresh option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-26 18:05:06 -05:00
Arksine ddc7405249 update_manager: resolve initialization issues
Fix issue where apt-get update is called on startup.  This should only be done by the "auto updater" or by a specific request to refresh.

Always set an Updater's init event to true when refresh() is called, regardless of the result.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-26 17:47:10 -05:00
Arksine 25b3911d3d confighelper: fix bug in "getfloat" method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-22 17:18:28 -05:00
Arksine 19bc2bfbb8 update_manager: make auto refresh optional
Decrease the frequency of auto updates roughly every 24 hours.  The manager will attempt to update once between 12am and 4am.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-22 17:18:28 -05:00
Arksine 578ce740c5 docs: update API documentation for changes to update_manager
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-22 17:18:28 -05:00
Arksine 6a88df095e scripts: modify update_manger.conf for new configuration
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-22 17:18:28 -05:00
Jordan Ruthe c17d86aa09 docs: update configuration to reflect multiple update clients
Signed-off-by: Jordan Ruthe <jordan.ruthe@gmail.com>
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-01-22 17:18:28 -05:00
Arksine 0ad97fd9eb update_manager: extract and verify configurable git repo options
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-22 17:18:28 -05:00
Jordan Ruthe f3ae6da635 update_manager: Allow for multiple client entries
Signed-off-by: Jordan Ruthe <jordan.ruthe@gmail.com>
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-01-22 17:18:28 -05:00
Arksine e9ab5fb480 power: add missing call to super() for Tasmota devices
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-22 17:16:51 -05:00
Arksine 21d1726bfd power: report device name in error when "locked while printing"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-22 11:20:36 -05:00
Jordan Ruthe 0b3b8cede8 power: Raise error if trying to change a locked device during printing
Signed-off-by: Jordan Ruthe <jordan.ruthe@gmail.com>
2021-01-22 11:00:31 -05:00
Jordan Ruthe 00db209d5d power: Add 'locked_while_printing' to device list
Signed-off-by: Jordan Ruthe <jordan.ruthe@gmail.com>
2021-01-22 11:00:31 -05:00
Jordan Ruthe b4602115d7 power: add "locked_while_printing" option to avoid accidental shutdown
Signed-off-by: Jordan Ruthe <jordan.ruthe@gmail.com>
2021-01-22 11:00:31 -05:00
Arksine ff8e53b269 moonraker: return list of registered directors in server.info response
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-20 10:21:27 -05:00
Arksine e2c325a724 extract_metadata: support first layer height expressed as a percentage
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-16 12:46:56 -05:00
Arksine a1f2228473 extract_metadata: add shebang to script
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-01-16 12:38:54 -05:00
Arksine d70bd8d2e0 data_store: add support for storing gcode commands
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-12 14:56:37 -05:00
Bryan Mayland 8c365c62cb data_store: Add heater PWM value to /server/temperature_store
Signed-off-by: Bryan Mayland <bmayland@capnbry.net>
2021-01-12 11:36:19 -05:00
Volodymyr Babchynskyy 6f4a72fe2e Readme: added link to Klipper
Signed-off-by: Volodymyr Babchynskyy <vvchik@gmail.com>
2021-01-09 05:46:28 -05:00
Arksine bdd270fa4a update_manager: wrap calls to http.fetch in "gen.with_timeout"
This is a workaround for an issue where the http client fails to propogate an exception back to the caller, hanging the update process.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-07 20:27:23 -05:00
Arksine d194ce00ab update_manager: send notification response upon update error
Attach "is_complete" to the response so clients know that the transaction is done, even though it resulted in an error.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-06 19:42:40 -05:00
Arksine 5f986ab770 power: refactor initialization
The entire configuration should be validated prior to device initialization.  In the event of an error, the GPIO Chip factory must be closed.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-06 14:39:33 -05:00
Arksine e0f4b46364 update_manager: refactor initialization
We need to be sure that the entire update_manager is correctly configured prior to queueing the callbacks for the initial refresh.   Rather than have each updater spawn a "refesh" callback, move them all into a single init method spawned after the module has been fully configured.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-06 14:14:12 -05:00
Arksine fb3706c54f paneldue: configure the serial connection last
This allows the PanelDue object to be properly cleaned in the event of a configuration error.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-06 14:00:29 -05:00
Arksine d1388080c4 moonraker: don't crash the server if an optional plugin fails to import
The server can still operate and be used to fetch the logs if a plugin fails to load.  Add a 'failed_plugins' field to the /server/info response so clients can notify users that this plugin failed to load.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-06 12:32:26 -05:00
Arksine f1a75117db confighelper: add config file path to systemargs
Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2021-01-06 12:05:10 -05:00
Arksine 4ae63dbbf8 moonraker: log config file at startup
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-06 12:05:10 -05:00
Arksine 30637011e6 utils: add method for setting rollover info
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-06 12:05:09 -05:00
Arksine 8a18fa6c2f confighelper: Add method to write config to a file object
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-06 09:09:29 -05:00
Arksine 4cd97d61f9 file_manager: remove unnecessary call to get_file_list() in get_file_metadata()
If the metadata doesnt exist simply return an empty dict.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-06 07:49:47 -05:00
Arksine 40f876192c file_manager: check for new metadata on each call to _list_directory
Previously this check was only on done when a directory was requested by the API.  Moving this check to _list_directory ()updates metadata for internal calls as well.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-06 07:19:37 -05:00
Arksine fa53d889d0 file_mananager: Use absolute paths instead of normalized paths
This prevents potential issues where relative paths may be compared to absolute paths.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-05 12:09:52 -05:00
Arksine 6fcb26ddd7 file_manager: skip broken symlinks in list directory
This resolves an issue where an exception is raised when path info is requested.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-05 11:27:46 -05:00
Arksine 67adcfc448 docs: note update_manager API changes
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-04 08:51:41 -05:00
Arksine 0c280122fb websockets: Add "update_refreshed" notification
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-04 08:18:11 -05:00
Arksine 5b9f637c2d update_manager: Implement auto refresh
The slower system package update will now only executed by the auto-refresh routine.  Moonraker will check for updates roughly every 2 hours, however system packages updates will only occur between 1am and 4am local time.

If a print is in progress any attempt to refresh or update will be aborted.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-04 08:18:10 -05:00
Arksine 2bb9128b5b docs: document the "off_when_shutdown" option for the power plugin
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-02 19:53:41 -05:00
Arksine 222f0c4695 power: introduce "off_when_shutdown" device option
This allows devices to power down when a Klippy shutdown is detected.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-02 19:42:04 -05:00
Arksine ea1ad0277d update_manager: use a lock to prevent concurrent update and refresh requests
This should reduce the load on low perfomance devices.  This also makes it possible to queue update requests.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-02 14:58:38 -05:00
Arksine 1e81297624 update_manager: resolve potential rentry issues
Calls to "refresh" should not be allowed to occur while a client a current refresh is in progress.  Updates will wait for a pending refresh to complete before beginning the update procedure.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-02 09:11:41 -05:00
Arksine ae3661b100 app: Force register moonraker and klippy log endpoints
It is possible for the log files to be registered after a rollover,  which can result in the file not existing.  Force the log endpoints to register, bypassing the existance check.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-02 06:45:04 -05:00
Arksine 67f5b32d84 file_manager: Increase extract_metadata timeout to 10 seconds
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-02 06:23:17 -05:00
Arksine 14b5384572 update_manager: retry failed "run_with_response" commands
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-01 20:52:46 -05:00
Arksine c261ee51f3 shell_command: Add retries to "run_with_response" method
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-01 20:52:46 -05:00
Arksine 67f992dabd file_manager: add disk usage to directory listing
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-01 17:06:33 -05:00
Arksine a535e6e94a paneldue: Improve file name parsing
Previously file names containing whitespace were not parsed correctly.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-01 12:46:31 -05:00
Arksine 4aa2a86e3b docs: Document "notify_klippy_shutdown"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-01 11:51:52 -05:00
Arksine 7d738c7a8b websockets: add "klippy_shutdown" notification
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-01 11:48:31 -05:00
Arksine f753263c60 docs: document the "-n" command line option
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-01 11:47:03 -05:00
Arksine 2f8a1567a8 moonraker: add --nologfile (-n) option to the command line
This allows moonraker to run without generating a log file.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2021-01-01 11:28:34 -05:00
Arksine 933622adda docs: Note changes to the file manager path restrictions
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-31 20:23:48 -05:00
Arksine 1814a11a8d file_manager: remove restriction that file paths must be in HOME
Instead make sure that the supplied path is not the system root and check that moonraker has the appropriate privileges to access the directory.

Also track visited directories when retreiving a full file list to prevent infinite recursion.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2020-12-31 19:36:55 -05:00
27 changed files with 2972 additions and 731 deletions

No files matched your search

+3 -3
View File
@@ -1,7 +1,7 @@
# Moonraker - API Web Server for Klipper
Moonraker is a Python 3 based web server that exposes APIs with which
client applications may use to interact with Klipper. Communcation between
client applications may use to interact with [Klipper](https://github.com/KevinOConnor/klipper). Communcation between
the Klippy host and Moonraker is done over a Unix Domain Socket. Tornado
is used to provide Moonraker's server functionality.
@@ -18,7 +18,7 @@ to see if any action is necessary on their part. The date of the most
recent change is included.
Users:\
[user_changes.md](/docs/user_changes.md) - December 6th 2020
[user_changes.md](/docs/user_changes.md) - March 4th 2021
Developers:\
[api_changes.md](/docs/api_changes.md) - November 28th 2020
[api_changes.md](/docs/api_changes.md) - January 31st 2021
+37
View File
@@ -1,4 +1,41 @@
This document keeps a record of all changes to Moonraker's web APIs.
### January 31st 2021
- The `GET /server/temperature_store` endpoint now only returns fields
that each sensor reports. For example, if a particuarly temperature
sensor does not report "target" or "power", then the corresponding
fields will not be reported for that sensor in response to the
`temperature_store` request.
### January 22nd 2021
- The `POST /machine/update/client` endpoint now requires a `name`
argument. This change added multiple client support
- The response to `GET /machine/update/status` no longer returns a
`client` field. Instead it will add fields matching the `name` of
each configured client. Keep in mind that the client object could
have a different set of fields depending on the type of a client. The
easy way to check for this is to see if a `branch` field is present.
If so, this client is a `git repo`. Otherwise it is a `web` client.
### January 4th 2021
- A `notify_update_refreshed` notification has been added. Moonraker now
auto-refreshes the update status at roughly a 2 hour interval. When
an auto-refresh is complete this notification is broadcast. Included
is an object that matches the response from `/machine/update/status`.
- The behavior of some of the `update_manager` APIs has changed:
- The `refresh` argument for `/machine/update/status` is now more
of a suggestion than a rule. If an update or a print is in
progress then the request will ignore the refresh argument
and immediately return the current status. Generally speaking requesting
a refresh should not be necessary with addition of auto refresh.
- The update requests (ie `/machine/update/klipper`) will now return
an error if a print is in progress. If the requested update is in
progress then the request will return valid with a message stating
that the update is in progress. If another object is being updated
then the request will be queued and block until it its complete.
### January 1st 2021
- A `notify_klippy_shutdown` websocket notification has been added
### December 30th 2020
- Some additional fields are now reported in the response to
`GET /machine/update/status`.
+126 -18
View File
@@ -35,8 +35,8 @@ port: 7125
klippy_uds_address: /tmp/klippy_uds
# The address of Unix Domain Socket used to communicate with Klippy. Default
# is /tmp/klippy_uds
max_upload_size: 200
# The maximum size allowed for a file upload. Default is 200 MiB.
max_upload_size: 1024
# The maximum size allowed for a file upload (in MiB). Default is 1024 MiB.
enable_debug_logging: True
# When set to True Moonraker will log in verbose mode. During this stage
# of development the default is True. In the future this will change.
@@ -44,13 +44,22 @@ config_path:
# The path to a directory where configuration files are located. This
# directory may contain Klipper config files (printer.cfg) or Moonraker
# config files (moonraker.conf). Clients may also write their own config
# files to this directory. There are restrictions on the location of
# this path, it must be located within the users HOME directory or within
# "/etc/moonraker". The path may not be the HOME directory itself. It is
# valid for the path to be "/etc/moonraker", however this is not recommended.
# Something like "/etc/moonraker/config" would be a more appropriate option.
# If you choose to locate files in "/etc/moonraker" be sure that Moonraker
# has read/write permissions in this directory.
# files to this directory. Note that this may not be the system root
# (ie: "/") and moonraker must have read and write access permissions
# for this directory.
database_path: ~/.moonraker_database
# The path to the folder that stores Moonraker's lmdb database files.
# It is NOT recommended to place this file in a location that is served by
# 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.
temperature_store_size: 1200
# The maximum number of temperature values to store for each sensor. Note
# that this value also applies to the "target", "power", and "fan_speed"
# if the sensor reports them. The default is 1200, which is enough to
# store approximately 20 minutes of data at one value per second.
gcode_store_size: 1000
# The maximum number "gcode lines" to store. The default is 1000.
```
## authorization
@@ -86,6 +95,17 @@ cors_domains:
The sections outlined here are optional and enable additional
functionality in moonraker.
## Octoprint compatibility
Enables partial support of Octoprint API is implemented with the purpose of
allowing uploading of sliced prints to a moonraker instance.
Currently we support Slic3r derivatives and Cura with Cura-Octoprint.
```
# moonraker.conf
[octoprint_compat]
```
## paneldue
Enables PanelDue display support. The PanelDue should be connected to the
host machine, either via the machine's UART GPIOs or through a USB-TTL
@@ -151,6 +171,21 @@ and Tasmota (via http) devices are supported.
type: gpio
# The type of device. Can be either gpio, tplink_smartplug or tasmota.
# This parameter must be provided.
off_when_shutdown: False
# If set to True the device will be powered off when Klipper enters
# the "shutdown" state. This option applies to all device types.
# The default is False.
locked_while_printing: False
# If True, locks the device so that the power cannot be changed while the
# printer is printing. This is useful to avert an accidental shutdown to
# the printer's power. The default is False.
restart_klipper_when_powered: False
# If set to True, Moonraker will issue a "FIRMWARE_RESTART" to Klipper
# after the device has been powered on. The default is False, thus no
# attempt to made to restart Klipper after power on.
restart_delay: 1.
# If "restart_klipper_when_powered" is set, this option specifies the amount
# of time (in seconds) to delay the restart. Default is 1 second.
pin: gpiochip0/gpio26
# The pin to use for GPIO devices. The chip is optional, if left out
# then the module will default to gpiochip0. If one wishes to invert
@@ -181,6 +216,17 @@ output_id:
# If your single-relay Tasmota device switches on/off successfully,
# but fails to report its state, ensure that 'SetOption26' is set in
# Tasmota.
address:
user:
password:
output_id:
# The above options are used for "shelly" devices. The
# address should be a valid ip or hostname for the Shelly device.
# 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).
```
Below are some potential examples:
@@ -190,6 +236,7 @@ Below are some potential examples:
[power printer]
type: gpio
pin: gpio26
off_when_shutdown: True
initial_state: off
[power printer_led]
@@ -210,6 +257,12 @@ address: 192.168.1.123
type: tasmota
address: 192.168.1.124
password: password1
[power shelly_plug]
type: shelly
address: 192.168.1.125
user: user2
password: password2
```
It is possible to toggle device power from the Klippy host, this can be done
@@ -258,18 +311,73 @@ enable_repo_debug: False
# detached repos are also allowed. This option is intended for
# developers and should not be used on production machines. The
# default is False.
enable_auto_refresh: False
# When set to True Moonraker will attempt to fetch status about
# available updates roughly every 24 hours, between 12am-4am.
# 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.
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
# meteyou/mainsail to update Mainsail. If this option is not set then
# the update manager will not attempt to update a client.
client_path:
# The path to the client's files on disk. This cannot be a symbolic link,
# it must be the real directory in which the client's files are located.
# If `client_repo` is set, this parameter must be provided
```
### Client Configuration
This allows client programs such as Fluidd, KlipperScreen, and Mainsail to be
updated in addition to klipper, moonraker, and the system os. Repos that have
been modified or cloned from unofficial sources are not supported.
There are two types of update manager clients and each will be detailed
separately. The first one is targeted towards releases that do not need a
service restart such as Fluidd/Mainsail.
```
# moonraker.conf
[update_manager client client_name]
type: web
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
# meteyou/mainsail to update Mainsail. This parameter must be provided.
path:
# The path to the client's files on disk. This parameter must be provided.
persistent_files:
# A list of newline separated file names that should persist between
# updates. This is useful for static configuration files, or perhaps
# themes. The default is no persistent files.
```
This second example is for git repositories that have a service that need
updating.
```
# moonraker.conf
# service_name must be the name of the systemd service
[update_manager client service_name]
type: git_repo
path:
# 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
# be be viewed by navigating to your repository and running:
# git remote -v
# This parameter must be provided.
env:
# The path to the client's virtual environment executable on disk. For
# example, Moonraker's venv is located at ~/moonraker-env/bin/python.
# The default is no env, which disables updating python packages.
requirements:
# This is the location in the repository to the client's virtual environment
# requirements file. This location is relative to the root of the repository.
# This parameter must be provided if the "env" option is set, otherwise it
# should be omitted.
install_script:
# The file location, relative to the repository, for the installation script.
# The update manager parses this file for "system" packages that need updating.
# The default is no install script, which disables system package updates
```
+19 -14
View File
@@ -110,7 +110,7 @@ Now you may install a client, such as
The configuration and log file paths may be specified via the command
line.
```
usage: moonraker.py [-h] [-c <configfile>] [-l <logfile>]
usage: moonraker.py [-h] [-c <configfile>] [-l <logfile>] [-n]
Moonraker - Klipper API Server
@@ -120,14 +120,26 @@ optional arguments:
Location of moonraker configuration file
-l <logfile>, --logfile <logfile>
log file name and location
-n, --nologfile disable logging to a file
```
The default configuration is:
- config file - `~/moonraker.conf`
- log file - `/tmp/moonraker.log`
- config file path- `~/moonraker.conf`
- log file path - `/tmp/moonraker.log`
- logging to a file is enabled
It is recommended to use the defaults, however one may change these
arguments by editing `/etc/default/moonraker`.
If one needs to start moonraker without generating a log file, the
'-n' option may be used, for example:
```
~/moonraker-env/bin/python ~/moonraker/moonraker/moonraker.py -n -c /path/to/moonraker.conf
```
In general it is not recommended to install moonraker with this option.
While moonraker will still log to stdout, all requests for support must
be accompanied by moonraker.log.
These options may be changed by editing
`/etc/systemd/system/moonraker.service`. The `install-moonraker.sh` script
may also be used to modify the config file location.
## Prerequisites (Klipper Configuration)
@@ -149,15 +161,8 @@ missing one or both, you can simply add the bare sections to printer.cfg:
path: ~/gcode_files
```
NOTES:
- While Klipper does not set any hard limits on the location of the
`path` option for the `virtual_sdcard`, Moonraker does have specific
requirements for the location of this folder:
- It must be directory located in the HOME path or in `/etc/moonraker`
- It may not be the HOME directory itself. It is ok for this folder
to be `/etc/moonraker`, however that is not recommended. Something
like `/etc/moonraker/gcode_files` would be more appropriate.
- If you choose to place files in `/etc/moonraker` you must be sure that
Moonraker has permission to read/write to the directory.
- Make sure that Moonraker (and Klipper) has read and write access to the
directory set in the `path` option for the `virtual_sdcard`.
- Upon first starting Moonraker is not aware of the gcode file path, thus
it cannot serve gcode files, add directories, etc. After Klippy enters
the "ready" state it sends Moonraker the gcode file path.
+11
View File
@@ -1,5 +1,16 @@
This file will track changes that require user intervention,
such as a configuration change or a reinstallation.
### March 4th 2021
- To enable Octoprint compatibility with slicer uploads it is now
required to add `[octoprint_compat]` to `moonraker.conf`.
### December 31st 2020
- The file manager no longer restricts the `config_path` to a folder
within the HOME directory. The path may not be the system root,
however it can reside anywhere else on the file system as long as
Moonraker has read and write access to the directory. This applies
to gcode path received from Klipper via the `virtual_sdcard` section
as well.
### December 6th 2020
- Moonraker is now installed as a systemd service. This allows logging
+597 -33
View File
@@ -2,32 +2,115 @@
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 printer generated events such as gcode
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.
Note that all HTTP responses are returned as a json encoded object in the form
of:
### HTTP API Overview
Moonraker's HTTP API could best be described as "RESTish". Attempts are
made to conform to REST standards, however the dynamic nature of
Moonraker's API registration along with the desire to keep consistency
between mulitple API protocols results in an HTTP API that does not
completely adhere to the standard.
Moonraker is capable of parsing request arguments from the both the body
(either JSON or form-data depending on the `Content-Type` header) and from
the query string. All arguments are grouped together in one data structure,
with body arguments taking precedence over query arguments. Thus
if the same argument is supplied both in the body and in the
query string the body argument would be used. It is left up to the client
developer to decide exactly how they want to provide arguments, however
future API documention will make recommendations. As of March 1st 2021
this document exclusively illustrates arguments via the query string.
All successful HTTP requests will return a json encoded object in the form of:
`{result: <response data>}`
Arguments sent via the HTTP APIs may either be included in the query string
or as part of the request's body. All of the examples in this document
use the query string for arguments.
Response data is generally an object itself, however for some requests this
may simply be an "ok" string.
Websocket requests are returned in JSON-RPC format:
`{jsonrpc: "2.0", "result": <response data>, id: <request id>}`
Should a request result in an error, a standard error code along with
an error specific message is returned.
HTML requests will recieve a 500 status code on error, accompanied by
the specific error message.
#### Query string type hints
Websocket requests that result in an error will receive a properly formatted
By default all arguments passed via the query string are represented as
strings. Most endpoint handlers know the data type for each of their
arguments, thus they can perform conversion from a string type if necessary.
However some endpoints accept arguments of a "generic" type, thus the
client is responsible for specifying the type if "string" is not desirable.
This is not a problem for websocket requests as the JSON parser can extract
the appropriate type. HTTP requests must provide "type hints" in these
scenarios. Moonraker supplies support for the following query string type hints:
- int
- bool
- float
- json
The `json` type hint can be specified to pass an array or an object via
the query string. Remember to percent encode the json string so that
the query string is correctly parsed.
Type hints may be specified by post-fixing them to a key, with a ":"
separating the key and the hint. For example, lets assume that we
have a request that takes `seconds` (integer) and `enabled` (boolean)
arguments. The query string with type hints might look like:
```
?seconds:int=120&enabled:bool=true
```
A query string that takes a `value` argument with which we want to
assing an object, `{foo: 21.5, bar: "hello"}` might look like:
```
?value:json=%7B%22foo%22%3A21.5%2C%22bar%22%3A%22hello%22%7D
```
As you can see, a percent encoded json string is not human readable,
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
The Websocket API is based on JSON-RPC, an encoded request should look
something like:
```json
{
"jsonrpc": "2.0",
"method": "API method",
"params": {"arg_one": 1, "arg_two": true},
"id": 354
}
```
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
with other JSON-RPC requests. The `method` is the API method, as defined
for each API in this document.
A successful request will return a response like the following:
```json
{
"jsonrpc": "2.0",
"result": {"res_data": "success"},
"id": 354
}
```
The `result` will generally contain an object, but as with the HTTP API in some
cases it may simply return a string. The `id` field will return an id that
matches the one provided by the request.
Requests that result in an error will receive a properly formatted
JSON-RPC response:
`{jsonrpc: "2.0", "error": {code: <code>, message: <msg>}, id: <request_id>}`
Note that under some circumstances it may not be possible for the server to
return a request ID, such as an improperly formatted json request.
```json
{
"jsonrpc": "2.0",
"error": {"code": 36000, "message": "Error Message"},
"id": 354
}
```
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
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).
@@ -227,6 +310,30 @@ websocket. See the `notify_status_update` notification for details.
enabled plugins. This can be used by clients to check if an optional
plugin is available.
### Get Server Configuration
- HTTP command:\
`GET /server/config`
- Websocket command:
`{jsonrpc: "2.0", method: "server.config", id: <request id>}`
- Returns:\
An object containing the server's configuration, structured as follows:
```json
{
config: {
server: {
...
},
authorization: {
...
},
...
}
}
```
### Fetch stored temperature data
- HTTP command:\
`GET /server/temperature_store`
@@ -240,6 +347,23 @@ websocket. See the `notify_status_update` notification for details.
1 second by default, containing a total of 1200 values (20 minutes). The
array is organized from oldest temperature to most recent (left to right).
Note that when the host starts each array is initialized to 0s.
```json
{
extruder: {
temperatures: [],
targets: [],
powers: []
},
temperature_fan my_fan: {
temperatures: [],
targets: [],
speeds: [],
},
temperature_sensor my_sensor: {
temperatures: []
}
}
```
### Fetch stored gcode info
- HTTP command:\
@@ -267,7 +391,8 @@ websocket. See the `notify_status_update` notification for details.
gcode_store: [
{
message: <string>,
time: unix_time_stamp
time: unix_time_stamp,
type: <string>
}, ...
]
}
@@ -282,6 +407,7 @@ for (let resp of result.gcode_store) {
// Do something with date and resp.message ...
}
```
The `type` field will either be "command" or "response".
### Restart Server
- HTTP command:\
@@ -412,7 +538,7 @@ for (let resp of result.gcode_store) {
### Restart a system service
Restarts a system service via `sudo systemctl restart <name>`. Currently
only `moonraker` and `klipper` are allowed.
only `moonraker`, `klipper`, and `webcamd` are allowed.
- HTTP command:\
`POST /machine/services/restart?service=<service_name>`
@@ -425,6 +551,91 @@ only `moonraker` and `klipper` are allowed.
`ok` when complete. Note that if `moonraker` is chosen, the return
value will be sent prior to the restart.
### Stop a system service
Stops a system service via `sudo systemctl stop <name>`. Currently
only `webcamd` and `klipper` are allowed.
- HTTP command:\
`POST /machine/services/stop?service=<service_name>`
- Websocket command:\
`{jsonrpc: "2.0", method: "machine.services.stop",
params: {service: "service name"}, id: <request id>}`
- Returns:\
`ok` when complete
### Start a system service
Starts a system service via `sudo systemctl start <name>`. Currently
only `webcamd` and `klipper` are allowed.
- HTTP command:\
`POST /machine/services/start?service=<service_name>`
- Websocket command:\
`{jsonrpc: "2.0", method: "machine.services.start",
params: {service: "service name"}, id: <request id>}`
- Returns:\
`ok` when complete
### Get Process Info
Returns system usage information about the moonraker process.
- HTTP command:\
`GET /machine/proc_info`
- Websocket command:\
`{jsonrpc: "2.0", method: "machine.proc_info", id: <request id>}`
- Returns:\
An object in the following format:
```json
{
proc_info: [
{
time: <system time of sample>,
cpu_usage: <usage percent>,
memory: <memory_used>,
mem_units: "<kB, mB, etc>"
},
...
],
throttled_state: {
bits: <throttled bits>,
flags: ["flag1", "flag2", ...]
}
}
```
Process information is sampled every second. The `proc_info` field
will return up to 30 samples, each sample with the following fields:
- `time`: Time of the sample (in seconds since the Epoch)
- `cpu_usage`: A floating point value between 0-100, representing the
CPU usage of the Moonraker process.
- `memory`: Integer value representing the current amount of memory
allocated in RAM (resident set size).
- `mem_units`: A string indentifying the units of the value in the
`memory` field. This is typically "kB", but not guaranteed.
If the system running Moonraker supports `vcgencmd` then Moonraker
will check the current throttled flags via `vcgencmd get_throttled`
and report them in the `throttled_state` field:
- `bits`: An integer value that represents the bits reported by
`vcgencmd get_throttled`
- `flags`: Descriptive flags parsed out of the bits. One or more
of the following flags may be reported:
- "Under-Voltage Detected"
- "Frequency Capped"
- "Currently Throttled"
- "Temperature Limit Active"
- "Previously Under-Volted"
- "Previously Frequency Capped"
- "Previously Throttled"
- "Previously Temperature Limited"
The first four flags indicate an active throttling condition,
whereas the last four indicate a previous condition (may or
may not still be active). If `vcgencmd` is not available the
`throttled_state` will report `null`.
## File Operations
Most file operations are available over both APIs, however file upload,
@@ -813,18 +1024,146 @@ only be used once, making them relatively for inclusion in the query string.
to any API endpoint. The query string should be added in the form of:
`?token=randomly_generated_token`
## Database APIs
The following endpoints provide access to Moonraker's ldbm database. The
database is divided into "namespaces", each client may define its own
namespace to store information. From the client's point of view, a
namespace is an "object". Items in the database are accessed by providing
a namespace and a key. A key may be specifed as string, where a "." is a
delimeter to access nested objects. Alternatively the key may be specified
as an array of strings, where each string references a nested object.
This is useful for scenarios where your namespace contain keys that include
a "." character.
Moonraker reserves "moonraker" and "gcode_metadata" namespaces. Clients may
read from these namespaces but they may not modify them.
For example, assume the following object is stored in the "superclient"
namespace:
```json
{
settings: {
console: {
enable_autocomple: True
}
}
theme: {
background_color: "black"
}
}
```
One may access the "enable_autocomplete" field by supplying `superclient` as
the "namespace" parameter and `settings.console.enable_autocomplete` or
`["settings", "console", "enable_autocomplete"]` as the "key" parameter for
the request. The entire settings object could be accessed by providing
`settings` or `["settings"]` as the key parameter. The entire namespace
may be read by omitting the "key" parameter, however as explained below it
is not possible to modify a namespace without specifying a key.
### List Namespaces
Lists all available namespaces.
- HTTP command:\
`GET /server/database/list`
- Websocket command:\
`{jsonrpc: "2.0", method: "server.database.list", id: <request id>}`
- Returns:\
An object containing an array of namespaces in the following format:
```json
{
'namespaces': ["namespace1", "namespace2"...]
}
```
### Get Database Item
Retreives an item from a specified namespace. The `key` parameter may be
omitted, in which case an object representing the entire namespace will
be returned in the `value` field. If the `key` is provided and does not
exist in the database an error will be returned.
- HTTP command:\
`GET /server/database/item?namespace=my_namespace&key=item.location`
- Websocket command:\
`{jsonrpc: "2.0", method: "server.database.get_item", params:
{namespace: "my_namespace", key: "item.location"}, id: <request id>}`
- Returns:\
An object containing the following fields:
```json
{
'namespace': "requested_namespace",
'key': "requested_key"
'value': <value at key>
}
```
### Add Database Item
Inserts an item into the database. If the namespace does not exist
it will be created. If the key specifies parent objects, all parents
will be created if they do not exist. If the key exists it will be
overwritten with the provided `value`. The key parameter must be provided,
it is not possible to assign a value directly to a namespace.
- HTTP command:\
`POST /server/database/item?namespace=my_namespace&key=item.location&value:int=100`
- Websocket command:\
`{jsonrpc: "2.0", method: "server.database.post_item", params:
{namespace: "my_namespace", key: "item.location", value: 100},
id: <request id>}`
- Returns:\
An object containing the following fields:
```json
{
'namespace': "requested_namespace",
'key': "requested_key"
'value': <the value inserted>
}
```
### Delete Database Item
Deletes an item from the database at the specified key. If the key does not
exist in the database an error will be returned. If the deleted item results
in an empty namespace, the namespace will be removed from the database.
- HTTP command:\
`DELETE /server/database/item?namespace=my_namespace&key=item.location`
- Websocket command:\
`{jsonrpc: "2.0", method: "server.database.delete_item", params:
{namespace: "my_namespace", key: "item.location"}, id: <request id>}`
- Returns:\
An object containing the following fields:
```json
{
'namespace': "requested_namespace",
'key': "requested_key"
'value': <value at deleted key>
}
```
## Update Manager APIs
The following endpoints are availabe when the `[update_manager]` plugin has
The following endpoints are available when the `[update_manager]` plugin has
been configured:
### Get update status
Retreives the current state of each "package" available for update. Typically
this will consist of information regarding `moonraker`, `klipper`, and
a `client`. If moonraker has not yet received information from Klipper then
its status will be omitted. If a client has not been configured then its
status will also be omitted. If the parameter "refresh" is passed and set
to true then Moonraker will query Github for the most recent release
information.
this will consist of information regarding `moonraker`, `klipper`, a `client`,
and `system` packages. If moonraker has not yet received information from
Klipper then its status will be omitted. If a client has not been configured
then its status will also be omitted. One may request that the update info
be refreshed by sending a `refresh=true` argument. Note that the refresh
parameter is ignored if an update is in progress or if a print is in progress.
In these cases the current status will be returned immediately.
- HTTP command:\
`GET /machine/update/status?refresh=false`
@@ -867,7 +1206,7 @@ information.
detached: <bool>,
debug_enabled: <bool>
},
'client': {
'client_name_1': {
name: <string>,
version: <string>,
remote_version: <string>
@@ -908,10 +1247,13 @@ information.
- `debug_enabled`: True when "enable_repo_debug" has been configured. This
will bypass repo validation, allowing detached updates, and updates from
a remote/origin other than "origin/master".
- The `client` object has the following fields:
- Multiple `client` fields may be present. Web clients have the following
fields:
- `name`: Name of the configured client
- `version`: version of the installed client.
- `remote_version`: version of the latest release published to GitHub
A `git_repo` client will have fields that match that of `klipper` and
`moonraker`
- The `system` object has the following fields:
- `package_count`: The number of system packages available for update
- `package_list`: An array containing the names of packages available
@@ -923,7 +1265,8 @@ the service. If "include_deps" is set to `true` an attempt will be made
to install new packages (via apt-get) and python dependencies (via pip).
Note that Moonraker uses semantic versioning to check for dependency changes
automatically, so it is generally not necessary to set `include_deps`
to `true`.
to `true`. If an update is requested while a print is in progress then
this request will return an error.
- HTTP command:\
`POST /machine/update/moonraker?include_deps=false`
@@ -946,7 +1289,8 @@ the service. If "include_deps" is set to `true` an attempt will be made
to install new packages (via apt-get) and python dependencies (via pip).
At the moment there is no method for automatically checking for updated
Klipper dependencies, so clients might wish to make this option available
to users via the UI.
to users via the UI. If an update is requested while a print is in progress
then this request will return an error.
- HTTP command:\
`POST /machine/update/klipper?include_deps=false`
@@ -964,22 +1308,27 @@ to users via the UI.
`ok` when complete
### Update Client
If `client_repo` and `client_path` have been configured in `[update_manager]`
this endpoint can be used to install the most recently publish release
of the client.
If one more more `[update_manager client client_name]` sections have
been configured this endpoint can be used to install the most recently
published release of the client. If an update is requested while a
print is in progress then this request will return an error. The
`name` argument is requred, it's value should match the `client_name`
of the configured section.
- HTTP command:\
`POST /machine/update/client`
`POST /machine/update/client?name=client_name`
- Websocket command:\
`{jsonrpc: "2.0", method: "machine.update.client",
id: <request id>}`
params: {name: "client_name"}, id: <request id>}`
- Returns:\
`ok` when complete
### Update System Packages
Upgrades the system packages. Currently only `apt-get` is supported.
If an update is requested while a print is in progress then this request
will return an error.
- HTTP command:\
`POST /machine/update/system`
@@ -1069,6 +1418,195 @@ The APIs below are available when the `[power]` plugin has been configured.
}
```
## Octoprint API emulation
Partial support of Octoprint API is implemented with the purpose of
allowing uploading of sliced prints to a moonraker instance.
Currently we support Slic3r derivatives and Cura with Cura-Octoprint.
### Version information
- HTTP command:\
`GET /api/version`
- Returns:\
An object containing simulated Octoprint version information
```json
{
server: "1.5.0",
api: "0.1",
text: "Octoprint (Moonraker v0.3.1-12)"
}
```
### Server status
- HTTP command:\
`GET /api/server`
- Returns:\
An object containing simulated Octoprint server status
```json
{
server: "1.5.0",
safemode: <None or "settings">
}
```
### Login verification & User information
- HTTP command:\
`GET /api/login`
- HTTP command:\
`GET /api/server`
- Returns:\
An object containing stubbed Octoprint login/user verification
```json
{
_is_external_client: false,
_login_mechanism: "apikey",
name: "_api",
active: true,
user: true,
admin: true,
apikey: null,
permissions: [],
groups: ["admins", "users"],
}
```
### Get settings
- HTTP command:\
`GET /api/server`
- Returns:\
An object containing stubbed Octoprint settings.
The webcam route is hardcoded to Fluidd/Mainsail default path.
We say we have the UFP plugin installed so that Cura-Octoprint will
upload in the preferred UFP format.
```json
{
plugins: {
UltimakerFormatPackage: {
align_inline_thumbnail: false,
inline_thumbnail: false,
inline_thumbnail_align_value: "left",
inline_thumbnail_scale_value: "50",
installed: true,
installed_version: "0.2.2",
scale_inline_thumbnail: false,
state_panel_thumbnail: true
}
},
feature: {
sdSupport: false,
temperatureGraph: false
},
webcam: {
flipH: false,
flipV: false,
rotate90: false,
streamUrl: "/webcam/?action=stream",
webcamEnabled': true
}
}
```
### File Upload
- HTTP command:\
`POST /api/files/local`
Otherwise identical to the standard Moonraker `POST /server/files/upload` API.
### Get Job status
- HTTP command:\
`GET /api/job`
- Returns:\
An object containing stubbed Octoprint Job status
```json
{
job: {
file: {name: null},
estimatedPrintTime: null,
filament: {length: null},
user: None
},
progress: {
completion: null,
filepos: null,
printTime: null,
printTimeLeft: null,
printTimeOrigin: null
},
state: <One of "Offline","Error", "Operational", "Printing", "Paused">
}
```
### Get Printer status
- HTTP command:\
`GET /api/printer`
- Returns:\
An object containing Octoprint Printer status
```json
{
temperature: {
<list of heater names: "bed", "tool<n>">: {
actual: <actual temp>,
offset: 0,
target: <target temp>
}
},
state: {
text': state,
flags': {
operational: <bool>,
paused: <bool>,
printing: <bool>,
cancelling: <bool>,
pausing: False,
error: <bool>,
ready: <bool>,
closedOrError: <bool>
}
}
}
```
### Send GCode command
- HTTP command:\
`POST /api/printer/command`
JSON payload with parameter:
* commands: List of GCode strings
- Returns:\
An blank JSON object
```json
{}
```
### List Printer profiles
- HTTP command:\
`GET /api/printerprofiles`
- Returns:\
An object containing simulates Octoprint Printer profile
```json
{
profiles: {
_default: {
id: "_default",
name: "Default",
color: "default",
model: "Default",
default': true,
current': true,
heatedBed: <true if "heater_bed" heater exists>,
heatedChamber: <true if "chamber" heater exists>
}
}
}
```
## Websocket notifications
Printer generated events are sent over the websocket as JSON-RPC 2.0
notifications. These notifications are sent to all connected clients
@@ -1104,6 +1642,11 @@ Notify clients when Klippy has reported a ready state
`{jsonrpc: "2.0", method: "notify_klippy_ready"}`
### Klippy Shutdown:
Notify clients when Klippy has reported a shutdown state
`{jsonrpc: "2.0", method: "notify_klippy_shutdown"}`
### Klippy Disconnected:
Notify clients when Moonraker's connection to Klippy has terminated
@@ -1211,6 +1754,27 @@ Where `response` is an object int he following format:
update, indicating that the update completed successfully. Otherwise it
will be false.
### Update Manager Refreshed
The update manager periodically auto refreshes the state of each application
it is tracking. After an auto refresh has completed the following
notification is broadcast:
`{jsonrpc: "2.0", method: "notify_update_refreshed", params: [update_info]}`
Where `update_info` is an object that matches the response from an
[update status](#get-update-status) request.
### CPU Throttled
If the system supports throttled CPU monitoring Moonraker will send the
following notification when it detectes an active throttled condition.
`{jsonrpc: "2.0", method: "notify_cpu_throttled", params: [throttled_state]}`
Where `throtled_state` is an object that matches the `throttled_state` 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.
# Appendix
## Websocket setup
+159 -113
View File
@@ -7,6 +7,7 @@
import os
import mimetypes
import logging
import json
import tornado
from inspect import isclass
from tornado.escape import url_unescape
@@ -15,6 +16,8 @@ from utils import ServerError
from websockets import WebRequest, WebsocketManager, WebSocket
from authorization import AuthorizedRequestHandler, AuthorizedFileHandler
from authorization import Authorization
from streaming_form_data import StreamingFormDataParser
from streaming_form_data.targets import FileTarget, ValueTarget
# These endpoints are reserved for klippy/server communication only and are
# not exposed via http or the websocket
@@ -23,36 +26,11 @@ RESERVED_ENDPOINTS = [
"register_remote_method"
]
# 50 MiB Max Standard Body Size
MAX_BODY_SIZE = 50 * 1024 * 1024
EXCLUDED_ARGS = ["_", "token", "connection_id"]
DEFAULT_KLIPPY_LOG_PATH = "/tmp/klippy.log"
# Status objects require special parsing
def _status_parser(request_handler):
request = request_handler.request
arg_list = request.arguments.keys()
args = {}
for key in arg_list:
if key in EXCLUDED_ARGS:
continue
val = request_handler.get_argument(key)
if not val:
args[key] = None
else:
args[key] = val.split(',')
logging.debug(f"Parsed Arguments: {args}")
return {'objects': args}
# Built-in Query String Parser
def _default_parser(request_handler):
request = request_handler.request
arg_list = request.arguments.keys()
args = {}
for key in arg_list:
if key in EXCLUDED_ARGS:
continue
args[key] = request_handler.get_argument(key)
return args
class MutableRouter(tornado.web.ReversibleRuleRouter):
def __init__(self, application):
self.application = application
@@ -87,14 +65,14 @@ class MutableRouter(tornado.web.ReversibleRuleRouter):
class APIDefinition:
def __init__(self, endpoint, http_uri, ws_methods,
request_methods, parser):
request_methods, need_object_parser):
self.endpoint = endpoint
self.uri = http_uri
self.ws_methods = ws_methods
if not isinstance(request_methods, list):
request_methods = [request_methods]
self.request_methods = request_methods
self.parser = parser
self.need_object_parser = need_object_parser
class MoonrakerApp:
def __init__(self, config):
@@ -102,7 +80,7 @@ class MoonrakerApp:
self.tornado_server = None
self.api_cache = {}
self.registered_base_handlers = []
self.max_upload_size = config.getint('max_upload_size', 200)
self.max_upload_size = config.getint('max_upload_size', 1024)
self.max_upload_size *= 1024 * 1024
# Set Up Websocket and Authorization Managers
@@ -118,8 +96,7 @@ class MoonrakerApp:
self.mutable_router = MutableRouter(self)
app_handlers = [
(AnyMatches(), self.mutable_router),
(r"/websocket", WebSocket),
(r"/api/version", EmulateOctoprintHandler)]
(r"/websocket", WebSocket)]
self.app = tornado.web.Application(
app_handlers,
@@ -131,14 +108,16 @@ class MoonrakerApp:
# Register handlers
logfile = config['system_args'].get('logfile')
self.register_static_file_handler("moonraker.log", logfile)
if logfile:
self.register_static_file_handler(
"moonraker.log", logfile, force=True)
self.register_static_file_handler(
"klippy.log", DEFAULT_KLIPPY_LOG_PATH)
"klippy.log", DEFAULT_KLIPPY_LOG_PATH, force=True)
self.auth.register_handlers(self)
def listen(self, host, port):
self.tornado_server = self.app.listen(
port, address=host, max_body_size=self.max_upload_size,
port, address=host, max_body_size=MAX_BODY_SIZE,
xheaders=True)
def get_server(self):
@@ -170,14 +149,16 @@ class MoonrakerApp:
f"Websocket: {', '.join(api_def.ws_methods)}")
self.wsm.register_remote_handler(api_def)
params = {}
params['arg_parser'] = api_def.parser
params['remote_callback'] = api_def.endpoint
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, RemoteRequestHandler, params)
api_def.uri, DynamicRequestHandler, params)
self.registered_base_handlers.append(api_def.uri)
def register_local_handler(self, uri, request_methods,
callback, protocol=["http", "websocket"]):
callback, protocol=["http", "websocket"],
wrap_result=True):
if uri in self.registered_base_handlers:
return
api_def = self._create_api_definition(
@@ -187,19 +168,20 @@ class MoonrakerApp:
msg += f" - HTTP: ({' '.join(request_methods)}) {uri}"
params = {}
params['methods'] = request_methods
params['arg_parser'] = api_def.parser
params['callback'] = callback
self.mutable_router.add_handler(uri, LocalRequestHandler, params)
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)
def register_static_file_handler(self, pattern, file_path):
def register_static_file_handler(self, pattern, file_path, force=False):
if pattern[0] != "/":
pattern = "/server/files/" + pattern
if os.path.isfile(file_path):
if os.path.isfile(file_path) or force:
pattern += '()'
elif os.path.isdir(file_path):
if pattern[-1] != "/":
@@ -213,7 +195,9 @@ class MoonrakerApp:
self.mutable_router.add_handler(pattern, FileRequestHandler, params)
def register_upload_handler(self, pattern):
self.mutable_router.add_handler(pattern, FileUploadHandler, {})
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)
@@ -250,76 +234,112 @@ class MoonrakerApp:
raise self.server.error(
"Invalid API definition. Number of websocket methods must "
"match the number of request methods")
if endpoint.startswith("objects/"):
parser = _status_parser
else:
parser = _default_parser
need_object_parser = endpoint.startswith("objects/")
api_def = APIDefinition(endpoint, uri, ws_methods,
request_methods, parser)
request_methods, need_object_parser)
self.api_cache[endpoint] = api_def
return api_def
# ***** Dynamic Handlers*****
class RemoteRequestHandler(AuthorizedRequestHandler):
def initialize(self, remote_callback, arg_parser):
super(RemoteRequestHandler, self).initialize()
self.remote_callback = remote_callback
self.query_parser = arg_parser
async def get(self):
await self._process_http_request()
async def post(self):
await self._process_http_request()
async def _process_http_request(self):
conn = self.get_associated_websocket()
args = self.query_parser(self)
try:
result = await self.server.make_request(
WebRequest(self.remote_callback, args, conn=conn))
except ServerError as e:
raise tornado.web.HTTPError(
e.status_code, str(e)) from e
self.finish({'result': result})
class LocalRequestHandler(AuthorizedRequestHandler):
def initialize(self, callback, methods, arg_parser):
super(LocalRequestHandler, self).initialize()
class DynamicRequestHandler(AuthorizedRequestHandler):
def initialize(self, callback, methods, need_object_parser=False,
is_remote=True, wrap_result=True):
super(DynamicRequestHandler, self).initialize()
self.callback = callback
self.methods = methods
self.query_parser = arg_parser
self.wrap_result = wrap_result
self._do_request = self._do_remote_request if is_remote \
else self._do_local_request
self._parse_query = self._object_parser if need_object_parser \
else self._default_parser
async def get(self):
if 'GET' in self.methods:
await self._process_http_request('GET')
else:
raise tornado.web.HTTPError(405)
async def post(self):
if 'POST' in self.methods:
await self._process_http_request('POST')
else:
raise tornado.web.HTTPError(405)
async def delete(self):
if 'DELETE' in self.methods:
await self._process_http_request('DELETE')
else:
raise tornado.web.HTTPError(405)
async def _process_http_request(self, method):
conn = self.get_associated_websocket()
args = self.query_parser(self)
# Converts query string values with type hints
def _convert_type(value, hint):
type_funcs = {
"int": int, "float": float,
"bool": lambda x: x.lower() == "true",
"json": json.loads}
if hint not in type_funcs:
logging.info(f"No conversion method for type hint {hint}")
return value
func = type_funcs[hint]
try:
result = await self.callback(
WebRequest(self.request.path, args, method, conn=conn))
converted = func(value)
except Exception:
logging.exception("Argument conversion error: Hint: "
f"{hint}, Arg: {value}")
return value
return converted
def _default_parser(self):
args = {}
for key in self.request.arguments.keys():
if key in EXCLUDED_ARGS:
continue
key_parts = key.rsplit(":", 1)
val = self.get_argument(key)
if len(key_parts) == 1:
args[key] = val
else:
args[key_parts[0]] = self._convert_type(val, key_parts[1])
return args
def _object_parser(self):
args = {}
for key in self.request.arguments.keys():
if key in EXCLUDED_ARGS:
continue
val = self.get_argument(key)
if not val:
args[key] = None
else:
args[key] = val.split(',')
logging.debug(f"Parsed Arguments: {args}")
return {'objects': args}
def parse_args(self):
args = self._parse_query()
content_type = self.request.headers.get('Content-Type', "").strip()
if content_type.startswith("application/json"):
try:
args.update(json.loads(self.request.body))
except json.JSONDecodeError:
pass
for key, value in self.path_kwargs.items():
if value is not None:
args[key] = value
return args
async def get(self, *args, **kwargs):
await self._process_http_request()
async def post(self, *args, **kwargs):
await self._process_http_request()
async def delete(self, *args, **kwargs):
await self._process_http_request()
async def _do_local_request(self, args, conn):
return await self.callback(
WebRequest(self.request.path, args, self.request.method,
conn=conn))
async def _do_remote_request(self, args, conn):
return await self.server.make_request(
WebRequest(self.callback, args, conn=conn))
async def _process_http_request(self):
if self.request.method not in self.methods:
raise tornado.web.HTTPError(405)
conn = self.get_associated_websocket()
args = self.parse_args()
try:
result = await self._do_request(args, conn)
except ServerError as e:
raise tornado.web.HTTPError(
e.status_code, str(e)) from e
self.finish({'result': result})
if self.wrap_result:
result = {'result': result}
self.finish(result)
class FileRequestHandler(AuthorizedFileHandler):
def set_extra_headers(self, path):
@@ -344,20 +364,46 @@ class FileRequestHandler(AuthorizedFileHandler):
raise tornado.web.HTTPError(e.status_code, str(e))
self.finish({'result': filename})
@tornado.web.stream_request_body
class FileUploadHandler(AuthorizedRequestHandler):
def initialize(self, max_upload_size):
super(FileUploadHandler, self).initialize()
self.file_manager = self.server.lookup_plugin('file_manager')
self.max_upload_size = max_upload_size
def prepare(self):
if self.request.method == "POST":
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(),
}
self._file = FileTarget(tmpname)
self._parser = StreamingFormDataParser(self.request.headers)
self._parser.register('file', self._file)
for name, target in self._targets.items():
self._parser.register(name, target)
def data_received(self, chunk):
if self.request.method == "POST":
self._parser.data_received(chunk)
async def post(self):
file_manager = self.server.lookup_plugin('file_manager')
form_args = {}
for name, target in self._targets.items():
if target.value:
form_args[name] = target.value.decode()
form_args['filename'] = self._file.multipart_filename
form_args['tmp_file_path'] = self._file.filename
debug_msg = "\nFile Upload Arguments:"
for name, value in form_args.items():
debug_msg += f"\n{name}: {value}"
logging.debug(debug_msg)
try:
result = await file_manager.process_file_upload(self.request)
result = await self.file_manager.finalize_upload(form_args)
except ServerError as e:
raise tornado.web.HTTPError(
e.status_code, str(e))
self.finish(result)
class EmulateOctoprintHandler(AuthorizedRequestHandler):
def get(self):
self.finish({
'server': "1.1.1",
'api': "0.1",
'text': "OctoPrint Upload Emulator"})
+41 -5
View File
@@ -15,10 +15,14 @@ class Sentinel:
class ConfigHelper:
error = ConfigError
def __init__(self, server, config, section):
def __init__(self, server, config, section, orig_sects, parsed={}):
self.server = server
self.config = config
self.section = section
self.orig_sections = orig_sects
self.parsed = parsed
if self.section not in self.parsed:
self.parsed[self.section] = {}
self.sections = config.sections
self.has_section = config.has_section
@@ -43,7 +47,8 @@ class ConfigHelper:
def getsection(self, section):
if section not in self.config:
raise ConfigError(f"No section [{section}] in config")
return ConfigHelper(self.server, self.config, section)
return ConfigHelper(self.server, self.config, section,
self.orig_sections, self.parsed)
def _get_option(self, func, option, default):
try:
@@ -55,6 +60,9 @@ class ConfigHelper:
if val == Sentinel:
raise ConfigError(
f"No option found ({option}) in section [{self.section}]")
if self.section in self.orig_sections:
# Only track sections included in the original config
self.parsed[self.section][option] = val
return val
def get(self, option, default=Sentinel):
@@ -70,7 +78,7 @@ class ConfigHelper:
self.config[self.section].getboolean, option, default)
def getfloat(self, option, default=Sentinel):
return self._get_item(
return self._get_option(
self.config[self.section].getfloat, option, default)
def read_supplemental_config(self, file_name):
@@ -83,6 +91,27 @@ class ConfigHelper:
except Exception:
raise ConfigError(f"Error Reading Config: '{cfg_file_path}'")
def write_config(self, file_obj):
self.config.write(file_obj)
def get_parsed_config(self):
return dict(self.parsed)
def validate_config(self):
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")
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.")
def get_configuration(server, system_args):
cfg_file_path = os.path.normpath(os.path.expanduser(
system_args.configfile))
@@ -99,10 +128,17 @@ def get_configuration(server, system_args):
except KeyError:
raise ConfigError("No section [server] in config")
if server_cfg.get('enable_debug_logging', True):
orig_sections = config.sections()
try:
orig_sections.remove("DEFAULT")
except Exception:
pass
if server_cfg.getboolean('enable_debug_logging', True):
logging.getLogger().setLevel(logging.DEBUG)
config['system_args'] = {
'configfile': system_args.configfile,
'logfile': system_args.logfile,
'software_version': system_args.software_version}
return ConfigHelper(server, config, 'server')
return ConfigHelper(server, config, 'server', orig_sections)
+107 -18
View File
@@ -8,10 +8,12 @@ import argparse
import sys
import importlib
import os
import io
import time
import socket
import logging
import json
import signal
import confighelper
import utils
import asyncio
@@ -27,18 +29,28 @@ LOG_ATTEMPT_INTERVAL = int(2. / INIT_TIME + .5)
MAX_LOG_ATTEMPTS = 10 * LOG_ATTEMPT_INTERVAL
CORE_PLUGINS = [
'file_manager', 'klippy_apis', 'machine',
'data_store', 'shell_command']
'database', 'file_manager', 'klippy_apis', 'machine',
'data_store', 'shell_command', 'proc_stats']
class Sentinel:
pass
class Server:
error = ServerError
def __init__(self, args):
config = confighelper.get_configuration(self, args)
def __init__(self, args, file_logger):
self.file_logger = file_logger
self.config = config = confighelper.get_configuration(self, args)
# log config file
strio = io.StringIO()
config.write_config(strio)
cfg_item = f"\n{'#'*20} Moonraker Configuration {'#'*20}\n\n"
cfg_item += strio.getvalue()
cfg_item += "#"*65
strio.close()
self.add_log_rollover_item('config', cfg_item)
self.host = config.get('host', "0.0.0.0")
self.port = config.getint('port', 7125)
self.exit_reason = ""
# Event initialization
self.events = {}
@@ -53,7 +65,9 @@ class Server:
self.init_handle = None
self.init_attempts = 0
self.klippy_state = "disconnected"
self.klippy_disconnect_evt = None
self.subscriptions = {}
self.failed_plugins = []
# Server/IOLoop
self.server_running = False
@@ -65,9 +79,17 @@ class Server:
self.register_endpoint(
"/server/info", ['GET'], self._handle_info_request)
self.register_endpoint(
"/server/config", ['GET'], self._handle_config_request)
self.register_endpoint(
"/server/restart", ['POST'], self._handle_server_restart)
self.register_notification("server:klippy_ready")
self.register_notification("server:klippy_shutdown")
self.register_notification("server:klippy_disconnect",
"klippy_disconnected")
self.register_notification("server:gcode_response")
# Setup remote methods accessable to Klippy. Note that all
# registered remote methods should be of the notification type,
# they do not return a response to Klippy after execution
@@ -83,8 +105,9 @@ class Server:
# Plugin initialization
self.plugins = {}
self.klippy_apis = self.load_plugin(config, 'klippy_apis')
self._load_plugins(config)
self.klippy_apis = self.lookup_plugin('klippy_apis')
config.validate_config()
def start(self):
hostname, hostport = self.get_host_info()
@@ -93,8 +116,20 @@ class Server:
f"Hostname: {hostname}")
self.moonraker_app.listen(self.host, self.port)
self.server_running = True
self.ioloop.spawn_callback(self._init_signals)
self.ioloop.spawn_callback(self._connect_klippy)
def _init_signals(self):
aioloop = asyncio.get_event_loop()
aioloop.add_signal_handler(
signal.SIGTERM, self._handle_term_signal)
def add_log_rollover_item(self, name, item, log=True):
if self.file_logger is not None:
self.file_logger.set_rollover_info(name, item)
if log and item is not None:
logging.info(item)
# ***** Plugin Management *****
def _load_plugins(self, config):
# load core plugins
@@ -116,11 +151,12 @@ class Server:
if not os.path.exists(mod_path):
msg = f"Plugin ({plugin_name}) does not exist"
logging.info(msg)
self.failed_plugins.append(plugin_name)
if default == Sentinel:
raise ServerError(msg)
return default
module = importlib.import_module("plugins." + plugin_name)
try:
module = importlib.import_module("plugins." + plugin_name)
func_name = "load_plugin"
if hasattr(module, "load_plugin_multi"):
func_name = "load_plugin_multi"
@@ -131,6 +167,7 @@ class Server:
except Exception:
msg = f"Unable to load plugin ({plugin_name})"
logging.exception(msg)
self.failed_plugins.append(plugin_name)
if default == Sentinel:
raise ServerError(msg)
return default
@@ -144,6 +181,10 @@ class Server:
raise ServerError(f"Plugin ({plugin_name}) not found")
return plugin
def register_notification(self, event_name, notify_name=None):
wsm = self.moonraker_app.get_websocket_manager()
wsm.register_notification(event_name, notify_name)
def register_event_handler(self, event, callback):
self.events.setdefault(event, []).append(callback)
@@ -229,6 +270,8 @@ class Server:
self.ioloop.remove_timeout(self.init_handle)
if self.server_running:
self.ioloop.call_later(.25, self._connect_klippy)
if self.klippy_disconnect_evt is not None:
self.klippy_disconnect_evt.set()
async def _initialize(self):
if not self.server_running:
@@ -368,6 +411,10 @@ class Server:
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_plugin('data_store')
data_store.store_gcode_command(script)
return await self._request_standard(web_request)
async def _request_subscripton(self, web_request):
@@ -427,17 +474,39 @@ class Server:
def remove_subscription(self, conn):
self.subscriptions.pop(conn, None)
async def _stop_server(self):
def _handle_term_signal(self):
logging.info(f"Exiting with signal SIGTERM")
self.ioloop.spawn_callback(self._stop_server, "terminate")
async def _stop_server(self, exit_reason="restart"):
self.server_running = False
for name, plugin in self.plugins.items():
if hasattr(plugin, "close"):
ret = plugin.close()
if asyncio.iscoroutine(ret):
await ret
self.klippy_connection.close()
while self.klippy_state != "disconnected":
await gen.sleep(.1)
await self.moonraker_app.close()
try:
ret = plugin.close()
if asyncio.iscoroutine(ret):
await ret
except Exception:
logging.exception(f"Error closing plugin: {name}")
try:
if self.klippy_connection.is_connected():
self.klippy_disconnect_evt = Event()
self.klippy_connection.close()
timeout = time.time() + 2.
await self.klippy_disconnect_evt.wait(timeout)
self.klippy_disconnect_evt = None
except Exception:
logging.exception("Klippy Disconnect Error")
# Sleep for 100ms to allow connected websockets
# to write out remaining data
await gen.sleep(.1)
try:
await self.moonraker_app.close()
except Exception:
logging.exception("Error Closing App")
self.exit_reason = exit_reason
aioloop = asyncio.get_event_loop()
aioloop.remove_signal_handler(signal.SIGTERM)
self.ioloop.stop()
async def _handle_server_restart(self, web_request):
@@ -445,10 +514,21 @@ class Server:
return "ok"
async def _handle_info_request(self, web_request):
file_manager = self.lookup_plugin('file_manager', None)
reg_dirs = []
if file_manager is not None:
reg_dirs = file_manager.get_registered_dirs()
return {
'klippy_connected': self.klippy_connection.is_connected(),
'klippy_state': self.klippy_state,
'plugins': list(self.plugins.keys())}
'plugins': list(self.plugins.keys()),
'failed_plugins': self.failed_plugins,
'registered_directories': reg_dirs}
async def _handle_config_request(self, web_request):
return {
'config': self.config.get_parsed_config()
}
class KlippyConnection:
def __init__(self, on_recd, on_close):
@@ -551,14 +631,21 @@ def main():
parser.add_argument(
"-l", "--logfile", default="/tmp/moonraker.log", metavar='<logfile>',
help="log file name and location")
parser.add_argument(
"-n", "--nologfile", action='store_true',
help="disable logging to a file")
system_args = parser.parse_args()
# Setup Logging
version = utils.get_software_version()
log_file = os.path.normpath(os.path.expanduser(system_args.logfile))
if system_args.nologfile:
log_file = ""
else:
log_file = os.path.normpath(os.path.expanduser(
system_args.logfile))
system_args.logfile = log_file
system_args.software_version = version
ql = utils.setup_logging(log_file, version)
ql, file_logger = utils.setup_logging(log_file, version)
if sys.version_info < (3, 7):
msg = f"Moonraker requires Python 3.7 or above. " \
@@ -573,7 +660,7 @@ def main():
estatus = 0
while True:
try:
server = Server(system_args)
server = Server(system_args, file_logger)
except Exception:
logging.exception("Moonraker Error")
estatus = 1
@@ -585,6 +672,8 @@ def main():
logging.exception("Server Running Error")
estatus = 1
break
if server.exit_reason == "terminate":
break
# Since we are running outside of the the server
# it is ok to use a blocking sleep here
time.sleep(.5)
+34 -17
View File
@@ -9,17 +9,16 @@ from collections import deque
from tornado.ioloop import IOLoop, PeriodicCallback
TEMPERATURE_UPDATE_MS = 1000
TEMPERATURE_STORE_SIZE = 20 * 60
MAX_GCODE_LINES = 1000
class DataStore:
def __init__(self, config):
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=MAX_GCODE_LINES)
self.gcode_queue = deque(maxlen=self.gcode_store_size)
self.temperature_store = {}
self.temp_update_cb = PeriodicCallback(
self._update_temperature_store, TEMPERATURE_UPDATE_MS)
@@ -61,14 +60,18 @@ class DataStore:
logging.info(f"Configuring available sensors: {sensors}")
new_store = {}
for sensor in sensors:
fields = list(status.get(sensor, {}).keys())
if sensor in self.temperature_store:
new_store[sensor] = self.temperature_store[sensor]
else:
new_store[sensor] = {
'temperatures': deque(maxlen=TEMPERATURE_STORE_SIZE),
'targets': deque(maxlen=TEMPERATURE_STORE_SIZE)}
'temperatures': deque(maxlen=self.temp_store_size)}
for item in ["target", "power", "speed"]:
if item in fields:
new_store[sensor][f"{item}s"] = deque(
maxlen=self.temp_store_size)
if sensor not in self.last_temps:
self.last_temps[sensor] = (0., 0.)
self.last_temps[sensor] = (0., 0., 0., 0.)
self.temperature_store = new_store
# Prune unconfigured sensors in self.last_temps
for sensor in list(self.last_temps.keys()):
@@ -86,17 +89,21 @@ class DataStore:
def _set_current_temps(self, data):
for sensor in self.temperature_store:
if sensor in data:
last_temp, last_target = self.last_temps[sensor]
last_val = self.last_temps[sensor]
self.last_temps[sensor] = (
round(data[sensor].get('temperature', last_temp), 2),
data[sensor].get('target', last_target))
round(data[sensor].get('temperature', last_val[0]), 2),
data[sensor].get('target', last_val[1]),
data[sensor].get('power', last_val[2]),
data[sensor].get('speed', last_val[3]))
def _update_temperature_store(self):
# XXX - If klippy is not connected, set values to zero
# as they are unknown?
for sensor, (temp, target) in self.last_temps.items():
self.temperature_store[sensor]['temperatures'].append(temp)
self.temperature_store[sensor]['targets'].append(target)
for sensor, vals in self.last_temps.items():
self.temperature_store[sensor]['temperatures'].append(vals[0])
for val, item in zip(vals[1:], ["targets", "powers", "speeds"]):
if item in self.temperature_store[sensor]:
self.temperature_store[sensor][item].append(val)
async def _handle_temp_store_request(self, web_request):
store = {}
@@ -109,15 +116,25 @@ class DataStore:
def _update_gcode_store(self, response):
curtime = time.time()
self.gcode_queue.append({'message': response, 'time': curtime})
self.gcode_queue.append(
{'message': response, 'time': curtime, 'type': "response"})
def store_gcode_command(self, script):
curtime = time.time()
for cmd in script.split('\n'):
cmd = cmd.strip()
if not cmd:
continue
self.gcode_queue.append(
{'message': script, 'time': curtime, 'type': "command"})
async def _handle_gcode_store_request(self, web_request):
count = web_request.get_int("count", None)
if count is not None:
res = list(self.gcode_queue)[-count:]
gc_responses = list(self.gcode_queue)[-count:]
else:
res = list(self.gcode_queue)
return {'gcode_store': res}
gc_responses = list(self.gcode_queue)
return {'gcode_store': gc_responses}
def load_plugin(config):
return DataStore(config)
+389
View File
@@ -0,0 +1,389 @@
# Mimimal database for moonraker storage
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import os
import json
import struct
import operator
import logging
from io import BytesIO
from functools import reduce
import lmdb
DATABASE_VERSION = 1
MAX_NAMESPACES = 50
MAX_DB_SIZE = 200 * 2**20
RECORD_ENCODE_FUNCS = {
int: lambda x: b"q" + struct.pack("q", x),
float: lambda x: b"d" + struct.pack("d", x),
bool: lambda x: b"?" + struct.pack("?", x),
str: lambda x: b"s" + x.encode(),
list: lambda x: json.dumps(x).encode(),
dict: lambda x: json.dumps(x).encode(),
}
RECORD_DECODE_FUNCS = {
ord("q"): lambda x: struct.unpack("q", x[1:])[0],
ord("d"): lambda x: struct.unpack("d", x[1:])[0],
ord("?"): lambda x: struct.unpack("?", x[1:])[0],
ord("s"): lambda x: bytes(x[1:]).decode(),
ord("["): lambda x: json.load(BytesIO(x)),
ord("{"): lambda x: json.load(BytesIO(x)),
}
def getitem_with_default(item, field):
if field not in item:
item[field] = {}
return item[field]
class Sentinel:
pass
class MoonrakerDatabase:
def __init__(self, config):
self.server = config.get_server()
self.namespaces = {}
self.protected_namespaces = {"moonraker"}
self.database_path = os.path.expanduser(config.get(
'database_path', "~/.moonraker_database"))
if not os.path.isdir(self.database_path):
os.mkdir(self.database_path)
self.lmdb_env = lmdb.open(self.database_path, map_size=MAX_DB_SIZE,
max_dbs=MAX_NAMESPACES)
with self.lmdb_env.begin(write=True, buffers=True) as txn:
# lookup existing namespaces
cursor = txn.cursor()
remaining = cursor.first()
while remaining:
key = bytes(cursor.key())
self.namespaces[key.decode()] = self.lmdb_env.open_db(key, txn)
remaining = cursor.next()
cursor.close()
if "moonraker" not in self.namespaces:
mrdb = self.lmdb_env.open_db(b"moonraker", txn)
self.namespaces["moonraker"] = mrdb
txn.put(b'database_version',
self._encode_value(DATABASE_VERSION),
db=mrdb)
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):
key_list = self._process_key(key)
if namespace not in self.namespaces:
self.namespaces[namespace] = self.lmdb_env.open_db(
namespace.encode())
record = value
if len(key_list) > 1:
record = self._get_record(namespace, key_list[0], force=True)
if not isinstance(record, dict):
record = {}
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[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):
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:
record = value
else:
try:
item = reduce(operator.getitem, key_list[1:-1], record)
except Exception:
raise self.server.error(
f"Key '{key}' in namespace '{namespace}' not found", 404)
if isinstance(item[key_list[-1]], dict) \
and isinstance(value, dict):
item[key_list[-1]].update(value)
else:
item[key_list[-1]] = value
if not self._insert_record(namespace, key_list[0], record):
logging.info(
f"Error updating key '{key}' in namespace '{namespace}'")
def delete_item(self, namespace, key, drop_empty_db=False):
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)
val = item.pop(key_list[-1])
except Exception:
raise self.server.error(
f"Key '{key}' in namespace '{namespace}' not found", 404)
remove_record = False if record else True
if remove_record:
db = self.namespaces[namespace]
with self.lmdb_env.begin(write=True, buffers=True, db=db) as txn:
ret = txn.delete(key_list[0].encode())
cursor = txn.cursor()
if not cursor.first() and drop_empty_db:
txn.drop(db)
del self.namespaces[namespace]
else:
ret = self._insert_record(namespace, key_list[0], record)
if not ret:
logging.info(
f"Error deleting key '{key}' from namespace '{namespace}'")
return val
def get_item(self, namespace, key=None, default=Sentinel):
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)
except Exception:
if default != Sentinel:
return default
raise self.server.error(
f"Key '{key}' in namespace '{namespace}' not found", 404)
return val
def ns_length(self, namespace):
return len(self.ns_keys(namespace))
def ns_keys(self, namespace):
keys = []
db = self.namespaces[namespace]
with self.lmdb_env.begin(db=db) as txn:
cursor = txn.cursor()
remaining = cursor.first()
while remaining:
keys.append(cursor.key().decode())
remaining = cursor.next()
return keys
def ns_values(self, namespace):
ns = self._get_namespace(namespace)
return ns.values()
def ns_items(self, namespace):
ns = self._get_namespace(namespace)
return ns.items()
def ns_contains(self, namespace, key):
try:
key_list = self._process_key(key)
if len(key_list) == 1:
return key_list[0] in self.ns_keys(namespace)
ns = self._get_namespace(namespace)
reduce(operator.getitem, key_list[1:], ns)
except Exception:
return False
return True
def register_local_namespace(self, namespace):
if namespace not in self.namespaces:
self.namespaces[namespace] = self.lmdb_env.open_db(
namespace.encode())
self.protected_namespaces.add(namespace)
def wrap_namespace(self, namespace, parse_keys=True):
if namespace not in self.namespaces:
raise self.server.error(
f"Namespace '{namespace}' not found", 404)
self.protected_namespaces.add(namespace)
return NamespaceWrapper(namespace, self, parse_keys)
def _process_key(self, key):
try:
key_list = key if isinstance(key, list) else key.split('.')
except Exception:
key_list = []
if not key_list or "" in key_list:
raise self.server.error(f"Invalid Key Format: '{key}'")
return key_list
def _insert_record(self, namespace, key, val):
db = self.namespaces[namespace]
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):
if namespace not in self.namespaces:
raise self.server.error(
f"Namespace '{namespace}' not found", 404)
db = self.namespaces[namespace]
with self.lmdb_env.begin(buffers=True, db=db) as txn:
value = txn.get(key.encode())
if value is None:
if force:
return {}
raise self.server.error(
f"Key '{key}' in namespace '{namespace}' not found", 404)
return self._decode_value(value)
def _get_namespace(self, namespace):
if namespace not in self.namespaces:
raise self.server.error(
f"Invalid database namespace '{namespace}'")
db = self.namespaces[namespace]
result = {}
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()
result[k] = self._decode_value(value)
return result
def _encode_value(self, value):
try:
enc_func = RECORD_ENCODE_FUNCS[type(value)]
return enc_func(value)
except Exception:
raise self.server.error(
f"Error encoding val: {value}, type: {type(value)}")
def _decode_value(self, bvalue):
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)}")
async def _handle_list_request(self, web_request):
return {'namespaces': list(self.namespaces.keys())}
async def _handle_item_request(self, web_request):
action = web_request.get_action()
namespace = web_request.get_str("namespace").lower()
if action != "GET":
if namespace in self.protected_namespaces:
raise self.server.error(
f"Namespace '{namespace}' is write protected")
key = web_request.get("key")
valid_types = (list, str)
else:
key = web_request.get("key", None)
valid_types = (list, str, type(None))
if not isinstance(key, valid_types):
raise self.server.error(
"Value for argument 'key' is an invalid type: "
f"{type(key).__name__}")
if isinstance(key, str):
key = key.lower()
if action == "GET":
val = self.get_item(namespace, key)
elif action == "POST":
val = web_request.get("value")
self.insert_item(namespace, key, val)
elif action == "DELETE":
val = self.delete_item(namespace, key, drop_empty_db=True)
return {'namespace': namespace, 'key': key, 'value': val}
def close(self):
# log db stats
msg = ""
with self.lmdb_env.begin() as txn:
for db_name, db in self.namespaces.items():
stats = txn.stat(db)
msg += f"\n{db_name}:"
msg += "\n".join([f"{k}: {v}" for k, v in stats.items()])
logging.info(f"Database statistics:\n{msg}")
self.lmdb_env.close()
class NamespaceWrapper:
def __init__(self, namespace, database, parse_keys):
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):
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):
if isinstance(key, str) and not self.parse_keys:
key = [key]
self.db.update_item(self.namespace, key, value)
def update(self, value):
val_keys = set(value.keys())
new_keys = val_keys - set(self.keys())
update_keys = val_keys - new_keys
for key in update_keys:
self.update_child([key], value[key])
for key in new_keys:
self.insert([key], value[key])
def get(self, key, default=None):
if isinstance(key, str) and not self.parse_keys:
key = [key]
return self.db.get_item(self.namespace, key, default)
def delete(self, key):
if isinstance(key, str) and not self.parse_keys:
key = [key]
self.db.delete_item(self.namespace, key)
def __len__(self):
return self.db.ns_length(self.namespace)
def __getitem__(self, key):
return self.get(key, default=Sentinel)
def __setitem__(self, key, value):
self.insert(key, value)
def __delitem__(self, key):
self.delete(key)
def __contains__(self, key):
if isinstance(key, str) and not self.parse_keys:
key = [key]
return self.db.ns_contains(self.namespace, key)
def keys(self):
return self.db.ns_keys(self.namespace)
def values(self):
return self.db.ns_values(self.namespace)
def items(self):
return self.db.ns_items(self.namespace)
def pop(self, key, default=Sentinel):
try:
val = self.delete(key)
except Exception:
if default == Sentinel:
raise
val = default
return val
def clear(self):
keys = self.keys()
for k in keys:
try:
self.delete([k])
except Exception:
pass
def load_plugin(config):
return MoonrakerDatabase(config)
+242 -183
View File
@@ -6,24 +6,29 @@
import os
import sys
import shutil
import io
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']
VALID_GCODE_EXTS = ['.gcode', '.g', '.gco', '.ufp']
FULL_ACCESS_ROOTS = ["gcodes", "config"]
ETC_DIR = "/etc/moonraker"
METADATA_SCRIPT = os.path.normpath(os.path.join(
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 = {}
self.gcode_metadata = MetadataStorage(self.server)
database = self.server.load_plugin(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
@@ -41,6 +46,9 @@ class FileManager:
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")
@@ -56,6 +64,10 @@ class FileManager:
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
@@ -78,26 +90,38 @@ class FileManager:
# Register log path
log_file = paths.get('log_file')
log_path = os.path.normpath(os.path.expanduser(log_file))
self.server.register_static_file_handler("klippy.log", log_path)
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
home = os.path.expanduser('~')
path = os.path.normpath(os.path.expanduser(path))
if not os.path.isdir(path) or path == home or \
not (path.startswith(home) or path.startswith(ETC_DIR)):
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}) not valid. Please\n"
"check that the path exists and is a subfolder in the HOME\n"
"directory. Note that the path may not BE the home directory.")
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":
# scan metadata
database = self.server.lookup_plugin(
"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")
@@ -109,6 +133,9 @@ class FileManager:
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)
@@ -132,18 +159,7 @@ class FileManager:
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)
# Check to see if a filelist update is necessary
for f in dir_info['files']:
fname = os.path.join(rel_path, f['filename'])
ext = os.path.splitext(f['filename'])[-1].lower()
if root != 'gcodes' or ext not in VALID_GCODE_EXTS:
continue
self.gcode_metadata.parse_metadata(
fname, f['size'], f['modified'], notify=True)
metadata = self.gcode_metadata.get(fname, None)
if metadata is not None and is_extended:
f.update(metadata)
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
@@ -265,20 +281,45 @@ class FileManager:
{'path': src_rel_path, 'root': source_root})
return "ok"
def _list_directory(self, path):
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):
@@ -287,31 +328,76 @@ class FileManager:
path_info = {'modified': modified, 'size': size}
return path_info
async def process_file_upload(self, request):
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
root = self._get_argument(request, 'root', "gcodes")
if root == "gcodes":
result = await self._do_gcode_upload(request)
elif root in FULL_ACCESS_ROOTS:
result = self._do_standard_upload(request, root)
else:
raise self.server.error(f"Invalid root request: {root}")
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
async def _do_gcode_upload(self, request):
start_print = print_ongoing = False
root_path = self.file_paths.get("gcodes", "")
if not root_path:
raise self.server.error("Gcodes root not available")
start_print = self._get_argument(request, 'print', "false") == "true"
upload = self._get_upload_info(request, root_path)
fparts = os.path.splitext(upload['full_path'])
is_ufp = fparts[-1].lower() == ".ufp"
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['full_path']
if is_ufp:
check_path = fparts[0] + ".gcode"
check_path = upload_info['dest_path']
print_ongoing = await self._handle_operation_check(
check_path)
except self.server.error as e:
@@ -324,120 +410,84 @@ class FileManager:
start_print = False
# Don't start if another print is currently in progress
start_print = start_print and not print_ongoing
self._write_file(upload, is_ufp)
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['full_path'])
finfo = self._get_path_info(upload_info['dest_path'])
evt = self.gcode_metadata.parse_metadata(
upload['filename'], finfo['size'], finfo['modified'])
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_plugin('klippy_apis')
try:
await klippy_apis.start_print(upload['filename'])
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['filename'], "gcodes")
return {'result': upload['filename'], 'print_started': start_print}
def _do_standard_upload(self, request, root):
path = self.file_paths.get(root, None)
if path is None:
raise self.server.error(f"Unknown root path: {root}")
upload = self._get_upload_info(request, path)
self._write_file(upload)
self.notify_filelist_changed('upload_file', upload['filename'], root)
return {'result': upload['filename']}
def _get_argument(self, request, name, default=None):
args = request.arguments.get(name, None)
if args is not None:
return args[0].decode().strip()
return default
def _get_upload_info(self, request, root_path):
# check relative path
dir_path = self._get_argument(request, 'path', "")
# fetch the upload from the request
if len(request.files) != 1:
raise self.server.error(
"Bad Request, can only process a single file upload")
f_list = list(request.files.values())[0]
if len(f_list) != 1:
raise self.server.error(
"Bad Request, can only process a single file upload")
upload = f_list[0]
if os.path.isfile(root_path):
filename = os.path.basename(root_path)
full_path = root_path
dir_path = ""
else:
filename = upload['filename'].strip().lstrip("/")
if dir_path:
filename = os.path.join(dir_path, filename)
full_path = os.path.normpath(os.path.join(root_path, filename))
# Validate the path. Don't allow uploads to a parent of the root
if not full_path.startswith(root_path):
raise self.server.error(
f"Cannot write to path: {full_path}")
'upload_file', upload_info['filename'], "gcodes")
return {
'filename': filename,
'body': upload['body'],
'dir_path': dir_path,
'full_path': full_path}
'result': upload_info['filename'],
'print_started': start_print
}
def _write_file(self, upload, unzip_ufp=False):
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['dir_path']:
if upload_info['dir_path']:
os.makedirs(os.path.dirname(
upload['full_path']), exist_ok=True)
if unzip_ufp:
self._unzip_ufp(upload)
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:
with open(upload['full_path'], 'wb') as fh:
fh.write(upload['body'])
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 by GitHub user @cdkeito
def _unzip_ufp(self, upload):
base_name = os.path.splitext(
os.path.basename(upload['filename']))[0]
working_dir = os.path.dirname(upload['full_path'])
thumb_dir = os.path.join(working_dir, "thumbs")
ufp_bytes = io.BytesIO(upload['body'])
gc_bytes = img_bytes = None
with zipfile.ZipFile(ufp_bytes) as zf:
gc_bytes = zf.read("/3D/model.gcode")
# 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:
img_bytes = zf.read("/Metadata/thumbnail.png")
os.remove(ufp_path)
except Exception:
img_bytes = None
if gc_bytes is not None:
gc_name = base_name + ".gcode"
gc_path = os.path.join(working_dir, gc_name)
with open(gc_path, "wb") as gc_file:
gc_file.write(gc_bytes)
# update upload file name to extracted gcode file
upload['full_path'] = gc_path
upload['filename'] = os.path.join(
os.path.dirname(upload['filename']), gc_name)
else:
raise self.server.error(
f"UFP file {upload['filename']} does not "
"contain a gcode file")
if img_bytes is not None:
thumb_name = base_name + ".png"
thumb_path = os.path.join(thumb_dir, thumb_name)
try:
if not os.path.exists(thumb_dir):
os.mkdir(thumb_dir)
with open(thumb_path, "wb") as thumb_file:
thumb_file.write(img_bytes)
except Exception:
logging.exception("Unable to write Image")
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
@@ -448,12 +498,30 @@ class FileManager:
logging.info(msg)
raise self.server.error(msg)
logging.info(f"Updating File List <{root}>...")
for root_path, dirs, files in os.walk(path, followlinks=True):
st = os.stat(path)
visited_dirs = {(st.st_dev, st.st_ino)}
for dir_path, dir_names, files in os.walk(path, followlinks=True):
scan_dirs = []
# Filter out directories that have already been visted. This
# prevents infinite recrusion "followlinks" is set to True
for dname in dir_names:
st = os.stat(os.path.join(dir_path, dname))
key = (st.st_dev, st.st_ino)
if key not in visited_dirs:
visited_dirs.add(key)
scan_dirs.append(dname)
dir_names[:] = scan_dirs
for name in files:
ext = os.path.splitext(name)[-1].lower()
if root == 'gcodes' and ext not in VALID_GCODE_EXTS:
continue
full_path = os.path.join(root_path, name)
full_path = os.path.join(dir_path, name)
if ext == ".ufp":
try:
full_path = self._process_ufp_from_refresh(full_path)
except Exception:
logging.exception("Error processing ufp file")
continue
fname = full_path[len(path) + 1:]
finfo = self._get_path_info(full_path)
filelist[fname] = finfo
@@ -478,12 +546,10 @@ class FileManager:
if filename.startswith('gcodes/'):
filename = filename[7:]
flist = self.get_file_list("gcodes")
return self.gcode_metadata.get(filename, flist.get(filename, {}))
return self.gcode_metadata.get(filename, {})
def list_dir(self, directory, simple_format=False):
# List a directory relative to its root. Currently the only
# Supported root is "gcodes"
# List a directory relative to its root.
if directory[0] == "/":
directory = directory[1:]
parts = directory.split("/", 1)
@@ -555,23 +621,25 @@ class FileManager:
METADATA_PRUNE_TIME = 600000
METADATA_NAMESPACE = "gcode_metadata"
class MetadataStorage:
def __init__(self, server):
def __init__(self, server, gc_path, database):
self.server = server
self.metadata = {}
database.register_local_namespace(METADATA_NAMESPACE)
self.mddb = database.wrap_namespace(
METADATA_NAMESPACE, parse_keys=False)
self.pending_requests = {}
self.events = {}
self.script_response = None
self.busy = False
self.gc_path = os.path.expanduser("~")
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.metadata = {}
self.mddb.clear()
self.gc_path = path
if not self.prune_cb.is_running():
self.prune_cb.start()
@@ -580,40 +648,28 @@ class MetadataStorage:
self.prune_cb.stop()
def get(self, key, default=None):
if key not in self.metadata:
return default
return dict(self.metadata[key])
return self.mddb.get(key, default)
def __getitem__(self, key):
return dict(self.metadata[key])
def _handle_script_response(self, result):
try:
proc_resp = json.loads(result.strip())
except Exception:
logging.exception("file_manager: unable to load metadata")
logging.debug(result)
return
proc_log = proc_resp.get('log', [])
for log_msg in proc_log:
logging.info(log_msg)
if 'file' in proc_resp:
self.script_response = proc_resp
return self.mddb[key]
def prune_metadata(self):
for fname in list(self.metadata.keys()):
for fname in list(self.mddb.keys()):
fpath = os.path.join(self.gc_path, fname)
if not os.path.exists(fpath):
del self.metadata[fname]
del self.mddb[fname]
logging.info(f"Pruned file: {fname}")
continue
def _has_valid_data(self, fname, fsize, modified):
mdata = self.metadata.get(fname, {'size': "", 'modified': 0})
mdata = self.mddb.get(fname, {'size': "", 'modified': 0})
return mdata['size'] == fsize and mdata['modified'] == modified
def remove_file(self, fname):
self.metadata.pop(fname)
try:
del self.mddb[fname]
except Exception:
pass
def parse_metadata(self, fname, fsize, modified, notify=False):
evt = Event()
@@ -646,7 +702,7 @@ class MetadataStorage:
else:
break
else:
self.metadata[fname] = {'size': fsize, 'modified': modified}
self.mddb[fname] = {'size': fsize, 'modified': modified}
logging.info(
f"Unable to extract medatadata from file: {fname}")
evt.set()
@@ -659,18 +715,21 @@ class MetadataStorage:
cmd = " ".join([sys.executable, METADATA_SCRIPT, "-p",
self.gc_path, "-f", f"\"{filename}\""])
shell_command = self.server.lookup_plugin('shell_command')
scmd = shell_command.build_shell_command(
cmd, self._handle_script_response)
self.script_response = None
await scmd.run(timeout=4.)
if self.script_response is None:
raise self.server.error("Unable to extract metadata")
path = self.script_response['file']
metadata = self.script_response['metadata']
scmd = shell_command.build_shell_command(cmd, log_stderr=True)
result = await scmd.run_with_response(timeout=10.)
if result is None:
raise self.server.error(f"Metadata extraction error")
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")
self.metadata[path] = dict(metadata)
self.mddb[path] = dict(metadata)
metadata['filename'] = path
if notify:
self.server.send_event(
+24 -8
View File
@@ -6,6 +6,8 @@
import logging
from tornado.ioloop import IOLoop
ALLOWED_SERVICES = ["moonraker", "klipper", "webcamd"]
class Machine:
def __init__(self, config):
self.server = config.get_server()
@@ -15,7 +17,13 @@ class Machine:
"/machine/shutdown", ['POST'], self._handle_machine_request)
self.server.register_endpoint(
"/machine/services/restart", ['POST'],
self._handle_service_restart)
self._handle_service_request)
self.server.register_endpoint(
"/machine/services/stop", ['POST'],
self._handle_service_request)
self.server.register_endpoint(
"/machine/services/start", ['POST'],
self._handle_service_request)
# Register remote methods
self.server.register_remote_method(
@@ -39,15 +47,23 @@ class Machine:
async def reboot_machine(self):
await self._execute_cmd("sudo shutdown -r now")
async def _handle_service_restart(self, web_request):
name = web_request.get('service')
if name == "klipper":
await self._execute_cmd(f'sudo systemctl restart {name}')
elif name == "moonraker":
async def do_service_action(self, action, service_name):
await self._execute_cmd(
f'sudo systemctl {action} {service_name}')
async def _handle_service_request(self, web_request):
name = web_request.get('service').lower()
action = web_request.get_endpoint().split('/')[-1]
if name == "moonraker":
if action != "restart":
raise self.server.error(
f"Service action '{action}' not available for moonraker")
IOLoop.current().spawn_callback(
self._execute_cmd, f'sudo systemctl restart {name}')
self.do_service_action, action, name)
elif name in ALLOWED_SERVICES:
await self.do_service_action(action, name)
else:
raise self.sever.error(
raise self.server.error(
f"Invalid argument recevied for 'name': {name}")
return "ok"
+278
View File
@@ -0,0 +1,278 @@
# Octoprint API compatibility
#
# Copyright (C) 2021 Nickolas Grigoriadis <nagrigoriadis@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import logging
import utils
OCTO_VERSION = '1.5.0'
class OctoprintCompat:
"""
Minimal implementation of the REST API as described here:
https://docs.octoprint.org/en/master/api/index.html
So that Cura Octoprint plugin will function for:
* Handshake
* Upload gcode/ufp
* Webcam config
* Manual GCode submission
* Heater temperatures
"""
def __init__(self, config):
self.server = config.get_server()
self.software_version = config['system_args'].get('software_version')
# Local variables
self.klippy_apis = None
self.heaters = []
# Register status update event
self.server.register_event_handler(
'server:klippy_ready', self._init)
# Version & Server information
self.server.register_endpoint(
'/api/version', ['GET'], self._get_version, wrap_result=False)
self.server.register_endpoint(
'/api/server', ['GET'], self._get_server, wrap_result=False)
# Login, User & Settings
self.server.register_endpoint(
'/api/login', ['POST'], self._post_login_user, wrap_result=False)
self.server.register_endpoint(
'/api/currentuser', ['GET'], self._post_login_user,
wrap_result=False)
self.server.register_endpoint(
'/api/settings', ['GET'], self._get_settings, wrap_result=False)
# File operations
# Note that file upload is handled in file_manager.py
# TODO: List/info/select/delete files
# Job operations
self.server.register_endpoint(
'/api/job', ['GET'], self._get_job, wrap_result=False)
# TODO: start/cancel/restart/pause jobs
# Printer operations
self.server.register_endpoint(
'/api/printer', ['GET'], self._get_printer, wrap_result=False)
self.server.register_endpoint(
'/api/printer/command', ['POST'], self._post_command,
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)
# System
# TODO: shutdown/reboot/restart operations
async def _init(self):
self.klippy_apis = self.server.lookup_plugin('klippy_apis')
# Fetch heaters
try:
result = await self.klippy_apis.query_objects({'heaters': None})
except self.server.error as e:
logging.info(f'Error Configuring heaters: {e}')
return
self.heaters = result.get('heaters', {}).get('available_sensors', [])
async def printer_state(self):
if not self.klippy_apis:
return 'Offline'
if self.server.klippy_state != 'ready':
return 'Error'
result = await self.klippy_apis.query_objects({'print_stats': None})
return {
'standby': 'Operational',
'printing': 'Printing',
'paused': 'Paused',
'complete': 'Operational'
}.get(result.get('state', 'standby'), 'Error')
async def printer_temps(self):
temps = {}
if not self.klippy_apis:
return temps
if self.heaters:
result = await self.klippy_apis.query_objects(
{heater: None for heater in self.heaters})
for heater in self.heaters:
data = result[heater]
name = 'bed'
if heater.startswith('extruder'):
try:
tool_no = int(heater[8:])
except ValueError:
tool_no = 0
name = f'tool{tool_no}'
temps[name] = {
'actual': int(data['temperature'] * 100.0) / 100.0,
'offset': 0,
'target': data['target'],
}
return temps
async def _get_version(self, web_request):
"""
Version information
"""
return {
'server': OCTO_VERSION,
'api': '0.1',
'text': f'OctoPrint (Moonraker {self.software_version})',
}
async def _get_server(self, web_request):
"""
Server status
"""
return {
'server': OCTO_VERSION,
'safemode': (
None if self.server.klippy_state == 'ready' else 'settings')
}
async def _post_login_user(self, web_request):
"""
Confirm session login.
Since we only support apikey auth, do nothing.
Report hardcoded user called _api
"""
return {
'_is_external_client': False,
'_login_mechanism': 'apikey',
'name': '_api',
'active': True,
'user': True,
'admin': True,
'apikey': None,
'permissions': [],
'groups': ['admins', 'users'],
}
async def _get_settings(self, web_request):
"""
Used to parse Octoprint capabilities
Hardcode capabilities to be basically there and use default
fluid/mainsail webcam path.
"""
return {
'plugins': {
'UltimakerFormatPackage': {
'align_inline_thumbnail': False,
'inline_thumbnail': False,
'inline_thumbnail_align_value': 'left',
'inline_thumbnail_scale_value': '50',
'installed': True,
'installed_version': '0.2.2',
'scale_inline_thumbnail': False,
'state_panel_thumbnail': True,
},
},
'feature': {
'sdSupport': False,
'temperatureGraph': False
},
# TODO: Get webcam settings from config file to allow user
# to customise this.
'webcam': {
'flipH': False,
'flipV': False,
'rotate90': False,
'streamUrl': '/webcam/?action=stream',
'webcamEnabled': True,
},
}
async def _get_job(self, web_request):
"""
Get current job status
"""
return {
'job': {
'file': {'name': None,},
'estimatedPrintTime': None,
'filament': {'length': None},
'user': None,
},
'progress': {
'completion': None,
'filepos': None,
'printTime': None,
'printTimeLeft': None,
'printTimeOrigin': None,
},
'state': await self.printer_state()
}
async def _get_printer(self, web_request):
"""
Get Printer status
"""
state = await self.printer_state()
return {
'temperature': await self.printer_temps(),
'state': {
'text': state,
'flags': {
'operational': state not in ['Error', 'Offline'],
'paused': state == 'Paused',
'printing': state == 'Printing',
'cancelling': state == 'Cancelling',
'pausing': False,
'error': state == 'Error',
'ready': state == 'Operational',
'closedOrError': state in ['Error', 'Offline'],
},
},
}
async def _post_command(self, web_request):
"""
Request to run some gcode command
"""
commands = web_request.get('commands', [])
for command in commands:
logging.info(f'Executing GCode: {command}')
try:
await self.klippy_apis.run_gcode(command)
except self.server.error:
msg = f"Error executing GCode {command}"
logging.exception(msg)
return {}
async def _get_printerprofiles(self, web_request):
"""
Get Printer profiles
"""
return {
'profiles': {
'_default': {
'id': '_default',
'name': 'Default',
'color': 'default',
'model': 'Default',
'default': True,
'current': True,
'heatedBed': 'heater_bed' in self.heaters,
'heatedChamber': 'chamber' in self.heaters,
}
}
}
def load_plugin(config):
return OctoprintCompat(config)
+13 -3
View File
@@ -122,6 +122,8 @@ class SerialConnection:
async def _do_send(self):
while self.send_buffer:
if not self.connected:
break
try:
sent = os.write(self.fd, self.send_buffer)
except os.error as e:
@@ -143,7 +145,6 @@ class PanelDue:
def __init__(self, config):
self.server = config.get_server()
self.ioloop = IOLoop.current()
self.ser_conn = SerialConnection(config, self)
self.file_manager = self.server.lookup_plugin('file_manager')
self.klippy_apis = self.server.lookup_plugin('klippy_apis')
self.kinematics = "none"
@@ -195,6 +196,7 @@ class PanelDue:
ntkeys = config.get('non_trivial_keys', "Klipper state")
self.non_trivial_keys = [k for k in ntkeys.split('\n') if k.strip()]
self.ser_conn = SerialConnection(config, self)
logging.info("PanelDue Configured")
# Register server events
@@ -362,12 +364,18 @@ class PanelDue:
# require special handling
parts = script.split()
cmd = parts[0].strip()
if cmd in ["M23", "M30", "M32", "M36", "M37", "M98"]:
arg = script[len(cmd):].strip()
parts = [cmd, arg]
# Check for commands that query state and require immediate response
if cmd in self.direct_gcodes:
params = {}
for p in parts[1:]:
arg = p[0].lower() if p[0].lower() in "psr" else "p"
if p[0] not in "PSR":
params["arg_p"] = p.strip(" \"\t\n")
continue
arg = p[0].lower()
try:
val = int(p[1:].strip()) if arg in "sr" \
else p[1:].strip(" \"\t\n")
@@ -376,7 +384,7 @@ class PanelDue:
self.handle_gcode_response("!! " + msg)
logging.exception(msg)
return
params["arg_" + arg] = val
params[f"arg_{arg}"] = val
func = self.direct_gcodes[cmd]
self.queue_command(func, **params)
return
@@ -743,6 +751,8 @@ class PanelDue:
# "gcodes/" root. The M20 HACK should add this in some cases.
# Ideally we would add support to the PanelDue firmware that
# indicates Moonraker supports a "gcodes" directory.
if filename[0] == "/":
filename = filename[1:]
if not filename.startswith("gcodes/"):
filename = "gcodes/" + filename
+174 -56
View File
@@ -20,6 +20,29 @@ from tornado.escape import json_decode
class PrinterPower:
def __init__(self, config):
self.server = config.get_server()
self.chip_factory = GpioChipFactory()
self.devices = {}
prefix_sections = config.get_prefix_sections("power")
logging.info(f"Power plugin loading devices: {prefix_sections}")
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)
else:
raise config.error(f"Unsupported Device Type: {dev_type}")
self.devices[dev.get_name()] = dev
except Exception:
self.chip_factory.close()
raise
self.server.register_endpoint(
"/machine/device_power/devices", ['GET'],
self._handle_list_devices)
@@ -34,24 +57,33 @@ class PrinterPower:
self._handle_power_request)
self.server.register_remote_method(
"set_device_power", self.set_device_power)
self.server.register_event_handler(
"server:klippy_shutdown", self._handle_klippy_shutdown)
self.server.register_notification("power:power_changed")
IOLoop.current().spawn_callback(
self._initalize_devices, list(self.devices.values()))
self.chip_factory = GpioChipFactory()
self.current_dev = None
self.devices = {}
prefix_sections = config.get_prefix_sections("power")
logging.info(f"Power plugin loading devices: {prefix_sections}")
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)
else:
raise config.error(f"Unsupported Device Type: {dev_type}")
self.devices[dev.get_name()] = dev
async def _check_klippy_printing(self):
klippy_apis = self.server.lookup_plugin('klippy_apis')
result = await klippy_apis.query_objects(
{'print_stats': None}, default={})
pstate = result.get('print_stats', {}).get('state', "").lower()
return pstate == "printing"
async def _initalize_devices(self, inital_devs):
for dev in inital_devs:
ret = dev.initialize()
if asyncio.iscoroutine(ret):
await ret
async def _handle_klippy_shutdown(self):
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")
async def _handle_list_devices(self, web_request):
dev_list = [d.get_device_info() for d in self.devices.values()]
@@ -75,11 +107,21 @@ class PrinterPower:
async def _process_request(self, device, req):
if req in ["on", "off"]:
cur_state = device.get_device_info()['status']
if req == cur_state:
# device is already in requested state, do nothing
return cur_state
printing = await self._check_klippy_printing()
if device.get_locked_while_printing() and printing:
raise self.server.error(
f"Unable to change power for {device.get_name()} "
"while printing")
ret = device.set_power(req)
if asyncio.iscoroutine(ret):
await ret
dev_info = device.get_device_info()
self.server.send_event("gpio_power:power_changed", dev_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):
@@ -125,6 +167,45 @@ class PrinterPower:
self.chip_factory.close()
class PowerDevice:
def __init__(self, config):
name_parts = config.get_name().split(maxsplit=1)
if len(name_parts) != 2:
raise config.error(f"Invalid Section Name: {config.get_name()}")
self.server = config.get_server()
self.name = name_parts[1]
self.state = "init"
self.locked_while_printing = config.getboolean(
'locked_while_printing', False)
self.off_when_shutdown = config.getboolean('off_when_shutdown', False)
self.restart_delay = 1.
self.klipper_restart = config.getboolean(
'restart_klipper_when_powered', False)
if self.klipper_restart:
self.restart_delay = config.getfloat('restart_delay', 1.)
if self.restart_delay < .000001:
raise config.error("Option 'restart_delay' must be above 0.0")
def get_name(self):
return self.name
def get_device_info(self):
return {
'device': self.name,
'status': self.state,
'locked_while_printing': self.locked_while_printing
}
def get_locked_while_printing(self):
return self.locked_while_printing
def run_power_changed_action(self):
if self.state == "on" and self.klipper_restart:
ioloop = IOLoop.current()
klippy_apis = self.server.lookup_plugin("klippy_apis")
ioloop.call_later(self.restart_delay, klippy_apis.do_restart,
"FIRMWARE_RESTART")
class GpioChipFactory:
def __init__(self):
self.chips = {}
@@ -140,13 +221,9 @@ class GpioChipFactory:
for chip in self.chips.values():
chip.close()
class GpioDevice:
class GpioDevice(PowerDevice):
def __init__(self, config, chip_factory):
name_parts = config.get_name().split(maxsplit=1)
if len(name_parts) != 2:
raise config.error(f"Invalid Section Name: {config.get_name()}")
self.name = name_parts[1]
self.state = "init"
super().__init__(config)
pin, chip_id, invert = self._parse_pin(config)
try:
chip = chip_factory.get_gpio_chip(chip_id)
@@ -164,8 +241,7 @@ class GpioDevice:
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")
initial_state = config.getboolean('initial_state', False)
self.set_power("on" if initial_state else "off")
self.initial_state = config.getboolean('initial_state', False)
def _parse_pin(self, config):
pin = cfg_pin = config.get("pin")
@@ -190,15 +266,11 @@ class GpioDevice:
return pin, chip_id, invert
def initialize(self):
pass
def get_name(self):
return self.name
self.set_power("on" if self.initial_state else "off")
def get_device_info(self):
return {
'device': self.name,
'status': self.state,
**super().get_device_info(),
'type': "gpio"
}
@@ -232,18 +304,13 @@ class GpioDevice:
# https://github.com/softScheck/tplink-smartplug
#
# Copyright 2016 softScheck GmbH
class TPLinkSmartPlug:
class TPLinkSmartPlug(PowerDevice):
START_KEY = 0xAB
def __init__(self, config):
super().__init__(config)
self.server = config.get_server()
self.addr = config.get("address")
self.port = config.getint("port", 9999)
name_parts = config.get_name().split(maxsplit=1)
if len(name_parts) != 2:
raise config.error(f"Invalid Section Name: {config.get_name()}")
self.name = name_parts[1]
self.state = "init"
IOLoop.current().spawn_callback(self.initialize)
async def _send_tplink_command(self, command):
out_cmd = {}
@@ -300,13 +367,9 @@ class TPLinkSmartPlug:
async def initialize(self):
await self.refresh_status()
def get_name(self):
return self.name
def get_device_info(self):
return {
'device': self.name,
'status': self.state,
**super().get_device_info(),
'type': "tplink_smartplug"
}
@@ -335,18 +398,13 @@ class TPLinkSmartPlug:
self.state = state
class Tasmota:
class Tasmota(PowerDevice):
def __init__(self, config):
super().__init__(config)
self.server = config.get_server()
self.addr = config.get("address")
self.output_id = config.getint("output_id", 1)
self.password = config.get("password", "")
name_parts = config.get_name().split(maxsplit=1)
if len(name_parts) != 2:
raise config.error(f"Invalid Section Name: {config.get_name()}")
self.name = name_parts[1]
self.state = "init"
IOLoop.current().spawn_callback(self.initialize)
async def _send_tasmota_command(self, command, password=None):
if command in ["on", "off"]:
@@ -372,13 +430,9 @@ class Tasmota:
async def initialize(self):
await self.refresh_status()
def get_name(self):
return self.name
def get_device_info(self):
return {
'device': self.name,
'status': self.state,
**super().get_device_info(),
'type': "tasmota"
}
@@ -404,6 +458,70 @@ class Tasmota:
raise self.server.error(msg) from None
self.state = state
class Shelly(PowerDevice):
def __init__(self, config):
super().__init__(config)
self.server = config.get_server()
self.addr = config.get("address")
self.output_id = config.getint("output_id", 0)
self.user = config.get("user", "admin")
self.password = config.get("password", "")
async def _send_shelly_command(self, command):
if command in ["on", "off"]:
out_cmd = f"relay/{self.output_id}?turn={command}"
elif command == "info":
out_cmd = f"relay/{self.output_id}"
else:
raise self.server.error(f"Invalid shelly 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}"
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
async def initialize(self):
await self.refresh_status()
def get_device_info(self):
return {
**super().get_device_info(),
'type': "shelly"
}
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"
# The power plugin has multiple configuration sections
def load_plugin_multi(config):
return PrinterPower(config)
+137
View File
@@ -0,0 +1,137 @@
# Moonraker Process Stat Tracking
#
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import time
import re
import os
import pathlib
import logging
from collections import deque
from tornado.ioloop import IOLoop, PeriodicCallback
VC_GEN_CMD_FILE = "/usr/bin/vcgencmd"
STATM_FILE_PATH = "/proc/self/smaps_rollup"
STAT_UPDATE_TIME_MS = 1000
REPORT_QUEUE_SIZE = 30
THROTTLE_CHECK_INTERVAL = 10
THROTTLED_FLAGS = {
1: "Under-Voltage Detected",
1 << 1: "Frequency Capped",
1 << 2: "Currently Throttled",
1 << 3: "Temperature Limit Active",
1 << 16: "Previously Under-Volted",
1 << 17: "Previously Frequency Capped",
1 << 18: "Previously Throttled",
1 << 19: "Previously Temperature Limited"
}
class ProcStats:
def __init__(self, config):
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
if os.path.exists(VC_GEN_CMD_FILE):
logging.info("Detected 'vcgencmd', throttle checking enabled")
shell_command = self.server.load_plugin(config, "shell_command")
self.vcgencmd = shell_command.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.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.last_update_time = time.time()
self.last_proc_time = time.process_time()
self.throttled = False
self.update_sequence = 0
self.stat_update_cb.start()
async def _handle_stat_request(self, web_request):
ts = None
if self.vcgencmd is not None:
ts = await self._check_throttled_state()
return {
'moonraker_stats': list(self.proc_stat_queue),
'throttled_state': ts
}
async def _handle_shutdown(self):
msg = "\nMoonraker System Usage Statistics:"
for stats in self.proc_stat_queue:
msg += f"\n{self._format_stats(stats)}"
logging.info(msg)
if self.vcgencmd is not None:
ts = await self._check_throttled_state()
logging.info(f"Throttled Flags: {' '.join(ts['flags'])}")
async def _handle_stat_update(self):
update_time = time.time()
proc_time = time.process_time()
time_diff = update_time - self.last_update_time
usage = round((proc_time - self.last_proc_time) / time_diff * 100, 2)
mem, mem_units = self._get_memory_usage()
self.proc_stat_queue.append({
"time": update_time,
"cpu_usage": usage,
"memory": mem,
"mem_units": mem_units
})
self.last_update_time = update_time
self.last_proc_time = proc_time
self.update_sequence += 1
if self.update_sequence == THROTTLE_CHECK_INTERVAL:
self.update_sequence = 0
if self.vcgencmd is not None:
ts = await self._check_throttled_state()
cur_throttled = ts['bits'] & 0xF
if cur_throttled and not self.throttled:
logging.info(
f"CPU Throttled State Detected: {ts['flags']}")
self.server.send_event("proc_stats:cpu_throttled", ts)
self.throttled = cur_throttled
async def _check_throttled_state(self):
try:
resp = await self.vcgencmd.run_with_response(
timeout=.5, quiet=True)
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):
try:
mem_data = self.smaps.read_text()
rss_match = re.search(r"Rss:\s+(\d+)\s+(\w+)", mem_data)
if rss_match is None:
return None, None
mem = int(rss_match.group(1))
units = rss_match.group(2)
except Exception:
return None, None
return mem, units
def _format_stats(self, stats):
return f"System Time: {stats['time']:2f}, " \
f"Usage: {stats['cpu_usage']}%, " \
f"Memory: {stats['memory']} {stats['mem_units']}"
def close(self):
self.stat_update_cb.stop()
def load_plugin(config):
return ProcStats(config)
+124 -68
View File
@@ -5,48 +5,81 @@
# This file may be distributed under the terms of the GNU GPLv3 license.
import os
import shlex
import subprocess
import logging
import tornado
import asyncio
from tornado import gen
from tornado.ioloop import IOLoop
class SCProcess(asyncio.subprocess.Process):
def initialize(self, cb, log_stderr, program):
self.callback = cb
self.log_stderr = log_stderr
self.program = program
self.partial_data = b""
async def _read_stream_with_cb(self, fd):
transport = self._transport.get_pipe_transport(fd)
if fd == 2:
stream = self.stderr
else:
assert fd == 1
stream = self.stdout
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}: {output.decode()}")
else:
output = output.rstrip(b'\n')
if output:
self.callback(output)
transport.close()
return output
def cancel(self):
self.stdout.feed_eof()
self.stderr.feed_eof()
self.terminate()
async def communicate_with_cb(self, input=None):
if input is not None:
stdin = self._feed_stdin(input)
else:
stdin = self._noop()
if self.stdout is not None:
stdout = self._read_stream_with_cb(1)
else:
stdout = self._noop()
if self.stderr is not None:
stderr = self._read_stream_with_cb(2)
else:
stderr = self._noop()
stdin, stdout, stderr = await asyncio.tasks.gather(
stdin, stdout, stderr, loop=self._loop)
await self.wait()
class ShellCommand:
def __init__(self, cmd, callback):
self.io_loop = IOLoop.current()
def __init__(self, cmd, callback, log_stderr=False):
self.name = cmd
self.output_cb = callback
cmd = os.path.expanduser(cmd)
self.command = shlex.split(cmd)
self.partial_output = b""
self.program = self.command[0]
self.log_stderr = log_stderr
self.proc = None
self.cancelled = False
self.return_code = None
def _process_output(self, fd, events):
if events & IOLoop.ERROR:
return
try:
data = os.read(fd, 4096)
except Exception:
return
data = self.partial_output + data
lines = data.split(b'\n')
self.partial_output = lines.pop()
for line in lines:
try:
self.output_cb(line)
except Exception:
logging.exception("Error writing command output")
def cancel(self):
self.cancelled = True
if self.proc is not None:
self.proc.cancel()
def get_return_code(self):
return self.return_code
async def run(self, timeout=2., verbose=True):
self.return_code = fd = None
self.partial_output = b""
self.return_code = self.proc = None
self.cancelled = False
if timeout is None:
# Never timeout
@@ -55,38 +88,74 @@ class ShellCommand:
# Fire and forget commands cannot be verbose as we can't
# clean up after the process terminates
verbose = False
if not await self._create_subprocess():
return False
if not timeout:
# fire and forget, return from execution
return True
try:
proc = subprocess.Popen(
self.command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
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
self.proc.terminate()
else:
complete = not self.cancelled
return self._check_proc_success(complete)
async def run_with_response(self, timeout=2., retries=1, quiet=False):
self.return_code = self.proc = None
self.cancelled = False
while retries > 0:
stdout = stderr = None
if await self._create_subprocess():
try:
ret = self.proc.communicate()
stdout, stderr = await asyncio.wait_for(
ret, timeout=timeout)
except asyncio.TimeoutError:
complete = False
self.proc.terminate()
else:
complete = not self.cancelled
if self.log_stderr and stderr:
logging.info(f"{self.program}: {stderr.decode()}")
if self._check_proc_success(complete, quiet):
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)
return None
async def _create_subprocess(self):
loop = asyncio.get_event_loop()
def protocol_factory():
return asyncio.subprocess.SubprocessStreamProtocol(
limit=2**20, loop=loop)
try:
errpipe = asyncio.subprocess.PIPE if self.log_stderr \
else asyncio.subprocess.STDOUT
transport, protocol = await loop.subprocess_exec(
protocol_factory, *self.command,
stdout=asyncio.subprocess.PIPE,
stderr=errpipe)
self.proc = SCProcess(transport, protocol, loop)
self.proc.initialize(self.output_cb, self.log_stderr, self.program)
except Exception:
logging.exception(
f"shell_command: Command ({self.name}) failed")
return False
if verbose:
fd = proc.stdout.fileno()
self.io_loop.add_handler(
fd, self._process_output, IOLoop.READ | IOLoop.ERROR)
elif not timeout:
# fire and forget, return from execution
return True
sleeptime = 0
complete = False
while sleeptime < timeout:
await gen.sleep(.05)
sleeptime += .05
if proc.poll() is not None:
complete = True
break
if self.cancelled:
break
if not complete:
proc.terminate()
if verbose:
if self.partial_output:
self.output_cb(self.partial_output)
self.partial_output = b""
self.io_loop.remove_handler(fd)
self.return_code = proc.returncode
return True
def _check_proc_success(self, complete, quiet=False):
self.return_code = self.proc.returncode
success = self.return_code == 0 and complete
if success:
msg = f"Command ({self.name}) successfully finished"
@@ -97,26 +166,13 @@ class ShellCommand:
else:
msg = f"Command ({self.name}) exited with return code" \
f" {self.return_code}"
logging.info(msg)
if not quiet:
logging.info(msg)
return success
async def run_with_response(self, timeout=2.):
result = []
def cb(data):
data = data.strip()
if data:
result.append(data.decode())
prev_cb = self.output_cb
self.output_cb = cb
await self.run(timeout)
self.output_cb = prev_cb
return "\n".join(result)
class ShellCommandFactory:
def build_shell_command(self, cmd, callback=None):
return ShellCommand(cmd, callback)
def build_shell_command(self, cmd, callback=None, log_stderr=False):
return ShellCommand(cmd, callback, log_stderr)
def load_plugin(config):
return ShellCommandFactory()
+332 -84
View File
@@ -4,6 +4,7 @@
#
# This file may be distributed under the terms of the GNU GPLv3 license.
import os
import glob
import re
import logging
import json
@@ -13,10 +14,11 @@ import zipfile
import io
import asyncio
import time
import tempfile
import tornado.gen
from tornado.ioloop import IOLoop
from tornado.ioloop import IOLoop, PeriodicCallback
from tornado.httpclient import AsyncHTTPClient
from tornado.locks import Event
from tornado.locks import Event, Condition, Lock
MOONRAKER_PATH = os.path.normpath(os.path.join(
os.path.dirname(__file__), "../.."))
@@ -25,39 +27,75 @@ SUPPLEMENTAL_CFG_PATH = os.path.join(
APT_CMD = "sudo DEBIAN_FRONTEND=noninteractive apt-get"
SUPPORTED_DISTROS = ["debian"]
# Check To see if Updates are necessary each hour
UPDATE_REFRESH_INTERVAL_MS = 3600000
# Perform auto refresh no sooner than 12 hours apart
MIN_REFRESH_TIME = 43200
# Perform auto refresh no later than 4am
MAX_PKG_UPDATE_HOUR = 4
class UpdateManager:
def __init__(self, config):
self.server = config.get_server()
self.config = config
self.config.read_supplemental_config(SUPPLEMENTAL_CFG_PATH)
AsyncHTTPClient.configure(None, defaults=dict(user_agent="Moonraker"))
self.http_client = AsyncHTTPClient()
self.repo_debug = config.getboolean('enable_repo_debug', False)
auto_refresh_enabled = config.getboolean('enable_auto_refresh', False)
self.distro = config.get('distro', "debian").lower()
if self.distro not in SUPPORTED_DISTROS:
raise config.error(f"Unsupported distro: {self.distro}")
if self.repo_debug:
logging.warn("UPDATE MANAGER: REPO DEBUG ENABLED")
env = sys.executable
mooncfg = self.config[f"update_manager static {self.distro} moonraker"]
self.updaters = {
"system": PackageUpdater(self),
"moonraker": GitUpdater(self, "moonraker", MOONRAKER_PATH, env)
"moonraker": GitUpdater(self, mooncfg, MOONRAKER_PATH, env)
}
self.current_update = None
# TODO: Check for client config in [update_manager]. This is
# deprecated and will be removed.
client_repo = config.get("client_repo", None)
if client_repo is not None:
client_path = os.path.expanduser(config.get("client_path"))
if os.path.islink(client_path):
raise config.error(
"Option 'client_path' cannot be set to a symbolic link")
self.updaters['client'] = ClientUpdater(
self, client_repo, client_path)
client_path = config.get("client_path")
name = client_repo.split("/")[-1]
self.updaters[name] = WebUpdater(
self, {'repo': client_repo, 'path': client_path})
client_sections = self.config.get_prefix_sections(
"update_manager client")
for section in client_sections:
cfg = self.config[section]
name = section.split()[-1]
if name in self.updaters:
raise config.error("Client repo named %s already added"
% (name,))
client_type = cfg.get("type")
if client_type == "git_repo":
self.updaters[name] = GitUpdater(self, cfg)
elif client_type == "web":
self.updaters[name] = WebUpdater(self, cfg)
else:
raise config.error("Invalid type '%s' for section [%s]"
% (client_type, section))
# GitHub API Rate Limit Tracking
self.gh_rate_limit = None
self.gh_limit_remaining = None
self.gh_limit_reset_time = None
self.gh_init_evt = Event()
self.cmd_request_lock = Lock()
self.is_refreshing = False
# Auto Status Refresh
self.last_auto_update_time = 0
self.refresh_cb = None
if auto_refresh_enabled:
self.refresh_cb = PeriodicCallback(
self._handle_auto_refresh, UPDATE_REFRESH_INTERVAL_MS)
self.refresh_cb.start()
AsyncHTTPClient.configure(None, defaults=dict(user_agent="Moonraker"))
self.http_client = AsyncHTTPClient()
self.server.register_endpoint(
"/machine/update/moonraker", ["POST"],
@@ -74,12 +112,27 @@ class UpdateManager:
self.server.register_endpoint(
"/machine/update/status", ["GET"],
self._handle_status_request)
self.server.register_notification("update_manager:update_response")
self.server.register_notification("update_manager:update_refreshed")
# Register Ready Event
self.server.register_event_handler(
"server:klippy_identified", self._set_klipper_repo)
# Initialize GitHub API Rate Limits
IOLoop.current().spawn_callback(self._init_api_rate_limit)
# Initialize GitHub API Rate Limits and configured updaters
IOLoop.current().spawn_callback(
self._initalize_updaters, list(self.updaters.values()))
async def _initalize_updaters(self, initial_updaters):
self.is_refreshing = True
await self._init_api_rate_limit()
for updater in initial_updaters:
if isinstance(updater, PackageUpdater):
ret = updater.refresh(False)
else:
ret = updater.refresh()
if asyncio.iscoroutine(ret):
await ret
self.is_refreshing = False
async def _set_klipper_repo(self):
kinfo = self.server.get_klippy_info()
@@ -93,36 +146,112 @@ class UpdateManager:
kupdater.env == env:
# Current Klipper Updater is valid
return
self.updaters['klipper'] = GitUpdater(self, "klipper", kpath, env)
kcfg = self.config[f"update_manager static {self.distro} klipper"]
self.updaters['klipper'] = GitUpdater(self, kcfg, kpath, env)
await self.updaters['klipper'].refresh()
async def _check_klippy_printing(self):
klippy_apis = self.server.lookup_plugin('klippy_apis')
result = await klippy_apis.query_objects(
{'print_stats': None}, default={})
pstate = result.get('print_stats', {}).get('state', "")
return pstate.lower() == "printing"
async def _handle_auto_refresh(self):
if await self._check_klippy_printing():
# Don't Refresh during a print
logging.info("Klippy is printing, auto refresh aborted")
return
cur_time = time.time()
cur_hour = time.localtime(cur_time).tm_hour
time_diff = cur_time - self.last_auto_update_time
# Update packages if it has been more than 12 hours
# and the local time is between 12AM and 5AM
if time_diff < MIN_REFRESH_TIME or cur_hour >= MAX_PKG_UPDATE_HOUR:
# Not within the update time window
return
self.last_auto_update_time = cur_time
vinfo = {}
need_refresh_all = not self.is_refreshing
async with self.cmd_request_lock:
self.is_refreshing = True
try:
for name, updater in list(self.updaters.items()):
if need_refresh_all:
ret = updater.refresh()
if asyncio.iscoroutine(ret):
await ret
if hasattr(updater, "get_update_status"):
vinfo[name] = updater.get_update_status()
except Exception:
logging.exception("Unable to Refresh Status")
return
finally:
self.is_refreshing = False
uinfo = {
'version_info': vinfo,
'github_rate_limit': self.gh_rate_limit,
'github_requests_remaining': self.gh_limit_remaining,
'github_limit_reset_time': self.gh_limit_reset_time,
'busy': self.current_update is not None}
self.server.send_event("update_manager:update_refreshed", uinfo)
async def _handle_update_request(self, web_request):
if await self._check_klippy_printing():
raise self.server.error("Update Refused: Klippy is printing")
app = web_request.get_endpoint().split("/")[-1]
if app == "client":
app = web_request.get('name')
inc_deps = web_request.get_boolean('include_deps', False)
if self.current_update:
raise self.server.error("A current update is in progress")
if self.current_update is not None and \
self.current_update[0] == app:
return f"Object {app} is currently being updated"
updater = self.updaters.get(app, None)
if updater is None:
raise self.server.error(f"Updater {app} not available")
self.current_update = (app, id(web_request))
try:
await updater.update(inc_deps)
except Exception:
self.current_update = None
raise
self.current_update = None
async with self.cmd_request_lock:
self.current_update = (app, id(web_request))
try:
await updater.update(inc_deps)
except Exception as e:
self.notify_update_response(f"Error updating {app}")
self.notify_update_response(str(e), is_complete=True)
raise
finally:
self.current_update = None
return "ok"
async def _handle_status_request(self, web_request):
refresh = web_request.get_boolean('refresh', False)
check_refresh = web_request.get_boolean('refresh', False)
# Don't refresh if a print is currently in progress or
# if an update is in progress. Just return the current
# state
if self.current_update is not None or \
await self._check_klippy_printing():
check_refresh = False
need_refresh = False
if check_refresh:
# If there is an outstanding request processing a
# refresh, we don't need to do it again.
need_refresh = not self.is_refreshing
await self.cmd_request_lock.acquire()
self.is_refreshing = True
vinfo = {}
for name, updater in self.updaters.items():
await updater.check_initialized(120.)
if refresh:
ret = updater.refresh()
if asyncio.iscoroutine(ret):
await ret
if hasattr(updater, "get_update_status"):
vinfo[name] = updater.get_update_status()
try:
for name, updater in list(self.updaters.items()):
await updater.check_initialized(120.)
if need_refresh:
ret = updater.refresh()
if asyncio.iscoroutine(ret):
await ret
if hasattr(updater, "get_update_status"):
vinfo[name] = updater.get_update_status()
except Exception:
raise
finally:
if check_refresh:
self.is_refreshing = False
self.cmd_request_lock.release()
return {
'version_info': vinfo,
'github_rate_limit': self.gh_rate_limit,
@@ -144,7 +273,10 @@ class UpdateManager:
async def execute_cmd_with_response(self, cmd, timeout=10.):
shell_command = self.server.lookup_plugin('shell_command')
scmd = shell_command.build_shell_command(cmd, None)
return await scmd.run_with_response(timeout)
result = await scmd.run_with_response(timeout, retries=5)
if result is None:
raise self.server.error(f"Error Running Command: {cmd}")
return result
async def _init_api_rate_limit(self):
url = "https://api.github.com/rate_limit"
@@ -190,9 +322,11 @@ class UpdateManager:
retries = 5
while retries:
try:
resp = await self.http_client.fetch(
timeout = time.time() + 10.
fut = self.http_client.fetch(
url, headers=headers, connect_timeout=5.,
request_timeout=5., raise_error=False)
resp = await tornado.gen.with_timeout(timeout, fut)
except Exception:
retries -= 1
msg = f"Error Processing GitHub API request: {url}"
@@ -241,9 +375,11 @@ class UpdateManager:
retries = 5
while retries:
try:
resp = await self.http_client.fetch(
timeout = time.time() + 130.
fut = self.http_client.fetch(
url, headers={"Accept": "application/zip"},
connect_timeout=5., request_timeout=120.)
resp = await tornado.gen.with_timeout(timeout, fut)
except Exception:
retries -= 1
logging.exception("Error Processing Download")
@@ -270,29 +406,69 @@ class UpdateManager:
def close(self):
self.http_client.close()
if self.refresh_cb is not None:
self.refresh_cb.stop()
class GitUpdater:
def __init__(self, umgr, name, path, env):
def __init__(self, umgr, config, path=None, env=None):
self.server = umgr.server
self.execute_cmd = umgr.execute_cmd
self.execute_cmd_with_response = umgr.execute_cmd_with_response
self.notify_update_response = umgr.notify_update_response
distro = umgr.distro
config = umgr.config
self.repo_info = config[f"repo_info {name}"].get_options()
self.dist_info = config[f"dist_info {distro} {name}"].get_options()
self.name = name
self.name = config.get_name().split()[-1]
self.owner = "?"
self.repo_path = path
self.env = env
if path is None:
self.repo_path = os.path.expanduser(config.get('path'))
self.env = config.get("env", env)
dist_packages = None
if self.env is not None:
self.env = os.path.expanduser(self.env)
dist_packages = config.get('python_dist_packages', None)
self.python_reqs = os.path.join(
self.repo_path, config.get("requirements"))
self.origin = config.get("origin").lower()
self.install_script = config.get('install_script', None)
if self.install_script is not None:
self.install_script = os.path.abspath(os.path.join(
self.repo_path, self.install_script))
self.venv_args = config.get('venv_args', None)
self.python_dist_packages = None
self.python_dist_path = None
self.env_package_path = None
if dist_packages is not None:
self.python_dist_packages = [
p.strip() for p in dist_packages.split('\n')
if p.strip()]
self.python_dist_path = os.path.abspath(
config.get('python_dist_path'))
env_package_path = os.path.abspath(os.path.join(
os.path.dirname(self.env), "..",
config.get('env_package_path')))
matches = glob.glob(env_package_path)
if len(matches) == 1:
self.env_package_path = matches[0]
else:
raise config.error("No match for 'env_package_path': %s"
% (env_package_path,))
for opt in ["repo_path", "env", "python_reqs", "install_script",
"python_dist_path", "env_package_path"]:
val = getattr(self, opt)
if val is None:
continue
if not os.path.exists(val):
raise config.error("Invalid path for option '%s': %s"
% (val, opt))
self.version = self.cur_hash = "?"
self.remote_version = self.remote_hash = "?"
self.init_evt = Event()
self.refresh_condition = None
self.debug = umgr.repo_debug
self.remote = "origin"
self.branch = "master"
self.is_valid = self.is_dirty = self.detached = False
IOLoop.current().spawn_callback(self.refresh)
def _get_version_info(self):
ver_path = os.path.join(self.repo_path, "scripts/version.txt")
@@ -338,13 +514,23 @@ class GitUpdater:
await self.init_evt.wait(timeout)
async def refresh(self):
await self._check_version()
if self.refresh_condition is None:
self.refresh_condition = Condition()
else:
self.refresh_condition.wait()
return
try:
await self._check_version()
except Exception:
logging.exception("Error Refreshing git state")
self.init_evt.set()
self.refresh_condition.notify_all()
self.refresh_condition = None
async def _check_version(self, need_fetch=True):
self.is_valid = self.detached = False
self.cur_hash = self.branch = self.remote = "?"
self.version = self.remote_version = "?"
self.version = self.remote_version = self.owner = "?"
try:
blist = await self.execute_cmd_with_response(
f"git -C {self.repo_path} branch --list")
@@ -392,11 +578,15 @@ class GitUpdater:
self._log_exc("Error retreiving git info")
return
remote_url = remote_url.strip()
owner_match = re.match(r"https?://[^/]+/([^/]+)", remote_url)
if owner_match is not None:
self.owner = owner_match.group(1)
self.is_dirty = repo_version.endswith("dirty")
versions = []
for ver in [repo_version, remote_version]:
tag_version = "?"
ver_match = re.match(r"v\d+\.\d+\.\d-\d+", ver)
ver_match = re.match(r"v\d+\.\d+\.\d-\d+", ver.strip())
if ver_match:
tag_version = ver_match.group()
versions.append(tag_version)
@@ -420,7 +610,7 @@ class GitUpdater:
remote_url = remote_url.lower()
if remote_url[-4:] != ".git":
remote_url += ".git"
if remote_url == self.repo_info['origin']:
if remote_url == self.origin:
self.is_valid = True
self._log_info("Validity check for git repo passed")
else:
@@ -431,6 +621,9 @@ class GitUpdater:
f"{self.remote}/{self.branch}")
async def update(self, update_deps=False):
await self.check_initialized(20.)
if self.refresh_condition is not None:
self.refresh_condition.wait()
if not self.is_valid:
raise self._log_exc("Update aborted, repo is not valid", False)
if self.is_dirty:
@@ -476,9 +669,10 @@ class GitUpdater:
self._notify_status("Update Finished...", is_complete=True)
async def _install_packages(self):
if self.install_script is None:
return
# Open install file file and read
inst_script = self.dist_info['install_script']
inst_path = os.path.join(self.repo_path, inst_script)
inst_path = self.install_script
if not os.path.isfile(inst_path):
self._log_info(f"Unable to open install script: {inst_path}")
return
@@ -505,24 +699,24 @@ class GitUpdater:
return
async def _update_virtualenv(self, rebuild_env=False):
if self.env is None:
return
# Update python dependencies
bin_dir = os.path.dirname(self.env)
env_path = os.path.normpath(os.path.join(bin_dir, ".."))
if rebuild_env:
env_args = self.repo_info['venv_args']
self._notify_status(f"Creating virtualenv at: {env_path}...")
if os.path.exists(env_path):
shutil.rmtree(env_path)
try:
await self.execute_cmd(
f"virtualenv {env_args} {env_path}", timeout=300.)
f"virtualenv {self.venv_args} {env_path}", timeout=300.)
except Exception:
self._log_exc(f"Error creating virtualenv")
return
if not os.path.expanduser(self.env):
if not os.path.exists(self.env):
raise self._log_exc("Failed to create new virtualenv", False)
reqs = os.path.join(
self.repo_path, self.repo_info['requirements'])
reqs = self.python_reqs
if not os.path.isfile(reqs):
self._log_exc(f"Invalid path to requirements_file '{reqs}'")
return
@@ -534,16 +728,14 @@ class GitUpdater:
retries=3)
except Exception:
self._log_exc("Error updating python requirements")
self._install_python_dist_requirements(env_path)
self._install_python_dist_requirements()
def _install_python_dist_requirements(self, env_path):
dist_reqs = self.dist_info.get('python_dist_packages', None)
def _install_python_dist_requirements(self):
dist_reqs = self.python_dist_packages
if dist_reqs is None:
return
dist_reqs = [r.strip() for r in dist_reqs.split("\n")
if r.strip()]
dist_path = self.dist_info['python_dist_path']
site_path = os.path.join(env_path, self.dist_info['env_package_path'])
dist_path = self.python_dist_path
site_path = self.env_package_path
for pkg in dist_reqs:
for f in os.listdir(dist_path):
if f.startswith(pkg):
@@ -571,6 +763,7 @@ class GitUpdater:
return {
'remote_alias': self.remote,
'branch': self.branch,
'owner': self.owner,
'version': self.version,
'remote_version': self.remote_version,
'current_hash': self.cur_hash,
@@ -589,17 +782,21 @@ class PackageUpdater:
self.notify_update_response = umgr.notify_update_response
self.available_packages = []
self.init_evt = Event()
IOLoop.current().spawn_callback(self.refresh)
self.refresh_condition = None
async def refresh(self):
async def refresh(self, fetch_packages=True):
# TODO: Use python-apt python lib rather than command line for updates
try:
await self.execute_cmd(f"{APT_CMD} update", timeout=300.)
res = await self.execute_cmd_with_response(
"apt list --upgradable")
except Exception:
logging.exception("Error Refreshing System Packages")
if self.refresh_condition is None:
self.refresh_condition = Condition()
else:
self.refresh_condition.wait()
return
try:
if fetch_packages:
await self.execute_cmd(
f"{APT_CMD} update", timeout=300., retries=3)
res = await self.execute_cmd_with_response(
"apt list --upgradable", timeout=60.)
pkg_list = [p.strip() for p in res.split("\n") if p.strip()]
if pkg_list:
pkg_list = pkg_list[2:]
@@ -609,7 +806,11 @@ class PackageUpdater:
logging.info(
f"Detected {len(self.available_packages)} package updates:"
f"\n{pkg_list}")
except Exception:
logging.exception("Error Refreshing System Packages")
self.init_evt.set()
self.refresh_condition.notify_all()
self.refresh_condition = None
async def check_initialized(self, timeout=None):
if self.init_evt.is_set():
@@ -619,6 +820,9 @@ class PackageUpdater:
await self.init_evt.wait(timeout)
async def update(self, *args):
await self.check_initialized(20.)
if self.refresh_condition is not None:
self.refresh_condition.wait()
self.notify_update_response("Updating packages...")
try:
await self.execute_cmd(
@@ -637,22 +841,35 @@ class PackageUpdater:
'package_list': self.available_packages
}
class ClientUpdater:
def __init__(self, umgr, repo, path):
class WebUpdater:
def __init__(self, umgr, config):
self.umgr = umgr
self.server = umgr.server
self.notify_update_response = umgr.notify_update_response
self.repo = repo.strip().strip("/")
self.name = self.repo.split("/")[-1]
self.path = path
self.repo = config.get('repo').strip().strip("/")
self.owner, self.name = self.repo.split("/", 1)
if hasattr(config, "get_name"):
self.name = config.get_name().split()[-1]
self.path = os.path.realpath(os.path.expanduser(
config.get("path")))
self.persistent_files = []
pfiles = config.get('persistent_files', None)
if pfiles is not None:
self.persistent_files = [pf.strip().strip("/") for pf in
pfiles.split("\n") if pf.strip()]
if ".version" in self.persistent_files:
raise config.error(
"Invalid value for option 'persistent_files': "
"'.version' can not be persistent")
self.version = self.remote_version = self.dl_url = "?"
self.etag = None
self.init_evt = Event()
self.refresh_condition = None
self._get_local_version()
logging.info(f"\nInitializing Client Updater: '{self.name}',"
f"\nversion: {self.version}"
f"\npath: {self.path}")
IOLoop.current().spawn_callback(self.refresh)
def _get_local_version(self):
version_path = os.path.join(self.path, ".version")
@@ -669,9 +886,21 @@ class ClientUpdater:
await self.init_evt.wait(timeout)
async def refresh(self):
# Local state
self._get_local_version()
if self.refresh_condition is None:
self.refresh_condition = Condition()
else:
self.refresh_condition.wait()
return
try:
self._get_local_version()
await self._get_remote_version()
except Exception:
logging.exception("Error Refreshing Client")
self.init_evt.set()
self.refresh_condition.notify_all()
self.refresh_condition = None
async def _get_remote_version(self):
# Remote state
url = f"https://api.github.com/repos/{self.repo}/releases/latest"
try:
@@ -681,7 +910,7 @@ class ClientUpdater:
result = {}
if result is None:
# No change, update not necessary
return None
return
self.etag = result.get('etag', None)
self.remote_version = result.get('name', "?")
release_assets = result.get('assets', [{}])[0]
@@ -691,9 +920,12 @@ class ClientUpdater:
f"Local Version: {self.version}\n"
f"Remote Version: {self.remote_version}\n"
f"url: {self.dl_url}")
self.init_evt.set()
async def update(self, *args):
await self.check_initialized(20.)
if self.refresh_condition is not None:
# wait for refresh if in progess
self.refresh_condition.wait()
if self.remote_version == "?":
await self.refresh()
if self.remote_version == "?":
@@ -705,13 +937,28 @@ class ClientUpdater:
if self.version == self.remote_version:
# Already up to date
return
if os.path.isdir(self.path):
shutil.rmtree(self.path)
os.mkdir(self.path)
self.notify_update_response(f"Downloading Client: {self.name}")
archive = await self.umgr.http_download_request(self.dl_url)
with zipfile.ZipFile(io.BytesIO(archive)) as zf:
zf.extractall(self.path)
with tempfile.TemporaryDirectory(
suffix=self.name, prefix="client") as tempdir:
if os.path.isdir(self.path):
# find and move persistent files
for fname in os.listdir(self.path):
src_path = os.path.join(self.path, fname)
if fname in self.persistent_files:
dest_dir = os.path.dirname(os.path.join(tempdir, fname))
os.makedirs(dest_dir, exist_ok=True)
shutil.move(src_path, dest_dir)
shutil.rmtree(self.path)
os.mkdir(self.path)
with zipfile.ZipFile(io.BytesIO(archive)) as zf:
zf.extractall(self.path)
# Move temporary files back into
for fname in os.listdir(tempdir):
src_path = os.path.join(tempdir, fname)
dest_dir = os.path.dirname(os.path.join(self.path, fname))
os.makedirs(dest_dir, exist_ok=True)
shutil.move(src_path, dest_dir)
self.version = self.remote_version
version_path = os.path.join(self.path, ".version")
if not os.path.exists(version_path):
@@ -723,6 +970,7 @@ class ClientUpdater:
def get_update_status(self):
return {
'name': self.name,
'owner': self.owner,
'version': self.version,
'remote_version': self.remote_version
}
+25 -13
View File
@@ -28,19 +28,26 @@ class LocalQueueHandler(logging.handlers.QueueHandler):
except Exception:
self.handleError(record)
# Timed Rotating File Handler, based on Klipper's implementation
class MoonrakerLoggingHandler(logging.handlers.TimedRotatingFileHandler):
def __init__(self, software_version, filename, **kwargs):
super(MoonrakerLoggingHandler, self).__init__(filename, **kwargs)
self.header = "Moonraker Log Start...\n"
self.header += f"Git Version: {software_version}\n"
self.header += "="*80 + "\n"
self.rollover_info = {
'header': f"{'-'*20}Moonraker Log Start{'-'*20}",
'version': f"Git Version: {software_version}",
}
lines = [line for line in self.rollover_info.values() if line]
if self.stream is not None:
self.stream.write(self.header)
self.stream.write("\n".join(lines) + "\n")
def set_rollover_info(self, name, item):
self.rollover_info[name] = item
def doRollover(self):
super(MoonrakerLoggingHandler, self).doRollover()
lines = [line for line in self.rollover_info.values() if line]
if self.stream is not None:
self.stream.write(self.header)
self.stream.write("\n".join(lines) + "\n")
# Parse the git version from the command line. This code
# is borrowed from Klipper.
@@ -74,16 +81,21 @@ def setup_logging(log_file, software_version):
queue_handler = LocalQueueHandler(queue)
root_logger.addHandler(queue_handler)
root_logger.setLevel(logging.INFO)
file_hdlr = MoonrakerLoggingHandler(
software_version, log_file, when='midnight', backupCount=2)
stdout_hdlr = logging.StreamHandler(sys.stdout)
formatter = logging.Formatter(
'%(asctime)s [%(filename)s:%(funcName)s()] - %(message)s')
file_hdlr.setFormatter(formatter)
stdout_fmt = logging.Formatter(
'[%(filename)s:%(funcName)s()] - %(message)s')
stdout_hdlr.setFormatter(stdout_fmt)
listener = logging.handlers.QueueListener(
queue, file_hdlr, stdout_hdlr)
file_hdlr = None
if log_file:
file_hdlr = MoonrakerLoggingHandler(
software_version, log_file, when='midnight', backupCount=2)
formatter = logging.Formatter(
'%(asctime)s [%(filename)s:%(funcName)s()] - %(message)s')
file_hdlr.setFormatter(formatter)
listener = logging.handlers.QueueListener(
queue, file_hdlr, stdout_hdlr)
else:
listener = logging.handlers.QueueListener(
queue, stdout_hdlr)
listener.start()
return listener
return listener, file_hdlr
+23 -41
View File
@@ -135,11 +135,12 @@ class JsonRPC:
try:
result = await method(ws, *args, **kwargs)
except TypeError as e:
return self.build_error(-32603, f"Invalid params:\n{e}", req_id)
return self.build_error(
-32603, f"Invalid params:\n{e}", req_id, True)
except ServerError as e:
return self.build_error(e.status_code, str(e), req_id)
return self.build_error(e.status_code, str(e), req_id, True)
except Exception as e:
return self.build_error(-31000, str(e), req_id)
return self.build_error(-31000, str(e), req_id, True)
if req_id is None:
return None
@@ -153,7 +154,12 @@ class JsonRPC:
'id': req_id
}
def build_error(self, code, msg, req_id=None):
def build_error(self, code, msg, req_id=None, is_exc=False):
log_msg = f"JSON-RPC Request Error: {code}\n{msg}"
if is_exc:
logging.exception(log_msg)
else:
logging.info(log_msg)
return {
'jsonrpc': "2.0",
'error': {'code': code, 'message': msg},
@@ -169,42 +175,14 @@ class WebsocketManager:
self.rpc.register_method("server.websocket.id", self._handle_id_request)
# Register events
self.server.register_event_handler(
"server:klippy_ready", self._handle_klippy_ready)
self.server.register_event_handler(
"server:klippy_disconnect", self._handle_klippy_disconnect)
self.server.register_event_handler(
"server:gcode_response", self._handle_gcode_response)
self.server.register_event_handler(
"file_manager:filelist_changed", self._handle_filelist_changed)
self.server.register_event_handler(
"file_manager:metadata_update", self._handle_metadata_update)
self.server.register_event_handler(
"gpio_power:power_changed", self._handle_power_changed)
self.server.register_event_handler(
"update_manager:update_response", self._handle_update_response)
def register_notification(self, event_name, notify_name=None):
if notify_name is None:
notify_name = event_name.split(':')[-1]
async def _handle_klippy_ready(self):
await self.notify_websockets("klippy_ready")
async def _handle_klippy_disconnect(self):
await self.notify_websockets("klippy_disconnected")
async def _handle_gcode_response(self, response):
await self.notify_websockets("gcode_response", response)
async def _handle_filelist_changed(self, flist):
await self.notify_websockets("filelist_changed", flist)
async def _handle_metadata_update(self, metadata):
await self.notify_websockets("metadata_update", metadata)
async def _handle_power_changed(self, pstatus):
await self.notify_websockets("power_changed", pstatus)
async def _handle_update_response(self, response):
await self.notify_websockets("update_response", response)
async def notify_handler(*args):
await 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 \
@@ -266,6 +244,7 @@ class WebsocketManager:
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(
@@ -273,7 +252,7 @@ class WebsocketManager:
async def close(self):
async with self.ws_lock:
for ws in self.websockets.values():
for ws in list(self.websockets.values()):
ws.close()
self.websockets = {}
@@ -284,6 +263,7 @@ class WebSocket(WebSocketHandler):
self.wsm = app.get_websocket_manager()
self.rpc = self.wsm.rpc
self.uid = id(self)
self.is_closed = False
async def open(self):
await self.wsm.add_websocket(self)
@@ -301,7 +281,7 @@ class WebSocket(WebSocketHandler):
logging.exception("Websocket Command Error")
def send_status(self, status):
if not status:
if not status or self.is_closed:
return
try:
self.write_message({
@@ -309,6 +289,7 @@ class WebSocket(WebSocketHandler):
'method': "notify_status_update",
'params': [status]})
except WebSocketClosedError:
self.is_closed = True
logging.info(
f"Websocket Closed During Status Update: {self.uid}")
except Exception:
@@ -316,6 +297,7 @@ class WebSocket(WebSocketHandler):
f"Error sending data over websocket: {self.uid}")
def on_close(self):
self.is_closed = True
io_loop = IOLoop.current()
io_loop.spawn_callback(self.wsm.remove_websocket, self)
+49 -24
View File
@@ -1,3 +1,4 @@
#!/usr/bin/env python3
# GCode metadata extraction utility
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
@@ -14,6 +15,10 @@ import traceback
import io
from PIL import Image
def log_to_stderr(msg):
sys.stderr.write(f"{msg}\n")
sys.stderr.flush()
# regex helpers
def _regex_find_floats(pattern, data, strict=False):
# If strict is enabled, pattern requires a floating point
@@ -54,13 +59,13 @@ def _regex_find_first(pattern, data, cast=float):
class BaseSlicer(object):
def __init__(self, file_path):
self.path = file_path
self.header_data = self.footer_data = self.log = None
self.header_data = self.footer_data = None
self.layer_height = None
def set_data(self, header_data, footer_data, fsize, log):
def set_data(self, header_data, footer_data, fsize):
self.header_data = header_data
self.footer_data = footer_data
self.size = fsize
self.log = log
def _parse_min_float(self, pattern, data, strict=False):
result = _regex_find_floats(pattern, data, strict)
@@ -145,12 +150,22 @@ class PrusaSlicer(BaseSlicer):
return None
def parse_first_layer_height(self):
# Check percentage
pct = _regex_find_first(
r"; first_layer_height = (\d+)%", self.footer_data)
if pct is not None:
if self.layer_height is None:
# Failed to parse the original layer height, so it is not
# possible to calculate a percentage
return None
return round(pct / 100. * self.layer_height, 6)
return _regex_find_first(
r"; first_layer_height = (\d+\.?\d*)", self.footer_data)
def parse_layer_height(self):
return _regex_find_first(
self.layer_height = _regex_find_first(
r"; layer_height = (\d+\.?\d*)", self.footer_data)
return self.layer_height
def parse_object_height(self):
matches = re.findall(
@@ -197,12 +212,12 @@ class PrusaSlicer(BaseSlicer):
info = _regex_find_ints(r".*", lines[0])
data = "".join(lines[1:-1])
if len(info) != 3:
self.log.append(
log_to_stderr(
f"MetadataError: Error parsing thumbnail"
f" header: {lines[0]}")
continue
if len(data) != info[2]:
self.log.append(
log_to_stderr(
f"MetadataError: Thumbnail Size Mismatch: "
f"detected {info[2]}, actual {len(data)}")
continue
@@ -259,7 +274,7 @@ class SuperSlicer(PrusaSlicer):
}
return None
class Cura(BaseSlicer):
class Cura(PrusaSlicer):
def check_identity(self, data):
match = re.search(r"Cura_SteamEngine\s(.*)", data)
if match:
@@ -273,8 +288,9 @@ class Cura(BaseSlicer):
return _regex_find_first(r";MINZ:(\d+\.?\d*)", self.header_data)
def parse_layer_height(self):
return _regex_find_first(
self.layer_height = _regex_find_first(
r";Layer\sheight:\s(\d+\.?\d*)", self.header_data)
return self.layer_height
def parse_object_height(self):
return _regex_find_first(r";MAXZ:(\d+\.?\d*)", self.header_data)
@@ -298,6 +314,11 @@ class Cura(BaseSlicer):
r"M190 S(\d+\.?\d*)", self.header_data)
def parse_thumbnails(self):
# Attempt to parse thumbnails from file metadata
thumbs = super().parse_thumbnails()
if thumbs is not None:
return thumbs
# Check for thumbnails extracted from the ufp
thumbName = os.path.splitext(
os.path.basename(self.path))[0] + ".png"
thumbPath = os.path.join(
@@ -327,7 +348,7 @@ class Cura(BaseSlicer):
'size': len(thumbSmall), 'data': thumbSmall
})
except Exception as e:
self.log.append(str(e))
log_to_stderr(str(e))
return None
return thumbs
@@ -345,8 +366,9 @@ class Simplify3D(BaseSlicer):
return self._parse_min_float(r"G1\sZ\d+\.\d*", self.header_data)
def parse_layer_height(self):
return _regex_find_first(
self.layer_height = _regex_find_first(
r";\s+layerHeight,(\d+\.?\d*)", self.header_data)
return self.layer_height
def parse_object_height(self):
return self._parse_max_float(r"G1\sZ\d+\.\d*", self.footer_data)
@@ -413,8 +435,9 @@ class KISSlicer(BaseSlicer):
r";\s+first_layer_thickness_mm\s=\s(\d+\.?\d*)", self.header_data)
def parse_layer_height(self):
return _regex_find_first(
self.layer_height = _regex_find_first(
r";\s+max_layer_thickness_mm\s=\s(\d+\.?\d*)", self.header_data)
return self.layer_height
def parse_object_height(self):
return self._parse_max_float(
@@ -466,7 +489,8 @@ class IdeaMaker(BaseSlicer):
layer_info = _regex_find_floats(
r";LAYER:1\s*.*\s*;HEIGHT.*", self.header_data)
if len(layer_info) >= 3:
return layer_info[2]
self.layer_height = layer_info[2]
return self.layer_height
return None
def parse_object_height(self):
@@ -508,9 +532,10 @@ class IceSL(BaseSlicer):
self.header_data, float)
def parse_layer_height(self):
return _regex_find_first(
self.layer_height = _regex_find_first(
r"; z_layer_height_mm :\s+(\d+\.\d+)",
self.header_data, float)
return self.layer_height
def parse_object_height(self):
return self._parse_max_float(
@@ -530,12 +555,12 @@ SUPPORTED_SLICERS = [
PrusaSlicer, Slic3rPE, Slic3r, SuperSlicer,
Cura, Simplify3D, KISSlicer, IdeaMaker, IceSL]
SUPPORTED_DATA = [
'first_layer_height', 'layer_height', 'object_height',
'layer_height', 'first_layer_height', 'object_height',
'filament_total', 'estimated_time', 'thumbnails',
'first_layer_bed_temp', 'first_layer_extr_temp',
'gcode_start_byte', 'gcode_end_byte']
def extract_metadata(file_path, log):
def extract_metadata(file_path):
metadata = {}
slicers = [s(file_path) for s in SUPPORTED_SLICERS]
header_data = footer_data = slicer = None
@@ -563,7 +588,7 @@ def extract_metadata(file_path, log):
footer_data = header_data[remaining - READ_SIZE:] + f.read()
else:
footer_data = header_data
slicer.set_data(header_data, footer_data, size, log)
slicer.set_data(header_data, footer_data, size)
for key in SUPPORTED_DATA:
func = getattr(slicer, "parse_" + key)
result = func()
@@ -573,18 +598,18 @@ def extract_metadata(file_path, log):
def main(path, filename):
file_path = os.path.join(path, filename)
log = []
metadata = {}
if not os.path.isfile(file_path):
log.append(f"File Not Found: {file_path}")
else:
try:
metadata = extract_metadata(file_path, log)
except Exception:
log.append(traceback.format_exc())
log_to_stderr(f"File Not Found: {file_path}")
sys.exit(-1)
try:
metadata = extract_metadata(file_path)
except Exception:
log_to_stderr(traceback.format_exc())
sys.exit(-1)
fd = sys.stdout.fileno()
data = json.dumps(
{'file': filename, 'log': log, 'metadata': metadata}).encode()
{'file': filename, 'metadata': metadata}).encode()
while data:
try:
ret = os.write(fd, data)
+1
View File
@@ -36,6 +36,7 @@ cleanup_legacy() {
install_packages()
{
PKGLIST="python3-virtualenv python3-dev nginx libopenjp2-7 python3-libgpiod"
PKGLIST="${PKGLIST} liblmdb0"
# Update system package info
report_status "Running apt-get update..."
+2
View File
@@ -2,3 +2,5 @@
tornado==6.1.0
pyserial==3.4
pillow==8.0.1
lmdb==1.1.1
streaming-form-data==1.8.1
+17 -18
View File
@@ -4,28 +4,25 @@
stop_service() {
# Stop Moonraker Service
echo "#### Stopping Moonraker Service.."
sudo service moonraker stop
sudo systemctl stop moonraker
}
remove_service() {
# Remove Moonraker from Startup
echo
echo "#### Removing Moonraker from Startup.."
sudo update-rc.d -f moonraker remove
# Remove Moonraker from Services
# Remove Moonraker LSB/systemd service
echo
echo "#### Removing Moonraker Service.."
sudo rm -f /etc/init.d/moonraker /etc/default/moonraker
}
remove_sudo_fix() {
echo
echo "#### Removing sudo_fix"
sudo gpasswd -d $USER mnrkrsudo
sudo delgroup --only-if-empty mnrkrsudo
sudo rm -f /etc/sudoers.d/020-sudo-for-moonraker
if [ -f "/etc/init.d/moonraker" ]; then
# legacy installation, remove the LSB service
sudo update-rc.d -f moonraker remove
sudo rm -f /etc/init.d/moonraker
sudo rm -f /etc/default/moonraker
else
# Remove systemd installation
sudo systemctl disable moonraker
sudo rm -f /etc/systemd/system/moonraker.service
sudo systemctl daemon-reload
sudo systemctl reset-failed
fi
}
remove_files() {
@@ -55,6 +52,9 @@ remove_files() {
echo
echo "The following command is typically used to remove source files:"
echo " rm -rf ~/moonraker"
echo
echo "You may also wish to uninstall nginx:"
echo " sudo apt-get remove nginx"
}
verify_ready()
@@ -69,4 +69,3 @@ verify_ready
stop_service
remove_service
remove_files
remove_sudo_fix
+7 -11
View File
@@ -1,24 +1,20 @@
# Supplemental configuration for Moonraker's Update Manager
# plugin. This file should not be modified.
[repo_info moonraker]
[update_manager static debian moonraker]
origin: https://github.com/arksine/moonraker.git
requirements: scripts/moonraker-requirements.txt
venv_args: -p python3
[repo_info klipper]
origin: https://github.com/kevinoconnor/klipper.git
requirements: scripts/klippy-requirements.txt
venv_args: -p python2
[dist_info debian moonraker]
install_script: scripts/install-moonraker.sh
python_dist_path: /usr/lib/python3/dist-packages
env_package_path: lib/python3.7/site-packages
env_package_path: lib/python*/site-packages
python_dist_packages:
gpiod
[dist_info debian klipper]
[update_manager static debian 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/python2.7/site-packages
env_package_path: lib/python*/site-packages
+1 -1
View File
@@ -1,2 +1,2 @@
env_version=0.2.6
deps_version=0.2.2
deps_version=0.4.1