iscsi-client-rs 0.0.9

A pure-Rust iSCSI initiator library
Documentation
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
// SPDX-License-Identifier: AGPL-3.0-or-later
// Copyright (C) 2012-2025 Andrei Maltsev

use std::{
    fmt::Debug,
    fs,
    future::Future,
    path::{Path, PathBuf},
    sync::Arc,
};

use anyhow::{Context, Result};
use chrono::Utc;
use fastrace::collector::{Config, ConsoleReporter};
use serde::{Deserialize, Serialize};
use simd_json::{json, value::owned::Object as JsonObject};
use tokio::{self, fs::File, io::AsyncWriteExt};
use tracing::{Event, Subscriber, span};
use tracing_appender::{
    non_blocking::WorkerGuard,
    rolling::{RollingFileAppender, Rotation},
};
use tracing_subscriber::{
    EnvFilter, Registry,
    fmt::{
        self, FmtContext, FormatEvent, FormatFields,
        format::{JsonFields, Writer},
        writer::BoxMakeWriter,
    },
    layer::{Layer, SubscriberExt},
    registry::LookupSpan,
};

#[derive(Debug, Deserialize, Clone)]
/// Configuration wrapper for logger settings
///
/// Contains the main logger configuration structure.
struct LoggerConfig {
    logger: LogConfig,
}

#[derive(Debug, Deserialize, Clone)]
#[serde(rename_all = "lowercase")]
/// Output destination for log messages
///
/// Specifies where log messages should be written - to stdout, stderr, or a
/// file.
enum Output {
    Stdout,
    Stderr,
    File,
}

#[derive(Debug, Deserialize, Clone)]
#[serde(rename_all = "lowercase")]
/// Log file rotation frequency
///
/// Defines how often log files should be rotated to prevent them from growing
/// too large.
enum RotationFreq {
    Minutely,
    Hourly,
    Daily,
    Never,
}

#[derive(Debug, Deserialize, Clone)]
/// Configuration for file-based logging
///
/// Specifies the file path and rotation frequency for file-based log output.
struct LogFileConfig {
    path: String,
    #[serde(default)]
    rotation_frequency: Option<RotationFreq>,
}

#[derive(Debug, Deserialize, Clone)]
/// Main logging configuration structure
///
/// Contains all configuration parameters for the logging system including
/// log level, output destination, formatting options, and file configuration.
struct LogConfig {
    level: String,
    output: Output,
    is_show_line: bool,
    is_show_module_path: bool,
    is_show_target: bool,
    file: Option<LogFileConfig>,
}

/// Container for span field data
///
/// Holds structured data fields associated with tracing spans as a JSON map.
#[derive(Default, Debug)]
struct SpanFields(pub JsonObject);

/// Tracing layer for capturing span field data
///
/// A tracing-subscriber layer that captures and stores field data from spans.
struct CaptureSpanFieldsLayer;

