-
Notifications
You must be signed in to change notification settings - Fork 198
/
Copy pathzypper.py
executable file
·274 lines (217 loc) · 7.9 KB
/
zypper.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
#!/usr/bin/env python3
"""
Description: Expose metrics from zypper updates and patches.
The script can take 2 arguments: `--more` and `--less`.
The selection of the arguments change how many informations are going to be printed.
The `--more` is by default.
Examples:
zypper.py --less
zypper.py -m
Authors: Gabriele Puliti <[email protected]>
Bernd Shubert <[email protected]>
"""
import argparse
import subprocess
import os
import sys
from collections.abc import Sequence
from prometheus_client import CollectorRegistry, Gauge, Info, generate_latest
REGISTRY = CollectorRegistry()
NAMESPACE = "zypper"
def __print_pending_data(data, fields, info, filters=None):
filters = filters or {}
if len(data) == 0:
field_str = ",".join([f'{name}=""' for _, name in fields])
info.info({field_str: '0'})
else:
for package in data:
check = all(package.get(k) == v for k, v in filters.items())
if check:
field_str = ",".join([f'{name}="{package[field]}"' for field, name in fields])
info.info({field_str: '1'})
def print_pending_updates(data, all_info, filters=None):
if all_info:
fields = [("Repository", "repository"),
("Name", "package-name"),
("Available Version",
"available-version")]
else:
fields = [("Repository", "repository"),
("Name", "package-name")]
prefix = "zypper_update_pending"
description = (
"zypper package update available from repository. "
"(0 = not available, 1 = available)"
)
info = Info(prefix, description)
__print_pending_data(data, fields, info, filters)
def print_pending_patches(data, all_info, filters=None):
if all_info:
fields = [("Repository", "repository"),
("Name", "patch-name"),
("Category", "category"),
("Severity", "severity"),
("Interactive", "interactive"),
("Status", "status")]
else:
fields = [("Repository", "repository"),
("Name", "patch-name"),
("Interactive", "interactive"),
("Status", "status")]
prefix = "zypper_patch_pending"
description = "zypper patch available from repository. (0 = not available , 1 = available)"
info = Info(prefix, description)
__print_pending_data(data, fields, info, filters)
def print_orphaned_packages(data, filters=None):
fields = [("Name", "package"),
("Version", "installed-version")]
prefix = "zypper_package_orphan"
description = "zypper packages with no update source (orphaned)"
info = Info(prefix, description)
__print_pending_data(data, fields, info, filters)
def print_data_sum(data, prefix, description, filters=None):
gauge = Gauge(prefix,
description,
namespace=NAMESPACE,
registry=REGISTRY)
filters = filters or {}
if len(data) == 0:
gauge.set(0)
else:
for package in data:
check = all(package.get(k) == v for k, v in filters.items())
if check:
gauge.inc()
def print_reboot_required():
needs_restarting_path = '/usr/bin/needs-restarting'
is_path_ok = os.path.isfile(needs_restarting_path) and os.access(needs_restarting_path, os.X_OK)
if is_path_ok:
prefix = "node_reboot_required"
description = (
"Node require reboot to activate installed updates or patches. "
"(0 = not needed, 1 = needed)"
)
info = Info(prefix, description)
result = subprocess.run(
[needs_restarting_path, '-r'],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
check=False)
if result.returncode == 0:
info.info({"node_reboot_required": "0"})
else:
info.info({"node_reboot_required": "1"})
def print_zypper_version():
result = subprocess.run(
['/usr/bin/zypper', '-V'],
stdout=subprocess.PIPE,
check=False).stdout.decode('utf-8')
info = Info("zypper_version", "zypper installed package version")
info.info({"zypper_version": result.split()[1]})
def __extract_data(raw, fields):
raw_lines = raw.splitlines()[2:]
extracted_data = []
for line in raw_lines:
parts = [part.strip() for part in line.split('|')]
if len(parts) >= max(fields.values()) + 1:
extracted_data.append({
field: parts[index] for field, index in fields.items()
})
return extracted_data
def stdout_zypper_command(command):
result = subprocess.run(
command,
stdout=subprocess.PIPE,
check=False
)
if result.returncode != 0:
raise RuntimeError(f"zypper returned exit code {result.returncode}: {result.stderr}")
return result.stdout.decode('utf-8')
def extract_lu_data(raw: str):
fields = {
"Repository": 1,
"Name": 2,
"Current Version": 3,
"Available Version": 4,
"Arch": 5
}
return __extract_data(raw, fields)
def extract_lp_data(raw: str):
fields = {
"Repository": 0,
"Name": 1,
"Category": 2,
"Severity": 3,
"Interactive": 4,
"Status": 5
}
return __extract_data(raw, fields)
def extract_orphaned_data(raw: str):
fields = {
"Name": 3,
"Version": 4
}
return __extract_data(raw, fields)
def __parse_arguments(argv):
parser = argparse.ArgumentParser()
parser.add_mutually_exclusive_group(required=False)
parser.add_argument(
"-m",
"--more",
dest="all_info",
action='store_true',
help="Print all the package infos",
)
parser.add_argument(
"-l",
"--less",
dest="all_info",
action='store_false',
help="Print less package infos",
)
parser.set_defaults(all_info=True)
return parser.parse_args(argv)
def main(argv: Sequence[str] | None = None) -> int:
args = __parse_arguments(argv)
data_zypper_lu = extract_lu_data(
stdout_zypper_command(['/usr/bin/zypper', '--quiet', 'lu'])
)
data_zypper_lp = extract_lp_data(
stdout_zypper_command(['/usr/bin/zypper', '--quiet', 'lp'])
)
data_zypper_orphaned = extract_orphaned_data(
stdout_zypper_command(['/usr/bin/zypper', '--quiet', 'pa', '--orphaned'])
)
print_pending_updates(data_zypper_lu,
args.all_info)
print_data_sum(data_zypper_lu,
"zypper_updates_pending_total",
"zypper packages updates available in total")
print_pending_patches(data_zypper_lp,
args.all_info)
print_data_sum(data_zypper_lp,
"zypper_patches_pending_total",
"zypper patches available total")
print_data_sum(data_zypper_lp,
"zypper_patches_pending_security_total",
"zypper patches available with category security total",
filters={'Category': 'security'})
print_data_sum(data_zypper_lp,
"zypper_patches_pending_security_important_total",
"zypper patches available with category security severity important total",
filters={'Category': 'security', 'Severity': 'important'})
print_data_sum(data_zypper_lp,
"zypper_patches_pending_reboot_total",
"zypper patches available which require reboot total",
filters={'Interactive': 'reboot'})
print_reboot_required()
print_zypper_version()
print_orphaned_packages(data_zypper_orphaned)
return 0
if __name__ == "__main__":
try:
main()
except Exception as e:
print("ERROR: {}".format(e), file=sys.stderr)
sys.exit(1)
print(generate_latest(REGISTRY).decode(), end="")