gcpdiag.queries.dataflow
Queries related to Dataflow.
DATAFLOW_REGIONS =
['asia-northeast2', 'us-central1', 'northamerica-northeast1', 'us-west3', 'southamerica-east1', 'us-east1', 'asia-northeast1', 'europe-west1', 'europe-west2', 'asia-northeast3', 'us-west4', 'asia-east2', 'europe-central2', 'europe-west6', 'us-west2', 'australia-southeast1', 'europe-west3', 'asia-south1', 'us-west1', 'us-east4', 'asia-southeast1']
class
Job(gcpdiag.models.Resource):
39class Job(models.Resource): 40 """Represents Dataflow job. 41 42 resource_data is of the form similar to: 43 {'id': 'my_job_id', 44 'projectId': 'my_project_id', 45 'name': 'pubsubtogcs-20240328-122953', 46 'environment': {}, 47 'currentState': 'JOB_STATE_FAILED', 48 'currentStateTime': '2024-03-28T12:34:27.383249Z', 49 'createTime': '2024-03-28T12:29:55.284524Z', 50 'location': 'europe-west2', 51 'startTime': '2024-03-28T12:29:55.284524Z'} 52 """ 53 54 _resource_data: dict 55 project_id: str 56 57 def __init__(self, project_id: str, resource_data: dict): 58 super().__init__(project_id) 59 self._resource_data = resource_data 60 61 @property 62 def full_path(self) -> str: 63 return self._resource_data.get('name', '') 64 65 @property 66 def id(self) -> str: 67 return self._resource_data['id'] 68 69 @property 70 def state(self) -> str: 71 return self._resource_data['currentState'] 72 73 @property 74 def job_type(self) -> str: 75 return self._resource_data['type'] 76 77 @property 78 def location(self) -> str: 79 return self._resource_data['location'] 80 81 @property 82 def sdk_support_status(self) -> str: 83 return self._resource_data['jobMetadata']['sdkVersion']['sdkSupportStatus'] 84 85 @property 86 def sdk_language(self) -> str: 87 return self._resource_data['jobMetadata']['sdkVersion']['versionDisplayName'] 88 89 @property 90 def minutes_in_current_state(self) -> int: 91 timestamp = datetime.strptime(self._resource_data['currentStateTime'], '%Y-%m-%dT%H:%M:%S.%fZ') 92 delta = datetime.now() - timestamp 93 return int(delta.total_seconds() // 60) 94 95 @property 96 def experiments(self) -> List[str]: 97 env = self._resource_data.get('environment') or {} 98 return env.get('experiments', []) 99 100 @property 101 def is_streaming_engine_enabled(self) -> bool: 102 experiments = self.experiments 103 if ( 104 'enable_streaming_engine' in experiments 105 or 'enable_windmill_service' in experiments 106 or 'use_runner_v2' in experiments 107 ): 108 return True 109 env = self._resource_data.get('environment') or {} 110 streaming_mode = env.get('streamingMode') 111 if streaming_mode == 'STREAMING_MODE_AT_LEAST_ONCE': 112 return True 113 if env.get('useStreamingEngineResourceBasedBilling'): 114 return True 115 return False
Represents Dataflow job.
resource_data is of the form similar to: {'id': 'my_job_id', 'projectId': 'my_project_id', 'name': 'pubsubtogcs-20240328-122953', 'environment': {}, 'currentState': 'JOB_STATE_FAILED', 'currentStateTime': '2024-03-28T12:34:27.383249Z', 'createTime': '2024-03-28T12:29:55.284524Z', 'location': 'europe-west2', 'startTime': '2024-03-28T12:29:55.284524Z'}
project_id: str
264 @property 265 def project_id(self) -> str: 266 """Project id (not project number).""" 267 return self._project_id
Project id (not project number).
full_path: str
Returns the full path of this resource.
Example: 'projects/gcpdiag-gke-1-9b90/zones/europe-west4-a/clusters/gke1'
is_streaming_engine_enabled: bool
100 @property 101 def is_streaming_engine_enabled(self) -> bool: 102 experiments = self.experiments 103 if ( 104 'enable_streaming_engine' in experiments 105 or 'enable_windmill_service' in experiments 106 or 'use_runner_v2' in experiments 107 ): 108 return True 109 env = self._resource_data.get('environment') or {} 110 streaming_mode = env.get('streamingMode') 111 if streaming_mode == 'STREAMING_MODE_AT_LEAST_ONCE': 112 return True 113 if env.get('useStreamingEngineResourceBasedBilling'): 114 return True 115 return False
118def get_region_dataflow_jobs(api, context: models.Context, region: str) -> List[Job]: 119 response = apis_utils.list_all( 120 request=api.projects().locations().jobs().list(projectId=context.project_id, location=region), 121 next_function=api.projects().locations().jobs().list_next, 122 response_keyword='jobs', 123 ) 124 jobs = [] 125 for job in response: 126 location = job.get('location', '') 127 labels = job.get('labels', {}) 128 name = job.get('name', '') 129 130 # add job id as one of labels for filtering 131 labels['id'] = job.get('id', '') 132 133 # we could get the specific job but correctly matching the location will take too 134 # much effort. Hence get all the jobs and filter afterwards 135 # https://cloud.google.com/dataflow/docs/reference/rest/v1b3/projects.jobs/list#query-parameters 136 if not context.match_project_resource(location=location, labels=labels, resource=name): 137 continue 138 jobs.append(Job(context.project_id, job)) 139 return jobs
142@caching.cached_api_call 143def get_all_dataflow_jobs(context: models.Context) -> List[Job]: 144 api = apis.get_api('dataflow', 'v1b3', context.project_id) 145 146 if not apis.is_enabled(context.project_id, 'dataflow'): 147 return [] 148 149 result: List[Job] = [] 150 executor = get_executor(context) 151 for jobs in executor.map(lambda r: get_region_dataflow_jobs(api, context, r), DATAFLOW_REGIONS): 152 result += jobs 153 154 print(f'\n\nFound {len(result)} Dataflow jobs\n') 155 156 # print one Dataflow job id when it is found 157 if context.labels and result and 'id' in context.labels: 158 print(f'{result[0].full_path} - {result[0].id}\n') 159 160 return result
163@caching.cached_api_call 164def get_job(project_id: str, job: str, region: str) -> Union[Job, None]: 165 """Fetch a specific Dataflow job.""" 166 api = apis.get_api('dataflow', 'v1b3', project_id) 167 168 if not apis.is_enabled(project_id, 'dataflow'): 169 return None 170 171 query = ( 172 api.projects() 173 .locations() 174 .jobs() 175 .get(projectId=project_id, location=region, jobId=job, view='JOB_VIEW_DESCRIPTION') 176 ) 177 try: 178 resp = query.execute(num_retries=config.API_RETRIES) 179 return Job(project_id, resp) 180 except googleapiclient.errors.HttpError as err: 181 raise utils.GcpApiError(err) from err
Fetch a specific Dataflow job.
@caching.cached_api_call
def
get_all_dataflow_jobs_for_project( project_id: str, filter_str: Optional[str] = None) -> Optional[List[Job]]:
184@caching.cached_api_call 185def get_all_dataflow_jobs_for_project( 186 project_id: str, 187 filter_str: Optional[str] = None, 188) -> Union[List[Job], None]: 189 """Fetch all Dataflow jobs for a project.""" 190 api = apis.get_api('dataflow', 'v1b3', project_id) 191 192 if not apis.is_enabled(project_id, 'dataflow'): 193 return None 194 195 jobs: List[Job] = [] 196 197 request = api.projects().jobs().aggregated(projectId=project_id, filter=filter_str) 198 logging.debug('listing dataflow jobs of project %s', project_id) 199 200 while request: # Continue as long as there are pages 201 response = request.execute(num_retries=config.API_RETRIES) 202 if 'jobs' in response: 203 jobs.extend([Job(project_id, job) for job in response['jobs']]) 204 request = ( 205 api.projects().jobs().aggregated_next(previous_request=request, previous_response=response) 206 ) 207 return jobs
Fetch all Dataflow jobs for a project.
@caching.cached_api_call
def
logs_excluded(project_id: str) -> Optional[bool]:
210@caching.cached_api_call 211def logs_excluded(project_id: str) -> Union[bool, None]: 212 """Check if Dataflow Logs are excluded.""" 213 214 if not apis.is_enabled(project_id, 'dataflow'): 215 return None 216 217 exclusions = logs.exclusions(project_id) 218 if exclusions is None: 219 return None 220 else: 221 for log_exclusion in exclusions: 222 if 'resource.type="dataflow_step"' in log_exclusion.filter and log_exclusion.disabled: 223 return True 224 return False
Check if Dataflow Logs are excluded.