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