Compare commits

...

2 Commits

Author SHA1 Message Date
fanyang89
0d41253279 fix 2025-09-19 22:32:09 +08:00
fanyang89
c09630006c Add commands to manage configuations 2025-09-19 21:06:13 +08:00
5 changed files with 233 additions and 2 deletions

View File

@@ -109,6 +109,8 @@ enum SubCommand {
Stats(StatsArgs), Stats(StatsArgs),
#[command(about = "manage logger configuration")] #[command(about = "manage logger configuration")]
Logger(LoggerArgs), Logger(LoggerArgs),
#[command(about = "manage network instance configuration")]
Config(ConfigArgs),
#[command(about = t!("core_clap.generate_completions").to_string())] #[command(about = t!("core_clap.generate_completions").to_string())]
GenAutocomplete { shell: Shell }, GenAutocomplete { shell: Shell },
} }
@@ -293,6 +295,23 @@ enum LoggerSubCommand {
}, },
} }
#[derive(Args, Debug)]
struct ConfigArgs {
#[command(subcommand)]
sub_command: Option<ConfigSubCommand>,
}
#[derive(Subcommand, Debug)]
enum ConfigSubCommand {
/// List network instances and their configurations
List,
/// Get configuration for a specific instance
Get {
#[arg(help = "Instance ID")]
inst_id: String,
},
}
#[derive(Args, Debug)] #[derive(Args, Debug)]
struct ServiceArgs { struct ServiceArgs {
#[arg(short, long, default_value = env!("CARGO_PKG_NAME"), help = "service name")] #[arg(short, long, default_value = env!("CARGO_PKG_NAME"), help = "service name")]
@@ -1286,6 +1305,68 @@ impl CommandHandler<'_> {
} }
Ok(ports) Ok(ports)
} }
async fn handle_config_list(&self) -> Result<(), Error> {
let client = self.get_peer_manager_client().await?;
let node_info = client
.show_node_info(BaseController::default(), ShowNodeInfoRequest::default())
.await?
.node_info
.ok_or(anyhow::anyhow!("node info not found"))?;
if self.verbose || *self.output_format == OutputFormat::Json {
println!("{}", serde_json::to_string_pretty(&node_info)?);
return Ok(());
}
#[derive(tabled::Tabled, serde::Serialize)]
struct ConfigTableItem {
#[tabled(rename = "Instance ID")]
inst_id: String,
#[tabled(rename = "Virtual IP")]
ipv4: String,
#[tabled(rename = "Hostname")]
hostname: String,
#[tabled(rename = "Network Name")]
network_name: String,
}
let items = vec![ConfigTableItem {
inst_id: node_info.peer_id.to_string(),
ipv4: node_info.ipv4_addr,
hostname: node_info.hostname,
network_name: "".to_string(), // NodeInfo doesn't have network_name field
}];
print_output(&items, self.output_format)?;
Ok(())
}
async fn handle_config_get(&self, inst_id: &str) -> Result<(), Error> {
let client = self.get_peer_manager_client().await?;
let node_info = client
.show_node_info(BaseController::default(), ShowNodeInfoRequest::default())
.await?
.node_info
.ok_or(anyhow::anyhow!("node info not found"))?;
// Check if the requested instance ID matches the current node
if node_info.peer_id.to_string() != inst_id {
return Err(anyhow::anyhow!(
"Instance ID {} not found. Current instance ID is {}",
inst_id,
node_info.peer_id
));
}
if self.verbose || *self.output_format == OutputFormat::Json {
println!("{}", serde_json::to_string_pretty(&node_info)?);
return Ok(());
}
println!("{}", node_info.config);
Ok(())
}
} }
#[derive(Debug)] #[derive(Debug)]
@@ -2097,6 +2178,14 @@ async fn main() -> Result<(), Error> {
handler.handle_logger_set(level).await?; handler.handle_logger_set(level).await?;
} }
}, },
SubCommand::Config(config_args) => match &config_args.sub_command {
Some(ConfigSubCommand::List) | None => {
handler.handle_config_list().await?;
}
Some(ConfigSubCommand::Get { inst_id }) => {
handler.handle_config_get(inst_id).await?;
}
},
SubCommand::GenAutocomplete { shell } => { SubCommand::GenAutocomplete { shell } => {
let mut cmd = Cli::command(); let mut cmd = Cli::command();
easytier::print_completions(shell, &mut cmd, "easytier-cli"); easytier::print_completions(shell, &mut cmd, "easytier-cli");

View File

@@ -140,6 +140,47 @@ impl NetworkInstanceManager {
.and_then(|instance| instance.value().get_running_info()) .and_then(|instance| instance.value().get_running_info())
} }
pub fn get_network_config(&self, instance_id: &uuid::Uuid) -> Option<TomlConfigLoader> {
self.instance_map
.get(instance_id)
.map(|instance| instance.value().get_config())
}
pub fn replace_network_config(
&self,
instance_id: &uuid::Uuid,
new_config: TomlConfigLoader,
) -> Result<(), anyhow::Error> {
let mut instance = self
.instance_map
.get_mut(instance_id)
.ok_or_else(|| anyhow::anyhow!("instance {} not found", instance_id))?;
// Stop the current instance if it's running
if instance.is_easytier_running() {
// Get the config source before stopping
let config_source = instance.get_config_source();
// Create a new instance with the new config
let mut new_instance = NetworkInstance::new(new_config, config_source);
// Start the new instance
new_instance.start()?;
// Replace the old instance with the new one
*instance = new_instance;
// Restart the instance task if needed
self.start_instance_task(*instance_id)?;
} else {
// If the instance is not running, just replace the config
let config_source = instance.get_config_source();
*instance = NetworkInstance::new(new_config, config_source);
}
Ok(())
}
pub fn list_network_instance_ids(&self) -> Vec<uuid::Uuid> { pub fn list_network_instance_ids(&self) -> Vec<uuid::Uuid> {
self.instance_map.iter().map(|item| *item.key()).collect() self.instance_map.iter().map(|item| *item.key()).collect()
} }

View File

@@ -460,6 +460,10 @@ impl NetworkInstance {
None None
} }
} }
pub fn get_config(&self) -> TomlConfigLoader {
self.config.clone()
}
} }
pub fn add_proxy_network_to_config( pub fn add_proxy_network_to_config(

View File

@@ -178,6 +178,25 @@ message DeleteNetworkInstanceResponse {
repeated common.UUID remain_inst_ids = 1; repeated common.UUID remain_inst_ids = 1;
} }
message GetConfigRequest {
common.UUID inst_id = 1;
}
message GetConfigResponse {
NetworkConfig config = 1;
string toml_config = 2;
}
message ReplaceConfigRequest {
common.UUID inst_id = 1;
NetworkConfig config = 2;
}
message ReplaceConfigResponse {
bool success = 1;
optional string error_msg = 2;
}
service WebClientService { service WebClientService {
rpc ValidateConfig(ValidateConfigRequest) returns (ValidateConfigResponse) {} rpc ValidateConfig(ValidateConfigRequest) returns (ValidateConfigResponse) {}
rpc RunNetworkInstance(RunNetworkInstanceRequest) returns (RunNetworkInstanceResponse) {} rpc RunNetworkInstance(RunNetworkInstanceRequest) returns (RunNetworkInstanceResponse) {}
@@ -185,4 +204,6 @@ service WebClientService {
rpc CollectNetworkInfo(CollectNetworkInfoRequest) returns (CollectNetworkInfoResponse) {} rpc CollectNetworkInfo(CollectNetworkInfoRequest) returns (CollectNetworkInfoResponse) {}
rpc ListNetworkInstance(ListNetworkInstanceRequest) returns (ListNetworkInstanceResponse) {} rpc ListNetworkInstance(ListNetworkInstanceRequest) returns (ListNetworkInstanceResponse) {}
rpc DeleteNetworkInstance(DeleteNetworkInstanceRequest) returns (DeleteNetworkInstanceResponse) {} rpc DeleteNetworkInstance(DeleteNetworkInstanceRequest) returns (DeleteNetworkInstanceResponse) {}
rpc GetConfig(GetConfigRequest) returns (GetConfigResponse) {}
rpc ReplaceConfig(ReplaceConfigRequest) returns (ReplaceConfigResponse) {}
} }

View File

@@ -6,8 +6,9 @@ use crate::{
rpc_types::{self, controller::BaseController}, rpc_types::{self, controller::BaseController},
web::{ web::{
CollectNetworkInfoRequest, CollectNetworkInfoResponse, DeleteNetworkInstanceRequest, CollectNetworkInfoRequest, CollectNetworkInfoResponse, DeleteNetworkInstanceRequest,
DeleteNetworkInstanceResponse, ListNetworkInstanceRequest, ListNetworkInstanceResponse, DeleteNetworkInstanceResponse, GetConfigRequest, GetConfigResponse,
NetworkInstanceRunningInfoMap, RetainNetworkInstanceRequest, ListNetworkInstanceRequest, ListNetworkInstanceResponse, NetworkInstanceRunningInfoMap,
ReplaceConfigRequest, ReplaceConfigResponse, RetainNetworkInstanceRequest,
RetainNetworkInstanceResponse, RunNetworkInstanceRequest, RunNetworkInstanceResponse, RetainNetworkInstanceResponse, RunNetworkInstanceRequest, RunNetworkInstanceResponse,
ValidateConfigRequest, ValidateConfigResponse, WebClientService, ValidateConfigRequest, ValidateConfigResponse, WebClientService,
}, },
@@ -153,4 +154,79 @@ impl WebClientService for Controller {
remain_inst_ids: remain_inst_ids.into_iter().map(Into::into).collect(), remain_inst_ids: remain_inst_ids.into_iter().map(Into::into).collect(),
}) })
} }
// rpc GetConfig(GetConfigRequest) returns (GetConfigResponse) {}
async fn get_config(
&self,
_: BaseController,
req: GetConfigRequest,
) -> Result<GetConfigResponse, rpc_types::error::Error> {
let inst_id = req.inst_id.ok_or_else(|| {
rpc_types::error::Error::ExecutionError(
anyhow::anyhow!("instance_id is required").into(),
)
})?;
let config = self
.manager
.get_network_config(&inst_id.into())
.ok_or_else(|| {
rpc_types::error::Error::ExecutionError(
anyhow::anyhow!("instance {} not found", inst_id).into(),
)
})?;
// Get the NetworkConfig from the instance
let network_config = crate::launcher::NetworkConfig::new_from_config(&config)?;
// Get the TOML config string
let toml_config = config.dump();
Ok(GetConfigResponse {
config: Some(network_config),
toml_config,
})
}
// rpc ReplaceConfig(ReplaceConfigRequest) returns (ReplaceConfigResponse) {}
async fn replace_config(
&self,
_: BaseController,
req: ReplaceConfigRequest,
) -> Result<ReplaceConfigResponse, rpc_types::error::Error> {
let inst_id = req.inst_id.ok_or_else(|| {
rpc_types::error::Error::ExecutionError(
anyhow::anyhow!("instance_id is required").into(),
)
})?;
let new_config = req.config.ok_or_else(|| {
rpc_types::error::Error::ExecutionError(anyhow::anyhow!("config is required").into())
})?;
// Generate the TomlConfigLoader from NetworkConfig
let new_toml_config = new_config.gen_config()?;
// Replace the configuration
match self
.manager
.replace_network_config(&inst_id.into(), new_toml_config)
{
Ok(()) => {
println!("instance {} config replaced successfully", inst_id);
Ok(ReplaceConfigResponse {
success: true,
error_msg: None,
})
}
Err(e) => {
let error_msg = format!("Failed to replace config for instance {}: {}", inst_id, e);
eprintln!("{}", error_msg);
Ok(ReplaceConfigResponse {
success: false,
error_msg: Some(error_msg),
})
}
}
}
} }