|
| 1 | +import boto3 |
| 2 | +from datetime import datetime |
| 3 | +import xml.etree.ElementTree as ET |
| 4 | +import os |
| 5 | + |
| 6 | + |
| 7 | +xml_path = "../canary/integration_tests.xml" |
| 8 | + |
| 9 | +def readXML_and_publish_metrics_to_cw(): |
| 10 | + if os.path.isfile(xml_path): |
| 11 | + tree = ET.parse(xml_path) |
| 12 | + testsuite = tree.find("testsuite") |
| 13 | + failures = testsuite.attrib["failures"] |
| 14 | + tests = testsuite.attrib["tests"] |
| 15 | + successes = int(tests) - int(failures) |
| 16 | + else: |
| 17 | + failures = 0 |
| 18 | + successes = 0 |
| 19 | + tests = 1 |
| 20 | + |
| 21 | + timestamp = datetime.now().strftime("%Y-%m-%dT%H:%M:%S") |
| 22 | + |
| 23 | + print(f"Failures: {failures}") |
| 24 | + print(f"Total tests: {tests}") |
| 25 | + |
| 26 | + # push to cloudwatch |
| 27 | + cw_client = boto3.client("cloudwatch") |
| 28 | + project_name = "CodeBuild-Run-All-Tests" |
| 29 | + |
| 30 | + # Define the metric data |
| 31 | + metric_data = [ |
| 32 | + { |
| 33 | + "MetricName": "failures", |
| 34 | + "Timestamp": timestamp, |
| 35 | + "Dimensions": [ |
| 36 | + {"Name": "CodeBuild Project Name", "Value": project_name}, |
| 37 | + ], |
| 38 | + "Value": int(failures), |
| 39 | + "Unit": "Count", |
| 40 | + }, |
| 41 | + { |
| 42 | + "MetricName": "total_tests", |
| 43 | + "Timestamp": timestamp, |
| 44 | + "Dimensions": [ |
| 45 | + {"Name": "CodeBuild Project Name", "Value": project_name}, |
| 46 | + ], |
| 47 | + "Value": int(tests), |
| 48 | + "Unit": "Count", |
| 49 | + }, |
| 50 | + { |
| 51 | + "MetricName": "successes", |
| 52 | + "Timestamp": timestamp, |
| 53 | + "Dimensions": [ |
| 54 | + {"Name": "CodeBuild Project Name", "Value": project_name}, |
| 55 | + ], |
| 56 | + "Value": int(successes), |
| 57 | + "Unit": "Count", |
| 58 | + }, |
| 59 | + ] |
| 60 | + |
| 61 | + # Use the put_metric_data method to push the metric data to CloudWatch |
| 62 | + try: |
| 63 | + response = cw_client.put_metric_data( |
| 64 | + Namespace="Canary_Telemetry", MetricData=metric_data |
| 65 | + ) |
| 66 | + if response["ResponseMetadata"]["HTTPStatusCode"] == 200: |
| 67 | + print("Successfully pushed data to CloudWatch") |
| 68 | + # return 200 status code if successful |
| 69 | + return 200 |
| 70 | + else: |
| 71 | + # raise exception if the status code is not 200 |
| 72 | + raise Exception( |
| 73 | + "Unexpected response status code: {}".format( |
| 74 | + response["ResponseMetadata"]["HTTPStatusCode"] |
| 75 | + ) |
| 76 | + ) |
| 77 | + except Exception as e: |
| 78 | + print("Error pushing data to CloudWatch: {}".format(e)) |
| 79 | + # raise exception if there was an error pushing data to CloudWatch |
| 80 | + raise |
| 81 | + |
| 82 | + |
| 83 | +def main(): |
| 84 | + readXML_and_publish_metrics_to_cw() |
| 85 | + |
| 86 | + |
| 87 | +if __name__ == "__main__": |
| 88 | + main() |
| 89 | + |
| 90 | + |
| 91 | + |
0 commit comments