Merge pull request #1983 from ethcore/ipc-rel-dir

Use relative path for IPC sockets
This commit is contained in:
Nikolay Volf 2016-08-23 16:36:23 +04:00 committed by GitHub
commit f2be2aec68
11 changed files with 95 additions and 24 deletions

View File

@ -60,6 +60,7 @@ impl ClientService {
config: ClientConfig, config: ClientConfig,
spec: &Spec, spec: &Spec,
db_path: &Path, db_path: &Path,
ipc_path: &Path,
miner: Arc<Miner>, miner: Arc<Miner>,
) -> Result<ClientService, Error> ) -> Result<ClientService, Error>
{ {
@ -86,7 +87,7 @@ impl ClientService {
try!(io_service.register_handler(client_io)); try!(io_service.register_handler(client_io));
let stop_guard = ::devtools::StopGuard::new(); let stop_guard = ::devtools::StopGuard::new();
run_ipc(client.clone(), stop_guard.share()); run_ipc(ipc_path, client.clone(), stop_guard.share());
Ok(ClientService { Ok(ClientService {
io_service: Arc::new(io_service), io_service: Arc::new(io_service),
@ -167,10 +168,13 @@ impl IoHandler<ClientIoMessage> for ClientIoHandler {
} }
#[cfg(feature="ipc")] #[cfg(feature="ipc")]
fn run_ipc(client: Arc<Client>, stop: Arc<AtomicBool>) { fn run_ipc(base_path: &Path, client: Arc<Client>, stop: Arc<AtomicBool>) {
let mut path = base_path.to_owned();
path.push("parity-chain.ipc");
let socket_addr = format!("ipc://{}", path.to_string_lossy());
::std::thread::spawn(move || { ::std::thread::spawn(move || {
let mut worker = nanoipc::Worker::new(&(client as Arc<BlockChainClient>)); let mut worker = nanoipc::Worker::new(&(client as Arc<BlockChainClient>));
worker.add_reqrep("ipc:///tmp/parity-chain.ipc").expect("Ipc expected to initialize with no issues"); worker.add_reqrep(&socket_addr).expect("Ipc expected to initialize with no issues");
while !stop.load(::std::sync::atomic::Ordering::Relaxed) { while !stop.load(::std::sync::atomic::Ordering::Relaxed) {
worker.poll(); worker.poll();
@ -179,7 +183,7 @@ fn run_ipc(client: Arc<Client>, stop: Arc<AtomicBool>) {
} }
#[cfg(not(feature="ipc"))] #[cfg(not(feature="ipc"))]
fn run_ipc(_client: Arc<Client>, _stop: Arc<AtomicBool>) { fn run_ipc(_base_path: &Path, _client: Arc<Client>, _stop: Arc<AtomicBool>) {
} }
#[cfg(test)] #[cfg(test)]
@ -203,6 +207,7 @@ mod tests {
ClientConfig::default(), ClientConfig::default(),
&spec, &spec,
&path, &path,
&path,
Arc::new(Miner::with_spec(&spec)), Arc::new(Miner::with_spec(&spec)),
); );
assert!(service.is_ok()); assert!(service.is_ok());

View File

@ -26,7 +26,7 @@ extern crate semver;
pub mod service; pub mod service;
/// Default value for hypervisor ipc listener /// Default value for hypervisor ipc listener
pub const HYPERVISOR_IPC_URL: &'static str = "ipc:///tmp/parity-internal-hyper-status.ipc"; pub const HYPERVISOR_IPC_URL: &'static str = "parity-internal-hyper-status.ipc";
use std::sync::{Arc,RwLock}; use std::sync::{Arc,RwLock};
use service::{HypervisorService, IpcModuleId}; use service::{HypervisorService, IpcModuleId};
@ -43,6 +43,7 @@ pub struct Hypervisor {
ipc_worker: RwLock<nanoipc::Worker<HypervisorService>>, ipc_worker: RwLock<nanoipc::Worker<HypervisorService>>,
processes: RwLock<HashMap<IpcModuleId, Child>>, processes: RwLock<HashMap<IpcModuleId, Child>>,
modules: HashMap<IpcModuleId, BootArgs>, modules: HashMap<IpcModuleId, BootArgs>,
pub io_path: String,
} }
/// Boot arguments for binary /// Boot arguments for binary
@ -90,6 +91,11 @@ impl Hypervisor {
self self
} }
pub fn io_path(mut self, directory: &str) -> Hypervisor {
self.io_path = directory.to_owned();
self
}
/// Starts with the specified address for the ipc listener and /// Starts with the specified address for the ipc listener and
/// the specified list of modules in form of created service /// the specified list of modules in form of created service
pub fn with_url(addr: &str) -> Hypervisor { pub fn with_url(addr: &str) -> Hypervisor {
@ -101,6 +107,7 @@ impl Hypervisor {
ipc_worker: RwLock::new(worker), ipc_worker: RwLock::new(worker),
processes: RwLock::new(HashMap::new()), processes: RwLock::new(HashMap::new()),
modules: HashMap::new(), modules: HashMap::new(),
io_path: "/tmp".to_owned(),
} }
} }

View File

@ -97,6 +97,7 @@ pub fn init_client<S>(socket_addr: &str) -> Result<GuardedSocket<S>, SocketError
SocketError::RequestLink SocketError::RequestLink
})); }));
trace!(target: "ipc", "Created cleint for {}", socket_addr);
Ok(GuardedSocket { Ok(GuardedSocket {
client: Arc::new(S::init(socket)), client: Arc::new(S::init(socket)),
_endpoint: endpoint, _endpoint: endpoint,
@ -189,6 +190,8 @@ impl<S: ?Sized> Worker<S> where S: IpcInterface {
self.rebuild_poll_request(); self.rebuild_poll_request();
trace!(target: "ipc", "Started duplex worker at {}", addr);
Ok(()) Ok(())
} }
@ -200,6 +203,7 @@ impl<S: ?Sized> Worker<S> where S: IpcInterface {
SocketError::DuplexLink SocketError::DuplexLink
})); }));
let endpoint = try!(socket.bind(addr).map_err(|e| { let endpoint = try!(socket.bind(addr).map_err(|e| {
warn!(target: "ipc", "Failed to bind socket to address '{}': {:?}", addr, e); warn!(target: "ipc", "Failed to bind socket to address '{}': {:?}", addr, e);
SocketError::DuplexLink SocketError::DuplexLink
@ -209,6 +213,7 @@ impl<S: ?Sized> Worker<S> where S: IpcInterface {
self.rebuild_poll_request(); self.rebuild_poll_request();
trace!(target: "ipc", "Started request-reply worker at {}", addr);
Ok(()) Ok(())
} }
} }

View File

@ -138,6 +138,7 @@ fn execute_import(cmd: ImportBlockchain) -> Result<String, String> {
client_config, client_config,
&spec, &spec,
Path::new(&client_path), Path::new(&client_path),
Path::new(&cmd.dirs.ipc_path()),
Arc::new(Miner::with_spec(&spec)), Arc::new(Miner::with_spec(&spec)),
).map_err(|e| format!("Client service error: {:?}", e))); ).map_err(|e| format!("Client service error: {:?}", e)));
@ -248,6 +249,7 @@ fn execute_export(cmd: ExportBlockchain) -> Result<String, String> {
client_config, client_config,
&spec, &spec,
Path::new(&client_path), Path::new(&client_path),
Path::new(&cmd.dirs.ipc_path()),
Arc::new(Miner::with_spec(&spec)), Arc::new(Miner::with_spec(&spec)),
).map_err(|e| format!("Client service error: {:?}", e))); ).map_err(|e| format!("Client service error: {:?}", e)));

