blob: 687e9829f4ab28565f8419dd7ed8486f5597188b [file] [log] [blame]
Alex0989ecf2022-03-29 13:43:21 -05001# Author: Alex Savatieiev (osavatieiev@mirantis.com; a.savex@gmail.com)
2# Copyright 2019-2022 Mirantis, Inc.
savex4448e132018-04-25 15:51:14 +02003import json
Alex3ebc5632019-04-18 16:47:18 -05004import subprocess
5import sys
savex4448e132018-04-25 15:51:14 +02006from multiprocessing.dummy import Pool
7
8
9def shell(command):
10 _ps = subprocess.Popen(
11 command.split(),
Alex9a4ad212020-10-01 18:04:25 -050012 stdout=subprocess.PIPE,
13 stderr=subprocess.PIPE
savex4448e132018-04-25 15:51:14 +020014 ).communicate()[0].decode()
15
16 return _ps
17
18
19def get_versions(pkg):
20 # get the info for the package
21 _pkg_info = shell('apt-cache policy ' + pkg)
22
23 _installed = 'none'
24 _candidate = 'none'
25
26 # extract the installed and candidate
27 for line in _pkg_info.splitlines():
28 if line.find("Installed") > 0:
29 _installed = line.split(':', 1)[1].strip()
30 elif line.find("Candidate") > 0:
31 _candidate = line.split(':', 1)[1].strip()
32 return [pkg, _installed, _candidate, _pkg_info]
33
34
35# get list of packages
36_list = shell("apt list --installed")
37pkg_list = _list.splitlines()
38pkg_list = [_pkg.split('/')[0] for _pkg in pkg_list[1:]]
39
40# threading pool
41pool = Pool(10)
42
43result = pool.map(get_versions, pkg_list)
44
45# init pkg storage
46pkgs = {}
47for res in result:
48 _pkg = res[0]
49 if _pkg not in pkgs:
50 pkgs[_pkg] = {}
51 pkgs[_pkg]['installed'] = res[1]
52 pkgs[_pkg]['candidate'] = res[2]
53 pkgs[_pkg]['raw'] = res[3]
54
55buff = json.dumps(pkgs)
Alex9a4ad212020-10-01 18:04:25 -050056if len(sys.argv) > 1 and sys.argv[1] == 'stdout':
57 sys.stdout.write(buff)
58else:
59 print(buff)