Skip to content

Commit c23277d

Browse files
committed
Add CLI to store kafka stream to a netCDF file
1 parent 98b2b27 commit c23277d

1 file changed

Lines changed: 49 additions & 1 deletion

File tree

src/imas_streams/cli.py

Lines changed: 49 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import logging
22
import sys
3+
from pathlib import Path
34

45
import click
56
import imas
@@ -154,7 +155,7 @@ def kafka_to_imasentry(
154155
overwrite: bool,
155156
timeout: float,
156157
):
157-
"""Consume streaming IMAS data from Kafka and store data in an IMAS Data Entry.
158+
"""Consume streaming IMAS data from Kafka and store the data in an IMAS Data Entry.
158159
159160
\b
160161
Arguments:
@@ -182,6 +183,53 @@ def kafka_to_imasentry(
182183
entry.put_slice(result)
183184

184185

186+
@main.command
187+
@click.argument("kafka_host")
188+
@click.argument("topic")
189+
@click.argument("filename")
190+
@click.option(
191+
"--batch-size",
192+
default=1024,
193+
help="Number of time slices to batch when writing data to disk",
194+
)
195+
@click.option("--overwrite", is_flag=True, help="Overwrite any existing file")
196+
@click.option("--timeout", "-t", default=5.0, help="Timeout for receiving next message")
197+
def kafka_to_netcdf(
198+
kafka_host: str,
199+
topic: str,
200+
filename: str,
201+
batch_size: int,
202+
overwrite: bool,
203+
timeout: float,
204+
):
205+
"""Consume streaming IMAS data from Kafka and store the data in an IMAS netCDF file.
206+
207+
\b
208+
Arguments:
209+
KAFKA_HOST Kafka host and port (aka bootstrap.servers). E.g. 'localhost:9092'.
210+
TOPIC Name of the kafka topic with streaming IMAS data.
211+
FILENAME Name of the NetCDF file to write the data to.
212+
"""
213+
# Local import: kafka and netCDF are optional dependencies
214+
from imas_streams.kafka import KafkaConsumer, KafkaSettings
215+
from imas_streams.netcdf_consumers import NetCDFConsumer
216+
217+
fpath = Path(filename)
218+
if overwrite and fpath.exists():
219+
logging.info("Removing existing file '%s'...")
220+
fpath.unlink()
221+
222+
consumer = KafkaConsumer(
223+
KafkaSettings(host=kafka_host, topic_name=topic),
224+
NetCDFConsumer,
225+
filename=fpath,
226+
batch_size=batch_size,
227+
)
228+
229+
for _ in consumer.stream(timeout=timeout):
230+
pass # The NetCDFConsumer does everything, but we need to loop over the stream
231+
232+
185233
@main.command()
186234
def kafka_to_muscle3():
187235
"""MUSCLE3 actor consuming streaming IMAS data from a Kafka topic and making it

0 commit comments

Comments
 (0)