Skip to content
This repository was archived by the owner on Mar 23, 2021. It is now read-only.

Commit 8f45042

Browse files
author
Tobin C. Harding
committed
Add data directory configuration option
Currently we have `--seed-file` for the seed file and a config option for the database. Both of these files default to the systems data directory with `comit/` appended. It makes more sense to configure these two items in the same fashion. Add configuration option [Data] dir = path/to/data/dir Use this path with `cnd.sqlite` and `seed.pem` appended for the database and seed file respectively. Remove `--seed-file` command line option and the database configuration option.
1 parent 25c9c3a commit 8f45042

File tree

8 files changed

+89
-64
lines changed

8 files changed

+89
-64
lines changed

cnd/src/cli.rs

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,6 @@ pub struct Options {
77
#[structopt(short = "c", long = "config", parse(from_os_str))]
88
pub config_file: Option<PathBuf>,
99

10-
/// Path to secret seed file.
11-
#[structopt(short = "s", long = "seed-file", parse(from_os_str))]
12-
pub seed_file: Option<PathBuf>,
13-
1410
/// Dump the current configuration and exit.
1511
#[structopt(long = "dump-config")]
1612
pub dump_config: bool,

cnd/src/config/file.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
use crate::config::{Bitcoin, Database, Ethereum, Network, Socket};
1+
use crate::config::{Bitcoin, Data, Ethereum, Network, Socket};
22
use config as config_rs;
33
use log::LevelFilter;
44
use std::{ffi::OsStr, path::Path};
@@ -12,7 +12,7 @@ use std::{ffi::OsStr, path::Path};
1212
pub struct File {
1313
pub network: Option<Network>,
1414
pub http_api: Option<HttpApi>,
15-
pub database: Option<Database>,
15+
pub data: Option<Data>,
1616
pub logging: Option<Logging>,
1717
pub bitcoin: Option<Bitcoin>,
1818
pub ethereum: Option<Ethereum>,
@@ -23,7 +23,7 @@ impl File {
2323
File {
2424
network: Option::None,
2525
http_api: Option::None,
26-
database: Option::None,
26+
data: Option::None,
2727
logging: Option::None,
2828
bitcoin: Option::None,
2929
ethereum: Option::None,
@@ -160,8 +160,8 @@ port = 8000
160160
[http_api.cors]
161161
allowed_origins = "all"
162162
163-
[database]
164-
sqlite = "/tmp/foobar.sqlite"
163+
[data]
164+
dir = "/tmp/comit/"
165165
166166
[logging]
167167
level = "DEBUG"
@@ -188,8 +188,8 @@ node_url = "http://example.com/"
188188
allowed_origins: AllowedOrigins::All(All::All),
189189
}),
190190
}),
191-
database: Some(Database {
192-
sqlite: PathBuf::from("/tmp/foobar.sqlite"),
191+
data: Some(Data {
192+
dir: PathBuf::from("/tmp/comit/"),
193193
}),
194194
logging: Some(Logging {
195195
level: Some(LevelFilter::Debug),

cnd/src/config/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,8 +9,8 @@ use std::{net::IpAddr, path::PathBuf};
99
pub use self::{file::File, settings::Settings};
1010

1111
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
12-
pub struct Database {
13-
pub sqlite: PathBuf,
12+
pub struct Data {
13+
pub dir: PathBuf,
1414
}
1515

1616
#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]

cnd/src/config/settings.rs

Lines changed: 12 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,8 @@
1-
use crate::config::{file, Bitcoin, Database, Ethereum, File, Network, Socket};
1+
use crate::config::{file, Bitcoin, Data, Ethereum, File, Network, Socket};
22
use anyhow::Context;
33
use log::LevelFilter;
44
use reqwest::Url;
5-
use std::{
6-
net::{IpAddr, Ipv4Addr},
7-
path::Path,
8-
};
5+
use std::net::{IpAddr, Ipv4Addr};
96

107
/// This structs represents the settings as they are used through out the code.
118
///
@@ -17,7 +14,7 @@ use std::{
1714
pub struct Settings {
1815
pub network: Network,
1916
pub http_api: HttpApi,
20-
pub database: Database,
17+
pub data: Data,
2118
pub logging: Logging,
2219
pub bitcoin: Bitcoin,
2320
pub ethereum: Ethereum,
@@ -28,7 +25,7 @@ impl From<Settings> for File {
2825
let Settings {
2926
network,
3027
http_api: HttpApi { socket, cors },
31-
database,
28+
data,
3229
logging: Logging { level, structured },
3330
bitcoin,
3431
ethereum,
@@ -46,7 +43,7 @@ impl From<Settings> for File {
4643
},
4744
}),
4845
}),
49-
database: Some(database),
46+
data: Some(data),
5047
logging: Some(file::Logging {
5148
level: Some(level),
5249
structured: Some(structured),
@@ -108,7 +105,7 @@ impl Settings {
108105
let File {
109106
network,
110107
http_api,
111-
database,
108+
data,
112109
logging,
113110
bitcoin,
114111
ethereum,
@@ -143,14 +140,14 @@ impl Settings {
143140
HttpApi { socket, cors }
144141
})
145142
.unwrap_or_default(),
146-
database: {
147-
let default_database_path = crate::data_dir()
148-
.map(|dir| Path::join(&dir, "cnd.sqlite"))
149-
.context("unable to determine default database path")?;
150-
database.unwrap_or_else(|| Database {
151-
sqlite: default_database_path,
143+
data: {
144+
let default_data_dir =
145+
crate::data_dir().context("unable to determine default database path")?;
146+
data.unwrap_or_else(|| Data {
147+
dir: default_data_dir,
152148
})
153149
},
150+
154151
logging: {
155152
let Logging {
156153
level: default_level,

cnd/src/db/mod.rs

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,11 @@ use crate::{
2525
swap_protocols::{Role, SwapId},
2626
};
2727
use diesel::{self, prelude::*, sqlite::SqliteConnection};
28-
use std::{path::Path, sync::Arc};
28+
use std::{
29+
ffi::OsStr,
30+
path::{Path, PathBuf},
31+
sync::Arc,
32+
};
2933

3034
/// This module provides persistent storage by way of Sqlite.
3135
@@ -39,16 +43,27 @@ pub struct Sqlite {
3943
impl Sqlite {
4044
/// Return a handle that can be used to access the database.
4145
///
42-
/// When this returns an Sqlite database exists at 'path', a
43-
/// successful connection to the database has been made, and
44-
/// the database migrations have been run.
45-
pub fn new(path: &Path) -> anyhow::Result<Self> {
46-
ensure_folder_tree_exists(path)?;
46+
/// When this returns, an Sqlite database file 'cnd.sql' exists in 'dir', a
47+
/// successful connection to the database has been made, and the database
48+
/// migrations have been run.
49+
pub fn new_in_dir<D: AsRef<OsStr>>(dir: D) -> anyhow::Result<Self> {
50+
let dir = Path::new(&dir);
51+
let path = db_path_from_dir(dir);
52+
Sqlite::new(&path)
53+
}
4754

48-
let connection = SqliteConnection::establish(&format!("file:{}", path.display()))?;
55+
/// Return a handle that can be used to access the database.
56+
///
57+
/// Reads or creates an SQLite database file at 'file'. When this returns
58+
/// an Sqlite database exists, a successful connection to the database has
59+
/// been made, and the database migrations have been run.
60+
pub fn new(file: &Path) -> anyhow::Result<Self> {
61+
ensure_folder_tree_exists(file)?;
62+
63+
let connection = SqliteConnection::establish(&format!("file:{}", file.display()))?;
4964
embedded_migrations::run(&connection)?;
5065

51-
log::info!("SQLite database file: {}", path.display());
66+
log::info!("SQLite database file: {}", file.display());
5267

5368
Ok(Sqlite {
5469
connection: Arc::new(async_std::sync::Mutex::new(connection)),
@@ -88,6 +103,12 @@ impl Sqlite {
88103
}
89104
}
90105

106+
// Construct an absolute path to the database file using 'dir' as the base.
107+
fn db_path_from_dir(dir: &Path) -> PathBuf {
108+
let path = dir.to_path_buf();
109+
path.join("cnd.sqlite")
110+
}
111+
91112
fn ensure_folder_tree_exists(path: &Path) -> anyhow::Result<()> {
92113
if let Some(parent) = path.parent() {
93114
std::fs::create_dir_all(parent)?;

cnd/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,6 @@ pub fn default_config_path() -> anyhow::Result<PathBuf> {
5959
// Linux: /home/<user>/.local/share/comit/
6060
// Windows: C:\Users\<user>\AppData\Roaming\comit\
6161
// OSX: /Users/<user>/Library/Application Support/comit/
62-
fn data_dir() -> Option<PathBuf> {
62+
pub fn data_dir() -> Option<PathBuf> {
6363
ProjectDirs::from("", "", "comit").map(|proj_dirs| proj_dirs.data_dir().to_path_buf())
6464
}

cnd/src/main.rs

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -48,10 +48,7 @@ fn main() -> anyhow::Result<()> {
4848
let base_log_level = settings.logging.level;
4949
logging::initialize(base_log_level, settings.logging.structured)?;
5050

51-
let seed = match options.seed_file {
52-
Some(file) => Seed::from_file(file)?,
53-
None => Seed::from_default_file_or_generate(OsRng)?,
54-
};
51+
let seed = Seed::from_dir_or_generate(&settings.data.dir, OsRng)?;
5552

5653
let mut runtime = tokio::runtime::Runtime::new()?;
5754

@@ -70,7 +67,7 @@ fn main() -> anyhow::Result<()> {
7067

7168
let state_store = Arc::new(InMemoryStateStore::default());
7269

73-
let database = Sqlite::new(&settings.database.sqlite)?;
70+
let database = Sqlite::new_in_dir(&settings.data.dir)?;
7471

7572
let local_key_pair = derive_key_pair(&seed);
7673
let local_peer_id = PeerId::from(local_key_pair.clone().public());

cnd/src/seed.rs

Lines changed: 36 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -49,8 +49,35 @@ impl Seed {
4949
Ok(Seed(arr))
5050
}
5151

52-
/// Construct a seed from base64 data read in from pem file.
53-
pub fn from_file<D: AsRef<OsStr>>(seed_file: D) -> Result<Seed, Error> {
52+
/// Read the seed from the default location if it exists, otherwise
53+
/// generate a random seed and write it to the default location.
54+
pub fn from_default_dir_or_generate<R: Rng>(rand: R) -> Result<Seed, Error> {
55+
let path = default_seed_path()?;
56+
Seed::from_dir_or_generate(&path, rand)
57+
}
58+
59+
/// Read the seed from the directory if it exists, otherwise
60+
/// generate a random seed and write it to that location.
61+
pub fn from_dir_or_generate<D: AsRef<OsStr>, R: Rng>(
62+
data_dir: D,
63+
rand: R,
64+
) -> Result<Seed, Error> {
65+
let dir = Path::new(&data_dir);
66+
let path = seed_path_from_dir(dir);
67+
68+
if path.exists() {
69+
return Self::from_file(&path);
70+
}
71+
72+
let random_seed = Seed::new_random(rand)?;
73+
random_seed.write_to(path.clone())?;
74+
75+
log::info!("No seed file found, creating at: {}", path.display());
76+
77+
Ok(random_seed)
78+
}
79+
80+
fn from_file<D: AsRef<OsStr>>(seed_file: D) -> Result<Seed, Error> {
5481
let file = Path::new(&seed_file);
5582
let contents = fs::read_to_string(file)?;
5683
let pem = pem::parse(contents)?;
@@ -73,23 +100,6 @@ impl Seed {
73100
}
74101
}
75102

76-
/// Read the seed from the default location if it exists, otherwise
77-
/// generate a random seed and write it to the default location.
78-
pub fn from_default_file_or_generate<R: Rng>(rand: R) -> Result<Seed, Error> {
79-
let path = default_seed_path()?;
80-
81-
if path.exists() {
82-
return Self::from_file(&path);
83-
}
84-
85-
let random_seed = Seed::new_random(rand)?;
86-
random_seed.write_to(path.clone())?;
87-
88-
log::info!("No seed file found, creating default at {}", path.display());
89-
90-
Ok(random_seed)
91-
}
92-
93103
fn write_to(&self, seed_file: PathBuf) -> Result<(), Error> {
94104
ensure_directory_exists(seed_file.clone())?;
95105
self._write_to(seed_file)?;
@@ -135,9 +145,13 @@ fn ensure_directory_exists(file: PathBuf) -> Result<(), Error> {
135145
}
136146

137147
fn default_seed_path() -> Result<PathBuf, Error> {
138-
crate::data_dir()
139-
.map(|dir| Path::join(&dir, "seed.pem"))
140-
.ok_or(Error::NoDefaultPath)
148+
let default_path = crate::data_dir().ok_or(Error::NoDefaultPath)?;
149+
Ok(seed_path_from_dir(&default_path))
150+
}
151+
152+
fn seed_path_from_dir(dir: &Path) -> PathBuf {
153+
let path = dir.to_path_buf();
154+
path.join("seed.pem")
141155
}
142156

143157
#[derive(Debug, thiserror::Error)]

0 commit comments

Comments
 (0)