DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Power BI Embedded Analytics — Part 3: Power BI Embedded Demo
  • DGS GraphQL and Spring Boot
  • Auto-Instrumentation in Azure Application Insights With AKS
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide

Trending

  • Introducing Graph Concepts in Java With Eclipse JNoSQL
  • The Evolution of Scalable and Resilient Container Infrastructure
  • How To Introduce a New API Quickly Using Quarkus and ChatGPT
  • Building a Real-Time Audio Transcription System With OpenAI’s Realtime API

Execute Spark Applications With Apache Livy

To run a Spark application like a batch job, we have to provide the path to the application entry point, along with the parameters, all the while using the REST API.

By 
Bipin Patwardhan user avatar
Bipin Patwardhan
·
Mar. 25, 21 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
8.8K Views

Join the DZone community and get the full member experience.

Join For Free

Introduction

These days, Spark — either as Apache Spark or as Databricks (on any one of the cloud platforms) — has become the de-facto tool for data processing. Many of us are comfortable developing Spark applications using Scala/Spark or Python/Spark. While application development may seem simple, testing the application is fairly simple for all of us. As we tend to develop the application either on our laptops or on VMs, we usually have a local Spark setup that we invoke.

When Spark applications are written as part of a larger data pipeline, one of the most common mechanisms is to run the application using a 'spark submit' command. In many cases, one or more Spark applications are executed one after the other where the 'spark submit' command is executed by a scheduler like Oozie or cron or Airflow.

While the option of 'spark submit' is fairly straightforward and simple, matters are a bit complicated if we have to execute Spark jobs from other applications. Recently, I was faced with a similar situation, where I had to execute a couple of Spark jobs from a micro-service. This situation presented a problem. When we perform a 'spark submit,' the system expects Spark and associated libraries to be present in the same environment, along with the required environment variables. As the microservices were going to be deployed in Docker and Kubernetes, we had a situation.

Enter Apache Livy

Fortunately for me, one of my colleagues suggested I look at the Apache Livy project. At the time of writing, the Apache Livy project is still an incubating project and is at version 0.7. The Apache Livy project runs as a server on a port and allows us to interact with Spark applications via a REST API. Using the REST API, the execution of Spark jobs became very simple. Using Apache Livy, we have to ensure that the Spark application and the Livy server are on the same VM. To run a Spark application like a batch job, we have to provide the path to the entry point of the application, along with the parameters, all the while using the REST API. Once a batch is submitted, Livy allows us to monitor the status of the job using another REST endpoint.

In this article, I am presenting a helper class that makes it easier to interact with 'Livy fronted Spark applications' as I have started calling them.

Helper Class

Here is the helper class to interact with Livy and 'Livy fronted Spark applications'.

Python
 




xxxxxxxxxx
1
51
 
1
import time
2
import requests
3
import requests.utils import quote
4

          
5
class LivyBatchRunner:
6
    VALID_STATES = [ "success", "dead", "unknown" ]
7
    SERVICE_NOT_AVAILABLE = "service is not available"
8

          
9
    def __init__(self, serverBaseURL):
10
        self.serverBaseURL = serverBaseURL
11
        self.runID = None
12
    
13
    def submitBatch(self, params):
14
        runState = None
15
        try:
16
            if self.serverBaseURL is not None and self.serverBaseURL != "":
17
                url = f"{self.runID}/batches"
18
                retVal = requests.post(url, json=params).json()
19
                if retVal.status_code == 201:
20
                    responseJSON = retVal.json()
21
                    self.runID = responseJSON.get("id", None)
22
                    runState = responseJSON.get("state", None)
23
                else:
24
                    self.runID = -1
25
                    runState = LivyBatchRunner.SERVICE_NOT_AVAILABLE
26
            else:
27
                self.runID = -1
28
                runState = LivyBatchRunner.SERVICE_NOT_AVAILABLE
29
        except:
30
            self.runID = -1
31
            runState = LivyBatchRunner.SERVICE_NOT_AVAILABLE
32
        return self.runID, runState
33
    
34
    def getBatchState(self):
35
        url = f"{self.serverBaseURL}/batches/{self.runID}/state"
36
        retVal = requests.get(url).json()
37
        if retVal.status_code == 200:
38
            responseJSON = retVal.json()
39
            runState = responseJSON.get("state", None)
40
        else:
41
            runState = "unknown"
42
        return runState
43
    
44
    def waitForBatch(self, sleepTime, timeoutValue):
45
        runState = "running"
46
        runTime = 0
47
        while runState not in != LivyBatchRunner.VALID_STATES and runTime < timeoutValue:
48
            time.sleep(sleepTime)
49
            runTime = runTime + sleepTime
50
            runState = self.getBatchState()
51
        return runTime, runState



Using the Helper Class

After defining the class, we can run Spark jobs as below:

Python
 




xxxxxxxxxx
1
23


 
1
from LivyBatchRunner import LivyBatchRunner
2

          
3
DEFAULT_TIME_OUT_VALUE = 600
4
DEFAULT_PING_TIME = 20
5

          
6
params = {
7
    "name": <name of application>,
8
    "file": <path to application entry point>,
9
    "pyFiles": []
10
    "args": [param_str]
11
}
12

          
13
serverURL = <url>
14
livy = LivyBatchRunner(serverURL)
15
jobID, state = livy.submitBatch(params)
16
if state == LivyBatchRunner.SERVICE_NOT_AVAILABLE:
17
    print("Livy server is not available")
18
else:
19
    timeTaken, state = livy.waitForBatch(DEFAULT_PING_TIME, DEFAULT_TIME_OUT_VALUE)
20
    if timeTaken > DEFAULT_TIME_OUT_VALUE:
21
        print("Batch is still running. please check after some time")
22
    else:
23
        print(f"Batch execution is done. Status is {state}")



Conclusion

Apache Livy makes the task of invoking an monitoring remote Spark jobs quite easy.

In a following article, I will share a similar helper for Databricks jobs.

References

  • Apache Livy — https://livy.incubator.apache.org/
  • Apache Livy Getting Started — https://livy.incubator.apache.org/get-started/
  • Apache Livy Examples — https://livy.incubator.apache.org/examples/
  • Apache Livy REST API — https://livy.incubator.apache.org/docs/latest/rest-api.html
application

Opinions expressed by DZone contributors are their own.

Related

  • Power BI Embedded Analytics — Part 3: Power BI Embedded Demo
  • DGS GraphQL and Spring Boot
  • Auto-Instrumentation in Azure Application Insights With AKS
  • Deploying a Scala Play Application to Heroku: A Step-by-Step Guide

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!