88# Authors: Kyle Fazzari <kyrofa@ubuntu.com>
99# Daniel Swarbrick <dswarbrick@debian.org>
1010
11- import apt
11+ import argparse
1212import collections
1313import contextlib
1414import os
15+ import apt
1516from prometheus_client import CollectorRegistry , Gauge , generate_latest
1617
1718_UpgradeInfo = collections .namedtuple ("_UpgradeInfo" , ["labels" , "count" ])
@@ -26,12 +27,12 @@ def _convert_candidates_to_upgrade_infos(candidates):
2627 )
2728 changes_dict ["," .join (origins )][candidate .architecture ] += 1
2829
29- changes_list = list ()
30+ changes_list = []
3031 for origin in sorted (changes_dict .keys ()):
3132 for arch in sorted (changes_dict [origin ].keys ()):
3233 changes_list .append (
3334 _UpgradeInfo (
34- labels = dict ( origin = origin , arch = arch ) ,
35+ labels = { " origin" : origin , " arch" : arch } ,
3536 count = changes_dict [origin ][arch ],
3637 )
3738 )
@@ -74,14 +75,14 @@ def _write_autoremove_pending(registry, cache):
7475 g .set (len (autoremovable_packages ))
7576
7677
77- def _write_reboot_required (registry ):
78+ def _write_reboot_required (registry , root_dir ):
7879 g = Gauge ('node_reboot_required' , "Node reboot is required for software updates." ,
7980 registry = registry )
80- g .set (int (os .path .isfile ('/ run/reboot-required' )))
81+ g .set (int (os .path .isfile (os . path . join ( root_dir , ' run/reboot-required') )))
8182
8283
83- def _main () :
84- cache = apt .cache .Cache ()
84+ def generate_metrics ( root_dir : str = '/' ) -> bytes :
85+ cache = apt .cache .Cache (rootdir = root_dir )
8586
8687 # First of all, attempt to update the index. If we don't have permission
8788 # to do so (or it fails for some reason), it's not the end of the world,
@@ -96,8 +97,20 @@ def _main():
9697 _write_pending_upgrades (registry , cache )
9798 _write_held_upgrades (registry , cache )
9899 _write_autoremove_pending (registry , cache )
99- _write_reboot_required (registry )
100- print (generate_latest (registry ).decode (), end = '' )
100+ _write_reboot_required (registry , root_dir )
101+
102+ return generate_latest (registry )
103+
104+
105+ def _main ():
106+ parser = argparse .ArgumentParser ()
107+ parser .add_argument ('-r' , '--root-dir' , dest = 'root_dir' , type = str , default = '/' ,
108+ help = "Set root directory to a different path than /" )
109+ args = parser .parse_args ()
110+
111+ metrics = generate_metrics (args .root_dir )
112+
113+ print (metrics .decode (), end = '' )
101114
102115
103116if __name__ == "__main__" :
0 commit comments