Skip to content

Commit ebcbda7

Browse files
committed
make kafka demo script run as part of docker compose
1 parent 3e01c5a commit ebcbda7

9 files changed

Lines changed: 202 additions & 219 deletions

File tree

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
**/registry.db

‎README.md‎

Lines changed: 15 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -1,68 +1,41 @@
1-
# Feast Spark + Kafka workshop
1+
# Feast Spark + Kafka + Redis workshop
22

33
## Overview
44

5-
This workshop focuses on how to achieve a common architecture:
5+
This workshop aims to teach basic Feast concepts and walk you through focuses on how to achieve a common architecture:
66

77
TODO: add architecture diagram
88

99
- **Data sources**: Kafka + File source
1010
- **Online store**: Redis
11-
- **Use cases**: Predicting churn for drivers
11+
- **Use case**: Predicting churn for drivers
1212
- Batch scoring via offline store
1313
- Real time scoring via online store
1414

15-
We will generate a model that will predict whether a driver will churn
15+
We will generate a model that will predict whether a driver will churn.
16+
17+
## Pre-requisites
18+
This workshop assumes you have the following installed:
19+
- A local development environment that supports running Jupyter notebooks (e.g. VSCode with Jupyter plugin)
20+
- Python 3.7+
21+
- pip
22+
- Docker & Docker Compose (e.g. `brew install docker docker-compose`)
1623

1724
## Setup
1825

1926
### Docker + Kafka + Redis
20-
First, we need Docker and Docker Compose
27+
First, we install Feast with Redis support:
2128
```
22-
brew install docker docker-compose
29+
pip install "feast[redis]"
2330
```
2431

25-
We then install the requirements:
26-
```
27-
pip install -r requirements.txt
28-
```
29-
30-
We then spin up a local Kafka cluster that generates events into a topic.
32+
We then use Docker Compose to spin up a local Kafka cluster and automatically publish events to it.
33+
- This leverages a script (in `kafka_demo/`) that creates a topic, reads from `feature_repo/data/driver_stats.parquet`, generates newer timestamps, and emits them to the topic.
3134

3235
```
3336
docker-compose up
3437
```
3538

36-
### Generate a topic
37-
If you run `python kafka_demo.py`, we now start generating streaming events from the parquet file continously (with sleeps to slow down event writes). We hard-code events to be a year fresher than what is available in the file.
38-
39-
### Register a push source
40-
This push source reflects the transformed features you're generating in Spark Structured Streaming. Here, we have a push source that will materialize the transformed features from the batch file source as well as push transformed features into the online store from a Push API.
41-
42-
```python
43-
driver_stats = FileSource(
44-
path="data/driver_stats.parquet",
45-
timestamp_field="event_timestamp",
46-
created_timestamp_column="created",
47-
description="A table describing the stats of a driver based on hourly logs",
48-
owner="test@gmail.com",
49-
)
50-
51-
driver_stats_push_source = PushSource(
52-
name="driver_stats_push_source", batch_source=driver_stats,
53-
)
54-
55-
driver_daily_features_view = FeatureView(
56-
name="driver_daily_features",
57-
entities=["driver"],
58-
ttl=timedelta(seconds=8640000000),
59-
schema=[Field(name="daily_miles_driven", dtype=Float32),],
60-
online=True,
61-
source=driver_stats_push_source,
62-
tags={"production": "True"},
63-
owner="test2@gmail.com",
64-
)
65-
```
6639
### Setting up Feast
6740

6841
Install Feast using pip

‎docker-compose.yml‎

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ services:
1313
container_name: broker
1414
ports:
1515
- "9092:9092"
16+
- "29092:29092"
1617
depends_on:
1718
- zookeeper
1819
environment:
@@ -23,8 +24,15 @@ services:
2324
KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
2425
KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: 1
2526
KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: 1
26-
27+
2728
redis:
2829
image: redis
2930
ports:
30-
- "6379:6379"
31+
- "6379:6379"
32+
33+
kafka_events:
34+
build:
35+
context: .
36+
dockerfile: kafka_demo/Dockerfile
37+
depends_on:
38+
- broker

‎feature_repo/features.py‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -71,10 +71,7 @@
7171
# Define an on demand feature view which can generate new features based on
7272
# existing feature views and RequestSource features
7373
@on_demand_feature_view(
74-
sources={
75-
"driver_hourly_stats": driver_hourly_stats_view,
76-
"vals_to_add": input_request,
77-
},
74+
sources=[driver_hourly_stats_view, input_request,],
7875
schema=[
7976
Field(name="conv_rate_plus_val1", dtype=Float64),
8077
Field(name="conv_rate_plus_val2", dtype=Float64),

‎feature_repo/workshop.ipynb‎

Lines changed: 75 additions & 100 deletions
Large diffs are not rendered by default.

‎kafka_demo.py‎

Lines changed: 0 additions & 68 deletions
This file was deleted.

‎kafka_demo/Dockerfile‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
FROM python:3.8-slim
2+
3+
# Copy app handler code
4+
COPY kafka_demo/kafka_demo.py kafka_demo.py
5+
COPY feature_repo/data/driver_stats.parquet .
6+
7+
# Install dependencies
8+
RUN pip3 install kafka-python==2.0.2
9+
RUN pip3 install pandas
10+
RUN pip3 install pyarrow
11+
12+
CMD [ "python", "-u", "kafka_demo.py", "--mode", "setup", "--bootstrap_servers", "broker:29092"]

‎kafka_demo/kafka_demo.py‎

Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
import json
2+
from time import sleep
3+
4+
import pandas as pd
5+
from kafka import KafkaAdminClient, KafkaProducer
6+
from kafka.admin import NewTopic
7+
import argparse
8+
9+
parser = argparse.ArgumentParser()
10+
parser.add_argument(
11+
"-m",
12+
"--mode",
13+
default="setup",
14+
choices=["setup", "teardown"],
15+
help="Whether to setup or teardown a Kafka topic with driver stats events. Setup will teardown before beginning emitting events.",
16+
)
17+
parser.add_argument(
18+
"-b",
19+
"--bootstrap_servers",
20+
default="localhost:9092",
21+
help="Where the bootstrap server is",
22+
)
23+
24+
args = parser.parse_args()
25+
26+
27+
def create_stream(topic_name, servers):
28+
topic_name = topic_name
29+
30+
producer = None
31+
admin = None
32+
for i in range(20):
33+
try:
34+
producer = KafkaProducer(bootstrap_servers=servers)
35+
admin = KafkaAdminClient(bootstrap_servers=servers)
36+
print("SUCCESS: instantiated Kafka admin and producer")
37+
break
38+
except Exception as e:
39+
print(
40+
f"Trying to instantiate admin and producer with bootstrap servers {servers} with error {e}"
41+
)
42+
sleep(10)
43+
pass
44+
45+
try:
46+
# Create Kafka topic
47+
topic = NewTopic(name=topic_name, num_partitions=3, replication_factor=1)
48+
admin.create_topics([topic])
49+
print(f"Topic {topic_name} created")
50+
except Exception as e:
51+
print(str(e))
52+
pass
53+
54+
print("Reading parquet")
55+
df = pd.read_parquet("driver_stats.parquet").sort_values(by="event_timestamp")
56+
print("Emitting events")
57+
iteration = 1
58+
while True:
59+
for row in df[
60+
["driver_id", "event_timestamp", "created", "miles_driven",]
61+
].to_dict("records"):
62+
# Make event one more year recent to simulate fresher data
63+
row["event_timestamp"] = (
64+
row["event_timestamp"] + pd.Timedelta(weeks=52 * iteration)
65+
).strftime("%Y-%m-%d %H:%M:%S")
66+
row["created"] = row["created"].strftime("%Y-%m-%d %H:%M:%S")
67+
producer.send(topic_name, json.dumps(row).encode())
68+
sleep(0.1)
69+
iteration += 1
70+
71+
72+
def teardown_stream(topic_name, servers=["localhost:9092"]):
73+
try:
74+
admin = KafkaAdminClient(bootstrap_servers=servers)
75+
print(admin.delete_topics([topic_name]))
76+
print(f"Topic {topic_name} deleted")
77+
except Exception as e:
78+
print(str(e))
79+
pass
80+
81+
82+
if __name__ == "__main__":
83+
parsed_args = vars(args)
84+
mode = parsed_args["mode"]
85+
servers = parsed_args["bootstrap_servers"]
86+
teardown_stream("drivers", [servers])
87+
if mode == "setup":
88+
create_stream("drivers", [servers])

‎requirements.txt‎

Lines changed: 0 additions & 3 deletions
This file was deleted.

0 commit comments

Comments
 (0)