Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
72 changes: 26 additions & 46 deletions build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,11 @@ use chrono::DateTime;
use gstuff::slurp;
use regex::Regex;
use std::fs;
use std::io::{Read, Write};
use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::str::from_utf8;

/// Absolute path taken from SuperNET's root + `path`.
fn rabs(rrel: &str) -> PathBuf { root().join(rrel) }

fn path2s(path: PathBuf) -> String {
path.to_str()
.unwrap_or_else(|| panic!("Non-stringy path {:?}", path))
Expand Down Expand Up @@ -40,7 +37,6 @@ fn root() -> PathBuf {
///
/// The build script will usually help us by putting the MarketMaker version into the “MM_VERSION” file
/// and the corresponding ISO 8601 time into the “MM_DATETIME” file
/// (environment variable isn't as useful because we can't `rerun-if-changed` on it).
///
/// For the nightly builds the version contains the short commit hash.
///
Expand All @@ -50,43 +46,32 @@ fn root() -> PathBuf {
/// we might skip synchronizing the Git repository there),
/// but if it is, then we're going to check if the “MM_DATETIME” and the Git data match.
fn mm_version() -> String {
// Try to load the variable from the file.
let mm_version_p = root().join("MM_VERSION");
let mut buf;
let version = if let Ok(mut mm_version_f) = fs::File::open(&mm_version_p) {
buf = String::new();
mm_version_f
.read_to_string(&mut buf)
.expect("Can't read from MM_VERSION");
buf.trim().to_string()
} else {
// If the “MM_VERSION” file is absent then we should create it
// in order for the Cargo dependency management to see it,
// because Cargo will keep rebuilding the `common` crate otherwise.
//
// We should probably fetch the actual git version here,
// with something like `git log '--pretty=format:%h' -n 1` for the nightlies,
// and a release tag when building from some kind of a stable branch,
// though we should keep the ability for the tooling to provide the “MM_VERSION”
// externally, because moving the entire ".git" around is not always practical.

let mut version = "UNKNOWN".to_string();
let mut command = Command::new("git");
command.arg("log").arg("--pretty=format:%h").arg("-n1");
if let Ok(go) = command.output() {
if go.status.success() {
version = from_utf8(&go.stdout).unwrap().trim().to_string();
if !Regex::new(r"^\w+$").unwrap().is_match(&version) {
panic!("{}", version)
}
// We fetch the actual git version here,
// with `git log '--pretty=format:%h' -n 1` for the nightlies,
// and a release tag when building from some kind of a stable branch,
// though we should keep the ability for the tooling to provide the “MM_VERSION”
// externally, because moving the entire ".git" around is not always practical.
let mut version = "UNKNOWN".to_string();
let mut command = Command::new("git");
command.arg("log").arg("--pretty=format:%h").arg("-n1");
if let Ok(go) = command.output() {
if go.status.success() {
version = from_utf8(&go.stdout).unwrap().trim().to_string();
if !Regex::new(r"^\w+$").unwrap().is_match(&version) {
panic!("{}", version)
}
}
}

let mm_version_p = root().join("MM_VERSION");
let v_file = String::from_utf8(slurp(&mm_version_p)).unwrap();
let v_file = v_file.trim().to_string();
if version[..] != v_file[..] {
// Create or update the MM_VERSION file in order to appease the Cargo dependency management.
let mut mm_version_f = fs::File::create(&mm_version_p).unwrap();
mm_version_f.write_all(version.as_bytes()).unwrap();
}

if let Ok(mut mm_version_f) = fs::File::create(&mm_version_p) {
mm_version_f.write_all(version.as_bytes()).unwrap();
}
version
};
println!("cargo:rustc-env=MM_VERSION={}", version);

let mut dt_git = None;
Expand All @@ -102,13 +87,12 @@ fn mm_version() -> String {

let mm_datetime_p = root().join("MM_DATETIME");
let dt_file = String::from_utf8(slurp(&mm_datetime_p)).unwrap();
let mut dt_file = dt_file.trim().to_string();
let dt_file = dt_file.trim().to_string();
if let Some(ref dt_git) = dt_git {
if dt_git[..] != dt_file[..] {
// Create or update the “MM_DATETIME” file in order to appease the Cargo dependency management.
let mut mm_datetime_f = fs::File::create(&mm_datetime_p).unwrap();
mm_datetime_f.write_all(dt_git.as_bytes()).unwrap();
dt_file = dt_git.clone();
}
}

Expand All @@ -117,8 +101,4 @@ fn mm_version() -> String {
version
}

fn main() {
println!("cargo:rerun-if-changed={}", path2s(rabs("MM_VERSION")));
println!("cargo:rerun-if-changed={}", path2s(rabs("MM_DATETIME")));
mm_version();
}
fn main() { mm_version(); }
9 changes: 9 additions & 0 deletions mm2src/database.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
pub mod database_common;
#[path = "database/my_orders.rs"] pub mod my_orders;
#[path = "database/my_swaps.rs"] pub mod my_swaps;
#[path = "database/stats_nodes.rs"] pub mod stats_nodes;
#[path = "database/stats_swaps.rs"] pub mod stats_swaps;

use crate::CREATE_MY_SWAPS_TABLE;
Expand Down Expand Up @@ -71,13 +72,21 @@ fn migration_4() -> Vec<(&'static str, Vec<String>)> { stats_swaps::add_and_spli

fn migration_5() -> Vec<(&'static str, Vec<String>)> { vec![(my_orders::CREATE_MY_ORDERS_TABLE, vec![])] }

fn migration_6() -> Vec<(&'static str, Vec<String>)> {
vec![
(stats_nodes::CREATE_NODES_TABLE, vec![]),
(stats_nodes::CREATE_STATS_NODES_TABLE, vec![]),
]
}

fn statements_for_migration(ctx: &MmArc, current_migration: i64) -> Option<Vec<(&'static str, Vec<String>)>> {
match current_migration {
1 => Some(migration_1(ctx)),
2 => Some(migration_2(ctx)),
3 => Some(migration_3()),
4 => Some(migration_4()),
5 => Some(migration_5()),
6 => Some(migration_6()),
_ => None,
}
}
Expand Down
72 changes: 72 additions & 0 deletions mm2src/database/stats_nodes.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
/// This module contains code to work with nodes table for stats collection in MM2 SQLite DB
use crate::mm2::lp_stats::{NodeInfo, NodeVersionStat};
use common::log::debug;
use common::mm_ctx::MmArc;
use common::rusqlite::{Error as SqlError, Result as SqlResult, NO_PARAMS};
use std::collections::hash_map::HashMap;

pub const CREATE_NODES_TABLE: &str = "CREATE TABLE IF NOT EXISTS nodes (
id INTEGER NOT NULL PRIMARY KEY,
name VARCHAR(255) NOT NULL UNIQUE,
address VARCHAR(255) NOT NULL,
peer_id VARCHAR(255) NOT NULL UNIQUE
);";

pub const CREATE_STATS_NODES_TABLE: &str = "CREATE TABLE IF NOT EXISTS stats_nodes (
id INTEGER NOT NULL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
version VARCHAR(255),
timestamp INTEGER NOT NULL,
error VARCHAR(255)
);";

const INSERT_NODE: &str = "INSERT INTO nodes (name, address, peer_id) VALUES (?1, ?2, ?3)";

const DELETE_NODE: &str = "DELETE FROM nodes WHERE name = ?1";

const SELECT_PEERS_NAMES: &str = "SELECT peer_id, name FROM nodes";

const INSERT_STAT: &str = "INSERT INTO stats_nodes (name, version, timestamp, error) VALUES (?1, ?2, ?3, ?4)";

pub fn insert_node_info(ctx: &MmArc, node_info: &NodeInfo) -> SqlResult<()> {
debug!("Inserting info about node {} to the SQLite database", node_info.name);
let params = vec![
node_info.name.clone(),
node_info.address.clone(),
node_info.peer_id.clone(),
];
let conn = ctx.sqlite_connection();
conn.execute(INSERT_NODE, &params).map(|_| ())
}

pub fn delete_node_info(ctx: &MmArc, name: String) -> SqlResult<()> {
debug!("Deleting info about node {} from the SQLite database", name);
let params = vec![name];
let conn = ctx.sqlite_connection();
conn.execute(DELETE_NODE, &params).map(|_| ())
}

pub fn select_peers_names(ctx: &MmArc) -> SqlResult<HashMap<String, String>, SqlError> {
let conn = ctx.sqlite_connection();
let mut stmt = conn.prepare(SELECT_PEERS_NAMES)?;
let peers_names = stmt
.query_map(NO_PARAMS, |row| Ok((row.get(0)?, row.get(1)?)))?
.collect::<SqlResult<HashMap<String, String>>>();

peers_names
}

pub fn insert_node_version_stat(ctx: &MmArc, node_version_stat: NodeVersionStat) -> SqlResult<()> {
debug!(
"Inserting new version stat for node {} to the SQLite database",
node_version_stat.name
);
let params = vec![
node_version_stat.name,
node_version_stat.version.unwrap_or_default(),
node_version_stat.timestamp.to_string(),
node_version_stat.error.unwrap_or_default(),
];
let conn = ctx.sqlite_connection();
conn.execute(INSERT_STAT, &params).map(|_| ())
}
18 changes: 1 addition & 17 deletions mm2src/lp_native_dex.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ use crate::mm2::database::init_and_migrate_db;
use crate::mm2::lp_network::{p2p_event_process_loop, P2PContext};
use crate::mm2::lp_ordermatch::{broadcast_maker_orders_keep_alive_loop, lp_ordermatch_loop, orders_kick_start,
BalanceUpdateOrdermatchHandler};
use crate::mm2::lp_stats::lp_ports;
use crate::mm2::lp_swap::{running_swaps_num, swap_kick_starts};
use crate::mm2::rpc::spawn_rpc;
use crate::mm2::{MM_DATETIME, MM_VERSION};
Expand Down Expand Up @@ -73,23 +74,6 @@ fn default_seednodes(netid: u16) -> Vec<String> {
}
}

pub fn lp_ports(netid: u16) -> Result<(u16, u16, u16), String> {
const LP_RPCPORT: u16 = 7783;
let max_netid = (65535 - 40 - LP_RPCPORT) / 4;
if netid > max_netid {
return ERR!("Netid {} is larger than max {}", netid, max_netid);
}

let other_ports = if netid != 0 {
let net_mod = netid % 10;
let net_div = netid / 10;
(net_div * 40) + LP_RPCPORT + net_mod
} else {
LP_RPCPORT
};
Ok((other_ports + 10, other_ports + 20, other_ports + 30))
}

/// Invokes `OS_ensure_directory`,
/// then prints an error and returns `false` if the directory is not writable.
fn ensure_dir_is_writable(dir_path: &Path) -> bool {
Expand Down
Loading