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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
|
# vim: tabstop=4 shiftwidth=4 softtabstop=4
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.
import datetime
from heat.common import exception
from heat.openstack.common import log as logging
from heat.openstack.common import timeutils
from heat.engine import timestamp
from heat.db import api as db_api
from heat.engine import parser
from heat.rpc import api as rpc_api
logger = logging.getLogger(__name__)
class WatchRule(object):
WATCH_STATES = (
ALARM,
NORMAL,
NODATA
) = (
rpc_api.WATCH_STATE_ALARM,
rpc_api.WATCH_STATE_OK,
rpc_api.WATCH_STATE_NODATA
)
ACTION_MAP = {ALARM: 'AlarmActions',
NORMAL: 'OKActions',
NODATA: 'InsufficientDataActions'}
created_at = timestamp.Timestamp(db_api.watch_rule_get, 'created_at')
updated_at = timestamp.Timestamp(db_api.watch_rule_get, 'updated_at')
def __init__(self, context, watch_name, rule, stack_id=None,
state=NORMAL, wid=None, watch_data=[],
last_evaluated=timeutils.utcnow()):
self.context = context
self.now = timeutils.utcnow()
self.name = watch_name
self.state = state
self.rule = rule
self.stack_id = stack_id
self.timeperiod = datetime.timedelta(seconds=int(rule['Period']))
self.id = wid
self.watch_data = watch_data
self.last_evaluated = last_evaluated
@classmethod
def load(cls, context, watch_name=None, watch=None):
'''
Load the watchrule object, either by name or via an existing DB object
'''
if watch is None:
try:
watch = db_api.watch_rule_get_by_name(context, watch_name)
except Exception as ex:
logger.warn('WatchRule.load (%s) db error %s' %
(watch_name, str(ex)))
if watch is None:
raise exception.WatchRuleNotFound(watch_name=watch_name)
else:
return cls(context=context,
watch_name=watch.name,
rule=watch.rule,
stack_id=watch.stack_id,
state=watch.state,
wid=watch.id,
watch_data=watch.watch_data,
last_evaluated=watch.last_evaluated)
def store(self):
'''
Store the watchrule in the database and return its ID
If self.id is set, we update the existing rule
'''
wr_values = {
'name': self.name,
'rule': self.rule,
'state': self.state,
'stack_id': self.stack_id
}
if not self.id:
wr = db_api.watch_rule_create(self.context, wr_values)
self.id = wr.id
else:
db_api.watch_rule_update(self.context, self.id, wr_values)
def do_data_cmp(self, data, threshold):
op = self.rule['ComparisonOperator']
if op == 'GreaterThanThreshold':
return data > threshold
elif op == 'GreaterThanOrEqualToThreshold':
return data >= threshold
elif op == 'LessThanThreshold':
return data < threshold
elif op == 'LessThanOrEqualToThreshold':
return data <= threshold
else:
return False
def do_Maximum(self):
data = 0
have_data = False
for d in self.watch_data:
if d.created_at < self.now - self.timeperiod:
continue
if not have_data:
data = float(d.data[self.rule['MetricName']]['Value'])
have_data = True
if float(d.data[self.rule['MetricName']]['Value']) > data:
data = float(d.data[self.rule['MetricName']]['Value'])
if not have_data:
return self.NODATA
if self.do_data_cmp(data,
float(self.rule['Threshold'])):
return self.ALARM
else:
return self.NORMAL
def do_Minimum(self):
data = 0
have_data = False
for d in self.watch_data:
if d.created_at < self.now - self.timeperiod:
continue
if not have_data:
data = float(d.data[self.rule['MetricName']]['Value'])
have_data = True
elif float(d.data[self.rule['MetricName']]['Value']) < data:
data = float(d.data[self.rule['MetricName']]['Value'])
if not have_data:
return self.NODATA
if self.do_data_cmp(data,
float(self.rule['Threshold'])):
return self.ALARM
else:
return self.NORMAL
def do_SampleCount(self):
'''
count all samples within the specified period
'''
data = 0
for d in self.watch_data:
if d.created_at < self.now - self.timeperiod:
continue
data = data + 1
if self.do_data_cmp(data,
float(self.rule['Threshold'])):
return self.ALARM
else:
return self.NORMAL
def do_Average(self):
data = 0
samples = 0
for d in self.watch_data:
if d.created_at < self.now - self.timeperiod:
continue
samples = samples + 1
data = data + float(d.data[self.rule['MetricName']]['Value'])
if samples == 0:
return self.NODATA
data = data / samples
if self.do_data_cmp(data,
float(self.rule['Threshold'])):
return self.ALARM
else:
return self.NORMAL
def do_Sum(self):
data = 0
for d in self.watch_data:
if d.created_at < self.now - self.timeperiod:
logger.debug('ignoring %s' % str(d.data))
continue
data = data + float(d.data[self.rule['MetricName']]['Value'])
if self.do_data_cmp(data,
float(self.rule['Threshold'])):
return self.ALARM
else:
return self.NORMAL
def get_alarm_state(self):
fn = getattr(self, 'do_%s' % self.rule['Statistic'])
return fn()
def evaluate(self):
# has enough time progressed to run the rule
self.now = timeutils.utcnow()
if self.now < (self.last_evaluated + self.timeperiod):
return []
return self.run_rule()
def run_rule(self):
new_state = self.get_alarm_state()
actions = []
if new_state != self.state:
actions = self.rule_actions(new_state)
self.state = new_state
self.last_evaluated = self.now
self.store()
return actions
def rule_actions(self, new_state):
logger.warn('WATCH: stack:%s, watch_name:%s %s',
self.stack_id, self.name, new_state)
actions = []
if not self.ACTION_MAP[new_state] in self.rule:
logger.info('no action for new state %s',
new_state)
else:
s = db_api.stack_get(self.context, self.stack_id)
if s and s.status in (parser.Stack.CREATE_COMPLETE,
parser.Stack.UPDATE_COMPLETE):
stack = parser.Stack.load(self.context, stack=s)
for a in self.rule[self.ACTION_MAP[new_state]]:
actions.append(stack[a].alarm)
else:
logger.warning("Could not process watch state %s for stack" %
new_state)
return actions
def create_watch_data(self, data):
if not self.rule['MetricName'] in data:
logger.warn('new data has incorrect metric:%s' %
(self.rule['MetricName']))
raise ValueError('MetricName %s missing' %
self.rule['MetricName'])
watch_data = {
'data': data,
'watch_rule_id': self.id
}
wd = db_api.watch_data_create(None, watch_data)
logger.debug('new watch:%s data:%s' % (self.name, str(wd.data)))
def set_watch_state(self, state):
'''
Temporarily set the watch state, returns list of functions to be
scheduled in the stack ThreadGroup for the specified state
'''
if state not in self.WATCH_STATES:
raise ValueError('Unknown watch state %s' % state)
actions = []
if state != self.state:
actions = self.rule_actions(state)
if actions:
logger.debug("Overriding state %s for watch %s with %s" %
(self.state, self.name, state))
else:
logger.warning("Unable to override state %s for watch %s" %
(self.state, self.name))
return actions
|