|
| 1 | +#! /bin/env python |
| 2 | +# |
| 3 | +# Template for RDR tool python program. |
| 4 | +# |
| 5 | +import argparse |
| 6 | +import logging |
| 7 | +import re |
| 8 | +import sys |
| 9 | + |
| 10 | +from rdr_service.code_constants import EMAIL_QUESTION_CODE as EQC, LOGIN_PHONE_NUMBER_QUESTION_CODE as PNQC |
| 11 | +from rdr_service.services.gcp_utils import gcp_make_auth_header |
| 12 | +from rdr_service.services.system_utils import make_api_request |
| 13 | +from rdr_service.services.system_utils import setup_logging, setup_i18n |
| 14 | +from rdr_service.tools.tool_libs import GCPProcessContext |
| 15 | + |
| 16 | +_logger = logging.getLogger("rdr_logger") |
| 17 | + |
| 18 | +# Tool_cmd and tool_desc name are required. |
| 19 | +# Remember to add/update bash completion in 'tool_lib/tools.bash' |
| 20 | +tool_cmd = "ppi-check" |
| 21 | +tool_desc = "check participant ppi data in rdr" |
| 22 | + |
| 23 | + |
| 24 | +class CheckPPIDataClass(object): |
| 25 | + def __init__(self, args, gcp_env): |
| 26 | + """ |
| 27 | + :param args: command line arguments. |
| 28 | + :param gcp_env: gcp environment information, see: gcp_initialize(). |
| 29 | + """ |
| 30 | + self.args = args |
| 31 | + self.gcp_env = gcp_env |
| 32 | + |
| 33 | + def check_ppi_data(self): |
| 34 | + """ |
| 35 | + Fetch and process spreadsheet, then call CheckPpiData for results |
| 36 | + :param client: Client object |
| 37 | + :param args: program arguments |
| 38 | + """ |
| 39 | + # See if we have filter criteria |
| 40 | + if not self.args.email and not self.args.phone: |
| 41 | + do_filter = False |
| 42 | + else: |
| 43 | + do_filter = True |
| 44 | + |
| 45 | + if not self.args.phone: |
| 46 | + self.args.phone = list() |
| 47 | + if not self.args.email: |
| 48 | + self.args.email = list() |
| 49 | + |
| 50 | + csv_data = self.fetch_csv_data() |
| 51 | + ppi_data = dict() |
| 52 | + |
| 53 | + # iterate over each data column, convert them into a dict. |
| 54 | + for column in range(0, len(csv_data[0]) - 1): |
| 55 | + row_dict = self.convert_csv_column_to_dict(csv_data, column) |
| 56 | + email = row_dict[EQC] if EQC in row_dict else None |
| 57 | + phone_no = row_dict[PNQC] if PNQC in row_dict else None |
| 58 | + |
| 59 | + if do_filter is False or (email in self.args.email or phone_no in self.args.phone): |
| 60 | + # prioritize using email value over phone number for key |
| 61 | + key = email if email else phone_no |
| 62 | + ppi_data[key] = row_dict |
| 63 | + |
| 64 | + if len(ppi_data) == 0: |
| 65 | + _logger.error("No participants matched filter criteria. aborting.") |
| 66 | + return |
| 67 | + |
| 68 | + host = f'{self.gcp_env.project}.appspot.com' |
| 69 | + data = {"ppi_data": ppi_data} |
| 70 | + |
| 71 | + headers = gcp_make_auth_header() |
| 72 | + code, resp = make_api_request(host, '/rdr/v1/CheckPpiData', headers=headers, json_data=data, req_type="POST") |
| 73 | + |
| 74 | + if code != 200: |
| 75 | + _logger.error(f'API request failed. {code}: {resp}') |
| 76 | + return |
| 77 | + |
| 78 | + self.log_ppi_results(resp["ppi_results"]) |
| 79 | + |
| 80 | + def fetch_csv_data(self): |
| 81 | + """ |
| 82 | + Download a google doc spreadsheet in CSV format |
| 83 | + :return: A list object with rows from spreadsheet |
| 84 | + """ |
| 85 | + host = 'docs.google.com' |
| 86 | + path = f'spreadsheets/d/{self.args.sheet_id}/export?format=csv&' + \ |
| 87 | + f'id={self.args.sheet_id}s&gid={self.args.sheet_gid}' |
| 88 | + |
| 89 | + code, resp = make_api_request(host, path, ret_type='text') |
| 90 | + if code != 200: |
| 91 | + _logger.error(f'Error fetching https://{host}{path}. {code}: {resp}') |
| 92 | + return |
| 93 | + |
| 94 | + resp = resp.replace('\r', '') |
| 95 | + |
| 96 | + csv_data = list() |
| 97 | + for row in resp.split('\n'): |
| 98 | + csv_data.append(row.split(',')) |
| 99 | + |
| 100 | + return csv_data |
| 101 | + |
| 102 | + def convert_csv_column_to_dict(self, csv_data, column): |
| 103 | + """ |
| 104 | + Return a dictionary object with keys from the first column and values from the specified |
| 105 | + column. |
| 106 | + :param csv_data: File-like CSV text downloaded from Google spreadsheets. (See main doc.) |
| 107 | + :return: dict of fields and values for given column |
| 108 | + """ |
| 109 | + results = dict() |
| 110 | + |
| 111 | + for row in csv_data: |
| 112 | + key = row[0] |
| 113 | + data = row[1:][column] |
| 114 | + |
| 115 | + if data: |
| 116 | + if key not in results: |
| 117 | + results[key] = data.strip() if data else "" |
| 118 | + else: |
| 119 | + # append multiple choice questions |
| 120 | + results[key] += "|{0}".format(data.strip()) |
| 121 | + |
| 122 | + return results |
| 123 | + |
| 124 | + def log_ppi_results(self, data): |
| 125 | + """ |
| 126 | + Formats and logs the validation results. See CheckPpiDataApi for response format details. |
| 127 | + """ |
| 128 | + clr = self.gcp_env.terminal_colors |
| 129 | + _logger.info(clr.fmt('')) |
| 130 | + _logger.info('Results:') |
| 131 | + _logger.info('=' * 110) |
| 132 | + |
| 133 | + total = 0 |
| 134 | + errors = 0 |
| 135 | + for email, results in data.items(): |
| 136 | + tests_count, errors_count = results["tests_count"], results["errors_count"] |
| 137 | + errors += errors_count |
| 138 | + total += tests_count |
| 139 | + log_lines = [ |
| 140 | + clr.fmt(f" {email}: {tests_count} tests, {errors_count} errors", |
| 141 | + clr.fg_bright_green if errors_count == 0 else clr.fg_bright_red) |
| 142 | + ] |
| 143 | + for message in results["error_messages"]: |
| 144 | + # Convert braces and unicode indicator to quotes for better readability |
| 145 | + message = re.sub("\['", '"', message) |
| 146 | + message = re.sub("'\]", '"', message) |
| 147 | + while ' ' in message: |
| 148 | + message = message.replace(' ', ' ') |
| 149 | + log_lines += ["\n " + message] |
| 150 | + _logger.info("".join(log_lines)) |
| 151 | + _logger.info('=' * 110) |
| 152 | + _logger.info(f"Completed {total} tests across {len(data)} participants with {errors} errors.") |
| 153 | + |
| 154 | + def run(self): |
| 155 | + """ |
| 156 | + Main program process |
| 157 | + :return: Exit code value |
| 158 | + """ |
| 159 | + self.check_ppi_data() |
| 160 | + return 0 |
| 161 | + |
| 162 | + |
| 163 | +def run(): |
| 164 | + # Set global debug value and setup application logging. |
| 165 | + setup_logging( |
| 166 | + _logger, tool_cmd, "--debug" in sys.argv, "{0}.log".format(tool_cmd) if "--log-file" in sys.argv else None |
| 167 | + ) |
| 168 | + setup_i18n() |
| 169 | + |
| 170 | + # Setup program arguments. |
| 171 | + parser = argparse.ArgumentParser(prog=tool_cmd, description=tool_desc) |
| 172 | + parser.add_argument("--debug", help="enable debug output", default=False, action="store_true") # noqa |
| 173 | + parser.add_argument("--log-file", help="write output to a log file", default=False, action="store_true") # noqa |
| 174 | + parser.add_argument("--project", help="gcp project name", default="localhost") # noqa |
| 175 | + parser.add_argument("--account", help="pmi-ops account", default=None) # noqa |
| 176 | + parser.add_argument("--service-account", help="gcp iam service account", default=None) # noqa |
| 177 | + |
| 178 | + parser.add_argument("--sheet-id", |
| 179 | + help='google spreadsheet doc id, after the "/d/" in the URL. the doc must be public.') # noqa |
| 180 | + parser.add_argument("--sheet-gid", help='google spreadsheet sheet id, after "gid=" in the url.') # noqa |
| 181 | + parser.add_argument("--email", help=("only validate the given e-mail(s). Validate all by default. " |
| 182 | + "this flag may be repeated to specify multiple e-mails."), action="append") # noqa |
| 183 | + parser.add_argument("--phone", help=("only validate the given phone number. " |
| 184 | + "this flag may be repeated to specify multiple phone numbers."), action="append") # noqa |
| 185 | + args = parser.parse_args() |
| 186 | + |
| 187 | + with GCPProcessContext(tool_cmd, args.project, args.account, args.service_account) as gcp_env: |
| 188 | + process = CheckPPIDataClass(args, gcp_env) |
| 189 | + exit_code = process.run() |
| 190 | + return exit_code |
| 191 | + |
| 192 | + |
| 193 | +# --- Main Program Call --- |
| 194 | +if __name__ == "__main__": |
| 195 | + sys.exit(run()) |
0 commit comments