SlideShare a Scribd company logo
Apache Toree
A Jupyter Kernel for Scala and Apache Spark
THIS IS NOT A CONTRIBUTION
Luciano Resende
Apache Torree committer and PPMC member | Apple
ApacheCon North America 2022
About me - Luciano Resende
lresende@apache.org https://www.linkedin.com/in/lresende
@lresende1975 https://github.com/lresende
AI/ML Data Platform Architect — Apple
•Over 20 years industry experience with over 15 year contributing to open source
•Creator of Elyra and Jupyter Enterprise Gateway
•Open source areas of contribution: Elyra, Jupyter Notebook ecosystem, Apache
Bahir, Apache Toree, Apache Spark among other projects related to AI/ML
platforms
Jupyter Notebooks
Jupyter Notebooks
Notebooks are interactive
computational environments, in
which you can combine code
execution, rich text, mathematics,
plots and rich media
•
Jupyter Notebooks
Jupyter Ecosystem is
the de-facto standard tool in data
science and AI community
Popular IDE usage
JupyterLab
Visual Studio Code
PyCharm
Rstudio
Spyder
Notepad++
Sublime Text
Vim, Emacs, or similar
Visual Studio
MATLAB
Other
None
0% 20% 40% 60% 80%
0.7%
5.6%
5.8%
10.1%
11.0%
15.2%
19.4%
21.8%
31.5%
31.9%
33.2%
74.1%
Jupyter Notebooks
Simple, but Powerful
As simple as opening a web page, with the capabilities of a powerful, multilingual, development environment.
Interactive widgets
Code can produce rich outputs such as images, videos, markdown, LaTeX and JavaScript. Interactive widgets can be
used to manipulate and visualize data in real-time.
Language of choice
Jupyter Notebooks have support for over 50 programming languages, including those popular in Data Science, Data Engineer,
and AI such as Python, R, Julia and Scala.
Big Data Integration
Leverage Big Data platforms such as Apache Spark from Python, R and Scala. Explore the same data with pandas,
scikit-learn, ggplot2, dplyr, etc.
Share Notebooks
Notebooks can be shared with others using e-mail, Dropbox, Google Drive, GitHub, etc
ō€™šō€†…ō€«ō€‚’ō€”“
⤵
Jupyter Notebooks
Single page web interface
• File Browser
• Code Console (QT Console)
• Text Editor
Current Release
• Jupyter Notebook 6.4.12
• Available in Anaconda
• pip install --upgrade notebook
Jupyter Notebooks
The Classic Notebook is starting to move
towards maintenance mode
• Community e
ff
orts being concentrated in
the new JupyterLab UI.
• Community continue to deliver bug-
fi
xes
and security updates frequently
Jupyter 7.0 (based on JupyterLab) discussion:
• https://jupyter.org/enhancement-
proposals/79-notebook-v7/notebook-
v7.html
JupyterLab
JupyterLab is the next generation UI
for the Jupyter Ecosystem.
Brings all the previous improvements
into a single uni
fi
ed platform plus
more!
Provides a modular, extensible
architecture
Retains backward compatibility with
the old notebook we know and love
JupyterLab
File Browser
Widgets/
Rich Output
Tabbed
Workspaces
Text Editor
Console/
Terminal
Jupyter Notebooks
Notebook UI runs on the browser
The Notebook Server serves the
ā€˜Notebooks’
Kernels interpret/execute cell contents
• Are responsible for code execution
• Abstracts di
ff
erent languages
• 1:1 relationship with Notebook
• Runs and consume resources as long as
notebook is running
Https/
websocket
ZMQ
ō€”“ō€ˆæ
Jupyter Notebooks
􀇳
Front-end
Kernel Proxy
DEAL SUB
IPython Kernel
ROUTER
􀇳􀇳
Front-end
Kernel Proxy
DEAL SUB
Front-end
Kernel Proxy
DEAL SUB DEAL
ROUTER PUB
Kernel raw_iput
Requests to kernal
Kernel output broadcast
Request / Reply direction
Available Sockets:
• Shell (requests, history, info)
• IOPub (status, display, results)
• Stdin (input requests from kernel)
• Control (shutdown, interrupt)
• Heartbeat (poll)
Jupyter Notebooks
Two types of responses
Results
• Computations that return a result
• 1+1
• val a = 2 + 5
Stream Content
• Values that are written to output stream
• df.show(10)
Client Program Kernel
Evaluate (msgid=1) ā€˜1+1’
Busy (msgid=1)
Status (msgid=1) ok/error
Result (msgid=1)
Stream Content (msgid=1)
Idle (msgid=1)
Apache Toree
Apache Toree
A Scala based Jupyter Kernel that enables Jupyter
Notebooks to execute Scala code and connect to Apache
Spark to build interactive applications.
Apache Toree History
• December 2014 - Open Sourced Spark Kernel to GitHub
• July 2015 - Joined developerWorks Open
• https://developer.ibm.com/open/spark-kernel/
• December 2015 - Accepted as an Apache Incubator Project
• https://toree.apache.org
Apache Toree Releases
Release Scala Version Spark Version
Toree 0.1.x Scala 2.11 Spark 1.6
Toree 0.2.x - 0.4.x Scala 2.11 Spark 2.x
Toree 0.5.x Scala 2.12 Spark 3.x
Apache Toree
Installing the Toree Kernel
• pip install –upgrade toree
Con
fi
guring the Toree Kernel
• jupyter toree install --spark_home=/usr/local/bin/apache-spark/
Apache Toree
{
"argv": [
"/usr/local/share/jupyter/kernels/apache_toree_scala/bin/run.sh",
"--profile",
"{connection_file}"
],
"env": {
"DEFAULT_INTERPRETER": "Scala",
"__TOREE_SPARK_OPTS__": "",
"__TOREE_OPTS__": "",
"SPARK_HOME": "/Users/lresende/opt/spark-3.2.2-bin-hadoop2.7/",
"PYTHONPATH": ā€œ/Users/lresende/opt/spark-3.2.2-bin-hadoop2.7//python:/Users/lresende/opt/spark-3.2.2-bin-
hadoop2.7/python/lib/py4j-0.10.9.5-src.zipā€,
"PYTHON_EXEC": "python"
},
"display_name": "Apache Toree - Scala",
"language": "scala",
"interrupt_mode": "signal",
"metadata": {}
}
Apache Toree
{
"argv": [
ā€œ/usr/local/share/jupyter/kernels/apache_toree_scala/bin/run.sh",
"--spark-context-initialization-mode",
"none",
"--profile",
"{connection_file}"
],
"env": {
"DEFAULT_INTERPRETER": "Scala",
"__TOREE_SPARK_OPTS__": "",
"__TOREE_OPTS__": "",
"SPARK_HOME": "/Users/lresende/opt/spark-3.2.2-bin-hadoop2.7/",
"PYTHONPATH": ā€œ/Users/lresende/opt/spark-3.2.2-bin-hadoop2.7//python:/Users/lresende/opt/spark-3.2.2-bin-hadoop2.7/
python/lib/py4j-0.10.9.5-src.zipā€,
"PYTHON_EXEC": "python"
},
"display_name": "Apache Toree - Scala",
"language": "scala",
"interrupt_mode": "signal",
"metadata": {}
}
Apache Toree
{
"language": "scala",
"display_name": "Spark - Scala (YARN Cluster Mode)",
"metadata": { "process_proxy": { "class_name":
"enterprise_gateway.services.processproxies.yarn.YarnClusterProcessProxyā€ } },
"env": {
"SPARK_HOME": "/usr/hdp/current/spark2-client",
"__TOREE_SPARK_OPTS__": "--master yarn --deploy-mode cluster --name ${KERNEL_ID:-ERROR__NO__KERNEL_ID} --conf
spark.yarn.submit.waitAppCompletion=false --conf spark.yarn.am.waitTime=1d ${KERNEL_EXTRA_SPARK_OPTS}",
"__TOREE_OPTS__": "--alternate-sigint USR2",
"DEFAULT_INTERPRETER": "Scala"
},
"argv": [
"/usr/local/share/jupyter/kernels/spark_scala_yarn_cluster/bin/run.sh",
"--RemoteProcessProxy.kernel-id",
"{kernel_id}",
"--RemoteProcessProxy.response-address",
"{response_address}",
"--RemoteProcessProxy.spark-context-initialization-mode",
"lazy"
]
}
Apache Toree
PROG_HOME="$(cd "`dirname "$0"`"/..; pwd)"
if [ -z "$SPARK_HOME" ]; then
echo "SPARK_HOME must be set to the location of a Spark distribution!"
exit 1
fi
echo "Starting Spark Kernel with SPARK_HOME=$SPARK_HOME"
KERNEL_ASSEMBLY=`(cd ${PROG_HOME}/lib; ls -1 toree-assembly-*.jar;)`
# disable randomized hash for string in Python 3.3+
TOREE_ASSEMBLY=${PROG_HOME}/lib/${KERNEL_ASSEMBLY}
eval exec 
"${SPARK_HOME}/bin/spark-submit" 
--name "'Apache Toree'" 
"${SPARK_OPTS}" 
--class org.apache.toree.Main 
"${TOREE_ASSEMBLY}" 
"${TOREE_OPTS}" 
"$@"
Apache Toree Architectural Diagram
Apache Toree running as an Apache Spark application in client mode
Bob
Alice
􀉩
JupyterLab
jupyter client
Application
Apache
Toree
Driver
Spark Context
Apache Spark Cluster
Worker
Executor
Worker
Executor
Worker
Executor
Cluster
Manager
0MQ
IPython Kernel
protocol
Jupyter Notebooks
Stack Limitation
Scalability
• Jupyter Kernels running as local process
• Resources are limited by what is available on
the one single node that runs all Kernels and
associated Spark drivers
Security
• Single user sharing the same privileges
• Users can see and control each other
process using Jupyter administrative utilities
Maximum Number of Simultaneous Kernels
Max
Kernels
(4GB
Heap)
0
10
20
Cluster Size (32GB Nodes)
4 Nodes 8 Nodes 12 Nodes 16 Nodes
ō€Ŗ¬ō€Ŗ¬ō€Ŗ¬ō€Ŗ¬ō€Ŗ¬ō€Ŗ¬
Cloud Cluster
ō€Ŗ¬
k Kernel
k
k
YARN
Workers
Apache Toree Architectural Diagram
Apache Toree running as an Apache Spark application in cluster mode
YARN Cluster
Gateway Edge Node
Bob
Alice
Jupyter Enterprise Gateway
• Multitenancy
• Remote kernel lifecycle management
Spark Executors
Spark Executors
Spark Executors
Yarn Container
Toree Kernel
Spark Driver
Spark Executors
Spark Executors
Spark Executors
Yarn Container
Toree Kernel
Spark Driver
Impersonation: Alice’s
kernel runs under
Alice’s user ID.
Spark Executors
Spark Executors
Spark Executors
Yarn Container
Toree Kernel
Spark Driver
Security
Layer
ō€‰©ō€Š
JupyterLab
Jupyter Notebook
(local)
Apache Toree Add-ons
Apache Toree, via extensions like
Brunel for Apache Toree or Plotly for
Scala, supports rich visualizations that
integrates directly with Spark Data
Frame APIs
Notes:
Brunel seems to be broken with Spark
3.2.2 (from previous 2.x/3.0.x)
Plotly seems to have a dependency
issue (https://github.com/
alexarchambault/plotly-scala/issues/14)
Apache Toree Visualizations
Apache Toree provides a set of
magics that enhances the user
experience manipulating data
coming from Spark tables or data
Apache Toree Visualizations
Apache Toree APIs
Apache Toree
Accessing Toree programmatically
using Scala
Torre Client APIs
https://github.com/lresende/toree-
gateway/blob/v1.0/src/main/scala/
org/apache/toree/gateway/
ToreeGateway.scala
object ToreeGatewayClient extends App {
// Parse our configuration and create a client connecting
to our kernel
val configFileContent =
scala.io.Source.fromFile(ā€œconfig.jsonā€).mkString
val config: Config =
ConfigFactory.parseString(configFileContent)
val client = (new ClientBootstrap(config)
with StandardSystemInitialization
with StandardHandlerInitialization).createClient()
…
val promise = Promise[String]
try {
val exRes: DeferredExecution = client.execute(ā€œ1+1ā€)
.onResult(executeResult => {
handleResult(promise, executeResult)
}).onError(executeReplyError =>{
handleError(promise, executeReplyError)
}).onSuccess(executeReplyOk => {
handleSuccess(promise, executeReplyOk)
}).onStream(streamResult => {
handleStream(promise, streamResult)
})
} catch {
case t : Throwable => {
log.info("Error submitting request: " + t.getMessage,
t)
promise.success("Error submitting request: " +
t.getMessage)
}
}
Await.result(promise.future, Duration.Inf)
}
Apache Toree
Accessing Toree programmatically
using Python
Jupyter Client package
https://github.com/lresende/toree-
gateway/blob/master/python/
toree_client.py
self.client =
BlockingKernelClient(connection_file=connectionFileLocation)
self.client.load_connection_file(connection_file=connectionFil
eLocation)
…
msg_id = self.client.execute(code=ā€˜1+1’, allow_stdin=False)
reply = self.client.get_shell_msg(block=True, timeout=timeout)
results = []
while True:
try:
msg = self.client.get_iopub_msg(timeout=timeout)
except:
raise Exception("Error: Timeout executing
request")
# Stream results are being returned, accumulate them to
results
if msg['msg_type'] == 'stream':
type = 'stream'
results.append(msg['content']['text'])
continue
elif msg['msg_type'] == 'execute_result’:
if 'text/plain' in msg['content']['data']:
type = 'text'
results.append(msg['content']['data']['text/
plain'])
elif 'text/html' in msg['content']['data']:
# When idle, responses have all been processed/returned
elif msg['msg_type'] == 'status’:
if msg['content']['execution_state'] == 'idle':
break
if reply['content']['status'] == 'ok’:
return ''.join(results)
Apache Toree
Accessing Toree programmatically
using Jupyter Enterprise Gateway
GatewayClient
https://github.com/jupyter-server/
enterprise_gateway/tree/master/
enterprise_gateway/client
# initialize environment
gatewayClient = GatewayClient()
kernel = gatewayClient.start_kernel(ā€˜toree-
kernelspec’)
…
result = self.kernel.execute(ā€1+1")
…
# shutdown environment
gatewayClient.shutdown_kernel(cls.kernel)
Demo
Apache Toree: Join the Community
Contribute to Apache Toree
Roadmap suggestions for contributors
• Decouple plain Scala kernel from Spark
• Enhance startup performance
• Evaluate/Implement better async/parallelism framework
• Progress bar for Spark Jobs
• Spark 3.x and Scala 2.13
• Help with documentation and website enhancements
Apache Toree
https://toree.apache.org
Apache Toree Mailing List
dev@toree.incubator.apache.org
Apache Toree source code at GitHub
https://github.com/apache/incubator-toree
􀋂
Star and fork the project on Github
Apache Toree Resources
Apache Toree
0.5.0 - incubating
pip install -upgrade toree
Questions
lresende@apache.org
@lresende1975
https://www.linkedin.com/in/lresende
https://github.com/lresende

More Related Content

PDF
Getting Started with Kubernetes
VMware Tanzu
Ā 
PPTX
EMEA Airheads- Switch stacking_ ArubaOS Switch
Aruba, a Hewlett Packard Enterprise company
Ā 
PDF
Red Hat Satellite
Katsutoshi Kojima
Ā 
PDF
ABS 2012 - Android Device Porting Walkthrough
Benjamin Zores
Ā 
PDF
Wpa supplicant introduction
awkman
Ā 
PDF
Delivering Quality at Speed with GitOps
Weaveworks
Ā 
PPTX
WebSphere Application Server Liberty Profile and Docker
David Currie
Ā 
PDF
HyperLedger Fabric V2.5.pdf
wonyong hwang
Ā 
Getting Started with Kubernetes
VMware Tanzu
Ā 
EMEA Airheads- Switch stacking_ ArubaOS Switch
Aruba, a Hewlett Packard Enterprise company
Ā 
Red Hat Satellite
Katsutoshi Kojima
Ā 
ABS 2012 - Android Device Porting Walkthrough
Benjamin Zores
Ā 
Wpa supplicant introduction
awkman
Ā 
Delivering Quality at Speed with GitOps
Weaveworks
Ā 
WebSphere Application Server Liberty Profile and Docker
David Currie
Ā 
HyperLedger Fabric V2.5.pdf
wonyong hwang
Ā 

What's hot (20)

PDF
PostgreSQL worst practices, version PGConf.US 2017 by Ilya Kosmodemiansky
PostgreSQL-Consulting
Ā 
PDF
Discover Neo4j Aura_ The Future of Graph Database-as-a-Service Workshop_3.13.24
Neo4j
Ā 
PDF
Simplifying Your IT Workflow with Katello and Foreman
Nikhil Kathole
Ā 
PPTX
Kubernetes & Google Kubernetes Engine (GKE)
Akash Agrawal
Ā 
PPTX
Difference between Github vs Gitlab vs Bitbucket
jeetendra mandal
Ā 
PDF
Distributed Locking in Kubernetes
Rafał Leszko
Ā 
PPTX
Container Monitoring with Sysdig
Sreenivas Makam
Ā 
PDF
Best Practices for a Complete Postgres Enterprise Architecture Setup
EDB
Ā 
PDF
2023 Ivanti August Patch Tuesday
Ivanti
Ā 
PPTX
GitLab for CI/CD process
HYS Enterprise
Ā 
PDF
Open shift 4-update
SaeidVarmazyar
Ā 
PDF
HandsOn ProxySQL Tutorial - PLSC18
Derek Downey
Ā 
PDF
Mastering OpenStack - Episode 01 - Simple Architectures
Roozbeh Shafiee
Ā 
ODP
SELinux for Everyday Users
PaulWay
Ā 
PDF
Github - Git Training Slides: Foundations
Lee Hanxue
Ā 
PPTX
Kubernetes security
Saiyam Pathak
Ā 
PPTX
NETCONF YANG tutorial
Tail-f Systems
Ā 
PDF
GitOps with ArgoCD
CloudOps2005
Ā 
PDF
Running PostgreSQL in Kubernetes: from day 0 to day 2 with CloudNativePG - Do...
DoKC
Ā 
PDF
CI/CD on Google Cloud Platform
DevOps Indonesia
Ā 
PostgreSQL worst practices, version PGConf.US 2017 by Ilya Kosmodemiansky
PostgreSQL-Consulting
Ā 
Discover Neo4j Aura_ The Future of Graph Database-as-a-Service Workshop_3.13.24
Neo4j
Ā 
Simplifying Your IT Workflow with Katello and Foreman
Nikhil Kathole
Ā 
Kubernetes & Google Kubernetes Engine (GKE)
Akash Agrawal
Ā 
Difference between Github vs Gitlab vs Bitbucket
jeetendra mandal
Ā 
Distributed Locking in Kubernetes
Rafał Leszko
Ā 
Container Monitoring with Sysdig
Sreenivas Makam
Ā 
Best Practices for a Complete Postgres Enterprise Architecture Setup
EDB
Ā 
2023 Ivanti August Patch Tuesday
Ivanti
Ā 
GitLab for CI/CD process
HYS Enterprise
Ā 
Open shift 4-update
SaeidVarmazyar
Ā 
HandsOn ProxySQL Tutorial - PLSC18
Derek Downey
Ā 
Mastering OpenStack - Episode 01 - Simple Architectures
Roozbeh Shafiee
Ā 
SELinux for Everyday Users
PaulWay
Ā 
Github - Git Training Slides: Foundations
Lee Hanxue
Ā 
Kubernetes security
Saiyam Pathak
Ā 
NETCONF YANG tutorial
Tail-f Systems
Ā 
GitOps with ArgoCD
CloudOps2005
Ā 
Running PostgreSQL in Kubernetes: from day 0 to day 2 with CloudNativePG - Do...
DoKC
Ā 
CI/CD on Google Cloud Platform
DevOps Indonesia
Ā 
Ad

Similar to A Jupyter kernel for Scala and Apache Spark.pdf (20)

PDF
APACHE TOREE: A JUPYTER KERNEL FOR SPARK by Marius van Niekerk
Spark Summit
Ā 
PDF
Jupyter con meetup extended jupyter kernel gateway
Luciano Resende
Ā 
PDF
Big analytics meetup - Extended Jupyter Kernel Gateway
Luciano Resende
Ā 
PDF
The Analytic Platform behind IBM’s Watson Data Platform - Big Data Spain 2017
Luciano Resende
Ā 
PDF
An Enterprise Analytics Platform with Jupyter Notebooks and Apache Spark
Luciano Resende
Ā 
PDF
Building analytical microservices powered by jupyter kernels
Luciano Resende
Ā 
PDF
The Analytic Platform behind IBM’s Watson Data Platform by Luciano Resende a...
Big Data Spain
Ā 
PDF
Using Elyra for COVID-19 Analytics
Luciano Resende
Ā 
PDF
Jupyter notebooks on steroids
Jose Enrique Ruiz
Ā 
PPT
Openstack - An introduction/Installation - Presented at Dr Dobb's conference...
Rahul Krishna Upadhyaya
Ā 
PPTX
2018 02 20-jeg_index
Chester Chen
Ā 
PPTX
Habitat Overview
Mandi Walls
Ā 
PPTX
Introduction to python history and platforms
Kirti Verma
Ā 
PPTX
Data Science at Scale: Using Apache Spark for Data Science at Bitly
Sarah Guido
Ā 
PPT
Undine: Turnkey Drupal Development Environments
David Watson
Ā 
PPTX
Neev Open Source Contributions
Neev Technologies
Ā 
PPT
Apache Sparkā„¢ + IBM Watson + Twitter DataPalooza SF 2015
Mike Broberg
Ā 
PPTX
Apache deep learning 101
DataWorks Summit
Ā 
PDF
.NET RDF APIs
Andrei Iacob
Ā 
PDF
Stackato
Jonas BrĆømsĆø
Ā 
APACHE TOREE: A JUPYTER KERNEL FOR SPARK by Marius van Niekerk
Spark Summit
Ā 
Jupyter con meetup extended jupyter kernel gateway
Luciano Resende
Ā 
Big analytics meetup - Extended Jupyter Kernel Gateway
Luciano Resende
Ā 
The Analytic Platform behind IBM’s Watson Data Platform - Big Data Spain 2017
Luciano Resende
Ā 
An Enterprise Analytics Platform with Jupyter Notebooks and Apache Spark
Luciano Resende
Ā 
Building analytical microservices powered by jupyter kernels
Luciano Resende
Ā 
The Analytic Platform behind IBM’s Watson Data Platform by Luciano Resende a...
Big Data Spain
Ā 
Using Elyra for COVID-19 Analytics
Luciano Resende
Ā 
Jupyter notebooks on steroids
Jose Enrique Ruiz
Ā 
Openstack - An introduction/Installation - Presented at Dr Dobb's conference...
Rahul Krishna Upadhyaya
Ā 
2018 02 20-jeg_index
Chester Chen
Ā 
Habitat Overview
Mandi Walls
Ā 
Introduction to python history and platforms
Kirti Verma
Ā 
Data Science at Scale: Using Apache Spark for Data Science at Bitly
Sarah Guido
Ā 
Undine: Turnkey Drupal Development Environments
David Watson
Ā 
Neev Open Source Contributions
Neev Technologies
Ā 
Apache Sparkā„¢ + IBM Watson + Twitter DataPalooza SF 2015
Mike Broberg
Ā 
Apache deep learning 101
DataWorks Summit
Ā 
.NET RDF APIs
Andrei Iacob
Ā 
Stackato
Jonas BrĆømsĆø
Ā 
Ad

More from Luciano Resende (20)

PDF
Elyra - a set of AI-centric extensions to JupyterLab Notebooks.
Luciano Resende
Ā 
PDF
From Data to AI - Silicon Valley Open Source projects come to you - Madrid me...
Luciano Resende
Ā 
PDF
Ai pipelines powered by jupyter notebooks
Luciano Resende
Ā 
PDF
Strata - Scaling Jupyter with Jupyter Enterprise Gateway
Luciano Resende
Ā 
PDF
Scaling notebooks for Deep Learning workloads
Luciano Resende
Ā 
PDF
Jupyter Enterprise Gateway Overview
Luciano Resende
Ā 
PPTX
Inteligencia artificial, open source e IBM Call for Code
Luciano Resende
Ā 
PDF
IoT Applications and Patterns using Apache Spark & Apache Bahir
Luciano Resende
Ā 
PDF
Getting insights from IoT data with Apache Spark and Apache Bahir
Luciano Resende
Ā 
PDF
Open Source AI - News and examples
Luciano Resende
Ā 
PDF
Building iot applications with Apache Spark and Apache Bahir
Luciano Resende
Ā 
PDF
What's new in Apache SystemML - Declarative Machine Learning
Luciano Resende
Ā 
PDF
Writing Apache Spark and Apache Flink Applications Using Apache Bahir
Luciano Resende
Ā 
PDF
How mentoring can help you start contributing to open source
Luciano Resende
Ā 
PDF
SystemML - Declarative Machine Learning
Luciano Resende
Ā 
PDF
Luciano Resende's keynote at Apache big data conference
Luciano Resende
Ā 
PPT
Asf icfoss-mentoring
Luciano Resende
Ā 
PDF
Open Source tools overview
Luciano Resende
Ā 
PDF
Data access layer and schema definitions
Luciano Resende
Ā 
PDF
How mentoring programs can help newcomers get started with open source
Luciano Resende
Ā 
Elyra - a set of AI-centric extensions to JupyterLab Notebooks.
Luciano Resende
Ā 
From Data to AI - Silicon Valley Open Source projects come to you - Madrid me...
Luciano Resende
Ā 
Ai pipelines powered by jupyter notebooks
Luciano Resende
Ā 
Strata - Scaling Jupyter with Jupyter Enterprise Gateway
Luciano Resende
Ā 
Scaling notebooks for Deep Learning workloads
Luciano Resende
Ā 
Jupyter Enterprise Gateway Overview
Luciano Resende
Ā 
Inteligencia artificial, open source e IBM Call for Code
Luciano Resende
Ā 
IoT Applications and Patterns using Apache Spark & Apache Bahir
Luciano Resende
Ā 
Getting insights from IoT data with Apache Spark and Apache Bahir
Luciano Resende
Ā 
Open Source AI - News and examples
Luciano Resende
Ā 
Building iot applications with Apache Spark and Apache Bahir
Luciano Resende
Ā 
What's new in Apache SystemML - Declarative Machine Learning
Luciano Resende
Ā 
Writing Apache Spark and Apache Flink Applications Using Apache Bahir
Luciano Resende
Ā 
How mentoring can help you start contributing to open source
Luciano Resende
Ā 
SystemML - Declarative Machine Learning
Luciano Resende
Ā 
Luciano Resende's keynote at Apache big data conference
Luciano Resende
Ā 
Asf icfoss-mentoring
Luciano Resende
Ā 
Open Source tools overview
Luciano Resende
Ā 
Data access layer and schema definitions
Luciano Resende
Ā 
How mentoring programs can help newcomers get started with open source
Luciano Resende
Ā 

Recently uploaded (20)

PPTX
The Power of IoT Sensor Integration in Smart Infrastructure and Automation.pptx
Rejig Digital
Ā 
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Captain IT
Ā 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
Ā 
PDF
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
Ā 
PDF
This slide provides an overview Technology
mineshkharadi333
Ā 
PDF
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
Ā 
PDF
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
Ā 
PDF
Test Bank, Solutions for Java How to Program, An Objects-Natural Approach, 12...
famaw19526
Ā 
PDF
Software Development Methodologies in 2025
KodekX
Ā 
PDF
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
Ā 
PDF
CIFDAQ's Token Spotlight: SKY - A Forgotten Giant's Comeback?
CIFDAQ
Ā 
PDF
madgavkar20181017ppt McKinsey Presentation.pdf
georgschmitzdoerner
Ā 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
Ā 
PDF
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
Ā 
PDF
Software Development Company | KodekX
KodekX
Ā 
PPTX
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
Ā 
PDF
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
AbdullahSani29
Ā 
PDF
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
Ā 
PDF
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
Ā 
PDF
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
Ā 
The Power of IoT Sensor Integration in Smart Infrastructure and Automation.pptx
Rejig Digital
Ā 
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Captain IT
Ā 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
Ā 
Google I/O Extended 2025 Baku - all ppts
HusseinMalikMammadli
Ā 
This slide provides an overview Technology
mineshkharadi333
Ā 
The Evolution of KM Roles (Presented at Knowledge Summit Dublin 2025)
Enterprise Knowledge
Ā 
Orbitly Pitch Deck|A Mission-Driven Platform for Side Project Collaboration (...
zz41354899
Ā 
Test Bank, Solutions for Java How to Program, An Objects-Natural Approach, 12...
famaw19526
Ā 
Software Development Methodologies in 2025
KodekX
Ā 
Building High-Performance Oracle Teams: Strategic Staffing for Database Manag...
SMACT Works
Ā 
CIFDAQ's Token Spotlight: SKY - A Forgotten Giant's Comeback?
CIFDAQ
Ā 
madgavkar20181017ppt McKinsey Presentation.pdf
georgschmitzdoerner
Ā 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
Ā 
Unlocking the Future- AI Agents Meet Oracle Database 23ai - AIOUG Yatra 2025.pdf
Sandesh Rao
Ā 
Software Development Company | KodekX
KodekX
Ā 
Smart Infrastructure and Automation through IoT Sensors
Rejig Digital
Ā 
solutions_manual_-_materials___processing_in_manufacturing__demargo_.pdf
AbdullahSani29
Ā 
Security features in Dell, HP, and Lenovo PC systems: A research-based compar...
Principled Technologies
Ā 
Accelerating Oracle Database 23ai Troubleshooting with Oracle AHF Fleet Insig...
Sandesh Rao
Ā 
How-Cloud-Computing-Impacts-Businesses-in-2025-and-Beyond.pdf
Artjoker Software Development Company
Ā 

A Jupyter kernel for Scala and Apache Spark.pdf

  • 1. Apache Toree A Jupyter Kernel for Scala and Apache Spark THIS IS NOT A CONTRIBUTION Luciano Resende Apache Torree committer and PPMC member | Apple ApacheCon North America 2022
  • 2. About me - Luciano Resende [email protected] https://www.linkedin.com/in/lresende @lresende1975 https://github.com/lresende AI/ML Data Platform Architect — Apple •Over 20 years industry experience with over 15 year contributing to open source •Creator of Elyra and Jupyter Enterprise Gateway •Open source areas of contribution: Elyra, Jupyter Notebook ecosystem, Apache Bahir, Apache Toree, Apache Spark among other projects related to AI/ML platforms
  • 4. Jupyter Notebooks Notebooks are interactive computational environments, in which you can combine code execution, rich text, mathematics, plots and rich media •
  • 5. Jupyter Notebooks Jupyter Ecosystem is the de-facto standard tool in data science and AI community Popular IDE usage JupyterLab Visual Studio Code PyCharm Rstudio Spyder Notepad++ Sublime Text Vim, Emacs, or similar Visual Studio MATLAB Other None 0% 20% 40% 60% 80% 0.7% 5.6% 5.8% 10.1% 11.0% 15.2% 19.4% 21.8% 31.5% 31.9% 33.2% 74.1%
  • 6. Jupyter Notebooks Simple, but Powerful As simple as opening a web page, with the capabilities of a powerful, multilingual, development environment. Interactive widgets Code can produce rich outputs such as images, videos, markdown, LaTeX and JavaScript. Interactive widgets can be used to manipulate and visualize data in real-time. Language of choice Jupyter Notebooks have support for over 50 programming languages, including those popular in Data Science, Data Engineer, and AI such as Python, R, Julia and Scala. Big Data Integration Leverage Big Data platforms such as Apache Spark from Python, R and Scala. Explore the same data with pandas, scikit-learn, ggplot2, dplyr, etc. Share Notebooks Notebooks can be shared with others using e-mail, Dropbox, Google Drive, GitHub, etc ō€™šō€†…ō€«ō€‚’ō€”“ ⤵
  • 7. Jupyter Notebooks Single page web interface • File Browser • Code Console (QT Console) • Text Editor Current Release • Jupyter Notebook 6.4.12 • Available in Anaconda • pip install --upgrade notebook
  • 8. Jupyter Notebooks The Classic Notebook is starting to move towards maintenance mode • Community e ff orts being concentrated in the new JupyterLab UI. • Community continue to deliver bug- fi xes and security updates frequently Jupyter 7.0 (based on JupyterLab) discussion: • https://jupyter.org/enhancement- proposals/79-notebook-v7/notebook- v7.html
  • 9. JupyterLab JupyterLab is the next generation UI for the Jupyter Ecosystem. Brings all the previous improvements into a single uni fi ed platform plus more! Provides a modular, extensible architecture Retains backward compatibility with the old notebook we know and love
  • 11. Jupyter Notebooks Notebook UI runs on the browser The Notebook Server serves the ā€˜Notebooks’ Kernels interpret/execute cell contents • Are responsible for code execution • Abstracts di ff erent languages • 1:1 relationship with Notebook • Runs and consume resources as long as notebook is running Https/ websocket ZMQ ō€”“ō€ˆæ
  • 12. Jupyter Notebooks ō€‡³ Front-end Kernel Proxy DEAL SUB IPython Kernel ROUTER ō€‡³ō€‡³ Front-end Kernel Proxy DEAL SUB Front-end Kernel Proxy DEAL SUB DEAL ROUTER PUB Kernel raw_iput Requests to kernal Kernel output broadcast Request / Reply direction Available Sockets: • Shell (requests, history, info) • IOPub (status, display, results) • Stdin (input requests from kernel) • Control (shutdown, interrupt) • Heartbeat (poll)
  • 13. Jupyter Notebooks Two types of responses Results • Computations that return a result • 1+1 • val a = 2 + 5 Stream Content • Values that are written to output stream • df.show(10) Client Program Kernel Evaluate (msgid=1) ā€˜1+1’ Busy (msgid=1) Status (msgid=1) ok/error Result (msgid=1) Stream Content (msgid=1) Idle (msgid=1)
  • 15. Apache Toree A Scala based Jupyter Kernel that enables Jupyter Notebooks to execute Scala code and connect to Apache Spark to build interactive applications.
  • 16. Apache Toree History • December 2014 - Open Sourced Spark Kernel to GitHub • July 2015 - Joined developerWorks Open • https://developer.ibm.com/open/spark-kernel/ • December 2015 - Accepted as an Apache Incubator Project • https://toree.apache.org
  • 17. Apache Toree Releases Release Scala Version Spark Version Toree 0.1.x Scala 2.11 Spark 1.6 Toree 0.2.x - 0.4.x Scala 2.11 Spark 2.x Toree 0.5.x Scala 2.12 Spark 3.x
  • 18. Apache Toree Installing the Toree Kernel • pip install –upgrade toree Con fi guring the Toree Kernel • jupyter toree install --spark_home=/usr/local/bin/apache-spark/
  • 19. Apache Toree { "argv": [ "/usr/local/share/jupyter/kernels/apache_toree_scala/bin/run.sh", "--profile", "{connection_file}" ], "env": { "DEFAULT_INTERPRETER": "Scala", "__TOREE_SPARK_OPTS__": "", "__TOREE_OPTS__": "", "SPARK_HOME": "/Users/lresende/opt/spark-3.2.2-bin-hadoop2.7/", "PYTHONPATH": ā€œ/Users/lresende/opt/spark-3.2.2-bin-hadoop2.7//python:/Users/lresende/opt/spark-3.2.2-bin- hadoop2.7/python/lib/py4j-0.10.9.5-src.zipā€, "PYTHON_EXEC": "python" }, "display_name": "Apache Toree - Scala", "language": "scala", "interrupt_mode": "signal", "metadata": {} }
  • 20. Apache Toree { "argv": [ ā€œ/usr/local/share/jupyter/kernels/apache_toree_scala/bin/run.sh", "--spark-context-initialization-mode", "none", "--profile", "{connection_file}" ], "env": { "DEFAULT_INTERPRETER": "Scala", "__TOREE_SPARK_OPTS__": "", "__TOREE_OPTS__": "", "SPARK_HOME": "/Users/lresende/opt/spark-3.2.2-bin-hadoop2.7/", "PYTHONPATH": ā€œ/Users/lresende/opt/spark-3.2.2-bin-hadoop2.7//python:/Users/lresende/opt/spark-3.2.2-bin-hadoop2.7/ python/lib/py4j-0.10.9.5-src.zipā€, "PYTHON_EXEC": "python" }, "display_name": "Apache Toree - Scala", "language": "scala", "interrupt_mode": "signal", "metadata": {} }
  • 21. Apache Toree { "language": "scala", "display_name": "Spark - Scala (YARN Cluster Mode)", "metadata": { "process_proxy": { "class_name": "enterprise_gateway.services.processproxies.yarn.YarnClusterProcessProxyā€ } }, "env": { "SPARK_HOME": "/usr/hdp/current/spark2-client", "__TOREE_SPARK_OPTS__": "--master yarn --deploy-mode cluster --name ${KERNEL_ID:-ERROR__NO__KERNEL_ID} --conf spark.yarn.submit.waitAppCompletion=false --conf spark.yarn.am.waitTime=1d ${KERNEL_EXTRA_SPARK_OPTS}", "__TOREE_OPTS__": "--alternate-sigint USR2", "DEFAULT_INTERPRETER": "Scala" }, "argv": [ "/usr/local/share/jupyter/kernels/spark_scala_yarn_cluster/bin/run.sh", "--RemoteProcessProxy.kernel-id", "{kernel_id}", "--RemoteProcessProxy.response-address", "{response_address}", "--RemoteProcessProxy.spark-context-initialization-mode", "lazy" ] }
  • 22. Apache Toree PROG_HOME="$(cd "`dirname "$0"`"/..; pwd)" if [ -z "$SPARK_HOME" ]; then echo "SPARK_HOME must be set to the location of a Spark distribution!" exit 1 fi echo "Starting Spark Kernel with SPARK_HOME=$SPARK_HOME" KERNEL_ASSEMBLY=`(cd ${PROG_HOME}/lib; ls -1 toree-assembly-*.jar;)` # disable randomized hash for string in Python 3.3+ TOREE_ASSEMBLY=${PROG_HOME}/lib/${KERNEL_ASSEMBLY} eval exec "${SPARK_HOME}/bin/spark-submit" --name "'Apache Toree'" "${SPARK_OPTS}" --class org.apache.toree.Main "${TOREE_ASSEMBLY}" "${TOREE_OPTS}" "$@"
  • 23. Apache Toree Architectural Diagram Apache Toree running as an Apache Spark application in client mode Bob Alice ō€‰© JupyterLab jupyter client Application Apache Toree Driver Spark Context Apache Spark Cluster Worker Executor Worker Executor Worker Executor Cluster Manager 0MQ IPython Kernel protocol
  • 24. Jupyter Notebooks Stack Limitation Scalability • Jupyter Kernels running as local process • Resources are limited by what is available on the one single node that runs all Kernels and associated Spark drivers Security • Single user sharing the same privileges • Users can see and control each other process using Jupyter administrative utilities Maximum Number of Simultaneous Kernels Max Kernels (4GB Heap) 0 10 20 Cluster Size (32GB Nodes) 4 Nodes 8 Nodes 12 Nodes 16 Nodes ō€Ŗ¬ō€Ŗ¬ō€Ŗ¬ō€Ŗ¬ō€Ŗ¬ō€Ŗ¬ Cloud Cluster ō€Ŗ¬ k Kernel k k
  • 25. YARN Workers Apache Toree Architectural Diagram Apache Toree running as an Apache Spark application in cluster mode YARN Cluster Gateway Edge Node Bob Alice Jupyter Enterprise Gateway • Multitenancy • Remote kernel lifecycle management Spark Executors Spark Executors Spark Executors Yarn Container Toree Kernel Spark Driver Spark Executors Spark Executors Spark Executors Yarn Container Toree Kernel Spark Driver Impersonation: Alice’s kernel runs under Alice’s user ID. Spark Executors Spark Executors Spark Executors Yarn Container Toree Kernel Spark Driver Security Layer ō€‰©ō€Š JupyterLab Jupyter Notebook (local)
  • 27. Apache Toree, via extensions like Brunel for Apache Toree or Plotly for Scala, supports rich visualizations that integrates directly with Spark Data Frame APIs Notes: Brunel seems to be broken with Spark 3.2.2 (from previous 2.x/3.0.x) Plotly seems to have a dependency issue (https://github.com/ alexarchambault/plotly-scala/issues/14) Apache Toree Visualizations
  • 28. Apache Toree provides a set of magics that enhances the user experience manipulating data coming from Spark tables or data Apache Toree Visualizations
  • 30. Apache Toree Accessing Toree programmatically using Scala Torre Client APIs https://github.com/lresende/toree- gateway/blob/v1.0/src/main/scala/ org/apache/toree/gateway/ ToreeGateway.scala object ToreeGatewayClient extends App { // Parse our configuration and create a client connecting to our kernel val configFileContent = scala.io.Source.fromFile(ā€œconfig.jsonā€).mkString val config: Config = ConfigFactory.parseString(configFileContent) val client = (new ClientBootstrap(config) with StandardSystemInitialization with StandardHandlerInitialization).createClient() … val promise = Promise[String] try { val exRes: DeferredExecution = client.execute(ā€œ1+1ā€) .onResult(executeResult => { handleResult(promise, executeResult) }).onError(executeReplyError =>{ handleError(promise, executeReplyError) }).onSuccess(executeReplyOk => { handleSuccess(promise, executeReplyOk) }).onStream(streamResult => { handleStream(promise, streamResult) }) } catch { case t : Throwable => { log.info("Error submitting request: " + t.getMessage, t) promise.success("Error submitting request: " + t.getMessage) } } Await.result(promise.future, Duration.Inf) }
  • 31. Apache Toree Accessing Toree programmatically using Python Jupyter Client package https://github.com/lresende/toree- gateway/blob/master/python/ toree_client.py self.client = BlockingKernelClient(connection_file=connectionFileLocation) self.client.load_connection_file(connection_file=connectionFil eLocation) … msg_id = self.client.execute(code=ā€˜1+1’, allow_stdin=False) reply = self.client.get_shell_msg(block=True, timeout=timeout) results = [] while True: try: msg = self.client.get_iopub_msg(timeout=timeout) except: raise Exception("Error: Timeout executing request") # Stream results are being returned, accumulate them to results if msg['msg_type'] == 'stream': type = 'stream' results.append(msg['content']['text']) continue elif msg['msg_type'] == 'execute_result’: if 'text/plain' in msg['content']['data']: type = 'text' results.append(msg['content']['data']['text/ plain']) elif 'text/html' in msg['content']['data']: # When idle, responses have all been processed/returned elif msg['msg_type'] == 'status’: if msg['content']['execution_state'] == 'idle': break if reply['content']['status'] == 'ok’: return ''.join(results)
  • 32. Apache Toree Accessing Toree programmatically using Jupyter Enterprise Gateway GatewayClient https://github.com/jupyter-server/ enterprise_gateway/tree/master/ enterprise_gateway/client # initialize environment gatewayClient = GatewayClient() kernel = gatewayClient.start_kernel(ā€˜toree- kernelspec’) … result = self.kernel.execute(ā€1+1") … # shutdown environment gatewayClient.shutdown_kernel(cls.kernel)
  • 33. Demo
  • 34. Apache Toree: Join the Community
  • 35. Contribute to Apache Toree Roadmap suggestions for contributors • Decouple plain Scala kernel from Spark • Enhance startup performance • Evaluate/Implement better async/parallelism framework • Progress bar for Spark Jobs • Spark 3.x and Scala 2.13 • Help with documentation and website enhancements
  • 36. Apache Toree https://toree.apache.org Apache Toree Mailing List [email protected] Apache Toree source code at GitHub https://github.com/apache/incubator-toree ō€‹‚ Star and fork the project on Github Apache Toree Resources Apache Toree 0.5.0 - incubating pip install -upgrade toree