forked from jeremietharaud/elasticbeanstalk-exporter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcollector.py
356 lines (330 loc) · 16.9 KB
/
collector.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
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import boto3
import botocore
from prometheus_client.core import GaugeMetricFamily
import logging
import time
from joblib import Parallel, delayed
class Logger:
"""Class used to display logs on the console.
"""
def __init__(self):
logger = logging.getLogger()
logger.setLevel(logging.INFO)
formatter = logging.Formatter('%(asctime)s %(message)s')
stream_handler = logging.StreamHandler()
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
self.logger = logger
class ElasticBeanstalkCollector:
"""Class used to get metrics from an Elastic Beanstalk application.
"""
def __init__(self):
self.client = boto3.client('elasticbeanstalk')
self.metric_prefix = "elasticbeanstalk_"
self.logger = Logger().logger
self.metric_collector_duration = None
def describe_environments(self):
environments = self.client.describe_environments(IncludeDeleted=False)
return environments['Environments']
def describe_applications(self):
applications = self.client.describe_applications()
return applications['Applications']
def describe_environment_health(self, environment):
metrics = None
try:
metrics = self.client.describe_environment_health(EnvironmentName=environment, AttributeNames=['All'])
except botocore.exceptions.ClientError as e:
if e.response.get("Error").get("Code") == "InvalidRequestException":
return "None", "None"
else:
raise e
return environment, metrics
def parallel_describe_environment_health(self, environments):
start = time.time()
r = Parallel(n_jobs=-1, prefer="threads")(
delayed(self.describe_environment_health)(environment['EnvironmentName']) for environment in environments)
end = time.time()
self.metric_collector_duration.add_metric(['parallel_environment_health'], end-start)
return r
def iterative_describe_environment_health(self, environments):
start = time.time()
r = []
for environment in environments:
r.append(self.describe_environment_health(environment['EnvironmentName']))
end = time.time()
self.metric_collector_duration.add_metric(['iterative_environment_health'], end-start)
return r
def describe_environment_instances_health(self, environment):
metrics = None
try:
metrics = self.client.describe_instances_health(
EnvironmentName=environment,
AttributeNames=['HealthStatus', 'ApplicationMetrics', 'System']
)
except botocore.exceptions.ClientError as e:
if e.response.get("Error").get("Code") == "InvalidRequestException":
return "None", "None"
else:
raise e
return environment, metrics['InstanceHealthList']
def parallel_describe_environment_instances_health(self, environments):
start = time.time()
r = Parallel(n_jobs=-1, prefer="threads")(
delayed(
self.describe_environment_instances_health)(
environment['EnvironmentName']
) for environment in environments
)
end = time.time()
self.metric_collector_duration.add_metric(['parallel_instance_health'], end-start)
return r
def iterative_describe_environment_instances_health(self, environments):
start = time.time()
r = []
for environment in environments:
r.append(self.describe_environment_instances_health(environment['EnvironmentName']))
end = time.time()
self.metric_collector_duration.add_metric(['iterative_instance_health'], end-start)
return r
def collect_applications(self, applications):
start = time.time()
app = GaugeMetricFamily(
self.metric_prefix + 'application',
'Description of Elastic Beanstalk application',
labels=['application_name', 'description']
)
for application in applications:
app.add_metric([application['ApplicationName'], self.get_label_value(application, 'Description')], 1)
end = time.time()
self.metric_collector_duration.add_metric(['applications'], end-start)
return app
def collect_environments(self, environments):
start = time.time()
env = GaugeMetricFamily(
self.metric_prefix + 'environment_status',
'Status of Elastic Beanstalk environment',
labels=['environment_name', 'id', 'application_name',
'platform', 'url', 'health', 'version', 'environment_tier']
)
for environment in environments:
env.add_metric(
[environment['EnvironmentName'], environment['EnvironmentId'],
environment['ApplicationName'], environment['PlatformArn'],
self.get_label_value(environment, 'CNAME'), environment['Health'],
self.get_label_value(environment, 'VersionLabel'),
environment['Tier']['Name']],
1 if environment['Health'] == 'Green' else 0
)
end = time.time()
self.metric_collector_duration.add_metric(['environments'], end-start)
return env
def collect_global_current_requests(self, environments_health):
start = time.time()
current_requests = GaugeMetricFamily(
self.metric_prefix + 'enhanced_global_current_requests',
'Average number of requests per second over the last 10 seconds',
labels=['environment_name']
)
for environment, health in environments_health:
if health != "None" and 'ApplicationMetrics' in health:
current_requests.add_metric([environment], health['ApplicationMetrics']['RequestCount'])
end = time.time()
self.metric_collector_duration.add_metric(['global_current_requests'], end-start)
return current_requests
def collect_current_requests(self, environments_instances_health):
start = time.time()
instance_current_requests = GaugeMetricFamily(
self.metric_prefix + 'enhanced_current_requests',
'Average number of requests per instance per second over the last 10 seconds',
labels=['environment_name', 'instance_id']
)
for environment, instances_health in environments_instances_health:
if instances_health != "None":
for instance_health in instances_health:
instance_current_requests.add_metric(
[environment, instance_health['InstanceId']],
instance_health['ApplicationMetrics']['RequestCount']
)
end = time.time()
self.metric_collector_duration.add_metric(['current_requests'], end-start)
return instance_current_requests
def collect_load_average(self, environments_instances_health):
start = time.time()
instance_load_average = GaugeMetricFamily(
self.metric_prefix + 'enhanced_load_average',
'Load average in the last 1-minute, 5-minute, and 15-minute periods',
labels=['environment_name', 'instance_id', 'mode']
)
for environment, instances_health in environments_instances_health:
if instances_health != "None":
for instance_health in instances_health:
instance_load_average.add_metric(
[environment,
instance_health['InstanceId'], 'Load1'],
instance_health['System']['LoadAverage'][0]
if 'LoadAverage' in instance_health['System'] else 0
)
instance_load_average.add_metric(
[environment,
instance_health['InstanceId'], 'Load5'],
instance_health['System']['LoadAverage'][1]
if 'LoadAverage' in instance_health['System'] else 0
)
instance_load_average.add_metric(
[environment,
instance_health['InstanceId'], 'Load15'],
instance_health['System']['LoadAverage'][2]
if 'LoadAverage' in instance_health['System'] else 0
)
end = time.time()
self.metric_collector_duration.add_metric(['load_average'], end-start)
return instance_load_average
def collect_cpu_usage(self, environments_instances_health):
start = time.time()
instance_cpu_usage = GaugeMetricFamily(
self.metric_prefix + 'enhanced_cpu_usage_percent',
'CPU utilization per instance and state',
labels=['environment_name', 'instance_id', 'state']
)
for environment, instances_health in environments_instances_health:
if instances_health != "None":
for instance_health in instances_health:
instance_cpu_usage.add_metric(
[environment,
instance_health['InstanceId'], 'User'],
instance_health['System']['CPUUtilization']['User']
if 'CPUUtilization' in instance_health['System'] else 0
)
instance_cpu_usage.add_metric(
[environment,
instance_health['InstanceId'], 'Nice'],
instance_health['System']['CPUUtilization']['Nice']
if 'CPUUtilization' in instance_health['System'] else 0
)
instance_cpu_usage.add_metric(
[environment,
instance_health['InstanceId'], 'System'],
instance_health['System']['CPUUtilization']['System']
if 'CPUUtilization' in instance_health['System'] else 0
)
instance_cpu_usage.add_metric(
[environment,
instance_health['InstanceId'], 'Idle'],
instance_health['System']['CPUUtilization']['Idle']
if 'CPUUtilization' in instance_health['System'] else 0
)
instance_cpu_usage.add_metric(
[environment,
instance_health['InstanceId'], 'IOWait'],
instance_health['System']['CPUUtilization']['IOWait']
if 'CPUUtilization' in instance_health['System'] else 0
)
instance_cpu_usage.add_metric(
[environment,
instance_health['InstanceId'], 'IRQ'],
instance_health['System']['CPUUtilization']['IRQ']
if 'CPUUtilization' in instance_health['System'] else 0
)
instance_cpu_usage.add_metric(
[environment,
instance_health['InstanceId'], 'SoftIRQ'],
instance_health['System']['CPUUtilization']['SoftIRQ']
if 'CPUUtilization' in instance_health['System'] else 0
)
end = time.time()
self.metric_collector_duration.add_metric(['cpu_usage'], end-start)
return instance_cpu_usage
def collect_global_http_requests(self, environments_health):
start = time.time()
http_requests = GaugeMetricFamily(
self.metric_prefix + 'enhanced_global_http_requests_percent',
'Percent of requests that resulted in a status code over the last 10 seconds',
labels=['environment_name', 'status_code']
)
for environment, health in environments_health:
if health != "None" and 'ApplicationMetrics' in health:
http_requests.add_metric(
[environment, 'Status2xx'],
health['ApplicationMetrics']['StatusCodes']['Status2xx']
if 'StatusCodes' in health['ApplicationMetrics'] else 0
)
http_requests.add_metric(
[environment, 'Status3xx'],
health['ApplicationMetrics']['StatusCodes']['Status3xx']
if 'StatusCodes' in health['ApplicationMetrics'] else 0
)
http_requests.add_metric(
[environment, 'Status4xx'],
health['ApplicationMetrics']['StatusCodes']['Status4xx']
if 'StatusCodes' in health['ApplicationMetrics'] else 0
)
http_requests.add_metric(
[environment, 'Status5xx'],
health['ApplicationMetrics']['StatusCodes']['Status5xx']
if 'StatusCodes' in health['ApplicationMetrics'] else 0
)
end = time.time()
self.metric_collector_duration.add_metric(['global_http_requests'], end-start)
return http_requests
def collect_health_status(self, environments_health):
start = time.time()
health_status = GaugeMetricFamily(
self.metric_prefix + 'enhanced_health_status',
'The health status of the environment',
labels=['environment_name', 'color', 'health_status']
)
for environment, health in environments_health:
if health != "None" and 'ApplicationMetrics' in health:
health_status.add_metric([environment, 'Green', 'Ok'], 1 if health['HealthStatus'] == 'Ok' else 0)
health_status.add_metric([environment, 'Yellow', 'Warning'], 1 if health['HealthStatus'] == 'Warning' else 0)
health_status.add_metric([environment, 'Red', 'Degraded'], 1 if health['HealthStatus'] == 'Degraded' else 0)
health_status.add_metric([environment, 'Red', 'Severe'], 1 if health['HealthStatus'] == 'Severe' else 0)
health_status.add_metric([environment, 'Green', 'Info'], 1 if health['HealthStatus'] == 'Info' else 0)
health_status.add_metric([environment, 'Grey', 'Pending'], 1 if health['HealthStatus'] == 'Pending' else 0)
health_status.add_metric([environment, 'Grey', 'Unknown'], 1 if health['HealthStatus'] == 'Unknown' else 0)
health_status.add_metric([environment, 'Grey', 'Suspended'], 1 if health['HealthStatus'] == 'Suspended' else 0)
end = time.time()
self.metric_collector_duration.add_metric(['health_status'], end-start)
return health_status
def collect_status(self, environments_health):
start = time.time()
status = GaugeMetricFamily(
self.metric_prefix + 'enhanced_status',
'The status of the environment',
labels=['environment_name', 'status']
)
for environment, health in environments_health:
if health != "None" and 'ApplicationMetrics' in health:
status.add_metric([environment, 'Ready'], 1 if health['Status'] == 'Ready' else 0)
status.add_metric([environment, 'Launching'], 1 if health['Status'] == 'Launching' else 0)
status.add_metric([environment, 'Updating'], 1 if health['Status'] == 'Updating' else 0)
status.add_metric([environment, 'Terminating'], 1 if health['Status'] == 'Terminating' else 0)
status.add_metric([environment, 'Terminated'], 1 if health['Status'] == 'Terminated' else 0)
end = time.time()
self.metric_collector_duration.add_metric(['status'], end-start)
return status
def collect(self):
self.logger.info("Collect metrics")
self.metric_collector_duration = GaugeMetricFamily(
self.metric_prefix + 'collector_duration_seconds',
'Duration of a collection', labels=['collector'])
environments = self.describe_environments()
applications = self.describe_applications()
environments_health = self.parallel_describe_environment_health(environments)
environments_instances_health = self.parallel_describe_environment_instances_health(environments)
yield self.collect_environments(environments)
yield self.collect_applications(applications)
yield self.collect_global_current_requests(environments_health)
yield self.collect_global_http_requests(environments_health)
yield self.collect_health_status(environments_health)
yield self.collect_status(environments_health)
yield self.collect_current_requests(environments_instances_health)
yield self.collect_load_average(environments_instances_health)
yield self.collect_cpu_usage(environments_instances_health)
yield self.metric_collector_duration
@staticmethod
def get_label_value(obj, label):
if label in obj:
return obj[label]
else:
return ''