|
| 1 | +"""Utilities to get workloads logs and some utils.""" |
| 2 | + |
| 3 | +from airflow.decorators import task |
| 4 | +from airflow.exceptions import AirflowFailException |
| 5 | +from google.cloud import logging as log_explorer |
| 6 | +from datetime import datetime, timezone, timedelta |
| 7 | +from typing import Optional |
| 8 | +from absl import logging |
| 9 | + |
| 10 | + |
| 11 | +@task |
| 12 | +def generate_timestamp(): |
| 13 | + return datetime.now(timezone.utc) |
| 14 | + |
| 15 | + |
| 16 | +@task |
| 17 | +def validate_log_with_step( |
| 18 | + project_id: str, |
| 19 | + location: str, |
| 20 | + cluster_name: str, |
| 21 | + namespace: str = "default", |
| 22 | + pod_pattern: str = "*", |
| 23 | + container_name: Optional[str] = None, |
| 24 | + text_filter: Optional[str] = None, |
| 25 | + start_time: Optional[datetime] = None, |
| 26 | + end_time: Optional[datetime] = None, |
| 27 | + vali_step_list: Optional[list] = None, |
| 28 | +) -> bool: |
| 29 | + """ |
| 30 | + Validate the workload log is training correct |
| 31 | + Args: |
| 32 | + project_id: The Google Cloud project ID |
| 33 | + location: GKE cluster location |
| 34 | + cluster_name: GKE cluster name |
| 35 | + namespace: Kubernetes namespace (defaults to "default") |
| 36 | + pod_pattern: Pattern to match pod names (defaults to "*") |
| 37 | + container_name: Optional container name to filter logs |
| 38 | + text_filter: Optional comma-separated string to |
| 39 | + filter log entries by textPayload content |
| 40 | + start_time: Optional start time for log retrieval |
| 41 | + (defaults to 12 hours ago) |
| 42 | + end_time: Optional end time for log retrieval (defaults to now) |
| 43 | + vali_step_list: optional to validate list of steps |
| 44 | + Returns: |
| 45 | + bool: validate success or not |
| 46 | + """ |
| 47 | + entries = list_log_entries( |
| 48 | + project_id=project_id, |
| 49 | + location=location, |
| 50 | + cluster_name=cluster_name, |
| 51 | + namespace=namespace, |
| 52 | + pod_pattern=pod_pattern, |
| 53 | + container_name=container_name, |
| 54 | + text_filter=text_filter, |
| 55 | + start_time=start_time, |
| 56 | + end_time=end_time, |
| 57 | + ) |
| 58 | + if vali_step_list is None: |
| 59 | + return False |
| 60 | + new_step_list = [] |
| 61 | + for entry in entries: |
| 62 | + if not entry.payload: |
| 63 | + continue |
| 64 | + payload_str = str(entry.payload) |
| 65 | + for line in payload_str.split("\n"): |
| 66 | + if vali_step_list is not None: |
| 67 | + for step in vali_step_list: |
| 68 | + vali_str = "directory=/local/" + str(step) |
| 69 | + if vali_str in line and step not in new_step_list: |
| 70 | + logging.info(f"├─ Timestamp: {entry.timestamp}") |
| 71 | + logging.info("└─ Payload:") |
| 72 | + logging.info(f" {line}") |
| 73 | + new_step_list.append(step) |
| 74 | + if len(vali_step_list) == len(new_step_list): |
| 75 | + logging.info("Validate success") |
| 76 | + return True |
| 77 | + else: |
| 78 | + raise AirflowFailException( |
| 79 | + f"{len(vali_step_list)} saves are expected," |
| 80 | + f"but got {len(new_step_list)}" |
| 81 | + ) |
| 82 | + |
| 83 | + |
| 84 | +def list_log_entries( |
| 85 | + project_id: str, |
| 86 | + location: str, |
| 87 | + cluster_name: str, |
| 88 | + namespace: str = "default", |
| 89 | + pod_pattern: str = "*", |
| 90 | + container_name: Optional[str] = None, |
| 91 | + text_filter: Optional[str] = None, |
| 92 | + start_time: Optional[datetime] = None, |
| 93 | + end_time: Optional[datetime] = None, |
| 94 | +) -> list: |
| 95 | + """ |
| 96 | + List log entries for the specified Google Cloud project. |
| 97 | + This function connects to Google Cloud Logging, |
| 98 | + constructs a filter for Kubernetes container logs |
| 99 | + within a specific project, location, cluster, namespace, |
| 100 | + and pod name pattern, and retrieves log |
| 101 | + entries from the specified time range. |
| 102 | + It prints the timestamp, severity, resource information, |
| 103 | + and payload for each log entry found. |
| 104 | + Args: |
| 105 | + project_id: The Google Cloud project ID |
| 106 | + location: GKE cluster location |
| 107 | + cluster_name: GKE cluster name |
| 108 | + namespace: Kubernetes namespace (defaults to "default") |
| 109 | + pod_pattern: Pattern to match pod names (defaults to "*") |
| 110 | + container_name: Optional container name to filter logs |
| 111 | + text_filter: Optional comma-separated string to |
| 112 | + filter log entries by textPayload content |
| 113 | + start_time: Optional start time for log retrieval |
| 114 | + (defaults to 12 hours ago) |
| 115 | + end_time: Optional end time for log retrieval (defaults to now) |
| 116 | + Returns: |
| 117 | + bool: Number of log entries found |
| 118 | + """ |
| 119 | + |
| 120 | + # Create a Logging Client for the specified project |
| 121 | + logging_client = log_explorer.Client(project=project_id) |
| 122 | + |
| 123 | + # Set the time window for log retrieval: |
| 124 | + # default to last 12 hours if not provided |
| 125 | + if end_time is None: |
| 126 | + end_time = datetime.now(timezone.utc) |
| 127 | + if start_time is None: |
| 128 | + start_time = end_time - timedelta(hours=12) |
| 129 | + |
| 130 | + # Format times as RFC3339 UTC "Zulu" format required by the Logging API |
| 131 | + start_time_str = start_time.strftime("%Y-%m-%dT%H:%M:%SZ") |
| 132 | + end_time_str = end_time.strftime("%Y-%m-%dT%H:%M:%SZ") |
| 133 | + |
| 134 | + # Construct the log filter |
| 135 | + log_filter = ( |
| 136 | + f'resource.labels.project_id="{project_id}" ' |
| 137 | + f'resource.labels.location="{location}" ' |
| 138 | + f'resource.labels.cluster_name="{cluster_name}" ' |
| 139 | + f'resource.labels.namespace_name="{namespace}" ' |
| 140 | + f'resource.labels.pod_name:"{pod_pattern}" ' |
| 141 | + "severity>=DEFAULT " |
| 142 | + f'timestamp>="{start_time_str}" ' |
| 143 | + f'timestamp<="{end_time_str}"' |
| 144 | + ) |
| 145 | + |
| 146 | + # Add container name filter if provided |
| 147 | + if container_name: |
| 148 | + log_filter += f' resource.labels.container_name="{container_name}"' |
| 149 | + |
| 150 | + # Add text content filter if provided |
| 151 | + if text_filter: |
| 152 | + log_filter += f' SEARCH("{text_filter}")' |
| 153 | + |
| 154 | + # Retrieve log entries matching the filter |
| 155 | + logging.info(f"Log filter constructed: {log_filter}") |
| 156 | + entries = logging_client.list_entries(filter_=log_filter) |
| 157 | + |
| 158 | + return entries |
0 commit comments