62 Commits
Author SHA1 Message Date
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
Arksine 77c483ea0f docs: document changes to the update_manager plugin
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-31 08:25:59 -05:00
Arksine 96941922bc update_manager: move repo specific data to a supplemental config file
This provides the update manager flexibility, such as the ability to define disto specific dependencies.  This also fixes an issue where two updates are necessary to install additional dependencies.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-30 19:45:20 -05:00
Arksine 1f2c1b3fcd confighelper: implement read_supplemental_config
This allows the config object to read additional config files as requred.  Also implement a "get_options" method that can be used to retrive a dictionary of all options in the current section.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-30 19:45:20 -05:00
Arksine 2953c3f16f update_manager: Use the "klippy_identified" event to update Klippy paths
Only update the Klipper Repo Object if the paths have changed.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-30 19:45:20 -05:00
Arksine 8fc5aab2f0 update_manager: report system package info
Report available package count and a list of available packages.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-30 19:45:20 -05:00
Arksine 1acb00e2f1 update_manager: only fetch the git remote when necessary
After a repo has been updated fetching the remote is not needed, as it was just done in the prior update step.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-30 11:53:27 -05:00
Arksine b0fda218f1 update_manager: manage GitHub rate limits
Track rate limit attributes and reject requests when the user IP has reached their limit.  Use conditional API requests to reduce the number of requests that count against the limit.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-30 11:53:27 -05:00
Arksine 34af0b4bfb shell_command: always log the result of a shell command
Use the return code to help determine if the command successfully finished.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-30 11:53:27 -05:00
Arksine fad6bc4ad7 update_manager: timeout bug fixes
It shouldn't be necessary to use gen.with_timeout during the fetch with tornado 6.1.  Also fix some potential issues with unbound timeouts variables.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-30 11:53:27 -05:00
Arksine 9501d72059 update_manager: Don't use github's API to check repo version
The remote version info can be retrieved by simply doing a git fetch, then running "git rev-parse" and "git describe" on the desired remote branch.

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2020-12-30 11:53:27 -05:00
Arksine 9993b1e656 update_manager: implement 'enable_repo_debug' option
Allow developers to update a detached git repo.  Note that this option should not be used on production machines.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-30 11:53:27 -05:00
Arksine b5394228ef shell_command: reset tracking attributes in run()
Clear partial output and cancelled attributes prior to each call of run().  This allows a command to be cleanly run again after a failure.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-30 11:53:27 -05:00
Arksine 6bf4ef8b00 moonraker: add "klippy_identified" event
This allows Moonraker to update its paths to Klippy immediately upon a successful response from the info endpoint.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-30 11:53:16 -05:00
Arksine 0a7080741c app: Register a default file path for klippy.log
This will make klippy.log available in the event that Klippy has not successfully connected, assuming the log is available at the default location.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-30 07:53:48 -05:00
Arksine 223c125106 app: Don't replace "+" with a space char when deleting a file
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-30 06:41:27 -05:00
Arksine f9fc679831 moonraker: add shebang to moonraker.py
Also make moonraker.py executable.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-28 20:00:56 -05:00
Arksine 586bb6a7ca docs: document "initial_state" option for the power plugin
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-25 19:31:57 -05:00
Arksine 76ccc8b3e1 power: Add 'initial_state' option for GPIO devices
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-25 19:31:03 -05:00
Arksine f91e425463 power: fix formatting issues with tasmota impelmentation
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-25 19:30:21 -05:00
Arksine 46de7c48c8 moonraker: bump env version to 0.2.6
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-22 19:06:53 -05:00
Arksine 063ef7194a update_manager: fix bug in env dist package update
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-22 18:33:37 -05:00
Arksine 313357061e moonraker: bump env version to 0.2.5
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-22 18:29:03 -05:00
Arksine 0f62b283bd update_manager: rebuild the enviroment if a new env version is detected
This should be done even if new dependencies are not required.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-22 18:10:58 -05:00
Arksine 9f9a05cabb update_manager: symlink dist packages on virtualenv rebuild
This allows for the installation of python "dist-packages" without enabling "system-site-packages" in the virtualenv.  As of the moment moonraker only requires the gpiod dist package.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-22 17:59:22 -05:00
Arksine 40fbe1abf1 scripts: don't install system site packages in virtualenv
This can create issues of the system includes conflicting packages.  Create a symlink for the system "gpiod" instead.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-22 15:41:42 -05:00
Arksine 9a309ffd59 file_manager: allow directories in "/etc/moonraker" to be registered
This may be useful for system packaging options that do not wish to put configuration in the home directory.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-20 08:37:45 -05:00
Arksine 684ff07ba2 update_manager: check local git version after an update
Before the service is restarted, check the local version.  This should make sure that the local repo state is reported correctly after an update, regardless of the timing of a status request.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-20 06:46:52 -05:00
Arksine 0a7eed2767 update_manager: fix bug in "check_initialized" methods
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-19 14:05:11 -05:00
Arksine 6898ff8ab6 update_manager: make sure than all updaters are intialized before updating status
It is possible that a status request can occur while an updater is checking intial state.  Use an event to wait on initializing before returning the status request.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-19 07:40:23 -05:00
Arksine 653c9190c4 docs: document "complete" field for "notifiy_update_response"
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-17 17:58:04 -05:00
Arksine cdbaaedc8a test client: log when an update is complete
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-17 17:45:51 -05:00
Arksine fa20d106cf update_manager: add "complete" field to update_repsonse notification
This signals to connected clients that the current update in progress has compelted.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-17 17:45:51 -05:00
Arksine 40b74cefb5 update_manager: refresh the local git repo state when a status refresh is requested
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-17 17:45:51 -05:00
Arksine 20d27b0be6 docs: Add KlipperScreen to list of available clients
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-16 12:39:46 -05:00
Arksine 44bdf708e6 update_manager: correctly handle origins that do not contain a ".git" extension
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-16 11:50:52 -05:00
Arksine 2ddd1966fe file_manager: handle gcode files with special characters
Files with quotation marks and spaces are now acceptable and properly handled.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-14 10:21:38 -05:00
Arksine 8bb7139468 websockets: remove refrenced to undefined attribute in websocket handler
This resolves an issue where an unhandled exception is rasied when a websocket attempts to write to a closed websocket.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-13 17:05:44 -05:00
Arksine ba4d771d10 paneldue: implement queues for command handling
This implements two queues, one for commands that execute locally and a second
for gcode commands that execute on the Klippy host.  While it is valid for a local
command to execute concurrently with a remote command, commands of the same type
(local or remote) should execute sequentially.

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

Update paneldue.py
2020-12-12 08:35:04 -05:00
Arksine eea2abd60e paneldue: execute commands synchronously
This prevents gcode requests from blocking temperature updates, accessing the file list, etc.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-11 07:28:39 -05:00
Arksine 70501772c1 paneldue: re-initalize if the paneldue disconnects
If 10 seconds passes without an update request, re-initialize the PanelDue.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-10 11:31:40 -05:00
Arksine 119b0bf60c paneldue: attempt reconnect if disconnected due to error
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-10 06:29:49 -05:00
Arksine 59e58226ff paneldue: prevent reentry when processing incoming commands
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-10 06:29:49 -05:00
Arksine ec5be560d5 paneldue: update macros on first connection
Report that the PanelDue is "idle" until it is first initialized.  This allows for the Macros to be set upon first connection

Signed-off-by: Eric Callahan <arksine.code@gmail.com>
2020-12-10 06:29:28 -05:00
KwadFan d19e9e2d28 scripts: add update support to sudo_fix.sh
Signed-off-by: Stephan Wendel <me@stephanwe.de>
2020-12-06 07:39:50 -05:00
Arksine abbd02aa73 scripts: minor fixes
Run the legacy install cleanup after Klipper is detected in install-moonraker.sh

Fix whitespace errros in uninstall-moonraker.sh

Signed-ff-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-06 07:28:11 -05:00
Arksine 1b997b7457 docs: Note changes to install script
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-06 07:05:21 -05:00
Arksine 6dfd3ca915 scripts: install Moonraker as a systemd service
This allows users to view the log using the journalctl command.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-06 06:54:48 -05:00
Arksine aaa6ec8eb2 utils: add support for logging to stdout
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-06 06:54:48 -05:00
Arksine aba5bdf339 docs: add clarification
This clarifies the installation and configuration instructions, updating some outdated info.  Also added is a sample moonraker.conf file.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-05 19:19:13 -05:00
Eric Callahan 43e2893e01 docs: Note supported version of PanelDue Firmware
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-02 07:46:26 -05:00
KwadFan e025a5ce01 make executable by default
Signed-off-by: Stephan Wendel <me@stephanwe.de>
2020-11-30 14:07:14 -05:00
Arksine 2e44766e1e shell_command: check the return code of the proc for success
Add a "get_return_code" method that allows users to fetch the return code after the shell command has executed.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-29 12:12:58 -05:00
KwadFan 77f79fcc20 scripts: add sudo_fix.sh
This script may be used to fix sudo permissions on "custompios" based distributions.

Signed-off-by: Stephan Wendel <me@stephanwe.de>
2020-11-29 07:46:02 -05:00
Arksine 1d0a790ef5 scripts: bump version to 0.2.2
Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-29 07:26:04 -05:00
Arksine e2a8a9b49f update_manager: Add 5 minute timeout to env build
This should remove the necessity of waiting after the shell command.

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-11-29 07:14:21 -05:00
24 changed files with 1119 additions and 322 deletions

No files matched your search

