Skip to content

Commit 1bfce77

Browse files
committed
**Breaking change**: use mongosh instead of mongo binary
1 parent 9c1e0ee commit 1bfce77

File tree

5 files changed

+89
-50
lines changed

5 files changed

+89
-50
lines changed

README.md

Lines changed: 31 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -6,27 +6,32 @@
66
![Output of check_mongodb_size.py](docs/img/check_mongodb_size.png?raw=true "Output of check_mongodb_size.py")
77

88
## About
9-
* this repository contains a collection of Icinga / Nagios plugins to monitor a MongoDB database
10-
* tested with MongoDB 4.2, 4.4 and 5.0
11-
* Written for python3
12-
* Minimal dependencies (only required non-default library is `toml`)
9+
10+
- this repository contains a collection of Icinga / Nagios plugins to monitor a MongoDB database
11+
- tested with MongoDB 4.2, 4.4 and 5.0
12+
- Written for python3
13+
- Minimal dependencies (only required non-default library is `toml`)
1314

1415
## Documentation
16+
1517
* [check_mongodb_stats.py](docs/check_mongodb_stats.md)
1618
* [check_mongodb_dbsize.py](docs/check_mongodb_dbsize.md)
1719

1820
## Configuration
1921

2022
#### Python setup
21-
* Make sure python 3.x is installed on the machine
22-
* Install `toml` library
23-
* `pip3 install toml`
23+
24+
- Make sure python 3.x is installed on the machine
25+
- Install `toml` library
26+
- `pip3 install toml`
2427

2528
#### Configuring the database connection settings
26-
* For security reasons these plugins do not accept the connections parameters for the database as arguments
27-
* Instead the plugins reads the parametes from a hidden toml-formatted configuration file
28-
* Default: `/etc/nagios/.mdbservice`, use `--credentialfile=/path/to/your/file`for a non-default location
29-
* Ideally change the file owner and permissions of `.mdbservice` so that only the user executing the plugins can read the config file
29+
30+
- For security reasons these plugins do not accept the connections parameters for the database as arguments
31+
- Instead the plugins reads the parametes from a hidden toml-formatted configuration file
32+
- Default: `/etc/nagios/.mdbservice`, use `--credentialfile=/path/to/your/file`for a non-default location
33+
- Ideally change the file owner and permissions of `.mdbservice` so that only the user executing the plugins can read the config file
34+
3035
```toml
3136
[localhost]
3237
hostname="localhost"
@@ -35,19 +40,26 @@
3540
pw="secretpassword"
3641
authdb="admin"
3742
tls=true
43+
tlscafile="/etc/pki/ca-trust/extracted/pem/tls-ca-bundle.pem"
3844
```
3945

4046
##### Parameters
41-
* `[instancename]` : you can configure multiple connections within one `.mdbservice`-file. This config section name corresponds with the `--instance`-argument of the plugin
42-
* `hostname` : optional, defaults to `localhost`
43-
* `port` : optional, defaults to `27017`
44-
* `user` : optional
45-
* `pw` : optional
46-
* `authdb` : optional, defaults to `admin`
47-
* `tls` : `true`/`false`, defaults to `true`
47+
48+
- `[instancename]` : you can configure multiple connections within one `.mdbservice`\-file. This config section name corresponds with the `--instance`\-argument of the plugin
49+
- `hostname` : optional, defaults to `localhost`
50+
- `port` : optional, defaults to `27017`
51+
- `user` : optional
52+
- `pw` : optional
53+
- `authdb` : optional, defaults to `admin`
54+
- `tls` : `true`/`false`, defaults to `true`
55+
- `tlscafile` : Path to cacerts file for TLS certificate validation
56+
- `tls_allow_invalid_hostnames` : `true`/`false`, connect to MongoDB via TLS even if the CommonName/SubjectAlternativeName of the Cert does not match our Servername. Defaults to `false`
57+
- `tls_allow_invalid_certificates`: `true`/`false`, connect to MongoDB via TLS even if the TLS-Certificate is invalid (i.e. expired). Defaults to `false`
4858

