forked from jgyates/genmon
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenslack.py
228 lines (185 loc) · 8.16 KB
/
genslack.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
#!/usr/bin/env python
#-------------------------------------------------------------------------------
# FILE: genslack.py
# PURPOSE: genmon.py support program to allow Slack messages
# to be sent when the generator status changes
#
# AUTHOR: Nate Renbarger - Mostly copied from gensms
# DATE: 20-Sep-2018
#
# MODIFICATIONS:
#-------------------------------------------------------------------------------
import datetime, time, sys, signal, os, threading, socket, json, requests, getopt
try:
from genmonlib.mylog import SetupLogger
from genmonlib.mynotify import GenNotify
from genmonlib.myconfig import MyConfig
from genmonlib.mysupport import MySupport
from genmonlib.program_defaults import ProgramDefaults
except Exception as e1:
print("\n\nThis program requires the modules located in the genmonlib directory in the github repository.\n")
print("Please see the project documentation at https://github.com/jgyates/genmon.\n")
print("Error: " + str(e1))
sys.exit(2)
#---------- Signal Handler ----------------------------------------------------
def signal_handler(signal, frame):
GenNotify.Close()
sys.exit(0)
#---------- OnRun -------------------------------------------------------------
def OnRun(Active):
if Active:
console.info("Generator Running")
SendNotice("Generator Running")
else:
console.info("Generator Running End")
#---------- OnRunManual -------------------------------------------------------
def OnRunManual(Active):
if Active:
console.info("Generator Running in Manual Mode")
SendNotice("Generator Running in Manual Mode")
else:
console.info("Generator Running in Manual Mode End")
#---------- OnExercise --------------------------------------------------------
def OnExercise(Active):
if Active:
console.info("Generator Exercising")
SendNotice("Generator Exercising")
else:
console.info("Generator Exercising End")
#---------- OnReady -----------------------------------------------------------
def OnReady(Active):
if Active:
console.info("Generator Ready")
SendNotice("Generator Ready")
else:
console.info("Generator Ready End")
#---------- OnOff -------------------------------------------------------------
def OnOff(Active):
if Active:
console.info("Generator Off")
SendNotice("Generator Off")
else:
console.info("Generator Off End")
#---------- OnManual ----------------------------------------------------------
def OnManual(Active):
if Active:
console.info("Generator Manual")
SendNotice("Generator Manual")
else:
console.info("Generator Manual End")
#---------- OnAlarm -----------------------------------------------------------
def OnAlarm(Active):
if Active:
console.info("Generator Alarm")
SendNotice("Generator Alarm")
else:
console.info("Generator Alarm End")
#---------- OnService ---------------------------------------------------------
def OnService(Active):
if Active:
console.info("Generator Service Due")
SendNotice("Generator Service Due")
else:
console.info("Generator Servcie Due End")
#---------- OnUtilityChange ---------------------------------------------------
def OnUtilityChange(Active):
if Active:
console.info("Utility Service is Down")
SendNotice("Utility Service is Down")
else:
SendNotice("Utility Service is Up")
console.info("Utility Service is Up")
#---------- SendNotice --------------------------------------------------------
def SendNotice(Message):
try:
slack_data = {'channel':channel, 'username':username, 'icon_emoji':icon_emoji, 'attachments': [{'title':'GenMon Alert', 'title_link':title_link, 'fields': [{ 'title':'Status', 'value':Message, 'short':'false' }]}]}
response = requests.post(
webhook_url, data=json.dumps(slack_data),
headers={'Content-Type': 'application/json'}
)
if response.status_code != 200:
raise ValueError(
'Request to slack returned an error %s, the response is:\n%s'
% (response.status_code, response.text)
)
except Exception as e1:
log.error("Error in SendNotice: " + str(e1))
console.error("Error in SendNotice: " + str(e1))
#------------------- Command-line interface for gengpio ------------------------
if __name__=='__main__':
address=ProgramDefaults.LocalHost
# Set the signal handler
signal.signal(signal.SIGINT, signal_handler)
console = SetupLogger("slack_console", log_file = "", stream = True)
HelpStr = '\nsudo python genslack.py -a <IP Address or localhost> -c <path to genmon config file>\n'
if os.geteuid() != 0:
console.error("You need to have root privileges to run this script.\nPlease try again, this time using 'sudo'. Exiting.")
sys.exit(2)
try:
ConfigFilePath = ProgramDefaults.ConfPath
opts, args = getopt.getopt(sys.argv[1:],"hc:a:",["configpath=","address="])
except getopt.GetoptError:
console.error("Invalid command line argument.")
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
console.error(HelpStr)
sys.exit()
elif opt in ("-a", "--address"):
address = arg
elif opt in ("-c", "--configpath"):
ConfigFilePath = arg
ConfigFilePath = ConfigFilePath.strip()
port, loglocation = MySupport.GetGenmonInitInfo(ConfigFilePath, log = console)
log = SetupLogger("client", loglocation + "genslack.log")
try:
config = MyConfig(filename = ConfigFilePath + 'genslack.conf', section = 'genslack', log = log)
webhook_url = config.ReadValue('webhook_url', default = None)
channel = config.ReadValue('channel', default = None)
username = config.ReadValue('username', default = None)
icon_emoji = config.ReadValue('icon_emoji', default = ":red_circle:")
title_link = config.ReadValue('title_link', default = None)
if webhook_url == None or not len(webhook_url):
log.error("Error: invalid webhoot_url setting")
console.error("Error: invalid webhoot_url setting")
sys.exit(2)
if channel == None or not len(channel):
log.error("Error: invalid channel setting")
console.error("Error: invalid channel setting")
sys.exit(2)
if username == None or not len(username):
log.error("Error: invalid username setting")
console.error("Error: invalid username setting")
sys.exit(2)
if icon_emoji == None or not len(icon_emoji):
log.error("Error: invalid username setting")
console.error("Error: invalid username setting")
sys.exit(2)
if title_link == None or not len(title_link):
log.error("Error: invalid title_link setting")
console.error("Error: invalid title_link setting")
sys.exit(2)
except Exception as e1:
log.error("Error reading /etc/genslack.conf: " + str(e1))
console.error("Error reading /etc/genslack.conf: " + str(e1))
sys.exit(1)
try:
GenNotify = GenNotify(
host = address,
port = port,
onready = OnReady,
onexercise = OnExercise,
onrun = OnRun,
onrunmanual = OnRunManual,
onalarm = OnAlarm,
onservice = OnService,
onoff = OnOff,
onmanual = OnManual,
onutilitychange = OnUtilityChange,
log = log,
loglocation = loglocation)
while True:
time.sleep(1)
except Exception as e1:
log.error("Error: " + str(e1))
console.error("Error: " + str(e1))