@@ -9,19 +9,20 @@ use systemd::{journal, journal::JournalRef};
99/// contained messages.
1010///
1111/// The options `tail` and `follow` in [`sender`] are taken into account.
12- /// If `follow` is `true` then messages are sent until the channel of
13- /// [`sender`] is closed. In this case an
12+ ///
13+ /// If `tail` is set with `Some(line_count)` then only the last
14+ /// `line_count` messages (or less if not enough available) are sent
15+ /// otherwise all available messages are sent.
16+ ///
17+ /// If `follow` is `true` then additionally all new messages are sent
18+ /// until the channel of [`sender`] is closed. In this case an
1419/// [`Err(kubelet::log::SendError::ChannelClosed)`] will be returned.
1520pub async fn send_messages ( sender : & mut Sender , invocation_id : & str ) -> Result < ( ) > {
1621 let mut journal = journal:: OpenOptions :: default ( ) . open ( ) ?;
1722 let journal = journal. match_add ( "_SYSTEMD_INVOCATION_ID" , invocation_id) ?;
1823
1924 if let Some ( line_count) = sender. tail ( ) {
20- journal. seek_tail ( ) ?;
21- let skipped = journal. previous_skip ( line_count as u64 + 1 ) ?;
22- if skipped < line_count + 1 {
23- journal. seek_head ( ) ?;
24- }
25+ seek_journal_backwards ( journal, line_count) ?;
2526
2627 if sender. follow ( ) {
2728 send_remaining_messages ( journal, sender) . await ?;
@@ -40,6 +41,23 @@ pub async fn send_messages(sender: &mut Sender, invocation_id: &str) -> Result<(
4041 Ok ( ( ) )
4142}
4243
44+ /// Sets the cursor of the journal to the position before the last `count`
45+ /// entries so that the next entry is the first of `count` remaining
46+ /// entries. If the beginning of the journal is reached then the cursor is
47+ /// set to the position before the first entry.
48+ fn seek_journal_backwards ( journal : & mut JournalRef , count : usize ) -> Result < ( ) > {
49+ journal. seek_tail ( ) ?;
50+
51+ let entries_to_skip = count + 1 ;
52+ let skipped = journal. previous_skip ( entries_to_skip as u64 ) ?;
53+ let beginning_reached = skipped < entries_to_skip;
54+ if beginning_reached {
55+ journal. seek_head ( ) ?;
56+ }
57+
58+ Ok ( ( ) )
59+ }
60+
4361/// Sends the given number of messages from the journal.
4462async fn send_n_messages (
4563 journal : & mut JournalRef ,
@@ -80,9 +98,11 @@ fn next_message(journal: &mut JournalRef) -> Result<Option<String>> {
8098 if let Some ( value) = entry. value ( ) {
8199 String :: from_utf8_lossy ( value) . into ( )
82100 } else {
101+ // The MESSAGE field contains no text, i.e. `MESSAGE=`.
83102 String :: new ( )
84103 }
85104 } else {
105+ // The journal entry contains no MESSAGE field.
86106 String :: new ( )
87107 } ;
88108 Some ( message)
0 commit comments