+4 -3
View File
@@ -6,9 +6,10 @@ the Klippy host and Moonraker is done over a Unix Domain Socket. Tornado
is used to provide Moonraker's server functionality.
Note that Moonraker does not come bundled with a client, you will need to
install one. The following web clients are currently available:
install one. The following clients are currently available:
- [Mainsail](https://github.com/meteyou/mainsail) by Meteyou
- [Fluidd](https://github.com/cadriel/fluidd) by Cadriel
- [KlipperScreen](https://github.com/jordanruthe/KlipperScreen) by jordanruthe
### Changes
@@ -17,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) - November 19th 2020
[user_changes.md](/docs/user_changes.md) - December 31st 2020
Developers:\
[api_changes.md](/docs/api_changes.md) - November 28th 2020
[api_changes.md](/docs/api_changes.md) - January 1st 2021
+6
View File
@@ -1,4 +1,10 @@
This document keeps a record of all changes to Moonraker's web APIs.
### 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`.
### November 28th 2020
- The following new endpoints are available when the `[update_manager]`
+53 -7
View File
@@ -1,9 +1,14 @@
This document describes Moonraker's full configuration.
This document describes Moonraker's full configuration. As this file
references configuration for both Klipper (printer.cfg) and Moonraker
(moonraker.conf), each example contains a commment indicating which
configuration file is being refrenenced.
# Primary Configuration
The sections outlined here are required for Moonraker to function. A
minimal functional configuration might look like the following:
```
# moonraker.conf
[server]
host: 0.0.0.0
port: 7125
@@ -19,6 +24,8 @@ trusted_clients:
## server
```
# moonraker.conf
[server]
host: 0.0.0.0
# The host address in which to bind the HTTP server. Default is to bind
@@ -34,15 +41,18 @@ 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.
config_path:
# An optional path where configuration files are located. If specified,
# Moonraker will serve this path allowing file and directory manipulation
# within it. This path must be located within the user's HOME directory,
# by may not be the home directory itself. The default is no path, which
# results in no configuration files being served.
# 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. Note that this may not be the system root
# (ie: "/") and moonraker must have read and write access permissions
# for this directory.
```
## authorization
```
# moonraker.conf
[authorization]
enabled: True
# Enables authorization. When set to true, requests must either contain
@@ -75,9 +85,12 @@ functionality in moonraker.
## 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
converter.
converter. Currently PanelDue Firmware Version 1.24 is supported. Other
releases may not behave correctly.
```
# moonraker.conf
[paneldue]
serial:
# The serial port in which the PanelDue is connected. This parameter
@@ -110,6 +123,8 @@ in the PanelDue's "macro" menu.
Note that buzzing the piezo requires the following gcode_macro in `printer.cfg`:
```
# printer.cfg
[gcode_macro PANELDUE_BEEP]
# Beep frequency
default_parameter_FREQUENCY: 300
@@ -126,6 +141,8 @@ Enables device power control. Currently GPIO (relays), TPLink Smartplug,
and Tasmota (via http) devices are supported.
```
# moonraker.conf
[power device_name]
type: gpio
# The type of device. Can be either gpio, tplink_smartplug or tasmota.
@@ -139,6 +156,10 @@ pin: gpiochip0/gpio26
# !gpiochip0/gpio26
# !gpio26
# This parameter must be provided for "gpio" type devices
initial_state: off
# The initial state for GPIO type devices. May be on or
# off. When moonraker starts the device will be set to this
# state. Default is off.
address:
port:
# The above options are used for "tplink_smartplug" devices. The
@@ -160,13 +181,22 @@ output_id:
```
Below are some potential examples:
```
# moonraker.conf
[power printer]
type: gpio
pin: gpio26
initial_state: off
[power printer_led]
type: gpio
pin: !gpiochip0/gpio16
initial_state: off
[power light_strip]
type: gpio
pin: gpiochip0/gpio17
initial_state: on
[power wifi_switch]
type: tplink_smartplug
@@ -181,6 +211,8 @@ password: password1
It is possible to toggle device power from the Klippy host, this can be done
with a gcode_macro, such as:
```
# printer.cfg
[gcode_macro POWER_OFF_PRINTER]
gcode:
{action_call_remote_method("set_device_power",
@@ -191,6 +223,8 @@ The `POWER_OFF_PRINTER` gcode can be run to turn off the "printer" device.
This could be used in conjunction with Klipper's idle timeout to turn the
printer off when idle with a configuration similar to that of below:
```
# printer.cfg
[delayed_gcode delayed_printer_off]
initial_duration: 0.
gcode:
@@ -211,7 +245,19 @@ performed on pristine git repos. Repos that have been modified on
disk or cloned from unofficial sources are not supported.
```
# moonraker.conf
[update_manager]
enable_repo_debug: False
# When set to True moonraker will bypass repo validation and allow
# updates from unofficial remotes and/or branches. Updates on
# detached repos are also allowed. This option is intended for
# developers and should not be used on production machines. 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
+60 -21
View File
@@ -8,7 +8,8 @@ Python 3 packages meet this requirement.
Klipper should be installed prior to installing Moonraker. Please see
[Klipper's Documention](https://github.com/KevinOConnor/klipper/blob/master/docs/Installation.md)
for instructions on how to do this.
for instructions on how to do this. After installation you should make
sure that the [prerequistes](#prerequisites-klipper-configuration) are configured.
After Klipper is installed, you need to modify its "default" file. This file
contains klipper's command line arguments, and you must add an argument that
@@ -38,8 +39,27 @@ KLIPPY_EXEC=/home/pi/klippy-env/bin/python
KLIPPY_ARGS="/home/pi/klipper/klippy/klippy.py /home/pi/printer.cfg -l /tmp/klippy.log -a /tmp/klippy_uds"
```
You may also want to take this opportunity to change the location of
printer.cfg if you enable Moonraker's "config_path" option (see the
[configuration section](#moonraker-configuration-moonrakerconf) for more information).
printer.cfg to match Moonraker's "config_path" option (see the
[configuration document](configuration.md#primary-configuration)
for more information on the config_path). For example, if the `config_path`
option is set to `~/printer_config`, your klipper defaults file might look
like the following:
```
# Configuration for /etc/init.d/klipper
KLIPPY_USER=pi
KLIPPY_EXEC=/home/pi/klippy-env/bin/python
KLIPPY_ARGS="/home/pi/klipper/klippy/klippy.py /home/pi/printer_config/printer.cfg -l /tmp/klippy.log -a /tmp/klippy_uds"
```
If necessary, create the config directory and move printer.cfg to it:
```
cd ~
mkdir printer_config
mv printer.cfg printer_config
```
You can now install the Moonraker application:
```
@@ -47,12 +67,24 @@ cd ~
git clone https://github.com/Arksine/moonraker.git
```
Finally, run moonraker's install script:
Prior to installation it is a good idea to create
[moonraker.conf](configuration.md). If you are using the `config_path`,
create it in the specified directory otherwise create it in the HOME
directory. A sample `moonraker.conf` may be found in the `docs` folder
of this repo.
For a default installation run the following commands:
```
cd ~/moonraker/scripts
./install-moonraker.sh
```
Or to install with `moonraker.conf` in the `config_path`:
```
cd ~/moonraker/scripts
./install-moonraker.sh -f -c /home/pi/printer_config/moonraker.conf
```
The install script has a few command line options that may be useful,
particularly for those upgrading:
- -r\
@@ -64,24 +96,21 @@ particularly for those upgrading:
detected as present.
- -c /path/to/moonraker.conf\
This allows the user to specify the path to Moonraker's config file.
The default location is "/home/<user>/moonraker.conf".
The default location is `/home/<user>/moonraker.conf`.
When the script completes it should start both Moonraker and Klipper. In
`klippy.log` you should find the following entry:\
`webhooks: New connection established`
`webhooks client <uid>: Client info {'program': 'Moonraker', 'version': '<version>'}`\
Now you may install a client, such as [Mainsail](
https://github.com/meteyou/mainsail).
- Note that as of the time of this writing (August 11 2020) the current version
of Mainsail (0.1.2) is not compatible with this repo. Please give the
developer some time to bring up Mainsail in line with the latest release
of Moonraker.
Now you may install a client, such as
[Mainsail](https://github.com/meteyou/mainsail) or
[Fluidd](https://github.com/cadriel/fluidd)
## Command line Usage
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
@@ -91,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)
@@ -120,10 +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 requires that the path
be located within the HOME directory, it cannot however be the HOME
directory. If you wish to host your files elsewhere, use a symlink.
- 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.
+15
View File
@@ -0,0 +1,15 @@
# Sample Moonraker Configuration File
[server]
# Bind server defaults of 0.0.0.0, port 7125
enable_debug_logging: True
config_path: ~/printer_config
[authorization]
enabled: True
trusted_clients:
# Enter your client IP here or range here
192.168.1.0/24
cors_domains:
# Allow CORS requests for Fluidd
http://app.fluidd.xyz
+20
View File
@@ -1,6 +1,26 @@
This file will track changes that require user intervention,
such as a configuration change or a reinstallation.
### 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
to stdout which can be viewed with the `journalctl -u moonraker` command.
This changes requires the user to rerun the install script. If
`moonraker.conf` is not located in the home directory, the command
will looks something like the following:
```
cd ~/moonraker
./scripts/install-moonraker.sh -f -c /home/pi/klipper_config/moonraker.conf
```
Otherwise you can run the install script with no arguments.
### November 19th 2020
- The install script (`install-moonraker.sh`) now has command-line
options:\
+54 -8
View File
@@ -844,41 +844,78 @@ information.
{
'version_info': {
'moonraker': {
branch: <string>,
remote_alias: <string>,
version: <string>,
remote_version: <string>,
current_hash: <string>,
remote_hash: <string>,
is_valid: <bool>,
is_dirty: <bool>
is_dirty: <bool>,
detached: <bool>,
debug_enabled: <bool>
},
'klipper': {
branch: <string>,
remote_alias: <string>,
version: <string>,
remote_version: <string>,
current_hash: <string>,
remote_hash: <string>,
is_valid: <bool>,
is_dirty: <bool>
}
is_dirty: <bool>,
detached: <bool>,
debug_enabled: <bool>
},
'client': {
name: <string>,
version: <string>,
remote_version: <string>
},
'system': {
package_count: <int>,
package_list: <array>
}
},
busy: false
busy: false,
github_rate_limit: <int>,
github_requests_remaining: <int>
github_limit_reset_time: <int>,
}
```
- The `busy` field is set to true if an update is in progress. Moonraker
will not allow concurrent updates.
- The `github_rate_limit` is the maximum number of github API requests
the user currently has. An unathenticated user typically has 60
requests per hour.
- The `github_requests_remaining` is the number of API request the user
currently has remaining.
- The `github_limit_reset_time` is reported as seconds since the epoch.
When this time is reached the user's limit will be reset.
- The `moonraker` and `klipper` objects have the following fields:
- `branch`: the name of the current git branch. This should typically
be "master".
- `remote_alias`: the alias for the remote. This should typically be
"origin".
- `version`: version of the current repo on disk
- `remote_version`: version of the latest available update
- `current_hash`: hash of the most recent commit on disk
- `remote_hash`: hash of the most recent commit pushed to the remote
- `is_valid`: True if installation is a valid git repo on the master branch
and an "origin" set to the official remote
- `is_dirty`: True if the repo has been modified
- `detached`: True if the repo is currently in a detached state
- `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:
`name`: Name of the configured client
`version`: version of the installed client.
`remote_version`: version of the latest release published to GitHub
- `name`: Name of the configured client
- `version`: version of the installed client.
- `remote_version`: version of the latest release published to GitHub
- 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
for update
### Update Moonraker
Pulls the most recent version of Moonraker from GitHub and restarts
@@ -1067,6 +1104,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
@@ -1159,7 +1201,8 @@ Where `response` is an object int he following format:
{
application: <string>,
proc_id: <int>,
message: <string>
message: <string>,
complete: <boolean>
}
```
- The `application` field contains the name of application currently being
@@ -1169,6 +1212,9 @@ Where `response` is an object int he following format:
process. This id is generated for each update request.
- The `message` field contains an asyncronous message sent during the update
process.
- The `complete` field is set to true on the final message sent during an
update, indicating that the update completed successfully. Otherwise it
will be false.
# Appendix
+6 -2
View File
@@ -24,6 +24,7 @@ RESERVED_ENDPOINTS = [
]
EXCLUDED_ARGS = ["_", "token", "connection_id"]
DEFAULT_KLIPPY_LOG_PATH = "/tmp/klippy.log"
# Status objects require special parsing
def _status_parser(request_handler):
@@ -130,7 +131,10 @@ 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)
self.register_static_file_handler(
"klippy.log", DEFAULT_KLIPPY_LOG_PATH)
self.auth.register_handlers(self)
def listen(self, host, port):
@@ -329,7 +333,7 @@ class FileRequestHandler(AuthorizedFileHandler):
async def delete(self, path):
path = self.request.path.lstrip("/").split("/", 2)[-1]
path = url_unescape(path)
path = url_unescape(path, plus=False)
file_manager = self.server.lookup_plugin('file_manager')
try:
filename = await file_manager.delete_file(path)
+13
View File
@@ -34,6 +34,9 @@ class ConfigHelper:
def get_name(self):
return self.section
def get_options(self):
return dict(self.config[self.section])
def get_prefix_sections(self, prefix):
return [s for s in self.sections() if s.startswith(prefix)]
@@ -70,6 +73,16 @@ class ConfigHelper:
return self._get_item(
self.config[self.section].getfloat, option, default)
def read_supplemental_config(self, file_name):
cfg_file_path = os.path.normpath(os.path.expanduser(file_name))
if not os.path.isfile(cfg_file_path):
raise ConfigError(
f"Configuration File Not Found: '{cfg_file_path}''")
try:
self.config.read(cfg_file_path)
except Exception:
raise ConfigError(f"Error Reading Config: '{cfg_file_path}'")
def get_configuration(server, system_args):
cfg_file_path = os.path.normpath(os.path.expanduser(
system_args.configfile))
Regular → Executable
+12 -3
View File
@@ -1,3 +1,4 @@
#!/usr/bin/env python3
# Moonraker - HTTP/Websocket API Server for Klipper
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
@@ -285,10 +286,11 @@ class Server:
f"Klippy may have experienced an error during startup.\n"
f"Please check klippy.log for more information")
return
if send_id:
self.init_list.append("identified")
self.klippy_info = dict(result)
self.klippy_state = result.get('state', "unknown")
if send_id:
self.init_list.append("identified")
self.send_event("server:klippy_identified")
if self.klippy_state == "ready":
await self._verify_klippy_requirements()
logging.info("Klippy ready")
@@ -549,11 +551,18 @@ 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)
+33 -12
View File
@@ -45,7 +45,7 @@ class FileManager:
self.server.register_upload_handler("/api/files/local")
self.server.register_event_handler(
"server:klippy_ready", self._update_fixed_paths)
"server:klippy_identified", self._update_fixed_paths)
# Register Klippy Configuration Path
config_path = config.get('config_path', None)
@@ -83,14 +83,21 @@ class FileManager:
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 not path.startswith(home) or \
path == home:
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
@@ -373,8 +380,7 @@ class FileManager:
full_path = root_path
dir_path = ""
else:
parts = os.path.split(upload['filename'].strip().lstrip("/"))
filename = os.path.join(parts[0], "_".join(parts[1].split()))
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))
@@ -448,12 +454,24 @@ 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)
fname = full_path[len(path) + 1:]
finfo = self._get_path_info(full_path)
filelist[fname] = finfo
@@ -653,8 +671,11 @@ class MetadataStorage:
self.busy = False
async def _run_extract_metadata(self, filename, notify):
# Escape single quotes in the file name so that it may be
# properly loaded
filename = filename.replace("\"", "\\\"")
cmd = " ".join([sys.executable, METADATA_SCRIPT, "-p",
self.gc_path, "-f", "'" + filename + "'"])
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)
+2
View File
@@ -80,6 +80,8 @@ class KlippyAPI:
# XXX - validate that file is on disk
if filename[0] == '/':
filename = filename[1:]
# Escape existing double quotes in the file name
filename = filename.replace("\"", "\\\"")
script = f'SDCARD_PRINT_FILE FILENAME="{filename}"'
return await self.run_gcode(script)
+149 -90
View File
@@ -9,13 +9,14 @@ import time
import json
import errno
import logging
import asyncio
from collections import deque
from utils import ServerError
from tornado import gen
from tornado.ioloop import IOLoop
from tornado.locks import Lock
MIN_EST_TIME = 10.
INITIALIZE_TIMEOUT = 10.
class PanelDueError(ServerError):
pass
@@ -29,13 +30,15 @@ class SerialConnection:
self.paneldue = paneldue
self.port = config.get('serial')
self.baud = config.getint('baud', 57600)
self.sendlock = Lock()
self.partial_input = b""
self.ser = self.fd = None
self.connected = False
self.send_busy = False
self.send_buffer = b""
self.attempting_connect = True
self.ioloop.spawn_callback(self._connect)
def disconnect(self):
def disconnect(self, reconnect=False):
if self.connected:
if self.fd is not None:
self.ioloop.remove_handler(self.fd)
@@ -43,7 +46,13 @@ class SerialConnection:
self.connected = False
self.ser.close()
self.ser = None
self.partial_input = b""
self.send_buffer = b""
self.paneldue.initialized = False
logging.info("PanelDue Disconnected")
if reconnect and not self.attempting_connect:
self.attempting_connect = True
self.ioloop.call_later(1., self._connect)
async def _connect(self):
start_time = connect_time = time.time()
@@ -69,11 +78,12 @@ class SerialConnection:
self.fd, self._handle_incoming, IOLoop.READ | IOLoop.ERROR)
self.connected = True
logging.info("PanelDue Connected")
self.attempting_connect = False
def _handle_incoming(self, fd, events):
if events & IOLoop.ERROR:
logging.info("PanelDue Connection Error")
self.disconnect()
self.disconnect(reconnect=True)
return
# Process incoming data using same method as gcode.py
try:
@@ -83,49 +93,51 @@ class SerialConnection:
if not data:
# possibly an error, disconnect
self.disconnect()
self.disconnect(reconnect=True)
logging.info("serial_display: No data received, disconnecting")
return
self.ioloop.spawn_callback(self._process_data, data)
async def _process_data(self, data):
# Remove null bytes, separate into lines
data = data.strip(b'\x00')
lines = data.split(b'\n')
lines[0] = self.partial_input + lines[0]
self.partial_input = lines.pop()
for line in lines:
line = line.strip().decode()
try:
await self.paneldue.process_line(line)
line = line.strip().decode('utf-8', 'ignore')
self.paneldue.process_line(line)
except ServerError:
logging.exception(
"GCode Processing Error: " + line)
f"GCode Processing Error: {line}")
self.paneldue.handle_gcode_response(
"!! GCode Processing Error: " + line)
f"!! GCode Processing Error: {line}")
except Exception:
logging.exception("Error during gcode processing")
async def send(self, data):
if self.connected:
async with self.sendlock:
while data:
try:
sent = os.write(self.fd, data)
except os.error as e:
if e.errno == errno.EBADF or e.errno == errno.EPIPE:
sent = 0
else:
await gen.sleep(.001)
continue
if sent:
data = data[sent:]
else:
logging.exception(
"Error writing data, closing serial connection")
self.disconnect()
return
def send(self, data):
self.send_buffer += data
if not self.send_busy:
self.send_busy = True
self.ioloop.spawn_callback(self._do_send)
async def _do_send(self):
while self.send_buffer:
try:
sent = os.write(self.fd, self.send_buffer)
except os.error as e:
if e.errno == errno.EBADF or e.errno == errno.EPIPE:
sent = 0
else:
await gen.sleep(.001)
continue
if sent:
self.send_buffer = self.send_buffer[sent:]
else:
logging.exception(
"Error writing data, closing serial connection")
self.disconnect(reconnect=True)
return
self.send_busy = False
class PanelDue:
def __init__(self, config):
@@ -153,7 +165,12 @@ class PanelDue:
self.heaters = []
self.is_ready = False
self.is_shutdown = False
self.last_printer_state = 'C'
self.initialized = False
self.cq_busy = self.gq_busy = False
self.command_queue = []
self.gc_queue = []
self.last_printer_state = 'O'
self.last_update_time = 0.
# Set up macros
self.confirmed_gcode = ""
@@ -277,31 +294,32 @@ class PanelDue:
self.is_shutdown = False
self.is_ready = True
async def _process_klippy_shutdown(self):
def _process_klippy_shutdown(self):
self.is_shutdown = True
async def _process_klippy_disconnect(self):
# Tell the PD that we are shutting down
await self.write_response({'status': 'S'})
self.is_ready = False
def _process_klippy_disconnect(self):
# Tell the PD that the printer is "off"
self.write_response({'status': 'O'})
self.last_printer_state = 'O'
self.is_shutdown = self.is_shutdown = False
async def handle_status_update(self, status):
def handle_status_update(self, status):
for obj, items in status.items():
if obj in self.printer_state:
self.printer_state[obj].update(items)
else:
self.printer_state[obj] = items
async def paneldue_beep(self, frequency, duration):
def paneldue_beep(self, frequency, duration):
duration = int(duration * 1000.)
await self.write_response(
self.write_response(
{'beep_freq': frequency, 'beep_length': duration})
async def process_line(self, line):
def process_line(self, line):
self.debug_queue.append(line)
# If we find M112 in the line then skip verification
if "M112" in line.upper():
await self.klippy_apis.emergency_stop()
self.ioloop.spawn_callback(self.klippy_apis.emergency_stop)
return
if self.enable_checksum:
@@ -337,31 +355,36 @@ class PanelDue:
logging.info("PanelDue: " + msg)
raise PanelDueError(msg)
await self._run_gcode(line[line_index+1:cs_index])
script = line[line_index+1:cs_index]
else:
await self._run_gcode(line)
async def _run_gcode(self, script):
script = line
# Execute the gcode. Check for special RRF gcodes that
# 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()
val = int(p[1:].strip()) if arg in "sr" \
else p[1:].strip(" \"\t\n")
except Exception:
msg = f"paneldue: Error parsing direct gcode {script}"
self.handle_gcode_response("!! " + msg)
logging.exception(msg)
return
params["arg_" + arg] = val
params[f"arg_{arg}"] = val
func = self.direct_gcodes[cmd]
await func(**params)
self.queue_command(func, **params)
return
# Prepare GCodes that require special handling
@@ -371,18 +394,48 @@ class PanelDue:
if not script:
return
elif script in RESTART_GCODES:
await self.klippy_apis.do_restart(script)
return
self.queue_gcode(script)
try:
await self.klippy_apis.run_gcode(script)
except self.server.error:
msg = f"Error executing script {script}"
self.handle_gcode_response("!! " + msg)
logging.exception(msg)
def queue_gcode(self, script):
self.gc_queue.append(script)
if not self.gq_busy:
self.gq_busy = True
self.ioloop.spawn_callback(self._process_gcode_queue)
async def _process_gcode_queue(self):
while self.gc_queue:
script = self.gc_queue.pop(0)
try:
if script in RESTART_GCODES:
await self.klippy_apis.do_restart(script)
else:
await self.klippy_apis.run_gcode(script)
except self.server.error:
msg = f"Error executing script {script}"
self.handle_gcode_response("!! " + msg)
logging.exception(msg)
self.gq_busy = False
def queue_command(self, cmd, *args, **kwargs):
self.command_queue.append((cmd, args, kwargs))
if not self.cq_busy:
self.cq_busy = True
self.ioloop.spawn_callback(self._process_command_queue)
async def _process_command_queue(self):
while self.command_queue:
cmd, args, kwargs = self.command_queue.pop(0)
try:
ret = cmd(*args, **kwargs)
if asyncio.iscoroutine(ret):
await ret
except Exception:
logging.exception("Error processing command")
self.cq_busy = False
def _clean_filename(self, filename):
# Remove quotes and whitespace
filename.strip(" \"\t\n")
# Remove drive number
if filename.startswith("0:/"):
filename = filename[3:]
@@ -399,15 +452,17 @@ class PanelDue:
return filename
def _prepare_M23(self, args):
filename = self._clean_filename(args[0].strip())
return "M23 " + filename
filename = self._clean_filename(args[0])
return f"M23 {filename}"
def _prepare_M32(self, args):
filename = self._clean_filename(args[0].strip())
return "SDCARD_PRINT_FILE FILENAME=" + filename
filename = self._clean_filename(args[0])
# Escape existing double quotes in the file name
filename = filename.replace("\"", "\\\"")
return f"SDCARD_PRINT_FILE FILENAME=\"{filename}\""
def _prepare_M98(self, args):
macro = args[0][1:].strip()
macro = args[0][1:].strip(" \"\t\n")
name_start = macro.rfind('/') + 1
macro = macro[name_start:]
cmd = self.available_macros.get(macro)
@@ -444,7 +499,8 @@ class PanelDue:
mbox['msgBox.title'] = title
mbox['msgBox.controls'] = 0
mbox['msgBox.timeout'] = 0
self.ioloop.spawn_callback(self.write_response, mbox)
logging.debug(f"Creating PanelDue Confirmation: {mbox}")
self.write_response(mbox)
def handle_gcode_response(self, response):
# Only queue up "non-trivial" gcode responses. At the
@@ -458,9 +514,9 @@ class PanelDue:
self.last_gcode_response = response
return
async def write_response(self, response):
def write_response(self, response):
byte_resp = json.dumps(response) + "\r\n"
await self.ser_conn.send(byte_resp.encode())
self.ser_conn.send(byte_resp.encode())
def _get_printer_status(self):
# PanelDue States applicable to Klipper:
@@ -471,8 +527,6 @@ class PanelDue:
return 'S'
printer_state = self.printer_state
p_busy = printer_state['idle_timeout'].get(
'state', 'Idle') == "Printing"
sd_state = printer_state['print_stats'].get('state', "standby")
if sd_state == "printing":
if self.last_printer_state == 'A':
@@ -481,37 +535,41 @@ class PanelDue:
# Printing
return 'P'
elif sd_state == "paused":
if p_busy and self.last_printer_state != 'A':
p_active = printer_state['idle_timeout'].get(
'state', 'Idle') == "Printing"
if p_active and self.last_printer_state != 'A':
# Pausing
return 'D'
else:
# Paused
return 'A'
if p_busy:
# Printer is "busy"
return 'B'
return 'I'
async def _run_paneldue_M408(self, arg_r=None, arg_s=1):
def _run_paneldue_M408(self, arg_r=None, arg_s=1):
response = {}
sequence = arg_r
response_type = arg_s
if not self.is_ready:
# Klipper is still starting up, do not query status
self.last_printer_state = 'S' if self.is_shutdown else 'C'
response['status'] = self.last_printer_state
await self.write_response(response)
return
curtime = self.ioloop.time()
if curtime - self.last_update_time > INITIALIZE_TIMEOUT:
self.initialized = False
self.last_update_time = curtime
# Send gcode responses
if not self.initialized:
response['dir'] = "/macros"
response['files'] = list(self.available_macros.keys())
self.initialized = True
if not self.is_ready:
self.last_printer_state = 'O'
response['status'] = self.last_printer_state
self.write_response(response)
return
if sequence is not None and self.last_gcode_response:
# Send gcode responses
response['seq'] = sequence + 1
response['resp'] = self.last_gcode_response
self.last_gcode_response = None
if response_type == 1:
# Extended response Request
response['myName'] = self.machine_name
@@ -611,9 +669,9 @@ class PanelDue:
# is strange about this, and displays it as a full screen
# notification
self.last_message = msg
await self.write_response(response)
self.write_response(response)
async def _run_paneldue_M20(self, arg_p, arg_s=0):
def _run_paneldue_M20(self, arg_p, arg_s=0):
response_type = arg_s
if response_type != 2:
logging.info(
@@ -651,7 +709,7 @@ class PanelDue:
flist = self.file_manager.list_dir(path, simple_format=True)
if flist:
response['files'] = flist
await self.write_response(response)
self.write_response(response)
async def _run_paneldue_M30(self, arg_p=None):
# Delete a file. Clean up the file name and make sure
@@ -667,7 +725,7 @@ class PanelDue:
path = "gcodes/" + path
await self.file_manager.delete_file(path)
async def _run_paneldue_M36(self, arg_p=None):
def _run_paneldue_M36(self, arg_p=None):
response = {}
filename = arg_p
sd_status = self.printer_state.get('virtual_sdcard', {})
@@ -682,16 +740,17 @@ class PanelDue:
if not filename or not active:
# Either no file printing or no virtual_sdcard
response['err'] = 1
await self.write_response(response)
self.write_response(response)
return
else:
response['fileName'] = filename.split("/")[-1]
# For consistency make sure that the filename begins with the
# "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
@@ -718,9 +777,9 @@ class PanelDue:
response['printTime'] = int(est_time + .5)
else:
response['err'] = 1
await self.write_response(response)
self.write_response(response)
async def close(self):
def close(self):
self.ser_conn.disconnect()
msg = "\nPanelDue GCode Dump:"
for i, gc in enumerate(self.debug_queue):
+6 -4
View File
@@ -164,7 +164,8 @@ 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")
self.set_power("off")
initial_state = config.getboolean('initial_state', False)
self.set_power("on" if initial_state else "off")
def _parse_pin(self, config):
pin = cfg_pin = config.get("pin")
@@ -351,11 +352,12 @@ class Tasmota:
if command in ["on", "off"]:
out_cmd = f"Power{self.output_id}%20{command}"
elif command == "info":
out_cmd = "Power{self.output_id}"
out_cmd = f"Power{self.output_id}"
else:
raise self.server.error(f"Invalid tasmota command: {command}")
url = f"http://{self.addr}/cm?user=admin&password={self.password}&cmnd={out_cmd}"
url = f"http://{self.addr}/cm?user=admin&password=" \
f"{self.password}&cmnd={out_cmd}"
data = ""
http_client = AsyncHTTPClient()
try:
+20 -9
View File
@@ -20,6 +20,7 @@ class ShellCommand:
self.command = shlex.split(cmd)
self.partial_output = b""
self.cancelled = False
self.return_code = None
def _process_output(self, fd, events):
if events & IOLoop.ERROR:
@@ -40,8 +41,13 @@ class ShellCommand:
def cancel(self):
self.cancelled = True
def get_return_code(self):
return self.return_code
async def run(self, timeout=2., verbose=True):
fd = None
self.return_code = fd = None
self.partial_output = b""
self.cancelled = False
if timeout is None:
# Never timeout
timeout = 9999999999999999.
@@ -79,15 +85,20 @@ class ShellCommand:
if self.partial_output:
self.output_cb(self.partial_output)
self.partial_output = b""
if complete:
msg = f"Command ({self.name}) finished"
elif self.cancelled:
msg = f"Command ({self.name}) cancelled"
else:
msg = f"Command ({self.name}) timed out"
logging.info(msg)
self.io_loop.remove_handler(fd)
return complete
self.return_code = proc.returncode
success = self.return_code == 0 and complete
if success:
msg = f"Command ({self.name}) successfully finished"
elif self.cancelled:
msg = f"Command ({self.name}) cancelled"
elif not complete:
msg = f"Command ({self.name}) timed out"
else:
msg = f"Command ({self.name}) exited with return code" \
f" {self.return_code}"
logging.info(msg)
return success
async def run_with_response(self, timeout=2.):
result = []
+378 -129
View File
@@ -11,44 +11,37 @@ import sys
import shutil
import zipfile
import io
import asyncio
import time
import tornado.gen
from tornado.ioloop import IOLoop
from tornado.httpclient import AsyncHTTPClient, HTTPRequest
from tornado.httpclient import AsyncHTTPClient
from tornado.locks import Event
MOONRAKER_PATH = os.path.normpath(os.path.join(
os.path.dirname(__file__), "../.."))
# TODO: May want to attempt to look up the disto for the correct
# klippy install script or have the user configure it
SUPPLEMENTAL_CFG_PATH = os.path.join(
MOONRAKER_PATH, "scripts/update_manager.conf")
APT_CMD = "sudo DEBIAN_FRONTEND=noninteractive apt-get"
REPO_PREFIX = "https://api.github.com/repos"
REPO_DATA = {
'moonraker': {
'repo_url': f"{REPO_PREFIX}/arksine/moonraker/branches/master",
'origin': "https://github.com/Arksine/moonraker.git",
'install_script': "scripts/install-moonraker.sh",
'requirements': "scripts/moonraker-requirements.txt",
'venv_args': "-p python3 --system-site-packages"
},
'klipper': {
'repo_url': f"{REPO_PREFIX}/kevinoconnor/klipper/branches/master",
'origin': "https://github.com/KevinOConnor/klipper.git",
'install_script': "scripts/install-octopi.sh",
'requirements': "scripts/klippy-requirements.txt",
'venv_args': "-p python2"
}
}
SUPPORTED_DISTROS = ["debian"]
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()
sw_version = config['system_args'].get('software_version')
self.repo_debug = config.getboolean('enable_repo_debug', 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
self.updaters = {
"system": PackageUpdater(self),
"moonraker": GitUpdater(self, "moonraker", MOONRAKER_PATH,
sw_version, sys.executable)
"moonraker": GitUpdater(self, "moonraker", MOONRAKER_PATH, env)
}
self.current_update = None
client_repo = config.get("client_repo", None)
@@ -60,6 +53,12 @@ class UpdateManager:
self.updaters['client'] = ClientUpdater(
self, client_repo, client_path)
# 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.server.register_endpoint(
"/machine/update/moonraker", ["POST"],
self._handle_update_request)
@@ -78,7 +77,9 @@ class UpdateManager:
# Register Ready Event
self.server.register_event_handler(
"server:klippy_ready", self._set_klipper_repo)
"server:klippy_identified", self._set_klipper_repo)
# Initialize GitHub API Rate Limits
IOLoop.current().spawn_callback(self._init_api_rate_limit)
async def _set_klipper_repo(self):
kinfo = self.server.get_klippy_info()
@@ -86,14 +87,13 @@ class UpdateManager:
logging.info("No valid klippy info received")
return
kpath = kinfo['klipper_path']
kversion = kinfo['software_version']
env = kinfo['python_path']
self.updaters['klipper'] = GitUpdater(
self, "klipper", kpath, kversion, env)
async def _check_versions(self):
for updater in self.updaters.values():
await updater.check_remote_version()
kupdater = self.updaters.get('klipper', None)
if kupdater is not None and kupdater.repo_path == kpath and \
kupdater.env == env:
# Current Klipper Updater is valid
return
self.updaters['klipper'] = GitUpdater(self, "klipper", kpath, env)
async def _handle_update_request(self, web_request):
app = web_request.get_endpoint().split("/")[-1]
@@ -113,14 +113,21 @@ class UpdateManager:
return "ok"
async def _handle_status_request(self, web_request):
if web_request.get_boolean('refresh', False):
await self._check_versions()
refresh = web_request.get_boolean('refresh', False)
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()
return {
'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}
async def execute_cmd(self, cmd, timeout=10., notify=False, retries=1):
@@ -139,40 +146,122 @@ class UpdateManager:
scmd = shell_command.build_shell_command(cmd, None)
return await scmd.run_with_response(timeout)
async def github_request(self, url, is_download=False):
cto = rto = 5.
content_type = "application/vnd.github.v3+json"
if is_download:
content_type = "application/zip"
rto = 120.
timeout = cto + rto + 2.
request = HTTPRequest(url, headers={"Accept": content_type},
connect_timeout=cto, request_timeout=rto)
retries = 5
while True:
to = IOLoop.current().time() + timeout
async def _init_api_rate_limit(self):
url = "https://api.github.com/rate_limit"
while 1:
try:
fut = self.http_client.fetch(request)
resp = await tornado.gen.with_timeout(to, fut)
except Exception as e:
resp = await self.github_api_request(url, is_init=True)
core = resp['resources']['core']
self.gh_rate_limit = core['limit']
self.gh_limit_remaining = core['remaining']
self.gh_limit_reset_time = core['reset']
except Exception:
logging.exception("Error Initializing GitHub API Rate Limit")
await tornado.gen.sleep(30.)
else:
reset_time = time.ctime(self.gh_limit_reset_time)
logging.info(
"GitHub API Rate Limit Initialized\n"
f"Rate Limit: {self.gh_rate_limit}\n"
f"Rate Limit Remaining: {self.gh_limit_remaining}\n"
f"Rate Limit Reset Time: {reset_time}, "
f"Seconds Since Epoch: {self.gh_limit_reset_time}")
break
self.gh_init_evt.set()
async def github_api_request(self, url, etag=None, is_init=False):
if not is_init:
timeout = time.time() + 30.
try:
await self.gh_init_evt.wait(timeout)
except Exception:
raise self.server.error(
"Timeout while waiting for GitHub "
"API Rate Limit initialization")
if self.gh_limit_remaining == 0:
curtime = time.time()
if curtime < self.gh_limit_reset_time:
raise self.server.error(
f"GitHub Rate Limit Reached\nRequest: {url}\n"
f"Limit Reset Time: {time.ctime(self.gh_limit_remaining)}")
headers = {"Accept": "application/vnd.github.v3+json"}
if etag is not None:
headers['If-None-Match'] = etag
retries = 5
while retries:
try:
resp = await self.http_client.fetch(
url, headers=headers, connect_timeout=5.,
request_timeout=5., raise_error=False)
except Exception:
retries -= 1
msg = f"Error Processing GitHub API request: {url}"
if not retries:
raise self.server.error(msg)
logging.exception(msg)
await tornado.gen.sleep(1.)
continue
etag = resp.headers.get('etag', None)
if etag is not None:
if etag[:2] == "W/":
etag = etag[2:]
logging.info(
"GitHub API Request Processed\n"
f"URL: {url}\n"
f"Response Code: {resp.code}\n"
f"Response Reason: {resp.reason}\n"
f"ETag: {etag}")
if resp.code == 403:
raise self.server.error(
f"Forbidden GitHub Request: {resp.reason}")
elif resp.code == 304:
logging.info(f"Github Request not Modified: {url}")
return None
if resp.code != 200:
retries -= 1
if not retries:
raise
logging.info(f"Github request error, retrying: {e}")
raise self.server.error(
f"Github Request failed: {resp.code} {resp.reason}")
logging.info(
f"Github request error, {retries} retries remaining")
await tornado.gen.sleep(1.)
continue
if is_download:
return resp.body
# Update rate limit on return success
if 'X-Ratelimit-Limit' in resp.headers and not is_init:
self.gh_rate_limit = int(resp.headers['X-Ratelimit-Limit'])
self.gh_limit_remaining = int(
resp.headers['X-Ratelimit-Remaining'])
self.gh_limit_reset_time = float(
resp.headers['X-Ratelimit-Reset'])
decoded = json.loads(resp.body)
decoded['etag'] = etag
return decoded
def notify_update_response(self, resp):
async def http_download_request(self, url):
retries = 5
while retries:
try:
resp = await self.http_client.fetch(
url, headers={"Accept": "application/zip"},
connect_timeout=5., request_timeout=120.)
except Exception:
retries -= 1
logging.exception("Error Processing Download")
if not retries:
raise
await tornado.gen.sleep(1.)
continue
return resp.body
def notify_update_response(self, resp, is_complete=False):
resp = resp.strip()
if isinstance(resp, bytes):
resp = resp.decode()
notification = {
'message': resp,
'application': None,
'proc_id': None}
'proc_id': None,
'complete': is_complete}
if self.current_update is not None:
notification['application'] = self.current_update[0]
notification['proc_id'] = self.current_update[1]
@@ -184,24 +273,26 @@ class UpdateManager:
class GitUpdater:
def __init__(self, umgr, name, path, ver, env):
def __init__(self, umgr, name, path, env):
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
self.github_request = umgr.github_request
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.repo_path = path
self.env = env
self.version = self.cur_hash = self.remote_hash = "?"
self.is_valid = False
self.is_dirty = ver.endswith("dirty")
tag_version = "?"
ver_match = re.match(r"v\d+\.\d+\.\d-\d+", ver)
if ver_match:
tag_version = ver_match.group()
self.version = tag_version
IOLoop.current().spawn_callback(self._init_repo)
self.version = self.cur_hash = "?"
self.remote_version = self.remote_hash = "?"
self.init_evt = Event()
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")
@@ -234,55 +325,110 @@ class GitUpdater:
log_msg = f"Repo {self.name}: {msg}"
logging.info(log_msg)
def _notify_status(self, msg):
def _notify_status(self, msg, is_complete=False):
log_msg = f"Repo {self.name}: {msg}"
logging.debug(log_msg)
self.notify_update_response(log_msg)
self.notify_update_response(log_msg, is_complete)
async def _init_repo(self):
self.is_valid = False
self.cur_hash = "?"
async def check_initialized(self, timeout=None):
if self.init_evt.is_set():
return
if timeout is not None:
timeout = IOLoop.current().time() + timeout
await self.init_evt.wait(timeout)
async def refresh(self):
await self._check_version()
self.init_evt.set()
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 = "?"
try:
branch = await self.execute_cmd_with_response(
f"git -C {self.repo_path} rev-parse --abbrev-ref HEAD")
origin = await self.execute_cmd_with_response(
f"git -C {self.repo_path} remote get-url origin")
hash = await self.execute_cmd_with_response(
blist = await self.execute_cmd_with_response(
f"git -C {self.repo_path} branch --list")
if blist.startswith("fatal:"):
self._log_info(f"Invalid git repo at path '{self.repo_path}'")
return
branch = None
for b in blist.split("\n"):
b = b.strip()
if b[0] == "*":
branch = b[2:]
break
if branch is None:
self._log_info(
"Unable to retreive current branch from branch list\n"
f"{blist}")
return
if "HEAD detached" in branch:
bparts = branch.split()[-1].strip("()")
self.remote, self.branch = bparts.split("/")
self.detached = True
else:
self.branch = branch.strip()
self.remote = await self.execute_cmd_with_response(
f"git -C {self.repo_path} config --get"
f" branch.{self.branch}.remote")
if need_fetch:
await self.execute_cmd(
f"git -C {self.repo_path} fetch {self.remote} --prune -q",
retries=3)
remote_url = await self.execute_cmd_with_response(
f"git -C {self.repo_path} remote get-url {self.remote}")
cur_hash = await self.execute_cmd_with_response(
f"git -C {self.repo_path} rev-parse HEAD")
remote_hash = await self.execute_cmd_with_response(
f"git -C {self.repo_path} rev-parse "
f"{self.remote}/{self.branch}")
repo_version = await self.execute_cmd_with_response(
f"git -C {self.repo_path} describe --always "
"--tags --long --dirty")
remote_version = await self.execute_cmd_with_response(
f"git -C {self.repo_path} describe {self.remote}/{self.branch}"
" --always --tags --long")
except Exception:
self._log_exc("Error retreiving git info")
return
if not branch.startswith("fatal:"):
self.cur_hash = hash
if branch == "master":
if origin == REPO_DATA[self.name]['origin']:
self.is_valid = True
self._log_info("Validity check for git repo passed")
else:
self._log_info(f"Invalid git origin '{origin}''")
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)
if ver_match:
tag_version = ver_match.group()
versions.append(tag_version)
self.version, self.remote_version = versions
self.cur_hash = cur_hash.strip()
self.remote_hash = remote_hash.strip()
self._log_info(
f"Repo Detected:\nPath: {self.repo_path}\nRemote: {self.remote}\n"
f"Branch: {self.branch}\nRemote URL: {remote_url}\n"
f"Current SHA: {self.cur_hash}\n"
f"Remote SHA: {self.remote_hash}\nVersion: {self.version}\n"
f"Remote Version: {self.remote_version}\n"
f"Is Dirty: {self.is_dirty}\nIs Detached: {self.detached}")
if self.debug:
self.is_valid = True
self._log_info("Debug enabled, bypassing official repo check")
elif self.branch == "master" and self.remote == "origin":
if self.detached:
self._log_info("Detached HEAD detected, repo invalid")
return
remote_url = remote_url.lower()
if remote_url[-4:] != ".git":
remote_url += ".git"
if remote_url == self.repo_info['origin']:
self.is_valid = True
self._log_info("Validity check for git repo passed")
else:
self._log_info("Git repo not on master branch")
self._log_info(f"Invalid git origin url '{remote_url}'")
else:
self._log_info(f"Invalid git repo at path '{self.repo_path}''")
try:
await self.check_remote_version()
except Exception:
pass
async def check_remote_version(self):
repo_url = REPO_DATA[self.name]['repo_url']
try:
branch_info = await self.github_request(repo_url)
except Exception:
raise self._log_exc(f"Error retreiving github info")
commit_hash = branch_info.get('commit', {}).get('sha', None)
if commit_hash is None:
self.is_valid = False
self.upstream_version = "?"
raise self._log_exc(f"Invalid github response", False)
self._log_info(f"Received latest commit hash: {commit_hash}")
self.remote_hash = commit_hash
self._log_info(
"Git repo not on offical remote/branch: "
f"{self.remote}/{self.branch}")
async def update(self, update_deps=False):
if not self.is_valid:
@@ -290,14 +436,21 @@ class GitUpdater:
if self.is_dirty:
raise self._log_exc(
"Update aborted, repo is has been modified", False)
if self.remote_hash == "?":
await self.check_remote_version()
if self.remote_hash == self.cur_hash:
# No need to update
return
self._notify_status("Updating Repo...")
try:
await self.execute_cmd(f"git -C {self.repo_path} pull -q")
if self.detached:
await self.execute_cmd(
f"git -C {self.repo_path} fetch {self.remote} -q",
retries=3)
await self.execute_cmd(
f"git -C {self.repo_path} checkout"
f" {self.remote}/{self.branch} -q")
else:
await self.execute_cmd(
f"git -C {self.repo_path} pull -q", retries=3)
except Exception:
raise self._log_exc("Error running 'git pull'")
# Check Semantic Versions
@@ -308,16 +461,23 @@ class GitUpdater:
if update_deps:
await self._install_packages()
await self._update_virtualenv(need_env_rebuild)
elif need_env_rebuild:
await self._update_virtualenv(True)
# Refresh local repo state
await self._check_version(need_fetch=False)
if self.name == "moonraker":
# Launch restart async so the request can return
# before the server restarts
IOLoop.current().spawn_callback(self.restart_service)
self._notify_status("Update Finished...",
is_complete=True)
IOLoop.current().call_later(.1, self.restart_service)
else:
await self.restart_service()
self._notify_status("Update Finished...", is_complete=True)
async def _install_packages(self):
# Open install file file and read
inst_script = REPO_DATA[self.name]['install_script']
inst_script = self.dist_info['install_script']
inst_path = os.path.join(self.repo_path, inst_script)
if not os.path.isfile(inst_path):
self._log_info(f"Unable to open install script: {inst_path}")
@@ -347,23 +507,22 @@ class GitUpdater:
async def _update_virtualenv(self, rebuild_env=False):
# Update python dependencies
bin_dir = os.path.dirname(self.env)
env_path = os.path.normpath(os.path.join(bin_dir, ".."))
if rebuild_env:
env_path = os.path.normpath(os.path.join(bin_dir, ".."))
env_args = REPO_DATA[self.name]['venv_args']
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}")
f"virtualenv {env_args} {env_path}", timeout=300.)
except Exception:
self._log_exc(f"Error creating virtualenv")
return
await tornado.gen.sleep(.5)
if not os.path.expanduser(self.env):
raise self._log_exc("Failed to create new virtualenv", False)
reqs = os.path.join(
self.repo_path, REPO_DATA[self.name]['requirements'])
self.repo_path, self.repo_info['requirements'])
if not os.path.isfile(reqs):
self._log_exc(f"Invalid path to requirements_file '{reqs}'")
return
@@ -375,6 +534,31 @@ class GitUpdater:
retries=3)
except Exception:
self._log_exc("Error updating python requirements")
self._install_python_dist_requirements(env_path)
def _install_python_dist_requirements(self, env_path):
dist_reqs = self.dist_info.get('python_dist_packages', None)
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'])
for pkg in dist_reqs:
for f in os.listdir(dist_path):
if f.startswith(pkg):
src = os.path.join(dist_path, f)
dest = os.path.join(site_path, f)
self._notify_status(f"Linking to dist package: {pkg}")
if os.path.islink(dest):
os.remove(dest)
elif os.path.exists(dest):
self._notify_status(
f"Error symlinking dist package: {pkg}, "
f"file already exists: {dest}")
continue
os.symlink(src, dest)
break
async def restart_service(self):
self._notify_status("Restarting Service...")
@@ -385,21 +569,54 @@ class GitUpdater:
def get_update_status(self):
return {
'remote_alias': self.remote,
'branch': self.branch,
'version': self.version,
'remote_version': self.remote_version,
'current_hash': self.cur_hash,
'remote_hash': self.remote_hash,
'is_dirty': self.is_dirty,
'is_valid': self.is_valid}
'is_valid': self.is_valid,
'detached': self.detached,
'debug_enabled': self.debug}
class PackageUpdater:
def __init__(self, umgr):
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
self.available_packages = []
self.init_evt = Event()
IOLoop.current().spawn_callback(self.refresh)
async def check_remote_version(self):
pass
async def refresh(self):
# 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")
else:
pkg_list = [p.strip() for p in res.split("\n") if p.strip()]
if pkg_list:
pkg_list = pkg_list[2:]
self.available_packages = [p.split("/", maxsplit=1)[0]
for p in pkg_list]
pkg_list = "\n".join(self.available_packages)
logging.info(
f"Detected {len(self.available_packages)} package updates:"
f"\n{pkg_list}")
self.init_evt.set()
async def check_initialized(self, timeout=None):
if self.init_evt.is_set():
return
if timeout is not None:
timeout = IOLoop.current().time() + timeout
await self.init_evt.wait(timeout)
async def update(self, *args):
self.notify_update_response("Updating packages...")
@@ -410,44 +627,75 @@ class PackageUpdater:
f"{APT_CMD} upgrade --yes", timeout=3600., notify=True)
except Exception:
raise self.server.error("Error updating system packages")
self.available_packages = []
self.notify_update_response("Package update finished...",
is_complete=True)
def get_update_status(self):
return {
'package_count': len(self.available_packages),
'package_list': self.available_packages
}
class ClientUpdater:
def __init__(self, umgr, repo, path):
self.umgr = umgr
self.server = umgr.server
self.github_request = umgr.github_request
self.notify_update_response = umgr.notify_update_response
self.repo = repo.strip().strip("/")
self.name = self.repo.split("/")[-1]
self.path = path
self.version = self.remote_version = self.dl_url = "?"
self.etag = None
self.init_evt = Event()
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")
if os.path.isfile(os.path.join(self.path, ".version")):
with open(version_path, "r") as f:
v = f.read()
self.version = v.strip()
logging.info(f"\nInitializing repo '{self.name}',"
f"\nversion: {self.version}"
f"\npath: {self.path}")
IOLoop.current().spawn_callback(self.check_remote_version)
async def check_remote_version(self):
async def check_initialized(self, timeout=None):
if self.init_evt.is_set():
return
if timeout is not None:
timeout = IOLoop.current().time() + timeout
await self.init_evt.wait(timeout)
async def refresh(self):
# Local state
self._get_local_version()
# Remote state
url = f"https://api.github.com/repos/{self.repo}/releases/latest"
try:
result = await self.github_request(url)
result = await self.umgr.github_api_request(url, etag=self.etag)
except Exception:
logging.exception(f"Client {self.repo}: Github Request Error")
result = {}
if result is None:
# No change, update not necessary
return None
self.etag = result.get('etag', None)
self.remote_version = result.get('name', "?")
release_assets = result.get('assets', [{}])[0]
self.dl_url = release_assets.get('browser_download_url', "?")
logging.info(
f"Github client Info Received: {self.name}, "
f"version: {self.remote_version} "
f"Github client Info Received:\nRepo: {self.name}\n"
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):
if self.remote_version == "?":
await self.check_remote_version()
await self.refresh()
if self.remote_version == "?":
raise self.server.error(
f"Client {self.repo}: Unable to locate update")
@@ -461,7 +709,7 @@ class ClientUpdater:
shutil.rmtree(self.path)
os.mkdir(self.path)
self.notify_update_response(f"Downloading Client: {self.name}")
archive = await self.github_request(self.dl_url, is_download=True)
archive = await self.umgr.http_download_request(self.dl_url)
with zipfile.ZipFile(io.BytesIO(archive)) as zf:
zf.extractall(self.path)
self.version = self.remote_version
@@ -469,7 +717,8 @@ class ClientUpdater:
if not os.path.exists(version_path):
with open(version_path, "w") as f:
f.write(self.version)
self.notify_update_response(f"Client Updated: {self.name}")
self.notify_update_response(f"Client Update Finished: {self.name}",
is_complete=True)
def get_update_status(self):
return {
+16 -6
View File
@@ -6,6 +6,7 @@
import logging
import logging.handlers
import os
import sys
import subprocess
import asyncio
from queue import SimpleQueue as Queue
@@ -73,11 +74,20 @@ 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)
formatter = logging.Formatter(
'%(asctime)s [%(filename)s:%(funcName)s()] - %(message)s')
file_hdlr.setFormatter(formatter)
listener = logging.handlers.QueueListener(queue, file_hdlr)
stdout_hdlr = logging.StreamHandler(sys.stdout)
stdout_fmt = logging.Formatter(
'[%(filename)s:%(funcName)s()] - %(message)s')
stdout_hdlr.setFormatter(stdout_fmt)
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
+7 -2
View File
@@ -172,6 +172,8 @@ class WebsocketManager:
# Register events
self.server.register_event_handler(
"server:klippy_ready", self._handle_klippy_ready)
self.server.register_event_handler(
"server:klippy_shutdown", self._handle_klippy_shutdown)
self.server.register_event_handler(
"server:klippy_disconnect", self._handle_klippy_disconnect)
self.server.register_event_handler(
@@ -188,6 +190,9 @@ class WebsocketManager:
async def _handle_klippy_ready(self):
await self.notify_websockets("klippy_ready")
async def _handle_klippy_shutdown(self):
await self.notify_websockets("klippy_shutdown")
async def _handle_klippy_disconnect(self):
await self.notify_websockets("klippy_disconnected")
@@ -309,8 +314,8 @@ class WebSocket(WebSocketHandler):
'method': "notify_status_update",
'params': [status]})
except WebSocketClosedError:
self.websockets.pop(self.uid, None)
logging.info(f"Websocket Removed: {self.uid}")
logging.info(
f"Websocket Closed During Status Update: {self.uid}")
except Exception:
logging.exception(
f"Error sending data over websocket: {self.uid}")
+42 -24
View File
@@ -3,6 +3,7 @@
# Raspbian/Raspberry Pi OS based distributions.
PYTHONDIR="${HOME}/moonraker-env"
SYSTEMDDIR="/etc/systemd/system"
REBUILD_ENV="n"
FORCE_DEFAULTS="n"
CONFIG_PATH="${HOME}/moonraker.conf"
@@ -19,7 +20,19 @@ check_klipper()
}
# Step 2: Install packages
# Step 2: Clean up legacy installation
cleanup_legacy() {
if [ -f "/etc/init.d/moonraker" ]; then
# Stop Moonraker Service
echo "#### Cleanup legacy install script"
sudo systemctl stop moonraker
sudo update-rc.d -f moonraker remove
sudo rm -f /etc/init.d/moonraker
sudo rm -f /etc/default/moonraker
fi
}
# Step 3: Install packages
install_packages()
{
PKGLIST="python3-virtualenv python3-dev nginx libopenjp2-7 python3-libgpiod"
@@ -33,7 +46,7 @@ install_packages()
sudo apt-get install --yes ${PKGLIST}
}
# Step 3: Create python virtual environment
# Step 4: Create python virtual environment
create_virtualenv()
{
report_status "Installing python virtual environment..."
@@ -44,45 +57,50 @@ create_virtualenv()
rm -rf ${PYTHONDIR}
fi
[ ! -d ${PYTHONDIR} ] && virtualenv -p /usr/bin/python3 --system-site-packages ${PYTHONDIR}
if [ ! -d ${PYTHONDIR} ]; then
virtualenv -p /usr/bin/python3 ${PYTHONDIR}
ln -s /usr/lib/python3/dist-packages/gpiod* ${PYTHONDIR}/lib/python*/site-packages
fi
# Install/update dependencies
${PYTHONDIR}/bin/pip install -r ${SRCDIR}/scripts/moonraker-requirements.txt
}
# Step 4: Install startup script
# Step 5: Install startup script
install_script()
{
# Create systemd service file
SERVICE_FILE="${SYSTEMDDIR}/moonraker.service"
[ -f $SERVICE_FILE ] && [ $FORCE_DEFAULTS = "n" ] && return
report_status "Installing system start script..."
sudo cp "${SRCDIR}/scripts/moonraker-start.sh" /etc/init.d/moonraker
sudo update-rc.d moonraker defaults
}
sudo /bin/sh -c "cat > ${SERVICE_FILE}" << EOF
#Systemd service file for moonraker
[Unit]
Description=Starts Moonraker on startup
After=network.target
# Step 5: Install startup script config
install_config()
{
DEFAULTS_FILE=/etc/default/moonraker
[ -f $DEFAULTS_FILE ] && [ $FORCE_DEFAULTS = "n" ] && return
report_status "Installing system start configuration..."
sudo /bin/sh -c "cat > $DEFAULTS_FILE" <<EOF
# Configuration for /etc/init.d/moonraker
MOONRAKER_USER=$USER
MOONRAKER_EXEC=${PYTHONDIR}/bin/python
MOONRAKER_ARGS="${SRCDIR}/moonraker/moonraker.py -c ${CONFIG_PATH}"
[Install]
WantedBy=multi-user.target
[Service]
Type=simple
User=$USER
RemainAfterExit=yes
ExecStart=${PYTHONDIR}/bin/python ${SRCDIR}/moonraker/moonraker.py -c ${CONFIG_PATH}
Restart=always
RestartSec=10
EOF
# Use systemctl to enable the klipper systemd service script
sudo systemctl enable moonraker.service
}
# Step 6: Start server
start_software()
{
report_status "Launching Moonraker API Server..."
sudo systemctl stop klipper
sudo /etc/init.d/moonraker restart
sudo systemctl restart moonraker
sudo systemctl start klipper
}
@@ -118,8 +136,8 @@ done
# Run installation steps defined above
verify_ready
check_klipper
cleanup_legacy
install_packages
create_virtualenv
install_script
install_config
start_software
+184
View File
@@ -0,0 +1,184 @@
#!/bin/bash
# moonraker-sudo (mnrkrsudo)
# Provides a specified Group that is intended to elevate user privileges
# to help moonraker with sudo actions, if in CustomPIOS Images with
# Module "password-for-sudo".
#
# Partially used functions from Arcsine
#
# Copyright (C) 2020 Stephan Wendel <me@stephanwe.de>
#
# This file may be distributed under the terms of the GNU GPLv3 license
### Exit on Errors
set -e
### Configuration
SUDOERS_DIR='/etc/sudoers.d'
SUDOERS_FILE='020-sudo-for-moonraker'
NEW_GROUP='mnrkrsudo'
### Functions
verify_ready()
{
if [ "$EUID" -eq 0 ]; then
echo "This script must not run as root"
exit -1
fi
}
create_sudoers_file()
{
SCRIPT_TEMP_PATH=/tmp
report_status "Creating ${SUDOERS_FILE} ..."
sudo rm -f $SCRIPT_TEMP_PATH/$SUDOERS_FILE
sudo sed "s/GROUPNAME/$NEW_GROUP/g" > $SCRIPT_TEMP_PATH/$SUDOERS_FILE << '#EOF'
### Elevate moonraker API rights
### Do NOT allow Command Parts only Full Commands
### for example
###
### /sbin/systemctl "reboot", /sbin/apt "update", .....
Defaults!/usr/bin/apt-get env_keep +="DEBIAN_FRONTEND"
Cmnd_Alias REBOOT = /sbin/shutdown -r now, /bin/systemctl "reboot"
Cmnd_Alias SHUTDOWN = /sbin/shutdown now, /sbin/shutdown -h now, /bin/systemctl "poweroff"
Cmnd_Alias APT = /usr/bin/apt-get
Cmnd_Alias SYSTEMCTL = /bin/systemctl
%GROUPNAME ALL=(ALL) NOPASSWD: REBOOT, SHUTDOWN, APT, SYSTEMCTL
#EOF
report_status "\e[1;32m...done\e[0m"
}
update_env()
{
report_status "Export System Variable: DEBIAN_FRONTEND=noninteractive"
sudo /bin/sh -c 'echo "DEBIAN_FRONTEND=noninteractive" >> /etc/environment'
}
verify_syntax()
{
report_status "\e[1;33mVerifying Syntax of ${SUDOERS_FILE}\e[0m\n"
if [ $(LANG=C visudo -cf $SCRIPT_TEMP_PATH/$SUDOERS_FILE | grep -c "OK" ) -eq 1 ];
then
VERIFY_STATUS=0
report_status "\e[1;32m$(LANG=C visudo -cf $SCRIPT_TEMP_PATH/$SUDOERS_FILE)\e[0m"
else
report_status "\e[1;31mSyntax Error:\e[0m Check File: $SCRIPT_TEMP_PATH/$SUDOERS_FILE"
exit 1
fi
}
install_sudoers_file()
{
verify_syntax
if [ $VERIFY_STATUS -eq 0 ];
then
report_status "Copying $SCRIPT_TEMP_PATH/$SUDOERS_FILE to $SUDOERS_DIR/$SUDOERS_FILE"
sudo chmod 0440 $SCRIPT_TEMP_PATH/$SUDOERS_FILE
sudo cp --preserve=mode $SCRIPT_TEMP_PATH/$SUDOERS_FILE $SUDOERS_DIR/$SUDOERS_FILE
else
exit 1
fi
}
check_update_sudoers_file()
{
if [ -e "$SUDOERS_DIR/$SUDOERS_FILE" ];
then
create_sudoers_file
if [ -z $(sudo diff $SCRIPT_TEMP_PATH/$SUDOERS_FILE $SUDOERS_DIR/$SUDOERS_FILE) ]
then
report_status "No need to update $SUDOERS_DIR/$SUDOERS_FILE"
else
report_status "$SUDOERS_DIR/$SUDOERS_FILE needs to be updated."
install_sudoers_file
fi
fi
}
add_new_group()
{
sudo addgroup --system $NEW_GROUP &> /dev/null
report_status "\e[1;32m...done\e[0m"
}
add_user_to_group()
{
sudo usermod -aG $NEW_GROUP $USER &> /dev/null
report_status "\e[1;32m...done\e[0m"
}
adduser_hint()
{
report_status "\e[1;31mYou have to REBOOT to take changes effect!\e[0m"
}
# Helper functions
report_status()
{
echo -e "\n\n###### $1"
}
clean_temp()
{
sudo rm -f $SCRIPT_TEMP_PATH/$SUDOERS_FILE
}
### Main
verify_ready
if [ -e "$SUDOERS_DIR/$SUDOERS_FILE" ] && [ $(sudo cat /etc/gshadow | grep -c "${NEW_GROUP}") -eq 1 ] && [ $(groups | grep -c "$NEW_GROUP") -eq 1 ];
then
check_update_sudoers_file
report_status "\e[1;32mEverything is setup, nothing to do...\e[0m\n"
exit 0
else
if [ -e "$SUDOERS_DIR/$SUDOERS_FILE" ];
then
report_status "\e[1;32mFile exists:\e[0m ${SUDOERS_FILE}"
check_update_sudoers_file
else
report_status "\e[1;31mFile not found:\e[0m ${SUDOERS_FILE}\n"
create_sudoers_file
install_sudoers_file
fi
if [ $(sudo cat /etc/gshadow | grep -c "${NEW_GROUP}") -eq 1 ];
then
report_status "Group ${NEW_GROUP} already exists..."
else
report_status "Group ${NEW_GROUP} will be added..."
add_new_group
fi
if [ $(groups | grep -c "$NEW_GROUP") -eq 1 ];
then
report_status "User ${USER} is already in $NEW_GROUP..."
else
report_status "Adding User ${USER} to Group $NEW_GROUP..."
add_user_to_group
adduser_hint
fi
fi
update_env
clean_temp
exit 0
+9
View File
@@ -20,6 +20,14 @@ remove_service() {
}
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
}
remove_files() {
# Remove API Key file from older versions
if [ -e ~/.klippy_api_key ]; then
@@ -61,3 +69,4 @@ verify_ready
stop_service
remove_service
remove_files
remove_sudo_fix
+24
View File
@@ -0,0 +1,24 @@
# Supplemental configuration for Moonraker's Update Manager
# plugin. This file should not be modified.
[repo_info 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
python_dist_packages:
gpiod
[dist_info debian klipper]
install_script: scripts/install-octopi.sh
python_dist_path: /usr/lib/python2.7/dist-packages
env_package_path: lib/python2.7/site-packages
+2 -2
View File
@@ -1,2 +1,2 @@
env_version=0.2.1
deps_version=0.2.1
env_version=0.2.6
deps_version=0.2.2
+4
View File
@@ -738,6 +738,10 @@ function handle_power_changed(power_status) {
json_rpc.register_method("notify_power_changed", handle_power_changed);
function handle_update_response(response) {
if (response.complete === true) {
console.log("Update complete");
console.log(response);
}
update_term(response.message)
}
json_rpc.register_method("notify_update_response", handle_update_response);