master
veypi 11 months ago
parent 3f3681b037
commit 236eabcab5

@ -14,95 +14,13 @@ use std::{
time::Duration, time::Duration,
}; };
use clap::{Args, Parser, Subcommand};
use sea_orm::{ConnectOptions, Database, DatabaseConnection}; use sea_orm::{ConnectOptions, Database, DatabaseConnection};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sqlx::{mysql::MySqlPoolOptions, Pool}; use sqlx::{mysql::MySqlPoolOptions, Pool};
use tracing::{info, Level}; use tracing::Level;
use crate::Result; use crate::Result;
// lazy_static! {
// pub static ref CLI: AppCli = AppCli::new();
// }
// use lazy_static::lazy_static;
// lazy_static! {
// pub static ref CONFIG: ApplicationConfig = ApplicationConfig::new();
// }
#[derive(Debug, Parser)]
#[clap(name = "oab")]
#[clap(about = "oab", long_about = None)]
pub struct AppCli {
#[clap(short = 'c', value_name = "cfg",default_value_t = String::from("~/.config/oa/oab.yml"), value_hint = clap::ValueHint::DirPath)]
cfg: String,
#[clap(subcommand)]
pub command: Option<Clis>,
}
#[derive(Debug, Subcommand)]
pub enum Clis {
Init,
Install,
Uninstall,
Start,
Stop,
Web,
Dump,
Cfg(CfgOpt),
}
#[derive(Debug, Args)]
#[clap(args_conflicts_with_subcommands = true)]
pub struct CfgOpt {
command: Option<String>,
}
impl AppCli {
pub fn new() -> Self {
AppCli::parse()
}
pub fn handle_service(&self, data: AppState) -> Result<bool> {
let label: service_manager::ServiceLabel = "v.oa".parse().unwrap();
// Get generic service by detecting what is available on the platform
let manager = <dyn service_manager::ServiceManager>::native()
.expect("Failed to detect management platform");
if let Some(c) = &self.command {
match c {
Clis::Install => {
let p = std::env::current_exe()?;
info!("deploy {}", p.to_str().unwrap());
manager.install(service_manager::ServiceInstallCtx {
label: label.clone(),
program: p,
args: vec![],
contents: None, // Optional String for system-specific service content.
})?
}
Clis::Uninstall => manager.uninstall(service_manager::ServiceUninstallCtx {
label: label.clone(),
})?,
Clis::Start => manager.start(service_manager::ServiceStartCtx {
label: label.clone(),
})?,
Clis::Stop => manager.stop(service_manager::ServiceStopCtx {
label: label.clone(),
})?,
Clis::Dump => {
let res = serde_yaml::to_string(&data)?;
println!("{}", res);
}
_ => return Ok(false),
}
return Ok(true);
};
Ok(false)
}
}
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]
pub struct ApplicationConfig { pub struct ApplicationConfig {
#[serde(skip)] #[serde(skip)]
@ -130,6 +48,7 @@ pub struct AppState {
pub db_pass: String, pub db_pass: String,
pub db_name: String, pub db_name: String,
pub log_dir: Option<String>, pub log_dir: Option<String>,
pub auto_task: bool,
pub fs_root: String, pub fs_root: String,
pub ts_url: String, pub ts_url: String,
pub nats_url: String, pub nats_url: String,
@ -149,9 +68,9 @@ pub struct AppState {
} }
impl AppState { impl AppState {
pub fn new(cli: &AppCli) -> Self { pub fn new(cli_path: &str) -> Self {
let mut res = Self::defaut(); let mut res = Self::defaut();
let mut f = match File::open(cli.cfg.clone()) { let mut f = match File::open(cli_path) {
Ok(f) => f, Ok(f) => f,
Err(ref e) if e.kind() == io::ErrorKind::NotFound => { Err(ref e) if e.kind() == io::ErrorKind::NotFound => {
// res.connect_sqlx().unwrap(); // res.connect_sqlx().unwrap();
@ -159,7 +78,7 @@ impl AppState {
} }
Err(e) => panic!("{}", e), Err(e) => panic!("{}", e),
}; };
File::open(cli.cfg.clone()).unwrap(); File::open(cli_path).unwrap();
let mut yml_data = String::new(); let mut yml_data = String::new();
f.read_to_string(&mut yml_data).unwrap(); f.read_to_string(&mut yml_data).unwrap();
//读取配置 //读取配置
@ -177,6 +96,7 @@ impl AppState {
db_pass: "123456".to_string(), db_pass: "123456".to_string(),
db_name: "oneauth".to_string(), db_name: "oneauth".to_string(),
log_dir: None, log_dir: None,
auto_task: true,
media_path: "/Users/veypi/test/media".to_string(), media_path: "/Users/veypi/test/media".to_string(),
fs_root: "/Users/veypi/test/media".to_string(), fs_root: "/Users/veypi/test/media".to_string(),
log_level: None, log_level: None,

@ -5,52 +5,81 @@
// Distributed under terms of the Apache license. // Distributed under terms of the Apache license.
// //
use crate::cfg::AppState;
use crate::Result;
use clap::{Args, Parser, Subcommand}; use clap::{Args, Parser, Subcommand};
use tracing::info;
use lazy_static::lazy_static;
lazy_static! {
pub static ref CLI: cli = cli::new();
}
#[derive(Debug, Parser)] #[derive(Debug, Parser)]
#[clap(name = "oab")] #[clap(name = "oab")]
#[clap(about = "oab", long_about = None)] #[clap(about = "oab", long_about = None)]
struct cli { pub struct AppCli {
#[clap(short = 'c', value_name = "cfg",default_value_t = String::from("~/.config/oa/oab.yml"), value_hint = clap::ValueHint::DirPath)]
pub cfg: String,
#[clap(short = 'n', value_name = "name",default_value_t = String::from("v.oab"))]
pub name: String,
#[clap(subcommand)] #[clap(subcommand)]
command: Commands, pub command: Option<Clis>,
} }
#[derive(Debug, Subcommand)] #[derive(Debug, Subcommand)]
enum Commands { pub enum Clis {
/// Clones repos Init,
#[clap(arg_required_else_help = true)] Install,
Clone { Uninstall,
/// The remote to clone Start,
#[clap(value_parser)] Stop,
remote: String, Web,
}, Dump,
/// pushes things Cfg(CfgOpt),
#[clap(arg_required_else_help = true)]
Push {
/// The remote to target
#[clap(value_parser)]
remote: String,
},
/// adds things
#[clap(arg_required_else_help = true)]
Add {
/// Stuff to add
#[clap(required = true, value_parser)]
path: Vec<PathBuf>,
},
Stash(Stash),
#[clap(external_subcommand)]
External(Vec<OsString>),
} }
impl cli { #[derive(Debug, Args)]
fn new() -> Self { #[clap(args_conflicts_with_subcommands = true)]
cli::parse() pub struct CfgOpt {
command: Option<String>,
}
impl AppCli {
pub fn new() -> Self {
AppCli::parse()
}
pub fn handle_service(&self, data: AppState) -> Result<bool> {
let label: service_manager::ServiceLabel = self.name.parse().unwrap();
// Get generic service by detecting what is available on the platform
let manager = <dyn service_manager::ServiceManager>::native()
.expect("Failed to detect management platform");
if let Some(c) = &self.command {
match c {
Clis::Install => {
let p = std::env::current_exe()?;
info!("deploy {} -c {}", p.to_str().unwrap(), self.cfg);
manager.install(service_manager::ServiceInstallCtx {
label: label.clone(),
program: p,
args: vec![format!("-c {}", self.cfg).into()],
contents: None, // Optional String for system-specific service content.
})?
}
Clis::Uninstall => manager.uninstall(service_manager::ServiceUninstallCtx {
label: label.clone(),
})?,
Clis::Start => manager.start(service_manager::ServiceStartCtx {
label: label.clone(),
})?,
Clis::Stop => manager.stop(service_manager::ServiceStopCtx {
label: label.clone(),
})?,
Clis::Dump => {
let res = serde_yaml::to_string(&data)?;
println!("{}", res);
}
_ => return Ok(false),
}
return Ok(true);
};
Ok(false)
} }
} }

@ -7,9 +7,11 @@
pub mod api; pub mod api;
mod cfg; mod cfg;
mod cli;
pub mod fs; pub mod fs;
pub mod libs; pub mod libs;
pub mod models; pub mod models;
mod result; mod result;
pub use cfg::{init_log, AppCli, AppState, ApplicationConfig, Clis, InfoOpt}; pub use cfg::{init_log, AppState, ApplicationConfig, InfoOpt};
pub use cli::{AppCli, Clis};
pub use result::{Error, Result}; pub use result::{Error, Result};

@ -22,14 +22,13 @@ use tracing::{error, info, warn};
#[tokio::main] #[tokio::main]
async fn main() -> Result<()> { async fn main() -> Result<()> {
let cli = AppCli::new(); let cli = AppCli::new();
let mut data = AppState::new(&cli); let mut data = AppState::new(&cli.cfg);
if data.debug { if data.debug {
std::env::set_var("RUST_LOG", "debug"); std::env::set_var("RUST_LOG", "debug");
std::env::set_var("RUST_BACKTRACE", "full"); std::env::set_var("RUST_BACKTRACE", "full");
} }
let _log = init_log(&data); let _log = init_log(&data);
if cli.handle_service(data.clone())? { if cli.handle_service(data.clone())? {
info!("2");
return Ok(()); return Ok(());
} }
if let Some(c) = &cli.command { if let Some(c) = &cli.command {
@ -44,13 +43,14 @@ async fn main() -> Result<()> {
}; };
data.connect().await?; data.connect().await?;
data.connect_sqlx()?; data.connect_sqlx()?;
if data.auto_task {
libs::task::start_stats_info(data.ts_url.clone());
}
web(data).await?; web(data).await?;
Ok(()) Ok(())
} }
async fn web(data: AppState) -> Result<()> { async fn web(data: AppState) -> Result<()> {
// libs::task::start_nats_online(client.clone());
libs::task::start_stats_info(data.ts_url.clone());
let url = data.server_url.clone(); let url = data.server_url.clone();
let serv = HttpServer::new(move || { let serv = HttpServer::new(move || {
let logger = middleware::Logger::default(); let logger = middleware::Logger::default();

Loading…
Cancel
Save