Skip to content

Commit ecd3380

Browse files
Hudi sink for Python (#141)
Co-authored-by: Gagan Brahmi <[email protected]>
1 parent 51572c8 commit ecd3380

File tree

7 files changed

+1027
-0
lines changed

7 files changed

+1027
-0
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,7 @@ Example applications in Java, Python, Scala and SQL for Amazon Managed Service f
6060
- [**S3 Sink**](./python/S3Sink) - Writing data to Amazon S3 using PyFlink
6161
- [**Firehose Sink**](./python/FirehoseSink) - Writing data to Amazon Kinesis Data Firehose
6262
- [**Iceberg Sink**](./python/IcebergSink) - Writing data to Apache Iceberg tables
63+
- [**Hudi Sink**](./python/HudiSink) - Writing data to Apache Hudi tables
6364

6465
#### Stream Processing Patterns
6566
- [**Windowing**](./python/Windowing) - Time-based window aggregation examples with PyFlink/SQL

python/HudiSink/.gitignore

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
# Maven build artifacts
2+
target/
3+
dependency-reduced-pom.xml
4+
5+
# Python cache
6+
__pycache__/
7+
*.pyc
8+
*.pyo
9+
10+
# IDE files
11+
.idea/
12+
.vscode/
13+
*.swp
14+
*.swo
15+
16+
# OS files
17+
.DS_Store
18+
Thumbs.db
19+
20+
# Log files
21+
*.log
22+
23+
# Temporary files
24+
*.tmp
25+
*.temp
26+
27+
# Deployment configuration files
28+
update-config.json

python/HudiSink/README.md

Lines changed: 265 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,265 @@
1+
## Example of writing to Apache Hudi with PyFlink
2+
3+
Example showing a PyFlink application writing to Hudi table in S3.
4+
5+
* Flink version: 1.20
6+
* Flink API: Table API & SQL
7+
* Flink Connectors: Apache Hudi & Flink S3
8+
* Language: Python
9+
10+
This application demonstrates setting up Apache Hudi table as sink.
11+
12+
The application is written in Python, but operators are defined using SQL. This is a popular way of defining applications in PyFlink, but not the only one. You could attain the same results using Table API ar DataStream API, in Python.
13+
14+
The job can run both on Amazon Managed Service for Apache Flink, and locally for development.
15+
---
16+
17+
### Dependency Management
18+
19+
This project uses Maven Shade Plugin with extensive exclusions to handle dependency conflicts and optimize the application size. The Hudi connector requires careful dependency management due to its complex ecosystem.
20+
21+
---
22+
23+
## Excluded Java Versions in maven-shade-plugin
24+
25+
Apache Flink 1.20 [only supports Java 11 as non-experimental](https://nightlies.apache.org/flink/flink-docs-release-1.20/docs/deployment/java_compatibility/).
26+
Amazon Managed Service for Apache Flink currently runs on Java 11.
27+
Any Java code must be compiled with a target java version 11.
28+
29+
We have excluded certain Java versions to avoid errors caused by [multi-release JARs](https://openjdk.org/jeps/238) where the META-INF/versions/XX directories contain **Java version-specific class files**.
30+
31+
Example: A dependency might include optimized code for Java 21+ in META-INF/versions/21/....
32+
33+
### Why Exclude Specific Versions
34+
35+
* Avoid Compatibility Issues - If you include JAR dependencies compiled for Java 21/22 you may face errors like *java.lang.UnsupportedClassVersionError: Unsupported major.minor version 65*
36+
* Prevent Conflicts - Some libraries include multi-release JARs that conflict with Flink's dependencies when merged into a fat JAR.
37+
38+
### Requirements
39+
40+
#### Development and build environment requirements
41+
42+
* Python 3.11
43+
* PyFlink library: `apache-flink==1.20.0`
44+
* Java JDK 11+ and Maven
45+
46+
> ⚠️ As of 2024-06-27, the Flink Python library 1.19.x may fail installing on Python 3.12.
47+
> We recommend using Python 3.11 for development, the same Python version used by Amazon Managed Service for Apache Flink
48+
> runtime 1.20.
49+
50+
> JDK and Maven are used to download and package any required Flink dependencies, e.g. connectors, and
51+
to package the application as `.zip` file, for deployment to Amazon Managed Service for Apache Flink.
52+
53+
> This code has been tested and compiled using OpenJDK 11.0.22 and Maven 3.9.6
54+
55+
#### External dependencies
56+
57+
The application requires Amazon S3 bucket to write the Hudi table data. The application needs appropriate permissions for Amazon S3 as [discussed below](#iam-permissions).
58+
59+
The target Hudi table parameters are defined in the configuration (see [below](#runtime-configuration)).
60+
61+
> **Local Development**: When running locally with `IS_LOCAL=true`, no external dependencies are required as the application uses local filesystem storage.
62+
63+
#### IAM permissions
64+
65+
The application must have sufficient permissions to read and write to Amazon S3 bucket where Hudi table data and metadata will be stored.
66+
67+
> **Local Development**: When running locally with `IS_LOCAL=true`, no AWS credentials or IAM permissions are required as the application uses local filesystem storage.
68+
69+
### Runtime configuration
70+
71+
* **Local development**: uses the local file [application_properties.json](./application_properties.json) - **Edit the file with your Hudi table details which includes warehouse location, database name, table name, and AWS region**
72+
* **On Amazon Managed Service for Apache Fink**: define Runtime Properties, using Group ID and property names based on the content of [application_properties.json](./application_properties.json)
73+
74+
For this application, the configuration properties to specify are:
75+
76+
Runtime parameters:
77+
78+
| Group ID | Key | Mandatory | Example Value (default for local) | Notes |
79+
|-----------------|-----------------|-----------|-----------------------------------|--------------------------------------------------|
80+
| `HudiTable0` | `catalog.name` | Y | `glue_catalog` | Catalog name (used for configuration consistency, not for Glue integration) |
81+
| `HudiTable0` | `warehouse.path`| Y | `s3a://my_bucket/my_warehouse` | Warehouse path for Hudi table. **Important** - Use `s3a://` protocol |
82+
| `HudiTable0` | `database.name` | Y | `my_database` | Database name for Hudi table |
83+
| `HudiTable0` | `table.name` | Y | `my_table` | Table name to write the data |
84+
| `HudiTable0` | `aws.region` | Y | `us-east-1` | AWS region for S3A filesystem configuration (used in production, ignored in local mode). |
85+
86+
87+
In addition to these configuration properties, when running a PyFlink application in Managed Flink you need to set two
88+
[Additional configuring for PyFink application on Managed Flink](#additional-configuring-for-pyfink-application-on-managed-flink).
89+
90+
> If you forget to edit the local `application_properties.json` configuration to point your Hudi table and warehouse path, the application will fail to start locally.
91+
92+
#### Additional configuring for PyFink application on Managed Flink
93+
94+
To tell Managed Flink what Python script to run and the fat-jar containing all dependencies, you need to specific some
95+
additional Runtime Properties, as part of the application configuration:
96+
97+
| Group ID | Key | Mandatory | Value | Notes |
98+
|---------------------------------------|-----------|-----------|--------------------------------|---------------------------------------------------------------------------|
99+
| `kinesis.analytics.flink.run.options` | `python` | Y | `main.py` | The Python script containing the main() method to start the job. |
100+
| `kinesis.analytics.flink.run.options` | `jarfile` | Y | `lib/pyflink-dependencies.jar` | Location (inside the zip) of the fat-jar containing all jar dependencies. |
101+
102+
> ⚠️ If you forget adding these parameters to the Runtime properties, the application will not start.
103+
---
104+
105+
### How to run and build the application
106+
107+
#### Local development - in the IDE
108+
109+
1. Run `mvn package` once, from this directory. This step is required to download the jar dependencies - the Hudi connector in this case
110+
2. Set the environment variable `IS_LOCAL=true`. You can do from the prompt or in the run profile of the IDE
111+
3. Run `main.py`
112+
113+
> **Note for Local Development**: When running locally with `IS_LOCAL=true`, the application automatically uses a local filesystem instead of S3 to avoid AWS credential requirements. The Hudi table will be created in a temporary directory on your local machine. This allows for easy testing without needing AWS credentials or S3 access.
114+
>
115+
> **Why HudiSink requires local filesystem for testing**: Unlike some other connectors, Hudi requires AWS credentials even during table creation because it needs to check if the table already exists by reading metadata from S3 (specifically the `.hoodie/hoodie.properties` file). This happens before any data is written. To provide a simple local testing experience, HudiSink automatically switches to local filesystem when `IS_LOCAL=true` is set.
116+
117+
You can also run the python script directly from the command line, like `IS_LOCAL=true python main.py`. This still require running `mvn package` before.
118+
119+
If you are using Virtual Environments, make sure the to select the venv as a runtime in your IDE.
120+
121+
If you forget the set the environment variable `IS_LOCAL=true` or forget to run `mvn package` the application fails on start.
122+
123+
> 🚨 The application does not log or print anything.
124+
> If you do not see any output in the console, it does not mean the application is not running.
125+
> The output is sent to the Hudi table. You can inspect the content of the table using Amazon Athena or Trino/Spark on EMR.
126+
127+
Note: if you modify the Python code, you do not need to re-run `mvn package` before running the application locally.
128+
129+
##### Troubleshooting the application when running locally
130+
131+
By default, the PyFlink application running locally does not send logs to the console.
132+
Any exception thrown by the Flink runtime (i.e. not due to Python error) will not appear in the console.
133+
The application may appear to be running, but actually continuously failing and restarting.
134+
135+
To see any error messages, you need to inspect the Flink logs.
136+
By default, PyFlink will send logs to the directory where the PyFlink module is installed (Flink home).
137+
Use this command to find the directory:
138+
139+
```
140+
$ python -c "import pyflink;import os;print(os.path.dirname(os.path.abspath(pyflink.__file__))+'/log')"
141+
```
142+
143+
144+
#### Deploy and run on Amazon Managed Service for Apache Flink
145+
146+
1. Make sure you have the S3 bucket location for Hudi warehouse path
147+
2. Create a Managed Flink application
148+
3. Modify the application IAM role to allow writing to S3 location for the Hudi table
149+
4. Package the application: run `mvn clean package` from this directory
150+
5. Upload to an S3 bucket the zip file that the previous creates in the [`./target`](./target) subdirectory
151+
6. Configure the Managed Flink application: set Application Code Location to the bucket and zip file you just uploaded
152+
7. Configure the Runtime Properties of the application, creating the Group ID, Keys and Values as defined in the [application_properties.json](./application_properties.json)
153+
8. Start the application
154+
9. When the application transitions to "Ready" you can open the Flink Dashboard to verify the job is running, and you can inspect the data published to the Hudi table using S3 directly or query tools like Athena or Trino/Spark on EMR.
155+
156+
##### Troubleshooting Python errors when the application runs on Amazon Managed Service for Apache Flink
157+
158+
Amazon Managed Service for Apache Flink sends all logs to CloudWatch Logs.
159+
You can find the name of the Log Group and Log Stream in the configuration of the application, in the console.
160+
161+
Errors caused by the Flink engine are usually logged as `ERROR` and easy to find. However, errors reported by the Python
162+
runtime are **not** logged as `ERROR`.
163+
164+
Apache Flink logs any entry reported by the Python runtime using a logger named `org.apache.flink.client.python.PythonDriver`.
165+
166+
The easiest way to find errors reported by Python is using CloudWatch Insight, and run the following query:
167+
168+
```
169+
fields @timestamp, message
170+
| sort @timestamp asc
171+
| filter logger like /PythonDriver/
172+
| limit 1000
173+
```
174+
175+
> 🚨 If the Flink jobs fails to start due to an error reported by Python, for example a missing expected configuration
176+
> parameters, the Amazon Managed Service for Apache Flink may report as *Running* but the job fails to start.
177+
> You can check whether the job is actually running using the Apache Flink Dashboard. If the job is not listed in the
178+
> Running Job List, it means it probably failed to start due to an error.
179+
>
180+
> In CloudWatch Logs you may find an `ERROR` entry with not very explanatory message "Run python process failed".
181+
> To find the actual cause of the problem, run the CloudWatch Insight above, to see the actual error reported by
182+
> the Python runtime.
183+
184+
185+
#### Publishing code changes to Amazon Managed Service for Apache Flink
186+
187+
Follow this process to make changes to the Python code
188+
189+
1. Modify the code locally (test/run locally, as required)
190+
2. Re-run `mvn clean package` - **if you skip this step, the zipfile is not updated**, and contains the old Python script.
191+
3. Upload the new zip file to the same location on S3 (overwriting the previous zip file)
192+
4. In the Managed Flink application console, enter *Configure*, scroll down and press *Save Changes*
193+
* If your application was running when you published the change, Managed Flink stops the application and restarts it with the new code
194+
* If the application was not running (in Ready state) you need to click *Run* to restart it with the new code
195+
196+
> 🚨 by design, Managed Flink does not detect the new zip file automatically.
197+
> You control when you want to restart the application with the code changes. This is done saving a new configuration from the
198+
> console or using the [*UpdateApplication*](https://docs.aws.amazon.com/managed-flink/latest/apiv2/API_UpdateApplication.html)
199+
> API.
200+
201+
---
202+
203+
### Local Development vs Production Differences
204+
205+
#### Why HudiSink uses local filesystem for local testing
206+
207+
**The Challenge:**
208+
Unlike other connectors (like IcebergSink), Apache Hudi requires immediate access to storage during table creation to:
209+
210+
1. **Check existing table metadata**: Hudi reads `.hoodie/hoodie.properties` from the target path to determine if a table already exists
211+
2. **Validate table schema**: Hudi needs to verify schema compatibility with existing tables
212+
3. **Initialize table metadata**: Even for new tables, Hudi immediately writes metadata files
213+
214+
**Technical Details:**
215+
- **Hudi Behavior**: Calls `StreamerUtil.getTableConfig()` during table creation, which immediately tries to read from S3
216+
- **Error without credentials**: `org.apache.hudi.exception.HoodieIOException: Get table config error` occurs when AWS credentials are not available
217+
218+
**Our Solution:**
219+
The application includes smart protocol handling:
220+
- **Auto-converts `s3://` to `s3a://`**: If you accidentally configure `s3://` in your properties, the application automatically converts it to `s3a://` (required by Hudi)
221+
- **Local development override**: When `IS_LOCAL=true` is set, automatically switches to `file://` protocol using a temporary local directory
222+
- **Maintains identical Hudi functionality**: All Hudi features work the same way in local testing
223+
- **Eliminates AWS credential requirements**: No AWS setup needed for local development
224+
225+
**Alternative Approaches:**
226+
If you prefer to test with actual S3 access locally, you can:
227+
1. Configure AWS credentials (`aws configure` or environment variables)
228+
2. Remove the local filesystem override in `main.py`
229+
3. Ensure your AWS credentials have S3 permissions
230+
231+
---
232+
233+
### Application structure
234+
235+
The application generates synthetic data using the [DataGen](https://nightlies.apache.org/flink/flink-docs-release-1.20/docs/connectors/table/datagen/) connector.
236+
No external data generator is required.
237+
238+
Generated records are written to a destination Hudi table with data stored in S3.
239+
240+
Data format is Parquet, and partitioning is by the `sensor_id`.
241+
242+
Note that the Hudi connector writes to S3 on checkpoint. For this reason, when running locally checkpoint is set up programmatically by the application every minute. When deployed on Amazon Managed Service for Apache Flink, the checkpoint
243+
configuration is configured as part of the Managed Flink application configuration. By default, it's every minute.
244+
245+
If you disable checkpoints (or forget to set it up when running locally) the application runs but never writes any data to S3.
246+
247+
---
248+
249+
### Application packaging and dependencies
250+
251+
This examples also demonstrate how to include jar dependencies - e.g. connectors - in a PyFlink application, and how to
252+
package it, for deploying on Amazon Managed Service for Apache Flink.
253+
254+
Any jar dependencies must be added to the `<dependencies>` block in the [pom.xml](pom.xml) file.
255+
In this case, you can see we have included `hudi-flink-bundle`, Hadoop dependencies, and AWS SDK components for Hudi sink to work with Flink.
256+
257+
Executing `mvn package` takes care of downloading any defined dependencies and create a single "fat-jar" containing all of them.
258+
This file, is generated in the `./target` subdirectory and is called `pyflink-dependencies.jar`
259+
260+
> The `./target` directory and any generated files are not supposed to be committed to git.
261+
262+
When running locally, for example in your IDE, PyFlink will look for this jar file in `./target`.
263+
264+
When you are happy with your Python code and you are ready to deploy the application to Amazon Managed Service for Apache Flink,
265+
run `mvn package` **again**. The zip file you find in `./target` is the artifact to upload to S3, containing both jar dependencies and your Python code.
Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
[
2+
{
3+
"PropertyGroupId": "kinesis.analytics.flink.run.options",
4+
"PropertyMap": {
5+
"python": "main.py",
6+
"jarfile": "lib/pyflink-dependencies.jar"
7+
}
8+
},
9+
{
10+
"PropertyGroupId": "HudiTable0",
11+
"PropertyMap": {
12+
"catalog.name": "glue_catalog",
13+
"warehouse.path": "s3a://<bucket-name>/my_warehouse",
14+
"database.name": "my_database",
15+
"table.name": "my_table",
16+
"aws.region": "us-east-1"
17+
}
18+
}
19+
]
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3"
2+
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3+
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.3 http://maven.apache.org/xsd/assembly-1.1.3.xsd">
4+
<id>my-assembly</id>
5+
<formats>
6+
<format>zip</format>
7+
</formats>
8+
<includeBaseDirectory>false</includeBaseDirectory>
9+
<fileSets>
10+
<fileSet>
11+
<directory>${project.basedir}</directory>
12+
<outputDirectory>/</outputDirectory>
13+
<includes>
14+
<include>main.py</include>
15+
</includes>
16+
</fileSet>
17+
<fileSet>
18+
<directory>${project.build.directory}</directory>
19+
<outputDirectory>lib</outputDirectory>
20+
<includes>
21+
<include>*.jar</include>
22+
</includes>
23+
</fileSet>
24+
</fileSets>
25+
</assembly>

0 commit comments

Comments
 (0)