Skip to content

Commit

Permalink
fix: apply some small python cleanups
Browse files Browse the repository at this point in the history
  • Loading branch information
marcoceppi authored Jun 29, 2023
1 parent f9328d3 commit 69e42d0
Showing 1 changed file with 18 additions and 20 deletions.
38 changes: 18 additions & 20 deletions update-ublue
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
#!/usr/bin/python3
#!/usr/bin/env python3

import psutil
import notify2
Expand All @@ -14,16 +14,18 @@ battery_percent = 50
cpu_load = 50
"""

log = logging.getLogger(__name__)


def check_cpu_load(max_cpu_load):
# get load average percentage in last 5 minutes: https://psutil.readthedocs.io/en/latest/index.html?highlight=getloadavg
# get load average percentage in last 5 minutes: https://psutil.readthedocs.io/en/latest/index.html?highlight=getloadavg
cpu_load = psutil.getloadavg()[1] / psutil.cpu_count() * 100
return {"passed": cpu_load < max_cpu_load, "message": f"CPU load is above {max_cpu_load}%"}


def check_network_status():
network_status = psutil.net_if_stats()
# check each network interface
# check each network interface
network_up = False
for key in network_status.keys():
if key != "lo":
Expand All @@ -41,6 +43,7 @@ def check_battery_status(min_battery_percent):
battery_pass = (battery_status.percent > min_battery_percent or battery_status.power_plugged)
return {"passed": battery_pass, "message": f"Battery less than {min_battery_percent}%"}


def check_inhibitors(config):
min_battery_percent = float(config['checks']['battery_percent'])
max_cpu_load = float(config['checks']['cpu_load'])
Expand All @@ -51,38 +54,35 @@ def check_inhibitors(config):
check_cpu_load(max_cpu_load),
]

failures = []
update_checks_failed = False
log = " \nupdate failed to pass checks:"
for inhibitor_result in update_inhibitors:
if not inhibitor_result["passed"]:
update_checks_failed = True
log = log + f" \n {inhibitor_result['message']}"
failures.append(inhibitor_result['message'])

# log the failed update
# log the failed update
if update_checks_failed:
logger = logging.getLogger(__name__)
logger.info(log)
# notify systemd that the checks have failed, systemd will try to rerun the unit
exit(1)
return update_checks_failed
raise Exception(f"update failed to pass checks: \n{'\n - '.join(failures)}")


def load_config():
# load config values
# load config values
config_paths = [
os.path.expanduser('~/.config/ublue-updater/ublue-updater.conf'),
"/etc/ublue-updater/ublue-updater.conf",
"/usr/etc/ublue-updater/ublue-updater.conf"
]

# search for the right config
# search for the right config
config_path = ""
for path in config_paths:
if os.path.isfile(path):
config_path = path
break

# if there's no config, create one
# if there's no config, create one
if config_path == "":
config_path = config_paths[0]
os.makedirs(os.path.dirname(config_path))
Expand All @@ -108,25 +108,23 @@ def run_updates():
stderr=subprocess.STDOUT)

if out.returncode != 0:
logger = logging.getLogger(__name__)
logger.info(f"{full_path} returned error code: {out.returncode} \n Program output: \n {out.stdout}")
log.info(f"{full_path} returned error code: {out.returncode} \n Program output: \n {out.stdout}")

notify2.Notification(
"System Updater",
f"Error in update script: {file}, check logs for more info",
"notification-message-im").show()
else:
logger = logging.getLogger(__name__)
logger.info(f"could not execute file {full_path}")
log.info(f"could not execute file {full_path}")


def main():
# setup logging
# setup logging
logging.basicConfig(
format="[%(asctime)s] %(name)s:%(levelname)s | %(message)s",
level=os.getenv("UBLUE_LOG", default=logging.INFO),
)
# setup argparse
# setup argparse
parser = argparse.ArgumentParser()
parser.add_argument("-f","--force",action="store_true",
help="force manual update, skipping update checks")
Expand All @@ -136,7 +134,7 @@ def main():

if not args.force:
check_inhibitors(load_config())
# system checks passed
# system checks passed
n = notify2.Notification("System Updater","System passed checks, updating ...","notification-message-im")
n.show()

Expand Down

0 comments on commit 69e42d0

Please sign in to comment.