-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathmod.rs
More file actions
1702 lines (1531 loc) · 64.9 KB
/
Copy pathmod.rs
File metadata and controls
1702 lines (1531 loc) · 64.9 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
use std::{
convert::TryFrom,
num::NonZeroU64,
path::{Path, PathBuf},
time::{Duration, Instant},
};
use async_compression::tokio::write::{GzipEncoder, ZstdEncoder};
use async_trait::async_trait;
use bytes::{Bytes, BytesMut};
use futures::{
FutureExt, future,
stream::{BoxStream, StreamExt},
};
use serde_with::serde_as;
use tokio::{
fs::{self, File},
io::AsyncWriteExt,
};
use tokio_util::{codec::Encoder as _, time::delay_queue::Expired};
use vector_lib::{
EstimatedJsonEncodedSizeOf, TimeZone,
codecs::{
TextSerializerConfig,
encoding::{Framer, FramingConfig},
},
configurable::configurable_component,
finalization::EventFinalizers,
internal_event::{CountByteSize, EventsSent, InternalEventHandle as _, Output, Registered},
json_size::JsonSize,
partition::Partitioner,
stream::BatcherSettings,
};
use crate::{
codecs::{Encoder, EncodingConfigWithFraming, SinkType, Transformer},
config::{AcknowledgementsConfig, GenerateConfig, Input, SinkConfig, SinkContext},
event::{Event, EventStatus, Finalizable},
expiring_hash_map::ExpiringHashMap,
internal_events::{
FileBytesSent, FileInternalMetricsConfig, FileIoError, FileOpen,
FilePathOutsideBaseDirError, TemplateRenderingError,
},
sinks::util::{
BatchConfig, RealtimeSizeBasedDefaultBatchSettings, StreamSink,
path_confinement::{ConfineError, PathConfinement},
timezone_to_offset,
},
template::{ConfinementConfig, UnconfinedTemplate},
};
mod bytes_path;
use bytes_path::BytesPath;
/// Configuration for the `file` sink.
#[serde_as]
#[configurable_component(sink("file", "Output observability events into files."))]
#[derive(Clone, Debug)]
#[serde(deny_unknown_fields)]
pub struct FileSinkConfig {
/// File path to write events to.
///
/// Compression format extension must be explicit.
#[configurable(metadata(docs::examples = "/tmp/vector-%Y-%m-%d.log"))]
#[configurable(metadata(
docs::examples = "/tmp/application-{{ application_id }}-%Y-%m-%d.log"
))]
#[configurable(metadata(docs::examples = "/tmp/vector-%Y-%m-%d.log.zst"))]
#[configurable(metadata(
docs::warnings = "Rendered paths are confined to `base_dir` (derived from the literal prefix of `path` when unset). See the `base_dir` option."
))]
pub path: UnconfinedTemplate,
/// Directory under which all rendered `path` values must resolve.
///
/// When `path` contains event-field references (`{{ field }}`), Vector
/// confines every rendered path to this directory. If unset, the base
/// directory is derived from the literal prefix of `path` (the portion
/// before the first `{{` or `%`). Configuration fails if `path`
/// references event fields and no non-root base directory can be
/// derived.
#[configurable(metadata(docs::examples = "/var/log/vector"))]
#[serde(default)]
pub base_dir: Option<PathBuf>,
#[serde(flatten)]
pub confinement: ConfinementConfig,
/// The amount of time that a file can be idle and stay open.
///
/// After not receiving any events in this amount of time, the file is flushed and closed.
#[serde(default = "default_idle_timeout")]
#[serde_as(as = "serde_with::DurationSeconds<u64>")]
#[serde(rename = "idle_timeout_secs")]
#[configurable(metadata(docs::examples = 600))]
#[configurable(metadata(docs::human_name = "Idle Timeout"))]
pub idle_timeout: Duration,
#[serde(flatten)]
pub encoding: EncodingConfigWithFraming,
#[configurable(derived)]
#[serde(default, skip_serializing_if = "crate::serde::is_default")]
pub compression: Compression,
#[configurable(derived)]
#[serde(
default,
deserialize_with = "crate::serde::bool_or_struct",
skip_serializing_if = "crate::serde::is_default"
)]
pub acknowledgements: AcknowledgementsConfig,
#[configurable(derived)]
#[serde(default)]
pub timezone: Option<TimeZone>,
#[configurable(derived)]
#[serde(default)]
pub internal_metrics: FileInternalMetricsConfig,
#[configurable(derived)]
#[serde(default)]
pub truncate: FileTruncateConfig,
/// Controls how events are batched per destination file before writing.
///
/// Events sharing the same rendered path are accumulated into a single buffer and written
/// with one syscall per batch, reducing overhead when routing to many partitions
/// (for example, one file per Kafka topic). The default timeout is 1 second; raising it
/// increases throughput at the cost of end-to-end latency.
#[configurable(derived)]
#[serde(default)]
pub batch: BatchConfig<RealtimeSizeBasedDefaultBatchSettings>,
}
/// Configuration for truncating files.
#[configurable_component]
#[derive(Clone, Debug, Default)]
#[serde(deny_unknown_fields)]
pub struct FileTruncateConfig {
/// If this is set, files will be truncated after being closed for a set amount of seconds.
#[serde(default)]
pub after_close_time_secs: Option<NonZeroU64>,
/// If this is set, files will be truncated after set amount of seconds of no modifications.
#[serde(default)]
pub after_modified_time_secs: Option<NonZeroU64>,
/// If this is set, files will be truncated after set amount of seconds regardless of the state.
#[serde(default)]
pub after_secs: Option<NonZeroU64>,
}
impl GenerateConfig for FileSinkConfig {
fn generate_config() -> serde_json::Value {
serde_json::to_value(Self {
path: UnconfinedTemplate::try_from("/tmp/vector-%Y-%m-%d.log").unwrap(),
idle_timeout: default_idle_timeout(),
encoding: (None::<FramingConfig>, TextSerializerConfig::default()).into(),
compression: Default::default(),
acknowledgements: Default::default(),
timezone: Default::default(),
internal_metrics: Default::default(),
truncate: Default::default(),
base_dir: None,
confinement: ConfinementConfig::default(),
batch: Default::default(),
})
.unwrap()
}
}
const fn default_idle_timeout() -> Duration {
Duration::from_secs(30)
}
/// Compression configuration.
// TODO: Why doesn't this already use `crate::sinks::util::Compression`
// `crate::sinks::util::Compression` doesn't support zstd yet
#[configurable_component]
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum Compression {
/// [Gzip][gzip] compression.
///
/// [gzip]: https://www.gzip.org/
Gzip,
/// [Zstandard][zstd] compression.
///
/// [zstd]: https://facebook.github.io/zstd/
Zstd,
/// No compression.
#[default]
None,
}
struct OutFile {
created_at: Instant,
inner: OutFileInner,
}
enum OutFileInner {
Regular(File),
Gzip(GzipEncoder<File>),
Zstd(ZstdEncoder<File>),
}
impl OutFile {
fn new(file: File, compression: Compression) -> Self {
Self {
created_at: Instant::now(),
inner: match compression {
Compression::None => OutFileInner::Regular(file),
Compression::Gzip => OutFileInner::Gzip(GzipEncoder::new(file)),
Compression::Zstd => OutFileInner::Zstd(ZstdEncoder::new(file)),
},
}
}
async fn sync_all(&mut self) -> Result<(), std::io::Error> {
match &mut self.inner {
OutFileInner::Regular(file) => file.sync_all().await,
OutFileInner::Gzip(gzip) => gzip.get_mut().sync_all().await,
OutFileInner::Zstd(zstd) => zstd.get_mut().sync_all().await,
}
}
async fn shutdown(&mut self) -> Result<(), std::io::Error> {
match &mut self.inner {
OutFileInner::Regular(file) => file.shutdown().await,
OutFileInner::Gzip(gzip) => gzip.shutdown().await,
OutFileInner::Zstd(zstd) => zstd.shutdown().await,
}
}
async fn write(&mut self, src: &[u8]) -> Result<usize, std::io::Error> {
match &mut self.inner {
OutFileInner::Regular(file) => file.write(src).await,
OutFileInner::Gzip(gzip) => gzip.write(src).await,
OutFileInner::Zstd(zstd) => zstd.write(src).await,
}
}
async fn write_all(&mut self, src: &[u8]) -> Result<(), std::io::Error> {
match &mut self.inner {
OutFileInner::Regular(file) => file.write_all(src).await,
OutFileInner::Gzip(gzip) => gzip.write_all(src).await,
OutFileInner::Zstd(zstd) => zstd.write_all(src).await,
}
}
const fn created_at(&self) -> Instant {
self.created_at
}
/// Shutdowns by flushing data, writing headers, and syncing all of that
/// data and metadata to the filesystem.
async fn close(&mut self) -> Result<(), std::io::Error> {
self.shutdown().await?;
self.sync_all().await
}
}
#[async_trait::async_trait]
#[typetag::serde(name = "file")]
impl SinkConfig for FileSinkConfig {
async fn build(
&self,
cx: SinkContext,
) -> crate::Result<(super::VectorSink, super::Healthcheck)> {
let sink = FileSink::new(self, cx)?;
Ok((
super::VectorSink::from_event_streamsink(sink),
future::ok(()).boxed(),
))
}
fn confinement_config(&self) -> Option<&crate::template::ConfinementConfig> {
Some(&self.confinement)
}
fn input(&self) -> Input {
Input::new(self.encoding.config().1.input_type())
}
fn acknowledgements(&self) -> &AcknowledgementsConfig {
&self.acknowledgements
}
}
pub struct FileSink {
path: UnconfinedTemplate,
transformer: Transformer,
encoder: Encoder<Framer>,
idle_timeout: Duration,
batch_settings: BatcherSettings,
files: ExpiringHashMap<Bytes, OutFile>,
compression: Compression,
events_sent: Registered<EventsSent>,
include_file_metric_tag: bool,
truncation_config: FileTruncateConfig,
confinement: Option<PathConfinement>,
}
impl FileSink {
pub fn new(config: &FileSinkConfig, cx: SinkContext) -> crate::Result<Self> {
let transformer = config.encoding.transformer();
let (framer, serializer) = config.encoding.build(SinkType::StreamBased)?;
let encoder = Encoder::<Framer>::new(framer, serializer);
let batch_settings = config.batch.validate()?.into_batcher_settings()?;
let offset = config
.timezone
.or(cx.globals.timezone)
.and_then(timezone_to_offset);
// Config validation runs regardless of the opt-out: a relative
// `base_dir` is a syntactic error, not a confinement decision.
if let Some(base) = config.base_dir.as_ref()
&& base.is_relative()
{
return Err(Box::new(
crate::sinks::util::path_confinement::BuildError::BaseNotAbsolute {
path: base.clone(),
},
));
}
let confinement = if config
.confinement
.dangerously_allow_unconfined_template_resolution
{
ConfinementConfig::warn_unconfined_template("sink", "file", "path");
None
} else {
PathConfinement::for_template(&config.path, config.base_dir.as_deref())
.map_err(Box::new)?
};
Ok(Self {
path: config.path.clone().with_tz_offset(offset),
transformer,
encoder,
idle_timeout: config.idle_timeout,
batch_settings,
files: ExpiringHashMap::default(),
compression: config.compression,
events_sent: register!(EventsSent::from(Output(None))),
include_file_metric_tag: config.internal_metrics.include_file_tag,
truncation_config: config.truncate.clone(),
confinement,
})
}
fn deadline_at(&self) -> Instant {
Instant::now()
.checked_add(self.idle_timeout)
.expect("unable to compute next deadline")
}
async fn run(&mut self, input: BoxStream<'_, Event>) -> crate::Result<()> {
let partitioner = FilePathPartitioner {
path: self.path.clone(),
};
let batch_settings = self.batch_settings;
// Per-path event buffers with a generation counter that increments each
// time the buffer is flushed and recreated. The generation lets us detect stale
// deadline entries in the BinaryHeap so that a completed batch's deadline
// is never applied to a later batch for the same path.
let mut buffers: std::collections::HashMap<Bytes, (Vec<Event>, u64)> =
std::collections::HashMap::new();
let mut per_path_gen: std::collections::HashMap<Bytes, u64> =
std::collections::HashMap::new();
let mut flush_deadlines: std::collections::BinaryHeap<
std::cmp::Reverse<(tokio::time::Instant, Bytes, u64)>,
> = std::collections::BinaryHeap::new();
tokio::pin!(input);
loop {
let input_next = input.next();
let next_timer_deadline = flush_deadlines.peek()
.map(|&std::cmp::Reverse((d, _, _))| d);
tokio::select! {
event = input_next => {
match event {
Some(event) => {
let path = match partitioner.partition(&event) {
Some(raw_path) => {
if let Some(ref confinement) = self.confinement {
match confinement.confine(&bytes_to_path(&raw_path)) {
Ok(confined) => {
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
Bytes::copy_from_slice(
confined.as_os_str().as_bytes(),
)
}
#[cfg(not(unix))]
{
Bytes::from(
confined
.to_string_lossy()
.as_bytes()
.to_vec(),
)
}
}
Err(error) => {
let rendered = bytes_to_path(&raw_path);
let base = confinement.base_dir().to_path_buf();
emit!(FilePathOutsideBaseDirError {
path: &rendered,
base_dir: &base,
error,
});
event.metadata()
.update_status(EventStatus::Errored);
continue;
}
}
} else {
raw_path
}
}
None => {
event.metadata().update_status(EventStatus::Errored);
continue;
}
};
let event_size = event.estimated_json_encoded_size_of().get();
if let Some((events, _)) = buffers.get_mut(&path) {
let current_size: usize = events.iter()
.map(|e| e.estimated_json_encoded_size_of().get())
.sum();
if current_size + event_size > batch_settings.size_limit
|| events.len() >= batch_settings.item_limit
{
// Buffer is full — flush old batch and start fresh.
let (old_events, _old_generation) = buffers.remove(&path).unwrap();
self.process_batch(path.clone(), old_events).await;
let generation = per_path_gen.entry(path.clone()).or_insert(0);
let deadline = tokio::time::Instant::now()
+ batch_settings.timeout;
buffers.insert(path.clone(), (vec![event], *generation));
flush_deadlines.push(
std::cmp::Reverse((deadline, path.clone(), *generation)),
);
*generation += 1;
} else {
events.push(event);
}
} else {
let generation = per_path_gen.entry(path.clone()).or_insert(0);
let deadline = tokio::time::Instant::now()
+ batch_settings.timeout;
buffers.insert(path.clone(), (vec![event], *generation));
flush_deadlines.push(
std::cmp::Reverse((deadline, path.clone(), *generation)),
);
*generation += 1;
}
// Flush immediately when the batch reaches the item or byte limit.
let needs_flush = buffers.get(&path).map_or(false, |(events, _)| {
let total_size: usize = events.iter()
.map(|e| e.estimated_json_encoded_size_of().get())
.sum();
total_size >= batch_settings.size_limit
|| events.len() >= batch_settings.item_limit
});
if needs_flush {
let (events, _generation) = buffers.remove(&path).unwrap();
self.process_batch(path.clone(), events).await;
// The stale deadline entry (generation) remains in the heap but won't
// match the new generation if this path receives more events.
}
// Bound active-buffer memory under high-cardinality templates.
// Also flush expired buffers inline.
{
let now = tokio::time::Instant::now();
loop {
let expire_or_cap =
flush_deadlines.peek().map_or(false,
|std::cmp::Reverse((d, _, _))| {
*d <= now || buffers.len() > 1000
},
);
if !expire_or_cap {
break;
}
let std::cmp::Reverse((_, path, generation)) =
match flush_deadlines.pop() {
Some(e) => e,
None => break,
};
if let Some((events, current_generation)) =
buffers.remove(&path)
{
if current_generation == generation {
self.process_batch(path, events).await;
} else {
buffers.insert(path, (events, current_generation));
}
}
}
}
}
None => {
// Stream exhausted — flush all remaining buffers, then close files.
debug!(message = "Receiver exhausted, flushing remaining buffers.");
let paths: Vec<Bytes> = buffers.keys().cloned().collect();
for p in paths {
if let Some((events, _generation)) = buffers.remove(&p) {
self.process_batch(p, events).await;
}
}
debug!(message = "Closing all the open files.");
for (path, file) in self.files.iter_mut() {
if let Err(error) = file.close().await {
emit!(FileIoError {
error,
code: "failed_closing_file",
message: "Failed to close file.",
path,
dropped_events: 0,
});
} else {
trace!(message = "Successfully closed file.", path = ?path);
}
}
emit!(FileOpen { count: 0 });
break;
}
}
}
result = self.files.next_expired(), if !self.files.is_empty() => {
match result {
None => unreachable!(),
Some((expired_file, path)) => {
self.close_file(expired_file, path).await;
}
}
}
_ = async {
tokio::time::sleep_until(
next_timer_deadline
.unwrap_or_else(|| {
tokio::time::Instant::now()
+ std::time::Duration::from_secs(3600)
}),
).await;
}, if next_timer_deadline.is_some() => {}
}
// Flush any expired buffers after every wake-up.
let now = tokio::time::Instant::now();
loop {
let expired = flush_deadlines.peek().map_or(false,
|std::cmp::Reverse((d, _, _))| *d <= now,
);
if !expired {
break;
}
let std::cmp::Reverse((_, path, generation)) =
match flush_deadlines.pop() {
Some(e) => e,
None => break,
};
if let Some((events, current_generation)) = buffers.remove(&path) {
if current_generation == generation {
self.process_batch(path, events).await;
} else {
buffers.insert(path, (events, current_generation));
}
}
}
}
Ok(())
}
async fn process_batch(&mut self, path: Bytes, mut events: Vec<Event>) {
let next_deadline = self.deadline_at();
trace!(message = "Computed next deadline.", next_deadline = ?next_deadline, path = ?path);
let bytes_path = BytesPath::new(path.clone());
let truncate = self.should_truncate(&bytes_path, &path).await;
let file = if !truncate {
if let Some(file) = self.files.reset_at(&path, next_deadline) {
trace!(message = "Working with an already opened file.", path = ?path);
file
} else {
trace!(message = "Opening new file.", ?path);
let file = match open_file(bytes_path, truncate, self.confinement.as_mut()).await {
Ok(file) => file,
Err(OpenError::Io(error)) => {
// We couldn't open the file for this event.
// Maybe other events will work though! Just log
// the error and skip this event.
let dropped_events = events.len();
emit!(FileIoError {
code: "failed_opening_file",
message: "Unable to open the file.",
error,
path: &path,
dropped_events,
});
events.iter_mut().for_each(|event| {
event.metadata().update_status(EventStatus::Errored);
});
return;
}
Err(OpenError::Confine(error)) => {
let rendered = bytes_to_path(&path);
let base = self
.confinement
.as_ref()
.map(|c| c.base_dir().to_path_buf())
.unwrap_or_default();
emit!(FilePathOutsideBaseDirError {
path: &rendered,
base_dir: &base,
error,
});
events.iter_mut().for_each(|event| {
event.metadata().update_status(EventStatus::Errored);
});
return;
}
};
let outfile = OutFile::new(file, self.compression);
self.files.insert_at(path.clone(), outfile, next_deadline);
emit!(FileOpen {
count: self.files.len()
});
self.files.get_mut(&path).unwrap()
}
} else {
trace!(message = "Opening new file (truncating).", ?path);
let file = match open_file(bytes_path, truncate, self.confinement.as_mut()).await {
Ok(file) => file,
Err(OpenError::Io(error)) => {
let dropped_events = events.len();
emit!(FileIoError {
code: "failed_opening_file",
message: "Unable to open the file.",
error,
path: &path,
dropped_events,
});
events.iter_mut().for_each(|event| {
event.metadata().update_status(EventStatus::Errored);
});
return;
}
Err(OpenError::Confine(error)) => {
let rendered = bytes_to_path(&path);
let base = self
.confinement
.as_ref()
.map(|c| c.base_dir().to_path_buf())
.unwrap_or_default();
emit!(FilePathOutsideBaseDirError {
path: &rendered,
base_dir: &base,
error,
});
events.iter_mut().for_each(|event| {
event.metadata().update_status(EventStatus::Errored);
});
return;
}
};
let outfile = OutFile::new(file, self.compression);
self.files.insert_at(path.clone(), outfile, next_deadline);
emit!(FileOpen {
count: self.files.len()
});
self.files.get_mut(&path).unwrap()
};
// Encode each event individually so we can write them one at a time.
// This ensures that if a write fails partway through (e.g. ENOSPC),
// events already written are acknowledged Delivered and only the
// remaining events are retried, avoiding silent duplicates.
let mut encoded: Vec<(BytesMut, EventFinalizers, JsonSize)> =
Vec::with_capacity(events.len());
trace!(message = "Encoding batch.", batch_size = events.len(), path = ?path);
for mut event in events {
let event_size = event.estimated_json_encoded_size_of();
let finalizers = event.take_finalizers();
self.transformer.transform(&mut event);
let mut buf = BytesMut::new();
match self.encoder.encode(event, &mut buf) {
Ok(()) => encoded.push((buf, finalizers, event_size)),
Err(error) => {
finalizers.update_status(EventStatus::Errored);
emit!(FileIoError {
code: "failed_encoding_event",
message: "Failed to encode event.",
error: std::io::Error::new(std::io::ErrorKind::InvalidData, error),
path: &path,
dropped_events: 1,
});
}
}
}
if encoded.is_empty() {
return;
}
// Combine all encoded records into a single buffer so we issue one
// write syscall per batch for the common uncompressed case. Track
// each event's byte boundary so a partial write (ENOSPC, quota) can
// still acknowledge the events that were fully persisted.
let n_events = encoded.len();
let mut batch_buffer = BytesMut::new();
let mut boundaries: Vec<usize> = Vec::with_capacity(n_events);
for (buf, _, _) in &encoded {
boundaries.push(batch_buffer.len() + buf.len());
batch_buffer.extend_from_slice(buf);
}
let len = batch_buffer.len();
let mut written = 0usize;
let write_result: Result<(), std::io::Error> = loop {
match file.write(&batch_buffer[written..]).await {
Ok(0) => break Err(std::io::Error::new(
std::io::ErrorKind::WriteZero,
"write returned 0",
)),
Ok(n) => {
written += n;
if written >= len {
break Ok(());
}
}
Err(e) => break Err(e),
}
};
match write_result {
Ok(()) => {
for (buf, finalizers, event_size) in encoded {
finalizers.update_status(EventStatus::Delivered);
self.events_sent.emit(CountByteSize(1, event_size));
}
emit!(FileBytesSent {
byte_size: len,
file: String::from_utf8_lossy(&path),
include_file_metric_tag: self.include_file_metric_tag,
});
}
Err(error) => {
// `written` bytes made it to the file / compression stream.
// Events whose end offset lies at or before `written` were
// fully persisted; everything beyond that must be retried.
let mut dropped_events = n_events;
for (i, (buf, finalizers, event_size)) in encoded.into_iter().enumerate() {
if boundaries[i] <= written {
finalizers.update_status(EventStatus::Delivered);
self.events_sent.emit(CountByteSize(1, event_size));
dropped_events -= 1;
} else {
finalizers.update_status(EventStatus::Errored);
if dropped_events == n_events {
dropped_events = n_events - i;
}
}
}
emit!(FileIoError {
code: "failed_writing_file",
message: "Failed to write the file.",
error,
path: &path,
dropped_events,
});
if written > 0 {
emit!(FileBytesSent {
byte_size: written,
file: String::from_utf8_lossy(&path),
include_file_metric_tag: self.include_file_metric_tag,
});
}
}
}
}
async fn should_truncate(&mut self, bytes_path: &BytesPath, path: &bytes::Bytes) -> bool {
let mut truncate = false;
if let Some(after_close_time_secs) = self.truncation_config.after_close_time_secs
&& self.files.get(path).is_none()
&& let Ok(metadata) = fs::metadata(bytes_path).await
&& let Ok(time) = metadata
.modified()
.map_err(|_| ())
.and_then(|t| t.elapsed().map_err(|_| ()))
&& time.as_secs() > after_close_time_secs.into()
{
truncate = true;
}
if let Some(after_secs) = self.truncation_config.after_secs
&& let Some(file) = self.files.get(path)
&& (file.created_at().elapsed().as_secs() > after_secs.into())
{
truncate = true;
}
if let Some(after_modified_time_secs) = self.truncation_config.after_modified_time_secs
&& let Some(previous_modification) = self
.files
.get_with_deadline(path)
.and_then(|(_, deadline)| deadline.checked_sub(self.idle_timeout))
&& previous_modification.elapsed().as_secs() > after_modified_time_secs.into()
{
truncate = true;
}
if truncate && let Some((file, path)) = self.files.remove(path) {
self.close_file(file, path).await;
}
truncate
}
async fn close_file(&self, mut file: OutFile, path: Expired<Bytes>) {
if let Err(error) = file.close().await {
emit!(FileIoError {
error,
code: "failed_closing_file",
message: "Failed to close file.",
path: &path,
dropped_events: 0,
});
}
drop(file); // ignore close error
emit!(FileOpen {
count: self.files.len()
});
}
}
#[cfg(unix)]
fn bytes_to_path(b: &Bytes) -> PathBuf {
use std::os::unix::ffi::OsStrExt;
PathBuf::from(std::ffi::OsStr::from_bytes(b))
}
#[cfg(not(unix))]
fn bytes_to_path(b: &Bytes) -> PathBuf {
PathBuf::from(String::from_utf8_lossy(b).as_ref())
}
/// Errors produced by `open_file`. Routed at the call site so that
/// confinement failures emit `FilePathOutsideBaseDirError` (INTENTIONAL drop)
/// instead of the generic `FileIoError` (UNINTENTIONAL).
#[derive(Debug)]
enum OpenError {
Io(std::io::Error),
Confine(ConfineError),
}
impl std::fmt::Display for OpenError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Io(e) => write!(f, "{e}"),
Self::Confine(e) => write!(f, "{e}"),
}
}
}
impl std::error::Error for OpenError {}
/// Create `path` and all missing ancestors, refusing to follow any symlink
/// in the components that fall *below* `base`.
///
/// The `base` directory is operator-authored and trusted — it is created with
/// the standard `create_dir_all` (which follows symlinks), so paths like
/// `/tmp/myapp` work correctly on macOS where `/tmp → /private/tmp`.
/// Only the suffix of `path` below `base` — the event-controlled part —
/// is walked component-by-component with `lstat` checks.
///
/// A residual TOCTOU window exists between the `symlink_metadata` check and
/// the `create_dir` call. Closing it requires fd-based traversal (`cap-std`),
/// which is Phase 1b scope. `verify_parent` provides a second layer of
/// defence after this call.
#[cfg(unix)]
async fn create_dirs_nofollow(path: &Path, base: &Path) -> std::io::Result<()> {
fs::create_dir_all(base).await?;
let suffix = path.strip_prefix(base).unwrap_or(path);
let mut current = base.to_path_buf();
for component in suffix.components() {
current.push(component);
match fs::symlink_metadata(¤t).await {
Ok(meta) if meta.file_type().is_symlink() => {
return Err(std::io::Error::other(format!(
"intermediate path component {:?} is a symlink",
current
)));
}
Ok(_) => {}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
match fs::create_dir(¤t).await {
Ok(()) => {}
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {}
Err(e) => return Err(e),
}
}
Err(e) => return Err(e),
}
}
Ok(())
}
async fn open_file(
path: impl AsRef<Path>,
truncate: bool,
confinement: Option<&mut PathConfinement>,
) -> Result<File, OpenError> {
let path_ref = path.as_ref();
let parent = path_ref.parent();
let file_name = path_ref.file_name();
let confined = confinement.is_some();
// Extract the base before `confinement` is moved into the open_path match.
#[cfg(unix)]
let base_dir = confinement.as_ref().map(|c| c.base_dir().to_path_buf());
if let Some(parent) = parent {
// When confined, refuse to follow intermediate symlinks in the
// event-controlled portion of the path. On non-Unix platforms we fall
// back to the standard `create_dir_all` (Windows reparse-point
// protection is Phase 1b scope).
#[cfg(unix)]
if let Some(ref base) = base_dir {
create_dirs_nofollow(parent, base)
.await
.map_err(OpenError::Io)?;
} else {
fs::create_dir_all(parent).await.map_err(OpenError::Io)?;
}
#[cfg(not(unix))]
fs::create_dir_all(parent).await.map_err(OpenError::Io)?;
}
// If confined, verify the parent canonicalizes within the base, and
// open relative to the canonicalized parent. This catches symlinks on
// any intermediate directory.
let open_path: PathBuf = match (confinement, parent, file_name) {
(Some(confinement), Some(parent), Some(file_name)) => {
let canonical_parent = confinement
.verify_parent(parent)
.await
.map_err(OpenError::Confine)?;
canonical_parent.join(file_name)
}
_ => path_ref.to_path_buf(),
};
let mut opts = fs::OpenOptions::new();
opts.read(false)
.write(true)
.create(true)
.append(!truncate)
.truncate(truncate);
// Reject final-component symlinks when confined. Do NOT apply
// O_NOFOLLOW to unconfined static paths — operators who intentionally
// symlink their log file (outside the threat model) must keep working.
#[cfg(unix)]
if confined {
opts.custom_flags(libc::O_NOFOLLOW);
}
#[cfg(not(unix))]
let _ = confined;
opts.open(open_path).await.map_err(OpenError::Io)
}
struct FilePathPartitioner {
path: UnconfinedTemplate,
}
impl Partitioner for FilePathPartitioner {
type Item = Event;
type Key = Option<Bytes>;
fn partition(&self, event: &Self::Item) -> Self::Key {