Working with Apache Kafka® topics using PySpark jobs in Yandex Data Processing
Yandex Data Processing clusters support integration with Managed Service for Apache Kafka® clusters. You can write and read messages to and from Apache Kafka® topics using PySpark jobs. Reading supports both batch processing and stream processing.
To configure integration between Managed Service for Apache Kafka® and Yandex Data Processing clusters:
If you no longer need the resources you created, delete them.
Getting started
Sign up for Yandex Cloud and create a billing account:
- Navigate to the management console
and log in to Yandex Cloud or create a new account. - On the Yandex Cloud Billing
page, make sure you have a billing account linked and it has theACTIVEorTRIAL_ACTIVEstatus. If you do not have a billing account, create one and link a cloud to it.
If you have an active billing account, you can create or select a folder for your infrastructure on the cloud page
Learn more about clouds and folders here.
Required paid resources
- Managed Service for Apache Kafka® cluster: use of computing resources allocated to hosts, storage and backup size (see Managed Service for Apache Kafka® pricing).
- Yandex Data Processing cluster: use of computing resources with a Yandex Data Processing markup, use of network drives, retrieval and storage of logs, amount of outgoing traffic (see Yandex Data Processing pricing).
- NAT gateway: hourly use of the gateway and its outgoing traffic (see Yandex Virtual Private Cloud pricing).
- Yandex Object Storage bucket: use of storage, data operations (see Object Storage pricing).
Set up your infrastructure
-
Create a cloud network named
dataproc-network, without subnets. -
Create a subnet named
dataproc-subnet-bin theru-central1-bavailability zone. -
Set up a NAT gateway for
dataproc-subnet-b. -
Create a security group named
dataproc-security-groupindataproc-network. -
Create a service account named
dataproc-sawith the following roles:storage.viewerstorage.uploaderdataproc.agentdataproc.user
-
Create a bucket with a unique name within Object Storage.
-
Grant the
FULL_CONTROLpermission for the new bucket to thedataproc-saservice account. -
Create a Yandex Data Processing cluster with the following parameters:
-
Cluster name:
dataproc-cluster. -
Environment:
PRODUCTION. -
Version:
2.1. -
Services:
HDFSLIVYSPARKTEZYARN
-
Service account:
dataproc-sa. -
Availability zone:
ru-central1-b. -
Bucket name: Name of the new bucket.
-
Network:
dataproc-network. -
Security groups:
dataproc-security-group. -
Subclusters: Master, one subcluster named
Dataand one subcluster namedCompute.
-
-
Create a Managed Service for Apache Kafka® cluster with the following parameters:
- Cluster name:
dataproc-kafka. - Environment:
PRODUCTION. - Version:
3.5. - Availability zone:
ru-central1-b. - Network:
dataproc-network. - Security groups:
dataproc-security-group. - Subnet:
dataproc-subnet-b.
- Cluster name:
-
Create an Apache Kafka® topic with the following parameters:
- Name:
dataproc-kafka-topic. - Number of partitions:
1. - Replication factor:
1.
- Name:
-
Create an Apache Kafka® user with the following parameters:
- Name:
user1. - Password:
password1. - Topics the user gets permissions for:
*(all topics). - Permissions for the topics:
ACCESS_ROLE_CONSUMER,ACCESS_ROLE_PRODUCER, andACCESS_ROLE_ADMIN.
- Name:
-
If you do not have Terraform yet, install it.
-
Get the authentication credentials. You can add them to environment variables or specify them later in the provider configuration file.
-
Configure and initialize a provider. There is no need to create a provider configuration file manually, you can download it
. -
Place the configuration file in a separate working directory and specify the parameter values. If you did not add the authentication credentials to environment variables, specify them in the configuration file.
-
Download the kafka-and-data-proc.tf
configuration file to the same working directory.This file describes:
- Network.
- NAT gateway and route table required for Yandex Data Processing.
- Subnet.
- Security group for the Yandex Data Processing and Managed Service for Apache Kafka® clusters.
- Service account for the Yandex Data Processing cluster.
- Service account for managing the Yandex Object Storage bucket.
- Yandex Object Storage bucket.
- Static access key required to grant the service account permissions for the bucket.
- Yandex Data Processing cluster.
- Managed Service for Apache Kafka® cluster.
- Apache Kafka® user.
- Apache Kafka® topic.
-
In
kafka-and-data-proc.tf, specify the following:folder_id: Cloud folder ID, same as in the provider settings.dp_ssh_key: Absolute path to the public key for the Yandex Data Processing cluster. Learn more about connecting to a Yandex Data Processing host over SSH here.
-
Make sure the Terraform configuration files are correct using this command:
terraform validateTerraform will display any configuration errors detected in your files.
-
Create the required infrastructure:
-
Run this command to view the planned changes:
terraform planIf you described the configuration correctly, the terminal will display a list of the resources to update and their parameters. This is a verification step that does not apply changes to your resources.
-
If everything looks correct, apply the changes:
-
Run this command:
terraform apply -
Confirm updating the resources.
-
Wait for the operation to complete.
-
All the required resources will be created in the specified folder. You can check resource availability and their settings in the management console
. -
Create PySpark jobs
-
On your local computer, save the following scripts:
kafka-write.pyScript for writing messages to an Apache Kafka® topic:
#!/usr/bin/env python3 from pyspark.sql import SparkSession, Row from pyspark.sql.functions import to_json, col, struct def main(): spark = SparkSession.builder.appName("dataproc-kafka-write-app").getOrCreate() df = spark.createDataFrame([ Row(msg="Test message #1 from dataproc-cluster"), Row(msg="Test message #2 from dataproc-cluster") ]) df = df.select(to_json(struct([col(c).alias(c) for c in df.columns])).alias('value')) df.write.format("kafka") \ .option("kafka.bootstrap.servers", "<host_FQDN>:9091") \ .option("topic", "dataproc-kafka-topic") \ .option("kafka.security.protocol", "SASL_SSL") \ .option("kafka.sasl.mechanism", "SCRAM-SHA-512") \ .option("kafka.sasl.jaas.config", "org.apache.kafka.common.security.scram.ScramLoginModule required " "username=user1 " "password=password1 " ";") \ .save() if __name__ == "__main__": main()kafka-read-batch.pyScript for reading from a topic and batch processing:
#!/usr/bin/env python3 from pyspark.sql import SparkSession, Row from pyspark.sql.functions import to_json, col, struct def main(): spark = SparkSession.builder.appName("dataproc-kafka-read-batch-app").getOrCreate() df = spark.read.format("kafka") \ .option("kafka.bootstrap.servers", "<host_FQDN>:9091") \ .option("subscribe", "dataproc-kafka-topic") \ .option("kafka.security.protocol", "SASL_SSL") \ .option("kafka.sasl.mechanism", "SCRAM-SHA-512") \ .option("kafka.sasl.jaas.config", "org.apache.kafka.common.security.scram.ScramLoginModule required " "username=user1 " "password=password1 " ";") \ .option("startingOffsets", "earliest") \ .load() \ .selectExpr("CAST(value AS STRING)") \ .where(col("value").isNotNull()) df.write.format("text").save("s3a://<new_bucket_name>/kafka-read-batch-output") if __name__ == "__main__": main()kafka-read-stream.pyScript for reading from a topic and stream processing:
#!/usr/bin/env python3 from pyspark.sql import SparkSession, Row from pyspark.sql.functions import to_json, col, struct def main(): spark = SparkSession.builder.appName("dataproc-kafka-read-stream-app").getOrCreate() query = spark.readStream.format("kafka")\ .option("kafka.bootstrap.servers", "<host_FQDN>:9091") \ .option("subscribe", "dataproc-kafka-topic") \ .option("kafka.security.protocol", "SASL_SSL") \ .option("kafka.sasl.mechanism", "SCRAM-SHA-512") \ .option("kafka.sasl.jaas.config", "org.apache.kafka.common.security.scram.ScramLoginModule required " "username=user1 " "password=password1 " ";") \ .option("startingOffsets", "earliest")\ .load()\ .selectExpr("CAST(value AS STRING)")\ .where(col("value").isNotNull())\ .writeStream\ .trigger(once=True)\ .queryName("received_messages")\ .format("memory")\ .start() query.awaitTermination() df = spark.sql("select value from received_messages") df.write.format("text").save("s3a://<new_bucket_name>/kafka-read-stream-output") if __name__ == "__main__": main() -
Get the Apache Kafka® host FQDN and specify it in each script.
-
Upload the prepared scripts to the bucket root.
-
Create a PySpark job for writing a message to the Apache Kafka® topic. In the Main python file field, specify the script path:
s3a://<new_bucket_name>/kafka-write.py. -
Wait for the job status to change to
Done. -
Make sure the data is successfully written to the topic. To do this, create a new PySpark job for reading data from the topic and batch processing. In the Main python file field, specify the script path:
s3a://<new_bucket_name>/kafka-read-batch.py. -
Wait for the new job status to change to
Done. -
Download the file with the read data from the bucket:
part-00000
{"msg":"Test message #1 from dataproc-cluster"} {"msg":"Test message #2 from dataproc-cluster"}The file resides in the new folder named
kafka-read-batch-outputin the bucket. -
Read messages from the topic during stream processing. To do this, create another PySpark job. In the Main python file field, specify the script path:
s3a://<new_bucket_name>/kafka-read-stream.py. -
Wait for the new job status to change to
Done. -
Download the files with the read data from the bucket:
part-00000
{"msg":"Test message #1 from dataproc-cluster"}part-00001
{"msg":"Test message #2 from dataproc-cluster"}The files reside in the new folder named
kafka-read-stream-outputin the bucket.
Note
You can view the job logs and search data in them using Yandex Cloud Logging. For more information, see Working with logs.
Delete the resources you created
Some resources are not free of charge. Delete the resources you no longer need to avoid paying for them:
-
Delete the objects from the bucket.
-
Delete the rest of the resources depending on how you created them:
ManuallyTerraform-
In the terminal window, go to the directory containing the infrastructure plan.
Warning
Make sure the directory has no Terraform manifests with the resources you want to keep. Terraform deletes all resources that were created using the manifests in the current directory.
-
Delete resources:
-
Run this command:
terraform destroy -
Confirm deleting the resources and wait for the operation to complete.
All the resources described in the Terraform manifests will be deleted.
-
-