-
Notifications
You must be signed in to change notification settings - Fork 479
/
Copy pathcheck_elasticsearch_query
executable file
·194 lines (164 loc) · 4.91 KB
/
check_elasticsearch_query
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
#!/usr/bin/env python3
# Copyright (C) 2019 Checkmk GmbH - License: GNU General Public License v2
# This file is part of Checkmk (https://checkmk.com). It is subject to the terms and
# conditions defined in the file COPYING, which is part of this source code package.
import argparse
import sys
import urllib.parse
from pathlib import Path
import requests
import urllib3
from cmk.utils import password_store
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
def main():
args = parse_arguments()
auth = _make_auth(args.user, args.password, args.password_id)
try:
msg, state, perfdata = handle_request(args, auth)
except Exception as exc:
sys.stdout.write("UNKNOWN - %s\n" % exc)
return 3
sys.stdout.write(f"{msg} | {perfdata}\n")
sys.exit(state)
def _make_auth(
user: str | None,
password: str | None,
password_ref: str | None,
) -> tuple[str, str] | None:
if user is None:
return None
if password is not None:
return (user, password)
if password_ref is not None:
pw_id, pw_file = password_ref.split(":", 1)
return (user, password_store.lookup(Path(pw_file), pw_id))
return None
def handle_request(args: argparse.Namespace, auth: tuple[str, str] | None) -> tuple[str, int, str]:
url = urllib.parse.urlunparse(
(
args.protocol,
"%s:%d" % (args.hostname, args.port),
"%s/_count" % args.index.replace(" ", ","),
None,
None,
None,
)
)
query = {
"query": {
"bool": {
"must": [
{"query_string": {"query": args.pattern}},
{"range": {"@timestamp": {"gte": "now-%ds" % args.timerange, "lt": "now"}}},
]
}
},
}
if args.fieldname:
query["query"]["bool"]["must"][0]["query_string"]["fields"] = args.fieldname.split(" ")
raw_response = requests.get(url, json=query, auth=auth) # nosec B113 # BNS:0b0eac
msg, state, perfdata = handle_query(raw_response, args.warn, args.crit)
return msg, state, perfdata
def handle_query(
raw_response: requests.Response, warn: int | None, crit: int | None
) -> tuple[str, int, str]:
response_data = raw_response.json()
if "count" not in response_data:
raise ValueError("Missing section count in raw response data")
state = 0
value = response_data["count"]
perfdata = "count=%s" % value
msg = "%s messages found" % value
if crit and warn:
msg += " (warn/crit at %d/%d)" % (warn, crit)
if value >= crit:
state = 2
elif value >= warn:
state = 1
return msg, state, perfdata
def parse_arguments(argv=None):
if argv is None:
argv = sys.argv[1:]
parser = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawTextHelpFormatter
)
parser.add_argument(
"-u",
"--user",
default=None,
help="Username for elasticsearch login",
)
group = parser.add_mutually_exclusive_group()
group.add_argument(
"-s",
"--password",
default=None,
help="Password for easticsearch login. Preferred over --password-id",
)
group.add_argument(
"--password-id",
default=None,
help="Password store reference to the password for easticsearch login",
)
parser.add_argument(
"-P",
"--protocol",
default="https",
help="Use 'http' or 'https' for connection to elasticsearch (default=https)",
)
parser.add_argument(
"-p",
"--port",
type=int,
default=9200,
help="Use alternative port (default: 9200)",
)
parser.add_argument(
"-q",
"--pattern",
help=("Search pattern"),
)
parser.add_argument(
"-f",
"--fieldname",
default=None,
help=("Fieldname to query"),
)
parser.add_argument(
"-i",
"--index",
help=("Index to query"),
default="_all",
)
parser.add_argument(
"-t",
"--timerange",
type=int,
default=60,
help=("The timerange to query, eg. x minutes from now."),
)
parser.add_argument(
"--debug",
action="store_true",
help=("Debug mode: let Python exceptions come through"),
)
parser.add_argument(
"--warn",
type=int,
default=None,
help=("number of log messages above which the check will warn"),
)
parser.add_argument(
"--crit",
type=int,
default=None,
help=("number of log messages above which the check will become critical"),
)
parser.add_argument(
"-H",
"--hostname",
help=("Defines the elasticsearch instances to query."),
)
return parser.parse_args()
if __name__ == "__main__":
sys.exit(main())