work on logger

This commit is contained in:
jb-alvarado 2024-06-04 19:01:53 +02:00
parent e84aa7e4e3
commit 6946b747ee
9 changed files with 878 additions and 1 deletions

2
Cargo.lock generated
View File

@ -1322,6 +1322,7 @@ dependencies = [
"home", "home",
"jsonwebtoken", "jsonwebtoken",
"lazy_static", "lazy_static",
"lettre",
"lexical-sort", "lexical-sort",
"local-ip-address", "local-ip-address",
"log", "log",
@ -1337,6 +1338,7 @@ dependencies = [
"sanitize-filename", "sanitize-filename",
"serde", "serde",
"serde_json", "serde_json",
"shlex",
"signal-child", "signal-child",
"simplelog", "simplelog",
"sqlx", "sqlx",

View File

@ -31,6 +31,7 @@ futures-util = { version = "0.3", default-features = false, features = ["std"] }
home = "0.5" home = "0.5"
jsonwebtoken = "9" jsonwebtoken = "9"
lazy_static = "1.4" lazy_static = "1.4"
lettre = { version = "0.11", features = ["builder", "rustls-tls", "smtp-transport"], default-features = false }
lexical-sort = "0.3" lexical-sort = "0.3"
local-ip-address = "0.6" local-ip-address = "0.6"
log = { version = "0.4", features = ["std", "serde", "kv", "kv_std", "kv_sval", "kv_serde"] } log = { version = "0.4", features = ["std", "serde", "kv", "kv_std", "kv_sval", "kv_serde"] }
@ -47,6 +48,7 @@ sanitize-filename = "0.5"
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0", features = ["derive"] }
serde_json = "1.0" serde_json = "1.0"
simplelog = { version = "0.12", features = ["paris"] } simplelog = { version = "0.12", features = ["paris"] }
shlex = "1.1"
static-files = "0.2" static-files = "0.2"
sysinfo ={ version = "0.30", features = ["linux-netdevs"] } sysinfo ={ version = "0.30", features = ["linux-netdevs"] }
sqlx = { version = "0.7", features = ["runtime-tokio", "sqlite"] } sqlx = { version = "0.7", features = ["runtime-tokio", "sqlite"] }

View File

@ -150,7 +150,7 @@ pub fn file_formatter(
fn main() { fn main() {
let to_file = true; let to_file = true;
Logger::try_with_str("trace") Logger::try_with_str("WARN")
.expect("LogSpecification String has errors") .expect("LogSpecification String has errors")
.format(console_formatter) .format(console_formatter)
.print_message() .print_message()

View File

@ -6,10 +6,12 @@ use sysinfo::{Disks, Networks, System};
pub mod api; pub mod api;
pub mod db; pub mod db;
pub mod macros;
pub mod player; pub mod player;
pub mod sse; pub mod sse;
pub mod utils; pub mod utils;
use utils::advanced_config::AdvancedConfig;
use utils::args_parse::Args; use utils::args_parse::Args;
lazy_static! { lazy_static! {

View File

@ -0,0 +1,6 @@
#[macro_export]
macro_rules! vec_strings {
($($str:expr),*) => ({
vec![$($str.to_string(),)*] as Vec<String>
});
}

View File

@ -0,0 +1,98 @@
use std::{fs::File, io::Read, path::PathBuf};
use serde::{Deserialize, Serialize};
use shlex::split;
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
pub struct AdvancedConfig {
pub decoder: DecoderConfig,
pub encoder: EncoderConfig,
pub ingest: IngestConfig,
}
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
pub struct DecoderConfig {
pub input_param: Option<String>,
pub output_param: Option<String>,
pub filters: Filters,
#[serde(skip_serializing, skip_deserializing)]
pub input_cmd: Option<Vec<String>>,
#[serde(skip_serializing, skip_deserializing)]
pub output_cmd: Option<Vec<String>>,
}
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
pub struct EncoderConfig {
pub input_param: Option<String>,
#[serde(skip_serializing, skip_deserializing)]
pub input_cmd: Option<Vec<String>>,
}
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
pub struct IngestConfig {
pub input_param: Option<String>,
#[serde(skip_serializing, skip_deserializing)]
pub input_cmd: Option<Vec<String>>,
}
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
pub struct Filters {
pub deinterlace: Option<String>,
pub pad_scale_w: Option<String>,
pub pad_scale_h: Option<String>,
pub pad_video: Option<String>,
pub fps: Option<String>,
pub scale: Option<String>,
pub set_dar: Option<String>,
pub fade_in: Option<String>,
pub fade_out: Option<String>,
pub overlay_logo_scale: Option<String>,
pub overlay_logo_fade_in: Option<String>,
pub overlay_logo_fade_out: Option<String>,
pub overlay_logo: Option<String>,
pub tpad: Option<String>,
pub drawtext_from_file: Option<String>,
pub drawtext_from_zmq: Option<String>,
pub aevalsrc: Option<String>,
pub afade_in: Option<String>,
pub afade_out: Option<String>,
pub apad: Option<String>,
pub volume: Option<String>,
pub split: Option<String>,
}
impl AdvancedConfig {
pub fn new(cfg_path: PathBuf) -> Self {
let mut config: AdvancedConfig = Default::default();
if let Ok(mut file) = File::open(cfg_path) {
let mut contents = String::new();
if let Err(e) = file.read_to_string(&mut contents) {
eprintln!("Read advanced config file: {e}")
};
if let Ok(tm) = toml_edit::de::from_str(&contents) {
config = tm
};
if let Some(input_parm) = &config.decoder.input_param {
config.decoder.input_cmd = split(input_parm);
}
if let Some(output_param) = &config.decoder.output_param {
config.decoder.output_cmd = split(output_param);
}
if let Some(input_param) = &config.encoder.input_param {
config.encoder.input_cmd = split(input_param);
}
if let Some(input_param) = &config.ingest.input_param {
config.ingest.input_cmd = split(input_param);
}
};
config
}
}

View File

@ -0,0 +1,585 @@
use std::{
env, fmt,
fs::File,
io::Read,
path::{Path, PathBuf},
process,
str::FromStr,
};
use chrono::NaiveTime;
use log::LevelFilter;
use serde::{de, Deserialize, Deserializer, Serialize, Serializer};
use shlex::split;
use crate::AdvancedConfig;
use crate::utils::{free_tcp_socket, time_to_sec};
use crate::vec_strings;
pub const DUMMY_LEN: f64 = 60.0;
pub const IMAGE_FORMAT: [&str; 21] = [
"bmp", "dds", "dpx", "exr", "gif", "hdr", "j2k", "jpg", "jpeg", "pcx", "pfm", "pgm", "phm",
"png", "psd", "ppm", "sgi", "svg", "tga", "tif", "webp",
];
// Some well known errors can be safely ignore
pub const FFMPEG_IGNORE_ERRORS: [&str; 11] = [
"ac-tex damaged",
"codec s302m, is muxed as a private data stream",
"corrupt decoded frame in stream",
"corrupt input packet in stream",
"end mismatch left",
"Packet corrupt",
"Referenced QT chapter track not found",
"skipped MB in I-frame at",
"Thread message queue blocking",
"Warning MVs not available",
"frame size not set",
];
pub const FFMPEG_UNRECOVERABLE_ERRORS: [&str; 5] = [
"Address already in use",
"Invalid argument",
"Numerical result",
"Error initializing complex filters",
"Error while decoding stream #0:0: Invalid data found when processing input",
];
#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum OutputMode {
Desktop,
HLS,
Null,
Stream,
}
impl FromStr for OutputMode {
type Err = String;
fn from_str(input: &str) -> Result<Self, Self::Err> {
match input {
"desktop" => Ok(Self::Desktop),
"hls" => Ok(Self::HLS),
"null" => Ok(Self::Null),
"stream" => Ok(Self::Stream),
_ => Err("Use 'desktop', 'hls', 'null' or 'stream'".to_string()),
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum ProcessMode {
Folder,
Playlist,
}
impl fmt::Display for ProcessMode {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ProcessMode::Folder => write!(f, "folder"),
ProcessMode::Playlist => write!(f, "playlist"),
}
}
}
impl FromStr for ProcessMode {
type Err = String;
fn from_str(input: &str) -> Result<Self, Self::Err> {
match input {
"folder" => Ok(Self::Folder),
"playlist" => Ok(Self::Playlist),
_ => Err("Use 'folder' or 'playlist'".to_string()),
}
}
}
pub fn string_to_log_level<'de, D>(deserializer: D) -> Result<LevelFilter, D::Error>
where
D: Deserializer<'de>,
{
let s: String = Deserialize::deserialize(deserializer)?;
match s.to_lowercase().as_str() {
"debug" => Ok(LevelFilter::Debug),
"error" => Ok(LevelFilter::Error),
"info" => Ok(LevelFilter::Info),
"trace" => Ok(LevelFilter::Trace),
"warn" => Ok(LevelFilter::Warn),
"off" => Ok(LevelFilter::Off),
_ => Err(de::Error::custom("Error level not exists!")),
}
}
fn log_level_to_string<S>(l: &LevelFilter, s: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
match l {
LevelFilter::Debug => s.serialize_str("DEBUG"),
LevelFilter::Error => s.serialize_str("ERROR"),
LevelFilter::Info => s.serialize_str("INFO"),
LevelFilter::Trace => s.serialize_str("TRACE"),
LevelFilter::Warn => s.serialize_str("WARNING"),
LevelFilter::Off => s.serialize_str("OFF"),
}
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Template {
pub sources: Vec<Source>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Source {
pub start: NaiveTime,
pub duration: NaiveTime,
pub shuffle: bool,
pub paths: Vec<PathBuf>,
}
/// Global Config
///
/// This we init ones, when ffplayout is starting and use them globally in the hole program.
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct PlayoutConfig {
#[serde(default, skip_serializing, skip_deserializing)]
pub advanced: Option<AdvancedConfig>,
pub general: General,
pub rpc_server: RpcServer,
pub mail: Mail,
pub logging: Logging,
pub processing: Processing,
pub ingest: Ingest,
pub playlist: Playlist,
pub storage: Storage,
pub text: Text,
#[serde(default)]
pub task: Task,
pub out: Out,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct General {
pub help_text: String,
pub stop_threshold: f64,
#[serde(default, skip_serializing, skip_deserializing)]
pub config_path: String,
#[serde(default)]
pub stat_file: String,
#[serde(skip_serializing, skip_deserializing)]
pub generate: Option<Vec<String>>,
#[serde(skip_serializing, skip_deserializing)]
pub ffmpeg_filters: Vec<String>,
#[serde(skip_serializing, skip_deserializing)]
pub ffmpeg_libs: Vec<String>,
#[serde(skip_serializing, skip_deserializing)]
pub template: Option<Template>,
#[serde(default, skip_serializing, skip_deserializing)]
pub skip_validation: bool,
#[serde(default, skip_serializing, skip_deserializing)]
pub validate: bool,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct RpcServer {
pub help_text: String,
pub enable: bool,
pub address: String,
pub authorization: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Mail {
pub help_text: String,
pub subject: String,
pub smtp_server: String,
pub starttls: bool,
pub sender_addr: String,
pub sender_pass: String,
pub recipient: String,
pub mail_level: String,
pub interval: u64,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Logging {
pub help_text: String,
pub log_to_file: bool,
pub backup_count: usize,
pub local_time: bool,
pub timestamp: bool,
#[serde(alias = "log_path")]
pub path: PathBuf,
#[serde(
alias = "log_level",
serialize_with = "log_level_to_string",
deserialize_with = "string_to_log_level"
)]
pub level: LevelFilter,
pub ffmpeg_level: String,
pub ingest_level: Option<String>,
#[serde(default)]
pub detect_silence: bool,
#[serde(default)]
pub ignore_lines: Vec<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Processing {
pub help_text: String,
pub mode: ProcessMode,
#[serde(default)]
pub audio_only: bool,
#[serde(default = "default_track_index")]
pub audio_track_index: i32,
#[serde(default)]
pub copy_audio: bool,
#[serde(default)]
pub copy_video: bool,
pub width: i64,
pub height: i64,
pub aspect: f64,
pub fps: f64,
pub add_logo: bool,
pub logo: String,
pub logo_scale: String,
pub logo_opacity: f32,
pub logo_position: String,
#[serde(default = "default_tracks")]
pub audio_tracks: i32,
#[serde(default = "default_channels")]
pub audio_channels: u8,
pub volume: f64,
#[serde(default)]
pub custom_filter: String,
#[serde(skip_serializing, skip_deserializing)]
pub cmd: Option<Vec<String>>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Ingest {
pub help_text: String,
pub enable: bool,
input_param: String,
#[serde(default)]
pub custom_filter: String,
#[serde(skip_serializing, skip_deserializing)]
pub input_cmd: Option<Vec<String>>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Playlist {
pub help_text: String,
pub path: PathBuf,
pub day_start: String,
#[serde(skip_serializing, skip_deserializing)]
pub start_sec: Option<f64>,
pub length: String,
#[serde(skip_serializing, skip_deserializing)]
pub length_sec: Option<f64>,
pub infinit: bool,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Storage {
pub help_text: String,
pub path: PathBuf,
#[serde(skip_serializing, skip_deserializing)]
pub paths: Vec<PathBuf>,
#[serde(alias = "filler_clip")]
pub filler: PathBuf,
pub extensions: Vec<String>,
pub shuffle: bool,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Text {
pub help_text: String,
pub add_text: bool,
#[serde(skip_serializing, skip_deserializing)]
pub node_pos: Option<usize>,
#[serde(skip_serializing, skip_deserializing)]
pub zmq_stream_socket: Option<String>,
#[serde(skip_serializing, skip_deserializing)]
pub zmq_server_socket: Option<String>,
pub fontfile: String,
pub text_from_filename: bool,
pub style: String,
pub regex: String,
}
#[derive(Debug, Default, Serialize, Deserialize, Clone)]
pub struct Task {
pub help_text: String,
pub enable: bool,
pub path: PathBuf,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Out {
pub help_text: String,
pub mode: OutputMode,
pub output_param: String,
#[serde(skip_serializing, skip_deserializing)]
pub output_count: usize,
#[serde(skip_serializing, skip_deserializing)]
pub output_filter: Option<String>,
#[serde(skip_serializing, skip_deserializing)]
pub output_cmd: Option<Vec<String>>,
}
fn default_track_index() -> i32 {
-1
}
fn default_tracks() -> i32 {
1
}
fn default_channels() -> u8 {
2
}
impl PlayoutConfig {
/// Read config from YAML file, and set some extra config values.
pub fn new(cfg_path: Option<PathBuf>, advanced_path: Option<PathBuf>) -> Self {
let mut config_path = PathBuf::from("/etc/ffplayout/ffplayout.toml");
if let Some(cfg) = cfg_path {
config_path = cfg;
}
if !config_path.is_file() {
if Path::new("./assets/ffplayout.toml").is_file() {
config_path = PathBuf::from("./assets/ffplayout.toml")
} else if let Some(p) = env::current_exe().ok().as_ref().and_then(|op| op.parent()) {
config_path = p.join("ffplayout.toml")
};
}
let mut file = match File::open(&config_path) {
Ok(file) => file,
Err(_) => {
eprintln!(
"ffplayout.toml not found!\nPut \"ffplayout.toml\" in \"/etc/playout/\" or beside the executable!"
);
process::exit(1);
}
};
let mut contents = String::new();
if let Err(e) = file.read_to_string(&mut contents) {
eprintln!("Read config file: {e}")
};
let mut config: PlayoutConfig = toml_edit::de::from_str(&contents).unwrap();
if let Some(adv_path) = advanced_path {
config.advanced = Some(AdvancedConfig::new(adv_path))
}
config.general.generate = None;
config.general.config_path = config_path.to_string_lossy().to_string();
config.general.stat_file = home::home_dir()
.unwrap_or_else(env::temp_dir)
.join(if config.general.stat_file.is_empty() {
".ffp_status"
} else {
&config.general.stat_file
})
.display()
.to_string();
if config.logging.ingest_level.is_none() {
config.logging.ingest_level = Some(config.logging.ffmpeg_level.clone())
}
config.playlist.start_sec = Some(time_to_sec(&config.playlist.day_start));
if config.playlist.length.contains(':') {
config.playlist.length_sec = Some(time_to_sec(&config.playlist.length));
} else {
config.playlist.length_sec = Some(86400.0);
}
if config.processing.add_logo && !Path::new(&config.processing.logo).is_file() {
config.processing.add_logo = false;
}
config.processing.logo_scale = config
.processing
.logo_scale
.trim_end_matches('~')
.to_string();
if config.processing.audio_tracks < 1 {
config.processing.audio_tracks = 1
}
let mut process_cmd = vec_strings![];
let advanced_output_cmd = config
.advanced
.as_ref()
.and_then(|a| a.decoder.output_cmd.clone());
if config.processing.audio_only {
process_cmd.append(&mut vec_strings!["-vn"]);
} else if config.processing.copy_video {
process_cmd.append(&mut vec_strings!["-c:v", "copy"]);
} else if let Some(decoder_cmd) = &advanced_output_cmd {
process_cmd.append(&mut decoder_cmd.clone());
} else {
let bitrate = format!(
"{}k",
config.processing.width * config.processing.height / 16
);
let buff_size = format!(
"{}k",
(config.processing.width * config.processing.height / 16) / 2
);
process_cmd.append(&mut vec_strings![
"-pix_fmt",
"yuv420p",
"-r",
&config.processing.fps,
"-c:v",
"mpeg2video",
"-g",
"1",
"-b:v",
&bitrate,
"-minrate",
&bitrate,
"-maxrate",
&bitrate,
"-bufsize",
&buff_size
]);
}
if config.processing.copy_audio {
process_cmd.append(&mut vec_strings!["-c:a", "copy"]);
} else if advanced_output_cmd.is_none() {
process_cmd.append(&mut pre_audio_codec(
&config.processing.custom_filter,
&config.ingest.custom_filter,
config.processing.audio_channels,
));
}
process_cmd.append(&mut vec_strings!["-f", "mpegts", "-"]);
config.processing.cmd = Some(process_cmd);
config.ingest.input_cmd = split(config.ingest.input_param.as_str());
config.out.output_count = 1;
config.out.output_filter = None;
if config.out.mode == OutputMode::Null {
config.out.output_cmd = Some(vec_strings!["-f", "null", "-"]);
} else if let Some(mut cmd) = split(config.out.output_param.as_str()) {
// get output count according to the var_stream_map value, or by counting output parameters
if let Some(i) = cmd.clone().iter().position(|m| m == "-var_stream_map") {
config.out.output_count = cmd[i + 1].split_whitespace().count();
} else {
config.out.output_count = cmd
.iter()
.enumerate()
.filter(|(i, p)| i > &0 && !p.starts_with('-') && !cmd[i - 1].starts_with('-'))
.count();
}
if let Some(i) = cmd.clone().iter().position(|r| r == "-filter_complex") {
config.out.output_filter = Some(cmd[i + 1].clone());
cmd.remove(i);
cmd.remove(i);
}
config.out.output_cmd = Some(cmd);
}
// when text overlay without text_from_filename is on, turn also the RPC server on,
// to get text messages from it
if config.text.add_text && !config.text.text_from_filename {
config.rpc_server.enable = true;
config.text.zmq_stream_socket = free_tcp_socket(String::new());
config.text.zmq_server_socket =
free_tcp_socket(config.text.zmq_stream_socket.clone().unwrap_or_default());
config.text.node_pos = Some(2);
} else {
config.text.zmq_stream_socket = None;
config.text.zmq_server_socket = None;
config.text.node_pos = None;
}
config
}
}
impl Default for PlayoutConfig {
fn default() -> Self {
Self::new(None, None)
}
}
/// When custom_filter contains loudnorm filter use a different audio encoder,
/// s302m has higher quality, but is experimental
/// and works not well together with the loudnorm filter.
fn pre_audio_codec(proc_filter: &str, ingest_filter: &str, channel_count: u8) -> Vec<String> {
let mut codec = vec_strings![
"-c:a",
"s302m",
"-strict",
"-2",
"-sample_fmt",
"s16",
"-ar",
"48000",
"-ac",
channel_count
];
if proc_filter.contains("loudnorm") || ingest_filter.contains("loudnorm") {
codec = vec_strings![
"-c:a",
"mp2",
"-b:a",
"384k",
"-ar",
"48000",
"-ac",
channel_count
];
}
codec
}

View File

@ -0,0 +1,163 @@
extern crate log;
extern crate simplelog;
use std::{
collections::HashMap,
io::{self, ErrorKind, Write},
path::PathBuf,
sync::{atomic::Ordering, Arc, Mutex},
thread::{self, sleep},
time::Duration,
};
use chrono::prelude::*;
use flexi_logger::writers::{FileLogWriter, LogWriter};
use flexi_logger::{Age, Cleanup, Criterion, DeferredNow, FileSpec, Logger, Naming};
use lettre::{
message::header, transport::smtp::authentication::Credentials, Message, SmtpTransport,
Transport,
};
use log::{kv::Value, Level, LevelFilter, Log, Metadata, Record};
use paris::formatter::colorize_string;
use crate::utils::{
config::{Logging, PlayoutConfig},
control::ProcessControl,
};
pub struct LogConsole;
impl LogWriter for LogConsole {
fn write(&self, now: &mut DeferredNow, record: &Record<'_>) -> std::io::Result<()> {
console_formatter(&mut std::io::stderr(), now, record)?;
println!();
Ok(())
}
fn flush(&self) -> std::io::Result<()> {
Ok(())
}
}
struct MultiFileLogger {
config: Logging,
writers: Arc<Mutex<HashMap<String, Arc<Mutex<FileLogWriter>>>>>,
}
impl MultiFileLogger {
pub fn new(config: &Logging) -> Self {
MultiFileLogger {
config: config.clone(),
writers: Arc::new(Mutex::new(HashMap::new())),
}
}
fn get_writer(&self, channel: &str) -> io::Result<Arc<Mutex<FileLogWriter>>> {
let mut writers = self.writers.lock().unwrap();
if !writers.contains_key(channel) {
let writer = FileLogWriter::builder(
FileSpec::default()
.suppress_timestamp()
.directory(self.config.path.clone())
.basename("ffplayout")
.discriminant(channel),
)
.format(file_formatter)
.append()
.rotate(
Criterion::Age(Age::Day),
Naming::TimestampsDirect,
Cleanup::KeepLogFiles(self.config.backup_count),
)
.try_build()
.map_err(|e| io::Error::new(io::ErrorKind::Other, e.to_string()))?;
writers.insert(channel.to_string(), Arc::new(Mutex::new(writer)));
}
Ok(writers.get(channel).unwrap().clone())
}
}
impl LogWriter for MultiFileLogger {
fn write(&self, now: &mut DeferredNow, record: &Record) -> io::Result<()> {
let channel = record
.key_values()
.get("channel".into())
.unwrap_or(Value::null())
.to_string();
let writer = self.get_writer(&channel);
let w = writer?.lock().unwrap().write(now, record);
w
}
fn flush(&self) -> io::Result<()> {
let writers = self.writers.lock().unwrap();
for writer in writers.values() {
writer.lock().unwrap().flush()?;
}
Ok(())
}
}
fn console_formatter(w: &mut dyn Write, _now: &mut DeferredNow, record: &Record) -> io::Result<()> {
let level = match record.level() {
Level::Debug => colorize_string("<bright magenta>[DEBUG]</>"),
Level::Error => colorize_string("<bright red>[ERROR]</>"),
Level::Info => colorize_string("<bright green>[ INFO]</>"),
Level::Trace => colorize_string("<bright yellow>[TRACE]</>"),
Level::Warn => colorize_string("<yellow>[ WARN]</>"),
};
write!(
w,
"{} {}",
level,
colorize_string(record.args().to_string()),
)
}
fn file_formatter(
w: &mut dyn Write,
now: &mut DeferredNow,
record: &Record,
) -> std::io::Result<()> {
write!(
w,
"[{}] {} {}",
now.now().format("%Y-%m-%d %H:%M:%S%.6f"),
record.level(),
record.args()
)
}
fn file_logger(config: &Logging) -> Box<dyn LogWriter> {
if config.log_to_file {
let logger = MultiFileLogger::new(config);
Box::new(logger)
} else {
Box::new(LogConsole)
}
}
/// Initialize our logging, to have:
///
/// - console logger
/// - file logger
/// - mail logger
pub fn init_logging(
config: &PlayoutConfig,
proc_ctl: Option<ProcessControl>,
messages: Option<Arc<Mutex<Vec<String>>>>,
) -> io::Result<()> {
Logger::try_with_str(config.logging.level.as_str())
.map_err(|e| io::Error::new(ErrorKind::Other, e.to_string()))?
.format(console_formatter)
.log_to_stderr()
.add_writer("file", file_logger(&config.logging))
// .add_writer("Mail", Box::new(LogMailer))
.start()
.map_err(|e| io::Error::new(ErrorKind::Other, e.to_string()))?;
Ok(())
}

View File

@ -4,6 +4,7 @@ use std::{
fmt, fmt,
fs::{self, metadata, File}, fs::{self, metadata, File},
io::{stdin, stdout, Read, Write}, io::{stdin, stdout, Read, Write},
net::TcpListener,
path::{Path, PathBuf}, path::{Path, PathBuf},
str::FromStr, str::FromStr,
}; };
@ -12,6 +13,7 @@ use chrono::{format::ParseErrorKind, prelude::*};
use faccess::PathExt; use faccess::PathExt;
use once_cell::sync::OnceCell; use once_cell::sync::OnceCell;
use path_clean::PathClean; use path_clean::PathClean;
use rand::Rng;
use rpassword::read_password; use rpassword::read_password;
use serde::{de, Deserialize, Deserializer, Serialize}; use serde::{de, Deserialize, Deserializer, Serialize};
use simplelog::*; use simplelog::*;
@ -19,11 +21,14 @@ use sqlx::{sqlite::SqliteRow, FromRow, Pool, Row, Sqlite};
use crate::ARGS; use crate::ARGS;
pub mod advanced_config;
pub mod args_parse; pub mod args_parse;
pub mod channels; pub mod channels;
pub mod config;
pub mod control; pub mod control;
pub mod errors; pub mod errors;
pub mod files; pub mod files;
pub mod logging;
pub mod playlist; pub mod playlist;
pub mod system; pub mod system;
@ -388,3 +393,17 @@ where
} }
} }
} }
/// get a free tcp socket
pub fn free_tcp_socket(exclude_socket: String) -> Option<String> {
for _ in 0..100 {
let port = rand::thread_rng().gen_range(45321..54268);
let socket = format!("127.0.0.1:{port}");
if socket != exclude_socket && TcpListener::bind(("127.0.0.1", port)).is_ok() {
return Some(socket);
}
}
None
}