-
Notifications
You must be signed in to change notification settings - Fork 0
/
ror_dag.py
234 lines (220 loc) · 7.83 KB
/
ror_dag.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
import json
from datetime import datetime
from airflow import DAG
from airflow.lineage.entities import File
from airflow.operators.python import PythonOperator
from airflow.providers.google.cloud.operators.bigquery import (
BigQueryCheckOperator,
BigQueryInsertJobOperator,
)
from airflow.providers.google.cloud.operators.gcs import GCSDeleteObjectsOperator
from airflow.providers.google.cloud.operators.kubernetes_engine import (
GKEStartPodOperator,
)
from airflow.providers.google.cloud.transfers.bigquery_to_bigquery import (
BigQueryToBigQueryOperator,
)
from airflow.providers.google.cloud.transfers.gcs_to_bigquery import (
GCSToBigQueryOperator,
)
from dataloader.airflow_utils.defaults import (
DAGS_DIR,
DATA_BUCKET,
GCP_ZONE,
PROJECT_ID,
get_default_args,
get_post_success,
)
from dataloader.scripts.populate_documentation import update_table_descriptions
args = get_default_args(pocs=["Jennifer"])
args["retries"] = 1
with DAG(
"ror_updater",
default_args=args,
description="Updates ROR dataset.",
schedule_interval="0 0 * * 5",
catchup=False,
) as dag:
gcs_folder = "ror"
tmp_dir = f"{gcs_folder}/tmp"
raw_data_dir = f"{gcs_folder}/data"
schema_dir = f"{gcs_folder}/schemas"
sql_dir = f"sql/{gcs_folder}"
production_dataset = "gcp_cset_ror"
staging_dataset = "staging_" + production_dataset
backup_dataset = production_dataset + "_backups"
# We keep several intermediate outputs in a tmp dir on gcs, so clean it out at the start of each run. We clean at
# the start of the run so if the run fails we can examine the failed data
clear_tmp_dir = GCSDeleteObjectsOperator(
task_id="clear_tmp_gcs_dir", bucket_name=DATA_BUCKET, prefix=tmp_dir + "/"
)
# Retrieve and expand the data
raw_jsonl_loc = tmp_dir + "/ror.jsonl"
working_dir = "ror_working_dir"
setup_commands = f"rm -rf {working_dir};" + " && ".join(
[
f"mkdir {working_dir}",
f"cd {working_dir}",
f"gsutil -m cp -r gs://{DATA_BUCKET}/{gcs_folder}/scripts/* .",
"virtualenv venv",
". venv/bin/activate",
"python3 -m pip install google-cloud-storage",
]
)
raw_gcs_lineage_file = File(url=f"gcs:{DATA_BUCKET}.{raw_jsonl_loc}")
download_data = GKEStartPodOperator(
task_id="download_data",
name="ror-download",
project_id=PROJECT_ID,
location=GCP_ZONE,
cluster_name="cc2-task-pool",
do_xcom_push=True,
cmds=["/bin/bash"],
arguments=[
"-c",
(
setup_commands
+ f" && python3 fetch.py --output_bucket '{DATA_BUCKET}' --output_loc '{raw_jsonl_loc}'"
),
],
inlets=[
File(
url="https://zenodo.org/api/records/?communities=ror-data&sort=mostrecent"
)
],
outlets=[raw_gcs_lineage_file],
namespace="default",
image=f"gcr.io/{PROJECT_ID}/cc2-task-pool",
get_logs=True,
startup_timeout_seconds=300,
on_finish_action="delete_pod",
affinity={
"nodeAffinity": {
"requiredDuringSchedulingIgnoredDuringExecution": {
"nodeSelectorTerms": [
{
"matchExpressions": [
{
"key": "cloud.google.com/gke-nodepool",
"operator": "In",
"values": [
"default-pool",
],
}
]
}
]
}
}
},
)
jsonl_with_up = f"{tmp_dir}/ror_json_with_up.jsonl"
add_ultimate_parent = GKEStartPodOperator(
task_id="add_ultimate_parent",
name="ror-ultimate-parent",
project_id=PROJECT_ID,
location=GCP_ZONE,
cluster_name="cc2-task-pool",
do_xcom_push=True,
cmds=["/bin/bash"],
arguments=[
"-c",
(
setup_commands
+ f" && python3 get_ultimate_parent.py --bucket '{DATA_BUCKET}' --input_loc '{raw_jsonl_loc}' --output_loc '{jsonl_with_up}'"
),
],
inlets=[raw_gcs_lineage_file],
outlets=[File(url=f"gcs:{DATA_BUCKET}.{jsonl_with_up}")],
namespace="default",
image=f"gcr.io/{PROJECT_ID}/cc2-task-pool",
get_logs=True,
startup_timeout_seconds=300,
on_finish_action="delete_pod",
affinity={
"nodeAffinity": {
"requiredDuringSchedulingIgnoredDuringExecution": {
"nodeSelectorTerms": [
{
"matchExpressions": [
{
"key": "cloud.google.com/gke-nodepool",
"operator": "In",
"values": [
"default-pool",
],
}
]
}
]
}
}
},
)
load_staging = GCSToBigQueryOperator(
task_id="load_staging",
bucket=DATA_BUCKET,
source_objects=[jsonl_with_up],
schema_object=f"{schema_dir}/ror.json",
destination_project_dataset_table=f"{staging_dataset}.ror",
source_format="NEWLINE_DELIMITED_JSON",
create_disposition="CREATE_IF_NEEDED",
write_disposition="WRITE_TRUNCATE",
)
# Check that the number of ids is >= what we have in production and that the ids are unique
checks = [
BigQueryCheckOperator(
task_id="check_unique_ids",
sql=(f"select count(distinct(id)) = count(id) from {staging_dataset}.ror"),
use_legacy_sql=False,
),
BigQueryCheckOperator(
task_id="check_monotonic_increase",
sql=(
f"select (select count(0) from {staging_dataset}.ror) >= "
f"(select count(0) from {production_dataset}.ror)"
),
use_legacy_sql=False,
),
]
load_production = BigQueryToBigQueryOperator(
task_id="load_production",
source_project_dataset_tables=[f"{staging_dataset}.ror"],
destination_project_dataset_table=f"{production_dataset}.ror",
create_disposition="CREATE_IF_NEEDED",
write_disposition="WRITE_TRUNCATE",
)
# Update column descriptions
with open(f"{DAGS_DIR}/schemas/{gcs_folder}/table_descriptions.json") as f:
table_desc = json.loads(f.read())
pop_descriptions = PythonOperator(
task_id="populate_column_documentation",
op_kwargs={
"input_schema": f"{DAGS_DIR}/schemas/{gcs_folder}/ror.json",
"table_name": f"{production_dataset}.ror",
"table_description": table_desc["ror"],
},
python_callable=update_table_descriptions,
)
# Copy to backups
curr_date = datetime.now().strftime("%Y%m%d")
backup = BigQueryToBigQueryOperator(
task_id="snapshot_ror",
source_project_dataset_tables=[f"{production_dataset}.ror"],
destination_project_dataset_table=f"{backup_dataset}.ror_{curr_date}",
create_disposition="CREATE_IF_NEEDED",
write_disposition="WRITE_TRUNCATE",
)
# Declare victory
success_alert = get_post_success("ROR update succeeded!", dag)
(
clear_tmp_dir
>> download_data
>> add_ultimate_parent
>> load_staging
>> checks
>> load_production
>> pop_descriptions
>> backup
>> success_alert
)