├── .github └── CODEOWNERS ├── Jenkinsfile ├── LICENSE ├── README.md ├── example_dags ├── livy_spark_operator_python_example.py ├── livy_spark_operator_r_example.py ├── livy_spark_operator_scala_example.py ├── spark_submit_operator_python_example.py ├── spark_submit_operator_r_example.py └── spark_submit_operator_scala_example.py ├── example_spark_jobs ├── python │ └── spark_test.py ├── r │ └── spark_test.R └── scala │ ├── pom.xml │ └── src │ └── main │ └── scala │ └── com │ └── softwaresanders │ └── spark │ └── spark_test │ └── Main.scala └── spark_operator_plugin.py /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @orsher @amirbilu 2 | -------------------------------------------------------------------------------- /Jenkinsfile: -------------------------------------------------------------------------------- 1 | pipeline { 2 | agent any 3 | stages{ 4 | stage('build'){ 5 | steps { 6 | echo "Hello world!" 7 | } 8 | } 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # airflow-spark-operator-plugin 2 | 3 | [![build passing](https://jenkins-public.personali.io/badge-icon?organization=personali&branch=master&project=airflow-spark-operator-plugin)](http://172.34.1.161:8080/view/Organization/job/personali/job/airflow-spark-operator-plugin/job/master/) 4 | 5 | ## Description 6 | 7 | A plugin to Apache Airflow (Documentation: https://pythonhosted.org/airflow/, Source Code: https://github.com/apache/incubator-airflow) to allow you to run Apache Spark Commands as an Operator from Workflows 8 | 9 | 10 | ## TODO List 11 | 12 | * Test extensively 13 | 14 | ## How do Deploy 15 | 16 | 1. Copy the spark_operator_plugin.py file into the Airflow Plugins directory 17 | 18 | * The Airflow Plugins Directory is defined in the airflow.cfg file as the variable "plugins_folder" 19 | 20 | * The Airflow Plugins Directory is, by default, ${AIRFLOW_HOME}/plugins 21 | 22 | * You may have to create the Airflow Plugins Directory folder as it is not created by default 23 | 24 | * quick way of doing this: 25 | 26 | $ cd {AIRFLOW_PLUGINS_FOLDER} 27 | $ wget https://raw.githubusercontent.com/rssanders3/airflow-zip-operator-plugin/master/zip_operator_plugin.py 28 | 29 | 2. Restart the Airflow Services 30 | 31 | 3. Create or Deploy DAGs which utilize the Operator 32 | 33 | 4. Your done! 34 | 35 | 36 | ## Spark Submit Operator 37 | 38 | ### Operator Definition 39 | 40 | class **airflow.operators.SparkSubmitOperator**(application_file, main_class=None, master=None, conf=None, deploy_mode=None, other_spark_options=None, application_args=None, xcom_push=False, env=None, output_encoding='utf-8', *args, **kwargs) 41 | 42 | Bases: **airflow.operators.BashOperator** 43 | 44 | An operator which executes the spark-submit command through Airflow. This operator accepts all the desired arguments and assembles the spark-submit command which is then executed by the BashOperator. 45 | 46 | Parameters: 47 | 48 | * **main_class** (string) - The entry point for your application (e.g. org.apache.spark.examples.SparkPi) 49 | * **master** (string) - The master value for the cluster. (e.g. spark://23.195.26.187:7077 or yarn-client) 50 | * **conf** (string) - Arbitrary Spark configuration property in key=value format. For values that contain spaces wrap “key=value” in quotes. (templated) 51 | * **deploy_mode** (string) - Whether to deploy your driver on the worker nodes (cluster) or locally as an external client (default: client) 52 | * **other_spark_options** (string) - Other options you would like to pass to the spark submit command that isn't covered by the current options. (e.g. --files /path/to/file.xml) (templated) 53 | * **application_file** (string) - Path to a bundled jar including your application and all dependencies. The URL must be globally visible inside of your cluster, for instance, an hdfs:// path or a file:// path that is present on all nodes. 54 | * **application_args** (string) - Arguments passed to the main method of your main class, if any. (templated) 55 | * **xcom_push** (bool) – If xcom_push is True, the last line written to stdout will also be pushed to an XCom when the bash command completes. 56 | * **env** (dict) – If env is not None, it must be a mapping that defines the environment variables for the new process; these are used instead of inheriting the current process environment, which is the default behavior. (templated) 57 | 58 | 59 | ### Prerequisites 60 | 61 | The executors need to have access to the spark-submit command on the local commandline shell. Spark libraries will need to be installed. 62 | 63 | 64 | ## Steps done by the Operator 65 | 66 | 1. Accept all the required input 67 | 2. Assemble the spark-submit command 68 | 3. Execute the spark-submit command on the executor node 69 | 70 | 71 | ### How to use the Operator 72 | 73 | There are some examples on how to use the operator under example_dags. 74 | 75 | Import the SparkSubmitOperator using the following line: 76 | 77 | ``` 78 | from airflow.operators import SparkSubmitOperator 79 | ``` 80 | 81 | 82 | ## Livy Spark Operator 83 | 84 | ### Operator Definition 85 | 86 | class **airflow.operators.LivySparkOperator**(spark_script, session_kind="spark", http_conn_id=None, poll_interval=30, *args, **kwargs) 87 | 88 | Bases: **airflow.models.BaseOperator** 89 | 90 | Operator to facilitate interacting with the Livy Server which executes Apache Spark code via a REST API. 91 | 92 | Parameters: 93 | 94 | * **spark_script** (string) - Scala, Python or R code to submit to the Livy Server (templated) 95 | * **session_kind** (string) - Type of session to setup with Livy. This will determine which type of code will be accepted. Possible values include "spark" (executes Scala code), "pyspark" (executes Python code) or "sparkr" (executes R code). 96 | * **http_conn_id** (string) - The http connection to run the operator against. 97 | * **poll_interval** (integer) - The polling interval to use when checking if the code in spark_script has finished executing. In seconds. (default: 30 seconds) 98 | 99 | 100 | ### Prerequisites 101 | 102 | 1. The Livy Server needs to be setup on the desired server. 103 | 104 | * Livy Source Code: https://github.com/cloudera/livy 105 | 106 | 2. Add an entry to the Connections list that points to the Livy Server 107 | 108 | 1. Open the Airflow WebServer 109 | 2. Navigate to Admin -> Connections 110 | 3. Create a new connection 111 | 112 | * Set the Conn Id as some unique value to identify it (example: livy_http_conn) and use this value as the http_conn_id 113 | * Set the Conn Type as "http" 114 | * Set the host 115 | * Set the port (default for livy is 8998) 116 | 117 | 118 | ## Steps done by the Operator 119 | 120 | 1. Accept all the required inputs 121 | 2. Establish an HTTP Connection with the Livy Server via the information provided in the http_conn_id 122 | 3. Create a dedicated Livy Spark Session for the execution of the Spark script provided 123 | 4. Submit the Spark script code 124 | 5. Poll to see if the Spark script has completed running 125 | 6. Print the logs and the output of the Spark script 126 | 7. Close the Livy Spark Session 127 | 128 | 129 | ### How to use the Operator 130 | 131 | There are some examples on how to use the operator under example_dags. 132 | 133 | Import the LivySparkOperator using the following line: 134 | 135 | ``` 136 | from airflow.operators import LivySparkOperator 137 | ``` 138 | -------------------------------------------------------------------------------- /example_dags/livy_spark_operator_python_example.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | from airflow.operators import LivySparkOperator 3 | from airflow.models import DAG 4 | from datetime import datetime, timedelta 5 | import os 6 | 7 | """ 8 | Pre-run Steps: 9 | 10 | 1. Open the Airflow WebServer 11 | 2. Navigate to Admin -> Connections 12 | 3. Add a new connection 13 | 1. Set the Conn Id as "livy_http_conn" 14 | 2. Set the Conn Type as "http" 15 | 3. Set the host 16 | 4. Set the port (default for livy is 8998) 17 | 5. Save 18 | """ 19 | 20 | DAG_ID = os.path.basename(__file__).replace(".pyc", "").replace(".py", "") 21 | 22 | HTTP_CONN_ID = "livy_http_conn" 23 | SESSION_TYPE = "pyspark" 24 | SPARK_SCRIPT = """ 25 | print "sc: " + str(sc) 26 | 27 | rdd = sc.parallelize([1, 2, 3, 4, 5]) 28 | rdd_filtered = rdd.filter(lambda entry: entry > 3) 29 | print(rdd_filtered.collect()) 30 | """ 31 | 32 | default_args = { 33 | 'owner': 'airflow', 34 | 'depends_on_past': False, 35 | 'retries': 0, 36 | } 37 | 38 | dag = DAG(DAG_ID, default_args=default_args, schedule_interval=None, start_date=(datetime.now() - timedelta(minutes=1))) 39 | 40 | dummy = LivySparkOperator( 41 | task_id='livy-' + SESSION_TYPE, 42 | spark_script=SPARK_SCRIPT, 43 | http_conn_id=HTTP_CONN_ID, 44 | session_kind=SESSION_TYPE, 45 | dag=dag) 46 | -------------------------------------------------------------------------------- /example_dags/livy_spark_operator_r_example.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | from airflow.operators import LivySparkOperator 3 | from airflow.models import DAG 4 | from datetime import datetime, timedelta 5 | import os 6 | 7 | """ 8 | Pre-run Steps: 9 | 10 | 1. Open the Airflow WebServer 11 | 2. Navigate to Admin -> Connections 12 | 3. Add a new connection 13 | 1. Set the Conn Id as "livy_http_conn" 14 | 2. Set the Conn Type as "http" 15 | 3. Set the host 16 | 4. Set the port (default for livy is 8998) 17 | 5. Save 18 | """ 19 | 20 | DAG_ID = os.path.basename(__file__).replace(".pyc", "").replace(".py", "") 21 | 22 | HTTP_CONN_ID = "livy_http_conn" 23 | SESSION_TYPE = "sparkr" 24 | SPARK_SCRIPT = """ 25 | print(cat("sc: ", sc)) 26 | 27 | rdd = SparkR:::parallelize(sc, 1:5, slices) 28 | print(SparkR:::collect(rdd)) 29 | """ 30 | 31 | default_args = { 32 | 'owner': 'airflow', 33 | 'depends_on_past': False, 34 | 'retries': 0, 35 | } 36 | 37 | dag = DAG(DAG_ID, default_args=default_args, schedule_interval=None, start_date=(datetime.now() - timedelta(minutes=1))) 38 | 39 | dummy = LivySparkOperator( 40 | task_id='livy-' + SESSION_TYPE, 41 | spark_script=SPARK_SCRIPT, 42 | http_conn_id=HTTP_CONN_ID, 43 | session_kind=SESSION_TYPE, 44 | dag=dag) 45 | -------------------------------------------------------------------------------- /example_dags/livy_spark_operator_scala_example.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | from airflow.operators import LivySparkOperator 3 | from airflow.models import DAG 4 | from datetime import datetime, timedelta 5 | import os 6 | 7 | """ 8 | Pre-run Steps: 9 | 10 | 1. Open the Airflow WebServer 11 | 2. Navigate to Admin -> Connections 12 | 3. Add a new connection 13 | 1. Set the Conn Id as "livy_http_conn" 14 | 2. Set the Conn Type as "http" 15 | 3. Set the host 16 | 4. Set the port (default for livy is 8998) 17 | 5. Save 18 | """ 19 | 20 | DAG_ID = os.path.basename(__file__).replace(".pyc", "").replace(".py", "") 21 | 22 | HTTP_CONN_ID = "livy_http_conn" 23 | SESSION_TYPE = "spark" 24 | SPARK_SCRIPT = """ 25 | import java.util 26 | 27 | println("sc: " + sc) 28 | 29 | val rdd = sc.parallelize(1 to 5) 30 | val rddFiltered = rdd.filter(entry => entry > 3) 31 | println(util.Arrays.toString(rddFiltered.collect())) 32 | """ 33 | 34 | default_args = { 35 | 'owner': 'airflow', 36 | 'depends_on_past': False, 37 | 'retries': 0, 38 | } 39 | 40 | dag = DAG(DAG_ID, default_args=default_args, schedule_interval=None, start_date=(datetime.now() - timedelta(minutes=1))) 41 | 42 | dummy = LivySparkOperator( 43 | task_id='livy-' + SESSION_TYPE, 44 | spark_script=SPARK_SCRIPT, 45 | http_conn_id=HTTP_CONN_ID, 46 | session_kind=SESSION_TYPE, 47 | dag=dag) 48 | -------------------------------------------------------------------------------- /example_dags/spark_submit_operator_python_example.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | from airflow.operators import SparkSubmitOperator 3 | from airflow.models import DAG 4 | from datetime import datetime, timedelta 5 | import os 6 | 7 | 8 | DAG_ID = os.path.basename(__file__).replace(".pyc", "").replace(".py", "") 9 | 10 | APPLICATION_FILE_PATH = "~/spark-test/spark_test.py" 11 | 12 | default_args = { 13 | 'owner': 'airflow', 14 | 'depends_on_past': False, 15 | 'retries': 0, 16 | } 17 | 18 | dag = DAG(DAG_ID, default_args=default_args, schedule_interval=None, start_date=(datetime.now() - timedelta(minutes=1))) 19 | 20 | dummy = SparkSubmitOperator( 21 | task_id='spark-submit-python', 22 | application_file=APPLICATION_FILE_PATH, 23 | application_args="arg1 arg2", 24 | dag=dag) 25 | 26 | -------------------------------------------------------------------------------- /example_dags/spark_submit_operator_r_example.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | from airflow.operators import SparkSubmitOperator 3 | from airflow.models import DAG 4 | from datetime import datetime, timedelta 5 | import os 6 | 7 | 8 | DAG_ID = os.path.basename(__file__).replace(".pyc", "").replace(".py", "") 9 | 10 | APPLICATION_FILE_PATH = "~/spark-test/spark_test.R" 11 | 12 | default_args = { 13 | 'owner': 'airflow', 14 | 'depends_on_past': False, 15 | 'retries': 0, 16 | } 17 | 18 | dag = DAG(DAG_ID, default_args=default_args, schedule_interval=None, start_date=(datetime.now() - timedelta(minutes=1))) 19 | 20 | dummy = SparkSubmitOperator( 21 | task_id='spark-submit-r', 22 | application_file=APPLICATION_FILE_PATH, 23 | dag=dag) 24 | 25 | -------------------------------------------------------------------------------- /example_dags/spark_submit_operator_scala_example.py: -------------------------------------------------------------------------------- 1 | from __future__ import print_function 2 | from airflow.operators import SparkSubmitOperator 3 | from airflow.models import DAG 4 | from datetime import datetime, timedelta 5 | import os 6 | 7 | DAG_ID = os.path.basename(__file__).replace(".pyc", "").replace(".py", "") 8 | 9 | APPLICATION_FILE_PATH = "~/spark-test/spark_test-jar-with-dependencies.jar" 10 | 11 | default_args = { 12 | 'owner': 'airflow', 13 | 'depends_on_past': False, 14 | 'retries': 0, 15 | } 16 | 17 | dag = DAG(DAG_ID, default_args=default_args, schedule_interval=None, start_date=(datetime.now() - timedelta(minutes=1))) 18 | 19 | dummy = SparkSubmitOperator( 20 | task_id='spark-submit-scala', 21 | application_file=APPLICATION_FILE_PATH, 22 | application_args="arg1 arg2", 23 | dag=dag) 24 | 25 | -------------------------------------------------------------------------------- /example_spark_jobs/python/spark_test.py: -------------------------------------------------------------------------------- 1 | from pyspark import SparkContext, SparkConf 2 | import sys 3 | 4 | APP_NAME = "Spark_Test_Python" 5 | 6 | args = sys.argv[1:] 7 | print 'Number of arguments:', len(args), 'arguments.' 8 | print 'Argument List:', str(args) 9 | 10 | conf = SparkConf().setAppName(APP_NAME) 11 | sc = SparkContext(conf=conf) 12 | 13 | rdd = sc.parallelize([1, 2, 3, 4, 5]) 14 | rdd_filtered = rdd.filter(lambda entry: entry > 3) 15 | print(rdd_filtered.collect()) 16 | -------------------------------------------------------------------------------- /example_spark_jobs/r/spark_test.R: -------------------------------------------------------------------------------- 1 | library(SparkR) 2 | 3 | sc = sparkR.init() 4 | rdd = SparkR:::parallelize(sc, 1:5) 5 | SparkR:::collect(rdd) -------------------------------------------------------------------------------- /example_spark_jobs/scala/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.softwaresanders.spark 8 | spark_test 9 | 1.0-SNAPSHOT 10 | 11 | 12 | 2.10.6 13 | 1.6.1 14 | 15 | 16 | 17 | 18 | org.apache.spark 19 | spark-core_2.10 20 | ${spark.version} 21 | 22 | 23 | 24 | org.apache.spark 25 | spark-sql_2.10 26 | ${spark.version} 27 | 28 | 29 | 30 | org.apache.spark 31 | spark-hive_2.10 32 | ${spark.version} 33 | 34 | 35 | 36 | 37 | 38 | cloudera-repo-releases 39 | Spark-Support 40 | https://repository.cloudera.com/artifactory/repo/ 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | org.codehaus.mojo 51 | build-helper-maven-plugin 52 | 53 | 54 | generate-sources 55 | add-source 56 | 57 | 58 | src/main/scala 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | org.scala-tools 68 | maven-scala-plugin 69 | 70 | 71 | 72 | compile 73 | testCompile 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | org.apache.maven.plugins 82 | maven-assembly-plugin 83 | 2.4 84 | 85 | 86 | jar-with-dependencies 87 | 88 | 89 | 90 | com.softwaresanders.spark.spark_test.Main 91 | 92 | 93 | 94 | 95 | 96 | package 97 | 98 | single 99 | 100 | 101 | 102 | 103 | 104 | 105 | 106 | org.apache.maven.plugins 107 | maven-surefire-plugin 108 | 2.7 109 | 110 | true 111 | 112 | 113 | 114 | 115 | 116 | ${project.artifactId} 117 | 118 | 119 | 120 | -------------------------------------------------------------------------------- /example_spark_jobs/scala/src/main/scala/com/softwaresanders/spark/spark_test/Main.scala: -------------------------------------------------------------------------------- 1 | package com.softwaresanders.spark.spark_test 2 | 3 | import java.util 4 | 5 | import org.apache.spark.{SparkContext, SparkConf} 6 | 7 | /** 8 | * Created by robertsanders on 10/31/16. 9 | */ 10 | object Main { 11 | 12 | val APP_NAME = "Spark_Test_Scala" 13 | 14 | def main (args: Array[String]) { 15 | 16 | println("Number of arguments: " + args.length + " arguments.") 17 | println("Argument List: " + args) 18 | 19 | val sparkConf = new SparkConf() 20 | sparkConf.setAppName(APP_NAME) 21 | val sc = new SparkContext(sparkConf) 22 | 23 | val rdd = sc.parallelize(1 to 5) 24 | val rddFiltered = rdd.filter(entry => entry > 3) 25 | println(util.Arrays.toString(rddFiltered.collect())) 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /spark_operator_plugin.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # Licensed under the Apache License, Version 2.0 (the "License"); 4 | # you may not use this file except in compliance with the License. 5 | # You may obtain a copy of the License at 6 | # 7 | # http://www.apache.org/licenses/LICENSE-2.0 8 | # 9 | # Unless required by applicable law or agreed to in writing, software 10 | # distributed under the License is distributed on an "AS IS" BASIS, 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | # See the License for the specific language governing permissions and 13 | # limitations under the License. 14 | 15 | from airflow.plugins_manager import AirflowPlugin 16 | from airflow.hooks import HttpHook 17 | from airflow.models import BaseOperator 18 | from airflow.operators import BashOperator 19 | from airflow.utils import apply_defaults 20 | import logging 21 | import textwrap 22 | import time 23 | import json 24 | 25 | 26 | class SparkSubmitOperator(BashOperator): 27 | """ 28 | An operator which executes the spark-submit command through Airflow. This operator accepts all the desired 29 | arguments and assembles the spark-submit command which is then executed by the BashOperator. 30 | 31 | :param application_file: Path to a bundled jar including your application 32 | and all dependencies. The URL must be globally visible inside of 33 | your cluster, for instance, an hdfs:// path or a file:// path 34 | that is present on all nodes. 35 | :type application_file: string 36 | :param main_class: The entry point for your application 37 | (e.g. org.apache.spark.examples.SparkPi) 38 | :type main_class: string 39 | :param master: The master value for the cluster. 40 | (e.g. spark://23.195.26.187:7077 or yarn-client) 41 | :type master: string 42 | :param conf: Dictionary consisting of arbitrary Spark configuration properties. 43 | (e.g. {"spark.eventLog.enabled": "false", 44 | "spark.executor.extraJavaOptions": "-XX:+PrintGCDetails -XX:+PrintGCTimeStamps"} 45 | :type conf: dict 46 | :param deploy_mode: Whether to deploy your driver on the worker nodes 47 | (cluster) or locally as an external client (default: client) 48 | :type deploy_mode: string 49 | :param other_spark_options: Other options you would like to pass to 50 | the spark submit command that isn't covered by the current 51 | options. (e.g. --files /path/to/file.xml) 52 | :type other_spark_options: string 53 | :param application_args: Arguments passed to the main method of your 54 | main class, if any. 55 | :type application_args: string 56 | :param xcom_push: If xcom_push is True, the last line written to stdout 57 | will also be pushed to an XCom when the bash command completes. 58 | :type xcom_push: bool 59 | :param env: If env is not None, it must be a mapping that defines the 60 | environment variables for the new process; these are used instead 61 | of inheriting the current process environment, which is the default 62 | behavior. (templated) 63 | :type env: dict 64 | :type output_encoding: output encoding of bash command 65 | """ 66 | 67 | template_fields = ('conf', 'other_spark_options', 'application_args', 'env') 68 | template_ext = [] 69 | ui_color = '#e47128' # Apache Spark's Main Color: Orange 70 | 71 | @apply_defaults 72 | def __init__( 73 | self, 74 | application_file, 75 | main_class=None, 76 | master=None, 77 | conf={}, 78 | deploy_mode=None, 79 | other_spark_options=None, 80 | application_args=None, 81 | xcom_push=False, 82 | env=None, 83 | output_encoding='utf-8', 84 | *args, **kwargs): 85 | self.bash_command = "" 86 | self.env = env 87 | self.output_encoding = output_encoding 88 | self.xcom_push_flag = xcom_push 89 | super(SparkSubmitOperator, self).__init__(bash_command=self.bash_command, xcom_push=xcom_push, env=env, output_encoding=output_encoding, *args, **kwargs) 90 | self.application_file = application_file 91 | self.main_class = main_class 92 | self.master = master 93 | self.conf = conf 94 | self.deploy_mode = deploy_mode 95 | self.other_spark_options = other_spark_options 96 | self.application_args = application_args 97 | 98 | def execute(self, context): 99 | logging.info("Executing SparkSubmitOperator.execute(context)") 100 | 101 | self.bash_command = "spark-submit " 102 | if self.is_not_null_and_is_not_empty_str(self.main_class): 103 | self.bash_command += "--class " + self.main_class + " " 104 | if self.is_not_null_and_is_not_empty_str(self.master): 105 | self.bash_command += "--master " + self.master + " " 106 | if self.is_not_null_and_is_not_empty_str(self.deploy_mode): 107 | self.bash_command += "--deploy-mode " + self.deploy_mode + " " 108 | for conf_key, conf_value in self.conf.items(): 109 | if self.is_not_null_and_is_not_empty_str(conf_key) and self.is_not_null_and_is_not_empty_str(conf_value): 110 | self.bash_command += "--conf " + "'" + conf_key + "=" + conf_value + "'" + " " 111 | if self.is_not_null_and_is_not_empty_str(self.other_spark_options): 112 | self.bash_command += self.other_spark_options + " " 113 | 114 | self.bash_command += self.application_file + " " 115 | 116 | if self.is_not_null_and_is_not_empty_str(self.application_args): 117 | self.bash_command += self.application_args + " " 118 | 119 | logging.info("Finished assembling bash_command in SparkSubmitOperator: " + str(self.bash_command)) 120 | 121 | logging.info("Executing bash execute statement") 122 | super(SparkSubmitOperator, self).execute(context) 123 | 124 | logging.info("Finished executing SparkSubmitOperator.execute(context)") 125 | 126 | @staticmethod 127 | def is_not_null_and_is_not_empty_str(value): 128 | return value is not None and value != "" 129 | 130 | 131 | class LivySparkOperator(BaseOperator): 132 | """ 133 | Operator to facilitate interacting with the Livy Server which executes Apache Spark code via a REST API. 134 | 135 | :param spark_script: Scala, Python or R code to submit to the Livy Server (templated) 136 | :type spark_script: string 137 | :param session_kind: Type of session to setup with Livy. This will determine which type of code will be accepted. Possible values include "spark" (executes Scala code), "pyspark" (executes Python code) or "sparkr" (executes R code). 138 | :type session_kind: string 139 | :param http_conn_id: The http connection to run the operator against 140 | :type http_conn_id: string 141 | :param poll_interval: The polling interval to use when checking if the code in spark_script has finished executing. In seconds. (default: 30 seconds) 142 | :type poll_interval: integer 143 | """ 144 | 145 | template_fields = ['spark_script'] # todo : make sure this works 146 | template_ext = ['.py', '.R', '.r'] 147 | ui_color = '#34a8dd' # Clouderas Main Color: Blue 148 | 149 | acceptable_response_codes = [200, 201] 150 | statement_non_terminated_status_list = ['waiting', 'running'] 151 | 152 | @apply_defaults 153 | def __init__( 154 | self, 155 | spark_script, 156 | session_kind="spark", # spark, pyspark, or sparkr 157 | http_conn_id='http_default', 158 | poll_interval=30, 159 | *args, **kwargs): 160 | super(LivySparkOperator, self).__init__(*args, **kwargs) 161 | 162 | self.spark_script = spark_script 163 | self.session_kind = session_kind 164 | self.http_conn_id = http_conn_id 165 | self.poll_interval = poll_interval 166 | 167 | self.http = HttpHook("GET", http_conn_id=self.http_conn_id) 168 | 169 | def execute(self, context): 170 | logging.info("Executing LivySparkOperator.execute(context)") 171 | 172 | logging.info("Validating arguments...") 173 | self._validate_arguments() 174 | logging.info("Finished validating arguments") 175 | 176 | logging.info("Creating a Livy Session...") 177 | session_id = self._create_session() 178 | logging.info("Finished creating a Livy Session. (session_id: " + str(session_id) + ")") 179 | 180 | logging.info("Submitting spark script...") 181 | statement_id, overall_statements_state = self._submit_spark_script(session_id=session_id) 182 | logging.info("Finished submitting spark script. (statement_id: " + str(statement_id) + ", overall_statements_state: " + str(overall_statements_state) + ")") 183 | 184 | poll_for_completion = (overall_statements_state in self.statement_non_terminated_status_list) 185 | 186 | if poll_for_completion: 187 | logging.info("Spark job did not complete immediately. Starting to Poll for completion...") 188 | 189 | while overall_statements_state in self.statement_non_terminated_status_list: # todo: test execution_timeout 190 | logging.info("Sleeping for " + str(self.poll_interval) + " seconds...") 191 | time.sleep(self.poll_interval) 192 | logging.info("Finished sleeping. Checking if Spark job has completed...") 193 | statements = self._get_session_statements(session_id=session_id) 194 | 195 | is_all_complete = True 196 | for statement in statements: 197 | if statement["state"] in self.statement_non_terminated_status_list: 198 | is_all_complete = False 199 | 200 | # In case one of the statements finished with errors throw exception 201 | elif statement["state"] != 'available' or statement["output"]["status"] == 'error': 202 | logging.error("Statement failed. (state: " + str(statement["state"]) + ". Output:\n" + 203 | str(statement["output"])) 204 | response = self._close_session(session_id=session_id) 205 | logging.error("Closed session. (response: " + str(response) + ")") 206 | raise Exception("Statement failed. (state: " + str(statement["state"]) + ". Output:\n" + 207 | str(statement["output"])) 208 | 209 | if is_all_complete: 210 | overall_statements_state = "available" 211 | 212 | logging.info("Finished checking if Spark job has completed. (overall_statements_state: " + str(overall_statements_state) + ")") 213 | 214 | if poll_for_completion: 215 | logging.info("Finished Polling for completion.") 216 | 217 | logging.info("Session Logs:\n" + str(self._get_session_logs(session_id=session_id))) 218 | 219 | for statement in self._get_session_statements(session_id): 220 | logging.info("Statement '" + str(statement["id"]) + "' Output:\n" + str(statement["output"])) 221 | 222 | logging.info("Closing session...") 223 | response = self._close_session(session_id=session_id) 224 | logging.info("Finished closing session. (response: " + str(response) + ")") 225 | 226 | logging.info("Finished executing LivySparkOperator.execute(context)") 227 | 228 | def _validate_arguments(self): 229 | if self.session_kind is None or self.session_kind == "": 230 | raise Exception( 231 | "session_kind argument is invalid. It is empty or None. (value: '" + str(self.session_kind) + "')") 232 | elif self.session_kind not in ["spark", "pyspark", "sparkr"]: 233 | raise Exception( 234 | "session_kind argument is invalid. It should be set to 'spark', 'pyspark', or 'sparkr'. (value: '" + str( 235 | self.session_kind) + "')") 236 | 237 | def _get_sessions(self): 238 | method = "GET" 239 | endpoint = "sessions" 240 | response = self._http_rest_call(method=method, endpoint=endpoint) 241 | 242 | if response.status_code in self.acceptable_response_codes: 243 | return response.json()["sessions"] 244 | else: 245 | raise Exception("Call to get sessions didn't return " + str(self.acceptable_response_codes) + ". Returned '" + str(response.status_code) + "'.") 246 | 247 | def _get_session(self, session_id): 248 | sessions = self._get_sessions() 249 | for session in sessions: 250 | if session["id"] == session_id: 251 | return session 252 | 253 | def _get_session_logs(self, session_id): 254 | method = "GET" 255 | endpoint = "sessions/" + str(session_id) + "/log" 256 | response = self._http_rest_call(method=method, endpoint=endpoint) 257 | return response.json() 258 | 259 | def _create_session(self): 260 | method = "POST" 261 | endpoint = "sessions" 262 | 263 | data = { 264 | "kind": self.session_kind 265 | } 266 | 267 | response = self._http_rest_call(method=method, endpoint=endpoint, data=data) 268 | 269 | if response.status_code in self.acceptable_response_codes: 270 | response_json = response.json() 271 | session_id = response_json["id"] 272 | session_state = response_json["state"] 273 | 274 | if session_state == "starting": 275 | logging.info("Session is starting. Polling to see if it is ready...") 276 | 277 | session_state_polling_interval = 10 278 | while session_state == "starting": 279 | logging.info("Sleeping for " + str(session_state_polling_interval) + " seconds") 280 | time.sleep(session_state_polling_interval) 281 | session_state_check_response = self._get_session(session_id=session_id) 282 | session_state = session_state_check_response["state"] 283 | logging.info("Got latest session state as '" + session_state + "'") 284 | 285 | return session_id 286 | else: 287 | raise Exception("Call to create a new session didn't return " + str(self.acceptable_response_codes) + ". Returned '" + str(response.status_code) + "'.") 288 | 289 | def _submit_spark_script(self, session_id): 290 | method = "POST" 291 | endpoint = "sessions/" + str(session_id) + "/statements" 292 | 293 | logging.info("Executing Spark Script: \n" + str(self.spark_script)) 294 | 295 | data = { 296 | 'code': textwrap.dedent(self.spark_script) 297 | } 298 | 299 | response = self._http_rest_call(method=method, endpoint=endpoint, data=data) 300 | 301 | if response.status_code in self.acceptable_response_codes: 302 | response_json = response.json() 303 | return response_json["id"], response_json["state"] 304 | else: 305 | raise Exception("Call to create a new statement didn't return " + str(self.acceptable_response_codes) + ". Returned '" + str(response.status_code) + "'.") 306 | 307 | def _get_session_statements(self, session_id): 308 | method = "GET" 309 | endpoint = "sessions/" + str(session_id) + "/statements" 310 | response = self._http_rest_call(method=method, endpoint=endpoint) 311 | 312 | if response.status_code in self.acceptable_response_codes: 313 | response_json = response.json() 314 | statements = response_json["statements"] 315 | return statements 316 | else: 317 | raise Exception("Call to get the session statement response didn't return " + str(self.acceptable_response_codes) + ". Returned '" + str(response.status_code) + "'.") 318 | 319 | def _close_session(self, session_id): 320 | method = "DELETE" 321 | endpoint = "sessions/" + str(session_id) 322 | return self._http_rest_call(method=method, endpoint=endpoint) 323 | 324 | def _http_rest_call(self, method, endpoint, data=None, headers=None, extra_options=None): 325 | if not extra_options: 326 | extra_options = {} 327 | logging.debug("Performing HTTP REST call... (method: " + str(method) + ", endpoint: " + str(endpoint) + ", data: " + str(data) + ", headers: " + str(headers) + ")") 328 | self.http.method = method 329 | response = self.http.run(endpoint, json.dumps(data), headers, extra_options=extra_options) 330 | 331 | logging.debug("status_code: " + str(response.status_code)) 332 | logging.debug("response_as_json: " + str(response.json())) 333 | 334 | return response 335 | 336 | 337 | # Defining the plugin class 338 | class SparkOperatorPlugin(AirflowPlugin): 339 | name = "spark_operator_plugin" 340 | operators = [SparkSubmitOperator, LivySparkOperator] 341 | flask_blueprints = [] 342 | hooks = [] 343 | executors = [] 344 | admin_views = [] 345 | menu_links = [] 346 | --------------------------------------------------------------------------------