fast2dev-dbt-runner 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,401 @@
1
+ import datetime
2
+ import textwrap
3
+ from datetime import datetime
4
+ from kubernetes.client import models as k8s
5
+ from fast2dev_dbt_runner._compat import AirflowException, TaskGroup
6
+ from airflow.providers.google.cloud.operators.kubernetes_engine import GKEStartPodOperator
7
+ import fast2dev_dbt_runner.utils as utils
8
+ from fast2dev_dbt_runner.cached_manifest_loader import load_dbt_manifest_cached
9
+
10
+
11
+ class CustomGKEStartPodOperator(GKEStartPodOperator):
12
+ def execute(self, context):
13
+ """
14
+ Executes a GKEStartPodOperator task with customized exception handling.
15
+
16
+ This custom operator extends the GKEStartPodOperator from the Airflow library.
17
+ It overrides the execute method to catch AirflowException raised by the parent class.
18
+ The error message is then shortened and a new AirflowException is raised with the
19
+ shortened message. This approach allows for more concise error reporting while
20
+ preserving the detailed error information.
21
+
22
+ :param context: The context dictionary provided by Airflow.
23
+ """
24
+ try:
25
+ super().execute(context)
26
+ except AirflowException as e:
27
+ # Shorten the error message for clearer reporting
28
+ msg = str(e)
29
+ short_msg = textwrap.shorten(msg, width=160)
30
+ raise AirflowException(short_msg) from None
31
+
32
+ class DbtManifestParser:
33
+ """
34
+ A class analyses dbt project and parses manifest.json and creates the respective task groups
35
+ :param manifest_path: Path to the directory containing the manifest files
36
+ :param pod_name: name of Kubercluster pod
37
+ :param dbt_tag: define different parts of a project. Have to be set as
38
+ a list of one or a few values
39
+ :param env_var: airflow variables
40
+ :param image: docker image where define dbt command
41
+ :param namespace: default
42
+ :param PROJECT_ID: identificator of google project project_id.
43
+ Getting from Airflow environment variables {{ var.value.PROJECT_ID }}
44
+ :param CLUSTER_ZONE: Getting from Airflow environment variables {{ var.value.CLUSTER_ZONE }}
45
+ :param CLUSTER_NAME: Getting from Airflow environment variables {{ var.value.CLUSTER_NAME_DBT }}
46
+ """
47
+ def __init__(
48
+ self,
49
+ dbt_tag,
50
+ env_vars,
51
+ airflow_vars,
52
+ manifest_path=None,
53
+ pod_name=None,
54
+ image=None,
55
+ namespace=None,
56
+ project_id=None,
57
+ cluster_zone=None,
58
+ cluster_name=None,
59
+ **kwargs
60
+ ) -> None:
61
+ self.env_vars = env_vars
62
+ self.airflow_vars = airflow_vars
63
+ self.pod_name = pod_name
64
+ self.dbt_tag = utils.check_dbt_tag(dbt_tag)
65
+ self.image = image
66
+ self.namespace = namespace
67
+ self.project_id = project_id
68
+ self.cluster_zone = cluster_zone
69
+ self.cluster_name = cluster_name
70
+ self.manifest_path = manifest_path
71
+ self.dbt_tag_ancestors = kwargs.get("dbt_tag_ancestors", False)
72
+ self.dbt_tag_descendants = kwargs.get("dbt_tag_descendants", False)
73
+ self.dbt_model_depends_on_snapshot = airflow_vars.get("DBT_MODEL_DEPENDS_ON_SNAPSHOT", "False")
74
+ self.manifest_data = load_dbt_manifest_cached(self.manifest_path,
75
+ dbt_tag=self.dbt_tag,
76
+ dbt_tag_ancestors=self.dbt_tag_ancestors,
77
+ dbt_tag_descendants=self.dbt_tag_descendants,
78
+ dbt_model_depends_on_snapshot=self.dbt_model_depends_on_snapshot)
79
+ self.dbt_tasks = {}
80
+ self.fqn_unique_list = []
81
+ self.existing_task_groups = {}
82
+
83
+ def is_resource_type_in_manifest(self, resource_type):
84
+ return utils.is_resource_type_in_manifest(self.manifest_data, resource_type)
85
+
86
+ def get_valid_start_date(self, start_date_raw):
87
+ return utils.get_valid_start_date(start_date_raw)
88
+
89
+ def add_additional_env_variables(self, task_params, dbt_command, node_name):
90
+ # create env_vars_with_model list as a copy of env_vars
91
+ # to avoid redefinition of env_vars list
92
+ env_vars_with_model = self.env_vars.copy()
93
+ airflow_var = self.airflow_vars.copy()
94
+
95
+ if task_params.get('full_refresh', None):
96
+ if dbt_command != "test":
97
+ dbt_command = task_params['full_refresh']
98
+
99
+ env_vars_with_model.append(k8s.V1EnvVar(name="DBT_COMMAND", value=f"{dbt_command}"))
100
+ # add to env_vars_with_model new variable MODEL that equal
101
+ # to current DBT project model node_name
102
+ if node_name:
103
+ env_vars_with_model.append(k8s.V1EnvVar(name="MODEL", value=f"{node_name}"))
104
+ if dbt_command == "seed":
105
+ env_vars_with_model.append(k8s.V1EnvVar(name="SEED", value="true"))
106
+ else:
107
+ env_vars_with_model.append(k8s.V1EnvVar(name="SEED", value="false"))
108
+
109
+ if dbt_command in ("run", "build") and self.airflow_vars.get("E2E_MODE_EMPTY"):
110
+ env_vars_with_model.append(k8s.V1EnvVar(name="E2E_MODE_EMPTY", value="true"))
111
+
112
+ if task_params:
113
+ env_vars_with_model_keys = [i.name for i in env_vars_with_model]
114
+ kuber_dag_new_params = [k8s.V1EnvVar(name=k, value=str(v)) for k, v in task_params.items() if
115
+ k not in env_vars_with_model_keys]
116
+ env_vars_with_model.extend(kuber_dag_new_params)
117
+ airflow_var = {**task_params, **airflow_var}
118
+
119
+ if dbt_command == "snapshot":
120
+ env_vars_with_model.append(k8s.V1EnvVar(name="SNAPSHOT", value="true"))
121
+ if self.airflow_vars.get("GIT_BRANCH"):
122
+ env_vars_with_model.append(k8s.V1EnvVar(name="GIT_BRANCH", value=str(self.airflow_vars.get("GIT_BRANCH"))))
123
+ if not airflow_var.get('DBT_SNAPSHOT_INTERVAL') or airflow_var['DBT_SNAPSHOT_INTERVAL'] == 'daily':
124
+ env_vars_with_model.append(k8s.V1EnvVar(name="SNAPSHOT_RUN_PERIOD", value="true"))
125
+ else:
126
+ env_vars_with_model.append(k8s.V1EnvVar(name="SNAPSHOT_RUN_PERIOD", value="false"))
127
+
128
+ if airflow_var.get('DBT_DAG_RUN_DATE'):
129
+ date_input = datetime.datetime.strptime(airflow_var['DBT_DAG_RUN_DATE'], "%Y-%m-%d")
130
+ if airflow_var.get('DBT_SNAPSHOT_VALID_FROM'):
131
+ date_input_from = datetime.datetime.strptime(airflow_var['DBT_SNAPSHOT_VALID_FROM'], "%Y-%m-%d")
132
+ if airflow_var.get('DBT_SNAPSHOT_VALID_TO'):
133
+ date_input_to = datetime.datetime.strptime(airflow_var['DBT_SNAPSHOT_VALID_TO'], "%Y-%m-%d")
134
+
135
+ if airflow_var['DBT_SNAPSHOT_INTERVAL'] == 'monthly' \
136
+ and date_input_from.day <= date_input.day <= date_input_to.day:
137
+ env_vars_with_model.append(k8s.V1EnvVar(name="SNAPSHOT_RUN_PERIOD", value="true"))
138
+ elif airflow_var['DBT_SNAPSHOT_INTERVAL'] == 'weekly' \
139
+ and date_input_from.weekday() <= date_input.weekday() <= date_input_to.weekday():
140
+ env_vars_with_model.append(k8s.V1EnvVar(name="SNAPSHOT_RUN_PERIOD", value="true"))
141
+ else:
142
+ env_vars_with_model.append(k8s.V1EnvVar(name="SNAPSHOT", value="false"))
143
+ return env_vars_with_model
144
+
145
+ def create_dbt_task(self, dbt_command, running_rule, task_params={}, node_name=None, node_alias=None, parent_group=None):
146
+ """
147
+ Takes the manifest JSON content and returns a GKEStartPodOperator task
148
+ to run a dbt command.
149
+ Args:
150
+ node_name: The name of the node from manifest.json. By default is equal to None
151
+ running_rule: trigger rules
152
+ dbt_command: dbt command: run, test
153
+ task_params:
154
+ Returns: A GKEStartPodOperator task that runs the respective dbt command
155
+ """
156
+ env_vars_with_model = self.add_additional_env_variables(task_params, dbt_command, node_name)
157
+
158
+ if node_name is None:
159
+ node_name = dbt_command + "_all_models"
160
+ node_alias = dbt_command + "_all_models"
161
+ if dbt_command == "source freshness":
162
+ node_name ="freshness_all_sources"
163
+ node_alias = "freshness_all_sources"
164
+
165
+ """
166
+ Create GKEStartPodOperator operators
167
+ Args:
168
+ task_id: The ID specified for the task.
169
+ name: Name of task you want to run, used to generate Pod ID
170
+ namespace: The namespace to run within Kubernetes
171
+ image: Docker image specified
172
+ trigger_rule: the conditions that Airflow applies to tasks
173
+ to determine whether they are ready to execute.
174
+ ALL_DONE - all upstream tasks are done with their execution
175
+ """
176
+ affinity = {
177
+ 'podAntiAffinity': {
178
+ 'preferredDuringSchedulingIgnoredDuringExecution': [
179
+ {
180
+ 'weight': 100,
181
+ 'podAffinityTerm': {
182
+ 'labelSelector': {
183
+ 'matchExpressions': [
184
+ {
185
+ 'key': 'component',
186
+ 'operator': 'In',
187
+ 'values': ['scheduler', 'triggerer', 'worker']
188
+ }
189
+ ]
190
+ },
191
+ 'topologyKey': 'kubernetes.io/hostname'
192
+ }
193
+ }
194
+ ]
195
+ }
196
+ }
197
+
198
+ dbt_task = CustomGKEStartPodOperator(
199
+ task_id=node_alias,
200
+ name=self.pod_name + "_" + node_alias,
201
+ project_id=self.project_id,
202
+ location=self.cluster_zone,
203
+ cluster_name=self.cluster_name,
204
+ namespace=self.namespace,
205
+ image=self.image,
206
+ use_internal_ip=True,
207
+ # Debug - uncomment for debug the container.
208
+ # cmds=["bash", "-cx"],
209
+ # arguments=[f" tail -f /dev/null "],
210
+ # trigger_rule=TriggerRule.ALL_DONE,
211
+ # Optional, run with specific K8S SA Account
212
+ # service_account_name="airflow",
213
+ trigger_rule=running_rule,
214
+ secrets=[],
215
+ labels={"app": "dbt"},
216
+ startup_timeout_seconds=240,
217
+ env_vars=env_vars_with_model,
218
+ get_logs=True,
219
+ image_pull_policy="IfNotPresent",
220
+ image_pull_secrets="fast2dev-common-secret",
221
+ annotations={},
222
+ do_xcom_push=False,
223
+ is_delete_operator_pod=True,
224
+ container_resources=k8s.V1ResourceRequirements(
225
+ requests={"memory": "128Mi", "cpu": "100m"},
226
+ ),
227
+ affinity=affinity,
228
+ task_group=parent_group
229
+ )
230
+ return dbt_task
231
+
232
+ def create_task_groups(self, parent_group, fqn, node, task_name, task_alias, dbt_command, running_rule,
233
+ task_params):
234
+ """
235
+ Recursively creates task groups from FQN and adds the task to the final group.
236
+ """
237
+ if not fqn:
238
+ # Base case: If FQN is empty, add a task
239
+ if node not in self.dbt_tasks:
240
+ self.dbt_tasks[node] = self.create_dbt_task(dbt_command=dbt_command,
241
+ running_rule=running_rule,
242
+ task_params=task_params,
243
+ node_name=task_name,
244
+ node_alias=task_alias,
245
+ parent_group=parent_group)
246
+ return
247
+
248
+ # Get the current level and create a subgroup
249
+ current_level = fqn[0]
250
+ if current_level != "re_data":
251
+ subgroup = getattr(parent_group, current_level, None)
252
+
253
+ # If the subgroup does not exist, create it
254
+ if not subgroup:
255
+ subgroup = TaskGroup(group_id=current_level, parent_group=parent_group)
256
+ setattr(parent_group, current_level, subgroup)
257
+
258
+ # Recurse into the next level
259
+ self.create_task_groups(subgroup, fqn[1:], node, task_name, task_alias, dbt_command, running_rule,
260
+ task_params)
261
+
262
+ def set_dependencies(self, resource_type):
263
+ """
264
+ Sets the dependencies between tasks based on the `depends_on` attribute in the manifest data.
265
+ """
266
+ for node in self.manifest_data.keys():
267
+ if resource_type in self.manifest_data[node]['group_type']:
268
+ # Only set dependencies for nodes that were actually created as tasks
269
+ if node not in self.dbt_tasks:
270
+ continue
271
+
272
+ for upstream_node in self.manifest_data[node].get("depends_on", []):
273
+ if self.dbt_tasks.get(upstream_node, []):
274
+ self.dbt_tasks[upstream_node] >> self.dbt_tasks[node]
275
+
276
+ def manifest_has_model_depends_on_snapshot(self):
277
+ """True when a selected model directly depends on a snapshot (batch build trigger)."""
278
+ return utils.manifest_has_model_depends_on_snapshot(self.manifest_data)
279
+
280
+ def get_model_names_for_resource_types(self, resource_types, task_params=None):
281
+ """
282
+ Collects node names from the filtered manifest for the given resource type(s).
283
+ Returns a space-separated string suitable for dbt --select, or None if empty.
284
+ """
285
+ if isinstance(resource_types, str):
286
+ resource_types = [resource_types]
287
+ resource_types = set(resource_types)
288
+
289
+ if task_params is None:
290
+ task_params = {}
291
+ task_params = {k: v for k, v in task_params.items() if v}
292
+
293
+ manifest = self.manifest_data
294
+ if "full_refresh_model_name" in task_params:
295
+ manifest = utils.filter_models(manifest, task_params["full_refresh_model_name"])
296
+
297
+ model_names = []
298
+ for node_id, node_data in manifest.items():
299
+ if node_data.get("resource_type") in resource_types:
300
+ model_names.append(node_data["name"])
301
+ return " ".join(model_names) if model_names else None
302
+
303
+ def get_model_names_for_resource_type(self, resource_type, task_params=None):
304
+ """
305
+ Collects all model names from the filtered manifest for a given resource type.
306
+ Returns a space-separated string suitable for dbt --select.
307
+ """
308
+ return self.get_model_names_for_resource_types([resource_type], task_params)
309
+
310
+ def create_dbt_batch_task(self, resource_type, dbt_command, running_rule, task_params=None):
311
+ """
312
+ Creates a single Airflow task that runs all models of the given resource_type
313
+ in one batch using dbt --select "model1 model2 model3 ...".
314
+ Bypasses per-model lineage — dbt handles internal dependency ordering.
315
+ """
316
+ select_string = self.get_model_names_for_resource_type(resource_type, task_params)
317
+ if not select_string:
318
+ return None
319
+
320
+ task_alias = f"{dbt_command}_all_models"
321
+ return self.create_dbt_task(
322
+ dbt_command=dbt_command,
323
+ running_rule=running_rule,
324
+ task_params=task_params if task_params else {},
325
+ node_name=select_string,
326
+ node_alias=task_alias
327
+ )
328
+
329
+ def create_dbt_build_batch_task(self, running_rule, task_params=None,
330
+ resource_types=("model", "snapshot")):
331
+ """
332
+ Creates a single ``dbt build`` batch pod over models + snapshots, so a
333
+ ``model -> snapshot -> model`` chain runs in lineage order in one pod
334
+ (used in non-sharded mode when DBT_MODEL_DEPENDS_ON_SNAPSHOT is enabled).
335
+ """
336
+ select_string = self.get_model_names_for_resource_types(list(resource_types), task_params)
337
+ if not select_string:
338
+ return None
339
+
340
+ return self.create_dbt_task(
341
+ dbt_command="build",
342
+ running_rule=running_rule,
343
+ task_params=task_params if task_params else {},
344
+ node_name=select_string,
345
+ node_alias="build_all_models"
346
+ )
347
+
348
+ def create_dbt_task_groups(
349
+ self,
350
+ group_name,
351
+ resource_type,
352
+ dbt_command,
353
+ running_rule,
354
+ task_params={}):
355
+ """
356
+ Parse out a JSON file and populates the task groups with dbt tasks
357
+ Args:
358
+ group_name: name of Task Groups uses for DAGs graph view in the Airflow UI.
359
+ resource_type: type of manifest nodes group: model, seed, snapshot
360
+ package_name: project name, tag that define by which certain records
361
+ from the manifest nodes will be selected
362
+ dbt_command: dbt command run or test
363
+ running_rule: trigger rule
364
+ task_params: parameters that was added in the task
365
+ Returns: task group
366
+ """
367
+ task_params = {k: v for k, v in task_params.items() if v} # Filter out empty values
368
+ if "full_refresh_model_name" in task_params:
369
+ self.manifest_data = utils.filter_models(self.manifest_data, task_params["full_refresh_model_name"])
370
+
371
+ if utils.is_resource_type_in_manifest(self.manifest_data, resource_type):
372
+ # Initialize the root TaskGroup from `group_name` (should be a TaskGroup instance, not a string)
373
+ with TaskGroup(group_id=group_name, parent_group=None) as root_group:
374
+ for node_id, node_data in self.manifest_data.items():
375
+ # Skip tests when creating source task groups - tests should run separately, not as part of source freshness
376
+ if resource_type == "source" and node_data.get('resource_type') == 'test':
377
+ continue
378
+ if group_name[:-1] in node_data["group_type"]:
379
+ # Extract FQN and task name
380
+ fqn = node_data["fqn"][:-1] # Remove model name from the FQN
381
+ task_name = node_data["name"]
382
+ task_alias = node_data["alias"]
383
+ # Use a per-node command so overrides (test/snapshot/source)
384
+ # do not leak into subsequent iterations of this loop.
385
+ node_command = dbt_command
386
+ if node_data['resource_type'] == "test":
387
+ node_command = "test"
388
+ elif node_data['resource_type'] == "snapshot":
389
+ # A snapshot woven into the model group (DBT_MODEL_DEPENDS_ON_SNAPSHOT)
390
+ # must still run as `dbt snapshot`, not `dbt run`.
391
+ node_command = "snapshot"
392
+ elif node_data['resource_type'] == "source":
393
+ task_name = f"source:{node_data['schema']}.{task_name}"
394
+ node_command = "source freshness"
395
+ # Create the dynamic task groups under root_group
396
+ self.create_task_groups(root_group, fqn, node_id, task_name, task_alias, node_command, running_rule,
397
+ task_params)
398
+ self.set_dependencies(resource_type)
399
+ if not root_group.children:
400
+ return None
401
+ return root_group