View File

@ -540,6 +540,15 @@ impl Configuration {
|e| warn!("Failed to create '{}' for geth mode: {}", &geth_path.to_str().unwrap(), e)); |e| warn!("Failed to create '{}' for geth mode: {}", &geth_path.to_str().unwrap(), e));
} }
if cfg!(feature = "ipc") && !cfg!(feature = "windows") {
let mut path_buf = PathBuf::from(db_path.clone());
path_buf.push("ipc");
let ipc_path = path_buf.to_str().unwrap();
::std::fs::create_dir_all(ipc_path).unwrap_or_else(
|e| warn!("Failed to directory '{}' for ipc sockets: {}", ipc_path, e)
);
}
Directories { Directories {
keys: keys_path, keys: keys_path,
db: db_path, db: db_path,

View File

@ -66,6 +66,13 @@ impl Directories {
dir.push("db"); dir.push("db");
dir dir
} }
/// Get the ipc sockets path
pub fn ipc_path(&self) -> PathBuf {
let mut dir = Path::new(&self.db).to_path_buf();
dir.push("ipc");
dir
}
} }
#[cfg(test)] #[cfg(test)]

View File

@ -23,12 +23,22 @@ use self::no_ipc_deps::*;
#[cfg(feature="ipc")] #[cfg(feature="ipc")]
use self::ipc_deps::*; use self::ipc_deps::*;
use ethcore_logger::Config as LogConfig; use ethcore_logger::Config as LogConfig;
use std::path::Path;
pub mod service_urls { pub mod service_urls {
pub const CLIENT: &'static str = "ipc:///tmp/parity-chain.ipc"; use std::path::PathBuf;
pub const SYNC: &'static str = "ipc:///tmp/parity-sync.ipc";
pub const SYNC_NOTIFY: &'static str = "ipc:///tmp/parity-sync-notify.ipc"; pub const CLIENT: &'static str = "parity-chain.ipc";
pub const NETWORK_MANAGER: &'static str = "ipc:///tmp/parity-manage-net.ipc"; pub const SYNC: &'static str = "parity-sync.ipc";
pub const SYNC_NOTIFY: &'static str = "parity-sync-notify.ipc";
pub const NETWORK_MANAGER: &'static str = "parity-manage-net.ipc";
pub fn with_base(data_dir: &str, service_path: &str) -> String {
let mut path = PathBuf::from(data_dir);
path.push(service_path);
format!("ipc://{}", path.to_str().unwrap())
}
} }
#[cfg(not(feature="ipc"))] #[cfg(not(feature="ipc"))]
@ -51,27 +61,30 @@ pub type SyncModules = (Arc<SyncProvider>, Arc<ManageNetwork>, Arc<ChainNotify>)
mod ipc_deps { mod ipc_deps {
pub use ethsync::{SyncClient, NetworkManagerClient, ServiceConfiguration}; pub use ethsync::{SyncClient, NetworkManagerClient, ServiceConfiguration};
pub use ethcore::client::ChainNotifyClient; pub use ethcore::client::ChainNotifyClient;
pub use hypervisor::{SYNC_MODULE_ID, BootArgs}; pub use hypervisor::{SYNC_MODULE_ID, BootArgs, HYPERVISOR_IPC_URL};
pub use nanoipc::{GuardedSocket, NanoSocket, init_client}; pub use nanoipc::{GuardedSocket, NanoSocket, init_client};
pub use ipc::IpcSocket; pub use ipc::IpcSocket;
pub use ipc::binary::serialize; pub use ipc::binary::serialize;
} }
#[cfg(feature="ipc")] #[cfg(feature="ipc")]
pub fn hypervisor() -> Option<Hypervisor> { pub fn hypervisor(base_path: &Path) -> Option<Hypervisor> {
Some(Hypervisor::new()) Some(Hypervisor
::with_url(&service_urls::with_base(base_path.to_str().unwrap(), HYPERVISOR_IPC_URL))
.io_path(base_path.to_str().unwrap()))
} }
#[cfg(not(feature="ipc"))] #[cfg(not(feature="ipc"))]
pub fn hypervisor() -> Option<Hypervisor> { pub fn hypervisor(_: &Path) -> Option<Hypervisor> {
None None
} }
#[cfg(feature="ipc")] #[cfg(feature="ipc")]
fn sync_arguments(sync_cfg: SyncConfig, net_cfg: NetworkConfiguration, log_settings: &LogConfig) -> BootArgs { fn sync_arguments(io_path: &str, sync_cfg: SyncConfig, net_cfg: NetworkConfiguration, log_settings: &LogConfig) -> BootArgs {
let service_config = ServiceConfiguration { let service_config = ServiceConfiguration {
sync: sync_cfg, sync: sync_cfg,
net: net_cfg, net: net_cfg,
io_path: io_path.to_owned(),
}; };
// initialisation payload is passed via stdin // initialisation payload is passed via stdin
@ -105,14 +118,18 @@ pub fn sync
-> Result<SyncModules, NetworkError> -> Result<SyncModules, NetworkError>
{ {
let mut hypervisor = hypervisor_ref.take().expect("There should be hypervisor for ipc configuration"); let mut hypervisor = hypervisor_ref.take().expect("There should be hypervisor for ipc configuration");
hypervisor = hypervisor.module(SYNC_MODULE_ID, sync_arguments(sync_cfg, net_cfg, log_settings)); let args = sync_arguments(&hypervisor.io_path, sync_cfg, net_cfg, log_settings);
hypervisor = hypervisor.module(SYNC_MODULE_ID, args);
hypervisor.start(); hypervisor.start();
hypervisor.wait_for_startup(); hypervisor.wait_for_startup();
let sync_client = init_client::<SyncClient<_>>(service_urls::SYNC).unwrap(); let sync_client = init_client::<SyncClient<_>>(
let notify_client = init_client::<ChainNotifyClient<_>>(service_urls::SYNC_NOTIFY).unwrap(); &service_urls::with_base(&hypervisor.io_path, service_urls::SYNC)).unwrap();
let manage_client = init_client::<NetworkManagerClient<_>>(service_urls::NETWORK_MANAGER).unwrap(); let notify_client = init_client::<ChainNotifyClient<_>>(
&service_urls::with_base(&hypervisor.io_path, service_urls::SYNC_NOTIFY)).unwrap();
let manage_client = init_client::<NetworkManagerClient<_>>(
&service_urls::with_base(&hypervisor.io_path, service_urls::NETWORK_MANAGER)).unwrap();
*hypervisor_ref = Some(hypervisor); *hypervisor_ref = Some(hypervisor);
Ok((sync_client, manage_client, notify_client)) Ok((sync_client, manage_client, notify_client))

View File

@ -163,13 +163,14 @@ pub fn execute(cmd: RunCmd) -> Result<(), String> {
} }
// create supervisor // create supervisor
let mut hypervisor = modules::hypervisor(); let mut hypervisor = modules::hypervisor(Path::new(&cmd.dirs.ipc_path()));
// create client service. // create client service.
let service = try!(ClientService::start( let service = try!(ClientService::start(
client_config, client_config,
&spec, &spec,
Path::new(&client_path), Path::new(&client_path),
Path::new(&cmd.dirs.ipc_path()),
miner.clone(), miner.clone(),
).map_err(|e| format!("Client service error: {:?}", e))); ).map_err(|e| format!("Client service error: {:?}", e)));

View File

@ -95,6 +95,7 @@ impl SnapshotCommand {
client_config, client_config,
&spec, &spec,
Path::new(&client_path), Path::new(&client_path),
Path::new(&self.dirs.ipc_path()),
Arc::new(Miner::with_spec(&spec)) Arc::new(Miner::with_spec(&spec))
).map_err(|e| format!("Client service error: {:?}", e))); ).map_err(|e| format!("Client service error: {:?}", e)));

