-
Notifications
You must be signed in to change notification settings - Fork 0
/
check_mount.py
367 lines (319 loc) · 11.4 KB
/
check_mount.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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
"""
An Icinga/Nagios-compatible plugin for checking mount points.
Example Usage
-------------
Insist on 15 mounts being present, and return WARNING or CRITICAL respectively
if the number of mounts is above or below that number:
check-mount -w15:15
check-mount -c15:15
Insist on a minimum of 3 and maximum of 5 mounts of type NFS and EXT4:
check-mount -t nfs -t ext4 -w 3:5
Make sure that three specific mounts are present. This may be
counterintuitive, but the warning range requires that there be precisely one
of each.
check-mount -p /home -p /var -p /opt -w1:1
"""
# ==============================================================================
# Copyright 2019-2022 Matthew Pounsett <[email protected]>
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ==============================================================================
import argparse
import inspect
import logging
import os
import platform
import re
import subprocess
import sys
from typing import Dict, List
import nagiosplugin
__version__ = "1.1.0"
_LOG = logging.getLogger('nagiosplugin')
IGNORE_TYPES = [
'autofs',
'bpf',
'cgroup',
'cgroup2',
'debugfs',
'devpts',
'devtmpfs',
'hugetlbfs',
'mqueue',
'proc',
'pstore',
'securityfs',
'sysfs',
'tmpfs',
]
MOUNT_PATH = {
'Darwin': '/sbin/mount',
'FreeBSD': '/sbin/mount',
'Linux': '/bin/mount',
}.get(platform.system(), '/sbin/mount')
class Mount(nagiosplugin.Resource):
"""
Domain model: Mount points.
Determines if the requested mount points are present. The `probe` method
returns a list of all mounts which match the selection criteria.
"""
name = 'Mount'
def __init__(self,
paths: List[str] = None, types: List[str] = None,
mount_path: str = MOUNT_PATH):
"""Create a Mount object."""
if paths and types:
raise ValueError("paths and types cannot both be set")
if paths is not None:
self.paths = paths
else:
self.paths = []
if types is not None:
self.types = [mount_type.lower() for mount_type in types]
else:
self.types = []
self.mount_path = mount_path
@classmethod
def process_mount_line(cls, text) -> Dict:
"""Abstract method that should be replaced by subclassing."""
raise NotImplementedError(
"Mount must be subclassed and process_mount_line overridden"
)
@classmethod
def process_mount_data(cls, text):
"""
Process mount output into a native data structure.
This method takes one or more lines of output from mount(8) as a
single string, splits it up into lines, and then passes those lines to
the appropriate processing function to retrieve a native data
structure.
Returns a list of dictionaries.
"""
results = []
for line in text.decode().split(os.linesep):
line = line.strip()
if line == '':
continue
detail = cls.process_mount_line(line)
_LOG.debug("found mount: %s", detail)
results.append(detail)
return results
def get_mount_data(self):
"""Shell out to run mount(8), return the processed output."""
cmd = [
self.mount_path,
]
try:
with subprocess.Popen(cmd, stdout=subprocess.PIPE) as result:
return result.communicate()[0]
except OSError as err:
_LOG.error("mount execution failed: %s", err)
raise
except Exception as err:
_LOG.error("unknown error calling mount: %s", err)
raise
def probe(self):
"""Return all mount points matching the selection criteria."""
_LOG.debug('obtaining mount list from mount')
mount_class = MountFactory.get_mount_class()
mount_data = mount_class.process_mount_data(self.get_mount_data())
# If we have a list of paths, then we're checking that specific paths
# exist.
if self.paths:
targets = [mount['target'] for mount in mount_data]
for path in self.paths:
if path in targets:
_LOG.debug("mount %s present", path)
yield nagiosplugin.Metric(path, 1, context=path)
else:
_LOG.debug("mount %s missing", path)
yield nagiosplugin.Metric(path, 0, context=path)
# Otherwise, we're just counting mounts
else:
mount_count = 0
for mount in mount_data:
if self.types and mount['filesystem_type'] in self.types:
_LOG.debug("mount %s counted", mount['target'])
mount_count += 1
else:
if (
self.types
and mount['filesystem_type'] not in self.types
):
_LOG.debug(
"ignoring mount %s: not in user types list",
(mount['target'], mount['filesystem_type'])
)
continue
if mount['filesystem_type'] in IGNORE_TYPES:
_LOG.debug(
"ignoring mount %s: type in default ignore list",
(mount['target'], mount['filesystem_type'])
)
continue
_LOG.debug("mount %s counted", mount['target'])
mount_count += 1
yield nagiosplugin.Metric(
'total mounts', mount_count, min=0, context='mount'
)
class BSDMount(Mount):
"""
Domain model: Mount points.
Determines if the requested mount points are present. The `probe` method
returns a list of all mounts which match the selection criteria.
"""
@classmethod
def process_mount_line(cls, text) -> Dict:
"""Process a line of BSD-style mount output into a native structure."""
detail = {}
mount_regex = r"^(.+) on (.+) \((.*)\)$"
result = re.search(mount_regex, text)
if result is not None:
detail['source'] = result.group(1)
detail['target'] = result.group(2)
opts = result.group(3).split(', ')
detail['filesystem_type'] = opts.pop(0)
detail['options'] = opts
_LOG.debug("Got mount info: %s", detail)
return detail
class LinuxMount(Mount):
"""
Domain model: Mount points.
Determines if the requested mount points are present. The `probe` method
returns a list of all mounts which match the selection criteria.
"""
@classmethod
def process_mount_line(cls, text) -> Dict:
"""Process a line of Linux-style mount output into a dict."""
detail = {}
mount_regex = r"^(.+) on (.+) type (.+) \((.*)\)$"
result = re.search(mount_regex, text)
if result is not None:
detail['source'] = result.group(1)
detail['target'] = result.group(2)
detail['filesystem_type'] = result.group(3)
opts = result.group(4).split(', ')
detail['options'] = opts
_LOG.debug("Got mount info: %s", detail)
return detail
# No need for more methods in a factory class
# pylint: disable-next=too-few-public-methods
class MountFactory:
"""Returns the appropriate Mount subclass for the platform."""
@staticmethod
def get_mount_class(paths: List[str] = None,
types: List[str] = None,
mount_path: str = MOUNT_PATH) -> Mount:
"""
Return an instance of the appropriate Mount subclass.
Maps platform.system() to a dictionary of OS names mapped to Mount
subclasses.
"""
class_map = {
'Darwin': BSDMount,
'FreeBSD': BSDMount,
'Linux': LinuxMount,
}
os_name = platform.system()
try:
new_class = class_map[os_name]
except KeyError:
raise NotImplementedError(f"OS {os_name} not supported") from None
return new_class(paths, types, mount_path)
def parse_args(args=None) -> argparse.Namespace:
"""Parse cmdline arguments and return an argparse.Namespace object."""
args = args or sys.argv[1:]
parser = argparse.ArgumentParser(
description=inspect.cleandoc(
"""
"""
),
)
parser.add_argument(
'-w', '--warning',
metavar='RANGE',
default='',
help=(
'Generate warning state if number of mounts is outside this range'
),
)
parser.add_argument(
'-c', '--critical',
metavar='RANGE',
default='',
help=(
'Generate critical state if number of mounts is outside this range'
),
)
parser.add_argument(
'-p', '--path',
action='append',
metavar='PATH',
help=inspect.cleandoc(
"""
A mount point to check to ensure it is present. May be specified
more than once. This option is incompatible with --type.
"""
),
)
parser.add_argument(
'-t', '--type',
action='append',
metavar='TYPE',
help=inspect.cleandoc(
"""
Only check mounts of a particular type. If specified more than
once, the count of present mounts will include all mounts of all
types specified. This option is incompatible with --path.
"""
),
)
parser.add_argument(
'-M', '--mount-path',
default=MOUNT_PATH,
metavar='PATH',
help=f"Override the path to mount(8) [Default: {MOUNT_PATH}]",
)
parser.add_argument(
'-v', '--verbose',
action='count',
default=0,
help="Increase output verbosity (use up to 3 times).",
)
args = parser.parse_args(args)
# Do some basic tests
if args.path and args.type:
parser.error(
"--path and --type cannot be specified together."
)
if not os.access(args.mount_path, os.X_OK):
parser.error(f"mount not found at {args.mount_path}")
# all good... return the results
return args
@nagiosplugin.guarded
def main():
"""Run the check-mount script. This is the main entrypoint."""
args = parse_args()
if args.path:
contexts = [
nagiosplugin.ScalarContext(path, args.warning, args.critical) for
path in args.path
]
else:
contexts = [
nagiosplugin.ScalarContext('mount', args.warning, args.critical)
]
mount_class = MountFactory.get_mount_class(args.path, args.type,
args.mount_path)
check = nagiosplugin.Check(mount_class, *contexts)
check.main(verbose=args.verbose)