1# 2# Copyright (C) 2018 The Android Open Source Project 3# 4# Licensed under the Apache License, Version 2.0 (the "License"); 5# you may not use this file except in compliance with the License. 6# You may obtain a copy of the License at 7# 8# http://www.apache.org/licenses/LICENSE-2.0 9# 10# Unless required by applicable law or agreed to in writing, software 11# distributed under the License is distributed on an "AS IS" BASIS, 12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13# See the License for the specific language governing permissions and 14# limitations under the License. 15# 16 17import json 18import logging 19import requests 20 21# timeout seconds for requests 22REQUESTS_TIMEOUT_SECONDS = 60 23 24 25def FillDictAndPost(msg, 26 dict_to_fill, 27 url, 28 headers, 29 filters={}, 30 caller_name=""): 31 """Fills up a dict using contents of the pb2 message and uploads it. 32 33 Args: 34 msg: pb2 msg, containing info about all task schedules. 35 dict_to_fill: dict, to be converted into a json object before 36 upload. 37 url: string, URL for the endpoit API to be called when 38 the dict_to_fill fills up. 39 40 Returns: 41 True if successful, False otherwise. 42 """ 43 terminal = True 44 ret = True 45 sub_msg_list = [] 46 for field in msg.DESCRIPTOR.fields: 47 if field.type == field.TYPE_MESSAGE: 48 terminal = False 49 for sub_msg in msg.__getattribute__(field.name): 50 # make all the messages to be processed after other attrs, 51 # otherwise dict_to_fill would be incomplete. 52 sub_msg_list.append(sub_msg) 53 else: 54 if filters and field.name in filters: 55 filtered_key = filters[field.name] 56 else: 57 filtered_key = field.name 58 59 if field.label == field.LABEL_REPEATED: 60 dict_to_fill[filtered_key] = list( 61 msg.__getattribute__(field.name)) 62 else: 63 dict_to_fill[filtered_key] = msg.__getattribute__(field.name) 64 65 for sub_msg in sub_msg_list: 66 ret = ret and FillDictAndPost(sub_msg, dict_to_fill, url, headers, 67 filters, caller_name) 68 69 if terminal: 70 try: 71 response = requests.post(url, data=json.dumps(dict_to_fill), 72 headers=headers, 73 timeout=REQUESTS_TIMEOUT_SECONDS) 74 except requests.exceptions.Timeout as e: 75 logging.exception(e) 76 return False 77 if response.status_code != requests.codes.ok: 78 logging.error("%s error: %s", caller_name, response) 79 ret = ret and False 80 81 return ret 82