View File

@ -86,18 +86,34 @@ pub fn main() {
io::stdin().read_to_end(&mut buffer).expect("Failed to read initialisation payload"); io::stdin().read_to_end(&mut buffer).expect("Failed to read initialisation payload");
let service_config = ipc::binary::deserialize::<ServiceConfiguration>(&buffer).expect("Failed deserializing initialisation payload"); let service_config = ipc::binary::deserialize::<ServiceConfiguration>(&buffer).expect("Failed deserializing initialisation payload");
let remote_client = nanoipc::init_client::<RemoteClient<_>>(service_urls::CLIENT).unwrap(); let remote_client = nanoipc::init_client::<RemoteClient<_>>(
&service_urls::with_base(&service_config.io_path, service_urls::CLIENT),
).unwrap();
remote_client.handshake().unwrap(); remote_client.handshake().unwrap();
let stop = Arc::new(AtomicBool::new(false)); let stop = Arc::new(AtomicBool::new(false));
let sync = EthSync::new(service_config.sync, remote_client.service().clone(), service_config.net).unwrap(); let sync = EthSync::new(service_config.sync, remote_client.service().clone(), service_config.net).unwrap();
run_service(service_urls::SYNC, stop.clone(), sync.clone() as Arc<SyncProvider>); run_service(
run_service(service_urls::NETWORK_MANAGER, stop.clone(), sync.clone() as Arc<ManageNetwork>); &service_urls::with_base(&service_config.io_path, service_urls::SYNC),
run_service(service_urls::SYNC_NOTIFY, stop.clone(), sync.clone() as Arc<ChainNotify>); stop.clone(),
sync.clone() as Arc<SyncProvider>
);
run_service(
&service_urls::with_base(&service_config.io_path, service_urls::NETWORK_MANAGER),
stop.clone(),
sync.clone() as Arc<ManageNetwork>
);
run_service(
&service_urls::with_base(&service_config.io_path, service_urls::SYNC_NOTIFY),
stop.clone(),
sync.clone() as Arc<ChainNotify>
);
let hypervisor_client = nanoipc::init_client::<HypervisorServiceClient<_>>(HYPERVISOR_IPC_URL).unwrap(); let hypervisor_client = nanoipc::init_client::<HypervisorServiceClient<_>>(
&service_urls::with_base(&service_config.io_path, HYPERVISOR_IPC_URL),
).unwrap();
hypervisor_client.handshake().unwrap(); hypervisor_client.handshake().unwrap();
hypervisor_client.module_ready(SYNC_MODULE_ID); hypervisor_client.module_ready(SYNC_MODULE_ID);

View File

@ -306,4 +306,5 @@ impl From<BasicNetworkConfiguration> for NetworkConfiguration {
pub struct ServiceConfiguration { pub struct ServiceConfiguration {
pub sync: SyncConfig, pub sync: SyncConfig,
pub net: NetworkConfiguration, pub net: NetworkConfiguration,
pub io_path: String,
} }