| 1 |
# SPDX-License-Identifier: LGPL-2.1-or-later |
| 2 |
import os |
| 3 |
import subprocess |
| 4 |
|
| 5 |
# get-timesync-backend - determine which NTP backend unit timedatectl |
| 6 |
# will likely enable. |
| 7 |
|
| 8 |
roots = ["/etc", "/run", "/usr/local", "/usr/lib", "/lib"] |
| 9 |
|
| 10 |
|
| 11 |
def gather_files(name, suffix): |
| 12 |
# This function creates a list of files in the same order that |
| 13 |
# systemd will read them in. |
| 14 |
# |
| 15 |
# First we collect all files in all root directories. Duplicates |
| 16 |
# are avoided by only storing files with a basename that hasn't |
| 17 |
# been seen yet. The roots are processed in order so that files |
| 18 |
# in /etc override identically named files in /usr, for example. |
| 19 |
# |
| 20 |
# The files are stored in a dict with their basename (such as |
| 21 |
# "10-chrony.list") as the key and their full pathname (such as |
| 22 |
# "/usr/lib/systemd/ntp-units.d/10-chrony.list") as the value. |
| 23 |
# |
| 24 |
# This arrangement allows for easy checks for duplicate basenames |
| 25 |
# while retaining access to the full pathname later when creating |
| 26 |
# the final result. |
| 27 |
# |
| 28 |
pathname_by_basename = {} |
| 29 |
for r in roots: |
| 30 |
dirname = os.path.join(r, name) |
| 31 |
if os.path.isdir(dirname): |
| 32 |
for basename in os.listdir(dirname): |
| 33 |
if basename.endswith(suffix) and basename not in pathname_by_basename: |
| 34 |
pathname_by_basename[basename] = os.path.join(dirname, basename) |
| 35 |
|
| 36 |
# Then we create a list of the full pathnames, sorted by their |
| 37 |
# basenames. |
| 38 |
# |
| 39 |
sorted_basenames = sorted(pathname_by_basename.keys()) |
| 40 |
return [pathname_by_basename[basename] for basename in sorted_basenames] |
| 41 |
|
| 42 |
|
| 43 |
def unit_exists(unit): |
| 44 |
load_state = subprocess.check_output(["systemctl", "show", "--value", "-p", "LoadState", unit], |
| 45 |
universal_newlines=True).strip() |
| 46 |
return load_state != "not-found" and load_state != "masked" |
| 47 |
|
| 48 |
|
| 49 |
def first_unit(files): |
| 50 |
for f in files: |
| 51 |
with open(f) as c: |
| 52 |
for ll in c.readlines(): |
| 53 |
w = ll.strip() |
| 54 |
if w != "" and not w.startswith("#") and unit_exists(w): |
| 55 |
return w |
| 56 |
return None |
| 57 |
|
| 58 |
|
| 59 |
unit = first_unit(gather_files("systemd/ntp-units.d", ".list")) |
| 60 |
|
| 61 |
if unit: |
| 62 |
print(unit) |