Alex | 0989ecf | 2022-03-29 13:43:21 -0500 | [diff] [blame] | 1 | # Author: Alex Savatieiev (osavatieiev@mirantis.com; a.savex@gmail.com) |
| 2 | # Copyright 2019-2022 Mirantis, Inc. |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 3 | import json |
Alex | 3ebc563 | 2019-04-18 16:47:18 -0500 | [diff] [blame] | 4 | import subprocess |
| 5 | import sys |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 6 | from multiprocessing.dummy import Pool |
| 7 | |
| 8 | |
| 9 | def shell(command): |
| 10 | _ps = subprocess.Popen( |
| 11 | command.split(), |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 12 | stdout=subprocess.PIPE, |
| 13 | stderr=subprocess.PIPE |
savex | 4448e13 | 2018-04-25 15:51:14 +0200 | [diff] [blame] | 14 | ).communicate()[0].decode() |
| 15 | |
| 16 | return _ps |
| 17 | |
| 18 | |
| 19 | def 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") |
| 37 | pkg_list = _list.splitlines() |
| 38 | pkg_list = [_pkg.split('/')[0] for _pkg in pkg_list[1:]] |
| 39 | |
| 40 | # threading pool |
| 41 | pool = Pool(10) |
| 42 | |
| 43 | result = pool.map(get_versions, pkg_list) |
| 44 | |
| 45 | # init pkg storage |
| 46 | pkgs = {} |
| 47 | for 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 | |
| 55 | buff = json.dumps(pkgs) |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 56 | if len(sys.argv) > 1 and sys.argv[1] == 'stdout': |
| 57 | sys.stdout.write(buff) |
| 58 | else: |
| 59 | print(buff) |