impl<S> Layer<S> for CaptureSpanFieldsLayer
where S: Subscriber + for<'a> LookupSpan<'a>
{
    fn on_new_span(
        &self,
        attrs: &span::Attributes<'_>,
        id: &span::Id,
        ctx: tracing_subscriber::layer::Context<'_, S>,
    ) {
        if let Some(span) = ctx.span(id) {
            let mut map = JsonObject::with_capacity(8);
            struct V<'a>(&'a mut JsonObject);
            impl<'a> tracing::field::Visit for V<'a> {
                fn record_debug(&mut self, f: &tracing::field::Field, v: &dyn Debug) {
                    self.0
                        .insert(f.name().to_string(), json!(format!("{:?}", v)));
                }

                fn record_i64(&mut self, f: &tracing::field::Field, v: i64) {
                    self.0.insert(f.name().to_string(), json!(v));
                }

                fn record_u64(&mut self, f: &tracing::field::Field, v: u64) {
                    self.0.insert(f.name().to_string(), json!(v));
                }

                fn record_bool(&mut self, f: &tracing::field::Field, v: bool) {
                    self.0.insert(f.name().to_string(), json!(v));
                }

                fn record_str(&mut self, f: &tracing::field::Field, v: &str) {
                    self.0.insert(f.name().to_string(), json!(v));
                }
            }
            let mut vis = V(&mut map);
            attrs.record(&mut vis);
            span.extensions_mut().insert(SpanFields(map));
        }
    }

    fn on_record(
        &self,
        id: &span::Id,
        values: &span::Record<'_>,
        ctx: tracing_subscriber::layer::Context<'_, S>,
    ) {
        if let Some(span) = ctx.span(id)
            && let Some(fields) = span.extensions_mut().get_mut::<SpanFields>()
        {
            struct V<'a>(&'a mut JsonObject);
            impl<'a> tracing::field::Visit for V<'a> {
                fn record_debug(&mut self, f: &tracing::field::Field, v: &dyn Debug) {
                    self.0
                        .insert(f.name().to_string(), json!(format!("{:?}", v)));
                }

                fn record_i64(&mut self, f: &tracing::field::Field, v: i64) {
                    self.0.insert(f.name().to_string(), json!(v));
                }

                fn record_u64(&mut self, f: &tracing::field::Field, v: u64) {
                    self.0.insert(f.name().to_string(), json!(v));
                }

                fn record_bool(&mut self, f: &tracing::field::Field, v: bool) {
                    self.0.insert(f.name().to_string(), json!(v));
                }

                fn record_str(&mut self, f: &tracing::field::Field, v: &str) {
                    self.0.insert(f.name().to_string(), json!(v));
                }
            }
            let mut vis = V(&mut fields.0);
            values.record(&mut vis);
        }
    }
}

/// JSON formatter for log messages
///
/// Formats log messages as JSON with configurable fields and structure.
struct JsonFormatter {
    config: Arc<LogConfig>,
}

impl JsonFormatter {
    fn new(config: Arc<LogConfig>) -> Self {
        Self { config }
    }
}

#[derive(Serialize)]
/// Structured log entry for JSON serialization
///
/// Represents a single log entry with timestamp, level, source location,
/// and structured field data for JSON output format.
struct LogEntry {
    timestamp: String,
    level: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    target: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    module_path: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    line: Option<u32>,
    fields: JsonObject,
}

/// Example usage:
/// let span = tracing::info_span!("my_span_after");
/// {
///     let _g = span.enter();
///     tracing::info!("info in span");
///     tracing::debug!("debug in span");
/// }
impl<S, N> FormatEvent<S, N> for JsonFormatter
where
    S: Subscriber + for<'a> LookupSpan<'a>,
    N: for<'a> FormatFields<'a> + 'static,
{
    fn format_event(
        &self,
        ctx: &FmtContext<'_, S, N>,
        mut writer: Writer<'_>,
        event: &Event<'_>,
    ) -> std::fmt::Result {
        let mut visitor = JsonVisitor::default();
        event.record(&mut visitor);

        let mut fields = visitor.fields;

        if let Some(scope) = ctx.event_scope() {
            let mut span_names = Vec::with_capacity(8);
            for span in scope.from_root() {
                span_names.push(span.name().to_string());
                if let Some(ext) = span.extensions().get::<SpanFields>() {
                    for (k, v) in &ext.0 {
                        fields.entry(k.clone()).or_insert(v.clone());
                    }
                }
            }
            fields.insert("span_names".to_string(), json!(span_names));
        }

        let log_entry = LogEntry {
            timestamp: Utc::now().to_rfc3339(),
            level: event.metadata().level().to_string(),
            target: if self.config.is_show_target {
                Some(event.metadata().target().to_string())
            } else {
                None
            },
            module_path: if self.config.is_show_module_path {
                Some(event.metadata().module_path().unwrap_or("").to_string())
            } else {
                None
            },
            line: if self.config.is_show_line {
                event.metadata().line()
            } else {
                None
            },
            fields,
        };

        writeln!(
            writer,
            "{}",
            simd_json::to_string(&log_entry).map_err(|_| std::fmt::Error)?
        )
    }
}

#[derive(Default)]
/// Visitor for collecting structured log fields
///
/// Implements the tracing field visitor pattern to collect log fields
/// into a JSON map structure for structured logging output.
struct JsonVisitor {
    fields: JsonObject,
}

