Skip to content

Commit

Permalink
golemsp stop + status version (#787)
Browse files Browse the repository at this point in the history
  • Loading branch information
mfranciszkiewicz authored Nov 16, 2020
2 parents 2b06923 + b9a418a commit 0c4943c
Show file tree
Hide file tree
Showing 14 changed files with 272 additions and 15 deletions.
25 changes: 25 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ ya-service-api-web = "0.1"
ya-service-bus = "0.2"
ya-sgx = "0.1"
ya-utils-path = "0.1"
ya-utils-process = { version = "0.1", features = ["lock"] }

actix-rt = "1.0"
actix-service = "1.0"
Expand Down
2 changes: 1 addition & 1 deletion agent/provider/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ ya-compile-time-utils = "0.1"
ya-core-model = { version = "0.2", features = ['activity'] }
ya-utils-actix = "0.1"
ya-utils-path = "0.1"
ya-utils-process = "0.1"
ya-utils-process = { version = "0.1", features = ['lock'] }

actix = "0.9"
actix-rt = "1.0"
Expand Down
2 changes: 2 additions & 0 deletions agent/provider/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ use provider_agent::ProviderAgent;
use startup_config::{
Commands, ConfigConfig, ExeUnitsConfig, PresetsConfig, ProfileConfig, StartupConfig,
};
use ya_utils_process::lock::ProcLock;

#[actix_rt::main]
async fn main() -> anyhow::Result<()> {
Expand All @@ -43,6 +44,7 @@ async fn main() -> anyhow::Result<()> {
log::info!("Starting {}...", app_name);
log::info!("Data directory: {}", data_dir.display());

let _lock = ProcLock::new("ya-provider", &data_dir)?.lock(std::process::id())?;
let agent = ProviderAgent::new(args, config).await?.start();
agent.send(Initialize).await??;

Expand Down
2 changes: 2 additions & 0 deletions core/serv/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ use ya_service_api_web::{
rest_api_host_port, DEFAULT_YAGNA_API_URL, YAGNA_API_URL_ENV_VAR,
};
use ya_utils_path::data_dir::DataDir;
use ya_utils_process::lock::ProcLock;

mod autocomplete;
use autocomplete::CompleteCommand;
Expand Down Expand Up @@ -328,6 +329,7 @@ impl ServiceCommand {
match self {
Self::Run(ServiceCommandOpts { api_url }) => {
log::info!("Starting {} service!", clap::crate_name!());
let _lock = ProcLock::new("yagna", &ctx.data_dir)?.lock(std::process::id())?;

ya_sb_router::bind_gsb_router(ctx.gsb_url.clone())
.await
Expand Down
7 changes: 6 additions & 1 deletion golem_cli/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,12 @@ rustyline="6.3.0"
prettytable-rs = "0.8.0"
ansi_term="0.12.1"
ya-core-model = { version = "0.2.1", path="../core/model", features=["payment"] }
ya-utils-path = "0.1.0"
ya-utils-process = { version = "0.1.0", features = ["lock"] }

[target.'cfg(target_os = "linux")'.dependencies]
[build-dependencies]
vergen = "3.1.0"

[target.'cfg(target_family = "unix")'.dependencies]
libc="0.2.73"
nix="0.18.0"
8 changes: 8 additions & 0 deletions golem_cli/build.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
extern crate vergen;
use vergen::{generate_cargo_keys, ConstantsFlags};

fn main() {
let mut flags = ConstantsFlags::empty();
flags.toggle(ConstantsFlags::SHA_SHORT);
generate_cargo_keys(flags).expect("Unable to generate the cargo keys");
}
2 changes: 1 addition & 1 deletion golem_cli/src/command/yagna.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ impl YagnaCommand {

match v {
future::Either::Left((_child_ends, _t)) => {
anyhow::bail!("fail to start service");
anyhow::bail!("failed to start service");
}
future::Either::Right((_t, child)) => Ok(child),
}
Expand Down
6 changes: 5 additions & 1 deletion golem_cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ enum Commands {
/// Run the golem provider
Run(setup::RunConfig),

/// Stop the golem provider
Stop,

/// Manage settings
///
/// This can be used regardless of whether golem is running or not.
Expand Down Expand Up @@ -69,6 +72,7 @@ async fn my_main() -> Result</*exit code*/ i32> {
match cli_args.commands {
Commands::Setup(mut run_config) => setup::setup(&mut run_config, true).await,
Commands::Run(run_config) => service::run(run_config).await,
Commands::Stop => service::stop().await,
Commands::Settings(command) => match command {
SettingsCommand::Set(set) => settings::run(set).await,
SettingsCommand::Show => settings_show::run().await,
Expand Down Expand Up @@ -97,7 +101,7 @@ async fn main() {
std::process::exit(match my_main().await {
Ok(code) => code,
Err(e) => {
log::error!("Error: {:?}", e);
log::error!("{:?}", e);
1
}
});
Expand Down
80 changes: 69 additions & 11 deletions golem_cli/src/service.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
use crate::appkey;
use crate::command::YaCommand;
use crate::setup::RunConfig;
use anyhow::{bail, Context, Result};
use anyhow::{Context, Result};
use futures::channel::{mpsc, oneshot};
use futures::prelude::*;
use std::io;

use crate::utils::is_yagna_running;

use crate::command::YaCommand;
use std::process::ExitStatus;
use tokio::process::Child;
use tokio::stream::StreamExt;
Expand Down Expand Up @@ -111,16 +108,11 @@ pub async fn watch_for_vm() -> anyhow::Result<()> {

pub async fn run(mut config: RunConfig) -> Result</*exit code*/ i32> {
crate::setup::setup(&mut config, false).await?;
if is_yagna_running().await? {
bail!("service already running")
}
let cmd = YaCommand::new()?;

let cmd = YaCommand::new()?;
let service = cmd.yagna()?.service_run().await?;

let app_key = appkey::get_app_key().await?;
let provider = cmd.ya_provider()?.spawn(&app_key).await?;

let ctrl_c = tokio::signal::ctrl_c();

log::info!("Golem provider is running");
Expand Down Expand Up @@ -151,3 +143,69 @@ pub async fn run(mut config: RunConfig) -> Result</*exit code*/ i32> {
}
Ok(0)
}

#[cfg(target_family = "unix")]
pub async fn stop() -> Result<i32> {
use ya_utils_path::data_dir::DataDir;
use ya_utils_process::lock::ProcLock;

let provider_dir = DataDir::new("ya-provider")
.get_or_create()
.expect("unable to get ya-provider data dir");
let provider_pid = ProcLock::new("ya-provider", &provider_dir)?.read_pid()?;

kill_pid(provider_pid as i32, 5)
.await
.context("failed to stop provider")?;

let yagna_dir = DataDir::new("yagna")
.get_or_create()
.expect("unable to get yagna data dir");
let yagna_pid = ProcLock::new("yagna", &yagna_dir)?.read_pid()?;

kill_pid(yagna_pid as i32, 5)
.await
.context("failed to stop yagna")?;

Ok(0)
}

#[cfg(target_family = "unix")]
async fn kill_pid(pid: i32, timeout: i64) -> Result<()> {
use nix::sys::signal::*;
use nix::sys::wait::*;
use nix::unistd::Pid;
use std::time::Instant;

fn alive(pid: Pid) -> bool {
match waitpid(pid, Some(WaitPidFlag::WNOHANG)) {
Ok(WaitStatus::Exited(_, _)) | Ok(WaitStatus::Signaled(_, _, _)) | Err(_) => false,
Ok(_) => true,
}
}

let pid = Pid::from_raw(pid);
let delay = Duration::from_secs_f32(timeout as f32 / 5.);
let started = Instant::now();

kill(pid, Signal::SIGTERM)?;
log::debug!("Sent SIGTERM to {:?}", pid);

while alive(pid) {
if Instant::now() >= started + delay {
log::debug!("Sending SIGKILL to {:?}", pid);

kill(pid, Signal::SIGKILL)?;
waitpid(pid, None)?;
break;
}
tokio::time::delay_for(delay).await;
}
Ok(())
}

#[cfg(not(target_family = "unix"))]
pub async fn stop() -> Result<i32> {
// FIXME: not implemented for windows
todo!("Implement for Windows");
}
24 changes: 24 additions & 0 deletions golem_cli/src/status.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,8 @@ pub async fn run() -> Result</*exit code*/ i32> {
Style::new().fg(Colour::Red).paint("is not running")
]);
}
table.add_row(row!["Version", version()]);

table.add_empty_row();
table.add_row(row!["Node Name", &config.node_name.unwrap_or_default()]);
table.add_row(row!["Subnet", &config.subnet.unwrap_or_default()]);
Expand All @@ -50,6 +52,7 @@ pub async fn run() -> Result</*exit code*/ i32> {
};
table.add_row(row!["VM", status]);
}

table
};
let mut table = Table::new();
Expand Down Expand Up @@ -124,3 +127,24 @@ pub async fn run() -> Result</*exit code*/ i32> {
}
Ok(0)
}

pub fn version() -> String {
let mut version = option_env!("GITHUB_REF").unwrap_or(env!("CARGO_PKG_VERSION"));
if let Some(pos) = version.rfind('/') {
version = &version[pos + 1..];
}

// convert tag to a semantic version
for prefix in ["v", "pre-rel-"].iter() {
if version.starts_with(prefix) {
version = &version[prefix.len()..];
break;
}
}
// create optional build metadata
let build = option_env!("GITHUB_RUN_NUMBER")
.map(|b| format!("+b{}", b))
.unwrap_or_else(String::new);

format!("{}{} ({})", version, build, env!("VERGEN_SHA_SHORT"))
}
6 changes: 6 additions & 0 deletions utils/process/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ version = "0.1.0"
authors = ["Golem Factory <[email protected]>"]
edition = "2018"

[features]
default = []
lock = ["fs2"]

[dependencies]
actix = "0.9"
anyhow = "1.0"
Expand All @@ -14,5 +18,7 @@ libc = "0.2"
shared_child = "0.3.4"
tokio = { version = "0.2.10", features = ["process", "signal"] }

fs2 = { version = "0.4.3", optional = true }

[target.'cfg(target_family = "unix")'.dependencies]
nix = "0.17.0"
3 changes: 3 additions & 0 deletions utils/process/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,9 @@ use std::sync::Arc;
use std::thread;
use std::time::Duration;

#[cfg(feature = "lock")]
pub mod lock;

#[cfg(unix)]
use {
actix::prelude::*,
Expand Down
Loading

0 comments on commit 0c4943c

Please sign in to comment.