forked from pensivealbatross/xm-labs-splunk-custom-messages
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathxmatters.py
executable file
·174 lines (151 loc) · 5.96 KB
/
xmatters.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
"""
This file is used for xMatters Splunk Alert Actions
"""
import sys
import json
# pylint: disable = import-error
# pylint: disable = wrong-import-position
from splunk.clilib.bundle_paths import make_splunkhome_path
sys.path.append(make_splunkhome_path(['etc', 'apps', 'xmatters_alert_action', 'lib']))
from common_utils.setup_logging import setup_logging
from common_utils.password import get_password
from xmatters_sdk.xm_event import XMattersEvent
from xmatters_sdk.xm_client import XMattersClient
# pylint: enable = wrong-import-position
# pylint: enable = import-error
# The name of the log file to write to
XM_ALERT_ACTION_LOG = 'xmatters_alert_action.log'
# The keys from the alert to send to the xMatters Event
KEYS = [
'app',
'cron.schedule',
'description',
'name',
'next_scheduled_time',
'owner',
'results_link',
'search',
'trigger.date',
'trigger.time',
'type',
'view_link',
'alert.expires',
'result.source',
'result.host',
'result.sourcetype',
'result.index',
'result.timestamp',
'result.DiskSpacePrct',
'result.source',
'result.splunk_server'
]
class XMattersAlert(object):
"""
Class for the xMatters Alert Action handler
"""
def __init__(self, settings):
"""
@param settings: the payload from the alert action script call
"""
self.logger = setup_logging(XM_ALERT_ACTION_LOG, 'xmatters.alert_actions')
self.settings = settings
self.config = settings.get('configuration')
self.endpoint_url = self.config.get('endpoint_url')
self.username = self.config.get('xMuser')
self.recipients = self.config.get('recipients')
self.session_key = settings.get('session_key')
def get_prop_value(self, key, value):
"""
Safely gets the value of a property for use in an xMatters Event. Currently supports
list, str, unicode, None types
@param key: <str> the name of the property
@param value: <any> the value of the property
@return: string
"""
value_type = type(value)
if value_type is list:
return ','.join(value)
elif value_type is str or value_type is unicode:
return value
elif value is None:
return ''
#else:
self.logger.warn('warning=INVALID_PROP_TYPE key=%s value_type=%s', key, value_type)
return False
def execute(self):
"""
Executes the Alert Action Handler
@return: True, if successful
@raises: Exception, if no request id is returned by xMatters
"""
self.logger.info(
"action=EXECUTE endpoint_url=%s username=%s recipients=%s",
self.endpoint_url,
self.username,
self.recipients
)
xm_client = XMattersClient()
if self.username:
password_name = 'xmatters_password'
password = get_password(
self.settings['server_uri'],
self.session_key,
password_name
)
if password is False:
raise Exception('Error getting password: %s' % password_name)
xm_client.add_credentials(self.username, password)
xm_event = XMattersEvent()
for key in KEYS:
value = self.get_prop_value(key, self.config.get(key))
if value is not False:
xm_event.add_property(key, value)
for recipient in self.recipients.split(';'):
target_name = recipient.strip()
xm_event.add_recipient(target_name)
xm_event.set_priority(self.config.get('priority'))
"""
xMCARW Added two custom message properties that can be defined at the time of creating the event so that any fields can be passed to xMatters
"""
xm_event.add_property('custom_short_message', self.get_prop_value('custom_short_message', self.config.get('custom_short_message')) )
xm_event.add_property('custom_detail_message', self.get_prop_value('custom_detail_message', self.config.get('custom_detail_message')) )
request_id = xm_client.send_event(self.endpoint_url, xm_event)
if request_id is False:
self.logger.error(
'An error occurred while sending request to xMatters. See %s for details.',
XM_ALERT_ACTION_LOG
)
raise Exception('Failed to execute one or more send event actions.')
return request_id
if __name__ == "__main__":
try:
LOGGER = setup_logging(XM_ALERT_ACTION_LOG, 'xmatters.alert_action.main')
if len(sys.argv) > 1 and sys.argv[1] == "--execute":
try:
# Capture the input, which is a big JSON object
# We stick it in a variable so we can print it if needed
SYSTEM_IN = sys.stdin.read()
INCOMING = json.loads(SYSTEM_IN)
LOGGER.debug('Incoming %s', SYSTEM_IN)
XM_ALERT = XMattersAlert(INCOMING)
REQUEST_ID = XM_ALERT.execute()
if REQUEST_ID:
LOGGER.info('action=ALERT_EXECUTE success=true request_id=%s', REQUEST_ID)
else:
LOGGER.error('action=ALERT_EXECUTE success=false error=SEND_FAILURE')
sys.exit(2)
# pylint: disable = broad-except
except Exception, exception:
LOGGER.error('Failed to execute xMatters Alert Action')
LOGGER.exception(exception)
sys.exit(2)
else:
MESSAGE = 'Unsupported execution mode (expected --execute flag)'
LOGGER.error('error=XM_MAIN_FAILURE message=%s', MESSAGE)
sys.exit(1)
# pylint: disable = broad-except
except Exception, exception:
print >> sys.stderr, "FATAL xMatters encountered an exception"
print >> sys.stderr, "FATAL xMatters encountered an %s" % json.dumps(exception)
sys.exit(1)
# pylint: enable = broad-except