4959
#### Configuring database use
50-
* Open a MongoDB DB shell, create a dedicated monitoring user and assign the `clusterMonitor` role
60+
61+
- Open a MongoDB DB shell, create a dedicated monitoring user and assign the `clusterMonitor` role
62+
5163
```java
5264
use admin
5365
db.createUser(
@@ -60,4 +72,3 @@
6072
}
6173
)
6274
```
63-

check_mongodb_dbsize.py

Lines changed: 23 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -15,11 +15,11 @@
1515
import sys
1616
import json
1717
from subprocess import run, PIPE
18-
from argparse import ArgumentParser
18+
from argparse import ArgumentParser, Namespace as Arguments
1919
from toml import load
2020

2121

22-
def get_args():
22+
def get_args() -> Arguments:
2323
""" Parse Arguments """
2424
parser = ArgumentParser(
2525
description="Icinga/Nagios plugin which checks the size of a \
@@ -47,8 +47,8 @@ def get_args():
4747

4848
miscopts = parser.add_argument_group('Miscellaneous options')
4949
miscopts.add_argument("--mongobin", required=False,
50-
help="Location of \"mongo\" binary", type=str, dest='mongoloc',
51-
default='/usr/bin/mongo')
50+
help="Location of \"mongosh\" binary", type=str, dest='mongoloc',
51+
default='/usr/bin/mongosh')
5252

5353
args = parser.parse_args()
5454
return args
@@ -70,7 +70,7 @@ def exit_plugin(returncode: int, output: str, perfdata: str):
7070
sys.exit(0)
7171

7272

73-
def convert_bytes_to_pretty(raw_bytes: int):
73+
def convert_bytes_to_pretty(raw_bytes: int) -> str:
7474
""" converts raw bytes into human readable output """
7575
if raw_bytes >= 1099511627776:
7676
output = f'{ round(raw_bytes / 1024 **4, 2) }TiB'
@@ -85,11 +85,11 @@ def convert_bytes_to_pretty(raw_bytes: int):
8585
return output
8686

8787

88-
def query_db(args, creds: dict):
88+
def query_db(args, creds: dict) -> dict:
8989
""" query instance statistics from MongoDB """
9090

9191
cmd = [args.mongoloc, f'{ creds["hostname"] }:{ creds["port"] }/{ args.db }',
92-
"--quiet", "--eval", "JSON.stringify(db.stats())"]
92+
"--quiet", "--eval", "EJSON.stringify(db.stats())"]
9393

9494
if creds["user"] != "" and creds["pw"] != "":
9595
# Append parameters for authentification
@@ -100,10 +100,20 @@ def query_db(args, creds: dict):
100100
cmd.append('--authenticationDatabase')
101101
cmd.append(creds["authdb"])
102102

103+
# Append parameter for TLS connection
103104
if creds["tls"] is True:
104-
# Append parameter for TLS connection
105105
cmd.append('--tls')
106106

107+
if creds.get("tlscafile") is not None:
108+
cmd.append('--tlsCAFile')
109+
cmd.append(f'{ creds["tlscafile"] }')
110+
111+
if creds["tls_allow_invalid_hostnames"] is True and creds["tls"] is True:
112+
cmd.append('--tlsAllowInvalidHostnames')
113+
114+
if creds["tls_allow_invalid_certificates"] is True and creds["tls"] is True:
115+
cmd.append('--tlsAllowInvalidCertificates')
116+
107117
result = run(cmd, shell=False, check=False, stdout=PIPE, stderr=PIPE)
108118

109119
# Check if command exited without error code
@@ -125,7 +135,7 @@ def query_db(args, creds: dict):
125135
return output
126136

127137

128-
def load_db_credentials(file: str, instance: str):
138+
def load_db_credentials(file: str, instance: str) -> dict:
129139
""" load MongoDB credentials from file """
130140

