forked from madflojo/RunbookWraps
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmonitor.py
More file actions
executable file
·221 lines (187 loc) · 6.95 KB
/
Copy pathmonitor.py
File metadata and controls
executable file
·221 lines (187 loc) · 6.95 KB
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
#!/usr/bin/env python
#####################################################################
#### monitor.py | Runbook Monitor Wrapper
#### -------------------------
#### This script can be used to integrate your own monitoring systems with Runbook
#### by wrapping your existing scripts. When executed this script will read the YAML
#### configuration file and execute the defined scripts. When the script is executed
#### this wrapper will read the exit code and send an appropriate webhook request to
#### Runbook.
#### -------------------------
#### Exit Codes:
####
#### When the sub shell returns with a 0 exit code the monitor will send a "Healty" webhook
#### call to Runbook. If the sub shell returns with any other exit code the monitor
#### will send a "Failed" webhook call.
#### -------------------------
#### Sample Config:
####
#### You can find a sample configurations in config/
#### -------------------------
#### Benjamin Cane | @madflojo
#####################################################################
#### Modules
#########################
## Base
import json
import sys
import getopt
import subprocess
import os
## Non-Base but needed
try:
import requests
except:
print "This application requires the requests python module. Please install it to continue"
sys.exit(2)
try:
import yaml
except:
print "This application requires the pyYAML python module. Please install it to continue"
sys.exit(2)
#### Core Functions
#########################
def usage(cmd):
''' Print usage summary '''
print("Usage: %s -c config_file [--debug]") % cmd
def main(arguments):
''' Grab command line args and assign them properly '''
## Grab the cmdline args from sys.argv
try:
opts, args = getopt.getopt(arguments[1:], "c:di", ["config=", "debug", "insecure"])
except getopt.GetoptError as err:
usage(arguments[0])
sys.exit(2)
## Set default config items
config = None
debug = False
insecure = False
## Go through opts and set given arguments
for opt, arg in opts:
if opt == "-c" or opt == "--config":
config = arg
elif opt == "-d" or opt == "--debug":
debug = True
elif opt == "-i" or opt == "--insecure":
insecure = True
else:
usage(arguments[0])
sys.exit(2)
## Make sure we can get a config file else exit
if config:
return config, debug, insecure
else:
usage(sys.argv[0])
sys.exit(2)
#### Main Execution
#########################
def crAPI(url, check_key, action):
''' Call Runbook API to change or update the monitors status '''
## Generate json message
data = { 'check_key': check_key,
'action': action }
payload = json.dumps(data)
## Set headers
headers = {'content-type': 'application/json'}
## If insecure set verify to False
if insecure:
verify = False
else:
verify = True
if debug:
print "-" * 25
print("Sending %s to %s") % (payload, url)
## Perform Request
try:
req = requests.post(url, data=payload, headers=headers, verify=verify)
except requests.exceptions.SSLError:
## If we get an SSL Error we should exit
print("[Reactor Wrapper] Error communicating with Runbook, got SSL certificate error")
print("Exiting...")
sys.exit(2)
## If debug print the status code and reply data
if debug:
print "-" * 25
print("[Monitor Wrapper Debug] Sent Request to Runbook and got return code: %r") % req.status_code
print "-" * 25
print(req.text)
print "-" * 25
## Verify we got a 200
if req.status_code == 200:
## Verify our request was successful
if "success" in req.text:
print("[Monitor Wrapper] Sent %s action to Runbook") % action
return True
else:
print("[Monitor Wrapper] Error sending %s action to Runbook") % action
return False
else:
print("[Monitor Wrapper] Could not send %s action to Runbook") % action
print req.text
return False
#### Main Execution
#########################
if __name__ == '__main__':
## Grab the provided command line arguments and get what we need
configfile, debug, insecure = main(sys.argv)
## Verify supplied file exists and load the config
if os.path.isfile(configfile):
fh = open(configfile, "r")
config = yaml.load(fh.read())
fh.close()
else:
print("Error: File not found - %s") % configfile
usage(sys.argv[0])
sys.exit(1)
## Run a for loop for each monitor specified
for key in config['monitors'].keys():
## Set monitor to monitor opject
monitor = config['monitors'][key]
print("[Monitor Wrapper] Starting to check monitor: %s") % key
## Verify Needed Configs are Here
run = True
## url is required
if monitor['url'] is None:
run = False
print("[Monitor Wrapper] Skipping monitor as it doesn't have a url defined: %s") % key
## check_key is required
if monitor['check_key'] is None:
run = False
print("[Monitor Wrapper] Skipping monitor as it doesn't have a check_key defined: %s") % key
## cmd is required
if monitor['cmd']:
cmd = monitor['cmd']
else:
run = False
print("[Monitor Wrapper] Skipping monitor as it doesn't have a command: %s") % key
## args is optional but should be set to something
if "args" in monitor:
args = " " + monitor['args']
else:
args = ""
## If all checks out let's execute
if run:
## Try running the command
try:
print "-" * 25
print "Monitor Output:"
## Commands should be run in a subshell for best portability
code = subprocess.call(cmd + args, shell=True)
print "-" * 25
print("[Monitor Wrapper] Executed cmd %s and got return code %r") % ( cmd + " " + args, code )
## If the process is killed we may get a negative return code
if code < 0:
print("[Monitor Wrapper] Execution Error: Child was terminated by signal - %d") % code
## Anything above 0 is failed
elif code > 0:
print("[Monitor Wrapper] Monitor returned failed: %s") % key
crAPI(monitor['url'], monitor['check_key'], "failed")
## Only zero is healthy
else:
print("[Monitor Wrapper] Monitor returned healthy: %s") % key
crAPI(monitor['url'], monitor['check_key'], "healthy")
## If we get an os error print the error
except OSError as e:
print("[Monitor Wrapper] Execution error: %r") % e
print "#" * 50
print ""