From 83718569b7094bdf48fa9e8c9504368f17ceda94 Mon Sep 17 00:00:00 2001 From: Nicholas Large <84149918+nlarge-google@users.noreply.github.com> Date: Wed, 1 Sep 2021 09:31:56 -0500 Subject: [PATCH] feat: Onboard NOAA dataset (#158) --- .../Dockerfile | 38 +++ .../Pipfile | 13 + .../csv_transform.py | 259 ++++++++++++++++++ .../requirements.txt | 3 + .../Dockerfile | 38 +++ .../Pipfile | 13 + .../csv_transform.py | 142 ++++++++++ .../requirements.txt | 3 + .../noaa/_terraform/gsod_stations_pipeline.tf | 39 +++ .../lightning_strikes_by_year_pipeline.tf | 39 +++ datasets/noaa/_terraform/noaa_dataset.tf | 26 ++ datasets/noaa/_terraform/provider.tf | 28 ++ datasets/noaa/_terraform/variables.tf | 23 ++ datasets/noaa/dataset.yaml | 58 ++++ .../noaa/gsod_stations/gsod_stations_dag.py | 79 ++++++ datasets/noaa/gsod_stations/pipeline.yaml | 141 ++++++++++ .../lightning_strikes_by_year_dag.py | 73 +++++ .../lightning_strikes_by_year/pipeline.yaml | 115 ++++++++ datasets/noaa/noaa_variables.json | 14 + 19 files changed, 1144 insertions(+) create mode 100644 datasets/noaa/_images/run_csv_transform_kub_gsod_stations/Dockerfile create mode 100644 datasets/noaa/_images/run_csv_transform_kub_gsod_stations/Pipfile create mode 100644 datasets/noaa/_images/run_csv_transform_kub_gsod_stations/csv_transform.py create mode 100644 datasets/noaa/_images/run_csv_transform_kub_gsod_stations/requirements.txt create mode 100644 datasets/noaa/_images/run_csv_transform_kub_lightning_strikes_by_year/Dockerfile create mode 100644 datasets/noaa/_images/run_csv_transform_kub_lightning_strikes_by_year/Pipfile create mode 100644 datasets/noaa/_images/run_csv_transform_kub_lightning_strikes_by_year/csv_transform.py create mode 100644 datasets/noaa/_images/run_csv_transform_kub_lightning_strikes_by_year/requirements.txt create mode 100644 datasets/noaa/_terraform/gsod_stations_pipeline.tf create mode 100644 datasets/noaa/_terraform/lightning_strikes_by_year_pipeline.tf create mode 100644 datasets/noaa/_terraform/noaa_dataset.tf create mode 100644 datasets/noaa/_terraform/provider.tf create mode 100644 datasets/noaa/_terraform/variables.tf create mode 100644 datasets/noaa/dataset.yaml create mode 100644 datasets/noaa/gsod_stations/gsod_stations_dag.py create mode 100644 datasets/noaa/gsod_stations/pipeline.yaml create mode 100644 datasets/noaa/lightning_strikes_by_year/lightning_strikes_by_year_dag.py create mode 100644 datasets/noaa/lightning_strikes_by_year/pipeline.yaml create mode 100644 datasets/noaa/noaa_variables.json diff --git a/datasets/noaa/_images/run_csv_transform_kub_gsod_stations/Dockerfile b/datasets/noaa/_images/run_csv_transform_kub_gsod_stations/Dockerfile new file mode 100644 index 000000000..85af90570 --- /dev/null +++ b/datasets/noaa/_images/run_csv_transform_kub_gsod_stations/Dockerfile @@ -0,0 +1,38 @@ +# 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. + +# The base image for this build +# FROM gcr.io/google.com/cloudsdktool/cloud-sdk:slim +FROM python:3.8 + +# Allow statements and log messages to appear in Cloud logs +ENV PYTHONUNBUFFERED True + +# Copy the requirements file into the image +COPY requirements.txt ./ + +# Install the packages specified in the requirements file +RUN python3 -m pip install --no-cache-dir -r requirements.txt + +# The WORKDIR instruction sets the working directory for any RUN, CMD, +# ENTRYPOINT, COPY and ADD instructions that follow it in the Dockerfile. +# If the WORKDIR doesn’t exist, it will be created even if it’s not used in +# any subsequent Dockerfile instruction +WORKDIR /custom + +# Copy the specific data processing script/s in the image under /custom/* +COPY ./csv_transform.py . + +# Command to run the data processing script when the container is run +CMD ["python3", "csv_transform.py"] diff --git a/datasets/noaa/_images/run_csv_transform_kub_gsod_stations/Pipfile b/datasets/noaa/_images/run_csv_transform_kub_gsod_stations/Pipfile new file mode 100644 index 000000000..37f9797d3 --- /dev/null +++ b/datasets/noaa/_images/run_csv_transform_kub_gsod_stations/Pipfile @@ -0,0 +1,13 @@ +[[source]] +url = "https://pypi.org/simple" +verify_ssl = true +name = "pypi" + +[packages] +requests = "*" +vaex = "*" + +[dev-packages] + +[requires] +python_version = "3.9" diff --git a/datasets/noaa/_images/run_csv_transform_kub_gsod_stations/csv_transform.py b/datasets/noaa/_images/run_csv_transform_kub_gsod_stations/csv_transform.py new file mode 100644 index 000000000..37c0b18f5 --- /dev/null +++ b/datasets/noaa/_images/run_csv_transform_kub_gsod_stations/csv_transform.py @@ -0,0 +1,259 @@ +# 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 gzip +import logging +import os +import pathlib +import re +import urllib.request +from ftplib import FTP + +import pandas as pd +import requests +from google.cloud import storage + + +def main( + source_url: str, + ftp_host: str, + ftp_dir: str, + ftp_filename: str, + source_file: pathlib.Path, + target_file: pathlib.Path, + target_gcs_bucket: str, + target_gcs_path: str, +): + + # source_url STRING -> The full url of the source file to transform + # ftp_host STRING -> The host IP of the ftp file (IP only) + # ftp_dir STRING -> The remote working directory that the FTP file resides in (directory only) + # ftp_filename STRING -> The name of the file to pull from the FTP site + # source_file PATHLIB.PATH -> The (local) path pertaining to the downloaded source file + # target_file PATHLIB.PATH -> The (local) target transformed file + filename + # target_gcs_bucket STRING -> The target GCS bucket to place the output (transformed) file + # target_gcs_path STRING -> The target GCS path ( within the GCS bucket ) to place the output (transformed) file + + logging.info("NOAA GSOD Stations By Year process started") + + logging.info(f"starting processing {source_url}") + + if url_is_reachable(source_url): + + logging.info("creating 'files' folder") + pathlib.Path("./files").mkdir(parents=True, exist_ok=True) + + logging.info(f"Downloading FTP file {source_url} from {ftp_host}") + download_file_ftp(ftp_host, ftp_dir, ftp_filename, source_file, source_url) + + logging.info(f"Removing unnecessary header in {source_file}") + os.system(f"tail -n +21 {source_file}.bak > {source_file}.1") + os.system(f"sed '2d' {source_file}.1 > {source_file}") + os.unlink(str(source_file) + ".bak") + os.unlink(str(source_file) + ".1") + + logging.info(f"Opening source file {source_file}") + colspecs = [ + (0, 6), # usaf + (7, 12), # wban + (13, 42), # name + (43, 45), # country + (48, 50), # state + (51, 56), # call + (57, 64), # lat + (65, 74), # lon + (75, 81), # elev + (82, 90), # begin + (91, 99), # end + ] + df = pd.read_fwf(str(source_file), colspecs=colspecs) + + logging.info(f"Transform: Renaming Headers.. {source_file}") + df.columns = [ + "usaf", + "wban", + "name", + "country", + "state", + "call", + "lat", + "lon", + "elev", + "begin", + "end", + ] + + # remove rows with empty (usaf) data + df = df[df.usaf != ""] + + # execute reg-ex replacements + logging.info(f"Transform: Executing Reg Ex.. {source_file}") + logging.info(f" Executing Reg Ex.. (lat) {source_file}") + df["lat"] = df["lat"].astype(str) + df["lat"][:].replace("^(-[0]+)(.*)", "-$2", regex=True, inplace=True) + df["lat"][:].replace("^(\\s+)$", "", regex=True, inplace=True) + df["lat"][:].replace( + "^(\\+\\d+\\.\\d+[0-9])\\s+", "$1", regex=True, inplace=True + ) + df["lat"][:].replace("^(-\\d+\\.\\d+[0-9])\\s+", "$1", regex=True, inplace=True) + df["lat"][:].replace("nan", "", regex=False, inplace=True) + + logging.info(f" Executing Reg Ex.. (lon) {source_file}") + df["lon"] = df["lon"].astype(str) + df["lon"][:].replace("^(-[0]+)(.*)", "-$2", regex=True, inplace=True) + df["lon"][:].replace("^(\\s+)$", "", regex=True, inplace=True) + df["lon"][:].replace( + "^(\\+\\d+\\.\\d+[0-9])\\s+", "$1", regex=True, inplace=True + ) + df["lon"][:].replace("^(-\\d+\\.\\d+[0-9])\\s+", "$1", regex=True, inplace=True) + df["lon"][:].replace("nan", "", regex=False, inplace=True) + + logging.info(f" Executing Reg Ex.. (usaf) {source_file}") + df["usaf"][:].replace("(\\d{1,})(\\s{1,})$", "$1", regex=True, inplace=True) + + logging.info(f" Executing Reg Ex.. (name) {source_file}") + df["name"][:].replace("^\\s{1,}([a-zA-Z]\\D+)", "$1", regex=True, inplace=True) + df["name"][:].replace("^(\\D+[a-zA-Z])\\s{1,}$", "$1", regex=True, inplace=True) + df["name"][:].replace("^(\\s+)$", "", regex=True, inplace=True) + + logging.info(f" Executing Reg Ex.. (call) {source_file}") + df["call"][:].replace("^(\\s+)$", "", regex=True, inplace=True) + df["call"][:].replace("^([a-zA-Z]+)\\s+", "$1", regex=True, inplace=True) + + logging.info(f" Executing Reg Ex.. (elev) {source_file}") + df["elev"][:].replace("^(\\s+)$", "", regex=True, inplace=True) + + logging.info(f" Executing Reg Ex.. (state) {source_file}") + df["state"][:].replace("^(\\s+)$", "", regex=True, inplace=True) + + logging.info(f" Executing Reg Ex.. (country) {source_file}") + df["country"][:].replace("^(\\s+)$", "", regex=True, inplace=True) + + logging.info(f"Transform: Saving to output file.. {target_file}") + df.to_csv(target_file, index=False) + + logging.info(f"completed processing {source_url}") + + logging.info( + f"Uploading output file to.. gs://{target_gcs_bucket}/{target_gcs_path}" + ) + upload_file_to_gcs(target_file, target_gcs_bucket, target_gcs_path) + + logging.info("NOAA GSOD Stations process completed") + + else: + + logging.info(f"Error: Unable to reach url: {source_url}") + logging.info("Process failed!") + + +def replace_value(val: str) -> str: + if val is None or len(val) == 0: + return val + else: + if val.find("\n") > 0: + return re.sub(r"(^\d):(\d{2}:\d{2})", "0$1:$2", val) + else: + return val + + +def replace_values_regex(df: pd.DataFrame) -> None: + header_names = {"checkout_time"} + + for dt_col in header_names: + if (df[dt_col] is not None) & (df[dt_col].str.len() > 0): + df[dt_col] = df[dt_col].apply(replace_value) + + +def download_file_ftp( + ftp_host: str, + ftp_dir: str, + ftp_filename: str, + local_file: pathlib.Path, + source_url: str, +) -> None: + + # ftp_host -> host ip (eg. 123.123.0.1) + # ftp_dir -> working directory in ftp host where file is located + # ftp_filename -> filename of FTP file to download + # source_file -> local file (including path) to create containing ftp content + + logging.info(f"Downloading {source_url} into {local_file}") + ftp_conn = FTP(ftp_host) + ftp_conn.login("", "") + ftp_conn.cwd(ftp_dir) + + try: + bak_local_file = str(local_file) + ".bak" + dest_file = open(bak_local_file, "wb") + ftp_conn.encoding = "utf-8" + ftp_conn.retrbinary( + cmd="RETR " + ftp_filename, + callback=dest_file.write, + blocksize=1024, + rest=None, + ) + ftp_conn.quit() + dest_file.close() + except Exception as e: + logging.error(f"Error saving output file: {e}.") + + +def gz_decompress(infile: str, tofile: str) -> None: + with open(infile, "rb") as inf, open(tofile, "w", encoding="utf8") as tof: + decom_str = gzip.decompress(inf.read()).decode("utf-8") + tof.write(decom_str) + + +def url_is_reachable(url: str) -> bool: + + request = urllib.request.Request(url) + request.get_method = lambda: "HEAD" + + try: + urllib.request.urlopen(request) + return True + except urllib.request.HTTPError: + return False + + +def download_file(source_url: str, source_file: pathlib.Path) -> None: + r = requests.get(source_url, stream=True) + if r.status_code == 200: + with open(source_file, "wb") as f: + for chunk in r: + f.write(chunk) + else: + logging.error(f"Couldn't download {source_url}: {r.text}") + + +def upload_file_to_gcs(file_path: pathlib.Path, gcs_bucket: str, gcs_path: str) -> None: + storage_client = storage.Client() + bucket = storage_client.bucket(gcs_bucket) + blob = bucket.blob(gcs_path) + blob.upload_from_filename(file_path) + + +if __name__ == "__main__": + logging.getLogger().setLevel(logging.INFO) + main( + source_url=os.environ["SOURCE_URL"], + ftp_host=os.environ["FTP_HOST"], + ftp_dir=os.environ["FTP_DIR"], + ftp_filename=os.environ["FTP_FILENAME"], + source_file=pathlib.Path(os.environ["SOURCE_FILE"]).expanduser(), + target_file=pathlib.Path(os.environ["TARGET_FILE"]).expanduser(), + target_gcs_bucket=os.environ["TARGET_GCS_BUCKET"], + target_gcs_path=os.environ["TARGET_GCS_PATH"], + ) diff --git a/datasets/noaa/_images/run_csv_transform_kub_gsod_stations/requirements.txt b/datasets/noaa/_images/run_csv_transform_kub_gsod_stations/requirements.txt new file mode 100644 index 000000000..f36704793 --- /dev/null +++ b/datasets/noaa/_images/run_csv_transform_kub_gsod_stations/requirements.txt @@ -0,0 +1,3 @@ +requests +pandas +google-cloud-storage diff --git a/datasets/noaa/_images/run_csv_transform_kub_lightning_strikes_by_year/Dockerfile b/datasets/noaa/_images/run_csv_transform_kub_lightning_strikes_by_year/Dockerfile new file mode 100644 index 000000000..85af90570 --- /dev/null +++ b/datasets/noaa/_images/run_csv_transform_kub_lightning_strikes_by_year/Dockerfile @@ -0,0 +1,38 @@ +# 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. + +# The base image for this build +# FROM gcr.io/google.com/cloudsdktool/cloud-sdk:slim +FROM python:3.8 + +# Allow statements and log messages to appear in Cloud logs +ENV PYTHONUNBUFFERED True + +# Copy the requirements file into the image +COPY requirements.txt ./ + +# Install the packages specified in the requirements file +RUN python3 -m pip install --no-cache-dir -r requirements.txt + +# The WORKDIR instruction sets the working directory for any RUN, CMD, +# ENTRYPOINT, COPY and ADD instructions that follow it in the Dockerfile. +# If the WORKDIR doesn’t exist, it will be created even if it’s not used in +# any subsequent Dockerfile instruction +WORKDIR /custom + +# Copy the specific data processing script/s in the image under /custom/* +COPY ./csv_transform.py . + +# Command to run the data processing script when the container is run +CMD ["python3", "csv_transform.py"] diff --git a/datasets/noaa/_images/run_csv_transform_kub_lightning_strikes_by_year/Pipfile b/datasets/noaa/_images/run_csv_transform_kub_lightning_strikes_by_year/Pipfile new file mode 100644 index 000000000..37f9797d3 --- /dev/null +++ b/datasets/noaa/_images/run_csv_transform_kub_lightning_strikes_by_year/Pipfile @@ -0,0 +1,13 @@ +[[source]] +url = "https://pypi.org/simple" +verify_ssl = true +name = "pypi" + +[packages] +requests = "*" +vaex = "*" + +[dev-packages] + +[requires] +python_version = "3.9" diff --git a/datasets/noaa/_images/run_csv_transform_kub_lightning_strikes_by_year/csv_transform.py b/datasets/noaa/_images/run_csv_transform_kub_lightning_strikes_by_year/csv_transform.py new file mode 100644 index 000000000..2244a729d --- /dev/null +++ b/datasets/noaa/_images/run_csv_transform_kub_lightning_strikes_by_year/csv_transform.py @@ -0,0 +1,142 @@ +# 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 gzip +import logging +import os +import pathlib +import urllib.request + +import pandas as pd +import requests +from google.cloud import storage + + +def main( + source_url: str, + source_file: pathlib.Path, + target_file: pathlib.Path, + target_gcs_bucket: str, + target_gcs_path: str, +): + + logging.info("NOAA Lightning Strikes By Year process started") + + if url_is_reachable(source_url): + + logging.info("creating 'files' folder") + pathlib.Path("./files").mkdir(parents=True, exist_ok=True) + + source_file_zipped = str(source_file) + ".gz" + source_file_unzipped = str(source_file) + ".1" + + logging.info(f"Downloading source file {source_url}") + download_file(source_url, source_file_zipped) + + logging.info(f"Decompressing {source_file_unzipped}") + gz_decompress(source_file_zipped, source_file_unzipped) + + logging.info(f"Removing unnecessary header in {source_file_unzipped}") + os.system(f"echo 'DATE,LONGITUDE,LATITUDE,TOTAL_COUNT' > {source_file}") + os.system(f"tail -n +4 {source_file_unzipped} >> {source_file}") + os.unlink(source_file_unzipped) + os.unlink(source_file_zipped) + + logging.info(f"Opening source file {source_file}") + df = pd.read_csv(str(source_file)) + + logging.info(f"Transform: Renaming Headers.. {source_file}") + df.columns = ["day_int", "centerlon", "centerlat", "number_of_strikes"] + + logging.info(f"Converting datetime format in {source_file}") + df["day"] = ( + pd.to_datetime( + (df["day_int"][:].astype("string") + "000000"), "raise", False, True + ).astype(str) + + " 00:00:00" + ) + + df["center_point"] = ( + "POINT(" + + df["centerlon"][:].astype("string") + + " " + + df["centerlat"][:].astype("string") + + ")" + ) + + logging.info(f"Reordering columns in {source_file}") + df = df[["day", "number_of_strikes", "center_point"]] + + logging.info(f"Transform: Saving to output file.. {target_file}") + df.to_csv(target_file, index=False) + + logging.info(f"completed processing {source_url}") + logging.info( + f"Uploading output file to.. gs://{target_gcs_bucket}/{target_gcs_path}" + ) + upload_file_to_gcs(target_file, target_gcs_bucket, target_gcs_path) + + logging.info("NOAA Lightning Strikes By Year process completed") + + else: + + logging.info(f"Error: Unable to reach url: {source_url}") + logging.info("Process failed!") + + +def gz_decompress(infile: str, tofile: str) -> None: + with open(infile, "rb") as inf, open(tofile, "w", encoding="utf8") as tof: + decom_str = gzip.decompress(inf.read()).decode("utf-8") + tof.write(decom_str) + + +def url_is_reachable(url: str) -> bool: + + request = urllib.request.Request(url) + request.get_method = lambda: "HEAD" + + try: + urllib.request.urlopen(request) + return True + except urllib.request.HTTPError: + return False + + +def download_file(source_url: str, source_file: pathlib.Path) -> None: + r = requests.get(source_url, stream=True) + if r.status_code == 200: + with open(source_file, "wb") as f: + for chunk in r: + f.write(chunk) + else: + logging.error(f"Couldn't download {source_url}: {r.text}") + + +def upload_file_to_gcs(file_path: pathlib.Path, gcs_bucket: str, gcs_path: str) -> None: + storage_client = storage.Client() + bucket = storage_client.bucket(gcs_bucket) + blob = bucket.blob(gcs_path) + blob.upload_from_filename(file_path) + + +if __name__ == "__main__": + logging.getLogger().setLevel(logging.INFO) + + main( + source_url=os.environ["SOURCE_URL"], + source_file=pathlib.Path(os.environ["SOURCE_FILE"]).expanduser(), + target_file=pathlib.Path(os.environ["TARGET_FILE"]).expanduser(), + target_gcs_bucket=os.environ["TARGET_GCS_BUCKET"], + target_gcs_path=os.environ["TARGET_GCS_PATH"], + ) diff --git a/datasets/noaa/_images/run_csv_transform_kub_lightning_strikes_by_year/requirements.txt b/datasets/noaa/_images/run_csv_transform_kub_lightning_strikes_by_year/requirements.txt new file mode 100644 index 000000000..f36704793 --- /dev/null +++ b/datasets/noaa/_images/run_csv_transform_kub_lightning_strikes_by_year/requirements.txt @@ -0,0 +1,3 @@ +requests +pandas +google-cloud-storage diff --git a/datasets/noaa/_terraform/gsod_stations_pipeline.tf b/datasets/noaa/_terraform/gsod_stations_pipeline.tf new file mode 100644 index 000000000..2b44b6b4b --- /dev/null +++ b/datasets/noaa/_terraform/gsod_stations_pipeline.tf @@ -0,0 +1,39 @@ +/** + * 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_bigquery_table" "gsod_stations" { + project = var.project_id + dataset_id = "noaa" + table_id = "gsod_stations" + + description = "noaaspc" + + + + + depends_on = [ + google_bigquery_dataset.noaa + ] +} + +output "bigquery_table-gsod_stations-table_id" { + value = google_bigquery_table.gsod_stations.table_id +} + +output "bigquery_table-gsod_stations-id" { + value = google_bigquery_table.gsod_stations.id +} diff --git a/datasets/noaa/_terraform/lightning_strikes_by_year_pipeline.tf b/datasets/noaa/_terraform/lightning_strikes_by_year_pipeline.tf new file mode 100644 index 000000000..e24620ca8 --- /dev/null +++ b/datasets/noaa/_terraform/lightning_strikes_by_year_pipeline.tf @@ -0,0 +1,39 @@ +/** + * 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_bigquery_table" "lightning_strikes_by_year" { + project = var.project_id + dataset_id = "noaa" + table_id = "lightning_strikes_by_year" + + description = "noaaspc" + + + + + depends_on = [ + google_bigquery_dataset.noaa + ] +} + +output "bigquery_table-lightning_strikes_by_year-table_id" { + value = google_bigquery_table.lightning_strikes_by_year.table_id +} + +output "bigquery_table-lightning_strikes_by_year-id" { + value = google_bigquery_table.lightning_strikes_by_year.id +} diff --git a/datasets/noaa/_terraform/noaa_dataset.tf b/datasets/noaa/_terraform/noaa_dataset.tf new file mode 100644 index 000000000..d7f371e74 --- /dev/null +++ b/datasets/noaa/_terraform/noaa_dataset.tf @@ -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. + */ + + +resource "google_bigquery_dataset" "noaa" { + dataset_id = "noaa" + project = var.project_id + description = "noaa" +} + +output "bigquery_dataset-noaa-dataset_id" { + value = google_bigquery_dataset.noaa.dataset_id +} diff --git a/datasets/noaa/_terraform/provider.tf b/datasets/noaa/_terraform/provider.tf new file mode 100644 index 000000000..23ab87dcd --- /dev/null +++ b/datasets/noaa/_terraform/provider.tf @@ -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 +} diff --git a/datasets/noaa/_terraform/variables.tf b/datasets/noaa/_terraform/variables.tf new file mode 100644 index 000000000..c3ec7c506 --- /dev/null +++ b/datasets/noaa/_terraform/variables.tf @@ -0,0 +1,23 @@ +/** + * 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" {} + diff --git a/datasets/noaa/dataset.yaml b/datasets/noaa/dataset.yaml new file mode 100644 index 000000000..d3aace4cd --- /dev/null +++ b/datasets/noaa/dataset.yaml @@ -0,0 +1,58 @@ +# 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. + +dataset: + # The `dataset` block includes properties for your dataset that will be shown + # to users of your data on the Google Cloud website. + + # Must be exactly the same name as the folder name your dataset.yaml is in. + name: noaa + + # A friendly, human-readable name of the dataset + friendly_name: ~ + + # A short, descriptive summary of the dataset. + description: ~ + + # A list of sources the dataset is derived from, using the YAML list syntax. + dataset_sources: ~ + + # A list of terms and conditions that users of the dataset should agree on, + # using the YAML list syntax. + terms_of_use: ~ + + +resources: + # A list of Google Cloud resources needed by your dataset. In principle, all + # pipelines under a dataset should be able to share these resources. + # + # The currently supported resources are shown below. Use only the resources + # you need, and delete the rest as needed by your pipeline. + # + # We will keep adding to the list below to support more Google Cloud resources + # over time. If a resource you need isn't supported, please file an issue on + # the repository. + + - type: bigquery_dataset + # Google BigQuery dataset to namespace all tables managed by this folder + # + # Required Properties: + # dataset_id + # + # Optional Properties: + # friendly_name (A user-friendly name of the dataset) + # description (A user-friendly description of the dataset) + # location (The geographic location where the dataset should reside) + dataset_id: noaa + description: noaa diff --git a/datasets/noaa/gsod_stations/gsod_stations_dag.py b/datasets/noaa/gsod_stations/gsod_stations_dag.py new file mode 100644 index 000000000..5551ac168 --- /dev/null +++ b/datasets/noaa/gsod_stations/gsod_stations_dag.py @@ -0,0 +1,79 @@ +# 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.contrib.operators import gcs_to_bq, kubernetes_pod_operator + +default_args = { + "owner": "Google", + "depends_on_past": False, + "start_date": "2021-03-01", +} + + +with DAG( + dag_id="noaa.gsod_stations", + default_args=default_args, + max_active_runs=1, + schedule_interval="@daily", + catchup=False, + default_view="graph", +) as dag: + + # Run CSV transform within kubernetes pod + transform_csv = kubernetes_pod_operator.KubernetesPodOperator( + task_id="transform_csv", + name="gsod_stations", + namespace="default", + image_pull_policy="Always", + image="{{ var.json.noaa_gsod_stations.container_registry.run_csv_transform_kub_gsod_stations }}", + env_vars={ + "SOURCE_URL": "ftp://ftp.ncdc.noaa.gov/pub/data/noaa/isd-history.txt", + "FTP_HOST": "ftp.ncdc.noaa.gov", + "FTP_DIR": "/pub/data/noaa", + "FTP_FILENAME": "isd-history.txt", + "SOURCE_FILE": "files/data.csv", + "TARGET_FILE": "files/data_output.csv", + "TARGET_GCS_BUCKET": "{{ var.json.shared.composer_bucket }}", + "TARGET_GCS_PATH": "data/noaa/gsod_stations/data_output.csv", + }, + resources={"limit_memory": "2G", "limit_cpu": "1"}, + ) + + # Task to load CSV data to a BigQuery table + load_to_bq = gcs_to_bq.GoogleCloudStorageToBigQueryOperator( + task_id="load_to_bq", + bucket="{{ var.json.shared.composer_bucket }}", + source_objects=["data/noaa/gsod_stations/data_output.csv"], + source_format="CSV", + destination_project_dataset_table="noaa.gsod_stations", + skip_leading_rows=1, + write_disposition="WRITE_TRUNCATE", + schema_fields=[ + {"name": "usaf", "type": "STRING", "mode": "NULLABLE"}, + {"name": "wban", "type": "STRING", "mode": "NULLABLE"}, + {"name": "name", "type": "STRING", "mode": "NULLABLE"}, + {"name": "country", "type": "STRING", "mode": "NULLABLE"}, + {"name": "state", "type": "STRING", "mode": "NULLABLE"}, + {"name": "call", "type": "STRING", "mode": "NULLABLE"}, + {"name": "lat", "type": "FLOAT", "mode": "NULLABLE"}, + {"name": "lon", "type": "FLOAT", "mode": "NULLABLE"}, + {"name": "elev", "type": "STRING", "mode": "NULLABLE"}, + {"name": "begin", "type": "STRING", "mode": "NULLABLE"}, + {"name": "end", "type": "STRING", "mode": "NULLABLE"}, + ], + ) + + transform_csv >> load_to_bq diff --git a/datasets/noaa/gsod_stations/pipeline.yaml b/datasets/noaa/gsod_stations/pipeline.yaml new file mode 100644 index 000000000..1534a1821 --- /dev/null +++ b/datasets/noaa/gsod_stations/pipeline.yaml @@ -0,0 +1,141 @@ +# 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. + +--- +resources: + + - type: bigquery_table + # Required Properties: + table_id: gsod_stations + + # Description of the table + description: "noaaspc" + +dag: + airflow_version: 2 + initialize: + dag_id: gsod_stations + default_args: + owner: "Google" + + # When set to True, keeps a task from getting triggered if the previous schedule for the task hasn’t succeeded + depends_on_past: False + start_date: '2021-12-30' + max_active_runs: 1 + schedule_interval: "@yearly" + catchup: False + default_view: graph + + tasks: + + - operator: "KubernetesPodOperator" + + # Task description + description: "Run CSV transform within kubernetes pod" + + args: + + task_id: "transform_csv" + + # The name of the pod in which the task will run. This will be used (plus a random suffix) to generate a pod id + name: "gsod_stations" + + # The namespace to run within Kubernetes. Always set its value to "default" because we follow the guideline that KubernetesPodOperator will only be used for very light workloads, i.e. use the Cloud Composer environment's resources without starving other pipelines. + namespace: "default" + + image_pull_policy: "Always" + + # Docker images will be built and pushed to GCR by default whenever the `scripts/generate_dag.py` is run. To skip building and pushing images, use the optional `--skip-builds` flag. + image: "{{ var.json.noaa_gsod_stations.container_registry.run_csv_transform_kub_gsod_stations }}" + + # Set the environment variables you need initialized in the container. Use these as input variables for the script your container is expected to perform. + env_vars: + SOURCE_URL: "ftp://ftp.ncdc.noaa.gov/pub/data/noaa/isd-history.txt" + FTP_HOST: "ftp.ncdc.noaa.gov" + FTP_DIR: "/pub/data/noaa" + FTP_FILENAME: "isd-history.txt" + SOURCE_FILE: "files/data.csv" + TARGET_FILE: "files/data_output.csv" + TARGET_GCS_BUCKET: "{{ var.json.shared.composer_bucket }}" + TARGET_GCS_PATH: "data/noaa/gsod_stations/data_output.csv" + + + # Set resource limits for the pod here. For resource units in Kubernetes, see https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#resource-units-in-kubernetes + resources: + limit_memory: "2G" + limit_cpu: "1" + + - operator: "GoogleCloudStorageToBigQueryOperator" + description: "Task to load CSV data to a BigQuery table" + + args: + task_id: "load_to_bq" + + # The GCS bucket where the CSV file is located in. + bucket: "{{ var.json.shared.composer_bucket }}" + + # The GCS object path for the CSV file + source_objects: ["data/noaa/gsod_stations/data_output.csv"] + source_format: "CSV" + destination_project_dataset_table: "noaa.gsod_stations" + + # Use this if your CSV file contains a header row + skip_leading_rows: 1 + + # How to write data to the table: overwrite, append, or write if empty + # See https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/WriteDisposition + write_disposition: "WRITE_TRUNCATE" + + # The BigQuery table schema based on the CSV file. For more info, see + # https://cloud.google.com/bigquery/docs/schemas. + # Always use snake_case and lowercase for column names, and be explicit, + # i.e. specify modes for all columns. + # types: "INTEGER", "TIMESTAMP", "STRING" + schema_fields: + - name: "usaf" + type: "STRING" + mode: "NULLABLE" + - name: "wban" + type: "STRING" + mode: "NULLABLE" + - name: "name" + type: "STRING" + mode: "NULLABLE" + - name: "country" + type: "STRING" + mode: "NULLABLE" + - name: "state" + type: "STRING" + mode: "NULLABLE" + - name: "call" + type: "STRING" + mode: "NULLABLE" + - name: "lat" + type: "FLOAT" + mode: "NULLABLE" + - name: "lon" + type: "FLOAT" + mode: "NULLABLE" + - name: "elev" + type: "STRING" + mode: "NULLABLE" + - name: "begin" + type: "STRING" + mode: "NULLABLE" + - name: "end" + type: "STRING" + mode: "NULLABLE" + + graph_paths: + - transform_csv >> load_to_bq diff --git a/datasets/noaa/lightning_strikes_by_year/lightning_strikes_by_year_dag.py b/datasets/noaa/lightning_strikes_by_year/lightning_strikes_by_year_dag.py new file mode 100644 index 000000000..4a197cd40 --- /dev/null +++ b/datasets/noaa/lightning_strikes_by_year/lightning_strikes_by_year_dag.py @@ -0,0 +1,73 @@ +# 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.contrib.operators import gcs_to_bq, kubernetes_pod_operator + +default_args = { + "owner": "Google", + "depends_on_past": False, + "start_date": "2021-03-01", +} + + +with DAG( + dag_id="noaa.lightning_strikes_by_year", + default_args=default_args, + max_active_runs=1, + schedule_interval="@daily", + catchup=False, + default_view="graph", +) as dag: + + # Run CSV transform within kubernetes pod + transform_csv = kubernetes_pod_operator.KubernetesPodOperator( + task_id="transform_csv", + name="lightning_strikes_by_year", + namespace="default", + image_pull_policy="Always", + image="{{ var.json.noaa_lightning_strikes_by_year.container_registry.run_csv_transform_kub_lightning_strikes_by_year }}", + env_vars={ + "SOURCE_URL": "https://www1.ncdc.noaa.gov/pub/data/swdi/database-csv/v2/nldn-tiles-{{ macros.ds_format(macros.ds_add(ds, -365), '%Y-%m-%d', '%Y') }}.csv.gz", + "SOURCE_FILE": "files/data.csv", + "TARGET_FILE": "files/data_output.csv", + "TARGET_GCS_BUCKET": "{{ var.json.shared.composer_bucket }}", + "TARGET_GCS_PATH": "data/noaa/lightning_strikes_by_year/data_output.csv", + }, + resources={"limit_memory": "2G", "limit_cpu": "1"}, + ) + + # Task to load CSV data to a BigQuery table + load_to_bq = gcs_to_bq.GoogleCloudStorageToBigQueryOperator( + task_id="load_to_bq", + bucket="{{ var.json.shared.composer_bucket }}", + source_objects=["data/noaa/lightning_strikes_by_year/data_output.csv"], + source_format="CSV", + destination_project_dataset_table="noaa.lightning_strikes_{{ macros.ds_format(macros.ds_add(ds, -365), \u0027%Y-%m-%d\u0027, \u0027%Y\u0027) }}", + skip_leading_rows=1, + write_disposition="WRITE_TRUNCATE", + schema_fields=[ + {"name": "date", "type": "TIMESTAMP", "mode": "NULLABLE"}, + {"name": "number_of_strikes", "type": "INTEGER", "mode": "NULLABLE"}, + { + "name": "center_point_geom", + "type": "GEOGRAPHY", + "description": "Center point of 0.10-degree tiles (roughly 1.1km) that aggregate strikes within the given tile.", + "mode": "NULLABLE", + }, + ], + ) + + transform_csv >> load_to_bq diff --git a/datasets/noaa/lightning_strikes_by_year/pipeline.yaml b/datasets/noaa/lightning_strikes_by_year/pipeline.yaml new file mode 100644 index 000000000..abf2f5da6 --- /dev/null +++ b/datasets/noaa/lightning_strikes_by_year/pipeline.yaml @@ -0,0 +1,115 @@ +# 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. + +--- +resources: + + - type: bigquery_table + # Required Properties: + table_id: lightning_strikes_by_year + + # Description of the table + description: "noaaspc" + +dag: + airflow_version: 2 + initialize: + dag_id: lightning_strikes_by_year + default_args: + owner: "Google" + + # When set to True, keeps a task from getting triggered if the previous schedule for the task hasn’t succeeded + depends_on_past: False + start_date: '2021-12-30' + max_active_runs: 1 + schedule_interval: "@yearly" # run once a week at Sunday 12am + catchup: False + default_view: graph + + tasks: + + - operator: "KubernetesPodOperator" + + # Task description + description: "Run CSV transform within kubernetes pod" + + args: + + task_id: "transform_csv" + + # The name of the pod in which the task will run. This will be used (plus a random suffix) to generate a pod id + name: "lightning_strikes_by_year" + + # The namespace to run within Kubernetes. Always set its value to "default" because we follow the guideline that KubernetesPodOperator will only be used for very light workloads, i.e. use the Cloud Composer environment's resources without starving other pipelines. + namespace: "default" + + image_pull_policy: "Always" + + # Docker images will be built and pushed to GCR by default whenever the `scripts/generate_dag.py` is run. To skip building and pushing images, use the optional `--skip-builds` flag. + image: "{{ var.json.noaa_lightning_strikes_by_year.container_registry.run_csv_transform_kub_lightning_strikes_by_year }}" + + # Set the environment variables you need initialized in the container. Use these as input variables for the script your container is expected to perform. + env_vars: + SOURCE_URL: "https://www1.ncdc.noaa.gov/pub/data/swdi/database-csv/v2/nldn-tiles-{{ macros.ds_format(macros.ds_add(ds, -365), '%Y-%m-%d', '%Y') }}.csv.gz" + SOURCE_FILE: "files/data.csv" + TARGET_FILE: "files/data_output.csv" + TARGET_GCS_BUCKET: "{{ var.json.shared.composer_bucket }}" + TARGET_GCS_PATH: "data/noaa/lightning_strikes_by_year/data_output.csv" + + + # Set resource limits for the pod here. For resource units in Kubernetes, see https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/#resource-units-in-kubernetes + resources: + limit_memory: "2G" + limit_cpu: "1" + + - operator: "GoogleCloudStorageToBigQueryOperator" + description: "Task to load CSV data to a BigQuery table" + + args: + task_id: "load_to_bq" + + # The GCS bucket where the CSV file is located in. + bucket: "{{ var.json.shared.composer_bucket }}" + + # The GCS object path for the CSV file + source_objects: ["data/noaa/lightning_strikes_by_year/data_output.csv"] + source_format: "CSV" + destination_project_dataset_table: "noaa.lightning_strikes_{{ macros.ds_format(macros.ds_add(ds, -365), '%Y-%m-%d', '%Y') }}" + + # Use this if your CSV file contains a header row + skip_leading_rows: 1 + + # How to write data to the table: overwrite, append, or write if empty + # See https://cloud.google.com/bigquery/docs/reference/auditlogs/rest/Shared.Types/WriteDisposition + write_disposition: "WRITE_TRUNCATE" + + # The BigQuery table schema based on the CSV file. For more info, see + # https://cloud.google.com/bigquery/docs/schemas. + # Always use snake_case and lowercase for column names, and be explicit, + # i.e. specify modes for all columns. + # types: "INTEGER", "TIMESTAMP", "STRING" + schema_fields: + - name: "date" + type: "TIMESTAMP" + mode: "NULLABLE" + - name: "number_of_strikes" + type: "INTEGER" + mode: "NULLABLE" + - name: "center_point_geom" + type: "GEOGRAPHY" + description: "Center point of 0.10-degree tiles (roughly 1.1km) that aggregate strikes within the given tile." + mode: "NULLABLE" + + graph_paths: + - transform_csv >> load_to_bq diff --git a/datasets/noaa/noaa_variables.json b/datasets/noaa/noaa_variables.json new file mode 100644 index 000000000..78ba25f50 --- /dev/null +++ b/datasets/noaa/noaa_variables.json @@ -0,0 +1,14 @@ +{ + "shared": { + "composer_bucket": "us-central1-pipelines-dev-fc245d58-bucket", + "airflow_data_folder": "/home/airflow/gcs/data", + "airflow_home": "/home/airflow/gcs" + }, + "noaa": { + "destination_bucket": "public-datasets-dev-noaa-project", + "container_registry": { + "run_csv_transform_kub_lightning_strikes_by_year": "gcr.io/bigquery-public-data-dev/noaa__run_csv_transform_kub_lightning_strikes_by_year:latest", + "run_csv_transform_kub_gsod_stations": "gcr.io/bigquery-public-data-dev/noaa__run_csv_transform_kub_gsod_stations:latest" + } + } +}