Metadata-Version: 2.4
Name: sparkmonitor
Version: 3.2.0
Dynamic: Keywords
Summary: Jupyter Notebook & Lab extension to monitor Apache Spark jobs from a notebook
Project-URL: Homepage, https://github.com/swan-cern/sparkmonitor
Project-URL: Bug Tracker, https://github.com/swan-cern/sparkmonitor/issues
Project-URL: Repository, https://github.com/swan-cern/sparkmonitor.git
Author-email: Krishnan R <krishnanr1997@gmail.com>
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship, whether in Source or
              Object form, made available under the License, as indicated by a
              copyright notice that is included in or attached to the work
              (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and Derivative Works thereof.
        
              "Contribution" shall mean any work of authorship, including
              the original version of the Work and any modifications or additions
              to that Work or Derivative Works thereof, that is intentionally
              submitted to Licensor for inclusion in the Work by the copyright owner
              or by an individual or Legal Entity authorized to submit on behalf of
              the copyright owner. For the purposes of this definition, "submitted"
              means any form of electronic, verbal, or written communication sent
              to the Licensor or its representatives, including but not limited to
              communication on electronic mailing lists, source code control systems,
              and issue tracking systems that are managed by, or on behalf of, the
              Licensor for the purpose of discussing and improving the Work, but
              excluding communication that is conspicuously marked or otherwise
              designated in writing by the copyright owner as "Not a Contribution."
        
              "Contributor" shall mean Licensor and any individual or Legal Entity
              on behalf of whom a Contribution has been received by Licensor and
              subsequently incorporated within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a
              cross-claim or counterclaim in a lawsuit) alleging that the Work
              or a Contribution incorporated within the Work constitutes direct
              or contributory patent infringement, then any patent licenses
              granted to You under this License for that Work shall terminate
              as of the date such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or
                  Derivative Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" text file as part of its
                  distribution, then any Derivative Works that You distribute must
                  include a readable copy of the attribution notices contained
                  within such NOTICE file, excluding those notices that do not
                  pertain to any part of the Derivative Works, in at least one
                  of the following places: within a NOTICE text file distributed
                  as part of the Derivative Works; within the Source form or
                  documentation, if provided along with the Derivative Works; or,
                  within a display generated by the Derivative Works, if and
                  wherever such third-party notices normally appear. The contents
                  of the NOTICE file are for informational purposes only and
                  do not modify the License. You may add Your own attribution
                  notices within Derivative Works that You distribute, alongside
                  or as an addendum to the NOTICE text from the Work, provided
                  that such additional attribution notices cannot be construed
                  as modifying the License.
        
              You may add Your own copyright statement to Your modifications and
              may provide additional or different license terms and conditions
              for use, reproduction, or distribution of Your modifications, or
              for any such Derivative Works as a whole, provided Your use,
              reproduction, and distribution of the Work otherwise complies with
              the conditions stated in this License.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any warranties or conditions
              of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
              PARTICULAR PURPOSE. You are solely responsible for determining the
              appropriateness of using or redistributing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or consequential damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or any and all
              other commercial damages or losses), even if such Contributor
              has been advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           APPENDIX: How to apply the Apache License to your work.
        
              To apply the Apache License to your work, attach the following
              boilerplate notice, with the fields enclosed by brackets "[]"
              replaced with your own identifying information. (Don't include
              the brackets!)  The text should be enclosed in the appropriate
              comment syntax for the file format. We also recommend that a
              file or class name and description of purpose be included on the
              same "printed page" as the copyright notice for easier
              identification within third-party archives.
        
           Copyright [yyyy] [name of copyright owner]
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
           See the License for the specific language governing permissions and
           limitations under the License.
License-File: LICENSE
Classifier: Framework :: Jupyter
Classifier: Framework :: Jupyter :: JupyterLab
Classifier: Framework :: Jupyter :: JupyterLab :: 4
Classifier: Framework :: Jupyter :: JupyterLab :: Extensions
Classifier: Framework :: Jupyter :: JupyterLab :: Extensions :: Prebuilt
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Requires-Python: >=3.10
Description-Content-Type: text/markdown

# SparkMonitor

SparkMonitor is a Jupyter extension for monitoring Apache Spark jobs
launched from notebooks. It displays live Spark metrics directly in the
notebook interface, making it easier to understand, debug, and profile
Spark workloads as they run.

It supports **JupyterLab** and **classic Jupyter Notebook** with
**PySpark 3.x** and **4.x**.

## About

<table>
  <tr>
    <td>
      <a href="http://jupyter.org/">
        <img
          src="https://user-images.githubusercontent.com/6822941/29750386-872556fe-8b5c-11e7-95e1-42b12d709017.png"
          height="50"
          alt="Jupyter"
        />
      </a>
    </td>
    <td><b>+</b></td>
    <td>
      <a href="https://spark.apache.org/">
        <img
          src="https://user-images.githubusercontent.com/6822941/29750352-e9807b36-8b5b-11e7-929a-249f56c7cf79.png"
          height="80"
          alt="Apache Spark"
        />
      </a>
    </td>
    <td><b>=</b></td>
    <td>
      <a
        href="https://user-images.githubusercontent.com/6822941/29601568-d5e42934-87f9-11e7-9780-3cd3a0d8d86b.png"
        title="SparkMonitor Extension"
      >
        <img
          src="https://user-images.githubusercontent.com/6822941/29601568-d5e42934-87f9-11e7-9780-3cd3a0d8d86b.png"
          height="80"
          alt="SparkMonitor"
        />
      </a>
    </td>
  </tr>
