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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Signed-off-by:  Eric Callahan <arksine.code@gmail.com>
2020-12-22 18:10:58 -05:00
12 changed files with 452 additions and 153 deletions

No files matched your search

+3
View File
@@ -1,4 +1,7 @@
This document keeps a record of all changes to Moonraker's web APIs.
### 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]`
+21
View File
@@ -160,6 +160,10 @@ pin: gpiochip0/gpio26
# !gpiochip0/gpio26
# !gpio26
# This parameter must be provided for "gpio" type devices
initial_state: off
# The initial state for GPIO type devices. May be on or
# off. When moonraker starts the device will be set to this
# state. Default is off.
address:
port:
# The above options are used for "tplink_smartplug" devices. The
@@ -186,10 +190,17 @@ Below are some potential examples:
[power printer]
type: gpio
pin: gpio26
initial_state: off
[power printer_led]
type: gpio
pin: !gpiochip0/gpio16
initial_state: off
[power light_strip]
type: gpio
pin: gpiochip0/gpio17
initial_state: on
[power wifi_switch]
type: tplink_smartplug
@@ -241,6 +252,16 @@ disk or cloned from unofficial sources are not supported.
# moonraker.conf
[update_manager]
enable_repo_debug: False
# When set to True moonraker will bypass repo validation and allow
# updates from unofficial remotes and/or branches. Updates on
# detached repos are also allowed. This option is intended for
# developers and should not be used on production machines. The
# default is False.
distro: debian
# The disto in which moonraker has been installed. Currently the
# update manager only supports "debian", which encompasses all of
# its derivatives. The default is debain.
client_repo:
# This is the GitHub repo of the client, in the format of user/client.
# For example, this could be set to cadriel/fluidd to update Fluidd or
+44 -7
View File
@@ -844,41 +844,78 @@ information.
{
'version_info': {
'moonraker': {
branch: <string>,
remote_alias: <string>,
version: <string>,
remote_version: <string>,
current_hash: <string>,
remote_hash: <string>,
is_valid: <bool>,
is_dirty: <bool>
is_dirty: <bool>,
detached: <bool>,
debug_enabled: <bool>
},
'klipper': {
branch: <string>,
remote_alias: <string>,
version: <string>,
remote_version: <string>,
current_hash: <string>,
remote_hash: <string>,
is_valid: <bool>,
is_dirty: <bool>
}
is_dirty: <bool>,
detached: <bool>,
debug_enabled: <bool>
},
'client': {
name: <string>,
version: <string>,
remote_version: <string>
},
'system': {
package_count: <int>,
package_list: <array>
}
},
busy: false
busy: false,
github_rate_limit: <int>,
github_requests_remaining: <int>
github_limit_reset_time: <int>,
}
```
- The `busy` field is set to true if an update is in progress. Moonraker
will not allow concurrent updates.
- The `github_rate_limit` is the maximum number of github API requests
the user currently has. An unathenticated user typically has 60
requests per hour.
- The `github_requests_remaining` is the number of API request the user
currently has remaining.
- The `github_limit_reset_time` is reported as seconds since the epoch.
When this time is reached the user's limit will be reset.
- The `moonraker` and `klipper` objects have the following fields:
- `branch`: the name of the current git branch. This should typically
be "master".
- `remote_alias`: the alias for the remote. This should typically be
"origin".
- `version`: version of the current repo on disk
- `remote_version`: version of the latest available update
- `current_hash`: hash of the most recent commit on disk
- `remote_hash`: hash of the most recent commit pushed to the remote
- `is_valid`: True if installation is a valid git repo on the master branch
and an "origin" set to the official remote
- `is_dirty`: True if the repo has been modified
- `detached`: True if the repo is currently in a detached state
- `debug_enabled`: True when "enable_repo_debug" has been configured. This
will bypass repo validation, allowing detached updates, and updates from
a remote/origin other than "origin/master".
- The `client` object has the following fields:
`name`: Name of the configured client
`version`: version of the installed client.
`remote_version`: version of the latest release published to GitHub
- `name`: Name of the configured client
- `version`: version of the installed client.
- `remote_version`: version of the latest release published to GitHub
- The `system` object has the following fields:
- `package_count`: The number of system packages available for update
- `package_list`: An array containing the names of packages available
for update
### Update Moonraker
Pulls the most recent version of Moonraker from GitHub and restarts
+4 -1
View File
@@ -24,6 +24,7 @@ RESERVED_ENDPOINTS = [
]
EXCLUDED_ARGS = ["_", "token", "connection_id"]
DEFAULT_KLIPPY_LOG_PATH = "/tmp/klippy.log"
# Status objects require special parsing
def _status_parser(request_handler):
@@ -131,6 +132,8 @@ class MoonrakerApp:
# Register handlers
logfile = config['system_args'].get('logfile')
self.register_static_file_handler("moonraker.log", logfile)
self.register_static_file_handler(
"klippy.log", DEFAULT_KLIPPY_LOG_PATH)
self.auth.register_handlers(self)
def listen(self, host, port):
@@ -329,7 +332,7 @@ class FileRequestHandler(AuthorizedFileHandler):
async def delete(self, path):
path = self.request.path.lstrip("/").split("/", 2)[-1]
path = url_unescape(path)
path = url_unescape(path, plus=False)
file_manager = self.server.lookup_plugin('file_manager')
try:
filename = await file_manager.delete_file(path)
+13
View File
@@ -34,6 +34,9 @@ class ConfigHelper:
def get_name(self):
return self.section
def get_options(self):
return dict(self.config[self.section])
def get_prefix_sections(self, prefix):
return [s for s in self.sections() if s.startswith(prefix)]
@@ -70,6 +73,16 @@ class ConfigHelper:
return self._get_item(
self.config[self.section].getfloat, option, default)
def read_supplemental_config(self, file_name):
cfg_file_path = os.path.normpath(os.path.expanduser(file_name))
if not os.path.isfile(cfg_file_path):
raise ConfigError(
f"Configuration File Not Found: '{cfg_file_path}''")
try:
self.config.read(cfg_file_path)
except Exception:
raise ConfigError(f"Error Reading Config: '{cfg_file_path}'")
def get_configuration(server, system_args):
cfg_file_path = os.path.normpath(os.path.expanduser(
system_args.configfile))
Regular → Executable
+4 -2
View File
@@ -1,3 +1,4 @@
#!/usr/bin/env python3
# Moonraker - HTTP/Websocket API Server for Klipper
#
# Copyright (C) 2020 Eric Callahan <arksine.code@gmail.com>
@@ -285,10 +286,11 @@ class Server:
f"Klippy may have experienced an error during startup.\n"
f"Please check klippy.log for more information")
return
if send_id:
self.init_list.append("identified")
self.klippy_info = dict(result)
self.klippy_state = result.get('state', "unknown")
if send_id:
self.init_list.append("identified")
self.send_event("server:klippy_identified")
if self.klippy_state == "ready":
await self._verify_klippy_requirements()
logging.info("Klippy ready")
+1 -1
View File
@@ -46,7 +46,7 @@ class FileManager:
self.server.register_upload_handler("/api/files/local")
self.server.register_event_handler(
"server:klippy_ready", self._update_fixed_paths)
"server:klippy_identified", self._update_fixed_paths)
# Register Klippy Configuration Path
config_path = config.get('config_path', None)
+6 -4
View File
@@ -164,7 +164,8 @@ class GpioDevice:
f"Unable to init {pin}. Make sure the gpio is not in "
"use by another program or exported by sysfs.")
raise config.error("Power GPIO Config Error")
self.set_power("off")
initial_state = config.getboolean('initial_state', False)
self.set_power("on" if initial_state else "off")
def _parse_pin(self, config):
pin = cfg_pin = config.get("pin")
@@ -351,11 +352,12 @@ class Tasmota:
if command in ["on", "off"]:
out_cmd = f"Power{self.output_id}%20{command}"
elif command == "info":
out_cmd = "Power{self.output_id}"
out_cmd = f"Power{self.output_id}"
else:
raise self.server.error(f"Invalid tasmota command: {command}")
url = f"http://{self.addr}/cm?user=admin&password={self.password}&cmnd={out_cmd}"
url = f"http://{self.addr}/cm?user=admin&password=" \
f"{self.password}&cmnd={out_cmd}"
data = ""
http_client = AsyncHTTPClient()
try:
+14 -8
View File
@@ -46,6 +46,8 @@ class ShellCommand:
async def run(self, timeout=2., verbose=True):
self.return_code = fd = None
self.partial_output = b""
self.cancelled = False
if timeout is None:
# Never timeout
timeout = 9999999999999999.
@@ -83,16 +85,20 @@ class ShellCommand:
if self.partial_output:
self.output_cb(self.partial_output)
self.partial_output = b""
if complete:
msg = f"Command ({self.name}) finished"
elif self.cancelled:
msg = f"Command ({self.name}) cancelled"
else:
msg = f"Command ({self.name}) timed out"
logging.info(msg)
self.io_loop.remove_handler(fd)
self.return_code = proc.returncode
return self.return_code == 0 and complete
success = self.return_code == 0 and complete
if success:
msg = f"Command ({self.name}) successfully finished"
elif self.cancelled:
msg = f"Command ({self.name}) cancelled"
elif not complete:
msg = f"Command ({self.name}) timed out"
else:
msg = f"Command ({self.name}) exited with return code" \
f" {self.return_code}"
logging.info(msg)
return success
async def run_with_response(self, timeout=2.):
result = []
+317 -129
View File
@@ -12,46 +12,32 @@ import shutil
import zipfile
import io
import asyncio
import time
import tornado.gen
from tornado.ioloop import IOLoop
from tornado.httpclient import AsyncHTTPClient, HTTPRequest
from tornado.httpclient import AsyncHTTPClient
from tornado.locks import Event
MOONRAKER_PATH = os.path.normpath(os.path.join(
os.path.dirname(__file__), "../.."))
# TODO: May want to attempt to look up the disto for the correct
# klippy install script or have the user configure it
SUPPLEMENTAL_CFG_PATH = os.path.join(
MOONRAKER_PATH, "scripts/update_manager.conf")
APT_CMD = "sudo DEBIAN_FRONTEND=noninteractive apt-get"
REPO_PREFIX = "https://api.github.com/repos"
REPO_DATA = {
'moonraker': {
'repo_url': f"{REPO_PREFIX}/arksine/moonraker/branches/master",
'origin': "https://github.com/arksine/moonraker.git",
'install_script': "scripts/install-moonraker.sh",
'requirements': "scripts/moonraker-requirements.txt",
'venv_args': "-p python3",
'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': "",
}
}
SUPPORTED_DISTROS = ["debian"]
class UpdateManager:
def __init__(self, config):
self.server = config.get_server()
self.config = config
self.config.read_supplemental_config(SUPPLEMENTAL_CFG_PATH)
AsyncHTTPClient.configure(None, defaults=dict(user_agent="Moonraker"))
self.http_client = AsyncHTTPClient()
self.repo_debug = config.getboolean('enable_repo_debug', False)
self.distro = config.get('distro', "debian").lower()
if self.distro not in SUPPORTED_DISTROS:
raise config.error(f"Unsupported distro: {self.distro}")
if self.repo_debug:
logging.warn("UPDATE MANAGER: REPO DEBUG ENABLED")
env = sys.executable
self.updaters = {
"system": PackageUpdater(self),
@@ -67,6 +53,12 @@ class UpdateManager:
self.updaters['client'] = ClientUpdater(
self, client_repo, client_path)
# GitHub API Rate Limit Tracking
self.gh_rate_limit = None
self.gh_limit_remaining = None
self.gh_limit_reset_time = None
self.gh_init_evt = Event()
self.server.register_endpoint(
"/machine/update/moonraker", ["POST"],
self._handle_update_request)
@@ -85,7 +77,9 @@ class UpdateManager:
# Register Ready Event
self.server.register_event_handler(
"server:klippy_ready", self._set_klipper_repo)
"server:klippy_identified", self._set_klipper_repo)
# Initialize GitHub API Rate Limits
IOLoop.current().spawn_callback(self._init_api_rate_limit)
async def _set_klipper_repo(self):
kinfo = self.server.get_klippy_info()
@@ -94,6 +88,11 @@ class UpdateManager:
return
kpath = kinfo['klipper_path']
env = kinfo['python_path']
kupdater = self.updaters.get('klipper', None)
if kupdater is not None and kupdater.repo_path == kpath and \
kupdater.env == env:
# Current Klipper Updater is valid
return
self.updaters['klipper'] = GitUpdater(self, "klipper", kpath, env)
async def _handle_update_request(self, web_request):
@@ -117,7 +116,7 @@ class UpdateManager:
refresh = web_request.get_boolean('refresh', False)
vinfo = {}
for name, updater in self.updaters.items():
await updater.check_initialized(10.)
await updater.check_initialized(120.)
if refresh:
ret = updater.refresh()
if asyncio.iscoroutine(ret):
@@ -126,6 +125,9 @@ class UpdateManager:
vinfo[name] = updater.get_update_status()
return {
'version_info': vinfo,
'github_rate_limit': self.gh_rate_limit,
'github_requests_remaining': self.gh_limit_remaining,
'github_limit_reset_time': self.gh_limit_reset_time,
'busy': self.current_update is not None}
async def execute_cmd(self, cmd, timeout=10., notify=False, retries=1):
@@ -144,32 +146,113 @@ class UpdateManager:
scmd = shell_command.build_shell_command(cmd, None)
return await scmd.run_with_response(timeout)
async def github_request(self, url, is_download=False):
cto = rto = 5.
content_type = "application/vnd.github.v3+json"
if is_download:
content_type = "application/zip"
rto = 120.
timeout = cto + rto + 2.
request = HTTPRequest(url, headers={"Accept": content_type},
connect_timeout=cto, request_timeout=rto)
retries = 5
while True:
to = IOLoop.current().time() + timeout
async def _init_api_rate_limit(self):
url = "https://api.github.com/rate_limit"
while 1:
try:
fut = self.http_client.fetch(request)
resp = await tornado.gen.with_timeout(to, fut)
except Exception as e:
resp = await self.github_api_request(url, is_init=True)
core = resp['resources']['core']
self.gh_rate_limit = core['limit']
self.gh_limit_remaining = core['remaining']
self.gh_limit_reset_time = core['reset']
except Exception:
logging.exception("Error Initializing GitHub API Rate Limit")
await tornado.gen.sleep(30.)
else:
reset_time = time.ctime(self.gh_limit_reset_time)
logging.info(
"GitHub API Rate Limit Initialized\n"
f"Rate Limit: {self.gh_rate_limit}\n"
f"Rate Limit Remaining: {self.gh_limit_remaining}\n"
f"Rate Limit Reset Time: {reset_time}, "
f"Seconds Since Epoch: {self.gh_limit_reset_time}")
break
self.gh_init_evt.set()
async def github_api_request(self, url, etag=None, is_init=False):
if not is_init:
timeout = time.time() + 30.
try:
await self.gh_init_evt.wait(timeout)
except Exception:
raise self.server.error(
"Timeout while waiting for GitHub "
"API Rate Limit initialization")
if self.gh_limit_remaining == 0:
curtime = time.time()
if curtime < self.gh_limit_reset_time:
raise self.server.error(
f"GitHub Rate Limit Reached\nRequest: {url}\n"
f"Limit Reset Time: {time.ctime(self.gh_limit_remaining)}")
headers = {"Accept": "application/vnd.github.v3+json"}
if etag is not None:
headers['If-None-Match'] = etag
retries = 5
while retries:
try:
resp = await self.http_client.fetch(
url, headers=headers, connect_timeout=5.,
request_timeout=5., raise_error=False)
except Exception:
retries -= 1
msg = f"Error Processing GitHub API request: {url}"
if not retries:
raise self.server.error(msg)
logging.exception(msg)
await tornado.gen.sleep(1.)
continue
etag = resp.headers.get('etag', None)
if etag is not None:
if etag[:2] == "W/":
etag = etag[2:]
logging.info(
"GitHub API Request Processed\n"
f"URL: {url}\n"
f"Response Code: {resp.code}\n"
f"Response Reason: {resp.reason}\n"
f"ETag: {etag}")
if resp.code == 403:
raise self.server.error(
f"Forbidden GitHub Request: {resp.reason}")
elif resp.code == 304:
logging.info(f"Github Request not Modified: {url}")
return None
if resp.code != 200:
retries -= 1
if not retries:
raise
logging.info(f"Github request error, retrying: {e}")
raise self.server.error(
f"Github Request failed: {resp.code} {resp.reason}")
logging.info(
f"Github request error, {retries} retries remaining")
await tornado.gen.sleep(1.)
continue
if is_download:
return resp.body
# Update rate limit on return success
if 'X-Ratelimit-Limit' in resp.headers and not is_init:
self.gh_rate_limit = int(resp.headers['X-Ratelimit-Limit'])
self.gh_limit_remaining = int(
resp.headers['X-Ratelimit-Remaining'])
self.gh_limit_reset_time = float(
resp.headers['X-Ratelimit-Reset'])
decoded = json.loads(resp.body)
decoded['etag'] = etag
return decoded
async def http_download_request(self, url):
retries = 5
while retries:
try:
resp = await self.http_client.fetch(
url, headers={"Accept": "application/zip"},
connect_timeout=5., request_timeout=120.)
except Exception:
retries -= 1
logging.exception("Error Processing Download")
if not retries:
raise
await tornado.gen.sleep(1.)
continue
return resp.body
def notify_update_response(self, resp, is_complete=False):
resp = resp.strip()
if isinstance(resp, bytes):
@@ -195,13 +278,20 @@ class GitUpdater:
self.execute_cmd = umgr.execute_cmd
self.execute_cmd_with_response = umgr.execute_cmd_with_response
self.notify_update_response = umgr.notify_update_response
self.github_request = umgr.github_request
distro = umgr.distro
config = umgr.config
self.repo_info = config[f"repo_info {name}"].get_options()
self.dist_info = config[f"dist_info {distro} {name}"].get_options()
self.name = name
self.repo_path = path
self.env = env
self.version = self.cur_hash = self.remote_hash = "?"
self.version = self.cur_hash = "?"
self.remote_version = self.remote_hash = "?"
self.init_evt = Event()
self.is_valid = self.is_dirty = False
self.debug = umgr.repo_debug
self.remote = "origin"
self.branch = "master"
self.is_valid = self.is_dirty = self.detached = False
IOLoop.current().spawn_callback(self.refresh)
def _get_version_info(self):
@@ -244,67 +334,101 @@ class GitUpdater:
if self.init_evt.is_set():
return
if timeout is not None:
to = IOLoop.current().time() + timeout
await self.init_evt.wait(to)
timeout = IOLoop.current().time() + timeout
await self.init_evt.wait(timeout)
async def refresh(self):
await self._check_local_version()
await self._check_remote_version()
await self._check_version()
self.init_evt.set()
async def _check_local_version(self):
self.is_valid = False
self.cur_hash = "?"
async def _check_version(self, need_fetch=True):
self.is_valid = self.detached = False
self.cur_hash = self.branch = self.remote = "?"
self.version = self.remote_version = "?"
try:
branch = await self.execute_cmd_with_response(
f"git -C {self.repo_path} rev-parse --abbrev-ref HEAD")
origin = await self.execute_cmd_with_response(
f"git -C {self.repo_path} remote get-url origin")
hash = await self.execute_cmd_with_response(
blist = await self.execute_cmd_with_response(
f"git -C {self.repo_path} branch --list")
if blist.startswith("fatal:"):
self._log_info(f"Invalid git repo at path '{self.repo_path}'")
return
branch = None
for b in blist.split("\n"):
b = b.strip()
if b[0] == "*":
branch = b[2:]
break
if branch is None:
self._log_info(
"Unable to retreive current branch from branch list\n"
f"{blist}")
return
if "HEAD detached" in branch:
bparts = branch.split()[-1].strip("()")
self.remote, self.branch = bparts.split("/")
self.detached = True
else:
self.branch = branch.strip()
self.remote = await self.execute_cmd_with_response(
f"git -C {self.repo_path} config --get"
f" branch.{self.branch}.remote")
if need_fetch:
await self.execute_cmd(
f"git -C {self.repo_path} fetch {self.remote} --prune -q",
retries=3)
remote_url = await self.execute_cmd_with_response(
f"git -C {self.repo_path} remote get-url {self.remote}")
cur_hash = await self.execute_cmd_with_response(
f"git -C {self.repo_path} rev-parse HEAD")
remote_hash = await self.execute_cmd_with_response(
f"git -C {self.repo_path} rev-parse "
f"{self.remote}/{self.branch}")
repo_version = await self.execute_cmd_with_response(
f"git -C {self.repo_path} describe --always "
"--tags --long --dirty")
remote_version = await self.execute_cmd_with_response(
f"git -C {self.repo_path} describe {self.remote}/{self.branch}"
" --always --tags --long")
except Exception:
self._log_exc("Error retreiving git info")
return
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}'")
versions = []
for ver in [repo_version, remote_version]:
tag_version = "?"
ver_match = re.match(r"v\d+\.\d+\.\d-\d+", ver)
if ver_match:
tag_version = ver_match.group()
versions.append(tag_version)
self.version, self.remote_version = versions
self.cur_hash = cur_hash.strip()
self.remote_hash = remote_hash.strip()
self._log_info(
f"Repo Detected:\nPath: {self.repo_path}\nRemote: {self.remote}\n"
f"Branch: {self.branch}\nRemote URL: {remote_url}\n"
f"Current SHA: {self.cur_hash}\n"
f"Remote SHA: {self.remote_hash}\nVersion: {self.version}\n"
f"Remote Version: {self.remote_version}\n"
f"Is Dirty: {self.is_dirty}\nIs Detached: {self.detached}")
if self.debug:
self.is_valid = True
self._log_info("Debug enabled, bypassing official repo check")
elif self.branch == "master" and self.remote == "origin":
if self.detached:
self._log_info("Detached HEAD detected, repo invalid")
return
remote_url = remote_url.lower()
if remote_url[-4:] != ".git":
remote_url += ".git"
if remote_url == self.repo_info['origin']:
self.is_valid = True
self._log_info("Validity check for git repo passed")
else:
self._log_info("Git repo not on master branch")
self._log_info(f"Invalid git origin url '{remote_url}'")
else:
self._log_info(f"Invalid git repo at path '{self.repo_path}'")
async def _check_remote_version(self):
repo_url = REPO_DATA[self.name]['repo_url']
try:
branch_info = await self.github_request(repo_url)
except Exception:
raise self._log_exc(f"Error retreiving github info")
commit_hash = branch_info.get('commit', {}).get('sha', None)
if commit_hash is None:
self.is_valid = False
self.upstream_version = "?"
raise self._log_exc(f"Invalid github response", False)
self._log_info(f"Received latest commit hash: {commit_hash}")
self.remote_hash = commit_hash
self._log_info(
"Git repo not on offical remote/branch: "
f"{self.remote}/{self.branch}")
async def update(self, update_deps=False):
if not self.is_valid:
@@ -312,14 +436,21 @@ class GitUpdater:
if self.is_dirty:
raise self._log_exc(
"Update aborted, repo is has been modified", False)
if self.remote_hash == "?":
await self._check_remote_version()
if self.remote_hash == self.cur_hash:
# No need to update
return
self._notify_status("Updating Repo...")
try:
await self.execute_cmd(f"git -C {self.repo_path} pull -q")
if self.detached:
await self.execute_cmd(
f"git -C {self.repo_path} fetch {self.remote} -q",
retries=3)
await self.execute_cmd(
f"git -C {self.repo_path} checkout"
f" {self.remote}/{self.branch} -q")
else:
await self.execute_cmd(
f"git -C {self.repo_path} pull -q", retries=3)
except Exception:
raise self._log_exc("Error running 'git pull'")
# Check Semantic Versions
@@ -330,8 +461,10 @@ class GitUpdater:
if update_deps:
await self._install_packages()
await self._update_virtualenv(need_env_rebuild)
elif need_env_rebuild:
await self._update_virtualenv(True)
# Refresh local repo state
await self._check_local_version()
await self._check_version(need_fetch=False)
if self.name == "moonraker":
# Launch restart async so the request can return
# before the server restarts
@@ -344,7 +477,7 @@ class GitUpdater:
async def _install_packages(self):
# Open install file file and read
inst_script = REPO_DATA[self.name]['install_script']
inst_script = self.dist_info['install_script']
inst_path = os.path.join(self.repo_path, inst_script)
if not os.path.isfile(inst_path):
self._log_info(f"Unable to open install script: {inst_path}")
@@ -374,9 +507,9 @@ class GitUpdater:
async def _update_virtualenv(self, rebuild_env=False):
# Update python dependencies
bin_dir = os.path.dirname(self.env)
env_path = os.path.normpath(os.path.join(bin_dir, ".."))
if rebuild_env:
env_path = os.path.normpath(os.path.join(bin_dir, ".."))
env_args = REPO_DATA[self.name]['venv_args']
env_args = self.repo_info['venv_args']
self._notify_status(f"Creating virtualenv at: {env_path}...")
if os.path.exists(env_path):
shutil.rmtree(env_path)
@@ -388,19 +521,8 @@ class GitUpdater:
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'])
self.repo_path, self.repo_info['requirements'])
if not os.path.isfile(reqs):
self._log_exc(f"Invalid path to requirements_file '{reqs}'")
return
@@ -412,6 +534,31 @@ class GitUpdater:
retries=3)
except Exception:
self._log_exc("Error updating python requirements")
self._install_python_dist_requirements(env_path)
def _install_python_dist_requirements(self, env_path):
dist_reqs = self.dist_info.get('python_dist_packages', None)
if dist_reqs is None:
return
dist_reqs = [r.strip() for r in dist_reqs.split("\n")
if r.strip()]
dist_path = self.dist_info['python_dist_path']
site_path = os.path.join(env_path, self.dist_info['env_package_path'])
for pkg in dist_reqs:
for f in os.listdir(dist_path):
if f.startswith(pkg):
src = os.path.join(dist_path, f)
dest = os.path.join(site_path, f)
self._notify_status(f"Linking to dist package: {pkg}")
if os.path.islink(dest):
os.remove(dest)
elif os.path.exists(dest):
self._notify_status(
f"Error symlinking dist package: {pkg}, "
f"file already exists: {dest}")
continue
os.symlink(src, dest)
break
async def restart_service(self):
self._notify_status("Restarting Service...")
@@ -422,26 +569,54 @@ class GitUpdater:
def get_update_status(self):
return {
'remote_alias': self.remote,
'branch': self.branch,
'version': self.version,
'remote_version': self.remote_version,
'current_hash': self.cur_hash,
'remote_hash': self.remote_hash,
'is_dirty': self.is_dirty,
'is_valid': self.is_valid}
'is_valid': self.is_valid,
'detached': self.detached,
'debug_enabled': self.debug}
class PackageUpdater:
def __init__(self, umgr):
self.server = umgr.server
self.execute_cmd = umgr.execute_cmd
self.execute_cmd_with_response = umgr.execute_cmd_with_response
self.notify_update_response = umgr.notify_update_response
self.available_packages = []
self.init_evt = Event()
IOLoop.current().spawn_callback(self.refresh)
def refresh(self):
# TODO: We should be able to determine if packages need to be
# updated here
pass
async def refresh(self):
# TODO: Use python-apt python lib rather than command line for updates
try:
await self.execute_cmd(f"{APT_CMD} update", timeout=300.)
res = await self.execute_cmd_with_response(
"apt list --upgradable")
except Exception:
logging.exception("Error Refreshing System Packages")
else:
pkg_list = [p.strip() for p in res.split("\n") if p.strip()]
if pkg_list:
pkg_list = pkg_list[2:]
self.available_packages = [p.split("/", maxsplit=1)[0]
for p in pkg_list]
pkg_list = "\n".join(self.available_packages)
logging.info(
f"Detected {len(self.available_packages)} package updates:"
f"\n{pkg_list}")
self.init_evt.set()
async def check_initialized(self, timeout=None):
pass
if self.init_evt.is_set():
return
if timeout is not None:
timeout = IOLoop.current().time() + timeout
await self.init_evt.wait(timeout)
async def update(self, *args):
self.notify_update_response("Updating packages...")
@@ -452,18 +627,26 @@ class PackageUpdater:
f"{APT_CMD} upgrade --yes", timeout=3600., notify=True)
except Exception:
raise self.server.error("Error updating system packages")
self.available_packages = []
self.notify_update_response("Package update finished...",
is_complete=True)
def get_update_status(self):
return {
'package_count': len(self.available_packages),
'package_list': self.available_packages
}
class ClientUpdater:
def __init__(self, umgr, repo, path):
self.umgr = umgr
self.server = umgr.server
self.github_request = umgr.github_request
self.notify_update_response = umgr.notify_update_response
self.repo = repo.strip().strip("/")
self.name = self.repo.split("/")[-1]
self.path = path
self.version = self.remote_version = self.dl_url = "?"
self.etag = None
self.init_evt = Event()
self._get_local_version()
logging.info(f"\nInitializing Client Updater: '{self.name}',"
@@ -482,8 +665,8 @@ class ClientUpdater:
if self.init_evt.is_set():
return
if timeout is not None:
to = IOLoop.current().time() + timeout
await self.init_evt.wait(to)
timeout = IOLoop.current().time() + timeout
await self.init_evt.wait(timeout)
async def refresh(self):
# Local state
@@ -492,16 +675,21 @@ class ClientUpdater:
# Remote state
url = f"https://api.github.com/repos/{self.repo}/releases/latest"
try:
result = await self.github_request(url)
result = await self.umgr.github_api_request(url, etag=self.etag)
except Exception:
logging.exception(f"Client {self.repo}: Github Request Error")
result = {}
if result is None:
# No change, update not necessary
return None
self.etag = result.get('etag', None)
self.remote_version = result.get('name', "?")
release_assets = result.get('assets', [{}])[0]
self.dl_url = release_assets.get('browser_download_url', "?")
logging.info(
f"Github client Info Received: {self.name}, "
f"version: {self.remote_version} "
f"Github client Info Received:\nRepo: {self.name}\n"
f"Local Version: {self.version}\n"
f"Remote Version: {self.remote_version}\n"
f"url: {self.dl_url}")
self.init_evt.set()
@@ -521,7 +709,7 @@ class ClientUpdater:
shutil.rmtree(self.path)
os.mkdir(self.path)
self.notify_update_response(f"Downloading Client: {self.name}")
archive = await self.github_request(self.dl_url, is_download=True)
archive = await self.umgr.http_download_request(self.dl_url)
with zipfile.ZipFile(io.BytesIO(archive)) as zf:
zf.extractall(self.path)
self.version = self.remote_version
@@ -529,7 +717,7 @@ class ClientUpdater:
if not os.path.exists(version_path):
with open(version_path, "w") as f:
f.write(self.version)
self.notify_update_response(f"Client Updated Finished: {self.name}",
self.notify_update_response(f"Client Update Finished: {self.name}",
is_complete=True)
def get_update_status(self):
+24
View File
@@ -0,0 +1,24 @@
# Supplemental configuration for Moonraker's Update Manager
# plugin. This file should not be modified.
[repo_info moonraker]
origin: https://github.com/arksine/moonraker.git
requirements: scripts/moonraker-requirements.txt
venv_args: -p python3
[repo_info klipper]
origin: https://github.com/kevinoconnor/klipper.git
requirements: scripts/klippy-requirements.txt
venv_args: -p python2
[dist_info debian moonraker]
install_script: scripts/install-moonraker.sh
python_dist_path: /usr/lib/python3/dist-packages
env_package_path: lib/python3.7/site-packages
python_dist_packages:
gpiod
[dist_info debian klipper]
install_script: scripts/install-octopi.sh
python_dist_path: /usr/lib/python2.7/dist-packages
env_package_path: lib/python2.7/site-packages
+1 -1
View File
@@ -1,2 +1,2 @@
env_version=0.2.4
env_version=0.2.6
deps_version=0.2.2