Unverified Commit 4b95a990 authored by Massimiliano Adamo's avatar Massimiliano Adamo
Browse files

minor

parent a99b69e3
......@@ -17,8 +17,12 @@ LATEST_TAG=$(git describe --tags $(git rev-list --tags --max-count=1))
PROG_VERSION=${LATEST_TAG:1}
git checkout $LATEST_TAG
pandoc -o README.txt --to=plain README.md
fpm -f -t deb -n ${PROG_NAME} -v $PROG_VERSION --maintainer "$EMAIL" --vendor "$EMAIL" \
-a all --description "$DESCRIPTION" --config-files etc/${PROG_NAME}.ini \
-p deb/${PROG_NAME}_${PROG_VERSION}_all.deb \
-d python3-docopt -d python3-packaging -s dir ${PROG_NAME}.ini=/etc/${PROG_NAME}.ini \
${PROG_NAME}.py=/usr/bin/${PROG_NAME}.py README.md=usr/share/doc/${PROG_NAME}/README.md
${PROG_NAME}.py=/usr/bin/${PROG_NAME}.py README.txt=usr/share/doc/${PROG_NAME}/README.txt
rm -f *.txt
\ No newline at end of file
......@@ -5,11 +5,11 @@
#
# If the running kernel does not belong to the list of the latest kernels,
# obtained with the "count" option, then "count + 1" kernels will be kept.
# obtained with the option "count", then the script will keep "count + 1" kernels.
count = 2
# prefix comes after the version number
kernel_prefixes = linux-tools,linux-headers,linux-modules, linux-modules-extra, linux-image, linux-image-unsigned
kernel_prefixes = linux-tools, linux-headers, linux-modules, linux-modules-extra, linux-image, linux-image-unsigned
# suffix come before the version number
kernel_suffixes = generic, aws
......@@ -2,7 +2,9 @@
#
"""
Remove intermediates and unused kernels from Ubuntu
Please check /etc/ubuntu-kernel-cleanup.ini for tweaking & information
For more information, please check inside:
- /etc/ubuntu-kernel-cleanup.ini
- /share/doc/ubuntu-kernel-cleanup/README.txt
Usage:
remove-ubuntu-kernels.py (--real-run | --dry-run)
......@@ -33,10 +35,10 @@ except ModuleNotFoundError as err:
def get_packages_list(pkg_match):
"""
run a shell command like this:
run a shell command like this one:
dpkg --list linux-image-[1-9]* | awk '/^ii /&&/linux-image-/{print $2}'
and create a sorted list of installed kernels.
Or if we need the version only:
Or if we need the version only it could be:
dpkg-query -f '${Status} ${Version}\n' -W linux-image-[1-9]* | awk '/ok installed/{print $NF}'
"""
installed = sp.Popen(
......@@ -46,40 +48,44 @@ def get_packages_list(pkg_match):
)
installed_out, _ = installed.communicate()
installed_list = installed_out.decode('utf-8').split('\n')
# delete empty items
kernels = [item for item in installed_list if item != '']
kernels = [x for x in installed_list if x != ''] # delete empty items
kernel_versions = [get_version(item) for item in kernels]
# sort by version and unique
return sorted(list(set(kernel_versions)), key=LooseVersion)
def remove_pkg(version_number, prefix, execution_type):
""" remove given package """
def process_packages(version_number, prefix, execution_type):
""" process package for removal """
for suffix in KERNEL_SUFFIXES:
pkg = "{}-{}{}".format(prefix, version_number, suffix)
if execution_type == 'real':
CACHE.update()
CACHE.open()
try:
# maybe this package does not exist in the DB
CACHE[pkg].is_installed
CACHE[pkg].is_installed # maybe the package does not exist
except KeyError:
pass
else:
if CACHE[pkg].is_installed:
if execution_type == 'real':
CACHE[pkg].mark_delete(True, True)
try:
CACHE.commit()
except Exception as err: # pylint: disable=W0703
print("Package removal failed [{err}]".format(
err=str(err)))
finally:
CACHE.close()
remove_package(pkg)
else:
print('Would have removed {} (noop)'.format(pkg))
def remove_package(pkg_name):
""" remove package """
CACHE[pkg_name].mark_delete(True, True)
try:
CACHE.commit()
except Exception as err: # pylint: disable=W0703
print("Package removal failed [{err}]".format(
err=str(err)))
finally:
CACHE.close()
def get_version(full_pkg_name):
"""
get version number from the full package name
......@@ -92,21 +98,21 @@ if __name__ == '__main__':
if os.geteuid() != 0:
print("You need to have root privileges to run this script")
print("Please try again, this time using 'sudo'. Exiting.")
print("Please try again, using 'sudo'. Exiting.")
os.sys.exit()
CFG_ONE = os.path.join(
os.path.expanduser('~'), ".ubuntu-kernel-cleanup.ini")
CFG_TWO = '/etc/ubuntu-kernel-cleanup.ini'
if not os.path.isfile(CFG_ONE) and not os.path.isfile(CFG_TWO):
INIFILE = 'ubuntu-kernel-cleanup.ini'
INIFILE_ONE = os.path.join('/etc', INIFILE)
INIFILE_TWO = os.path.join(os.path.expanduser('~'), ".{}".format(INIFILE))
if not os.path.isfile(INIFILE_ONE) and not os.path.isfile(INIFILE_TWO):
print("you need to create either {} or {}.\nGiving up & waiting for better days to come")
os.sys.exit()
CONFIG = configparser.RawConfigParser()
CONFIG.read([CFG_ONE, CFG_TWO])
CONFIG.read([INIFILE_ONE, INIFILE_TWO])
try:
KERNEL_PREFIXES = CONFIG.get(
'ubuntu-kernel-cleanup', 'kernel_prefixes').replace(' ', '').split(',')
'ubuntu-kernel-cleanup', 'kernel_prefixes'
).replace(' ', '').split(',')
except configparser.NoOptionError:
print('could not find an array option for "kernel_prefixes". Exiting')
os.sys.exit()
......@@ -142,32 +148,33 @@ if __name__ == '__main__':
kern_list = get_packages_list('linux-image-')
for kern_count in list(range(COUNT)):
# do we still have kernels in the list?
if len(kern_list) > 1:
latest_kernel = kern_list[-1]
if parse(running_kernel) < parse(latest_kernel):
# keep only items not containing the latest version
sanitized_kernel_list = [
item for item in kern_list if latest_kernel != item]
else:
# we are running the latest kernel
sanitized_kernel_list = kern_list
del kern_list[-1]
if len(kern_list) > COUNT:
for kern_count in list(range(COUNT)):
# do we still have kernels in the list?
if len(kern_list) > 1:
latest_kernel = kern_list[-1]
if parse(running_kernel) < parse(latest_kernel):
# keep only items not containing the latest version
sanitized_kernel_list = [
item for item in kern_list if latest_kernel != item]
else:
# we are running the latest kernel
sanitized_kernel_list = kern_list
del kern_list[-1]
try:
sanitized_kernel_list
except NameError:
pass
else:
# delete running kernel package from list
purged_list = [
item for item in sanitized_kernel_list if running_kernel not in item]
# uninstall packages from list
for kernel_pkg in KERNEL_PREFIXES:
for kernel_version in purged_list:
remove_pkg(kernel_version, kernel_pkg, EXECUTION)
try:
sanitized_kernel_list
except NameError:
pass
else:
# delete running kernel package from list
purged_list = [
item for item in sanitized_kernel_list if running_kernel not in item]
# uninstall packages from list
for kernel_pkg in KERNEL_PREFIXES:
for kernel_version in purged_list:
process_packages(kernel_version, kernel_pkg, EXECUTION)
CACHE.close() # it returns always true... keeps closing :)
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment