-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path4-2ConnectFileStream.py
73 lines (59 loc) · 2.09 KB
/
4-2ConnectFileStream.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import asyncio
import json
import requests
KAFKA_CONNECT_URL = "http://localhost:8083/connectors"
CONNECTOR_NAME = "exercise2"
def configure_connector():
"""Calls Kafka Connect to create the Connector"""
print("creating or updating kafka connect connector...")
rest_method = requests.post
resp = requests.get(f"{KAFKA_CONNECT_URL}/{CONNECTOR_NAME}")
if resp.status_code == 200:
return
# Complete the Kafka Connect Config below.
# See: https://docs.confluent.io/current/connect/references/restapi.html
# See: https://docs.confluent.io/current/connect/filestream_connector.html#filesource-connector
resp = rest_method(
KAFKA_CONNECT_URL,
headers={"Content-Type": "application/json"},
data=json.dumps(
{
"name": CONNECTOR_NAME,
"config": {
"connector.class": "FileStreamSource",
"topic": "lesson4.sample2.logs",
"tasks.max": 1,
"file": f"/tmp/{CONNECTOR_NAME}.log",
"key.converter": "org.apache.kafka.connect.json.JsonConverter",
"key.converter.schemas.enable": "false",
"value.converter": "org.apache.kafka.connect.json.JsonConverter",
"value.converter.schemas.enable": "false",
},
}
),
)
# Ensure a healthy response was given
resp.raise_for_status()
print("connector created successfully")
async def log():
"""Continually appends to the end of a file"""
with open(f"/tmp/{CONNECTOR_NAME}.log", "w") as f:
iteration = 0
while True:
f.write(f"log number {iteration}\n")
f.flush()
await asyncio.sleep(1.0)
iteration += 1
async def log_task():
"""Runs the log task"""
task = asyncio.create_task(log())
configure_connector()
await task
def run():
"""Runs the simulation"""
try:
asyncio.run(log_task())
except KeyboardInterrupt as e:
print("shutting down")
if __name__ == "__main__":
run()