def run_rule()

in gcpdiag/lint/datafusion/err_2024_001_delete_operation_failing.py [0:0]


def run_rule(context: models.Context, report: lint.LintReportRuleInterface):
  """Checks if Data Fusion instance delete operation is failing.

  Args:
    context: The context for the rule, including the project_id, credentials,
      and other info.
    report: The report to which to report results.
  """
  if not apis.is_enabled(context.project_id, 'datafusion'):
    report.add_skipped(
        None,
        'Cloud Data Fusion API is not enabled in'
        f' { projects[context.project_id]}',
    )
    return

  datafusion_instances = projects_instances[context.project_id]
  project = projects[context.project_id]

  if not datafusion_instances:
    report.add_skipped(None,
                       f'Cloud Data Fusion instances were not found {context}')
    return

  instance_full_path_set = set()
  deleting_instance_flag = False

  for datafusion_instance in sorted(datafusion_instances.values()):
    instance_full_path_set.add(datafusion_instance.full_path)
    if datafusion_instance.is_deleting:
      deleting_instance_flag = True

  if (logs_by_project.get(context.project_id) and \
     logs_by_project[context.project_id].entries) or deleting_instance_flag:

    iam_policy = iam.get_project_policy(context.project_id)
    datafusion_sa = (
        f'serviceAccount:service-{project.number}@gcp-sa-datafusion.iam.gserviceaccount.com'
    )
    project_iam_policy_result = iam_policy.has_role_permissions(
        datafusion_sa, IAM_ROLE)
    if not project_iam_policy_result:
      report.add_failed(project, f'{datafusion_sa}\nLacks {IAM_ROLE}')
      return

  project_ok_flag = True

  for log_entry in logs_by_project[context.project_id].entries:
    if (log_entry['protoPayload']['methodName'] == METHOD_NAME and
        log_entry['severity'] == 'ERROR' and
        log_entry['protoPayload']['resourceName'] in instance_full_path_set):

      message = log_entry['protoPayload']['status']['message']
      match = re.search(r'::(.*?):([^:]+)\.', message)
      instance_name = find_instance(datafusion_instances,
                                    log_entry['protoPayload']['resourceName'])
      if match:
        message = match.group(2)
      report.add_failed(instance_name, f'{message}')
      project_ok_flag = False
      instance_full_path_set.remove(log_entry['protoPayload']['resourceName'])

  if project_ok_flag:
    report.add_ok(project)