Skip to content

Commit

Permalink
feat: release for v0.1.16. (#10)
Browse files Browse the repository at this point in the history
Main feature includes:
 - Fix linux shell envs.
 - Fix bug of write output to tmp file.
  • Loading branch information
hustclf authored Dec 17, 2021
1 parent f491cc2 commit 3fde1b4
Show file tree
Hide file tree
Showing 6 changed files with 84 additions and 25 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
# Changelog

All notable changes to this project will be documented in this file.

## [0.1.16] - 2021-12-09

### Changed

- Fix bug of write output to tmp file.

## [0.1.15] - 2021-12-05

### Changed
Expand Down
2 changes: 1 addition & 1 deletion Cargo.lock

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

3 changes: 1 addition & 2 deletions Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "tat_agent"
version = "0.1.15"
version = "0.1.16"
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
Expand Down Expand Up @@ -45,7 +45,6 @@ users = { version = "0.11.0"}
openssl = { version = '0.10.35', features = ["vendored"] }
procfs = "0.11.0"


[target.'cfg(windows)'.dependencies]
codepage-strings = "1.0.1"
winapi = { version = "0.3", features = ["winsvc","winbase","winnt","stringapiset","winnls","wow64apiset","synchapi","namedpipeapi"] }
6 changes: 3 additions & 3 deletions install/install.sh
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ install() {
elif has_sysvinit; then
cp -f tat_agent_service /etc/init.d/
chmod 755 /etc/init.d/tat_agent_service
# TODO: uncomment following code after 0.1.14 is released.
# TODO: uncomment following code after 0.1.15 is released.
# if test "${need_restart}" = true; then
/etc/init.d/tat_agent_service restart
# fi
Expand All @@ -110,7 +110,7 @@ install() {
fi
fi
else
# TODO: uncomment following code after 0.1.14 is released.
# TODO: uncomment following code after 0.1.15 is released.
# if test "${need_restart}" = true; then
echo "no proper daemon manager found, tat_agent can not auto start"
PID=$(cat ${PID_FILE})
Expand Down Expand Up @@ -155,4 +155,4 @@ case $1 in
*)
install true
;;
esac
esac
2 changes: 1 addition & 1 deletion src/executor/proc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -599,7 +599,7 @@ mod tests {
use std::fs::File;
use std::io::Write;
use std::time::{Duration, Instant, SystemTime};
use std::{fs, thread};
use std::fs;

use log::info;
use rand::distributions::Alphanumeric;
Expand Down
89 changes: 71 additions & 18 deletions src/executor/shell_command.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ use std::time::Duration;
use std::{env, fmt, io};

use crate::common::consts::PIPE_BUF_DEFAULT_SIZE;
use crate::executor::proc::{self, BaseCommand, MyCommand};
use crate::executor::proc::{BaseCommand, MyCommand};
use crate::start_failed_err_info;
use async_trait::async_trait;
use libc;
Expand Down Expand Up @@ -81,24 +81,40 @@ impl ShellCommand {
}

fn prepare_cmd(&self, user: User) -> Command {
let mut envs = HashMap::new();
// find shell
let mut shell_path = cmd_path("bash");
let (shell, login_init) = if shell_path.is_some() {
let login_init = ". ~/.bash_profile 2> /dev/null || . ~/.bashrc 2> /dev/null ; ";
("bash", login_init)
} else {
shell_path = cmd_path("sh");
("sh", "")
};

//build envs
let mut envs = HashMap::<String, String>::new();
let shell_path = shell_path.unwrap();
envs.insert("SHELL".to_string(), shell_path);
match user.home_dir().to_str() {
Some(dir) => {
envs.insert("HOME", dir);
envs.insert("HOME".to_string(), dir.to_string());
}
None => {}
};
envs.insert("USER", self.base.username.as_str());
envs.insert("LOGNAME", self.base.username.as_str());

let mut shell = "bash";
let mut login_init = ". ~/.bash_profile 2> /dev/null || . ~/.bashrc 2> /dev/null ; ";
if !cmd_exists(shell) {
shell = "sh";
login_init = "";
envs.insert("USER".to_string(), self.base.username.clone());
envs.insert("LOGNAME".to_string(), self.base.username.clone());
envs.insert("USERNAME".to_string(), self.base.username.clone());

let etc_envs;
if let Ok(content) = std::fs::read_to_string("/etc/environment") {
etc_envs = load_envs(content);
for (key, value) in etc_envs.into_iter() {
envs.insert(key, value);
}
};
let entrypoint = format!("{}{}", login_init, self.base.cmd_path());

//build comand
let entrypoint = format!("{}{}", login_init, self.base.cmd_path());
let mut cmd = Command::new(shell);
cmd.args(&["-c", entrypoint.as_str()])
.uid(user.uid())
Expand Down Expand Up @@ -177,8 +193,8 @@ impl BaseCommand {
let mut reader = BufReader::new(stdout.unwrap());
let mut byte_after_finish = 0;
let proc = match Process::new(pid as i32) {
Ok(proc)=> proc,
Err(_)=> return ,
Ok(proc) => proc,
Err(_) => return,
};
loop {
let process_finish = !proc.is_alive();
Expand All @@ -201,7 +217,7 @@ impl BaseCommand {

let len = read_size.unwrap();
if len > 0 {
if let Err(e) = log_file.write(&buffer) {
if let Err(e) = log_file.write(&buffer[..len]) {
error!("write output file fail: {:?}", e)
}

Expand Down Expand Up @@ -273,16 +289,43 @@ fn own_process_group() -> Result<(), io::Error> {
}
}

fn cmd_exists(cmd: &str) -> bool {
fn cmd_path(cmd: &str) -> Option<String> {
if let Ok(path) = env::var("PATH") {
for p in path.split(":") {
let p_str = format!("{}/{}", p, cmd);
if Path::new(&p_str).exists() {
return true;
return Some(p_str);
}
}
}
None
}

fn load_envs(content: String) -> HashMap<String, String> {
let mut envs: HashMap<String, String> = HashMap::new();
let lines: Vec<&str> = content.split('\n').collect();
for mut line in lines {
line = line.trim_start();
if line.len() == 0 || line.starts_with("#") {
continue;
}
if line.starts_with("export ") {
line = &line[7..];
}
let env_part: Vec<&str> = line.splitn(2, '=').collect();
if env_part.len() == 2 {
let key = env_part[0].trim_start().to_string();
let mut value = env_part[1].to_string();
if value.starts_with('"') && value.ends_with('"')
|| value.ends_with('\'') && value.starts_with('\'')
{
value.remove(0);
value.pop();
}
envs.insert(key, value);
}
}
false
envs
}

#[cfg(test)]
Expand All @@ -299,4 +342,14 @@ mod tests {
fn test_working_directory_exists() {
assert_eq!(working_directory_exists("/etc"), true);
}

#[test]
fn test_load_envs() {
let content = "# \n B=b\n D=d=d\n C= \"x\n";
let envs = load_envs(content.to_string());
assert!(envs.keys().len() == 3);
assert!(envs.get("B").unwrap() == "b");
assert!(envs.get("D").unwrap() == "d=d");
assert!(envs.get("C").unwrap() == " \"x");
}
}

0 comments on commit 3fde1b4

Please sign in to comment.