131141
try:
@@ -152,6 +162,10 @@ def load_db_credentials(file: str, instance: str):
152162
creds["authdb"] = "admin"
153163
if creds.get("tls") is None:
154164
creds["tls"] = True
165+
if creds.get("tls_allow_invalid_hostnames") is None:
166+
creds["tls_allow_invalid_hostnames"] = False
167+
if creds.get("tls_allow_invalid_certificates") is None:
168+
creds["tls_allow_invalid_certificates"] = False
155169

156170
return creds
157171

check_mongodb_stats.py

Lines changed: 25 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,11 @@
1616
import json
1717
from datetime import timedelta
1818
from subprocess import run, PIPE
19-
from argparse import ArgumentParser
19+
from argparse import ArgumentParser, Namespace as Arguments
2020
from toml import load
2121

2222

23-
def get_args():
23+
def get_args() -> Arguments:
2424
""" Parse Arguments """
2525
parser = ArgumentParser(
2626
description="Icinga/Nagios plugin which checks metrics of a \
@@ -34,8 +34,8 @@ def get_args():
3434
dest='instance', default='localhost')
3535
miscopts = parser.add_argument_group('Miscellaneous options')
3636
miscopts.add_argument("--mongobin", required=False,
37-
help="Location of \"mongo\" binary", type=str, dest='mongoloc',
38-
default='/usr/bin/mongo')
37+
help="Location of \"mongosh\" binary", type=str, dest='mongoloc',
38+
default='/usr/bin/mongosh')
3939

4040
args = parser.parse_args()
4141
return args
@@ -57,11 +57,11 @@ def exit_plugin(returncode: int, output: str, perfdata: str):
5757
sys.exit(0)
5858

5959

60-
def query_db(args, creds: dict):
60+
def query_db(args, creds: dict) -> dict:
6161
""" query instance statistics from MongoDB """
6262

6363
cmd = [args.mongoloc, f'{ creds["hostname"] }:{ creds["port"] }',
64-
"--quiet", "--eval", "JSON.stringify(db.serverStatus())"]
64+
"--quiet", "--eval", "EJSON.stringify(db.serverStatus())"]
6565

6666
if creds["user"] != "" and creds["pw"] != "":
6767
# Append parameters for authentification
@@ -72,10 +72,20 @@ def query_db(args, creds: dict):
7272
cmd.append('--authenticationDatabase')
7373
cmd.append(creds["authdb"])
7474

75+
# Append parameter for TLS connection
7576
if creds["tls"] is True:
76-
# Append parameter for TLS connection
7777
cmd.append('--tls')
7878

79+
if creds.get("tlscafile") is not None:
80+
cmd.append('--tlsCAFile')
81+
cmd.append(f'{ creds["tlscafile"] }')
82+
83+
if creds["tls_allow_invalid_hostnames"] is True and creds["tls"] is True:
84+
cmd.append('--tlsAllowInvalidHostnames')
85+
86+
if creds["tls_allow_invalid_certificates"] is True and creds["tls"] is True:
87+
cmd.append('--tlsAllowInvalidCertificates')
88+
7989
result = run(cmd, shell=False, check=False, stdout=PIPE, stderr=PIPE)
8090

8191
# Check if command exited without error code
@@ -93,7 +103,7 @@ def query_db(args, creds: dict):
93103
return output
94104

95105

96-
def load_db_credentials(file: str, instance: str):
106+
def load_db_credentials(file: str, instance: str) -> dict:
97107
""" load MongoDB credentials from file """
98108

99109
try:
@@ -120,6 +130,10 @@ def load_db_credentials(file: str, instance: str):
120130
creds["authdb"] = "admin"
121131
if creds.get("tls") is None:
122132
creds["tls"] = True
133+
if creds.get("tls_allow_invalid_hostnames") is None:
134+
creds["tls_allow_invalid_hostnames"] = False
135+
if creds.get("tls_allow_invalid_certificates") is None:
136+
creds["tls_allow_invalid_certificates"] = False
123137

124138
return creds
125139