impl tracing::field::Visit for JsonVisitor {
    fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn Debug) {
        self.fields
            .insert(field.name().to_string(), json!(format!("{:?}", value)));
    }

    fn record_i64(&mut self, field: &tracing::field::Field, value: i64) {
        self.fields.insert(field.name().to_string(), json!(value));
    }

    fn record_u64(&mut self, field: &tracing::field::Field, value: u64) {
        self.fields.insert(field.name().to_string(), json!(value));
    }

    fn record_bool(&mut self, field: &tracing::field::Field, value: bool) {
        self.fields.insert(field.name().to_string(), json!(value));
    }

    fn record_str(&mut self, field: &tracing::field::Field, value: &str) {
        self.fields.insert(field.name().to_string(), json!(value));
    }
}

pub fn init_logger(config_path: &str) -> anyhow::Result<WorkerGuard> {
    let config_content = fs::read_to_string(config_path)
        .with_context(|| format!("Failed to read config file: {config_path}"))?;
    let config: LoggerConfig = serde_yaml::from_str(&config_content)
        .with_context(|| format!("Failed to parse config file: {config_path}"))?;

    let (writer, guard) = make_writer(&config.logger)?;

    fastrace::set_reporter(ConsoleReporter, Config::default());
    let compat_layer = fastrace_tracing::FastraceCompatLayer::new();

    let env_filter = EnvFilter::try_new(&config.logger.level)
        .or_else(|_| EnvFilter::try_from_default_env())
        .context("Failed to parse log level from config or env")?;

    let json_layer = fmt::layer()
        .with_writer(writer)
        .with_ansi(false)
        .json()
        .event_format(JsonFormatter::new(Arc::new(config.logger)))
        .fmt_fields(JsonFields::default());

    let subscriber = Registry::default()
        .with(env_filter)
        .with(compat_layer)
        .with(CaptureSpanFieldsLayer)
        .with(json_layer);

    tracing::subscriber::set_global_default(subscriber)
        .context("Failed to set global default subscriber")?;

    Ok(guard)
}

fn make_writer(cfg: &LogConfig) -> anyhow::Result<(BoxMakeWriter, WorkerGuard)> {
    Ok(match cfg.output {
        Output::Stdout => {
            let (w, g) = tracing_appender::non_blocking(std::io::stdout());
            (BoxMakeWriter::new(w), g)
        },
        Output::Stderr => {
            let (w, g) = tracing_appender::non_blocking(std::io::stderr());
            (BoxMakeWriter::new(w), g)
        },
        Output::File => {
            let fcfg = cfg
                .file
                .clone()
                .context("log.file is required for output=file")?;
            let path = PathBuf::from(&fcfg.path);
            let dir = path.parent().unwrap_or_else(|| Path::new(""));

            let rotation = match fcfg.rotation_frequency.unwrap_or(RotationFreq::Never) {
                RotationFreq::Minutely => Rotation::MINUTELY,
                RotationFreq::Hourly => Rotation::HOURLY,
                RotationFreq::Daily => Rotation::DAILY,
                RotationFreq::Never => Rotation::NEVER,
            };

            let file_appender = RollingFileAppender::new(
                rotation,
                dir,
                path.file_name().unwrap_or_default(),
            );
            let (w, g) = tracing_appender::non_blocking(file_appender);
            (BoxMakeWriter::new(w), g)
        },
    })
}

/// Trait for objects that can be logged to files
///
/// Provides functionality for saving content to log files with customizable
/// naming and asynchronous file operations.
pub trait LoggableToFile {
    fn get_name() -> &'static str {
        "unknown"
    }

    fn save_to_file(
        file_name: &str,
        content: &str,
    ) -> impl Future<Output = Result<()>> + Send {
        perform_save_to_file(file_name, content)
    }
}

pub async fn perform_save_to_file<P: AsRef<Path>, C: AsRef<[u8]>>(
    file_name: P,
    content: C,
) -> Result<()> {
    if let Some(parent_dir) = file_name.as_ref().parent() {
        tokio::fs::create_dir_all(parent_dir)
            .await
            .context("Failed to create directory for the file")?;
    }

    let mut file = File::create(&file_name)
        .await
        .context("Failed to create file")?;
    file.write_all(content.as_ref())
        .await
        .context("Failed to write content to file")?;

    Ok(())
}