Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d60b852b27 | ||
|
|
dacd9f7565 | ||
|
|
d76abe019f | ||
|
|
b6cd19d6ef | ||
|
|
74630f933a | ||
|
|
9133b59dbf | ||
|
|
10da7b714f | ||
|
|
908501cbc8 | ||
|
|
5d35cc0d10 | ||
|
|
f2b48d0f1a | ||
|
|
88ee83c7d8 | ||
|
|
d3ec2dbae2 | ||
|
|
78edcab86e | ||
|
|
627db24c63 | ||
|
|
7c56a8fa74 | ||
|
|
0527904c48 | ||
|
|
3642003dd2 | ||
|
|
2c47064d79 | ||
|
|
39a532cf87 | ||
|
|
ebaac290e7 | ||
|
|
5379e4b4bd | ||
|
|
6b03c4600d | ||
|
|
7ed54a166b | ||
|
|
2ab63d75fc | ||
|
|
1c248d1de8 | ||
|
|
261fbbc867 | ||
|
|
346015e528 | ||
|
|
8b8d538a9c | ||
|
|
5b260a5ba6 | ||
|
|
03892a517e | ||
|
|
30155c4a8c | ||
|
|
bfef2eb98e | ||
|
|
7ccb455174 | ||
|
|
80df137437 | ||
|
|
a605cd3048 | ||
|
|
c7f8689bfe | ||
|
|
12a7f957c3 | ||
|
|
c6fee3c1f4 | ||
|
|
81854d1daf | ||
|
|
4836f52a5d | ||
|
|
5c05afae42 | ||
|
|
77052e15b0 | ||
|
|
ecc0fbdae9 | ||
|
|
00f4bd594f | ||
|
|
3529acfeec | ||
|
|
1510f66121 | ||
|
|
c22dcc18dc | ||
|
|
b6f9769488 | ||
|
|
188dc4c782 | ||
|
|
0126aa794f | ||
|
|
2bc7efd20e | ||
|
|
566df69ca5 | ||
|
|
40f21b10cd | ||
|
|
a7801db6e7 | ||
|
|
06bbca7ae3 | ||
|
|
331be63c9e | ||
|
|
d3df568aec | ||
|
|
9e909e8532 | ||
|
|
1b2fa4924b | ||
|
|
20673b9edd | ||
|
|
3b4bfba85e | ||
|
|
42bdb42573 | ||
|
|
c9a958f861 | ||
|
|
9a316fe84a | ||
|
|
92423911a9 | ||
|
|
6770a965a6 | ||
|
|
33cb18517a | ||
|
|
9ea91f4f5d | ||
|
|
d9d3739118 | ||
|
|
0b885ec5ec | ||
|
|
b16110bcd0 | ||
|
|
936d766cae | ||
|
|
108d0578a2 | ||
|
|
39343f984a | ||
|
|
628c0193f3 | ||
|
|
def6b365fa | ||
|
|
0ab9ffdc93 | ||
|
|
1b3efb1a78 | ||
|
|
d6156dee68 | ||
|
|
541f5e54dc | ||
|
|
793ab6b24b | ||
|
|
082134b9a0 | ||
|
|
2db727e40f | ||
|
|
fc5420db27 | ||
|
|
aeb24dabdb | ||
|
|
3d0d1e1dcb | ||
|
|
5f7cff9af8 | ||
|
|
d7c367f095 | ||
|
|
aa9641024a | ||
|
|
60d6c748ef | ||
|
|
dc4da6087f | ||
|
|
8a3b885eca | ||
|
|
ce7f659a32 | ||
|
|
e4e58f6d97 | ||
|
|
a18987aa59 | ||
|
|
5db74b724e | ||
|
|
aba3e374c3 | ||
|
|
dcf1cdf526 | ||
|
|
68b9a073af | ||
|
|
f1ba8e3d9b | ||
|
|
e7193dbb5f | ||
|
|
e15ef345bc | ||
|
|
564e33bc18 | ||
|
|
daa7b5edd4 | ||
|
|
a012c4b772 | ||
|
|
58f7aa0a57 | ||
|
|
81f2393b46 | ||
|
|
5d783a743a | ||
|
|
c335b62d26 | ||
|
|
e7ca2d6adc | ||
|
|
ceae5bb88b | ||
|
|
36aec50bce | ||
|
|
b8cf0d7fd2 | ||
|
|
dca7bd51cd | ||
|
|
6b9a3c656d | ||
|
|
829b3a4ee8 | ||
|
|
f5ccddb52b | ||
|
|
94e1dcf2cb | ||
|
|
7465de389f | ||
|
|
c83d91eea7 | ||
|
|
dbe28751df | ||
|
|
d392a895d9 | ||
|
|
1026d59cad | ||
|
|
1ada457364 | ||
|
|
12246029ef | ||
|
|
c977948c2c | ||
|
|
9994e1eb84 | ||
|
|
1755d0f970 | ||
|
|
f5010e960b | ||
|
|
9bf4ade35b | ||
|
|
ce7495ecce | ||
|
|
41ddbb16a8 | ||
|
|
410db750c6 | ||
|
|
b91df6642d | ||
|
|
420ba065da | ||
|
|
ca69a10838 | ||
|
|
9c76dbef7a | ||
|
|
96e69240ca | ||
|
|
6c27885702 | ||
|
|
5a2e2b1f3f | ||
|
|
316c6b5fa1 | ||
|
|
b2f8413057 | ||
|
|
17a436bc27 | ||
|
|
93a29e0e34 | ||
|
|
d46f04de0b | ||
|
|
55941b106b | ||
|
|
ebaf355878 | ||
|
|
21d290beb7 | ||
|
|
a9f1a98fa2 | ||
|
|
5fe9f1a217 | ||
|
|
9da74f7bc6 | ||
|
|
e4d61de406 | ||
|
|
93fcd1ae86 | ||
|
|
43fcca5ffa | ||
|
|
9c31a360ee | ||
|
|
bb00825cd2 | ||
|
|
db0eb8f22b | ||
|
|
c40c202220 | ||
|
|
eaf35ded0c | ||
|
|
ecbf663b18 | ||
|
|
23dd001a9b | ||
|
|
48607f8ab3 | ||
|
|
c2871d94ed | ||
|
|
7744b1fd8a | ||
|
|
5756e27711 | ||
|
|
fbb1fcf500 | ||
|
|
5f9b0e9b86 | ||
|
|
9fe6ef82a5 | ||
|
|
fd07b077b9 | ||
|
|
158f92f17f | ||
|
|
e73f9b7bf5 | ||
|
|
2ba85533c2 | ||
|
|
490e66fe07 | ||
|
|
4a61bf21de | ||
|
|
b3187710d0 | ||
|
|
e472fb6c1e | ||
|
|
1af7f7d550 | ||
|
|
400cefebc8 | ||
|
|
d3c251bc52 | ||
|
|
0274a641b2 | ||
|
|
0917536ccc | ||
|
|
724c29c4a7 | ||
|
|
8e6bb34d1b | ||
|
|
c02964e95c | ||
|
|
cb8e5af8f7 | ||
|
|
06bea715a3 | ||
|
|
3d01b0b9da | ||
|
|
f339aa7454 | ||
|
|
e69ac489c7 | ||
|
|
52f08eda08 | ||
|
|
a746019790 | ||
|
|
efdcc263dd | ||
|
|
4ee32ebaf3 | ||
|
|
acd3b3c064 | ||
|
|
c53b95aa93 | ||
|
|
40d4daa96b | ||
|
|
68b793f059 | ||
|
|
f705f1145a | ||
|
|
5321a8a558 | ||
|
|
46e1d7b66b | ||
|
|
497423ddc2 | ||
|
|
80707d1734 | ||
|
|
275bcde081 | ||
|
|
24eaff6951 | ||
|
|
5e87d8793d | ||
|
|
0791c658ad | ||
|
|
37615d4790 | ||
|
|
b9487276e9 | ||
|
|
46dea00b2f | ||
|
|
85be5cbfc1 | ||
|
|
2b79a129aa | ||
|
|
d42fd3b095 | ||
|
|
25b6f6fb34 | ||
|
|
9478678ea0 | ||
|
|
2c078cbc7c | ||
|
|
3627331527 | ||
|
|
f4ebb93546 | ||
|
|
64e794f1b5 | ||
|
|
5bba0fc2fa | ||
|
|
a4273d2d0a | ||
|
|
0c765f7b71 | ||
|
|
4e0e223599 | ||
|
|
7eba8e58e3 | ||
|
|
43a8d25619 | ||
|
|
24e6fded91 | ||
|
|
dee9055347 | ||
|
|
0ce53bd98f | ||
|
|
14991ac3b9 | ||
|
|
57836047f6 | ||
|
|
9873084667 | ||
|
|
e8f6862fd2 | ||
|
|
4d69a1f1c6 | ||
|
|
f203567381 | ||
|
|
0d601073a6 | ||
|
|
daf3b202c3 | ||
|
|
087240aa67 | ||
|
|
210cae2736 | ||
|
|
dae0f05378 | ||
|
|
4d1a2668f5 | ||
|
|
7d3bba75e1 | ||
|
|
b111e3d6c7 | ||
|
|
6cc11276c8 | ||
|
|
5db596f0a5 | ||
|
|
aa3ffdbaaf | ||
|
|
8724d5e9ed | ||
|
|
da9401dd1a | ||
|
|
85b1b44e20 | ||
|
|
c36f989c52 | ||
|
|
210f505157 | ||
|
|
61c62154ae | ||
|
|
c18f0dac60 | ||
|
|
daad55640b | ||
|
|
e489b795e6 | ||
|
|
6b91b1eac1 | ||
|
|
c0389fbf3f | ||
|
|
9b0c9810a4 | ||
|
|
da9b9e184d | ||
|
|
eb681fc960 | ||
|
|
6b0d981274 | ||
|
|
f1f318ea40 | ||
|
|
fb1f76e008 | ||
|
|
d6de095e66 | ||
|
|
b1f8eaae51 | ||
|
|
f0a6620267 | ||
|
|
eec85f86a9 | ||
|
|
e7f605327f | ||
|
|
4b13af4d86 | ||
|
|
f38cacd513 | ||
|
|
c48fe983de | ||
|
|
8acd0f2728 | ||
|
|
1dc920019c | ||
|
|
976f9a732c | ||
|
|
bf67bce65f | ||
|
|
f5c27f27ce | ||
|
|
480430720f | ||
|
|
fe8c7af79f | ||
|
|
891d6bd871 | ||
|
|
e251f26487 | ||
|
|
e2894b9907 | ||
|
|
92ac1ee21f | ||
|
|
6e6d974bad | ||
|
|
8e609c503f | ||
|
|
7949b6400b | ||
|
|
8d93bcf438 | ||
|
|
ce78e42065 | ||
|
|
ed217fb3e9 | ||
|
|
0c455fcc0d | ||
|
|
5e99378466 | ||
|
|
48621da6aa | ||
|
|
47902cb03c | ||
|
|
038fcec1f4 | ||
|
|
06c35fa0b2 | ||
|
|
3f48dd5510 | ||
|
|
d9d087b9f3 | ||
|
|
1e8ec5c517 | ||
|
|
06a07f09e5 | ||
|
|
94ed9fbd7f | ||
|
|
cd4641f959 | ||
|
|
4b89de53f7 | ||
|
|
62265fd086 | ||
|
|
e990e64ccd | ||
|
|
1615af731b | ||
|
|
dc60143ef8 | ||
|
|
7e230c1c77 | ||
|
|
78324e0df4 | ||
|
|
a04958b1bf | ||
|
|
f09cd413ca | ||
|
|
62012726da | ||
|
|
a5c455a305 | ||
|
|
ca2bd380cf | ||
|
|
05b8c4eaef | ||
|
|
3b99307109 | ||
|
|
5f741c28a5 | ||
|
|
91e59706fa | ||
|
|
ec3bb22c63 | ||
|
|
978fcffab5 | ||
|
|
083d63568c | ||
|
|
53ad4cb493 | ||
|
|
dd321a4754 | ||
|
|
84bc9aa311 | ||
|
|
1367083f99 | ||
|
|
9331031f55 | ||
|
|
f0adbcf62d | ||
|
|
d45ec3466e | ||
|
|
832eb6f130 | ||
|
|
9988da72c1 | ||
|
|
7c89756263 | ||
|
|
92de4b75ee | ||
|
|
93e7eaa5b5 | ||
|
|
0a3a83de37 | ||
|
|
df82730832 | ||
|
|
9632465a78 | ||
|
|
22b3a953c5 | ||
|
|
51fd460b59 | ||
|
|
2e0d3f36b4 | ||
|
|
5144508410 | ||
|
|
056a9db23e | ||
|
|
d20631e69f | ||
|
|
15890b9e87 | ||
|
|
9563bcff11 | ||
|
|
5d095125d3 | ||
|
|
44f1147f71 | ||
|
|
dc165636cb | ||
|
|
29644bd44c | ||
|
|
606625a3aa | ||
|
|
438ffece72 | ||
|
|
d108334c37 | ||
|
|
13ccdb4df1 | ||
|
|
4de33bae4a | ||
|
|
316fac1e75 | ||
|
|
d057795bee | ||
|
|
4efce1b868 | ||
|
|
db13827a48 | ||
|
|
4c914d7b4d | ||
|
|
f1edaa1f61 | ||
|
|
a111733431 | ||
|
|
c8a2aa7a6c | ||
|
|
84f663e2bc | ||
|
|
6ba45f6e35 | ||
|
|
39ab419c1f | ||
|
|
228ed34eb1 | ||
|
|
0fa3c14f51 | ||
|
|
46680f4cda | ||
|
|
e32c14b1a7 | ||
|
|
1f9d896e17 | ||
|
|
d9edcd9396 | ||
|
|
22a5f6720c | ||
|
|
cea9af1ef8 | ||
|
|
63c685e1c4 | ||
|
|
84f46b1cb1 | ||
|
|
d1dfa86081 | ||
|
|
dbf5f93919 | ||
|
|
d878340a7a | ||
|
|
fb24917f1a | ||
|
|
62324650e5 | ||
|
|
bf48744048 | ||
|
|
6c994f6c9c | ||
|
|
bb3eb27b3d | ||
|
|
94b690c2e9 | ||
|
|
aa4c13742e | ||
|
|
900345e2d9 | ||
|
|
ec85b31a62 | ||
|
|
ab6ed40bcb | ||
|
|
87e136003f | ||
|
|
7ff54d8f2f | ||
|
|
9e41d9d84b | ||
|
|
75dce0af1a | ||
|
|
4abfb886f5 | ||
|
|
979aef2903 | ||
|
|
958a0f3270 | ||
|
|
54b1bd8b04 | ||
|
|
1f61357dd6 | ||
|
|
b89aa77bc9 | ||
|
|
537ba281ab | ||
|
|
83c24ff765 | ||
|
|
b726747261 | ||
|
|
eb37ce767d | ||
|
|
60ba8ff1d5 | ||
|
|
45557b8260 | ||
|
|
f229c3ec2c | ||
|
|
0e22a0cfe8 | ||
|
|
f2135d7483 | ||
|
|
baf97f8ea4 | ||
|
|
29b89fb87d | ||
|
|
ec7936ee97 | ||
|
|
ceaa4911bb | ||
|
|
f9dcda7ba9 | ||
|
|
0fcae5b6e4 | ||
|
|
dd81beab47 | ||
|
|
9648630392 | ||
|
|
fe2cec1087 | ||
|
|
81104a6618 | ||
|
|
980912270e | ||
|
|
39334d1098 | ||
|
|
943b78195b | ||
|
|
49c5583e95 | ||
|
|
e8776a5d85 | ||
|
|
9c385ce067 | ||
|
|
9e240c3b86 | ||
|
|
c365de32cf | ||
|
|
aa9bf0fb9c | ||
|
|
ddc7405249 | ||
|
|
25b3911d3d | ||
|
|
19bc2bfbb8 | ||
|
|
578ce740c5 | ||
|
|
6a88df095e | ||
|
|
c17d86aa09 | ||
|
|
0ad97fd9eb | ||
|
|
f3ae6da635 | ||
|
|
e9ab5fb480 | ||
|
|
21d1726bfd | ||
|
|
0b3b8cede8 | ||
|
|
00db209d5d | ||
|
|
b4602115d7 | ||
|
|
ff8e53b269 | ||
|
|
e2c325a724 | ||
|
|
a1f2228473 | ||
|
|
d70bd8d2e0 | ||
|
|
8c365c62cb | ||
|
|
6f4a72fe2e | ||
|
|
bdd270fa4a | ||
|
|
d194ce00ab | ||
|
|
5f986ab770 | ||
|
|
e0f4b46364 | ||
|
|
fb3706c54f | ||
|
|
d1388080c4 | ||
|
|
f1a75117db | ||
|
|
4ae63dbbf8 | ||
|
|
30637011e6 | ||
|
|
8a18fa6c2f | ||
|
|
4cd97d61f9 | ||
|
|
40f876192c | ||
|
|
fa53d889d0 | ||
|
|
6fcb26ddd7 | ||
|
|
67adcfc448 | ||
|
|
0c280122fb | ||
|
|
5b9f637c2d | ||
|
|
2bb9128b5b | ||
|
|
222f0c4695 | ||
|
|
ea1ad0277d | ||
|
|
1e81297624 | ||
|
|
ae3661b100 | ||
|
|
67f5b32d84 | ||
|
|
14b5384572 | ||
|
|
c261ee51f3 | ||
|
|
67f992dabd | ||
|
|
a535e6e94a | ||
|
|
4aa2a86e3b | ||
|
|
7d738c7a8b | ||
|
|
f753263c60 | ||
|
|
2f8a1567a8 | ||
|
|
933622adda | ||
|
|
1814a11a8d | ||
|
|
77c483ea0f | ||
|
|
96941922bc | ||
|
|
1f2c1b3fcd | ||
|
|
2953c3f16f | ||
|
|
8fc5aab2f0 | ||
|
|
1acb00e2f1 | ||
|
|
b0fda218f1 | ||
|
|
34af0b4bfb | ||
|
|
fad6bc4ad7 | ||
|
|
9501d72059 | ||
|
|
9993b1e656 | ||
|
|
b5394228ef | ||
|
|
6bf4ef8b00 | ||
|
|
0a7080741c | ||
|
|
223c125106 | ||
|
|
f9fc679831 | ||
|
|
586bb6a7ca | ||
|
|
76ccc8b3e1 | ||
|
|
f91e425463 | ||
|
|
46de7c48c8 | ||
|
|
063ef7194a |
No files matched your search
@@ -0,0 +1,51 @@
|
||||
# CI Code for generating and publishing beta assets
|
||||
|
||||
name: publish_assets
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
jobs:
|
||||
generate_assets:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Moonraker
|
||||
uses: actions/checkout@v2
|
||||
with:
|
||||
fetch-depth: 0
|
||||
ref: ${{ github.ref }}
|
||||
path: moonraker
|
||||
|
||||
- name: Checkout Klipper
|
||||
uses: actions/checkout@v2
|
||||
with:
|
||||
fetch-depth: 0
|
||||
repository: KevinOConnor/klipper
|
||||
path: klipper
|
||||
|
||||
- name: Build Beta Assets
|
||||
if: ${{ github.event.release.prerelease }}
|
||||
run: >
|
||||
./moonraker/scripts/build-zip-release.sh -b
|
||||
-o ${{ github.workspace }}
|
||||
-k ${{ github.workspace }}/klipper
|
||||
|
||||
- name: Build Stable Assets
|
||||
if: ${{ !github.event.release.prerelease }}
|
||||
run: >
|
||||
./moonraker/scripts/build-zip-release.sh
|
||||
-o ${{ github.workspace }}
|
||||
-k ${{ github.workspace }}/klipper
|
||||
|
||||
- name: Upload assets
|
||||
run: |
|
||||
cd moonraker
|
||||
gh release upload ${{ env.TAG }} ${{ env.FILES }}
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
FILES: >
|
||||
${{ github.workspace }}/moonraker.zip
|
||||
${{ github.workspace }}/klipper.zip
|
||||
${{ github.workspace }}/RELEASE_INFO
|
||||
${{ github.workspace }}/COMMIT_LOG
|
||||
TAG: ${{ github.event.release.tag_name }}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
# CI for code style and application tests
|
||||
|
||||
name: test-code
|
||||
on: [push, pull_request]
|
||||
jobs:
|
||||
lint-python-code:
|
||||
runs-on: ubuntu-18.04
|
||||
steps:
|
||||
- uses: actions/checkout@v1
|
||||
- uses: ricardochaves/python-lint@v1.4.0
|
||||
with:
|
||||
python-root-list: "moonraker scripts"
|
||||
use-pylint: false
|
||||
use-pycodestyle: true
|
||||
use-flake8: false
|
||||
use-black: false
|
||||
use-mypy: true
|
||||
use-isort: false
|
||||
extra-pycodestyle-options: "--ignore=E226,E301,E302,E303,W503,W504 --max-line-length=80 --max-doc-length=80"
|
||||
extra-mypy-options: "--ignore-missing-imports --follow-imports=silent"
|
||||
@@ -0,0 +1,4 @@
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
@@ -0,0 +1,10 @@
|
||||
version: 2
|
||||
|
||||
mkdocs:
|
||||
configuration: mkdocs.yml
|
||||
fail_on_warning: false
|
||||
|
||||
python:
|
||||
version: 3.8
|
||||
install:
|
||||
- requirements: docs/doc-requirements.txt
|
||||
@@ -1,15 +1,21 @@
|
||||
# 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.
|
||||
|
||||
Documentation for users and developers can be found on
|
||||
[Read the Docs](https://moonraker.readthedocs.io/en/latest/).
|
||||
|
||||
Note that Moonraker does not come bundled with a client, you will need to
|
||||
install one. The following clients are currently available:
|
||||
- [Mainsail](https://github.com/meteyou/mainsail) by Meteyou
|
||||
- [Fluidd](https://github.com/cadriel/fluidd) by Cadriel
|
||||
- [KlipperScreen](https://github.com/jordanruthe/KlipperScreen) by jordanruthe
|
||||
- [mooncord](https://github.com/eliteSchwein/mooncord) by eliteSchwein
|
||||
|
||||
|
||||
### Changes
|
||||
|
||||
@@ -18,7 +24,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](https://moonraker.readthedocs.io/en/latest/user_changes/) - April 19th 2021
|
||||
|
||||
Developers:\
|
||||
[api_changes.md](/docs/api_changes.md) - November 28th 2020
|
||||
[api_changes.md](https://moonraker.readthedocs.io/en/latest/api_changes/) - March 15th 2021
|
||||
@@ -1,5 +1,95 @@
|
||||
##
|
||||
This document keeps a record of all changes to Moonraker's web APIs.
|
||||
|
||||
### May 8th 2021
|
||||
- The `file_manager` has been refactored to support system file
|
||||
file events through `inotify`. Only mutable `roots` are monitored,
|
||||
(currently `gcodes` and `config`). Subfolders within these
|
||||
these roots are also monitored, however hidden folders are not.
|
||||
The following changes API changes have been made to acccommodate
|
||||
this functionality:
|
||||
- The `notify_filelist_changed` actions have changed. The new
|
||||
actions are as follows:
|
||||
- `create_file`: sent when a new file has been created. This
|
||||
includes file uploads and copied files.
|
||||
- `create_dir`: sent when a new directory has been created.
|
||||
- `delete_file`: sent when a file has been deleted.
|
||||
- `delete_dir`: sent when a directory has been deleted.
|
||||
- `move_file`: sent when a file has moved.
|
||||
- `move_dir`: sent when a directory has moved.
|
||||
- `modify_file`: sent when an existing file has been modified
|
||||
- `root_update`: sent when a root directory location has been set.
|
||||
For example, if a user changes the gcode path in Klipper, this
|
||||
action is sent with a `notify_filelist_changed` notification.
|
||||
- File list notifications for gcode files are now only sent after
|
||||
all metadata has been processed. Likewise, requests to copy,
|
||||
move, or upload a file will only return after metadata has been
|
||||
processed. Notifications are synced with requests so that the
|
||||
request should always return before the notification is sent.
|
||||
- Thumbnails are now stored in the `.thumbs` directory to prevent
|
||||
changes to thumbnails from emitting filelist notications. This
|
||||
change will be reflected in the metadata's `relative_path` field,
|
||||
so clients that use this field should not need to take additional
|
||||
action. Note that existing thumbnails will remain in the `thumbs`
|
||||
directory and filelist notifications will be sent for changes to
|
||||
these thumbnails.
|
||||
- The `notify_metadata_update` notification has been removed Clients
|
||||
- can reliably expect metadata to be available for new or moved gcode
|
||||
files when a request returns.
|
||||
- The return values for several endpoints have been updated. They
|
||||
now contain information similar to that which is pushed by the
|
||||
`notify_filelist_changed` notification.
|
||||
- The deprecated `data` field in gcode metadata has been removed.
|
||||
The `size` field now returns the size of the `.png` file.
|
||||
|
||||
|
||||
### March 15th 2021
|
||||
- The `data` field for gcode thumbnails is now deprecated and will
|
||||
be removed in the near future. Thumbnails are now saved to png
|
||||
files in a `thumbs` directory relative to a gcode file's location.
|
||||
This path is available in the `relative_path` field for each
|
||||
thumbnail entry in the metadata.
|
||||
|
||||
### 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`.
|
||||
|
||||
### November 28th 2020
|
||||
- The following new endpoints are available when the `[update_manager]`
|
||||
section has been configured:
|
||||
|
||||
@@ -0,0 +1,365 @@
|
||||
## Components
|
||||
|
||||
Components in Moonraker are used to extend Moonraker's functionality,
|
||||
similar to "extras" in Klipper. Moonraker divides components into
|
||||
two categories, "core" components and "optional" components. A core
|
||||
component gets its configuration from the `[server]` section and is
|
||||
loaded when Moonraker starts. For example, the `file_manager` is a
|
||||
core component. If a core component fails to load Moonraker will
|
||||
exit with an error.
|
||||
|
||||
Optional components must be configured in `moonraker.conf`. If they
|
||||
have no specific configuration, a bare section, such as `[octoprint_compat]`
|
||||
must be present in `moonraker.conf`. Unlike with core components,
|
||||
Moonraker will still start if an optional component fails to load.
|
||||
Its failed status will be available for clients to query and present
|
||||
to the user.
|
||||
|
||||
### Basic Example
|
||||
|
||||
Components exist in the `components` directory. The below example
|
||||
shows how an `example.py` component might look:
|
||||
```python
|
||||
# Example Component
|
||||
#
|
||||
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
class Example:
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
self.name = config.get_name()
|
||||
|
||||
# Raises an error if "example_int_option" is not configured in
|
||||
# the [example] section
|
||||
self.example_int_opt = config.getint("example_int_option")
|
||||
|
||||
# Returns a NoneType if "example_float_option is not configured
|
||||
# in the config
|
||||
self.example_float_opt = config.getfloat("example_float_option", None)
|
||||
|
||||
self.server.register_endpoint("/server/example", ['GET'],
|
||||
self._handle_example request)
|
||||
|
||||
async def request_some_klippy_state(self):
|
||||
klippy_apis = self.server.lookup_component('klippy_apis')
|
||||
return await klippy_apis.query_objects({'print_stats': None})
|
||||
|
||||
async def _handle_example_request(self, web_request):
|
||||
web_request.get_int("required_reqest_param")
|
||||
web_request.get_float("optional_request_param", None)
|
||||
state = await self.request_some_klippy_state()
|
||||
return {"example_return_value": state}
|
||||
|
||||
def load_component(config):
|
||||
return Example(config)
|
||||
|
||||
```
|
||||
If you have created a "Klippy extras" module then the above should look
|
||||
look familiar. Moonraker attempts to use similar method for adding
|
||||
extensions, making easier Klipper contributors to add new functionality
|
||||
to Moonraker. Be aware that there is no "Reactor" object in Moonraker,
|
||||
it uses `asyncio` for coroutines. Like Klippy, you should not write
|
||||
code that blocks the main thread.
|
||||
|
||||
### The ConfigHelper Object
|
||||
|
||||
As shown above, each component is passed a config object. This object
|
||||
will be a `ConfigHelper` type, which is an object that wraps a
|
||||
configuration section to simply access to the native `ConfigParser`.
|
||||
A `ConfigHelper` should never be directly instantiated.
|
||||
|
||||
#### *ConfigHelper.get_server()*
|
||||
|
||||
Returns the primary [server](#the-server-object) instance.
|
||||
|
||||
#### *ConfigHelper.get_name()*
|
||||
|
||||
Returns the configuration section name associated with this `ConfigHelper`.
|
||||
|
||||
#### *ConfigHelper.get(option_name, default=Sentinel)*
|
||||
|
||||
Returns the value of the option`option_name` as a string. If
|
||||
the option does not exist, returns `default`. If `default` is
|
||||
not provided raises a `ConfigError`.
|
||||
|
||||
#### *ConfigHelper.getint(option_name, default=Sentinel)*
|
||||
|
||||
Returns the value of the option`option_name` as an integer. If
|
||||
the option does not exist, returns `default`. If `default` is
|
||||
not provided raises a `ConfigError`.
|
||||
|
||||
#### *ConfigHelper.getfloat(option_name, default=Sentinel)*
|
||||
|
||||
Returns the value of the option`option_name` as a float. If
|
||||
the option does not exist, returns `default`. If `default` is
|
||||
not provided raises a `ConfigError`.
|
||||
|
||||
#### *ConfigHelper.getboolean(option_name, default=Sentinel)*
|
||||
|
||||
Returns the value of the option`option_name` as a boolean. If
|
||||
the option does not exist, returns `default`. If `default` is
|
||||
not provided raises a `ConfigError`.
|
||||
|
||||
#### *ConfigHelper.has_section(section_name)*
|
||||
|
||||
Returns True if a section matching `section_name` is in the configuration,
|
||||
otherwise False.
|
||||
|
||||
Note that a ConfigHelper object also implements `__contains__`,
|
||||
which is an alias for `has_section`, ie: `section_name in config_instance`
|
||||
|
||||
#### *ConfigHelper.getsection(section_name)*
|
||||
|
||||
Returns a Config object for the section matching `section_name`. If the
|
||||
section does not exist in the configuration raises a `ConfigError`.
|
||||
|
||||
Note that a ConfigHelper object also implements `__getitem__`,
|
||||
which is an alias for `get_section`, ie: `config_instance[section_name]`
|
||||
|
||||
#### *ConfigHelper.get_options()*
|
||||
|
||||
Returns a dict mapping options to values for all options in the Config
|
||||
object.
|
||||
|
||||
#### *ConfigHelper.get_prefix_sections(prefix)*
|
||||
|
||||
Returns a list section names in the configuration that start with `prefix`.
|
||||
These strings can be used to retreve ConfigHelpers via
|
||||
[get_section()](#confighelpergetsectionsection_name).
|
||||
|
||||
### The Server Object
|
||||
|
||||
The server instance represents the central management object in Moonraker.
|
||||
It can be used to register endpoints, register notifications, look up other
|
||||
components, send events, and more.
|
||||
|
||||
#### *Server.lookup_component(component_name, default=Sentinel)*
|
||||
|
||||
Attempts to look up a loaded component, returning the result. If
|
||||
the component has not been loaded, `default` will be returned.
|
||||
If `default` is not provided a `ServerError` will be raised.
|
||||
|
||||
#### *Server.load_component(config, component_name, default=Sentinel)*
|
||||
|
||||
Attempts to load an uninitialized component and returns the result. It is
|
||||
only valid to call this within a a component's `__init__()` method, and
|
||||
should only be necessary if one optional component relies on another. Core components will always be loaded before optional components, thus an optional
|
||||
component may always call
|
||||
[lookup_component()](#serverlookup_componentcomponent_name-defaultsentinel)
|
||||
when it needs a reference to core component.
|
||||
|
||||
If the component fails to load `default` will be returned. If `default`
|
||||
is not provided a `ServerError` will be raised.
|
||||
|
||||
#### *Server.register_endpoint(uri, request_methods, callback, transports=["http", "websocket", "mqtt"], wrap_result=True)*
|
||||
|
||||
Registers the supplied `uri` with the server.
|
||||
|
||||
The `request_methods` argument should be a list of strings containing any
|
||||
combination of `GET`, `POST`, and `DELETE`.
|
||||
|
||||
The `callback` is executed when a request matching the `uri` and a
|
||||
`request_method` is received. The callback function will be passed a
|
||||
`WebRequest` object with details about the request. This function
|
||||
should be able of handling each registered `request_method`. The
|
||||
provided callback must be a coroutine.
|
||||
|
||||
The `transports` argument is a list containing any combination of
|
||||
`http`, `websocket` and `mqtt`. JSON-RPC methods for `websocket` and `mqtt`
|
||||
will be generated based on what is supplied by the `uri` and
|
||||
request_methods` argument. A unique JSON_RPC method is generated for each
|
||||
request method. For example:
|
||||
```python
|
||||
self.server.register_endpoint("/server/example", ["POST"], self._handle_request)
|
||||
```
|
||||
would register a JSON-RPC method like:
|
||||
```
|
||||
server.example
|
||||
```
|
||||
|
||||
However, if multiple requests methods are supplied, the generated JSON-RPC
|
||||
methods will differ:
|
||||
```python
|
||||
self.server.register_endpoint("/server/example", ["GET", "POST", "DELETE"],
|
||||
self._handle_request)
|
||||
```
|
||||
would register:
|
||||
```
|
||||
server.get_example
|
||||
server.post_example
|
||||
server.delete_example
|
||||
```
|
||||
|
||||
The `wrap_result` argument applies only to the `http` protocol. In Moonraker
|
||||
all http requests return a result with a JSON body. By default, the value returned
|
||||
by a `callback` is wrapped in a dict:
|
||||
```python
|
||||
{"result": return_value}
|
||||
```
|
||||
It is only necessary to set this to false if you need to return a body that
|
||||
does not match this result. For example, the `[octoprint_compat]` component
|
||||
uses this functionality to return results in a format that match what
|
||||
Octoprint itself would return.
|
||||
|
||||
#### *Server.register_event_handler(event, callback)*
|
||||
|
||||
Registers the provided `callback` method to be executed when the
|
||||
provided `event` is sent. The callback may be a coroutine, however it
|
||||
is not required.
|
||||
|
||||
#### *Server.send_event(event, \*args)*
|
||||
|
||||
Emits the event named `event`, calling all callbacks registered to the
|
||||
event. All positional arguments in `*args` will be passed to each
|
||||
callback. Event names should be in the form of
|
||||
`"module_name:event_description"`.
|
||||
|
||||
#### *Server.register_notification(event_name, notify_name=None)*
|
||||
|
||||
Registers a websocket notification to be pushed when `event_name`
|
||||
is emitted. By default JSON-RPC notifcation sent will be in the form of
|
||||
`notify_{event_description}`. For example, when the server sends the
|
||||
`server:klippy_connected` event, the JSON_RPC notification will be
|
||||
`notify_klippy_connected`.
|
||||
|
||||
If a `notify_name` is provided it will override the `{event_description}`
|
||||
extracted from the `event_name`. For example, if the `notify_name="kconnect`
|
||||
were specfied when registering the `server:klippy_connected` event, the
|
||||
websocket would emit a `notify_kconnect` notification.
|
||||
|
||||
#### *Server.get_host_info()*
|
||||
|
||||
Returns a tuple of the current host name of the PC and the port Moonraker
|
||||
is serving on.
|
||||
|
||||
#### *Server.get_klippy_info()*
|
||||
|
||||
Returns a dict containing the values from the most recent `info` request to
|
||||
Klippy. If Klippy has never connected this will be an empty dict.
|
||||
|
||||
### The WebRequest Object
|
||||
|
||||
All callbacks registered with the
|
||||
[register_endpoint()](#serverregister_endpointuri-request_methods-callback-protocolhttp-websocket-wrap_resulttrue)
|
||||
method are passed a WebRequest object when they are executed. This object
|
||||
contains information about the request including its endpoint name and arguments
|
||||
parsed from the request.
|
||||
|
||||
#### *WebRequest.get_endpoint()*
|
||||
|
||||
Returns the URI registered with this request, ie: `/server/example`.
|
||||
|
||||
#### *WebRequest.get_action()*
|
||||
|
||||
Returns the request action, which is synonomous with its HTTP request
|
||||
method. Will be either `GET`, `POST`, or `DELETE`. This is useful
|
||||
if your endpoint was registered with multiple request methods and
|
||||
needs to handle each differently.
|
||||
|
||||
#### *WebRequest.get_connection()*
|
||||
|
||||
Returns the associated Websocket connection ID. This will be `None`
|
||||
for HTTP requests when no associated websocket is connected to
|
||||
the client.
|
||||
|
||||
#### *WebRequest.get_args()*
|
||||
|
||||
Returns a reference to the entire argument dictionary. Useful if
|
||||
one request handler needs to preprocess the arguments before
|
||||
passing the WebRequest on to another request handler.
|
||||
|
||||
#### *WebRequest.get(key, default=Sentinel)*
|
||||
|
||||
Returns the request argument at the provided `key`. If the key is not
|
||||
present `default` will be returned. If `default` is not provided a
|
||||
`ServerError` will be raised.
|
||||
|
||||
#### *WebRequest.get_str(key, default=Sentinel)*
|
||||
|
||||
Retrieves the request argument at the provided `key` and converts it
|
||||
to a string, returning the result. If the key is not present the `default`
|
||||
value will be returned. If `default` is not provided or if the attempt at
|
||||
type conversion fails a `ServerError` will be raised.
|
||||
|
||||
#### *WebRequest.get_int(key, default=Sentinel)*
|
||||
|
||||
Retrieves the request argument at the provided `key` and converts it
|
||||
to an integer, returning the result. If the key is not present the `default`
|
||||
value will be returned. If `default` is not provided or if the attempt at
|
||||
type conversion fails a `ServerError` will be raised.
|
||||
|
||||
#### *WebRequest.get_float(key, default=Sentinel)*
|
||||
|
||||
Retrieves the request argument at the provided `key` and converts it
|
||||
to a float, returning the result. If the key is not present the `default`
|
||||
value will be returned. If `default` is not provided or if the attempt at
|
||||
type conversion fails a `ServerError` will be raised.
|
||||
|
||||
#### *WebRequest.get_boolean(key, default=Sentinel)*
|
||||
|
||||
Retrieves the request argument at the provided `key` and converts it
|
||||
to a boolean, returning the result. If the key is not present the `default`
|
||||
value will be returned. If `default` is not provided or if the attempt at
|
||||
type conversion fails a `ServerError` will be raised.
|
||||
|
||||
### MQTT
|
||||
|
||||
If configured by the user the MQTT component is available for lookup.
|
||||
Developers may use this to subscribe and publish topics.
|
||||
|
||||
#### *MQTTClient.is_connected()*
|
||||
|
||||
Returns true if Moonraker is currently connected to the Broker, false
|
||||
otherwise.
|
||||
|
||||
#### *MQTTClient.wait_connection(timeout=None)*
|
||||
|
||||
Blocks until a connection with the broker has been successfully established
|
||||
or until the specified timeout has exceeded. Returns true if the connection
|
||||
was successful established, or False on timeout. If no timeout is specified
|
||||
then this method will block indefinitely until a connection has been
|
||||
established.
|
||||
|
||||
#### *MQTTClient.publish_topic(topic, payload=None, qos=None, retain=False)*
|
||||
|
||||
Attempts to publish a topic to the Broker. The `payload` may be a bool, int,
|
||||
float, string, or json encodable (Dict or List). If omitted then an empty
|
||||
payload is sent. The `qos` may be an integer from 0 to 2. If not specifed
|
||||
then the QOS level will use the configured default. If `retain` is set to
|
||||
`True` then the retain flag for the payload will be set.
|
||||
|
||||
Returns a Future that will block until topic is confirmed as published.
|
||||
For QOS level 0 an exception will be raised if the broker is not connected.
|
||||
|
||||
|
||||
#### *MQTTClient.publish_topic_with_response(topic, response_topic, payload=None, qos=None, retain=False, timeout=None)*
|
||||
|
||||
Publishes the supplied `topic` with the arguments specified by `payload`,
|
||||
`qos`, and `retain`, then subscribes to the `response_topic`. The payload
|
||||
delivered by the response topic is returned. Note that this method is
|
||||
a coroutine, it must always be awaited. The call will block until the
|
||||
entire process has completed unless a `timeout` (in seconds) is specifed.
|
||||
The `timeout` is applied to both the attempt to publish and the pending
|
||||
response, so the maximum waiting time would be approximately 2*timeout.
|
||||
|
||||
!!! warning
|
||||
This should only be used when it is guaranteed that the `response_topic`
|
||||
does not have a retained value. Otherwise the returned response will
|
||||
be the retained value.
|
||||
|
||||
#### *MQTTClient.subscribe_topic(topic, callback, qos=None)*
|
||||
|
||||
Subscibes to the supplied `topic` with the specified `qos`. If `qos` is not
|
||||
supplied the configured default will be used. The `callback` should be a
|
||||
callable that accepts a `payload` argument of a `bytes` type. The callable
|
||||
may be a coroutine. The callback will be run each time the subscribed topic
|
||||
is published by another client.
|
||||
|
||||
Returns a `SubscriptionHandle` that may be used to unsubscribe the topic.
|
||||
|
||||
#### *MQTTClinet.unsubscribe(hdl)*
|
||||
|
||||
Unsubscribes the callback associated with `hdl`. If no outstanding callbacks
|
||||
exist for the topic then the topic is unsubscribed from the broker.
|
||||
+378
-75
@@ -1,29 +1,17 @@
|
||||
#
|
||||
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.
|
||||
references configuration for both Klipper (`printer.cfg`) and Moonraker
|
||||
(`moonraker.conf`), each example contains a commment indicating which
|
||||
configuration file is being refrenenced. A basic
|
||||
[sample configuration](./moonraker.conf) in the `docs` directory.
|
||||
|
||||
# Primary Configuration
|
||||
The sections outlined here are required for Moonraker to function. A
|
||||
minimal functional configuration might look like the following:
|
||||
```
|
||||
# moonraker.conf
|
||||
## `[server]`
|
||||
|
||||
[server]
|
||||
host: 0.0.0.0
|
||||
port: 7125
|
||||
enable_debug_logging: True
|
||||
config_path: ~/.klippy_config
|
||||
The `[server]` section provides essential configuration for Moonraker
|
||||
and its core components. This section is requrired.
|
||||
|
||||
[authorization]
|
||||
enabled: True
|
||||
trusted_clients:
|
||||
192.168.1.0/24
|
||||
```
|
||||
```ini
|
||||
|
||||
## server
|
||||
|
||||
```
|
||||
# moonraker.conf
|
||||
|
||||
[server]
|
||||
@@ -32,67 +20,128 @@ host: 0.0.0.0
|
||||
# to all interfaces
|
||||
port: 7125
|
||||
# The port the HTTP server will listen on. Default is 7125
|
||||
ssl_port: 7130
|
||||
# The port to listen on for SSS (HTTPS) connections. Note that the HTTPS
|
||||
# server will only be started of the certificate and key options outlined
|
||||
# below are provied. The default is 7130.
|
||||
ssl_certificate_path:
|
||||
# The path to a self signed ssl certificate. The default is no path, which
|
||||
# disables HTTPS.
|
||||
ssl_key_path:
|
||||
# The path to the private key used to signed the certificate. The default
|
||||
# is no path, which disables HTTPS.
|
||||
klippy_uds_address: /tmp/klippy_uds
|
||||
# The address of Unix Domain Socket used to communicate with Klippy. Default
|
||||
# is /tmp/klippy_uds
|
||||
max_upload_size: 200
|
||||
# The maximum size allowed for a file upload. Default is 200 MiB.
|
||||
enable_debug_logging: True
|
||||
max_upload_size: 1024
|
||||
# The maximum size allowed for a file upload (in MiB). Default is 1024 MiB.
|
||||
enable_debug_logging: False
|
||||
# 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.
|
||||
# of development the default is False.
|
||||
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.
|
||||
log_path:
|
||||
# An optional path to a directory where log files are located. Users may
|
||||
# configure various applications to store logs here and Moonraker will serve
|
||||
# them at "/server/files/logs/*". The default is no log paths.
|
||||
enable_database_debug: False
|
||||
# For developer use only. End users should leave this option set to False.
|
||||
temperature_store_size: 1200
|
||||
# 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
|
||||
## `[authorization]`
|
||||
|
||||
```
|
||||
The `[authorization]` section provides configuration for Moonraker's
|
||||
authorization module.
|
||||
|
||||
```ini
|
||||
# moonraker.conf
|
||||
|
||||
[authorization]
|
||||
enabled: True
|
||||
# Enables authorization. When set to true, requests must either contain
|
||||
# a valid API key or originate from a trusted client. Default is True.
|
||||
api_key_file: ~/.moonraker_api_key
|
||||
# Path of the file that stores Moonraker's API key. The default is
|
||||
# ~/.moonraker_api_key
|
||||
login_timeout:
|
||||
# The time, in days, after which a user is forced to re-enter their
|
||||
# credentials to log in. This period begins when a logged out user
|
||||
# first logs in. Successive logins without logging out will not
|
||||
# renew the timeout. The default is 90 days.
|
||||
trusted_clients:
|
||||
192.168.1.30
|
||||
192.168.1.0/24
|
||||
# A list of newline separated ip addresses and/or ip ranges that are
|
||||
# trusted. Trusted clients are given full access to the API. Both IPv4
|
||||
# and IPv6 addresses and ranges are supported. Ranges must be expressed
|
||||
# in CIDR notation (see http://ip.sb/cidr for more info). For example, an
|
||||
# entry of 192.168.1.0/24 will authorize IPs in the range of 192.168.1.1 -
|
||||
# 192.168.1.254. Note that when specifying IPv4 ranges the last segment
|
||||
# of the ip address must be 0. The default is no clients or ranges are
|
||||
my-printer.lan
|
||||
# A list of newline separated ip addresses, ip ranges, or fully qualified
|
||||
# domain names that are trusted. Trusted clients are given full access to
|
||||
# the API. Both IPv4 and IPv6 addresses and ranges are supported. Ranges
|
||||
# must be expressed in CIDR notation (see http://ip.sb/cidr for more info).
|
||||
# For example, an entry of 192.168.1.0/24 will authorize IPs in the range of
|
||||
# 192.168.1.1 - 192.168.1.254. Note that when specifying IPv4 ranges the
|
||||
# last segment of the ip address must be 0. The default is no clients are
|
||||
# trusted.
|
||||
cors_domains:
|
||||
http://klipper-printer.local
|
||||
http://second-printer.local:7125
|
||||
# Enables CORS for the specified domains. One may specify * if they wish
|
||||
# to allow all domains.
|
||||
# to allow all domains, however this should be an option reserved for
|
||||
# client developers and not used in production. A * can also be used
|
||||
# to specify a wildcard that matches several domains. For example:
|
||||
# *.local
|
||||
# http://*.my-domain.com
|
||||
# *.my-domain.com:*
|
||||
# Are all valid entries. However, a wildcard may not be specified in
|
||||
# the top level domain:
|
||||
# http://my-printer.*
|
||||
# The above example will be rejected.
|
||||
# When CORS is enabled by adding an entry to this option, all origins
|
||||
# matching the "trusted_clients" option will have CORS headers set as
|
||||
# well. If this option is not specified then CORS is disabled.
|
||||
force_logins: False
|
||||
# When set to True a user login is required for authorization if at least
|
||||
# one user has been created, overriding the "trusted_clients" configuration.
|
||||
# If no users have been created then trusted client checks will apply.
|
||||
# The default is False.
|
||||
```
|
||||
|
||||
# Plugin Configuration
|
||||
The sections outlined here are optional and enable additional
|
||||
functionality in moonraker.
|
||||
## `[octoprint_compat]`
|
||||
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.
|
||||
|
||||
## paneldue
|
||||
```ini
|
||||
# moonraker.conf
|
||||
|
||||
[octoprint_compat]
|
||||
```
|
||||
|
||||
## `[history]`
|
||||
Enables print history tracking.
|
||||
|
||||
```ini
|
||||
# moonraker.conf
|
||||
|
||||
[history]
|
||||
```
|
||||
|
||||
## `[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. Currently PanelDue Firmware Version 1.24 is supported. Other
|
||||
releases may not behave correctly.
|
||||
|
||||
```
|
||||
```ini
|
||||
# moonraker.conf
|
||||
|
||||
[paneldue]
|
||||
@@ -126,7 +175,7 @@ to specify commands (either built in or gcode_macros) that will show up
|
||||
in the PanelDue's "macro" menu.
|
||||
|
||||
Note that buzzing the piezo requires the following gcode_macro in `printer.cfg`:
|
||||
```
|
||||
```ini
|
||||
# printer.cfg
|
||||
|
||||
[gcode_macro PANELDUE_BEEP]
|
||||
@@ -140,17 +189,33 @@ gcode:
|
||||
duration=DURATION|float)}
|
||||
```
|
||||
|
||||
## power
|
||||
## `[power]`
|
||||
Enables device power control. Currently GPIO (relays), TPLink Smartplug,
|
||||
and Tasmota (via http) devices are supported.
|
||||
and Tasmota (via http) devices, HomeAssistant switch are supported.
|
||||
|
||||
```
|
||||
```ini
|
||||
# moonraker.conf
|
||||
|
||||
[power device_name]
|
||||
type: gpio
|
||||
# The type of device. Can be either gpio, tplink_smartplug or tasmota.
|
||||
# The type of device. Can be either gpio, tplink_smartplug, tasmota
|
||||
# shelly, homeseer, homeassistant, or loxonev1.
|
||||
# This parameter must be provided.
|
||||
off_when_shutdown: False
|
||||
# If set to True the device will be powered off when Klipper enters
|
||||
# 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
|
||||
@@ -160,15 +225,23 @@ 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
|
||||
# address should be a valid ip or hostname for the tplink device.
|
||||
# The port should be the port the device is configured to use. The
|
||||
# address must be provided. The port defaults to 9999.
|
||||
# The port should be the port the device is configured to use.
|
||||
# "Power Strips" can be controlled by including the socket index
|
||||
# in the ip address. For example, to control socket index 1:
|
||||
# 192.168.1.127/1
|
||||
# The address must be provided. The port defaults to 9999.
|
||||
address:
|
||||
password:
|
||||
output_id:
|
||||
timer:
|
||||
# The above options are used for "tasmota" devices. The
|
||||
# address should be a valid ip or hostname for the tasmota device.
|
||||
# Provide a password if configured in Tasmota (default is empty).
|
||||
@@ -177,19 +250,73 @@ 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:
|
||||
timer:
|
||||
# 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). When timer option is used to delay the turn
|
||||
# off make sure to set the state to "on" in action call_remote_method.
|
||||
# So we send a command to turn it on for x sec when its already on then
|
||||
# it turns off.
|
||||
address:
|
||||
device:
|
||||
user:
|
||||
password:
|
||||
# The above options are used for "homeseer" devices. The
|
||||
# address should be a valid ip or hostname for the homeseer controller.
|
||||
# "device" should be the ID of the device to control.
|
||||
# To find out the ID, in the HomeSeer UI, click on the device you want to
|
||||
# control (Make sure to click the sub-device that actually has On/Off
|
||||
# buttons). And then go to the "status/graphics" tab and it should list
|
||||
# "ID" in the "advanced information" section.
|
||||
# Provide a user and password with access to "device control"
|
||||
# and at least the specific device you want to control
|
||||
address:
|
||||
port:
|
||||
device:
|
||||
token:
|
||||
domain:
|
||||
# The above options are used for "homeassistant" devices. The
|
||||
# address should be a valid ip or hostname for the homeassistant controller.
|
||||
# "device" should be the ID of the switch to control.
|
||||
# "domain" is the class of device set managed by homeassistant, defaults to "switch".
|
||||
address:
|
||||
user:
|
||||
password:
|
||||
output_id:
|
||||
# The above options are used for "loxone smart home miniserver v1 " devices.
|
||||
# The address should be a valid ip or hostname for the loxone miniserver v1
|
||||
# device. All entries must be configured in advance in the loxone config.
|
||||
# Provide a user and password configured in loxone config.
|
||||
# The output_id is the name of a programmed output, virtual input or virtual
|
||||
# output in the loxone config his output_id (name) may only be used once in
|
||||
# the loxone config
|
||||
```
|
||||
Below are some potential examples:
|
||||
```
|
||||
```ini
|
||||
# moonraker.conf
|
||||
|
||||
[power printer]
|
||||
type: gpio
|
||||
pin: gpio26
|
||||
off_when_shutdown: True
|
||||
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
|
||||
@@ -199,11 +326,25 @@ 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
|
||||
|
||||
[power homeassistant_switch]
|
||||
type: homeassistant
|
||||
address: 192.168.1.126
|
||||
port: 8123
|
||||
device: switch.1234567890abcdefghij
|
||||
token: home-assistant-very-long-token
|
||||
domain: switch
|
||||
```
|
||||
|
||||
It is possible to toggle device power from the Klippy host, this can be done
|
||||
with a gcode_macro, such as:
|
||||
```
|
||||
```ini
|
||||
# printer.cfg
|
||||
|
||||
[gcode_macro POWER_OFF_PRINTER]
|
||||
@@ -215,7 +356,7 @@ gcode:
|
||||
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:
|
||||
```
|
||||
```ini
|
||||
# printer.cfg
|
||||
|
||||
[delayed_gcode delayed_printer_off]
|
||||
@@ -227,28 +368,190 @@ gcode:
|
||||
|
||||
[idle_timeout]
|
||||
gcode:
|
||||
TURN_OFF_MOTORS
|
||||
M84
|
||||
TURN_OFF_HEATERS
|
||||
UPDATE_DELAYED_GCODE ID=delayed_printer_off DURATION=60
|
||||
```
|
||||
|
||||
## update_manager
|
||||
## `[update_manager]`
|
||||
This enables moonraker's update manager. Note that updates can only be
|
||||
performed on pristine git repos. Repos that have been modified on
|
||||
disk or cloned from unofficial sources are not supported.
|
||||
|
||||
```
|
||||
```ini
|
||||
# moonraker.conf
|
||||
|
||||
[update_manager]
|
||||
client_repo:
|
||||
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.
|
||||
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.
|
||||
enable_system_updates: True
|
||||
# A boolean value that can be used to toggle system package updates.
|
||||
# Currently Moonraker only supports updating packages via APT, so
|
||||
# this option is useful for users that wish to experiment with linux
|
||||
# distros that use other package management applications, or users
|
||||
# that prefer to manage their packages directly. Note that if this
|
||||
# is set to False users will be need to make sure that all system
|
||||
# dependencies are up to date. The default is True.
|
||||
channel: dev
|
||||
# The update channel applied to Klipper and Moonraker. May be 'dev'
|
||||
# which will fetch updates using git, or 'beta' which will fetch
|
||||
# zipped beta releases. Note that this channel does not apply to
|
||||
# client updates, a client's update channel is determined by its
|
||||
# 'type' option. When this option is changed the next "update" will
|
||||
# swap channels, any untracked files in the application's path will be
|
||||
# removed during this process. The default is dev.
|
||||
```
|
||||
|
||||
### Client Configuration
|
||||
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.
|
||||
|
||||
```ini
|
||||
# moonraker.conf
|
||||
|
||||
[update_manager client_name]
|
||||
type: web
|
||||
# Indicates that this is a web client.
|
||||
repo:
|
||||
# This is the GitHub repo of the client, in the format of user/client.
|
||||
# For example, this could be set to cadriel/fluidd to update Fluidd or
|
||||
# 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
|
||||
|
||||
# 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 "applications". These may be git repositories
|
||||
or zipped distributions.
|
||||
|
||||
Note that git repos must have at least one tag for Moonraker
|
||||
to identify its version.
|
||||
|
||||
```ini
|
||||
# moonraker.conf
|
||||
|
||||
# service_name must be the name of the systemd service
|
||||
[update_manager service_name]
|
||||
type: git_repo
|
||||
# Can be git_repo, zip, or zip_beta. See your the client's documentation
|
||||
# for recommendations on which value to use. Generally a git_repo is
|
||||
# an applications "dev" channel, zip_beta is its "beta" channel, and zip
|
||||
# is its "stable" channel. This parameter must be provided.
|
||||
path:
|
||||
# The absolute path to the client's files on disk. This parameter must be
|
||||
# provided.
|
||||
# Example:
|
||||
# path: ~/service_name
|
||||
origin:
|
||||
# The full git URL of the "origin" remote for the repository. This can
|
||||
# be be viewed by navigating to your repository and running:
|
||||
# git remote -v
|
||||
# This parameter must be provided.
|
||||
primary_branch:
|
||||
# The name of the primary branch used for release code on this repo. This
|
||||
# option allows clients to specify 'main', or their own unique name, as
|
||||
# the branch used for repo validity checks. The default is master.
|
||||
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
|
||||
enable_node_updates:
|
||||
# When set to True, Moonraker will asssume that this repo relies upon node
|
||||
# and will attempt to execute "npm ci --only=prod" when it detects a change
|
||||
# to package-lock.json. Note that if your project does not have a
|
||||
# package-lock.json in its root directory then the plugin will fail to load.
|
||||
# Default is False.
|
||||
host_repo:
|
||||
# The GitHub repo in which zipped releases are hosted. Note that this does
|
||||
# not need to match the repository in the "origin" option, as it is possible
|
||||
# to use a central GitHub repository to host multiple client builds. As
|
||||
# an example, Moonraker's repo hosts builds for both Moonraker and Klipper.
|
||||
# This option defaults to the repo extracted from the "origin" option,
|
||||
# however if the origin is not hosted on GitHub then this parameter must
|
||||
# be provided.
|
||||
```
|
||||
|
||||
## `[mqtt]`
|
||||
|
||||
Enables an MQTT Client. When configured most of Moonraker's APIs are availble
|
||||
by publishing JSON-RPC requests to `{instance_name}/moonraker/api/request`.
|
||||
Responses will be published to `{instance_name}/moonraker/api/response`. See
|
||||
the [API Documentation](web_api.md#json-rpc-api-overview) for details on
|
||||
on JSON-RPC.
|
||||
|
||||
It is also possible for other components within Moonraker to use MQTT to
|
||||
publish and subscribe to topics.
|
||||
|
||||
```ini
|
||||
[mqtt]
|
||||
address:
|
||||
# Address of the Broker. This may be a hostname or IP Address. This
|
||||
# parameter must be provided.
|
||||
port:
|
||||
# Port the Broker is listening on. Default is 1883.
|
||||
username:
|
||||
# An optional username used to log in to the Broker. Default is no
|
||||
# username (an anonymous login will be attempted)
|
||||
password_file:
|
||||
# An optional path to a text file containing a password used to log in
|
||||
# to the broker. It is strongly recommended that this file be located
|
||||
# in a folder not served by Moonraker. It is also recommended that the
|
||||
# password be unique and not used for other logins, as it is stored in
|
||||
# plain text. To create a password file, one may ssh in to the device
|
||||
# and enter the following commands:
|
||||
# cd ~
|
||||
# echo mypassword > .mqttpass
|
||||
# Then set this option to:
|
||||
# ~/.mqttpass
|
||||
# If this option is omitted no password will be used to login.
|
||||
mqtt_protocol: v3.1.1
|
||||
# The protocol to use when connecting to the Broker. May be v3.1,
|
||||
# v3.1.1, and v5. The default is v3.1.1
|
||||
enable_moonraker_api: True
|
||||
# If set to true the MQTT client will subscribe to API topic, ie:
|
||||
# {instance_name}/moonraker/api/request
|
||||
# This can be set to False if the user does not wish to allow API
|
||||
# requests over MQTT. The default is True.
|
||||
instance_name:
|
||||
# An identifer used to create unique API topics for each instance of
|
||||
# Moonraker on network. This name cannot contain wildcards (+ or #).
|
||||
# For example, if the instance name is set to my_printer, Moonraker
|
||||
# will subscribe to the following topic for API requests:
|
||||
# my_printer/moonraker/api/request
|
||||
# Responses will be published to the following topic:
|
||||
# my_printer/moonraker/api/response
|
||||
# The default is the machine's hostname.
|
||||
default_qos: 0
|
||||
# The default QOS level used when publishing or subscribing to topics.
|
||||
# Must be an integer value from 0 to 2. The default is 0.
|
||||
api_qos:
|
||||
# The QOS level to use for the API topics. If not provided, the
|
||||
# value specified by "default_qos" will be used.
|
||||
```
|
||||
+67
-16
@@ -8,24 +8,75 @@ are near those of Klipper:
|
||||
|
||||
- All source files should begin with a copyright notice in the following
|
||||
format:
|
||||
```
|
||||
# Module name and brief description of module
|
||||
#
|
||||
# Copyright (C) 2020 YOUR NAME <YOUR EMAIL ADDRESS>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
```
|
||||
- No line in the source code or documentation should exceed 80 characters.
|
||||
Be sure there is no trailing whitespace.
|
||||
|
||||
# Module name and brief description of module
|
||||
#
|
||||
# Copyright (C) 2021 YOUR NAME <YOUR EMAIL ADDRESS>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
|
||||
- No line in the source code should exceed 80 characters. Be sure there is no
|
||||
trailing whitespace. To validate code before submission one may use `pycodestyle`
|
||||
with the following options:
|
||||
- `--ignore=E226,E301,E302,E303,W503,W504`
|
||||
- `--max-line-length=80`
|
||||
- `--max-doc-length=80`
|
||||
- Generally speaking, each line in submitted documentation should also be no
|
||||
longer than 80 characters, however there are situations where this isn't
|
||||
possible, such as long hyperlinks or example return values.
|
||||
- Python code should be fully annotated. Moonraker uses the `mypy` static
|
||||
type checker for code validation with the following options:
|
||||
- `--ignore-missing-imports`
|
||||
- `--follow-imports=silent`
|
||||
- Each Commit message should be in the following format:
|
||||
```
|
||||
module name: brief description of commit
|
||||
|
||||
More detailed explanation if necessary.
|
||||
module name: brief description of commit
|
||||
|
||||
More detailed explanation if necessary.
|
||||
|
||||
Signed-off-by: Your Name <your email address>
|
||||
|
||||
Signed-off-by: Your Name <your email address>
|
||||
```
|
||||
- By signing off on commits, you acknowledge that you agree to the
|
||||
[developer certificate of origin](developer-certificate-of-origin).
|
||||
As with Klipper, this must contain your real name and a current
|
||||
[developer certificate of origin](../developer-certificate-of-origin)
|
||||
shown below. Your signature must contain your real name and a current
|
||||
email address.
|
||||
|
||||
```text
|
||||
Developer Certificate of Origin
|
||||
Version 1.1
|
||||
|
||||
Copyright (C) 2004, 2006 The Linux Foundation and its contributors.
|
||||
1 Letterman Drive
|
||||
Suite D4700
|
||||
San Francisco, CA, 94129
|
||||
|
||||
Everyone is permitted to copy and distribute verbatim copies of this
|
||||
license document, but changing it is not allowed.
|
||||
|
||||
|
||||
Developer's Certificate of Origin 1.1
|
||||
|
||||
By making a contribution to this project, I certify that:
|
||||
|
||||
(a) The contribution was created in whole or in part by me and I
|
||||
have the right to submit it under the open source license
|
||||
indicated in the file; or
|
||||
|
||||
(b) The contribution is based upon previous work that, to the best
|
||||
of my knowledge, is covered under an appropriate open source
|
||||
license and I have the right under that license to submit that
|
||||
work with modifications, whether created in whole or in part
|
||||
by me, under the same open source license (unless I am
|
||||
permitted to submit under a different license), as indicated
|
||||
in the file; or
|
||||
|
||||
(c) The contribution was provided directly to me by some other
|
||||
person who certified (a), (b) or (c) and I have not modified
|
||||
it.
|
||||
|
||||
(d) I understand and agree that this project and the contribution
|
||||
are public and that a record of the contribution (including all
|
||||
personal information I submit with it, including my sign-off) is
|
||||
maintained indefinitely and may be redistributed consistent with
|
||||
this project or the open source license(s) involved.
|
||||
```
|
||||
@@ -0,0 +1 @@
|
||||
mkdocs==1.2.1
|
||||
@@ -0,0 +1,15 @@
|
||||
# Welcome to Moonraker Documentation
|
||||
|
||||
Users should refer to the [Installation](installation.md) and
|
||||
[Configuration](configuration.md) sections for documentation on how
|
||||
to install and configure Moonraker.
|
||||
|
||||
Client developers may refer to the [Client API](web_api.md)
|
||||
documentation.
|
||||
|
||||
Backend developers should refer to the
|
||||
[contibuting](contributing.md) section for basic contribution
|
||||
guidelines prior to creating a pull request. The
|
||||
[components](components.md) document provides a brief overview
|
||||
of how to create a component and interact with Moonraker's
|
||||
primary internal APIs.
|
||||
+111
-63
@@ -6,14 +6,39 @@ may work, however they may need a custom install script. Moonraker
|
||||
requires Python 3.7 or greater, verify that your distribution's
|
||||
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. After installation you should make
|
||||
sure that the [prerequistes](#prerequisites-klipper-configuration) are configured.
|
||||
### Installing Klipper
|
||||
|
||||
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
|
||||
instructs Klippy to create a Unix Domain socket:
|
||||
Klipper should be installed prior to installing Moonraker. Please see
|
||||
[Klipper's Documention](https://klipper3d.com/Overview.html) for details.
|
||||
After installing Klipper you should make sure to add Moonraker's
|
||||
[configuration requirements](#klipper-configuration-requirements).
|
||||
|
||||
### Klipper Configuration Requirements
|
||||
|
||||
Moonraker depends on the following Klippy extras for full functionality:
|
||||
|
||||
- `[virtual_sdcard]`
|
||||
- `[pause_resume]`
|
||||
- `[display_status]`
|
||||
|
||||
If you have a `[filament_switch_sensor]` configured then `[pause_resume]` will
|
||||
automatically be loaded. Likewise, if you have a `[display]` configured then
|
||||
`[display_status]` will be automatically loaded. If your configuration is
|
||||
missing one or both, you can simply add the bare sections to `printer.cfg`:
|
||||
```ini
|
||||
[pause_resume]
|
||||
|
||||
[display_status]
|
||||
|
||||
[virtual_sdcard]
|
||||
path: ~/gcode_files
|
||||
```
|
||||
|
||||
### Enabling the Unix Socket
|
||||
|
||||
After Klipper is installed it may be necessary to modify its `defaults` file in
|
||||
order to enable the Unix Domain Socket. Begin by opening the file in your
|
||||
editor of choice, for example:
|
||||
```
|
||||
sudo nano /etc/default/klipper
|
||||
```
|
||||
@@ -28,7 +53,7 @@ KLIPPY_EXEC=/home/pi/klippy-env/bin/python
|
||||
KLIPPY_ARGS="/home/pi/klipper/klippy/klippy.py /home/pi/printer.cfg -l /tmp/klippy.log"
|
||||
```
|
||||
|
||||
You need to add `-a /tmp/klippy_uds` to KLIPPY_ARGS:
|
||||
Add `-a /tmp/klippy_uds` to KLIPPY_ARGS:
|
||||
```
|
||||
# Configuration for /etc/init.d/klipper
|
||||
|
||||
@@ -38,11 +63,17 @@ 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"
|
||||
```
|
||||
|
||||
!!! note
|
||||
Your installation of Klipper may use systemd instead of
|
||||
the default LSB script. In this case, you need to modify the
|
||||
klipper.service file.
|
||||
|
||||
You may also want to take this opportunity to change the location of
|
||||
printer.cfg to match Moonraker's "config_path" option (see the
|
||||
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
|
||||
is set to `~/printer_config`, your klipper defaults file might look
|
||||
like the following:
|
||||
```
|
||||
# Configuration for /etc/init.d/klipper
|
||||
@@ -61,17 +92,19 @@ mkdir printer_config
|
||||
mv printer.cfg printer_config
|
||||
```
|
||||
|
||||
You can now install the Moonraker application:
|
||||
### Installing Moonraker
|
||||
|
||||
Begin by cloning the git respository:
|
||||
|
||||
```
|
||||
cd ~
|
||||
git clone https://github.com/Arksine/moonraker.git
|
||||
```
|
||||
|
||||
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.
|
||||
Now is a good time to create [moonraker.conf](configuration.md). If you are
|
||||
using the `config_path`, create it in the specified directory otherwise create
|
||||
it in the HOME directory. The [sample moonraker.conf](./moonraker.conf) in
|
||||
the `docs` directory may be used as a starting point.
|
||||
|
||||
For a default installation run the following commands:
|
||||
```
|
||||
@@ -87,30 +120,34 @@ cd ~/moonraker/scripts
|
||||
|
||||
The install script has a few command line options that may be useful,
|
||||
particularly for those upgrading:
|
||||
- -r\
|
||||
This will rebuild the virtual environment for existing installations.
|
||||
|
||||
- `-r`:
|
||||
Rebuilds the virtual environment for existing installations.
|
||||
Sometimes this is necessary when a dependency has been added.
|
||||
- -f\
|
||||
This will tell the script to overwrite Moonraker's "defaults" file.
|
||||
By default the script will not modify the "defaults" file if it is
|
||||
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`.
|
||||
- `-f`:
|
||||
Force an overwrite of Moonraker's systemd script. By default the
|
||||
the systemd script will not be modified if it exists.
|
||||
- `-c /home/pi/moonraker.conf`:
|
||||
Specifies the path to Moonraker's config file. The default location
|
||||
is `/home/<user>/moonraker.conf`. When using this option to modify
|
||||
an existing installation it is necessary to add `-f` as well.
|
||||
|
||||
When the script completes it should start both Moonraker and Klipper. In
|
||||
`klippy.log` you should find the following entry:\
|
||||
`webhooks client <uid>: Client info {'program': 'Moonraker', 'version': '<version>'}`\
|
||||
`/tmp/klippy.log` you should find the following entry:
|
||||
|
||||
`webhooks client <uid>: Client info {'program': 'Moonraker', 'version': '<version>'}`
|
||||
|
||||
Now you may install a client, such as
|
||||
[Mainsail](https://github.com/meteyou/mainsail) or
|
||||
[Fluidd](https://github.com/cadriel/fluidd)
|
||||
|
||||
## Command line Usage
|
||||
The configuration and log file paths may be specified via the command
|
||||
line.
|
||||
### Command line usage
|
||||
|
||||
This section is intended for users that need to write their own
|
||||
installation script. Detailed are the command line arguments
|
||||
available to Moonraker:
|
||||
```
|
||||
usage: moonraker.py [-h] [-c <configfile>] [-l <logfile>]
|
||||
usage: moonraker.py [-h] [-c <configfile>] [-l <logfile>] [-n]
|
||||
|
||||
Moonraker - Klipper API Server
|
||||
|
||||
@@ -120,44 +157,55 @@ 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`.
|
||||
|
||||
## Prerequisites (Klipper Configuration)
|
||||
|
||||
Moonraker depends on the following Klippy extras for full functionality:
|
||||
- [virtual_sdcard]
|
||||
- [pause_resume]
|
||||
- [display_status]
|
||||
|
||||
If you have a `filament_switch_sensor` configured then `pause_resume` will
|
||||
automatically be loaded. Likewise, if you have a `display` configured then
|
||||
`display_status` will be automatically loaded. If your configuration is
|
||||
missing one or both, you can simply add the bare sections to printer.cfg:
|
||||
If one needs to start moonraker without generating a log file, the
|
||||
`-n` option may be used, for example:
|
||||
```
|
||||
[pause_resume]
|
||||
|
||||
[display_status]
|
||||
|
||||
[virtual_sdcard]
|
||||
path: ~/gcode_files
|
||||
~/moonraker-env/bin/python ~/moonraker/moonraker/moonraker.py -n -c /path/to/moonraker.conf
|
||||
```
|
||||
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.
|
||||
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.
|
||||
|
||||
### Retreiving the API Key
|
||||
|
||||
Some clients may require an API Key to connect to Moonraker. After the
|
||||
`[authorization]` component is first configured Moonraker will automatically
|
||||
generate an API Key. There are two ways in which the key may be retreived
|
||||
by the user:
|
||||
|
||||
Retreive the API Key via the command line (SSH):
|
||||
```
|
||||
cd ~/moonraker/scripts
|
||||
./fetch-apikey.sh
|
||||
```
|
||||
|
||||
Retreive the API Key via the browser from a trusted client:
|
||||
|
||||
- Navigate to `http://{moonraker-host}/access/api_key`, where
|
||||
`{moonraker-host}` is the host name or ip address of the desired
|
||||
moonraker instance.
|
||||
- The result will appear in the browser window in JSON format. Copy
|
||||
The API Key without the quotes.
|
||||
|
||||
{"result": "8ce6ae5d354a4365812b83140ed62e4b"}
|
||||
|
||||
### Additional Notes
|
||||
|
||||
- Make sure that Moonraker and Klipper both have read and write access to the
|
||||
directory set in the `path` option for the `[virtual_sdcard]` in
|
||||
`printer.cfg`.
|
||||
- Upon first starting Moonraker is not aware of the gcode file path, thus
|
||||
it cannot serve gcode files, add directories, etc. After Klippy enters
|
||||
the "ready" state it sends Moonraker the gcode file path.
|
||||
|
||||
@@ -13,3 +13,8 @@ trusted_clients:
|
||||
cors_domains:
|
||||
# Allow CORS requests for Fluidd
|
||||
http://app.fluidd.xyz
|
||||
|
||||
# Enable Octoprint compatibility for Slicer uploads
|
||||
# Supports Cura, Slic3r, and Slic3r dervivatives
|
||||
# (PrusaSlicer, SuperSlicer)
|
||||
[octoprint_compat]
|
||||
@@ -1,3 +0,0 @@
|
||||
## Plugins
|
||||
|
||||
Documentation Forthcoming
|
||||
+142
-101
@@ -1,3 +1,4 @@
|
||||
#
|
||||
As mentioned in the API documentation, it is possible to
|
||||
[query](web_api.md#query-printer-object-status) or
|
||||
[subscribe](web_api.md#subscribe-to-printer-object-status)
|
||||
@@ -17,31 +18,32 @@ that reports state which can be queried.
|
||||
## webhooks
|
||||
```json
|
||||
{
|
||||
state: "startup",
|
||||
state_message: "message"
|
||||
"state": "startup",
|
||||
"state_message": "message"
|
||||
}
|
||||
```
|
||||
The `webhooks` object contains the current printer state and the current
|
||||
state message. These fields match those returned via the `/printer/info`
|
||||
endpoint. This is provided as a convience, clients may subscribe to `webhooks`
|
||||
so they are asynchonously notified of a change to printer state. The `state`
|
||||
may be "startup", "ready", "shutdown", or "error". The `state_message`
|
||||
may be `startup`, `ready`, `shutdown`, or `error`. The `state_message`
|
||||
contains a message specific to the current printers state.
|
||||
|
||||
## gcode_move
|
||||
```json
|
||||
{
|
||||
speed_factor: 1.0,
|
||||
speed: 100.0,
|
||||
extrude_factor: 1.0,
|
||||
absolute_coordinates: true,
|
||||
absolute_extrude: false,
|
||||
homing_origin: [0.0, 0.0, 0.0, 0.0],
|
||||
position: [0.0, 0.0, 0.0, 0.0],
|
||||
gcode_position: [0.0, 0.0, 0.0, 0.0]
|
||||
"speed_factor": 1.0,
|
||||
"speed": 100.0,
|
||||
"extrude_factor": 1.0,
|
||||
"absolute_coordinates": true,
|
||||
"absolute_extrude": false,
|
||||
"homing_origin": [0.0, 0.0, 0.0, 0.0],
|
||||
"position": [0.0, 0.0, 0.0, 0.0],
|
||||
"gcode_position": [0.0, 0.0, 0.0, 0.0]
|
||||
}
|
||||
```
|
||||
The `gcode_move` object reports the current gcode state:
|
||||
|
||||
- `speed_factor`: AKA "feedrate", this is the current speed multiplier
|
||||
- `speed`: The current gcode speed in mm/s.
|
||||
- `extrude_factor`: AKA "extrusion multiplier".
|
||||
@@ -59,24 +61,26 @@ The `gcode_move` object reports the current gcode state:
|
||||
the most recent "G1" or "G0" processed assuming the machine is
|
||||
using absolute coordinates.
|
||||
|
||||
Note: The printer's actual movement may lag behind the reported positional
|
||||
coordinates due to lookahead.
|
||||
!!! Note
|
||||
The printer's actual movement will lag behind the reported positional
|
||||
coordinates due to lookahead.
|
||||
|
||||
## toolhead
|
||||
```json
|
||||
{
|
||||
homed_axes: "xyz",
|
||||
print_time: 0.0,
|
||||
estimated_print_time: 0.0,
|
||||
extruder: "extruder",
|
||||
position: [0.0, 0.0, 0.0, 0.0],
|
||||
max_velocity: 500.0,
|
||||
max_accel: 3000.0,
|
||||
max_accel_to_decel: 1500.0,
|
||||
square_corner_velocity: 5.0
|
||||
"homed_axes": "xyz",
|
||||
"print_time": 0.0,
|
||||
"estimated_print_time": 0.0,
|
||||
"extruder": "extruder",
|
||||
"position": [0.0, 0.0, 0.0, 0.0],
|
||||
"max_velocity": 500.0,
|
||||
"max_accel": 3000.0,
|
||||
"max_accel_to_decel": 1500.0,
|
||||
"square_corner_velocity": 5.0
|
||||
}
|
||||
```
|
||||
The `toolhead` object reports state of the current tool:
|
||||
|
||||
- `homed_axes`: a string containing the axes that are homed. If no axes
|
||||
are homed, returns a null string.
|
||||
- `print_time`: internal value, not generally useful for clients
|
||||
@@ -95,23 +99,29 @@ The `toolhead` object reports state of the current tool:
|
||||
- `square_corner_velocity`: The currently set square corner velocity. This
|
||||
is the maximum velocity at which the tool may travel a 90 degree corner.
|
||||
|
||||
Note: `max_velocity`, `max_accel`, `max_accel_to_decel`, and
|
||||
`square_corner_velocity` can be changed by the `SET_VELOCITY_LIMIT` gcode.
|
||||
`M204` can also change `max_accel`.
|
||||
!!! tip
|
||||
`max_velocity`, `max_accel`, `max_accel_to_decel`, and
|
||||
`square_corner_velocity` can be changed by the `SET_VELOCITY_LIMIT` gcode.
|
||||
`M204` can also change `max_accel`.
|
||||
|
||||
## configfile
|
||||
```json
|
||||
{
|
||||
config: {},
|
||||
save_config_pending: false
|
||||
"config": {},
|
||||
"settings": {},
|
||||
"save_config_pending": false
|
||||
}
|
||||
```
|
||||
The `configfile` object reports printer configuration state:
|
||||
|
||||
- `config`: This is an object containing the configuration as read from
|
||||
printer.cfg. Each config section will be an object containing the
|
||||
configured options. Option values will ALWAYS be reported as
|
||||
configured options. Values will ALWAYS be reported as
|
||||
strings. Note that default values are not reported, only options
|
||||
configured in printer.cfg are present.
|
||||
- `settings`: Similar to `config`, however this object includes default
|
||||
values that may not have been included in `printer.cfg`. It is possible
|
||||
for a value to be a string, integer, boolean, or float.
|
||||
- `save_config_pending`: True if the printer has taken an action which
|
||||
has updated the internal configuration (ie: PID calibration, probe
|
||||
calibration, bed mesh calibration). This allows clients to present
|
||||
@@ -119,75 +129,91 @@ The `configfile` object reports printer configuration state:
|
||||
save the configuration to printer.cfg and restart the Klippy Host.
|
||||
|
||||
## extruder
|
||||
*Enabled when [extruder] is included in printer.cfg*
|
||||
Note: If multiple extruders are configured, extruder 0 is available as
|
||||
`extruder`, extruder 1 as `extruder1` and so on.
|
||||
*Enabled when `[extruder]` is included in printer.cfg*
|
||||
!!! note
|
||||
If multiple extruders are configured, extruder 0 is available as
|
||||
`extruder`, extruder 1 as `extruder1` and so on.
|
||||
```json
|
||||
{
|
||||
temperature: 0.0,
|
||||
target: 0.0
|
||||
pressure_advance: 0.0,
|
||||
smooth_time: 0.0
|
||||
"temperature": 0.0,
|
||||
"target": 0.0,
|
||||
"power": 0.0,
|
||||
"pressure_advance": 0.0,
|
||||
"smooth_time": 0.0
|
||||
}
|
||||
```
|
||||
The `extruder` object reports state of an extruder:
|
||||
|
||||
- `temperature`: The extruder's current temperature (in C).
|
||||
- `target`: The extruder's target temperature (in C).
|
||||
- `power`: The current pwm value applied to the heater. This value is
|
||||
expressed as a percentage from 0.0 to 1.0.
|
||||
- `pressure_advance`: The extruder's current pressure advance value.
|
||||
- `smooth_time`: The currently set time range to use when calculating the
|
||||
average extruder velocity for pressure advance.
|
||||
|
||||
## heater_bed
|
||||
*Enabled when [heater_bed] is included in printer.cfg*
|
||||
*Enabled when `[heater_bed]` is included in printer.cfg*
|
||||
```json
|
||||
{
|
||||
temperature: 0.0,
|
||||
target: 0.0
|
||||
"temperature": 0.0,
|
||||
"target": 0.0,
|
||||
"power": 0.0,
|
||||
}
|
||||
```
|
||||
The `heater_bed` object reports state of the heated bed:
|
||||
|
||||
- `temperature`: The bed's current temperature
|
||||
- `target`: The bed's target temperature
|
||||
- `power`: The current pwm value applied to the heater. This value is
|
||||
expressed as a percentage from 0.0 to 1.0.
|
||||
|
||||
## fan
|
||||
*Enabled when [fan] is included in printer.cfg*
|
||||
*Enabled when `[fan]` is included in printer.cfg*
|
||||
```json
|
||||
{
|
||||
speed: 0.0
|
||||
"speed": 0.0,
|
||||
"rpm": 4000
|
||||
}
|
||||
```
|
||||
The `fan` object returns state of the part cooling fan:
|
||||
|
||||
- `speed`: The current fan speed. This is reported as a
|
||||
percentage of maximum speed in the range of 0.0 - 1.0.
|
||||
- `rpm`: The fan's revolutions per minute if the tachometer
|
||||
pin has been configured. Will report `null` if no tach
|
||||
has been configured.
|
||||
|
||||
## idle_timeout
|
||||
```json
|
||||
{
|
||||
state: "Idle",
|
||||
printing_time: 0.0
|
||||
"state": "Idle",
|
||||
"printing_time": 0.0
|
||||
}
|
||||
```
|
||||
|
||||
The `idle_timeout` object reports the idle state of the printer:
|
||||
- `state`: Can be "Idle", "Ready", or "Printing". The printer will
|
||||
transition to the "Printing" state whenever a gcode is issued that
|
||||
|
||||
- `state`: Can be `Idle`, `Ready`, or `Printing`. The printer will
|
||||
transition to the `Printing` state whenever a gcode is issued that
|
||||
commands the tool, this includes manual commands. Thus this should
|
||||
not be used to determine if a gcode file print is in progress. It can
|
||||
however be used to determine if the printer is busy.
|
||||
- `printing_time`: The amount of time the printer has been in the
|
||||
"Printing" state. This is reset to 0 whenever the printer transitions
|
||||
from "Printing" to "Ready".
|
||||
`Printing` state. This is reset to 0 whenever the printer transitions
|
||||
from `Printing` to `Ready`.
|
||||
|
||||
## virtual_sdcard
|
||||
*Enabled when [virtual_sdcard] is included in printer.cfg*
|
||||
*Enabled when `[virtual_sdcard]` is included in printer.cfg*
|
||||
```json
|
||||
{
|
||||
progress: 0.0,
|
||||
is_active: false,
|
||||
file_position: 0
|
||||
"progress": 0.0,
|
||||
"is_active": false,
|
||||
"file_position": 0
|
||||
}
|
||||
```
|
||||
The `virtual_sdcard` object reports the state of the virtual sdcard:
|
||||
|
||||
- `progress`: The print progress reported as a percentage of the file
|
||||
read, in the range of 0.0 - 1.0.
|
||||
- `is_active`: Returns true if the virtual sdcard is currently processing
|
||||
@@ -196,23 +222,25 @@ The `virtual_sdcard` object reports the state of the virtual sdcard:
|
||||
- `file_position`: The current file position in bytes. This will always
|
||||
be an integer value
|
||||
|
||||
Note: `progress` and `file_position` will persist after a print has
|
||||
paused, completed, or errored. They are cleared when the user issues
|
||||
a SDCARD_RESET_FILE gcode or when a new print has started.
|
||||
!!! Note
|
||||
`progress` and `file_position` will persist after a print has
|
||||
paused, completed, or errored. They are cleared when the user issues
|
||||
a SDCARD_RESET_FILE gcode or when a new print has started.
|
||||
|
||||
## print_stats
|
||||
*Enabled when [virtual_sdcard] is included in printer.cfg*
|
||||
*Enabled when `[virtual_sdcard]` is included in printer.cfg*
|
||||
```json
|
||||
{
|
||||
filename: "",
|
||||
total_duration: 0.0,
|
||||
print_duration: 0.0,
|
||||
filament_used: 0.0,
|
||||
state: "standby",
|
||||
message: ""
|
||||
"filename": "",
|
||||
"total_duration": 0.0,
|
||||
"print_duration": 0.0,
|
||||
"filament_used": 0.0,
|
||||
"state": "standby",
|
||||
"message": ""
|
||||
}
|
||||
```
|
||||
The `print_stats` object reports "virtual_sdcard" print state:
|
||||
The `print_stats` object reports `virtual_sdcard` print state:
|
||||
|
||||
- `filename`: The name of the current file loaded. This will be a null
|
||||
string if no file is loaded. Note that name is a path relative to the
|
||||
gcode folder, thus if the file is located in a subdirectory it would
|
||||
@@ -223,57 +251,66 @@ The `print_stats` object reports "virtual_sdcard" print state:
|
||||
equivalent to `total_duration` - time paused.
|
||||
- `filament_used`: The amount of filament used during the current print
|
||||
(in mm). Any extrusion during a pause is excluded.
|
||||
- `state`: Current print state. Can be "standby", "printing", "paused",
|
||||
"complete", or "error". If an error is detected the print will abort.
|
||||
- `state`: Current print state. Can be one of the following values:
|
||||
- `"standby"`
|
||||
- `"printing"`
|
||||
- `"paused"`
|
||||
- `"complete"`
|
||||
- `"cancelled"`
|
||||
- `"error"` - Note that if an error is detected the print will abort
|
||||
- `message`: If an error is detected, this field contains the error
|
||||
message generated. Otherwise it will be a null string.
|
||||
|
||||
Note: After a print has started all of the values above will persist until
|
||||
the user issues a SDCARD_RESET_FILE gcode or when a new print has started.
|
||||
!!! Note
|
||||
After a print has started all of the values above will persist until
|
||||
the user issues a SDCARD_RESET_FILE gcode or when a new print has started.
|
||||
|
||||
## display_status
|
||||
*Enabled when [display] or [display_status] is included in printer.cfg*
|
||||
*Enabled when `[display]` or `[display_status]` is included in printer.cfg*
|
||||
```json
|
||||
{
|
||||
message: "",
|
||||
progress: 0.0
|
||||
"message": "",
|
||||
"progress": 0.0
|
||||
}
|
||||
```
|
||||
The `display_status` object contains state typically used to update displays:
|
||||
|
||||
- `message`: The message set by a M117 gcode. If no message is set this will
|
||||
be a null string.
|
||||
- `progress`: The percentage of print progress, as reported by M73. This
|
||||
will be in the range of 0.0 - 1.0. If no M73 has been issued this value
|
||||
will fallback to the eqivalent of `virtual_sdcard.progess`. Note that
|
||||
will fallback to the eqivalent of `virtual_sdcard.progress`. Note that
|
||||
progress updated via M73 has a timeout. If no M73 is received after 5
|
||||
seconds, `progress` will be set to the fallback value.
|
||||
|
||||
## temperature_sensor sensor_name
|
||||
*Enabled when [temperature_sensor sensor_name] is included in printer.cfg. It is*
|
||||
*possible for multiple temperature sensors to be configured.*
|
||||
*Enabled when `[temperature_sensor sensor_name]` is included in printer.cfg.
|
||||
It is possible for multiple temperature sensors to be configured.*
|
||||
```json
|
||||
{
|
||||
temperature: 0.0,
|
||||
measured_min_temp: 0.0,
|
||||
measured_max_temp: 0.0
|
||||
"temperature": 0.0,
|
||||
"measured_min_temp": 0.0,
|
||||
"measured_max_temp": 0.0
|
||||
}
|
||||
```
|
||||
A `temperature_sensor` reports the following state:
|
||||
|
||||
- `temperature`: Sensor's current reported temperature
|
||||
- `measured_min_temp`: The mimimum temperature read from the sensor
|
||||
- `measured_max_temp`: The maximum temperature read from the sensor
|
||||
|
||||
## temperature_fan fan_name
|
||||
*Enabled when [temperature_fan fan_name] is included in printer.cfg. It is*
|
||||
*possible for multiple temperature fans to be configured.*
|
||||
*Enabled when `[temperature_fan fan_name]` is included in printer.cfg. It is
|
||||
possible for multiple temperature fans to be configured.*
|
||||
```json
|
||||
{
|
||||
speed: 0.0,
|
||||
temperature: 0.0,
|
||||
target: 0.0
|
||||
"speed": 0.0,
|
||||
"temperature": 0.0,
|
||||
"target": 0.0
|
||||
}
|
||||
```
|
||||
A `temperature_fan` reports the following state:
|
||||
|
||||
- `speed`: Current fan speed as a percentage of maximum speed, reported
|
||||
in the range of 0.0 - 1.0
|
||||
- `temperature`: Currently reported temperature of the sensor associated
|
||||
@@ -281,48 +318,51 @@ A `temperature_fan` reports the following state:
|
||||
- `target`: The current target temperature for the `temperature_fan`.
|
||||
|
||||
## filament_switch_sensor sensor_name
|
||||
*Enabled when [filament_switch_sensor sensor_name] is included in printer.cfg.*
|
||||
*It is possible for multiple filament sensors to be configured.*
|
||||
*Enabled when `[filament_switch_sensor sensor_name]` is included in
|
||||
printer.cfg. It is possible for multiple filament sensors to be configured.*
|
||||
```json
|
||||
{
|
||||
filament_detected: false,
|
||||
enabled: true
|
||||
"filament_detected": false,
|
||||
"enabled": true
|
||||
}
|
||||
```
|
||||
A `filament_switch_sensor` reports the following state:
|
||||
|
||||
- `filament_detected`: Set to true if the switch detects filament, otherwise
|
||||
false
|
||||
- `enabled`: Set to true if the sensor is currently enabled, otherwise false
|
||||
|
||||
## output_pin pin_name
|
||||
*Enabled when [output_pin pin_name] is included in printer.cfg.*
|
||||
*It is possible for multiple output pins to be configured.*
|
||||
*Enabled when `[output_pin pin_name]` is included in printer.cfg.
|
||||
It is possible for multiple output pins to be configured.*
|
||||
```json
|
||||
{
|
||||
value: 0.0
|
||||
"value": 0.0
|
||||
}
|
||||
```
|
||||
An `output_pin` reports the following state:
|
||||
|
||||
- `value`: The currently set value of the pin, in the range of 0.0 - 1.0.
|
||||
A digital pin will always be 0 or 1, whereas a pwm pin may report a value
|
||||
across the entire range.
|
||||
|
||||
## bed_mesh
|
||||
*Enabled when [bed_mesh] is included in printer.cfg.*
|
||||
*Enabled when `[bed_mesh]` is included in printer.cfg.*
|
||||
```json
|
||||
{
|
||||
profile_name: "",
|
||||
mesh_min: [0.0, 0.0],
|
||||
mesh_max: [0.0, 0.0],
|
||||
probed_matrix: [[]],
|
||||
mesh_matrix: [[]]
|
||||
"profile_name": "",
|
||||
"mesh_min": [0.0, 0.0],
|
||||
"mesh_max": [0.0, 0.0],
|
||||
"probed_matrix": [[]],
|
||||
"mesh_matrix": [[]]
|
||||
}
|
||||
```
|
||||
The `bed_mesh` printer object reports the following state:
|
||||
|
||||
- `profile_name`: The name of the currently loaded profile. If no profile is
|
||||
loaded then this will report a null string. If the user is not using bed_mesh
|
||||
profile management then this will report "default" after mesh calibration
|
||||
completes.
|
||||
loaded then this will report a null string. If the user is not using
|
||||
bed_mesh profile management then this will report `default` after mesh
|
||||
calibration completes.
|
||||
- `mesh_min`: [X, Y] - The minimum x and y coordinates of the mesh.
|
||||
- `mesh_max`: [X, Y] - The maximum x and y coordinates of the mesh.
|
||||
- `probed_matrix`: A 2 dimensional array representing the matrix of probed
|
||||
@@ -330,15 +370,16 @@ The `bed_mesh` printer object reports the following state:
|
||||
- `mesh_matrix`: A 2 dimension array representing the interpolated mesh. If
|
||||
no matrix has been generated the result is `[[]]`.
|
||||
|
||||
Note: See [web_api.md](web_api.md##bed-mesh-coordinates) for an example
|
||||
of how to use this information to generate (X,Y,Z) coordinates.
|
||||
!!! tip
|
||||
See [web_api.md](web_api.md##bed-mesh-coordinates) for an example
|
||||
of how to use this information to generate (X,Y,Z) coordinates.
|
||||
|
||||
## gcode_macro macro_name
|
||||
*Enabled when [gcode_macro macro_name] is included in printer.cfg.*
|
||||
*It is possible for multiple gcode macros to be configured.*
|
||||
*Enabled when `[gcode_macro macro_name]` is included in printer.cfg.
|
||||
It is possible for multiple gcode macros to be configured.*
|
||||
|
||||
Gcode macros will report the state of configured "variables".
|
||||
Gcode macros will report the state of configured `variables`.
|
||||
While user defined macros likely won't report state that is useful
|
||||
for a client, it is possible for client developers to recommend or
|
||||
request a specific gcode_macro configuration, then have the client
|
||||
take action based on the variables reported by the macro.
|
||||
take action based on the variables reported by the macro.
|
||||
+56
-16
@@ -1,16 +1,56 @@
|
||||
##
|
||||
This file will track changes that require user intervention,
|
||||
such as a configuration change or a reinstallation.
|
||||
|
||||
### April 19th 2021
|
||||
- The `[authorization]` module is now a component, thus is only
|
||||
loaded if the user has it configured in `moonraker.conf`. This
|
||||
deprecates the previous `enable` option, as it is enabled
|
||||
if configured and disabled otherwise.
|
||||
- The API Key is now stored in the database. This deprecates the
|
||||
`api_key_file` option in the `[authorization]` module. Users can
|
||||
no longer read the contents of the API Key file to retreive the
|
||||
API Key. Instead, users can run `scripts/fetch-apikey.sh` to
|
||||
print the API Key. Alternative a user can navigate to
|
||||
`http://{moonraker-host}/access/api_key` from a trusted client
|
||||
to retreive the API Key.
|
||||
|
||||
### March 10th 2021
|
||||
- The `cors_domain` option in the `[authoriztion]` section is now
|
||||
checked for dangerous entries. If a domain entry contains a
|
||||
wildcard in the top level domain (ie: `http://www.*`) then it
|
||||
will be rejected, as malicious website can easily reproduce
|
||||
this match.
|
||||
|
||||
### March 6th 2021
|
||||
- The `enable_debug_logging` in the `[server]` section now defaults
|
||||
to `False`. This dramatically reduces the amount of logging produced
|
||||
by Moonraker for the typical user.
|
||||
|
||||
### March 4th 2021
|
||||
- To enable Octoprint compatibility with slicer uploads it is now
|
||||
required to add `[octoprint_compat]` to `moonraker.conf`. After
|
||||
making this change it is necessary to restart the Moonraker service
|
||||
so the module is loaded.
|
||||
|
||||
### 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
|
||||
```
|
||||
|
||||
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
|
||||
@@ -23,24 +63,24 @@ such as a configuration change or a reinstallation.
|
||||
will update the defaults file wih the new path.
|
||||
- New dependencies have been added to Moonraker which require reinstallation.
|
||||
Run the following command to reinstall and rebuild the virtualenv:
|
||||
```
|
||||
~/moonraker/scripts/install-moonraker.sh -r
|
||||
```
|
||||
|
||||
~/moonraker/scripts/install-moonraker.sh -r
|
||||
|
||||
- The power plugin configuration has changed. See the
|
||||
[install guide](installation.md#power-control-plugin) for
|
||||
details on the new configuration.
|
||||
- Users transitioning from the previous version of the power plugin will need
|
||||
to unexport any curently used pins. For example, the following command
|
||||
may be used to unexport pin 19:
|
||||
```
|
||||
echo 19 > /sys/class/gpio/unexport
|
||||
```
|
||||
|
||||
echo 19 > /sys/class/gpio/unexport
|
||||
|
||||
Alternatively one may reboot the machine after upgrading:
|
||||
```
|
||||
cd ~/moonraker/
|
||||
git pull
|
||||
~/moonraker/scripts/install-moonraker.sh -r
|
||||
sudo reboot
|
||||
```
|
||||
|
||||
cd ~/moonraker/
|
||||
git pull
|
||||
~/moonraker/scripts/install-moonraker.sh -r
|
||||
sudo reboot
|
||||
|
||||
Make sure that the power plugin configuration has been updated prior
|
||||
to rebooting the machine.
|
||||
+3174
-1010
File diff suppressed because it is too large.
Load diff
+22
@@ -0,0 +1,22 @@
|
||||
site_name: Moonraker
|
||||
site_url: https://moonraker.readthedocs.io
|
||||
repo_url: https://github.com/Arksine/moonraker
|
||||
nav:
|
||||
- 'User Documentation':
|
||||
- Installation: installation.md
|
||||
- Configuration : configuration.md
|
||||
- User Changes: user_changes.md
|
||||
- 'Client Developers':
|
||||
- Client API: web_api.md
|
||||
- Printer Objects: printer_objects.md
|
||||
- API Changes: api_changes.md
|
||||
- 'Backend Developers':
|
||||
- Contributing: contributing.md
|
||||
- Components: components.md
|
||||
theme:
|
||||
name: readthedocs
|
||||
plugins:
|
||||
- search
|
||||
markdown_extensions:
|
||||
- codehilite
|
||||
- admonition
|
||||
+660
-180
@@ -4,17 +4,52 @@
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
|
||||
from __future__ import annotations
|
||||
import os
|
||||
import mimetypes
|
||||
import logging
|
||||
import json
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import traceback
|
||||
import ssl
|
||||
import urllib.parse
|
||||
import tornado
|
||||
import tornado.iostream
|
||||
import tornado.httputil
|
||||
import tornado.web
|
||||
from inspect import isclass
|
||||
from tornado.escape import url_unescape
|
||||
from tornado.routing import Rule, PathMatches, AnyMatches
|
||||
from tornado.http1connection import HTTP1Connection
|
||||
from tornado.log import access_log
|
||||
from tornado.ioloop import IOLoop
|
||||
from utils import ServerError
|
||||
from websockets import WebRequest, WebsocketManager, WebSocket
|
||||
from authorization import AuthorizedRequestHandler, AuthorizedFileHandler
|
||||
from authorization import Authorization
|
||||
from streaming_form_data import StreamingFormDataParser
|
||||
from streaming_form_data.targets import FileTarget, ValueTarget, SHA256Target
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Optional,
|
||||
Callable,
|
||||
Coroutine,
|
||||
Union,
|
||||
Dict,
|
||||
List,
|
||||
AsyncGenerator,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from tornado.httpserver import HTTPServer
|
||||
from moonraker import Server
|
||||
from confighelper import ConfigHelper
|
||||
from websockets import APITransport
|
||||
from components.file_manager.file_manager import FileManager
|
||||
import components.authorization
|
||||
MessageDelgate = Optional[tornado.httputil.HTTPMessageDelegate]
|
||||
AuthComp = Optional[components.authorization.Authorization]
|
||||
APICallback = Callable[[WebRequest], Coroutine]
|
||||
|
||||
# These endpoints are reserved for klippy/server communication only and are
|
||||
# not exposed via http or the websocket
|
||||
@@ -23,42 +58,24 @@ RESERVED_ENDPOINTS = [
|
||||
"register_remote_method"
|
||||
]
|
||||
|
||||
EXCLUDED_ARGS = ["_", "token", "connection_id"]
|
||||
|
||||
# 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
|
||||
# 50 MiB Max Standard Body Size
|
||||
MAX_BODY_SIZE = 50 * 1024 * 1024
|
||||
EXCLUDED_ARGS = ["_", "token", "access_token", "connection_id"]
|
||||
AUTHORIZED_EXTS = [".png"]
|
||||
DEFAULT_KLIPPY_LOG_PATH = "/tmp/klippy.log"
|
||||
ALL_TRANSPORTS = ["http", "websocket", "mqtt"]
|
||||
|
||||
class MutableRouter(tornado.web.ReversibleRuleRouter):
|
||||
def __init__(self, application):
|
||||
def __init__(self, application: MoonrakerApp) -> None:
|
||||
self.application = application
|
||||
self.pattern_to_rule = {}
|
||||
self.pattern_to_rule: Dict[str, Rule] = {}
|
||||
super(MutableRouter, self).__init__(None)
|
||||
|
||||
def get_target_delegate(self, target, request, **target_params):
|
||||
def get_target_delegate(self,
|
||||
target: Any,
|
||||
request: tornado.httputil.HTTPServerRequest,
|
||||
**target_params
|
||||
) -> MessageDelgate:
|
||||
if isclass(target) and issubclass(target, tornado.web.RequestHandler):
|
||||
return self.application.get_handler_delegate(
|
||||
request, target, **target_params)
|
||||
@@ -66,17 +83,21 @@ class MutableRouter(tornado.web.ReversibleRuleRouter):
|
||||
return super(MutableRouter, self).get_target_delegate(
|
||||
target, request, **target_params)
|
||||
|
||||
def has_rule(self, pattern):
|
||||
def has_rule(self, pattern: str) -> bool:
|
||||
return pattern in self.pattern_to_rule
|
||||
|
||||
def add_handler(self, pattern, target, target_params):
|
||||
def add_handler(self,
|
||||
pattern: str,
|
||||
target: Any,
|
||||
target_params: Optional[Dict[str, Any]]
|
||||
) -> None:
|
||||
if pattern in self.pattern_to_rule:
|
||||
self.remove_handler(pattern)
|
||||
new_rule = Rule(PathMatches(pattern), target, target_params)
|
||||
self.pattern_to_rule[pattern] = new_rule
|
||||
self.rules.append(new_rule)
|
||||
|
||||
def remove_handler(self, pattern):
|
||||
def remove_handler(self, pattern: str) -> None:
|
||||
rule = self.pattern_to_rule.pop(pattern, None)
|
||||
if rule is not None:
|
||||
try:
|
||||
@@ -85,76 +106,149 @@ class MutableRouter(tornado.web.ReversibleRuleRouter):
|
||||
logging.exception(f"Unable to remove rule: {pattern}")
|
||||
|
||||
class APIDefinition:
|
||||
def __init__(self, endpoint, http_uri, ws_methods,
|
||||
request_methods, parser):
|
||||
def __init__(self,
|
||||
endpoint: str,
|
||||
http_uri: str,
|
||||
jrpc_methods: List[str],
|
||||
request_methods: Union[str, List[str]],
|
||||
transports: List[str],
|
||||
callback: Optional[APICallback],
|
||||
need_object_parser: bool):
|
||||
self.endpoint = endpoint
|
||||
self.uri = http_uri
|
||||
self.ws_methods = ws_methods
|
||||
self.jrpc_methods = jrpc_methods
|
||||
if not isinstance(request_methods, list):
|
||||
request_methods = [request_methods]
|
||||
self.request_methods = request_methods
|
||||
self.parser = parser
|
||||
self.supported_transports = transports
|
||||
self.callback = callback
|
||||
self.need_object_parser = need_object_parser
|
||||
|
||||
class MoonrakerApp:
|
||||
def __init__(self, config):
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.tornado_server = None
|
||||
self.api_cache = {}
|
||||
self.registered_base_handlers = []
|
||||
self.max_upload_size = config.getint('max_upload_size', 200)
|
||||
self.http_server: Optional[HTTPServer] = None
|
||||
self.secure_server: Optional[HTTPServer] = None
|
||||
self.api_cache: Dict[str, APIDefinition] = {}
|
||||
self.registered_base_handlers: List[str] = []
|
||||
self.max_upload_size = config.getint('max_upload_size', 1024)
|
||||
self.max_upload_size *= 1024 * 1024
|
||||
|
||||
# SSL config
|
||||
self.cert_path: str = self._get_path_option(
|
||||
config, 'ssl_certificate_path')
|
||||
self.key_path: str = self._get_path_option(
|
||||
config, 'ssl_key_path')
|
||||
|
||||
# Set Up Websocket and Authorization Managers
|
||||
self.wsm = WebsocketManager(self.server)
|
||||
self.auth = Authorization(config['authorization'])
|
||||
self.api_transports: Dict[str, APITransport] = {
|
||||
"websocket": self.wsm
|
||||
}
|
||||
|
||||
mimetypes.add_type('text/plain', '.log')
|
||||
mimetypes.add_type('text/plain', '.gcode')
|
||||
mimetypes.add_type('text/plain', '.cfg')
|
||||
debug = config.getboolean('enable_debug_logging', True)
|
||||
|
||||
self.debug = config.getboolean('enable_debug_logging', False)
|
||||
log_level = logging.DEBUG if self.debug else logging.INFO
|
||||
logging.getLogger().setLevel(log_level)
|
||||
app_args: Dict[str, Any] = {
|
||||
'serve_traceback': self.debug,
|
||||
'websocket_ping_interval': 10,
|
||||
'websocket_ping_timeout': 30,
|
||||
'parent': self,
|
||||
'default_handler_class': AuthorizedErrorHandler,
|
||||
'default_handler_args': {},
|
||||
'log_function': self.log_request
|
||||
}
|
||||
|
||||
# Set up HTTP only requests
|
||||
self.mutable_router = MutableRouter(self)
|
||||
app_handlers = [
|
||||
app_handlers: List[Any] = [
|
||||
(AnyMatches(), self.mutable_router),
|
||||
(r"/websocket", WebSocket),
|
||||
(r"/api/version", EmulateOctoprintHandler)]
|
||||
|
||||
self.app = tornado.web.Application(
|
||||
app_handlers,
|
||||
serve_traceback=debug,
|
||||
websocket_ping_interval=10,
|
||||
websocket_ping_timeout=30,
|
||||
parent=self)
|
||||
(r"/server/redirect", RedirectHandler)]
|
||||
self.app = tornado.web.Application(app_handlers, **app_args)
|
||||
self.get_handler_delegate = self.app.get_handler_delegate
|
||||
|
||||
# Register handlers
|
||||
logfile = config['system_args'].get('logfile')
|
||||
self.register_static_file_handler("moonraker.log", logfile)
|
||||
self.auth.register_handlers(self)
|
||||
logfile = self.server.get_app_args().get('log_file')
|
||||
if logfile:
|
||||
self.register_static_file_handler(
|
||||
"moonraker.log", logfile, force=True)
|
||||
self.register_static_file_handler(
|
||||
"klippy.log", DEFAULT_KLIPPY_LOG_PATH, force=True)
|
||||
|
||||
def listen(self, host, port):
|
||||
self.tornado_server = self.app.listen(
|
||||
port, address=host, max_body_size=self.max_upload_size,
|
||||
def _get_path_option(self, config: ConfigHelper, option: str) -> str:
|
||||
path: Optional[str] = config.get(option, None)
|
||||
if path is None:
|
||||
return ""
|
||||
expanded = os.path.abspath(os.path.expanduser(path))
|
||||
if not os.path.exists(expanded):
|
||||
raise self.server.error(
|
||||
f"Invalid path for option '{option}', "
|
||||
f"{path} does not exist")
|
||||
return expanded
|
||||
|
||||
def listen(self, host: str, port: int, ssl_port: int) -> None:
|
||||
self.http_server = self.app.listen(
|
||||
port, address=host, max_body_size=MAX_BODY_SIZE,
|
||||
xheaders=True)
|
||||
if os.path.exists(self.cert_path) and os.path.exists(self.key_path):
|
||||
logging.info(f"Starting secure server on port {ssl_port}")
|
||||
ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
|
||||
ssl_ctx.load_cert_chain(self.cert_path, self.key_path)
|
||||
self.secure_server = self.app.listen(
|
||||
ssl_port, address=host, max_body_size=MAX_BODY_SIZE,
|
||||
xheaders=True, ssl_options=ssl_ctx)
|
||||
else:
|
||||
logging.info("SSL Certificate/Key not configured, "
|
||||
"aborting HTTPS Server startup")
|
||||
|
||||
def get_server(self):
|
||||
def log_request(self, handler: tornado.web.RequestHandler) -> None:
|
||||
status_code = handler.get_status()
|
||||
if not self.debug and status_code in [200, 204, 206, 304]:
|
||||
# don't log successful requests in release mode
|
||||
return
|
||||
if status_code < 400:
|
||||
log_method = access_log.info
|
||||
elif status_code < 500:
|
||||
log_method = access_log.warning
|
||||
else:
|
||||
log_method = access_log.error
|
||||
request_time = 1000.0 * handler.request.request_time()
|
||||
user = handler.current_user
|
||||
username = "No User"
|
||||
if user is not None and 'username' in user:
|
||||
username = user['username']
|
||||
log_method(
|
||||
f"{status_code} {handler._request_summary()} "
|
||||
f"[{username}] {request_time:.2f}ms")
|
||||
|
||||
def get_server(self) -> Server:
|
||||
return self.server
|
||||
|
||||
def get_auth(self):
|
||||
return self.auth
|
||||
|
||||
def get_websocket_manager(self):
|
||||
def get_websocket_manager(self) -> WebsocketManager:
|
||||
return self.wsm
|
||||
|
||||
async def close(self):
|
||||
if self.tornado_server is not None:
|
||||
self.tornado_server.stop()
|
||||
await self.tornado_server.close_all_connections()
|
||||
async def close(self) -> None:
|
||||
if self.http_server is not None:
|
||||
self.http_server.stop()
|
||||
await self.http_server.close_all_connections()
|
||||
if self.secure_server is not None:
|
||||
self.secure_server.stop()
|
||||
await self.secure_server.close_all_connections()
|
||||
await self.wsm.close()
|
||||
self.auth.close()
|
||||
|
||||
def register_remote_handler(self, endpoint):
|
||||
def register_api_transport(self,
|
||||
name: str,
|
||||
transport: APITransport
|
||||
) -> Dict[str, APIDefinition]:
|
||||
self.api_transports[name] = transport
|
||||
return self.api_cache
|
||||
|
||||
def register_remote_handler(self, endpoint: str) -> None:
|
||||
if endpoint in RESERVED_ENDPOINTS:
|
||||
return
|
||||
api_def = self._create_api_definition(endpoint)
|
||||
@@ -162,41 +256,52 @@ class MoonrakerApp:
|
||||
# reserved handler or already registered
|
||||
return
|
||||
logging.info(
|
||||
f"Registering remote endpoint - "
|
||||
f"HTTP: ({' '.join(api_def.request_methods)}) {api_def.uri}; "
|
||||
f"Websocket: {', '.join(api_def.ws_methods)}")
|
||||
self.wsm.register_remote_handler(api_def)
|
||||
params = {}
|
||||
params['arg_parser'] = api_def.parser
|
||||
params['remote_callback'] = api_def.endpoint
|
||||
f"Registering HTTP endpoint: "
|
||||
f"({' '.join(api_def.request_methods)}) {api_def.uri}")
|
||||
params: Dict[str, Any] = {}
|
||||
params['methods'] = api_def.request_methods
|
||||
params['callback'] = api_def.endpoint
|
||||
params['need_object_parser'] = api_def.need_object_parser
|
||||
self.mutable_router.add_handler(
|
||||
api_def.uri, RemoteRequestHandler, params)
|
||||
api_def.uri, DynamicRequestHandler, params)
|
||||
self.registered_base_handlers.append(api_def.uri)
|
||||
for name, transport in self.api_transports.items():
|
||||
transport.register_api_handler(api_def)
|
||||
|
||||
def register_local_handler(self, uri, request_methods,
|
||||
callback, protocol=["http", "websocket"]):
|
||||
def register_local_handler(self,
|
||||
uri: str,
|
||||
request_methods: List[str],
|
||||
callback: APICallback,
|
||||
transports: List[str] = ALL_TRANSPORTS,
|
||||
wrap_result: bool = True
|
||||
) -> None:
|
||||
if uri in self.registered_base_handlers:
|
||||
return
|
||||
api_def = self._create_api_definition(
|
||||
uri, request_methods, is_remote=False)
|
||||
msg = "Registering local endpoint"
|
||||
if "http" in protocol:
|
||||
msg += f" - HTTP: ({' '.join(request_methods)}) {uri}"
|
||||
params = {}
|
||||
uri, request_methods, callback, transports=transports)
|
||||
if "http" in transports:
|
||||
logging.info(
|
||||
f"Registering HTTP Endpoint: "
|
||||
f"({' '.join(request_methods)}) {uri}")
|
||||
params: dict[str, Any] = {}
|
||||
params['methods'] = request_methods
|
||||
params['arg_parser'] = api_def.parser
|
||||
params['callback'] = callback
|
||||
self.mutable_router.add_handler(uri, LocalRequestHandler, 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)
|
||||
params['wrap_result'] = wrap_result
|
||||
params['is_remote'] = False
|
||||
self.mutable_router.add_handler(uri, DynamicRequestHandler, params)
|
||||
self.registered_base_handlers.append(uri)
|
||||
for name, transport in self.api_transports.items():
|
||||
if name in transports:
|
||||
transport.register_api_handler(api_def)
|
||||
|
||||
def register_static_file_handler(self, pattern, file_path):
|
||||
def register_static_file_handler(self,
|
||||
pattern: str,
|
||||
file_path: str,
|
||||
force: bool = False
|
||||
) -> None:
|
||||
if pattern[0] != "/":
|
||||
pattern = "/server/files/" + pattern
|
||||
if os.path.isfile(file_path):
|
||||
if os.path.isfile(file_path) or force:
|
||||
pattern += '()'
|
||||
elif os.path.isdir(file_path):
|
||||
if pattern[-1] != "/":
|
||||
@@ -209,17 +314,25 @@ class MoonrakerApp:
|
||||
params = {'path': file_path}
|
||||
self.mutable_router.add_handler(pattern, FileRequestHandler, params)
|
||||
|
||||
def register_upload_handler(self, pattern):
|
||||
self.mutable_router.add_handler(pattern, FileUploadHandler, {})
|
||||
def register_upload_handler(self, pattern: str) -> None:
|
||||
self.mutable_router.add_handler(
|
||||
pattern, FileUploadHandler,
|
||||
{'max_upload_size': self.max_upload_size})
|
||||
|
||||
def remove_handler(self, endpoint):
|
||||
api_def = self.api_cache.get(endpoint)
|
||||
def remove_handler(self, endpoint: str) -> None:
|
||||
api_def = self.api_cache.pop(endpoint, None)
|
||||
if api_def is not None:
|
||||
self.wsm.remove_handler(api_def.uri)
|
||||
self.mutable_router.remove_handler(api_def.ws_method)
|
||||
self.mutable_router.remove_handler(api_def.uri)
|
||||
for name, transport in self.api_transports.items():
|
||||
transport.remove_api_handler(api_def)
|
||||
|
||||
def _create_api_definition(self, endpoint, request_methods=[],
|
||||
is_remote=True):
|
||||
def _create_api_definition(self,
|
||||
endpoint: str,
|
||||
request_methods: List[str] = [],
|
||||
callback: Optional[APICallback] = None,
|
||||
transports: List[str] = ALL_TRANSPORTS
|
||||
) -> APIDefinition:
|
||||
is_remote = callback is None
|
||||
if endpoint in self.api_cache:
|
||||
return self.api_cache[endpoint]
|
||||
if endpoint[0] == '/':
|
||||
@@ -228,109 +341,270 @@ class MoonrakerApp:
|
||||
uri = "/printer/" + endpoint
|
||||
else:
|
||||
uri = "/server/" + endpoint
|
||||
ws_methods = []
|
||||
jrpc_methods = []
|
||||
if is_remote:
|
||||
# Remote requests accept both GET and POST requests. These
|
||||
# requests execute the same callback, thus they resolve to
|
||||
# only a single websocket method.
|
||||
ws_methods.append(uri[1:].replace('/', '.'))
|
||||
jrpc_methods.append(uri[1:].replace('/', '.'))
|
||||
request_methods = ['GET', 'POST']
|
||||
else:
|
||||
name_parts = uri[1:].split('/')
|
||||
if len(request_methods) > 1:
|
||||
for req_mthd in request_methods:
|
||||
func_name = req_mthd.lower() + "_" + name_parts[-1]
|
||||
ws_methods.append(".".join(name_parts[:-1] + [func_name]))
|
||||
jrpc_methods.append(".".join(
|
||||
name_parts[:-1] + [func_name]))
|
||||
else:
|
||||
ws_methods.append(".".join(name_parts))
|
||||
if not is_remote and len(request_methods) != len(ws_methods):
|
||||
jrpc_methods.append(".".join(name_parts))
|
||||
if not is_remote and len(request_methods) != len(jrpc_methods):
|
||||
raise self.server.error(
|
||||
"Invalid API definition. Number of websocket methods must "
|
||||
"match the number of request methods")
|
||||
if endpoint.startswith("objects/"):
|
||||
parser = _status_parser
|
||||
else:
|
||||
parser = _default_parser
|
||||
|
||||
api_def = APIDefinition(endpoint, uri, ws_methods,
|
||||
request_methods, parser)
|
||||
need_object_parser = endpoint.startswith("objects/")
|
||||
api_def = APIDefinition(endpoint, uri, jrpc_methods, request_methods,
|
||||
transports, callback, 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
|
||||
class AuthorizedRequestHandler(tornado.web.RequestHandler):
|
||||
def initialize(self) -> None:
|
||||
self.server: Server = self.settings['parent'].get_server()
|
||||
|
||||
async def get(self):
|
||||
await self._process_http_request()
|
||||
def set_default_headers(self) -> None:
|
||||
origin: Optional[str] = self.request.headers.get("Origin")
|
||||
# it is necessary to look up the parent app here,
|
||||
# as initialize() may not yet be called
|
||||
server: Server = self.settings['parent'].get_server()
|
||||
auth: AuthComp = server.lookup_component('authorization', None)
|
||||
self.cors_enabled = False
|
||||
if auth is not None:
|
||||
self.cors_enabled = auth.check_cors(origin, self)
|
||||
|
||||
async def post(self):
|
||||
await self._process_http_request()
|
||||
def prepare(self) -> None:
|
||||
auth: AuthComp = self.server.lookup_component('authorization', None)
|
||||
if auth is not None:
|
||||
self.current_user = auth.check_authorized(self.request)
|
||||
|
||||
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})
|
||||
def options(self, *args, **kwargs) -> None:
|
||||
# Enable CORS if configured
|
||||
if self.cors_enabled:
|
||||
self.set_status(204)
|
||||
self.finish()
|
||||
else:
|
||||
super(AuthorizedRequestHandler, self).options()
|
||||
|
||||
class LocalRequestHandler(AuthorizedRequestHandler):
|
||||
def initialize(self, callback, methods, arg_parser):
|
||||
super(LocalRequestHandler, self).initialize()
|
||||
def get_associated_websocket(self) -> Optional[WebSocket]:
|
||||
# Return associated websocket connection if an id
|
||||
# was provided by the request
|
||||
conn = None
|
||||
conn_id: Any = self.get_argument('connection_id', None)
|
||||
if conn_id is not None:
|
||||
try:
|
||||
conn_id = int(conn_id)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
parent: MoonrakerApp = self.settings['parent']
|
||||
wsm: WebsocketManager = parent.get_websocket_manager()
|
||||
conn = wsm.get_websocket(conn_id)
|
||||
return conn
|
||||
|
||||
def write_error(self, status_code: int, **kwargs) -> None:
|
||||
err = {'code': status_code, 'message': self._reason}
|
||||
if 'exc_info' in kwargs:
|
||||
err['traceback'] = "\n".join(
|
||||
traceback.format_exception(*kwargs['exc_info']))
|
||||
self.finish({'error': err})
|
||||
|
||||
# Due to the way Python treats multiple inheritance its best
|
||||
# to create a separate authorized handler for serving files
|
||||
class AuthorizedFileHandler(tornado.web.StaticFileHandler):
|
||||
def initialize(self,
|
||||
path: str,
|
||||
default_filename: Optional[str] = None
|
||||
) -> None:
|
||||
super(AuthorizedFileHandler, self).initialize(path, default_filename)
|
||||
self.server: Server = self.settings['parent'].get_server()
|
||||
|
||||
def set_default_headers(self) -> None:
|
||||
origin: Optional[str] = self.request.headers.get("Origin")
|
||||
# it is necessary to look up the parent app here,
|
||||
# as initialize() may not yet be called
|
||||
server: Server = self.settings['parent'].get_server()
|
||||
auth: AuthComp = server.lookup_component('authorization', None)
|
||||
self.cors_enabled = False
|
||||
if auth is not None:
|
||||
self.cors_enabled = auth.check_cors(origin, self)
|
||||
|
||||
def prepare(self) -> None:
|
||||
auth: AuthComp = self.server.lookup_component('authorization', None)
|
||||
if auth is not None and self._check_need_auth():
|
||||
self.current_user = auth.check_authorized(self.request)
|
||||
|
||||
def options(self, *args, **kwargs) -> None:
|
||||
# Enable CORS if configured
|
||||
if self.cors_enabled:
|
||||
self.set_status(204)
|
||||
self.finish()
|
||||
else:
|
||||
super(AuthorizedFileHandler, self).options()
|
||||
|
||||
def write_error(self, status_code: int, **kwargs) -> None:
|
||||
err = {'code': status_code, 'message': self._reason}
|
||||
if 'exc_info' in kwargs:
|
||||
err['traceback'] = "\n".join(
|
||||
traceback.format_exception(*kwargs['exc_info']))
|
||||
self.finish({'error': err})
|
||||
|
||||
def _check_need_auth(self) -> bool:
|
||||
if self.request.method != "GET":
|
||||
return True
|
||||
ext = os.path.splitext(self.request.path)[-1].lower()
|
||||
if ext in AUTHORIZED_EXTS:
|
||||
return False
|
||||
return True
|
||||
|
||||
class DynamicRequestHandler(AuthorizedRequestHandler):
|
||||
def initialize(
|
||||
self,
|
||||
callback: Union[str, Callable[[WebRequest], Coroutine]] = "",
|
||||
methods: List[str] = [],
|
||||
need_object_parser: bool = False,
|
||||
is_remote: bool = True,
|
||||
wrap_result: bool = True
|
||||
) -> None:
|
||||
super(DynamicRequestHandler, self).initialize()
|
||||
self.callback = callback
|
||||
self.methods = methods
|
||||
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(self, value: str, hint: str) -> Any:
|
||||
type_funcs: Dict[str, Callable] = {
|
||||
"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) -> Dict[str, Any]:
|
||||
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) -> Dict[str, Dict[str, Any]]:
|
||||
args: Dict[str, Any] = {}
|
||||
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) -> Dict[str, Any]:
|
||||
try:
|
||||
args = self._parse_query()
|
||||
except Exception:
|
||||
raise ServerError(
|
||||
"Error Parsing Request Arguments. "
|
||||
"Is the Content-Type correct?")
|
||||
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) -> None:
|
||||
await self._process_http_request()
|
||||
|
||||
async def post(self, *args, **kwargs) -> None:
|
||||
await self._process_http_request()
|
||||
|
||||
async def delete(self, *args, **kwargs) -> None:
|
||||
await self._process_http_request()
|
||||
|
||||
async def _do_local_request(self,
|
||||
args: Dict[str, Any],
|
||||
conn: Optional[WebSocket]
|
||||
) -> Any:
|
||||
assert callable(self.callback)
|
||||
return await self.callback(
|
||||
WebRequest(self.request.path, args, self.request.method,
|
||||
conn=conn, ip_addr=self.request.remote_ip,
|
||||
user=self.current_user))
|
||||
|
||||
async def _do_remote_request(self,
|
||||
args: Dict[str, Any],
|
||||
conn: Optional[WebSocket]
|
||||
) -> Any:
|
||||
assert isinstance(self.callback, str)
|
||||
return await self.server.make_request(
|
||||
WebRequest(self.callback, args, conn=conn,
|
||||
ip_addr=self.request.remote_ip,
|
||||
user=self.current_user))
|
||||
|
||||
async def _process_http_request(self) -> None:
|
||||
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):
|
||||
def set_extra_headers(self, path: str) -> None:
|
||||
# The call below shold never return an empty string,
|
||||
# as the path should have already been validated to be
|
||||
# a file
|
||||
assert isinstance(self.absolute_path, str)
|
||||
basename = os.path.basename(self.absolute_path)
|
||||
ascii_basename = self._escape_filename_to_ascii(basename)
|
||||
utf8_basename = self._escape_filename_to_utf8(basename)
|
||||
self.set_header(
|
||||
"Content-Disposition", f"attachment; filename={basename}")
|
||||
"Content-Disposition", f"attachment; filename={ascii_basename}; "
|
||||
f"filename*=UTF-8\'\'{utf8_basename}")
|
||||
|
||||
async def delete(self, path):
|
||||
async def delete(self, path: str) -> None:
|
||||
path = self.request.path.lstrip("/").split("/", 2)[-1]
|
||||
path = url_unescape(path)
|
||||
file_manager = self.server.lookup_plugin('file_manager')
|
||||
path = url_unescape(path, plus=False)
|
||||
file_manager = self.server.lookup_component('file_manager')
|
||||
try:
|
||||
filename = await file_manager.delete_file(path)
|
||||
except self.server.error as e:
|
||||
@@ -341,20 +615,226 @@ class FileRequestHandler(AuthorizedFileHandler):
|
||||
raise tornado.web.HTTPError(e.status_code, str(e))
|
||||
self.finish({'result': filename})
|
||||
|
||||
async def get(self, path: str, include_body: bool = True) -> None:
|
||||
# Set up our path instance variables.
|
||||
self.path = self.parse_url_path(path)
|
||||
del path # make sure we don't refer to path instead of self.path again
|
||||
absolute_path = self.get_absolute_path(self.root, self.path)
|
||||
self.absolute_path = self.validate_absolute_path(
|
||||
self.root, absolute_path)
|
||||
if self.absolute_path is None:
|
||||
return
|
||||
|
||||
self.modified = self.get_modified_time()
|
||||
self.set_headers()
|
||||
|
||||
self.request.headers.pop("If-None-Match", None)
|
||||
if self.should_return_304():
|
||||
self.set_status(304)
|
||||
return
|
||||
|
||||
request_range = None
|
||||
range_header = self.request.headers.get("Range")
|
||||
if range_header:
|
||||
# As per RFC 2616 14.16, if an invalid Range header is specified,
|
||||
# the request will be treated as if the header didn't exist.
|
||||
request_range = tornado.httputil._parse_request_range(range_header)
|
||||
|
||||
size = self.get_content_size()
|
||||
if request_range:
|
||||
start, end = request_range
|
||||
if start is not None and start < 0:
|
||||
start += size
|
||||
if start < 0:
|
||||
start = 0
|
||||
if (
|
||||
start is not None
|
||||
and (start >= size or (end is not None and start >= end))
|
||||
) or end == 0:
|
||||
# As per RFC 2616 14.35.1, a range is not satisfiable only: if
|
||||
# the first requested byte is equal to or greater than the
|
||||
# content, or when a suffix with length 0 is specified.
|
||||
# https://tools.ietf.org/html/rfc7233#section-2.1
|
||||
# A byte-range-spec is invalid if the last-byte-pos value is
|
||||
# present and less than the first-byte-pos.
|
||||
self.set_status(416) # Range Not Satisfiable
|
||||
self.set_header("Content-Type", "text/plain")
|
||||
self.set_header("Content-Range", "bytes */%s" % (size,))
|
||||
return
|
||||
if end is not None and end > size:
|
||||
# Clients sometimes blindly use a large range to limit their
|
||||
# download size; cap the endpoint at the actual file size.
|
||||
end = size
|
||||
# Note: only return HTTP 206 if less than the entire range has been
|
||||
# requested. Not only is this semantically correct, but Chrome
|
||||
# refuses to play audio if it gets an HTTP 206 in response to
|
||||
# ``Range: bytes=0-``.
|
||||
if size != (end or size) - (start or 0):
|
||||
self.set_status(206) # Partial Content
|
||||
self.set_header(
|
||||
"Content-Range", tornado.httputil._get_content_range(
|
||||
start, end, size)
|
||||
)
|
||||
else:
|
||||
start = end = None
|
||||
|
||||
if start is not None and end is not None:
|
||||
content_length = end - start
|
||||
elif end is not None:
|
||||
content_length = end
|
||||
elif start is not None:
|
||||
end = size
|
||||
content_length = size - start
|
||||
else:
|
||||
end = size
|
||||
content_length = size
|
||||
self.set_header("Content-Length", content_length)
|
||||
|
||||
if include_body:
|
||||
content = self.get_content_nonblock(self.absolute_path, start, end)
|
||||
async for chunk in content:
|
||||
try:
|
||||
self.write(chunk)
|
||||
await self.flush()
|
||||
except tornado.iostream.StreamClosedError:
|
||||
return
|
||||
else:
|
||||
assert self.request.method == "HEAD"
|
||||
|
||||
def _escape_filename_to_ascii(self, basename: str) -> str:
|
||||
return basename.encode("ascii", "replace").decode()
|
||||
|
||||
def _escape_filename_to_utf8(self, basename: str) -> str:
|
||||
return urllib.parse.quote(basename, encoding="utf-8")
|
||||
|
||||
@classmethod
|
||||
async def get_content_nonblock(
|
||||
cls, abspath: str, start: Optional[int] = None,
|
||||
end: Optional[int] = None
|
||||
) -> AsyncGenerator[bytes, None]:
|
||||
ioloop = IOLoop.current()
|
||||
with open(abspath, "rb") as file:
|
||||
if start is not None:
|
||||
file.seek(start)
|
||||
if end is not None:
|
||||
remaining = end - (start or 0) # type: Optional[int]
|
||||
else:
|
||||
remaining = None
|
||||
while True:
|
||||
chunk_size = 64 * 1024
|
||||
if remaining is not None and remaining < chunk_size:
|
||||
chunk_size = remaining
|
||||
with ThreadPoolExecutor(max_workers=1) as tpe:
|
||||
chunk = await ioloop.run_in_executor(
|
||||
tpe, file.read, chunk_size)
|
||||
if chunk:
|
||||
if remaining is not None:
|
||||
remaining -= len(chunk)
|
||||
yield chunk
|
||||
else:
|
||||
if remaining is not None:
|
||||
assert remaining == 0
|
||||
return
|
||||
|
||||
@classmethod
|
||||
def _get_cached_version(cls, abs_path: str) -> Optional[str]:
|
||||
return None
|
||||
|
||||
@tornado.web.stream_request_body
|
||||
class FileUploadHandler(AuthorizedRequestHandler):
|
||||
async def post(self):
|
||||
file_manager = self.server.lookup_plugin('file_manager')
|
||||
def initialize(self, max_upload_size: int = MAX_BODY_SIZE) -> None:
|
||||
super(FileUploadHandler, self).initialize()
|
||||
self.file_manager: FileManager = self.server.lookup_component(
|
||||
'file_manager')
|
||||
self.max_upload_size = max_upload_size
|
||||
|
||||
def prepare(self) -> None:
|
||||
super(FileUploadHandler, self).prepare()
|
||||
if self.request.method == "POST":
|
||||
assert isinstance(self.request.connection, HTTP1Connection)
|
||||
self.request.connection.set_max_body_size(self.max_upload_size)
|
||||
tmpname = self.file_manager.gen_temp_upload_path()
|
||||
self._targets = {
|
||||
'root': ValueTarget(),
|
||||
'print': ValueTarget(),
|
||||
'path': ValueTarget(),
|
||||
'checksum': ValueTarget(),
|
||||
}
|
||||
self._file = FileTarget(tmpname)
|
||||
self._sha256_target = SHA256Target()
|
||||
self._parser = StreamingFormDataParser(self.request.headers)
|
||||
self._parser.register('file', self._file)
|
||||
self._parser.register('file', self._sha256_target)
|
||||
for name, target in self._targets.items():
|
||||
self._parser.register(name, target)
|
||||
|
||||
async def data_received(self, chunk: bytes) -> None:
|
||||
if self.request.method == "POST":
|
||||
with ThreadPoolExecutor(max_workers=1) as tpe:
|
||||
await IOLoop.current().run_in_executor(
|
||||
tpe, self._parser.data_received, chunk)
|
||||
|
||||
async def post(self) -> None:
|
||||
form_args = {}
|
||||
chk_target = self._targets.pop('checksum')
|
||||
calc_chksum = self._sha256_target.value.lower()
|
||||
if chk_target.value:
|
||||
# Validate checksum
|
||||
recd_cksum = chk_target.value.decode().lower()
|
||||
if calc_chksum != recd_cksum:
|
||||
# remove temporary file
|
||||
try:
|
||||
os.remove(self._file.filename)
|
||||
except Exception:
|
||||
pass
|
||||
raise self.server.error(
|
||||
f"File checksum mismatch: expected {recd_cksum}, "
|
||||
f"calculated {calc_chksum}", 422)
|
||||
for name, target in self._targets.items():
|
||||
if target.value:
|
||||
form_args[name] = target.value.decode()
|
||||
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}"
|
||||
debug_msg += f"\nChecksum: {calc_chksum}"
|
||||
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)
|
||||
|
||||
# Default Handler for unregistered endpoints
|
||||
class AuthorizedErrorHandler(AuthorizedRequestHandler):
|
||||
def prepare(self) -> None:
|
||||
super(AuthorizedRequestHandler, self).prepare()
|
||||
self.set_status(404)
|
||||
raise tornado.web.HTTPError(404)
|
||||
|
||||
class EmulateOctoprintHandler(AuthorizedRequestHandler):
|
||||
def get(self):
|
||||
self.finish({
|
||||
'server': "1.1.1",
|
||||
'api': "0.1",
|
||||
'text': "OctoPrint Upload Emulator"})
|
||||
def check_xsrf_cookie(self) -> None:
|
||||
pass
|
||||
|
||||
def write_error(self, status_code: int, **kwargs) -> None:
|
||||
err = {'code': status_code, 'message': self._reason}
|
||||
if 'exc_info' in kwargs:
|
||||
err['traceback'] = "\n".join(
|
||||
traceback.format_exception(*kwargs['exc_info']))
|
||||
self.finish({'error': err})
|
||||
|
||||
class RedirectHandler(AuthorizedRequestHandler):
|
||||
def get(self, *args, **kwargs) -> None:
|
||||
url: Optional[str] = self.get_argument('url', None)
|
||||
if url is None:
|
||||
try:
|
||||
body_args: Dict[str, Any] = json.loads(self.request.body)
|
||||
except json.JSONDecodeError:
|
||||
body_args = {}
|
||||
if 'url' not in body_args:
|
||||
raise tornado.web.HTTPError(
|
||||
400, "No url argument provided")
|
||||
url = body_args['url']
|
||||
assert url is not None
|
||||
self.redirect(url)
|
||||
@@ -1,284 +0,0 @@
|
||||
# API Key Based Authorization
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
import base64
|
||||
import uuid
|
||||
import os
|
||||
import time
|
||||
import ipaddress
|
||||
import re
|
||||
import logging
|
||||
import tornado
|
||||
from tornado.ioloop import IOLoop, PeriodicCallback
|
||||
from utils import ServerError
|
||||
|
||||
TOKEN_TIMEOUT = 5
|
||||
CONNECTION_TIMEOUT = 3600
|
||||
PRUNE_CHECK_TIME = 300 * 1000
|
||||
|
||||
class Authorization:
|
||||
def __init__(self, config):
|
||||
api_key_file = config.get('api_key_file', "~/.moonraker_api_key")
|
||||
self.api_key_file = os.path.expanduser(api_key_file)
|
||||
self.api_key = self._read_api_key()
|
||||
self.auth_enabled = config.getboolean('enabled', True)
|
||||
self.trusted_connections = {}
|
||||
self.access_tokens = {}
|
||||
|
||||
# Get allowed cors domains
|
||||
cors_cfg = config.get('cors_domains', "").strip()
|
||||
self.cors_domains = [d.strip().replace(".", "\\.").replace("*", ".*")
|
||||
for d in cors_cfg.split('\n')if d.strip()]
|
||||
|
||||
# Get Trusted Clients
|
||||
self.trusted_ips = []
|
||||
self.trusted_ranges = []
|
||||
trusted_clients = config.get('trusted_clients', "")
|
||||
trusted_clients = [c.strip() for c in trusted_clients.split('\n')
|
||||
if c.strip()]
|
||||
for ip in trusted_clients:
|
||||
# Check IP address
|
||||
try:
|
||||
tc = ipaddress.ip_address(ip)
|
||||
except ValueError:
|
||||
tc = None
|
||||
if tc is None:
|
||||
# Check ip network
|
||||
try:
|
||||
tc = ipaddress.ip_network(ip)
|
||||
except ValueError:
|
||||
raise ServerError(
|
||||
f"Invalid option in trusted_clients: {ip}")
|
||||
self.trusted_ranges.append(tc)
|
||||
else:
|
||||
self.trusted_ips.append(tc)
|
||||
|
||||
t_clients = "\n".join(
|
||||
[str(ip) for ip in self.trusted_ips] +
|
||||
[str(rng) for rng in self.trusted_ranges])
|
||||
c_domains = "\n".join(self.cors_domains)
|
||||
|
||||
logging.info(
|
||||
f"Authorization Configuration Loaded\n"
|
||||
f"Auth Enabled: {self.auth_enabled}\n"
|
||||
f"Trusted Clients:\n{t_clients}\n"
|
||||
f"CORS Domains:\n{c_domains}")
|
||||
|
||||
self.prune_handler = PeriodicCallback(
|
||||
self._prune_conn_handler, PRUNE_CHECK_TIME)
|
||||
self.prune_handler.start()
|
||||
|
||||
def register_handlers(self, app):
|
||||
# Register Authorization Endpoints
|
||||
app.register_local_handler(
|
||||
"/access/api_key", ['GET', 'POST'],
|
||||
self._handle_apikey_request, protocol=['http'])
|
||||
app.register_local_handler(
|
||||
"/access/oneshot_token", ['GET'],
|
||||
self._handle_token_request, protocol=['http'])
|
||||
|
||||
async def _handle_apikey_request(self, web_request):
|
||||
action = web_request.get_action()
|
||||
if action.upper() == 'POST':
|
||||
self.api_key = self._create_api_key()
|
||||
return self.api_key
|
||||
|
||||
async def _handle_token_request(self, web_request):
|
||||
return self.get_access_token()
|
||||
|
||||
def _read_api_key(self):
|
||||
if os.path.exists(self.api_key_file):
|
||||
with open(self.api_key_file, 'r') as f:
|
||||
api_key = f.read()
|
||||
return api_key
|
||||
# API Key file doesn't exist. Generate
|
||||
# a new api key and create the file.
|
||||
logging.info(
|
||||
f"No API Key file found, creating new one at:"
|
||||
f"\n{self.api_key_file}")
|
||||
return self._create_api_key()
|
||||
|
||||
def _create_api_key(self):
|
||||
api_key = uuid.uuid4().hex
|
||||
with open(self.api_key_file, 'w') as f:
|
||||
f.write(api_key)
|
||||
return api_key
|
||||
|
||||
def _check_authorized_ip(self, ip):
|
||||
if ip in self.trusted_ips:
|
||||
return True
|
||||
for rng in self.trusted_ranges:
|
||||
if ip in rng:
|
||||
return True
|
||||
return False
|
||||
|
||||
def _prune_conn_handler(self):
|
||||
cur_time = time.time()
|
||||
expired_conns = []
|
||||
for ip, access_time in self.trusted_connections.items():
|
||||
if cur_time - access_time > CONNECTION_TIMEOUT:
|
||||
expired_conns.append(ip)
|
||||
for ip in expired_conns:
|
||||
self.trusted_connections.pop(ip, None)
|
||||
logging.info(
|
||||
f"Trusted Connection Expired, IP: {ip}")
|
||||
|
||||
def _token_expire_handler(self, token):
|
||||
self.access_tokens.pop(token, None)
|
||||
|
||||
def is_enabled(self):
|
||||
return self.auth_enabled
|
||||
|
||||
def get_access_token(self):
|
||||
token = base64.b32encode(os.urandom(20)).decode()
|
||||
ioloop = IOLoop.current()
|
||||
self.access_tokens[token] = ioloop.call_later(
|
||||
TOKEN_TIMEOUT, self._token_expire_handler, token)
|
||||
return token
|
||||
|
||||
def _check_trusted_connection(self, ip):
|
||||
if ip is not None:
|
||||
if ip in self.trusted_connections:
|
||||
self.trusted_connections[ip] = time.time()
|
||||
return True
|
||||
elif self._check_authorized_ip(ip):
|
||||
logging.info(
|
||||
f"Trusted Connection Detected, IP: {ip}")
|
||||
self.trusted_connections[ip] = time.time()
|
||||
return True
|
||||
return False
|
||||
|
||||
def _check_access_token(self, token):
|
||||
if token in self.access_tokens:
|
||||
token_handler = self.access_tokens.pop(token, None)
|
||||
IOLoop.current().remove_timeout(token_handler)
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
def check_authorized(self, request):
|
||||
# Authorization is disabled, request may pass
|
||||
if not self.auth_enabled:
|
||||
return True
|
||||
|
||||
# Check if IP is trusted
|
||||
try:
|
||||
ip = ipaddress.ip_address(request.remote_ip)
|
||||
except ValueError:
|
||||
logging.exception(
|
||||
f"Unable to Create IP Address {request.remote_ip}")
|
||||
ip = None
|
||||
if self._check_trusted_connection(ip):
|
||||
return True
|
||||
|
||||
# Check API Key Header
|
||||
key = request.headers.get("X-Api-Key")
|
||||
if key and key == self.api_key:
|
||||
return True
|
||||
|
||||
# Check one-shot access token
|
||||
token = request.arguments.get('token', [b""])[0].decode()
|
||||
if self._check_access_token(token):
|
||||
return True
|
||||
return False
|
||||
|
||||
def check_cors(self, origin, request=None):
|
||||
if origin is None:
|
||||
return False
|
||||
for regex in self.cors_domains:
|
||||
match = re.match(regex, origin)
|
||||
if match is not None:
|
||||
if match.group() == origin:
|
||||
logging.debug(f"CORS Pattern Matched, origin: {origin} "
|
||||
f" | pattern: {regex}")
|
||||
self._set_cors_headers(origin, request)
|
||||
return True
|
||||
else:
|
||||
logging.debug(f"Partial Cors Match: {match.group()}")
|
||||
else:
|
||||
logging.debug(f"No CORS match for origin: {origin}\n"
|
||||
f"Patterns: {self.cors_domains}")
|
||||
return False
|
||||
|
||||
def _set_cors_headers(self, origin, request):
|
||||
if request is None:
|
||||
return
|
||||
request.set_header("Access-Control-Allow-Origin", origin)
|
||||
request.set_header(
|
||||
"Access-Control-Allow-Methods",
|
||||
"GET, POST, PUT, DELETE, OPTIONS")
|
||||
request.set_header(
|
||||
"Access-Control-Allow-Headers",
|
||||
"Origin, Accept, Content-Type, X-Requested-With, "
|
||||
"X-CRSF-Token")
|
||||
|
||||
def close(self):
|
||||
self.prune_handler.stop()
|
||||
|
||||
class AuthorizedRequestHandler(tornado.web.RequestHandler):
|
||||
def initialize(self):
|
||||
app = self.settings['parent']
|
||||
self.server = app.get_server()
|
||||
self.auth = app.get_auth()
|
||||
self.wsm = app.get_websocket_manager()
|
||||
|
||||
def set_default_headers(self):
|
||||
origin = self.request.headers.get("Origin")
|
||||
# it is necessary to look up the parent app here,
|
||||
# as initialize() may not yet be called
|
||||
auth = self.settings['parent'].get_auth()
|
||||
self.cors_enabled = auth.check_cors(origin, self)
|
||||
|
||||
def prepare(self):
|
||||
if not self.auth.check_authorized(self.request):
|
||||
raise tornado.web.HTTPError(401, "Unauthorized")
|
||||
|
||||
def options(self, *args, **kwargs):
|
||||
# Enable CORS if configured
|
||||
if self.cors_enabled:
|
||||
self.set_status(204)
|
||||
self.finish()
|
||||
else:
|
||||
super(AuthorizedRequestHandler, self).options()
|
||||
|
||||
def get_associated_websocket(self):
|
||||
# Return associated websocket connection if an id
|
||||
# was provided by the request
|
||||
conn = None
|
||||
conn_id = self.get_argument('connection_id', None)
|
||||
if conn_id is not None:
|
||||
try:
|
||||
conn_id = int(conn_id)
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
conn = self.wsm.get_websocket(conn_id)
|
||||
return conn
|
||||
|
||||
# Due to the way Python treats multiple inheritance its best
|
||||
# to create a separate authorized handler for serving files
|
||||
class AuthorizedFileHandler(tornado.web.StaticFileHandler):
|
||||
def initialize(self, path, default_filename=None):
|
||||
super(AuthorizedFileHandler, self).initialize(path, default_filename)
|
||||
app = self.settings['parent']
|
||||
self.server = app.get_server()
|
||||
self.auth = app.get_auth()
|
||||
|
||||
def set_default_headers(self):
|
||||
origin = self.request.headers.get("Origin")
|
||||
auth = self.settings['parent'].get_auth()
|
||||
self.cors_enabled = auth.check_cors(origin, self)
|
||||
|
||||
def prepare(self):
|
||||
if not self.auth.check_authorized(self.request):
|
||||
raise tornado.web.HTTPError(401, "Unauthorized")
|
||||
|
||||
def options(self, *args, **kwargs):
|
||||
# Enable CORS if configured
|
||||
if self.cors_enabled:
|
||||
self.set_status(204)
|
||||
self.finish()
|
||||
else:
|
||||
super(AuthorizedFileHandler, self).options()
|
||||
@@ -1,5 +1,5 @@
|
||||
|
||||
# Package definition for the plugins directory
|
||||
# Package definition for the components directory
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
@@ -0,0 +1,681 @@
|
||||
# API Key Based Authorization
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
|
||||
from __future__ import annotations
|
||||
import base64
|
||||
import uuid
|
||||
import hashlib
|
||||
import secrets
|
||||
import os
|
||||
import time
|
||||
import datetime
|
||||
import ipaddress
|
||||
import re
|
||||
import socket
|
||||
import logging
|
||||
import json
|
||||
from tornado.ioloop import IOLoop, PeriodicCallback
|
||||
from tornado.web import HTTPError
|
||||
from libnacl.sign import Signer, Verifier
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Tuple,
|
||||
Set,
|
||||
Optional,
|
||||
Union,
|
||||
Dict,
|
||||
List,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from confighelper import ConfigHelper
|
||||
from websockets import WebRequest
|
||||
from tornado.httputil import HTTPServerRequest
|
||||
from tornado.web import RequestHandler
|
||||
from . import database
|
||||
DBComp = database.MoonrakerDatabase
|
||||
IPAddr = Union[ipaddress.IPv4Address, ipaddress.IPv6Address]
|
||||
IPNetwork = Union[ipaddress.IPv4Network, ipaddress.IPv6Network]
|
||||
OneshotToken = Tuple[IPAddr, Optional[Dict[str, Any]], object]
|
||||
|
||||
# Helpers for base64url encoding and decoding
|
||||
def base64url_encode(data: bytes) -> bytes:
|
||||
return base64.urlsafe_b64encode(data).rstrip(b"=")
|
||||
|
||||
def base64url_decode(data: str) -> bytes:
|
||||
pad_cnt = len(data) % 4
|
||||
if pad_cnt:
|
||||
data += "=" * (4 - pad_cnt)
|
||||
return base64.urlsafe_b64decode(data)
|
||||
|
||||
|
||||
ONESHOT_TIMEOUT = 5
|
||||
TRUSTED_CONNECTION_TIMEOUT = 3600
|
||||
PRUNE_CHECK_TIME = 300 * 1000
|
||||
|
||||
HASH_ITER = 100000
|
||||
API_USER = "_API_KEY_USER_"
|
||||
TRUSTED_USER = "_TRUSTED_USER_"
|
||||
RESERVED_USERS = [API_USER, TRUSTED_USER]
|
||||
JWT_EXP_TIME = datetime.timedelta(hours=1)
|
||||
JWT_HEADER = {
|
||||
'alg': "EdDSA",
|
||||
'typ': "JWT"
|
||||
}
|
||||
|
||||
class Authorization:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.login_timeout = config.getint('login_timeout', 90)
|
||||
self.force_logins = config.getboolean('force_logins', False)
|
||||
database: DBComp = self.server.lookup_component('database')
|
||||
database.register_local_namespace('authorized_users', forbidden=True)
|
||||
self.users = database.wrap_namespace('authorized_users')
|
||||
api_user: Optional[Dict[str, Any]] = self.users.get(API_USER, None)
|
||||
if api_user is None:
|
||||
self.api_key = uuid.uuid4().hex
|
||||
self.users[API_USER] = {
|
||||
'username': API_USER,
|
||||
'api_key': self.api_key,
|
||||
'created_on': time.time()
|
||||
}
|
||||
else:
|
||||
self.api_key = api_user['api_key']
|
||||
host_name, port = self.server.get_host_info()
|
||||
self.issuer = f"http://{host_name}:{port}"
|
||||
self.public_jwks: Dict[str, Dict[str, Any]] = {}
|
||||
for username, user_info in list(self.users.items()):
|
||||
if username == API_USER:
|
||||
continue
|
||||
if 'jwt_secret' in user_info:
|
||||
try:
|
||||
priv_key = self._load_private_key(user_info['jwt_secret'])
|
||||
jwk_id = user_info['jwk_id']
|
||||
except (self.server.error, KeyError):
|
||||
logging.info("Invalid key found for user, removing")
|
||||
user_info.pop('jwt_secret', None)
|
||||
user_info.pop('jwk_id', None)
|
||||
self.users[username] = user_info
|
||||
continue
|
||||
self.public_jwks[jwk_id] = self._generate_public_jwk(priv_key)
|
||||
|
||||
self.trusted_users: Dict[IPAddr, Any] = {}
|
||||
self.oneshot_tokens: Dict[str, OneshotToken] = {}
|
||||
self.permitted_paths: Set[str] = set()
|
||||
|
||||
# Get allowed cors domains
|
||||
self.cors_domains: List[str] = []
|
||||
cors_cfg = config.get('cors_domains', "").strip()
|
||||
cds = [d.strip() for d in cors_cfg.split('\n') if d.strip()]
|
||||
for domain in cds:
|
||||
bad_match = re.search(r"^.+\.[^:]*\*", domain)
|
||||
if bad_match is not None:
|
||||
raise config.error(
|
||||
f"Unsafe CORS Domain '{domain}'. Wildcards are not"
|
||||
" permitted in the top level domain.")
|
||||
self.cors_domains.append(
|
||||
domain.replace(".", "\\.").replace("*", ".*"))
|
||||
|
||||
# Get Trusted Clients
|
||||
self.trusted_ips: List[IPAddr] = []
|
||||
self.trusted_ranges: List[IPNetwork] = []
|
||||
self.trusted_domains: List[str] = []
|
||||
tcs = config.get('trusted_clients', "")
|
||||
trusted_clients = [c.strip() for c in tcs.split('\n') if c.strip()]
|
||||
for val in trusted_clients:
|
||||
# Check IP address
|
||||
try:
|
||||
tc = ipaddress.ip_address(val)
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
self.trusted_ips.append(tc)
|
||||
continue
|
||||
# Check ip network
|
||||
try:
|
||||
tc = ipaddress.ip_network(val)
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
self.trusted_ranges.append(tc)
|
||||
continue
|
||||
# Check hostname
|
||||
self.trusted_domains.append(val.lower())
|
||||
|
||||
t_clients = "\n".join(
|
||||
[str(ip) for ip in self.trusted_ips] +
|
||||
[str(rng) for rng in self.trusted_ranges] +
|
||||
self.trusted_domains)
|
||||
c_domains = "\n".join(self.cors_domains)
|
||||
|
||||
logging.info(
|
||||
f"Authorization Configuration Loaded\n"
|
||||
f"Trusted Clients:\n{t_clients}\n"
|
||||
f"CORS Domains:\n{c_domains}")
|
||||
|
||||
self.prune_handler = PeriodicCallback(
|
||||
self._prune_conn_handler, PRUNE_CHECK_TIME)
|
||||
self.prune_handler.start()
|
||||
|
||||
# Register Authorization Endpoints
|
||||
self.permitted_paths.add("/server/redirect")
|
||||
self.permitted_paths.add("/access/login")
|
||||
self.permitted_paths.add("/access/refresh_jwt")
|
||||
self.server.register_endpoint(
|
||||
"/access/login", ['POST'], self._handle_login,
|
||||
transports=['http'])
|
||||
self.server.register_endpoint(
|
||||
"/access/logout", ['POST'], self._handle_logout,
|
||||
transports=['http'])
|
||||
self.server.register_endpoint(
|
||||
"/access/refresh_jwt", ['POST'], self._handle_refresh_jwt,
|
||||
transports=['http'])
|
||||
self.server.register_endpoint(
|
||||
"/access/user", ['GET', 'POST', 'DELETE'],
|
||||
self._handle_user_request, transports=['http'])
|
||||
self.server.register_endpoint(
|
||||
"/access/users/list", ['GET'], self._handle_list_request,
|
||||
transports=['http'])
|
||||
self.server.register_endpoint(
|
||||
"/access/user/password", ['POST'], self._handle_password_reset,
|
||||
transports=['http'])
|
||||
self.server.register_endpoint(
|
||||
"/access/api_key", ['GET', 'POST'],
|
||||
self._handle_apikey_request, transports=['http'])
|
||||
self.server.register_endpoint(
|
||||
"/access/oneshot_token", ['GET'],
|
||||
self._handle_oneshot_request, transports=['http'])
|
||||
self.server.register_notification("authorization:user_created")
|
||||
self.server.register_notification("authorization:user_deleted")
|
||||
|
||||
async def _handle_apikey_request(self, web_request: WebRequest) -> str:
|
||||
action = web_request.get_action()
|
||||
if action.upper() == 'POST':
|
||||
self.api_key = uuid.uuid4().hex
|
||||
self.users[f'{API_USER}.api_key'] = self.api_key
|
||||
return self.api_key
|
||||
|
||||
async def _handle_oneshot_request(self, web_request: WebRequest) -> str:
|
||||
ip = web_request.get_ip_address()
|
||||
assert ip is not None
|
||||
user_info = web_request.get_current_user()
|
||||
return self.get_oneshot_token(ip, user_info)
|
||||
|
||||
async def _handle_login(self, web_request: WebRequest) -> Dict[str, Any]:
|
||||
return self._login_jwt_user(web_request)
|
||||
|
||||
async def _handle_logout(self, web_request: WebRequest) -> Dict[str, str]:
|
||||
user_info = web_request.get_current_user()
|
||||
if user_info is None:
|
||||
raise self.server.error("No user logged in")
|
||||
username: str = user_info['username']
|
||||
if username in RESERVED_USERS:
|
||||
raise self.server.error(
|
||||
f"Invalid log out request for user {username}")
|
||||
self.users.pop(f"{username}.jwt_secret", None)
|
||||
jwk_id: str = self.users.pop(f"{username}.jwk_id", "")
|
||||
self.public_jwks.pop(jwk_id, None)
|
||||
return {
|
||||
"username": username,
|
||||
"action": "user_logged_out"
|
||||
}
|
||||
|
||||
async def _handle_refresh_jwt(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, str]:
|
||||
refresh_token: str = web_request.get_str('refresh_token')
|
||||
try:
|
||||
user_info = self._decode_jwt(refresh_token, token_type="refresh")
|
||||
except Exception:
|
||||
raise self.server.error("Invalid Refresh Token", 401)
|
||||
username: str = user_info['username']
|
||||
if 'jwt_secret' not in user_info or "jwk_id" not in user_info:
|
||||
raise self.server.error("User not logged in", 401)
|
||||
private_key = self._load_private_key(user_info['jwt_secret'])
|
||||
jwk_id: str = user_info['jwk_id']
|
||||
token = self._generate_jwt(username, jwk_id, private_key)
|
||||
return {
|
||||
'username': username,
|
||||
'token': token,
|
||||
'action': 'user_jwt_refresh'
|
||||
}
|
||||
|
||||
async def _handle_user_request(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
action = web_request.get_action()
|
||||
if action == "GET":
|
||||
user = web_request.get_current_user()
|
||||
if user is None:
|
||||
return {
|
||||
'username': None,
|
||||
'created_on': None,
|
||||
}
|
||||
else:
|
||||
return {
|
||||
'username': user['username'],
|
||||
'created_on': user.get('created_on')
|
||||
}
|
||||
elif action == "POST":
|
||||
# Create User
|
||||
return self._login_jwt_user(web_request, create=True)
|
||||
elif action == "DELETE":
|
||||
# Delete User
|
||||
return self._delete_jwt_user(web_request)
|
||||
raise self.server.error("Invalid Request Method")
|
||||
|
||||
async def _handle_list_request(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, List[Dict[str, Any]]]:
|
||||
user_list = []
|
||||
for user in self.users.values():
|
||||
if user['username'] == API_USER:
|
||||
continue
|
||||
user_list.append({
|
||||
'username': user['username'],
|
||||
'created_on': user['created_on']
|
||||
})
|
||||
return {
|
||||
'users': user_list
|
||||
}
|
||||
|
||||
async def _handle_password_reset(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, str]:
|
||||
password: str = web_request.get_str('password')
|
||||
new_pass: str = web_request.get_str('new_password')
|
||||
user_info = web_request.get_current_user()
|
||||
if user_info is None:
|
||||
raise self.server.error("No Current User")
|
||||
username = user_info['username']
|
||||
if username in RESERVED_USERS:
|
||||
raise self.server.error(
|
||||
f"Invalid Reset Request for user {username}")
|
||||
salt = bytes.fromhex(user_info['salt'])
|
||||
hashed_pass = hashlib.pbkdf2_hmac(
|
||||
'sha256', password.encode(), salt, HASH_ITER).hex()
|
||||
if hashed_pass != user_info['password']:
|
||||
raise self.server.error("Invalid Password")
|
||||
new_hashed_pass = hashlib.pbkdf2_hmac(
|
||||
'sha256', new_pass.encode(), salt, HASH_ITER).hex()
|
||||
self.users[f'{username}.password'] = new_hashed_pass
|
||||
return {
|
||||
'username': username,
|
||||
'action': "user_password_reset"
|
||||
}
|
||||
|
||||
def _login_jwt_user(self,
|
||||
web_request: WebRequest,
|
||||
create: bool = False
|
||||
) -> Dict[str, Any]:
|
||||
username: str = web_request.get_str('username')
|
||||
password: str = web_request.get_str('password')
|
||||
user_info: Dict[str, Any]
|
||||
if username in RESERVED_USERS:
|
||||
raise self.server.error(
|
||||
f"Invalid Request for user {username}")
|
||||
if create:
|
||||
if username in self.users:
|
||||
raise self.server.error(f"User {username} already exists")
|
||||
salt = secrets.token_bytes(32)
|
||||
hashed_pass = hashlib.pbkdf2_hmac(
|
||||
'sha256', password.encode(), salt, HASH_ITER).hex()
|
||||
user_info = {
|
||||
'username': username,
|
||||
'password': hashed_pass,
|
||||
'salt': salt.hex(),
|
||||
'created_on': time.time()
|
||||
}
|
||||
self.users[username] = user_info
|
||||
action = "user_created"
|
||||
else:
|
||||
if username not in self.users:
|
||||
raise self.server.error(f"Unregistered User: {username}")
|
||||
user_info = self.users[username]
|
||||
salt = bytes.fromhex(user_info['salt'])
|
||||
hashed_pass = hashlib.pbkdf2_hmac(
|
||||
'sha256', password.encode(), salt, HASH_ITER).hex()
|
||||
action = "user_logged_in"
|
||||
if hashed_pass != user_info['password']:
|
||||
raise self.server.error("Invalid Password")
|
||||
jwt_secret_hex: Optional[str] = user_info.get('jwt_secret', None)
|
||||
if jwt_secret_hex is None:
|
||||
private_key = Signer()
|
||||
jwk_id = base64url_encode(secrets.token_bytes()).decode()
|
||||
user_info['jwt_secret'] = private_key.hex_seed().decode()
|
||||
user_info['jwk_id'] = jwk_id
|
||||
self.users[username] = user_info
|
||||
self.public_jwks[jwk_id] = self._generate_public_jwk(private_key)
|
||||
else:
|
||||
private_key = self._load_private_key(jwt_secret_hex)
|
||||
jwk_id = user_info['jwk_id']
|
||||
token = self._generate_jwt(username, jwk_id, private_key)
|
||||
refresh_token = self._generate_jwt(
|
||||
username, jwk_id, private_key, token_type="refresh",
|
||||
exp_time=datetime.timedelta(days=self.login_timeout))
|
||||
if create:
|
||||
IOLoop.current().call_later(
|
||||
.005, self.server.send_event,
|
||||
"authorization:user_created",
|
||||
{'username': username})
|
||||
return {
|
||||
'username': username,
|
||||
'token': token,
|
||||
'refresh_token': refresh_token,
|
||||
'action': action
|
||||
}
|
||||
|
||||
def _delete_jwt_user(self, web_request: WebRequest) -> Dict[str, str]:
|
||||
username: str = web_request.get_str('username')
|
||||
current_user = web_request.get_current_user()
|
||||
if current_user is not None:
|
||||
curname = current_user.get('username', None)
|
||||
if curname is not None and curname == username:
|
||||
raise self.server.error(
|
||||
f"Cannot delete logged in user {curname}")
|
||||
if username in RESERVED_USERS:
|
||||
raise self.server.error(
|
||||
f"Invalid Request for reserved user {username}")
|
||||
user_info: Optional[Dict[str, Any]] = self.users.get(username)
|
||||
if user_info is None:
|
||||
raise self.server.error(f"No registered user: {username}")
|
||||
self.public_jwks.pop(self.users.get(f"{username}.jwk_id"), None)
|
||||
del self.users[username]
|
||||
IOLoop.current().call_later(
|
||||
.005, self.server.send_event,
|
||||
"authorization:user_deleted",
|
||||
{'username': username})
|
||||
return {
|
||||
"username": username,
|
||||
"action": "user_deleted"
|
||||
}
|
||||
|
||||
def _generate_jwt(self,
|
||||
username: str,
|
||||
jwk_id: str,
|
||||
private_key: Signer,
|
||||
token_type: str = "access",
|
||||
exp_time: datetime.timedelta = JWT_EXP_TIME
|
||||
) -> str:
|
||||
curtime = int(time.time())
|
||||
payload = {
|
||||
'iss': self.issuer,
|
||||
'aud': "Moonraker",
|
||||
'iat': curtime,
|
||||
'exp': curtime + int(exp_time.total_seconds()),
|
||||
'username': username,
|
||||
'token_type': token_type
|
||||
}
|
||||
header = {'kid': jwk_id}
|
||||
header.update(JWT_HEADER)
|
||||
jwt_header = base64url_encode(json.dumps(header).encode())
|
||||
jwt_payload = base64url_encode(json.dumps(payload).encode())
|
||||
jwt_msg = b".".join([jwt_header, jwt_payload])
|
||||
sig = private_key.signature(jwt_msg)
|
||||
jwt_sig = base64url_encode(sig)
|
||||
return b".".join([jwt_msg, jwt_sig]).decode()
|
||||
|
||||
def _decode_jwt(self,
|
||||
token: str,
|
||||
token_type: str = "access"
|
||||
) -> Dict[str, Any]:
|
||||
message, sig = token.rsplit('.', maxsplit=1)
|
||||
enc_header, enc_payload = message.split('.')
|
||||
header: Dict[str, Any] = json.loads(base64url_decode(enc_header))
|
||||
sig_bytes = base64url_decode(sig)
|
||||
|
||||
# verify header
|
||||
if header.get('typ') != "JWT" or header.get('alg') != "EdDSA":
|
||||
raise self.server.error("Invalid JWT header")
|
||||
jwk_id = header.get('kid')
|
||||
if jwk_id not in self.public_jwks:
|
||||
raise self.server.error("Invalid key ID")
|
||||
|
||||
# validate signature
|
||||
public_key = self._public_key_from_jwk(self.public_jwks[jwk_id])
|
||||
public_key.verify(sig_bytes + message.encode())
|
||||
|
||||
# validate claims
|
||||
payload: Dict[str, Any] = json.loads(base64url_decode(enc_payload))
|
||||
if payload['token_type'] != token_type:
|
||||
raise self.server.error(
|
||||
f"JWT Token type mismatch: Expected {token_type}, "
|
||||
f"Recd: {payload['token_type']}", 401)
|
||||
if payload['iss'] != self.issuer:
|
||||
raise self.server.error("Invalid JWT Issuer", 401)
|
||||
if payload['aud'] != "Moonraker":
|
||||
raise self.server.error("Invalid JWT Audience", 401)
|
||||
if payload['exp'] < int(time.time()):
|
||||
raise self.server.error("JWT Expired", 401)
|
||||
|
||||
# get user
|
||||
user_info: Optional[Dict[str, Any]] = self.users.get(
|
||||
payload.get('username', ""), None)
|
||||
if user_info is None:
|
||||
raise self.server.error("Unknown user", 401)
|
||||
return user_info
|
||||
|
||||
def _load_private_key(self, secret: str) -> Signer:
|
||||
try:
|
||||
key = Signer(bytes.fromhex(secret))
|
||||
except Exception:
|
||||
raise self.server.error(
|
||||
"Error decoding private key, user data may"
|
||||
" be corrupt", 500) from None
|
||||
return key
|
||||
|
||||
def _generate_public_jwk(self, private_key: Signer) -> Dict[str, Any]:
|
||||
public_key = private_key.vk
|
||||
return {
|
||||
'x': base64url_encode(public_key).decode(),
|
||||
'kty': "OKP",
|
||||
'crv': "Ed25519",
|
||||
'use': "sig"
|
||||
}
|
||||
|
||||
def _public_key_from_jwk(self, jwk: Dict[str, Any]) -> Verifier:
|
||||
if jwk.get('kty') != "OKP":
|
||||
raise self.server.error("Not an Octet Key Pair")
|
||||
if jwk.get('crv') != "Ed25519":
|
||||
raise self.server.error("Invalid Curve")
|
||||
if 'x' not in jwk:
|
||||
raise self.server.error("No 'x' argument in jwk")
|
||||
key = base64url_decode(jwk['x'])
|
||||
return Verifier(key.hex().encode())
|
||||
|
||||
def _prune_conn_handler(self) -> None:
|
||||
cur_time = time.time()
|
||||
for ip, user_info in list(self.trusted_users.items()):
|
||||
exp_time: float = user_info['expires_at']
|
||||
if cur_time >= exp_time:
|
||||
self.trusted_users.pop(ip, None)
|
||||
logging.info(
|
||||
f"Trusted Connection Expired, IP: {ip}")
|
||||
|
||||
def _oneshot_token_expire_handler(self, token):
|
||||
self.oneshot_tokens.pop(token, None)
|
||||
|
||||
def get_oneshot_token(self,
|
||||
ip_addr: IPAddr,
|
||||
user: Optional[Dict[str, Any]]
|
||||
) -> str:
|
||||
token = base64.b32encode(os.urandom(20)).decode()
|
||||
ioloop = IOLoop.current()
|
||||
hdl = ioloop.call_later(
|
||||
ONESHOT_TIMEOUT, self._oneshot_token_expire_handler, token)
|
||||
self.oneshot_tokens[token] = (ip_addr, user, hdl)
|
||||
return token
|
||||
|
||||
def _check_json_web_token(self,
|
||||
request: HTTPServerRequest
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
auth_token: Optional[str] = request.headers.get("Authorization")
|
||||
if auth_token is None:
|
||||
auth_token = request.headers.get("X-Access-Token")
|
||||
if auth_token and auth_token.startswith("Bearer "):
|
||||
auth_token = auth_token[7:]
|
||||
else:
|
||||
qtoken = request.query_arguments.get('access_token', None)
|
||||
if qtoken is not None:
|
||||
auth_token = qtoken[-1].decode()
|
||||
if auth_token:
|
||||
try:
|
||||
return self._decode_jwt(auth_token)
|
||||
except Exception as e:
|
||||
raise HTTPError(401, str(e))
|
||||
return None
|
||||
|
||||
def _check_authorized_ip(self, ip: IPAddr) -> bool:
|
||||
if ip in self.trusted_ips:
|
||||
return True
|
||||
for rng in self.trusted_ranges:
|
||||
if ip in rng:
|
||||
return True
|
||||
fqdn = socket.getfqdn(str(ip)).lower()
|
||||
if fqdn in self.trusted_domains:
|
||||
return True
|
||||
return False
|
||||
|
||||
def _check_trusted_connection(self,
|
||||
ip: Optional[IPAddr]
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
if ip is not None:
|
||||
curtime = time.time()
|
||||
exp_time = curtime + TRUSTED_CONNECTION_TIMEOUT
|
||||
if ip in self.trusted_users:
|
||||
self.trusted_users[ip]['expires_at'] = exp_time
|
||||
return self.trusted_users[ip]
|
||||
elif self._check_authorized_ip(ip):
|
||||
logging.info(
|
||||
f"Trusted Connection Detected, IP: {ip}")
|
||||
self.trusted_users[ip] = {
|
||||
'username': TRUSTED_USER,
|
||||
'password': None,
|
||||
'created_on': curtime,
|
||||
'expires_at': exp_time
|
||||
}
|
||||
return self.trusted_users[ip]
|
||||
return None
|
||||
|
||||
def _check_oneshot_token(self,
|
||||
token: str,
|
||||
cur_ip: IPAddr
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
if token in self.oneshot_tokens:
|
||||
ip_addr, user, hdl = self.oneshot_tokens.pop(token)
|
||||
IOLoop.current().remove_timeout(hdl)
|
||||
if cur_ip != ip_addr:
|
||||
logging.info(f"Oneshot Token IP Mismatch: expected{ip_addr}"
|
||||
f", Recd: {cur_ip}")
|
||||
return None
|
||||
return user
|
||||
else:
|
||||
return None
|
||||
|
||||
def check_authorized(self,
|
||||
request: HTTPServerRequest
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
if request.path in self.permitted_paths or \
|
||||
request.method == "OPTIONS":
|
||||
return None
|
||||
|
||||
# Check JSON Web Token
|
||||
jwt_user = self._check_json_web_token(request)
|
||||
if jwt_user is not None:
|
||||
return jwt_user
|
||||
|
||||
try:
|
||||
ip = ipaddress.ip_address(request.remote_ip)
|
||||
except ValueError:
|
||||
logging.exception(
|
||||
f"Unable to Create IP Address {request.remote_ip}")
|
||||
ip = None
|
||||
|
||||
# Check oneshot access token
|
||||
ost: Optional[List[bytes]] = request.arguments.get('token', None)
|
||||
if ost is not None:
|
||||
ost_user = self._check_oneshot_token(ost[-1].decode(), ip)
|
||||
if ost_user is not None:
|
||||
return ost_user
|
||||
|
||||
# Check API Key Header
|
||||
key: Optional[str] = request.headers.get("X-Api-Key")
|
||||
if key and key == self.api_key:
|
||||
return self.users[API_USER]
|
||||
|
||||
# If the force_logins option is enabled and at least one
|
||||
# user is created this is an unauthorized request
|
||||
if self.force_logins and len(self.users) > 1:
|
||||
raise HTTPError(401, "Unauthorized")
|
||||
|
||||
# Check if IP is trusted
|
||||
trusted_user = self._check_trusted_connection(ip)
|
||||
if trusted_user is not None:
|
||||
return trusted_user
|
||||
|
||||
raise HTTPError(401, "Unauthorized")
|
||||
|
||||
def check_cors(self,
|
||||
origin: Optional[str],
|
||||
req_hdlr: Optional[RequestHandler] = None
|
||||
) -> bool:
|
||||
if origin is None or not self.cors_domains:
|
||||
return False
|
||||
for regex in self.cors_domains:
|
||||
match = re.match(regex, origin)
|
||||
if match is not None:
|
||||
if match.group() == origin:
|
||||
logging.debug(f"CORS Pattern Matched, origin: {origin} "
|
||||
f" | pattern: {regex}")
|
||||
self._set_cors_headers(origin, req_hdlr)
|
||||
return True
|
||||
else:
|
||||
logging.debug(f"Partial Cors Match: {match.group()}")
|
||||
else:
|
||||
# Check to see if the origin contains an IP that matches a
|
||||
# current trusted connection
|
||||
match = re.search(r"^https?://([^/:]+)", origin)
|
||||
if match is not None:
|
||||
ip = match.group(1)
|
||||
try:
|
||||
ipaddr = ipaddress.ip_address(ip)
|
||||
except ValueError:
|
||||
pass
|
||||
else:
|
||||
if self._check_authorized_ip(ipaddr):
|
||||
logging.debug(
|
||||
f"Cors request matched trusted IP: {ip}")
|
||||
self._set_cors_headers(origin, req_hdlr)
|
||||
return True
|
||||
logging.debug(f"No CORS match for origin: {origin}\n"
|
||||
f"Patterns: {self.cors_domains}")
|
||||
return False
|
||||
|
||||
def _set_cors_headers(self,
|
||||
origin: str,
|
||||
req_hdlr: Optional[RequestHandler]
|
||||
) -> None:
|
||||
if req_hdlr is None:
|
||||
return
|
||||
req_hdlr.set_header("Access-Control-Allow-Origin", origin)
|
||||
if req_hdlr.request.method == "OPTIONS":
|
||||
req_hdlr.set_header(
|
||||
"Access-Control-Allow-Methods",
|
||||
"GET, POST, PUT, DELETE, OPTIONS")
|
||||
req_hdlr.set_header(
|
||||
"Access-Control-Allow-Headers",
|
||||
"Origin, Accept, Content-Type, X-Requested-With, "
|
||||
"X-CRSF-Token, Authorization, X-Access-Token, "
|
||||
"X-Api-Key")
|
||||
|
||||
def close(self) -> None:
|
||||
self.prune_handler.stop()
|
||||
|
||||
|
||||
def load_component(config: ConfigHelper) -> Authorization:
|
||||
return Authorization(config)
|
||||
@@ -0,0 +1,167 @@
|
||||
# Klipper data logging and storage storage
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
import logging
|
||||
import time
|
||||
from collections import deque
|
||||
from tornado.ioloop import PeriodicCallback
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Optional,
|
||||
Dict,
|
||||
List,
|
||||
Tuple,
|
||||
Deque,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from confighelper import ConfigHelper
|
||||
from websockets import WebRequest
|
||||
from . import klippy_apis
|
||||
APIComp = klippy_apis.KlippyAPI
|
||||
GCQueue = Deque[Dict[str, Any]]
|
||||
TempStore = Dict[str, Dict[str, Deque[float]]]
|
||||
|
||||
TEMPERATURE_UPDATE_MS = 1000
|
||||
|
||||
class DataStore:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.temp_store_size = config.getint('temperature_store_size', 1200)
|
||||
self.gcode_store_size = config.getint('gcode_store_size', 1000)
|
||||
|
||||
# Temperature Store Tracking
|
||||
self.last_temps: Dict[str, Tuple[float, ...]] = {}
|
||||
self.gcode_queue: GCQueue = deque(maxlen=self.gcode_store_size)
|
||||
self.temperature_store: TempStore = {}
|
||||
self.temp_update_cb = PeriodicCallback(
|
||||
self._update_temperature_store, TEMPERATURE_UPDATE_MS)
|
||||
|
||||
# Register status update event
|
||||
self.server.register_event_handler(
|
||||
"server:status_update", self._set_current_temps)
|
||||
self.server.register_event_handler(
|
||||
"server:gcode_response", self._update_gcode_store)
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_ready", self._init_sensors)
|
||||
|
||||
# Register endpoints
|
||||
self.server.register_endpoint(
|
||||
"/server/temperature_store", ['GET'],
|
||||
self._handle_temp_store_request)
|
||||
self.server.register_endpoint(
|
||||
"/server/gcode_store", ['GET'],
|
||||
self._handle_gcode_store_request)
|
||||
|
||||
async def _init_sensors(self) -> None:
|
||||
klippy_apis: APIComp = self.server.lookup_component('klippy_apis')
|
||||
# Fetch sensors
|
||||
try:
|
||||
result: Dict[str, Any]
|
||||
result = await klippy_apis.query_objects({'heaters': None})
|
||||
except self.server.error as e:
|
||||
logging.info(f"Error Configuring Sensors: {e}")
|
||||
return
|
||||
sensors: List[str]
|
||||
sensors = result.get("heaters", {}).get("available_sensors", [])
|
||||
|
||||
if sensors:
|
||||
# Add Subscription
|
||||
sub: Dict[str, Optional[List[str]]] = {s: None for s in sensors}
|
||||
try:
|
||||
status: Dict[str, Any]
|
||||
status = await klippy_apis.subscribe_objects(sub)
|
||||
except self.server.error as e:
|
||||
logging.info(f"Error subscribing to sensors: {e}")
|
||||
return
|
||||
logging.info(f"Configuring available sensors: {sensors}")
|
||||
new_store: TempStore = {}
|
||||
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=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., 0., 0.)
|
||||
self.temperature_store = new_store
|
||||
# Prune unconfigured sensors in self.last_temps
|
||||
for sensor in list(self.last_temps.keys()):
|
||||
if sensor not in self.temperature_store:
|
||||
del self.last_temps[sensor]
|
||||
# Update initial temperatures
|
||||
self._set_current_temps(status)
|
||||
self.temp_update_cb.start()
|
||||
else:
|
||||
logging.info("No sensors found")
|
||||
self.last_temps = {}
|
||||
self.temperature_store = {}
|
||||
self.temp_update_cb.stop()
|
||||
|
||||
def _set_current_temps(self, data: Dict[str, Any]) -> None:
|
||||
for sensor in self.temperature_store:
|
||||
if sensor in data:
|
||||
last_val = self.last_temps[sensor]
|
||||
self.last_temps[sensor] = (
|
||||
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) -> None:
|
||||
# XXX - If klippy is not connected, set values to zero
|
||||
# as they are unknown?
|
||||
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: WebRequest
|
||||
) -> Dict[str, Dict[str, List[float]]]:
|
||||
store = {}
|
||||
for name, sensor in self.temperature_store.items():
|
||||
store[name] = {k: list(v) for k, v in sensor.items()}
|
||||
return store
|
||||
|
||||
async def close(self) -> None:
|
||||
self.temp_update_cb.stop()
|
||||
|
||||
def _update_gcode_store(self, response: str) -> None:
|
||||
curtime = time.time()
|
||||
self.gcode_queue.append(
|
||||
{'message': response, 'time': curtime, 'type': "response"})
|
||||
|
||||
def store_gcode_command(self, script: str) -> None:
|
||||
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: WebRequest
|
||||
) -> Dict[str, List[Dict[str, Any]]]:
|
||||
count = web_request.get_int("count", None)
|
||||
if count is not None:
|
||||
gc_responses = list(self.gcode_queue)[-count:]
|
||||
else:
|
||||
gc_responses = list(self.gcode_queue)
|
||||
return {'gcode_store': gc_responses}
|
||||
|
||||
def load_component(config: ConfigHelper) -> DataStore:
|
||||
return DataStore(config)
|
||||
@@ -0,0 +1,518 @@
|
||||
# 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.
|
||||
|
||||
from __future__ import annotations
|
||||
import os
|
||||
import json
|
||||
import struct
|
||||
import operator
|
||||
import logging
|
||||
from io import BytesIO
|
||||
from functools import reduce
|
||||
import lmdb
|
||||
from utils import SentinelClass
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
ItemsView,
|
||||
ValuesView,
|
||||
Tuple,
|
||||
Optional,
|
||||
Union,
|
||||
Dict,
|
||||
List,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from confighelper import ConfigHelper
|
||||
from websockets import WebRequest
|
||||
DBRecord = Union[int, float, bool, str, List[Any], Dict[str, Any]]
|
||||
DBType = Optional[DBRecord]
|
||||
|
||||
DATABASE_VERSION = 1
|
||||
MAX_NAMESPACES = 50
|
||||
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)),
|
||||
}
|
||||
|
||||
SENTINEL = SentinelClass.get_instance()
|
||||
|
||||
def getitem_with_default(item: Dict, field: Any) -> Any:
|
||||
if field not in item:
|
||||
item[field] = {}
|
||||
return item[field]
|
||||
|
||||
|
||||
class MoonrakerDatabase:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.namespaces: Dict[str, object] = {}
|
||||
self.enable_debug = config.getboolean("enable_database_debug", False)
|
||||
self.database_path = os.path.expanduser(config.get(
|
||||
'database_path', "~/.moonraker_database"))
|
||||
if not os.path.isdir(self.database_path):
|
||||
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)
|
||||
# Read out all namespaces to remove any invalid keys on init
|
||||
for ns in self.namespaces.keys():
|
||||
self._get_namespace(ns)
|
||||
# Protected Namespaces have read-only API access. Write access can
|
||||
# be granted by enabling the debug option. Forbidden namespaces
|
||||
# have no API access. This cannot be overridden.
|
||||
self.protected_namespaces = set(self.get_item(
|
||||
"moonraker", "database.protected_namespaces", ["moonraker"]))
|
||||
self.forbidden_namespaces = set(self.get_item(
|
||||
"moonraker", "database.forbidden_namespaces", []))
|
||||
debug_counter: int = self.get_item(
|
||||
"moonraker", "database.debug_counter", 0)
|
||||
if self.enable_debug:
|
||||
debug_counter += 1
|
||||
self.insert_item("moonraker", "database.debug_counter",
|
||||
debug_counter)
|
||||
if debug_counter:
|
||||
logging.info(f"Database Debug Count: {debug_counter}")
|
||||
|
||||
# Track unsafe shutdowns
|
||||
unsafe_shutdowns: int = self.get_item(
|
||||
"moonraker", "database.unsafe_shutdowns", 0)
|
||||
logging.info(f"Unsafe Shutdown Count: {unsafe_shutdowns}")
|
||||
# Increment unsafe shutdown counter. This will be reset if
|
||||
# moonraker is safely restarted
|
||||
self.insert_item("moonraker", "database.unsafe_shutdowns",
|
||||
unsafe_shutdowns + 1)
|
||||
self.server.register_endpoint(
|
||||
"/server/database/list", ['GET'], self._handle_list_request)
|
||||
self.server.register_endpoint(
|
||||
"/server/database/item", ["GET", "POST", "DELETE"],
|
||||
self._handle_item_request)
|
||||
|
||||
def insert_item(self,
|
||||
namespace: str,
|
||||
key: Union[List[str], str],
|
||||
value: DBType
|
||||
) -> None:
|
||||
key_list = self._process_key(key)
|
||||
if namespace not in self.namespaces:
|
||||
self.namespaces[namespace] = self.lmdb_env.open_db(
|
||||
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: Dict[str, Any] = reduce(getitem_with_default, key_list[1:-1],
|
||||
record)
|
||||
item[key_list[-1]] = value
|
||||
if not self._insert_record(namespace, key_list[0], record):
|
||||
logging.info(
|
||||
f"Error inserting key '{key}' in namespace '{namespace}'")
|
||||
|
||||
def update_item(self,
|
||||
namespace: str,
|
||||
key: Union[List[str], str],
|
||||
value: DBType
|
||||
) -> None:
|
||||
key_list = self._process_key(key)
|
||||
record = self._get_record(namespace, key_list[0])
|
||||
if len(key_list) == 1:
|
||||
if isinstance(record, dict) and isinstance(value, dict):
|
||||
record.update(value)
|
||||
else:
|
||||
assert value is not None
|
||||
record = value
|
||||
else:
|
||||
try:
|
||||
assert isinstance(record, dict)
|
||||
item: Dict[str, Any] = reduce(
|
||||
operator.getitem, key_list[1:-1], record)
|
||||
except Exception:
|
||||
raise self.server.error(
|
||||
f"Key '{key}' in namespace '{namespace}' not found", 404)
|
||||
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: str,
|
||||
key: Union[List[str], str],
|
||||
drop_empty_db: bool = False
|
||||
) -> Any:
|
||||
key_list = self._process_key(key)
|
||||
val = record = self._get_record(namespace, key_list[0])
|
||||
remove_record = True
|
||||
if len(key_list) > 1:
|
||||
try:
|
||||
assert isinstance(record, dict)
|
||||
item: Dict[str, Any] = reduce(
|
||||
operator.getitem, key_list[1:-1], record)
|
||||
val = item.pop(key_list[-1])
|
||||
except Exception:
|
||||
raise self.server.error(
|
||||
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: str,
|
||||
key: Optional[Union[List[str], str]] = None,
|
||||
default: Any = SENTINEL
|
||||
) -> Any:
|
||||
try:
|
||||
if key is None:
|
||||
return self._get_namespace(namespace)
|
||||
key_list = self._process_key(key)
|
||||
ns = self._get_record(namespace, key_list[0])
|
||||
val = reduce(operator.getitem, key_list[1:], ns) # type: ignore
|
||||
except Exception:
|
||||
if not isinstance(default, SentinelClass):
|
||||
return default
|
||||
raise self.server.error(
|
||||
f"Key '{key}' in namespace '{namespace}' not found", 404)
|
||||
return val
|
||||
|
||||
def ns_length(self, namespace: str) -> int:
|
||||
return len(self.ns_keys(namespace))
|
||||
|
||||
def ns_keys(self, namespace: str) -> List[str]:
|
||||
keys: List[str] = []
|
||||
db = self.namespaces[namespace]
|
||||
with self.lmdb_env.begin(db=db) as txn:
|
||||
cursor = txn.cursor()
|
||||
remaining = cursor.first()
|
||||
while remaining:
|
||||
keys.append(cursor.key().decode())
|
||||
remaining = cursor.next()
|
||||
return keys
|
||||
|
||||
def ns_values(self, namespace: str) -> ValuesView:
|
||||
ns = self._get_namespace(namespace)
|
||||
return ns.values()
|
||||
|
||||
def ns_items(self, namespace: str) -> ItemsView:
|
||||
ns = self._get_namespace(namespace)
|
||||
return ns.items()
|
||||
|
||||
def ns_contains(self, namespace: str, key: Union[List[str], str]) -> bool:
|
||||
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: str,
|
||||
forbidden: bool = False
|
||||
) -> None:
|
||||
if namespace not in self.namespaces:
|
||||
self.namespaces[namespace] = self.lmdb_env.open_db(
|
||||
namespace.encode())
|
||||
if forbidden:
|
||||
if namespace not in self.forbidden_namespaces:
|
||||
self.forbidden_namespaces.add(namespace)
|
||||
self.insert_item(
|
||||
"moonraker", "database.forbidden_namespaces",
|
||||
list(self.forbidden_namespaces))
|
||||
elif namespace not in self.protected_namespaces:
|
||||
self.protected_namespaces.add(namespace)
|
||||
self.insert_item("moonraker", "database.protected_namespaces",
|
||||
list(self.protected_namespaces))
|
||||
|
||||
def wrap_namespace(self,
|
||||
namespace: str,
|
||||
parse_keys: bool = True
|
||||
) -> NamespaceWrapper:
|
||||
if namespace not in self.namespaces:
|
||||
raise self.server.error(
|
||||
f"Namespace '{namespace}' not found", 404)
|
||||
return NamespaceWrapper(namespace, self, parse_keys)
|
||||
|
||||
def _process_key(self, key: Union[List[str], str]) -> List[str]:
|
||||
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: str, key: str, val: DBType) -> bool:
|
||||
db = self.namespaces[namespace]
|
||||
if val is None:
|
||||
return False
|
||||
with self.lmdb_env.begin(write=True, buffers=True, db=db) as txn:
|
||||
ret = txn.put(key.encode(), self._encode_value(val))
|
||||
return ret
|
||||
|
||||
def _get_record(self,
|
||||
namespace: str,
|
||||
key: str,
|
||||
force: bool = False
|
||||
) -> DBRecord:
|
||||
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: str) -> Dict[str, Any]:
|
||||
if namespace not in self.namespaces:
|
||||
raise self.server.error(
|
||||
f"Invalid database namespace '{namespace}'")
|
||||
db = self.namespaces[namespace]
|
||||
result = {}
|
||||
invalid_key_result = None
|
||||
with self.lmdb_env.begin(buffers=True, db=db) as txn:
|
||||
cursor = txn.cursor()
|
||||
cursor.first()
|
||||
for db_key, value in cursor:
|
||||
k = bytes(db_key).decode()
|
||||
if not k:
|
||||
invalid_key_result = self._decode_value(value)
|
||||
continue
|
||||
result[k] = self._decode_value(value)
|
||||
if invalid_key_result:
|
||||
logging.info(f"Invalid Key found in namespace '{namespace}', "
|
||||
f"dropping value: {repr(invalid_key_result)}")
|
||||
with self.lmdb_env.begin(write=True, buffers=True, db=db) as txn:
|
||||
txn.delete(b"")
|
||||
return result
|
||||
|
||||
def _encode_value(self, value: DBRecord) -> bytes:
|
||||
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: bytes) -> DBRecord:
|
||||
fmt = bvalue[0]
|
||||
try:
|
||||
decode_func = RECORD_DECODE_FUNCS[fmt]
|
||||
return decode_func(bvalue)
|
||||
except Exception:
|
||||
raise self.server.error(
|
||||
f"Error decoding value {bvalue.decode()}, format: {chr(fmt)}")
|
||||
|
||||
async def _handle_list_request(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, List[str]]:
|
||||
ns_list = set(self.namespaces.keys()) - self.forbidden_namespaces
|
||||
return {'namespaces': list(ns_list)}
|
||||
|
||||
async def _handle_item_request(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
action = web_request.get_action()
|
||||
namespace = web_request.get_str("namespace")
|
||||
if namespace in self.forbidden_namespaces:
|
||||
raise self.server.error(
|
||||
f"Read/Write access to namespace '{namespace}'"
|
||||
" is forbidden", 403)
|
||||
key: Any
|
||||
valid_types: Tuple[type, ...]
|
||||
if action != "GET":
|
||||
if namespace in self.protected_namespaces and \
|
||||
not self.enable_debug:
|
||||
raise self.server.error(
|
||||
f"Write access to namespaces '{namespace}'"
|
||||
" is forbidden", 403)
|
||||
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 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) -> None:
|
||||
# Decrement unsafe shutdown counter
|
||||
unsafe_shutdowns: int = self.get_item(
|
||||
"moonraker", "database.unsafe_shutdowns", 0)
|
||||
self.insert_item("moonraker", "database.unsafe_shutdowns",
|
||||
unsafe_shutdowns - 1)
|
||||
|
||||
# log db stats
|
||||
msg = ""
|
||||
with self.lmdb_env.begin() as txn:
|
||||
for db_name, db in self.namespaces.items():
|
||||
stats = txn.stat(db)
|
||||
msg += f"\n{db_name}:\n"
|
||||
msg += "\n".join([f"{k}: {v}" for k, v in stats.items()])
|
||||
logging.info(f"Database statistics:\n{msg}")
|
||||
self.lmdb_env.sync()
|
||||
self.lmdb_env.close()
|
||||
|
||||
class NamespaceWrapper:
|
||||
def __init__(self,
|
||||
namespace: str,
|
||||
database: MoonrakerDatabase,
|
||||
parse_keys: bool
|
||||
) -> None:
|
||||
self.namespace = namespace
|
||||
self.db = database
|
||||
# If parse keys is true, keys of a string type
|
||||
# will be passed straight to the DB methods.
|
||||
self.parse_keys = parse_keys
|
||||
|
||||
def insert(self, key: Union[List[str], str], value: DBType) -> None:
|
||||
if isinstance(key, str) and not self.parse_keys:
|
||||
key = [key]
|
||||
self.db.insert_item(self.namespace, key, value)
|
||||
|
||||
def update_child(self, key: Union[List[str], str], value: DBType) -> None:
|
||||
if isinstance(key, str) and not self.parse_keys:
|
||||
key = [key]
|
||||
self.db.update_item(self.namespace, key, value)
|
||||
|
||||
def update(self, value: Dict[str, Any]) -> None:
|
||||
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: Union[List[str], str],
|
||||
default: Any = None
|
||||
) -> Any:
|
||||
if isinstance(key, str) and not self.parse_keys:
|
||||
key = [key]
|
||||
return self.db.get_item(self.namespace, key, default)
|
||||
|
||||
def delete(self, key: Union[List[str], str]) -> Any:
|
||||
if isinstance(key, str) and not self.parse_keys:
|
||||
key = [key]
|
||||
return self.db.delete_item(self.namespace, key)
|
||||
|
||||
def __len__(self) -> int:
|
||||
return self.db.ns_length(self.namespace)
|
||||
|
||||
def __getitem__(self, key: Union[List[str], str]) -> Any:
|
||||
return self.get(key, default=SENTINEL)
|
||||
|
||||
def __setitem__(self,
|
||||
key: Union[List[str], str],
|
||||
value: DBType
|
||||
) -> None:
|
||||
self.insert(key, value)
|
||||
|
||||
def __delitem__(self, key: Union[List[str], str]):
|
||||
self.delete(key)
|
||||
|
||||
def __contains__(self, key: Union[List[str], str]) -> bool:
|
||||
if isinstance(key, str) and not self.parse_keys:
|
||||
key = [key]
|
||||
return self.db.ns_contains(self.namespace, key)
|
||||
|
||||
def keys(self) -> List[str]:
|
||||
return self.db.ns_keys(self.namespace)
|
||||
|
||||
def values(self) -> ValuesView:
|
||||
return self.db.ns_values(self.namespace)
|
||||
|
||||
def items(self) -> ItemsView:
|
||||
return self.db.ns_items(self.namespace)
|
||||
|
||||
def pop(self,
|
||||
key: Union[List[str], str],
|
||||
default: Any = SENTINEL
|
||||
) -> Any:
|
||||
try:
|
||||
val = self.delete(key)
|
||||
except Exception:
|
||||
if isinstance(default, SentinelClass):
|
||||
raise
|
||||
val = default
|
||||
return val
|
||||
|
||||
def clear(self) -> None:
|
||||
keys = self.keys()
|
||||
for k in keys:
|
||||
try:
|
||||
self.delete([k])
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def load_component(config: ConfigHelper) -> MoonrakerDatabase:
|
||||
return MoonrakerDatabase(config)
|
||||
@@ -0,0 +1,15 @@
|
||||
# Package definition for the file_manager
|
||||
#
|
||||
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
from . import file_manager as fm
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
if TYPE_CHECKING:
|
||||
from confighelper import ConfigHelper
|
||||
|
||||
def load_component(config: ConfigHelper) -> fm.FileManager:
|
||||
return fm.load_component(config)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,9 +1,11 @@
|
||||
#!/usr/bin/env python3
|
||||
# GCode metadata extraction utility
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import argparse
|
||||
import re
|
||||
@@ -11,11 +13,35 @@ import os
|
||||
import sys
|
||||
import base64
|
||||
import traceback
|
||||
import io
|
||||
import tempfile
|
||||
import zipfile
|
||||
import shutil
|
||||
from PIL import Image
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Optional,
|
||||
Dict,
|
||||
List,
|
||||
Type,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
pass
|
||||
|
||||
UFP_MODEL_PATH = "/3D/model.gcode"
|
||||
UFP_THUMB_PATH = "/Metadata/thumbnail.png"
|
||||
|
||||
def log_to_stderr(msg: str) -> None:
|
||||
sys.stderr.write(f"{msg}\n")
|
||||
sys.stderr.flush()
|
||||
|
||||
# regex helpers
|
||||
def _regex_find_floats(pattern, data, strict=False):
|
||||
def _regex_find_floats(pattern: str,
|
||||
data: str,
|
||||
strict: bool = False
|
||||
) -> List[float]:
|
||||
# If strict is enabled, pattern requires a floating point
|
||||
# value, otherwise it can be an integer value
|
||||
fptrn = r'\d+\.\d*' if strict else r'\d+\.?\d*'
|
||||
@@ -24,118 +50,133 @@ def _regex_find_floats(pattern, data, strict=False):
|
||||
# return the maximum height value found
|
||||
try:
|
||||
return [float(h) for h in re.findall(
|
||||
fptrn, " ".join(matches))]
|
||||
fptrn, " ".join(matches))]
|
||||
except Exception:
|
||||
pass
|
||||
return []
|
||||
|
||||
def _regex_find_ints(pattern, data):
|
||||
def _regex_find_ints(pattern: str, data: str) -> List[int]:
|
||||
matches = re.findall(pattern, data)
|
||||
if matches:
|
||||
# return the maximum height value found
|
||||
try:
|
||||
return [int(h) for h in re.findall(
|
||||
r'\d+', " ".join(matches))]
|
||||
r'\d+', " ".join(matches))]
|
||||
except Exception:
|
||||
pass
|
||||
return []
|
||||
|
||||
def _regex_find_first(pattern, data, cast=float):
|
||||
def _regex_find_first(pattern: str, data: str) -> Optional[float]:
|
||||
match = re.search(pattern, data)
|
||||
val = None
|
||||
val: Optional[float] = None
|
||||
if match:
|
||||
try:
|
||||
val = cast(match.group(1))
|
||||
val = float(match.group(1))
|
||||
except Exception:
|
||||
return None
|
||||
return val
|
||||
|
||||
# Slicer parsing implementations
|
||||
class BaseSlicer(object):
|
||||
def __init__(self, file_path):
|
||||
def __init__(self, file_path: str) -> None:
|
||||
self.path = file_path
|
||||
self.header_data = self.footer_data = self.log = None
|
||||
self.header_data: str = ""
|
||||
self.footer_data: str = ""
|
||||
self.layer_height: Optional[float] = None
|
||||
|
||||
def set_data(self, header_data, footer_data, fsize, log):
|
||||
def set_data(self,
|
||||
header_data: str,
|
||||
footer_data: str,
|
||||
fsize: int) -> None:
|
||||
self.header_data = header_data
|
||||
self.footer_data = footer_data
|
||||
self.size = fsize
|
||||
self.log = log
|
||||
self.size: int = fsize
|
||||
|
||||
def _parse_min_float(self, pattern, data, strict=False):
|
||||
def _parse_min_float(self,
|
||||
pattern: str,
|
||||
data: str,
|
||||
strict: bool = False
|
||||
) -> Optional[float]:
|
||||
result = _regex_find_floats(pattern, data, strict)
|
||||
if result:
|
||||
return min(result)
|
||||
else:
|
||||
return None
|
||||
|
||||
def _parse_max_float(self, pattern, data, strict=False):
|
||||
def _parse_max_float(self,
|
||||
pattern: str,
|
||||
data: str,
|
||||
strict: bool = False
|
||||
) -> Optional[float]:
|
||||
result = _regex_find_floats(pattern, data, strict)
|
||||
if result:
|
||||
return max(result)
|
||||
else:
|
||||
return None
|
||||
|
||||
def check_identity(self, data):
|
||||
def check_identity(self, data: str) -> Optional[Dict[str, str]]:
|
||||
return None
|
||||
|
||||
def parse_gcode_start_byte(self):
|
||||
def parse_gcode_start_byte(self) -> Optional[int]:
|
||||
m = re.search(r"\n[MG]\d+\s.*\n", self.header_data)
|
||||
if m is None:
|
||||
return None
|
||||
return m.start()
|
||||
|
||||
def parse_gcode_end_byte(self):
|
||||
def parse_gcode_end_byte(self) -> Optional[int]:
|
||||
rev_data = self.footer_data[::-1]
|
||||
m = re.search(r"\n.*\s\d+[MG]\n", rev_data)
|
||||
if m is None:
|
||||
return None
|
||||
return self.size - m.start()
|
||||
|
||||
def parse_first_layer_height(self):
|
||||
def parse_first_layer_height(self) -> Optional[float]:
|
||||
return None
|
||||
|
||||
def parse_layer_height(self):
|
||||
def parse_layer_height(self) -> Optional[float]:
|
||||
return None
|
||||
|
||||
def parse_object_height(self):
|
||||
def parse_object_height(self) -> Optional[float]:
|
||||
return None
|
||||
|
||||
def parse_filament_total(self):
|
||||
def parse_filament_total(self) -> Optional[float]:
|
||||
return None
|
||||
|
||||
def parse_estimated_time(self):
|
||||
def parse_filament_weight_total(self) -> Optional[float]:
|
||||
return None
|
||||
|
||||
def parse_first_layer_bed_temp(self):
|
||||
def parse_estimated_time(self) -> Optional[float]:
|
||||
return None
|
||||
|
||||
def parse_first_layer_extr_temp(self):
|
||||
def parse_first_layer_bed_temp(self) -> Optional[float]:
|
||||
return None
|
||||
|
||||
def parse_thumbnails(self):
|
||||
def parse_first_layer_extr_temp(self) -> Optional[float]:
|
||||
return None
|
||||
|
||||
def parse_thumbnails(self) -> Optional[List[Dict[str, Any]]]:
|
||||
return None
|
||||
|
||||
class UnknownSlicer(BaseSlicer):
|
||||
def check_identity(self, data):
|
||||
def check_identity(self, data: str) -> Optional[Dict[str, str]]:
|
||||
return {'slicer': "Unknown"}
|
||||
|
||||
def parse_first_layer_height(self):
|
||||
def parse_first_layer_height(self) -> Optional[float]:
|
||||
return self._parse_min_float(r"G1\sZ\d+\.\d*", self.header_data)
|
||||
|
||||
def parse_object_height(self):
|
||||
def parse_object_height(self) -> Optional[float]:
|
||||
return self._parse_max_float(r"G1\sZ\d+\.\d*", self.footer_data)
|
||||
|
||||
def parse_first_layer_extr_temp(self):
|
||||
def parse_first_layer_extr_temp(self) -> Optional[float]:
|
||||
return _regex_find_first(
|
||||
r"M109 S(\d+\.?\d*)", self.header_data)
|
||||
|
||||
def parse_first_layer_bed_temp(self):
|
||||
def parse_first_layer_bed_temp(self) -> Optional[float]:
|
||||
return _regex_find_first(
|
||||
r"M190 S(\d+\.?\d*)", self.header_data)
|
||||
|
||||
class PrusaSlicer(BaseSlicer):
|
||||
def check_identity(self, data):
|
||||
def check_identity(self, data: str) -> Optional[Dict[str, str]]:
|
||||
match = re.search(r"PrusaSlicer\s(.*)\son", data)
|
||||
if match:
|
||||
return {
|
||||
@@ -144,15 +185,25 @@ class PrusaSlicer(BaseSlicer):
|
||||
}
|
||||
return None
|
||||
|
||||
def parse_first_layer_height(self):
|
||||
def parse_first_layer_height(self) -> Optional[float]:
|
||||
# Check percentage
|
||||
pct = _regex_find_first(
|
||||
r"; first_layer_height = (\d+)%", self.footer_data)
|
||||
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(
|
||||
def parse_layer_height(self) -> Optional[float]:
|
||||
self.layer_height = _regex_find_first(
|
||||
r"; layer_height = (\d+\.?\d*)", self.footer_data)
|
||||
return self.layer_height
|
||||
|
||||
def parse_object_height(self):
|
||||
def parse_object_height(self) -> Optional[float]:
|
||||
matches = re.findall(
|
||||
r";BEFORE_LAYER_CHANGE\n(?:.*\n)?;(\d+\.?\d*)", self.footer_data)
|
||||
if matches:
|
||||
@@ -164,63 +215,81 @@ class PrusaSlicer(BaseSlicer):
|
||||
return max(matches)
|
||||
return self._parse_max_float(r"G1\sZ\d+\.\d*\sF", self.footer_data)
|
||||
|
||||
def parse_filament_total(self):
|
||||
def parse_filament_total(self) -> Optional[float]:
|
||||
return _regex_find_first(
|
||||
r"filament\sused\s\[mm\]\s=\s(\d+\.\d*)", self.footer_data)
|
||||
|
||||
def parse_estimated_time(self):
|
||||
def parse_filament_weight_total(self) -> Optional[float]:
|
||||
return _regex_find_first(
|
||||
r"total\sfilament\sused\s\[g\]\s=\s(\d+\.\d*)", self.footer_data)
|
||||
|
||||
def parse_estimated_time(self) -> Optional[float]:
|
||||
time_match = re.search(
|
||||
r';\sestimated\sprinting\stime.*', self.footer_data)
|
||||
if not time_match:
|
||||
return None
|
||||
total_time = 0
|
||||
time_match = time_match.group()
|
||||
time_group = time_match.group()
|
||||
time_patterns = [(r"(\d+)d", 24*60*60), (r"(\d+)h", 60*60),
|
||||
(r"(\d+)m", 60), (r"(\d+)s", 1)]
|
||||
try:
|
||||
for pattern, multiplier in time_patterns:
|
||||
t = re.search(pattern, time_match)
|
||||
t = re.search(pattern, time_group)
|
||||
if t:
|
||||
total_time += int(t.group(1)) * multiplier
|
||||
except Exception:
|
||||
return None
|
||||
return round(total_time, 2)
|
||||
|
||||
def parse_thumbnails(self):
|
||||
thumb_matches = re.findall(
|
||||
def parse_thumbnails(self) -> Optional[List[Dict[str, Any]]]:
|
||||
thumb_matches: List[str] = re.findall(
|
||||
r"; thumbnail begin[;/\+=\w\s]+?; thumbnail end", self.header_data)
|
||||
if not thumb_matches:
|
||||
return None
|
||||
parsed_matches = []
|
||||
thumb_dir = os.path.join(os.path.dirname(self.path), ".thumbs")
|
||||
if not os.path.exists(thumb_dir):
|
||||
try:
|
||||
os.mkdir(thumb_dir)
|
||||
except Exception:
|
||||
log_to_stderr(f"Unable to create thumb dir: {thumb_dir}")
|
||||
return None
|
||||
thumb_base = os.path.splitext(os.path.basename(self.path))[0]
|
||||
parsed_matches: List[Dict[str, Any]] = []
|
||||
for match in thumb_matches:
|
||||
lines = re.split(r"\r?\n", match.replace('; ', ''))
|
||||
info = _regex_find_ints(r".*", lines[0])
|
||||
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
|
||||
thumb_name = f"{thumb_base}-{info[0]}x{info[1]}.png"
|
||||
thumb_path = os.path.join(thumb_dir, thumb_name)
|
||||
rel_thumb_path = os.path.join(".thumbs", thumb_name)
|
||||
with open(thumb_path, "wb") as f:
|
||||
f.write(base64.b64decode(data.encode()))
|
||||
parsed_matches.append({
|
||||
'width': info[0], 'height': info[1],
|
||||
'size': info[2], 'data': data})
|
||||
'size': os.path.getsize(thumb_path),
|
||||
'relative_path': rel_thumb_path})
|
||||
return parsed_matches
|
||||
|
||||
def parse_first_layer_extr_temp(self):
|
||||
def parse_first_layer_extr_temp(self) -> Optional[float]:
|
||||
return _regex_find_first(
|
||||
r"; first_layer_temperature = (\d+\.?\d*)", self.footer_data)
|
||||
|
||||
def parse_first_layer_bed_temp(self):
|
||||
def parse_first_layer_bed_temp(self) -> Optional[float]:
|
||||
return _regex_find_first(
|
||||
r"; first_layer_bed_temperature = (\d+\.?\d*)", self.footer_data)
|
||||
|
||||
class Slic3rPE(PrusaSlicer):
|
||||
def check_identity(self, data):
|
||||
def check_identity(self, data: str) -> Optional[Dict[str, str]]:
|
||||
match = re.search(r"Slic3r\sPrusa\sEdition\s(.*)\son", data)
|
||||
if match:
|
||||
return {
|
||||
@@ -229,15 +298,15 @@ class Slic3rPE(PrusaSlicer):
|
||||
}
|
||||
return None
|
||||
|
||||
def parse_filament_total(self):
|
||||
def parse_filament_total(self) -> Optional[float]:
|
||||
return _regex_find_first(
|
||||
r"filament\sused\s=\s(\d+\.\d+)mm", self.footer_data)
|
||||
|
||||
def parse_thumbnails(self):
|
||||
def parse_thumbnails(self) -> Optional[List[Dict[str, Any]]]:
|
||||
return None
|
||||
|
||||
class Slic3r(Slic3rPE):
|
||||
def check_identity(self, data):
|
||||
def check_identity(self, data: str) -> Optional[Dict[str, str]]:
|
||||
match = re.search(r"Slic3r\s(\d.*)\son", data)
|
||||
if match:
|
||||
return {
|
||||
@@ -246,11 +315,22 @@ class Slic3r(Slic3rPE):
|
||||
}
|
||||
return None
|
||||
|
||||
def parse_estimated_time(self):
|
||||
def parse_filament_total(self) -> Optional[float]:
|
||||
filament = _regex_find_first(
|
||||
r";\sfilament\_length\_m\s=\s(\d+\.\d*)", self.footer_data)
|
||||
if filament is not None:
|
||||
filament *= 1000
|
||||
return filament
|
||||
|
||||
def parse_filament_weight_total(self) -> Optional[float]:
|
||||
return _regex_find_first(
|
||||
r";\sfilament\smass\_g\s=\s(\d+\.\d*)", self.footer_data)
|
||||
|
||||
def parse_estimated_time(self) -> Optional[float]:
|
||||
return None
|
||||
|
||||
class SuperSlicer(PrusaSlicer):
|
||||
def check_identity(self, data):
|
||||
def check_identity(self, data: str) -> Optional[Dict[str, str]]:
|
||||
match = re.search(r"SuperSlicer\s(.*)\son", data)
|
||||
if match:
|
||||
return {
|
||||
@@ -259,8 +339,8 @@ class SuperSlicer(PrusaSlicer):
|
||||
}
|
||||
return None
|
||||
|
||||
class Cura(BaseSlicer):
|
||||
def check_identity(self, data):
|
||||
class Cura(PrusaSlicer):
|
||||
def check_identity(self, data: str) -> Optional[Dict[str, str]]:
|
||||
match = re.search(r"Cura_SteamEngine\s(.*)", data)
|
||||
if match:
|
||||
return {
|
||||
@@ -269,70 +349,77 @@ class Cura(BaseSlicer):
|
||||
}
|
||||
return None
|
||||
|
||||
def parse_first_layer_height(self):
|
||||
def parse_first_layer_height(self) -> Optional[float]:
|
||||
return _regex_find_first(r";MINZ:(\d+\.?\d*)", self.header_data)
|
||||
|
||||
def parse_layer_height(self):
|
||||
return _regex_find_first(
|
||||
def parse_layer_height(self) -> Optional[float]:
|
||||
self.layer_height = _regex_find_first(
|
||||
r";Layer\sheight:\s(\d+\.?\d*)", self.header_data)
|
||||
return self.layer_height
|
||||
|
||||
def parse_object_height(self):
|
||||
def parse_object_height(self) -> Optional[float]:
|
||||
return _regex_find_first(r";MAXZ:(\d+\.?\d*)", self.header_data)
|
||||
|
||||
def parse_filament_total(self):
|
||||
def parse_filament_total(self) -> Optional[float]:
|
||||
filament = _regex_find_first(
|
||||
r";Filament\sused:\s(\d+\.?\d*)m", self.header_data)
|
||||
if filament is not None:
|
||||
filament *= 1000
|
||||
return filament
|
||||
|
||||
def parse_estimated_time(self):
|
||||
def parse_filament_weight_total(self) -> Optional[float]:
|
||||
return _regex_find_first(
|
||||
r";Filament\sweight\s=\s.(\d+\.\d+).", self.header_data)
|
||||
|
||||
def parse_estimated_time(self) -> Optional[float]:
|
||||
return self._parse_max_float(r";TIME:.*", self.header_data)
|
||||
|
||||
def parse_first_layer_extr_temp(self):
|
||||
def parse_first_layer_extr_temp(self) -> Optional[float]:
|
||||
return _regex_find_first(
|
||||
r"M109 S(\d+\.?\d*)", self.header_data)
|
||||
|
||||
def parse_first_layer_bed_temp(self):
|
||||
def parse_first_layer_bed_temp(self) -> Optional[float]:
|
||||
return _regex_find_first(
|
||||
r"M190 S(\d+\.?\d*)", self.header_data)
|
||||
|
||||
def parse_thumbnails(self):
|
||||
thumbName = os.path.splitext(
|
||||
os.path.basename(self.path))[0] + ".png"
|
||||
thumbPath = os.path.join(
|
||||
os.path.dirname(self.path), "thumbs", thumbName)
|
||||
if not os.path.isfile(thumbPath):
|
||||
def parse_thumbnails(self) -> Optional[List[Dict[str, Any]]]:
|
||||
# Attempt to parse thumbnails from file metadata
|
||||
thumbs = super().parse_thumbnails()
|
||||
if thumbs is not None:
|
||||
return thumbs
|
||||
# Check for thumbnails extracted from the ufp
|
||||
thumb_dir = os.path.join(os.path.dirname(self.path), ".thumbs")
|
||||
thumb_base = os.path.splitext(os.path.basename(self.path))[0]
|
||||
thumb_path = os.path.join(thumb_dir, f"{thumb_base}.png")
|
||||
rel_path_full = os.path.join(".thumbs", f"{thumb_base}.png")
|
||||
rel_path_small = os.path.join(".thumbs", f"{thumb_base}-32x32.png")
|
||||
thumb_path_small = os.path.join(thumb_dir, f"{thumb_base}-32x32.png")
|
||||
if not os.path.isfile(thumb_path):
|
||||
return None
|
||||
# read file
|
||||
thumbs = []
|
||||
try:
|
||||
with open(thumbPath, 'rb') as thumbFile:
|
||||
fbytes = thumbFile.read()
|
||||
with Image.open(io.BytesIO(fbytes)) as im:
|
||||
thumbFull = base64.b64encode(fbytes).decode()
|
||||
thumbs.append({
|
||||
'width': im.width, 'height': im.height,
|
||||
'size': len(thumbFull), 'data': thumbFull
|
||||
})
|
||||
# Create 32x32 thumbnail
|
||||
im.thumbnail((32, 32), Image.ANTIALIAS)
|
||||
tmpThumb = io.BytesIO()
|
||||
im.save(tmpThumb, format="PNG")
|
||||
thumbSmall = base64.b64encode(
|
||||
tmpThumb.getbuffer()).decode()
|
||||
tmpThumb.close()
|
||||
thumbs.insert(0, {
|
||||
'width': im.width, 'height': im.height,
|
||||
'size': len(thumbSmall), 'data': thumbSmall
|
||||
})
|
||||
with Image.open(thumb_path) as im:
|
||||
thumbs.append({
|
||||
'width': im.width, 'height': im.height,
|
||||
'size': os.path.getsize(thumb_path),
|
||||
'relative_path': rel_path_full
|
||||
})
|
||||
# Create 32x32 thumbnail
|
||||
im.thumbnail((32, 32), Image.ANTIALIAS)
|
||||
im.save(thumb_path_small, format="PNG")
|
||||
thumbs.insert(0, {
|
||||
'width': im.width, 'height': im.height,
|
||||
'size': os.path.getsize(thumb_path_small),
|
||||
'relative_path': rel_path_small
|
||||
})
|
||||
except Exception as e:
|
||||
self.log.append(str(e))
|
||||
log_to_stderr(str(e))
|
||||
return None
|
||||
return thumbs
|
||||
|
||||
class Simplify3D(BaseSlicer):
|
||||
def check_identity(self, data):
|
||||
def check_identity(self, data: str) -> Optional[Dict[str, str]]:
|
||||
match = re.search(r"Simplify3D\(R\)\sVersion\s(.*)", data)
|
||||
if match:
|
||||
return {
|
||||
@@ -341,45 +428,50 @@ class Simplify3D(BaseSlicer):
|
||||
}
|
||||
return None
|
||||
|
||||
def parse_first_layer_height(self):
|
||||
def parse_first_layer_height(self) -> Optional[float]:
|
||||
return self._parse_min_float(r"G1\sZ\d+\.\d*", self.header_data)
|
||||
|
||||
def parse_layer_height(self):
|
||||
return _regex_find_first(
|
||||
def parse_layer_height(self) -> Optional[float]:
|
||||
self.layer_height = _regex_find_first(
|
||||
r";\s+layerHeight,(\d+\.?\d*)", self.header_data)
|
||||
return self.layer_height
|
||||
|
||||
def parse_object_height(self):
|
||||
def parse_object_height(self) -> Optional[float]:
|
||||
return self._parse_max_float(r"G1\sZ\d+\.\d*", self.footer_data)
|
||||
|
||||
def parse_filament_total(self):
|
||||
def parse_filament_total(self) -> Optional[float]:
|
||||
return _regex_find_first(
|
||||
r";\s+Filament\slength:\s(\d+\.?\d*)\smm", self.footer_data)
|
||||
|
||||
def parse_estimated_time(self):
|
||||
def parse_filament_weight_total(self) -> Optional[float]:
|
||||
return _regex_find_first(
|
||||
r";\s+Plastic\sweight:\s(\d+\.?\d*)\sg", self.footer_data)
|
||||
|
||||
def parse_estimated_time(self) -> Optional[float]:
|
||||
time_match = re.search(
|
||||
r';\s+Build time:.*', self.footer_data)
|
||||
if not time_match:
|
||||
return None
|
||||
total_time = 0
|
||||
time_match = time_match.group()
|
||||
time_group = time_match.group()
|
||||
time_patterns = [(r"(\d+)\shours", 60*60), (r"(\d+)\smin", 60),
|
||||
(r"(\d+)\ssec", 1)]
|
||||
try:
|
||||
for pattern, multiplier in time_patterns:
|
||||
t = re.search(pattern, time_match)
|
||||
t = re.search(pattern, time_group)
|
||||
if t:
|
||||
total_time += int(t.group(1)) * multiplier
|
||||
except Exception:
|
||||
return None
|
||||
return round(total_time, 2)
|
||||
|
||||
def _get_temp_items(self, pattern):
|
||||
def _get_temp_items(self, pattern: str) -> List[str]:
|
||||
match = re.search(pattern, self.header_data)
|
||||
if match is None:
|
||||
return []
|
||||
return match.group().split(",")[1:]
|
||||
|
||||
def _get_first_layer_temp(self, heater):
|
||||
def _get_first_layer_temp(self, heater: str) -> Optional[float]:
|
||||
heaters = self._get_temp_items(r"temperatureName.*")
|
||||
temps = self._get_temp_items(r"temperatureSetpointTemperatures.*")
|
||||
for h, temp in zip(heaters, temps):
|
||||
@@ -390,14 +482,14 @@ class Simplify3D(BaseSlicer):
|
||||
return None
|
||||
return None
|
||||
|
||||
def parse_first_layer_extr_temp(self):
|
||||
def parse_first_layer_extr_temp(self) -> Optional[float]:
|
||||
return self._get_first_layer_temp("Extruder 1")
|
||||
|
||||
def parse_first_layer_bed_temp(self):
|
||||
def parse_first_layer_bed_temp(self) -> Optional[float]:
|
||||
return self._get_first_layer_temp("Heated Bed")
|
||||
|
||||
class KISSlicer(BaseSlicer):
|
||||
def check_identity(self, data):
|
||||
def check_identity(self, data: str) -> Optional[Dict[str, Any]]:
|
||||
match = re.search(r";\sKISSlicer", data)
|
||||
if match:
|
||||
ident = {'slicer': "KISSlicer"}
|
||||
@@ -408,26 +500,27 @@ class KISSlicer(BaseSlicer):
|
||||
return ident
|
||||
return None
|
||||
|
||||
def parse_first_layer_height(self):
|
||||
def parse_first_layer_height(self) -> Optional[float]:
|
||||
return _regex_find_first(
|
||||
r";\s+first_layer_thickness_mm\s=\s(\d+\.?\d*)", self.header_data)
|
||||
|
||||
def parse_layer_height(self):
|
||||
return _regex_find_first(
|
||||
def parse_layer_height(self) -> Optional[float]:
|
||||
self.layer_height = _regex_find_first(
|
||||
r";\s+max_layer_thickness_mm\s=\s(\d+\.?\d*)", self.header_data)
|
||||
return self.layer_height
|
||||
|
||||
def parse_object_height(self):
|
||||
def parse_object_height(self) -> Optional[float]:
|
||||
return self._parse_max_float(
|
||||
r";\sEND_LAYER_OBJECT\sz.*", self.footer_data)
|
||||
|
||||
def parse_filament_total(self):
|
||||
def parse_filament_total(self) -> Optional[float]:
|
||||
filament = _regex_find_floats(
|
||||
r";\s+Ext\s.*mm", self.footer_data, strict=True)
|
||||
if filament:
|
||||
return sum(filament)
|
||||
return None
|
||||
|
||||
def parse_estimated_time(self):
|
||||
def parse_estimated_time(self) -> Optional[float]:
|
||||
time = _regex_find_first(
|
||||
r";\sCalculated.*Build\sTime:\s(\d+\.?\d*)\sminutes",
|
||||
self.footer_data)
|
||||
@@ -436,17 +529,17 @@ class KISSlicer(BaseSlicer):
|
||||
return round(time, 2)
|
||||
return None
|
||||
|
||||
def parse_first_layer_extr_temp(self):
|
||||
def parse_first_layer_extr_temp(self) -> Optional[float]:
|
||||
return _regex_find_first(
|
||||
r"; first_layer_C = (\d+\.?\d*)", self.header_data)
|
||||
|
||||
def parse_first_layer_bed_temp(self):
|
||||
def parse_first_layer_bed_temp(self) -> Optional[float]:
|
||||
return _regex_find_first(
|
||||
r"; bed_C = (\d+\.?\d*)", self.header_data)
|
||||
|
||||
|
||||
class IdeaMaker(BaseSlicer):
|
||||
def check_identity(self, data):
|
||||
def check_identity(self, data: str) -> Optional[Dict[str, str]]:
|
||||
match = re.search(r"\sideaMaker\s(.*),", data)
|
||||
if match:
|
||||
return {
|
||||
@@ -455,90 +548,108 @@ class IdeaMaker(BaseSlicer):
|
||||
}
|
||||
return None
|
||||
|
||||
def parse_first_layer_height(self):
|
||||
def parse_first_layer_height(self) -> Optional[float]:
|
||||
layer_info = _regex_find_floats(
|
||||
r";LAYER:0\s*.*\s*;HEIGHT.*", self.header_data)
|
||||
if len(layer_info) >= 3:
|
||||
return layer_info[2]
|
||||
return None
|
||||
|
||||
def parse_layer_height(self):
|
||||
def parse_layer_height(self) -> Optional[float]:
|
||||
layer_info = _regex_find_floats(
|
||||
r";LAYER:1\s*.*\s*;HEIGHT.*", self.header_data)
|
||||
if len(layer_info) >= 3:
|
||||
return layer_info[2]
|
||||
self.layer_height = layer_info[2]
|
||||
return self.layer_height
|
||||
return None
|
||||
|
||||
def parse_object_height(self):
|
||||
def parse_object_height(self) -> Optional[float]:
|
||||
bounds = _regex_find_floats(
|
||||
r";Bounding Box:.*", self.header_data)
|
||||
if len(bounds) >= 6:
|
||||
return bounds[5]
|
||||
return None
|
||||
|
||||
def parse_filament_total(self):
|
||||
def parse_filament_total(self) -> Optional[float]:
|
||||
filament = _regex_find_floats(
|
||||
r";Material.\d\sUsed:.*", self.header_data, strict=True)
|
||||
r";Material.\d\sUsed:.*", self.footer_data, strict=True)
|
||||
if filament:
|
||||
return sum(filament)
|
||||
return None
|
||||
|
||||
def parse_estimated_time(self):
|
||||
def parse_filament_weight_total(self) -> Optional[float]:
|
||||
pi = 3.141592653589793
|
||||
length = _regex_find_floats(
|
||||
r";Material.\d\sUsed:.*", self.footer_data, strict=True)
|
||||
diameter = _regex_find_floats(
|
||||
r";Filament\sDiameter\s.\d:.*", self.header_data, strict=True)
|
||||
density = _regex_find_floats(
|
||||
r";Filament\sDensity\s.\d:.*", self.header_data, strict=True)
|
||||
if len(length) == len(density) == len(diameter):
|
||||
# calc individual weight for each filament with m=pi/4*d²*l*rho
|
||||
weights = [(pi/4 * diameter[i]**2 * length[i] * density[i]/10**6)
|
||||
for i in range(len(length))]
|
||||
return sum(weights)
|
||||
return None
|
||||
|
||||
def parse_estimated_time(self) -> Optional[float]:
|
||||
return _regex_find_first(
|
||||
r";Print\sTime:\s(\d+\.?\d*)", self.footer_data)
|
||||
|
||||
def parse_first_layer_extr_temp(self):
|
||||
def parse_first_layer_extr_temp(self) -> Optional[float]:
|
||||
return _regex_find_first(
|
||||
r"M109 T0 S(\d+\.?\d*)", self.header_data)
|
||||
|
||||
def parse_first_layer_bed_temp(self):
|
||||
def parse_first_layer_bed_temp(self) -> Optional[float]:
|
||||
return _regex_find_first(
|
||||
r"M190 S(\d+\.?\d*)", self.header_data)
|
||||
|
||||
class IceSL(BaseSlicer):
|
||||
def check_identity(self, data):
|
||||
def check_identity(self, data) -> Optional[Dict[str, Any]]:
|
||||
match = re.search(r"; <IceSL.*>", data)
|
||||
if match:
|
||||
return {'slicer': "IceSL"}
|
||||
return None
|
||||
|
||||
def parse_first_layer_height(self):
|
||||
def parse_first_layer_height(self) -> Optional[float]:
|
||||
return _regex_find_first(
|
||||
r"; z_layer_height_first_layer_mm :\s+(\d+\.\d+)",
|
||||
self.header_data, float)
|
||||
self.header_data)
|
||||
|
||||
def parse_layer_height(self):
|
||||
return _regex_find_first(
|
||||
def parse_layer_height(self) -> Optional[float]:
|
||||
self.layer_height = _regex_find_first(
|
||||
r"; z_layer_height_mm :\s+(\d+\.\d+)",
|
||||
self.header_data, float)
|
||||
self.header_data)
|
||||
return self.layer_height
|
||||
|
||||
def parse_object_height(self):
|
||||
def parse_object_height(self) -> Optional[float]:
|
||||
return self._parse_max_float(
|
||||
r"G0 F\d+ Z\d+\.\d+", self.footer_data, strict=True)
|
||||
|
||||
def parse_first_layer_extr_temp(self):
|
||||
def parse_first_layer_extr_temp(self) -> Optional[float]:
|
||||
return _regex_find_first(
|
||||
r"; extruder_temp_degree_c_0 :\s+(\d+\.?\d*)", self.header_data)
|
||||
|
||||
def parse_first_layer_bed_temp(self):
|
||||
def parse_first_layer_bed_temp(self) -> Optional[float]:
|
||||
return _regex_find_first(
|
||||
r"; bed_temp_degree_c :\s+(\d+\.?\d*)", self.header_data)
|
||||
|
||||
|
||||
READ_SIZE = 512 * 1024
|
||||
SUPPORTED_SLICERS = [
|
||||
SUPPORTED_SLICERS: List[Type[BaseSlicer]] = [
|
||||
PrusaSlicer, Slic3rPE, Slic3r, SuperSlicer,
|
||||
Cura, Simplify3D, KISSlicer, IdeaMaker, IceSL]
|
||||
SUPPORTED_DATA = [
|
||||
'first_layer_height', 'layer_height', 'object_height',
|
||||
'filament_total', 'estimated_time', 'thumbnails',
|
||||
'first_layer_bed_temp', 'first_layer_extr_temp',
|
||||
'layer_height', 'first_layer_height', 'object_height',
|
||||
'filament_total', 'filament_weight_total', 'estimated_time',
|
||||
'thumbnails', 'first_layer_bed_temp', 'first_layer_extr_temp',
|
||||
'gcode_start_byte', 'gcode_end_byte']
|
||||
|
||||
def extract_metadata(file_path, log):
|
||||
metadata = {}
|
||||
def extract_metadata(file_path: str) -> Dict[str, Any]:
|
||||
metadata: Dict[str, Any] = {}
|
||||
slicers = [s(file_path) for s in SUPPORTED_SLICERS]
|
||||
header_data = footer_data = slicer = None
|
||||
header_data = footer_data = ""
|
||||
slicer: Optional[BaseSlicer] = None
|
||||
size = os.path.getsize(file_path)
|
||||
metadata['size'] = size
|
||||
metadata['modified'] = os.path.getmtime(file_path)
|
||||
@@ -563,7 +674,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()
|
||||
@@ -571,20 +682,52 @@ def extract_metadata(file_path, log):
|
||||
metadata[key] = result
|
||||
return metadata
|
||||
|
||||
def main(path, filename):
|
||||
def extract_ufp(ufp_path: str, dest_path: str) -> None:
|
||||
if not os.path.isfile(ufp_path):
|
||||
log_to_stderr(f"UFP file Not Found: {ufp_path}")
|
||||
sys.exit(-1)
|
||||
thumb_name = os.path.splitext(
|
||||
os.path.basename(dest_path))[0] + ".png"
|
||||
dest_thumb_dir = os.path.join(os.path.dirname(dest_path), ".thumbs")
|
||||
dest_thumb_path = os.path.join(dest_thumb_dir, thumb_name)
|
||||
try:
|
||||
with tempfile.TemporaryDirectory() as tmp_dir_name:
|
||||
tmp_thumb_path = ""
|
||||
with zipfile.ZipFile(ufp_path) as zf:
|
||||
tmp_model_path = zf.extract(
|
||||
UFP_MODEL_PATH, path=tmp_dir_name)
|
||||
if UFP_THUMB_PATH in zf.namelist():
|
||||
tmp_thumb_path = zf.extract(
|
||||
UFP_THUMB_PATH, path=tmp_dir_name)
|
||||
shutil.move(tmp_model_path, dest_path)
|
||||
if tmp_thumb_path:
|
||||
if not os.path.exists(dest_thumb_dir):
|
||||
os.mkdir(dest_thumb_dir)
|
||||
shutil.move(tmp_thumb_path, dest_thumb_path)
|
||||
except Exception:
|
||||
log_to_stderr(traceback.format_exc())
|
||||
sys.exit(-1)
|
||||
try:
|
||||
os.remove(ufp_path)
|
||||
except Exception:
|
||||
log_to_stderr(f"Error removing ufp file: {ufp_path}")
|
||||
|
||||
def main(path: str, filename: str, ufp: Optional[str]) -> None:
|
||||
file_path = os.path.join(path, filename)
|
||||
log = []
|
||||
metadata = {}
|
||||
if ufp is not None:
|
||||
extract_ufp(ufp, file_path)
|
||||
metadata: Dict[str, Any] = {}
|
||||
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)
|
||||
@@ -605,5 +748,9 @@ if __name__ == "__main__":
|
||||
metavar='<path>',
|
||||
help="optional absolute path for file"
|
||||
)
|
||||
parser.add_argument(
|
||||
"-u", "--ufp", metavar="<ufp file>", default=None,
|
||||
help="optional path of ufp file to extract"
|
||||
)
|
||||
args = parser.parse_args()
|
||||
main(args.path, args.filename)
|
||||
main(args.path, args.filename, args.ufp)
|
||||
@@ -0,0 +1,362 @@
|
||||
# History cache for printer jobs
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
import logging
|
||||
import time
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Union,
|
||||
Optional,
|
||||
Dict,
|
||||
List,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from confighelper import ConfigHelper
|
||||
from websockets import WebRequest
|
||||
from . import database
|
||||
from . import klippy_apis
|
||||
from .file_manager import file_manager
|
||||
DBComp = database.MoonrakerDatabase
|
||||
APIComp = klippy_apis.KlippyAPI
|
||||
FMComp = file_manager.FileManager
|
||||
|
||||
HIST_NAMESPACE = "history"
|
||||
MAX_JOBS = 10000
|
||||
|
||||
class History:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.file_manager: FMComp = self.server.lookup_component(
|
||||
'file_manager')
|
||||
database: DBComp = self.server.lookup_component("database")
|
||||
self.gcdb = database.wrap_namespace("gcode_metadata", parse_keys=False)
|
||||
self.job_totals: Dict[str, float] = database.get_item(
|
||||
"moonraker", "history.job_totals",
|
||||
{
|
||||
'total_jobs': 0,
|
||||
'total_time': 0.,
|
||||
'total_print_time': 0.,
|
||||
'total_filament_used': 0.,
|
||||
'longest_job': 0.,
|
||||
'longest_print': 0.
|
||||
})
|
||||
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_ready", self._init_ready)
|
||||
self.server.register_event_handler(
|
||||
"server:status_update", self._status_update)
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_disconnect", self._handle_disconnect)
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_shutdown", self._handle_shutdown)
|
||||
self.server.register_notification("history:history_changed")
|
||||
|
||||
self.server.register_endpoint(
|
||||
"/server/history/job", ['GET', 'DELETE'], self._handle_job_request)
|
||||
self.server.register_endpoint(
|
||||
"/server/history/list", ['GET'], self._handle_jobs_list)
|
||||
self.server.register_endpoint(
|
||||
"/server/history/totals", ['GET'], self._handle_job_totals)
|
||||
|
||||
database.register_local_namespace(HIST_NAMESPACE)
|
||||
self.history_ns = database.wrap_namespace(HIST_NAMESPACE,
|
||||
parse_keys=False)
|
||||
|
||||
self.current_job: Optional[PrinterJob] = None
|
||||
self.current_job_id: Optional[str] = None
|
||||
self.print_stats: Dict[str, Any] = {}
|
||||
self.next_job_id: int = 0
|
||||
self.cached_job_ids = self.history_ns.keys()
|
||||
if self.cached_job_ids:
|
||||
self.next_job_id = int(self.cached_job_ids[-1], 16) + 1
|
||||
|
||||
async def _init_ready(self) -> None:
|
||||
klippy_apis: APIComp = self.server.lookup_component('klippy_apis')
|
||||
sub: Dict[str, Optional[List[str]]] = {"print_stats": None}
|
||||
try:
|
||||
result = await klippy_apis.subscribe_objects(sub)
|
||||
except self.server.error as e:
|
||||
logging.info(f"Error subscribing to print_stats")
|
||||
self.print_stats = result.get("print_stats", {})
|
||||
|
||||
async def _handle_job_request(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
action = web_request.get_action()
|
||||
if action == "GET":
|
||||
job_id = web_request.get_str("uid")
|
||||
if job_id not in self.cached_job_ids:
|
||||
raise self.server.error(f"Invalid job uid: {job_id}", 404)
|
||||
job = self.history_ns[job_id]
|
||||
return {"job": self._prep_requested_job(job, job_id)}
|
||||
if action == "DELETE":
|
||||
all = web_request.get_boolean("all", False)
|
||||
if all:
|
||||
deljobs = self.cached_job_ids
|
||||
self.history_ns.clear()
|
||||
self.cached_job_ids = []
|
||||
self.next_job_id = 0
|
||||
return {'deleted_jobs': deljobs}
|
||||
|
||||
job_id = web_request.get_str("uid")
|
||||
if job_id not in self.cached_job_ids:
|
||||
raise self.server.error(f"Invalid job uid: {job_id}", 404)
|
||||
|
||||
self.delete_job(job_id)
|
||||
return {'deleted_jobs': [job_id]}
|
||||
raise self.server.error("Invalid Request Method")
|
||||
|
||||
async def _handle_jobs_list(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
i = 0
|
||||
count = 0
|
||||
end_num = len(self.cached_job_ids)
|
||||
jobs: List[Dict[str, Any]] = []
|
||||
start_num = 0
|
||||
|
||||
before = web_request.get_float("before", -1)
|
||||
since = web_request.get_float("since", -1)
|
||||
limit = web_request.get_int("limit", 50)
|
||||
start = web_request.get_int("start", 0)
|
||||
order = web_request.get_str("order", "desc")
|
||||
|
||||
if order not in ["asc", "desc"]:
|
||||
raise self.server.error(f"Invalid `order` value: {order}", 400)
|
||||
|
||||
reverse_order = (order == "desc")
|
||||
|
||||
# cached jobs is asc order, find lower and upper boundary
|
||||
if since != -1:
|
||||
while start_num < end_num:
|
||||
job_id = self.cached_job_ids[start_num]
|
||||
job: Dict[str, Any] = self.history_ns[job_id]
|
||||
if job['start_time'] > since:
|
||||
break
|
||||
start_num += 1
|
||||
|
||||
if before != -1:
|
||||
while end_num > 0:
|
||||
job_id = self.cached_job_ids[end_num-1]
|
||||
job = self.history_ns[job_id]
|
||||
if job['end_time'] < before:
|
||||
break
|
||||
end_num -= 1
|
||||
|
||||
if start_num >= end_num or end_num == 0:
|
||||
return {"count": 0, "jobs": []}
|
||||
|
||||
i = start
|
||||
count = end_num - start_num
|
||||
|
||||
if limit == 0:
|
||||
limit = MAX_JOBS
|
||||
|
||||
while i < count and len(jobs) < limit:
|
||||
if reverse_order:
|
||||
job_id = self.cached_job_ids[end_num - i - 1]
|
||||
else:
|
||||
job_id = self.cached_job_ids[start_num + i]
|
||||
job = self.history_ns[job_id]
|
||||
jobs.append(self._prep_requested_job(job, job_id))
|
||||
i += 1
|
||||
|
||||
return {"count": count, "jobs": jobs}
|
||||
|
||||
async def _handle_job_totals(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Dict[str, float]]:
|
||||
return {'job_totals': self.job_totals}
|
||||
|
||||
async def _status_update(self, data: Dict[str, Any]) -> None:
|
||||
ps = data.get("print_stats", {})
|
||||
if "state" in ps:
|
||||
old_state: str = self.print_stats['state']
|
||||
new_state: str = ps['state']
|
||||
new_ps = dict(self.print_stats)
|
||||
new_ps.update(ps)
|
||||
|
||||
if new_state is not old_state:
|
||||
if new_state == "printing" and self.current_job is None:
|
||||
# always add new job if no existing job is present
|
||||
self.add_job(PrinterJob(new_ps))
|
||||
elif self.current_job is not None:
|
||||
if new_state == "complete":
|
||||
self.finish_job("completed", new_ps)
|
||||
elif new_state == "cancelled":
|
||||
self.finish_job("cancelled", new_ps)
|
||||
elif new_state == "standby":
|
||||
# Backward compatibility with
|
||||
# `CLEAR_PAUSE/SDCARD_RESET_FILE` workflow
|
||||
self.finish_job("cancelled", self.print_stats)
|
||||
elif new_state == "error":
|
||||
self.finish_job("error", new_ps)
|
||||
elif new_state == "printing" and \
|
||||
self._check_need_cancel(new_ps):
|
||||
# Finish with the previous state
|
||||
self.finish_job("cancelled", self.print_stats)
|
||||
self.add_job(PrinterJob(new_ps))
|
||||
|
||||
self.print_stats.update(ps)
|
||||
|
||||
def _handle_shutdown(self) -> None:
|
||||
self.finish_job("klippy_shutdown", self.print_stats)
|
||||
|
||||
def _handle_disconnect(self) -> None:
|
||||
self.finish_job("klippy_disconnect", self.print_stats)
|
||||
|
||||
def _check_need_cancel(self, new_stats: Dict[str, Any]) -> bool:
|
||||
# Cancel if the file name has changed, total duration has
|
||||
# decreased, or if job is not resuming from a pause
|
||||
ps = self.print_stats
|
||||
return ps['filename'] != new_stats['filename'] or \
|
||||
ps['total_duration'] > new_stats['total_duration'] or \
|
||||
ps['state'] != "paused"
|
||||
|
||||
def add_job(self, job: PrinterJob) -> None:
|
||||
if len(self.cached_job_ids) >= MAX_JOBS:
|
||||
self.delete_job(self.cached_job_ids[0])
|
||||
job_id = f"{self.next_job_id:06X}"
|
||||
self.current_job = job
|
||||
self.current_job_id = job_id
|
||||
self.grab_job_metadata()
|
||||
self.history_ns[job_id] = job.get_stats()
|
||||
self.cached_job_ids.append(job_id)
|
||||
self.next_job_id += 1
|
||||
self.send_history_event("added")
|
||||
|
||||
def delete_job(self, job_id: Union[int, str]) -> None:
|
||||
if isinstance(job_id, int):
|
||||
job_id = f"{job_id:06X}"
|
||||
|
||||
if job_id in self.cached_job_ids:
|
||||
del self.history_ns[job_id]
|
||||
self.cached_job_ids.remove(job_id)
|
||||
|
||||
def finish_job(self, status: str, pstats: Dict[str, Any]) -> None:
|
||||
if self.current_job is None:
|
||||
return
|
||||
|
||||
self.current_job.finish(status, pstats)
|
||||
# Regrab metadata incase metadata wasn't parsed yet due to file upload
|
||||
self.grab_job_metadata()
|
||||
self.save_current_job()
|
||||
self._update_job_totals()
|
||||
self.send_history_event("finished")
|
||||
self.current_job = None
|
||||
self.current_job_id = None
|
||||
|
||||
def get_job(self, job_id: Union[int, str]) -> Optional[Dict[str, Any]]:
|
||||
if isinstance(job_id, int):
|
||||
job_id = f"{job_id:06X}"
|
||||
return self.history_ns.get(job_id, None)
|
||||
|
||||
def grab_job_metadata(self) -> None:
|
||||
if self.current_job is None:
|
||||
return
|
||||
filename: str = self.current_job.get("filename")
|
||||
metadata: Dict[str, Any] = self.gcdb.get(filename, {})
|
||||
if metadata:
|
||||
# Add the start time and job id to the
|
||||
# persistent metadata storage
|
||||
metadata.update({
|
||||
'print_start_time': self.current_job.get('start_time'),
|
||||
'job_id': self.current_job_id
|
||||
})
|
||||
self.gcdb[filename] = metadata
|
||||
# We don't need to store these fields in the
|
||||
# job metadata, as they are redundant
|
||||
metadata.pop('print_start_time', None)
|
||||
metadata.pop('job_id', None)
|
||||
if "thumbnails" in metadata:
|
||||
thumb: Dict[str, Any]
|
||||
for thumb in metadata['thumbnails']:
|
||||
thumb.pop('data', None)
|
||||
self.current_job.set("metadata", metadata)
|
||||
|
||||
def save_current_job(self) -> None:
|
||||
if self.current_job is None or self.current_job_id is None:
|
||||
return
|
||||
self.history_ns[self.current_job_id] = self.current_job.get_stats()
|
||||
|
||||
def _update_job_totals(self) -> None:
|
||||
if self.current_job is None:
|
||||
return
|
||||
job = self.current_job
|
||||
self.job_totals['total_jobs'] += 1
|
||||
self.job_totals['total_time'] += job.get('total_duration')
|
||||
self.job_totals['total_print_time'] += job.get('print_duration')
|
||||
self.job_totals['total_filament_used'] += job.get('filament_used')
|
||||
self.job_totals['longest_job'] = max(
|
||||
self.job_totals['longest_job'], job.get('total_duration'))
|
||||
self.job_totals['longest_print'] = max(
|
||||
self.job_totals['longest_print'], job.get('print_duration'))
|
||||
database: DBComp = self.server.lookup_component("database")
|
||||
database.insert_item(
|
||||
"moonraker", "history.job_totals", self.job_totals)
|
||||
|
||||
def send_history_event(self, evt_action: str) -> None:
|
||||
if self.current_job is None or self.current_job_id is None:
|
||||
return
|
||||
job = self._prep_requested_job(
|
||||
self.current_job.get_stats(), self.current_job_id)
|
||||
self.server.send_event("history:history_changed",
|
||||
{'action': evt_action, 'job': job})
|
||||
|
||||
def _prep_requested_job(self,
|
||||
job: Dict[str, Any],
|
||||
job_id: str
|
||||
) -> Dict[str, Any]:
|
||||
job['job_id'] = job_id
|
||||
job['exists'] = self.file_manager.check_file_exists(
|
||||
"gcodes", job['filename'])
|
||||
return job
|
||||
|
||||
def on_exit(self) -> None:
|
||||
self.finish_job("server_exit", self.print_stats)
|
||||
|
||||
class PrinterJob:
|
||||
def __init__(self, data: Dict[str, Any] = {}) -> None:
|
||||
self.end_time: Optional[float] = None
|
||||
self.filament_used: float = 0
|
||||
self.filename: Optional[str] = None
|
||||
self.metadata: Optional[Dict[str, Any]] = None
|
||||
self.print_duration: float = 0.
|
||||
self.status: str = "in_progress"
|
||||
self.start_time = time.time()
|
||||
self.total_duration: float = 0.
|
||||
self.update_from_ps(data)
|
||||
|
||||
def finish(self,
|
||||
status: str,
|
||||
print_stats: Dict[str, Any] = {}
|
||||
) -> None:
|
||||
self.end_time = time.time()
|
||||
self.status = status
|
||||
self.update_from_ps(print_stats)
|
||||
|
||||
def get(self, name: str) -> Any:
|
||||
if not hasattr(self, name):
|
||||
return None
|
||||
return getattr(self, name)
|
||||
|
||||
def get_stats(self) -> Dict[str, Any]:
|
||||
return self.__dict__.copy()
|
||||
|
||||
def set(self, name: str, val: Any) -> None:
|
||||
if not hasattr(self, name):
|
||||
return
|
||||
setattr(self, name, val)
|
||||
|
||||
def update_from_ps(self, data: Dict[str, Any]) -> None:
|
||||
for i in data:
|
||||
if hasattr(self, i):
|
||||
setattr(self, i, data[i])
|
||||
|
||||
def load_component(config: ConfigHelper) -> History:
|
||||
return History(config)
|
||||
@@ -3,8 +3,27 @@
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import utils
|
||||
from websockets import WebRequest
|
||||
|
||||
from __future__ import annotations
|
||||
from utils import SentinelClass
|
||||
from websockets import WebRequest, Subscribable
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Union,
|
||||
Optional,
|
||||
Dict,
|
||||
List,
|
||||
TypeVar,
|
||||
Mapping,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from confighelper import ConfigHelper
|
||||
from websockets import WebRequest
|
||||
Subscription = Dict[str, Optional[List[Any]]]
|
||||
_T = TypeVar("_T")
|
||||
|
||||
INFO_ENDPOINT = "info"
|
||||
ESTOP_ENDPOINT = "emergency_stop"
|
||||
@@ -15,17 +34,16 @@ SUBSCRIPTION_ENDPOINT = "objects/subscribe"
|
||||
STATUS_ENDPOINT = "objects/query"
|
||||
OBJ_LIST_ENDPOINT = "objects/list"
|
||||
REG_METHOD_ENDPOINT = "register_remote_method"
|
||||
SENTINEL = SentinelClass.get_instance()
|
||||
|
||||
class Sentinel:
|
||||
pass
|
||||
|
||||
class KlippyAPI:
|
||||
def __init__(self, config):
|
||||
class KlippyAPI(Subscribable):
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
|
||||
app_args = self.server.get_app_args()
|
||||
self.version = app_args.get('software_version')
|
||||
# Maintain a subscription for all moonraker requests, as
|
||||
# we do not want to overwrite them
|
||||
self.host_subscription = {}
|
||||
self.host_subscription: Subscription = {}
|
||||
|
||||
# Register GCode Aliases
|
||||
self.server.register_endpoint(
|
||||
@@ -41,42 +59,49 @@ class KlippyAPI:
|
||||
self.server.register_endpoint(
|
||||
"/printer/firmware_restart", ['POST'], self._gcode_firmware_restart)
|
||||
|
||||
async def _gcode_pause(self, web_request):
|
||||
return await self.run_gcode("PAUSE")
|
||||
async def _gcode_pause(self, web_request: WebRequest) -> str:
|
||||
return await self._send_klippy_request("pause_resume/pause", {})
|
||||
|
||||
async def _gcode_resume(self, web_request):
|
||||
return await self.run_gcode("RESUME")
|
||||
async def _gcode_resume(self, web_request: WebRequest) -> str:
|
||||
return await self._send_klippy_request("pause_resume/resume", {})
|
||||
|
||||
async def _gcode_cancel(self, web_request):
|
||||
return await self.run_gcode("CANCEL_PRINT")
|
||||
async def _gcode_cancel(self, web_request: WebRequest) -> str:
|
||||
return await self._send_klippy_request("pause_resume/cancel", {})
|
||||
|
||||
async def _gcode_start_print(self, web_request):
|
||||
filename = web_request.get_str('filename')
|
||||
async def _gcode_start_print(self, web_request: WebRequest) -> str:
|
||||
filename: str = web_request.get_str('filename')
|
||||
return await self.start_print(filename)
|
||||
|
||||
async def _gcode_restart(self, web_request):
|
||||
async def _gcode_restart(self, web_request: WebRequest) -> str:
|
||||
return await self.do_restart("RESTART")
|
||||
|
||||
async def _gcode_firmware_restart(self, web_request):
|
||||
async def _gcode_firmware_restart(self, web_request: WebRequest) -> str:
|
||||
return await self.do_restart("FIRMWARE_RESTART")
|
||||
|
||||
async def _send_klippy_request(self, method, params, default=Sentinel):
|
||||
async def _send_klippy_request(self,
|
||||
method: str,
|
||||
params: Dict[str, Any],
|
||||
default: Any = SENTINEL
|
||||
) -> Any:
|
||||
try:
|
||||
result = await self.server.make_request(
|
||||
WebRequest(method, params, conn=self))
|
||||
except self.server.error as e:
|
||||
if default == Sentinel:
|
||||
except self.server.error:
|
||||
if isinstance(default, SentinelClass):
|
||||
raise
|
||||
result = default
|
||||
return result
|
||||
|
||||
async def run_gcode(self, script, default=Sentinel):
|
||||
async def run_gcode(self,
|
||||
script: str,
|
||||
default: Any = SENTINEL
|
||||
) -> str:
|
||||
params = {'script': script}
|
||||
result = await self._send_klippy_request(
|
||||
GCODE_ENDPOINT, params, default)
|
||||
return result
|
||||
|
||||
async def start_print(self, filename):
|
||||
async def start_print(self, filename: str) -> str:
|
||||
# XXX - validate that file is on disk
|
||||
if filename[0] == '/':
|
||||
filename = filename[1:]
|
||||
@@ -85,7 +110,7 @@ class KlippyAPI:
|
||||
script = f'SDCARD_PRINT_FILE FILENAME="{filename}"'
|
||||
return await self.run_gcode(script)
|
||||
|
||||
async def do_restart(self, gc):
|
||||
async def do_restart(self, gc: str) -> str:
|
||||
try:
|
||||
result = await self.run_gcode(gc)
|
||||
except self.server.error as e:
|
||||
@@ -95,28 +120,38 @@ class KlippyAPI:
|
||||
raise
|
||||
return result
|
||||
|
||||
async def list_endpoints(self, default=Sentinel):
|
||||
async def list_endpoints(self,
|
||||
default: Union[SentinelClass, _T] = SENTINEL
|
||||
) -> Union[_T, Dict[str, List[str]]]:
|
||||
return await self._send_klippy_request(
|
||||
LIST_EPS_ENDPOINT, {}, default)
|
||||
|
||||
async def emergency_stop(self, default=Sentinel):
|
||||
return await self._send_klippy_request(ESTOP_ENDPOINT, {}, default)
|
||||
async def emergency_stop(self) -> str:
|
||||
return await self._send_klippy_request(ESTOP_ENDPOINT, {})
|
||||
|
||||
async def get_klippy_info(self, send_id=False, default=Sentinel):
|
||||
async def get_klippy_info(self,
|
||||
send_id: bool = False,
|
||||
default: Union[SentinelClass, _T] = SENTINEL
|
||||
) -> Union[_T, Dict[str, Any]]:
|
||||
params = {}
|
||||
if send_id:
|
||||
ver = utils.get_software_version()
|
||||
ver = self.version
|
||||
params = {'client_info': {'program': "Moonraker", 'version': ver}}
|
||||
return await self._send_klippy_request(INFO_ENDPOINT, params, default)
|
||||
|
||||
async def get_object_list(self, default=Sentinel):
|
||||
async def get_object_list(self,
|
||||
default: Union[SentinelClass, _T] = SENTINEL
|
||||
) -> Union[_T, List[str]]:
|
||||
result = await self._send_klippy_request(
|
||||
OBJ_LIST_ENDPOINT, {}, default)
|
||||
if isinstance(result, dict) and 'objects' in result:
|
||||
return result['objects']
|
||||
return result
|
||||
|
||||
async def query_objects(self, objects, default=Sentinel):
|
||||
async def query_objects(self,
|
||||
objects: Mapping[str, Optional[List[str]]],
|
||||
default: Union[SentinelClass, _T] = SENTINEL
|
||||
) -> Union[_T, Dict[str, Any]]:
|
||||
params = {'objects': objects}
|
||||
result = await self._send_klippy_request(
|
||||
STATUS_ENDPOINT, params, default)
|
||||
@@ -124,7 +159,10 @@ class KlippyAPI:
|
||||
return result['status']
|
||||
return result
|
||||
|
||||
async def subscribe_objects(self, objects, default=Sentinel):
|
||||
async def subscribe_objects(self,
|
||||
objects: Mapping[str, Optional[List[str]]],
|
||||
default: Union[SentinelClass, _T] = SENTINEL
|
||||
) -> Union[_T, Dict[str, Any]]:
|
||||
for obj, items in objects.items():
|
||||
if obj in self.host_subscription:
|
||||
prev = self.host_subscription[obj]
|
||||
@@ -142,20 +180,22 @@ class KlippyAPI:
|
||||
return result['status']
|
||||
return result
|
||||
|
||||
async def subscribe_gcode_output(self, default=Sentinel):
|
||||
async def subscribe_gcode_output(self) -> str:
|
||||
template = {'response_template':
|
||||
{'method': "process_gcode_response"}}
|
||||
return await self._send_klippy_request(
|
||||
GC_OUTPUT_ENDPOINT, template, default)
|
||||
return await self._send_klippy_request(GC_OUTPUT_ENDPOINT, template)
|
||||
|
||||
async def register_method(self, method_name):
|
||||
async def register_method(self, method_name: str) -> str:
|
||||
return await self._send_klippy_request(
|
||||
REG_METHOD_ENDPOINT,
|
||||
{'response_template': {"method": method_name},
|
||||
'remote_method': method_name})
|
||||
|
||||
def send_status(self, status):
|
||||
def send_status(self,
|
||||
status: Dict[str, Any],
|
||||
eventtime: float
|
||||
) -> None:
|
||||
self.server.send_event("server:status_update", status)
|
||||
|
||||
def load_plugin(config):
|
||||
def load_component(config: ConfigHelper) -> KlippyAPI:
|
||||
return KlippyAPI(config)
|
||||
@@ -0,0 +1,269 @@
|
||||
# Machine manipulation request handlers
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
import os
|
||||
import re
|
||||
import pathlib
|
||||
import logging
|
||||
import platform
|
||||
import distro
|
||||
from tornado.ioloop import IOLoop
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
List,
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Dict,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from confighelper import ConfigHelper
|
||||
from websockets import WebRequest
|
||||
from . import shell_command
|
||||
SCMDComp = shell_command.ShellCommandFactory
|
||||
|
||||
ALLOWED_SERVICES = [
|
||||
"moonraker", "klipper", "webcamd", "MoonCord",
|
||||
"KlipperScreen"]
|
||||
SYSTEMD_PATH = "/etc/systemd/system"
|
||||
SD_CID_PATH = "/sys/block/mmcblk0/device/cid"
|
||||
SD_CSD_PATH = "/sys/block/mmcblk0/device/csd"
|
||||
SD_MFGRS = {
|
||||
'1b': "Samsung",
|
||||
'03': "Sandisk"
|
||||
}
|
||||
|
||||
class Machine:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
dist_info: Dict[str, Any]
|
||||
dist_info = {'name': distro.name(pretty=True)}
|
||||
dist_info.update(distro.info())
|
||||
self.system_info: Dict[str, Any] = {
|
||||
'cpu_info': self._get_cpu_info(),
|
||||
'sd_info': self._get_sdcard_info(),
|
||||
'distribution': dist_info
|
||||
}
|
||||
# Add system info to log rollover
|
||||
sys_info_msg = "\nSystem Info:"
|
||||
for header, info in self.system_info.items():
|
||||
sys_info_msg += f"\n\n***{header}***"
|
||||
for key, val in info.items():
|
||||
sys_info_msg += f"\n {key}: {val}"
|
||||
self.server.add_log_rollover_item('system_info', sys_info_msg)
|
||||
self.available_services: List[str] = []
|
||||
|
||||
self.server.register_endpoint(
|
||||
"/machine/reboot", ['POST'], self._handle_machine_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/shutdown", ['POST'], self._handle_machine_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/services/restart", ['POST'],
|
||||
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)
|
||||
self.server.register_endpoint(
|
||||
"/machine/system_info", ['GET'],
|
||||
self._handle_sysinfo_request)
|
||||
|
||||
# Register remote methods
|
||||
self.server.register_remote_method(
|
||||
"shutdown_machine", self.shutdown_machine)
|
||||
self.server.register_remote_method(
|
||||
"reboot_machine", self.reboot_machine)
|
||||
|
||||
# Retreive list of services
|
||||
IOLoop.current().spawn_callback(self._find_active_services)
|
||||
|
||||
async def _handle_machine_request(self, web_request: WebRequest) -> str:
|
||||
ep = web_request.get_endpoint()
|
||||
if ep == "/machine/shutdown":
|
||||
await self.shutdown_machine()
|
||||
elif ep == "/machine/reboot":
|
||||
await self.reboot_machine()
|
||||
else:
|
||||
raise self.server.error("Unsupported machine request")
|
||||
return "ok"
|
||||
|
||||
async def shutdown_machine(self) -> None:
|
||||
await self._execute_cmd("sudo shutdown now")
|
||||
|
||||
async def reboot_machine(self) -> None:
|
||||
await self._execute_cmd("sudo shutdown -r now")
|
||||
|
||||
async def do_service_action(self,
|
||||
action: str,
|
||||
service_name: str
|
||||
) -> None:
|
||||
await self._execute_cmd(
|
||||
f'sudo systemctl {action} {service_name}')
|
||||
|
||||
async def _handle_service_request(self, web_request: WebRequest) -> str:
|
||||
name: str = web_request.get('service')
|
||||
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.do_service_action, action, name)
|
||||
elif name in self.available_services:
|
||||
await self.do_service_action(action, name)
|
||||
else:
|
||||
if name in ALLOWED_SERVICES and \
|
||||
name not in self.available_services:
|
||||
raise self.server.error(f"Service '{name}' not installed")
|
||||
raise self.server.error(
|
||||
f"Service '{name}' not allowed")
|
||||
return "ok"
|
||||
|
||||
async def _handle_sysinfo_request(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
return {'system_info': self.system_info}
|
||||
|
||||
async def _execute_cmd(self, cmd: str) -> None:
|
||||
shell_cmd: SCMDComp = self.server.lookup_component('shell_command')
|
||||
scmd = shell_cmd.build_shell_command(cmd, None)
|
||||
try:
|
||||
await scmd.run(timeout=2., verbose=False)
|
||||
except Exception:
|
||||
logging.exception(f"Error running cmd '{cmd}'")
|
||||
raise
|
||||
|
||||
def get_system_info(self) -> Dict[str, Dict[str, Any]]:
|
||||
return self.system_info
|
||||
|
||||
def _get_sdcard_info(self) -> Dict[str, Any]:
|
||||
sd_info: Dict[str, Any] = {}
|
||||
cid_file = pathlib.Path(SD_CID_PATH)
|
||||
if not cid_file.exists():
|
||||
# No SDCard detected at mmcblk0
|
||||
return {}
|
||||
try:
|
||||
cid_text = cid_file.read_text().strip().lower()
|
||||
mid = cid_text[:2]
|
||||
sd_info['manufacturer_id'] = mid
|
||||
sd_info['manufacturer'] = SD_MFGRS.get(mid, "Unknown")
|
||||
sd_info['oem_id'] = cid_text[2:6]
|
||||
sd_info['product_name'] = bytes.fromhex(cid_text[6:16]).decode(
|
||||
encoding="ascii", errors="ignore")
|
||||
sd_info['product_revision'] = \
|
||||
f"{int(cid_text[16], 16)}.{int(cid_text[17], 16)}"
|
||||
sd_info['serial_number'] = cid_text[18:26]
|
||||
mfg_year = int(cid_text[27:29], 16) + 2000
|
||||
mfg_month = int(cid_text[29], 16)
|
||||
sd_info['manufacturer_date'] = f"{mfg_month}/{mfg_year}"
|
||||
except Exception:
|
||||
logging.info("Error reading SDCard CID Register")
|
||||
return {}
|
||||
sd_info['capacity'] = "Unknown"
|
||||
sd_info['total_bytes'] = 0
|
||||
csd_file = pathlib.Path(SD_CSD_PATH)
|
||||
# Read CSD Register
|
||||
try:
|
||||
csd_reg = bytes.fromhex(csd_file.read_text().strip())
|
||||
csd_type = (csd_reg[0] >> 6) & 0x3
|
||||
if csd_type == 0:
|
||||
# Standard Capacity (CSD Version 1.0)
|
||||
max_block_len: int = 2**(csd_reg[5] & 0xF)
|
||||
c_size = ((csd_reg[6] & 0x3) << 10) | (csd_reg[7] << 2) | \
|
||||
((csd_reg[8] >> 6) & 0x3)
|
||||
c_mult_reg = ((csd_reg[9] & 0x3) << 1) | (csd_reg[10] >> 7)
|
||||
c_mult = 2**(c_mult_reg + 2)
|
||||
total_bytes: int = (c_size + 1) * c_mult * max_block_len
|
||||
sd_info['capacity'] = f"{(total_bytes / (1024.0**2)):.1f} MiB"
|
||||
elif csd_type == 1:
|
||||
# High Capacity (CSD Version 2.0)
|
||||
c_size = ((csd_reg[7] & 0x3F) << 16) | (csd_reg[8] << 8) | \
|
||||
csd_reg[9]
|
||||
total_bytes = (c_size + 1) * 512 * 1024
|
||||
sd_info['capacity'] = f"{(total_bytes / (1024.0**3)):.1f} GiB"
|
||||
elif csd_type == 2:
|
||||
# Ultra Capacity (CSD Version 3.0)
|
||||
c_size = ((csd_reg[6]) & 0xF) << 24 | (csd_reg[7] << 16) | \
|
||||
(csd_reg[8] << 8) | csd_reg[9]
|
||||
total_bytes = (c_size + 1) * 512 * 1024
|
||||
sd_info['capacity'] = f"{(total_bytes / (1024.0**4)):.1f} TiB"
|
||||
else:
|
||||
# Invalid CSD, skip capacity check
|
||||
return sd_info
|
||||
sd_info['total_bytes'] = total_bytes
|
||||
except Exception:
|
||||
logging.info("Error Reading SDCard CSD Register")
|
||||
return sd_info
|
||||
|
||||
def _get_cpu_info(self) -> Dict[str, Any]:
|
||||
cpu_file = pathlib.Path("/proc/cpuinfo")
|
||||
mem_file = pathlib.Path("/proc/meminfo")
|
||||
cpu_info = {
|
||||
'cpu_count': os.cpu_count(),
|
||||
'bits': platform.architecture()[0],
|
||||
'processor': platform.processor() or platform.machine(),
|
||||
'cpu_desc': "",
|
||||
'hardware_desc': "",
|
||||
'model': "",
|
||||
'total_memory': None,
|
||||
'memory_units': ""
|
||||
}
|
||||
if cpu_file.exists():
|
||||
try:
|
||||
cpu_text = cpu_file.read_text().strip()
|
||||
cpu_items = [item.strip() for item in cpu_text.split("\n\n")
|
||||
if item.strip()]
|
||||
for item in cpu_items:
|
||||
cpu_desc_match = re.search(r"model name\s+:\s+(.+)", item)
|
||||
if cpu_desc_match is not None:
|
||||
cpu_info['cpu_desc'] = cpu_desc_match.group(1).strip()
|
||||
continue
|
||||
hw_match = re.search(r"Hardware\s+:\s+(.+)", cpu_items[-1])
|
||||
if hw_match is not None:
|
||||
cpu_info['hardware_desc'] = hw_match.group(1).strip()
|
||||
model_match = re.search(r"Model\s+:\s+(.+)", cpu_items[-1])
|
||||
if model_match is not None:
|
||||
cpu_info['model'] = model_match.group(1).strip()
|
||||
except Exception:
|
||||
logging.info("Error Reading /proc/cpuinfo")
|
||||
if mem_file.exists():
|
||||
try:
|
||||
mem_text = mem_file.read_text().strip()
|
||||
for line in mem_text.split('\n'):
|
||||
line = line.strip()
|
||||
if line.startswith("MemTotal:"):
|
||||
parts = line.split()
|
||||
cpu_info['total_memory'] = int(parts[1])
|
||||
cpu_info['memory_units'] = parts[2]
|
||||
break
|
||||
except Exception:
|
||||
logging.info("Error Reading /proc/meminfo")
|
||||
return cpu_info
|
||||
|
||||
async def _find_active_services(self):
|
||||
shell_cmd: SCMDComp = self.server.lookup_component('shell_command')
|
||||
scmd = shell_cmd.build_shell_command(
|
||||
"systemctl list-units --type=service")
|
||||
try:
|
||||
resp = await scmd.run_with_response()
|
||||
lines = resp.split('\n')
|
||||
services = [line.split()[0].strip() for line in lines
|
||||
if ".service" in line.strip()]
|
||||
except Exception:
|
||||
services = []
|
||||
for svc in services:
|
||||
sname = svc.rsplit('.', 1)[0]
|
||||
for allowed in ALLOWED_SERVICES:
|
||||
if sname.startswith(allowed):
|
||||
self.available_services.append(sname)
|
||||
self.system_info['available_services'] = self.available_services
|
||||
|
||||
|
||||
def load_component(config: ConfigHelper) -> Machine:
|
||||
return Machine(config)
|
||||
@@ -0,0 +1,599 @@
|
||||
# MQTT client implemenation for Moonraker
|
||||
#
|
||||
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
import socket
|
||||
import asyncio
|
||||
import logging
|
||||
import json
|
||||
import pathlib
|
||||
from collections import deque
|
||||
import paho.mqtt.client as paho_mqtt
|
||||
from tornado.ioloop import IOLoop
|
||||
from websockets import WebRequest, JsonRPC, APITransport
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
List,
|
||||
Optional,
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Callable,
|
||||
Coroutine,
|
||||
Dict,
|
||||
Union,
|
||||
Tuple,
|
||||
Awaitable,
|
||||
Deque,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from app import APIDefinition
|
||||
from confighelper import ConfigHelper
|
||||
FlexCallback = Callable[[bytes], Optional[Coroutine]]
|
||||
RPCCallback = Callable[..., Coroutine]
|
||||
|
||||
DUP_API_REQ_CODE = -10000
|
||||
MQTT_PROTOCOLS = {
|
||||
'v3.1': paho_mqtt.MQTTv31,
|
||||
'v3.1.1': paho_mqtt.MQTTv311,
|
||||
'v5': paho_mqtt.MQTTv5
|
||||
}
|
||||
|
||||
class SubscriptionHandle:
|
||||
def __init__(self, topic: str, callback: FlexCallback) -> None:
|
||||
self.callback = callback
|
||||
self.topic = topic
|
||||
|
||||
class BrokerAckLogger:
|
||||
def __init__(self, topics: List[str], action: str) -> None:
|
||||
self.topics = topics
|
||||
self.action = action
|
||||
|
||||
def __call__(self, fut: asyncio.Future) -> None:
|
||||
if self.action == "subscribe":
|
||||
res: Union[List[int], List[paho_mqtt.ReasonCodes]]
|
||||
res = fut.result()
|
||||
log_msg = "MQTT Subscriptions Acknowledged"
|
||||
if len(res) != len(self.topics):
|
||||
log_msg += "\nTopic / QOS count mismatch, " \
|
||||
f"\nTopics: {self.topics} " \
|
||||
f"\nQoS responses: {res}"
|
||||
else:
|
||||
for topic, qos in zip(self.topics, res):
|
||||
log_msg += f"\n Topic: {topic} | "
|
||||
if isinstance(qos, paho_mqtt.ReasonCodes):
|
||||
log_msg += qos.getName()
|
||||
else:
|
||||
log_msg += f"Granted QoS {qos}"
|
||||
elif self.action == "unsubscribe":
|
||||
log_msg = "MQTT Unsubscribe Acknowledged"
|
||||
for topic in self.topics:
|
||||
log_msg += f"\n Topic: {topic}"
|
||||
else:
|
||||
log_msg = f"Unknown action: {self.action}"
|
||||
logging.debug(log_msg)
|
||||
|
||||
|
||||
SubscribedDict = Dict[str, Tuple[int, List[SubscriptionHandle]]]
|
||||
|
||||
class AIOHelper:
|
||||
def __init__(self, client: paho_mqtt.Client) -> None:
|
||||
self.loop = asyncio.get_running_loop()
|
||||
self.client = client
|
||||
self.client.on_socket_open = self._on_socket_open
|
||||
self.client.on_socket_close = self._on_socket_close
|
||||
self.client._on_socket_register_write = self._on_socket_register_write
|
||||
self.client._on_socket_unregister_write = \
|
||||
self._on_socket_unregister_write
|
||||
self.misc_task: Optional[asyncio.Task] = None
|
||||
|
||||
def _on_socket_open(self,
|
||||
client: paho_mqtt.Client,
|
||||
userdata: Any,
|
||||
sock: socket.socket
|
||||
) -> None:
|
||||
logging.info("MQTT Socket Opened")
|
||||
self.loop.add_reader(sock, client.loop_read)
|
||||
self.misc_task = self.loop.create_task(self.misc_loop())
|
||||
|
||||
def _on_socket_close(self,
|
||||
client: paho_mqtt.Client,
|
||||
userdata: Any,
|
||||
sock: socket.socket
|
||||
) -> None:
|
||||
logging.info("MQTT Socket Closed")
|
||||
self.loop.remove_reader(sock)
|
||||
if self.misc_task is not None:
|
||||
self.misc_task.cancel()
|
||||
|
||||
def _on_socket_register_write(self,
|
||||
client: paho_mqtt.Client,
|
||||
userdata: Any,
|
||||
sock: socket.socket
|
||||
) -> None:
|
||||
self.loop.add_writer(sock, client.loop_write)
|
||||
|
||||
def _on_socket_unregister_write(self,
|
||||
client: paho_mqtt.Client,
|
||||
userdata: Any,
|
||||
sock: socket.socket
|
||||
) -> None:
|
||||
self.loop.remove_writer(sock)
|
||||
|
||||
async def misc_loop(self) -> None:
|
||||
while self.client.loop_misc() == paho_mqtt.MQTT_ERR_SUCCESS:
|
||||
try:
|
||||
await asyncio.sleep(1)
|
||||
except asyncio.CancelledError:
|
||||
break
|
||||
logging.info("MQTT Misc Loop Complete")
|
||||
|
||||
|
||||
class MQTTClient(APITransport):
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.address: str = config.get('address')
|
||||
self.port: int = config.getint('port', 1883)
|
||||
self.user_name = config.get('username', None)
|
||||
pw_file_path = config.get('password_file', None)
|
||||
self.password: Optional[str] = None
|
||||
if pw_file_path is not None:
|
||||
pw_file = pathlib.Path(pw_file_path).expanduser().absolute()
|
||||
if not pw_file.exists():
|
||||
raise config.error(
|
||||
f"Password file '{pw_file}' does not exist")
|
||||
self.password = pw_file.read_text().strip()
|
||||
protocol = config.get('mqtt_protocol', "v3.1.1")
|
||||
self.protocol = MQTT_PROTOCOLS.get(protocol, None)
|
||||
if self.protocol is None:
|
||||
raise config.error(
|
||||
f"Invalid value '{protocol}' for option 'mqtt_protocol' "
|
||||
"in section [mqtt]. Must be one of "
|
||||
f"{MQTT_PROTOCOLS.values()}")
|
||||
self.instance_name = config.get('instance_name', socket.gethostname())
|
||||
if '+' in self.instance_name or '#' in self.instance_name:
|
||||
raise config.error(
|
||||
"Option 'instance_name' in section [mqtt] cannot "
|
||||
"contain a wildcard.")
|
||||
self.qos = config.getint("default_qos", 0)
|
||||
if self.qos > 2 or self.qos < 0:
|
||||
raise config.error(
|
||||
"Option 'default_qos' in section [mqtt] must be "
|
||||
"between 0 and 2")
|
||||
self.client = paho_mqtt.Client(protocol=self.protocol)
|
||||
self.client.on_connect = self._on_connect
|
||||
self.client.on_message = self._on_message
|
||||
self.client.on_disconnect = self._on_disconnect
|
||||
self.client.on_publish = self._on_publish
|
||||
self.client.on_subscribe = self._on_subscribe
|
||||
self.client.on_unsubscribe = self._on_unsubscribe
|
||||
self.connect_evt: asyncio.Event = asyncio.Event()
|
||||
self.disconnect_evt: Optional[asyncio.Event] = None
|
||||
self.reconnect_task: Optional[asyncio.Task] = None
|
||||
self.subscribed_topics: SubscribedDict = {}
|
||||
self.pending_responses: List[asyncio.Future] = []
|
||||
self.pending_acks: Dict[int, asyncio.Future] = {}
|
||||
|
||||
self.server.register_endpoint(
|
||||
"/server/mqtt/publish", ["POST"],
|
||||
self._handle_publish_request,
|
||||
transports=["http", "websocket"])
|
||||
self.server.register_endpoint(
|
||||
"/server/mqtt/subscribe", ["POST"],
|
||||
self._handle_subscription_request,
|
||||
transports=["http", "websocket"])
|
||||
|
||||
|
||||
# Subscribe to API requests
|
||||
self.json_rpc = JsonRPC(transport="MQTT")
|
||||
self.api_request_topic = f"{self.instance_name}/moonraker/api/request"
|
||||
self.api_resp_topic = f"{self.instance_name}/moonraker/api/response"
|
||||
self.timestamp_deque: Deque = deque(maxlen=20)
|
||||
self.api_qos = config.getint('api_qos', self.qos)
|
||||
if config.getboolean("enable_moonraker_api", True):
|
||||
api_cache = self.server.register_api_transport("mqtt", self)
|
||||
for api_def in api_cache.values():
|
||||
if "mqtt" in api_def.supported_transports:
|
||||
self.register_api_handler(api_def)
|
||||
self.subscribe_topic(self.api_request_topic,
|
||||
self._process_api_request,
|
||||
self.api_qos)
|
||||
logging.info(
|
||||
f"Moonraker API topics - Request: {self.api_request_topic}, "
|
||||
f"Response: {self.api_resp_topic}")
|
||||
|
||||
IOLoop.current().spawn_callback(self._initialize)
|
||||
|
||||
async def _initialize(self) -> None:
|
||||
# We must wait for the IOLoop (asyncio event loop) to start
|
||||
# prior to retreiving it
|
||||
self.helper = AIOHelper(self.client)
|
||||
if self.user_name is not None:
|
||||
self.client.username_pw_set(self.user_name, self.password)
|
||||
retries = 15
|
||||
while retries:
|
||||
try:
|
||||
self.client.connect(self.address, self.port)
|
||||
except ConnectionRefusedError:
|
||||
retries -= 1
|
||||
if retries:
|
||||
logging.info("Unable to connect to MQTT broker, "
|
||||
f"retries remaining: {retries}")
|
||||
await asyncio.sleep(2.)
|
||||
continue
|
||||
self.server.set_failed_component("mqtt")
|
||||
self.server.add_warning(
|
||||
f"MQTT Broker Connection at ({self.address}, {self.port}) "
|
||||
"refused. Check your client and broker configuration.")
|
||||
return
|
||||
break
|
||||
self.client.socket().setsockopt(
|
||||
socket.SOL_SOCKET, socket.SO_SNDBUF, 2048)
|
||||
|
||||
def _on_message(self,
|
||||
client: str,
|
||||
user_data: Any,
|
||||
message: paho_mqtt.MQTTMessage
|
||||
) -> None:
|
||||
topic = message.topic
|
||||
if topic in self.subscribed_topics:
|
||||
cb_hdls = self.subscribed_topics[topic][1]
|
||||
for hdl in cb_hdls:
|
||||
IOLoop.current().spawn_callback(
|
||||
hdl.callback, message.payload) # type: ignore
|
||||
else:
|
||||
logging.debug(
|
||||
f"Unregistered MQTT Topic Received: {topic}, "
|
||||
f"payload: {message.payload.decode()}")
|
||||
|
||||
def _on_connect(self,
|
||||
client: paho_mqtt.Client,
|
||||
user_data: Any,
|
||||
flags: Dict[str, Any],
|
||||
reason_code: Union[int, paho_mqtt.ReasonCodes],
|
||||
properties: Optional[paho_mqtt.Properties] = None
|
||||
) -> None:
|
||||
logging.info("MQTT Client Connected")
|
||||
if reason_code == 0:
|
||||
subs = [(k, v[0]) for k, v in self.subscribed_topics.items()]
|
||||
if subs:
|
||||
res, msg_id = client.subscribe(subs)
|
||||
if msg_id is not None:
|
||||
sub_fut: asyncio.Future = asyncio.Future()
|
||||
topics = list(self.subscribed_topics.keys())
|
||||
sub_fut.add_done_callback(
|
||||
BrokerAckLogger(topics, "subscribe"))
|
||||
self.pending_acks[msg_id] = sub_fut
|
||||
self.connect_evt.set()
|
||||
else:
|
||||
if isinstance(reason_code, int):
|
||||
err_str = paho_mqtt.connack_string(reason_code)
|
||||
else:
|
||||
err_str = reason_code.getName()
|
||||
self.server.set_failed_component("mqtt")
|
||||
self.server.add_warning(f"MQTT Connection Failed: {err_str}")
|
||||
|
||||
def _on_disconnect(self,
|
||||
client: paho_mqtt.Client,
|
||||
user_data: Any,
|
||||
reason_code: int,
|
||||
properties: Optional[paho_mqtt.Properties] = None
|
||||
) -> None:
|
||||
if self.disconnect_evt is not None:
|
||||
self.disconnect_evt.set()
|
||||
elif self.is_connected():
|
||||
# The server connection was dropped, attempt to reconnect
|
||||
logging.info("MQTT Server Disconnected, reason: "
|
||||
f"{paho_mqtt.error_string(reason_code)}")
|
||||
if self.reconnect_task is None:
|
||||
self.reconnect_task = asyncio.create_task(self._do_reconnect())
|
||||
self.connect_evt.clear()
|
||||
|
||||
def _on_publish(self,
|
||||
client: paho_mqtt.Client,
|
||||
user_data: Any,
|
||||
msg_id: int
|
||||
) -> None:
|
||||
pub_fut = self.pending_acks.pop(msg_id, None)
|
||||
if pub_fut is not None and not pub_fut.done():
|
||||
pub_fut.set_result(None)
|
||||
|
||||
def _on_subscribe(self,
|
||||
client: paho_mqtt.Client,
|
||||
user_data: Any,
|
||||
msg_id: int,
|
||||
flex: Union[List[int], List[paho_mqtt.ReasonCodes]],
|
||||
properties: Optional[paho_mqtt.Properties] = None
|
||||
) -> None:
|
||||
sub_fut = self.pending_acks.pop(msg_id, None)
|
||||
if sub_fut is not None and not sub_fut.done():
|
||||
sub_fut.set_result(flex)
|
||||
|
||||
def _on_unsubscribe(self,
|
||||
client: paho_mqtt.Client,
|
||||
user_data: Any,
|
||||
msg_id: int,
|
||||
properties: Optional[paho_mqtt.Properties] = None,
|
||||
reasoncodes: Optional[paho_mqtt.ReasonCodes] = None
|
||||
) -> None:
|
||||
unsub_fut = self.pending_acks.pop(msg_id, None)
|
||||
if unsub_fut is not None and not unsub_fut.done():
|
||||
unsub_fut.set_result(None)
|
||||
|
||||
async def _do_reconnect(self) -> None:
|
||||
logging.info("Attempting MQTT Reconnect")
|
||||
while True:
|
||||
try:
|
||||
await asyncio.sleep(2.)
|
||||
except asyncio.CancelledError:
|
||||
break
|
||||
try:
|
||||
self.client.reconnect()
|
||||
except ConnectionRefusedError:
|
||||
continue
|
||||
self.client.socket().setsockopt(
|
||||
socket.SOL_SOCKET, socket.SO_SNDBUF, 2048)
|
||||
break
|
||||
self.reconnect_task = None
|
||||
|
||||
async def wait_connection(self, timeout: Optional[float] = None) -> bool:
|
||||
try:
|
||||
await asyncio.wait_for(self.connect_evt.wait(), timeout)
|
||||
except asyncio.TimeoutError:
|
||||
return False
|
||||
return True
|
||||
|
||||
def is_connected(self) -> bool:
|
||||
return self.connect_evt.is_set()
|
||||
|
||||
def subscribe_topic(self,
|
||||
topic: str,
|
||||
callback: FlexCallback,
|
||||
qos: Optional[int] = None
|
||||
) -> SubscriptionHandle:
|
||||
if '#' in topic or '+' in topic:
|
||||
raise self.server.error("Wildcards may not be used")
|
||||
qos = qos or self.qos
|
||||
if qos > 2 or qos < 0:
|
||||
raise self.server.error("QOS must be between 0 and 2")
|
||||
hdl = SubscriptionHandle(topic, callback)
|
||||
sub_handles = [hdl]
|
||||
need_sub = True
|
||||
if topic in self.subscribed_topics:
|
||||
prev_qos, sub_handles = self.subscribed_topics[topic]
|
||||
qos = max(qos, prev_qos)
|
||||
sub_handles.append(hdl)
|
||||
need_sub = qos != prev_qos
|
||||
self.subscribed_topics[topic] = (qos, sub_handles)
|
||||
if self.is_connected() and need_sub:
|
||||
res, msg_id = self.client.subscribe(topic, qos)
|
||||
if msg_id is not None:
|
||||
sub_fut: asyncio.Future = asyncio.Future()
|
||||
sub_fut.add_done_callback(
|
||||
BrokerAckLogger([topic], "subscribe"))
|
||||
self.pending_acks[msg_id] = sub_fut
|
||||
return hdl
|
||||
|
||||
def unsubscribe(self, hdl: SubscriptionHandle) -> None:
|
||||
topic = hdl.topic
|
||||
if topic in self.subscribed_topics:
|
||||
sub_hdls = self.subscribed_topics[topic][1]
|
||||
try:
|
||||
sub_hdls.remove(hdl)
|
||||
except Exception:
|
||||
pass
|
||||
if not sub_hdls:
|
||||
del self.subscribed_topics[topic]
|
||||
res, msg_id = self.client.unsubscribe(topic)
|
||||
if msg_id is not None:
|
||||
unsub_fut: asyncio.Future = asyncio.Future()
|
||||
unsub_fut.add_done_callback(
|
||||
BrokerAckLogger([topic], "unsubscribe"))
|
||||
self.pending_acks[msg_id] = unsub_fut
|
||||
|
||||
def publish_topic(self,
|
||||
topic: str,
|
||||
payload: Any = None,
|
||||
qos: Optional[int] = None,
|
||||
retain: bool = False
|
||||
) -> Awaitable[None]:
|
||||
qos = qos or self.qos
|
||||
if qos > 2 or qos < 0:
|
||||
raise self.server.error("QOS must be between 0 and 2")
|
||||
pub_fut: asyncio.Future = asyncio.Future()
|
||||
if isinstance(payload, (dict, list)):
|
||||
try:
|
||||
payload = json.dumps(payload)
|
||||
except json.JSONDecodeError:
|
||||
raise self.server.error(
|
||||
"Dict or List is not json encodable") from None
|
||||
elif isinstance(payload, bool):
|
||||
payload = str(payload).lower()
|
||||
try:
|
||||
msg_info = self.client.publish(topic, payload, qos, retain)
|
||||
if msg_info.is_published():
|
||||
pub_fut.set_result(None)
|
||||
else:
|
||||
if qos == 0:
|
||||
# There is no delivery guarantee for qos == 0, so
|
||||
# it is possible that the on_publish event will
|
||||
# not be called if paho mqtt encounters an error
|
||||
# during publication. Return immediately as
|
||||
# a workaround.
|
||||
if msg_info.rc != paho_mqtt.MQTT_ERR_SUCCESS:
|
||||
err_str = paho_mqtt.error_string(msg_info.rc)
|
||||
pub_fut.set_exception(self.server.error(
|
||||
f"MQTT Publish Error: {err_str}", 503))
|
||||
else:
|
||||
pub_fut.set_result(None)
|
||||
return pub_fut
|
||||
self.pending_acks[msg_info.mid] = pub_fut
|
||||
except ValueError:
|
||||
pub_fut.set_exception(self.server.error(
|
||||
"MQTT Message Queue Full", 529))
|
||||
except Exception as e:
|
||||
pub_fut.set_exception(self.server.error(
|
||||
f"MQTT Publish Error: {e}", 503))
|
||||
return pub_fut
|
||||
|
||||
async def publish_topic_with_response(self,
|
||||
topic: str,
|
||||
response_topic: str,
|
||||
payload: Any = None,
|
||||
qos: Optional[int] = None,
|
||||
retain: bool = False,
|
||||
timeout: Optional[float] = None
|
||||
) -> bytes:
|
||||
qos = qos or self.qos
|
||||
if qos > 2 or qos < 0:
|
||||
raise self.server.error("QOS must be between 0 and 2")
|
||||
resp_fut: asyncio.Future = asyncio.Future()
|
||||
resp_hdl = self.subscribe_topic(
|
||||
response_topic, resp_fut.set_result, qos)
|
||||
self.pending_responses.append(resp_fut)
|
||||
try:
|
||||
await asyncio.wait_for(self.publish_topic(
|
||||
topic, payload, qos, retain), timeout)
|
||||
await asyncio.wait_for(resp_fut, timeout)
|
||||
except asyncio.TimeoutError:
|
||||
logging.info(f"Response to request {topic} timed out")
|
||||
raise self.server.error("MQTT Request Timed Out", 504)
|
||||
finally:
|
||||
try:
|
||||
self.pending_responses.remove(resp_fut)
|
||||
except Exception:
|
||||
pass
|
||||
self.unsubscribe(resp_hdl)
|
||||
return resp_fut.result()
|
||||
|
||||
async def _handle_publish_request(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
topic: str = web_request.get_str("topic")
|
||||
payload: Any = web_request.get("payload", None)
|
||||
qos: int = web_request.get_int("qos", self.qos)
|
||||
retain: bool = web_request.get_boolean("retain", False)
|
||||
timeout: Optional[float] = web_request.get_float('timeout', None)
|
||||
try:
|
||||
await asyncio.wait_for(self.publish_topic(
|
||||
topic, payload, qos, retain), timeout)
|
||||
except asyncio.TimeoutError:
|
||||
raise self.server.error("MQTT Publish Timed Out", 504)
|
||||
return {
|
||||
"topic": topic
|
||||
}
|
||||
|
||||
async def _handle_subscription_request(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
topic: str = web_request.get_str("topic")
|
||||
qos: int = web_request.get_int("qos", self.qos)
|
||||
timeout: Optional[float] = web_request.get_float('timeout', None)
|
||||
resp: asyncio.Future = asyncio.Future()
|
||||
hdl: Optional[SubscriptionHandle] = None
|
||||
try:
|
||||
hdl = self.subscribe_topic(topic, resp.set_result, qos)
|
||||
self.pending_responses.append(resp)
|
||||
await asyncio.wait_for(resp, timeout)
|
||||
ret: bytes = resp.result()
|
||||
except asyncio.TimeoutError:
|
||||
raise self.server.error("MQTT Subscribe Timed Out", 504)
|
||||
finally:
|
||||
try:
|
||||
self.pending_responses.remove(resp)
|
||||
except Exception:
|
||||
pass
|
||||
if hdl is not None:
|
||||
self.unsubscribe(hdl)
|
||||
try:
|
||||
payload = json.loads(ret)
|
||||
except json.JSONDecodeError:
|
||||
payload = ret.decode()
|
||||
return {
|
||||
'topic': topic,
|
||||
'payload': payload
|
||||
}
|
||||
|
||||
async def _process_api_request(self, payload: bytes) -> None:
|
||||
response = await self.json_rpc.dispatch(payload.decode())
|
||||
if response is not None:
|
||||
await self.publish_topic(self.api_resp_topic, response,
|
||||
self.api_qos)
|
||||
|
||||
def register_api_handler(self, api_def: APIDefinition) -> None:
|
||||
if api_def.callback is None:
|
||||
# Remote API, uses RPC to reach out to Klippy
|
||||
mqtt_method = api_def.jrpc_methods[0]
|
||||
rpc_cb = self._generate_remote_callback(api_def.endpoint)
|
||||
self.json_rpc.register_method(mqtt_method, rpc_cb)
|
||||
else:
|
||||
# Local API, uses local callback
|
||||
for mqtt_method, req_method in \
|
||||
zip(api_def.jrpc_methods, api_def.request_methods):
|
||||
rpc_cb = self._generate_local_callback(
|
||||
api_def.endpoint, req_method, api_def.callback)
|
||||
self.json_rpc.register_method(mqtt_method, rpc_cb)
|
||||
logging.info(
|
||||
"Registering MQTT JSON-RPC methods: "
|
||||
f"{', '.join(api_def.jrpc_methods)}")
|
||||
|
||||
def remove_api_handler(self, api_def: APIDefinition) -> None:
|
||||
for jrpc_method in api_def.jrpc_methods:
|
||||
self.json_rpc.remove_method(jrpc_method)
|
||||
|
||||
def _generate_local_callback(self,
|
||||
endpoint: str,
|
||||
request_method: str,
|
||||
callback: Callable[[WebRequest], Coroutine]
|
||||
) -> RPCCallback:
|
||||
async def func(**kwargs) -> Any:
|
||||
self._check_timestamp(kwargs)
|
||||
result = await callback(
|
||||
WebRequest(endpoint, kwargs, request_method))
|
||||
return result
|
||||
return func
|
||||
|
||||
def _generate_remote_callback(self, endpoint: str) -> RPCCallback:
|
||||
async def func(**kwargs) -> Any:
|
||||
self._check_timestamp(kwargs)
|
||||
result = await self.server.make_request(
|
||||
WebRequest(endpoint, kwargs))
|
||||
return result
|
||||
return func
|
||||
|
||||
def _check_timestamp(self, args: Dict[str, Any]) -> None:
|
||||
ts = args.pop("mqtt_timestamp", None)
|
||||
if ts is not None:
|
||||
if ts in self.timestamp_deque:
|
||||
logging.debug("Duplicate MQTT API request received")
|
||||
raise self.server.error(
|
||||
"Duplicate MQTT Request", DUP_API_REQ_CODE)
|
||||
else:
|
||||
self.timestamp_deque.append(ts)
|
||||
|
||||
async def close(self) -> None:
|
||||
if self.reconnect_task is not None:
|
||||
self.reconnect_task.cancel()
|
||||
self.reconnect_task = None
|
||||
if not self.is_connected():
|
||||
return
|
||||
self.disconnect_evt = asyncio.Event()
|
||||
self.client.disconnect()
|
||||
try:
|
||||
await asyncio.wait_for(self.disconnect_evt.wait(), 2.)
|
||||
except asyncio.TimeoutError:
|
||||
logging.info("MQTT Disconnect Timeout")
|
||||
futs = list(self.pending_acks.values())
|
||||
futs.extend(self.pending_responses)
|
||||
for fut in futs:
|
||||
if fut.done():
|
||||
continue
|
||||
fut.set_exception(
|
||||
self.server.error("Moonraker Shutdown", 503))
|
||||
|
||||
|
||||
def load_component(config: ConfigHelper) -> MQTTClient:
|
||||
return MQTTClient(config)
|
||||
@@ -0,0 +1,329 @@
|
||||
# Octoprint API compatibility
|
||||
#
|
||||
# Copyright (C) 2021 Nickolas Grigoriadis <nagrigoriadis@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
import logging
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Dict,
|
||||
List,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from confighelper import ConfigHelper
|
||||
from websockets import WebRequest
|
||||
from . import klippy_apis
|
||||
APIComp = klippy_apis.KlippyAPI
|
||||
|
||||
OCTO_VERSION = '1.5.0'
|
||||
|
||||
|
||||
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: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.software_version = self.server.get_app_args().get(
|
||||
'software_version')
|
||||
|
||||
# Local variables
|
||||
self.klippy_apis: APIComp = self.server.lookup_component('klippy_apis')
|
||||
self.heaters: Dict[str, Dict[str, Any]] = {}
|
||||
self.last_print_stats: Dict[str, Any] = {}
|
||||
|
||||
# Register status update event
|
||||
self.server.register_event_handler(
|
||||
'server:klippy_ready', self._init)
|
||||
self.server.register_event_handler(
|
||||
'server:status_update', self._handle_status_update)
|
||||
|
||||
# Version & Server information
|
||||
self.server.register_endpoint(
|
||||
'/api/version', ['GET'], self._get_version,
|
||||
transports=['http'], wrap_result=False)
|
||||
self.server.register_endpoint(
|
||||
'/api/server', ['GET'], self._get_server,
|
||||
transports=['http'], wrap_result=False)
|
||||
|
||||
# Login, User & Settings
|
||||
self.server.register_endpoint(
|
||||
'/api/login', ['POST'], self._post_login_user,
|
||||
transports=['http'], wrap_result=False)
|
||||
self.server.register_endpoint(
|
||||
'/api/currentuser', ['GET'], self._post_login_user,
|
||||
transports=['http'], wrap_result=False)
|
||||
self.server.register_endpoint(
|
||||
'/api/settings', ['GET'], self._get_settings,
|
||||
transports=['http'], 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,
|
||||
transports=['http'], wrap_result=False)
|
||||
# TODO: start/cancel/restart/pause jobs
|
||||
|
||||
# Printer operations
|
||||
self.server.register_endpoint(
|
||||
'/api/printer', ['GET'], self._get_printer,
|
||||
transports=['http'], wrap_result=False)
|
||||
self.server.register_endpoint(
|
||||
'/api/printer/command', ['POST'], self._post_command,
|
||||
transports=['http'], wrap_result=False)
|
||||
# TODO: head/tool/bed/chamber specific read/issue
|
||||
|
||||
# Printer profiles
|
||||
self.server.register_endpoint(
|
||||
'/api/printerprofiles', ['GET'], self._get_printerprofiles,
|
||||
transports=['http'], wrap_result=False)
|
||||
|
||||
# System
|
||||
# TODO: shutdown/reboot/restart operations
|
||||
|
||||
async def _init(self) -> None:
|
||||
self.heaters = {}
|
||||
# Fetch heaters
|
||||
try:
|
||||
result: Dict[str, Any]
|
||||
sensors: List[str]
|
||||
result = await self.klippy_apis.query_objects({'heaters': None})
|
||||
sensors = result.get('heaters', {}).get('available_sensors', [])
|
||||
except self.server.error as e:
|
||||
logging.info(f'Error Configuring heaters: {e}')
|
||||
sensors = []
|
||||
# subscribe objects
|
||||
sub: Dict[str, Any] = {s: None for s in sensors}
|
||||
sub['print_stats'] = None
|
||||
result = await self.klippy_apis.subscribe_objects(sub)
|
||||
self.last_print_stats = result.get('print_stats', {})
|
||||
if sensors:
|
||||
self.heaters = {name: result.get(name, {}) for name in sensors}
|
||||
|
||||
def _handle_status_update(self, status: Dict[str, Any]) -> None:
|
||||
if 'print_stats' in status:
|
||||
self.last_print_stats.update(status['print_stats'])
|
||||
for heater_name, data in self.heaters.items():
|
||||
if heater_name in status:
|
||||
data.update(status[heater_name])
|
||||
|
||||
def printer_state(self) -> str:
|
||||
klippy_state = self.server.get_klippy_state()
|
||||
if klippy_state in ["disconnected", "startup"]:
|
||||
return 'Offline'
|
||||
elif klippy_state != 'ready':
|
||||
return 'Error'
|
||||
return {
|
||||
'standby': 'Operational',
|
||||
'printing': 'Printing',
|
||||
'paused': 'Paused',
|
||||
'complete': 'Operational'
|
||||
}.get(self.last_print_stats.get('state', 'standby'), 'Error')
|
||||
|
||||
def printer_temps(self) -> Dict[str, Any]:
|
||||
temps: Dict[str, Any] = {}
|
||||
for heater, data in self.heaters.items():
|
||||
name = 'bed'
|
||||
if heater.startswith('extruder'):
|
||||
try:
|
||||
tool_no = int(heater[8:])
|
||||
except ValueError:
|
||||
tool_no = 0
|
||||
name = f'tool{tool_no}'
|
||||
elif heater != "heater_bed":
|
||||
continue
|
||||
temps[name] = {
|
||||
'actual': round(data.get('temperature', 0.), 2),
|
||||
'offset': 0,
|
||||
'target': data.get('target', 0.),
|
||||
}
|
||||
return temps
|
||||
|
||||
async def _get_version(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, str]:
|
||||
"""
|
||||
Version information
|
||||
"""
|
||||
return {
|
||||
'server': OCTO_VERSION,
|
||||
'api': '0.1',
|
||||
'text': f'OctoPrint (Moonraker {self.software_version})',
|
||||
}
|
||||
|
||||
async def _get_server(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Server status
|
||||
"""
|
||||
klippy_state = self.server.get_klippy_state()
|
||||
return {
|
||||
'server': OCTO_VERSION,
|
||||
'safemode': (
|
||||
None if klippy_state == 'ready' else 'settings')
|
||||
}
|
||||
|
||||
async def _post_login_user(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
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: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
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: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
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': self.printer_state()
|
||||
}
|
||||
|
||||
async def _get_printer(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
Get Printer status
|
||||
"""
|
||||
state = self.printer_state()
|
||||
return {
|
||||
'temperature': 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: WebRequest
|
||||
) -> Dict:
|
||||
"""
|
||||
Request to run some gcode command
|
||||
"""
|
||||
commands: List[str] = 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: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
"""
|
||||
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_component(config: ConfigHelper) -> OctoprintCompat:
|
||||
return OctoprintCompat(config)
|
||||
@@ -3,18 +3,39 @@
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
import serial
|
||||
import os
|
||||
import time
|
||||
import json
|
||||
import errno
|
||||
import logging
|
||||
import asyncio
|
||||
from collections import deque
|
||||
from utils import ServerError
|
||||
from tornado import gen
|
||||
from tornado.ioloop import IOLoop
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Deque,
|
||||
Any,
|
||||
Tuple,
|
||||
Optional,
|
||||
Dict,
|
||||
List,
|
||||
Callable,
|
||||
Coroutine,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from confighelper import ConfigHelper
|
||||
from . import klippy_apis
|
||||
from .file_manager import file_manager
|
||||
APIComp = klippy_apis.KlippyAPI
|
||||
FMComp = file_manager.FileManager
|
||||
FlexCallback = Callable[..., Optional[Coroutine]]
|
||||
|
||||
MIN_EST_TIME = 10.
|
||||
INITIALIZE_TIMEOUT = 10.
|
||||
|
||||
@@ -25,26 +46,31 @@ class PanelDueError(ServerError):
|
||||
RESTART_GCODES = ["RESTART", "FIRMWARE_RESTART"]
|
||||
|
||||
class SerialConnection:
|
||||
def __init__(self, config, paneldue):
|
||||
def __init__(self,
|
||||
config: ConfigHelper,
|
||||
paneldue: PanelDue
|
||||
) -> None:
|
||||
self.ioloop = IOLoop.current()
|
||||
self.paneldue = paneldue
|
||||
self.port = config.get('serial')
|
||||
self.port: str = config.get('serial')
|
||||
self.baud = config.getint('baud', 57600)
|
||||
self.partial_input = b""
|
||||
self.ser = self.fd = None
|
||||
self.connected = False
|
||||
self.send_busy = False
|
||||
self.send_buffer = b""
|
||||
self.attempting_connect = True
|
||||
self.partial_input: bytes = b""
|
||||
self.ser: Optional[serial.Serial] = None
|
||||
self.fd: Optional[int] = None
|
||||
self.connected: bool = False
|
||||
self.send_busy: bool = False
|
||||
self.send_buffer: bytes = b""
|
||||
self.attempting_connect: bool = True
|
||||
self.ioloop.spawn_callback(self._connect)
|
||||
|
||||
def disconnect(self, reconnect=False):
|
||||
def disconnect(self, reconnect: bool = False) -> None:
|
||||
if self.connected:
|
||||
if self.fd is not None:
|
||||
self.ioloop.remove_handler(self.fd)
|
||||
self.fd = None
|
||||
self.connected = False
|
||||
self.ser.close()
|
||||
if self.ser is not None:
|
||||
self.ser.close()
|
||||
self.ser = None
|
||||
self.partial_input = b""
|
||||
self.send_buffer = b""
|
||||
@@ -52,9 +78,9 @@ class SerialConnection:
|
||||
logging.info("PanelDue Disconnected")
|
||||
if reconnect and not self.attempting_connect:
|
||||
self.attempting_connect = True
|
||||
self.ioloop.call_later(1., self._connect)
|
||||
self.ioloop.call_later(1., self._connect) # type: ignore
|
||||
|
||||
async def _connect(self):
|
||||
async def _connect(self) -> None:
|
||||
start_time = connect_time = time.time()
|
||||
while not self.connected:
|
||||
if connect_time > start_time + 30.:
|
||||
@@ -73,14 +99,15 @@ class SerialConnection:
|
||||
connect_time += time.time()
|
||||
continue
|
||||
self.fd = self.ser.fileno()
|
||||
os.set_blocking(self.fd, False)
|
||||
self.ioloop.add_handler(
|
||||
self.fd, self._handle_incoming, IOLoop.READ | IOLoop.ERROR)
|
||||
fd = self.fd = self.ser.fileno()
|
||||
os.set_blocking(fd, False)
|
||||
self.ioloop.add_handler(fd, self._handle_incoming,
|
||||
IOLoop.READ | IOLoop.ERROR)
|
||||
self.connected = True
|
||||
logging.info("PanelDue Connected")
|
||||
self.attempting_connect = False
|
||||
|
||||
def _handle_incoming(self, fd, events):
|
||||
def _handle_incoming(self, fd: int, events: int) -> None:
|
||||
if events & IOLoop.ERROR:
|
||||
logging.info("PanelDue Connection Error")
|
||||
self.disconnect(reconnect=True)
|
||||
@@ -104,24 +131,27 @@ class SerialConnection:
|
||||
self.partial_input = lines.pop()
|
||||
for line in lines:
|
||||
try:
|
||||
line = line.strip().decode('utf-8', 'ignore')
|
||||
self.paneldue.process_line(line)
|
||||
decoded_line = line.strip().decode('utf-8', 'ignore')
|
||||
self.paneldue.process_line(decoded_line)
|
||||
except ServerError:
|
||||
logging.exception(
|
||||
f"GCode Processing Error: {line}")
|
||||
f"GCode Processing Error: {decoded_line}")
|
||||
self.paneldue.handle_gcode_response(
|
||||
f"!! GCode Processing Error: {line}")
|
||||
f"!! GCode Processing Error: {decoded_line}")
|
||||
except Exception:
|
||||
logging.exception("Error during gcode processing")
|
||||
|
||||
def send(self, data):
|
||||
def send(self, data: bytes) -> None:
|
||||
self.send_buffer += data
|
||||
if not self.send_busy:
|
||||
self.send_busy = True
|
||||
self.ioloop.spawn_callback(self._do_send)
|
||||
|
||||
async def _do_send(self):
|
||||
async def _do_send(self) -> None:
|
||||
assert self.fd is not None
|
||||
while self.send_buffer:
|
||||
if not self.connected:
|
||||
break
|
||||
try:
|
||||
sent = os.write(self.fd, self.send_buffer)
|
||||
except os.error as e:
|
||||
@@ -140,42 +170,44 @@ class SerialConnection:
|
||||
self.send_busy = False
|
||||
|
||||
class PanelDue:
|
||||
def __init__(self, config):
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.ioloop = IOLoop.current()
|
||||
self.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"
|
||||
self.file_manager: FMComp = \
|
||||
self.server.lookup_component('file_manager')
|
||||
self.klippy_apis: APIComp = \
|
||||
self.server.lookup_component('klippy_apis')
|
||||
self.kinematics: str = "none"
|
||||
self.machine_name = config.get('machine_name', "Klipper")
|
||||
self.firmware_name = "Repetier | Klipper"
|
||||
self.last_message = None
|
||||
self.last_gcode_response = None
|
||||
self.current_file = ""
|
||||
self.file_metadata = {}
|
||||
self.firmware_name: str = "Repetier | Klipper"
|
||||
self.last_message: Optional[str] = None
|
||||
self.last_gcode_response: Optional[str] = None
|
||||
self.current_file: str = ""
|
||||
self.file_metadata: Dict[str, Any] = {}
|
||||
self.enable_checksum = config.getboolean('enable_checksum', True)
|
||||
self.debug_queue = deque(maxlen=100)
|
||||
self.debug_queue: Deque[str] = deque(maxlen=100)
|
||||
|
||||
# Initialize tracked state.
|
||||
self.printer_state = {
|
||||
self.printer_state: Dict[str, Dict[str, Any]] = {
|
||||
'gcode_move': {}, 'toolhead': {}, 'virtual_sdcard': {},
|
||||
'fan': {}, 'display_status': {}, 'print_stats': {},
|
||||
'idle_timeout': {}, 'gcode_macro PANELDUE_BEEP': {}}
|
||||
self.extruder_count = 0
|
||||
self.heaters = []
|
||||
self.is_ready = False
|
||||
self.is_shutdown = False
|
||||
self.initialized = False
|
||||
self.cq_busy = self.gq_busy = False
|
||||
self.command_queue = []
|
||||
self.gc_queue = []
|
||||
self.last_printer_state = 'O'
|
||||
self.last_update_time = 0.
|
||||
self.extruder_count: int = 0
|
||||
self.heaters: List[str] = []
|
||||
self.is_ready: bool = False
|
||||
self.is_shutdown: bool = False
|
||||
self.initialized: bool = False
|
||||
self.cq_busy: bool = False
|
||||
self.gq_busy: bool = False
|
||||
self.command_queue: List[Tuple[FlexCallback, Any, Any]] = []
|
||||
self.gc_queue: List[str] = []
|
||||
self.last_printer_state: str = 'O'
|
||||
self.last_update_time: float = 0.
|
||||
|
||||
# Set up macros
|
||||
self.confirmed_gcode = ""
|
||||
self.mbox_sequence = 0
|
||||
self.available_macros = {}
|
||||
self.confirmed_gcode: str = ""
|
||||
self.mbox_sequence: int = 0
|
||||
self.available_macros: Dict[str, str] = {}
|
||||
self.confirmed_macros = {
|
||||
"RESTART": "RESTART",
|
||||
"FIRMWARE_RESTART": "FIRMWARE_RESTART"}
|
||||
@@ -183,18 +215,19 @@ class PanelDue:
|
||||
if macros is not None:
|
||||
# The macro's configuration name is the key, whereas the full
|
||||
# command is the value
|
||||
macros = [m for m in macros.split('\n') if m.strip()]
|
||||
self.available_macros = {m.split()[0]: m for m in macros}
|
||||
macro_list = [m for m in macros.split('\n') if m.strip()]
|
||||
self.available_macros = {m.split()[0]: m for m in macro_list}
|
||||
conf_macros = config.get('confirmed_macros', None)
|
||||
if conf_macros is not None:
|
||||
# The macro's configuration name is the key, whereas the full
|
||||
# command is the value
|
||||
conf_macros = [m for m in conf_macros.split('\n') if m.strip()]
|
||||
self.confirmed_macros = {m.split()[0]: m for m in conf_macros}
|
||||
macro_list = [m for m in conf_macros.split('\n') if m.strip()]
|
||||
self.confirmed_macros = {m.split()[0]: m for m in macro_list}
|
||||
self.available_macros.update(self.confirmed_macros)
|
||||
|
||||
ntkeys = config.get('non_trivial_keys', "Klipper state")
|
||||
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
|
||||
@@ -214,7 +247,7 @@ class PanelDue:
|
||||
|
||||
# These commands are directly executued on the server and do not to
|
||||
# make a request to Klippy
|
||||
self.direct_gcodes = {
|
||||
self.direct_gcodes: Dict[str, FlexCallback] = {
|
||||
'M20': self._run_paneldue_M20,
|
||||
'M30': self._run_paneldue_M30,
|
||||
'M36': self._run_paneldue_M36,
|
||||
@@ -223,7 +256,7 @@ class PanelDue:
|
||||
|
||||
# These gcodes require special parsing or handling prior to being
|
||||
# sent via Klippy's "gcode/script" api command.
|
||||
self.special_gcodes = {
|
||||
self.special_gcodes: Dict[str, Callable[[List[str]], str]] = {
|
||||
'M0': lambda args: "CANCEL_PRINT",
|
||||
'M23': self._prepare_M23,
|
||||
'M24': lambda args: "RESUME",
|
||||
@@ -237,7 +270,7 @@ class PanelDue:
|
||||
'M999': lambda args: "FIRMWARE_RESTART"
|
||||
}
|
||||
|
||||
async def _process_klippy_ready(self):
|
||||
async def _process_klippy_ready(self) -> None:
|
||||
# Request "info" and "configfile" status
|
||||
retries = 10
|
||||
printer_info = cfg_status = {}
|
||||
@@ -257,8 +290,9 @@ class PanelDue:
|
||||
|
||||
self.firmware_name = "Repetier | Klipper " + \
|
||||
printer_info['software_version']
|
||||
config = cfg_status.get('configfile', {}).get('config', {})
|
||||
printer_cfg = config.get('printer', {})
|
||||
config: Dict[str, Any] = cfg_status.get(
|
||||
'configfile', {}).get('config', {})
|
||||
printer_cfg: Dict[str, Any] = config.get('printer', {})
|
||||
self.kinematics = printer_cfg.get('kinematics', "none")
|
||||
|
||||
logging.info(
|
||||
@@ -286,6 +320,7 @@ class PanelDue:
|
||||
self.heaters.append(cfg)
|
||||
sub_args[cfg] = None
|
||||
try:
|
||||
status: Dict[str, Any]
|
||||
status = await self.klippy_apis.subscribe_objects(sub_args)
|
||||
except self.server.error:
|
||||
logging.exception("Unable to complete subscription request")
|
||||
@@ -294,28 +329,28 @@ class PanelDue:
|
||||
self.is_shutdown = False
|
||||
self.is_ready = True
|
||||
|
||||
def _process_klippy_shutdown(self):
|
||||
def _process_klippy_shutdown(self) -> None:
|
||||
self.is_shutdown = True
|
||||
|
||||
def _process_klippy_disconnect(self):
|
||||
def _process_klippy_disconnect(self) -> None:
|
||||
# Tell the PD that the printer is "off"
|
||||
self.write_response({'status': 'O'})
|
||||
self.last_printer_state = 'O'
|
||||
self.is_shutdown = self.is_shutdown = False
|
||||
|
||||
def handle_status_update(self, status):
|
||||
def handle_status_update(self, status: Dict[str, Any]) -> None:
|
||||
for obj, items in status.items():
|
||||
if obj in self.printer_state:
|
||||
self.printer_state[obj].update(items)
|
||||
else:
|
||||
self.printer_state[obj] = items
|
||||
|
||||
def paneldue_beep(self, frequency, duration):
|
||||
def paneldue_beep(self, frequency: int, duration: float) -> None:
|
||||
duration = int(duration * 1000.)
|
||||
self.write_response(
|
||||
{'beep_freq': frequency, 'beep_length': duration})
|
||||
|
||||
def process_line(self, line):
|
||||
def process_line(self, line: str) -> None:
|
||||
self.debug_queue.append(line)
|
||||
# If we find M112 in the line then skip verification
|
||||
if "M112" in line.upper():
|
||||
@@ -326,7 +361,7 @@ class PanelDue:
|
||||
# Get line number
|
||||
line_index = line.find(' ')
|
||||
try:
|
||||
line_no = int(line[1:line_index])
|
||||
line_no: Optional[int] = int(line[1:line_index])
|
||||
except Exception:
|
||||
line_index = -1
|
||||
line_no = None
|
||||
@@ -362,12 +397,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 = {}
|
||||
params: Dict[str, Any] = {}
|
||||
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,27 +417,27 @@ 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
|
||||
|
||||
# Prepare GCodes that require special handling
|
||||
if cmd in self.special_gcodes:
|
||||
func = self.special_gcodes[cmd]
|
||||
script = func(parts[1:])
|
||||
sgc_func = self.special_gcodes[cmd]
|
||||
script = sgc_func(parts[1:])
|
||||
|
||||
if not script:
|
||||
return
|
||||
self.queue_gcode(script)
|
||||
|
||||
def queue_gcode(self, script):
|
||||
def queue_gcode(self, script: str) -> None:
|
||||
self.gc_queue.append(script)
|
||||
if not self.gq_busy:
|
||||
self.gq_busy = True
|
||||
self.ioloop.spawn_callback(self._process_gcode_queue)
|
||||
|
||||
async def _process_gcode_queue(self):
|
||||
async def _process_gcode_queue(self) -> None:
|
||||
while self.gc_queue:
|
||||
script = self.gc_queue.pop(0)
|
||||
try:
|
||||
@@ -410,24 +451,24 @@ class PanelDue:
|
||||
logging.exception(msg)
|
||||
self.gq_busy = False
|
||||
|
||||
def queue_command(self, cmd, *args, **kwargs):
|
||||
def queue_command(self, cmd: FlexCallback, *args, **kwargs) -> None:
|
||||
self.command_queue.append((cmd, args, kwargs))
|
||||
if not self.cq_busy:
|
||||
self.cq_busy = True
|
||||
self.ioloop.spawn_callback(self._process_command_queue)
|
||||
|
||||
async def _process_command_queue(self):
|
||||
async def _process_command_queue(self) -> None:
|
||||
while self.command_queue:
|
||||
cmd, args, kwargs = self.command_queue.pop(0)
|
||||
try:
|
||||
ret = cmd(*args, **kwargs)
|
||||
if asyncio.iscoroutine(ret):
|
||||
if ret is not None:
|
||||
await ret
|
||||
except Exception:
|
||||
logging.exception("Error processing command")
|
||||
self.cq_busy = False
|
||||
|
||||
def _clean_filename(self, filename):
|
||||
def _clean_filename(self, filename: str) -> str:
|
||||
# Remove quotes and whitespace
|
||||
filename.strip(" \"\t\n")
|
||||
# Remove drive number
|
||||
@@ -445,17 +486,17 @@ class PanelDue:
|
||||
filename = "/" + filename
|
||||
return filename
|
||||
|
||||
def _prepare_M23(self, args):
|
||||
def _prepare_M23(self, args: List[str]) -> str:
|
||||
filename = self._clean_filename(args[0])
|
||||
return f"M23 {filename}"
|
||||
|
||||
def _prepare_M32(self, args):
|
||||
def _prepare_M32(self, args: List[str]) -> str:
|
||||
filename = self._clean_filename(args[0])
|
||||
# Escape existing double quotes in the file name
|
||||
filename = filename.replace("\"", "\\\"")
|
||||
return f"SDCARD_PRINT_FILE FILENAME=\"{filename}\""
|
||||
|
||||
def _prepare_M98(self, args):
|
||||
def _prepare_M98(self, args: List[str]) -> str:
|
||||
macro = args[0][1:].strip(" \"\t\n")
|
||||
name_start = macro.rfind('/') + 1
|
||||
macro = macro[name_start:]
|
||||
@@ -467,12 +508,12 @@ class PanelDue:
|
||||
cmd = ""
|
||||
return cmd
|
||||
|
||||
def _prepare_M290(self, args):
|
||||
def _prepare_M290(self, args: List[str]) -> str:
|
||||
# args should in in the format Z0.02
|
||||
offset = args[0][1:].strip()
|
||||
return f"SET_GCODE_OFFSET Z_ADJUST={offset} MOVE=1"
|
||||
|
||||
def _prepare_M292(self, args):
|
||||
def _prepare_M292(self, args: List[str]) -> str:
|
||||
p_val = int(args[0][1])
|
||||
if p_val == 0:
|
||||
cmd = self.confirmed_gcode
|
||||
@@ -480,13 +521,13 @@ class PanelDue:
|
||||
return cmd
|
||||
return ""
|
||||
|
||||
def _create_confirmation(self, name, gcode):
|
||||
def _create_confirmation(self, name: str, gcode: str) -> None:
|
||||
self.mbox_sequence += 1
|
||||
self.confirmed_gcode = gcode
|
||||
title = "Confirmation Dialog"
|
||||
msg = f"Please confirm your intent to run {name}." \
|
||||
" Press OK to continue, or CANCEL to abort."
|
||||
mbox = {}
|
||||
mbox: Dict[str, Any] = {}
|
||||
mbox['msgBox.mode'] = 3
|
||||
mbox['msgBox.msg'] = msg
|
||||
mbox['msgBox.seq'] = self.mbox_sequence
|
||||
@@ -496,7 +537,7 @@ class PanelDue:
|
||||
logging.debug(f"Creating PanelDue Confirmation: {mbox}")
|
||||
self.write_response(mbox)
|
||||
|
||||
def handle_gcode_response(self, response):
|
||||
def handle_gcode_response(self, response: str) -> None:
|
||||
# Only queue up "non-trivial" gcode responses. At the
|
||||
# moment we'll handle state changes and errors
|
||||
if "Klipper state" in response \
|
||||
@@ -508,11 +549,11 @@ class PanelDue:
|
||||
self.last_gcode_response = response
|
||||
return
|
||||
|
||||
def write_response(self, response):
|
||||
def write_response(self, response: Dict[str, Any]) -> None:
|
||||
byte_resp = json.dumps(response) + "\r\n"
|
||||
self.ser_conn.send(byte_resp.encode())
|
||||
|
||||
def _get_printer_status(self):
|
||||
def _get_printer_status(self) -> str:
|
||||
# PanelDue States applicable to Klipper:
|
||||
# I = idle, P = printing from SD, S = stopped (shutdown),
|
||||
# C = starting up (not ready), A = paused, D = pausing,
|
||||
@@ -521,6 +562,7 @@ class PanelDue:
|
||||
return 'S'
|
||||
|
||||
printer_state = self.printer_state
|
||||
sd_state: str
|
||||
sd_state = printer_state['print_stats'].get('state', "standby")
|
||||
if sd_state == "printing":
|
||||
if self.last_printer_state == 'A':
|
||||
@@ -540,8 +582,11 @@ class PanelDue:
|
||||
|
||||
return 'I'
|
||||
|
||||
def _run_paneldue_M408(self, arg_r=None, arg_s=1):
|
||||
response = {}
|
||||
def _run_paneldue_M408(self,
|
||||
arg_r: Optional[int] = None,
|
||||
arg_s: int = 1
|
||||
) -> None:
|
||||
response: Dict[str, Any] = {}
|
||||
sequence = arg_r
|
||||
response_type = arg_s
|
||||
|
||||
@@ -579,6 +624,9 @@ class PanelDue:
|
||||
'homing_origin', [0., 0., 0., 0.])[2], 3)
|
||||
|
||||
# Current position
|
||||
pos: List[float]
|
||||
homed_pos: str
|
||||
sfactor: float
|
||||
pos = p_state['toolhead'].get('position', [0., 0., 0., 0.])
|
||||
response['pos'] = [round(p, 2) for p in pos[:3]]
|
||||
homed_pos = p_state['toolhead'].get('homed_axes', "")
|
||||
@@ -589,38 +637,41 @@ class PanelDue:
|
||||
# Print Progress Tracking
|
||||
sd_status = p_state['virtual_sdcard']
|
||||
print_stats = p_state['print_stats']
|
||||
fname = print_stats.get('filename', "")
|
||||
sd_print_state = print_stats.get('state')
|
||||
fname: str = print_stats.get('filename', "")
|
||||
sd_print_state: Optional[str] = print_stats.get('state')
|
||||
if sd_print_state in ['printing', 'paused']:
|
||||
# We know a file has been loaded, initialize metadata
|
||||
if self.current_file != fname:
|
||||
self.current_file = fname
|
||||
self.file_metadata = self.file_manager.get_file_metadata(fname)
|
||||
progress = sd_status.get('progress', 0)
|
||||
progress: float = sd_status.get('progress', 0)
|
||||
# progress and print tracking
|
||||
if progress:
|
||||
response['fraction_printed'] = round(progress, 3)
|
||||
est_time = self.file_metadata.get('estimated_time', 0)
|
||||
est_time: float = self.file_metadata.get('estimated_time', 0)
|
||||
if est_time > MIN_EST_TIME:
|
||||
# file read estimate
|
||||
times_left = [int(est_time - est_time * progress)]
|
||||
# filament estimate
|
||||
est_total_fil: Optional[float]
|
||||
est_total_fil = self.file_metadata.get('filament_total')
|
||||
if est_total_fil:
|
||||
cur_filament = print_stats.get('filament_used', 0.)
|
||||
cur_filament: float = print_stats.get(
|
||||
'filament_used', 0.)
|
||||
fpct = min(1., cur_filament / est_total_fil)
|
||||
times_left.append(int(est_time - est_time * fpct))
|
||||
# object height estimate
|
||||
obj_height: Optional[float]
|
||||
obj_height = self.file_metadata.get('object_height')
|
||||
if obj_height:
|
||||
cur_height = p_state['gcode_move'].get(
|
||||
cur_height: float = p_state['gcode_move'].get(
|
||||
'gcode_position', [0., 0., 0., 0.])[2]
|
||||
hpct = min(1., cur_height / obj_height)
|
||||
times_left.append(int(est_time - est_time * hpct))
|
||||
else:
|
||||
# The estimated time is not in the metadata, however we
|
||||
# can still provide an estimate based on file progress
|
||||
duration = print_stats.get('print_duration', 0.)
|
||||
duration: float = print_stats.get('print_duration', 0.)
|
||||
times_left = [int(duration / progress - duration)]
|
||||
response['timesLeft'] = times_left
|
||||
else:
|
||||
@@ -628,11 +679,12 @@ class PanelDue:
|
||||
self.current_file = ""
|
||||
self.file_metadata = {}
|
||||
|
||||
fan_speed = p_state['fan'].get('speed')
|
||||
fan_speed: Optional[float] = p_state['fan'].get('speed')
|
||||
if fan_speed is not None:
|
||||
response['fanPercent'] = [round(fan_speed * 100, 1)]
|
||||
|
||||
if self.extruder_count > 0:
|
||||
extruder_name: Optional[str]
|
||||
extruder_name = p_state['toolhead'].get('extruder')
|
||||
if extruder_name is not None:
|
||||
tool = 0
|
||||
@@ -641,12 +693,12 @@ class PanelDue:
|
||||
response['tool'] = tool
|
||||
|
||||
# Report Heater Status
|
||||
efactor = round(p_state['gcode_move'].get(
|
||||
efactor: float = round(p_state['gcode_move'].get(
|
||||
'extrude_factor', 1.) * 100., 2)
|
||||
|
||||
for name in self.heaters:
|
||||
temp = round(p_state[name].get('temperature', 0.0), 1)
|
||||
target = round(p_state[name].get('target', 0.0), 1)
|
||||
temp: float = round(p_state[name].get('temperature', 0.0), 1)
|
||||
target: float = round(p_state[name].get('target', 0.0), 1)
|
||||
response.setdefault('heaters', []).append(temp)
|
||||
response.setdefault('active', []).append(target)
|
||||
response.setdefault('standby', []).append(target)
|
||||
@@ -656,7 +708,7 @@ class PanelDue:
|
||||
response.setdefault('extr', []).append(round(pos[3], 2))
|
||||
|
||||
# Display message (via M117)
|
||||
msg = p_state['display_status'].get('message')
|
||||
msg: str = p_state['display_status'].get('message', "")
|
||||
if msg and msg != self.last_message:
|
||||
response['message'] = msg
|
||||
# reset the message so it only shows once. The paneldue
|
||||
@@ -665,7 +717,7 @@ class PanelDue:
|
||||
self.last_message = msg
|
||||
self.write_response(response)
|
||||
|
||||
def _run_paneldue_M20(self, arg_p, arg_s=0):
|
||||
def _run_paneldue_M20(self, arg_p: str, arg_s: int = 0) -> None:
|
||||
response_type = arg_s
|
||||
if response_type != 2:
|
||||
logging.info(
|
||||
@@ -681,7 +733,7 @@ class PanelDue:
|
||||
# ie. "0:/"
|
||||
if path.startswith("0:/"):
|
||||
path = path[2:]
|
||||
response = {'dir': path}
|
||||
response: Dict[str, Any] = {'dir': path}
|
||||
response['files'] = []
|
||||
|
||||
if path == "/macros":
|
||||
@@ -705,7 +757,7 @@ class PanelDue:
|
||||
response['files'] = flist
|
||||
self.write_response(response)
|
||||
|
||||
async def _run_paneldue_M30(self, arg_p=None):
|
||||
async def _run_paneldue_M30(self, arg_p: str = "") -> None:
|
||||
# Delete a file. Clean up the file name and make sure
|
||||
# it is relative to the "gcodes" root.
|
||||
path = arg_p
|
||||
@@ -719,9 +771,9 @@ class PanelDue:
|
||||
path = "gcodes/" + path
|
||||
await self.file_manager.delete_file(path)
|
||||
|
||||
def _run_paneldue_M36(self, arg_p=None):
|
||||
response = {}
|
||||
filename = arg_p
|
||||
def _run_paneldue_M36(self, arg_p: Optional[str] = None) -> None:
|
||||
response: Dict[str, Any] = {}
|
||||
filename: Optional[str] = arg_p
|
||||
sd_status = self.printer_state.get('virtual_sdcard', {})
|
||||
print_stats = self.printer_state.get('print_stats', {})
|
||||
if filename is None:
|
||||
@@ -743,40 +795,43 @@ 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
|
||||
|
||||
metadata = self.file_manager.get_file_metadata(filename)
|
||||
metadata: Dict[str, Any] = \
|
||||
self.file_manager.get_file_metadata(filename)
|
||||
if metadata:
|
||||
response['err'] = 0
|
||||
response['size'] = metadata['size']
|
||||
# workaround for PanelDue replacing the first "T" found
|
||||
response['lastModified'] = "T" + time.ctime(metadata['modified'])
|
||||
slicer = metadata.get('slicer')
|
||||
slicer: Optional[str] = metadata.get('slicer')
|
||||
if slicer is not None:
|
||||
response['generatedBy'] = slicer
|
||||
height = metadata.get('object_height')
|
||||
height: Optional[float] = metadata.get('object_height')
|
||||
if height is not None:
|
||||
response['height'] = round(height, 2)
|
||||
layer_height = metadata.get('layer_height')
|
||||
layer_height: Optional[float] = metadata.get('layer_height')
|
||||
if layer_height is not None:
|
||||
response['layerHeight'] = round(layer_height, 2)
|
||||
filament = metadata.get('filament_total')
|
||||
filament: Optional[float] = metadata.get('filament_total')
|
||||
if filament is not None:
|
||||
response['filament'] = [round(filament, 1)]
|
||||
est_time = metadata.get('estimated_time')
|
||||
est_time: Optional[float] = metadata.get('estimated_time')
|
||||
if est_time is not None:
|
||||
response['printTime'] = int(est_time + .5)
|
||||
else:
|
||||
response['err'] = 1
|
||||
self.write_response(response)
|
||||
|
||||
def close(self):
|
||||
def close(self) -> None:
|
||||
self.ser_conn.disconnect()
|
||||
msg = "\nPanelDue GCode Dump:"
|
||||
for i, gc in enumerate(self.debug_queue):
|
||||
msg += f"\nSequence {i}: {gc}"
|
||||
logging.debug(msg)
|
||||
|
||||
def load_plugin(config):
|
||||
def load_component(config: ConfigHelper) -> PanelDue:
|
||||
return PanelDue(config)
|
||||
@@ -0,0 +1,761 @@
|
||||
# Raspberry Pi Power Control
|
||||
#
|
||||
# Copyright (C) 2020 Jordan Ruthe <jordanruthe@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
import os
|
||||
import sys
|
||||
import logging
|
||||
import json
|
||||
import struct
|
||||
import socket
|
||||
from tornado.ioloop import IOLoop
|
||||
from tornado.iostream import IOStream
|
||||
from tornado.locks import Lock
|
||||
from tornado.httpclient import AsyncHTTPClient
|
||||
from tornado.escape import json_decode
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Type,
|
||||
List,
|
||||
Any,
|
||||
Optional,
|
||||
Dict,
|
||||
Coroutine,
|
||||
Tuple,
|
||||
Union,
|
||||
)
|
||||
|
||||
# Special handling for gpiod import
|
||||
HAS_GPIOD = True
|
||||
DIST_PATH = "/usr/lib/python3/dist-packages"
|
||||
if os.path.exists(DIST_PATH):
|
||||
sys.path.insert(0, DIST_PATH)
|
||||
try:
|
||||
import gpiod
|
||||
except ImportError:
|
||||
HAS_GPIOD = False
|
||||
sys.path.pop(0)
|
||||
else:
|
||||
HAS_GPIOD = False
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from confighelper import ConfigHelper
|
||||
from websockets import WebRequest
|
||||
from . import klippy_apis
|
||||
APIComp = klippy_apis.KlippyAPI
|
||||
|
||||
class PrinterPower:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
if not HAS_GPIOD:
|
||||
self.server.add_warning(
|
||||
"Unable to load gpiod library, GPIO power "
|
||||
"devices will not be loaded")
|
||||
self.chip_factory = GpioChipFactory()
|
||||
self.devices: Dict[str, PowerDevice] = {}
|
||||
prefix_sections = config.get_prefix_sections("power")
|
||||
logging.info(f"Power component loading devices: {prefix_sections}")
|
||||
dev_types = {
|
||||
"gpio": GpioDevice,
|
||||
"tplink_smartplug": TPLinkSmartPlug,
|
||||
"tasmota": Tasmota,
|
||||
"shelly": Shelly,
|
||||
"homeseer": HomeSeer,
|
||||
"homeassistant": HomeAssistant,
|
||||
"loxonev1": Loxonev1
|
||||
}
|
||||
try:
|
||||
for section in prefix_sections:
|
||||
cfg = config[section]
|
||||
dev_type: str = cfg.get("type")
|
||||
dev_class: Optional[Type[PowerDevice]]
|
||||
dev_class = dev_types.get(dev_type)
|
||||
if dev_class is None:
|
||||
raise config.error(f"Unsupported Device Type: {dev_type}")
|
||||
dev = dev_class(cfg)
|
||||
if isinstance(dev, GpioDevice):
|
||||
if not HAS_GPIOD:
|
||||
continue
|
||||
dev.configure_line(cfg, self.chip_factory)
|
||||
self.devices[dev.get_name()] = dev
|
||||
except Exception:
|
||||
self.chip_factory.close()
|
||||
raise
|
||||
|
||||
self.server.register_endpoint(
|
||||
"/machine/device_power/devices", ['GET'],
|
||||
self._handle_list_devices)
|
||||
self.server.register_endpoint(
|
||||
"/machine/device_power/status", ['GET'],
|
||||
self._handle_batch_power_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/device_power/on", ['POST'],
|
||||
self._handle_batch_power_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/device_power/off", ['POST'],
|
||||
self._handle_batch_power_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/device_power/device", ['GET', 'POST'],
|
||||
self._handle_single_power_request)
|
||||
self.server.register_remote_method(
|
||||
"set_device_power", self.set_device_power)
|
||||
self.server.register_event_handler(
|
||||
"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()))
|
||||
|
||||
async def _check_klippy_printing(self) -> bool:
|
||||
kapis: APIComp = self.server.lookup_component('klippy_apis')
|
||||
result: Dict[str, Any] = await kapis.query_objects(
|
||||
{'print_stats': None}, default={})
|
||||
pstate = result.get('print_stats', {}).get('state', "").lower()
|
||||
return pstate == "printing"
|
||||
|
||||
async def _initalize_devices(self,
|
||||
inital_devs: List[PowerDevice]
|
||||
) -> None:
|
||||
for dev in inital_devs:
|
||||
ret = dev.initialize()
|
||||
if ret is not None:
|
||||
await ret
|
||||
|
||||
async def _handle_klippy_shutdown(self) -> None:
|
||||
for name, dev in self.devices.items():
|
||||
if dev.has_off_when_shutdown():
|
||||
logging.info(
|
||||
f"Powering off device [{name}] due to"
|
||||
" klippy shutdown")
|
||||
await self._process_request(dev, "off")
|
||||
|
||||
async def _handle_list_devices(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
dev_list = [d.get_device_info() for d in self.devices.values()]
|
||||
output = {"devices": dev_list}
|
||||
return output
|
||||
|
||||
async def _handle_single_power_request(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
dev_name: str = web_request.get_str('device')
|
||||
req_action = web_request.get_action()
|
||||
if dev_name not in self.devices:
|
||||
raise self.server.error(f"No valid device named {dev_name}")
|
||||
dev = self.devices[dev_name]
|
||||
if req_action == 'GET':
|
||||
action = "status"
|
||||
elif req_action == "POST":
|
||||
action = web_request.get_str('action').lower()
|
||||
if action not in ["on", "off", "toggle"]:
|
||||
raise self.server.error(
|
||||
f"Invalid requested action '{action}'")
|
||||
result = await self._process_request(dev, action)
|
||||
return {dev_name: result}
|
||||
|
||||
async def _handle_batch_power_request(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
args = web_request.get_args()
|
||||
ep = web_request.get_endpoint()
|
||||
if not args:
|
||||
raise self.server.error("No arguments provided")
|
||||
requested_devs = {k: self.devices.get(k, None) for k in args}
|
||||
result = {}
|
||||
req = ep.split("/")[-1]
|
||||
for name, device in requested_devs.items():
|
||||
if device is not None:
|
||||
result[name] = await self._process_request(device, req)
|
||||
else:
|
||||
result[name] = "device_not_found"
|
||||
return result
|
||||
|
||||
async def _process_request(self,
|
||||
device: PowerDevice,
|
||||
req: str
|
||||
) -> str:
|
||||
ret = device.refresh_status()
|
||||
if ret is not None:
|
||||
await ret
|
||||
dev_info = device.get_device_info()
|
||||
if req == "toggle":
|
||||
req = "on" if dev_info['status'] == "off" else "off"
|
||||
if req in ["on", "off"]:
|
||||
cur_state: str = dev_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 ret is not None:
|
||||
await ret
|
||||
dev_info = device.get_device_info()
|
||||
self.server.send_event("power:power_changed", dev_info)
|
||||
device.run_power_changed_action()
|
||||
elif req != "status":
|
||||
raise self.server.error(f"Unsupported power request: {req}")
|
||||
return dev_info['status']
|
||||
|
||||
def set_device_power(self, device: str, state: str) -> None:
|
||||
status: Optional[str] = None
|
||||
if isinstance(state, bool):
|
||||
status = "on" if state else "off"
|
||||
elif isinstance(state, str):
|
||||
status = state.lower()
|
||||
if status in ["true", "false"]:
|
||||
status = "on" if status == "true" else "off"
|
||||
if status not in ["on", "off"]:
|
||||
logging.info(f"Invalid state received: {state}")
|
||||
return
|
||||
if device not in self.devices:
|
||||
logging.info(f"No device found: {device}")
|
||||
return
|
||||
ioloop = IOLoop.current()
|
||||
ioloop.spawn_callback(
|
||||
self._process_request, self.devices[device], status)
|
||||
|
||||
async def add_device(self, name: str, device: PowerDevice) -> None:
|
||||
if name in self.devices:
|
||||
raise self.server.error(
|
||||
f"Device [{name}] already configured")
|
||||
ret = device.initialize()
|
||||
if ret is not None:
|
||||
await ret
|
||||
self.devices[name] = device
|
||||
|
||||
async def close(self) -> None:
|
||||
for device in self.devices.values():
|
||||
ret = device.close()
|
||||
if ret is not None:
|
||||
await ret
|
||||
self.chip_factory.close()
|
||||
|
||||
|
||||
class PowerDevice:
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
name_parts = config.get_name().split(maxsplit=1)
|
||||
if len(name_parts) != 2:
|
||||
raise config.error(f"Invalid Section Name: {config.get_name()}")
|
||||
self.server = config.get_server()
|
||||
self.name = name_parts[1]
|
||||
self.type: str = config.get('type')
|
||||
self.state: str = "init"
|
||||
self.locked_while_printing = config.getboolean(
|
||||
'locked_while_printing', False)
|
||||
self.off_when_shutdown = config.getboolean('off_when_shutdown', False)
|
||||
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) -> str:
|
||||
return self.name
|
||||
|
||||
def get_device_info(self) -> Dict[str, Any]:
|
||||
return {
|
||||
'device': self.name,
|
||||
'status': self.state,
|
||||
'locked_while_printing': self.locked_while_printing,
|
||||
'type': self.type
|
||||
}
|
||||
|
||||
def get_locked_while_printing(self) -> bool:
|
||||
return self.locked_while_printing
|
||||
|
||||
def run_power_changed_action(self) -> None:
|
||||
if self.state == "on" and self.klipper_restart:
|
||||
ioloop = IOLoop.current()
|
||||
kapis: APIComp = self.server.lookup_component("klippy_apis")
|
||||
ioloop.call_later(
|
||||
self.restart_delay, kapis.do_restart, # type:ignore
|
||||
"FIRMWARE_RESTART")
|
||||
|
||||
def has_off_when_shutdown(self) -> bool:
|
||||
return self.off_when_shutdown
|
||||
|
||||
def initialize(self) -> Optional[Coroutine]:
|
||||
raise NotImplementedError
|
||||
|
||||
def refresh_status(self) -> Optional[Coroutine]:
|
||||
raise NotImplementedError
|
||||
|
||||
def set_power(self, state: str) -> Optional[Coroutine]:
|
||||
raise NotImplementedError
|
||||
|
||||
def close(self) -> Optional[Coroutine]:
|
||||
pass
|
||||
|
||||
class HTTPDevice(PowerDevice):
|
||||
def __init__(self,
|
||||
config: ConfigHelper,
|
||||
default_port: int = -1,
|
||||
default_user: str = "",
|
||||
default_password: str = "",
|
||||
default_protocol: str = "http"
|
||||
) -> None:
|
||||
super().__init__(config)
|
||||
self.client = AsyncHTTPClient()
|
||||
self.request_mutex = Lock()
|
||||
self.addr: str = config.get("address")
|
||||
self.port = config.getint("port", default_port)
|
||||
self.user = config.get("user", default_user)
|
||||
self.password = config.get("password", default_password)
|
||||
self.protocol = config.get("protocol", default_protocol)
|
||||
|
||||
async def initialize(self) -> None:
|
||||
await self.refresh_status()
|
||||
|
||||
async def _send_http_command(self,
|
||||
url: str,
|
||||
command: str
|
||||
) -> Dict[str, Any]:
|
||||
try:
|
||||
response = await self.client.fetch(url)
|
||||
data = json_decode(response.body)
|
||||
except Exception:
|
||||
msg = f"Error sending '{self.type}' command: {command}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg)
|
||||
return data
|
||||
|
||||
async def _send_power_request(self, state: str) -> str:
|
||||
raise NotImplementedError(
|
||||
"_send_power_request must be implemented by children")
|
||||
|
||||
async def _send_status_request(self) -> str:
|
||||
raise NotImplementedError(
|
||||
"_send_status_request must be implemented by children")
|
||||
|
||||
async def refresh_status(self) -> None:
|
||||
async with self.request_mutex:
|
||||
try:
|
||||
state = await self._send_status_request()
|
||||
except Exception:
|
||||
self.state = "error"
|
||||
msg = f"Error Refeshing Device Status: {self.name}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg) from None
|
||||
self.state = state
|
||||
|
||||
async def set_power(self, state):
|
||||
async with self.request_mutex:
|
||||
try:
|
||||
state = await self._send_power_request(state)
|
||||
except Exception:
|
||||
self.state = "error"
|
||||
msg = f"Error Setting Device Status: {self.name} to {state}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg) from None
|
||||
self.state = state
|
||||
|
||||
|
||||
class GpioChipFactory:
|
||||
def __init__(self) -> None:
|
||||
self.chips: Dict[str, gpiod.Chip] = {}
|
||||
|
||||
def get_gpio_chip(self, chip_name) -> gpiod.Chip:
|
||||
if chip_name in self.chips:
|
||||
return self.chips[chip_name]
|
||||
chip = gpiod.Chip(chip_name, gpiod.Chip.OPEN_BY_NAME)
|
||||
self.chips[chip_name] = chip
|
||||
return chip
|
||||
|
||||
def close(self) -> None:
|
||||
for chip in self.chips.values():
|
||||
chip.close()
|
||||
|
||||
class GpioDevice(PowerDevice):
|
||||
def __init__(self, config: ConfigHelper):
|
||||
super().__init__(config)
|
||||
self.initial_state = config.getboolean('initial_state', False)
|
||||
|
||||
def configure_line(self,
|
||||
config: ConfigHelper,
|
||||
chip_factory: GpioChipFactory
|
||||
) -> None:
|
||||
pin, chip_id, invert = self._parse_pin(config)
|
||||
try:
|
||||
chip = chip_factory.get_gpio_chip(chip_id)
|
||||
self.line = chip.get_line(pin)
|
||||
if invert:
|
||||
self.line.request(
|
||||
consumer="moonraker", type=gpiod.LINE_REQ_DIR_OUT,
|
||||
flags=gpiod.LINE_REQ_FLAG_ACTIVE_LOW)
|
||||
else:
|
||||
self.line.request(
|
||||
consumer="moonraker", type=gpiod.LINE_REQ_DIR_OUT)
|
||||
except Exception:
|
||||
self.state = "error"
|
||||
logging.exception(
|
||||
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")
|
||||
|
||||
|
||||
def _parse_pin(self, config: ConfigHelper) -> Tuple[int, str, bool]:
|
||||
pin = cfg_pin = config.get("pin")
|
||||
invert = False
|
||||
if pin[0] == "!":
|
||||
pin = pin[1:]
|
||||
invert = True
|
||||
chip_id: str = "gpiochip0"
|
||||
pin_parts = pin.split("/")
|
||||
if len(pin_parts) == 2:
|
||||
chip_id, pin = pin_parts
|
||||
elif len(pin_parts) == 1:
|
||||
pin = pin_parts[0]
|
||||
# Verify pin
|
||||
if not chip_id.startswith("gpiochip") or \
|
||||
not chip_id[-1].isdigit() or \
|
||||
not pin.startswith("gpio") or \
|
||||
not pin[4:].isdigit():
|
||||
raise config.error(
|
||||
f"Invalid Power Pin configuration: {cfg_pin}")
|
||||
pin_id = int(pin[4:])
|
||||
return pin_id, chip_id, invert
|
||||
|
||||
def initialize(self) -> None:
|
||||
self.set_power("on" if self.initial_state else "off")
|
||||
|
||||
def refresh_status(self) -> None:
|
||||
pass
|
||||
|
||||
def set_power(self, state) -> None:
|
||||
try:
|
||||
self.line.set_value(int(state == "on"))
|
||||
except Exception:
|
||||
self.state = "error"
|
||||
msg = f"Error Toggling Device Power: {self.name}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg) from None
|
||||
self.state = state
|
||||
|
||||
def close(self) -> None:
|
||||
self.line.release()
|
||||
|
||||
|
||||
# This implementation based off the work tplink_smartplug
|
||||
# script by Lubomir Stroetmann available at:
|
||||
#
|
||||
# https://github.com/softScheck/tplink-smartplug
|
||||
#
|
||||
# Copyright 2016 softScheck GmbH
|
||||
class TPLinkSmartPlug(PowerDevice):
|
||||
START_KEY = 0xAB
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
super().__init__(config)
|
||||
self.request_mutex = Lock()
|
||||
self.addr: List[str] = config.get("address").split('/')
|
||||
self.port = config.getint("port", 9999)
|
||||
|
||||
async def _send_tplink_command(self,
|
||||
command: str
|
||||
) -> Dict[str, Any]:
|
||||
out_cmd: Dict[str, Any] = {}
|
||||
if command in ["on", "off"]:
|
||||
out_cmd = {
|
||||
'system': {'set_relay_state': {'state': int(command == "on")}}
|
||||
}
|
||||
# TPLink device controls multiple devices
|
||||
if len(self.addr) == 2:
|
||||
sysinfo = await self._send_tplink_command("info")
|
||||
dev_id = sysinfo["system"]["get_sysinfo"]["deviceId"]
|
||||
out_cmd["context"] = {
|
||||
'child_ids': [f"{dev_id}{int(self.addr[1]):02}"]
|
||||
}
|
||||
elif command == "info":
|
||||
out_cmd = {'system': {'get_sysinfo': {}}}
|
||||
else:
|
||||
raise self.server.error(f"Invalid tplink command: {command}")
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
stream = IOStream(s)
|
||||
try:
|
||||
await stream.connect((self.addr[0], self.port))
|
||||
await stream.write(self._encrypt(out_cmd))
|
||||
data = await stream.read_bytes(2048, partial=True)
|
||||
length: int = struct.unpack(">I", data[:4])[0]
|
||||
data = data[4:]
|
||||
retries = 5
|
||||
remaining = length - len(data)
|
||||
while remaining and retries:
|
||||
data += await stream.read_bytes(remaining)
|
||||
remaining = length - len(data)
|
||||
retries -= 1
|
||||
if not retries:
|
||||
raise self.server.error("Unable to read tplink packet")
|
||||
except Exception:
|
||||
msg = f"Error sending tplink command: {command}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg)
|
||||
finally:
|
||||
stream.close()
|
||||
return json.loads(self._decrypt(data))
|
||||
|
||||
def _encrypt(self, outdata: Dict[str, Any]) -> bytes:
|
||||
data = json.dumps(outdata)
|
||||
key = self.START_KEY
|
||||
res = struct.pack(">I", len(data))
|
||||
for c in data:
|
||||
val = key ^ ord(c)
|
||||
key = val
|
||||
res += bytes([val])
|
||||
return res
|
||||
|
||||
def _decrypt(self, data: bytes) -> str:
|
||||
key: int = self.START_KEY
|
||||
res: str = ""
|
||||
for c in data:
|
||||
val = key ^ c
|
||||
key = c
|
||||
res += chr(val)
|
||||
return res
|
||||
|
||||
async def initialize(self) -> None:
|
||||
await self.refresh_status()
|
||||
|
||||
async def refresh_status(self) -> None:
|
||||
async with self.request_mutex:
|
||||
try:
|
||||
state: str
|
||||
res = await self._send_tplink_command("info")
|
||||
if len(self.addr) == 2:
|
||||
# TPLink device controls multiple devices
|
||||
children: Dict[int, Any]
|
||||
children = res['system']['get_sysinfo']['children']
|
||||
state = children[int(self.addr[1])]['state']
|
||||
else:
|
||||
state = res['system']['get_sysinfo']['relay_state']
|
||||
except Exception:
|
||||
self.state = "error"
|
||||
msg = f"Error Refeshing Device Status: {self.name}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg) from None
|
||||
self.state = "on" if state else "off"
|
||||
|
||||
async def set_power(self, state) -> None:
|
||||
async with self.request_mutex:
|
||||
err: int
|
||||
try:
|
||||
res = await self._send_tplink_command(state)
|
||||
err = res['system']['set_relay_state']['err_code']
|
||||
except Exception:
|
||||
err = 1
|
||||
logging.exception(f"Power Toggle Error: {self.name}")
|
||||
if err:
|
||||
self.state = "error"
|
||||
raise self.server.error(
|
||||
f"Error Toggling Device Power: {self.name}")
|
||||
self.state = state
|
||||
|
||||
|
||||
class Tasmota(HTTPDevice):
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
super().__init__(config, default_password="")
|
||||
self.output_id = config.getint("output_id", 1)
|
||||
self.timer = config.get("timer", "")
|
||||
|
||||
async def _send_tasmota_command(self,
|
||||
command: str,
|
||||
password: Optional[str] = None
|
||||
) -> Dict[str, Any]:
|
||||
if command in ["on", "off"]:
|
||||
out_cmd = f"Power{self.output_id}%20{command}"
|
||||
if self.timer != "" and command == "off":
|
||||
out_cmd = f"Backlog%20Delay%20{self.timer}0%3B%20{out_cmd}"
|
||||
elif command == "info":
|
||||
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=" \
|
||||
f"{self.password}&cmnd={out_cmd}"
|
||||
return await self._send_http_command(url, command)
|
||||
|
||||
async def _send_status_request(self) -> str:
|
||||
res = await self._send_tasmota_command("info")
|
||||
try:
|
||||
state: str = res[f"POWER{self.output_id}"].lower()
|
||||
except KeyError as e:
|
||||
if self.output_id == 1:
|
||||
state = res[f"POWER"].lower()
|
||||
else:
|
||||
raise KeyError(e)
|
||||
return state
|
||||
|
||||
async def _send_power_request(self, state: str) -> str:
|
||||
res = await self._send_tasmota_command(state)
|
||||
if self.timer == "" or state != "off":
|
||||
try:
|
||||
state = res[f"POWER{self.output_id}"].lower()
|
||||
except KeyError as e:
|
||||
if self.output_id == 1:
|
||||
state = res[f"POWER"].lower()
|
||||
else:
|
||||
raise KeyError(e)
|
||||
return state
|
||||
|
||||
|
||||
class Shelly(HTTPDevice):
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
super().__init__(config, default_user="admin", default_password="")
|
||||
self.output_id = config.getint("output_id", 0)
|
||||
self.timer = config.get("timer", "")
|
||||
|
||||
async def _send_shelly_command(self, command: str) -> Dict[str, Any]:
|
||||
if command == "on":
|
||||
out_cmd = f"relay/{self.output_id}?turn={command}"
|
||||
elif command == "off":
|
||||
if self.timer != "":
|
||||
out_cmd = f"relay/{self.output_id}?turn=on&timer={self.timer}"
|
||||
else:
|
||||
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}"
|
||||
return await self._send_http_command(url, command)
|
||||
|
||||
async def _send_status_request(self) -> str:
|
||||
res = await self._send_shelly_command("info")
|
||||
state: str = res[f"ison"]
|
||||
timer_remaining = res[f"timer_remaining"] if self.timer != "" else 0
|
||||
return "on" if state and timer_remaining == 0 else "off"
|
||||
|
||||
async def _send_power_request(self, state: str) -> str:
|
||||
res = await self._send_shelly_command(state)
|
||||
state = res[f"ison"]
|
||||
timer_remaining = res[f"timer_remaining"] if self.timer != "" else 0
|
||||
return "on" if state and timer_remaining == 0 else "off"
|
||||
|
||||
|
||||
class HomeSeer(HTTPDevice):
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
super().__init__(config, default_user="admin", default_password="")
|
||||
self.device = config.getint("device")
|
||||
|
||||
async def _send_homeseer(self,
|
||||
request: str,
|
||||
additional: str = ""
|
||||
) -> Dict[str, Any]:
|
||||
url = (f"http://{self.user}:{self.password}@{self.addr}"
|
||||
f"/JSON?user={self.user}&pass={self.password}"
|
||||
f"&request={request}&ref={self.device}&{additional}")
|
||||
return await self._send_http_command(url, request)
|
||||
|
||||
async def _send_status_request(self) -> str:
|
||||
res = await self._send_homeseer("getstatus")
|
||||
return res[f"Devices"][0]["status"].lower()
|
||||
|
||||
async def _send_power_request(self, state: str) -> str:
|
||||
if state == "on":
|
||||
state_hs = "On"
|
||||
elif state == "off":
|
||||
state_hs = "Off"
|
||||
res = await self._send_homeseer("controldevicebylabel",
|
||||
f"label={state_hs}")
|
||||
return state
|
||||
|
||||
|
||||
class HomeAssistant(HTTPDevice):
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
super().__init__(config, default_port=8123)
|
||||
self.device: str = config.get("device")
|
||||
self.token: str = config.get("token")
|
||||
self.domain: str = config.get("domain", "switch")
|
||||
|
||||
async def _send_homeassistant_command(self,
|
||||
command: str
|
||||
) -> Dict[Union[str, int], Any]:
|
||||
if command == "on":
|
||||
out_cmd = f"api/services/{self.domain}/turn_on"
|
||||
body = {"entity_id": self.device}
|
||||
method = "POST"
|
||||
elif command == "off":
|
||||
out_cmd = f"api/services/{self.domain}/turn_off"
|
||||
body = {"entity_id": self.device}
|
||||
method = "POST"
|
||||
elif command == "info":
|
||||
out_cmd = f"api/states/{self.device}"
|
||||
method = "GET"
|
||||
else:
|
||||
raise self.server.error(
|
||||
f"Invalid homeassistant command: {command}")
|
||||
url = f"{self.protocol}://{self.addr}:{self.port}/{out_cmd}"
|
||||
headers = {
|
||||
'Authorization': f'Bearer {self.token}',
|
||||
'Content-Type': 'application/json'
|
||||
}
|
||||
try:
|
||||
if (method == "POST"):
|
||||
response = await self.client.fetch(
|
||||
url, method="POST", body=json.dumps(body), headers=headers)
|
||||
else:
|
||||
response = await self.client.fetch(
|
||||
url, method="GET", headers=headers)
|
||||
data: Dict[Union[str, int], Any] = json_decode(response.body)
|
||||
except Exception:
|
||||
msg = f"Error sending homeassistant command: {command}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg)
|
||||
return data
|
||||
|
||||
async def _send_status_request(self) -> str:
|
||||
res = await self._send_homeassistant_command("info")
|
||||
return res[f"state"]
|
||||
|
||||
async def _send_power_request(self, state: str) -> str:
|
||||
await self._send_homeassistant_command(state)
|
||||
res = await self._send_status_request()
|
||||
return res
|
||||
|
||||
class Loxonev1(HTTPDevice):
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
super().__init__(config, default_user="admin",
|
||||
default_password="admin")
|
||||
self.output_id = config.get("output_id", "")
|
||||
|
||||
async def _send_loxonev1_command(self, command: str) -> Dict[str, Any]:
|
||||
if command in ["on", "off"]:
|
||||
out_cmd = f"jdev/sps/io/{self.output_id}/{command}"
|
||||
elif command == "info":
|
||||
out_cmd = f"jdev/sps/io/{self.output_id}"
|
||||
else:
|
||||
raise self.server.error(f"Invalid loxonev1 command: {command}")
|
||||
if self.password != "":
|
||||
out_pwd = f"{self.user}:{self.password}@"
|
||||
else:
|
||||
out_pwd = f""
|
||||
url = f"http://{out_pwd}{self.addr}/{out_cmd}"
|
||||
return await self._send_http_command(url, command)
|
||||
|
||||
async def _send_status_request(self) -> str:
|
||||
res = await self._send_loxonev1_command("info")
|
||||
state = res[f"LL"][f"value"]
|
||||
return "on" if int(state) == 1 else "off"
|
||||
|
||||
async def _send_power_request(self, state: str) -> str:
|
||||
res = await self._send_loxonev1_command(state)
|
||||
state = res[f"LL"][f"value"]
|
||||
return "on" if int(state) == 1 else "off"
|
||||
|
||||
|
||||
# The power component has multiple configuration sections
|
||||
def load_component_multi(config: ConfigHelper) -> PrinterPower:
|
||||
return PrinterPower(config)
|
||||
@@ -0,0 +1,189 @@
|
||||
# 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.
|
||||
|
||||
from __future__ import annotations
|
||||
import time
|
||||
import re
|
||||
import os
|
||||
import pathlib
|
||||
import logging
|
||||
from collections import deque
|
||||
from tornado.ioloop import IOLoop, PeriodicCallback
|
||||
from tornado.locks import Lock
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Deque,
|
||||
Any,
|
||||
Tuple,
|
||||
Optional,
|
||||
Dict,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from confighelper import ConfigHelper
|
||||
from websockets import WebRequest
|
||||
from . import shell_command
|
||||
|
||||
VC_GEN_CMD_FILE = "/usr/bin/vcgencmd"
|
||||
STATM_FILE_PATH = "/proc/self/smaps_rollup"
|
||||
TEMPERATURE_PATH = "/sys/class/thermal/thermal_zone0/temp"
|
||||
STAT_UPDATE_TIME_MS = 1000
|
||||
REPORT_QUEUE_SIZE = 30
|
||||
THROTTLE_CHECK_INTERVAL = 10
|
||||
REPORT_BLOCKED_TIME = 5.
|
||||
|
||||
THROTTLED_FLAGS = {
|
||||
1: "Under-Voltage Detected",
|
||||
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: ConfigHelper) -> None:
|
||||
self.server = config.get_server()
|
||||
self.ioloop = IOLoop.current()
|
||||
self.stat_update_cb = PeriodicCallback(
|
||||
self._handle_stat_update, STAT_UPDATE_TIME_MS) # type: ignore
|
||||
self.vcgencmd: Optional[shell_command.ShellCommand] = None
|
||||
if os.path.exists(VC_GEN_CMD_FILE):
|
||||
logging.info("Detected 'vcgencmd', throttle checking enabled")
|
||||
shell_cmd: shell_command.ShellCommandFactory
|
||||
shell_cmd = self.server.load_component(config, "shell_command")
|
||||
self.vcgencmd = shell_cmd.build_shell_command(
|
||||
"vcgencmd get_throttled")
|
||||
self.server.register_notification("proc_stats:cpu_throttled")
|
||||
else:
|
||||
logging.info("Unable to find 'vcgencmd', throttle checking "
|
||||
"disabled")
|
||||
self.temp_file = pathlib.Path(TEMPERATURE_PATH)
|
||||
self.smaps = pathlib.Path(STATM_FILE_PATH)
|
||||
self.server.register_endpoint(
|
||||
"/machine/proc_stats", ["GET"], self._handle_stat_request)
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_shutdown", self._handle_shutdown)
|
||||
self.server.register_notification("proc_stats:proc_stat_update")
|
||||
self.proc_stat_queue: Deque[Dict[str, Any]] = deque(maxlen=30)
|
||||
self.last_update_time = time.time()
|
||||
self.last_proc_time = time.process_time()
|
||||
self.throttle_check_lock = Lock()
|
||||
self.total_throttled: int = 0
|
||||
self.last_throttled: int = 0
|
||||
self.update_sequence: int = 0
|
||||
self.stat_update_cb.start()
|
||||
|
||||
async def _handle_stat_request(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
ts: Optional[Dict[str, Any]] = None
|
||||
if self.vcgencmd is not None:
|
||||
ts = await self._check_throttled_state()
|
||||
return {
|
||||
'moonraker_stats': list(self.proc_stat_queue),
|
||||
'throttled_state': ts,
|
||||
'cpu_temp': self._get_cpu_temperature()
|
||||
}
|
||||
|
||||
async def _handle_shutdown(self) -> None:
|
||||
msg = "\nMoonraker System Usage Statistics:"
|
||||
for stats in self.proc_stat_queue:
|
||||
msg += f"\n{self._format_stats(stats)}"
|
||||
msg += f"\nCPU Temperature: {self._get_cpu_temperature()}"
|
||||
logging.info(msg)
|
||||
if self.vcgencmd is not None:
|
||||
ts = await self._check_throttled_state()
|
||||
logging.info(f"Throttled Flags: {' '.join(ts['flags'])}")
|
||||
|
||||
async def _handle_stat_update(self) -> None:
|
||||
update_time = time.time()
|
||||
proc_time = time.process_time()
|
||||
time_diff = update_time - self.last_update_time
|
||||
usage = round((proc_time - self.last_proc_time) / time_diff * 100, 2)
|
||||
if time_diff > REPORT_BLOCKED_TIME:
|
||||
logging.info(
|
||||
f"EVENT LOOP BLOCKED: {round(time_diff, 2)} seconds, "
|
||||
f"Moonraker Process Usage: {usage}%")
|
||||
mem, mem_units = self._get_memory_usage()
|
||||
cpu_temp = self._get_cpu_temperature()
|
||||
result = {
|
||||
"time": update_time,
|
||||
"cpu_usage": usage,
|
||||
"memory": mem,
|
||||
"mem_units": mem_units,
|
||||
}
|
||||
self.proc_stat_queue.append(result)
|
||||
self.server.send_event("proc_stats:proc_stat_update", {
|
||||
'moonraker_stats': result,
|
||||
'cpu_temp': cpu_temp
|
||||
})
|
||||
self.last_update_time = update_time
|
||||
self.last_proc_time = proc_time
|
||||
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']
|
||||
if cur_throttled & ~self.total_throttled:
|
||||
self.server.add_log_rollover_item(
|
||||
'throttled', f"CPU Throttled Flags: {ts['flags']}")
|
||||
if cur_throttled != self.last_throttled:
|
||||
self.server.send_event("proc_stats:cpu_throttled", ts)
|
||||
self.last_throttled = cur_throttled
|
||||
self.total_throttled |= cur_throttled
|
||||
|
||||
async def _check_throttled_state(self) -> Dict[str, Any]:
|
||||
async with self.throttle_check_lock:
|
||||
assert self.vcgencmd is not None
|
||||
try:
|
||||
resp = await self.vcgencmd.run_with_response(
|
||||
timeout=.5, log_complete=False)
|
||||
ts = int(resp.strip().split("=")[-1], 16)
|
||||
except Exception:
|
||||
return {'bits': 0, 'flags': ["?"]}
|
||||
flags = []
|
||||
for flag, desc in THROTTLED_FLAGS.items():
|
||||
if flag & ts:
|
||||
flags.append(desc)
|
||||
return {'bits': ts, 'flags': flags}
|
||||
|
||||
def _get_memory_usage(self) -> Tuple[Optional[int], Optional[str]]:
|
||||
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 _get_cpu_temperature(self) -> Optional[float]:
|
||||
temp = None
|
||||
if self.temp_file.exists():
|
||||
try:
|
||||
res = int(self.temp_file.read_text().strip())
|
||||
temp = res / 1000.
|
||||
except Exception:
|
||||
return None
|
||||
return temp
|
||||
|
||||
def _format_stats(self, stats: Dict[str, Any]) -> str:
|
||||
return f"System Time: {stats['time']:2f}, " \
|
||||
f"Usage: {stats['cpu_usage']}%, " \
|
||||
f"Memory: {stats['memory']} {stats['mem_units']}"
|
||||
|
||||
def close(self) -> None:
|
||||
self.stat_update_cb.stop()
|
||||
|
||||
def load_component(config: ConfigHelper) -> ProcStats:
|
||||
return ProcStats(config)
|
||||
@@ -0,0 +1,319 @@
|
||||
# linux shell command execution utility
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
import os
|
||||
import shlex
|
||||
import logging
|
||||
import signal
|
||||
import asyncio
|
||||
from tornado import gen
|
||||
from tornado.locks import Lock
|
||||
from utils import ServerError
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Optional,
|
||||
Callable,
|
||||
Coroutine,
|
||||
Dict,
|
||||
Set,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from confighelper import ConfigHelper
|
||||
from asyncio import BaseTransport
|
||||
OutputCallback = Optional[Callable[[bytes], None]]
|
||||
|
||||
class ShellCommandError(ServerError):
|
||||
def __init__(self,
|
||||
message: str,
|
||||
return_code: Optional[int],
|
||||
stdout: Optional[bytes] = b"",
|
||||
stderr: Optional[bytes] = b"",
|
||||
status_code: int = 500
|
||||
) -> None:
|
||||
super().__init__(message, status_code=status_code)
|
||||
self.stdout = stdout or b""
|
||||
self.stderr = stderr or b""
|
||||
self.return_code = return_code
|
||||
|
||||
class SCProcess(asyncio.subprocess.Process):
|
||||
def initialize(self,
|
||||
program_name: str,
|
||||
std_out_cb: OutputCallback,
|
||||
std_err_cb: OutputCallback,
|
||||
log_stderr: bool
|
||||
) -> None:
|
||||
self.program_name = program_name
|
||||
self.std_out_cb = std_out_cb
|
||||
self.std_err_cb = std_err_cb
|
||||
self.log_stderr = log_stderr
|
||||
self.cancel_requested = False
|
||||
|
||||
async def _read_stream_with_cb(self, fd: int) -> bytes:
|
||||
transport: BaseTransport = \
|
||||
self._transport.get_pipe_transport(fd) # type: ignore
|
||||
if fd == 2:
|
||||
stream = self.stderr
|
||||
cb = self.std_err_cb
|
||||
else:
|
||||
assert fd == 1
|
||||
stream = self.stdout
|
||||
cb = self.std_out_cb
|
||||
assert stream is not None
|
||||
while not stream.at_eof():
|
||||
output = await stream.readline()
|
||||
if not output:
|
||||
break
|
||||
if fd == 2 and self.log_stderr:
|
||||
logging.info(
|
||||
f"{self.program_name}: "
|
||||
f"{output.decode(errors='ignore')}")
|
||||
output = output.rstrip(b'\n')
|
||||
if output and cb is not None:
|
||||
cb(output)
|
||||
transport.close()
|
||||
return output
|
||||
|
||||
async def cancel(self, sig_idx: int = 1) -> None:
|
||||
if self.cancel_requested:
|
||||
return
|
||||
self.cancel_requested = True
|
||||
exit_success = False
|
||||
sig_idx = min(2, max(0, sig_idx))
|
||||
sigs = [signal.SIGINT, signal.SIGTERM, signal.SIGKILL][sig_idx:]
|
||||
for sig in sigs:
|
||||
self.send_signal(sig)
|
||||
try:
|
||||
ret = self.wait()
|
||||
await asyncio.wait_for(ret, timeout=2.)
|
||||
except asyncio.TimeoutError:
|
||||
continue
|
||||
logging.debug(f"Command '{self.program_name}' exited with "
|
||||
f"signal: {sig.name}")
|
||||
exit_success = True
|
||||
break
|
||||
if not exit_success:
|
||||
logging.info(f"WARNING: {self.program_name} did not cleanly exit")
|
||||
if self.stdout is not None:
|
||||
self.stdout.feed_eof()
|
||||
if self.stderr is not None:
|
||||
self.stderr.feed_eof()
|
||||
|
||||
async def communicate_with_cb(self,
|
||||
input: Optional[bytes] = None
|
||||
) -> None:
|
||||
if input is not None:
|
||||
stdin: Coroutine = self._feed_stdin(input) # type: ignore
|
||||
else:
|
||||
stdin = self._noop() # type: ignore
|
||||
if self.stdout is not None and self.std_out_cb is not None:
|
||||
stdout: Coroutine = self._read_stream_with_cb(1)
|
||||
else:
|
||||
stdout = self._noop() # type: ignore
|
||||
has_err_output = self.std_err_cb is not None or self.log_stderr
|
||||
if self.stderr is not None and has_err_output:
|
||||
stderr: Coroutine = self._read_stream_with_cb(2)
|
||||
else:
|
||||
stderr = self._noop() # type: ignore
|
||||
stdin, stdout, stderr = await asyncio.tasks.gather(
|
||||
stdin, stdout, stderr, loop=self._loop) # type: ignore
|
||||
await self.wait()
|
||||
|
||||
class ShellCommand:
|
||||
IDX_SIGINT = 0
|
||||
IDX_SIGTERM = 1
|
||||
IDX_SIGKILL = 2
|
||||
def __init__(self,
|
||||
factory: ShellCommandFactory,
|
||||
cmd: str,
|
||||
std_out_callback: OutputCallback,
|
||||
std_err_callback: OutputCallback,
|
||||
env: Optional[Dict[str, str]] = None,
|
||||
log_stderr: bool = False,
|
||||
cwd: Optional[str] = None
|
||||
) -> None:
|
||||
self.factory = factory
|
||||
self.name = cmd
|
||||
self.std_out_cb = std_out_callback
|
||||
self.std_err_cb = std_err_callback
|
||||
cmd = os.path.expanduser(cmd)
|
||||
self.command = shlex.split(cmd)
|
||||
self.log_stderr = log_stderr
|
||||
self.env = env
|
||||
self.cwd = cwd
|
||||
self.proc: Optional[SCProcess] = None
|
||||
self.cancelled = False
|
||||
self.return_code: Optional[int] = None
|
||||
self.run_lock = Lock()
|
||||
|
||||
async def cancel(self, sig_idx: int = 1) -> None:
|
||||
self.cancelled = True
|
||||
if self.proc is not None:
|
||||
await self.proc.cancel(sig_idx)
|
||||
|
||||
def get_return_code(self) -> Optional[int]:
|
||||
return self.return_code
|
||||
|
||||
def _reset_command_data(self) -> None:
|
||||
self.return_code = self.proc = None
|
||||
self.cancelled = False
|
||||
|
||||
async def run(self,
|
||||
timeout: float = 2.,
|
||||
verbose: bool = True,
|
||||
log_complete: bool = True,
|
||||
sig_idx: int = 1
|
||||
) -> bool:
|
||||
async with self.run_lock:
|
||||
self.factory.add_running_command(self)
|
||||
self._reset_command_data()
|
||||
if not timeout:
|
||||
# Never timeout
|
||||
timeout = 9999999999999999.
|
||||
if self.std_out_cb is None and self.std_err_cb is None and \
|
||||
not self.log_stderr:
|
||||
# No callbacks set so output cannot be verbose
|
||||
verbose = False
|
||||
if not await self._create_subprocess():
|
||||
self.factory.remove_running_command(self)
|
||||
return False
|
||||
assert self.proc is not None
|
||||
try:
|
||||
if verbose:
|
||||
ret: Coroutine = self.proc.communicate_with_cb()
|
||||
else:
|
||||
ret = self.proc.wait()
|
||||
await asyncio.wait_for(ret, timeout=timeout)
|
||||
except asyncio.TimeoutError:
|
||||
complete = False
|
||||
await self.proc.cancel(sig_idx)
|
||||
else:
|
||||
complete = not self.cancelled
|
||||
self.factory.remove_running_command(self)
|
||||
return self._check_proc_success(complete, log_complete)
|
||||
|
||||
async def run_with_response(self,
|
||||
timeout: float = 2.,
|
||||
retries: int = 1,
|
||||
log_complete: bool = True,
|
||||
sig_idx: int = 1
|
||||
) -> str:
|
||||
async with self.run_lock:
|
||||
self.factory.add_running_command(self)
|
||||
retries = max(1, retries)
|
||||
while retries > 0:
|
||||
self._reset_command_data()
|
||||
timed_out = False
|
||||
stdout = stderr = b""
|
||||
if await self._create_subprocess():
|
||||
assert self.proc is not None
|
||||
try:
|
||||
ret = self.proc.communicate()
|
||||
stdout, stderr = await asyncio.wait_for(
|
||||
ret, timeout=timeout)
|
||||
except asyncio.TimeoutError:
|
||||
complete = False
|
||||
timed_out = True
|
||||
await self.proc.cancel(sig_idx)
|
||||
else:
|
||||
complete = not self.cancelled
|
||||
if self.log_stderr and stderr:
|
||||
logging.info(
|
||||
f"{self.command[0]}: "
|
||||
f"{stderr.decode(errors='ignore')}")
|
||||
if self._check_proc_success(complete, log_complete):
|
||||
self.factory.remove_running_command(self)
|
||||
return stdout.decode(errors='ignore').rstrip("\n")
|
||||
if stdout:
|
||||
logging.debug(
|
||||
f"Shell command '{self.name}' output:"
|
||||
f"\n{stdout.decode(errors='ignore')}")
|
||||
if self.cancelled and not timed_out:
|
||||
break
|
||||
retries -= 1
|
||||
await gen.sleep(.5)
|
||||
self.factory.remove_running_command(self)
|
||||
raise ShellCommandError(
|
||||
f"Error running shell command: '{self.command}'",
|
||||
self.return_code, stdout, stderr)
|
||||
|
||||
async def _create_subprocess(self) -> bool:
|
||||
loop = asyncio.get_event_loop()
|
||||
|
||||
def protocol_factory():
|
||||
return asyncio.subprocess.SubprocessStreamProtocol(
|
||||
limit=2**20, loop=loop)
|
||||
try:
|
||||
if self.std_err_cb is not None or self.log_stderr:
|
||||
errpipe = asyncio.subprocess.PIPE
|
||||
else:
|
||||
errpipe = asyncio.subprocess.STDOUT
|
||||
transport, protocol = await loop.subprocess_exec(
|
||||
protocol_factory, *self.command,
|
||||
stdout=asyncio.subprocess.PIPE,
|
||||
stderr=errpipe, env=self.env, cwd=self.cwd)
|
||||
self.proc = SCProcess(transport, protocol, loop)
|
||||
self.proc.initialize(self.command[0], self.std_out_cb,
|
||||
self.std_err_cb, self.log_stderr)
|
||||
except Exception:
|
||||
logging.exception(
|
||||
f"shell_command: Command ({self.name}) failed")
|
||||
return False
|
||||
return True
|
||||
|
||||
def _check_proc_success(self,
|
||||
complete: bool,
|
||||
log_complete: bool
|
||||
) -> bool:
|
||||
assert self.proc is not None
|
||||
self.return_code = self.proc.returncode
|
||||
success = self.return_code == 0 and complete
|
||||
if success:
|
||||
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}"
|
||||
if log_complete:
|
||||
logging.info(msg)
|
||||
return success
|
||||
|
||||
class ShellCommandFactory:
|
||||
error = ShellCommandError
|
||||
def __init__(self, config: ConfigHelper) -> None:
|
||||
self.running_commands: Set[ShellCommand] = set()
|
||||
|
||||
def add_running_command(self, cmd: ShellCommand) -> None:
|
||||
self.running_commands.add(cmd)
|
||||
|
||||
def remove_running_command(self, cmd: ShellCommand) -> None:
|
||||
try:
|
||||
self.running_commands.remove(cmd)
|
||||
except KeyError:
|
||||
pass
|
||||
|
||||
def build_shell_command(self,
|
||||
cmd: str,
|
||||
callback: OutputCallback = None,
|
||||
std_err_callback: OutputCallback = None,
|
||||
env: Optional[Dict[str, str]] = None,
|
||||
log_stderr: bool = False,
|
||||
cwd: Optional[str] = None
|
||||
) -> ShellCommand:
|
||||
return ShellCommand(self, cmd, callback, std_err_callback, env,
|
||||
log_stderr, cwd)
|
||||
|
||||
async def close(self) -> None:
|
||||
for cmd in self.running_commands:
|
||||
await cmd.cancel()
|
||||
|
||||
def load_component(config: ConfigHelper) -> ShellCommandFactory:
|
||||
return ShellCommandFactory(config)
|
||||
@@ -0,0 +1,15 @@
|
||||
# Package definition for the update_manager
|
||||
#
|
||||
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
from . import update_manager as um
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
if TYPE_CHECKING:
|
||||
from confighelper import ConfigHelper
|
||||
|
||||
def load_component(config: ConfigHelper) -> um.UpdateManager:
|
||||
return um.load_component(config)
|
||||
@@ -0,0 +1,249 @@
|
||||
# Deploy updates for applications managed by Moonraker
|
||||
#
|
||||
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
import pathlib
|
||||
import shutil
|
||||
import hashlib
|
||||
from concurrent.futures.thread import ThreadPoolExecutor
|
||||
from tornado.ioloop import IOLoop
|
||||
from .base_deploy import BaseDeploy
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Optional,
|
||||
Union,
|
||||
Dict,
|
||||
List,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from confighelper import ConfigHelper
|
||||
from .update_manager import CommandHelper
|
||||
|
||||
CHANNEL_TO_TYPE = {
|
||||
"stable": "zip",
|
||||
"beta": "zip_beta",
|
||||
"dev": "git_repo"
|
||||
}
|
||||
TYPE_TO_CHANNEL = {
|
||||
"zip": "stable",
|
||||
"zip_beta": "beta",
|
||||
"dev": "git_repo"
|
||||
}
|
||||
|
||||
class AppDeploy(BaseDeploy):
|
||||
def __init__(self,
|
||||
config: ConfigHelper,
|
||||
cmd_helper: CommandHelper,
|
||||
app_params: Optional[Dict[str, Any]]
|
||||
) -> None:
|
||||
super().__init__(config, cmd_helper)
|
||||
self.config = config
|
||||
self.app_params = app_params
|
||||
self.debug = self.cmd_helper.is_debug_enabled()
|
||||
if app_params is not None:
|
||||
self.channel: str = app_params['channel']
|
||||
self.path: pathlib.Path = pathlib.Path(
|
||||
app_params['path']).expanduser().resolve()
|
||||
executable: Optional[str] = app_params['executable']
|
||||
self.type = CHANNEL_TO_TYPE[self.channel]
|
||||
else:
|
||||
self.type = config.get('type')
|
||||
self.channel = TYPE_TO_CHANNEL[self.type]
|
||||
self.path = pathlib.Path(
|
||||
config.get('path')).expanduser().resolve()
|
||||
executable = config.get('env', None)
|
||||
if self.channel not in CHANNEL_TO_TYPE.keys():
|
||||
raise config.error(
|
||||
f"Invalid Channel '{self.channel}' for config "
|
||||
f"section [{config.get_name()}]")
|
||||
self._verify_path(config, 'path', self.path)
|
||||
self.executable: Optional[pathlib.Path] = None
|
||||
self.venv_args: Optional[str] = None
|
||||
if executable is not None:
|
||||
self.executable = pathlib.Path(executable).expanduser().resolve()
|
||||
self._verify_path(config, 'env', self.executable)
|
||||
self.venv_args = config.get('venv_args', None)
|
||||
|
||||
self.need_channel_update = False
|
||||
self._is_valid = False
|
||||
|
||||
# We need to fetch all potential options for an Application. Not
|
||||
# all options apply to each subtype, however we can't limit the
|
||||
# options in children if we want to switch between channels and
|
||||
# satisfy the confighelper's requirements.
|
||||
self.origin: str = config.get('origin')
|
||||
self.primary_branch = config.get("primary_branch", "master")
|
||||
self.npm_pkg_json: Optional[pathlib.Path] = None
|
||||
if config.get("enable_node_updates", False):
|
||||
self.npm_pkg_json = self.path.joinpath("package-lock.json")
|
||||
self._verify_path(config, 'enable_node_updates', self.npm_pkg_json)
|
||||
self.python_reqs: Optional[pathlib.Path] = None
|
||||
if self.executable is not None:
|
||||
self.python_reqs = self.path.joinpath(config.get("requirements"))
|
||||
self._verify_path(config, 'requirements', self.python_reqs)
|
||||
self.install_script: Optional[pathlib.Path] = None
|
||||
install_script = config.get('install_script', None)
|
||||
if install_script is not None:
|
||||
self.install_script = self.path.joinpath(install_script).resolve()
|
||||
self._verify_path(config, 'install_script', self.install_script)
|
||||
|
||||
@staticmethod
|
||||
def _is_git_repo(app_path: Union[str, pathlib.Path]) -> bool:
|
||||
if isinstance(app_path, str):
|
||||
app_path = pathlib.Path(app_path).expanduser()
|
||||
return app_path.joinpath('.git').exists()
|
||||
|
||||
def _verify_path(self,
|
||||
config: ConfigHelper,
|
||||
option: str,
|
||||
file_path: pathlib.Path
|
||||
) -> None:
|
||||
if not file_path.exists():
|
||||
raise config.error(
|
||||
f"Invalid path for option `{option}` in section "
|
||||
f"[{config.get_name()}]: Path `{file_path}` does not exist")
|
||||
|
||||
def check_need_channel_swap(self) -> bool:
|
||||
return self.need_channel_update
|
||||
|
||||
def get_configured_type(self) -> str:
|
||||
return self.type
|
||||
|
||||
def check_same_paths(self,
|
||||
app_path: Union[str, pathlib.Path],
|
||||
executable: Union[str, pathlib.Path]
|
||||
) -> bool:
|
||||
if isinstance(app_path, str):
|
||||
app_path = pathlib.Path(app_path)
|
||||
if isinstance(executable, str):
|
||||
executable = pathlib.Path(executable)
|
||||
app_path = app_path.expanduser()
|
||||
executable = executable.expanduser()
|
||||
if self.executable is None:
|
||||
return False
|
||||
return self.path.samefile(app_path) and \
|
||||
self.executable.samefile(executable)
|
||||
|
||||
async def recover(self,
|
||||
hard: bool = False,
|
||||
force_dep_update: bool = False
|
||||
) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
async def reinstall(self):
|
||||
raise NotImplementedError
|
||||
|
||||
async def restart_service(self):
|
||||
if self.name == "moonraker":
|
||||
# Launch restart async so the request can return
|
||||
# before the server restarts
|
||||
IOLoop.current().call_later(
|
||||
.1, self._do_restart) # type: ignore
|
||||
else:
|
||||
await self._do_restart()
|
||||
|
||||
async def _do_restart(self) -> None:
|
||||
self.notify_status("Restarting Service...")
|
||||
try:
|
||||
await self.cmd_helper.run_cmd(
|
||||
f"sudo systemctl restart {self.name}")
|
||||
except Exception:
|
||||
if self.name == "moonraker":
|
||||
# We will always get an error when restarting moonraker
|
||||
# from within the child process, so ignore it
|
||||
return
|
||||
raise self.log_exc("Error restarting service")
|
||||
|
||||
def get_update_status(self) -> Dict[str, Any]:
|
||||
return {
|
||||
'channel': self.channel,
|
||||
'debug_enabled': self.debug,
|
||||
'need_channel_update': self.need_channel_update,
|
||||
'is_valid': self._is_valid,
|
||||
'configured_type': self.type
|
||||
}
|
||||
|
||||
async def _get_file_hash(self,
|
||||
filename: Optional[pathlib.Path]
|
||||
) -> Optional[str]:
|
||||
if filename is None or not filename.is_file():
|
||||
return None
|
||||
|
||||
def hash_func(f: pathlib.Path) -> str:
|
||||
return hashlib.sha256(f.read_bytes()).hexdigest()
|
||||
try:
|
||||
with ThreadPoolExecutor(max_workers=1) as tpe:
|
||||
return await IOLoop.current().run_in_executor(
|
||||
tpe, hash_func, filename)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
async def _check_need_update(self,
|
||||
prev_hash: Optional[str],
|
||||
filename: Optional[pathlib.Path]
|
||||
) -> bool:
|
||||
cur_hash = await self._get_file_hash(filename)
|
||||
if prev_hash is None or cur_hash is None:
|
||||
return False
|
||||
return prev_hash != cur_hash
|
||||
|
||||
async def _install_packages(self, package_list: List[str]) -> None:
|
||||
self.notify_status("Installing system dependencies...")
|
||||
# Install packages with apt-get
|
||||
try:
|
||||
await self.cmd_helper.install_packages(
|
||||
package_list, timeout=3600., notify=True)
|
||||
except Exception:
|
||||
self.log_exc("Error updating packages")
|
||||
return
|
||||
|
||||
async def _update_virtualenv(self,
|
||||
requirements: Union[pathlib.Path, List[str]]
|
||||
) -> None:
|
||||
if self.executable is None:
|
||||
return
|
||||
# Update python dependencies
|
||||
bin_dir = self.executable.parent
|
||||
if isinstance(requirements, pathlib.Path):
|
||||
if not requirements.is_file():
|
||||
self.log_info(
|
||||
f"Invalid path to requirements_file '{requirements}'")
|
||||
return
|
||||
args = f"-r {requirements}"
|
||||
else:
|
||||
args = " ".join(requirements)
|
||||
pip = bin_dir.joinpath("pip")
|
||||
self.notify_status("Updating python packages...")
|
||||
try:
|
||||
# First attempt to update pip
|
||||
await self.cmd_helper.run_cmd(
|
||||
f"{pip} install -U pip", timeout=1200., notify=True,
|
||||
retries=3)
|
||||
await self.cmd_helper.run_cmd(
|
||||
f"{pip} install {args}", timeout=1200., notify=True,
|
||||
retries=3)
|
||||
except Exception:
|
||||
self.log_exc("Error updating python requirements")
|
||||
|
||||
async def _build_virtualenv(self) -> None:
|
||||
if self.executable is None or self.venv_args is None:
|
||||
return
|
||||
bin_dir = self.executable.parent
|
||||
env_path = bin_dir.joinpath("..").resolve()
|
||||
self.notify_status(f"Creating virtualenv at: {env_path}...")
|
||||
if env_path.exists():
|
||||
shutil.rmtree(env_path)
|
||||
try:
|
||||
await self.cmd_helper.run_cmd(
|
||||
f"virtualenv {self.venv_args} {env_path}", timeout=300.)
|
||||
except Exception:
|
||||
self.log_exc(f"Error creating virtualenv")
|
||||
return
|
||||
if not self.executable.exists():
|
||||
raise self.log_exc("Failed to create new virtualenv", False)
|
||||
@@ -0,0 +1,56 @@
|
||||
# Base Deployment Interface
|
||||
#
|
||||
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
import logging
|
||||
|
||||
from typing import TYPE_CHECKING, Dict, Any
|
||||
if TYPE_CHECKING:
|
||||
from confighelper import ConfigHelper
|
||||
from utils import ServerError
|
||||
from .update_manager import CommandHelper
|
||||
|
||||
class BaseDeploy:
|
||||
def __init__(self,
|
||||
config: ConfigHelper,
|
||||
cmd_helper: CommandHelper
|
||||
) -> None:
|
||||
name_parts = config.get_name().split()
|
||||
self.name = name_parts[-1]
|
||||
self.server = config.get_server()
|
||||
self.cmd_helper = cmd_helper
|
||||
if name_parts == 1:
|
||||
self.prefix: str = ""
|
||||
if config.get('type', "") == "web":
|
||||
self.prefix = f"Web Client {self.name}: "
|
||||
else:
|
||||
self.prefix = f"Application {self.name}: "
|
||||
|
||||
async def refresh(self) -> None:
|
||||
pass
|
||||
|
||||
async def update(self) -> bool:
|
||||
return False
|
||||
|
||||
def get_update_status(self) -> Dict[str, Any]:
|
||||
return {}
|
||||
|
||||
def log_exc(self, msg: str, traceback: bool = True) -> ServerError:
|
||||
log_msg = f"{self.prefix}{msg}"
|
||||
if traceback:
|
||||
logging.exception(log_msg)
|
||||
else:
|
||||
logging.info(log_msg)
|
||||
return self.server.error(msg)
|
||||
|
||||
def log_info(self, msg: str) -> None:
|
||||
log_msg = f"{self.prefix}{msg}"
|
||||
logging.info(log_msg)
|
||||
|
||||
def notify_status(self, msg: str, is_complete: bool = False) -> None:
|
||||
log_msg = f"{self.prefix}{msg}"
|
||||
logging.debug(log_msg)
|
||||
self.cmd_helper.notify_update_response(log_msg, is_complete)
|
||||
@@ -0,0 +1,747 @@
|
||||
# Git Deployment implementation
|
||||
#
|
||||
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
import asyncio
|
||||
import os
|
||||
import pathlib
|
||||
import shutil
|
||||
import re
|
||||
import logging
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from tornado.ioloop import IOLoop
|
||||
from .app_deploy import AppDeploy
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Tuple,
|
||||
Optional,
|
||||
Dict,
|
||||
List,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from confighelper import ConfigHelper
|
||||
from components import database
|
||||
from components import shell_command
|
||||
from .update_manager import CommandHelper
|
||||
DBComp = database.MoonrakerDatabase
|
||||
|
||||
|
||||
class GitDeploy(AppDeploy):
|
||||
def __init__(self,
|
||||
config: ConfigHelper,
|
||||
cmd_helper: CommandHelper,
|
||||
app_params: Optional[Dict[str, Any]] = None
|
||||
) -> None:
|
||||
super().__init__(config, cmd_helper, app_params)
|
||||
self.repo = GitRepo(cmd_helper, self.path, self.name, self.origin)
|
||||
if self.type != 'git_repo':
|
||||
self.need_channel_update = True
|
||||
|
||||
@staticmethod
|
||||
async def from_application(app: AppDeploy) -> GitDeploy:
|
||||
new_app = GitDeploy(app.config, app.cmd_helper, app.app_params)
|
||||
await new_app.reinstall()
|
||||
return new_app
|
||||
|
||||
async def refresh(self) -> None:
|
||||
try:
|
||||
await self._update_repo_state()
|
||||
except Exception:
|
||||
logging.exception("Error Refreshing git state")
|
||||
|
||||
async def _update_repo_state(self, need_fetch: bool = True) -> None:
|
||||
self._is_valid = False
|
||||
await self.repo.initialize(need_fetch=need_fetch)
|
||||
self.log_info(
|
||||
f"Channel: {self.channel}, "
|
||||
f"Need Channel Update: {self.need_channel_update}"
|
||||
)
|
||||
invalids = self.repo.report_invalids(self.primary_branch)
|
||||
if invalids:
|
||||
msgs = '\n'.join(invalids)
|
||||
self.log_info(
|
||||
f"Repo validation checks failed:\n{msgs}")
|
||||
if self.debug:
|
||||
self._is_valid = True
|
||||
self.log_info(
|
||||
"Repo debug enabled, overriding validity checks")
|
||||
else:
|
||||
self.log_info("Updates on repo disabled")
|
||||
else:
|
||||
self._is_valid = True
|
||||
self.log_info("Validity check for git repo passed")
|
||||
|
||||
async def update(self) -> bool:
|
||||
await self.repo.wait_for_init()
|
||||
if not self._is_valid:
|
||||
raise self.log_exc("Update aborted, repo not valid", False)
|
||||
if self.repo.is_dirty():
|
||||
raise self.log_exc(
|
||||
"Update aborted, repo has been modified", False)
|
||||
if self.repo.is_current():
|
||||
# No need to update
|
||||
return False
|
||||
self.cmd_helper.notify_update_response(
|
||||
f"Updating Application {self.name}...")
|
||||
inst_hash = await self._get_file_hash(self.install_script)
|
||||
pyreqs_hash = await self._get_file_hash(self.python_reqs)
|
||||
npm_hash = await self._get_file_hash(self.npm_pkg_json)
|
||||
await self._pull_repo()
|
||||
# Check Semantic Versions
|
||||
await self._update_dependencies(inst_hash, pyreqs_hash, npm_hash)
|
||||
# Refresh local repo state
|
||||
await self._update_repo_state(need_fetch=False)
|
||||
await self.restart_service()
|
||||
self.notify_status("Update Finished...", is_complete=True)
|
||||
return True
|
||||
|
||||
async def recover(self,
|
||||
hard: bool = False,
|
||||
force_dep_update: bool = False
|
||||
) -> None:
|
||||
self.notify_status("Attempting Repo Recovery...")
|
||||
inst_hash = await self._get_file_hash(self.install_script)
|
||||
pyreqs_hash = await self._get_file_hash(self.python_reqs)
|
||||
npm_hash = await self._get_file_hash(self.npm_pkg_json)
|
||||
|
||||
if hard:
|
||||
await self.repo.clone()
|
||||
await self._update_repo_state()
|
||||
else:
|
||||
self.notify_status("Resetting Git Repo...")
|
||||
await self.repo.reset()
|
||||
await self._update_repo_state()
|
||||
|
||||
if self.repo.is_dirty() or not self._is_valid:
|
||||
raise self.server.error(
|
||||
"Recovery attempt failed, repo state not pristine", 500)
|
||||
await self._update_dependencies(inst_hash, pyreqs_hash, npm_hash,
|
||||
force=force_dep_update)
|
||||
await self.restart_service()
|
||||
self.notify_status("Reinstall Complete", is_complete=True)
|
||||
|
||||
async def reinstall(self):
|
||||
await self.recover(True, True)
|
||||
|
||||
def get_update_status(self) -> Dict[str, Any]:
|
||||
status = super().get_update_status()
|
||||
status.update(self.repo.get_repo_status())
|
||||
return status
|
||||
|
||||
async def _pull_repo(self) -> None:
|
||||
self.notify_status("Updating Repo...")
|
||||
try:
|
||||
if self.repo.is_detached():
|
||||
await self.repo.fetch()
|
||||
await self.repo.checkout()
|
||||
else:
|
||||
await self.repo.pull()
|
||||
except Exception:
|
||||
raise self.log_exc("Error running 'git pull'")
|
||||
|
||||
async def _update_dependencies(self,
|
||||
inst_hash: Optional[str],
|
||||
pyreqs_hash: Optional[str],
|
||||
npm_hash: Optional[str],
|
||||
force: bool = False
|
||||
) -> None:
|
||||
ret = await self._check_need_update(inst_hash, self.install_script)
|
||||
if force or ret:
|
||||
package_list = await self._parse_install_script()
|
||||
if package_list is not None:
|
||||
await self._install_packages(package_list)
|
||||
ret = await self._check_need_update(pyreqs_hash, self.python_reqs)
|
||||
if force or ret:
|
||||
if self.python_reqs is not None:
|
||||
await self._update_virtualenv(self.python_reqs)
|
||||
ret = await self._check_need_update(npm_hash, self.npm_pkg_json)
|
||||
if force or ret:
|
||||
if self.npm_pkg_json is not None:
|
||||
self.notify_status("Updating Node Packages...")
|
||||
try:
|
||||
await self.cmd_helper.run_cmd(
|
||||
"npm ci --only=prod", notify=True, timeout=600.,
|
||||
cwd=str(self.path))
|
||||
except Exception:
|
||||
self.notify_status("Node Package Update failed")
|
||||
|
||||
async def _parse_install_script(self) -> Optional[List[str]]:
|
||||
if self.install_script is None:
|
||||
return None
|
||||
# Open install file file and read
|
||||
inst_path: pathlib.Path = self.install_script
|
||||
if not inst_path.is_file():
|
||||
self.log_info(f"Unable to open install script: {inst_path}")
|
||||
return None
|
||||
with ThreadPoolExecutor(max_workers=1) as tpe:
|
||||
data = await IOLoop.current().run_in_executor(
|
||||
tpe, inst_path.read_text)
|
||||
packages: List[str] = re.findall(r'PKGLIST="(.*)"', data)
|
||||
packages = [p.lstrip("${PKGLIST}").strip() for p in packages]
|
||||
if not packages:
|
||||
self.log_info(f"No packages found in script: {inst_path}")
|
||||
return None
|
||||
logging.debug(f"Repo {self.name}: Detected Packages: {repr(packages)}")
|
||||
return packages
|
||||
|
||||
|
||||
GIT_ASYNC_TIMEOUT = 300.
|
||||
GIT_ENV_VARS = {
|
||||
'GIT_HTTP_LOW_SPEED_LIMIT': "1000",
|
||||
'GIT_HTTP_LOW_SPEED_TIME ': "20"
|
||||
}
|
||||
GIT_MAX_LOG_CNT = 100
|
||||
GIT_LOG_FMT = \
|
||||
"\"sha:%H%x1Dauthor:%an%x1Ddate:%ct%x1Dsubject:%s%x1Dmessage:%b%x1E\""
|
||||
GIT_OBJ_ERR = "fatal: loose object"
|
||||
|
||||
class GitRepo:
|
||||
def __init__(self,
|
||||
cmd_helper: CommandHelper,
|
||||
git_path: pathlib.Path,
|
||||
alias: str,
|
||||
origin_url: str
|
||||
) -> None:
|
||||
self.server = cmd_helper.get_server()
|
||||
self.cmd_helper = cmd_helper
|
||||
self.alias = alias
|
||||
self.git_path = git_path
|
||||
git_dir = git_path.parent
|
||||
git_base = git_path.name
|
||||
self.backup_path = git_dir.joinpath(f".{git_base}_repo_backup")
|
||||
self.origin_url = origin_url
|
||||
self.valid_git_repo: bool = False
|
||||
self.git_owner: str = "?"
|
||||
self.git_remote: str = "?"
|
||||
self.git_branch: str = "?"
|
||||
self.current_version: str = "?"
|
||||
self.upstream_version: str = "?"
|
||||
self.current_commit: str = "?"
|
||||
self.upstream_commit: str = "?"
|
||||
self.upstream_url: str = "?"
|
||||
self.full_version_string: str = "?"
|
||||
self.branches: List[str] = []
|
||||
self.dirty: bool = False
|
||||
self.head_detached: bool = False
|
||||
self.git_messages: List[str] = []
|
||||
self.commits_behind: List[Dict[str, Any]] = []
|
||||
self.recovery_message = \
|
||||
f"""
|
||||
Manually restore via SSH with the following commands:
|
||||
sudo service {self.alias} stop
|
||||
cd {git_dir}
|
||||
rm -rf {git_base}
|
||||
git clone {self.origin_url}
|
||||
sudo service {self.alias} start
|
||||
"""
|
||||
|
||||
self.init_evt: Optional[asyncio.Event] = None
|
||||
self.initialized: bool = False
|
||||
self.git_operation_lock = asyncio.Lock()
|
||||
self.fetch_timeout_handle: Optional[object] = None
|
||||
self.fetch_input_recd: bool = False
|
||||
|
||||
async def initialize(self, need_fetch: bool = True) -> None:
|
||||
if self.init_evt is not None:
|
||||
# No need to initialize multiple requests
|
||||
await self.init_evt.wait()
|
||||
if self.initialized:
|
||||
return
|
||||
self.initialized = False
|
||||
self.init_evt = asyncio.Event()
|
||||
self.git_messages.clear()
|
||||
try:
|
||||
await self.update_repo_status()
|
||||
self._verify_repo()
|
||||
if not self.head_detached:
|
||||
# lookup remote via git config
|
||||
self.git_remote = await self.get_config_item(
|
||||
f"branch.{self.git_branch}.remote")
|
||||
|
||||
# Populate list of current branches
|
||||
blist = await self.list_branches()
|
||||
self.branches = []
|
||||
for branch in blist:
|
||||
branch = branch.strip()
|
||||
if branch[0] == "*":
|
||||
branch = branch[2:]
|
||||
if branch[0] == "(":
|
||||
continue
|
||||
self.branches.append(branch)
|
||||
|
||||
if need_fetch:
|
||||
await self.fetch()
|
||||
|
||||
self.upstream_url = await self.remote(f"get-url {self.git_remote}")
|
||||
self.current_commit = await self.rev_parse("HEAD")
|
||||
self.upstream_commit = await self.rev_parse(
|
||||
f"{self.git_remote}/{self.git_branch}")
|
||||
current_version = await self.describe(
|
||||
"--always --tags --long --dirty")
|
||||
self.full_version_string = current_version.strip()
|
||||
upstream_version = await self.describe(
|
||||
f"{self.git_remote}/{self.git_branch} "
|
||||
"--always --tags --long")
|
||||
|
||||
# Store current remote in the database if in a detached state
|
||||
if self.head_detached:
|
||||
mrdb: DBComp = self.server.lookup_component("database")
|
||||
db_key = f"update_manager.git_repo_{self.alias}" \
|
||||
".detached_remote"
|
||||
mrdb.insert_item(
|
||||
"moonraker", db_key,
|
||||
[self.current_commit, self.git_remote, self.git_branch])
|
||||
|
||||
# Parse GitHub Owner from URL
|
||||
owner_match = re.match(r"https?://[^/]+/([^/]+)", self.upstream_url)
|
||||
self.git_owner = "?"
|
||||
if owner_match is not None:
|
||||
self.git_owner = owner_match.group(1)
|
||||
self.dirty = current_version.endswith("dirty")
|
||||
|
||||
# Parse Version Info
|
||||
versions = []
|
||||
for ver in [current_version, upstream_version]:
|
||||
tag_version = "?"
|
||||
ver_match = re.match(r"v\d+\.\d+\.\d-\d+", ver)
|
||||
if ver_match:
|
||||
tag_version = ver_match.group()
|
||||
versions.append(tag_version)
|
||||
self.current_version, self.upstream_version = versions
|
||||
|
||||
# Get Commits Behind
|
||||
self.commits_behind = []
|
||||
cbh = await self.get_commits_behind()
|
||||
if cbh:
|
||||
tagged_commits = await self.get_tagged_commits()
|
||||
debug_msg = '\n'.join([f"{k}: {v}" for k, v in
|
||||
tagged_commits.items()])
|
||||
logging.debug(f"Git Repo {self.alias}: Tagged Commits\n"
|
||||
f"{debug_msg}")
|
||||
for i, commit in enumerate(cbh):
|
||||
tag = tagged_commits.get(commit['sha'], None)
|
||||
if i < 30 or tag is not None:
|
||||
commit['tag'] = tag
|
||||
self.commits_behind.append(commit)
|
||||
|
||||
self.log_repo_info()
|
||||
except Exception:
|
||||
logging.exception(f"Git Repo {self.alias}: Initialization failure")
|
||||
raise
|
||||
else:
|
||||
self.initialized = True
|
||||
finally:
|
||||
self.init_evt.set()
|
||||
self.init_evt = None
|
||||
|
||||
async def wait_for_init(self) -> None:
|
||||
if self.init_evt is not None:
|
||||
await self.init_evt.wait()
|
||||
if not self.initialized:
|
||||
raise self.server.error(
|
||||
f"Git Repo {self.alias}: Initialization failure")
|
||||
|
||||
async def update_repo_status(self) -> bool:
|
||||
async with self.git_operation_lock:
|
||||
if not self.git_path.joinpath(".git").is_dir():
|
||||
logging.info(
|
||||
f"Git Repo {self.alias}: path '{self.git_path}'"
|
||||
" is not a valid git repo")
|
||||
return False
|
||||
await self._wait_for_lock_release()
|
||||
self.valid_git_repo = False
|
||||
retries = 3
|
||||
while retries:
|
||||
self.git_messages.clear()
|
||||
try:
|
||||
resp: Optional[str] = await self._run_git_cmd(
|
||||
"status -u no", retries=1)
|
||||
except Exception:
|
||||
retries -= 1
|
||||
resp = None
|
||||
# Attempt to recover from "loose object" error
|
||||
if retries and GIT_OBJ_ERR in "\n".join(self.git_messages):
|
||||
ret = await self._repair_loose_objects()
|
||||
if not ret:
|
||||
# Since we are unable to recover, immediately
|
||||
# return
|
||||
return False
|
||||
else:
|
||||
break
|
||||
if resp is None:
|
||||
return False
|
||||
resp = resp.strip().split('\n', 1)[0]
|
||||
self.head_detached = resp.startswith("HEAD detached")
|
||||
branch_info = resp.split()[-1]
|
||||
if self.head_detached:
|
||||
bparts = branch_info.split("/", 1)
|
||||
if len(bparts) == 2:
|
||||
self.git_remote, self.git_branch = bparts
|
||||
else:
|
||||
mrdb: DBComp = self.server.lookup_component("database")
|
||||
db_key = f"update_manager.git_repo_{self.alias}" \
|
||||
".detached_remote"
|
||||
detached_remote: List[str] = mrdb.get_item(
|
||||
"moonraker", db_key, ["", "?", "?"])
|
||||
if detached_remote[0].startswith(branch_info):
|
||||
self.git_remote = detached_remote[1]
|
||||
self.git_branch = detached_remote[2]
|
||||
msg = "Using remote stored in database:"\
|
||||
f" {self.git_remote}/{self.git_branch}"
|
||||
elif self.git_remote == "?":
|
||||
msg = "Resolve by manually checking out" \
|
||||
" a branch via SSH."
|
||||
else:
|
||||
msg = "Defaulting to previously tracked " \
|
||||
f"{self.git_remote}/{self.git_branch}."
|
||||
logging.info(
|
||||
f"Git Repo {self.alias}: HEAD detached on untracked "
|
||||
f"commit {branch_info}. {msg}")
|
||||
else:
|
||||
self.git_branch = branch_info
|
||||
self.valid_git_repo = True
|
||||
return True
|
||||
|
||||
def log_repo_info(self) -> None:
|
||||
logging.info(
|
||||
f"Git Repo {self.alias} Detected:\n"
|
||||
f"Owner: {self.git_owner}\n"
|
||||
f"Path: {self.git_path}\n"
|
||||
f"Remote: {self.git_remote}\n"
|
||||
f"Branch: {self.git_branch}\n"
|
||||
f"Remote URL: {self.upstream_url}\n"
|
||||
f"Current Commit SHA: {self.current_commit}\n"
|
||||
f"Upstream Commit SHA: {self.upstream_commit}\n"
|
||||
f"Current Version: {self.current_version}\n"
|
||||
f"Upstream Version: {self.upstream_version}\n"
|
||||
f"Is Dirty: {self.dirty}\n"
|
||||
f"Is Detached: {self.head_detached}\n"
|
||||
f"Commits Behind: {len(self.commits_behind)}")
|
||||
|
||||
def report_invalids(self, primary_branch: str) -> List[str]:
|
||||
invalids: List[str] = []
|
||||
upstream_url = self.upstream_url.lower()
|
||||
if upstream_url[-4:] != ".git":
|
||||
upstream_url += ".git"
|
||||
if upstream_url != self.origin_url:
|
||||
invalids.append(f"Unofficial remote url: {self.upstream_url}")
|
||||
if self.git_branch != primary_branch or self.git_remote != "origin":
|
||||
invalids.append(
|
||||
"Repo not on valid remote branch, expected: "
|
||||
f"origin/{primary_branch}, detected: "
|
||||
f"{self.git_remote}/{self.git_branch}")
|
||||
if self.head_detached:
|
||||
invalids.append("Detached HEAD detected")
|
||||
return invalids
|
||||
|
||||
def _verify_repo(self, check_remote: bool = False) -> None:
|
||||
if not self.valid_git_repo:
|
||||
raise self.server.error(
|
||||
f"Git Repo {self.alias}: repo not initialized")
|
||||
if check_remote:
|
||||
if self.git_remote == "?":
|
||||
raise self.server.error(
|
||||
f"Git Repo {self.alias}: No valid git remote detected")
|
||||
|
||||
async def reset(self) -> None:
|
||||
if self.git_remote == "?" or self.git_branch == "?":
|
||||
raise self.server.error("Cannot reset, unknown remote/branch")
|
||||
async with self.git_operation_lock:
|
||||
await self._run_git_cmd("clean -d -f", retries=2)
|
||||
await self._run_git_cmd(
|
||||
f"reset --hard {self.git_remote}/{self.git_branch}",
|
||||
retries=2)
|
||||
|
||||
async def fetch(self) -> None:
|
||||
self._verify_repo(check_remote=True)
|
||||
async with self.git_operation_lock:
|
||||
await self._run_git_cmd_async(
|
||||
f"fetch {self.git_remote} --prune --progress")
|
||||
|
||||
|
||||
async def pull(self) -> None:
|
||||
self._verify_repo()
|
||||
if self.head_detached:
|
||||
raise self.server.error(
|
||||
f"Git Repo {self.alias}: Cannot perform pull on a "
|
||||
"detached HEAD")
|
||||
async with self.git_operation_lock:
|
||||
await self._run_git_cmd_async("pull --progress")
|
||||
|
||||
async def list_branches(self) -> List[str]:
|
||||
self._verify_repo()
|
||||
async with self.git_operation_lock:
|
||||
resp = await self._run_git_cmd("branch --list")
|
||||
return resp.strip().split("\n")
|
||||
|
||||
async def remote(self, command: str) -> str:
|
||||
self._verify_repo(check_remote=True)
|
||||
async with self.git_operation_lock:
|
||||
resp = await self._run_git_cmd(
|
||||
f"remote {command}")
|
||||
return resp.strip()
|
||||
|
||||
async def describe(self, args: str = "") -> str:
|
||||
self._verify_repo()
|
||||
async with self.git_operation_lock:
|
||||
resp = await self._run_git_cmd(f"describe {args}".strip())
|
||||
return resp.strip()
|
||||
|
||||
async def rev_parse(self, args: str = "") -> str:
|
||||
self._verify_repo()
|
||||
async with self.git_operation_lock:
|
||||
resp = await self._run_git_cmd(f"rev-parse {args}".strip())
|
||||
return resp.strip()
|
||||
|
||||
async def get_config_item(self, item: str) -> str:
|
||||
self._verify_repo()
|
||||
async with self.git_operation_lock:
|
||||
resp = await self._run_git_cmd(f"config --get {item}")
|
||||
return resp.strip()
|
||||
|
||||
async def checkout(self, branch: Optional[str] = None) -> None:
|
||||
self._verify_repo()
|
||||
async with self.git_operation_lock:
|
||||
branch = branch or f"{self.git_remote}/{self.git_branch}"
|
||||
await self._run_git_cmd(f"checkout {branch} -q")
|
||||
|
||||
async def run_fsck(self) -> None:
|
||||
async with self.git_operation_lock:
|
||||
await self._run_git_cmd("fsck --full", timeout=300., retries=1)
|
||||
|
||||
async def clone(self) -> None:
|
||||
async with self.git_operation_lock:
|
||||
self.cmd_helper.notify_update_response(
|
||||
f"Git Repo {self.alias}: Starting Clone Recovery...")
|
||||
if self.backup_path.exists():
|
||||
shutil.rmtree(self.backup_path)
|
||||
self._check_lock_file_exists(remove=True)
|
||||
git_cmd = f"clone {self.origin_url} {self.backup_path}"
|
||||
try:
|
||||
await self._run_git_cmd_async(git_cmd, 1, False, False)
|
||||
except Exception as e:
|
||||
self.cmd_helper.notify_update_response(
|
||||
f"Git Repo {self.alias}: Git Clone Failed")
|
||||
raise self.server.error("Git Clone Error") from e
|
||||
if self.git_path.exists():
|
||||
shutil.rmtree(self.git_path)
|
||||
shutil.move(str(self.backup_path), str(self.git_path))
|
||||
self.cmd_helper.notify_update_response(
|
||||
f"Git Repo {self.alias}: Git Clone Complete")
|
||||
|
||||
async def get_commits_behind(self) -> List[Dict[str, Any]]:
|
||||
self._verify_repo()
|
||||
if self.is_current():
|
||||
return []
|
||||
async with self.git_operation_lock:
|
||||
branch = f"{self.git_remote}/{self.git_branch}"
|
||||
resp = await self._run_git_cmd(
|
||||
f"log {self.current_commit}..{branch} "
|
||||
f"--format={GIT_LOG_FMT} --max-count={GIT_MAX_LOG_CNT}")
|
||||
commits_behind: List[Dict[str, Any]] = []
|
||||
for log_entry in resp.split('\x1E'):
|
||||
log_entry = log_entry.strip()
|
||||
if not log_entry:
|
||||
continue
|
||||
log_items = [li.strip() for li in log_entry.split('\x1D')
|
||||
if li.strip()]
|
||||
cbh = [li.split(':', 1) for li in log_items]
|
||||
commits_behind.append(dict(cbh)) # type: ignore
|
||||
return commits_behind
|
||||
|
||||
async def get_tagged_commits(self) -> Dict[str, Any]:
|
||||
self._verify_repo()
|
||||
async with self.git_operation_lock:
|
||||
resp = await self._run_git_cmd(f"show-ref --tags -d")
|
||||
tagged_commits: Dict[str, Any] = {}
|
||||
tags = [tag.strip() for tag in resp.split('\n') if tag.strip()]
|
||||
for tag in tags:
|
||||
sha, ref = tag.split(' ', 1)
|
||||
ref = ref.split('/')[-1]
|
||||
if ref[-3:] == "^{}":
|
||||
# Dereference this commit and overwrite any existing tag
|
||||
ref = ref[:-3]
|
||||
tagged_commits[ref] = sha
|
||||
elif ref not in tagged_commits:
|
||||
# This could be a lightweight tag pointing to a commit. If
|
||||
# it is an annotated tag it will be overwritten by the
|
||||
# dereferenced tag
|
||||
tagged_commits[ref] = sha
|
||||
# Return tagged commits as SHA keys mapped to tag values
|
||||
return {v: k for k, v in tagged_commits.items()}
|
||||
|
||||
def get_repo_status(self) -> Dict[str, Any]:
|
||||
return {
|
||||
'detected_type': "git_repo",
|
||||
'remote_alias': self.git_remote,
|
||||
'branch': self.git_branch,
|
||||
'owner': self.git_owner,
|
||||
'version': self.current_version,
|
||||
'remote_version': self.upstream_version,
|
||||
'current_hash': self.current_commit,
|
||||
'remote_hash': self.upstream_commit,
|
||||
'is_dirty': self.dirty,
|
||||
'detached': self.head_detached,
|
||||
'commits_behind': self.commits_behind,
|
||||
'git_messages': self.git_messages,
|
||||
'full_version_string': self.full_version_string,
|
||||
'pristine': not self.dirty
|
||||
}
|
||||
|
||||
def get_version(self, upstream: bool = False) -> Tuple[Any, ...]:
|
||||
version = self.upstream_version if upstream else self.current_version
|
||||
return tuple(re.findall(r"\d+", version))
|
||||
|
||||
def is_detached(self) -> bool:
|
||||
return self.head_detached
|
||||
|
||||
def is_dirty(self) -> bool:
|
||||
return self.dirty
|
||||
|
||||
def is_current(self) -> bool:
|
||||
return self.current_commit == self.upstream_commit
|
||||
|
||||
def _check_lock_file_exists(self, remove: bool = False) -> bool:
|
||||
lock_path = self.git_path.joinpath(".git/index.lock")
|
||||
if lock_path.is_file():
|
||||
if remove:
|
||||
logging.info(f"Git Repo {self.alias}: Git lock file found "
|
||||
"after git process exited, removing")
|
||||
try:
|
||||
os.remove(lock_path)
|
||||
except Exception:
|
||||
pass
|
||||
return True
|
||||
return False
|
||||
|
||||
async def _wait_for_lock_release(self, timeout: int = 60) -> None:
|
||||
while timeout:
|
||||
if self._check_lock_file_exists():
|
||||
if not timeout % 10:
|
||||
logging.info(f"Git Repo {self.alias}: Git lock file "
|
||||
f"exists, {timeout} seconds remaining "
|
||||
"before removal.")
|
||||
await asyncio.sleep(1.)
|
||||
timeout -= 1
|
||||
else:
|
||||
return
|
||||
self._check_lock_file_exists(remove=True)
|
||||
|
||||
async def _repair_loose_objects(self) -> bool:
|
||||
try:
|
||||
await self.cmd_helper.run_cmd_with_response(
|
||||
"find .git/objects/ -type f -empty | xargs rm",
|
||||
timeout=10., retries=1, cwd=str(self.git_path))
|
||||
await self._run_git_cmd_async(
|
||||
"fetch --all -p", retries=1, fix_loose=False)
|
||||
await self._run_git_cmd("fsck --full", timeout=300., retries=1)
|
||||
except Exception:
|
||||
logging.exception("Attempt to repair loose objects failed")
|
||||
return False
|
||||
return True
|
||||
|
||||
async def _run_git_cmd_async(self,
|
||||
cmd: str,
|
||||
retries: int = 5,
|
||||
need_git_path: bool = True,
|
||||
fix_loose: bool = True
|
||||
) -> None:
|
||||
# Fetch and pull require special handling. If the request
|
||||
# gets delayed we do not want to terminate it while the command
|
||||
# is processing.
|
||||
await self._wait_for_lock_release()
|
||||
env = os.environ.copy()
|
||||
env.update(GIT_ENV_VARS)
|
||||
if need_git_path:
|
||||
git_cmd = f"git -C {self.git_path} {cmd}"
|
||||
else:
|
||||
git_cmd = f"git {cmd}"
|
||||
scmd = self.cmd_helper.build_shell_command(
|
||||
git_cmd, callback=self._handle_process_output,
|
||||
env=env)
|
||||
while retries:
|
||||
self.git_messages.clear()
|
||||
ioloop = IOLoop.current()
|
||||
self.fetch_input_recd = False
|
||||
self.fetch_timeout_handle = ioloop.call_later(
|
||||
GIT_ASYNC_TIMEOUT, self._check_process_active, # type: ignore
|
||||
scmd, cmd)
|
||||
try:
|
||||
await scmd.run(timeout=0)
|
||||
except Exception:
|
||||
pass
|
||||
ioloop.remove_timeout(self.fetch_timeout_handle)
|
||||
ret = scmd.get_return_code()
|
||||
if ret == 0:
|
||||
self.git_messages.clear()
|
||||
return
|
||||
elif fix_loose:
|
||||
if GIT_OBJ_ERR in "\n".join(self.git_messages):
|
||||
ret = await self._repair_loose_objects()
|
||||
if ret:
|
||||
break
|
||||
# since the attept to repair failed, bypass retries
|
||||
# and immediately raise an exception
|
||||
raise self.server.error(
|
||||
f"Unable to repair loose objects, use hard recovery")
|
||||
retries -= 1
|
||||
await asyncio.sleep(.5)
|
||||
self._check_lock_file_exists(remove=True)
|
||||
raise self.server.error(f"Git Command '{cmd}' failed")
|
||||
|
||||
def _handle_process_output(self, output: bytes) -> None:
|
||||
self.fetch_input_recd = True
|
||||
out = output.decode().strip()
|
||||
if out:
|
||||
self.git_messages.append(out)
|
||||
self.cmd_helper.notify_update_response(out)
|
||||
logging.debug(
|
||||
f"Git Repo {self.alias}: {out}")
|
||||
|
||||
async def _check_process_active(self,
|
||||
scmd: shell_command.ShellCommand,
|
||||
cmd_name: str
|
||||
) -> None:
|
||||
ret = scmd.get_return_code()
|
||||
if ret is not None:
|
||||
logging.debug(f"Git Repo {self.alias}: {cmd_name} returned")
|
||||
return
|
||||
if self.fetch_input_recd:
|
||||
# Received some input, reschedule timeout
|
||||
logging.debug(
|
||||
f"Git Repo {self.alias}: {cmd_name} active, rescheduling")
|
||||
ioloop = IOLoop.current()
|
||||
self.fetch_input_recd = False
|
||||
self.fetch_timeout_handle = ioloop.call_later(
|
||||
GIT_ASYNC_TIMEOUT, self._check_process_active, # type: ignore
|
||||
scmd, cmd_name)
|
||||
else:
|
||||
# Request has timed out with no input, terminate it
|
||||
logging.debug(f"Git Repo {self.alias}: {cmd_name} timed out")
|
||||
# Cancel with SIGKILL
|
||||
await scmd.cancel(2)
|
||||
|
||||
async def _run_git_cmd(self,
|
||||
git_args: str,
|
||||
timeout: float = 20.,
|
||||
retries: int = 5,
|
||||
env: Optional[Dict[str, str]] = None
|
||||
) -> str:
|
||||
try:
|
||||
return await self.cmd_helper.run_cmd_with_response(
|
||||
f"git -C {self.git_path} {git_args}",
|
||||
timeout=timeout, retries=retries, env=env, sig_idx=2)
|
||||
except self.cmd_helper.scmd_error as e:
|
||||
stdout = e.stdout.decode().strip()
|
||||
stderr = e.stderr.decode().strip()
|
||||
if stdout:
|
||||
self.git_messages.append(stdout)
|
||||
if stderr:
|
||||
self.git_messages.append(stderr)
|
||||
raise
|
||||
@@ -0,0 +1,16 @@
|
||||
# Supplemental configuration for Moonraker's Update Manager
|
||||
# component. This file should not be modified.
|
||||
|
||||
[update_manager moonraker]
|
||||
origin: https://github.com/arksine/moonraker.git
|
||||
requirements: scripts/moonraker-requirements.txt
|
||||
venv_args: -p python3
|
||||
install_script: scripts/install-moonraker.sh
|
||||
host_repo: arksine/moonraker
|
||||
|
||||
[update_manager klipper]
|
||||
origin: https://github.com/kevinoconnor/klipper.git
|
||||
requirements: scripts/klippy-requirements.txt
|
||||
venv_args: -p python2
|
||||
install_script: scripts/install-octopi.sh
|
||||
host_repo: arksine/moonraker
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,416 @@
|
||||
# Zip Application Deployment implementation
|
||||
#
|
||||
# Copyright (C) 2021 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
from __future__ import annotations
|
||||
import asyncio
|
||||
import os
|
||||
import pathlib
|
||||
import json
|
||||
import shutil
|
||||
import re
|
||||
import time
|
||||
import tempfile
|
||||
import zipfile
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from tornado.ioloop import IOLoop
|
||||
from .app_deploy import AppDeploy
|
||||
from utils import verify_source
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Tuple,
|
||||
Optional,
|
||||
Dict,
|
||||
List,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from confighelper import ConfigHelper
|
||||
from .update_manager import CommandHelper
|
||||
|
||||
RINFO_KEYS = [
|
||||
"git_version", "long_version", "commit_hash", "source_checksum",
|
||||
"ignored_exts", "ignored_dirs", "build_date", "channel",
|
||||
"owner_repo", "host_repo", "release_tag"
|
||||
]
|
||||
|
||||
class ZipDeploy(AppDeploy):
|
||||
def __init__(self,
|
||||
config: ConfigHelper,
|
||||
cmd_helper: CommandHelper,
|
||||
app_params: Optional[Dict[str, Any]]
|
||||
) -> None:
|
||||
super().__init__(config, cmd_helper, app_params)
|
||||
self.official_repo: str = "?"
|
||||
self.owner: str = "?"
|
||||
# Extract repo from origin for validation
|
||||
match = re.match(r"https?://(?:www\.)?github.com/([^/]+/[^.]+)",
|
||||
self.origin)
|
||||
if match is not None:
|
||||
self.official_repo = match.group(1)
|
||||
self.owner = self.official_repo.split('/')[0]
|
||||
else:
|
||||
raise config.error(
|
||||
"Invalid url set for 'origin' option in section "
|
||||
f"[{config.get_name()}]. Unable to extract owner/repo.")
|
||||
self.host_repo: str = config.get('host_repo', self.official_repo)
|
||||
self.detected_type: str = "?"
|
||||
self.source_checksum: str = ""
|
||||
self.pristine = False
|
||||
self.verified = False
|
||||
self.build_date: int = 0
|
||||
self.full_version: str = "?"
|
||||
self.short_version: str = "?"
|
||||
self.commit_hash: str = "?"
|
||||
self.lastest_hash: str = "?"
|
||||
self.latest_version: str = "?"
|
||||
self.latest_checksum: str = "?"
|
||||
self.latest_build_date: int = 0
|
||||
self.commit_log: List[Dict[str, Any]] = []
|
||||
self.package_list: List[str] = []
|
||||
self.python_pkg_list: List[str] = []
|
||||
self.release_download_info: Tuple[str, str, int] = ("?", "?", 0)
|
||||
self.errors: List[str] = []
|
||||
self.mutex: asyncio.Lock = asyncio.Lock()
|
||||
self.refresh_event: Optional[asyncio.Event] = None
|
||||
|
||||
@staticmethod
|
||||
async def from_application(app: AppDeploy) -> ZipDeploy:
|
||||
new_app = ZipDeploy(app.config, app.cmd_helper, app.app_params)
|
||||
await new_app.reinstall()
|
||||
return new_app
|
||||
|
||||
async def _parse_info_file(self, file_name: str) -> Dict[str, Any]:
|
||||
try:
|
||||
info_file = self.path.joinpath(file_name)
|
||||
with ThreadPoolExecutor(max_workers=1) as tpe:
|
||||
info_bytes = await IOLoop.current().run_in_executor(
|
||||
tpe, info_file.read_text)
|
||||
info: Dict[str, Any] = json.loads(info_bytes)
|
||||
except Exception:
|
||||
self.log_exc(f"Unable to parse info file {file_name}")
|
||||
info = {}
|
||||
return info
|
||||
|
||||
def _get_tag_version(self, version_string: str) -> str:
|
||||
tag_version: str = "?"
|
||||
ver_match = re.match(r"v\d+\.\d+\.\d-\d+", version_string)
|
||||
if ver_match:
|
||||
tag_version = ver_match.group()
|
||||
return tag_version
|
||||
|
||||
async def refresh(self) -> None:
|
||||
if self.refresh_event is not None:
|
||||
await self.refresh_event.wait()
|
||||
return
|
||||
async with self.mutex:
|
||||
self.refresh_event = asyncio.Event()
|
||||
try:
|
||||
await self._update_repo_state()
|
||||
except Exception:
|
||||
self.verified = False
|
||||
self.log_exc("Error refreshing application state")
|
||||
self.refresh_event.set()
|
||||
self.refresh_event = None
|
||||
|
||||
async def _update_repo_state(self) -> None:
|
||||
self.errors = []
|
||||
self._is_valid = False
|
||||
self.verified = False
|
||||
release_info = await self._parse_info_file(".release_info")
|
||||
dep_info = await self._parse_info_file(".dependencies")
|
||||
for key in RINFO_KEYS:
|
||||
if key not in release_info:
|
||||
self._add_error(f"Missing release info item: {key}")
|
||||
self.detected_type = "?"
|
||||
self.need_channel_update = False
|
||||
if 'channel' in release_info:
|
||||
local_channel = release_info['channel']
|
||||
self.need_channel_update = self.channel != local_channel
|
||||
self.detected_type = "zip"
|
||||
if local_channel == "beta":
|
||||
self.detected_type = "zip_beta"
|
||||
self.full_version = release_info.get('long_version', "?")
|
||||
self.short_version = self._get_tag_version(
|
||||
release_info.get('git_version', ""))
|
||||
self.commit_hash = release_info.get('commit_hash', "?")
|
||||
self.build_date = release_info.get('build_date', 0)
|
||||
owner_repo = release_info.get('owner_repo', "?")
|
||||
if self.official_repo != owner_repo:
|
||||
self._add_error(
|
||||
f"Owner repo mismatch. Received {owner_repo}, "
|
||||
f"official: {self.official_repo}")
|
||||
# validate the local source code
|
||||
with ThreadPoolExecutor(max_workers=1) as tpe:
|
||||
res = await IOLoop.current().run_in_executor(
|
||||
tpe, verify_source, self.path)
|
||||
if res is not None:
|
||||
self.source_checksum, self.pristine = res
|
||||
if self.name in ["moonraker", "klipper"]:
|
||||
self.server.add_log_rollover_item(
|
||||
f"{self.name}_validation",
|
||||
f"{self.name} checksum: {self.source_checksum}, "
|
||||
f"pristine: {self.pristine}")
|
||||
else:
|
||||
self._add_error("Unable to validate source checksum")
|
||||
self.source_checksum = ""
|
||||
self.pristine = False
|
||||
self.package_list = sorted(dep_info.get(
|
||||
'debian', {}).get('packages', []))
|
||||
self.python_pkg_list = sorted(dep_info.get('python', []))
|
||||
# Retreive version info from github to check for updates and
|
||||
# validate local release info
|
||||
host_repo = release_info.get('host_repo', "?")
|
||||
release_tag = release_info.get('release_tag', "?")
|
||||
if host_repo != self.host_repo:
|
||||
self._add_error(
|
||||
f"Host repo mismatch, received: {host_repo}, "
|
||||
f"expected: {self.host_repo}. This could result in "
|
||||
" a failed update.")
|
||||
url = f"https://api.github.com/repos/{self.host_repo}/releases"
|
||||
current_release, latest_release = await self._fetch_github_releases(
|
||||
url, release_tag)
|
||||
await self._validate_current_release(release_info, current_release)
|
||||
if not self.errors:
|
||||
self.verified = True
|
||||
await self._process_latest_release(latest_release)
|
||||
self._log_zipapp_info()
|
||||
|
||||
async def _fetch_github_releases(self,
|
||||
release_url: str,
|
||||
current_tag: Optional[str] = None
|
||||
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
|
||||
try:
|
||||
releases = await self.cmd_helper.github_api_request(release_url)
|
||||
assert isinstance(releases, list)
|
||||
except Exception:
|
||||
self.log_exc("Error fetching releases from GitHub")
|
||||
return {}, {}
|
||||
release: Dict[str, Any]
|
||||
latest_release: Dict[str, Any] = {}
|
||||
current_release: Dict[str, Any] = {}
|
||||
for release in releases:
|
||||
if not latest_release:
|
||||
if release['prerelease']:
|
||||
if self.channel != "stable":
|
||||
latest_release = release
|
||||
elif self.channel == "stable":
|
||||
latest_release = release
|
||||
if current_tag is not None:
|
||||
if not current_release and release['tag_name'] == current_tag:
|
||||
current_release = release
|
||||
if latest_release and current_release:
|
||||
break
|
||||
elif latest_release:
|
||||
break
|
||||
return current_release, latest_release
|
||||
|
||||
async def _validate_current_release(self,
|
||||
release_info: Dict[str, Any],
|
||||
release: Dict[str, Any]
|
||||
) -> None:
|
||||
if not release:
|
||||
self._add_error("Unable to find current release on GitHub")
|
||||
return
|
||||
asset_info = self._get_asset_urls(release, ["RELEASE_INFO"])
|
||||
if "RELEASE_INFO" not in asset_info:
|
||||
self._add_error(
|
||||
"RELEASE_INFO not found in current release assets")
|
||||
info_url, content_type, size = asset_info['RELEASE_INFO']
|
||||
rinfo_bytes = await self.cmd_helper.http_download_request(
|
||||
info_url, content_type)
|
||||
github_rinfo: Dict[str, Any] = json.loads(rinfo_bytes)
|
||||
if github_rinfo.get(self.name, {}) != release_info:
|
||||
self._add_error(
|
||||
"Local release info does not match the remote")
|
||||
else:
|
||||
self.log_info("Current Release Info Validated")
|
||||
|
||||
async def _process_latest_release(self, release: Dict[str, Any]):
|
||||
if not release:
|
||||
self._add_error("Unable to find latest release on GitHub")
|
||||
return
|
||||
zip_file_name = f"{self.name}.zip"
|
||||
asset_names = ["RELEASE_INFO", "COMMIT_LOG", zip_file_name]
|
||||
asset_info = self._get_asset_urls(release, asset_names)
|
||||
if "RELEASE_INFO" in asset_info:
|
||||
asset_url, content_type, size = asset_info['RELEASE_INFO']
|
||||
rinfo_bytes = await self.cmd_helper.http_download_request(
|
||||
asset_url, content_type)
|
||||
update_release_info: Dict[str, Any] = json.loads(rinfo_bytes)
|
||||
update_info = update_release_info.get(self.name, {})
|
||||
self.lastest_hash = update_info.get('commit_hash', "?")
|
||||
self.latest_checksum = update_info.get('source_checksum', "?")
|
||||
self.latest_version = self._get_tag_version(
|
||||
update_info.get('git_version', "?"))
|
||||
self.latest_build_date = update_info.get('build_date', 0)
|
||||
else:
|
||||
self._add_error(
|
||||
"RELEASE_INFO not found in latest release assets")
|
||||
self.commit_log = []
|
||||
if self.short_version == self.latest_version:
|
||||
# No need to report the commit log when versions match
|
||||
return
|
||||
if "COMMIT_LOG" in asset_info:
|
||||
asset_url, content_type, size = asset_info['COMMIT_LOG']
|
||||
commit_bytes = await self.cmd_helper.http_download_request(
|
||||
asset_url, content_type)
|
||||
commit_info: Dict[str, Any] = json.loads(commit_bytes)
|
||||
self.commit_log = commit_info.get(self.name, [])
|
||||
if zip_file_name in asset_info:
|
||||
self.release_download_info = asset_info[zip_file_name]
|
||||
self._is_valid = True
|
||||
else:
|
||||
self.release_download_info = ("?", "?", 0)
|
||||
self._add_error(f"Release asset {zip_file_name} not found")
|
||||
|
||||
def _get_asset_urls(self,
|
||||
release: Dict[str, Any],
|
||||
filenames: List[str]
|
||||
) -> Dict[str, Tuple[str, str, int]]:
|
||||
asset_info: Dict[str, Tuple[str, str, int]] = {}
|
||||
asset: Dict[str, Any]
|
||||
for asset in release.get('assets', []):
|
||||
name = asset['name']
|
||||
if name in filenames:
|
||||
rinfo_url = asset['browser_download_url']
|
||||
content_type = asset['content_type']
|
||||
size = asset['size']
|
||||
asset_info[name] = (rinfo_url, content_type, size)
|
||||
filenames.remove(name)
|
||||
if not filenames:
|
||||
break
|
||||
return asset_info
|
||||
|
||||
def _add_error(self, warning: str):
|
||||
self.log_info(warning)
|
||||
self.errors.append(warning)
|
||||
|
||||
def _log_zipapp_info(self):
|
||||
self.log_info(
|
||||
"\nZip Application Distribution Detected\n"
|
||||
f" Valid: {self._is_valid}\n"
|
||||
f" Verified: {self.verified}\n"
|
||||
f" Channel: {self.channel}\n"
|
||||
f" Repo: {self.official_repo}\n"
|
||||
f" Path: {self.path}\n"
|
||||
f" Pristine: {self.pristine}\n"
|
||||
f" Need Channel Update: {self.need_channel_update}\n"
|
||||
f" Commits Behind: {len(self.commit_log)}\n"
|
||||
f"Current Release Info:\n"
|
||||
f" Source Checksum: {self.source_checksum}\n"
|
||||
f" Commit SHA: {self.commit_hash}\n"
|
||||
f" Long Version: {self.full_version}\n"
|
||||
f" Short Version: {self.short_version}\n"
|
||||
f" Build Date: {time.ctime(self.build_date)}\n"
|
||||
f"Latest Available Release Info:\n"
|
||||
f" Source Checksum: {self.latest_checksum}\n"
|
||||
f" Commit SHA: {self.lastest_hash}\n"
|
||||
f" Version: {self.latest_version}\n"
|
||||
f" Build Date: {time.ctime(self.latest_build_date)}\n"
|
||||
f" Download URL: {self.release_download_info[0]}\n"
|
||||
f" Content Type: {self.release_download_info[1]}\n"
|
||||
f" Download Size: {self.release_download_info[2]}"
|
||||
)
|
||||
|
||||
async def _update_dependencies(self,
|
||||
npm_hash,
|
||||
force: bool = False
|
||||
) -> None:
|
||||
new_deps = await self._parse_info_file('.dependencies')
|
||||
system_pkgs = sorted(
|
||||
new_deps.get('debian', {}).get('packages', []))
|
||||
python_pkgs = sorted(new_deps.get('python', []))
|
||||
if system_pkgs:
|
||||
if force or system_pkgs != self.package_list:
|
||||
await self._install_packages(system_pkgs)
|
||||
if python_pkgs:
|
||||
if force or python_pkgs != self.python_pkg_list:
|
||||
await self._update_virtualenv(python_pkgs)
|
||||
ret = await self._check_need_update(npm_hash, self.npm_pkg_json)
|
||||
if force or ret:
|
||||
if self.npm_pkg_json is not None:
|
||||
self.notify_status("Updating Node Packages...")
|
||||
try:
|
||||
await self.cmd_helper.run_cmd(
|
||||
"npm ci --only=prod", notify=True, timeout=600.,
|
||||
cwd=str(self.path))
|
||||
except Exception:
|
||||
self.notify_status("Node Package Update failed")
|
||||
|
||||
def _extract_release(self, release_zip: pathlib.Path) -> None:
|
||||
if self.path.is_dir():
|
||||
shutil.rmtree(self.path)
|
||||
os.mkdir(self.path)
|
||||
with zipfile.ZipFile(release_zip) as zf:
|
||||
zf.extractall(self.path)
|
||||
|
||||
async def update(self, force_dep_update: bool = False) -> bool:
|
||||
async with self.mutex:
|
||||
if not self._is_valid:
|
||||
raise self.log_exc("Update aborted, repo not valid", False)
|
||||
if self.short_version == self.latest_version:
|
||||
# already up to date
|
||||
return False
|
||||
self.cmd_helper.notify_update_response(
|
||||
f"Updating Application {self.name}...")
|
||||
npm_hash = await self._get_file_hash(self.npm_pkg_json)
|
||||
dl_url, content_type, size = self.release_download_info
|
||||
self.notify_status("Starting Download...")
|
||||
with tempfile.TemporaryDirectory(
|
||||
suffix=self.name, prefix="app") as tempdirname:
|
||||
tempdir = pathlib.Path(tempdirname)
|
||||
temp_download_file = tempdir.joinpath(f"{self.name}.zip")
|
||||
await self.cmd_helper.streaming_download_request(
|
||||
dl_url, temp_download_file, content_type, size)
|
||||
self.notify_status(
|
||||
f"Download Complete, extracting release to '{self.path}'")
|
||||
with ThreadPoolExecutor(max_workers=1) as tpe:
|
||||
await IOLoop.current().run_in_executor(
|
||||
tpe, self._extract_release, temp_download_file)
|
||||
await self._update_dependencies(npm_hash, force=force_dep_update)
|
||||
await self._update_repo_state()
|
||||
await self.restart_service()
|
||||
self.notify_status("Update Finished...", is_complete=True)
|
||||
return True
|
||||
|
||||
async def recover(self,
|
||||
hard: bool = False,
|
||||
force_dep_update: bool = False
|
||||
) -> None:
|
||||
async with self.mutex:
|
||||
url = f"https://api.github.com/repos/{self.host_repo}/releases"
|
||||
releases = await self._fetch_github_releases(url)
|
||||
await self._process_latest_release(releases[1])
|
||||
await self.update(force_dep_update=force_dep_update)
|
||||
|
||||
async def reinstall(self) -> None:
|
||||
await self.recover(force_dep_update=True)
|
||||
|
||||
def get_update_status(self) -> Dict[str, Any]:
|
||||
status = super().get_update_status()
|
||||
# XXX - Currently this reports status matching
|
||||
# that of the git repo so as to not break existing
|
||||
# client functionality. In the future it would be
|
||||
# good to report values that are specifc
|
||||
status.update({
|
||||
'detected_type': self.detected_type,
|
||||
'remote_alias': "origin",
|
||||
'branch': "master",
|
||||
'owner': self.owner,
|
||||
'version': self.short_version,
|
||||
'remote_version': self.latest_version,
|
||||
'current_hash': self.commit_hash,
|
||||
'remote_hash': self.lastest_hash,
|
||||
'is_dirty': False,
|
||||
'detached': not self.verified,
|
||||
'commits_behind': self.commit_log,
|
||||
'git_messages': self.errors,
|
||||
'full_version_string': self.full_version,
|
||||
'pristine': self.pristine,
|
||||
})
|
||||
return status
|
||||
+124
-31
@@ -3,93 +3,186 @@
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
|
||||
from __future__ import annotations
|
||||
import configparser
|
||||
import os
|
||||
import logging
|
||||
from utils import SentinelClass
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Callable,
|
||||
IO,
|
||||
TypeVar,
|
||||
Union,
|
||||
Dict,
|
||||
List,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from moonraker import Server
|
||||
_T = TypeVar("_T")
|
||||
ConfigVal = Union[None, int, float, bool, str]
|
||||
|
||||
SENTINEL = SentinelClass.get_instance()
|
||||
|
||||
class ConfigError(Exception):
|
||||
pass
|
||||
|
||||
class Sentinel:
|
||||
pass
|
||||
|
||||
class ConfigHelper:
|
||||
error = ConfigError
|
||||
def __init__(self, server, config, section):
|
||||
def __init__(self,
|
||||
server: Server,
|
||||
config: configparser.ConfigParser,
|
||||
section: str,
|
||||
orig_sects: List[str],
|
||||
parsed: Dict[str, Dict[str, ConfigVal]] = {}
|
||||
) -> None:
|
||||
self.server = server
|
||||
self.config = config
|
||||
self.section = section
|
||||
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
|
||||
|
||||
def get_server(self):
|
||||
def get_server(self) -> Server:
|
||||
return self.server
|
||||
|
||||
def __getitem__(self, key):
|
||||
def __getitem__(self, key: str) -> ConfigHelper:
|
||||
return self.getsection(key)
|
||||
|
||||
def __contains__(self, key):
|
||||
def __contains__(self, key: str) -> bool:
|
||||
return key in self.config
|
||||
|
||||
def get_name(self):
|
||||
def get_name(self) -> str:
|
||||
return self.section
|
||||
|
||||
def get_prefix_sections(self, prefix):
|
||||
def get_options(self) -> Dict[str, str]:
|
||||
return dict(self.config[self.section])
|
||||
|
||||
def get_prefix_sections(self, prefix: str) -> List[str]:
|
||||
return [s for s in self.sections() if s.startswith(prefix)]
|
||||
|
||||
def getsection(self, section):
|
||||
def getsection(self, section: str) -> ConfigHelper:
|
||||
if section not in self.config:
|
||||
raise ConfigError(f"No section [{section}] in config")
|
||||
return ConfigHelper(self.server, self.config, section)
|
||||
return ConfigHelper(self.server, self.config, section,
|
||||
self.orig_sections, self.parsed)
|
||||
|
||||
def _get_option(self, func, option, default):
|
||||
def _get_option(self,
|
||||
func: Callable[..., Any],
|
||||
option: str,
|
||||
default: Union[SentinelClass, _T]
|
||||
) -> _T:
|
||||
try:
|
||||
val = func(option, default)
|
||||
except Exception:
|
||||
raise ConfigError(
|
||||
f"Error parsing option ({option}) from "
|
||||
f"section [{self.section}]")
|
||||
if val == Sentinel:
|
||||
if isinstance(val, SentinelClass):
|
||||
raise ConfigError(
|
||||
f"No option found ({option}) in section [{self.section}]")
|
||||
if self.section in self.orig_sections:
|
||||
# Only track sections included in the original config
|
||||
self.parsed[self.section][option] = val
|
||||
return val
|
||||
|
||||
def get(self, option, default=Sentinel):
|
||||
def get(self,
|
||||
option: str,
|
||||
default: Union[SentinelClass, _T] = SENTINEL
|
||||
) -> Union[str, _T]:
|
||||
return self._get_option(
|
||||
self.config[self.section].get, option, default)
|
||||
|
||||
def getint(self, option, default=Sentinel):
|
||||
def getint(self,
|
||||
option: str,
|
||||
default: Union[SentinelClass, _T] = SENTINEL
|
||||
) -> Union[int, _T]:
|
||||
return self._get_option(
|
||||
self.config[self.section].getint, option, default)
|
||||
|
||||
def getboolean(self, option, default=Sentinel):
|
||||
def getboolean(self,
|
||||
option: str,
|
||||
default: Union[SentinelClass, _T] = SENTINEL
|
||||
) -> Union[bool, _T]:
|
||||
return self._get_option(
|
||||
self.config[self.section].getboolean, option, default)
|
||||
|
||||
def getfloat(self, option, default=Sentinel):
|
||||
return self._get_item(
|
||||
def getfloat(self,
|
||||
option: str,
|
||||
default: Union[SentinelClass, _T] = SENTINEL
|
||||
) -> Union[float, _T]:
|
||||
return self._get_option(
|
||||
self.config[self.section].getfloat, option, default)
|
||||
|
||||
def get_configuration(server, system_args):
|
||||
cfg_file_path = os.path.normpath(os.path.expanduser(
|
||||
system_args.configfile))
|
||||
def read_supplemental_config(self, file_name: str) -> ConfigHelper:
|
||||
cfg_file_path = os.path.normpath(os.path.expanduser(file_name))
|
||||
if not os.path.isfile(cfg_file_path):
|
||||
raise ConfigError(
|
||||
f"Configuration File Not Found: '{cfg_file_path}''")
|
||||
try:
|
||||
sup_cfg = configparser.ConfigParser(interpolation=None)
|
||||
sup_cfg.read(cfg_file_path)
|
||||
except Exception:
|
||||
raise ConfigError(f"Error Reading Config: '{cfg_file_path}'")
|
||||
sections = sup_cfg.sections()
|
||||
return ConfigHelper(self.server, sup_cfg, sections[0], sections)
|
||||
|
||||
def write_config(self, file_obj: IO[str]) -> None:
|
||||
self.config.write(file_obj)
|
||||
|
||||
def get_parsed_config(self) -> Dict[str, Dict[str, ConfigVal]]:
|
||||
return dict(self.parsed)
|
||||
|
||||
def validate_config(self) -> None:
|
||||
for sect in self.orig_sections:
|
||||
if sect not in self.parsed:
|
||||
self.server.add_warning(
|
||||
f"Unparsed config section [{sect}] detected. This "
|
||||
"may be the result of a component that failed to "
|
||||
"load. In the future this will result in a startup "
|
||||
"error.")
|
||||
continue
|
||||
parsed_opts = self.parsed[sect]
|
||||
for opt, val in self.config.items(sect):
|
||||
if opt not in parsed_opts:
|
||||
self.server.add_warning(
|
||||
f"Invalid config option '{opt}' detected in section "
|
||||
f"[{sect}]. Remove the option to resolve this issue. "
|
||||
"In the future this will result in a startup error.")
|
||||
|
||||
def get_configuration(server: Server,
|
||||
app_args: Dict[str, Any]
|
||||
) -> ConfigHelper:
|
||||
cfg_file_path: str = os.path.normpath(os.path.expanduser(
|
||||
app_args['config_file']))
|
||||
if not os.path.isfile(cfg_file_path):
|
||||
raise ConfigError(f"Configuration File Not Found: '{cfg_file_path}''")
|
||||
raise ConfigError(
|
||||
f"Configuration File Not Found: '{cfg_file_path}''")
|
||||
if not os.access(cfg_file_path, os.R_OK | os.W_OK):
|
||||
raise ConfigError(
|
||||
"Moonraker does not have Read/Write permission for "
|
||||
f"config file at path '{cfg_file_path}'")
|
||||
config = configparser.ConfigParser(interpolation=None)
|
||||
try:
|
||||
config.read(cfg_file_path)
|
||||
except Exception:
|
||||
raise ConfigError(f"Error Reading Config: '{cfg_file_path}'") from None
|
||||
|
||||
except Exception as e:
|
||||
raise ConfigError(f"Error Reading Config: '{cfg_file_path}'") from e
|
||||
try:
|
||||
server_cfg = config['server']
|
||||
except KeyError:
|
||||
raise ConfigError("No section [server] in config")
|
||||
|
||||
if server_cfg.get('enable_debug_logging', True):
|
||||
logging.getLogger().setLevel(logging.DEBUG)
|
||||
orig_sections = config.sections()
|
||||
try:
|
||||
orig_sections.remove("DEFAULT")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
config['system_args'] = {
|
||||
'logfile': system_args.logfile,
|
||||
'software_version': system_args.software_version}
|
||||
return ConfigHelper(server, config, 'server')
|
||||
return ConfigHelper(server, config, 'server', orig_sections)
|
||||
Regular → Executable
+316
-133
@@ -1,16 +1,21 @@
|
||||
#!/usr/bin/env python3
|
||||
# Moonraker - HTTP/Websocket API Server for Klipper
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
|
||||
from __future__ import annotations
|
||||
import 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
|
||||
@@ -19,60 +24,108 @@ from tornado.ioloop import IOLoop
|
||||
from tornado.util import TimeoutError
|
||||
from tornado.locks import Event
|
||||
from app import MoonrakerApp
|
||||
from utils import ServerError
|
||||
from utils import ServerError, SentinelClass
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Optional,
|
||||
Callable,
|
||||
Coroutine,
|
||||
Tuple,
|
||||
Dict,
|
||||
List,
|
||||
Union,
|
||||
TypeVar,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from websockets import WebRequest, Subscribable
|
||||
from components.data_store import DataStore
|
||||
from components.klippy_apis import KlippyAPI
|
||||
from components.file_manager.file_manager import FileManager
|
||||
FlexCallback = Callable[..., Optional[Coroutine]]
|
||||
_T = TypeVar("_T")
|
||||
|
||||
INIT_TIME = .25
|
||||
LOG_ATTEMPT_INTERVAL = int(2. / INIT_TIME + .5)
|
||||
MAX_LOG_ATTEMPTS = 10 * LOG_ATTEMPT_INTERVAL
|
||||
|
||||
CORE_PLUGINS = [
|
||||
'file_manager', 'klippy_apis', 'machine',
|
||||
'data_store', 'shell_command']
|
||||
CORE_COMPONENTS = [
|
||||
'database', 'file_manager', 'klippy_apis', 'machine',
|
||||
'data_store', 'shell_command', 'proc_stats']
|
||||
|
||||
class Sentinel:
|
||||
pass
|
||||
SENTINEL = SentinelClass.get_instance()
|
||||
|
||||
class Server:
|
||||
error = ServerError
|
||||
def __init__(self, args):
|
||||
config = confighelper.get_configuration(self, args)
|
||||
self.host = config.get('host', "0.0.0.0")
|
||||
self.port = config.getint('port', 7125)
|
||||
def __init__(self,
|
||||
args: Dict[str, Any],
|
||||
file_logger: Optional[utils.MoonrakerLoggingHandler]
|
||||
) -> None:
|
||||
self.file_logger = file_logger
|
||||
self.app_args = args
|
||||
self.config = config = confighelper.get_configuration(self, args)
|
||||
# log config file
|
||||
strio = io.StringIO()
|
||||
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: str = config.get('host', "0.0.0.0")
|
||||
self.port: int = config.getint('port', 7125)
|
||||
self.ssl_port: int = config.getint('ssl_port', 7130)
|
||||
self.exit_reason: str = ""
|
||||
|
||||
# Event initialization
|
||||
self.events = {}
|
||||
self.events: Dict[str, List[FlexCallback]] = {}
|
||||
|
||||
# Klippy Connection Handling
|
||||
self.klippy_address = config.get(
|
||||
self.klippy_address: str = config.get(
|
||||
'klippy_uds_address', "/tmp/klippy_uds")
|
||||
self.klippy_connection = KlippyConnection(
|
||||
self.process_command, self.on_connection_closed)
|
||||
self.klippy_info = {}
|
||||
self.init_list = []
|
||||
self.init_handle = None
|
||||
self.init_attempts = 0
|
||||
self.klippy_state = "disconnected"
|
||||
self.subscriptions = {}
|
||||
self.klippy_info: Dict[str, Any] = {}
|
||||
self.init_list: List[str] = []
|
||||
self.init_handle: Optional[object] = None
|
||||
self.init_attempts: int = 0
|
||||
self.klippy_state: str = "disconnected"
|
||||
self.klippy_disconnect_evt: Optional[Event] = None
|
||||
self.subscriptions: Dict[Subscribable, Dict[str, Any]] = {}
|
||||
self.failed_components: List[str] = []
|
||||
self.warnings: List[str] = []
|
||||
|
||||
# Server/IOLoop
|
||||
self.server_running = False
|
||||
self.server_running: bool = False
|
||||
self.moonraker_app = app = MoonrakerApp(config)
|
||||
self.register_endpoint = app.register_local_handler
|
||||
self.register_static_file_handler = app.register_static_file_handler
|
||||
self.register_upload_handler = app.register_upload_handler
|
||||
self.get_websocket_manager = app.get_websocket_manager
|
||||
self.register_api_transport = app.register_api_transport
|
||||
self.ioloop = IOLoop.current()
|
||||
|
||||
self.register_endpoint(
|
||||
"/server/info", ['GET'], self._handle_info_request)
|
||||
self.register_endpoint(
|
||||
"/server/config", ['GET'], self._handle_config_request)
|
||||
self.register_endpoint(
|
||||
"/server/restart", ['POST'], self._handle_server_restart)
|
||||
|
||||
self.register_notification("server:klippy_ready")
|
||||
self.register_notification("server:klippy_shutdown")
|
||||
self.register_notification("server:klippy_disconnect",
|
||||
"klippy_disconnected")
|
||||
self.register_notification("server:gcode_response")
|
||||
|
||||
# Setup remote methods accessable to Klippy. Note that all
|
||||
# registered remote methods should be of the notification type,
|
||||
# they do not return a response to Klippy after execution
|
||||
self.pending_requests = {}
|
||||
self.remote_methods = {}
|
||||
self.klippy_reg_methods = []
|
||||
self.pending_requests: Dict[int, BaseRequest] = {}
|
||||
self.remote_methods: Dict[str, FlexCallback] = {}
|
||||
self.klippy_reg_methods: List[str] = []
|
||||
self.register_remote_method(
|
||||
'process_gcode_response', self._process_gcode_response,
|
||||
need_klippy_reg=False)
|
||||
@@ -80,78 +133,118 @@ class Server:
|
||||
'process_status_update', self._process_status_update,
|
||||
need_klippy_reg=False)
|
||||
|
||||
# Plugin initialization
|
||||
self.plugins = {}
|
||||
self.klippy_apis = self.load_plugin(config, 'klippy_apis')
|
||||
self._load_plugins(config)
|
||||
# Component initialization
|
||||
self.components: Dict[str, Any] = {}
|
||||
self._load_components(config)
|
||||
self.klippy_apis: KlippyAPI = self.lookup_component('klippy_apis')
|
||||
config.validate_config()
|
||||
|
||||
def start(self):
|
||||
def get_app_args(self) -> Dict[str, Any]:
|
||||
return dict(self.app_args)
|
||||
|
||||
def start(self) -> None:
|
||||
hostname, hostport = self.get_host_info()
|
||||
logging.info(
|
||||
f"Starting Moonraker on ({self.host}, {hostport}), "
|
||||
f"Hostname: {hostname}")
|
||||
self.moonraker_app.listen(self.host, self.port)
|
||||
self.moonraker_app.listen(self.host, self.port, self.ssl_port)
|
||||
self.server_running = True
|
||||
self.ioloop.spawn_callback(self._init_signals)
|
||||
self.ioloop.spawn_callback(self._connect_klippy)
|
||||
|
||||
# ***** Plugin Management *****
|
||||
def _load_plugins(self, config):
|
||||
# load core plugins
|
||||
for plugin in CORE_PLUGINS:
|
||||
self.load_plugin(config, plugin)
|
||||
def _init_signals(self) -> None:
|
||||
aioloop = asyncio.get_event_loop()
|
||||
aioloop.add_signal_handler(
|
||||
signal.SIGTERM, self._handle_term_signal)
|
||||
|
||||
# check for optional plugins
|
||||
opt_sections = set([s.split()[0] for s in config.sections()]) - \
|
||||
set(['server', 'authorization', 'system_args'])
|
||||
def add_log_rollover_item(self, name: str, item: str,
|
||||
log: bool = True) -> None:
|
||||
if self.file_logger is not None:
|
||||
self.file_logger.set_rollover_info(name, item)
|
||||
if log and item is not None:
|
||||
logging.info(item)
|
||||
|
||||
def add_warning(self, warning: str, log: bool = True) -> None:
|
||||
self.warnings.append(warning)
|
||||
if log:
|
||||
logging.warning(warning)
|
||||
|
||||
# ***** Component Management *****
|
||||
def _load_components(self, config: confighelper.ConfigHelper) -> None:
|
||||
# load core components
|
||||
for component in CORE_COMPONENTS:
|
||||
self.load_component(config, component)
|
||||
|
||||
# check for optional components
|
||||
opt_sections = set([s.split()[0] for s in config.sections()])
|
||||
opt_sections.remove('server')
|
||||
for section in opt_sections:
|
||||
self.load_plugin(config, section, None)
|
||||
self.load_component(config, section, None)
|
||||
|
||||
def load_plugin(self, config, plugin_name, default=Sentinel):
|
||||
if plugin_name in self.plugins:
|
||||
return self.plugins[plugin_name]
|
||||
# Make sure plugin exists
|
||||
mod_path = os.path.join(
|
||||
os.path.dirname(__file__), 'plugins', plugin_name + '.py')
|
||||
if not os.path.exists(mod_path):
|
||||
msg = f"Plugin ({plugin_name}) does not exist"
|
||||
logging.info(msg)
|
||||
if default == Sentinel:
|
||||
raise ServerError(msg)
|
||||
return default
|
||||
module = importlib.import_module("plugins." + plugin_name)
|
||||
def load_component(self,
|
||||
config: confighelper.ConfigHelper,
|
||||
component_name: str,
|
||||
default: Union[SentinelClass, _T] = SENTINEL
|
||||
) -> Union[_T, Any]:
|
||||
if component_name in self.components:
|
||||
return self.components[component_name]
|
||||
try:
|
||||
func_name = "load_plugin"
|
||||
if hasattr(module, "load_plugin_multi"):
|
||||
func_name = "load_plugin_multi"
|
||||
if plugin_name not in CORE_PLUGINS and func_name == "load_plugin":
|
||||
config = config[plugin_name]
|
||||
module = importlib.import_module("components." + component_name)
|
||||
func_name = "load_component"
|
||||
if hasattr(module, "load_component_multi"):
|
||||
func_name = "load_component_multi"
|
||||
if component_name not in CORE_COMPONENTS and \
|
||||
func_name == "load_component":
|
||||
config = config[component_name]
|
||||
load_func = getattr(module, func_name)
|
||||
plugin = load_func(config)
|
||||
component = load_func(config)
|
||||
except Exception:
|
||||
msg = f"Unable to load plugin ({plugin_name})"
|
||||
msg = f"Unable to load component: ({component_name})"
|
||||
logging.exception(msg)
|
||||
if default == Sentinel:
|
||||
self.failed_components.append(component_name)
|
||||
if isinstance(default, SentinelClass):
|
||||
raise ServerError(msg)
|
||||
return default
|
||||
self.plugins[plugin_name] = plugin
|
||||
logging.info(f"Plugin ({plugin_name}) loaded")
|
||||
return plugin
|
||||
self.components[component_name] = component
|
||||
logging.info(f"Component ({component_name}) loaded")
|
||||
return component
|
||||
|
||||
def lookup_plugin(self, plugin_name, default=Sentinel):
|
||||
plugin = self.plugins.get(plugin_name, default)
|
||||
if plugin == Sentinel:
|
||||
raise ServerError(f"Plugin ({plugin_name}) not found")
|
||||
return plugin
|
||||
def lookup_component(self,
|
||||
component_name: str,
|
||||
default: Union[SentinelClass, _T] = SENTINEL
|
||||
) -> Union[_T, Any]:
|
||||
component = self.components.get(component_name, default)
|
||||
if isinstance(component, SentinelClass):
|
||||
raise ServerError(f"Component ({component_name}) not found")
|
||||
return component
|
||||
|
||||
def register_event_handler(self, event, callback):
|
||||
def set_failed_component(self, component_name: str) -> None:
|
||||
if component_name not in self.failed_components:
|
||||
self.failed_components.append(component_name)
|
||||
|
||||
def register_notification(self,
|
||||
event_name: str,
|
||||
notify_name: Optional[str] = None
|
||||
) -> None:
|
||||
wsm = self.get_websocket_manager()
|
||||
wsm.register_notification(event_name, notify_name)
|
||||
|
||||
def register_event_handler(self,
|
||||
event: str,
|
||||
callback: FlexCallback
|
||||
) -> None:
|
||||
self.events.setdefault(event, []).append(callback)
|
||||
|
||||
def send_event(self, event, *args):
|
||||
def send_event(self, event: str, *args) -> None:
|
||||
events = self.events.get(event, [])
|
||||
for evt in events:
|
||||
self.ioloop.spawn_callback(evt, *args)
|
||||
|
||||
def register_remote_method(self, method_name, cb, need_klippy_reg=True):
|
||||
def register_remote_method(self,
|
||||
method_name: str,
|
||||
cb: FlexCallback,
|
||||
need_klippy_reg: bool = True
|
||||
) -> None:
|
||||
if method_name in self.remote_methods:
|
||||
# XXX - may want to raise an exception here
|
||||
logging.info(f"Remote method ({method_name}) already registered")
|
||||
@@ -161,25 +254,28 @@ class Server:
|
||||
# These methods need to be registered with Klippy
|
||||
self.klippy_reg_methods.append(method_name)
|
||||
|
||||
def get_host_info(self):
|
||||
def get_host_info(self) -> Tuple[str, int]:
|
||||
hostname = socket.gethostname()
|
||||
return hostname, self.port
|
||||
|
||||
def get_klippy_info(self):
|
||||
def get_klippy_info(self) -> Dict[str, Any]:
|
||||
return dict(self.klippy_info)
|
||||
|
||||
def get_klippy_state(self) -> str:
|
||||
return self.klippy_state
|
||||
|
||||
# ***** Klippy Connection *****
|
||||
async def _connect_klippy(self):
|
||||
async def _connect_klippy(self) -> None:
|
||||
if not self.server_running:
|
||||
return
|
||||
ret = await self.klippy_connection.connect(self.klippy_address)
|
||||
if not ret:
|
||||
self.ioloop.call_later(.25, self._connect_klippy)
|
||||
self.ioloop.call_later(.25, self._connect_klippy) # type: ignore
|
||||
return
|
||||
# begin server iniialization
|
||||
self.ioloop.spawn_callback(self._initialize)
|
||||
|
||||
def process_command(self, cmd):
|
||||
def process_command(self, cmd: Dict[str, Any]) -> None:
|
||||
method = cmd.get('method', None)
|
||||
if method is not None:
|
||||
# This is a remote method called from klippy
|
||||
@@ -207,15 +303,15 @@ class Server:
|
||||
result = ServerError(err, 400)
|
||||
request.notify(result)
|
||||
|
||||
async def _execute_method(self, method_name, **kwargs):
|
||||
async def _execute_method(self, method_name: str, **kwargs) -> None:
|
||||
try:
|
||||
ret = self.remote_methods[method_name](**kwargs)
|
||||
if asyncio.iscoroutine(ret):
|
||||
if ret is not None:
|
||||
await ret
|
||||
except Exception:
|
||||
logging.exception(f"Error running remote method: {method_name}")
|
||||
|
||||
def on_connection_closed(self):
|
||||
def on_connection_closed(self) -> None:
|
||||
self.init_list = []
|
||||
self.klippy_state = "disconnected"
|
||||
for request in self.pending_requests.values():
|
||||
@@ -227,9 +323,11 @@ class Server:
|
||||
if self.init_handle is not None:
|
||||
self.ioloop.remove_timeout(self.init_handle)
|
||||
if self.server_running:
|
||||
self.ioloop.call_later(.25, self._connect_klippy)
|
||||
self.ioloop.call_later(.25, self._connect_klippy) # type: ignore
|
||||
if self.klippy_disconnect_evt is not None:
|
||||
self.klippy_disconnect_evt.set()
|
||||
|
||||
async def _initialize(self):
|
||||
async def _initialize(self) -> None:
|
||||
if not self.server_running:
|
||||
return
|
||||
await self._check_ready()
|
||||
@@ -263,18 +361,19 @@ class Server:
|
||||
else:
|
||||
self.init_attempts += 1
|
||||
self.init_handle = self.ioloop.call_later(
|
||||
INIT_TIME, self._initialize)
|
||||
INIT_TIME, self._initialize) # type: ignore
|
||||
|
||||
async def _request_endpoints(self):
|
||||
async def _request_endpoints(self) -> None:
|
||||
result = await self.klippy_apis.list_endpoints(default=None)
|
||||
if result is None:
|
||||
return
|
||||
endpoints = result.get('endpoints', {})
|
||||
endpoints = result.get('endpoints', [])
|
||||
for ep in endpoints:
|
||||
self.moonraker_app.register_remote_handler(ep)
|
||||
|
||||
async def _check_ready(self):
|
||||
async def _check_ready(self) -> None:
|
||||
send_id = "identified" not in self.init_list
|
||||
result: Dict[str, Any]
|
||||
try:
|
||||
result = await self.klippy_apis.get_klippy_info(send_id)
|
||||
except ServerError as e:
|
||||
@@ -285,10 +384,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")
|
||||
@@ -305,7 +405,7 @@ class Server:
|
||||
msg = result.get('state_message', "Klippy Not Ready")
|
||||
logging.info("\n" + msg)
|
||||
|
||||
async def _verify_klippy_requirements(self):
|
||||
async def _verify_klippy_requirements(self) -> None:
|
||||
result = await self.klippy_apis.get_object_list(default=None)
|
||||
if result is None:
|
||||
logging.info(
|
||||
@@ -321,54 +421,64 @@ class Server:
|
||||
f"to printer.cfg for full Moonraker functionality.")
|
||||
if "virtual_sdcard" not in missing_objs:
|
||||
# Update the gcode path
|
||||
result = await self.klippy_apis.query_objects(
|
||||
query_res = await self.klippy_apis.query_objects(
|
||||
{'configfile': None}, default=None)
|
||||
if result is None:
|
||||
if query_res is None:
|
||||
logging.info(f"Unable to set SD Card path")
|
||||
else:
|
||||
config = result.get('configfile', {}).get('config', {})
|
||||
config = query_res.get('configfile', {}).get('config', {})
|
||||
vsd_config = config.get('virtual_sdcard', {})
|
||||
vsd_path = vsd_config.get('path', None)
|
||||
if vsd_path is not None:
|
||||
file_manager = self.lookup_plugin('file_manager')
|
||||
file_manager: FileManager = self.lookup_component(
|
||||
'file_manager')
|
||||
file_manager.register_directory('gcodes', vsd_path)
|
||||
else:
|
||||
logging.info(
|
||||
"Configuration for [virtual_sdcard] not found,"
|
||||
" unable to set SD Card path")
|
||||
|
||||
def _process_gcode_response(self, response):
|
||||
def _process_gcode_response(self, response: str) -> None:
|
||||
self.send_event("server:gcode_response", response)
|
||||
|
||||
def _process_status_update(self, eventtime, status):
|
||||
def _process_status_update(self,
|
||||
eventtime: float,
|
||||
status: Dict[str, Any]
|
||||
) -> None:
|
||||
if 'webhooks' in status:
|
||||
# XXX - process other states (startup, ready, error, etc)?
|
||||
state = status['webhooks'].get('state', None)
|
||||
state: Optional[str] = status['webhooks'].get('state', None)
|
||||
if state is not None:
|
||||
if state == "shutdown":
|
||||
logging.info("Klippy has shutdown")
|
||||
self.send_event("server:klippy_shutdown")
|
||||
self.klippy_state = state
|
||||
for conn, sub in self.subscriptions.items():
|
||||
conn_status = {}
|
||||
conn_status: Dict[str, Any] = {}
|
||||
for name, fields in sub.items():
|
||||
if name in status:
|
||||
val = status[name]
|
||||
val: Dict[str, Any] = status[name]
|
||||
if fields is None:
|
||||
conn_status[name] = dict(val)
|
||||
else:
|
||||
conn_status[name] = {
|
||||
k: v for k, v in val.items() if k in fields}
|
||||
conn.send_status(conn_status)
|
||||
conn.send_status(conn_status, eventtime)
|
||||
|
||||
async def make_request(self, web_request):
|
||||
async def make_request(self, web_request: WebRequest) -> Any:
|
||||
rpc_method = web_request.get_endpoint()
|
||||
if rpc_method == "objects/subscribe":
|
||||
return await self._request_subscripton(web_request)
|
||||
else:
|
||||
if rpc_method == "gcode/script":
|
||||
script = web_request.get_str('script', "")
|
||||
data_store: DataStore = self.lookup_component('data_store')
|
||||
data_store.store_gcode_command(script)
|
||||
return await self._request_standard(web_request)
|
||||
|
||||
async def _request_subscripton(self, web_request):
|
||||
async def _request_subscripton(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
args = web_request.get_args()
|
||||
conn = web_request.get_connection()
|
||||
|
||||
@@ -379,7 +489,7 @@ class Server:
|
||||
raise self.error(
|
||||
"No connection associated with subscription request")
|
||||
self.subscriptions[conn] = sub
|
||||
all_subs = {}
|
||||
all_subs: Dict[str, Any] = {}
|
||||
# request superset of all client subscriptions
|
||||
for sub in self.subscriptions.values():
|
||||
for obj, items in sub.items():
|
||||
@@ -412,7 +522,7 @@ class Server:
|
||||
result['status'] = pruned_status
|
||||
return result
|
||||
|
||||
async def _request_standard(self, web_request):
|
||||
async def _request_standard(self, web_request: WebRequest) -> Any:
|
||||
rpc_method = web_request.get_endpoint()
|
||||
args = web_request.get_args()
|
||||
# Create a base klippy request
|
||||
@@ -422,40 +532,104 @@ class Server:
|
||||
self.klippy_connection.send_request, base_request)
|
||||
return await base_request.wait()
|
||||
|
||||
def remove_subscription(self, conn):
|
||||
def remove_subscription(self, conn: Subscribable) -> None:
|
||||
self.subscriptions.pop(conn, None)
|
||||
|
||||
async def _stop_server(self):
|
||||
def _handle_term_signal(self) -> None:
|
||||
logging.info(f"Exiting with signal SIGTERM")
|
||||
self.ioloop.spawn_callback(self._stop_server, "terminate")
|
||||
|
||||
async def _stop_server(self, exit_reason: str = "restart") -> None:
|
||||
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()
|
||||
# Call each component's "on_exit" method
|
||||
for name, component in self.components.items():
|
||||
if hasattr(component, "on_exit"):
|
||||
func: FlexCallback = getattr(component, "on_exit")
|
||||
try:
|
||||
ret = func()
|
||||
if ret is not None:
|
||||
await ret
|
||||
except Exception:
|
||||
logging.exception(
|
||||
f"Error executing 'on_exit()' for component: {name}")
|
||||
|
||||
# Sleep for 100ms to allow connected websockets to write out
|
||||
# remaining data
|
||||
await gen.sleep(.1)
|
||||
try:
|
||||
await self.moonraker_app.close()
|
||||
except Exception:
|
||||
logging.exception("Error Closing App")
|
||||
|
||||
# Disconnect from Klippy
|
||||
try:
|
||||
if self.klippy_connection.is_connected():
|
||||
self.klippy_disconnect_evt = Event()
|
||||
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")
|
||||
|
||||
# Close all components
|
||||
for name, component in self.components.items():
|
||||
if hasattr(component, "close"):
|
||||
func = getattr(component, "close")
|
||||
try:
|
||||
ret = func()
|
||||
if ret is not None:
|
||||
await ret
|
||||
except Exception:
|
||||
logging.exception(
|
||||
f"Error executing 'close()' for component: {name}")
|
||||
|
||||
self.exit_reason = exit_reason
|
||||
aioloop = asyncio.get_event_loop()
|
||||
aioloop.remove_signal_handler(signal.SIGTERM)
|
||||
self.ioloop.stop()
|
||||
|
||||
async def _handle_server_restart(self, web_request):
|
||||
async def _handle_server_restart(self, web_request: WebRequest) -> str:
|
||||
self.ioloop.spawn_callback(self._stop_server)
|
||||
return "ok"
|
||||
|
||||
async def _handle_info_request(self, web_request):
|
||||
async def _handle_info_request(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
file_manager: Optional[FileManager] = self.lookup_component(
|
||||
'file_manager', None)
|
||||
reg_dirs = []
|
||||
if file_manager is not None:
|
||||
reg_dirs = file_manager.get_registered_dirs()
|
||||
return {
|
||||
'klippy_connected': self.klippy_connection.is_connected(),
|
||||
'klippy_state': self.klippy_state,
|
||||
'plugins': list(self.plugins.keys())}
|
||||
'components': list(self.components.keys()),
|
||||
'failed_components': self.failed_components,
|
||||
'plugins': list(self.components.keys()),
|
||||
'failed_plugins': self.failed_components,
|
||||
'registered_directories': reg_dirs,
|
||||
'warnings': self.warnings
|
||||
}
|
||||
|
||||
async def _handle_config_request(self,
|
||||
web_request: WebRequest
|
||||
) -> Dict[str, Any]:
|
||||
return {
|
||||
'config': self.config.get_parsed_config()
|
||||
}
|
||||
|
||||
class KlippyConnection:
|
||||
def __init__(self, on_recd, on_close):
|
||||
def __init__(self,
|
||||
on_recd: Callable[[dict], None],
|
||||
on_close: Callable[[], None]
|
||||
) -> None:
|
||||
self.ioloop = IOLoop.current()
|
||||
self.iostream = None
|
||||
self.iostream: Optional[iostream.IOStream] = None
|
||||
self.on_recd = on_recd
|
||||
self.on_close = on_close
|
||||
|
||||
async def connect(self, address):
|
||||
async def connect(self, address: str) -> bool:
|
||||
ksock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
|
||||
kstream = iostream.IOStream(ksock)
|
||||
try:
|
||||
@@ -468,7 +642,7 @@ class KlippyConnection:
|
||||
self.ioloop.spawn_callback(self._read_stream, self.iostream)
|
||||
return True
|
||||
|
||||
async def _read_stream(self, stream):
|
||||
async def _read_stream(self, stream: iostream.IOStream) -> None:
|
||||
while not stream.closed():
|
||||
try:
|
||||
data = await stream.read_until(b'\x03')
|
||||
@@ -484,7 +658,7 @@ class KlippyConnection:
|
||||
logging.exception(
|
||||
f"Error processing Klippy Host Response: {data.decode()}")
|
||||
|
||||
async def send_request(self, request):
|
||||
async def send_request(self, request: BaseRequest) -> None:
|
||||
if self.iostream is None:
|
||||
request.notify(ServerError("Klippy Host not connected", 503))
|
||||
return
|
||||
@@ -494,24 +668,24 @@ class KlippyConnection:
|
||||
except iostream.StreamClosedError:
|
||||
request.notify(ServerError("Klippy Host not connected", 503))
|
||||
|
||||
def is_connected(self):
|
||||
def is_connected(self) -> bool:
|
||||
return self.iostream is not None and not self.iostream.closed()
|
||||
|
||||
def close(self):
|
||||
def close(self) -> None:
|
||||
if self.iostream is not None and \
|
||||
not self.iostream.closed():
|
||||
self.iostream.close()
|
||||
|
||||
# Basic WebRequest class, easily converted to dict for json encoding
|
||||
class BaseRequest:
|
||||
def __init__(self, rpc_method, params):
|
||||
def __init__(self, rpc_method: str, params: Dict[str, Any]) -> None:
|
||||
self.id = id(self)
|
||||
self.rpc_method = rpc_method
|
||||
self.params = params
|
||||
self._event = Event()
|
||||
self.response = None
|
||||
self.response: Any = None
|
||||
|
||||
async def wait(self):
|
||||
async def wait(self) -> Any:
|
||||
# Log pending requests every 60 seconds
|
||||
start_time = time.time()
|
||||
while True:
|
||||
@@ -530,15 +704,15 @@ class BaseRequest:
|
||||
raise self.response
|
||||
return self.response
|
||||
|
||||
def notify(self, response):
|
||||
def notify(self, response: Any) -> None:
|
||||
self.response = response
|
||||
self._event.set()
|
||||
|
||||
def to_dict(self):
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {'id': self.id, 'method': self.rpc_method,
|
||||
'params': self.params}
|
||||
|
||||
def main():
|
||||
def main() -> None:
|
||||
# Parse start arguments
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Moonraker - Klipper API Server")
|
||||
@@ -549,14 +723,21 @@ def main():
|
||||
parser.add_argument(
|
||||
"-l", "--logfile", default="/tmp/moonraker.log", metavar='<logfile>',
|
||||
help="log file name and location")
|
||||
system_args = parser.parse_args()
|
||||
parser.add_argument(
|
||||
"-n", "--nologfile", action='store_true',
|
||||
help="disable logging to a file")
|
||||
cmd_line_args = parser.parse_args()
|
||||
app_args = {'config_file': cmd_line_args.configfile}
|
||||
|
||||
# Setup Logging
|
||||
version = utils.get_software_version()
|
||||
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)
|
||||
if cmd_line_args.nologfile:
|
||||
app_args['log_file'] = ""
|
||||
else:
|
||||
app_args['log_file'] = os.path.normpath(
|
||||
os.path.expanduser(cmd_line_args.logfile))
|
||||
app_args['software_version'] = version
|
||||
ql, file_logger = utils.setup_logging(app_args)
|
||||
|
||||
if sys.version_info < (3, 7):
|
||||
msg = f"Moonraker requires Python 3.7 or above. " \
|
||||
@@ -571,7 +752,7 @@ def main():
|
||||
estatus = 0
|
||||
while True:
|
||||
try:
|
||||
server = Server(system_args)
|
||||
server = Server(app_args, file_logger)
|
||||
except Exception:
|
||||
logging.exception("Moonraker Error")
|
||||
estatus = 1
|
||||
@@ -583,6 +764,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)
|
||||
|
||||
@@ -1,123 +0,0 @@
|
||||
# Klipper data logging and storage storage
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import logging
|
||||
import time
|
||||
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()
|
||||
|
||||
# Temperature Store Tracking
|
||||
self.last_temps = {}
|
||||
self.gcode_queue = deque(maxlen=MAX_GCODE_LINES)
|
||||
self.temperature_store = {}
|
||||
self.temp_update_cb = PeriodicCallback(
|
||||
self._update_temperature_store, TEMPERATURE_UPDATE_MS)
|
||||
|
||||
# Register status update event
|
||||
self.server.register_event_handler(
|
||||
"server:status_update", self._set_current_temps)
|
||||
self.server.register_event_handler(
|
||||
"server:gcode_response", self._update_gcode_store)
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_ready", self._init_sensors)
|
||||
|
||||
# Register endpoints
|
||||
self.server.register_endpoint(
|
||||
"/server/temperature_store", ['GET'],
|
||||
self._handle_temp_store_request)
|
||||
self.server.register_endpoint(
|
||||
"/server/gcode_store", ['GET'],
|
||||
self._handle_gcode_store_request)
|
||||
|
||||
async def _init_sensors(self):
|
||||
klippy_apis = self.server.lookup_plugin('klippy_apis')
|
||||
# Fetch sensors
|
||||
try:
|
||||
result = await klippy_apis.query_objects({'heaters': None})
|
||||
except self.server.error as e:
|
||||
logging.info(f"Error Configuring Sensors: {e}")
|
||||
return
|
||||
sensors = result.get("heaters", {}).get("available_sensors", [])
|
||||
|
||||
if sensors:
|
||||
# Add Subscription
|
||||
sub = {s: None for s in sensors}
|
||||
try:
|
||||
status = await klippy_apis.subscribe_objects(sub)
|
||||
except self.server.error as e:
|
||||
logging.info(f"Error subscribing to sensors: {e}")
|
||||
return
|
||||
logging.info(f"Configuring available sensors: {sensors}")
|
||||
new_store = {}
|
||||
for sensor in sensors:
|
||||
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)}
|
||||
if sensor not in self.last_temps:
|
||||
self.last_temps[sensor] = (0., 0.)
|
||||
self.temperature_store = new_store
|
||||
# Prune unconfigured sensors in self.last_temps
|
||||
for sensor in list(self.last_temps.keys()):
|
||||
if sensor not in self.temperature_store:
|
||||
del self.last_temps[sensor]
|
||||
# Update initial temperatures
|
||||
self._set_current_temps(status)
|
||||
self.temp_update_cb.start()
|
||||
else:
|
||||
logging.info("No sensors found")
|
||||
self.last_temps = {}
|
||||
self.temperature_store = {}
|
||||
self.temp_update_cb.stop()
|
||||
|
||||
def _set_current_temps(self, data):
|
||||
for sensor in self.temperature_store:
|
||||
if sensor in data:
|
||||
last_temp, last_target = self.last_temps[sensor]
|
||||
self.last_temps[sensor] = (
|
||||
round(data[sensor].get('temperature', last_temp), 2),
|
||||
data[sensor].get('target', last_target))
|
||||
|
||||
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)
|
||||
|
||||
async def _handle_temp_store_request(self, web_request):
|
||||
store = {}
|
||||
for name, sensor in self.temperature_store.items():
|
||||
store[name] = {k: list(v) for k, v in sensor.items()}
|
||||
return store
|
||||
|
||||
async def close(self):
|
||||
self.temp_update_cb.stop()
|
||||
|
||||
def _update_gcode_store(self, response):
|
||||
curtime = time.time()
|
||||
self.gcode_queue.append({'message': response, 'time': curtime})
|
||||
|
||||
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:]
|
||||
else:
|
||||
res = list(self.gcode_queue)
|
||||
return {'gcode_store': res}
|
||||
|
||||
def load_plugin(config):
|
||||
return DataStore(config)
|
||||
@@ -1,680 +0,0 @@
|
||||
# Enhanced gcode file management and analysis
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import os
|
||||
import sys
|
||||
import shutil
|
||||
import io
|
||||
import zipfile
|
||||
import logging
|
||||
import json
|
||||
from tornado.ioloop import IOLoop, PeriodicCallback
|
||||
from tornado.locks import Event
|
||||
|
||||
VALID_GCODE_EXTS = ['.gcode', '.g', '.gco']
|
||||
FULL_ACCESS_ROOTS = ["gcodes", "config"]
|
||||
ETC_DIR = "/etc/moonraker"
|
||||
METADATA_SCRIPT = os.path.normpath(os.path.join(
|
||||
os.path.dirname(__file__), "../../scripts/extract_metadata.py"))
|
||||
|
||||
class FileManager:
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
self.file_paths = {}
|
||||
self.gcode_metadata = MetadataStorage(self.server)
|
||||
self.fixed_path_args = {}
|
||||
|
||||
# Register file management endpoints
|
||||
self.server.register_endpoint(
|
||||
"/server/files/list", ['GET'], self._handle_filelist_request)
|
||||
self.server.register_endpoint(
|
||||
"/server/files/metadata", ['GET'], self._handle_metadata_request)
|
||||
self.server.register_endpoint(
|
||||
"/server/files/directory", ['GET', 'POST', 'DELETE'],
|
||||
self._handle_directory_request)
|
||||
self.server.register_endpoint(
|
||||
"/server/files/move", ['POST'], self._handle_file_move_copy)
|
||||
self.server.register_endpoint(
|
||||
"/server/files/copy", ['POST'], self._handle_file_move_copy)
|
||||
self.server.register_endpoint(
|
||||
"/server/files/delete_file", ['DELETE'], self._handle_file_delete,
|
||||
protocol=["websocket"])
|
||||
# Register APIs to handle file uploads
|
||||
self.server.register_upload_handler("/server/files/upload")
|
||||
self.server.register_upload_handler("/api/files/local")
|
||||
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_ready", self._update_fixed_paths)
|
||||
|
||||
# Register Klippy Configuration Path
|
||||
config_path = config.get('config_path', None)
|
||||
if config_path is not None:
|
||||
ret = self.register_directory('config', config_path)
|
||||
if not ret:
|
||||
raise config.error(
|
||||
"Option 'config_path' is not a valid directory")
|
||||
|
||||
def _update_fixed_paths(self):
|
||||
kinfo = self.server.get_klippy_info()
|
||||
paths = {k: kinfo.get(k) for k in
|
||||
['klipper_path', 'python_path',
|
||||
'log_file', 'config_file']}
|
||||
if paths == self.fixed_path_args:
|
||||
# No change in fixed paths
|
||||
return
|
||||
self.fixed_path_args = paths
|
||||
str_paths = "\n".join([f"{k}: {v}" for k, v in paths.items()])
|
||||
logging.debug(f"\nUpdating Fixed Paths:\n{str_paths}")
|
||||
|
||||
# Register path for example configs
|
||||
klipper_path = paths.get('klipper_path', None)
|
||||
if klipper_path is not None:
|
||||
example_cfg_path = os.path.join(klipper_path, "config")
|
||||
self.register_directory("config_examples", example_cfg_path)
|
||||
docs_path = os.path.join(klipper_path, "docs")
|
||||
self.register_directory("docs", docs_path)
|
||||
|
||||
# Register log path
|
||||
log_file = paths.get('log_file')
|
||||
log_path = os.path.normpath(os.path.expanduser(log_file))
|
||||
self.server.register_static_file_handler("klippy.log", log_path)
|
||||
|
||||
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)):
|
||||
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.")
|
||||
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
|
||||
self.gcode_metadata.update_gcode_path(path)
|
||||
try:
|
||||
self.get_file_list("gcodes")
|
||||
except Exception:
|
||||
logging.exception(
|
||||
f"Unable to initialize gcode metadata")
|
||||
return True
|
||||
|
||||
def get_sd_directory(self):
|
||||
return self.file_paths.get('gcodes', "")
|
||||
|
||||
def get_fixed_path_args(self):
|
||||
return dict(self.fixed_path_args)
|
||||
|
||||
async def _handle_filelist_request(self, web_request):
|
||||
root = web_request.get_str('root', "gcodes")
|
||||
return self.get_file_list(root, list_format=True, notify=True)
|
||||
|
||||
async def _handle_metadata_request(self, web_request):
|
||||
requested_file = web_request.get_str('filename')
|
||||
metadata = self.gcode_metadata.get(requested_file, None)
|
||||
if metadata is None:
|
||||
raise self.server.error(
|
||||
f"Metadata not available for <{requested_file}>", 404)
|
||||
metadata['filename'] = requested_file
|
||||
return metadata
|
||||
|
||||
async def _handle_directory_request(self, web_request):
|
||||
directory = web_request.get_str('path', "gcodes")
|
||||
root, rel_path, dir_path = self._convert_path(directory)
|
||||
action = web_request.get_action()
|
||||
if action == 'GET':
|
||||
is_extended = web_request.get_boolean('extended', False)
|
||||
# Get list of files and subdirectories for this target
|
||||
dir_info = self._list_directory(dir_path)
|
||||
# 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)
|
||||
return dir_info
|
||||
elif action == 'POST' and root in FULL_ACCESS_ROOTS:
|
||||
# Create a new directory
|
||||
try:
|
||||
os.mkdir(dir_path)
|
||||
except Exception as e:
|
||||
raise self.server.error(str(e))
|
||||
self.notify_filelist_changed("create_dir", rel_path, root)
|
||||
elif action == 'DELETE' and root in FULL_ACCESS_ROOTS:
|
||||
# Remove a directory
|
||||
if directory.strip("/") == root:
|
||||
raise self.server.error(
|
||||
"Cannot delete root directory")
|
||||
if not os.path.isdir(dir_path):
|
||||
raise self.server.error(
|
||||
f"Directory does not exist ({directory})")
|
||||
force = web_request.get_boolean('force', False)
|
||||
if force:
|
||||
# Make sure that the directory does not contain a file
|
||||
# loaded by the virtual_sdcard
|
||||
await self._handle_operation_check(dir_path)
|
||||
shutil.rmtree(dir_path)
|
||||
if root == "gcodes":
|
||||
self.gcode_metadata.prune_metadata()
|
||||
else:
|
||||
try:
|
||||
os.rmdir(dir_path)
|
||||
except Exception as e:
|
||||
raise self.server.error(str(e))
|
||||
self.notify_filelist_changed("delete_dir", rel_path, root)
|
||||
else:
|
||||
raise self.server.error("Operation Not Supported", 405)
|
||||
return "ok"
|
||||
|
||||
async def _handle_operation_check(self, requested_path):
|
||||
# Get virtual_sdcard status
|
||||
klippy_apis = self.server.lookup_plugin('klippy_apis')
|
||||
result = await klippy_apis.query_objects({'print_stats': None})
|
||||
pstats = result.get('print_stats', {})
|
||||
loaded_file = pstats.get('filename', "")
|
||||
state = pstats.get('state', "")
|
||||
gc_path = self.file_paths.get('gcodes', "")
|
||||
full_path = os.path.join(gc_path, loaded_file)
|
||||
if loaded_file and state != "complete":
|
||||
if os.path.isdir(requested_path):
|
||||
# Check to see of the loaded file is in the request
|
||||
if full_path.startswith(requested_path):
|
||||
raise self.server.error("File currently in use", 403)
|
||||
elif full_path == requested_path:
|
||||
raise self.server.error("File currently in use", 403)
|
||||
ongoing = state in ["printing", "paused"]
|
||||
return ongoing
|
||||
|
||||
def _convert_path(self, request_path):
|
||||
# Parse the root, relative path, and disk path from a remote request
|
||||
parts = request_path.strip("/").split("/")
|
||||
if not parts:
|
||||
raise self.server.error(f"Invalid path: {request_path}")
|
||||
root = parts[0]
|
||||
if root not in self.file_paths:
|
||||
raise self.server.error(f"Invalid root path ({root})")
|
||||
disk_path = self.file_paths[root]
|
||||
rel_path = ""
|
||||
if len(parts) > 1:
|
||||
rel_path = "/".join(parts[1:])
|
||||
disk_path = os.path.join(disk_path, rel_path)
|
||||
return root, rel_path, disk_path
|
||||
|
||||
async def _handle_file_move_copy(self, web_request):
|
||||
source = web_request.get_str("source")
|
||||
destination = web_request.get_str("dest")
|
||||
ep = web_request.get_endpoint()
|
||||
if source is None:
|
||||
raise self.server.error("File move/copy request issing source")
|
||||
if destination is None:
|
||||
raise self.server.error(
|
||||
"File move/copy request missing destination")
|
||||
source_root, src_rel_path, source_path = self._convert_path(source)
|
||||
dest_root, dst_rel_path, dest_path = self._convert_path(destination)
|
||||
if dest_root not in FULL_ACCESS_ROOTS:
|
||||
raise self.server.error(
|
||||
f"Destination path is read-only: {dest_root}")
|
||||
if not os.path.exists(source_path):
|
||||
raise self.server.error(f"File {source_path} does not exist")
|
||||
# make sure the destination is not in use
|
||||
if os.path.exists(dest_path):
|
||||
await self._handle_operation_check(dest_path)
|
||||
action = op_result = ""
|
||||
if ep == "/server/files/move":
|
||||
if source_root not in FULL_ACCESS_ROOTS:
|
||||
raise self.server.error(
|
||||
f"Source path is read-only, cannot move: {source_root}")
|
||||
# if moving the file, make sure the source is not in use
|
||||
await self._handle_operation_check(source_path)
|
||||
try:
|
||||
op_result = shutil.move(source_path, dest_path)
|
||||
except Exception as e:
|
||||
raise self.server.error(str(e))
|
||||
if source_root == "gcodes":
|
||||
if os.path.isdir(op_result):
|
||||
self.gcode_metadata.prune_metadata()
|
||||
else:
|
||||
self.gcode_metadata.remove_file(src_rel_path)
|
||||
action = "move_item"
|
||||
elif ep == "/server/files/copy":
|
||||
try:
|
||||
if os.path.isdir(source_path):
|
||||
op_result = shutil.copytree(source_path, dest_path)
|
||||
else:
|
||||
op_result = shutil.copy2(source_path, dest_path)
|
||||
except Exception as e:
|
||||
raise self.server.error(str(e))
|
||||
action = "copy_item"
|
||||
if op_result != dest_path:
|
||||
dst_rel_path = os.path.join(
|
||||
dst_rel_path, os.path.basename(op_result))
|
||||
self.notify_filelist_changed(
|
||||
action, dst_rel_path, dest_root,
|
||||
{'path': src_rel_path, 'root': source_root})
|
||||
return "ok"
|
||||
|
||||
def _list_directory(self, path):
|
||||
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)
|
||||
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
|
||||
flist['files'].append(path_info)
|
||||
return flist
|
||||
|
||||
def _get_path_info(self, path):
|
||||
modified = os.path.getmtime(path)
|
||||
size = os.path.getsize(path)
|
||||
path_info = {'modified': modified, 'size': size}
|
||||
return path_info
|
||||
|
||||
async def process_file_upload(self, request):
|
||||
# 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}")
|
||||
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"
|
||||
# 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"
|
||||
print_ongoing = await self._handle_operation_check(
|
||||
check_path)
|
||||
except self.server.error as e:
|
||||
if e.status_code == 403:
|
||||
raise self.server.error(
|
||||
"File is loaded, upload not permitted", 403)
|
||||
else:
|
||||
# Couldn't reach Klippy, so it should be safe
|
||||
# to permit the upload but not start
|
||||
start_print = False
|
||||
# Don't start if another print is currently in progress
|
||||
start_print = start_print and not print_ongoing
|
||||
self._write_file(upload, is_ufp)
|
||||
# Fetch Metadata
|
||||
finfo = self._get_path_info(upload['full_path'])
|
||||
evt = self.gcode_metadata.parse_metadata(
|
||||
upload['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'])
|
||||
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}")
|
||||
return {
|
||||
'filename': filename,
|
||||
'body': upload['body'],
|
||||
'dir_path': dir_path,
|
||||
'full_path': full_path}
|
||||
|
||||
def _write_file(self, upload, unzip_ufp=False):
|
||||
try:
|
||||
if upload['dir_path']:
|
||||
os.makedirs(os.path.dirname(
|
||||
upload['full_path']), exist_ok=True)
|
||||
if unzip_ufp:
|
||||
self._unzip_ufp(upload)
|
||||
else:
|
||||
with open(upload['full_path'], 'wb') as fh:
|
||||
fh.write(upload['body'])
|
||||
except Exception:
|
||||
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")
|
||||
try:
|
||||
img_bytes = zf.read("/Metadata/thumbnail.png")
|
||||
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")
|
||||
|
||||
def get_file_list(self, root, list_format=False, notify=False):
|
||||
# Use os.walk find files in sd path and subdirs
|
||||
filelist = {}
|
||||
path = self.file_paths.get(root, None)
|
||||
if path is None or not os.path.isdir(path):
|
||||
msg = f"Failed to build file list, invalid path: {root}: {path}"
|
||||
logging.info(msg)
|
||||
raise self.server.error(msg)
|
||||
logging.info(f"Updating File List <{root}>...")
|
||||
for root_path, dirs, files in os.walk(path, followlinks=True):
|
||||
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)
|
||||
fname = full_path[len(path) + 1:]
|
||||
finfo = self._get_path_info(full_path)
|
||||
filelist[fname] = finfo
|
||||
if root == 'gcodes':
|
||||
self.gcode_metadata.parse_metadata(
|
||||
fname, finfo['size'], finfo['modified'], notify)
|
||||
if list_format:
|
||||
flist = []
|
||||
for fname in sorted(filelist, key=str.lower):
|
||||
fdict = {'filename': fname}
|
||||
fdict.update(filelist[fname])
|
||||
flist.append(fdict)
|
||||
return flist
|
||||
return filelist
|
||||
|
||||
def get_file_metadata(self, filename):
|
||||
if filename[0] == '/':
|
||||
filename = filename[1:]
|
||||
|
||||
# Remove "gcodes" of its added. It is valid for a request to
|
||||
# include to the root or assume the root is gcodes
|
||||
if filename.startswith('gcodes/'):
|
||||
filename = filename[7:]
|
||||
|
||||
flist = self.get_file_list("gcodes")
|
||||
return self.gcode_metadata.get(filename, flist.get(filename, {}))
|
||||
|
||||
def list_dir(self, directory, simple_format=False):
|
||||
# List a directory relative to its root. Currently the only
|
||||
# Supported root is "gcodes"
|
||||
if directory[0] == "/":
|
||||
directory = directory[1:]
|
||||
parts = directory.split("/", 1)
|
||||
root = parts[0]
|
||||
if root not in self.file_paths:
|
||||
raise self.server.error(
|
||||
f"Invalid Directory Request: {directory}")
|
||||
path = self.file_paths[root]
|
||||
if len(parts) == 1:
|
||||
dir_path = path
|
||||
else:
|
||||
dir_path = os.path.join(path, parts[1])
|
||||
if not os.path.isdir(dir_path):
|
||||
raise self.server.error(
|
||||
f"Directory does not exist ({dir_path})")
|
||||
flist = self._list_directory(dir_path)
|
||||
if simple_format:
|
||||
simple_list = []
|
||||
for dirobj in flist['dirs']:
|
||||
simple_list.append("*" + dirobj['dirname'])
|
||||
for fileobj in flist['files']:
|
||||
fname = fileobj['filename']
|
||||
ext = os.path.splitext(fname)[-1].lower()
|
||||
if root == "gcodes" and ext in VALID_GCODE_EXTS:
|
||||
simple_list.append(fname)
|
||||
return simple_list
|
||||
return flist
|
||||
|
||||
async def _handle_file_delete(self, web_request):
|
||||
file_path = web_request.get_str("path")
|
||||
return await self.delete_file(file_path)
|
||||
|
||||
async def delete_file(self, path):
|
||||
parts = path.lstrip("/").split("/", 1)
|
||||
if len(parts) != 2:
|
||||
raise self.server.error(
|
||||
f"Path not available for DELETE: {path}", 405)
|
||||
root = parts[0]
|
||||
filename = parts[1]
|
||||
if root not in self.file_paths or root not in FULL_ACCESS_ROOTS:
|
||||
raise self.server.error(
|
||||
f"Path not available for DELETE: {path}", 405)
|
||||
root_path = self.file_paths[root]
|
||||
full_path = os.path.join(root_path, filename)
|
||||
if not os.path.isfile(full_path):
|
||||
raise self.server.error(f"Invalid file path: {path}")
|
||||
if root == "gcodes":
|
||||
try:
|
||||
await self._handle_operation_check(full_path)
|
||||
except self.server.error as e:
|
||||
if e.status_code == 403:
|
||||
raise
|
||||
self.gcode_metadata.remove_file(filename)
|
||||
os.remove(full_path)
|
||||
self.notify_filelist_changed('delete_file', filename, root)
|
||||
return filename
|
||||
|
||||
def notify_filelist_changed(self, action, fname, root, source_item={}):
|
||||
flist = self.get_file_list(root, notify=True)
|
||||
file_info = flist.get(fname, {'size': 0, 'modified': 0})
|
||||
file_info.update({'path': fname, 'root': root})
|
||||
result = {'action': action, 'item': file_info}
|
||||
if source_item:
|
||||
result.update({'source_item': source_item})
|
||||
self.server.send_event("file_manager:filelist_changed", result)
|
||||
|
||||
def close(self):
|
||||
self.gcode_metadata.close()
|
||||
|
||||
|
||||
METADATA_PRUNE_TIME = 600000
|
||||
|
||||
class MetadataStorage:
|
||||
def __init__(self, server):
|
||||
self.server = server
|
||||
self.metadata = {}
|
||||
self.pending_requests = {}
|
||||
self.events = {}
|
||||
self.script_response = None
|
||||
self.busy = False
|
||||
self.gc_path = os.path.expanduser("~")
|
||||
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.gc_path = path
|
||||
if not self.prune_cb.is_running():
|
||||
self.prune_cb.start()
|
||||
|
||||
def close(self):
|
||||
self.prune_cb.stop()
|
||||
|
||||
def get(self, key, default=None):
|
||||
if key not in self.metadata:
|
||||
return default
|
||||
return dict(self.metadata[key])
|
||||
|
||||
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
|
||||
|
||||
def prune_metadata(self):
|
||||
for fname in list(self.metadata.keys()):
|
||||
fpath = os.path.join(self.gc_path, fname)
|
||||
if not os.path.exists(fpath):
|
||||
del self.metadata[fname]
|
||||
logging.info(f"Pruned file: {fname}")
|
||||
continue
|
||||
|
||||
def _has_valid_data(self, fname, fsize, modified):
|
||||
mdata = self.metadata.get(fname, {'size': "", 'modified': 0})
|
||||
return mdata['size'] == fsize and mdata['modified'] == modified
|
||||
|
||||
def remove_file(self, fname):
|
||||
self.metadata.pop(fname)
|
||||
|
||||
def parse_metadata(self, fname, fsize, modified, notify=False):
|
||||
evt = Event()
|
||||
if fname in self.pending_requests or \
|
||||
self._has_valid_data(fname, fsize, modified):
|
||||
# request already pending or not necessary
|
||||
evt.set()
|
||||
return evt
|
||||
self.pending_requests[fname] = (fsize, modified, notify, evt)
|
||||
if self.busy:
|
||||
return evt
|
||||
self.busy = True
|
||||
IOLoop.current().spawn_callback(self._process_metadata_update)
|
||||
return evt
|
||||
|
||||
async def _process_metadata_update(self):
|
||||
while self.pending_requests:
|
||||
fname, (fsize, modified, notify, evt) = \
|
||||
self.pending_requests.popitem()
|
||||
if self._has_valid_data(fname, fsize, modified):
|
||||
evt.set()
|
||||
continue
|
||||
retries = 3
|
||||
while retries:
|
||||
try:
|
||||
await self._run_extract_metadata(fname, notify)
|
||||
except Exception:
|
||||
logging.exception("Error running extract_metadata.py")
|
||||
retries -= 1
|
||||
else:
|
||||
break
|
||||
else:
|
||||
self.metadata[fname] = {'size': fsize, 'modified': modified}
|
||||
logging.info(
|
||||
f"Unable to extract medatadata from file: {fname}")
|
||||
evt.set()
|
||||
self.busy = False
|
||||
|
||||
async def _run_extract_metadata(self, filename, notify):
|
||||
# Escape single quotes in the file name so that it may be
|
||||
# properly loaded
|
||||
filename = filename.replace("\"", "\\\"")
|
||||
cmd = " ".join([sys.executable, METADATA_SCRIPT, "-p",
|
||||
self.gc_path, "-f", f"\"{filename}\""])
|
||||
shell_command = self.server.lookup_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']
|
||||
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)
|
||||
metadata['filename'] = path
|
||||
if notify:
|
||||
self.server.send_event(
|
||||
"file_manager:metadata_update", metadata)
|
||||
|
||||
def load_plugin(config):
|
||||
return FileManager(config)
|
||||
@@ -1,64 +0,0 @@
|
||||
# Machine manipulation request handlers
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import logging
|
||||
from tornado.ioloop import IOLoop
|
||||
|
||||
class Machine:
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
self.server.register_endpoint(
|
||||
"/machine/reboot", ['POST'], self._handle_machine_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/shutdown", ['POST'], self._handle_machine_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/services/restart", ['POST'],
|
||||
self._handle_service_restart)
|
||||
|
||||
# Register remote methods
|
||||
self.server.register_remote_method(
|
||||
"shutdown_machine", self.shutdown_machine)
|
||||
self.server.register_remote_method(
|
||||
"reboot_machine", self.reboot_machine)
|
||||
|
||||
async def _handle_machine_request(self, web_request):
|
||||
ep = web_request.get_endpoint()
|
||||
if ep == "/machine/shutdown":
|
||||
await self.shutdown_machine()
|
||||
elif ep == "/machine/reboot":
|
||||
await self.reboot_machine()
|
||||
else:
|
||||
raise self.server.error("Unsupported machine request")
|
||||
return "ok"
|
||||
|
||||
async def shutdown_machine(self):
|
||||
await self._execute_cmd("sudo shutdown now")
|
||||
|
||||
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":
|
||||
IOLoop.current().spawn_callback(
|
||||
self._execute_cmd, f'sudo systemctl restart {name}')
|
||||
else:
|
||||
raise self.sever.error(
|
||||
f"Invalid argument recevied for 'name': {name}")
|
||||
return "ok"
|
||||
|
||||
async def _execute_cmd(self, cmd):
|
||||
shell_command = self.server.lookup_plugin('shell_command')
|
||||
scmd = shell_command.build_shell_command(cmd, None)
|
||||
try:
|
||||
await scmd.run(timeout=2., verbose=False)
|
||||
except Exception:
|
||||
logging.exception(f"Error running cmd '{cmd}'")
|
||||
raise
|
||||
|
||||
def load_plugin(config):
|
||||
return Machine(config)
|
||||
@@ -1,407 +0,0 @@
|
||||
# Raspberry Pi Power Control
|
||||
#
|
||||
# Copyright (C) 2020 Jordan Ruthe <jordanruthe@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
|
||||
import logging
|
||||
import os
|
||||
import asyncio
|
||||
import json
|
||||
import struct
|
||||
import socket
|
||||
import gpiod
|
||||
from tornado.ioloop import IOLoop
|
||||
from tornado.iostream import IOStream
|
||||
from tornado import gen
|
||||
from tornado.httpclient import AsyncHTTPClient
|
||||
from tornado.escape import json_decode
|
||||
|
||||
class PrinterPower:
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
self.server.register_endpoint(
|
||||
"/machine/device_power/devices", ['GET'],
|
||||
self._handle_list_devices)
|
||||
self.server.register_endpoint(
|
||||
"/machine/device_power/status", ['GET'],
|
||||
self._handle_power_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/device_power/on", ['POST'],
|
||||
self._handle_power_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/device_power/off", ['POST'],
|
||||
self._handle_power_request)
|
||||
self.server.register_remote_method(
|
||||
"set_device_power", self.set_device_power)
|
||||
|
||||
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 _handle_list_devices(self, web_request):
|
||||
dev_list = [d.get_device_info() for d in self.devices.values()]
|
||||
output = {"devices": dev_list}
|
||||
return output
|
||||
|
||||
async def _handle_power_request(self, web_request):
|
||||
args = web_request.get_args()
|
||||
ep = web_request.get_endpoint()
|
||||
if not args:
|
||||
raise self.server.error("No arguments provided")
|
||||
requsted_devs = {k: self.devices.get(k, None) for k in args}
|
||||
result = {}
|
||||
req = ep.split("/")[-1]
|
||||
for name, device in requsted_devs.items():
|
||||
if device is not None:
|
||||
result[name] = await self._process_request(device, req)
|
||||
else:
|
||||
result[name] = "device_not_found"
|
||||
return result
|
||||
|
||||
async def _process_request(self, device, req):
|
||||
if req in ["on", "off"]:
|
||||
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)
|
||||
elif req == "status":
|
||||
ret = device.refresh_status()
|
||||
if asyncio.iscoroutine(ret):
|
||||
await ret
|
||||
dev_info = device.get_device_info()
|
||||
else:
|
||||
raise self.server.error(f"Unsupported power request: {req}")
|
||||
return dev_info['status']
|
||||
|
||||
def set_device_power(self, device, state):
|
||||
status = None
|
||||
if isinstance(state, bool):
|
||||
status = "on" if state else "off"
|
||||
elif isinstance(state, str):
|
||||
status = state.lower()
|
||||
if status in ["true", "false"]:
|
||||
status = "on" if status == "true" else "off"
|
||||
if status not in ["on", "off"]:
|
||||
logging.info(f"Invalid state received: {state}")
|
||||
return
|
||||
if device not in self.devices:
|
||||
logging.info(f"No device found: {device}")
|
||||
return
|
||||
ioloop = IOLoop.current()
|
||||
ioloop.spawn_callback(
|
||||
self._process_request, self.devices[device], status)
|
||||
|
||||
async def add_device(self, name, device):
|
||||
if name in self.devices:
|
||||
raise self.server.error(
|
||||
f"Device [{name}] already configured")
|
||||
ret = device.initialize()
|
||||
if asyncio.iscoroutine(ret):
|
||||
await ret
|
||||
self.devices[name] = device
|
||||
|
||||
async def close(self):
|
||||
for device in self.devices.values():
|
||||
if hasattr(device, "close"):
|
||||
ret = device.close()
|
||||
if asyncio.iscoroutine(ret):
|
||||
await ret
|
||||
self.chip_factory.close()
|
||||
|
||||
|
||||
class GpioChipFactory:
|
||||
def __init__(self):
|
||||
self.chips = {}
|
||||
|
||||
def get_gpio_chip(self, chip_name):
|
||||
if chip_name in self.chips:
|
||||
return self.chips[chip_name]
|
||||
chip = gpiod.Chip(chip_name, gpiod.Chip.OPEN_BY_NAME)
|
||||
self.chips[chip_name] = chip
|
||||
return chip
|
||||
|
||||
def close(self):
|
||||
for chip in self.chips.values():
|
||||
chip.close()
|
||||
|
||||
class GpioDevice:
|
||||
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"
|
||||
pin, chip_id, invert = self._parse_pin(config)
|
||||
try:
|
||||
chip = chip_factory.get_gpio_chip(chip_id)
|
||||
self.line = chip.get_line(pin)
|
||||
if invert:
|
||||
self.line.request(
|
||||
consumer="moonraker", type=gpiod.LINE_REQ_DIR_OUT,
|
||||
flags=gpiod.LINE_REQ_FLAG_ACTIVE_LOW)
|
||||
else:
|
||||
self.line.request(
|
||||
consumer="moonraker", type=gpiod.LINE_REQ_DIR_OUT)
|
||||
except Exception:
|
||||
self.state = "error"
|
||||
logging.exception(
|
||||
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")
|
||||
|
||||
def _parse_pin(self, config):
|
||||
pin = cfg_pin = config.get("pin")
|
||||
invert = False
|
||||
if pin[0] == "!":
|
||||
pin = pin[1:]
|
||||
invert = True
|
||||
chip_id = "gpiochip0"
|
||||
pin_parts = pin.split("/")
|
||||
if len(pin_parts) == 2:
|
||||
chip_id, pin = pin_parts
|
||||
elif len(pin_parts) == 1:
|
||||
pin = pin_parts[0]
|
||||
# Verify pin
|
||||
if not chip_id.startswith("gpiochip") or \
|
||||
not chip_id[-1].isdigit() or \
|
||||
not pin.startswith("gpio") or \
|
||||
not pin[4:].isdigit():
|
||||
raise config.error(
|
||||
f"Invalid Power Pin configuration: {cfg_pin}")
|
||||
pin = int(pin[4:])
|
||||
return pin, chip_id, invert
|
||||
|
||||
def initialize(self):
|
||||
pass
|
||||
|
||||
def get_name(self):
|
||||
return self.name
|
||||
|
||||
def get_device_info(self):
|
||||
return {
|
||||
'device': self.name,
|
||||
'status': self.state,
|
||||
'type': "gpio"
|
||||
}
|
||||
|
||||
def refresh_status(self):
|
||||
try:
|
||||
val = self.line.get_value()
|
||||
except Exception:
|
||||
self.state = "error"
|
||||
msg = f"Error Refeshing Device Status: {self.name}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg) from None
|
||||
self.state = "on" if val else "off"
|
||||
|
||||
def set_power(self, state):
|
||||
try:
|
||||
self.line.set_value(int(state == "on"))
|
||||
except Exception:
|
||||
self.state = "error"
|
||||
msg = f"Error Toggling Device Power: {self.name}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg) from None
|
||||
self.state = state
|
||||
|
||||
def close(self):
|
||||
self.line.release()
|
||||
|
||||
|
||||
# This implementation based off the work tplink_smartplug
|
||||
# script by Lubomir Stroetmann available at:
|
||||
#
|
||||
# https://github.com/softScheck/tplink-smartplug
|
||||
#
|
||||
# Copyright 2016 softScheck GmbH
|
||||
class TPLinkSmartPlug:
|
||||
START_KEY = 0xAB
|
||||
def __init__(self, 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 = {}
|
||||
if command in ["on", "off"]:
|
||||
out_cmd = {'system': {'set_relay_state':
|
||||
{'state': int(command == "on")}}}
|
||||
elif command == "info":
|
||||
out_cmd = {'system': {'get_sysinfo': {}}}
|
||||
else:
|
||||
raise self.server.error(f"Invalid tplink command: {command}")
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
stream = IOStream(s)
|
||||
try:
|
||||
await stream.connect((self.addr, self.port))
|
||||
await stream.write(self._encrypt(out_cmd))
|
||||
data = await stream.read_bytes(2048, partial=True)
|
||||
length = struct.unpack(">I", data[:4])[0]
|
||||
data = data[4:]
|
||||
retries = 5
|
||||
remaining = length - len(data)
|
||||
while remaining and retries:
|
||||
data += await stream.read_bytes(remaining)
|
||||
remaining = length - len(data)
|
||||
retries -= 1
|
||||
if not retries:
|
||||
raise self.server.error("Unable to read tplink packet")
|
||||
except Exception:
|
||||
msg = f"Error sending tplink command: {command}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg)
|
||||
finally:
|
||||
stream.close()
|
||||
return json.loads(self._decrypt(data))
|
||||
|
||||
def _encrypt(self, data):
|
||||
data = json.dumps(data)
|
||||
key = self.START_KEY
|
||||
res = struct.pack(">I", len(data))
|
||||
for c in data:
|
||||
val = key ^ ord(c)
|
||||
key = val
|
||||
res += bytes([val])
|
||||
return res
|
||||
|
||||
def _decrypt(self, data):
|
||||
key = self.START_KEY
|
||||
res = ""
|
||||
for c in data:
|
||||
val = key ^ c
|
||||
key = c
|
||||
res += chr(val)
|
||||
return res
|
||||
|
||||
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,
|
||||
'type': "tplink_smartplug"
|
||||
}
|
||||
|
||||
async def refresh_status(self):
|
||||
try:
|
||||
res = await self._send_tplink_command("info")
|
||||
state = res['system']['get_sysinfo']['relay_state']
|
||||
except Exception:
|
||||
self.state = "error"
|
||||
msg = f"Error Refeshing Device Status: {self.name}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg) from None
|
||||
self.state = "on" if state else "off"
|
||||
|
||||
async def set_power(self, state):
|
||||
try:
|
||||
res = await self._send_tplink_command(state)
|
||||
err = res['system']['set_relay_state']['err_code']
|
||||
except Exception:
|
||||
err = 1
|
||||
logging.exception(f"Power Toggle Error: {self.name}")
|
||||
if err:
|
||||
self.state = "error"
|
||||
raise self.server.error(
|
||||
f"Error Toggling Device Power: {self.name}")
|
||||
self.state = state
|
||||
|
||||
|
||||
class Tasmota:
|
||||
def __init__(self, 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"]:
|
||||
out_cmd = f"Power{self.output_id}%20{command}"
|
||||
elif command == "info":
|
||||
out_cmd = "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}"
|
||||
data = ""
|
||||
http_client = AsyncHTTPClient()
|
||||
try:
|
||||
response = await http_client.fetch(url)
|
||||
data = json_decode(response.body)
|
||||
except Exception:
|
||||
msg = f"Error sending tplink command: {command}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg)
|
||||
return data
|
||||
|
||||
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,
|
||||
'type': "tasmota"
|
||||
}
|
||||
|
||||
async def refresh_status(self):
|
||||
try:
|
||||
res = await self._send_tasmota_command("info")
|
||||
state = res[f"POWER{self.output_id}"].lower()
|
||||
except Exception:
|
||||
self.state = "error"
|
||||
msg = f"Error Refeshing Device Status: {self.name}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg) from None
|
||||
self.state = state
|
||||
|
||||
async def set_power(self, state):
|
||||
try:
|
||||
res = await self._send_tasmota_command(state)
|
||||
state = res[f"POWER{self.output_id}"].lower()
|
||||
except Exception:
|
||||
self.state = "error"
|
||||
msg = f"Error Setting Device Status: {self.name} to {state}"
|
||||
logging.exception(msg)
|
||||
raise self.server.error(msg) from None
|
||||
self.state = state
|
||||
|
||||
# The power plugin has multiple configuration sections
|
||||
def load_plugin_multi(config):
|
||||
return PrinterPower(config)
|
||||
@@ -1,116 +0,0 @@
|
||||
# linux shell command execution utility
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import os
|
||||
import shlex
|
||||
import subprocess
|
||||
import logging
|
||||
import tornado
|
||||
from tornado import gen
|
||||
from tornado.ioloop import IOLoop
|
||||
|
||||
class ShellCommand:
|
||||
def __init__(self, cmd, callback):
|
||||
self.io_loop = IOLoop.current()
|
||||
self.name = cmd
|
||||
self.output_cb = callback
|
||||
cmd = os.path.expanduser(cmd)
|
||||
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:
|
||||
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
|
||||
|
||||
def get_return_code(self):
|
||||
return self.return_code
|
||||
|
||||
async def run(self, timeout=2., verbose=True):
|
||||
self.return_code = fd = None
|
||||
if timeout is None:
|
||||
# Never timeout
|
||||
timeout = 9999999999999999.
|
||||
if not timeout or self.output_cb is None:
|
||||
# Fire and forget commands cannot be verbose as we can't
|
||||
# clean up after the process terminates
|
||||
verbose = False
|
||||
try:
|
||||
proc = subprocess.Popen(
|
||||
self.command, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
|
||||
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""
|
||||
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)
|
||||
self.return_code = proc.returncode
|
||||
return self.return_code == 0 and complete
|
||||
|
||||
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 load_plugin(config):
|
||||
return ShellCommandFactory()
|
||||
@@ -1,545 +0,0 @@
|
||||
# Provides updates for Klipper and Moonraker
|
||||
#
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license.
|
||||
import os
|
||||
import re
|
||||
import logging
|
||||
import json
|
||||
import sys
|
||||
import shutil
|
||||
import zipfile
|
||||
import io
|
||||
import asyncio
|
||||
import tornado.gen
|
||||
from tornado.ioloop import IOLoop
|
||||
from tornado.httpclient import AsyncHTTPClient, HTTPRequest
|
||||
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
|
||||
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",
|
||||
'dist_packages': ["gpiod"],
|
||||
'dist_dir': "/usr/lib/python3/dist-packages",
|
||||
'site_pkg_path': "lib/python3.7/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",
|
||||
'dist_packages': [],
|
||||
'dist_dir': "",
|
||||
'site_pkg_path': "",
|
||||
}
|
||||
}
|
||||
|
||||
class UpdateManager:
|
||||
def __init__(self, config):
|
||||
self.server = config.get_server()
|
||||
AsyncHTTPClient.configure(None, defaults=dict(user_agent="Moonraker"))
|
||||
self.http_client = AsyncHTTPClient()
|
||||
env = sys.executable
|
||||
self.updaters = {
|
||||
"system": PackageUpdater(self),
|
||||
"moonraker": GitUpdater(self, "moonraker", MOONRAKER_PATH, env)
|
||||
}
|
||||
self.current_update = None
|
||||
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)
|
||||
|
||||
self.server.register_endpoint(
|
||||
"/machine/update/moonraker", ["POST"],
|
||||
self._handle_update_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/update/klipper", ["POST"],
|
||||
self._handle_update_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/update/system", ["POST"],
|
||||
self._handle_update_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/update/client", ["POST"],
|
||||
self._handle_update_request)
|
||||
self.server.register_endpoint(
|
||||
"/machine/update/status", ["GET"],
|
||||
self._handle_status_request)
|
||||
|
||||
# Register Ready Event
|
||||
self.server.register_event_handler(
|
||||
"server:klippy_ready", self._set_klipper_repo)
|
||||
|
||||
async def _set_klipper_repo(self):
|
||||
kinfo = self.server.get_klippy_info()
|
||||
if not kinfo:
|
||||
logging.info("No valid klippy info received")
|
||||
return
|
||||
kpath = kinfo['klipper_path']
|
||||
env = kinfo['python_path']
|
||||
self.updaters['klipper'] = GitUpdater(self, "klipper", kpath, env)
|
||||
|
||||
async def _handle_update_request(self, web_request):
|
||||
app = web_request.get_endpoint().split("/")[-1]
|
||||
inc_deps = web_request.get_boolean('include_deps', False)
|
||||
if self.current_update:
|
||||
raise self.server.error("A current update is in progress")
|
||||
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
|
||||
return "ok"
|
||||
|
||||
async def _handle_status_request(self, web_request):
|
||||
refresh = web_request.get_boolean('refresh', False)
|
||||
vinfo = {}
|
||||
for name, updater in self.updaters.items():
|
||||
await updater.check_initialized(10.)
|
||||
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,
|
||||
'busy': self.current_update is not None}
|
||||
|
||||
async def execute_cmd(self, cmd, timeout=10., notify=False, retries=1):
|
||||
shell_command = self.server.lookup_plugin('shell_command')
|
||||
cb = self.notify_update_response if notify else None
|
||||
scmd = shell_command.build_shell_command(cmd, callback=cb)
|
||||
while retries:
|
||||
if await scmd.run(timeout=timeout, verbose=notify):
|
||||
break
|
||||
retries -= 1
|
||||
if not retries:
|
||||
raise self.server.error("Shell Command Error")
|
||||
|
||||
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)
|
||||
|
||||
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
|
||||
try:
|
||||
fut = self.http_client.fetch(request)
|
||||
resp = await tornado.gen.with_timeout(to, fut)
|
||||
except Exception as e:
|
||||
retries -= 1
|
||||
if not retries:
|
||||
raise
|
||||
logging.info(f"Github request error, retrying: {e}")
|
||||
continue
|
||||
if is_download:
|
||||
return resp.body
|
||||
decoded = json.loads(resp.body)
|
||||
return decoded
|
||||
|
||||
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,
|
||||
'complete': is_complete}
|
||||
if self.current_update is not None:
|
||||
notification['application'] = self.current_update[0]
|
||||
notification['proc_id'] = self.current_update[1]
|
||||
self.server.send_event(
|
||||
"update_manager:update_response", notification)
|
||||
|
||||
def close(self):
|
||||
self.http_client.close()
|
||||
|
||||
|
||||
class GitUpdater:
|
||||
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
|
||||
self.name = name
|
||||
self.repo_path = path
|
||||
self.env = env
|
||||
self.version = self.cur_hash = self.remote_hash = "?"
|
||||
self.init_evt = Event()
|
||||
self.is_valid = self.is_dirty = False
|
||||
IOLoop.current().spawn_callback(self.refresh)
|
||||
|
||||
def _get_version_info(self):
|
||||
ver_path = os.path.join(self.repo_path, "scripts/version.txt")
|
||||
vinfo = {}
|
||||
if os.path.isfile(ver_path):
|
||||
data = ""
|
||||
with open(ver_path, 'r') as f:
|
||||
data = f.read()
|
||||
try:
|
||||
entries = [e.strip() for e in data.split('\n') if e.strip()]
|
||||
vinfo = dict([i.split('=') for i in entries])
|
||||
vinfo = {k: tuple(re.findall(r"\d+", v)) for k, v in
|
||||
vinfo.items()}
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
self._log_info(f"Version Info Found: {vinfo}")
|
||||
vinfo['version'] = tuple(re.findall(r"\d+", self.version))
|
||||
return vinfo
|
||||
|
||||
def _log_exc(self, msg, traceback=True):
|
||||
log_msg = f"Repo {self.name}: {msg}"
|
||||
if traceback:
|
||||
logging.exception(log_msg)
|
||||
else:
|
||||
logging.info(log_msg)
|
||||
return self.server.error(msg)
|
||||
|
||||
def _log_info(self, msg):
|
||||
log_msg = f"Repo {self.name}: {msg}"
|
||||
logging.info(log_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, is_complete)
|
||||
|
||||
async def check_initialized(self, timeout=None):
|
||||
if self.init_evt.is_set():
|
||||
return
|
||||
if timeout is not None:
|
||||
to = IOLoop.current().time() + timeout
|
||||
await self.init_evt.wait(to)
|
||||
|
||||
async def refresh(self):
|
||||
await self._check_local_version()
|
||||
await self._check_remote_version()
|
||||
self.init_evt.set()
|
||||
|
||||
async def _check_local_version(self):
|
||||
self.is_valid = False
|
||||
self.cur_hash = "?"
|
||||
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(
|
||||
f"git -C {self.repo_path} rev-parse HEAD")
|
||||
repo_version = await self.execute_cmd_with_response(
|
||||
f"git -C {self.repo_path} describe --always "
|
||||
"--tags --long --dirty")
|
||||
except Exception:
|
||||
self._log_exc("Error retreiving git info")
|
||||
return
|
||||
|
||||
self.is_dirty = repo_version.endswith("dirty")
|
||||
tag_version = "?"
|
||||
ver_match = re.match(r"v\d+\.\d+\.\d-\d+", repo_version)
|
||||
if ver_match:
|
||||
tag_version = ver_match.group()
|
||||
self.version = tag_version
|
||||
|
||||
if not branch.startswith("fatal:"):
|
||||
self.cur_hash = hash
|
||||
if branch == "master":
|
||||
origin = origin.lower()
|
||||
if origin[-4:] != ".git":
|
||||
origin += ".git"
|
||||
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}'")
|
||||
else:
|
||||
self._log_info("Git repo not on master branch")
|
||||
else:
|
||||
self._log_info(f"Invalid git repo at path '{self.repo_path}'")
|
||||
|
||||
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
|
||||
|
||||
async def update(self, update_deps=False):
|
||||
if not self.is_valid:
|
||||
raise self._log_exc("Update aborted, repo is not valid", False)
|
||||
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")
|
||||
except Exception:
|
||||
raise self._log_exc("Error running 'git pull'")
|
||||
# Check Semantic Versions
|
||||
vinfo = self._get_version_info()
|
||||
cur_version = vinfo.get('version', ())
|
||||
update_deps |= cur_version < vinfo.get('deps_version', ())
|
||||
need_env_rebuild = cur_version < vinfo.get('env_version', ())
|
||||
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_local_version()
|
||||
if self.name == "moonraker":
|
||||
# Launch restart async so the request can return
|
||||
# before the server restarts
|
||||
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_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}")
|
||||
return
|
||||
with open(inst_path, 'r') as f:
|
||||
data = f.read()
|
||||
packages = re.findall(r'PKGLIST="(.*)"', data)
|
||||
packages = [p.lstrip("${PKGLIST}").strip() for p in packages]
|
||||
if not packages:
|
||||
self._log_info(f"No packages found in script: {inst_path}")
|
||||
return
|
||||
# TODO: Log and notify that packages will be installed
|
||||
pkgs = " ".join(packages)
|
||||
logging.debug(f"Repo {self.name}: Detected Packages: {pkgs}")
|
||||
self._notify_status("Installing system dependencies...")
|
||||
# Install packages with apt-get
|
||||
try:
|
||||
await self.execute_cmd(
|
||||
f"{APT_CMD} update", timeout=300., notify=True)
|
||||
await self.execute_cmd(
|
||||
f"{APT_CMD} install --yes {pkgs}", timeout=3600.,
|
||||
notify=True)
|
||||
except Exception:
|
||||
self._log_exc("Error updating packages via apt-get")
|
||||
return
|
||||
|
||||
async def _update_virtualenv(self, rebuild_env=False):
|
||||
# Update python dependencies
|
||||
bin_dir = os.path.dirname(self.env)
|
||||
if rebuild_env:
|
||||
env_path = os.path.normpath(os.path.join(bin_dir, ".."))
|
||||
env_args = REPO_DATA[self.name]['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.)
|
||||
except Exception:
|
||||
self._log_exc(f"Error creating virtualenv")
|
||||
return
|
||||
if not os.path.expanduser(self.env):
|
||||
raise self._log_exc("Failed to create new virtualenv", False)
|
||||
dist_pkgs = REPO_DATA[self.name]['dist_packages']
|
||||
dist_dir = REPO_DATA[self.name]['dist_dir']
|
||||
site_path = REPO_DATA[self.name]['site_pkg_path']
|
||||
for pkg in dist_pkgs:
|
||||
for f in os.listdir(dist_dir):
|
||||
if f.startswith(pkg):
|
||||
src = os.path.join(dist_dir, f)
|
||||
dest = os.path.join(env_path, site_path, f)
|
||||
self._notify_status(f"Linking to dist package: {pkg}")
|
||||
os.symlink(f, dest)
|
||||
break
|
||||
reqs = os.path.join(
|
||||
self.repo_path, REPO_DATA[self.name]['requirements'])
|
||||
if not os.path.isfile(reqs):
|
||||
self._log_exc(f"Invalid path to requirements_file '{reqs}'")
|
||||
return
|
||||
pip = os.path.join(bin_dir, "pip")
|
||||
self._notify_status("Updating python packages...")
|
||||
try:
|
||||
await self.execute_cmd(
|
||||
f"{pip} install -r {reqs}", timeout=1200., notify=True,
|
||||
retries=3)
|
||||
except Exception:
|
||||
self._log_exc("Error updating python requirements")
|
||||
|
||||
async def restart_service(self):
|
||||
self._notify_status("Restarting Service...")
|
||||
try:
|
||||
await self.execute_cmd(f"sudo systemctl restart {self.name}")
|
||||
except Exception:
|
||||
raise self._log_exc("Error restarting service")
|
||||
|
||||
def get_update_status(self):
|
||||
return {
|
||||
'version': self.version,
|
||||
'current_hash': self.cur_hash,
|
||||
'remote_hash': self.remote_hash,
|
||||
'is_dirty': self.is_dirty,
|
||||
'is_valid': self.is_valid}
|
||||
|
||||
|
||||
class PackageUpdater:
|
||||
def __init__(self, umgr):
|
||||
self.server = umgr.server
|
||||
self.execute_cmd = umgr.execute_cmd
|
||||
self.notify_update_response = umgr.notify_update_response
|
||||
|
||||
def refresh(self):
|
||||
# TODO: We should be able to determine if packages need to be
|
||||
# updated here
|
||||
pass
|
||||
|
||||
async def check_initialized(self, timeout=None):
|
||||
pass
|
||||
|
||||
async def update(self, *args):
|
||||
self.notify_update_response("Updating packages...")
|
||||
try:
|
||||
await self.execute_cmd(
|
||||
f"{APT_CMD} update", timeout=300., notify=True)
|
||||
await self.execute_cmd(
|
||||
f"{APT_CMD} upgrade --yes", timeout=3600., notify=True)
|
||||
except Exception:
|
||||
raise self.server.error("Error updating system packages")
|
||||
self.notify_update_response("Package update finished...",
|
||||
is_complete=True)
|
||||
|
||||
class ClientUpdater:
|
||||
def __init__(self, umgr, repo, path):
|
||||
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.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()
|
||||
|
||||
async def check_initialized(self, timeout=None):
|
||||
if self.init_evt.is_set():
|
||||
return
|
||||
if timeout is not None:
|
||||
to = IOLoop.current().time() + timeout
|
||||
await self.init_evt.wait(to)
|
||||
|
||||
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)
|
||||
except Exception:
|
||||
logging.exception(f"Client {self.repo}: Github Request Error")
|
||||
result = {}
|
||||
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"url: {self.dl_url}")
|
||||
self.init_evt.set()
|
||||
|
||||
async def update(self, *args):
|
||||
if self.remote_version == "?":
|
||||
await self.refresh()
|
||||
if self.remote_version == "?":
|
||||
raise self.server.error(
|
||||
f"Client {self.repo}: Unable to locate update")
|
||||
if self.dl_url == "?":
|
||||
raise self.server.error(
|
||||
f"Client {self.repo}: Invalid download url")
|
||||
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.github_request(self.dl_url, is_download=True)
|
||||
with zipfile.ZipFile(io.BytesIO(archive)) as zf:
|
||||
zf.extractall(self.path)
|
||||
self.version = self.remote_version
|
||||
version_path = os.path.join(self.path, ".version")
|
||||
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 Finished: {self.name}",
|
||||
is_complete=True)
|
||||
|
||||
def get_update_status(self):
|
||||
return {
|
||||
'name': self.name,
|
||||
'version': self.version,
|
||||
'remote_version': self.remote_version
|
||||
}
|
||||
|
||||
def load_plugin(config):
|
||||
return UpdateManager(config)
|
||||
+127
-40
@@ -3,19 +3,46 @@
|
||||
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
|
||||
from __future__ import annotations
|
||||
import logging
|
||||
import logging.handlers
|
||||
import os
|
||||
import pathlib
|
||||
import sys
|
||||
import subprocess
|
||||
import asyncio
|
||||
import hashlib
|
||||
import json
|
||||
from queue import SimpleQueue as Queue
|
||||
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
List,
|
||||
Optional,
|
||||
ClassVar,
|
||||
Tuple,
|
||||
Dict,
|
||||
Any,
|
||||
)
|
||||
|
||||
MOONRAKER_PATH = os.path.join(os.path.dirname(__file__), '..')
|
||||
|
||||
class ServerError(Exception):
|
||||
def __init__(self, message, status_code=400):
|
||||
def __init__(self, message: str, status_code: int = 400) -> None:
|
||||
Exception.__init__(self, message)
|
||||
self.status_code = status_code
|
||||
|
||||
|
||||
class SentinelClass:
|
||||
_instance: ClassVar[Optional[SentinelClass]] = None
|
||||
|
||||
@staticmethod
|
||||
def get_instance() -> SentinelClass:
|
||||
if SentinelClass._instance is None:
|
||||
SentinelClass._instance = SentinelClass()
|
||||
return SentinelClass._instance
|
||||
|
||||
# Coroutine friendly QueueHandler courtesy of Martjin Pieters:
|
||||
# https://www.zopatista.com/python/2019/05/11/asyncio-logging/
|
||||
class LocalQueueHandler(logging.handlers.QueueHandler):
|
||||
@@ -28,62 +55,122 @@ 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"
|
||||
def __init__(self, app_args: Dict[str, Any], **kwargs) -> None:
|
||||
super().__init__(app_args['log_file'], **kwargs)
|
||||
self.rollover_info: Dict[str, str] = {
|
||||
'header': f"{'-'*20}Moonraker Log Start{'-'*20}"
|
||||
}
|
||||
self.rollover_info['application_args'] = "\n".join(
|
||||
[f"{k}: {v}" for k, v in app_args.items()])
|
||||
lines = [line for line in self.rollover_info.values() if line]
|
||||
if self.stream is not None:
|
||||
self.stream.write(self.header)
|
||||
self.stream.write("\n".join(lines) + "\n")
|
||||
|
||||
def doRollover(self):
|
||||
super(MoonrakerLoggingHandler, self).doRollover()
|
||||
def set_rollover_info(self, name: str, item: str) -> None:
|
||||
self.rollover_info[name] = item
|
||||
|
||||
def doRollover(self) -> None:
|
||||
super().doRollover()
|
||||
lines = [line for line in self.rollover_info.values() if line]
|
||||
if self.stream is not None:
|
||||
self.stream.write(self.header)
|
||||
self.stream.write("\n".join(lines) + "\n")
|
||||
|
||||
# Parse the git version from the command line. This code
|
||||
# is borrowed from Klipper.
|
||||
def get_software_version():
|
||||
moonraker_path = os.path.join(
|
||||
os.path.dirname(__file__), '..')
|
||||
|
||||
def retreive_git_version(source_path: str) -> str:
|
||||
# Obtain version info from "git" program
|
||||
prog = ('git', '-C', moonraker_path, 'describe', '--always',
|
||||
prog = ('git', '-C', source_path, 'describe', '--always',
|
||||
'--tags', '--long', '--dirty')
|
||||
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE)
|
||||
ver, err = process.communicate()
|
||||
retcode = process.wait()
|
||||
if retcode == 0:
|
||||
return ver.strip().decode()
|
||||
raise Exception(f"Failed to retreive git version: {err.decode()}")
|
||||
|
||||
def get_software_version() -> str:
|
||||
version = "?"
|
||||
|
||||
try:
|
||||
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE)
|
||||
ver, err = process.communicate()
|
||||
retcode = process.wait()
|
||||
if retcode == 0:
|
||||
version = ver.strip()
|
||||
if isinstance(version, bytes):
|
||||
version = version.decode()
|
||||
return version
|
||||
else:
|
||||
logging.debug(f"Error getting git version: {err}")
|
||||
except OSError:
|
||||
logging.exception("Error runing git describe")
|
||||
version = retreive_git_version(MOONRAKER_PATH)
|
||||
except Exception:
|
||||
vfile = pathlib.Path(os.path.join(
|
||||
MOONRAKER_PATH, "moonraker/.version"))
|
||||
if vfile.exists():
|
||||
try:
|
||||
version = vfile.read_text().strip()
|
||||
except Exception:
|
||||
logging.exception("Unable to extract version from file")
|
||||
version = "?"
|
||||
return version
|
||||
|
||||
return "?"
|
||||
|
||||
def setup_logging(log_file, software_version):
|
||||
def setup_logging(app_args: Dict[str, Any]
|
||||
) -> Tuple[logging.handlers.QueueListener,
|
||||
Optional[MoonrakerLoggingHandler]]:
|
||||
root_logger = logging.getLogger()
|
||||
queue = Queue()
|
||||
queue: Queue = Queue()
|
||||
queue_handler = LocalQueueHandler(queue)
|
||||
root_logger.addHandler(queue_handler)
|
||||
root_logger.setLevel(logging.INFO)
|
||||
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)
|
||||
for name, val in app_args.items():
|
||||
logging.info(f"{name}: {val}")
|
||||
file_hdlr = None
|
||||
if app_args.get('log_file', ""):
|
||||
file_hdlr = MoonrakerLoggingHandler(
|
||||
app_args, 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
|
||||
|
||||
def hash_directory(dir_path: str,
|
||||
ignore_exts: List[str],
|
||||
ignore_dirs: List[str]
|
||||
) -> str:
|
||||
checksum = hashlib.blake2s()
|
||||
if not os.path.exists(dir_path):
|
||||
return ""
|
||||
for dpath, dnames, fnames in os.walk(dir_path):
|
||||
valid_dirs: List[str] = []
|
||||
for dname in sorted(dnames):
|
||||
if dname[0] == '.' or dname in ignore_dirs:
|
||||
continue
|
||||
valid_dirs.append(dname)
|
||||
dnames[:] = valid_dirs
|
||||
for fname in sorted(fnames):
|
||||
ext = os.path.splitext(fname)[-1].lower()
|
||||
if fname[0] == '.' or ext in ignore_exts:
|
||||
continue
|
||||
fpath = pathlib.Path(os.path.join(dpath, fname))
|
||||
try:
|
||||
checksum.update(fpath.read_bytes())
|
||||
except Exception:
|
||||
pass
|
||||
return checksum.hexdigest()
|
||||
|
||||
def verify_source(path: str = MOONRAKER_PATH) -> Optional[Tuple[str, bool]]:
|
||||
rfile = pathlib.Path(os.path.join(path, ".release_info"))
|
||||
if not rfile.exists():
|
||||
return None
|
||||
try:
|
||||
rinfo = json.loads(rfile.read_text())
|
||||
except Exception:
|
||||
return None
|
||||
orig_chksum = rinfo['source_checksum']
|
||||
ign_dirs = rinfo['ignored_dirs']
|
||||
ign_exts = rinfo['ignored_exts']
|
||||
checksum = hash_directory(path, ign_exts, ign_dirs)
|
||||
return checksum, checksum == orig_chksum
|
||||
+296
-163
@@ -4,113 +4,195 @@
|
||||
#
|
||||
# This file may be distributed under the terms of the GNU GPLv3 license
|
||||
|
||||
from __future__ import annotations
|
||||
import logging
|
||||
import tornado
|
||||
import ipaddress
|
||||
import json
|
||||
import tornado.util
|
||||
from tornado.ioloop import IOLoop
|
||||
from tornado.websocket import WebSocketHandler, WebSocketClosedError
|
||||
from utils import ServerError
|
||||
from tornado.locks import Event
|
||||
from utils import ServerError, SentinelClass
|
||||
|
||||
class Sentinel:
|
||||
pass
|
||||
# Annotation imports
|
||||
from typing import (
|
||||
TYPE_CHECKING,
|
||||
Any,
|
||||
Optional,
|
||||
Callable,
|
||||
Coroutine,
|
||||
Type,
|
||||
TypeVar,
|
||||
Union,
|
||||
Dict,
|
||||
List,
|
||||
)
|
||||
if TYPE_CHECKING:
|
||||
from moonraker import Server
|
||||
from app import APIDefinition, MoonrakerApp
|
||||
import components.authorization
|
||||
_T = TypeVar("_T")
|
||||
_C = TypeVar("_C", str, bool, float, int)
|
||||
IPUnion = Union[ipaddress.IPv4Address, ipaddress.IPv6Address]
|
||||
ConvType = Union[str, bool, float, int]
|
||||
ArgVal = Union[None, int, float, bool, str]
|
||||
RPCCallback = Callable[..., Coroutine]
|
||||
AuthComp = Optional[components.authorization.Authorization]
|
||||
|
||||
SENTINEL = SentinelClass.get_instance()
|
||||
|
||||
class Subscribable:
|
||||
def send_status(self,
|
||||
status: Dict[str, Any],
|
||||
eventtime: float
|
||||
) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
class WebRequest:
|
||||
def __init__(self, endpoint, args, action="", conn=None):
|
||||
def __init__(self,
|
||||
endpoint: str,
|
||||
args: Dict[str, Any],
|
||||
action: Optional[str] = "",
|
||||
conn: Optional[Subscribable] = None,
|
||||
ip_addr: str = "",
|
||||
user: Optional[Dict[str, Any]] = None
|
||||
) -> None:
|
||||
self.endpoint = endpoint
|
||||
self.action = action
|
||||
self.action = action or ""
|
||||
self.args = args
|
||||
self.conn = conn
|
||||
self.ip_addr: Optional[IPUnion] = None
|
||||
try:
|
||||
self.ip_addr = ipaddress.ip_address(ip_addr)
|
||||
except Exception:
|
||||
self.ip_addr = None
|
||||
self.current_user = user
|
||||
|
||||
def get_endpoint(self):
|
||||
def get_endpoint(self) -> str:
|
||||
return self.endpoint
|
||||
|
||||
def get_action(self):
|
||||
def get_action(self) -> str:
|
||||
return self.action
|
||||
|
||||
def get_args(self):
|
||||
def get_args(self) -> Dict[str, Any]:
|
||||
return self.args
|
||||
|
||||
def get_connection(self):
|
||||
def get_connection(self) -> Optional[Subscribable]:
|
||||
return self.conn
|
||||
|
||||
def _get_converted_arg(self, key, default=Sentinel, dtype=str):
|
||||
def get_ip_address(self) -> Optional[IPUnion]:
|
||||
return self.ip_addr
|
||||
|
||||
def get_current_user(self) -> Optional[Dict[str, Any]]:
|
||||
return self.current_user
|
||||
|
||||
def _get_converted_arg(self,
|
||||
key: str,
|
||||
default: Union[SentinelClass, _T],
|
||||
dtype: Type[_C]
|
||||
) -> Union[_C, _T]:
|
||||
if key not in self.args:
|
||||
if default == Sentinel:
|
||||
if isinstance(default, SentinelClass):
|
||||
raise ServerError(f"No data for argument: {key}")
|
||||
return default
|
||||
val = self.args[key]
|
||||
try:
|
||||
if dtype != bool:
|
||||
if dtype is not bool:
|
||||
return dtype(val)
|
||||
else:
|
||||
if isinstance(val, str):
|
||||
val = val.lower()
|
||||
if val in ["true", "false"]:
|
||||
return True if val == "true" else False
|
||||
return True if val == "true" else False # type: ignore
|
||||
elif isinstance(val, bool):
|
||||
return val
|
||||
return val # type: ignore
|
||||
raise TypeError
|
||||
except Exception:
|
||||
raise ServerError(
|
||||
f"Unable to convert argument [{key}] to {dtype}: "
|
||||
f"value recieved: {val}")
|
||||
|
||||
def get(self, key, default=Sentinel):
|
||||
def get(self,
|
||||
key: str,
|
||||
default: Union[SentinelClass, _T] = SENTINEL
|
||||
) -> Union[_T, Any]:
|
||||
val = self.args.get(key, default)
|
||||
if val == Sentinel:
|
||||
if isinstance(val, SentinelClass):
|
||||
raise ServerError(f"No data for argument: {key}")
|
||||
return val
|
||||
|
||||
def get_str(self, key, default=Sentinel):
|
||||
return self._get_converted_arg(key, default)
|
||||
def get_str(self,
|
||||
key: str,
|
||||
default: Union[SentinelClass, _T] = SENTINEL
|
||||
) -> Union[str, _T]:
|
||||
return self._get_converted_arg(key, default, str)
|
||||
|
||||
def get_int(self, key, default=Sentinel):
|
||||
def get_int(self,
|
||||
key: str,
|
||||
default: Union[SentinelClass, _T] = SENTINEL
|
||||
) -> Union[int, _T]:
|
||||
return self._get_converted_arg(key, default, int)
|
||||
|
||||
def get_float(self, key, default=Sentinel):
|
||||
def get_float(self,
|
||||
key: str,
|
||||
default: Union[SentinelClass, _T] = SENTINEL
|
||||
) -> Union[float, _T]:
|
||||
return self._get_converted_arg(key, default, float)
|
||||
|
||||
def get_boolean(self, key, default=Sentinel):
|
||||
def get_boolean(self,
|
||||
key: str,
|
||||
default: Union[SentinelClass, _T] = SENTINEL
|
||||
) -> Union[bool, _T]:
|
||||
return self._get_converted_arg(key, default, bool)
|
||||
|
||||
class JsonRPC:
|
||||
def __init__(self):
|
||||
self.methods = {}
|
||||
def __init__(self, transport: str = "Websocket") -> None:
|
||||
self.methods: Dict[str, RPCCallback] = {}
|
||||
self.transport = transport
|
||||
|
||||
def register_method(self, name, method):
|
||||
def register_method(self,
|
||||
name: str,
|
||||
method: RPCCallback
|
||||
) -> None:
|
||||
self.methods[name] = method
|
||||
|
||||
def remove_method(self, name):
|
||||
def remove_method(self, name: str) -> None:
|
||||
self.methods.pop(name, None)
|
||||
|
||||
async def dispatch(self, data, ws):
|
||||
response = None
|
||||
async def dispatch(self,
|
||||
data: str,
|
||||
conn: Optional[WebSocket] = None
|
||||
) -> Optional[str]:
|
||||
response: Any = None
|
||||
try:
|
||||
request = json.loads(data)
|
||||
request: Union[Dict[str, Any], List[dict]] = json.loads(data)
|
||||
except Exception:
|
||||
msg = f"Websocket data not json: {data}"
|
||||
msg = f"{self.transport} data not json: {data}"
|
||||
logging.exception(msg)
|
||||
response = self.build_error(-32700, "Parse error")
|
||||
return json.dumps(response)
|
||||
logging.debug("Websocket Request::" + data)
|
||||
logging.debug(f"{self.transport} Request::{data}")
|
||||
if isinstance(request, list):
|
||||
response = []
|
||||
for req in request:
|
||||
resp = await self.process_request(req, ws)
|
||||
resp = await self.process_request(req, conn)
|
||||
if resp is not None:
|
||||
response.append(resp)
|
||||
if not response:
|
||||
response = None
|
||||
else:
|
||||
response = await self.process_request(request, ws)
|
||||
response = await self.process_request(request, conn)
|
||||
if response is not None:
|
||||
response = json.dumps(response)
|
||||
logging.debug("Websocket Response::" + response)
|
||||
logging.debug(f"{self.transport} Response::{response}")
|
||||
return response
|
||||
|
||||
async def process_request(self, request, ws):
|
||||
req_id = request.get('id', None)
|
||||
rpc_version = request.get('jsonrpc', "")
|
||||
async def process_request(self,
|
||||
request: Dict[str, Any],
|
||||
conn: Optional[WebSocket]
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
req_id: Optional[int] = request.get('id', None)
|
||||
rpc_version: str = request.get('jsonrpc', "")
|
||||
method_name = request.get('method', None)
|
||||
if rpc_version != "2.0" or not isinstance(method_name, str):
|
||||
return self.build_error(-32600, "Invalid Request", req_id)
|
||||
@@ -121,209 +203,260 @@ class JsonRPC:
|
||||
params = request['params']
|
||||
if isinstance(params, list):
|
||||
response = await self.execute_method(
|
||||
method, req_id, ws, *params)
|
||||
method, req_id, conn, *params)
|
||||
elif isinstance(params, dict):
|
||||
response = await self.execute_method(
|
||||
method, req_id, ws, **params)
|
||||
method, req_id, conn, **params)
|
||||
else:
|
||||
return self.build_error(-32600, "Invalid Request", req_id)
|
||||
else:
|
||||
response = await self.execute_method(method, req_id, ws)
|
||||
response = await self.execute_method(method, req_id, conn)
|
||||
return response
|
||||
|
||||
async def execute_method(self, method, req_id, ws, *args, **kwargs):
|
||||
async def execute_method(self,
|
||||
method: RPCCallback,
|
||||
req_id: Optional[int],
|
||||
conn: Optional[WebSocket],
|
||||
*args,
|
||||
**kwargs
|
||||
) -> Optional[Dict[str, Any]]:
|
||||
try:
|
||||
result = await method(ws, *args, **kwargs)
|
||||
if conn is not None:
|
||||
result = await method(conn, *args, **kwargs)
|
||||
else:
|
||||
result = await method(*args, **kwargs)
|
||||
except TypeError as e:
|
||||
return self.build_error(-32603, f"Invalid params:\n{e}", req_id)
|
||||
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
|
||||
else:
|
||||
return self.build_result(result, req_id)
|
||||
|
||||
def build_result(self, result, req_id):
|
||||
def build_result(self, result: Any, req_id: int) -> Dict[str, Any]:
|
||||
return {
|
||||
'jsonrpc': "2.0",
|
||||
'result': result,
|
||||
'id': req_id
|
||||
}
|
||||
|
||||
def build_error(self, code, msg, req_id=None):
|
||||
def build_error(self,
|
||||
code: int,
|
||||
msg: str,
|
||||
req_id: Optional[int] = None,
|
||||
is_exc: bool = False
|
||||
) -> Dict[str, Any]:
|
||||
log_msg = f"JSON-RPC Request Error: {code}\n{msg}"
|
||||
if is_exc:
|
||||
logging.exception(log_msg)
|
||||
else:
|
||||
logging.info(log_msg)
|
||||
return {
|
||||
'jsonrpc': "2.0",
|
||||
'error': {'code': code, 'message': msg},
|
||||
'id': req_id
|
||||
}
|
||||
|
||||
class WebsocketManager:
|
||||
def __init__(self, server):
|
||||
class APITransport:
|
||||
def register_api_handler(self, api_def: APIDefinition) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
def remove_api_handler(self, api_def: APIDefinition) -> None:
|
||||
raise NotImplementedError
|
||||
|
||||
class WebsocketManager(APITransport):
|
||||
def __init__(self, server: Server) -> None:
|
||||
self.server = server
|
||||
self.websockets = {}
|
||||
self.ws_lock = tornado.locks.Lock()
|
||||
self.websockets: Dict[int, WebSocket] = {}
|
||||
self.rpc = JsonRPC()
|
||||
self.closed_event: Optional[Event] = None
|
||||
|
||||
self.rpc.register_method("server.websocket.id", self._handle_id_request)
|
||||
|
||||
# Register events
|
||||
def register_notification(self,
|
||||
event_name: str,
|
||||
notify_name: Optional[str] = None
|
||||
) -> None:
|
||||
if notify_name is None:
|
||||
notify_name = event_name.split(':')[-1]
|
||||
|
||||
def notify_handler(*args):
|
||||
self.notify_websockets(notify_name, *args)
|
||||
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)
|
||||
event_name, notify_handler)
|
||||
|
||||
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)
|
||||
|
||||
def register_local_handler(self, api_def, callback):
|
||||
for ws_method, req_method in \
|
||||
zip(api_def.ws_methods, api_def.request_methods):
|
||||
rpc_cb = self._generate_local_callback(
|
||||
api_def.endpoint, req_method, callback)
|
||||
def register_api_handler(self, api_def: APIDefinition) -> None:
|
||||
if api_def.callback is None:
|
||||
# Remote API, uses RPC to reach out to Klippy
|
||||
ws_method = api_def.jrpc_methods[0]
|
||||
rpc_cb = self._generate_callback(api_def.endpoint)
|
||||
self.rpc.register_method(ws_method, rpc_cb)
|
||||
else:
|
||||
# Local API, uses local callback
|
||||
for ws_method, req_method in \
|
||||
zip(api_def.jrpc_methods, api_def.request_methods):
|
||||
rpc_cb = self._generate_local_callback(
|
||||
api_def.endpoint, req_method, api_def.callback)
|
||||
self.rpc.register_method(ws_method, rpc_cb)
|
||||
logging.info(
|
||||
"Registering Websocket JSON-RPC methods: "
|
||||
f"{', '.join(api_def.jrpc_methods)}")
|
||||
|
||||
def register_remote_handler(self, api_def):
|
||||
ws_method = api_def.ws_methods[0]
|
||||
rpc_cb = self._generate_callback(api_def.endpoint)
|
||||
self.rpc.register_method(ws_method, rpc_cb)
|
||||
def remove_api_handler(self, api_def: APIDefinition) -> None:
|
||||
for jrpc_method in api_def.jrpc_methods:
|
||||
self.rpc.remove_method(jrpc_method)
|
||||
|
||||
def remove_handler(self, ws_method):
|
||||
self.rpc.remove_method(ws_method)
|
||||
|
||||
def _generate_callback(self, endpoint):
|
||||
async def func(ws, **kwargs):
|
||||
def _generate_callback(self, endpoint: str) -> RPCCallback:
|
||||
async def func(ws: WebSocket, **kwargs) -> Any:
|
||||
result = await self.server.make_request(
|
||||
WebRequest(endpoint, kwargs, conn=ws))
|
||||
WebRequest(endpoint, kwargs, conn=ws, ip_addr=ws.ip_addr,
|
||||
user=ws.current_user))
|
||||
return result
|
||||
return func
|
||||
|
||||
def _generate_local_callback(self, endpoint, request_method, callback):
|
||||
async def func(ws, **kwargs):
|
||||
def _generate_local_callback(self,
|
||||
endpoint: str,
|
||||
request_method: str,
|
||||
callback: Callable[[WebRequest], Coroutine]
|
||||
) -> RPCCallback:
|
||||
async def func(ws: WebSocket, **kwargs) -> Any:
|
||||
result = await callback(
|
||||
WebRequest(endpoint, kwargs, request_method, ws))
|
||||
WebRequest(endpoint, kwargs, request_method, ws,
|
||||
ip_addr=ws.ip_addr, user=ws.current_user))
|
||||
return result
|
||||
return func
|
||||
|
||||
async def _handle_id_request(self, ws, **kwargs):
|
||||
async def _handle_id_request(self,
|
||||
ws: WebSocket,
|
||||
**kwargs
|
||||
) -> Dict[str, int]:
|
||||
return {'websocket_id': ws.uid}
|
||||
|
||||
def has_websocket(self, ws_id):
|
||||
def has_websocket(self, ws_id: int) -> bool:
|
||||
return ws_id in self.websockets
|
||||
|
||||
def get_websocket(self, ws_id):
|
||||
def get_websocket(self, ws_id: int) -> Optional[WebSocket]:
|
||||
return self.websockets.get(ws_id, None)
|
||||
|
||||
async def add_websocket(self, ws):
|
||||
async with self.ws_lock:
|
||||
self.websockets[ws.uid] = ws
|
||||
logging.info(f"New Websocket Added: {ws.uid}")
|
||||
def add_websocket(self, ws: WebSocket) -> None:
|
||||
self.websockets[ws.uid] = ws
|
||||
logging.info(f"New Websocket Added: {ws.uid}")
|
||||
|
||||
async def remove_websocket(self, ws):
|
||||
async with self.ws_lock:
|
||||
old_ws = self.websockets.pop(ws.uid, None)
|
||||
if old_ws is not None:
|
||||
self.server.remove_subscription(old_ws)
|
||||
logging.info(f"Websocket Removed: {ws.uid}")
|
||||
def remove_websocket(self, ws: WebSocket) -> None:
|
||||
old_ws = self.websockets.pop(ws.uid, None)
|
||||
if old_ws is not None:
|
||||
self.server.remove_subscription(old_ws)
|
||||
logging.info(f"Websocket Removed: {ws.uid}")
|
||||
if self.closed_event is not None and not self.websockets:
|
||||
self.closed_event.set()
|
||||
|
||||
async def notify_websockets(self, name, data=Sentinel):
|
||||
msg = {'jsonrpc': "2.0", 'method': "notify_" + name}
|
||||
if data != Sentinel:
|
||||
def notify_websockets(self,
|
||||
name: str,
|
||||
data: Any = SENTINEL
|
||||
) -> None:
|
||||
msg: Dict[str, Any] = {'jsonrpc': "2.0", 'method': "notify_" + name}
|
||||
if data != SENTINEL:
|
||||
msg['params'] = [data]
|
||||
async with self.ws_lock:
|
||||
for ws in list(self.websockets.values()):
|
||||
try:
|
||||
ws.write_message(msg)
|
||||
except WebSocketClosedError:
|
||||
self.websockets.pop(ws.uid, None)
|
||||
logging.info(f"Websocket Removed: {ws.uid}")
|
||||
except Exception:
|
||||
logging.exception(
|
||||
f"Error sending data over websocket: {ws.uid}")
|
||||
for ws in list(self.websockets.values()):
|
||||
ws.queue_message(msg)
|
||||
|
||||
async def close(self):
|
||||
async with self.ws_lock:
|
||||
for ws in self.websockets.values():
|
||||
ws.close()
|
||||
self.websockets = {}
|
||||
async def close(self) -> None:
|
||||
if not self.websockets:
|
||||
return
|
||||
self.closed_event = Event()
|
||||
for ws in list(self.websockets.values()):
|
||||
ws.close()
|
||||
try:
|
||||
await self.closed_event.wait(IOLoop.current().time() + 2.)
|
||||
except tornado.util.TimeoutError:
|
||||
pass
|
||||
self.closed_event = None
|
||||
|
||||
class WebSocket(WebSocketHandler):
|
||||
def initialize(self):
|
||||
app = self.settings['parent']
|
||||
self.auth = app.get_auth()
|
||||
class WebSocket(WebSocketHandler, Subscribable):
|
||||
def initialize(self) -> None:
|
||||
app: MoonrakerApp = self.settings['parent']
|
||||
self.server = app.get_server()
|
||||
self.wsm = app.get_websocket_manager()
|
||||
self.rpc = self.wsm.rpc
|
||||
self.uid = id(self)
|
||||
self.is_closed: bool = False
|
||||
self.ip_addr: str = self.request.remote_ip
|
||||
self.queue_busy: bool = False
|
||||
self.message_buf: List[Union[str, Dict[str, Any]]] = []
|
||||
|
||||
async def open(self):
|
||||
await self.wsm.add_websocket(self)
|
||||
def open(self, *args, **kwargs) -> None:
|
||||
self.set_nodelay(True)
|
||||
self.wsm.add_websocket(self)
|
||||
|
||||
def on_message(self, message):
|
||||
def on_message(self, message: Union[bytes, str]) -> None:
|
||||
io_loop = IOLoop.current()
|
||||
io_loop.spawn_callback(self._process_message, message)
|
||||
|
||||
async def _process_message(self, message):
|
||||
async def _process_message(self, message: str) -> None:
|
||||
try:
|
||||
response = await self.rpc.dispatch(message, self)
|
||||
if response is not None:
|
||||
self.write_message(response)
|
||||
self.queue_message(response)
|
||||
except Exception:
|
||||
logging.exception("Websocket Command Error")
|
||||
|
||||
def send_status(self, status):
|
||||
def queue_message(self, message: Union[str, Dict[str, Any]]):
|
||||
self.message_buf.append(message)
|
||||
if self.queue_busy:
|
||||
return
|
||||
self.queue_busy = True
|
||||
IOLoop.current().spawn_callback(self._process_messages)
|
||||
|
||||
async def _process_messages(self):
|
||||
if self.is_closed:
|
||||
self.message_buf = []
|
||||
self.queue_busy = False
|
||||
return
|
||||
while self.message_buf:
|
||||
msg = self.message_buf.pop(0)
|
||||
try:
|
||||
await self.write_message(msg)
|
||||
except WebSocketClosedError:
|
||||
self.is_closed = True
|
||||
logging.info(
|
||||
f"Websocket closed while writing: {self.uid}")
|
||||
break
|
||||
except Exception:
|
||||
logging.exception(
|
||||
f"Error sending data over websocket: {self.uid}")
|
||||
self.queue_busy = False
|
||||
|
||||
def send_status(self,
|
||||
status: Dict[str, Any],
|
||||
eventtime: float
|
||||
) -> None:
|
||||
if not status:
|
||||
return
|
||||
try:
|
||||
self.write_message({
|
||||
'jsonrpc': "2.0",
|
||||
'method': "notify_status_update",
|
||||
'params': [status]})
|
||||
except WebSocketClosedError:
|
||||
logging.info(
|
||||
f"Websocket Closed During Status Update: {self.uid}")
|
||||
except Exception:
|
||||
logging.exception(
|
||||
f"Error sending data over websocket: {self.uid}")
|
||||
self.queue_message({
|
||||
'jsonrpc': "2.0",
|
||||
'method': "notify_status_update",
|
||||
'params': [status, eventtime]})
|
||||
|
||||
def on_close(self):
|
||||
io_loop = IOLoop.current()
|
||||
io_loop.spawn_callback(self.wsm.remove_websocket, self)
|
||||
def on_close(self) -> None:
|
||||
self.is_closed = True
|
||||
self.message_buf = []
|
||||
self.wsm.remove_websocket(self)
|
||||
|
||||
def check_origin(self, origin):
|
||||
def check_origin(self, origin: str) -> bool:
|
||||
if not super(WebSocket, self).check_origin(origin):
|
||||
return self.auth.check_cors(origin)
|
||||
auth: AuthComp = self.server.lookup_component('authorization', None)
|
||||
if auth is not None:
|
||||
return auth.check_cors(origin)
|
||||
return False
|
||||
return True
|
||||
|
||||
# Check Authorized User
|
||||
def prepare(self):
|
||||
if not self.auth.check_authorized(self.request):
|
||||
raise tornado.web.HTTPError(401, "Unauthorized")
|
||||
auth: AuthComp = self.server.lookup_component('authorization', None)
|
||||
if auth is not None:
|
||||
self.current_user = auth.check_authorized(self.request)
|
||||
Executable
+64
@@ -0,0 +1,64 @@
|
||||
#!/bin/bash
|
||||
# This script builds a zipped source release for Moonraker and Klipper.
|
||||
|
||||
install_packages()
|
||||
{
|
||||
PKGLIST="python3-dev curl"
|
||||
|
||||
# Update system package info
|
||||
report_status "Running apt-get update..."
|
||||
sudo apt-get update
|
||||
|
||||
# Install desired packages
|
||||
report_status "Installing packages..."
|
||||
sudo apt-get install --yes $PKGLIST
|
||||
}
|
||||
|
||||
report_status()
|
||||
{
|
||||
echo -e "\n\n###### $1"
|
||||
}
|
||||
|
||||
verify_ready()
|
||||
{
|
||||
if [ "$EUID" -eq 0 ]; then
|
||||
echo "This script must not run as root"
|
||||
exit -1
|
||||
fi
|
||||
|
||||
if [ ! -d "$SRCDIR/.git" ]; then
|
||||
echo "This script must be run from a git repo"
|
||||
exit -1
|
||||
fi
|
||||
|
||||
if [ ! -d "$KLIPPER_DIR/.git" ]; then
|
||||
echo "This script must be run from a git repo"
|
||||
exit -1
|
||||
fi
|
||||
}
|
||||
|
||||
# Force script to exit if an error occurs
|
||||
set -e
|
||||
|
||||
SRCDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )"/.. && pwd )"
|
||||
OUTPUT_DIR="$SRCDIR/.dist"
|
||||
KLIPPER_DIR="$HOME/klipper"
|
||||
BETA=""
|
||||
|
||||
# Parse command line arguments
|
||||
while getopts "o:k:b" arg; do
|
||||
case $arg in
|
||||
o) OUTPUT_DIR=$OPTARG;;
|
||||
k) KLIPPER_DIR=$OPTARG;;
|
||||
b) BETA="-b";;
|
||||
esac
|
||||
done
|
||||
|
||||
[ ! -d $OUTPUT_DIR ] && mkdir $OUTPUT_DIR
|
||||
verify_ready
|
||||
if [ "$BETA" = "" ]; then
|
||||
releaseTag=$( git -C $KLIPPER_DIR describe --tags `git -C $KLIPPER_DIR rev-list --tags --max-count=1` )
|
||||
echo "Checking out Klipper release $releaseTag"
|
||||
git -C $KLIPPER_DIR checkout $releaseTag
|
||||
fi
|
||||
python3 "$SRCDIR/scripts/build_release.py" -k $KLIPPER_DIR -o $OUTPUT_DIR $BETA
|
||||
@@ -0,0 +1,338 @@
|
||||
#!/usr/bin/python3
|
||||
# Builds zip release files for Moonraker and Klipper
|
||||
|
||||
import os
|
||||
import sys
|
||||
import argparse
|
||||
import shutil
|
||||
import tempfile
|
||||
import json
|
||||
import pathlib
|
||||
import time
|
||||
import traceback
|
||||
import subprocess
|
||||
import re
|
||||
from typing import Dict, Any, List, Set, Optional
|
||||
|
||||
MOONRAKER_PATH = os.path.abspath(
|
||||
os.path.join(os.path.dirname(__file__), ".."))
|
||||
sys.path.append(os.path.join(MOONRAKER_PATH, "moonraker"))
|
||||
from utils import hash_directory, retreive_git_version # noqa:E402
|
||||
|
||||
# Dirs and exts to ignore when calculating the repo hash
|
||||
IGNORE_DIRS = ["out", "lib", "test", "docs", "__pycache__"]
|
||||
IGNORE_EXTS = [".o", ".so", ".pyc", ".pyo", ".pyd", ".yml", ".yaml"]
|
||||
|
||||
# Files not to include in the source package
|
||||
SKIP_FILES = [".gitignore", ".gitattributes", ".readthedocs.yaml",
|
||||
"mkdocs.yml", "__pycache__"]
|
||||
|
||||
RELEASE_URL = "https://api.github.com/repos/Arksine/moonraker/releases"
|
||||
GIT_MAX_LOG_CNT = 100
|
||||
GIT_LOG_FMT = \
|
||||
"sha:%H%x1Dauthor:%an%x1Ddate:%ct%x1Dsubject:%s%x1Dmessage:%b%x1E"
|
||||
OWNER_REPOS = {
|
||||
'moonraker': "arksine/moonraker",
|
||||
'klippy': "kevinoconnor/klipper"
|
||||
}
|
||||
INSTALL_SCRIPTS = {
|
||||
'klippy': {
|
||||
'debian': "install-octopi.sh",
|
||||
'arch': "install-arch.sh",
|
||||
'centos': "install-centos.sh"
|
||||
},
|
||||
'moonraker': {
|
||||
'debian': "install-moonraker.sh"
|
||||
}
|
||||
}
|
||||
|
||||
class CopyIgnore:
|
||||
def __init__(self, root_dir: str) -> None:
|
||||
self.root_dir = root_dir
|
||||
|
||||
def __call__(self, dir_path: str, dir_items: List[str]) -> List[str]:
|
||||
ignored: List[str] = []
|
||||
for item in dir_items:
|
||||
if item in SKIP_FILES:
|
||||
ignored.append(item)
|
||||
elif dir_path == self.root_dir:
|
||||
full_path = os.path.join(dir_path, item)
|
||||
# Ignore all hidden directories in the root
|
||||
if os.path.isdir(full_path) and item[0] == ".":
|
||||
ignored.append(item)
|
||||
return ignored
|
||||
|
||||
def search_install_script(data: str,
|
||||
regex: str,
|
||||
exclude: str
|
||||
) -> List[str]:
|
||||
items: Set[str] = set()
|
||||
lines: List[str] = re.findall(regex, data)
|
||||
for line in lines:
|
||||
items.update(line.strip().split())
|
||||
try:
|
||||
items.remove(exclude)
|
||||
except KeyError:
|
||||
pass
|
||||
return list(items)
|
||||
|
||||
def generate_dependency_info(repo_path: str, app_name: str) -> None:
|
||||
inst_scripts = INSTALL_SCRIPTS[app_name]
|
||||
package_info: Dict[str, Any] = {}
|
||||
for distro, script_name in inst_scripts.items():
|
||||
script_path = os.path.join(repo_path, "scripts", script_name)
|
||||
script = pathlib.Path(script_path)
|
||||
if not script.exists():
|
||||
continue
|
||||
data = script.read_text()
|
||||
packages: List[str] = search_install_script(
|
||||
data, r'PKGLIST="(.*)"', "${PKGLIST}")
|
||||
package_info[distro] = {'packages': sorted(packages)}
|
||||
if distro == "arch":
|
||||
aur_packages: List[str] = search_install_script(
|
||||
data, r'AURLIST="(.*)"', "${AURLIST}")
|
||||
package_info[distro]['aur_packages'] = sorted(aur_packages)
|
||||
req_file_name = os.path.join(repo_path, "scripts",
|
||||
f"{app_name}-requirements.txt")
|
||||
req_file = pathlib.Path(req_file_name)
|
||||
python_reqs: List[str] = []
|
||||
if req_file.exists():
|
||||
req_data = req_file.read_text()
|
||||
lines = [line.strip() for line in req_data.split('\n')
|
||||
if line.strip()]
|
||||
for line in lines:
|
||||
comment_idx = line.find('#')
|
||||
if comment_idx == 0:
|
||||
continue
|
||||
if comment_idx > 0:
|
||||
line = line[:comment_idx].strip()
|
||||
python_reqs.append(line)
|
||||
package_info['python'] = sorted(python_reqs)
|
||||
dep_file = pathlib.Path(os.path.join(repo_path, ".dependencies"))
|
||||
dep_file.write_text(json.dumps(package_info))
|
||||
|
||||
def clean_repo(path: str) -> None:
|
||||
# Obtain version info from "git" program
|
||||
prog = ('git', '-C', path, 'clean', '-x', '-f', '-d')
|
||||
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, cwd=path)
|
||||
retcode = process.wait()
|
||||
if retcode != 0:
|
||||
print(f"Error running git clean: {path}")
|
||||
|
||||
def get_releases() -> List[Dict[str, Any]]:
|
||||
print("Fetching Release List...")
|
||||
prog = ('curl', '-H', "Accept: application/vnd.github.v3+json",
|
||||
RELEASE_URL)
|
||||
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE)
|
||||
response, err = process.communicate()
|
||||
retcode = process.wait()
|
||||
if retcode != 0:
|
||||
print(f"Release list request returned with code {retcode},"
|
||||
f" response:\n{err.decode()}")
|
||||
return []
|
||||
releases = json.loads(response.decode().strip())
|
||||
print(f"Found {len(releases)} releases")
|
||||
return releases
|
||||
|
||||
def get_last_release_info(moonraker_version: str,
|
||||
is_beta: bool,
|
||||
releases: List[Dict[str, Any]]
|
||||
) -> Dict[str, Any]:
|
||||
print("Searching for previous release assets...")
|
||||
cur_tag, commit_count = moonraker_version.split('-', 2)[:2]
|
||||
release_assets = []
|
||||
matched_tag: Optional[str] = None
|
||||
for release in releases:
|
||||
if int(commit_count) != 0:
|
||||
# This is build is not being done against a fresh release,
|
||||
# return release info from a matching tag
|
||||
if release['tag_name'] == cur_tag:
|
||||
release_assets = release['assets']
|
||||
matched_tag = cur_tag
|
||||
break
|
||||
else:
|
||||
# Get the most recent non-matching tag
|
||||
if release['tag_name'] == cur_tag:
|
||||
continue
|
||||
if is_beta or not release['prerelease']:
|
||||
# Get the last tagged release. If we are building a beta,
|
||||
# that is the most recent release. Otherwise we should
|
||||
# omit pre-releases
|
||||
release_assets = release['assets']
|
||||
matched_tag = release['tag_name']
|
||||
break
|
||||
if matched_tag is None:
|
||||
print("No matching release found")
|
||||
matched_tag = "No Tag"
|
||||
else:
|
||||
print(f"Found release: {matched_tag}")
|
||||
|
||||
asset_url: Optional[str] = None
|
||||
content_type: str = ""
|
||||
for asset in release_assets:
|
||||
if asset['name'] == "RELEASE_INFO":
|
||||
asset_url = asset['browser_download_url']
|
||||
content_type = asset['content_type']
|
||||
break
|
||||
if asset_url is None:
|
||||
print(f"RELEASE_INFO asset not found in release: {matched_tag}")
|
||||
return {}
|
||||
# This build is prior to a tagged release, so fetch the current tag
|
||||
print(f"Release Info Download URL: {asset_url}")
|
||||
prog = ('curl', '-L', '-H', f"Accept: {content_type}", asset_url)
|
||||
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE)
|
||||
response, err = process.communicate()
|
||||
retcode = process.wait()
|
||||
if retcode != 0:
|
||||
print("Request for release info failed")
|
||||
return {}
|
||||
resp = response.decode().strip()
|
||||
print(f"Found Info for release {matched_tag}")
|
||||
return json.loads(resp)
|
||||
|
||||
def get_commit_log(path: str,
|
||||
release_info: Dict[str, Any]
|
||||
) -> List[Dict[str, Any]]:
|
||||
print(f"Preparing commit log for {path.split('/')[-1]}")
|
||||
start_sha = release_info.get('commit_hash', None)
|
||||
prog = ['git', '-C', path, 'log', f'--format={GIT_LOG_FMT}',
|
||||
f'--max-count={GIT_MAX_LOG_CNT}']
|
||||
if start_sha is not None:
|
||||
prog = ['git', '-C', path, 'log', f'{start_sha}..HEAD',
|
||||
f'--format={GIT_LOG_FMT}', f'--max-count={GIT_MAX_LOG_CNT}']
|
||||
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, cwd=path)
|
||||
response, err = process.communicate()
|
||||
retcode = process.wait()
|
||||
if retcode != 0:
|
||||
return []
|
||||
resp = response.decode().strip()
|
||||
commit_log: List[Dict[str, Any]] = []
|
||||
for log_entry in resp.split('\x1E'):
|
||||
log_entry = log_entry.strip()
|
||||
if not log_entry:
|
||||
continue
|
||||
log_items = [li.strip() for li in log_entry.split('\x1D')
|
||||
if li.strip()]
|
||||
cbh = [li.split(':', 1) for li in log_items]
|
||||
commit_log.append(dict(cbh)) # type: ignore
|
||||
print(f"Found {len(commit_log)} commits")
|
||||
return commit_log
|
||||
|
||||
def get_commit_hash(path: str) -> str:
|
||||
prog = ('git', '-C', path, 'rev-parse', 'HEAD')
|
||||
process = subprocess.Popen(prog, stdout=subprocess.PIPE,
|
||||
stderr=subprocess.PIPE, cwd=path)
|
||||
commit_hash, err = process.communicate()
|
||||
retcode = process.wait()
|
||||
if retcode == 0:
|
||||
return commit_hash.strip().decode()
|
||||
raise Exception(f"Failed to get commit hash: {commit_hash.decode()}")
|
||||
|
||||
def generate_version_info(path: str,
|
||||
source_dir: str,
|
||||
channel: str,
|
||||
release_tag: Optional[str] = None
|
||||
) -> Dict[str, Any]:
|
||||
print(f"Generating version info: {source_dir}")
|
||||
clean_repo(path)
|
||||
owner_repo = OWNER_REPOS[source_dir]
|
||||
curtime = int(time.time())
|
||||
date_str = time.strftime("%Y%m%d", time.gmtime(curtime))
|
||||
version = retreive_git_version(path)
|
||||
if release_tag is None:
|
||||
release_tag = version.split('-')[0]
|
||||
source_hash = hash_directory(path, IGNORE_EXTS, IGNORE_DIRS)
|
||||
long_version = f"{version}-moonraker-{date_str}"
|
||||
release_info = {
|
||||
'git_version': version,
|
||||
'long_version': long_version,
|
||||
'commit_hash': get_commit_hash(path),
|
||||
'source_checksum': source_hash,
|
||||
'ignored_exts': IGNORE_EXTS,
|
||||
'ignored_dirs': IGNORE_DIRS,
|
||||
'build_date': curtime,
|
||||
'channel': channel,
|
||||
'owner_repo': owner_repo,
|
||||
'host_repo': OWNER_REPOS['moonraker'],
|
||||
'release_tag': release_tag
|
||||
}
|
||||
vfile = pathlib.Path(os.path.join(path, source_dir, ".version"))
|
||||
vfile.write_text(long_version)
|
||||
rfile = pathlib.Path(os.path.join(path, ".release_info"))
|
||||
rfile.write_text(json.dumps(release_info))
|
||||
generate_dependency_info(path, source_dir)
|
||||
return release_info
|
||||
|
||||
def create_zip(repo_path: str,
|
||||
repo_name: str,
|
||||
output_path: str
|
||||
) -> None:
|
||||
print(f"Creating Zip Release: {repo_name}")
|
||||
zip_path = os.path.join(output_path, repo_name)
|
||||
with tempfile.TemporaryDirectory() as tmp_dir:
|
||||
dest_path = os.path.join(tmp_dir, repo_name)
|
||||
ingore_cb = CopyIgnore(repo_path)
|
||||
shutil.copytree(repo_path, dest_path, ignore=ingore_cb)
|
||||
shutil.make_archive(zip_path, "zip", root_dir=dest_path)
|
||||
|
||||
def main() -> None:
|
||||
# Parse start arguments
|
||||
parser = argparse.ArgumentParser(
|
||||
description="Generates zip releases for Moonraker and Klipper")
|
||||
parser.add_argument(
|
||||
"-k", "--klipper", default="~/klipper",
|
||||
metavar='<klipper_path>',
|
||||
help="Path to Klipper git repo")
|
||||
parser.add_argument(
|
||||
"-o", "--output", default=os.path.join(MOONRAKER_PATH, ".dist"),
|
||||
metavar='<output_path>', help="Path to output directory")
|
||||
parser.add_argument(
|
||||
"-b", "--beta", action='store_true',
|
||||
help="Tag release as beta")
|
||||
args = parser.parse_args()
|
||||
kpath: str = os.path.abspath(os.path.expanduser(args.klipper))
|
||||
opath: str = os.path.abspath(os.path.expanduser(args.output))
|
||||
is_beta: bool = args.beta
|
||||
channel = "beta" if is_beta else "stable"
|
||||
if not os.path.exists(kpath):
|
||||
print(f"Invalid path to Klipper: {kpath}")
|
||||
sys.exit(-1)
|
||||
if not os.path.exists(opath):
|
||||
print(f"Invalid output path: {opath}")
|
||||
sys.exit(-1)
|
||||
releases = get_releases()
|
||||
all_info: Dict[str, Dict[str, Any]] = {}
|
||||
try:
|
||||
print("Generating Moonraker Zip Distribution...")
|
||||
all_info['moonraker'] = generate_version_info(
|
||||
MOONRAKER_PATH, "moonraker", channel)
|
||||
create_zip(MOONRAKER_PATH, 'moonraker', opath)
|
||||
rtag: str = all_info['moonraker']['release_tag']
|
||||
print("Generating Klipper Zip Distribution...")
|
||||
all_info['klipper'] = generate_version_info(
|
||||
kpath, "klippy", channel, rtag)
|
||||
create_zip(kpath, 'klipper', opath)
|
||||
info_file = pathlib.Path(os.path.join(opath, "RELEASE_INFO"))
|
||||
info_file.write_text(json.dumps(all_info))
|
||||
last_rinfo = get_last_release_info(
|
||||
all_info['moonraker']['git_version'], is_beta, releases)
|
||||
commit_log = {}
|
||||
commit_log['moonraker'] = get_commit_log(
|
||||
MOONRAKER_PATH, last_rinfo.get('moonraker', {}))
|
||||
commit_log['klipper'] = get_commit_log(
|
||||
kpath, last_rinfo.get('klipper', {}))
|
||||
clog_file = pathlib.Path(os.path.join(opath, "COMMIT_LOG"))
|
||||
clog_file.write_text(json.dumps(commit_log))
|
||||
except Exception:
|
||||
print("Error Creating Zip Distribution")
|
||||
traceback.print_exc(file=sys.stdout)
|
||||
sys.exit(-1)
|
||||
print(f"Build Complete. Files are located at '{opath}'")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Executable
+42
@@ -0,0 +1,42 @@
|
||||
#!/bin/bash
|
||||
# Helper Script for fetching the API Key from a moonraker database
|
||||
DATABASE_PATH="${HOME}/.moonraker_database"
|
||||
MOONRAKER_ENV="${HOME}/moonraker-env"
|
||||
DB_ARGS="--read=READ --db=authorized_users get _API_KEY_USER_"
|
||||
API_REGEX='(?<="api_key": ")([^"]+)'
|
||||
|
||||
print_help()
|
||||
{
|
||||
echo "Moonraker API Key Extraction Utility"
|
||||
echo
|
||||
echo "usage: fetch-apikey.sh [-h] [-e <python env path>] [-d <database path>]"
|
||||
echo
|
||||
echo "optional arguments:"
|
||||
echo " -h show this message"
|
||||
echo " -e <env path> path to Moonraker env folder"
|
||||
echo " -d <database path> path to Moonraker LMDB database folder"
|
||||
exit 0
|
||||
}
|
||||
|
||||
# Parse command line arguments
|
||||
while getopts "he:d:" arg; do
|
||||
case $arg in
|
||||
h) print_help;;
|
||||
e) MOONRAKER_ENV=$OPTARG;;
|
||||
d) DATABASE_PATH=$OPTARG;;
|
||||
esac
|
||||
done
|
||||
|
||||
PYTHON_BIN="${MOONRAKER_ENV}/bin/python"
|
||||
|
||||
if [ ! -f $PYTHON_BIN ]; then
|
||||
echo "No Python binary found at '${PYTHON_BIN}'"
|
||||
exit -1
|
||||
fi
|
||||
|
||||
if [ ! -d $DATABASE_PATH ]; then
|
||||
echo "No Moonraker database found at '${DATABASE_PATH}'"
|
||||
exit -1
|
||||
fi
|
||||
|
||||
${PYTHON_BIN} -mlmdb --env=${DATABASE_PATH} ${DB_ARGS} | grep -Po "${API_REGEX}"
|
||||
@@ -7,11 +7,12 @@ SYSTEMDDIR="/etc/systemd/system"
|
||||
REBUILD_ENV="n"
|
||||
FORCE_DEFAULTS="n"
|
||||
CONFIG_PATH="${HOME}/moonraker.conf"
|
||||
LOG_PATH="/tmp/moonraker.log"
|
||||
|
||||
# Step 1: Verify Klipper has been installed
|
||||
check_klipper()
|
||||
{
|
||||
if [ "$(systemctl list-units --full -all -t service --no-legend | grep -F "klipper.service")" ]; then
|
||||
if [ "$(sudo systemctl list-units --full -all -t service --no-legend | grep -F "klipper.service")" ]; then
|
||||
echo "Klipper service found!"
|
||||
else
|
||||
echo "Klipper service not found, please install Klipper first"
|
||||
@@ -36,6 +37,7 @@ cleanup_legacy() {
|
||||
install_packages()
|
||||
{
|
||||
PKGLIST="python3-virtualenv python3-dev nginx libopenjp2-7 python3-libgpiod"
|
||||
PKGLIST="${PKGLIST} liblmdb0 libsodium-dev zlib1g-dev"
|
||||
|
||||
# Update system package info
|
||||
report_status "Running apt-get update..."
|
||||
@@ -59,7 +61,6 @@ create_virtualenv()
|
||||
|
||||
if [ ! -d ${PYTHONDIR} ]; then
|
||||
virtualenv -p /usr/bin/python3 ${PYTHONDIR}
|
||||
ln -s /usr/lib/python3/dist-packages/gpiod* ${PYTHONDIR}/lib/python*/site-packages
|
||||
fi
|
||||
|
||||
# Install/update dependencies
|
||||
@@ -76,7 +77,7 @@ install_script()
|
||||
sudo /bin/sh -c "cat > ${SERVICE_FILE}" << EOF
|
||||
#Systemd service file for moonraker
|
||||
[Unit]
|
||||
Description=Starts Moonraker on startup
|
||||
Description=API Server for Klipper
|
||||
After=network.target
|
||||
|
||||
[Install]
|
||||
@@ -86,12 +87,14 @@ WantedBy=multi-user.target
|
||||
Type=simple
|
||||
User=$USER
|
||||
RemainAfterExit=yes
|
||||
ExecStart=${PYTHONDIR}/bin/python ${SRCDIR}/moonraker/moonraker.py -c ${CONFIG_PATH}
|
||||
WorkingDirectory=${SRCDIR}
|
||||
ExecStart=${LAUNCH_CMD} -c ${CONFIG_PATH} -l ${LOG_PATH}
|
||||
Restart=always
|
||||
RestartSec=10
|
||||
EOF
|
||||
# Use systemctl to enable the klipper systemd service script
|
||||
sudo systemctl enable moonraker.service
|
||||
sudo systemctl daemon-reload
|
||||
}
|
||||
|
||||
|
||||
@@ -123,13 +126,15 @@ set -e
|
||||
|
||||
# Find SRCDIR from the pathname of this script
|
||||
SRCDIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )"/.. && pwd )"
|
||||
LAUNCH_CMD="${PYTHONDIR}/bin/python ${SRCDIR}/moonraker/moonraker.py"
|
||||
|
||||
# Parse command line arguments
|
||||
while getopts "rfc:" arg; do
|
||||
while getopts "rfc:l:" arg; do
|
||||
case $arg in
|
||||
r) REBUILD_ENV="y";;
|
||||
f) FORCE_DEFAULTS="y";;
|
||||
c) CONFIG_PATH=$OPTARG;;
|
||||
l) LOG_PATH=$OPTARG;;
|
||||
esac
|
||||
done
|
||||
|
||||
|
||||
@@ -1,4 +1,10 @@
|
||||
# Python dependencies for Moonraker
|
||||
tornado==6.1.0
|
||||
pyserial==3.4
|
||||
pillow==8.0.1
|
||||
pillow==8.2.0
|
||||
lmdb==1.2.1
|
||||
streaming-form-data==1.8.1
|
||||
distro==1.5.0
|
||||
inotify-simple==1.3.5
|
||||
libnacl==1.7.2
|
||||
paho-mqtt==1.5.1
|
||||
@@ -1,55 +0,0 @@
|
||||
#!/bin/sh
|
||||
# System startup script for Moonraker, Klipper's API Server
|
||||
|
||||
### BEGIN INIT INFO
|
||||
# Provides: moonraker
|
||||
# Required-Start: $local_fs
|
||||
# Required-Stop:
|
||||
# X-Start-Before: $klipper
|
||||
# Default-Start: 2 3 4 5
|
||||
# Default-Stop: 0 1 6
|
||||
# Short-Description: moonraker daemon
|
||||
# Description: Starts the Moonraker daemon
|
||||
### END INIT INFO
|
||||
|
||||
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
|
||||
DESC="moonraker daemon"
|
||||
NAME="moonraker"
|
||||
DEFAULTS_FILE=/etc/default/moonraker
|
||||
PIDFILE=/var/run/moonraker.pid
|
||||
|
||||
. /lib/lsb/init-functions
|
||||
|
||||
# Read defaults file
|
||||
[ -r $DEFAULTS_FILE ] && . $DEFAULTS_FILE
|
||||
|
||||
case "$1" in
|
||||
start) log_daemon_msg "Starting moonraker" $NAME
|
||||
start-stop-daemon --start --quiet --exec $MOONRAKER_EXEC \
|
||||
--background --pidfile $PIDFILE --make-pidfile \
|
||||
--chuid $MOONRAKER_USER --user $MOONRAKER_USER \
|
||||
-- $MOONRAKER_ARGS
|
||||
log_end_msg $?
|
||||
;;
|
||||
stop) log_daemon_msg "Stopping moonraker" $NAME
|
||||
killproc -p $PIDFILE $MOONRAKER_EXEC
|
||||
RETVAL=$?
|
||||
[ $RETVAL -eq 0 ] && [ -e "$PIDFILE" ] && rm -f $PIDFILE
|
||||
log_end_msg $RETVAL
|
||||
;;
|
||||
restart) log_daemon_msg "Restarting moonraker" $NAME
|
||||
$0 stop
|
||||
$0 start
|
||||
;;
|
||||
reload|force-reload)
|
||||
log_daemon_msg "Reloading configuration not supported" $NAME
|
||||
log_end_msg 1
|
||||
;;
|
||||
status)
|
||||
status_of_proc -p $PIDFILE $MOONRAKER_EXEC $NAME && exit 0 || exit $?
|
||||
;;
|
||||
*) log_action_msg "Usage: /etc/init.d/moonraker {start|stop|status|restart|reload|force-reload}"
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
exit 0
|
||||
@@ -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
|
||||
@@ -1,2 +0,0 @@
|
||||
env_version=0.2.5
|
||||
deps_version=0.2.2
|
||||
@@ -0,0 +1,128 @@
|
||||
#lean_overlay {
|
||||
position: fixed;
|
||||
z-index:100;
|
||||
top: 0px;
|
||||
left: 0px;
|
||||
height:100%;
|
||||
width:100%;
|
||||
background: #000;
|
||||
display: none;
|
||||
}
|
||||
|
||||
.user {
|
||||
width: 404px;
|
||||
padding-bottom: 2px;
|
||||
display:none;
|
||||
background: #FFF;
|
||||
border-radius: 5px;
|
||||
-moz-border-radius: 5px;
|
||||
-webkit-border-radius: 5px;
|
||||
box-shadow: 0px 0px 4px rgba(0,0,0,0.7);
|
||||
-webkit-box-shadow: 0 0 4px rgba(0,0,0,0.7);
|
||||
-moz-box-shadow: 0 0px 4px rgba(0,0,0,0.7);
|
||||
}
|
||||
|
||||
.user-header {
|
||||
/*background: url(../img/hd-bg.png);*/
|
||||
background: #cecece;
|
||||
padding: 8px 8px 8px 8px;
|
||||
border-bottom: 1px solid #CCC;
|
||||
border-top-left-radius: 5px;
|
||||
-moz-border-radius-topleft: 5px;
|
||||
-webkit-border-top-left-radius: 5px;
|
||||
border-top-right-radius: 5px;
|
||||
-moz-border-radius-topright: 5px;
|
||||
-webkit-border-top-right-radius: 5px;
|
||||
}
|
||||
|
||||
.user-header h2 {
|
||||
color: #444;
|
||||
font-size: 1.2em;
|
||||
font-weight: 700;
|
||||
margin-bottom: 3px;
|
||||
text-shadow: 1px 1px 0 rgba(255, 255, 255, 0.5);
|
||||
}
|
||||
|
||||
.user-header p {
|
||||
color: #444;
|
||||
font-size: 1em;
|
||||
margin: 0;
|
||||
text-shadow: 1px 1px 0 rgba(255, 255, 255, 0.5);
|
||||
text-shadow: none;
|
||||
}
|
||||
|
||||
.user .text-field {
|
||||
position: relative;
|
||||
width: 364px;
|
||||
padding: 14px 20px;
|
||||
border-bottom: 1px solid #EEE;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.user .button-field {
|
||||
width: 254px;
|
||||
overflow: hidden;
|
||||
padding: 12px 20px 12px 130px;
|
||||
}
|
||||
|
||||
.user .text-field label {
|
||||
display: block;
|
||||
float: left;
|
||||
width: 90px;
|
||||
padding-top: 8px;
|
||||
color: #222;
|
||||
font-size: 1em;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.user .text-field input {
|
||||
width: 244px;
|
||||
padding: 8px;
|
||||
border-radius: 4px;
|
||||
-moz-border-radius: 4px;
|
||||
-webkit-border-radius: 4px;
|
||||
font-size: 1em; color: #222;
|
||||
background: #F7F7F7;
|
||||
font-family: "Helvetica Neue";
|
||||
outline: none;
|
||||
border-top: 1px solid #CCC;
|
||||
border-left: 1px solid #CCC;
|
||||
border-right: 1px solid #E7E6E6;
|
||||
border-bottom: 1px solid #E7E6E6;
|
||||
}
|
||||
|
||||
/*.user .text-field input.good_input {
|
||||
background: #DEF5E1 url(../img/good.png) 236px center no-repeat;
|
||||
}*/
|
||||
|
||||
.user .text-field input.error_input {
|
||||
background: #FDE0E0;
|
||||
}
|
||||
|
||||
.user-button {
|
||||
float: right;
|
||||
font-family: "Helvetica Neue", "Helvetica", "Arial", sans-serif;
|
||||
background: #cecece;
|
||||
border: none;
|
||||
width: auto;
|
||||
overflow: visible;
|
||||
font-size: 1.1em;
|
||||
color: rgb(0, 0, 0);
|
||||
padding: 7px 10px;
|
||||
border-radius: 4px;
|
||||
-webkit-border-radius: 4px;
|
||||
-moz-border-radius: 4px;
|
||||
text-shadow: 0 1px 0 rgba(0,0,0,0.4);
|
||||
}
|
||||
|
||||
.modal_close {
|
||||
position: absolute;
|
||||
top: 12px;
|
||||
right: 12px;
|
||||
display: inline-block;
|
||||
border: none;
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
background: url(../img/close-button.png);
|
||||
z-index: 2;
|
||||
}
|
||||
+5
@@ -0,0 +1,5 @@
|
||||
// leanModal v1.1 by Ray Stone - http://finelysliced.com.au
|
||||
// Dual licensed under the MIT and GPL
|
||||
|
||||
(function($){$.fn.extend({leanModal:function(options){var defaults={top:100,overlay:0.5,closeButton:null};var overlay=$("<div id='lean_overlay'></div>");$("body").append(overlay);options=$.extend(defaults,options);return this.each(function(){var o=options;$(this).click(function(e){var modal_id=$(this).attr("href");$("#lean_overlay").click(function(){close_modal(modal_id)});$(o.closeButton).click(function(){close_modal(modal_id)});var modal_height=$(modal_id).outerHeight();var modal_width=$(modal_id).outerWidth();
|
||||
$("#lean_overlay").css({"display":"block",opacity:0});$("#lean_overlay").fadeTo(200,o.overlay);$(modal_id).css({"display":"block","position":"fixed","opacity":0,"z-index":11000,"left":50+"%","margin-left":-(modal_width/2)+"px","top":o.top+"px"});$(modal_id).fadeTo(200,1);e.preventDefault()})});function close_modal(modal_id){$("#lean_overlay").fadeOut(200);$(modal_id).css({"display":"none"})}}})})(jQuery);
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 643 B |
+112
-2
@@ -2,9 +2,12 @@
|
||||
<html>
|
||||
<head>
|
||||
<link rel="stylesheet" href="dist/themes/default/style.min.css"/>
|
||||
<script src="http://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
|
||||
<link rel="stylesheet" href="css/login_dialog.css"/>
|
||||
<script src="//cdn.jsdelivr.net/npm/sha256-uint8array/dist/sha256-uint8array.min.js"></script>
|
||||
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
|
||||
<script src="dist/jstree.min.js"></script>
|
||||
<script src="/js/main.js?v=0.1.2" type="module"></script>
|
||||
<script src="dist/jquery.leanModal.min.js"></script>
|
||||
<script src="/js/main.js?v=0.1.3" type="module"></script>
|
||||
</head>
|
||||
<body>
|
||||
<h3>Klippy Web API Test</h3>
|
||||
@@ -67,10 +70,117 @@ Progress: <progress id="progressbar" value="0" max="100"></progress>
|
||||
<button id="btnshutdown" style="width: 9em">Shutdown OS</button>
|
||||
<button id="btngetlog" style="width: 9em">Klippy Log</button>
|
||||
<button id="btnmoonlog" style="width: 9em">Moonraker Log</button>
|
||||
<br/><br/>
|
||||
<button id="btnloginuser" style="width: 9em">Login User</button>
|
||||
<button id="btncreateuser" style="width: 9em">Create User</button>
|
||||
<button id="btnsetapikey" style="width: 9em">Set API Key</button>
|
||||
<button id="btnlogout" style="width: 9em" class="req-login">Log Out</button>
|
||||
<button id="btndeluser" style="width: 9em" class="req-login">Delete User</button>
|
||||
<button id="btnchangepass" style="width: 9em" class="req-login">Change Pass</button>
|
||||
|
||||
<br/><br/>
|
||||
<span id="filename" hidden></span></br>
|
||||
<div id="streamdiv">
|
||||
</div>
|
||||
|
||||
<a id="nav_home" href="#" hidden>Hidden Home</a>
|
||||
<a id="do_login" rel="leanModal" name="login" href="#login" hidden>Hidden Login</a>
|
||||
<div id="login" class="user">
|
||||
<div id="login-ct">
|
||||
<div id="login-header" class="user-header">
|
||||
<h2>Moonraker Login</h2>
|
||||
<button id="login_close" class="modal_close"></a>
|
||||
</div>
|
||||
|
||||
<form id="login_form" class="user-form">
|
||||
<div class="text-field">
|
||||
<label for="login_username">Username</label>
|
||||
<input id="login_username" class="good_input" name="login_username" type="text" />
|
||||
</div>
|
||||
<div class="text-field">
|
||||
<label for="login_password">Password</label>
|
||||
<input id="login_password" name="login_password" type="password" />
|
||||
</div>
|
||||
<div class="button-field">
|
||||
<button type="submit" class="user-button">Login</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<a id="do_deleteuser" rel="leanModal" name="deleteuser" href="#deleteuser" hidden>Hidden Delete</a>
|
||||
<div id="deleteuser" class="user">
|
||||
<div id="login-ct">
|
||||
<div id="deleteuser-header" class="user-header">
|
||||
<h2>Delete User</h2>
|
||||
<button id="deleteuser_close" class="modal_close"></a>
|
||||
</div>
|
||||
|
||||
<form id="deleteuser_form" class="user-form">
|
||||
<div class="text-field">
|
||||
<label for="deleteuser_username">Username</label>
|
||||
<input id="deleteuser_username" class="good_input" name="deleteuser_username" type="text" />
|
||||
</div>
|
||||
<div class="button-field">
|
||||
<button type="submit" class="user-button">Submit</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<a id="do_signup" rel="leanModal" name="signup" href="#signup" hidden>Hidden Signup</a>
|
||||
<div id="signup" class="user">
|
||||
<div id="signup-ct">
|
||||
<div id="signup-header" class="user-header">
|
||||
<h2>Create User</h2>
|
||||
<button id="signup_close" class="modal_close"></a>
|
||||
</div>
|
||||
<form id="signup_form" class="user-form">
|
||||
<div class="text-field">
|
||||
<label for="signup_username">Username</label>
|
||||
<input id="signup_username" class="good_input" name="signup_username" type="text" />
|
||||
</div>
|
||||
<div class="text-field">
|
||||
<label for="signup_password">Password</label>
|
||||
<input id="signup_password" name="signup_password" type="password" />
|
||||
</div>
|
||||
<div class="text-field">
|
||||
<label for="signup_verify_pass">Re-Enter Password</label>
|
||||
<input id="signup_verify_pass" name="signup_verify_pass" type="password" />
|
||||
</div>
|
||||
<div class="button-field">
|
||||
<button type="submit" class="user-button">Signup</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<a id="do_changepass" rel="leanModal" name="changepass" href="#changepass" hidden></a>
|
||||
<div id="changepass" class="user">
|
||||
<div id="changepass-ct">
|
||||
<div id="changepass-header" class="user-header">
|
||||
<h2>Change Password</h2>
|
||||
<button id="changepass_close" class="modal_close"></a>
|
||||
</div>
|
||||
<form id="changepass_form" class="user-form">
|
||||
<div class="text-field">
|
||||
<label for="changepass_oldpass">Current Password</label>
|
||||
<input id="changepass_oldpass" name="changepass_oldpass" type="password" />
|
||||
</div>
|
||||
<div class="text-field">
|
||||
<label for="changepass_newpass">New Password</label>
|
||||
<input id="changepass_newpass" name="changepass_newpass" type="password" />
|
||||
</div>
|
||||
<div class="text-field">
|
||||
<label for="changepass_verify_pass">Re-Enter New Password</label>
|
||||
<input id="changepass_verify_pass" name="changepass_verify_pass" type="password" />
|
||||
</div>
|
||||
<div class="button-field">
|
||||
<button type="submit" class="user-button">Submit</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
+389
-36
@@ -7,7 +7,7 @@
|
||||
import JsonRPC from "./json-rpc.js?v=0.1.2";
|
||||
|
||||
var origin = location.origin;
|
||||
var ws_url = (window.location.protocol == "https" ? "wss://" : "ws://")
|
||||
var ws_url = (window.location.protocol == "https:" ? "wss://" : "ws://")
|
||||
+ location.host;
|
||||
|
||||
// API Definitions
|
||||
@@ -120,6 +120,12 @@ var api = {
|
||||
url: "/server/files/config_examples/"
|
||||
},
|
||||
|
||||
// Server APIs
|
||||
server_info: {
|
||||
url: "/server/info",
|
||||
method: "server.info"
|
||||
},
|
||||
|
||||
// Machine APIs
|
||||
reboot: {
|
||||
url: "/machine/reboot",
|
||||
@@ -136,11 +142,28 @@ var api = {
|
||||
},
|
||||
oneshot_token: {
|
||||
url: "/access/oneshot_token"
|
||||
},
|
||||
login: {
|
||||
url: "/access/login"
|
||||
},
|
||||
logout: {
|
||||
url: "/access/logout"
|
||||
},
|
||||
refresh_jwt: {
|
||||
url: "/access/refresh_jwt"
|
||||
},
|
||||
user: {
|
||||
url: "/access/user"
|
||||
},
|
||||
reset_password: {
|
||||
url: "/access/user/password"
|
||||
}
|
||||
}
|
||||
|
||||
var websocket = null;
|
||||
var apikey = null;
|
||||
var auth_token = null;
|
||||
var refresh_token = window.localStorage.getItem('refresh_token');
|
||||
var paused = false;
|
||||
var klippy_ready = false;
|
||||
var api_type = 'http';
|
||||
@@ -277,6 +300,29 @@ function process_mesh(result) {
|
||||
console.log("Processed Mesh Coordinates:");
|
||||
console.log(coordinates);
|
||||
}
|
||||
|
||||
async function calculate_checksum(file) {
|
||||
let done_promise = new Promise((resolve, reject) => {
|
||||
let reader = file.stream().getReader();
|
||||
let hash = SHA256.createHash();
|
||||
reader.read().then(function read_file({done, value}) {
|
||||
if (done) {
|
||||
resolve(hash.digest("hex"));
|
||||
return;
|
||||
}
|
||||
hash.update(value);
|
||||
return reader.read().then(read_file)
|
||||
});
|
||||
})
|
||||
let checksum = await done_promise;
|
||||
if (checksum == null) {
|
||||
console.log("Unable to calculate checksum for file")
|
||||
return null;
|
||||
} else {
|
||||
console.log(`Calculated Checksum: ${checksum}`)
|
||||
return checksum;
|
||||
}
|
||||
}
|
||||
//***********End UI Update Functions****************/
|
||||
|
||||
//***********Websocket-Klipper API Functions (JSON-RPC)************/
|
||||
@@ -752,7 +798,7 @@ function handle_file_list_changed(file_info) {
|
||||
// Update the jstree based on the action and info
|
||||
let parent_node = parse_node_path(file_info.item.root, file_info.item.path);
|
||||
$("#filelist").jstree('refresh_node', parent_node);
|
||||
if (file_info.action == "move_item") {
|
||||
if (file_info.action.startsWith("move_")) {
|
||||
let src_parent_node = parse_node_path(
|
||||
file_info.source_item.root, file_info.source_item.path)
|
||||
if (src_parent_node != parent_node)
|
||||
@@ -768,6 +814,18 @@ function handle_metadata_update(metadata) {
|
||||
}
|
||||
json_rpc.register_method("notify_metadata_update", handle_metadata_update);
|
||||
|
||||
function handle_cpu_throttled(tdata) {
|
||||
console.log("CPU Throttled");
|
||||
console.log(tdata);
|
||||
}
|
||||
json_rpc.register_method("notify_cpu_throttled", handle_cpu_throttled);
|
||||
|
||||
function handle_proc_stat_update(proc_stats) {
|
||||
// TODO: Display Temp
|
||||
return;
|
||||
}
|
||||
json_rpc.register_method("notify_proc_stat_update", handle_proc_stat_update);
|
||||
|
||||
//***********End Klipper Event Handlers (JSON-RPC)*****************/
|
||||
|
||||
//*****************Websocket Batch GCode Tests*********************/
|
||||
@@ -859,6 +917,17 @@ function run_request(url, method, callback=null)
|
||||
let settings = {
|
||||
url: url,
|
||||
method: method,
|
||||
statusCode: {
|
||||
401: function() {
|
||||
if (refresh_token != null) {
|
||||
refresh_json_web_token(run_request, url, method, callback);
|
||||
}
|
||||
else {
|
||||
auth_token = null;
|
||||
$("#do_login").click();
|
||||
}
|
||||
}
|
||||
},
|
||||
success: (resp, status) => {
|
||||
console.log(resp);
|
||||
if (callback != null)
|
||||
@@ -872,7 +941,9 @@ function run_request(url, method, callback=null)
|
||||
settings.contentType = false,
|
||||
settings.processData = false
|
||||
}
|
||||
if (apikey != null)
|
||||
if (auth_token != null)
|
||||
settings.headers = {"Authorization": `Bearer ${auth_token}`};
|
||||
else if (apikey != null)
|
||||
settings.headers = {"X-Api-Key": apikey};
|
||||
$.ajax(settings);
|
||||
}
|
||||
@@ -894,9 +965,9 @@ function form_delete_request(api_url, query_string="", callback=null) {
|
||||
|
||||
function form_download_request(uri) {
|
||||
let dl_url = origin + uri;
|
||||
if (apikey != null) {
|
||||
form_get_request(api.oneshot_token.url,
|
||||
callback=(resp) => {
|
||||
if (apikey != null || auth_token != null) {
|
||||
form_get_request(api.oneshot_token.url, "",
|
||||
(resp) => {
|
||||
let token = resp.result;
|
||||
dl_url += "?token=" + token;
|
||||
do_download(dl_url);
|
||||
@@ -961,7 +1032,9 @@ function jstree_populate_children(node, callback) {
|
||||
if (api_type == "http") {
|
||||
let qs = `?path=${node.id}`;
|
||||
let settings = {url: origin + api.directory.url + qs};
|
||||
if (apikey != null)
|
||||
if (auth_token != null)
|
||||
settings.headers = {"Authorization": `Bearer ${auth_token}`};
|
||||
else if (apikey != null)
|
||||
settings.headers = {"X-Api-Key": apikey};
|
||||
$.get(settings, (resp, status) => {
|
||||
callback(generate_children(resp.result, node));
|
||||
@@ -1130,6 +1203,7 @@ class KlippyWebsocket {
|
||||
this.onmessage = null;
|
||||
this.onopen = null;
|
||||
this.id = null;
|
||||
this.reconnect = true
|
||||
this.connect();
|
||||
}
|
||||
|
||||
@@ -1138,14 +1212,15 @@ class KlippyWebsocket {
|
||||
// to reconnect if its closed. This is nice as it allows the
|
||||
// client to easily recover from Klippy restarts without user
|
||||
// intervention
|
||||
if (apikey != null) {
|
||||
if (apikey != null || auth_token != null) {
|
||||
// Fetch a oneshot token to pass websocket authorization
|
||||
let token_settings = {
|
||||
url: origin + api.oneshot_token.url,
|
||||
headers: {
|
||||
"X-Api-Key": apikey
|
||||
}
|
||||
}
|
||||
if (auth_token != null)
|
||||
token_settings.headers = {"Authorization": `Bearer ${auth_token}`};
|
||||
else
|
||||
token_settings.headers = {"X-Api-Key": apikey};
|
||||
$.get(token_settings, (data, status) => {
|
||||
let token = data.result;
|
||||
let url = this.base_address + "/websocket?token=" + token;
|
||||
@@ -1172,10 +1247,14 @@ class KlippyWebsocket {
|
||||
klippy_ready = false;
|
||||
this.connected = false;
|
||||
this.id = null;
|
||||
console.log("Websocket Closed, reconnecting in 1s: ", e.reason);
|
||||
setTimeout(() => {
|
||||
this.connect();
|
||||
}, 1000);
|
||||
// TODO: Need to cancel any pending JSON-RPC requests
|
||||
if (this.reconnect) {
|
||||
console.log("Websocket Closed, reconnecting in 1s: ", e.reason);
|
||||
setTimeout(() => {
|
||||
if (this.reconnect)
|
||||
this.connect();
|
||||
}, 1000);
|
||||
}
|
||||
};
|
||||
|
||||
this.ws.onerror = (err) => {
|
||||
@@ -1202,7 +1281,7 @@ class KlippyWebsocket {
|
||||
}
|
||||
|
||||
close() {
|
||||
// TODO: Cancel the timeout
|
||||
this.reconnect = false
|
||||
this.ws.close();
|
||||
}
|
||||
|
||||
@@ -1227,25 +1306,168 @@ function create_websocket(url) {
|
||||
json_rpc.register_transport(websocket);
|
||||
}
|
||||
|
||||
function login_jwt_user(user, pass, do_create) {
|
||||
if (!user || !pass) {
|
||||
alert("Invalid username/password")
|
||||
return;
|
||||
}
|
||||
let close_btn_name = "#login_close"
|
||||
if (do_create)
|
||||
close_btn_name = "#signup_close"
|
||||
let settings = {
|
||||
url: origin + api.login.url,
|
||||
data: JSON.stringify({username: user, password: pass}),
|
||||
contentType: "application/json",
|
||||
dataType: 'json'
|
||||
}
|
||||
if (do_create) {
|
||||
settings.url = origin + api.user.url;
|
||||
if (auth_token != null)
|
||||
settings.headers = {"Authorization": `Bearer ${auth_token}`};
|
||||
else if (apikey != null)
|
||||
settings.headers = {"X-Api-Key": apikey};
|
||||
}
|
||||
$.post(settings, (resp, status) => {
|
||||
let res = resp.result;
|
||||
console.log("Login Response:");
|
||||
console.log(res);
|
||||
auth_token = res.token;
|
||||
refresh_token = res.refresh_token;
|
||||
window.localStorage.setItem('refresh_token', refresh_token);
|
||||
$('.req-login').prop('disabled', false);
|
||||
$(close_btn_name).click();
|
||||
check_authorization();
|
||||
}).fail(() => {
|
||||
console.log("Login Failed");
|
||||
alert("Login Failed")
|
||||
});
|
||||
}
|
||||
|
||||
function logout_jwt_user() {
|
||||
if (auth_token == null) {
|
||||
console.log("No User Logged In")
|
||||
return;
|
||||
}
|
||||
let settings = {
|
||||
url: origin + api.logout.url,
|
||||
contentType: "application/json",
|
||||
dataType: 'json',
|
||||
headers: {
|
||||
"Authorization": `Bearer ${auth_token}`
|
||||
}
|
||||
}
|
||||
|
||||
$.post(settings, (resp, status) => {
|
||||
let res = resp.result;
|
||||
console.log("Logout Response:");
|
||||
console.log(res);
|
||||
auth_token = null;
|
||||
refresh_token = null;
|
||||
window.localStorage.removeItem('refresh_token');
|
||||
$('.req-login').prop('disabled', true);
|
||||
}).fail(() => {
|
||||
console.log("Logout User Failed");
|
||||
});
|
||||
}
|
||||
|
||||
function delete_jwt_user(user) {
|
||||
if (!user) {
|
||||
alert("Invalid username or password, Cannot Delete User");
|
||||
return;
|
||||
}
|
||||
|
||||
let settings = {
|
||||
method: 'DELETE',
|
||||
url: origin + api.user.url,
|
||||
contentType: "application/json",
|
||||
data: JSON.stringify({username: user}),
|
||||
dataType: 'json',
|
||||
headers: {
|
||||
"Authorization": `Bearer ${auth_token}`
|
||||
},
|
||||
success: (resp, status) => {
|
||||
let res = resp.result;
|
||||
console.log("Delete User Response:");
|
||||
console.log(res);
|
||||
$("#deleteuser_close").click()
|
||||
}
|
||||
}
|
||||
|
||||
$.ajax(settings)
|
||||
.fail(() => {
|
||||
console.log("Delete User Failed");
|
||||
$("#deleteuser_close").click()
|
||||
window.alert("Unable to delete user!")
|
||||
});
|
||||
}
|
||||
|
||||
function change_jwt_password(old_pass, new_pass) {
|
||||
if (!old_pass || !new_pass) {
|
||||
alert("Invalid input for change password")
|
||||
return;
|
||||
}
|
||||
let settings = {
|
||||
url: origin + api.reset_password.url,
|
||||
data: JSON.stringify({password: old_pass, new_password: new_pass}),
|
||||
contentType: "application/json",
|
||||
dataType: 'json',
|
||||
headers: {
|
||||
"Authorization": `Bearer ${auth_token}`
|
||||
}
|
||||
}
|
||||
$.post(settings, (resp, status) => {
|
||||
let res = resp.result;
|
||||
console.log("Change Password Response:");
|
||||
console.log(res);
|
||||
$("#changepass_close").click();
|
||||
}).fail(() => {
|
||||
console.log("Failed to change password");
|
||||
alert("Password Reset Failed")
|
||||
});
|
||||
}
|
||||
|
||||
function refresh_json_web_token(callback, ...args) {
|
||||
let settings = {
|
||||
url: origin + api.refresh_jwt.url,
|
||||
data: JSON.stringify({refresh_token: refresh_token}),
|
||||
contentType: "application/json",
|
||||
dataType: 'json',
|
||||
}
|
||||
$.post(settings, (resp, status) => {
|
||||
let res = resp.result;
|
||||
console.log("Refresh JWT Response:");
|
||||
console.log(res);
|
||||
auth_token = res.token;
|
||||
$('.req-login').prop('disabled', false);
|
||||
if (callback != null)
|
||||
callback(...args);
|
||||
}).fail(() => {
|
||||
console.log("Refresh JWT Failed");
|
||||
auth_token = null;
|
||||
refresh_token = null;
|
||||
window.localStorage.removeItem('refresh_token');
|
||||
$('.req-login').prop('disabled', true);
|
||||
$("#do_login").click();
|
||||
});
|
||||
}
|
||||
|
||||
function check_authorization() {
|
||||
// send a HTTP "run gcode" command
|
||||
let settings = {
|
||||
url: origin + api.printer_info.url,
|
||||
url: origin + api.server_info.url,
|
||||
statusCode: {
|
||||
401: function() {
|
||||
// Show APIKey Popup
|
||||
let result = window.prompt("Enter a valid API Key:", "");
|
||||
if (result == null || result.length != 32) {
|
||||
console.log("Invalid API Key: " + result);
|
||||
apikey = null;
|
||||
} else {
|
||||
apikey = result;
|
||||
}
|
||||
check_authorization();
|
||||
if (refresh_token != null) {
|
||||
refresh_json_web_token(check_authorization);
|
||||
} else {
|
||||
$("#do_login").click();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (apikey != null)
|
||||
if (auth_token != null)
|
||||
settings.headers = {"Authorization": `Bearer ${auth_token}`};
|
||||
else if (apikey != null)
|
||||
settings.headers = {"X-Api-Key": apikey};
|
||||
$.get(settings, (data, status) => {
|
||||
// Create a websocket if /printer/info successfully returns
|
||||
@@ -1261,11 +1483,9 @@ function do_download(url) {
|
||||
window.onload = () => {
|
||||
// Handle changes between the HTTP and Websocket API
|
||||
$('.reqws').prop('disabled', true);
|
||||
$('.req-login').prop('disabled', true);
|
||||
$('input[type=radio][name=test_type]').on('change', function() {
|
||||
api_type = $(this).val();
|
||||
let disable_transfer = (!$('#cbxFileTransfer').is(":checked") && is_printing);
|
||||
$('.toggleable').prop(
|
||||
'disabled', (api_type == 'websocket' || disable_transfer));
|
||||
$('.reqws').prop('disabled', (api_type == 'http'));
|
||||
$('#apimethod').prop('hidden', (api_type == "websocket"));
|
||||
$('#apiargs').prop('hidden', (api_type == "http"));
|
||||
@@ -1467,7 +1687,9 @@ window.onload = () => {
|
||||
let sendtype = $("input[type=radio][name=api_cmd_type]:checked").val();
|
||||
let url = $('#apirequest').val();
|
||||
let settings = {url: url}
|
||||
if (apikey != null)
|
||||
if (auth_token != null)
|
||||
settings.headers = {"Authorization": `Bearer ${auth_token}`};
|
||||
else if (apikey != null)
|
||||
settings.headers = {"X-Api-Key": apikey};
|
||||
if (sendtype == "get") {
|
||||
console.log("Sending GET " + url);
|
||||
@@ -1510,7 +1732,7 @@ window.onload = () => {
|
||||
});
|
||||
|
||||
// Uploads a selected file to the server
|
||||
$('#upload-file').change(() => {
|
||||
$('#upload-file').change(async () => {
|
||||
update_progress(0, 100);
|
||||
let file = $('#upload-file').prop('files')[0];
|
||||
let dir = get_selected_item("dir");
|
||||
@@ -1521,6 +1743,8 @@ window.onload = () => {
|
||||
let root = dir[0];
|
||||
let directory = dir.slice(1).join("/");
|
||||
console.log("Sending Upload Request...");
|
||||
// First, calculate the file checksum
|
||||
let chksum = await calculate_checksum(file);
|
||||
// It might not be a bad idea to validate that this is
|
||||
// a gcode file here, and reject and other files.
|
||||
|
||||
@@ -1532,6 +1756,8 @@ window.onload = () => {
|
||||
fdata.append("file", file);
|
||||
fdata.append("root", root);
|
||||
fdata.append("path", directory);
|
||||
if (chksum != null)
|
||||
fdata.append("checksum", chksum);
|
||||
let settings = {
|
||||
url: origin + api.upload.url,
|
||||
data: fdata,
|
||||
@@ -1553,7 +1779,9 @@ window.onload = () => {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
if (apikey != null)
|
||||
if (auth_token != null)
|
||||
settings.headers = {"Authorization": `Bearer ${auth_token}`};
|
||||
else if (apikey != null)
|
||||
settings.headers = {"X-Api-Key": apikey};
|
||||
$.ajax(settings);
|
||||
$('#upload-file').val('');
|
||||
@@ -1645,11 +1873,13 @@ window.onload = () => {
|
||||
$('#btntestmesh').click(() => {
|
||||
if (api_type == 'http') {
|
||||
let settings = {url: origin + api.object_status.url + "?bed_mesh"};
|
||||
if (apikey != null)
|
||||
if (auth_token != null)
|
||||
settings.headers = {"Authorization": `Bearer ${auth_token}`};
|
||||
else if (apikey != null)
|
||||
settings.headers = {"X-Api-Key": apikey};
|
||||
$.get(settings, (resp, status) => {
|
||||
process_mesh(resp.result)
|
||||
return false;
|
||||
process_mesh(resp.result)
|
||||
return false;
|
||||
});
|
||||
} else {
|
||||
get_mesh();
|
||||
@@ -1726,5 +1956,128 @@ window.onload = () => {
|
||||
form_download_request(api.moonraker_log.url);
|
||||
});
|
||||
|
||||
$('#btnloginuser').click(() => {
|
||||
$("#do_login").click();
|
||||
});
|
||||
|
||||
$('#btncreateuser').click(() => {
|
||||
$("#do_signup").click();
|
||||
});
|
||||
|
||||
$('#btnlogout').click(() => {
|
||||
logout_jwt_user();
|
||||
});
|
||||
|
||||
$('#btndeluser').click(() => {
|
||||
$("#do_deleteuser").click()
|
||||
});
|
||||
|
||||
$('#btnchangepass').click(() => {
|
||||
$("#do_changepass").click();
|
||||
});
|
||||
|
||||
$('#btnsetapikey').click(() => {
|
||||
let defkey = apikey;
|
||||
if (!defkey)
|
||||
defkey = ""
|
||||
let new_key = window.prompt("Enter your API Key", defkey);
|
||||
if (!new_key)
|
||||
apikey = null;
|
||||
else
|
||||
apikey = new_key;
|
||||
check_authorization();
|
||||
});
|
||||
|
||||
$("#do_login").leanModal({
|
||||
top : 200,
|
||||
overlay : 0.4,
|
||||
closeButton: "#login_close"
|
||||
});
|
||||
|
||||
$("#do_signup").leanModal({
|
||||
top : 200,
|
||||
overlay : 0.4,
|
||||
closeButton: "#signup_close"
|
||||
});
|
||||
|
||||
$("#do_changepass").leanModal({
|
||||
top : 200,
|
||||
overlay : 0.4,
|
||||
closeButton: "#changepass_close"
|
||||
});
|
||||
|
||||
$("#do_deleteuser").leanModal({
|
||||
top : 200,
|
||||
overlay : 0.4,
|
||||
closeButton: "#deleteuser_close"
|
||||
});
|
||||
|
||||
|
||||
$("#login_close").click(() => {
|
||||
//$("#login_username").val("");
|
||||
$("#login_password").val("");
|
||||
$("#nav_home").click();
|
||||
});
|
||||
|
||||
$("#signup_close").click(() => {
|
||||
$("#signup_username").val("");
|
||||
$("#signup_password").val("");
|
||||
$("#signup_verify_pass").val("");
|
||||
$("#nav_home").click();
|
||||
});
|
||||
|
||||
$("#changepass_close").click(() => {
|
||||
$("#changepass_oldpass").val("");
|
||||
$("#changepass_newpass").val("");
|
||||
$("#changepass_verify_pass").val("");
|
||||
$("#nav_home").click();
|
||||
});
|
||||
|
||||
$("#deleteuser_close").click(() => {
|
||||
$("#deleteuser_username").val("");
|
||||
$("#nav_home").click();
|
||||
});
|
||||
|
||||
$("#login_form").submit((evt)=> {
|
||||
let user = $("#login_username").val()
|
||||
let pass = $("#login_password").val()
|
||||
if (user != "" && pass != "")
|
||||
login_jwt_user(user, pass, false);
|
||||
else
|
||||
alert("Invalid username/password");
|
||||
return false;
|
||||
});
|
||||
|
||||
$("#signup_form").submit((evt)=> {
|
||||
let user = $("#signup_username").val()
|
||||
let pass = $("#signup_password").val()
|
||||
let verify_pass = $("#signup_verify_pass").val()
|
||||
if (user != "" && pass != "" && pass == verify_pass)
|
||||
login_jwt_user(user, pass, true);
|
||||
else
|
||||
alert("Invalid username/password");
|
||||
return false;
|
||||
});
|
||||
|
||||
$("#changepass_form").submit((evt)=> {
|
||||
let old_pass = $("#changepass_oldpass").val()
|
||||
let new_pass = $("#changepass_newpass").val()
|
||||
let verify_pass = $("#changepass_verify_pass").val()
|
||||
if (old_pass != "" && new_pass != "" && new_pass == verify_pass)
|
||||
change_jwt_password(old_pass, new_pass)
|
||||
else
|
||||
alert("All fields are required to change password");
|
||||
return false;
|
||||
});
|
||||
|
||||
$("#deleteuser_form").submit((evt)=> {
|
||||
let user = $("#deleteuser_username").val()
|
||||
if (user != "")
|
||||
delete_jwt_user(user);
|
||||
else
|
||||
alert("Invalid username/password");
|
||||
return false;
|
||||
});
|
||||
|
||||
check_authorization();
|
||||
};
|
||||
Reference in new issue
Block a user