@@ -146,9 +160,9 @@ def main():
146160
instance['conn_cur'] = int(stats['connections']['current'])
147161
instance['conn_avail'] = int(stats['connections']['available'])
148162
instance['conn_total'] = int(instance['conn_cur'] + instance['conn_avail'])
149-
instance['byte_in'] = int(stats['network']['bytesIn']['$numberLong'])
150-
instance['byte_out'] = int(stats['network']['bytesOut']['$numberLong'])
151-
instance['transactions'] = int(stats['transactions']['totalCommitted']['$numberLong'])
163+
instance['byte_in'] = int(stats['network']['bytesIn'])
164+
instance['byte_out'] = int(stats['network']['bytesOut'])
165+
instance['transactions'] = int(stats['transactions']['totalCommitted'])
152166
instance['mem_virt'] = int(stats['mem']['virtual'])
153167
instance['mem_resident'] = int(stats['mem']['resident'])
154168

docs/check_mongodb_dbsize.md

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44

55
## Usage
66
```
7-
usage: check_mongodb_dbsize.py [-h] --database DB [--wsize WSIZE] [--csize CSIZE] [--wobj WOBJ] [--cobj COBJ] [--credentialfile CREDFILE] [--instance INSTANCE]
8-
[--mongobin MONGOLOC]
7+
usage: check_mongodb_dbsize.py [-h] --database DB [--wsize WSIZE] [--csize CSIZE] [--wobj WOBJ] [--cobj COBJ] [--credentialfile CREDFILE]
8+
[--instance INSTANCE] [--mongobin MONGOLOC]
99
1010
Icinga/Nagios plugin which checks the size of a MongoDB database
1111
@@ -25,7 +25,7 @@ Instance parameters:
2525
--instance INSTANCE Use credentials for this instance
2626
2727
Miscellaneous options:
28-
--mongobin MONGOLOC Location of "mongo" binary
28+
--mongobin MONGOLOC Location of "mongosh" binary
2929
```
3030

3131
### Usage example
@@ -36,7 +36,7 @@ OK - Database "exampledb" contains: 6 Collections, 0 Views, 8011700 Objects, 19
3636
```
3737

3838
### Parameters
39-
* `--credentialfile /path/to/.mdbservice` : specify a non-default location for your connection settings file (default: `/etc/nagios/.mdbservice`)
40-
* `--instance server01` : refers to the config section within the `.mdbservice` file (defaults to `localhost`)
41-
* `--mongobin /path/to/mongo` : use this parameter if your `mongo` binary is not located at `/usr/bin/mongo`
39+
- `--credentialfile /path/to/.mdbservice` : specify a non-default location for your connection settings file (default: `/etc/nagios/.mdbservice`)
40+
- `--instance server01` : refers to the config section within the `.mdbservice` file (defaults to `localhost`)
41+
- `--mongobin /path/to/mongosh` : use this parameter if your `mongosh` binary is not located at `/usr/bin/mongosh`
4242

docs/check_mongodb_stats.md

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ Instance parameters:
1717
--instance INSTANCE Use credentials for this instance
1818
1919
Miscellaneous options:
20-
--mongobin MONGOLOC Location of "mongo" binary
20+
--mongobin MONGOLOC Location of "mongosh" binary
2121
```
2222

2323
### Usage example
@@ -28,7 +28,7 @@ OK - MongoDB 4.2.20 is up for 15 days, 3:35:10 - Connections: 61, Memory: 7132Mi
2828
```
2929

3030
### Parameters
31-
* `--credentialfile /path/to/.mdbservice` : specify a non-default location for your connection settings file (default: `/etc/nagios/.mdbservice`)
32-
* `--instance server01` : refers to the config section within the `.mdbservice` file (defaults to `localhost`)
33-
* `--mongobin /path/to/mongo` : use this parameter if your `mongo` binary is not located at `/usr/bin/mongo`
31+
- `--credentialfile /path/to/.mdbservice` : specify a non-default location for your connection settings file (default: `/etc/nagios/.mdbservice`)
32+
- `--instance server01` : refers to the config section within the `.mdbservice` file (defaults to `localhost`)
33+
- `--mongobin /path/to/mongosh` : use this parameter if your `mongosh` binary is not located at `/usr/bin/mongosh`
3434

0 commit comments

Comments
 (0)