2018-07-19 17:30:09 -07:00
|
|
|
"""
|
|
|
|
|
Utilities for working with the apt package manager
|
|
|
|
|
"""
|
|
|
|
|
import os
|
|
|
|
|
import subprocess
|
2019-05-19 13:45:57 -07:00
|
|
|
from tljh import utils
|
2018-07-19 17:30:09 -07:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def trust_gpg_key(key):
|
|
|
|
|
"""
|
|
|
|
|
Trust given GPG public key.
|
|
|
|
|
|
|
|
|
|
key is a GPG public key (bytes) that can be passed to apt-key add via stdin.
|
|
|
|
|
"""
|
2018-07-19 18:38:58 -07:00
|
|
|
# If gpg2 doesn't exist, install it.
|
2021-11-03 23:55:34 +01:00
|
|
|
if not os.path.exists("/usr/bin/gpg2"):
|
|
|
|
|
install_packages(["gnupg2"])
|
|
|
|
|
utils.run_subprocess(["apt-key", "add", "-"], input=key)
|
2018-07-19 17:30:09 -07:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def add_source(name, source_url, section):
|
|
|
|
|
"""
|
|
|
|
|
Add a debian package source.
|
|
|
|
|
|
|
|
|
|
distro is determined from /etc/os-release
|
|
|
|
|
"""
|
|
|
|
|
# lsb_release is not installed in most docker images by default
|
2021-11-01 09:42:45 +01:00
|
|
|
distro = (
|
|
|
|
|
subprocess.check_output(
|
2021-11-03 23:55:34 +01:00
|
|
|
["/bin/bash", "-c", "source /etc/os-release && echo ${VERSION_CODENAME}"],
|
2021-11-01 09:42:45 +01:00
|
|
|
stderr=subprocess.STDOUT,
|
|
|
|
|
)
|
|
|
|
|
.decode()
|
|
|
|
|
.strip()
|
|
|
|
|
)
|
2021-11-03 23:55:34 +01:00
|
|
|
line = f"deb {source_url} {distro} {section}\n"
|
|
|
|
|
with open(os.path.join("/etc/apt/sources.list.d/", name + ".list"), "a+") as f:
|
2018-07-19 17:30:09 -07:00
|
|
|
# Write out deb line only if it already doesn't exist
|
2019-10-21 13:47:16 +03:00
|
|
|
f.seek(0)
|
|
|
|
|
if line not in f.read():
|
2018-07-19 17:30:09 -07:00
|
|
|
f.write(line)
|
|
|
|
|
f.truncate()
|
2021-11-03 23:55:34 +01:00
|
|
|
utils.run_subprocess(["apt-get", "update", "--yes"])
|
2018-07-19 17:30:09 -07:00
|
|
|
|
|
|
|
|
|
|
|
|
|
def install_packages(packages):
|
|
|
|
|
"""
|
|
|
|
|
Install debian packages
|
|
|
|
|
"""
|
2018-07-19 18:51:55 -07:00
|
|
|
# Check if an apt-get update is required
|
2021-11-03 23:55:34 +01:00
|
|
|
if len(os.listdir("/var/lib/apt/lists")) == 0:
|
|
|
|
|
utils.run_subprocess(["apt-get", "update", "--yes"])
|
2019-06-18 13:14:14 -07:00
|
|
|
env = os.environ.copy()
|
|
|
|
|
# Stop apt from asking questions!
|
2021-11-03 23:55:34 +01:00
|
|
|
env["DEBIAN_FRONTEND"] = "noninteractive"
|
|
|
|
|
utils.run_subprocess(["apt-get", "install", "--yes"] + packages, env=env)
|