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
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Key Takeaways From Integrating a RAG Application With LangSmith
  • Improving Java Application Reliability with Dynatrace AI Engine
  • Enabling Single-Sign-On in SaaS Application
  • Reimagining Innovation: How Citizen Application Development is Reshaping the Modern Enterprise

Trending

  • OpenAPI From Code With Spring and Java: A Recipe for Your CI
  • Why AI-Generated Code Breaks Your Testing Assumptions
  • Lambda-Driven API Design: Building Composable Node.js Endpoints With Functional Primitives
  • Key Takeaways From Integrating a RAG Application With LangSmith

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
9.1K 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

  • Key Takeaways From Integrating a RAG Application With LangSmith
  • Improving Java Application Reliability with Dynatrace AI Engine
  • Enabling Single-Sign-On in SaaS Application
  • Reimagining Innovation: How Citizen Application Development is Reshaping the Modern Enterprise

Partner Resources

×

Comments

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

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

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 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook