Repository: airflow-plugins/Example-Airflow-DAGs
Branch: master
Commit: 3cf6b9bb59aa
Files: 25
Total size: 93.3 KB
Directory structure:
gitextract_p8z34sgi/
├── .gitignore
├── LICENSE
├── README.md
├── _config.yml
├── etl/
│ ├── facebook_ads_to_redshift.py
│ ├── github_to_redshift.py
│ ├── google_analytics_to_redshift.py
│ ├── hubspot_to_redshift.py
│ ├── imap_to_redshift.py
│ ├── marketo_to_redshift.py
│ ├── mongo_to_redshift/
│ │ ├── collections/
│ │ │ ├── __init__.py
│ │ │ ├── _collection_processing.py
│ │ │ └── example_mongo_collection.json
│ │ └── mongo_to_redshift.py
│ ├── salesforce_to_redshift.py
│ └── sftp_to_mongo.py
├── poc/
│ ├── dbt_example.py
│ ├── dummy_sensor_example.py
│ ├── dynamic_dag_example.py
│ ├── imap_example.py
│ ├── mailgun_validation_example.py
│ ├── selenium_example.py
│ └── singer_example.py
└── system/
├── dynamic_connection_creation.py
└── rate_limit_reset.py
================================================
FILE CONTENTS
================================================
================================================
FILE: .gitignore
================================================
.DS_Store
================================================
FILE: LICENSE
================================================
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
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.
================================================
FILE: README.md
================================================
# Example DAGs
This repository contains example DAGs that can be used "out-of-the-box" using
operators found in the Airflow Plugins organization. These DAGs have a range
of use cases and vary from moving data (see [ETL](https://github.com/airflow-plugins/example_dags/tree/master/etl))
to background system automation that can give your Airflow "super-powers".
## Getting Started
The example DAGs found here can be split into three main categories:
### ETL
These DAGs focus on pulling data from various systems and putting them into
Amazon Redshift, with S3 as a staging store. These represent the simplest
implementation of an "ETL" workflow and can either be used "out-of-the-box"
or extended to add additional custom logic.
### PoC (Proof of Concept)
These DAGs demonstrate simple implementations of custom operators and Airflow
setups. They are typically not "copy-and-paste" DAGs but rather walk through
how something would work.
### System
These DAGs are used on the system administration level and can be thought of
as "meta-DAGs" that maintain various states and configurations within Airflow
itself. In some cases, these DAGs are used in concert with other custom
operators, such as the `rate_limit_reset` DAG.
## Contributions
Contributions of your own DAGs are very welcome. Please see some of the example
DAGs for a sense of general formatting guidelines.
## License
Apache 2.0
================================================
FILE: _config.yml
================================================
theme: jekyll-theme-cayman
================================================
FILE: etl/facebook_ads_to_redshift.py
================================================
"""
Facebook Ads to Redshift
This file contains one ongoing daily DAG.
This DAG makes use of two custom operators:
- FacebookAdsInsightsToS3Operator
https://github.com/airflow-plugins/facebook_ads_plugin/blob/master/operators/facebook_ads_to_s3_operator.py#L10
- S3ToRedshiftOperator
https://github.com/airflow-plugins/redshift_plugin/blob/master/operators/s3_to_redshift_operator.py#L13
This DAG creates four breakdown reports:
- age_gender
- device_platform
- region_country
- no_breakdown
The standard fields included in each report are as follows:
- account_id
- ad_id
- adset_id
- ad_name
- adset_name
- campaign_id
- date_start
- date_stop
- campaign_name
- clicks
- cpc
- cpm
- cpp
- ctr
- impressions
- objective
- reach
- social_clicks
- social_impressions
- social_spend
- spend
- total_unique_actions
In addition these standard fields, custom fields can also be specified.
"""
from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators import FacebookAdsInsightsToS3Operator, S3ToRedshiftOperator
time_string = '{{ ts_nodash }}'
FACEBOOK_CONN_ID = ''
ACCOUNT_ID = ''
S3_BUCKET = ''
S3_CONN_ID = ''
REDSHIFT_CONN_ID = ''
REDSHIFT_SCHEMA = ''
default_args = {
'start_date': datetime(2016, 1, 1, 0, 0),
'email': [],
'email_on_failure': True,
'email_on_retry': False,
'depends_on_past': True,
'retries': 5,
'retry_delay': timedelta(minutes=5)
}
dag = DAG('facebook_ads_to_redshift',
schedule_interval='@daily',
default_args=default_args,
catchup=True)
COPY_PARAMS = ["COMPUPDATE OFF",
"STATUPDATE OFF",
"JSON 'auto'",
"TIMEFORMAT 'auto'"
"TRUNCATECOLUMNS",
"region as 'us-east-1'"]
execution_date = '{{ execution_date }}'
next_execution_date = '{{ next_execution_date }}'
breakdowns = [
{
'name': 'age_gender',
'fields': [
{'name': 'age', 'type': 'varchar(64)'},
{'name': 'gender', 'type': 'varchar(64)'}
]
},
{
'name': 'device_platform',
'fields': [
{'name': 'device_platform', 'type': 'varchar(64)'}
]
},
{
'name': 'region_country',
'fields': [
{'name': 'region', 'type': 'varchar(128)'},
{'name': 'country', 'type': 'varchar(128)'}
]
},
{
'name': 'no_breakdown',
'fields': []
}
]
fields = [
{'name': 'account_id', 'type': 'varchar(64)'},
{'name': 'ad_id', 'type': 'varchar(64)'},
{'name': 'adset_id', 'type': 'varchar(64)'},
{'name': 'campaign_id', 'type': 'varchar(64)'},
{'name': 'date_start', 'type': 'date'},
{'name': 'date_stop', 'type': 'date'},
{'name': 'ad_name', 'type': 'varchar(255)'},
{'name': 'adset_name', 'type': 'varchar(255)'},
{'name': 'campaign_name', 'type': 'varchar(255)'},
{'name': 'clicks', 'type': 'int(11)'},
{'name': 'cpc', 'type': 'decimal(20,6)'},
{'name': 'cpm', 'type': 'decimal(20,6)'},
{'name': 'cpp', 'type': 'decimal(20,6)'},
{'name': 'ctr', 'type': 'decimal(20,6)'},
{'name': 'impressions', 'type': 'int(11)'},
{'name': 'objective', 'type': 'varchar(255)'},
{'name': 'reach', 'type': 'int(11)'},
{'name': 'social_clicks', 'type': 'int(11)'},
{'name': 'social_impressions', 'type': 'int(11)'},
{'name': 'social_spend', 'type': 'decimal(20,6)'},
{'name': 'spend', 'type': 'decimal(20,6)'},
{'name': 'total_unique_actions', 'type': 'int(11)'}
]
field_names = [field['name'] for field in fields]
# Add any custom fields after building insight api field_names
fields.extend([{'name': 'example', 'type': 'text'}])
start = DummyOperator(
task_id='start',
dag=dag
)
for breakdown in breakdowns:
breakdown_fields = [field['name'] for field in breakdown['fields']]
S3_KEY = 'facebook_insights/{}_{}'.format(breakdown['name'], time_string)
facebook_ads = FacebookAdsInsightsToS3Operator(
task_id='facebook_ads_{}_to_s3'.format(breakdown['name']),
facebook_conn_id=FACEBOOK_CONN_ID,
s3_conn_id=S3_CONN_ID,
s3_bucket=S3_BUCKET,
s3_key=S3_KEY,
account_ids=ACCOUNT_ID,
insight_fields=field_names,
breakdowns=breakdown_fields,
since=execution_date,
until=next_execution_date,
time_increment=1,
level='ad',
limit=200,
dag=dag
)
# Append breakdown fields (primary keys) after
# primary keys which are in every workflow
output_table_fields = list(fields)
output_table_fields = output_table_fields[:4] + breakdown['fields'] + output_table_fields[4:]
primary_key = ['ad_id',
'adset_id',
'campaign_id',
'account_id',
'date_start']
primary_key.extend(breakdown_fields)
s3_to_redshift = S3ToRedshiftOperator(
task_id='s3_{}_to_redshift'.format(breakdown['name']),
s3_conn_id=S3_CONN_ID,
s3_bucket=S3_BUCKET,
s3_key=S3_KEY,
redshift_conn_id=REDSHIFT_CONN_ID,
redshift_schema=REDSHIFT_SCHEMA,
copy_params=COPY_PARAMS,
table=breakdown['name'],
origin_schema=output_table_fields,
schema_location='local',
primary_key=primary_key,
load_type='upsert',
dag=dag
)
start >> facebook_ads >> s3_to_redshift
================================================
FILE: etl/github_to_redshift.py
================================================
"""
Github to Redshift
This file contains one ongoing hourly DAG.
This DAG makes use of two custom operators:
- GithubToS3Operator
https://github.com/airflow-plugins/github_plugin/blob/master/operators/github_to_s3_operator.py#L9
- S3ToRedshiftOperator
https://github.com/airflow-plugins/redshift_plugin/blob/master/operators/s3_to_redshift_operator.py#L13
This DAG accesses the following objects:
- commits
- issue_comments
- issues
- repositories
- members
- pull_requests
"""
from datetime import datetime
from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators import GithubToS3Operator, S3ToRedshiftOperator
S3_CONN_ID = ''
S3_BUCKET = ''
REDSHIFT_CONN_ID = ''
REDSHIFT_SCHEMA = ''
ORIGIN_SCHEMA = ''
SCHEMA_LOCATION = ''
LOAD_TYPE = ''
# For each org being accessed, add additional objects
# with 'name' and 'github_conn_id' to this list.
orgs = [{'name': '',
'github_conn_id': ''}]
default_args = {'owner': 'airflow',
'start_date': datetime(2018, 2, 13),
'email': [''],
'email_on_failure': True,
'email_on_retry': False
}
dag = DAG('github_to_redshift',
default_args=default_args,
schedule_interval='@hourly',
catchup=False
)
endpoints = [{"name": "commits",
"payload": {},
"load_type": "rebuild"},
{"name": "issue_comments",
"payload": {"state": "all"},
"load_type": "rebuild"},
{"name": "issues",
"payload": {"state": "all"},
"load_type": "rebuild"},
{"name": "repositories",
"payload": {},
"load_type": "rebuild"},
{"name": "members",
"payload": {},
"load_type": "rebuild"},
{"name": "pull_requests",
"payload": {"state": "all"},
"load_type": "rebuild"}]
COPY_PARAMS = ["COMPUPDATE OFF",
"STATUPDATE OFF",
"JSON 'auto'",
"TIMEFORMAT 'auto'",
"TRUNCATECOLUMNS",
"region as 'us-east-1'"]
with dag:
kick_off_dag = DummyOperator(task_id='kick_off_dag')
for endpoint in endpoints:
for org in orgs:
S3_KEY = 'github/{0}/{1}.json'.format(org['name'], endpoint['name'])
TI_PREFIX = 'github_{0}_from_{1}'.format(endpoint['name'], org['name'])
GITHUB_TASK_ID = '{0}_to_s3'.format(TI_PREFIX)
REDSHIFT_TASK_ID = '{0}_to_redshift'.format(TI_PREFIX)
github = GithubToS3Operator(task_id=GITHUB_TASK_ID,
github_conn_id=org['github_conn_id'],
github_org=org['name'],
github_repo='all',
github_object=endpoint['name'],
payload=endpoint['payload'],
s3_conn_id=S3_CONN_ID,
s3_bucket=S3_BUCKET,
s3_key=S3_KEY)
redshift = S3ToRedshiftOperator(task_id=REDSHIFT_TASK_ID,
s3_conn_id=S3_CONN_ID,
s3_bucket=S3_BUCKET,
s3_key=S3_KEY,
origin_schema=ORIGIN_SCHEMA,
SCHEMA_LOCATION=SCHEMA_LOCATION,
load_type=LOAD_TYPE,
copy_params=COPY_PARAMS,
redshift_schema=REDSHIFT_SCHEMA,
table='{0}_{1}'.format(org['name'],
endpoint['name']),
redshift_conn_id=REDSHIFT_CONN_ID,
primary_key='id')
kick_off_dag >> github >> redshift
================================================
FILE: etl/google_analytics_to_redshift.py
================================================
"""
Google Analytics to Redshift
This file contains one ongoing hourly DAG.
This DAG makes use of two custom operators:
- GoogleAnalyticsToS3Operator
https://github.com/airflow-plugins/google_analytics_plugin/blob/master/operators/google_analytics_reporting_to_s3_operator.py#L11
- S3ToRedshiftOperator
https://github.com/airflow-plugins/redshift_plugin/blob/master/operators/s3_to_redshift_operator.py#L13
This DAG generates a report using v4 of the Google Analytics Core Reporting
API. The dimensions and metrics are as follows. Note that while these can be
modified, a maximum of 10 metrics and 7 dimensions can be requested at once.
METRICS
- pageView
- bounces
- users
- newUsers
- goal1starts
- goal1completions
DIMENSIONS
- dateHourMinute
- keyword
- referralPath
- campaign
- sourceMedium
Not all metrics and dimensions are compatible with each other. When forming
the request, please refer to the official Google Analytics API Reference docs:
https://developers.google.com/analytics/devguides/reporting/core/dimsmets
"""
from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
from GoogleAnalyticsPlugin.schemas.google_analytics_schemas import google_analytics_reporting_schema
from airflow.operators import (GoogleAnalyticsReportingToS3Operator,
S3ToRedshiftOperator)
S3_CONN_ID = ''
S3_BUCKET = ''
GOOGLE_ANALYTICS_CONN_ID = ''
REDSHIFT_CONN_ID = ''
REDSHIFT_SCHEMA = ''
# Google Analytics has a "lookback window" that defaults to 30 days.
# During this period, metrics are in flux as users return to the property
# and complete various actions and conversion goals.
# https://support.google.com/analytics/answer/1665189?hl=en
# The period set as the LOOKBACK_WINDOW will be dropped and replaced during
# each run of this workflow.
LOOKBACK_WINDOW = 30
# NOTE: While GA supports relative input dates, it is not advisable to use
# these in case older workflows need to be re-run.
# https://developers.google.com/analytics/devguides/reporting/core/v4/basics
SINCE = "{{{{ macros.ds_add(ds, -{0}) }}}}".format(str(LOOKBACK_WINDOW))
UNTIL = "{{ ds }}"
view_ids = []
# https://developers.google.com/analytics/devguides/reporting/core/v3/reference#sampling
SAMPLING_LEVEL = None
# https://developers.google.com/analytics/devguides/reporting/core/v3/reference#includeEmptyRows
INCLUDE_EMPTY_ROWS = False
PAGE_SIZE = 1000
# NOTE: Not all metrics and dimensions are available together. It is
# advisable to test with the GA explorer before deploying.
# https://developers.google.com/analytics/devguides/reporting/core/dimsmets
METRICS = [{'expression': 'ga:pageViews'},
{'expression': 'ga:bounces'},
{'expression': 'ga:users'},
{'expression': 'ga:newUsers'},
{'expression': 'ga:goal1starts'},
{'expression': 'ga:goal1completions'}]
DIMENSIONS = [{'name': 'ga:dateHourMinute'},
{'name': 'ga:keyword'},
{'name': 'ga:referralPath'},
{'name': 'ga:campaign'},
{'name': 'ga:sourceMedium'}]
# The specified TIMEFORMAT is based on the ga:dateHourMinute dimension.
# If using ga:date or ga:dateHour, this format will need to adjust accordingly.
COPY_PARAMS = ["COMPUPDATE OFF",
"STATUPDATE OFF",
"JSON 'auto'",
"TIMEFORMAT 'YYYYMMDDHHMI'"
"TRUNCATECOLUMNS",
"region as 'us-east-1'"]
# Primary and Incremental Keys are set to same value as no other reliable
# primary_key can found. This will result in all records with matching values of
# dateHourMinute to be deleted and new records inserted for the period of time
# covered by the lookback window. Timestamps matching records greater than
# the lookback window from the current data will not be pulled again and
# therefore not replaced.
PRIMARY_KEY = 'datehourminute'
INCREMENTAL_KEY = 'datehourminute'
default_args = {'start_date': datetime(2018, 2, 22),
'retries': 2,
'retry_delay': timedelta(minutes=5),
'email': [],
'email_on_failure': True}
dag = DAG('{}_to_redshift_hourly'.format(GOOGLE_ANALYTICS_CONN_ID),
schedule_interval='@hourly',
default_args=default_args,
catchup=False)
with dag:
d = DummyOperator(task_id='kick_off_dag')
for view_id in view_ids:
S3_KEY = 'google_analytics/{0}/{1}_{2}_{3}.json'.format(REDSHIFT_SCHEMA,
GOOGLE_ANALYTICS_CONN_ID,
view_id,
"{{ ts_nodash }}")
g = GoogleAnalyticsReportingToS3Operator(task_id='get_google_analytics_data',
google_analytics_conn_id=GOOGLE_ANALYTICS_CONN_ID,
view_id=view_id,
since=SINCE,
until=UNTIL,
sampling_level=SAMPLING_LEVEL,
dimensions=DIMENSIONS,
metrics=METRICS,
page_size=PAGE_SIZE,
include_empty_rows=INCLUDE_EMPTY_ROWS,
s3_conn_id=S3_CONN_ID,
s3_bucket=S3_BUCKET,
s3_key=S3_KEY
)
redshift = S3ToRedshiftOperator(task_id='sink_to_redshift',
redshift_conn_id=REDSHIFT_CONN_ID,
redshift_schema=REDSHIFT_SCHEMA,
table='report_{}'.format(view_id),
s3_conn_id=S3_CONN_ID,
s3_bucket=S3_BUCKET,
s3_key=S3_KEY,
origin_schema=google_analytics_reporting_schema,
schema_location='local',
copy_params=COPY_PARAMS,
load_type='upsert',
primary_key=PRIMARY_KEY,
incremental_key=INCREMENTAL_KEY
)
d >> g >> redshift
================================================
FILE: etl/hubspot_to_redshift.py
================================================
"""
Hubspot to Redshift
This files contains three dags:
- A monthly backfill from Jan 1, 2010.
- A daily backfill from Jan 1, 2018.
- An ongoing hourly workflow.
Each DAG makes use of two custom operators:
- HubspotToS3Operator
https://github.com/airflow-plugins/hubspot_plugin/blob/master/operators/hubspot_to_s3_operator.py#L16
- S3ToRedshiftOperator
https://github.com/airflow-plugins/redshift_plugin/blob/master/operators/s3_to_redshift_operator.py#L13
This dag pulls the following endpoints and inserts data to the following
table/subtable based on the followings schedules:
NOTE: Only endpoints with the appropriate scope will be included in this dag.
The associated scope to the varius endpoints can be found in the "scope" field
within the endpoints array below.
The scope available to a given token can be found by passing the associated
token to: https://api.hubapi.com/oauth/v1/access-tokens/{OAUTH_TOKEN}
NOTE: The contacts table and associated subtables are built based on an
incrementing contact id that is stored as an Airflow Variable with the
naming convention "INCREMENTAL_KEY__{DAG_ID}_{TASK_ID}_vidOffset" at the end
of each run and then pulled on the next to be used as an offset. As such,
while accessing the Contacts endpoint, "max_active_runs" should be set to 1 to
avoid pulling the same incremental key offset and therefore pulling the same
data twice.
- Campaigns - Rebuild
- Companies - Rebuild
- Contacts - Append - Built based on incremental contact id
- Form Submissions - Append
- Identity Profiles - Append
- List Memberships - Append
- Merge Audits - Append
- Deals - rebuild
- Associations_AssociatedVids - Append
- Associations_AssociatedCompanyVids - Append
- Associations_AssociatedDealIds - Append
- Deal Pipelines - Rebuild
- Engagments - Rebuild
- Associations - Rebuild
- Attachments - Rebuild
- Events - Append - Built based on incremental date
- Forms - Rebuild
- Field Groups - Rebuild
- Keywords - Rebuild
- Lists - Rebuild
- Filters - Rebuild
- Owners - Rebuild
- Remote List - Rebuild
- Social - Rebuild
- Timeline - Append - Built based on incremental date
- Workflow - Rebuild
- Persona Tag Ids - Rebuild
- Contact List Ids Steps - Rebuild
"""
from datetime import datetime, timedelta
from os import path
from airflow import DAG
from airflow.hooks.http_hook import HttpHook
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators import HubspotToS3Operator, S3ToRedshiftOperator
from HubspotPlugin.schemas import hubspot_schema
S3_CONN_ID = ''
S3_BUCKET = ''
HUBSPOT_CONN_ID = ''
REDSHIFT_SCHEMA = ''
REDSHIFT_CONN_ID = ''
endpoints = [{"name": "campaigns",
"scope": "content",
"hubspot_args": {},
"load_type": "rebuild",
"primary_key": "id",
"subtables": []},
{"name": "companies",
"scope": "contacts",
"hubspot_args": {},
"load_type": "rebuild",
"primary_key": "company_id",
"subtables": []},
{"name": "contacts",
"scope": "contacts",
"hubspot_args": {},
"load_type": "append",
"primary_key": "vid",
"subtables": ["formsubmissions",
"identityprofiles",
"listmemberships",
"mergeaudits"]},
{"name": "deals",
"scope": "contacts",
"hubspot_args": {},
"load_type": "rebuild",
"primary_key": "deal_id",
"subtables": ["associations_associatedvids",
"associations_associatedcompanyvids",
"associations_associateddealids"]},
{"name": "deal_pipelines",
"scope": "contacts",
"hubspot_args": {},
"load_type": "rebuild",
"subtables": ['stages']},
{"name": "engagements",
"scope": "contacts",
"hubspot_args": {},
"load_type": "rebuild",
"subtables": ["associations",
"attachments"]},
{"name": "events",
"scope": "content",
"hubspot_args": {
"startTimestamp": "{{ execution_date }}",
"endTimestamp": "{{ next_execution_date }}"},
"load_type": "append",
"primary_key": "id",
"subtables": []},
{"name": "forms",
"scope": "forms",
"hubspot_args": {},
"load_type": "rebuild",
"subtables": ["fieldgroups"]},
{"name": "keywords",
"scope": "reports",
"hubspot_args": {},
"load_type": "rebuild",
"subtables": []},
{"name": "lists",
"scope": "contacts",
"hubspot_args": {},
"load_type": "rebuild",
"primary_key": "internal_list_id",
"subtables": ["filters"]},
{"name": "owners",
"scope": "contacts",
"hubspot_args": {},
"load_type": "rebuild",
"primary_key": "owner_id",
"subtables": ["remote_list"]},
{"name": "social",
"scope": "social",
"hubspot_args": {},
"load_type": "rebuild",
"primary_key": "channel_guid",
"subtables": []},
{"name": "timeline",
"scope": "timeline",
"hubspot_args": {
"startTimestamp": "{{ execution_date }}",
"endTimestamp": "{{ next_execution_date }}"},
"load_type": "append",
"subtables": ["changes"]},
{"name": "workflows",
"scope": "automation",
"hubspot_args": {},
"load_type": "rebuild",
"primary_key": "id",
"subtables": ["persona_tag_ids",
"contact_list_ids_steps"]}]
hourly_id = '{}_to_redshift_hourly'.format(HUBSPOT_CONN_ID)
daily_id = '{}_to_redshift_daily_backfill'.format(HUBSPOT_CONN_ID)
monthly_id = '{}_to_redshift_monthly_backfill'.format(HUBSPOT_CONN_ID)
COPY_PARAMS = ["COMPUPDATE OFF",
"STATUPDATE OFF",
"JSON 'auto'",
"TIMEFORMAT 'epochmillisecs'"
"TRUNCATECOLUMNS",
"region as 'us-east-1'"]
def create_dag(dag_id,
schedule,
hubspot_conn_id,
redshift_conn_id,
redshift_schema,
default_args,
catchup=False,
max_active_runs=3):
try:
h = HttpHook(method='GET', http_conn_id=hubspot_conn_id)
pw = h.get_connection(conn_id=hubspot_conn_id).password
response = h.run('oauth/v1/access-tokens/{0}'.format(pw))
scopes = response.json()['scopes']
dag = DAG(dag_id,
default_args=default_args,
schedule_interval=schedule,
catchup=catchup,
max_active_runs=max_active_runs
)
with dag:
kick_off_dag = DummyOperator(task_id='kick_off_dag')
kick_off_dag
tables_to_build = []
for endpoint in endpoints:
if endpoint['scope'] in scopes:
if 'backfill' in dag_id and 'startTimestamp':
if endpoint['hubspot_args'].keys():
tables_to_build.append(endpoint)
else:
tables_to_build.append(endpoint)
for table in tables_to_build:
HUBSPOT_ARGS = table.get('hubspot_args', {})
TABLE_NAME = table.get('name', '')
LOAD_TYPE = table.get('load_type', '')
PRIMARY_KEY = None
INCREMENTAL_KEY = None
if 'primary_key' in table.keys():
PRIMARY_KEY = table['primary_key']
if 'incremental_key' in table.keys():
INCREMENTAL_KEY = table['incremental_key']
S3_KEY = ('hubspot/{0}/{1}_{2}.json'.format(
redshift_schema,
TABLE_NAME,
"{{ ts_nodash }}"))
split_key = path.splitext(S3_KEY)
LOAD_KEY = '{0}_core'.format(split_key[0])
h = HubspotToS3Operator(task_id='hubspot_{0}_data_to_s3'
.format(TABLE_NAME),
hubspot_conn_id=hubspot_conn_id,
hubspot_object=TABLE_NAME,
hubspot_args=HUBSPOT_ARGS,
s3_conn_id=S3_CONN_ID,
s3_bucket=S3_BUCKET,
s3_key=S3_KEY)
kick_off_dag >> h
if table['name'] == 'timeline':
pass
else:
r = S3ToRedshiftOperator(task_id='hubspot_{0}_to_redshift'
.format(TABLE_NAME),
s3_conn_id=S3_CONN_ID,
s3_bucket=S3_BUCKET,
s3_key=LOAD_KEY,
origin_schema=getattr(hubspot_schema,
TABLE_NAME),
origin_datatype='json',
copy_params=COPY_PARAMS,
load_type=LOAD_TYPE,
primary_key=PRIMARY_KEY,
incremental_key=INCREMENTAL_KEY,
schema_location='local',
redshift_schema=redshift_schema,
table=TABLE_NAME,
redshift_conn_id=redshift_conn_id)
h >> r
if table['subtables']:
for subtable in table['subtables']:
SUBTABLE_LOAD_KEY = '{0}_{1}'.format(split_key[0],
subtable)
SUBTABLE_NAME = '{0}_{1}'.format(TABLE_NAME, subtable)
if SUBTABLE_NAME == 'timeline':
SUBTABLE_NAME = TABLE_NAME
s = S3ToRedshiftOperator(task_id='hubspot_{0}_{1}_to_redshift'
.format(TABLE_NAME,
subtable),
s3_conn_id=S3_CONN_ID,
s3_bucket=S3_BUCKET,
s3_key=SUBTABLE_LOAD_KEY,
origin_schema=getattr(hubspot_schema,
'{0}_{1}'.format(TABLE_NAME,subtable)),
origin_datatype='json',
load_type=LOAD_TYPE,
schema_location='local',
copy_params=COPY_PARAMS,
redshift_schema=redshift_schema,
table=SUBTABLE_NAME,
redshift_conn_id=REDSHIFT_CONN_ID)
h >> s
return dag
except:
pass
globals()[hourly_id] = create_dag(hourly_id,
'@hourly',
HUBSPOT_CONN_ID,
REDSHIFT_CONN_ID,
REDSHIFT_SCHEMA,
{'start_date': datetime(2018, 2, 13),
'retries': 2,
'retry_delay': timedelta(minutes=5),
'email': [],
'email_on_failure': True},
catchup=False,
max_active_runs=1)
globals()[daily_id] = create_dag(daily_id,
'@daily',
HUBSPOT_CONN_ID,
REDSHIFT_CONN_ID,
REDSHIFT_SCHEMA,
{'start_date': datetime(2018, 1, 1),
'end_date': datetime(2018, 2, 13),
'retries': 2,
'retry_delay': timedelta(minutes=5),
'email': [],
'email_on_failure': True},
catchup=True)
globals()[monthly_id] = create_dag(monthly_id,
'@monthly',
HUBSPOT_CONN_ID,
REDSHIFT_CONN_ID,
REDSHIFT_SCHEMA,
{'start_date': datetime(2010, 1, 1),
'end_date': datetime(2018, 1, 1),
'retries': 2,
'retry_delay': timedelta(minutes=5),
'email': [],
'email_on_failure': True},
catchup=True)
================================================
FILE: etl/imap_to_redshift.py
================================================
"""
An example DAG designed to:
1) Access an IMAP Server
2) Search the inbox for an email with a specific subject
3) Pull in the csv attachments of the email and store them in S3
4) Load these files into Redshift.
This files contains one dag:
- An ongoing daily workflow.
Each DAG makes use of two custom operators:
- IMAPToS3Operator
https://github.com/airflow-plugins/imap_plugin/blob/master/operators/imap_to_s3_operator.py#L13
- S3ToRedshiftOperator
https://github.com/airflow-plugins/redshift_plugin/blob/master/operators/s3_to_redshift_operator.py#L13
"""
from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators import ImapToS3Operator
from airflow.operators import S3ToRedshiftOperator
IMAP_CONN_ID = ''
IMAP_EMAIL = ''
S3_CONN_ID = ''
S3_BUCKET = ''
REDSHIFT_SCHEMA = ''
REDSHIFT_CONN_ID = ''
TIME = '{{ ts_nodash }}'
email_workflows = [
{
'id': 'transaction',
'name': 'Transaction',
'fields': [
{'name': "event_code", 'type': "varchar(256)"},
{'name': "customer_id", 'type': "varchar(256)"},
{'name': "date", 'type': "timestamp"},
{'name': "code", 'type': "varchar(256)"},
{'name': "name", 'type': "varchar(256)"},
{'name': "class_code", 'type': "varchar(256)"},
{'name': "price", 'type': "varchar(256)"},
{'name': "order_qty", 'type': "varchar(256)"},
]
},
{
'id': 'customer',
'name': 'Customers',
'fields': [
{'name': "customer_id", 'type': "varchar(256)"},
{'name': "full_name", 'type': "varchar(256)"},
{'name': "mail_addr1", 'type': "varchar(256)"},
{'name': "mail_addr2", 'type': "varchar(256)"},
{'name': "mail_city", 'type': "varchar(256)"},
{'name': "mail_state", 'type': "varchar(256)"},
{'name': "mail_zip", 'type': "varchar(256)"},
{'name': "mail_country", 'type': "varchar(256)"},
{'name': "bill_addr1", 'type': "varchar(256)"},
{'name': "bill_addr2", 'type': "varchar(256)"},
{'name': "bill_state", 'type': "varchar(256)"},
{'name': "bill_city", 'type': "varchar(256)"},
{'name': "bill_zip", 'type': "varchar(256)"},
{'name': "bill_country", 'type': "varchar(256)"},
{'name': "bill_name", 'type': "varchar(256)"},
{'name': "phone", 'type': "varchar(256)"},
{'name': "email", 'type': "varchar(256)"}
]
},
{
'id': 'event',
'name': 'Events',
'fields': [
{'name': "code", 'type': "varchar(256)"},
{'name': "name", 'type': "varchar(256)"},
{'name': "facility_code", 'type': "varchar(256)"},
{'name': "facility_name", 'type': "varchar(256)"},
{'name': "group_code", 'type': "varchar(256)"},
{'name': "group_name", 'type': "varchar(256)"},
{'name': "type_code", 'type': "varchar(256)"},
{'name': "type", 'type': "varchar(256)"},
{'name': "date", 'type': "timestamp"},
{'name': "keywords", 'type': "varchar"},
{'name': "tags", 'type': "varchar"}
]
}
]
default_args = {
'start_date': datetime(2017, 2, 14, 0, 0),
'email': [],
'email_on_failure': True,
'email_on_retry': False,
'retries': 2,
'retry_delay': timedelta(minutes=5)
}
dag = DAG(
'caa_imap_to_redshift',
schedule_interval='@daily',
default_args=default_args,
catchup=False
)
with dag:
kick_off_dag = DummyOperator(task_id='kick_off_dag')
for workflow in email_workflows:
type = workflow.get('id', None)
name = workflow.get('name', None)
fields = workflow.get('fields', None)
S3_KEY = '{type}_{time}.csv'.format(type=workflow['id'],
time=TIME)
imap_to_s3 = ImapToS3Operator(
task_id='{}_to_s3'.format(type),
imap_conn_id=IMAP_CONN_ID,
imap_email=IMAP_EMAIL,
imap_subject=name,
s3_conn_id=S3_CONN_ID,
s3_bucket=S3_BUCKET,
s3_key=S3_KEY,
)
s3_to_redshift = S3ToRedshiftOperator(
task_id='{}_to_redshift'.format(type),
s3_conn_id=S3_CONN_ID,
s3_bucket=S3_BUCKET,
s3_key=S3_KEY,
redshift_conn_id=REDSHIFT_CONN_ID,
redshift_schema=REDSHIFT_SCHEMA,
table=type,
origin_schema=fields,
schema_location='local',
)
kick_off_dag >> imap_to_s3 >> s3_to_redshift
================================================
FILE: etl/marketo_to_redshift.py
================================================
"""
Marketo to Redshift
This files contains three dags:
- A monthly backfill from Jan 1, 2013.
- A daily backfill from Jan 1, 2018.
- An ongoing hourly workflow.
Each DAG makes use of three custom operators:
- RateLimitOperator
https://github.com/airflow-plugins/rate_limit_plugin/blob/master/operators/rate_limit_operator.py
- MarketoToS3Operator
https://github.com/airflow-plugins/marketo_plugin/blob/master/operators/marketo_to_s3_operator.py#L19
- S3ToRedshiftOperator
https://github.com/airflow-plugins/redshift_plugin/blob/master/operators/s3_to_redshift_operator.py#L13
This ongoing DAG pulls the following Marketo objects:
- Activities
- Campaigns
- Leads
- Lead Lists
- Programs
When backfilling, only the leads object is pulled. By default, it begins
pulling since Jan 1, 2013.
"""
from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators import (MarketoToS3Operator,
S3ToRedshiftOperator,
RateLimitOperator)
from MarketoPlugin.schemas._schema import schema
MARKETO_CONN_ID = ''
MARKETO_SCHEMA = ''
REDSHIFT_SCHEMA = ''
REDSHIFT_CONN_ID = ''
S3_CONN_ID = ''
S3_BUCKET = ''
RATE_LIMIT_THRESHOLD = 0.8
RATE_LIMIT_THRESHOLD_TYPE = 'percentage'
hourly_id = '{}_to_redshift_hourly'.format(MARKETO_CONN_ID)
daily_id = '{}_to_redshift_daily_backfill'.format(MARKETO_CONN_ID)
monthly_id = '{}_to_redshift_monthly_backfill'.format(MARKETO_CONN_ID)
def create_dag(dag_id,
schedule,
marketo_conn_id,
redshift_conn_id,
redshift_schema,
s3_conn_id,
s3_bucket,
default_args,
catchup=False):
dag = DAG(dag_id,
schedule_interval=schedule,
default_args=default_args,
catchup=catchup)
if 'backfill' in dag_id:
endpoints = ['leads']
else:
endpoints = ['activities',
'campaigns',
'leads',
'programs',
'lead_lists']
COPY_PARAMS = ["COMPUPDATE OFF",
"STATUPDATE OFF",
"JSON 'auto'",
"TIMEFORMAT 'auto'"
"TRUNCATECOLUMNS",
"region as 'us-east-1'"]
with dag:
d = DummyOperator(task_id='kick_off_dag')
l = RateLimitOperator(task_id='check_rate_limit',
service='marketo',
service_conn_id=marketo_conn_id,
threshold=RATE_LIMIT_THRESHOLD,
threshold_type=RATE_LIMIT_THRESHOLD_TYPE)
d >> l
for endpoint in endpoints:
MARKETO_SCHEMA = schema[endpoint]
TABLE_NAME = 'mkto_{0}'.format(endpoint)
S3_KEY = 'marketo/{0}/{1}_{2}.json'.format(redshift_schema,
endpoint,
"{{ ts_nodash }}")
MARKETO_TASK_ID = 'get_{0}_marketo_data'.format(endpoint)
REDSHIFT_TASK_ID = 'marketo_{0}_to_redshift'.format(endpoint)
START_AT = "{{ execution_date.isoformat() }}"
END_AT = "{{ next_execution_date.isoformat() }}"
m = MarketoToS3Operator(task_id=MARKETO_TASK_ID,
marketo_conn_id=marketo_conn_id,
endpoint=endpoint,
s3_conn_id=s3_conn_id,
s3_bucket=s3_bucket,
s3_key=S3_KEY,
output_format='json',
start_at=START_AT,
end_at=END_AT)
l >> m
if endpoint != 'leads':
r = S3ToRedshiftOperator(task_id=REDSHIFT_TASK_ID,
s3_conn_id=s3_conn_id,
s3_bucket=s3_bucket,
s3_key=S3_KEY,
load_type='rebuild',
load_format='JSON',
schema_location='local',
origin_schema=MARKETO_SCHEMA,
redshift_schema=redshift_schema,
table=TABLE_NAME,
copy_params=COPY_PARAMS,
redshift_conn_id=redshift_conn_id)
m >> r
else:
rl = S3ToRedshiftOperator(task_id=REDSHIFT_TASK_ID,
s3_conn_id=s3_conn_id,
s3_bucket=s3_bucket,
s3_key=S3_KEY,
load_type='upsert',
load_format='JSON',
schema_location='local',
origin_schema=MARKETO_SCHEMA,
redshift_schema=redshift_schema,
table=TABLE_NAME,
primary_key='id',
copy_params=COPY_PARAMS,
incremental_key='updated_at',
redshift_conn_id=redshift_conn_id)
m >> rl
return dag
globals()[hourly_id] = create_dag(hourly_id,
'@hourly',
MARKETO_CONN_ID,
REDSHIFT_CONN_ID,
REDSHIFT_SCHEMA,
S3_CONN_ID,
S3_BUCKET,
{'start_date': datetime(2018, 2, 13),
'retries': 2,
'retry_delay': timedelta(minutes=5),
'email': [],
'email_on_failure': True},
catchup=True)
globals()[daily_id] = create_dag(daily_id,
'@daily',
MARKETO_CONN_ID,
REDSHIFT_CONN_ID,
REDSHIFT_SCHEMA,
S3_CONN_ID,
S3_BUCKET,
{'start_date': datetime(2018, 1, 1),
'end_date': datetime(2018, 2, 13),
'retries': 2,
'retry_delay': timedelta(minutes=5),
'email': [],
'email_on_failure': True},
catchup=True)
globals()[monthly_id] = create_dag(monthly_id,
'@monthly',
MARKETO_CONN_ID,
REDSHIFT_CONN_ID,
REDSHIFT_SCHEMA,
S3_CONN_ID,
S3_BUCKET,
{'start_date': datetime(2013, 1, 1),
'end_date': datetime(2018, 1, 1),
'retries': 2,
'retry_delay': timedelta(minutes=5),
'email': [],
'email_on_failure': True},
catchup=True)
================================================
FILE: etl/mongo_to_redshift/collections/__init__.py
================================================
================================================
FILE: etl/mongo_to_redshift/collections/_collection_processing.py
================================================
"""
This file contains a single method that accepts a mongo formatted schema
(see "example_monog_collection.json") and outputs a mongo field projection
and Redshift formatted schema mapping.
This method will recursively crawl through the inputted json file, flattening
out nested dictionaries and ignoring arrays. To flatten arrays, it is
recommended that that gets broken out as a separate table.
"""
def _prepareData(data, subtable=''):
schemaMapper = [{"mongo": "string",
"redshift": "varchar(512)"},
{"mongo": "text",
"redshift": "varchar(6000)"},
{"mongo": "integer",
"redshift": "integer"},
{"mongo": "bigint",
"redshift": "bigint"},
{"mongo": "boolean",
"redshift": "boolean"},
{"mongo": "datetime",
"redshift": "datetime"},
{"mongo": "float",
"redshift": "float"},
{"mongo": "double",
"redshift": "float(53)"}]
def projection(d, parent_key='', sep='_', subtable=''):
projection_items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
alt_key = parent_key + '.' + k if parent_key else k
if isinstance(v, dict):
projection_items.extend(projection(v, new_key.replace(sep, '.'), sep=sep).items())
elif isinstance(v, str):
projection_items.append((new_key.replace('.', '_'), '${}'.format(alt_key)))
return dict(projection_items)
def schema(d, parent_key='', sep='_'):
schema_items = []
for k, v in d.items():
new_key = parent_key + sep + k if parent_key else k
if isinstance(v, dict):
schema_items.extend(schema(v, new_key, sep=sep).items())
elif isinstance(v, str):
schema_items.append((new_key, v))
return dict(schema_items)
def _convertSchema(schema):
output_array = []
for k, v in schema.items():
base_dict = dict()
base_dict['name'] = k
base_dict['type'] = v
for mapping in schemaMapper:
if mapping['mongo'] == v.lower():
base_dict['type'] = mapping['redshift']
output_array.append(base_dict)
return output_array
return projection(data, subtable), _convertSchema(schema(data))
================================================
FILE: etl/mongo_to_redshift/collections/example_mongo_collection.json
================================================
"""
Example MongoDB Collection Schema
Below is an example schema mapping for a mongo collection.
Available datatypes include:
- string
- text
- integer
- bigint
- boolean
- datetime
- float
- double
The Redshift mappings these translate to can be found in the
'_collection_processing' file.
"""
{
"_id": "String",
"title": "String",
"archived": "Boolean",
"description": "String",
"dateLastActivity": "DateTime",
"companyId": "String",
"userId": "String",
"createdAt": "DateTime",
"relatedUsers": [
"String"
],
"address": {
"ID": "Integer",
"Address1": "String",
"Address2": "String",
"City": "String",
"State": "String",
"ZipCode": "String",
"PrimaryPhone": "String",
"SecondaryPhone": "String",
"Fax": "String"
}
}
================================================
FILE: etl/mongo_to_redshift/mongo_to_redshift.py
================================================
"""
MongoDB to Redshift
This file contains one ongoing daily DAG.
This DAG makes use of two custom operators:
- MongoToS3Operator
https://github.com/airflow-plugins/mongo_plugin/blob/master/operators/mongo_to_s3_operator.py#L9
- S3ToRedshiftOperator
https://github.com/airflow-plugins/redshift_plugin/blob/master/operators/s3_to_redshift_operator.py#L13
This DAG also uses a Mongo collection processing script that accepts a
json formatted Mongo schema mapping and outputs both a Mongo query projection
and a compatible Redshift schema mapping. This script can be found in
"etl/mongo_to_redshift/collections/_collection_processing.py".
This DAG also contains a flattening script that removes invalid characters
from the Mongo keys as well as scrubbing out the "_$date" suffix that
PyMongo appends to datetime fields.
"""
from datetime import datetime, timedelta
import json
import re
import os
from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.hooks import S3Hook
from airflow.operators import (MongoToS3Operator,
S3ToRedshiftOperator,
PythonOperator)
from mongo_to_redshift.collections._collection_processing import _prepareData
S3_CONN = ''
S3_BUCKET = ''
REDSHIFT_SCHEMA = ''
REDSHIFT_CONN_ID = ''
MONGO_CONN_ID = ''
MONGO_DATABASE = ''
default_args = {'start_date': datetime(2018, 2, 22),
'retries': 2,
'retry_delay': timedelta(minutes=5),
'email': [],
'email_on_failure': True,
'email_on_retry': False}
dag = DAG('mongo_to_redshift_daily',
default_args=default_args,
schedule_interval='@daily',
catchup=True)
cwd = os.getcwd()
def process_collection(collection):
file_path = 'dags/etl/mongo_to_redshift/collections/{0}.json'.format(collection)
new_path = os.path.join(cwd, file_path)
order = json.load(open(new_path))
projection, schema = _prepareData(order)
collections = [{'name': 'example_mongo_collection',
'collection': 'example_mongo_collection',
'mongo_query': [{"$match": {"dateLastActivity": {
"$lt": '{{ next_execution_date }}',
"$gte": '{{ execution_date }}'
}}},
{"$project": process_collection('example_mongo_collection')[0]}],
'schema': process_collection('example_mongo_collection')[1],
'primary_key': ["id"],
'incremental_key': 'dateLastActivity',
'load_type': 'upsert'}]
def flatten_py(**kwargs):
s3_key = kwargs['templates_dict']['s3_key']
flattened_key = kwargs['templates_dict']['flattened_key']
s3_conn = kwargs['templates_dict']['s3_conn']
s3_bucket = kwargs['templates_dict']['s3_bucket']
s3 = S3Hook(s3_conn)
output = (s3.get_key(s3_key,
bucket_name=s3_bucket)
.get_contents_as_string(encoding='utf-8'))
output = output.split('\n')
output = '\n'.join([json.dumps({re.sub(r'[?|$|.|!]', r'', k.lower().replace('_$date', '')): v for k, v in i.items()}) for i in output])
s3.load_string(output,
flattened_key,
bucket_name=s3_bucket,
replace=True)
with dag:
kick_off_dag = DummyOperator(task_id='kick_off_dag')
for collection in collections:
if 'collection' in collection.keys():
collection_name = collection['collection']
else:
collection_name = collection['name']
S3_KEY = 'mongo/raw/{0}_{1}.json'.format(collection['name'], '{{ ts_nodash}}')
FLATTENED_KEY = 'mongo/flattened/{0}_{1}_flattened.json'.format(collection['name'], '{{ ts_nodash}}')
mongo = MongoToS3Operator(task_id='{0}_to_s3'.format(collection['name']),
mongo_conn_id=MONGO_CONN_ID,
mongo_collection=collection_name,
mongo_database=MONGO_DATABASE,
mongo_query=collection['mongo_query'],
s3_conn_id=S3_CONN,
s3_bucket=S3_BUCKET,
s3_key=S3_KEY,
replace=True
)
flatten_object = PythonOperator(task_id='flatten_{0}'.format(collection['name']),
python_callable=flatten_py,
templates_dict={'s3_key': S3_KEY,
's3_conn': S3_CONN,
's3_bucket': S3_BUCKET,
'collection_name': collection['name'],
'flattened_key': FLATTENED_KEY,
'origin_schema': collection['schema']},
provide_context=True)
redshift = S3ToRedshiftOperator(task_id='{0}_to_redshift'.format(collection['name']),
s3_conn_id=S3_CONN,
s3_bucket=S3_BUCKET,
s3_key=FLATTENED_KEY,
redshift_conn_id=REDSHIFT_CONN_ID,
redshift_schema=REDSHIFT_SCHEMA,
origin_schema=collection['schema'],
redshift_table=collection['name'],
primary_key=collection.get('primary_key', None),
incremental_key=collection.get('incremental_key', None),
load_type=collection['load_type'])
kick_off_dag >> mongo >> flatten_object >> redshift
================================================
FILE: etl/salesforce_to_redshift.py
================================================
"""
Salesforce to Redshift
This files contains an ongoing hourly workflow.
Each DAG makes use of three custom operators:
- SalesforceToS3Operator
https://github.com/airflow-plugins/salesforce_plugin/blob/master/operators/salesforce_to_s3_operator.py#L60
- S3ToRedshiftOperator
https://github.com/airflow-plugins/redshift_plugin/blob/master/operators/s3_to_redshift_operator.py#L13
This ongoing DAG pulls the following Salesforce objects:
- Account
- Campaign
- CampaignMember
- Contact
- Lead
- Opportunity
- OpportunityContactRole
- OpportunityHistory
- Task
- User
The output from Salesforce will be formatted as newline delimited JSON (ndjson)
and will include """
from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.salesforce_plugin import SalesforceToS3Operator
from airflow.operators import S3ToRedshiftOperator
SF_CONN_ID = ''
S3_CONN_ID = ''
S3_BUCKET = ''
REDSHIFT_CONN_ID = ''
REDSHIFT_SCHEMA_NAME = ''
ORIGIN_SCHEMA = ''
SCHEMA_LOCATION = ''
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2017, 8, 29),
'email': [],
'email_on_failure': False,
'email_on_retry': False,
'retries': 1,
'retry_delay': timedelta(minutes=5)
}
dag = DAG('salesforce_to_redshift',
default_args=default_args,
schedule_interval='@hourly',
catchup=False)
tables = [{'name': 'Account',
'load_type': 'Upsert'},
{'name': 'Campaign',
'load_type': 'Upsert'},
{'name': 'CampaignMember',
'load_type': 'Upsert'},
{'name': 'Contact',
'load_type': 'Upsert'},
{'name': 'Lead',
'load_type': 'Upsert'},
{'name': 'Opportunity',
'load_type': 'Upsert'},
{'name': 'OpportunityContactRole',
'load_type': 'Upsert'},
{'name': 'OpportunityHistory',
'load_type': 'Upsert'},
{'name': 'Task',
'load_type': 'Upsert'},
{'name': 'User',
'load_type': 'Upsert'}]
COPY_PARAMS = ["JSON 'auto'",
"TRUNCATECOLUMNS",
"region as 'us-east-1'"]
kick_off_dag = DummyOperator(task_id='kick_off_dag', dag=dag)
for table in tables:
S3_KEY = 'salesforce/{}/{}.json'.format('{{ execution_date }}',
table['name'].lower())
salesforce_to_s3 = SalesforceToS3Operator(task_id='{0}_to_S3'.format(table['name']),
sf_conn_id=SF_CONN_ID,
sf_obj=table,
fmt='ndjson',
s3_conn_id=S3_CONN_ID,
s3_bucket=S3_BUCKET,
record_time_added=True,
coerce_to_timestamp=True,
dag=dag)
s3_to_redshift = S3ToRedshiftOperator(task_id='{0}_to_Redshift'.format(table['name']),
redshift_conn_id=REDSHIFT_CONN_ID,
redshift_schema=REDSHIFT_SCHEMA_NAME,
table=table,
s3_conn_id=S3_CONN_ID,
s3_bucket=S3_BUCKET,
s3_key=S3_KEY,
origin_schema=ORIGIN_SCHEMA,
copy_params=COPY_PARAMS,
schema_location=SCHEMA_LOCATION,
load_type=table['load_type'],
dag=dag)
kick_off_dag >> salesforce_to_s3 >> s3_to_redshift
================================================
FILE: etl/sftp_to_mongo.py
================================================
"""
SFTP to Mongo
This files contains an ongoing daily workflow that:
1) Looks for a csv in SFTP
2) If that file exists, retrieves it.
3) Converts that csv to json.
4) Inserts these records into Mongo.
Throughout this process, S3 is used as a intermediary storage layer.
This DAG makes use of two custom operators:
- S3ToMongoOperator
https://github.com/airflow-plugins/mongo_plugin/blob/master/operators/s3_to_mongo_operator.py#L11
- SFTPToS3Operator
https://github.com/airflow-plugins/sftp_plugin/blob/master/operators.py/sftp_to_s3_operator.py#L7
"""
from datetime import datetime, timedelta
from flatten_json import unflatten_list
import pandas as pd
import logging
import json
from airflow import DAG
from airflow.hooks import S3Hook, SSHHook
from airflow.operators.python_operator import ShortCircuitOperator, PythonOperator
from mongo_plugin.operators.s3_to_mongo_operator import S3ToMongoOperator
from sftp_plugin.operators.sftp_to_s3_operator import SFTPToS3Operator
SSH_CONN_ID = ''
MONGO_CONN_ID = ''
MONGO_DB = ''
MONGO_COLLECTION = ''
FILENAME = ''
FILEPATH = ''
SFTP_PATH = '/{0}/{1}'.format(FILEPATH, FILENAME)
S3_CONN_ID = ''
S3_BUCKET = ''
S3_KEY = ''
today = "{{ ds }}"
S3_KEY_TRANSFORMED = '{0}_{1}.json'.format(S3_KEY, today)
default_args = {
'start_date': datetime(2018, 4, 12, 0, 0, 0),
'email': [],
'email_on_failure': True,
'email_on_retry': False,
'retries': 5,
'retry_delay': timedelta(minutes=5)
}
dag = DAG(
'sftp_to_mongo',
schedule_interval='@daily',
default_args=default_args,
catchup=True
)
def check_for_file_py(**kwargs):
path = kwargs.get('path', None)
sftp_conn_id = kwargs.get('sftp_conn_id', None)
filename = kwargs.get('templates_dict').get('filename', None)
ssh_hook = SSHHook(ssh_conn_id=sftp_conn_id)
sftp_client = ssh_hook.get_conn().open_sftp()
ftp_files = sftp_client.listdir(path)
logging.info('Filename: ' + str(filename))
if filename in ftp_files:
return True
else:
return False
def transform_py(**kwargs):
s3 = kwargs.get('s3_conn_id', None)
s3_key = kwargs.get('templates_dict').get('s3_key', None)
transformed_key = kwargs.get('templates_dict').get('transformed_key', None)
s3_bucket = kwargs.get('s3_bucket', None)
hook = S3Hook(s3)
(hook.get_key(s3_key,
bucket_name=s3_bucket)
.get_contents_to_filename('temp.csv'))
df = pd.read_csv('temp.csv')
records = json.loads(df.to_json(orient='records'))
del df
records = [unflatten_list(record) for record in records]
records = '\n'.join([json.dumps(record) for record in records])
hook.load_string(string_data=records,
key=transformed_key,
bucket_name=s3_bucket,
replace=True)
with dag:
files = ShortCircuitOperator(task_id='check_for_file',
python_callable=check_for_file_py,
templates_dict={'filename': FILENAME},
op_kwargs={"path": FILEPATH,
"sftp_conn_id": SSH_CONN_ID},
provide_context=True)
sftp = SFTPToS3Operator(
task_id='retrieve_file',
sftp_conn_id=SSH_CONN_ID,
sftp_path=SFTP_PATH,
s3_conn_id=S3_CONN_ID,
s3_bucket=S3_BUCKET,
s3_key=S3_KEY
)
transform = PythonOperator(task_id='transform_to_json',
python_callable=transform_py,
templates_dict={'s3_key': S3_KEY,
'transformed_key': S3_KEY_TRANSFORMED},
op_kwargs={"s3_conn_id": S3_CONN_ID,
"s3_bucket": S3_BUCKET},
provide_context=True)
mongo = S3ToMongoOperator(
task_id='sink_to_mongo',
s3_conn_id=S3_CONN_ID,
s3_bucket=S3_BUCKET,
s3_key=S3_KEY_TRANSFORMED,
mongo_conn_id=MONGO_CONN_ID,
mongo_collection=MONGO_COLLECTION,
mongo_db=MONGO_COLLECTION,
mongo_method='replace',
mongo_replacement_filter='',
upsert=True
)
files >> sftp >> transform, mongo
================================================
FILE: poc/dbt_example.py
================================================
# Originally from @adamhaney -- https://gist.github.com/adamhaney/916a21b0adcabef4038c38e3ac96a36f
from datetime import datetime, timedelta
import networkx as nx
from airflow import DAG
from airflow.operators import BashOperator, SubDagOperator
start_date = datetime(year=2017, month=6, day=13, hour=19, minute=0)
schedule_interval = '0 * * * 1-5'
default_args = {
'owner': 'The Owner',
'email': ['theoperator@email.com'],
'retry_interval': timedelta(minutes=15),
'sla': timedelta(minutes=60),
'depends_on_downstream': True,
'email_on_failure': True,
'email_on_retry': True,
'provide_context': True,
}
dag = DAG('dbt', start_date=start_date, schedule_interval=schedule_interval, default_args=default_args, max_active_runs=1)
dbt_clone = BashOperator(
task_id='dbt_clone',
bash_command='cd ~/project && git fetch --all && git reset --hard origin/master',
dag=dag
)
dbt_deps = BashOperator(
task_id='dbt_deps',
bash_command='cd ~/project && dbt deps --profile=warehouse --target=prod',
dag=dag
)
dbt_deps.set_upstream(dbt_clone)
dbt_clean = BashOperator(
task_id='dbt_clean',
bash_command='cd ~/project && dbt clean --profile=warehouse --target=prod',
dag=dag
)
dbt_clean.set_upstream(dbt_deps)
dbt_archive = BashOperator(
task_id='dbt_archive',
bash_command='cd ~/project && dbt archive --profile=warehouse --target=prod',
dag=dag
)
dbt_archive.set_upstream(dbt_clean)
dbt_seed = BashOperator(
task_id='dbt_seed',
bash_command='cd ~/gospel && dbt seed --profile=warehouse --target=prod',
dag=dag
)
dbt_seed.set_upstream(dbt_archive)
dbt_compile = BashOperator(
task_id='dbt_compile',
bash_command='''cd ~/project && dbt compile --profile=warehouse --target=prod && find target/build | xargs -I {} bash -c "echo '-------------------- '{}' --------------------' && cat {} || exit 0"''',
dag=dag
)
dbt_compile.set_upstream(dbt_seed)
copy_gpickle_file = BashOperator(
task_id='copy_gpickle_file',
bash_command='''cp ~/project/target/graph.gpickle ~/project/graph.gpickle''',
dag=dag
)
copy_gpickle_file.set_upstream(dbt_compile)
def dbt_dag(start_date, schedule_interval, default_args):
temp_dag = DAG('gospel_.dbt_sub_dag', start_date=start_date, schedule_interval=schedule_interval, default_args=default_args)
G = nx.read_gpickle('/home/airflowuser/project/graph.gpickle')
def make_dbt_task(model_name):
simple_model_name = model_name.split('.')[-1]
dbt_task = BashOperator(
task_id=model_name,
bash_command='cd ~/gospel && dbt run --profile=warehouse --target=prod --non-destructive --models {simple_model_name}'.format(simple_model_name=simple_model_name),
dag=temp_dag
)
return dbt_task
dbt_tasks = {}
for node_name in set(G.nodes()):
dbt_task = make_dbt_task(node_name)
dbt_tasks[node_name] = dbt_task
for edge in G.edges():
dbt_tasks[edge[0]].set_downstream(dbt_tasks[edge[1]])
return temp_dag
dbt_sub_dag = SubDagOperator(
subdag=dbt_dag(dag.start_date, dag.schedule_interval, default_args=default_args),
task_id='dbt_sub_dag',
dag=dag,
trigger_rule='all_done'
)
dbt_sub_dag.set_upstream(copy_gpickle_file)
dbt_test = BashOperator(
task_id='dbt_test',
bash_command='cd ~/project && dbt test --profile=warehouse --target=prod',
dag=dag
)
dbt_test.set_upstream(dbt_sub_dag)
================================================
FILE: poc/dummy_sensor_example.py
================================================
"""
This example dag uses the custom "DummySensorOperator" found here:
https://github.com/airflow-plugins/dummy_sensor_plugin/blob/master/operators/dummy_sensor_operator.py
"""
from datetime import datetime
from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
# Custom Plugin
from airflow.operators import DummySensorOperator
args = {
'owner': 'airflow',
'start_date': datetime(2017, 4, 20, 0, 0),
'provide_context': True
}
dag = DAG(
'replicate_skipped_bug',
schedule_interval="@once",
default_args=args
)
start = DummyOperator(
task_id='start_pipeline',
dag=dag
)
with dag:
for i in range(0, 75):
d_sensor = DummySensorOperator(
task_id='dummy_sensor_{}'.format(i),
timeout=1,
poke_interval=2,
flag=False,
soft_fail=True,
dag=dag
)
d_operator = DummyOperator(task_id='dummy_operator_{}'.format(i))
start >> d_sensor >> d_operator
================================================
FILE: poc/dynamic_dag_example.py
================================================
"""
This example uses the existing Dummy Operator and Variable model to
demonstrate dynamic creation of DAGs based on a Variable setting. As
shown below, a list of customer objects is retrieved and used to create
unique dags based on the imput.
"""
from datetime import datetime, timedelta
from airflow.models import DAG
from airflow.models import Variable
from airflow.operators.dummy_operator import DummyOperator
# Create JSON Variable if it doesn't exist
CUSTOMERS = [
{
'customer_name': 'Faux Customer',
'customer_id': 'faux_customer',
'email': ['admin@fauxcustomer.com', 'admin@astronomer.io'],
'schedule_interval': None,
'enabled': True
},
{
'customer_name': 'Bogus Customer',
'customer_id': 'bogus_customer',
'email': ['admin@boguscustomer.com', 'admin@astronomer.io'],
'schedule_interval': '@once',
'enabled': True
}
]
# Get JSON Variable
CUSTOMERS = Variable.get("customer_list",
default_var=CUSTOMERS,
deserialize_json=True)
def create_dag(customer):
"""
Accepts a customer parameters dict and
overrides default args to create a DAG object
Returns: DAG() Object
"""
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'email': 'xyz@xyz.com',
'retries': 1,
'retry_delay': timedelta(minutes=5),
'start_date': datetime(2017, 1, 1, 0, 0),
'end_date': None
}
"""
This allows DAG parameters to be passed in from the Variable if
a customer needs something specific overridden in their DAG.
Consider how email being passed in from the customer object
overrides email in the resulting replaced_args object.
"""
replaced_args = {k: default_args[k] if customer.get(
k, None) is None else customer[k] for k in default_args}
dag_id = '{base_name}_{id}'.format(
base_name='load_clickstream_data', id=customer['customer_id'])
return DAG(dag_id=dag_id,
default_args=replaced_args,
schedule_interval=customer['schedule_interval'])
# Loop customers array of containing customer objects
for cust in CUSTOMERS:
if cust['enabled']:
dag = create_dag(cust)
globals()[dag.dag_id] = dag
extract = DummyOperator(
task_id='extract_data',
dag=dag
)
transform = DummyOperator(
task_id='transform_data',
dag=dag
)
load = DummyOperator(
task_id='load_data',
dag=dag
)
extract >> transform >> load
else:
# TODO Create but programmatically pause
pass
================================================
FILE: poc/imap_example.py
================================================
"""
An example DAG using the IMAP plugin to:
1) Access an IMAP Server.
2) Search the inbox for an email with a specific subject
3) Extract the body of the specified email
4) Parse the body according to a Regular Expression
5) Return the parsed result as an XCOM
This files contains one dag:
- An ongoing daily workflow.
Each DAG makes use of one custom hook:
- ImapHook
https://github.com/airflow-plugins/imap_plugin/blob/master/hooks/imap_hook.py#L9
"""
from datetime import datetime, timedelta
import re
import logging
from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.python_operator import PythonOperator
from imap_plugin.hooks.imap_hook import ImapHook
IMAP_CONN_ID = ''
SUBJECT = ''
SEARCH_STRING = r''
default_args = {
'start_date': datetime(2018, 2, 10, 0, 0),
'email': [],
'email_on_failure': True,
'email_on_retry': False,
'retries': 2,
'retry_delay': timedelta(minutes=5),
'catchup': False
}
dag = DAG(
'imap_inbox_search',
schedule_interval='@daily',
default_args=default_args,
catchup=False
)
def imap_py(**kwargs):
imap_conn_id = kwargs.get('templates_dict', None).get('imap_conn_id', None)
imap_subject = kwargs.get('templates_dict', None).get('imap_subject', None)
reg_ex = kwargs.get('templates_dict', None).get('reg_ex', None)
search_criteria = '(HEADER Subject "{}")'.format(imap_subject)
logging.info('Retrieving emails...')
message = ImapHook(imap_conn_id=imap_conn_id).read_body(search_criteria)
logging.info('Successfully retrieved email...')
logging.info('Parsing Email...')
result = re.search(reg_ex, message).group(0)
logging.info('Result: {}'.format(result))
return result
with dag:
kick_off_dag = DummyOperator(task_id='kick_off_dag')
imap = PythonOperator(
task_id='imap_search',
python_callable=imap_py,
templates_dict={"imap_conn_id": IMAP_CONN_ID,
"imap_subject": SUBJECT,
"reg_ex": SEARCH_STRING
},
provide_context=True
)
kick_off_dag >> imap
================================================
FILE: poc/mailgun_validation_example.py
================================================
"""
An example DAG using the Mailgun plugin to validate an existing list of emails.
This files contains one dag:
- An ongoing daily workflow.
Each DAG makes use of two custom operators:
- EmailListChangedSensor
https://github.com/airflow-plugins/mailgun_plugin/blob/master/operators/sensor.py#L4
- EmailValidationOperator
https://github.com/airflow-plugins/mailgun_plugin/blob/master/operators/validate.py#L14
"""
from datetime import datetime, timedelta
from airflow import DAG
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators import EmailListChangedSensor
from airflow.operators import EmailValidationOperator
default_args = {
'owner': 'airflow',
'depends_on_past': False,
'start_date': datetime(2018, 4, 6),
'email': 'taylor@astronomer.io',
'email_on_failure': False,
'email_on_retry': False,
'retries': 0,
'retry_delay': timedelta(minutes=0),
}
dag = DAG(
'mailgun_dag',
default_args=default_args,
schedule_interval='@daily',
)
start = DummyOperator(
task_id='start',
dag=dag,
)
emails_changed = EmailListChangedSensor(
task_id='email_list_delta_sensor',
poke_interval=0,
timeout=0,
soft_fail=True,
dag=dag,
)
emails_changed.set_upstream(start)
email_validation_operator = EmailValidationOperator(
task_id='validate_emails',
mailgun_conn_id='mailgun_api',
aws_conn_id='aws_s3',
s3_bucket_name='my_bucket',
s3_key_source='my_contacts_list.json',
dag=dag,
)
email_validation_operator.set_upstream(emails_changed)
================================================
FILE: poc/selenium_example.py
================================================
"""
Headless Site Navigation and File Download (Using Selenium) to S3
This example demonstrates using Selenium (via Firefox/GeckoDriver) to:
1) Log into a website w/ credentials stored in connection labeled 'selenium_conn_id'
2) Download a file (initiated on login)
3) Transform the CSV into JSON formatting
4) Append the current data to each record
5) Load the corresponding file into S3
To use this DAG, you will need to have the following installed:
[XVFB](https://www.x.org/archive/X11R7.6/doc/man/man1/Xvfb.1.xhtml)
[GeckoDriver](https://github.com/mozilla/geckodriver/releases/download)
selenium==3.11.0
xvfbwrapper==0.2.9
"""
from datetime import datetime, timedelta
import os
import boa
import csv
import json
import time
import logging
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.firefox.options import Options
from xvfbwrapper import Xvfb
from airflow import DAG
from airflow.models import Connection
from airflow.utils.db import provide_session
from airflow.operators.dummy_operator import DummyOperator
from airflow.operators.python_operator import PythonOperator
from airflow.hooks import S3Hook
S3_CONN_ID = ''
S3_BUCKET = ''
S3_KEY = ''
date = '{{ ds }}'
default_args = {
'start_date': datetime(2018, 2, 10, 0, 0),
'email': [],
'email_on_failure': True,
'email_on_retry': False,
'retries': 2,
'retry_delay': timedelta(minutes=5),
'catchup': False
}
dag = DAG(
'selenium_extraction_to_s3',
schedule_interval='@daily',
default_args=default_args,
catchup=False
)
def imap_py(**kwargs):
selenium_conn_id = kwargs.get('templates_dict', None).get('selenium_conn_id', None)
filename = kwargs.get('templates_dict', None).get('filename', None)
s3_conn_id = kwargs.get('templates_dict', None).get('s3_conn_id', None)
s3_bucket = kwargs.get('templates_dict', None).get('s3_bucket', None)
s3_key = kwargs.get('templates_dict', None).get('s3_key', None)
date = kwargs.get('templates_dict', None).get('date', None)
@provide_session
def get_conn(conn_id, session=None):
conn = (
session.query(Connection)
.filter(Connection.conn_id == conn_id)
.first()
)
return conn
url = get_conn(selenium_conn_id).host
email = get_conn(selenium_conn_id).user
pwd = get_conn(selenium_conn_id).password
vdisplay = Xvfb()
vdisplay.start()
caps = webdriver.DesiredCapabilities.FIREFOX
caps["marionette"] = True
profile = webdriver.FirefoxProfile()
profile.set_preference("browser.download.manager.showWhenStarting", False)
profile.set_preference('browser.helperApps.neverAsk.saveToDisk', "text/csv")
logging.info('Profile set...')
options = Options()
options.set_headless(headless=True)
logging.info('Options set...')
logging.info('Initializing Driver...')
driver = webdriver.Firefox(firefox_profile=profile,
firefox_options=options,
capabilities=caps)
logging.info('Driver Intialized...')
driver.get(url)
logging.info('Authenticating...')
elem = driver.find_element_by_id("email")
elem.send_keys(email)
elem = driver.find_element_by_id("password")
elem.send_keys(pwd)
elem.send_keys(Keys.RETURN)
logging.info('Successfully authenticated.')
sleep_time = 15
logging.info('Downloading File....Sleeping for {} Seconds.'.format(str(sleep_time)))
time.sleep(sleep_time)
driver.close()
vdisplay.stop()
dest_s3 = S3Hook(s3_conn_id=s3_conn_id)
os.chdir('/root/Downloads')
csvfile = open(filename, 'r')
output_json = 'file.json'
with open(output_json, 'w') as jsonfile:
reader = csv.DictReader(csvfile)
for row in reader:
row = dict((boa.constrict(k), v) for k, v in row.items())
row['run_date'] = date
json.dump(row, jsonfile)
jsonfile.write('\n')
dest_s3.load_file(
filename=output_json,
key=s3_key,
bucket_name=s3_bucket,
replace=True
)
dest_s3.connection.close()
with dag:
kick_off_dag = DummyOperator(task_id='kick_off_dag')
selenium = PythonOperator(
task_id='selenium_retrieval_to_s3',
python_callable=imap_py,
templates_dict={"s3_conn_id": S3_CONN_ID,
"s3_bucket": S3_BUCKET,
"s3_key": S3_KEY,
"date": date},
provide_context=True
)
kick_off_dag >> selenium
================================================
FILE: poc/singer_example.py
================================================
"""
Singer
This example shows how to use Singer within Airflow using a custom operator:
- SingerOperator
https://github.com/airflow-plugins/singer_plugin/blob/master/operators/singer_operator.py#L5
A complete list of Taps and Targets can be found in the Singer.io Github org:
https://github.com/singer-io
"""
from datetime import datetime
from airflow import DAG
from airflow.operators import SingerOperator
default_args = {'start_date': datetime(2018, 2, 22),
'retries': 0,
'email': [],
'email_on_failure': True,
'email_on_retry': False}
dag = DAG('__singer__fixerio_to_csv',
schedule_interval='@hourly',
default_args=default_args)
with dag:
singer = SingerOperator(task_id='singer',
tap='fixerio',
target='csv')
singer
================================================
FILE: system/dynamic_connection_creation.py
================================================
"""
Dynamic Connection Creation from a Variable
This file contains one ongoing DAG that executes every 15 minutes.
This DAG makes use of one custom operator:
- CreateConnectionsFromVariable
https://github.com/airflow-plugins/variable_connection_plugin/blob/master/operator/variable_connection_operator.py#L36
If using encrypted tokens in the Variable (recommended), it is necessary
to create a separate "Fernet Key Connection" with the relevant Fernet Key
kept in the password field. This Conn ID can then be specified in the
operator below.
"""
from datetime import datetime
from airflow import DAG
from airflow.operators import CreateConnectionsFromVariable
FERNET_KEY_CONN_ID = None
CONFIG_VARIABLE_KEY = ''
args = {
'owner': 'airflow',
'start_date': datetime(2018, 2, 22, 0, 0),
'provide_context': True,
'email': [],
'email_on_failure': True
}
dag = DAG(
'__VARIABLE_CONNECTION_CREATION__',
schedule_interval="*/15 * * * *",
default_args=args,
catchup=False
)
create_airflow_connections = CreateConnectionsFromVariable(
task_id='create_airflow_connections',
fernet_key_conn_id=FERNET_KEY_CONN_ID,
config_variable_key=CONFIG_VARIABLE_KEY,
dag=dag)
create_airflow_connections
================================================
FILE: system/rate_limit_reset.py
================================================
"""
Rate Limit Reset
This files contains one dag that executes every 12 hours by default.
This DAG should be used in tandem with the RateLimitOperator:
https://github.com/airflow-plugins/rate_limit_plugin/blob/master/operators/rate_limit_operator.py
Every run, this DAG will look for variables with the specified key as it's name.
By default, this key is set to '__SYSTEM__RATE_LIMIT_EXCEEDED__'.
Once found, this DAG will clear the task that caused the variable to be set
(see above Operator) as well as downstream tasks. It will then set the relevant
DAG to "running" and clear the variable.
"""
from datetime import datetime, timedelta
from sqlalchemy import and_
import json
from airflow import DAG
from airflow.models import Variable, TaskInstance, DagRun
from airflow.utils.db import provide_session
from airflow.operators.python_operator import PythonOperator
default_args = {'start_date': datetime(2018, 2, 9),
'retries': 2,
'retry_delay': timedelta(minutes=2),
'email': [],
'email_on_failure': True}
dag = DAG('__CHECK_FOR_RATE_LIMIT_VARIABLES',
default_args=default_args,
schedule_interval='30 */12 * * *',
catchup=False
)
@provide_session
def check_py(session=None, **kwargs):
key = '__SYSTEM__RATE_LIMIT_EXCEEDED__'
obj = (session
.query(Variable)
.filter(Variable.key.ilike('{}%'.format(key)))
.all())
if obj is None:
raise KeyError('Variable {} does not exist'.format(key))
else:
for _ in obj:
_ = json.loads(_.val)
# Clear the rate limit operator task in the specified Dag Run.
(session
.query(TaskInstance)
.filter(and_(TaskInstance.task_id == _['task_id'],
TaskInstance.dag_id == _['dag_id'],
TaskInstance.execution_date == datetime.strptime(_['ts'],
"%Y-%m-%dT%H:%M:%S")))
.delete())
# Clear downstream tasks in the specified Dag Run.
for task in _['downstream_tasks']:
(session
.query(TaskInstance)
.filter(and_(TaskInstance.task_id == task,
TaskInstance.dag_id == _['dag_id'],
TaskInstance.execution_date == datetime.strptime(_['ts'],
"%Y-%m-%dT%H:%M:%S")))
.delete())
# Set the Dag Run state to "running"
dag_run = (session
.query(DagRun)
.filter(and_(DagRun.dag_id == _['dag_id'],
DagRun.execution_date == datetime.strptime(_['ts'],
"%Y-%m-%dT%H:%M:%S")))
.first())
dag_run.set_state('running')
# Clear the rate limit exceeded variable.
variable_identifier = '_'.join([_['dag_id'],
_['task_id'],
_['ts']])
variable_name = ''.join([key, variable_identifier])
(session
.query(Variable)
.filter(Variable.key == variable_name)
.delete())
with dag:
run_check = PythonOperator(task_id='run_check',
python_callable=check_py,
provide_context=True)
run_check
gitextract_p8z34sgi/
├── .gitignore
├── LICENSE
├── README.md
├── _config.yml
├── etl/
│ ├── facebook_ads_to_redshift.py
│ ├── github_to_redshift.py
│ ├── google_analytics_to_redshift.py
│ ├── hubspot_to_redshift.py
│ ├── imap_to_redshift.py
│ ├── marketo_to_redshift.py
│ ├── mongo_to_redshift/
│ │ ├── collections/
│ │ │ ├── __init__.py
│ │ │ ├── _collection_processing.py
│ │ │ └── example_mongo_collection.json
│ │ └── mongo_to_redshift.py
│ ├── salesforce_to_redshift.py
│ └── sftp_to_mongo.py
├── poc/
│ ├── dbt_example.py
│ ├── dummy_sensor_example.py
│ ├── dynamic_dag_example.py
│ ├── imap_example.py
│ ├── mailgun_validation_example.py
│ ├── selenium_example.py
│ └── singer_example.py
└── system/
├── dynamic_connection_creation.py
└── rate_limit_reset.py
SYMBOL INDEX (12 symbols across 10 files) FILE: etl/hubspot_to_redshift.py function create_dag (line 184) | def create_dag(dag_id, FILE: etl/marketo_to_redshift.py function create_dag (line 53) | def create_dag(dag_id, FILE: etl/mongo_to_redshift/collections/_collection_processing.py function _prepareData (line 12) | def _prepareData(data, subtable=''): FILE: etl/mongo_to_redshift/mongo_to_redshift.py function process_collection (line 57) | def process_collection(collection): function flatten_py (line 77) | def flatten_py(**kwargs): FILE: etl/sftp_to_mongo.py function check_for_file_py (line 68) | def check_for_file_py(**kwargs): function transform_py (line 83) | def transform_py(**kwargs): FILE: poc/dbt_example.py function dbt_dag (line 79) | def dbt_dag(start_date, schedule_interval, default_args): FILE: poc/dynamic_dag_example.py function create_dag (line 38) | def create_dag(customer): FILE: poc/imap_example.py function imap_py (line 50) | def imap_py(**kwargs): FILE: poc/selenium_example.py function imap_py (line 64) | def imap_py(**kwargs): FILE: system/rate_limit_reset.py function check_py (line 43) | def check_py(session=None, **kwargs):
Condensed preview — 25 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (101K chars).
[
{
"path": ".gitignore",
"chars": 10,
"preview": ".DS_Store\n"
},
{
"path": "LICENSE",
"chars": 11357,
"preview": " Apache License\n Version 2.0, January 2004\n "
},
{
"path": "README.md",
"chars": 1397,
"preview": "# Example DAGs\n\nThis repository contains example DAGs that can be used \"out-of-the-box\" using\noperators found in the Air"
},
{
"path": "_config.yml",
"chars": 26,
"preview": "theme: jekyll-theme-cayman"
},
{
"path": "etl/facebook_ads_to_redshift.py",
"chars": 5605,
"preview": "\"\"\"\nFacebook Ads to Redshift\n\nThis file contains one ongoing daily DAG.\n\nThis DAG makes use of two custom operators:\n "
},
{
"path": "etl/github_to_redshift.py",
"chars": 4219,
"preview": "\"\"\"\nGithub to Redshift\n\nThis file contains one ongoing hourly DAG.\n\nThis DAG makes use of two custom operators:\n - Gi"
},
{
"path": "etl/google_analytics_to_redshift.py",
"chars": 6780,
"preview": "\"\"\"\nGoogle Analytics to Redshift\n\nThis file contains one ongoing hourly DAG.\n\nThis DAG makes use of two custom operators"
},
{
"path": "etl/hubspot_to_redshift.py",
"chars": 14142,
"preview": "\"\"\"\nHubspot to Redshift\n\nThis files contains three dags:\n - A monthly backfill from Jan 1, 2010.\n - A daily backfi"
},
{
"path": "etl/imap_to_redshift.py",
"chars": 4757,
"preview": "\"\"\"\nAn example DAG designed to:\n1) Access an IMAP Server\n2) Search the inbox for an email with a specific subject\n3) Pul"
},
{
"path": "etl/marketo_to_redshift.py",
"chars": 7996,
"preview": "\"\"\"\nMarketo to Redshift\n\nThis files contains three dags:\n - A monthly backfill from Jan 1, 2013.\n - A daily backfi"
},
{
"path": "etl/mongo_to_redshift/collections/__init__.py",
"chars": 0,
"preview": ""
},
{
"path": "etl/mongo_to_redshift/collections/_collection_processing.py",
"chars": 2568,
"preview": "\"\"\"\nThis file contains a single method that accepts a mongo formatted schema\n(see \"example_monog_collection.json\") and o"
},
{
"path": "etl/mongo_to_redshift/collections/example_mongo_collection.json",
"chars": 769,
"preview": "\"\"\"\nExample MongoDB Collection Schema\n\nBelow is an example schema mapping for a mongo collection.\n\nAvailable datatypes i"
},
{
"path": "etl/mongo_to_redshift/mongo_to_redshift.py",
"chars": 6093,
"preview": "\"\"\"\nMongoDB to Redshift\n\nThis file contains one ongoing daily DAG.\n\nThis DAG makes use of two custom operators:\n - Mo"
},
{
"path": "etl/salesforce_to_redshift.py",
"chars": 3998,
"preview": "\"\"\"\nSalesforce to Redshift\n\nThis files contains an ongoing hourly workflow.\n\nEach DAG makes use of three custom operator"
},
{
"path": "etl/sftp_to_mongo.py",
"chars": 4373,
"preview": "\"\"\"\nSFTP to Mongo\n\nThis files contains an ongoing daily workflow that:\n 1) Looks for a csv in SFTP\n 2) If that fil"
},
{
"path": "poc/dbt_example.py",
"chars": 3507,
"preview": "# Originally from @adamhaney -- https://gist.github.com/adamhaney/916a21b0adcabef4038c38e3ac96a36f\n\nfrom datetime import"
},
{
"path": "poc/dummy_sensor_example.py",
"chars": 1010,
"preview": "\"\"\"\nThis example dag uses the custom \"DummySensorOperator\" found here:\nhttps://github.com/airflow-plugins/dummy_sensor_p"
},
{
"path": "poc/dynamic_dag_example.py",
"chars": 2819,
"preview": "\"\"\"\nThis example uses the existing Dummy Operator and Variable model to\ndemonstrate dynamic creation of DAGs based on a "
},
{
"path": "poc/imap_example.py",
"chars": 2176,
"preview": "\"\"\"\nAn example DAG using the IMAP plugin to:\n1) Access an IMAP Server.\n2) Search the inbox for an email with a specific "
},
{
"path": "poc/mailgun_validation_example.py",
"chars": 1574,
"preview": "\"\"\"\nAn example DAG using the Mailgun plugin to validate an existing list of emails.\n\nThis files contains one dag:\n - "
},
{
"path": "poc/selenium_example.py",
"chars": 4598,
"preview": "\"\"\"\nHeadless Site Navigation and File Download (Using Selenium) to S3\n\nThis example demonstrates using Selenium (via Fir"
},
{
"path": "poc/singer_example.py",
"chars": 880,
"preview": "\"\"\"\nSinger\n\nThis example shows how to use Singer within Airflow using a custom operator:\n- SingerOperator\nhttps://github"
},
{
"path": "system/dynamic_connection_creation.py",
"chars": 1248,
"preview": "\"\"\"\nDynamic Connection Creation from a Variable\n\nThis file contains one ongoing DAG that executes every 15 minutes.\n\nThi"
},
{
"path": "system/rate_limit_reset.py",
"chars": 3665,
"preview": "\"\"\"\nRate Limit Reset\n\nThis files contains one dag that executes every 12 hours by default.\n\nThis DAG should be used in t"
}
]
About this extraction
This page contains the full source code of the airflow-plugins/Example-Airflow-DAGs GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 25 files (93.3 KB), approximately 21.3k tokens, and a symbol index with 12 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.