| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
import boto3 |
| 6 |
import psutil |
| 7 |
|
| 8 |
import time |
| 9 |
import os |
| 10 |
import json |
| 11 |
import subprocess |
| 12 |
import zipfile |
| 13 |
import datetime |
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
class DataSnapshot_Metric(): |
| 19 |
def __init__(self, metric_name, metric_function, metric_dimensions=[], |
| 20 |
metric_unit="None", metric_alarm_threshold=None, metric_alarm_severity=6, |
| 21 |
git_hash="", git_repo_name="", reports_to_skip=0, is_percent=False): |
| 22 |
self.metric_name = metric_name |
| 23 |
self.metric_function = metric_function |
| 24 |
self.metric_dimensions = metric_dimensions |
| 25 |
self.metric_unit = metric_unit |
| 26 |
self.metric_alarm_threshold = metric_alarm_threshold |
| 27 |
self.metric_alarm_name = self.metric_name + "-" + git_repo_name + "-" + git_hash |
| 28 |
self.metric_alarm_description = 'Alarm for metric "' + self.metric_name + '" - git hash: ' + git_hash |
| 29 |
self.metric_value = None |
| 30 |
self.reports_to_skip = reports_to_skip |
| 31 |
self.metric_alarm_severity = metric_alarm_severity |
| 32 |
self.is_percent = is_percent |
| 33 |
|
| 34 |
|
| 35 |
def get_metric_value(self, psutil_process : psutil.Process): |
| 36 |
if not self.metric_function is None: |
| 37 |
self.metric_value = self.metric_function(psutil_process) |
| 38 |
return self.metric_value |
| 39 |
|
| 40 |
|
| 41 |
def get_metric_cloudwatch_dictionary(self): |
| 42 |
if (self.reports_to_skip > 0): |
| 43 |
self.reports_to_skip -= 1 |
| 44 |
return None |
| 45 |
|
| 46 |
if (self.metric_value == None): |
| 47 |
return None |
| 48 |
|
| 49 |
return { |
| 50 |
"MetricName": self.metric_name, |
| 51 |
"Dimensions": self.metric_dimensions, |
| 52 |
"Value": self.metric_value, |
| 53 |
"Unit": self.metric_unit |
| 54 |
} |
| 55 |
|
| 56 |
class DataSnapshot_Dashboard_Widget(): |
| 57 |
def __init__(self, widget_name, metric_namespace, metric_dimension, cloudwatch_region="us-east-1", widget_period=60) -> None: |
| 58 |
self.metric_list = [] |
| 59 |
self.region = cloudwatch_region |
| 60 |
self.widget_name = widget_name |
| 61 |
self.metric_namespace = metric_namespace |
| 62 |
self.metric_dimension = metric_dimension |
| 63 |
self.widget_period = widget_period |
| 64 |
|
| 65 |
def add_metric_to_widget(self, new_metric_name): |
| 66 |
try: |
| 67 |
self.metric_list.append(new_metric_name) |
| 68 |
except Exception as e: |
| 69 |
print ("[DataSnapshot_Dashboard] ERROR - could not add metric to dashboard widget due to exception!") |
| 70 |
print (f"[DataSnapshot_Dashboard] Exception: {repr(e)}") |
| 71 |
|
| 72 |
def remove_metric_from_widget(self, existing_metric_name): |
| 73 |
try: |
| 74 |
self.metric_list.remove(existing_metric_name) |
| 75 |
except Exception as e: |
| 76 |
print ("[DataSnapshot_Dashboard] ERROR - could not remove metric from dashboard widget due to exception!") |
| 77 |
print (f"[DataSnapshot_Dashboard] Exception: {repr(e)}") |
| 78 |
|
| 79 |
def get_widget_dictionary(self): |
| 80 |
metric_list_json = [] |
| 81 |
for metric_name in self.metric_list: |
| 82 |
metric_list_json.append([self.metric_namespace, metric_name, self.metric_dimension, metric_name]) |
| 83 |
|
| 84 |
return { |
| 85 |
"type":"metric", |
| 86 |
"properties" : { |
| 87 |
"metrics" : metric_list_json, |
| 88 |
"region": self.region, |
| 89 |
"title": self.widget_name, |
| 90 |
"period": self.widget_period, |
| 91 |
}, |
| 92 |
"width": 14, |
| 93 |
"height": 10 |
| 94 |
} |
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
class DataSnapshot(): |
| 101 |
def __init__(self, |
| 102 |
git_hash=None, |
| 103 |
git_repo_name=None, |
| 104 |
git_hash_as_namespace=False, |
| 105 |
git_fixed_namespace_text="mqtt5_canary", |
| 106 |
datetime_string=None, |
| 107 |
output_log_filepath=None, |
| 108 |
output_to_console=True, |
| 109 |
cloudwatch_region="us-east-1", |
| 110 |
cloudwatch_make_dashboard=False, |
| 111 |
cloudwatch_teardown_alarms_on_complete=True, |
| 112 |
cloudwatch_teardown_dashboard_on_complete=True, |
| 113 |
s3_bucket_name="canary-wrapper-bucket", |
| 114 |
s3_bucket_upload_on_complete=True, |
| 115 |
lambda_name="CanarySendEmailLambda", |
| 116 |
metric_frequency=None): |
| 117 |
|
| 118 |
|
| 119 |
|
| 120 |
self.first_metric_call = True |
| 121 |
self.metrics = [] |
| 122 |
self.metrics_numbers = [] |
| 123 |
self.metric_report_number = 0 |
| 124 |
self.metric_report_non_zero_count = 4 |
| 125 |
|
| 126 |
|
| 127 |
|
| 128 |
|
| 129 |
self.perform_final_initialization = True |
| 130 |
|
| 131 |
|
| 132 |
self.abort_due_to_internal_error = False |
| 133 |
self.abort_due_to_internal_error_reason = "" |
| 134 |
self.abort_due_to_internal_error_due_to_credentials = False |
| 135 |
|
| 136 |
self.git_hash = None |
| 137 |
self.git_repo_name = None |
| 138 |
self.git_hash_as_namespace = git_hash_as_namespace |
| 139 |
self.git_fixed_namespace_text = git_fixed_namespace_text |
| 140 |
self.git_metric_namespace = None |
| 141 |
|
| 142 |
self.cloudwatch_region = cloudwatch_region |
| 143 |
self.cloudwatch_client = None |
| 144 |
self.cloudwatch_make_dashboard = cloudwatch_make_dashboard |
| 145 |
self.cloudwatch_teardown_alarms_on_complete = cloudwatch_teardown_alarms_on_complete |
| 146 |
self.cloudwatch_teardown_dashboard_on_complete = cloudwatch_teardown_dashboard_on_complete |
| 147 |
self.cloudwatch_dashboard_name = "" |
| 148 |
self.cloudwatch_dashboard_widgets = [] |
| 149 |
|
| 150 |
self.s3_bucket_name = s3_bucket_name |
| 151 |
self.s3_client = None |
| 152 |
self.s3_bucket_upload_on_complete = s3_bucket_upload_on_complete |
| 153 |
|
| 154 |
self.output_to_file_filepath = output_log_filepath |
| 155 |
self.output_to_file = False |
| 156 |
self.output_file = None |
| 157 |
self.output_to_console = output_to_console |
| 158 |
|
| 159 |
self.lambda_client = None |
| 160 |
self.lambda_name = lambda_name |
| 161 |
|
| 162 |
self.datetime_string = datetime_string |
| 163 |
self.metric_frequency = metric_frequency |
| 164 |
|
| 165 |
|
| 166 |
|
| 167 |
|
| 168 |
try: |
| 169 |
tmp_sts_client = boto3.client('sts') |
| 170 |
tmp_sts_client.get_caller_identity() |
| 171 |
except Exception as e: |
| 172 |
print ("[DataSnapshot] ERROR - AWS credentials are NOT valid!") |
| 173 |
print (f"[DataSnapshot] ERROR - Exception: {repr(e)}") |
| 174 |
self.abort_due_to_internal_error = True |
| 175 |
self.abort_due_to_internal_error_reason = "AWS credentials are NOT valid!" |
| 176 |
self.abort_due_to_internal_error_due_to_credentials = True |
| 177 |
return |
| 178 |
|
| 179 |
|
| 180 |
|
| 181 |
|
| 182 |
if (git_hash == None or git_repo_name == None): |
| 183 |
print("[DataSnapshot] ERROR - a Git hash and repository name are REQUIRED for the canary wrapper to run!") |
| 184 |
self.abort_due_to_internal_error = True |
| 185 |
self.abort_due_to_internal_error_reason = "No Git hash and repository passed!" |
| 186 |
return |
| 187 |
|
| 188 |
self.git_hash = git_hash |
| 189 |
self.git_repo_name = git_repo_name |
| 190 |
|
| 191 |
if (self.git_hash_as_namespace == False): |
| 192 |
self.git_metric_namespace = self.git_fixed_namespace_text |
| 193 |
else: |
| 194 |
if (self.datetime_string == None): |
| 195 |
git_namespace_prepend_text = self.git_repo_name + "-" + self.git_hash |
| 196 |
else: |
| 197 |
git_namespace_prepend_text = self.git_repo_name + "/" + self.datetime_string + "-" + self.git_hash |
| 198 |
self.git_metric_namespace = git_namespace_prepend_text |
| 199 |
|
| 200 |
|
| 201 |
|
| 202 |
|
| 203 |
try: |
| 204 |
self.cloudwatch_client = boto3.client('cloudwatch', self.cloudwatch_region) |
| 205 |
self.cloudwatch_dashboard_name = self.git_metric_namespace |
| 206 |
except Exception as e: |
| 207 |
self.print_message("[DataSnapshot] ERROR - could not make Cloudwatch client due to exception!") |
| 208 |
self.print_message(f"[DataSnapshot] Exception: {repr(e)}") |
| 209 |
self.cloudwatch_client = None |
| 210 |
self.abort_due_to_internal_error = True |
| 211 |
self.abort_due_to_internal_error_reason = "Could not make Cloudwatch client!" |
| 212 |
return |
| 213 |
|
| 214 |
|
| 215 |
|
| 216 |
|
| 217 |
try: |
| 218 |
self.s3_client = boto3.client("s3") |
| 219 |
except Exception as e: |
| 220 |
self.print_message("[DataSnapshot] ERROR - could not make S3 client due to exception!") |
| 221 |
self.print_message(f"[DataSnapshot] Exception: {repr(e)}") |
| 222 |
self.s3_client = None |
| 223 |
self.abort_due_to_internal_error = True |
| 224 |
self.abort_due_to_internal_error_reason = "Could not make S3 client!" |
| 225 |
return |
| 226 |
|
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
try: |
| 231 |
self.lambda_client = boto3.client("lambda", self.cloudwatch_region) |
| 232 |
except Exception as e: |
| 233 |
self.print_message("[DataSnapshot] ERROR - could not make Lambda client due to exception!") |
| 234 |
self.print_message(f"[DataSnapshot] Exception: {repr(e)}") |
| 235 |
self.lambda_client = None |
| 236 |
self.abort_due_to_internal_error = True |
| 237 |
self.abort_due_to_internal_error_reason = "Could not make Lambda client!" |
| 238 |
return |
| 239 |
|
| 240 |
|
| 241 |
|
| 242 |
|
| 243 |
if (not output_log_filepath is None): |
| 244 |
self.output_to_file = True |
| 245 |
self.output_file = open(self.output_to_file_filepath, "w") |
| 246 |
else: |
| 247 |
self.output_to_file = False |
| 248 |
self.output_file = None |
| 249 |
|
| 250 |
|
| 251 |
self.print_message("[DataSnapshot] Data snapshot created!") |
| 252 |
|
| 253 |
|
| 254 |
|
| 255 |
def cleanup(self, error_occurred=False): |
| 256 |
if (self.s3_bucket_upload_on_complete == True): |
| 257 |
self.export_result_to_s3_bucket(copy_output_log=True, log_is_error=error_occurred) |
| 258 |
|
| 259 |
self._cleanup_cloudwatch_alarms() |
| 260 |
if (self.cloudwatch_make_dashboard == True): |
| 261 |
self._cleanup_cloudwatch_dashboard() |
| 262 |
|
| 263 |
self.print_message("[DataSnapshot] Data snapshot cleaned!") |
| 264 |
|
| 265 |
if (self.output_file is not None): |
| 266 |
self.output_file.close() |
| 267 |
self.output_file = None |
| 268 |
|
| 269 |
|
| 270 |
def print_message(self, message): |
| 271 |
if self.output_to_file == True: |
| 272 |
try: |
| 273 |
if (self.output_file is None): |
| 274 |
self.output_file = open(self.output_to_file_filepath, "w") |
| 275 |
self.output_file.write(message + "\n") |
| 276 |
|
| 277 |
except Exception as ex: |
| 278 |
print (f"[DataSnapshot] ERROR - Exception trying to print to file") |
| 279 |
print (f"[DataSnapshot] ERROR - Exception: {repr(ex)}") |
| 280 |
if (self.output_file is not None): |
| 281 |
self.output_file.close() |
| 282 |
self.output_file = None |
| 283 |
self.abort_due_to_internal_error = True |
| 284 |
self.abort_due_to_internal_error_reason = "Could not print data to output file!" |
| 285 |
|
| 286 |
if self.output_to_console == True: |
| 287 |
print(message, flush=True) |
| 288 |
|
| 289 |
|
| 290 |
|
| 291 |
def _init_cloudwatch_pre_first_run(self): |
| 292 |
for metric in self.metrics: |
| 293 |
if (not metric.metric_alarm_threshold is None): |
| 294 |
self._add_cloudwatch_metric_alarm(metric) |
| 295 |
|
| 296 |
if (self.cloudwatch_make_dashboard == True): |
| 297 |
self._init_cloudwatch_pre_first_run_dashboard() |
| 298 |
|
| 299 |
|
| 300 |
def _init_cloudwatch_pre_first_run_dashboard(self): |
| 301 |
try: |
| 302 |
|
| 303 |
self._cleanup_cloudwatch_dashboard() |
| 304 |
|
| 305 |
new_dashboard_widgets_array = [] |
| 306 |
for widget in self.cloudwatch_dashboard_widgets: |
| 307 |
new_dashboard_widgets_array.append(widget.get_widget_dictionary()) |
| 308 |
|
| 309 |
new_dashboard_body = { |
| 310 |
"start": "-PT1H", |
| 311 |
"widgets": new_dashboard_widgets_array, |
| 312 |
} |
| 313 |
new_dashboard_body_json = json.dumps(new_dashboard_body) |
| 314 |
|
| 315 |
self.cloudwatch_client.put_dashboard( |
| 316 |
DashboardName=self.cloudwatch_dashboard_name, |
| 317 |
DashboardBody= new_dashboard_body_json) |
| 318 |
self.print_message("[DataSnapshot] Added Cloudwatch dashboard successfully") |
| 319 |
except Exception as e: |
| 320 |
self.print_message(f"[DataSnapshot] ERROR - Cloudwatch client could not make dashboard due to exception") |
| 321 |
self.print_message(f"[DataSnapshot] ERROR - Exception: {repr(e)}") |
| 322 |
self.abort_due_to_internal_error = True |
| 323 |
self.abort_due_to_internal_error_reason = f"Cloudwatch client could not make dashboard due to exception" |
| 324 |
return |
| 325 |
|
| 326 |
|
| 327 |
def _add_cloudwatch_metric_alarm(self, metric): |
| 328 |
if self.cloudwatch_client is None: |
| 329 |
self.print_message("[DataSnapshot] ERROR - Cloudwatch client not setup. Cannot register alarm") |
| 330 |
return |
| 331 |
|
| 332 |
try: |
| 333 |
self.cloudwatch_client.put_metric_alarm( |
| 334 |
AlarmName=metric.metric_alarm_name, |
| 335 |
AlarmDescription=metric.metric_alarm_description, |
| 336 |
MetricName=metric.metric_name, |
| 337 |
Namespace=self.git_metric_namespace, |
| 338 |
Statistic="Maximum", |
| 339 |
Dimensions=metric.metric_dimensions, |
| 340 |
Period=60, |
| 341 |
EvaluationPeriods=120, |
| 342 |
DatapointsToAlarm=1, |
| 343 |
Threshold=metric.metric_alarm_threshold, |
| 344 |
ComparisonOperator="GreaterThanOrEqualToThreshold", |
| 345 |
) |
| 346 |
except Exception as e: |
| 347 |
self.print_message(f"[DataSnapshot] ERROR - could not register alarm for metric {metric.metric_name} due to exception") |
| 348 |
self.print_message(f"[DataSnapshot] ERROR - Exception {repr(e)}") |
| 349 |
self.abort_due_to_internal_error = True |
| 350 |
self.abort_due_to_internal_error_reason = f"Cloudwatch client could not make alarm due to exception" |
| 351 |
|
| 352 |
|
| 353 |
def _cleanup_cloudwatch_alarms(self): |
| 354 |
if (self.cloudwatch_teardown_alarms_on_complete == True): |
| 355 |
try: |
| 356 |
for metric in self.metrics: |
| 357 |
if (not metric.metric_alarm_threshold is None): |
| 358 |
self.cloudwatch_client.delete_alarms(AlarmNames=[metric.metric_alarm_name]) |
| 359 |
except Exception as e: |
| 360 |
self.print_message(f"[DataSnapshot] ERROR - could not delete alarms due to exception") |
| 361 |
self.print_message(f"[DataSnapshot] ERROR - Exception {repr(e)}") |
| 362 |
|
| 363 |
|
| 364 |
def _cleanup_cloudwatch_dashboard(self): |
| 365 |
if (self.cloudwatch_teardown_dashboard_on_complete == True): |
| 366 |
try: |
| 367 |
self.cloudwatch_client.delete_dashboards(DashboardNames=[self.cloudwatch_dashboard_name]) |
| 368 |
self.print_message("[DataSnapshot] Cloudwatch Dashboards deleted successfully!") |
| 369 |
except Exception as e: |
| 370 |
self.print_message(f"[DataSnapshot] ERROR - dashboard cleaning function failed due to exception") |
| 371 |
self.print_message(f"[DataSnapshot] ERROR - Exception {repr(e)}") |
| 372 |
self.abort_due_to_internal_error = True |
| 373 |
self.abort_due_to_internal_error_reason = "Cloudwatch dashboard cleaning function failed due to exception" |
| 374 |
return |
| 375 |
|
| 376 |
|
| 377 |
|
| 378 |
|
| 379 |
|
| 380 |
def get_cloudwatch_alarm_results(self): |
| 381 |
return self._check_cloudwatch_alarm_states() |
| 382 |
|
| 383 |
|
| 384 |
def _check_cloudwatch_alarm_states(self): |
| 385 |
return_result_list = [] |
| 386 |
|
| 387 |
tmp = None |
| 388 |
for metric in self.metrics: |
| 389 |
tmp = self._check_cloudwatch_alarm_state_metric(metric) |
| 390 |
if (tmp[1] != None): |
| 391 |
|
| 392 |
if ("Alive_Alarm" in tmp[1] == False): |
| 393 |
if (tmp[0] != True): |
| 394 |
return_result_list.append(tmp) |
| 395 |
|
| 396 |
return return_result_list |
| 397 |
|
| 398 |
|
| 399 |
|
| 400 |
def _check_cloudwatch_alarm_state_metric(self, metric): |
| 401 |
try: |
| 402 |
alarms_response = self.cloudwatch_client.describe_alarms_for_metric( |
| 403 |
MetricName=metric.metric_name, |
| 404 |
Namespace=self.git_metric_namespace, |
| 405 |
Dimensions=metric.metric_dimensions) |
| 406 |
|
| 407 |
return_result = [True, None, metric.metric_alarm_severity] |
| 408 |
|
| 409 |
for metric_alarm_dict in alarms_response["MetricAlarms"]: |
| 410 |
if metric_alarm_dict["StateValue"] == "ALARM": |
| 411 |
return_result[0] = False |
| 412 |
return_result[1] = metric_alarm_dict["AlarmName"] |
| 413 |
break |
| 414 |
|
| 415 |
return return_result |
| 416 |
except Exception as e: |
| 417 |
self.print_message(f"[DataSnapshot] ERROR - checking cloudwatch alarm failed due to exception") |
| 418 |
self.print_message(f"[DataSnapshot] ERROR - Exception {repr(e)}") |
| 419 |
return None |
| 420 |
|
| 421 |
|
| 422 |
|
| 423 |
|
| 424 |
def export_result_to_s3_bucket(self, copy_output_log=False, log_is_error=False): |
| 425 |
if (self.s3_client is None): |
| 426 |
self.print_message("[DataSnapshot] ERROR - No S3 client initialized! Cannot send log to S3") |
| 427 |
self.abort_due_to_internal_error = True |
| 428 |
self.abort_due_to_internal_error_reason = "S3 client not initialized and therefore cannot send log to S3" |
| 429 |
return |
| 430 |
|
| 431 |
s3_file = open(self.git_hash + ".log", "w") |
| 432 |
s3_file.write(self.git_hash) |
| 433 |
|
| 434 |
|
| 435 |
if (copy_output_log == True and self.output_to_file == True): |
| 436 |
|
| 437 |
is_output_file_open_previously = False |
| 438 |
if (self.output_file != None): |
| 439 |
self.output_file.close() |
| 440 |
is_output_file_open_previously = True |
| 441 |
self.output_file = open(self.output_to_file_filepath, "r") |
| 442 |
|
| 443 |
s3_file.write("\n\nOUTPUT LOG\n") |
| 444 |
s3_file.write("==========================================================================================\n") |
| 445 |
output_file_lines = self.output_file.readlines() |
| 446 |
for line in output_file_lines: |
| 447 |
s3_file.write(line) |
| 448 |
|
| 449 |
self.output_file.close() |
| 450 |
|
| 451 |
|
| 452 |
if (is_output_file_open_previously == True): |
| 453 |
self.output_to_file = open(self.output_to_file_filepath, "a") |
| 454 |
|
| 455 |
s3_file.close() |
| 456 |
|
| 457 |
|
| 458 |
try: |
| 459 |
if (log_is_error == False): |
| 460 |
if (self.datetime_string == None): |
| 461 |
self.s3_client.upload_file(self.git_hash + ".log", self.s3_bucket_name, self.git_repo_name + "/" + self.git_hash + ".log") |
| 462 |
else: |
| 463 |
self.s3_client.upload_file(self.git_hash + ".log", self.s3_bucket_name, self.git_repo_name + "/" + self.datetime_string + "/" + self.git_hash + ".log") |
| 464 |
else: |
| 465 |
if (self.datetime_string == None): |
| 466 |
self.s3_client.upload_file(self.git_hash + ".log", self.s3_bucket_name, self.git_repo_name + "/Failed_Logs/" + self.git_hash + ".log") |
| 467 |
else: |
| 468 |
self.s3_client.upload_file(self.git_hash + ".log", self.s3_bucket_name, self.git_repo_name + "/Failed_Logs/" + self.datetime_string + "/" + self.git_hash + ".log") |
| 469 |
self.print_message("[DataSnapshot] Uploaded to S3!") |
| 470 |
except Exception as e: |
| 471 |
self.print_message(f"[DataSnapshot] ERROR - could not upload to S3 due to exception") |
| 472 |
self.print_message(f"[DataSnapshot] ERROR - Exception {repr(e)}") |
| 473 |
self.abort_due_to_internal_error = True |
| 474 |
self.abort_due_to_internal_error_reason = "S3 client had exception and therefore could not upload log!" |
| 475 |
os.remove(self.git_hash + ".log") |
| 476 |
return |
| 477 |
|
| 478 |
|
| 479 |
os.remove(self.git_hash + ".log") |
| 480 |
|
| 481 |
|
| 482 |
|
| 483 |
|
| 484 |
def lambda_send_email(self, message, subject): |
| 485 |
payload = {"Message":message, "Subject":subject} |
| 486 |
payload_string = json.dumps(payload) |
| 487 |
|
| 488 |
try: |
| 489 |
self.lambda_client.invoke( |
| 490 |
FunctionName=self.lambda_name, |
| 491 |
InvocationType="Event", |
| 492 |
ClientContext="MQTT Wrapper Script", |
| 493 |
Payload=payload_string |
| 494 |
) |
| 495 |
except Exception as e: |
| 496 |
self.print_message(f"[DataSnapshot] ERROR - could not send email via Lambda due to exception") |
| 497 |
self.print_message(f"[DataSnapshot] ERROR - Exception {repr(e)}") |
| 498 |
self.abort_due_to_internal_error = True |
| 499 |
self.abort_due_to_internal_error_reason = "Lambda email function had an exception!" |
| 500 |
return |
| 501 |
|
| 502 |
|
| 503 |
|
| 504 |
|
| 505 |
|
| 506 |
|
| 507 |
|
| 508 |
|
| 509 |
|
| 510 |
|
| 511 |
def register_metric(self, new_metric_name, new_metric_function, new_metric_unit="None", |
| 512 |
new_metric_alarm_threshold=None, new_metric_reports_to_skip=0, new_metric_alarm_severity=6, is_percent=False): |
| 513 |
|
| 514 |
new_metric_dimensions = [] |
| 515 |
|
| 516 |
if (self.git_hash_as_namespace == False): |
| 517 |
git_namespace_prepend_text = self.git_repo_name + "-" + self.git_hash |
| 518 |
new_metric_dimensions.append( |
| 519 |
{"Name": git_namespace_prepend_text, "Value": new_metric_name}) |
| 520 |
else: |
| 521 |
new_metric_dimensions.append( |
| 522 |
{"Name": "System_Metrics", "Value": new_metric_name}) |
| 523 |
|
| 524 |
new_metric = DataSnapshot_Metric( |
| 525 |
metric_name=new_metric_name, |
| 526 |
metric_function=new_metric_function, |
| 527 |
metric_dimensions=new_metric_dimensions, |
| 528 |
metric_unit=new_metric_unit, |
| 529 |
metric_alarm_threshold=new_metric_alarm_threshold, |
| 530 |
metric_alarm_severity=new_metric_alarm_severity, |
| 531 |
git_hash=self.git_hash, |
| 532 |
git_repo_name=self.git_repo_name, |
| 533 |
reports_to_skip=new_metric_reports_to_skip, |
| 534 |
is_percent=is_percent |
| 535 |
) |
| 536 |
self.metrics.append(new_metric) |
| 537 |
|
| 538 |
self.metrics_numbers.append([]) |
| 539 |
|
| 540 |
def register_dashboard_widget(self, new_widget_name, metrics_to_add=[], new_widget_period=60): |
| 541 |
|
| 542 |
|
| 543 |
metric_dimension_string = "" |
| 544 |
if (self.git_hash_as_namespace == False): |
| 545 |
metric_dimension_string = self.git_repo_name + "-" + self.git_hash |
| 546 |
else: |
| 547 |
metric_dimension_string = "System_Metrics" |
| 548 |
|
| 549 |
widget = self._find_cloudwatch_widget(name=new_widget_name) |
| 550 |
if (widget == None): |
| 551 |
widget = DataSnapshot_Dashboard_Widget( |
| 552 |
widget_name=new_widget_name, metric_namespace=self.git_metric_namespace, |
| 553 |
metric_dimension=metric_dimension_string, |
| 554 |
cloudwatch_region=self.cloudwatch_region, |
| 555 |
widget_period=new_widget_period) |
| 556 |
self.cloudwatch_dashboard_widgets.append(widget) |
| 557 |
|
| 558 |
for metric in metrics_to_add: |
| 559 |
self.register_metric_to_dashboard_widget(widget_name=new_widget_name, metric_name=metric) |
| 560 |
|
| 561 |
def register_metric_to_dashboard_widget(self, widget_name, metric_name, widget=None): |
| 562 |
if widget is None: |
| 563 |
widget = self._find_cloudwatch_widget(name=widget_name) |
| 564 |
if widget is None: |
| 565 |
print ("[DataSnapshot] ERROR - could not find widget with name: " + widget_name, flush=True) |
| 566 |
return |
| 567 |
|
| 568 |
|
| 569 |
metric_name_formatted = metric_name |
| 570 |
|
| 571 |
widget.add_metric_to_widget(new_metric_name=metric_name_formatted) |
| 572 |
return |
| 573 |
|
| 574 |
def remove_metric_from_dashboard_widget(self, widget_name, metric_name, widget=None): |
| 575 |
if widget is None: |
| 576 |
widget = self._find_cloudwatch_widget(name=widget_name) |
| 577 |
if widget is None: |
| 578 |
print ("[DataSnapshot] ERROR - could not find widget with name: " + widget_name, flush=True) |
| 579 |
return |
| 580 |
widget.remove_metric_from_widget(existing_metric_name=metric_name) |
| 581 |
return |
| 582 |
|
| 583 |
def _find_cloudwatch_widget(self, name): |
| 584 |
result = None |
| 585 |
for widget in self.cloudwatch_dashboard_widgets: |
| 586 |
if widget.widget_name == name: |
| 587 |
return widget |
| 588 |
return result |
| 589 |
|
| 590 |
|
| 591 |
def export_metrics_console(self): |
| 592 |
datetime_now = datetime.datetime.now() |
| 593 |
datetime_string = datetime_now.strftime("%d-%m-%Y/%H:%M:%S") |
| 594 |
|
| 595 |
self.print_message("\n[DataSnapshot] Metric report: " + str(self.metric_report_number) + " (" + datetime_string + ")") |
| 596 |
for metric in self.metrics: |
| 597 |
if (metric.is_percent == True): |
| 598 |
self.print_message(" " + metric.metric_name + |
| 599 |
" - value: " + str(metric.metric_value) + "%") |
| 600 |
else: |
| 601 |
self.print_message(" " + metric.metric_name + |
| 602 |
" - value: " + str(metric.metric_value)) |
| 603 |
self.print_message("") |
| 604 |
|
| 605 |
|
| 606 |
|
| 607 |
|
| 608 |
def export_metrics_cloudwatch(self): |
| 609 |
if (self.cloudwatch_client == None): |
| 610 |
self.print_message("[DataSnapshot] Error - cannot export Cloudwatch metrics! Cloudwatch was not initialized.") |
| 611 |
self.abort_due_to_internal_error = True |
| 612 |
self.abort_due_to_internal_error_reason = "Could not export Cloudwatch metrics due to no Cloudwatch client initialized!" |
| 613 |
return |
| 614 |
|
| 615 |
self.print_message("[DataSnapshot] Preparing to send to Cloudwatch...") |
| 616 |
metrics_data = [] |
| 617 |
metric_data_tmp = None |
| 618 |
for metric in self.metrics: |
| 619 |
metric_data_tmp = metric.get_metric_cloudwatch_dictionary() |
| 620 |
if (not metric_data_tmp is None): |
| 621 |
metrics_data.append(metric_data_tmp) |
| 622 |
|
| 623 |
if (len(metrics_data) == 0): |
| 624 |
self.print_message("[DataSnapshot] INFO - no metric data to send. Skipping...") |
| 625 |
return |
| 626 |
|
| 627 |
try: |
| 628 |
self.cloudwatch_client.put_metric_data( |
| 629 |
Namespace=self.git_metric_namespace, |
| 630 |
MetricData=metrics_data) |
| 631 |
self.print_message("[DataSnapshot] Metrics sent to Cloudwatch.") |
| 632 |
except Exception as e: |
| 633 |
self.print_message(f"[DataSnapshot] Error - something when wrong posting cloudwatch metrics") |
| 634 |
self.print_message(f"[DataSnapshot] ERROR - Exception {repr(e)}") |
| 635 |
self.print_message("[DataSnapshot] Not going to crash - just going to try again later") |
| 636 |
return |
| 637 |
|
| 638 |
|
| 639 |
|
| 640 |
def post_metrics(self, psutil_process : psutil.Process): |
| 641 |
if (self.perform_final_initialization == True): |
| 642 |
self.perform_final_initialization = False |
| 643 |
self._init_cloudwatch_pre_first_run() |
| 644 |
|
| 645 |
|
| 646 |
for i in range(0, len(self.metrics)): |
| 647 |
metric_value = self.metrics[i].get_metric_value(psutil_process) |
| 648 |
self.metrics_numbers[i].insert(0, metric_value) |
| 649 |
|
| 650 |
|
| 651 |
if (len(self.metrics_numbers[i]) > self.metric_report_non_zero_count): |
| 652 |
amount_to_delete = len(self.metrics_numbers[i]) - self.metric_report_non_zero_count |
| 653 |
del self.metrics_numbers[i][-amount_to_delete:] |
| 654 |
|
| 655 |
|
| 656 |
if (len(self.metrics_numbers[i]) == self.metric_report_non_zero_count): |
| 657 |
non_zero_found = False |
| 658 |
for j in range(0, len(self.metrics_numbers[i])): |
| 659 |
if (self.metrics_numbers[i][j] != 0.0 and self.metrics_numbers[i][j] != None): |
| 660 |
non_zero_found = True |
| 661 |
break |
| 662 |
if (non_zero_found == False): |
| 663 |
self.print_message("\n[DataSnapshot] METRIC ZERO ERROR!") |
| 664 |
self.print_message(f"[DataSnapshot] Metric index {i} has been zero for last {self.metric_report_non_zero_count} reports!") |
| 665 |
self.print_message("\n") |
| 666 |
|
| 667 |
self.metric_report_number += 1 |
| 668 |
|
| 669 |
self.export_metrics_console() |
| 670 |
self.export_metrics_cloudwatch() |
| 671 |
|
| 672 |
def output_diagnosis_information(self, dependencies_list): |
| 673 |
|
| 674 |
|
| 675 |
self.print_message("\n========== Canary Wrapper diagnosis information ==========") |
| 676 |
self.print_message("\nRunning Canary for repository: " + self.git_repo_name) |
| 677 |
self.print_message("\t Commit hash: " + self.git_hash) |
| 678 |
|
| 679 |
if not dependencies_list == "": |
| 680 |
self.print_message("\nDependencies:") |
| 681 |
dependencies_list = dependencies_list.split(";") |
| 682 |
dependencies_list_found_hash = False |
| 683 |
for i in range(0, len(dependencies_list)): |
| 684 |
|
| 685 |
if (dependencies_list_found_hash == True): |
| 686 |
dependencies_list_found_hash = False |
| 687 |
continue |
| 688 |
self.print_message("* " + dependencies_list[i]) |
| 689 |
if (i+1 < len(dependencies_list)): |
| 690 |
self.print_message("\t Commit hash: " + dependencies_list[i+1]) |
| 691 |
dependencies_list_found_hash = True |
| 692 |
else: |
| 693 |
self.print_message("\t Commit hash: Unknown") |
| 694 |
|
| 695 |
if (self.metric_frequency != None): |
| 696 |
self.print_message("\nMetric Snapshot Frequency: " + str(self.metric_frequency) + " seconds") |
| 697 |
self.print_message("\nMetrics:") |
| 698 |
for metric in self.metrics: |
| 699 |
self.print_message("* " + metric.metric_name) |
| 700 |
if metric.metric_alarm_threshold is not None: |
| 701 |
self.print_message("\t Alarm Threshold: " + str(metric.metric_alarm_threshold)) |
| 702 |
self.print_message("\t Alarm Severity: " + str(metric.metric_alarm_severity)) |
| 703 |
else: |
| 704 |
self.print_message("\t No alarm set for metric.") |
| 705 |
|
| 706 |
self.print_message("\n") |
| 707 |
self.print_message("==========================================================") |
| 708 |
self.print_message("\n") |
| 709 |
|
| 710 |
|
| 711 |
|
| 712 |
class SnapshotMonitor(): |
| 713 |
def __init__(self, wrapper_data_snapshot, wrapper_metrics_wait_time) -> None: |
| 714 |
|
| 715 |
self.data_snapshot = wrapper_data_snapshot |
| 716 |
self.had_internal_error = False |
| 717 |
self.error_due_to_credentials = False |
| 718 |
self.internal_error_reason = "" |
| 719 |
self.error_due_to_alarm = False |
| 720 |
|
| 721 |
self.can_cut_ticket = False |
| 722 |
self.has_cut_ticket = False |
| 723 |
|
| 724 |
|
| 725 |
|
| 726 |
self.cloudwatch_current_alarms_triggered = [] |
| 727 |
|
| 728 |
|
| 729 |
if (self.data_snapshot.abort_due_to_internal_error == True): |
| 730 |
self.had_internal_error = True |
| 731 |
self.internal_error_reason = "Could not initialize DataSnapshot. Likely credentials are not setup!" |
| 732 |
if (self.data_snapshot.abort_due_to_internal_error_due_to_credentials == True): |
| 733 |
self.error_due_to_credentials = True |
| 734 |
self.data_snapshot.cleanup() |
| 735 |
return |
| 736 |
|
| 737 |
|
| 738 |
self.metric_post_timer = 0 |
| 739 |
self.metric_post_timer_time = wrapper_metrics_wait_time |
| 740 |
|
| 741 |
|
| 742 |
def register_metric(self, new_metric_name, new_metric_function, new_metric_unit="None", new_metric_alarm_threshold=None, |
| 743 |
new_metric_reports_to_skip=0, new_metric_alarm_severity=6): |
| 744 |
|
| 745 |
try: |
| 746 |
self.data_snapshot.register_metric( |
| 747 |
new_metric_name=new_metric_name, |
| 748 |
new_metric_function=new_metric_function, |
| 749 |
new_metric_unit=new_metric_unit, |
| 750 |
new_metric_alarm_threshold=new_metric_alarm_threshold, |
| 751 |
new_metric_reports_to_skip=new_metric_reports_to_skip, |
| 752 |
new_metric_alarm_severity=new_metric_alarm_severity) |
| 753 |
except Exception as e: |
| 754 |
self.print_message(f"[SnaptshotMonitor] ERROR - could not register metric in data snapshot due to exception") |
| 755 |
self.print_message(f"[SnaptshotMonitor] ERROR - Exception {repr(e)}") |
| 756 |
self.had_internal_error = True |
| 757 |
self.internal_error_reason = "Could not register metric in data snapshot due to exception" |
| 758 |
return |
| 759 |
|
| 760 |
def register_dashboard_widget(self, new_widget_name, metrics_to_add=[], widget_period=60): |
| 761 |
self.data_snapshot.register_dashboard_widget(new_widget_name=new_widget_name, metrics_to_add=metrics_to_add, new_widget_period=widget_period) |
| 762 |
|
| 763 |
def output_diagnosis_information(self, dependencies=""): |
| 764 |
self.data_snapshot.output_diagnosis_information(dependencies_list=dependencies) |
| 765 |
|
| 766 |
def check_alarms_for_new_alarms(self, triggered_alarms): |
| 767 |
|
| 768 |
if len(triggered_alarms) > 0: |
| 769 |
self.data_snapshot.print_message( |
| 770 |
"WARNING - One or more alarms are in state of ALARM") |
| 771 |
|
| 772 |
old_alarms_still_active = [] |
| 773 |
new_alarms = [] |
| 774 |
new_alarms_highest_severity = 6 |
| 775 |
new_alarm_found = True |
| 776 |
new_alarm_ticket_description = "Canary has metrics in ALARM state!\n\nMetrics in alarm:\n" |
| 777 |
|
| 778 |
for triggered_alarm in triggered_alarms: |
| 779 |
new_alarm_found = True |
| 780 |
|
| 781 |
|
| 782 |
for old_alarm_name in self.cloudwatch_current_alarms_triggered: |
| 783 |
if (old_alarm_name == triggered_alarm[1]): |
| 784 |
new_alarm_found = False |
| 785 |
old_alarms_still_active.append(triggered_alarm[1]) |
| 786 |
|
| 787 |
new_alarm_ticket_description += "* (STILL IN ALARM) " + triggered_alarm[1] + "\n" |
| 788 |
new_alarm_ticket_description += "\tSeverity: " + str(triggered_alarm[2]) |
| 789 |
new_alarm_ticket_description += "\n" |
| 790 |
break |
| 791 |
|
| 792 |
|
| 793 |
if (new_alarm_found == True): |
| 794 |
self.data_snapshot.print_message(' (NEW) Alarm with name "' + triggered_alarm[1] + '" is in the ALARM state!') |
| 795 |
new_alarms.append(triggered_alarm[1]) |
| 796 |
if (triggered_alarm[2] < new_alarms_highest_severity): |
| 797 |
new_alarms_highest_severity = triggered_alarm[2] |
| 798 |
new_alarm_ticket_description += "* " + triggered_alarm[1] + "\n" |
| 799 |
new_alarm_ticket_description += "\tSeverity: " + str(triggered_alarm[2]) |
| 800 |
new_alarm_ticket_description += "\n" |
| 801 |
|
| 802 |
|
| 803 |
if len(new_alarms) > 0: |
| 804 |
if (self.can_cut_ticket == True): |
| 805 |
cut_ticket_using_cloudwatch( |
| 806 |
git_repo_name=self.data_snapshot.git_repo_name, |
| 807 |
git_hash=self.data_snapshot.git_hash, |
| 808 |
git_hash_as_namespace=False, |
| 809 |
git_fixed_namespace_text=self.data_snapshot.git_fixed_namespace_text, |
| 810 |
cloudwatch_region="us-east-1", |
| 811 |
ticket_description="New metric(s) went into alarm for the Canary! Metrics in alarm: " + str(new_alarms), |
| 812 |
ticket_reason="New metric(s) went into alarm", |
| 813 |
ticket_allow_duplicates=True, |
| 814 |
ticket_category="AWS", |
| 815 |
ticket_item="IoT SDK for CPP", |
| 816 |
ticket_group="AWS IoT Device SDK", |
| 817 |
ticket_type="SDKs and Tools", |
| 818 |
ticket_severity=4) |
| 819 |
self.has_cut_ticket = True |
| 820 |
|
| 821 |
|
| 822 |
self.cloudwatch_current_alarms_triggered = old_alarms_still_active + new_alarms |
| 823 |
|
| 824 |
else: |
| 825 |
self.cloudwatch_current_alarms_triggered.clear() |
| 826 |
|
| 827 |
|
| 828 |
def monitor_loop_function(self, psutil_process : psutil.Process, time_passed=30): |
| 829 |
|
| 830 |
if (self.data_snapshot.abort_due_to_internal_error == True): |
| 831 |
self.had_internal_error = True |
| 832 |
self.internal_error_reason = "Data Snapshot internal error: " + self.data_snapshot.abort_due_to_internal_error_reason |
| 833 |
return |
| 834 |
|
| 835 |
try: |
| 836 |
|
| 837 |
if (self.had_internal_error == False): |
| 838 |
|
| 839 |
triggered_alarms = self.data_snapshot.get_cloudwatch_alarm_results() |
| 840 |
self.check_alarms_for_new_alarms(triggered_alarms) |
| 841 |
except Exception as e: |
| 842 |
self.print_message("[SnaptshotMonitor] ERROR - exception occurred checking metric alarms!") |
| 843 |
self.print_message(f"[SnaptshotMonitor] ERROR - Exception {repr(e)}") |
| 844 |
self.print_message("[SnaptshotMonitor] Not going to crash - just going to try again later") |
| 845 |
return |
| 846 |
|
| 847 |
if (self.metric_post_timer <= 0): |
| 848 |
if (self.had_internal_error == False): |
| 849 |
try: |
| 850 |
self.data_snapshot.post_metrics(psutil_process) |
| 851 |
except Exception as e: |
| 852 |
self.print_message("[SnaptshotMonitor] ERROR - exception occurred posting metrics!") |
| 853 |
self.print_message(f"[SnaptshotMonitor] ERROR - Exception {repr(e)}") |
| 854 |
self.print_message("[SnaptshotMonitor] Not going to crash - just going to try again later") |
| 855 |
|
| 856 |
self.metric_post_timer += self.metric_post_timer_time |
| 857 |
return |
| 858 |
|
| 859 |
|
| 860 |
self.metric_post_timer += self.metric_post_timer_time |
| 861 |
|
| 862 |
|
| 863 |
self.metric_post_timer -= time_passed |
| 864 |
|
| 865 |
|
| 866 |
def send_email(self, email_body, email_subject_text_append=None): |
| 867 |
if (email_subject_text_append != None): |
| 868 |
self.data_snapshot.lambda_send_email(email_body, "Canary: " + self.data_snapshot.git_repo_name + ":" + self.data_snapshot.git_hash + " - " + email_subject_text_append) |
| 869 |
else: |
| 870 |
self.data_snapshot.lambda_send_email(email_body, "Canary: " + self.data_snapshot.git_repo_name + ":" + self.data_snapshot.git_hash) |
| 871 |
|
| 872 |
|
| 873 |
def stop_monitoring(self): |
| 874 |
|
| 875 |
pass |
| 876 |
|
| 877 |
|
| 878 |
def start_monitoring(self): |
| 879 |
|
| 880 |
pass |
| 881 |
|
| 882 |
|
| 883 |
def restart_monitoring(self): |
| 884 |
|
| 885 |
pass |
| 886 |
|
| 887 |
|
| 888 |
def cleanup_monitor(self, error_occurred=False): |
| 889 |
self.data_snapshot.cleanup(error_occurred=error_occurred) |
| 890 |
|
| 891 |
def print_message(self, message): |
| 892 |
if (self.data_snapshot != None): |
| 893 |
self.data_snapshot.print_message(message) |
| 894 |
else: |
| 895 |
print(message, flush=True) |
| 896 |
|
| 897 |
|
| 898 |
|
| 899 |
class ApplicationMonitor(): |
| 900 |
def __init__(self, wrapper_application_path, wrapper_application_arguments, wrapper_application_restart_on_finish=True, data_snapshot=None) -> None: |
| 901 |
self.application_process = None |
| 902 |
self.application_process_psutil = None |
| 903 |
self.error_has_occurred = False |
| 904 |
self.error_due_to_credentials = False |
| 905 |
self.error_reason = "" |
| 906 |
self.error_code = 0 |
| 907 |
self.wrapper_application_path = wrapper_application_path |
| 908 |
self.wrapper_application_arguments = wrapper_application_arguments |
| 909 |
self.wrapper_application_restart_on_finish = wrapper_application_restart_on_finish |
| 910 |
self.data_snapshot=data_snapshot |
| 911 |
self.still_running_wait_number = 0 |
| 912 |
self.stdout_file_path = "Canary_Stdout_File.txt" |
| 913 |
|
| 914 |
def start_monitoring(self): |
| 915 |
self.print_message("[ApplicationMonitor] Starting to monitor application...") |
| 916 |
|
| 917 |
if (self.application_process == None): |
| 918 |
try: |
| 919 |
canary_command = self.wrapper_application_path + " " + self.wrapper_application_arguments |
| 920 |
self.application_process = subprocess.Popen(canary_command + " | tee " + self.stdout_file_path, shell=True) |
| 921 |
self.application_process_psutil = psutil.Process(self.application_process.pid) |
| 922 |
self.print_message ("[ApplicationMonitor] Application started...") |
| 923 |
except Exception as e: |
| 924 |
self.print_message ("[ApplicationMonitor] ERROR - Could not launch Canary/Application due to exception!") |
| 925 |
self.print_message(f"[ApplicationMonitor] ERROR - Exception {repr(e)}") |
| 926 |
self.error_has_occurred = True |
| 927 |
self.error_reason = "Could not launch Canary/Application due to exception" |
| 928 |
self.error_code = 1 |
| 929 |
return |
| 930 |
else: |
| 931 |
self.print_message("[ApplicationMonitor] ERROR - Monitor already has an application process! Cannot monitor two applications with one monitor class!") |
| 932 |
|
| 933 |
def restart_monitoring(self): |
| 934 |
self.print_message ("[ApplicationMonitor] Restarting monitor application...") |
| 935 |
|
| 936 |
if (self.application_process != None): |
| 937 |
try: |
| 938 |
self.stop_monitoring() |
| 939 |
self.start_monitoring() |
| 940 |
self.print_message("\n[ApplicationMonitor] Restarted monitor application!") |
| 941 |
self.print_message("================================================================================") |
| 942 |
except Exception as e: |
| 943 |
self.print_message(f"[ApplicationMonitor] ERROR - Could not restart Canary/Application due to exception") |
| 944 |
self.print_message(f"[ApplicationMonitor] ERROR - Exception {repr(e)}") |
| 945 |
self.error_has_occurred = True |
| 946 |
self.error_reason = "Could not restart Canary/Application due to exception" |
| 947 |
self.error_code = 1 |
| 948 |
return |
| 949 |
else: |
| 950 |
self.print_message("[ApplicationMonitor] ERROR - Application process restart called but process is/was not running!") |
| 951 |
self.error_has_occurred = True |
| 952 |
self.error_reason = "Could not restart Canary/Application due to application process not being started initially" |
| 953 |
self.error_code = 1 |
| 954 |
return |
| 955 |
|
| 956 |
|
| 957 |
def stop_monitoring(self): |
| 958 |
self.print_message ("[ApplicationMonitor] Stopping monitor application...") |
| 959 |
if (not self.application_process == None): |
| 960 |
self.application_process.terminate() |
| 961 |
self.application_process.wait() |
| 962 |
self.print_message ("[ApplicationMonitor] Stopped monitor application!") |
| 963 |
self.application_process = None |
| 964 |
self.print_stdout() |
| 965 |
else: |
| 966 |
self.print_message ("[ApplicationMonitor] ERROR - cannot stop monitor application because no process is found!") |
| 967 |
|
| 968 |
def print_stdout(self): |
| 969 |
|
| 970 |
if (os.path.isfile(self.stdout_file_path)): |
| 971 |
self.print_message("Just finished Application STDOUT: ") |
| 972 |
try: |
| 973 |
with open(self.stdout_file_path, "r") as stdout_file: |
| 974 |
self.print_message(stdout_file.read()) |
| 975 |
os.remove(self.stdout_file_path) |
| 976 |
except Exception as e: |
| 977 |
self.print_message(f"[ApplicationMonitor] ERROR - Could not print Canary/Application stdout to exception") |
| 978 |
self.print_message(f"[ApplicationMonitor] ERROR - Exception {repr(e)}") |
| 979 |
|
| 980 |
def monitor_loop_function(self, time_passed=30): |
| 981 |
if (self.application_process != None): |
| 982 |
|
| 983 |
application_process_return_code = None |
| 984 |
try: |
| 985 |
application_process_return_code = self.application_process.poll() |
| 986 |
except Exception as e: |
| 987 |
self.print_message("[ApplicationMonitor] ERROR - exception occurred while trying to poll application status!") |
| 988 |
self.print_message(f"[ApplicationMonitor] ERROR - Exception {repr(e)}") |
| 989 |
self.error_has_occurred = True |
| 990 |
self.error_reason = "Exception when polling application status" |
| 991 |
self.error_code = 1 |
| 992 |
return |
| 993 |
|
| 994 |
|
| 995 |
if (application_process_return_code != None): |
| 996 |
self.print_message("[ApplicationMonitor] Monitor application has stopped! Processing result...") |
| 997 |
|
| 998 |
if (application_process_return_code != 0): |
| 999 |
self.print_message("[ApplicationMonitor] ERROR - Something Crashed in Canary/Application!") |
| 1000 |
self.print_message("[ApplicationMonitor] Error code: " + str(application_process_return_code)) |
| 1001 |
|
| 1002 |
self.error_has_occurred = True |
| 1003 |
self.error_reason = "Canary application crashed!" |
| 1004 |
self.error_code = application_process_return_code |
| 1005 |
else: |
| 1006 |
|
| 1007 |
if (self.wrapper_application_restart_on_finish == True): |
| 1008 |
self.print_message("[ApplicationMonitor] NOTE - Canary finished running and is restarting...") |
| 1009 |
self.restart_monitoring() |
| 1010 |
else: |
| 1011 |
self.print_message("[ApplicationMonitor] Monitor application has stopped and monitor is not supposed to restart... Finishing...") |
| 1012 |
self.error_has_occurred = True |
| 1013 |
self.error_reason = "Canary Application Finished" |
| 1014 |
self.error_code = 0 |
| 1015 |
else: |
| 1016 |
|
| 1017 |
self.still_running_wait_number =+ 1 |
| 1018 |
if self.still_running_wait_number >= 4: |
| 1019 |
self.print_message("[ApplicationMonitor] Monitor application is still running...") |
| 1020 |
self.still_running_wait_number = 0 |
| 1021 |
|
| 1022 |
def cleanup_monitor(self, error_occurred=False): |
| 1023 |
pass |
| 1024 |
|
| 1025 |
def print_message(self, message): |
| 1026 |
if (self.data_snapshot != None): |
| 1027 |
self.data_snapshot.print_message(message) |
| 1028 |
else: |
| 1029 |
print(message, flush=True) |
| 1030 |
|
| 1031 |
|
| 1032 |
|
| 1033 |
class S3Monitor(): |
| 1034 |
|
| 1035 |
def __init__(self, s3_bucket_name, s3_file_name, s3_file_name_in_zip, canary_local_application_path, data_snapshot) -> None: |
| 1036 |
self.s3_client = None |
| 1037 |
self.s3_current_object_version_id = None |
| 1038 |
self.s3_current_object_last_modified = None |
| 1039 |
self.s3_bucket_name = s3_bucket_name |
| 1040 |
self.s3_file_name = s3_file_name |
| 1041 |
self.s3_file_name_only_path, self.s3_file_name_only_extension = os.path.splitext(s3_file_name) |
| 1042 |
self.data_snapshot = data_snapshot |
| 1043 |
|
| 1044 |
self.canary_local_application_path = canary_local_application_path |
| 1045 |
|
| 1046 |
self.s3_file_name_in_zip = s3_file_name_in_zip |
| 1047 |
self.s3_file_name_in_zip_only_path = None |
| 1048 |
self.s3_file_name_in_zip_only_extension = None |
| 1049 |
if (self.s3_file_name_in_zip != None): |
| 1050 |
self.s3_file_name_in_zip_only_path, self.s3_file_name_in_zip_only_extension = os.path.splitext(s3_file_name_in_zip) |
| 1051 |
|
| 1052 |
self.s3_file_needs_replacing = False |
| 1053 |
|
| 1054 |
self.had_internal_error = False |
| 1055 |
self.error_due_to_credentials = False |
| 1056 |
self.internal_error_reason = "" |
| 1057 |
|
| 1058 |
|
| 1059 |
|
| 1060 |
try: |
| 1061 |
tmp_sts_client = boto3.client('sts') |
| 1062 |
tmp_sts_client.get_caller_identity() |
| 1063 |
except Exception as e: |
| 1064 |
self.print_message("[S3Monitor] ERROR - (S3 Check) AWS credentials are NOT valid!") |
| 1065 |
self.print_message(f"[S3Monitor] ERROR - Exception {repr(e)}") |
| 1066 |
self.had_internal_error = True |
| 1067 |
self.error_due_to_credentials = True |
| 1068 |
self.internal_error_reason = "AWS credentials are NOT valid!" |
| 1069 |
return |
| 1070 |
|
| 1071 |
|
| 1072 |
try: |
| 1073 |
self.s3_client = boto3.client("s3") |
| 1074 |
except Exception as e: |
| 1075 |
self.print_message("[S3Monitor] ERROR - (S3 Check) Could not make S3 client") |
| 1076 |
self.print_message(f"[S3Monitor] ERROR - Exception {repr(e)}") |
| 1077 |
self.had_internal_error = True |
| 1078 |
self.internal_error_reason = "Could not make S3 client for S3 Monitor" |
| 1079 |
return |
| 1080 |
|
| 1081 |
|
| 1082 |
def check_for_file_change(self): |
| 1083 |
try: |
| 1084 |
version_check_response = self.s3_client.list_object_versions( |
| 1085 |
Bucket=self.s3_bucket_name, |
| 1086 |
Prefix=self.s3_file_name_only_path) |
| 1087 |
if "Versions" in version_check_response: |
| 1088 |
for version in version_check_response["Versions"]: |
| 1089 |
if (version["IsLatest"] == True): |
| 1090 |
if (version["VersionId"] != self.s3_current_object_version_id or |
| 1091 |
version["LastModified"] != self.s3_current_object_last_modified): |
| 1092 |
|
| 1093 |
self.print_message("[S3Monitor] Found new version of Canary/Application in S3!") |
| 1094 |
self.print_message("[S3Monitor] Changing running Canary/Application to new one...") |
| 1095 |
|
| 1096 |
|
| 1097 |
self.s3_file_needs_replacing = True |
| 1098 |
|
| 1099 |
self.s3_current_object_version_id = version["VersionId"] |
| 1100 |
self.s3_current_object_last_modified = version["LastModified"] |
| 1101 |
return |
| 1102 |
|
| 1103 |
except Exception as e: |
| 1104 |
self.print_message(f"[S3Monitor] ERROR - Could not check for new version of file in S3 due to exception") |
| 1105 |
self.print_message(f"[S3Monitor] ERROR - Exception {repr(e)}") |
| 1106 |
self.print_message("[S3Monitor] Going to try again later - will not crash Canary") |
| 1107 |
|
| 1108 |
|
| 1109 |
def replace_current_file_for_new_file(self): |
| 1110 |
try: |
| 1111 |
self.print_message("[S3Monitor] Making directory...") |
| 1112 |
if not os.path.exists("tmp"): |
| 1113 |
os.makedirs("tmp") |
| 1114 |
except Exception as e: |
| 1115 |
self.print_message ("[S3Monitor] ERROR - could not make tmp directory to place S3 file into!") |
| 1116 |
self.print_message(f"[S3Monitor] ERROR - Exception {repr(e)}") |
| 1117 |
self.had_internal_error = True |
| 1118 |
self.internal_error_reason = "Could not make TMP folder for S3 file download" |
| 1119 |
return |
| 1120 |
|
| 1121 |
|
| 1122 |
new_file_path = "tmp/new_file" + self.s3_file_name_only_extension |
| 1123 |
try: |
| 1124 |
self.print_message("[S3Monitor] Downloading file...") |
| 1125 |
s3_resource = boto3.resource("s3") |
| 1126 |
s3_resource.meta.client.download_file(self.s3_bucket_name, self.s3_file_name, new_file_path) |
| 1127 |
except Exception as e: |
| 1128 |
self.print_message("[S3Monitor] ERROR - could not download latest S3 file into TMP folder!") |
| 1129 |
self.print_message(f"[S3Monitor] ERROR - Exception {repr(e)}") |
| 1130 |
self.had_internal_error = True |
| 1131 |
self.internal_error_reason = "Could not download latest S3 file into TMP folder" |
| 1132 |
return |
| 1133 |
|
| 1134 |
|
| 1135 |
if (self.s3_file_name_in_zip != None): |
| 1136 |
self.print_message("[S3Monitor] New file is zip file. Unzipping...") |
| 1137 |
|
| 1138 |
with zipfile.ZipFile(new_file_path, 'r') as zip_file: |
| 1139 |
zip_file.extractall("tmp/new_file_zip") |
| 1140 |
new_file_path = "tmp/new_file_zip/" + self.s3_file_name_in_zip_only_path + self.s3_file_name_in_zip_only_extension |
| 1141 |
|
| 1142 |
try: |
| 1143 |
|
| 1144 |
if os.path.exists(self.canary_local_application_path) == True: |
| 1145 |
os.remove(self.canary_local_application_path) |
| 1146 |
|
| 1147 |
self.print_message("[S3Monitor] Moving file...") |
| 1148 |
os.replace(new_file_path, self.canary_local_application_path) |
| 1149 |
self.print_message("[S3Monitor] Getting execution rights...") |
| 1150 |
os.system("chmod u+x " + self.canary_local_application_path) |
| 1151 |
|
| 1152 |
except Exception as e: |
| 1153 |
self.print_message("[S3Monitor] ERROR - could not move file into local application path due to exception!") |
| 1154 |
self.print_message(f"[S3Monitor] ERROR - Exception {repr(e)}") |
| 1155 |
self.had_internal_error = True |
| 1156 |
self.internal_error_reason = "Could not move file into local application path" |
| 1157 |
return |
| 1158 |
|
| 1159 |
self.print_message("[S3Monitor] New file downloaded and moved into correct location!") |
| 1160 |
self.s3_file_needs_replacing = False |
| 1161 |
|
| 1162 |
|
| 1163 |
def stop_monitoring(self): |
| 1164 |
|
| 1165 |
pass |
| 1166 |
|
| 1167 |
|
| 1168 |
def start_monitoring(self): |
| 1169 |
|
| 1170 |
pass |
| 1171 |
|
| 1172 |
|
| 1173 |
def restart_monitoring(self): |
| 1174 |
|
| 1175 |
pass |
| 1176 |
|
| 1177 |
|
| 1178 |
def cleanup_monitor(self): |
| 1179 |
|
| 1180 |
pass |
| 1181 |
|
| 1182 |
def monitor_loop_function(self, time_passed=30): |
| 1183 |
self.check_for_file_change() |
| 1184 |
|
| 1185 |
def print_message(self, message): |
| 1186 |
if (self.data_snapshot != None): |
| 1187 |
self.data_snapshot.print_message(message) |
| 1188 |
else: |
| 1189 |
print(message, flush=True) |
| 1190 |
|
| 1191 |
|
| 1192 |
|
| 1193 |
|
| 1194 |
|
| 1195 |
|
| 1196 |
|
| 1197 |
|
| 1198 |
|
| 1199 |
def cut_ticket_using_cloudwatch( |
| 1200 |
ticket_description="Description here!", |
| 1201 |
ticket_reason="Reason here!", |
| 1202 |
ticket_severity=5, |
| 1203 |
ticket_category="AWS", |
| 1204 |
ticket_type="SDKs and Tools", |
| 1205 |
ticket_item="IoT SDK for CPP", |
| 1206 |
ticket_group="AWS IoT Device SDK", |
| 1207 |
ticket_allow_duplicates=False, |
| 1208 |
git_repo_name="REPO NAME", |
| 1209 |
git_hash="HASH", |
| 1210 |
git_hash_as_namespace=False, |
| 1211 |
git_fixed_namespace_text="mqtt5_canary", |
| 1212 |
cloudwatch_region="us-east-1"): |
| 1213 |
|
| 1214 |
git_metric_namespace = "" |
| 1215 |
if (git_hash_as_namespace == False): |
| 1216 |
git_metric_namespace = git_fixed_namespace_text |
| 1217 |
else: |
| 1218 |
git_namespace_prepend_text = git_repo_name + "-" + git_hash |
| 1219 |
git_metric_namespace = git_namespace_prepend_text |
| 1220 |
|
| 1221 |
try: |
| 1222 |
cloudwatch_client = boto3.client('cloudwatch', cloudwatch_region) |
| 1223 |
ticket_alarm_name = git_repo_name + "-" + git_hash + "-AUTO-TICKET" |
| 1224 |
except Exception as e: |
| 1225 |
print (f"ERROR - could not create Cloudwatch client to make ticket metric alarm due to exception", flush=True) |
| 1226 |
print(f"ERROR - Exception {repr(e)}", flush=True) |
| 1227 |
return |
| 1228 |
|
| 1229 |
new_metric_dimensions = [] |
| 1230 |
if (git_hash_as_namespace == False): |
| 1231 |
git_namespace_prepend_text = git_repo_name + "-" + git_hash |
| 1232 |
new_metric_dimensions.append( |
| 1233 |
{"Name": git_namespace_prepend_text, "Value": ticket_alarm_name}) |
| 1234 |
else: |
| 1235 |
new_metric_dimensions.append( |
| 1236 |
{"Name": "System_Metrics", "Value": ticket_alarm_name}) |
| 1237 |
|
| 1238 |
ticket_arn = f"arn:aws:cloudwatch::cwa-internal:ticket:{ticket_severity}:{ticket_category}:{ticket_type}:{ticket_item}:{ticket_group}:" |
| 1239 |
if (ticket_allow_duplicates == True): |
| 1240 |
|
| 1241 |
ticket_arn += "DO-NOT-DEDUPE" |
| 1242 |
|
| 1243 |
ticket_arn = ticket_arn.replace(" ", "+") |
| 1244 |
|
| 1245 |
ticket_alarm_description = f"AUTO CUT CANARY WRAPPER TICKET\n\nREASON: {ticket_reason}\n\nDESCRIPTION: {ticket_description}\n\n" |
| 1246 |
|
| 1247 |
|
| 1248 |
try: |
| 1249 |
cloudwatch_client.put_metric_alarm( |
| 1250 |
AlarmName=ticket_alarm_name, |
| 1251 |
AlarmDescription=ticket_alarm_description, |
| 1252 |
MetricName=ticket_alarm_name, |
| 1253 |
Namespace=git_metric_namespace, |
| 1254 |
Statistic="Maximum", |
| 1255 |
Dimensions=new_metric_dimensions, |
| 1256 |
Period=60, |
| 1257 |
EvaluationPeriods=1, |
| 1258 |
DatapointsToAlarm=1, |
| 1259 |
Threshold=1, |
| 1260 |
ComparisonOperator="GreaterThanOrEqualToThreshold", |
| 1261 |
|
| 1262 |
|
| 1263 |
AlarmActions=[ticket_arn] |
| 1264 |
) |
| 1265 |
except Exception as e: |
| 1266 |
print (f"ERROR - could not create ticket metric alarm due to exception", flush=True) |
| 1267 |
print(f"ERROR - Exception {repr(e)}", flush=True) |
| 1268 |
return |
| 1269 |
|
| 1270 |
|
| 1271 |
try: |
| 1272 |
cloudwatch_client.set_alarm_state( |
| 1273 |
AlarmName=ticket_alarm_name, |
| 1274 |
StateValue="ALARM", |
| 1275 |
StateReason="AUTO TICKET CUT") |
| 1276 |
except Exception as e: |
| 1277 |
print (f"ERROR - could not cut ticket due to exception", flush=True) |
| 1278 |
print(f"ERROR - Exception {repr(e)}", flush=True) |
| 1279 |
return |
| 1280 |
|
| 1281 |
print("Waiting for ticket metric to trigger...", flush=True) |
| 1282 |
|
| 1283 |
time.sleep(2) |
| 1284 |
|
| 1285 |
|
| 1286 |
print("Removing ticket metric...", flush=True) |
| 1287 |
cloudwatch_client.delete_alarms(AlarmNames=[ticket_alarm_name]) |
| 1288 |
|
| 1289 |
print ("Finished cutting ticket via Cloudwatch!", flush=True) |
| 1290 |
return |
| 1291 |
|
| 1292 |
|
| 1293 |
def cut_ticket_using_cloudwatch_from_args( |
| 1294 |
ticket_description="", |
| 1295 |
ticket_reason="", |
| 1296 |
ticket_severity=6, |
| 1297 |
arguments=None): |
| 1298 |
|
| 1299 |
|
| 1300 |
if (ticket_severity >= 6): |
| 1301 |
return |
| 1302 |
|
| 1303 |
cut_ticket_using_cloudwatch( |
| 1304 |
ticket_description=ticket_description, |
| 1305 |
ticket_reason=ticket_reason, |
| 1306 |
ticket_severity=ticket_severity, |
| 1307 |
ticket_category=arguments.ticket_category, |
| 1308 |
ticket_type=arguments.ticket_type, |
| 1309 |
ticket_item=arguments.ticket_item, |
| 1310 |
ticket_group=arguments.ticket_group, |
| 1311 |
ticket_allow_duplicates=False, |
| 1312 |
git_repo_name=arguments.git_repo_name, |
| 1313 |
git_hash=arguments.git_hash, |
| 1314 |
git_hash_as_namespace=arguments.git_hash_as_namespace) |
| 1315 |
|
| 1316 |
|