-
Notifications
You must be signed in to change notification settings - Fork 100
Expand file tree
/
Copy pathparquet_exporter.rs
More file actions
1612 lines (1471 loc) · 66.7 KB
/
parquet_exporter.rs
File metadata and controls
1612 lines (1471 loc) · 66.7 KB
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
//! Parquet exporter for OTAP data
//!
//! This writes the parquet files in a denormalized star-schema, where each OTAP payload
//! type is it's own parquet "table" that can be joined by id -> parent_id relationship.
//!
//! It also handles minor transformations of the data, such as creating a unique ID
//! (normally, IDs are only unique within some OTAP batch) and removing certain encodings
//! such as the delta encoded parent IDs.
//!
//! This exporter is currently experimental and is not yet ready for production use. There
//! are several outstanding issues that need to be addressed including:
//! - support for metrics and traces
//! - proper error handling and retry logic
//! - support for acknowledgements and nack messages
//! - handle periodically flushing batches after some time threshold
//! - dynamic configuration updates
//! See the [GitHub issue](https://github.com/open-telemetry/otel-arrow/issues/399) for more details.
use crate::OTAP_EXPORTER_FACTORIES;
use crate::parquet_exporter::schema::transform_to_known_schema;
use crate::pdata::OtapPdata;
use std::io::ErrorKind;
use std::sync::Arc;
use std::time::{Duration, Instant};
use self::idgen::PartitionSequenceIdGenerator;
use self::partition::{Partition, partition};
use self::writer::WriteBatch;
use crate::metrics::ExporterPDataMetrics;
use crate::parquet_exporter::metrics::ParquetExporterMetrics;
use async_trait::async_trait;
use futures::{FutureExt, pin_mut};
use futures_timer::Delay;
use linkme::distributed_slice;
use otap_df_config::node::NodeUserConfig;
use otap_df_engine::ExporterFactory;
use otap_df_engine::config::ExporterConfig;
use otap_df_engine::context::PipelineContext;
use otap_df_engine::control::NodeControlMsg;
use otap_df_engine::error::{Error, ExporterErrorKind, format_error_sources};
use otap_df_engine::exporter::ExporterWrapper;
use otap_df_engine::local::exporter::{EffectHandler, Exporter};
use otap_df_engine::message::{Message, MessageChannel};
use otap_df_engine::node::NodeId;
use otap_df_engine::terminal_state::TerminalState;
use otap_df_pdata::otap::OtapArrowRecords;
use otap_df_telemetry::metrics::{MetricSet, MetricSetHandler};
mod config;
mod error;
mod idgen;
mod metrics;
mod partition;
mod schema;
mod writer;
#[allow(dead_code)]
const PARQUET_EXPORTER_URN: &str = "urn:otel:parquet:exporter";
/// Parquet exporter for OTAP Data
pub struct ParquetExporter {
config: config::Config,
pdata_metrics: Option<MetricSet<ExporterPDataMetrics>>,
io_metrics: Option<MetricSet<ParquetExporterMetrics>>,
}
/// Declares the Parquet exporter as a local exporter factory
///
/// Unsafe code is temporarily used here to allow the use of `distributed_slice` macro
/// This macro is part of the `linkme` crate which is considered safe and well maintained.
#[allow(unsafe_code)]
#[distributed_slice(OTAP_EXPORTER_FACTORIES)]
pub static PARQUET_EXPORTER: ExporterFactory<OtapPdata> = ExporterFactory {
name: PARQUET_EXPORTER_URN,
create: |pipeline: PipelineContext,
node: NodeId,
node_config: Arc<NodeUserConfig>,
exporter_config: &ExporterConfig| {
Ok(ExporterWrapper::local(
ParquetExporter::from_config(pipeline, &node_config.config)?,
node,
node_config,
exporter_config,
))
},
wiring_contract: otap_df_engine::wiring_contract::WiringContract::UNRESTRICTED,
};
impl ParquetExporter {
/// construct a new instance of the `ParquetExporter`
#[must_use]
pub const fn new(config: config::Config) -> Self {
// NOTE: This constructor does not register metrics because it lacks a PipelineContext.
// Prefer using from_config in the factory path so metrics are properly wired.
Self {
config,
pdata_metrics: None,
io_metrics: None,
}
}
/// construct a new instance from the configuration object
pub fn from_config(
pipeline_ctx: PipelineContext,
config: &serde_json::Value,
) -> Result<Self, otap_df_config::error::Error> {
let config: config::Config = serde_json::from_value(config.clone()).map_err(|e| {
otap_df_config::error::Error::InvalidUserConfig {
error: e.to_string(),
}
})?;
let pdata_metrics = pipeline_ctx.register_metrics::<ExporterPDataMetrics>();
let io_metrics = pipeline_ctx.register_metrics::<ParquetExporterMetrics>();
Ok(ParquetExporter {
config,
pdata_metrics: Some(pdata_metrics),
io_metrics: Some(io_metrics),
})
}
fn terminal_state(
deadline: Instant,
pdata_metrics: Option<MetricSet<ExporterPDataMetrics>>,
io_metrics: Option<MetricSet<ParquetExporterMetrics>>,
) -> TerminalState {
let mut snapshots = Vec::new();
if let Some(metrics) = &pdata_metrics {
if metrics.needs_flush() {
snapshots.push(metrics.snapshot());
}
}
if let Some(metrics) = &io_metrics {
if metrics.needs_flush() {
snapshots.push(metrics.snapshot());
}
}
TerminalState::new(deadline, snapshots)
}
}
#[async_trait(?Send)]
impl Exporter<OtapPdata> for ParquetExporter {
async fn start(
mut self: Box<Self>,
mut msg_chan: MessageChannel<OtapPdata>,
effect_handler: EffectHandler<OtapPdata>,
) -> Result<TerminalState, Error> {
let exporter_id = effect_handler.exporter_id();
let object_store =
crate::object_store::from_storage_type(&self.config.storage).map_err(|e| {
let source_detail = format_error_sources(&e);
Error::ExporterError {
exporter: exporter_id.clone(),
kind: ExporterErrorKind::Configuration,
error: format!("error initializing object store {e}"),
source_detail,
}
})?;
let writer_options = self.config.writer_options.unwrap_or_default();
// if threshold set to flush old messages, get the timer interval. If timer interval isn't
// configured, we use a default period of 5s
let flush_age_check_interval = writer_options
.flush_when_older_than
.map(calculate_flush_timeout_check_period);
// start timer-tick to periodically flush batches older than threshold
if let Some(flush_age_check_interval) = flush_age_check_interval {
// ignoring timer cancel for now..
// TODO when we have the ability to inject dynamic config we may need to cancel and
// recreate the interval timer
// https://github.com/open-telemetry/otel-arrow/issues/500
let _timer_cancel = effect_handler
.start_periodic_timer(flush_age_check_interval)
.await?;
}
// Start periodic telemetry collection (internal metrics)
let telemetry_cancel_handle = effect_handler
.start_periodic_telemetry(Duration::from_secs(1))
.await?;
let mut writer = writer::WriterManager::new(object_store, writer_options);
let mut batch_id = 0;
let mut id_generator = PartitionSequenceIdGenerator::new();
loop {
match msg_chan.recv().await? {
Message::Control(NodeControlMsg::TimerTick { .. }) => {
match writer.flush_aged_beyond_threshold().await {
Ok(stats) => {
if let Some(io) = self.io_metrics.as_mut() {
if stats.flush_scheduled_max_rows > 0 {
io.flush_scheduled_max_rows
.add(stats.flush_scheduled_max_rows);
}
if stats.flush_scheduled_max_age > 0 {
io.flush_scheduled_max_age
.add(stats.flush_scheduled_max_age);
}
if stats.files_closed > 0 {
io.files_closed.add(stats.files_closed);
}
}
}
Err(e) => {
// TODO - this is not the error handling we want long term. eventually we
// should have the concept of retryable & non-retryable errors and use Nack
// message + a Retry processor to handle this gracefully
// https://github.com/open-telemetry/otel-arrow/issues/504
let source_detail = format_error_sources(&e);
return Err(Error::ExporterError {
exporter: effect_handler.exporter_id(),
kind: ExporterErrorKind::Transport,
error: format!("Parquet write failed: {e}"),
source_detail,
});
}
}
}
Message::Control(NodeControlMsg::CollectTelemetry {
mut metrics_reporter,
}) => {
if let Some(metrics) = self.pdata_metrics.as_mut() {
_ = metrics_reporter.report(metrics);
}
if let Some(metrics) = self.io_metrics.as_mut() {
_ = metrics_reporter.report(metrics);
}
}
Message::Control(NodeControlMsg::Config { .. }) => {
// TODO when we have the ability to inject dynamic config into the
// pipeline, we'll handle updating the exporter config here.
// https://github.com/open-telemetry/otel-arrow/issues/500
}
Message::Control(NodeControlMsg::Shutdown {
deadline,
reason: _,
}) => {
let mut timeout = Delay::new(deadline.duration_since(Instant::now())).fuse();
let flush_all = writer.flush_all().fuse();
pin_mut!(flush_all);
// Stop telemetry loop concurrently with flushing; do not block shutdown on cancel
let cancel_fut = async {
let _ = telemetry_cancel_handle.cancel().await;
futures::future::pending::<()>().await
}
.fuse();
pin_mut!(cancel_fut);
return futures::select_biased! {
_ = cancel_fut => unreachable!(),
_timeout = timeout => Err(Error::IoError {
node: exporter_id.clone(),
error: std::io::Error::from(ErrorKind::TimedOut)
}),
_ = flush_all => Ok(Self::terminal_state(deadline, self.pdata_metrics, self.io_metrics)),
};
}
Message::PData(pdata) => {
// Capture signal type before moving pdata into try_from
let signal_type = pdata.signal_type();
// Note: context is not used
let (_context, payload) = pdata.into_parts();
// Mark as consumed for this signal
if let Some(metrics) = self.pdata_metrics.as_mut() {
metrics.inc_consumed(signal_type);
}
let mut otap_batch: OtapArrowRecords =
payload.try_into().inspect_err(|_| {
if let Some(metrics) = self.pdata_metrics.as_mut() {
metrics.inc_failed(signal_type);
}
})?;
// generate unique IDs
let id_gen_result = id_generator.generate_unique_ids(&mut otap_batch);
if let Err(e) = id_gen_result {
// mark failure before returning
if let Some(metrics) = self.pdata_metrics.as_mut() {
metrics.inc_failed(signal_type);
}
// TODO - this is not the error handling we want long term.
// eventually we should have the concept of retryable & non-retryable errors and
// use Nack message + a Retry processor to handle this gracefully
// https://github.com/open-telemetry/otel-arrow/issues/504
let source_detail = format_error_sources(&e);
return Err(Error::ExporterError {
exporter: exporter_id.clone(),
kind: ExporterErrorKind::Other,
error: format!("ID Generation failed: {e}"),
source_detail,
});
}
// ensure the batches has the schema the parquet writer expects
transform_to_known_schema(&mut otap_batch).map_err(|e| {
// mark failure before returning
if let Some(metrics) = self.pdata_metrics.as_mut() {
metrics.inc_failed(signal_type);
}
// TODO - Ack/Nack instead of returning error
let source_detail = format_error_sources(&e);
Error::ExporterError {
exporter: exporter_id.clone(),
kind: ExporterErrorKind::Other,
error: format!("Schema transformation failed: {e}"),
source_detail,
}
})?;
// compute any partitions
let partitions = match self.config.partitioning_strategies.as_ref() {
Some(strategies) => partition(&otap_batch, strategies),
None => vec![Partition {
otap_batch,
attributes: None,
}],
};
// write the data
let writes = partitions
.iter()
.map(|partition| {
WriteBatch::new(
batch_id,
&partition.otap_batch,
partition.attributes.as_deref(),
)
})
.collect::<Vec<_>>();
batch_id += 1;
match writer.write(&writes).await {
Ok(stats) => {
// successful write
if let Some(metrics) = self.pdata_metrics.as_mut() {
metrics.inc_exported(signal_type);
}
if let Some(io) = self.io_metrics.as_mut() {
if stats.files_created > 0 {
io.files_created.add(stats.files_created);
}
if stats.files_closed > 0 {
io.files_closed.add(stats.files_closed);
}
if stats.rows_written > 0 {
io.rows_written.add(stats.rows_written);
}
if stats.flush_scheduled_max_rows > 0 {
io.flush_scheduled_max_rows
.add(stats.flush_scheduled_max_rows);
}
if stats.flush_scheduled_max_age > 0 {
io.flush_scheduled_max_age
.add(stats.flush_scheduled_max_age);
}
}
}
Err(e) => {
// mark failure before returning
if let Some(metrics) = self.pdata_metrics.as_mut() {
metrics.inc_failed(signal_type);
}
// TODO - this is not the error handling we want long term.
// eventually we should have the concept of retryable & non-retryable errors and
// use Nack message + a Retry processor to handle this gracefully
// https://github.com/open-telemetry/otel-arrow/issues/504
let source_detail = format_error_sources(&e);
return Err(Error::ExporterError {
exporter: effect_handler.exporter_id(),
kind: ExporterErrorKind::Transport,
error: format!("Parquet write failed: {e}"),
source_detail,
});
}
}
}
_ => {
// ignore unexpected messages
}
}
}
}
}
/// This calculates the period at which we instruct the [`WriterManager`] to flush any writers
/// older than the threshold.
fn calculate_flush_timeout_check_period(configured_threshold: Duration) -> Duration {
// try to choose a period that is relatively close the the configured threshold.
// this avoids the check happening long after the file writer is beyond the threshold.
let period = configured_threshold / 60;
// we make the minimum period at which we'll check that a flush should happen 1 second.
// this avoids a too short check interval causing a lot of overhead.
period.max(Duration::from_secs(1))
}
#[cfg(test)]
mod test {
use crate::parquet_exporter::config::WriterOptions;
use std::ops::Add;
use super::*;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use arrow::array::{DictionaryArray, RecordBatch, StringArray, UInt16Array};
use arrow::compute::concat_batches;
use arrow::datatypes::{DataType, Field, Schema, UInt16Type};
use fixtures::SimpleDataGenOptions;
use futures::StreamExt;
use otap_df_config::node::NodeUserConfig;
use otap_df_engine::control::{
Controllable, PipelineControlMsg, PipelineCtrlMsgReceiver, PipelineCtrlMsgSender,
pipeline_ctrl_msg_channel,
};
use otap_df_engine::exporter::ExporterWrapper;
use otap_df_engine::local::message::{LocalReceiver, LocalSender};
use otap_df_engine::message::{Receiver, Sender};
use otap_df_engine::node::NodeWithPDataReceiver;
use otap_df_engine::testing::{create_not_send_channel, setup_test_runtime};
use otap_df_engine::testing::{
exporter::{TestContext, TestRuntime},
test_node,
};
use otap_df_pdata::Consumer;
use otap_df_pdata::otap::from_record_messages;
use otap_df_pdata::proto::opentelemetry::arrow::v1::ArrowPayloadType;
use otap_df_pdata::proto::opentelemetry::common::v1::{AnyValue, KeyValue, any_value::Value};
use otap_df_pdata::schema::consts;
use parquet::arrow::async_reader::ParquetRecordBatchStreamBuilder;
use tokio::fs::File;
use tokio::time::sleep;
use crate::fixtures;
fn logs_scenario(
num_rows: usize,
shutdown_timeout: Instant,
) -> impl FnOnce(TestContext<OtapPdata>) -> Pin<Box<dyn Future<Output = ()>>> {
move |ctx| {
Box::pin(async move {
let mut consumer = Consumer::default();
let otap_batch = consumer
.consume_bar(&mut fixtures::create_simple_logs_arrow_record_batches(
SimpleDataGenOptions {
num_rows,
..Default::default()
},
))
.unwrap();
ctx.send_pdata(OtapPdata::new_default(
OtapArrowRecords::Logs(from_record_messages(otap_batch)).into(),
))
.await
.expect("Failed to send logs message");
ctx.send_shutdown(shutdown_timeout, "test completed")
.await
.unwrap();
})
}
}
#[test]
#[cfg_attr(
target_os = "windows",
ignore = "Skipping on Windows due to timing flakiness"
)]
fn test_adaptive_schema_dict_upgrade_write() {
let test_runtime = TestRuntime::<OtapPdata>::new();
let temp_dir = tempfile::tempdir().unwrap();
let base_dir: String = temp_dir.path().to_str().unwrap().into();
let exporter = ParquetExporter::new(config::Config {
storage: crate::object_store::StorageType::File {
base_uri: base_dir.clone(),
},
partitioning_strategies: None,
writer_options: None,
});
let node_config = Arc::new(NodeUserConfig::new_exporter_config(PARQUET_EXPORTER_URN));
let exporter = ExporterWrapper::<OtapPdata>::local::<ParquetExporter>(
exporter,
test_node(test_runtime.config().name.clone()),
node_config,
test_runtime.config(),
);
test_runtime
.set_exporter(exporter)
.run_test(move |ctx| {
Box::pin(async move {
// this should generate an attributes key & string_val column with type Dict<u16, String>
let mut attrs1 = vec![];
for i in 0..257 {
attrs1.push(KeyValue {
key: format!("attr{i}"),
value: Some(AnyValue {
value: Some(Value::StringValue(format!("val{i}"))),
}),
})
}
let pdata1 = fixtures::create_single_logs_pdata_with_attrs(attrs1);
ctx.send_pdata(pdata1).await.unwrap();
// this should generate an attributes column with type Dict<u8, String>
let pdata2 = fixtures::create_single_logs_pdata_with_attrs(vec![KeyValue {
key: "attr1".to_string(),
value: Some(AnyValue {
value: Some(Value::StringValue("val1".to_string())),
}),
}]);
ctx.send_pdata(pdata2).await.unwrap();
// this should create a record batch with the string_val column as native array
// manually switching the type b/c otherwise would need to create > u16::MAX
// attributes, and it could lead to unpredictable write times which could lead
// to some test flakiness.
let mut attrs3 = vec![];
for i in 0..20 {
attrs3.push(KeyValue {
key: format!("attr{i}"),
value: Some(AnyValue {
value: Some(Value::StringValue(format!("val{i}"))),
}),
})
}
let pdata3 = fixtures::create_single_logs_pdata_with_attrs(attrs3).payload();
let mut otap_batch = OtapArrowRecords::try_from(pdata3).unwrap();
let mut attrs_batch =
otap_batch.get(ArrowPayloadType::LogAttrs).unwrap().clone();
let old_column = attrs_batch.remove_column(
attrs_batch
.schema()
.index_of(consts::ATTRIBUTE_STR)
.unwrap(),
);
let tmp = old_column
.as_any()
.downcast_ref::<DictionaryArray<UInt16Type>>()
.unwrap();
let new_column =
StringArray::from_iter(tmp.downcast_dict::<StringArray>().unwrap());
let mut columns = attrs_batch.columns().to_vec();
columns.push(Arc::new(new_column));
let mut fields = attrs_batch.schema().fields().to_vec();
fields.push(Arc::new(Field::new(
consts::ATTRIBUTE_STR,
DataType::Utf8,
true,
)));
otap_batch.set(
ArrowPayloadType::LogAttrs,
RecordBatch::try_new(Arc::new(Schema::new(fields)), columns).unwrap(),
);
ctx.send_pdata(OtapPdata::new_default(otap_batch.into()))
.await
.unwrap();
let deadline = Instant::now().add(Duration::from_millis(200));
ctx.send_shutdown(deadline, "test completed").await.unwrap();
})
})
.run_validation(move |_ctx, exporter_result| {
Box::pin(async move {
exporter_result.unwrap();
assert_parquet_file_has_rows(&base_dir, ArrowPayloadType::Logs, 3).await;
assert_parquet_file_has_rows(&base_dir, ArrowPayloadType::LogAttrs, 278).await;
})
});
}
#[test]
fn test_adaptive_schema_optional_columns() {
let test_runtime = TestRuntime::<OtapPdata>::new();
let temp_dir = tempfile::tempdir().unwrap();
let base_dir: String = temp_dir.path().to_str().unwrap().into();
let exporter = ParquetExporter::new(config::Config {
storage: crate::object_store::StorageType::File {
base_uri: base_dir.clone(),
},
partitioning_strategies: None,
writer_options: None,
});
let node_config = Arc::new(NodeUserConfig::new_exporter_config(PARQUET_EXPORTER_URN));
let exporter = ExporterWrapper::<OtapPdata>::local::<ParquetExporter>(
exporter,
test_node(test_runtime.config().name.clone()),
node_config,
test_runtime.config(),
);
test_runtime
.set_exporter(exporter)
.run_test(move |ctx| {
Box::pin(async move {
let batch1: OtapArrowRecords =
fixtures::create_single_logs_pdata_with_attrs(vec![KeyValue {
key: "strkey".to_string(),
value: Some(AnyValue::new_string("terry")),
}])
.payload()
.try_into()
.unwrap();
let batch2: OtapArrowRecords =
fixtures::create_single_logs_pdata_with_attrs(vec![KeyValue {
key: "intkey".to_string(),
value: Some(AnyValue::new_int(418)),
}])
.payload()
.try_into()
.unwrap();
// double check that these contain schemas that are not the same ...
let batch1_attrs = batch1.get(ArrowPayloadType::LogAttrs).unwrap();
let batch2_attrs = batch2.get(ArrowPayloadType::LogAttrs).unwrap();
assert_ne!(batch1_attrs.schema(), batch2_attrs.schema());
ctx.send_pdata(OtapPdata::new_default(batch1.into()))
.await
.unwrap();
ctx.send_pdata(OtapPdata::new_default(batch2.into()))
.await
.unwrap();
ctx.send_shutdown(
Instant::now().add(Duration::from_millis(200)),
"test completed",
)
.await
.unwrap();
})
})
.run_validation(move |_ctx, exporter_result| {
Box::pin(async move {
// check no error
exporter_result.unwrap();
assert_parquet_file_has_rows(&base_dir, ArrowPayloadType::Logs, 2).await;
assert_parquet_file_has_rows(&base_dir, ArrowPayloadType::LogAttrs, 2).await;
})
});
}
async fn wait_table_exists(base_dir: &str, payload_type: ArrowPayloadType) {
let table_name = payload_type.as_str_name().to_lowercase();
loop {
_ = sleep(Duration::from_millis(100)).await;
// ensure the table exists
let mut dir = match tokio::fs::read_dir(format!("{base_dir}/{table_name}")).await {
Ok(dir) => dir,
Err(_) => continue,
};
// ensure a parquet file exists
let table_dir_entry = match dir.next_entry().await.unwrap() {
Some(table_dir) => table_dir,
None => continue,
};
// open the file and ensure a batch is written in it
let file = match File::open(table_dir_entry.path()).await {
Ok(file) => file,
Err(_) => continue,
};
let reader_builder = match ParquetRecordBatchStreamBuilder::new(file).await {
Ok(rb) => rb,
Err(_) => continue,
};
let mut reader = match reader_builder.build() {
Ok(r) => r,
Err(_) => continue,
};
match reader.next().await {
Some(_) => break,
None => continue,
}
}
}
async fn try_wait_table_exists(
base_dir: &str,
payload_type: ArrowPayloadType,
max_wait: Duration,
) -> Result<(), Error> {
tokio::select! {
_ = Delay::new(max_wait) => Err(Error::InternalError {
message: "timed out waiting for table to exist".into()
}),
_ = wait_table_exists(base_dir, payload_type) => Ok(())
}
}
async fn assert_parquet_file_has_rows(
base_dir: &str,
payload_type: ArrowPayloadType,
num_rows: usize,
) {
let table_name = payload_type.as_str_name().to_lowercase();
let file_path = tokio::fs::read_dir(format!("{base_dir}/{table_name}"))
.await
.unwrap_or_else(|_| panic!("expect to have found table for {payload_type:?}"))
.next_entry()
.await
.unwrap_or_else(|_| {
panic!("expect at least one parquet file file for type {payload_type:?}")
})
.unwrap()
.path();
let file = File::open(file_path).await.unwrap();
let reader_builder = ParquetRecordBatchStreamBuilder::new(file).await.unwrap();
let mut reader = reader_builder.build().unwrap();
let batch = reader.next().await.unwrap().unwrap();
assert_eq!(batch.num_rows(), num_rows);
}
#[test]
fn test_with_partitioning() {
let test_runtime = TestRuntime::<OtapPdata>::new();
let temp_dir = tempfile::tempdir().unwrap();
let base_dir: String = temp_dir.path().to_str().unwrap().into();
let exporter = ParquetExporter::new(config::Config {
storage: crate::object_store::StorageType::File {
base_uri: base_dir.clone(),
},
partitioning_strategies: Some(vec![config::PartitioningStrategy::SchemaMetadata(
vec![idgen::PARTITION_METADATA_KEY.to_string()],
)]),
writer_options: None,
});
let node_config = Arc::new(NodeUserConfig::new_exporter_config(PARQUET_EXPORTER_URN));
let exporter = ExporterWrapper::<OtapPdata>::local::<ParquetExporter>(
exporter,
test_node(test_runtime.config().name.clone()),
node_config,
test_runtime.config(),
);
let num_rows = 100;
test_runtime
.set_exporter(exporter)
.run_test(logs_scenario(
num_rows,
Instant::now().add(Duration::from_secs(1)),
))
.run_validation(move |_ctx, exporter_result| {
Box::pin(async move {
exporter_result.unwrap();
// simply ensure there is a parquet file for each type we should have
// written and that it has the expected number of rows
for payload_type in [
ArrowPayloadType::Logs,
ArrowPayloadType::LogAttrs,
ArrowPayloadType::ResourceAttrs,
ArrowPayloadType::ScopeAttrs,
] {
let table_name = payload_type.as_str_name().to_lowercase();
// ensure we have files partitioned and that the partition starts
// with the expected key
let partition_path = tokio::fs::read_dir(format!(
"{base_dir}/{table_name}"
))
.await
.unwrap_or_else(|_| {
panic!("expect to have found table for {payload_type:?}")
})
.next_entry()
.await
.unwrap_or_else(|_| {
panic!(
"expect at least one partition directory for type {payload_type:?}"
)
})
.unwrap()
.path();
let last_segment = partition_path.iter().next_back().unwrap();
assert!(
last_segment
.to_string_lossy()
.starts_with(idgen::PARTITION_METADATA_KEY)
);
let file_path = tokio::fs::read_dir(partition_path)
.await
.unwrap()
.next_entry()
.await
.unwrap_or_else(|_| {
panic!("expect at least one parquet file for type {payload_type:?}")
})
.unwrap()
.path();
let file = File::open(file_path).await.unwrap();
let reader_builder =
ParquetRecordBatchStreamBuilder::new(file).await.unwrap();
let mut reader = reader_builder.build().unwrap();
let batch = reader.next().await.unwrap().unwrap();
assert_eq!(batch.num_rows(), num_rows);
}
})
});
}
#[test]
fn test_no_partitioning() {
let test_runtime = TestRuntime::<OtapPdata>::new();
let temp_dir = tempfile::tempdir().unwrap();
let base_dir: String = temp_dir.path().to_str().unwrap().into();
let exporter = ParquetExporter::new(config::Config {
storage: crate::object_store::StorageType::File {
base_uri: base_dir.clone(),
},
partitioning_strategies: None,
writer_options: None,
});
let node_config = Arc::new(NodeUserConfig::new_exporter_config(PARQUET_EXPORTER_URN));
let exporter = ExporterWrapper::<OtapPdata>::local::<ParquetExporter>(
exporter,
test_node(test_runtime.config().name.clone()),
node_config,
test_runtime.config(),
);
let num_rows = 100;
test_runtime
.set_exporter(exporter)
.run_test(logs_scenario(
num_rows,
Instant::now().add(Duration::from_secs(1)),
))
.run_validation(move |_ctx, exporter_result| {
Box::pin(async move {
exporter_result.unwrap();
// simply ensure there is a parquet file for each type we should have
// written and that it has the expected number of rows
for payload_type in [
ArrowPayloadType::Logs,
ArrowPayloadType::LogAttrs,
ArrowPayloadType::ResourceAttrs,
ArrowPayloadType::ScopeAttrs,
] {
assert_parquet_file_has_rows(&base_dir, payload_type, num_rows).await;
}
})
});
}
// Skipping on Windows and macOS due to flakiness: https://github.com/open-telemetry/otel-arrow/issues/1614
#[test]
#[cfg_attr(
any(target_os = "windows", target_os = "macos"),
ignore = "Skipping on Windows and macOS due to flakiness"
)]
fn test_shutdown_timeout() {
let test_runtime = TestRuntime::<OtapPdata>::new();
let temp_dir = tempfile::tempdir().unwrap();
let base_dir: String = temp_dir.path().to_str().unwrap().into();
let exporter = ParquetExporter::new(config::Config {
storage: crate::object_store::StorageType::File {
base_uri: format!("testdelayed://{base_dir}?delay=500ms"),
},
partitioning_strategies: None,
writer_options: Some(WriterOptions {
target_rows_per_file: Some(50),
..Default::default()
}),
});
let node_config = Arc::new(NodeUserConfig::new_exporter_config(PARQUET_EXPORTER_URN));
let mut exporter = ExporterWrapper::<OtapPdata>::local::<ParquetExporter>(
exporter,
test_node(test_runtime.config().name.clone()),
node_config,
test_runtime.config(),
);
let exporter_config = ExporterConfig::new("test_parquet_exporter");
let (rt, _) = setup_test_runtime();
let control_sender = exporter.control_sender();
let (pdata_tx, pdata_rx) = create_not_send_channel::<OtapPdata>(1);
let pdata_tx = Sender::Local(LocalSender::mpsc(pdata_tx));
let pdata_rx = Receiver::Local(LocalReceiver::mpsc(pdata_rx));
let (pipeline_ctrl_msg_tx, _pipeline_ctrl_msg_rx) = pipeline_ctrl_msg_channel(10);
// Keep the receiver alive so EffectHandler can send telemetry/timer requests without error.
exporter
.set_pdata_receiver(test_node(exporter_config.name.clone()), pdata_rx)
.expect("Failed to set PData Receiver");
async fn start_exporter(
exporter: ExporterWrapper<OtapPdata>,
pipeline_ctrl_msg_tx: PipelineCtrlMsgSender<OtapPdata>,
) -> Result<(), Error> {
let (_metrics_rx, metrics_reporter) =
otap_df_telemetry::reporter::MetricsReporter::create_new_and_receiver(1);
exporter
.start(pipeline_ctrl_msg_tx, metrics_reporter)
.await
.map(|_| ())
}
async fn send_messages(
base_dir: &str,
pdata_tx: Sender<OtapPdata>,
ctrl_sender: Sender<NodeControlMsg<OtapPdata>>,
) -> () {
// have the parquet writer queue a batch to be written. Since it's a bit difficult to
// know for certain when the batches will actually be queued because we have no direct
// way to investigate it, we can inspect it indirectly. Below, we'll write just enough
// data to cause the log attributes table to flush, but not the logs, resource attrs or
// scope attrs. Since we know the log attrs table has been written, we can guess the
// writer has buffered files ..
let logs_data = Consumer::default()
.consume_bar(&mut fixtures::create_simple_logs_arrow_record_batches(
SimpleDataGenOptions {
// a pretty big batch
num_rows: 48,
..Default::default()
},
))
.unwrap();
let otap_batch = OtapArrowRecords::Logs(from_record_messages(logs_data)).into();
pdata_tx
.send(OtapPdata::new_default(otap_batch))
.await
.unwrap();
let logs_data = Consumer::default()
.consume_bar(&mut fixtures::create_simple_logs_arrow_record_batches(
SimpleDataGenOptions {
num_rows: 1,
..Default::default()
},
))
.unwrap();
let mut otap_batch2 = OtapArrowRecords::Logs(from_record_messages(logs_data));
let log_attrs = otap_batch2.get(ArrowPayloadType::LogAttrs).unwrap();
// adding extra attributes should just put us over the limit where this table will be
// flushed on write
otap_batch2.set(
ArrowPayloadType::LogAttrs,
concat_batches(log_attrs.schema_ref(), vec![&log_attrs.clone(), log_attrs])
.unwrap(),
);
pdata_tx
.send(OtapPdata::new_default(otap_batch2.into()))
.await
.unwrap();
// wait for the log_attrs table to exist
try_wait_table_exists(base_dir, ArrowPayloadType::LogAttrs, Duration::from_secs(5))
.await
.unwrap();
// double check that the other tables have not been written (this is a sanity check)
for payload_type in &[
ArrowPayloadType::Logs,
ArrowPayloadType::ResourceAttrs,
ArrowPayloadType::ScopeAttrs,
] {
let table_name = payload_type.as_str_name().to_lowercase();
assert!(
tokio::fs::read_dir(format!("{base_dir}/{table_name}"))
.await
.is_err()
);
}
// shutdown faster than it could possibly flush
_ = ctrl_sender
.send(NodeControlMsg::Shutdown {
deadline: Instant::now().add(Duration::from_secs(1)),