1 #!/usr/bin/env python 2 # 3 # Copyright 2017 - The Android Open Source Project 4 # 5 # Licensed under the Apache License, Version 2.0 (the "License"); 6 # you may not use this file except in compliance with the License. 7 # You may obtain a copy of the License at 8 # 9 # http://www.apache.org/licenses/LICENSE-2.0 10 # 11 # Unless required by applicable law or agreed to in writing, software 12 # distributed under the License is distributed on an "AS IS" BASIS, 13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 # See the License for the specific language governing permissions and 15 # limitations under the License. 16 17 import json 18 19 from metrics.usb_metric import Device 20 from reporters.reporter import Reporter 21 22 23 class JsonReporter(Reporter): 24 """Reporter class that reports information in JSON format to a file. 25 26 This defaults to writing to the current working directory with name 27 output.json 28 29 Attributes: 30 health_checker: a HealthChecker object 31 file_name: Path of file to write to. 32 """ 33 34 def __init__(self, h_checker, file_name='output.json'): 35 super(JsonReporter, self).__init__(h_checker) 36 self.file_name = file_name 37 38 def report(self, metric_responses): 39 unhealthy_metrics = self.health_checker.get_unhealthy(metric_responses) 40 for metric_name in metric_responses: 41 if metric_name not in unhealthy_metrics: 42 metric_responses[metric_name]['is_healthy'] = True 43 else: 44 metric_responses[metric_name]['is_healthy'] = False 45 # add a total unhealthy score 46 metric_responses['total_unhealthy'] = { 47 'total_unhealthy': len(set(unhealthy_metrics)) 48 } 49 with open(self.file_name, 'w') as outfile: 50 json.dump( 51 metric_responses, indent=4, cls=AutoJsonEncoder, fp=outfile) 52 53 54 class AutoJsonEncoder(json.JSONEncoder): 55 def default(self, obj): 56 if isinstance(obj, Device): 57 return { 58 'name': obj.name, 59 'trans_bytes': obj.trans_bytes, 60 'dev_id': obj.dev_id 61 } 62 else: 63 return json.JSONEncoder.default(self, obj) 64