aboutsummaryrefslogtreecommitdiff
path: root/src/server.rs
blob: d5da8c178eb044e1b83618232bfff5ee98dbd0ce (plain) (blame)
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
use std::io::{Read, Write};
use std::sync::Arc;
use std::net::SocketAddr;
use std::path::PathBuf;
use futures::channel::oneshot;
use serde::Deserialize;

use crate::data::*;
use crate::error::Error;
use crate::membership::System;
use crate::api_server;
use crate::rpc_server;

fn default_block_size() -> usize {
	1048576
}
fn default_meta_replication_factor() -> usize {
	3
}

#[derive(Deserialize, Debug)]
pub struct Config {
	pub metadata_dir: PathBuf,
	pub data_dir: PathBuf,

	pub api_port: u16,
	pub rpc_port: u16,

	pub bootstrap_peers: Vec<SocketAddr>,

	#[serde(default = "default_block_size")]
	pub block_size: usize,

	#[serde(default = "default_meta_replication_factor")]
	pub meta_replication_factor: usize,
}

fn read_config(config_file: PathBuf) -> Result<Config, Error> {
	let mut file = std::fs::OpenOptions::new()
		.read(true)
		.open(config_file.as_path())?;
	
	let mut config = String::new();
	file.read_to_string(&mut config)?;

	Ok(toml::from_str(&config)?)
}

fn gen_node_id(metadata_dir: &PathBuf) -> Result<UUID, Error> {
	let mut id_file = metadata_dir.clone();
	id_file.push("node_id");
	if id_file.as_path().exists() {
		let mut f = std::fs::File::open(id_file.as_path())?;
		let mut d = vec![];
		f.read_to_end(&mut d)?;
		if d.len() != 32 {
			return Err(Error::Message(format!("Corrupt node_id file")))
		}

		let mut id = [0u8; 32];
		id.copy_from_slice(&d[..]);
		Ok(id.into())
	} else {
		let id = gen_uuid();

		let mut f = std::fs::File::create(id_file.as_path())?;
		f.write_all(id.as_slice())?;
		Ok(id)
	}
}

async fn shutdown_signal(chans: Vec<oneshot::Sender<()>>) {
    // Wait for the CTRL+C signal
    tokio::signal::ctrl_c()
        .await
        .expect("failed to install CTRL+C signal handler");
	println!("Received CTRL+C, shutting down.");
	for ch in chans {
		ch.send(()).unwrap();
	}
}

async fn wait_from(chan: oneshot::Receiver<()>) -> () {
	chan.await.unwrap()
}

pub async fn run_server(config_file: PathBuf) -> Result<(), Error> {
	let config = read_config(config_file)
		.expect("Unable to read config file");

	let id = gen_node_id(&config.metadata_dir)
		.expect("Unable to read or generate node ID");
	println!("Node ID: {}", hex::encode(&id));

	let sys = Arc::new(System::new(config, id));

	let (tx1, rx1) = oneshot::channel();
	let (tx2, rx2) = oneshot::channel();

	let rpc_server = rpc_server::run_rpc_server(sys.clone(), wait_from(rx1));
	let api_server = api_server::run_api_server(sys.clone(), wait_from(rx2));

	tokio::spawn(shutdown_signal(vec![tx1, tx2]));
	tokio::spawn(sys.bootstrap());

	futures::try_join!(rpc_server, api_server)?;
	Ok(())
}