Skip to content

Commit

Permalink
example small exe-unit base on gminer
Browse files Browse the repository at this point in the history
  • Loading branch information
prekucki committed Oct 18, 2023
1 parent 0197bde commit 7e018b4
Show file tree
Hide file tree
Showing 13 changed files with 1,172 additions and 0 deletions.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,8 @@ Cargo.lock

# MSVC Windows builds of rustc generate these, which store debugging information
*.pdb


# Added by cargo

/target
26 changes: 26 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
[package]
name = "ya-runtime-ai"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
ya-service-bus = "0.6.1"
actix-rt="2"
log = "0.4.8"
serde = { version = "^1.0", features = ["derive"] }
serde_json = "1.0"
clap = { version = "4", features = ["derive", "env"] }
anyhow = "1.0.19"
env_logger="0.10.0"
yansi = "0.5.0"
chrono = "0.4"
tokio = { version = "1.32", features = ["macros"] }
futures = "0.3.28"

ya-core-model = { git = "https://github.com/golemfactory/yagna.git", branch="release/v0.13", features = ["activity", "appkey"] }
ya-runtime-api= { git = "https://github.com/golemfactory/yagna.git", branch="release/v0.13" }
ya-client-model = "0.5.0"

regex = "1"
43 changes: 43 additions & 0 deletions conf/ya-runtime-ai.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
[
{
"name": "ai",
"version": "0.1.0",
"supervisor-path": "ya-runtime-ai",
"description": "Golem ai (PoC)",
"extra-args": [],
"config": {
"counters": {
"golem.usage.mining.hash": {
"name": "share",
"description": "Hash share normalized to 1GH",
"price": true
},
"golem.usage.mining.share": {
"name": "raw-share",
"description": "Share count",
"price": false
},
"golem.usage.mining.stale-share": {
"name": "stale-share",
"description": "Stale share count",
"price": false
},
"golem.usage.mining.invalid-share": {
"name": "invalid-share",
"description": "Invalid share count",
"price": false
},
"golem.usage.mining.hash-rate": {
"name": "hash-rate",
"description": "Current hashrate",
"price": false
},
"golem.usage.duration_sec": {
"name": "duration",
"description": "Duration",
"price": true
}
}
}
}
]
33 changes: 33 additions & 0 deletions src/agreement.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
use std::fs::File;
use std::io::BufReader;
use std::path::Path;

pub struct AgreementDesc {
pub counters: Vec<String>,
}

impl AgreementDesc {
pub fn load(path: impl AsRef<Path>) -> anyhow::Result<Self> {
let agreement: serde_json::Value =
serde_json::from_reader(BufReader::new(File::open(path)?))?;
let counters =
if let Some(v) = agreement.pointer("/offer/properties/golem/com/usage/vector") {
serde_json::from_value(v.clone())?
} else {
anyhow::bail!("invalid agreement. missing usage counters")
};

Ok(AgreementDesc { counters })
}

pub fn resolve_counter(&self, counter_id: &str) -> Option<usize> {
self.counters
.iter()
.enumerate()
.find_map(|(idx, name)| if name == counter_id { Some(idx) } else { None })
}

pub fn clean_usage_vector(&self) -> Vec<f64> {
self.counters.iter().map(|_| 0f64).collect()
}
}
63 changes: 63 additions & 0 deletions src/cli.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
//! Exe-Unit Cli Definitions
//!
use std::path::PathBuf;
use clap::{Parser, Subcommand};

#[derive(Parser, Debug)]
#[command(author, version, about)]
pub struct Cli {
/// Runtime binary path
#[arg(long, short)]
pub binary: Option<PathBuf>,
#[command(subcommand)]
pub command: Command,
}


#[derive(Subcommand, Debug)]
pub enum Command {
/// Bind to Service Bus
ServiceBus {
/// ExeUnit service ID
#[arg(long, short)]
service_id: String,
/// ExeUnit daemon GSB URL
#[arg(long, short)]
report_url: String,
#[command(flatten)]
args: RunArgs,
},
/// Print an offer template in JSON format
OfferTemplate,
/// Run runtime's test command
Test
}

#[derive(Parser, Debug)]
pub struct RunArgs {
/// Agreement file path
#[arg(long, short)]
pub agreement: PathBuf,
/// Working directory
#[arg(long, short)]
pub work_dir: Option<PathBuf>,
/// Common cache directory
#[arg(long, short)]
pub cache_dir: Option<PathBuf>,
}

#[cfg(test)]
mod test {
use std::path::Path;
use super::*;

#[test]
fn test_args() {
let cli = Cli::parse_from(["-b", "/tmp/false-runtime", "offer-template"]);
assert_eq!(cli.binary, Some(Path::new("/tmp/false-runtime")));
assert!(matches!(cli.command, Command::OfferTemplate));
}


}
34 changes: 34 additions & 0 deletions src/logs.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@


pub fn colored_stderr_exeunit_prefixed_format(
w: &mut dyn std::io::Write,
now: &mut DeferredNow,
record: &Record,
) -> Result<(), std::io::Error> {
write!(w, "{}", yansi::Color::Fixed(92).paint("[ExeUnit] "))?;
flexi_logger::colored_opt_format(w, now, record)
}

fn configure_logger(logger: flexi_logger::Logger) -> flexi_logger::Logger {
logger
.format(flexi_logger::colored_opt_format)
.duplicate_to_stderr(flexi_logger::Duplicate::Debug)
.format_for_stderr(colored_stderr_exeunit_prefixed_format)
}


pub fn init() -> anyhow::Result<()> {
let default_log_level = "debug";
if configure_logger(flexi_logger::Logger::with_env_or_str(default_log_level))
.log_to_file()
.directory("logs")
.start()
.is_err()
{
configure_logger(flexi_logger::Logger::with_env_or_str(default_log_level))
.start()
.expect("Failed to initialize logging");
log::warn!("Switched to fallback logging method");
}
Ok(())
}
Loading

0 comments on commit 7e018b4

Please sign in to comment.