-
Notifications
You must be signed in to change notification settings - Fork 66
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Feat: Onboard Carbon-Free Energy Calculator dataset (#391)
- Loading branch information
1 parent
36056eb
commit f3a9447
Showing
9 changed files
with
459 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
/** | ||
* Copyright 2021 Google LLC | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
|
||
resource "google_storage_bucket" "cfe_calculator" { | ||
name = "${var.bucket_name_prefix}-cfe_calculator" | ||
force_destroy = true | ||
location = "US" | ||
uniform_bucket_level_access = true | ||
lifecycle { | ||
ignore_changes = [ | ||
logging, | ||
] | ||
} | ||
} | ||
|
||
data "google_iam_policy" "storage_bucket__cfe_calculator" { | ||
dynamic "binding" { | ||
for_each = var.iam_policies["storage_buckets"]["cfe_calculator"] | ||
content { | ||
role = binding.value["role"] | ||
members = binding.value["members"] | ||
} | ||
} | ||
} | ||
|
||
resource "google_storage_bucket_iam_policy" "cfe_calculator" { | ||
bucket = google_storage_bucket.cfe_calculator.name | ||
policy_data = data.google_iam_policy.storage_bucket__cfe_calculator.policy_data | ||
} | ||
output "storage_bucket-cfe_calculator-name" { | ||
value = google_storage_bucket.cfe_calculator.name | ||
} | ||
|
||
resource "google_bigquery_dataset" "cfe_calculator" { | ||
dataset_id = "cfe_calculator" | ||
project = var.project_id | ||
description = "OEDI commercial and residential hourly load" | ||
} | ||
|
||
output "bigquery_dataset-cfe_calculator-dataset_id" { | ||
value = google_bigquery_dataset.cfe_calculator.dataset_id | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
/** | ||
* Copyright 2021 Google LLC | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
|
||
provider "google" { | ||
project = var.project_id | ||
impersonate_service_account = var.impersonating_acct | ||
region = var.region | ||
} | ||
|
||
data "google_client_openid_userinfo" "me" {} | ||
|
||
output "impersonating-account" { | ||
value = data.google_client_openid_userinfo.me.email | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,26 @@ | ||
/** | ||
* Copyright 2021 Google LLC | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
|
||
|
||
variable "project_id" {} | ||
variable "bucket_name_prefix" {} | ||
variable "impersonating_acct" {} | ||
variable "region" {} | ||
variable "env" {} | ||
variable "iam_policies" { | ||
default = {} | ||
} | ||
|
21 changes: 21 additions & 0 deletions
21
datasets/cfe_calculator/pipelines/_images/copy_bq_datasets/Dockerfile
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
# Copyright 2021 Google LLC | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
FROM python:3.8 | ||
ENV PYTHONUNBUFFERED True | ||
COPY requirements.txt ./ | ||
RUN python3 -m pip install --no-cache-dir -r requirements.txt | ||
WORKDIR /custom | ||
COPY ./script.py . | ||
CMD ["python3", "script.py"] |
3 changes: 3 additions & 0 deletions
3
datasets/cfe_calculator/pipelines/_images/copy_bq_datasets/requirements.txt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
google-api-core | ||
google-cloud-bigquery-datatransfer | ||
protobuf |
188 changes: 188 additions & 0 deletions
188
datasets/cfe_calculator/pipelines/_images/copy_bq_datasets/script.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,188 @@ | ||
# Copyright 2021 Google LLC | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
import json | ||
import logging | ||
import operator | ||
import os | ||
import time | ||
import typing | ||
|
||
from google.api_core.exceptions import ResourceExhausted | ||
from google.cloud import bigquery_datatransfer_v1 | ||
from google.protobuf.timestamp_pb2 import Timestamp | ||
|
||
RETRY_DELAY = 10 | ||
|
||
|
||
class TimeoutError(Exception): | ||
"""Raised when the BQ transfer jobs haven't all finished within the allotted time""" | ||
|
||
pass | ||
|
||
|
||
def main( | ||
source_project_id: str, | ||
target_project_id: str, | ||
service_account: str, | ||
dataset_name: str, | ||
dataset_versions: typing.List[str], | ||
timeout: int, | ||
): | ||
client = bigquery_datatransfer_v1.DataTransferServiceClient() | ||
transfer_config_prefix = f"{dataset_name}-copy" | ||
transfer_configs = client.list_transfer_configs( | ||
request=bigquery_datatransfer_v1.types.ListTransferConfigsRequest( | ||
parent=f"projects/{target_project_id}" | ||
) | ||
) | ||
|
||
existing_configs = [ | ||
config | ||
for config in transfer_configs | ||
if config.display_name.startswith(transfer_config_prefix) | ||
] | ||
|
||
_running_configs = [] | ||
for version in dataset_versions: | ||
dataset_id = f"{version}" | ||
display_name = f"{transfer_config_prefix}-{version}" | ||
|
||
_config = next( | ||
( | ||
config | ||
for config in existing_configs | ||
if config.display_name == display_name | ||
), | ||
None, | ||
) | ||
if not _config: | ||
_config = create_transfer_config( | ||
client, | ||
source_project_id, | ||
target_project_id, | ||
dataset_id, | ||
display_name, | ||
service_account, | ||
) | ||
|
||
trigger_config(client, _config) | ||
_running_configs.append(_config) | ||
|
||
wait_for_completion(client, _running_configs, timeout) | ||
|
||
|
||
def wait_for_completion( | ||
client: bigquery_datatransfer_v1.DataTransferServiceClient, | ||
running_configs: typing.List[bigquery_datatransfer_v1.types.TransferConfig], | ||
timeout: int, | ||
) -> None: | ||
_start = int(time.time()) | ||
|
||
while True: | ||
latest_runs = [] | ||
for config in running_configs: | ||
latest_runs.append(latest_transfer_run(client, config)) | ||
|
||
logging.info(f"States: {[str(run.state) for run in latest_runs]}") | ||
|
||
# Mark as complete when all runs have succeeded | ||
if all([str(run.state) == "TransferState.SUCCEEDED" for run in latest_runs]): | ||
return | ||
|
||
if all([str(run.state) == "TransferState.FAILED" for run in latest_runs]): | ||
logging.info("error log:") | ||
logging.info(all(str(run.errorStatus.message) for run in latest_runs)) | ||
return | ||
# projects.transferConfigs.runs.transferLogs.list | ||
|
||
# Stop the process when it's longer than the allotted time | ||
if int(time.time()) - _start > timeout: | ||
raise TimeoutError | ||
|
||
time.sleep(RETRY_DELAY) | ||
|
||
|
||
def latest_transfer_run( | ||
client: bigquery_datatransfer_v1.DataTransferServiceClient, | ||
config: bigquery_datatransfer_v1.types.TransferConfig, | ||
) -> bigquery_datatransfer_v1.types.TransferRun: | ||
transfer_runs = client.list_transfer_runs(parent=config.name) | ||
return max(transfer_runs, key=operator.attrgetter("run_time")) | ||
|
||
|
||
def create_transfer_config( | ||
client: bigquery_datatransfer_v1.DataTransferServiceClient, | ||
source_project_id: str, | ||
target_project_id: str, | ||
dataset_id: str, | ||
display_name: str, | ||
service_account: str, | ||
) -> bigquery_datatransfer_v1.types.TransferConfig: | ||
transfer_config = bigquery_datatransfer_v1.TransferConfig( | ||
destination_dataset_id=dataset_id, | ||
display_name=display_name, | ||
data_source_id="cross_region_copy", | ||
dataset_region="US", | ||
params={ | ||
"source_project_id": source_project_id, | ||
"source_dataset_id": dataset_id, | ||
}, | ||
schedule_options=bigquery_datatransfer_v1.ScheduleOptions( | ||
disable_auto_scheduling=True | ||
), | ||
) | ||
|
||
request = bigquery_datatransfer_v1.types.CreateTransferConfigRequest( | ||
parent=client.common_project_path(target_project_id), | ||
transfer_config=transfer_config, | ||
service_account_name=service_account, | ||
) | ||
|
||
return client.create_transfer_config(request=request) | ||
|
||
|
||
def trigger_config( | ||
client: bigquery_datatransfer_v1.DataTransferServiceClient, | ||
config: bigquery_datatransfer_v1.types.TransferConfig, | ||
) -> None: | ||
now = time.time() | ||
seconds = int(now) | ||
nanos = int((now - seconds) * pow(10, 9)) | ||
|
||
try: | ||
client.start_manual_transfer_runs( | ||
request=bigquery_datatransfer_v1.types.StartManualTransferRunsRequest( | ||
parent=config.name, | ||
requested_run_time=Timestamp(seconds=seconds, nanos=nanos), | ||
) | ||
) | ||
except ResourceExhausted: | ||
logging.info( | ||
f"Transfer job is currently running for config ({config.display_name}) {config.name}." | ||
) | ||
return | ||
|
||
|
||
if __name__ == "__main__": | ||
logging.getLogger().setLevel(logging.INFO) | ||
|
||
main( | ||
source_project_id=os.environ["SOURCE_PROJECT_ID"], | ||
target_project_id=os.environ["TARGET_PROJECT_ID"], | ||
service_account=os.environ["SERVICE_ACCOUNT"], | ||
dataset_name=os.environ["DATASET_NAME"], | ||
dataset_versions=json.loads(os.environ["DATASET_VERSIONS"]), | ||
timeout=int(os.getenv("TIMEOUT", 1200)), | ||
) |
53 changes: 53 additions & 0 deletions
53
datasets/cfe_calculator/pipelines/copy_cfe_data/copy_cfe_data_dag.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
# Copyright 2021 Google LLC | ||
# | ||
# Licensed under the Apache License, Version 2.0 (the "License"); | ||
# you may not use this file except in compliance with the License. | ||
# You may obtain a copy of the License at | ||
# | ||
# http://www.apache.org/licenses/LICENSE-2.0 | ||
# | ||
# Unless required by applicable law or agreed to in writing, software | ||
# distributed under the License is distributed on an "AS IS" BASIS, | ||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
# See the License for the specific language governing permissions and | ||
# limitations under the License. | ||
|
||
|
||
from airflow import DAG | ||
from airflow.providers.cncf.kubernetes.operators import kubernetes_pod | ||
|
||
default_args = { | ||
"owner": "Google", | ||
"depends_on_past": False, | ||
"start_date": "2021-11-23", | ||
} | ||
|
||
|
||
with DAG( | ||
dag_id="cfe_calculator.copy_cfe_data", | ||
default_args=default_args, | ||
max_active_runs=1, | ||
schedule_interval="@once", | ||
catchup=False, | ||
default_view="graph", | ||
) as dag: | ||
|
||
# Transfer CFE Databases | ||
copy_bq_dataset = kubernetes_pod.KubernetesPodOperator( | ||
task_id="copy_bq_dataset", | ||
name="copy_bq_dataset", | ||
namespace="composer", | ||
service_account_name="datasets", | ||
image_pull_policy="Always", | ||
image="{{ var.json.cfe_calculator.container_registry.copy_bq_datasets }}", | ||
env_vars={ | ||
"SOURCE_PROJECT_ID": "{{ var.json.cfe_calculator.source_project_id }}", | ||
"TARGET_PROJECT_ID": "{{ var.json.cfe_calculator.target_project_id }}", | ||
"DATASET_NAME": "{{ var.json.cfe_calculator.dataset_name }}", | ||
"DATASET_VERSIONS": "{{ var.json.cfe_calculator.dataset_versions }}", | ||
"SERVICE_ACCOUNT": "{{ var.json.cfe_calculator.service_account }}", | ||
}, | ||
resources={"request_memory": "128M", "request_cpu": "200m"}, | ||
) | ||
|
||
copy_bq_dataset |
Oops, something went wrong.