</table>

SparkMonitor adds an interactive monitoring panel below notebook cells
that trigger Spark jobs, so you can inspect execution progress without
leaving the notebook.

---

![SparkMonitor job display](https://user-images.githubusercontent.com/6822941/29753710-ff8849b6-8b94-11e7-8f9c-bdc59bf72143.gif)

## Requirements

- **Python 3.x**
- **PySpark 3.x** or **4.x**
- **JupyterLab 4.x** or **classic Jupyter Notebook 4.4.0 or later**
- **Spark Classic API mode**
  - SparkMonitor works with the traditional Spark driver model used by
    PySpark.
  - It is **not compatible** with
    [Spark Connect](https://spark.apache.org/docs/latest/spark-connect-overview.html).

## Features

- **Live monitoring** of Spark jobs launched from a notebook cell
- **Job and stage table** with progress bars and execution details
- **Timeline view** showing jobs, stages, and tasks over time
- **Resource graphs** for active tasks and executor core usage

<table>
  <tr>
    <td>
      <a
        href="https://user-images.githubusercontent.com/6822941/29601990-d6256a1e-87fb-11e7-94cb-b4418c61d221.png"
        title="Jobs and stages started from a cell"
      >
        <img
          src="https://user-images.githubusercontent.com/6822941/29601990-d6256a1e-87fb-11e7-94cb-b4418c61d221.png"
          alt="Jobs and stages view"
        />
      </a>
    </td>
    <td>
      <a
        href="https://user-images.githubusercontent.com/6822941/29601769-d8e82a26-87fa-11e7-9b0e-91b1414e7821.png"
        title="Graph of active tasks and available executor cores"
      >
        <img
          src="https://user-images.githubusercontent.com/6822941/29601769-d8e82a26-87fa-11e7-9b0e-91b1414e7821.png"
          alt="Resource graphs"
        />
      </a>
    </td>
    <td>
      <a
        href="https://user-images.githubusercontent.com/6822941/29601776-d919dae4-87fa-11e7-8939-a6c0d0072d90.png"
        title="Timeline of jobs, stages and tasks"
      >
        <img
          src="https://user-images.githubusercontent.com/6822941/29601776-d919dae4-87fa-11e7-8939-a6c0d0072d90.png"
          alt="Timeline view"
        />
      </a>
    </td>
  </tr>
</table>

## Quick Start

### Installation

Create and activate a virtual environment:

```bash
python -m venv venv
source venv/bin/activate
```

Install SparkMonitor together with PySpark and a notebook frontend.

#### For JupyterLab

```bash
pip install sparkmonitor pyspark jupyterlab
```

Enable the SparkMonitor IPython kernel extension:

```bash
ipython profile create
echo "c.InteractiveShellApp.extensions.append('sparkmonitor.kernelextension')" >> "$(ipython profile locate default)/ipython_kernel_config.py"
```

This only needs to be done once per IPython profile.

### Using SparkMonitor in a Notebook

To use SparkMonitor, create your Spark session with the SparkMonitor
listener enabled.

This requires two Spark configurations:

| Configuration                 | Purpose                                                                         |
| ----------------------------- | ------------------------------------------------------------------------------- |
| `spark.extraListeners`        | Registers the SparkMonitor listener that collects Spark job metrics             |
| `spark.driver.extraClassPath` | Points to the SparkMonitor listener JAR bundled with the `sparkmonitor` package |

### Example with a manually specified listener JAR path

If you already know the exact path to the matching SparkMonitor
listener JAR in your current environment, you can set
`spark.driver.extraClassPath` directly:

```python
from pyspark.sql import SparkSession

spark = (
    SparkSession.builder.config(
        "spark.extraListeners",
        "sparkmonitor.listener.JupyterSparkMonitorListener",
    )
    .config(
        "spark.driver.extraClassPath",
        # Put the path to the matching SparkMonitor listener JAR here.
        "venv/lib/python3.13/site-packages/sparkmonitor/listener_spark4_2.13.jar",
    )
    .getOrCreate()
)
```

### Example with automatic listener JAR detection

The most robust approach is to resolve the listener JAR path
dynamically from the installed Python package instead of hardcoding the
full environment path. The example below first checks `SPARK_HOME` and
then falls back to the `pyspark` package layout used by
`pip install pyspark`, where `SPARK_HOME` is often not set:

```python
import os
from pathlib import Path

import pyspark
import sparkmonitor
from pyspark.sql import SparkSession


def iter_spark_jar_dirs() -> list[Path]:
    candidates = []

    spark_home = os.environ.get("SPARK_HOME")
    if spark_home:
        candidates.append(Path(spark_home) / "jars")

    candidates.append(Path(pyspark.__file__).resolve().parent / "jars")
    return [path for path in candidates if path.exists()]


def resolve_listener_jar(sparkmonitor_dir: Path) -> Path:
    for jars_dir in iter_spark_jar_dirs():
        for jar in jars_dir.glob("spark-core_*.jar"):
            # spark-core_2.13-3.5.8.jar => scala=2.13, spark_major=3
            scala_ver, spark_ver = jar.name.split("_")[1].split("-")[:2]
            spark_major = spark_ver.split(".")[0]
            if spark_major == "3" and scala_ver == "2.12":
                return sparkmonitor_dir / "listener_spark3_2.12.jar"
            if spark_major == "3" and scala_ver == "2.13":
                return sparkmonitor_dir / "listener_spark3_2.13.jar"
            if spark_major == "4" and scala_ver == "2.13":
                return sparkmonitor_dir / "listener_spark4_2.13.jar"

    raise RuntimeError(
        "Could not detect Spark/Scala version from SPARK_HOME or the pyspark installation"
    )


sparkmonitor_dir = Path(sparkmonitor.__file__).resolve().parent
listener_jar = resolve_listener_jar(sparkmonitor_dir)

spark = (
    SparkSession.builder.config(
        "spark.extraListeners",
        "sparkmonitor.listener.JupyterSparkMonitorListener",
    )
    .config("spark.driver.extraClassPath", str(listener_jar))
    .getOrCreate()
)
```

> **Important**
>
> The correct listener JAR depends on:
>
> - the location of your Python environment
> - your Spark major version and Scala version
> - how Spark is installed (`SPARK_HOME` vs `pip install pyspark`)

You can inspect the installed package location with:

```python
import sparkmonitor

print(sparkmonitor.__path__)
```

Then locate the corresponding listener JAR in that package directory:

- `listener_spark3_2.12.jar` for Spark 3 + Scala 2.12
- `listener_spark3_2.13.jar` for Spark 3 + Scala 2.13
- `listener_spark4_2.13.jar` for Spark 4 + Scala 2.13

If needed, you can also build the listener JAR yourself with `sbt`, as
described in the development section below.

## Development

To work on SparkMonitor locally:

```bash
# Install the package in editable mode
pip install -e .

# Build the frontend (see package.json for available scripts)
yarn run build:<action>

# Link the JupyterLab extension into your local Jupyter environment
jupyter labextension develop --overwrite .

# Watch frontend files for changes
yarn run watch

# Build the Spark listener JARs
cd scalalistener_spark3 # Spark 3 / Scala 2.12 and 2.13
sbt +package

cd ../scalalistener_spark4 # Spark 4 / Scala 2.13
sbt package
```

## Troubleshooting

### SparkMonitor panel does not appear

Check the following:

- `sparkmonitor` is installed in the same Python environment as your
  notebook kernel
- `pyspark` is installed
- `jupyterlab` or `notebook` is installed
- the IPython kernel extension is enabled
- your Spark session includes `spark.extraListeners`
- `spark.driver.extraClassPath` points to a valid listener JAR
- you are using Spark Classic, not Spark Connect

### Wrong listener JAR selected

The listener JAR must match both your Spark major version and Scala
version:

```text
Spark 3 + Scala 2.12 -> listener_spark3_2.12.jar
Spark 3 + Scala 2.13 -> listener_spark3_2.13.jar
Spark 4 + Scala 2.13 -> listener_spark4_2.13.jar
```

Using the wrong listener JAR may prevent the listener from loading correctly.

### Hardcoded virtual environment path does not work

Avoid hardcoding paths when possible. Environment-specific paths vary
across systems, Python versions, and virtual environments. The dynamic
path resolution example above is usually more portable.

### `SPARK_HOME` is not set

This is expected in some setups, especially when Spark comes from
`pip install pyspark`. In that case, use the `pyspark` package location
to find the bundled Spark JARs instead of assuming `SPARK_HOME/jars`
exists.

## Project History

- The first version of SparkMonitor was written by krishnan-r as a
  [Google Summer of Code project](https://github.com/krishnan-r/sparkmonitor)
  with the [SWAN](https://swan.web.cern.ch/swan/) Notebook Service team
  at [CERN](http://home.cern/).
- Further fixes and improvements were made by the CERN team and
  community contributors in
  [swan-cern/jupyter-extensions/tree/master/SparkMonitor](https://github.com/swan-cern/jupyter-extensions/tree/master/SparkMonitor).
- [Jafer Haider](https://github.com/itsjafer) updated the extension for
  JupyterLab during an internship at Yelp.
- Work from the
  [jupyterlab-sparkmonitor](https://github.com/itsjafer/jupyterlab-sparkmonitor)
  fork was later merged into this repository so that both JupyterLab and
  Jupyter Notebook are supported from a single package.
- Ongoing maintenance and development continue through the SWAN team at
  CERN and the community.

## References

- PyPI package: [sparkmonitor](https://pypi.org/project/sparkmonitor/)
- Releases:
  [swan-cern/sparkmonitor releases](https://github.com/swan-cern/sparkmonitor/releases)
