summaryrefslogtreecommitdiff
path: root/crates/jmap/src/api/management/log.rs
blob: 94a87af2b81de8615b0a6bcbd6b2a771529645fa (plain)
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
use std::{
    fs::{self, File},
    io,
    path::Path,
};

use chrono::DateTime;
use common::auth::AccessToken;
use directory::{backend::internal::manage, Permission};
use rev_lines::RevLines;
use serde::Serialize;
use serde_json::json;
use tokio::sync::oneshot;
use utils::url_params::UrlParams;

use crate::{
    api::{http::ToHttpResponse, HttpRequest, HttpResponse, JsonResponse},
    JMAP,
};

#[derive(Serialize)]
struct LogEntry {
    timestamp: String,
    level: String,
    event: String,
    event_id: String,
    details: String,
}

impl JMAP {
    pub async fn handle_view_logs(
        &self,
        req: &HttpRequest,
        access_token: &AccessToken,
    ) -> trc::Result<HttpResponse> {
        // Validate the access token
        access_token.assert_has_permission(Permission::LogsView)?;

        let path = self
            .core
            .metrics
            .log_path
            .clone()
            .ok_or_else(|| manage::unsupported("Tracer log path not configured"))?;

        let params = UrlParams::new(req.uri().query());
        let filter = params.get("filter").unwrap_or_default().to_string();
        let page: usize = params.parse("page").unwrap_or(0);
        let limit: usize = params.parse("limit").unwrap_or(100);
        let offset = page.saturating_sub(1) * limit;

        // TODO: Use worker pool
        let (tx, rx) = oneshot::channel();
        tokio::task::spawn_blocking(move || {
            let _ = tx.send(read_log_files(path, &filter, offset, limit));
        });

        let (total, items) = rx
            .await
            .map_err(|err| {
                trc::EventType::Server(trc::ServerEvent::ThreadError)
                    .reason(err)
                    .caused_by(trc::location!())
            })?
            .map_err(|err| {
                trc::ManageEvent::Error
                    .reason(err)
                    .details("Failed to read log files")
                    .caused_by(trc::location!())
            })?;

        Ok(JsonResponse::new(json!({
            "data": {
                "items": items,
                "total": total,
            },
        }))
        .into_http_response())
    }
}

fn read_log_files(
    path: impl AsRef<Path>,
    filter: &str,
    mut offset: usize,
    limit: usize,
) -> io::Result<(usize, Vec<LogEntry>)> {
    let mut logs = fs::read_dir(path)?.collect::<Result<Vec<_>, _>>()?;
    let mut total = 0;

    // Sort the entries by file name in reverse order.
    logs.sort_by_key(|b| std::cmp::Reverse(b.file_name()));

    // Iterate and print the file names.
    let mut entries = Vec::with_capacity(limit);
    let mut logs = logs.into_iter();
    while let Some(log) = logs.next() {
        if log.file_type()?.is_file() {
            let mut rev_lines = RevLines::new(File::open(log.path())?);

            while let Some(line) = rev_lines.next() {
                let line = line.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
                if filter.is_empty() || line.contains(filter) {
                    total += 1;
                    if offset == 0 {
                        if let Some(entry) = LogEntry::from_line(&line) {
                            entries.push(entry);
                            if entries.len() == limit {
                                if rev_lines.next().is_some() || logs.next().is_some() {
                                    total += limit;
                                }

                                return Ok((total, entries));
                            }
                        }
                    } else {
                        offset -= 1;
                    }
                }
            }
        }
    }

    Ok((total, entries))
}

impl LogEntry {
    fn from_line(line: &str) -> Option<Self> {
        let (timestamp, rest) = line.split_once(' ')?;
        let timestamp = DateTime::parse_from_rfc3339(timestamp).ok()?;
        let (level, rest) = rest.trim().split_once(' ')?;
        let (event, rest) = rest.trim().split_once(" (")?;
        let (event_id, details) = rest.split_once(")")?;
        Some(Self {
            timestamp: timestamp.to_rfc3339_opts(chrono::SecondsFormat::Secs, true),
            level: level.to_string(),
            event: event.to_string(),
            event_id: event_id.to_string(),
            details: details.trim().to_string(),
        })
    }
}