Compare commits
No commits in common. "master" and "v0.11.3" have entirely different histories.
|
|
@ -1,6 +1,4 @@
|
|||
/target
|
||||
.idea
|
||||
/.env
|
||||
Cargo.lock
|
||||
hagent_test.sock
|
||||
release
|
||||
|
|
|
|||
31
Dockerfile
31
Dockerfile
|
|
@ -1,31 +0,0 @@
|
|||
FROM ubuntu:22.04
|
||||
|
||||
USER root
|
||||
|
||||
RUN apt update && apt install -y \
|
||||
curl \
|
||||
build-essential \
|
||||
libssl-dev \
|
||||
pkg-config \
|
||||
libudev-dev \
|
||||
procps \
|
||||
gcc-riscv64-unknown-elf \
|
||||
gcc-riscv64-linux-gnu \
|
||||
binutils-riscv64-linux-gnu \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
RUN curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y
|
||||
|
||||
ENV PATH="/root/.cargo/bin:${PATH}"
|
||||
|
||||
WORKDIR /usr/src/kii/
|
||||
|
||||
COPY . ./
|
||||
|
||||
RUN chmod +x noxis-rs/temp-process
|
||||
|
||||
RUN rustup target add riscv64gc-unknown-linux-gnu && rustup target add x86_64-unknown-linux-gnu
|
||||
|
||||
RUN cargo unibuild
|
||||
|
||||
ENTRYPOINT ["cargo", "test"]
|
||||
|
|
@ -1,243 +0,0 @@
|
|||
pipeline {
|
||||
agent any
|
||||
stages {
|
||||
stage('Tests and compiling binaries') {
|
||||
when {
|
||||
expression { env.CHANGE_BRANCH?.startsWith('feature/') || env.CHANGE_BRANCH?.startsWith('rc') }
|
||||
}
|
||||
steps {
|
||||
script {
|
||||
echo "Building and running tests in Docker for feature branch..."
|
||||
try {
|
||||
def targetDirAmd = "${env.WORKSPACE}/${env.CHANGE_BRANCH}/amd64"
|
||||
def targetDirRisc = "${env.WORKSPACE}/${env.CHANGE_BRANCH}/riscv64"
|
||||
|
||||
sh "mkdir -p ${targetDirAmd}"
|
||||
sh "mkdir -p ${targetDirRisc}"
|
||||
|
||||
sh """
|
||||
docker build --network=host -t e-monitor .
|
||||
docker run --name e-monitor --dns 8.8.8.8 --network=host e-monitor:latest
|
||||
"""
|
||||
|
||||
sh "cp noxis-rs/settings.json ${targetDirAmd}"
|
||||
sh "cp noxis-rs/settings.json ${targetDirRisc}"
|
||||
|
||||
sh "docker cp e-monitor:/usr/src/kii/target/x86_64-unknown-linux-gnu/release/noxis-cli ${targetDirAmd}"
|
||||
sh "docker cp e-monitor:/usr/src/kii/target/x86_64-unknown-linux-gnu/release/noxis-rs ${targetDirAmd}"
|
||||
|
||||
sh "docker cp e-monitor:/usr/src/kii/target/riscv64gc-unknown-linux-gnu/release/noxis-cli ${targetDirRisc}"
|
||||
sh "docker cp e-monitor:/usr/src/kii/target/riscv64gc-unknown-linux-gnu/release/noxis-rs ${targetDirRisc}"
|
||||
|
||||
echo "Tests passed successfully and binaries were extracted!"
|
||||
} catch (Exception e) {
|
||||
echo "Tests failed during Docker run."
|
||||
error "Build failed at 'CI for feature' stage."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('Calculate Install Size') {
|
||||
when {
|
||||
expression { env.CHANGE_BRANCH?.startsWith('rc') }
|
||||
}
|
||||
steps {
|
||||
script {
|
||||
echo "Calculating installation size for rc branch..."
|
||||
def targetDirAmd = "${env.WORKSPACE}/${env.CHANGE_BRANCH}/amd64"
|
||||
def targetDirRisc = "${env.WORKSPACE}/${env.CHANGE_BRANCH}/riscv64"
|
||||
|
||||
def installSizeAmd = sh(script: "du -s --block-size=1024 ${targetDirAmd} | awk '{print \$1}'", returnStdout: true).trim()
|
||||
def installSizeRisc = sh(script: "du -s --block-size=1024 ${targetDirRisc} | awk '{print \$1}'", returnStdout: true).trim()
|
||||
|
||||
env.INSTALL_SIZE_AMD = installSizeAmd
|
||||
env.INSTALL_SIZE_RISC = installSizeRisc
|
||||
|
||||
echo "Installation size for amd64: ${env.INSTALL_SIZE_AMD} kB"
|
||||
echo "Installation size for riscv64: ${env.INSTALL_SIZE_RISC} kB"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('Create Deb Packages') {
|
||||
when {
|
||||
expression { env.CHANGE_BRANCH?.startsWith('rc') }
|
||||
}
|
||||
steps {
|
||||
script {
|
||||
echo "Creating deb packages for rc branch..."
|
||||
|
||||
def targetDirAmd = "${env.WORKSPACE}/${env.CHANGE_BRANCH}/amd64"
|
||||
def targetDirRisc = "${env.WORKSPACE}/${env.CHANGE_BRANCH}/riscv64"
|
||||
def packageName = "noxis"
|
||||
def version = sh(script: "git describe --tags --abbrev=0", returnStdout: true).trim()
|
||||
def createDebPackage = { arch, binDir, targetDir, installSize ->
|
||||
echo "Creating deb package for ${arch}..."
|
||||
|
||||
sh """
|
||||
mkdir -p ${targetDir}/package/DEBIAN
|
||||
mkdir -p ${targetDir}/package/usr/local/enode/${packageName}
|
||||
mkdir -p ${targetDir}/package/usr/bin
|
||||
mkdir -p ${targetDir}/package/etc/enode
|
||||
mkdir -p ${targetDir}/package/lib/systemd/system
|
||||
|
||||
cp ${binDir}/noxis-cli ${targetDir}/package/usr/local/enode/${packageName}/
|
||||
cp ${binDir}/noxis-rs ${targetDir}/package/usr/local/enode/${packageName}/
|
||||
cp ${binDir}/settings.json ${targetDir}/package/etc/enode/
|
||||
|
||||
cat > ${targetDir}/package/DEBIAN/control <<EOF
|
||||
Package: ${packageName}
|
||||
Version: ${version}
|
||||
Section: unknown
|
||||
Priority: optional
|
||||
Architecture: ${arch}
|
||||
Maintainer: kis <supervisor@rosatom.ru>
|
||||
Description: Noxis Agent Linux
|
||||
Installed-Size: ${installSize}
|
||||
EOF
|
||||
|
||||
chmod +x ${targetDir}/package/usr/local/enode/${packageName}/noxis-cli
|
||||
chmod +x ${targetDir}/package/usr/local/enode/${packageName}/noxis-rs
|
||||
|
||||
cat > ${targetDir}/package/DEBIAN/postinst <<EOF
|
||||
#!/bin/bash
|
||||
ln -sf "/usr/local/enode/${packageName}/noxis-cli" "/usr/bin/noxis-cli"
|
||||
ln -sf "/usr/local/enode/${packageName}/noxis-rs" "/usr/bin/noxis-rs"
|
||||
systemctl daemon-reload
|
||||
systemctl start ${packageName}.service
|
||||
EOF
|
||||
chmod +x ${targetDir}/package/DEBIAN/postinst
|
||||
|
||||
cat > ${targetDir}/package/lib/systemd/system/${packageName}.service <<EOF
|
||||
[Unit]
|
||||
Description=Noxis Service
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
ExecStart=/usr/local/enode/${packageName}/noxis-rs
|
||||
Restart=always
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
EOF
|
||||
|
||||
dpkg-deb --build ${targetDir}/package ${targetDir}/rc/${arch}/${packageName}_${version}_${arch}.deb
|
||||
echo "${packageName}_${version}_${arch}.deb created successfully!"
|
||||
"""
|
||||
}
|
||||
|
||||
createDebPackage("amd64", targetDirAmd, env.WORKSPACE, env.INSTALL_SIZE_AMD)
|
||||
createDebPackage("riscv64", targetDirRisc, env.WORKSPACE, env.INSTALL_SIZE_RISC)
|
||||
|
||||
env.DEB_PATH_AMD64 = "${env.WORKSPACE}/rc/amd64/${packageName}_${version}_amd64.deb"
|
||||
env.DEB_PATH_RISCV64 = "${env.WORKSPACE}/rc/riscv64/${packageName}_${version}_riscv64.deb"
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('Transfer Binaries') {
|
||||
when {
|
||||
expression { env.CHANGE_BRANCH?.startsWith('feature/') }
|
||||
}
|
||||
steps {
|
||||
script {
|
||||
echo "Transferring binaries packages to remote machine..."
|
||||
|
||||
withCredentials([usernamePassword(credentialsId: 'ift', passwordVariable: 'SSH_PASS', usernameVariable: 'SSH_USER')]) {
|
||||
def targetDir = "${env.WORKSPACE}/${env.CHANGE_BRANCH}"
|
||||
def remote = [:]
|
||||
remote.name = "remote-server"
|
||||
remote.host = "192.168.2.33"
|
||||
remote.user = SSH_USER
|
||||
remote.password = SSH_PASS
|
||||
remote.allowAnyHosts = true
|
||||
|
||||
sshPut remote: remote, from: "${targetDir}", into: "/home/user/deployments/"
|
||||
echo "Binaries successfully transferred to remote machine."
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
stage('Upload Debs to Repository') {
|
||||
when {
|
||||
expression { env.CHANGE_BRANCH?.startsWith('rc') }
|
||||
}
|
||||
steps {
|
||||
script {
|
||||
echo "Uploading deb packages to remote repository..."
|
||||
|
||||
withCredentials([usernamePassword(credentialsId: 'prod', passwordVariable: 'SSH_PASS', usernameVariable: 'SSH_USER')]) {
|
||||
def remote = [:]
|
||||
remote.name = "remote-server"
|
||||
remote.host = "192.168.2.99"
|
||||
remote.user = SSH_USER
|
||||
remote.password = SSH_PASS
|
||||
remote.allowAnyHosts = true
|
||||
|
||||
echo "Uploading deb packages using sshPut..."
|
||||
sshPut remote: remote, from: "${env.DEB_PATH_AMD64}", into: "/home/user/repo/debs/"
|
||||
sshPut remote: remote, from: "${env.DEB_PATH_RISCV64}", into: "/home/user/repo/debs/"
|
||||
|
||||
echo "Running repository update commands via sshCommand..."
|
||||
sshCommand remote: remote, command: '''
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
cd /home/user/repo/debs/
|
||||
for deb in *.deb; do
|
||||
reprepro -b /var/www/deb/debian/ includedeb stable $deb
|
||||
done
|
||||
rm -f *.deb
|
||||
'''
|
||||
|
||||
echo "Deb packages successfully uploaded and added to the repository!"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
post {
|
||||
always {
|
||||
script {
|
||||
echo "Cleaning up workspace..."
|
||||
try {
|
||||
if (fileExists("${env.WORKSPACE}/package/")) {
|
||||
sh "rm -rf ${env.WORKSPACE}/package/"
|
||||
}
|
||||
if (fileExists("${env.WORKSPACE}/rc/")) {
|
||||
sh "rm -rf ${env.WORKSPACE}/rc/"
|
||||
}
|
||||
sh "docker stop e-monitor && docker rm e-monitor"
|
||||
} catch (Exception e) {
|
||||
echo "Failed to clean up workspace: ${e}"
|
||||
}
|
||||
}
|
||||
}
|
||||
success {
|
||||
script {
|
||||
when {
|
||||
expression { env.CHANGE_BRANCH?.startsWith('rc') }
|
||||
}
|
||||
echo "Attempting to merge PR ${env.CHANGE_ID} into master..."
|
||||
withCredentials([usernamePassword(credentialsId: 'gitea_creds', usernameVariable: 'GITEA_USER', passwordVariable: 'GITEA_PASS')]) {
|
||||
def prId = env.CHANGE_ID
|
||||
sh """
|
||||
curl -X POST \
|
||||
-u "${GITEA_USER}:${GITEA_PASS}" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"Do":"merge"}' \
|
||||
http://git.entcor/api/v1/repos/VladislavD/runner-rs/pulls/${prId}/merge
|
||||
"""
|
||||
echo "PR ${prId} merged successfully into master!"
|
||||
}
|
||||
}
|
||||
}
|
||||
failure {
|
||||
echo "Pipeline failed. Check the logs for details."
|
||||
}
|
||||
aborted {
|
||||
echo "Pipeline was aborted."
|
||||
}
|
||||
}
|
||||
}
|
||||
75
build.sh
75
build.sh
|
|
@ -1,75 +0,0 @@
|
|||
#!/bin/bash
|
||||
|
||||
# Скрипт для сборки и копирования бинарников
|
||||
# Использование: ./build.sh <архитектура>
|
||||
# Поддерживаемые архитектуры: amd64, riscv64
|
||||
|
||||
if [ -z "$1" ]; then
|
||||
echo "Ошибка: Необходимо указать архитектуру (например, amd64 или riscv64)."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
ARCH="$1"
|
||||
TARGET_DIR="release/${ARCH}"
|
||||
CONTAINER_NAME="e-monitor"
|
||||
|
||||
SUPPORTED_ARCHS=("amd64" "riscv64")
|
||||
if [[ ! " ${SUPPORTED_ARCHS[@]} " =~ " ${ARCH} " ]]; then
|
||||
echo "Ошибка: Неизвестная архитектура $ARCH. Допустимые значения: ${SUPPORTED_ARCHS[*]}."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# На случай, если контейнер с таким именем уже существует
|
||||
docker stop e-monitor && docker rm e-monitor
|
||||
|
||||
echo "Building Docker image..."
|
||||
|
||||
docker build --network=host -t e-monitor . || {
|
||||
echo "Ошибка: Не удалось построить Docker-образ."
|
||||
exit 1
|
||||
}
|
||||
|
||||
echo "Running Docker container..."
|
||||
|
||||
docker run --name "$CONTAINER_NAME" --dns 8.8.8.8 --network=host e-monitor:latest || {
|
||||
echo "Ошибка: Не удалось запустить Docker-контейнер."
|
||||
exit 1
|
||||
}
|
||||
|
||||
echo "Creating target directory: $TARGET_DIR"
|
||||
mkdir -p "$TARGET_DIR"
|
||||
|
||||
case "$ARCH" in
|
||||
amd64)
|
||||
echo "Copying binaries for architecture: amd64"
|
||||
docker cp "$CONTAINER_NAME:/usr/src/kii/target/x86_64-unknown-linux-gnu/release/noxis-cli" "$TARGET_DIR/" || {
|
||||
echo "Ошибка: Не удалось скопировать noxis-cli для amd64."
|
||||
docker stop "$CONTAINER_NAME" && docker rm "$CONTAINER_NAME"
|
||||
exit 1
|
||||
}
|
||||
docker cp "$CONTAINER_NAME:/usr/src/kii/target/x86_64-unknown-linux-gnu/release/noxis-rs" "$TARGET_DIR/" || {
|
||||
echo "Ошибка: Не удалось скопировать noxis-rs для amd64."
|
||||
docker stop "$CONTAINER_NAME" && docker rm "$CONTAINER_NAME"
|
||||
exit 1
|
||||
}
|
||||
;;
|
||||
riscv64)
|
||||
echo "Copying binaries for architecture: riscv64"
|
||||
docker cp "$CONTAINER_NAME:/usr/src/kii/target/riscv64gc-unknown-linux-gnu/release/noxis-cli" "$TARGET_DIR/" || {
|
||||
echo "Ошибка: Не удалось скопировать noxis-cli для riscv64."
|
||||
docker stop "$CONTAINER_NAME" && docker rm "$CONTAINER_NAME"
|
||||
exit 1
|
||||
}
|
||||
docker cp "$CONTAINER_NAME:/usr/src/kii/target/riscv64gc-unknown-linux-gnu/release/noxis-rs" "$TARGET_DIR/" || {
|
||||
echo "Ошибка: Не удалось скопировать noxis-rs для riscv64."
|
||||
docker stop "$CONTAINER_NAME" && docker rm "$CONTAINER_NAME"
|
||||
exit 1
|
||||
}
|
||||
;;
|
||||
esac
|
||||
|
||||
echo "Stopping and removing Docker container..."
|
||||
docker stop "$CONTAINER_NAME" && docker rm "$CONTAINER_NAME"
|
||||
|
||||
echo "Build and extraction completed successfully for architecture: $ARCH"
|
||||
exit 0
|
||||
|
|
@ -1,12 +1,9 @@
|
|||
[package]
|
||||
name = "noxis-cli"
|
||||
version = "0.2.4"
|
||||
version = "0.1.6"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
anyhow = "1.0.94"
|
||||
clap = { version = "4.5.22", features = ["derive"] }
|
||||
serde = { version = "1.0.215", features = ["derive"] }
|
||||
serde_json = "1.0.133"
|
||||
thiserror = "2.0.11"
|
||||
tokio = { version = "1.42.0", features = ["full", "net"] }
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
use clap::{Parser, Subcommand};
|
||||
|
||||
#[derive(Debug, Parser, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Debug, Parser)]
|
||||
pub struct Cli {
|
||||
#[command(
|
||||
subcommand,
|
||||
|
|
@ -8,8 +8,7 @@ pub struct Cli {
|
|||
)]
|
||||
command : Commands,
|
||||
}
|
||||
|
||||
#[derive(Debug, Subcommand, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Debug, Subcommand)]
|
||||
pub enum Commands {
|
||||
#[command(
|
||||
about = "To get info about current Noxis status",
|
||||
|
|
@ -43,7 +42,7 @@ pub enum Commands {
|
|||
Config(ConfigCommand),
|
||||
}
|
||||
|
||||
#[derive(Debug, Parser, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Debug, Parser)]
|
||||
pub struct StartAction {
|
||||
#[arg(
|
||||
long="with-flags",
|
||||
|
|
@ -53,13 +52,13 @@ pub struct StartAction {
|
|||
flags : Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Parser, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Debug, Parser)]
|
||||
pub struct ConfigCommand {
|
||||
#[command(subcommand)]
|
||||
action : ConfigAction,
|
||||
}
|
||||
|
||||
#[derive(Debug, Subcommand, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Debug, Subcommand)]
|
||||
pub enum ConfigAction {
|
||||
#[command(
|
||||
about = "To change current Noxis configuration",
|
||||
|
|
@ -75,7 +74,7 @@ pub enum ConfigAction {
|
|||
Reset,
|
||||
}
|
||||
|
||||
#[derive(Debug, Parser, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Debug, Parser)]
|
||||
pub struct LocalConfig {
|
||||
// flag
|
||||
#[arg(
|
||||
|
|
@ -91,7 +90,7 @@ pub struct LocalConfig {
|
|||
config : String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Parser, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Debug, Parser)]
|
||||
pub struct ProcessCommand {
|
||||
#[arg(
|
||||
help = "name of needed process",
|
||||
|
|
@ -104,7 +103,7 @@ pub struct ProcessCommand {
|
|||
action : ProcessAction,
|
||||
}
|
||||
|
||||
#[derive(Debug, Subcommand, serde::Serialize, serde::Deserialize)]
|
||||
#[derive(Debug, Subcommand)]
|
||||
enum ProcessAction {
|
||||
#[command(
|
||||
about = "To get info about current process status",
|
||||
|
|
|
|||
|
|
@ -1,14 +0,0 @@
|
|||
use thiserror::Error;
|
||||
use super::cli_net::NOXIS_RS_CREDS;
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum NoxisCliError {
|
||||
#[error("Can't send any data to {:?}. Noxis-rs daemon is disabled or can't be accessed", NOXIS_RS_CREDS)]
|
||||
NoxisDaemonMissing,
|
||||
#[error("Noxis CLI can't write any data to the Noxis-rs port. Check daemon and it's web-functionality")]
|
||||
PortIsNotWritable,
|
||||
#[error("Can't send Cli-prompt to the Noxis-rs. Check it's state")]
|
||||
CliPromptCanNotBeSent,
|
||||
#[error("Can't parse CLI struct and send as byte stream")]
|
||||
ToStringCliParsingParsing,
|
||||
}
|
||||
|
|
@ -1,32 +0,0 @@
|
|||
use tokio::net::TcpStream;
|
||||
use tokio::io::AsyncWriteExt;
|
||||
use tokio::time::{Duration, sleep};
|
||||
use anyhow::Result;
|
||||
use super::Cli;
|
||||
use super::cli_error::NoxisCliError;
|
||||
|
||||
pub const NOXIS_RS_CREDS: &str = "127.0.0.1:7753";
|
||||
|
||||
|
||||
pub async fn create_tcp_stream() -> Result<TcpStream> {
|
||||
Ok(TcpStream::connect(NOXIS_RS_CREDS).await.map_err(|_| NoxisCliError::NoxisDaemonMissing)?)
|
||||
}
|
||||
|
||||
pub async fn try_send(stream: Result<TcpStream>, params: Cli) -> Result<()> {
|
||||
use serde_json::to_string;
|
||||
let mut stream = stream.map_err(|_| NoxisCliError::NoxisDaemonMissing)?;
|
||||
loop {
|
||||
if stream.writable().await.is_err() {
|
||||
sleep(Duration::from_millis(100)).await;
|
||||
continue;
|
||||
}
|
||||
// let msg: Cli = from_str(&format!("{:?}", params))?;
|
||||
let msg= to_string(¶ms).map_err(|_| NoxisCliError::ToStringCliParsingParsing)?;
|
||||
// let msg = r"HTTP/1.1 POST\r\nContent-Length: 14\r\nContent-Type: text/plain\r\n\r\nHello, World!@";
|
||||
|
||||
stream.write_all(msg.as_bytes()).await.map_err(|_| NoxisCliError::CliPromptCanNotBeSent)?;
|
||||
// ...
|
||||
break;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
|
@ -1,5 +1,3 @@
|
|||
mod cli;
|
||||
mod cli_net;
|
||||
mod cli_error;
|
||||
|
||||
pub use cli::*;
|
||||
|
|
@ -1,15 +1,11 @@
|
|||
mod cli;
|
||||
mod cli_net;
|
||||
mod cli_error;
|
||||
|
||||
use clap::Parser;
|
||||
use cli::Cli;
|
||||
use cli_net::{create_tcp_stream, try_send};
|
||||
use anyhow::Result;
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()>{
|
||||
fn main() -> Result<(), std::io::Error>{
|
||||
let cli = Cli::parse();
|
||||
try_send(create_tcp_stream().await, cli).await?;
|
||||
dbg!(&cli);
|
||||
println!("{:?}", cli);
|
||||
Ok(())
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
[package]
|
||||
name = "noxis-rs"
|
||||
version = "0.11.10"
|
||||
version = "0.11.3"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
|
|
@ -16,5 +16,3 @@ serde = { version = "1.0.203", features = ["derive"] }
|
|||
serde_json = "1.0.118"
|
||||
sysinfo = "0.32.0"
|
||||
tokio = { version = "1.38.0", features = ["full", "time"] }
|
||||
noxis-cli = { path = "../noxis-cli" }
|
||||
dotenv = "0.15.0"
|
||||
|
|
|
|||
|
|
@ -0,0 +1,25 @@
|
|||
FROM ubuntu
|
||||
|
||||
RUN mkdir -p /usr/src/kii/
|
||||
|
||||
WORKDIR /usr/src/kii/
|
||||
|
||||
RUN mkdir monitor/
|
||||
RUN mkdir -p services/temp-process/
|
||||
RUN touch services/temp-process/dep.txt
|
||||
RUN touch services/temp-process/run.sh
|
||||
RUN echo "./services/temp-process/temp-process &>/dev/null" >> services/temp-process/run.sh
|
||||
|
||||
COPY target/x86_64-unknown-linux-gnu/release/runner-rs monitor/
|
||||
COPY settings.json .
|
||||
COPY temp-process services/temp-process/
|
||||
|
||||
RUN chmod +x services/temp-process/temp-process
|
||||
RUN chmod +x services/temp-process/run.sh
|
||||
RUN chmod +x monitor/runner-rs
|
||||
|
||||
# some troubles with execution this row-cmd
|
||||
# ?: cannot get while initializing container
|
||||
RUN export ENODE_CID=$(cat /proc/self/mountinfo | grep "/docker/containers/" | head -1 | awk -F '/' "{print \$6}")
|
||||
|
||||
ENTRYPOINT [ "/usr/src/kii/monitor/runner-rs" ]
|
||||
|
|
@ -31,3 +31,4 @@
|
|||
}
|
||||
]
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -1,7 +1,6 @@
|
|||
mod options;
|
||||
mod utils;
|
||||
|
||||
use anyhow::Error;
|
||||
use clap::Parser;
|
||||
use log::{error, info};
|
||||
use options::config::*;
|
||||
|
|
@ -13,11 +12,17 @@ use std::sync::Arc;
|
|||
use std::time::Duration;
|
||||
use tokio::sync::mpsc;
|
||||
use utils::*;
|
||||
|
||||
#[allow(unused_imports)]
|
||||
use options::preboot::PrebootParams;
|
||||
|
||||
#[tokio::main(flavor = "multi_thread")]
|
||||
async fn main() -> anyhow::Result<()>{
|
||||
let preboot = Arc::new(PrebootParams::parse().validate()?);
|
||||
async fn main() {
|
||||
let preboot = PrebootParams::parse().validate();
|
||||
|
||||
if let Err(_) = preboot {
|
||||
return;
|
||||
}
|
||||
|
||||
let _ = setup_logger();
|
||||
|
||||
|
|
@ -25,9 +30,9 @@ async fn main() -> anyhow::Result<()>{
|
|||
|
||||
// setting up redis connection \
|
||||
// then conf checks to choose the most actual \
|
||||
let processes: Processes = get_actual_config(preboot.clone()).await.unwrap_or_else(|| {
|
||||
let processes: Processes = get_actual_config().await.unwrap_or_else(|| {
|
||||
error!("No actual configuration for runner. Stopping...");
|
||||
std::process::exit(1);
|
||||
std::process::exit(101);
|
||||
});
|
||||
|
||||
info!(
|
||||
|
|
@ -38,7 +43,7 @@ async fn main() -> anyhow::Result<()>{
|
|||
|
||||
if processes.processes.is_empty() {
|
||||
error!("Processes list is null, runner-rs initialization is stopped");
|
||||
return Err(Error::msg("Empty processes segment in config"));
|
||||
return;
|
||||
}
|
||||
let mut handler: Vec<tokio::task::JoinHandle<()>> = vec![];
|
||||
// is in need to send to the signals handler thread
|
||||
|
|
@ -81,7 +86,7 @@ async fn main() -> anyhow::Result<()>{
|
|||
|
||||
// remote config update subscription
|
||||
handler.push(tokio::spawn(async move {
|
||||
let _ = subscribe_config_stream(Arc::new(processes), preboot.clone()).await;
|
||||
let _ = subscribe_config_stream(Arc::new(processes)).await;
|
||||
}));
|
||||
|
||||
// cli pipeline
|
||||
|
|
@ -92,7 +97,7 @@ async fn main() -> anyhow::Result<()>{
|
|||
for i in handler {
|
||||
let _ = i.await;
|
||||
}
|
||||
Ok(())
|
||||
return;
|
||||
}
|
||||
|
||||
// todo: integration tests
|
||||
|
|
|
|||
|
|
@ -5,24 +5,10 @@ use tokio::time::{sleep, Duration};
|
|||
use std::{borrow::BorrowMut, net::{IpAddr, Ipv4Addr}};
|
||||
// use std::io::BufReader;
|
||||
use tokio::io::{BufReader, AsyncWriteExt, AsyncBufReadExt};
|
||||
use noxis_cli::Cli;
|
||||
use serde_json::from_str;
|
||||
|
||||
/// # Fn `init_cli_pipeline`
|
||||
/// ## for catching all input requests from CLI
|
||||
///
|
||||
/// *input* : -
|
||||
///
|
||||
/// *output* : `anyhow::Result<()>` to wrap errors
|
||||
///
|
||||
/// *initiator* : fn `main`
|
||||
///
|
||||
/// *managing* : `TcpListener` object to handle requests
|
||||
///
|
||||
/// *depends on* : -
|
||||
///
|
||||
|
||||
pub async fn init_cli_pipeline() -> DynResult<()> {
|
||||
match init_listener().await {
|
||||
return match init_listener().await {
|
||||
Some(list) => {
|
||||
loop {
|
||||
if let Ok((socket, addr)) = list.accept().await {
|
||||
|
|
@ -41,21 +27,8 @@ pub async fn init_cli_pipeline() -> DynResult<()> {
|
|||
}
|
||||
}
|
||||
|
||||
/// # Fn `init_listener`
|
||||
/// ## for creating TCP-listener for communicating with CLI
|
||||
///
|
||||
/// *input* : -
|
||||
///
|
||||
/// *output* : `Some<TcpListener>` if port 7753 was opened | None if not
|
||||
///
|
||||
/// *initiator* : fn `init_cli_pipeline`
|
||||
///
|
||||
/// *managing* : `TcpListener` object to handle requests
|
||||
///
|
||||
/// *depends on* : `tokio::net::TcpListener`
|
||||
///
|
||||
async fn init_listener() -> Option<TcpListener> {
|
||||
match TcpListener::bind("127.0.0.1:7753").await {
|
||||
return match TcpListener::bind("127.0.0.1:7753").await {
|
||||
Ok(listener) => {
|
||||
info!("Runner is listening localhost:7753");
|
||||
Some(listener)
|
||||
|
|
@ -67,40 +40,22 @@ async fn init_listener() -> Option<TcpListener> {
|
|||
}
|
||||
}
|
||||
|
||||
/// # Fn `process_connection`
|
||||
/// ## for processing input CLI requests
|
||||
///
|
||||
/// *input* : mut stream: `TcpStream`
|
||||
///
|
||||
/// *output* : -
|
||||
///
|
||||
/// *initiator* : fn `init_cli_pipeline`
|
||||
///
|
||||
/// *managing* : mutable object of `TcpStream`
|
||||
///
|
||||
/// *depends on* : `tokio::net::TcpStream`
|
||||
///
|
||||
async fn process_connection(mut stream: TcpStream) {
|
||||
// loop{
|
||||
// stream.
|
||||
// }
|
||||
let buf_reader = BufReader::new(stream.borrow_mut());
|
||||
let mut rqst = buf_reader.lines();
|
||||
|
||||
|
||||
while let Ok(Some(line)) = rqst.next_line().await {
|
||||
if line.is_empty() {
|
||||
break
|
||||
}
|
||||
match from_str::<Cli>(&line) {
|
||||
Ok(req) => {
|
||||
// TODO: func wrapper
|
||||
dbg!(req);
|
||||
},
|
||||
Err(_) => {
|
||||
break
|
||||
},
|
||||
break;
|
||||
}
|
||||
println!("{}", line);
|
||||
}
|
||||
|
||||
// .map(|result| result.unwrap())
|
||||
// .take_while(|line| !line.is_empty())
|
||||
// .collect();
|
||||
let response = "HTTP/1.1 200 OK\r\nContent-Length: 13\r\nContent-Type: text/plain\r\n\r\nHello, World!";
|
||||
stream.write_all(response.as_bytes()).await.unwrap();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
use super::structs::*;
|
||||
use crate::options::structs::*;
|
||||
use log::{error, info, warn};
|
||||
use redis::{Client, Connection};
|
||||
use std::fs::OpenOptions;
|
||||
|
|
@ -7,10 +7,9 @@ use std::os::unix::process::CommandExt;
|
|||
use std::process::Command;
|
||||
use std::sync::Arc;
|
||||
use std::{env, fs};
|
||||
use super::preboot::PrebootParams;
|
||||
use tokio::time::{Duration, sleep};
|
||||
use tokio::time::Duration;
|
||||
|
||||
// const CONFIG_PATH: &str = "settings.json";
|
||||
const CONFIG_PATH: &str = "settings.json";
|
||||
|
||||
/// # Fn `load_processes`
|
||||
/// ## for reading and parsing *local* storing config
|
||||
|
|
@ -47,24 +46,18 @@ fn load_processes(json_filename: &str) -> Option<Processes> {
|
|||
///
|
||||
/// *depends on* : struct `Processes`
|
||||
///
|
||||
pub async fn get_actual_config(params : Arc<PrebootParams>) -> Option<Processes> {
|
||||
pub async fn get_actual_config() -> Option<Processes> {
|
||||
// * if no local conf -> loop and +inf getting conf from redis server
|
||||
// * if local conf -> once getting conf from redis server
|
||||
let config_path = params.config.to_str().unwrap_or_else(|| {
|
||||
error!("Invalid character in config file. Config path was set to default");
|
||||
"settings.json"
|
||||
});
|
||||
info!("Configurating config module with params: no-remote-config={}, no-sub={}, local config path={:?}, remote server={}", params.no_remote_config, params.no_sub, params.config, params.remote_server_url);
|
||||
match load_processes(config_path) {
|
||||
match load_processes(CONFIG_PATH) {
|
||||
Some(local_conf) => {
|
||||
info!(
|
||||
"Found local configuration, version - {}",
|
||||
&local_conf.date_of_creation
|
||||
);
|
||||
if !params.no_remote_config {
|
||||
if let Some(remote_conf) =
|
||||
// TODO : rework with pubsub mech
|
||||
once_get_remote_configuration(&format!("redis://{}/", ¶ms.remote_server_url))
|
||||
once_get_remote_configuration(&format!("redis://{}/", local_conf.config_server))
|
||||
{
|
||||
return match config_comparing(&local_conf, &remote_conf) {
|
||||
ConfigActuality::Local => {
|
||||
|
|
@ -73,26 +66,24 @@ pub async fn get_actual_config(params : Arc<PrebootParams>) -> Option<Processes>
|
|||
}
|
||||
ConfigActuality::Remote => {
|
||||
info!("Pulled config is more actual. Saving changes!");
|
||||
if save_new_config(&remote_conf, config_path).is_err() {
|
||||
if save_new_config(&remote_conf, CONFIG_PATH).is_err() {
|
||||
error!("Saving changes process failed due to unexpected error...")
|
||||
}
|
||||
Some(remote_conf)
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
Some(local_conf)
|
||||
}
|
||||
None => {
|
||||
warn!("No local valid conf was found. Trying to pull remote one...");
|
||||
if !params.no_remote_config {
|
||||
let mut conn = get_connection_watcher(&open_watcher(&format!("redis://{}/", ¶ms.remote_server_url)));
|
||||
if let Some(conf) = get_remote_conf_watcher(&mut conn).await {
|
||||
let mut conn = get_connection_watcher(&open_watcher("redis://localhost/"));
|
||||
let remote_config = get_remote_conf_watcher(&mut conn).await;
|
||||
if let Some(conf) = remote_config {
|
||||
info!("Config {} was pulled from Redis-Server. Starting...", &conf.date_of_creation);
|
||||
let _ = save_new_config(&conf, config_path);
|
||||
let _ = save_new_config(&conf, CONFIG_PATH);
|
||||
return Some(conf);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
|
@ -191,22 +182,23 @@ fn once_get_remote_configuration(serv_info: &str) -> Option<Processes> {
|
|||
if remote.is_none() {
|
||||
error!("Pulled config is invalid. Check it in Redis Server");
|
||||
}
|
||||
remote
|
||||
return remote;
|
||||
},
|
||||
Err(_) => {
|
||||
error!("Cannot extract payload from new message. Check Redis Server state");
|
||||
None
|
||||
return None;
|
||||
},
|
||||
}
|
||||
},
|
||||
Err(_) => {
|
||||
None
|
||||
warn!("Cannot get config from Redis Server. Empty channel");
|
||||
return None;
|
||||
},
|
||||
}
|
||||
},
|
||||
Err(_) => {
|
||||
error!("Redis subscription process failed. Check Redis configuration!");
|
||||
None
|
||||
return None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -319,13 +311,8 @@ fn restart_main_thread() -> std::io::Result<()> {
|
|||
///
|
||||
/// *depends on* : `Processes`
|
||||
///
|
||||
pub async fn subscribe_config_stream(actual_prcs: Arc<Processes>, params: Arc<PrebootParams>) -> Result<(), CustomError> {
|
||||
let config_path = params.config.to_str().unwrap_or_else(|| "settings.json");
|
||||
|
||||
if params.no_sub || params.no_remote_config {
|
||||
return Err(CustomError::Fatal);
|
||||
}
|
||||
if let Ok(client) = Client::open(format!("redis://{}/", ¶ms.remote_server_url)) {
|
||||
pub async fn subscribe_config_stream(actual_prcs: Arc<Processes>) -> Result<(), CustomError> {
|
||||
if let Ok(client) = Client::open(format!("redis://{}/", &actual_prcs.config_server)) {
|
||||
if let Ok(mut conn) = client.get_connection() {
|
||||
match crate::utils::get_container_id() {
|
||||
Some(channel_name) => {
|
||||
|
|
@ -335,6 +322,7 @@ pub async fn subscribe_config_stream(actual_prcs: Arc<Processes>, params: Arc<Pr
|
|||
info!("Runner subscribed on config update publishing in channel {}", &channel_name);
|
||||
loop {
|
||||
if let Ok(msg) = pubsub.get_message() {
|
||||
info!("New config was pulled from Redis Server");
|
||||
let get_remote_config: Result<String, redis::RedisError> = msg.get_payload();
|
||||
match get_remote_config {
|
||||
Ok(payload) => {
|
||||
|
|
@ -342,8 +330,8 @@ pub async fn subscribe_config_stream(actual_prcs: Arc<Processes>, params: Arc<Pr
|
|||
match config_comparing(&actual_prcs, &remote_config) {
|
||||
ConfigActuality::Remote => {
|
||||
warn!("Pulled config is actual. Saving and restarting...");
|
||||
if save_new_config(&remote_config, config_path).is_err() {
|
||||
error!("Error with saving new config to {}. Stopping sub mechanism...", config_path);
|
||||
if save_new_config(&remote_config, CONFIG_PATH).is_err() {
|
||||
error!("Error with saving new config to {}. Stopping sub mechanism...", &CONFIG_PATH);
|
||||
return Err(CustomError::Fatal);
|
||||
}
|
||||
if restart_main_thread().is_err() {
|
||||
|
|
@ -351,10 +339,7 @@ pub async fn subscribe_config_stream(actual_prcs: Arc<Processes>, params: Arc<Pr
|
|||
return Err(CustomError::Fatal);
|
||||
}
|
||||
}
|
||||
_ => {
|
||||
warn!("Pulled new config. Current config is more actual ...");
|
||||
continue
|
||||
},
|
||||
_ => continue,
|
||||
}
|
||||
}
|
||||
else {
|
||||
|
|
@ -367,7 +352,7 @@ pub async fn subscribe_config_stream(actual_prcs: Arc<Processes>, params: Arc<Pr
|
|||
},
|
||||
}
|
||||
}
|
||||
sleep(Duration::from_secs(30)).await;
|
||||
tokio::time::sleep(tokio::time::Duration::from_secs(30)).await;
|
||||
}
|
||||
} else {
|
||||
error!("Cannot subscribe channel {}. Check Redis Server status", &channel_name);
|
||||
|
|
@ -448,7 +433,7 @@ fn save_new_config(config: &Processes, config_file: &str) -> Result<(), CustomEr
|
|||
Err(_) => Err(CustomError::Fatal),
|
||||
}
|
||||
}
|
||||
Err(_) => Err(CustomError::Fatal),
|
||||
Err(_) => return Err(CustomError::Fatal),
|
||||
}
|
||||
}
|
||||
Err(_) => Err(CustomError::Fatal),
|
||||
|
|
|
|||
|
|
@ -1,107 +1,10 @@
|
|||
// module to handle pre-boot params of the monitor
|
||||
#[allow(unused_imports)]
|
||||
use anyhow::{Result, Ok, Error};
|
||||
use clap::Parser;
|
||||
use std::path::PathBuf;
|
||||
use std::env::var;
|
||||
use dotenv::dotenv;
|
||||
|
||||
const SOCKET_PATH: &str = "/var/run/enode/hostagent.sock";
|
||||
|
||||
///
|
||||
enum EnvVars {
|
||||
NoxisNoHagent,
|
||||
NoxisNoLogs,
|
||||
NoxisRefreshLogs,
|
||||
NoxisNoRemoteConfig,
|
||||
NoxisNoConfigSub,
|
||||
NoxisSocketPath,
|
||||
NoxisLogTo,
|
||||
NoxisRemoteServerUrl,
|
||||
NoxisConfig,
|
||||
NoxisMetrics,
|
||||
}
|
||||
|
||||
///
|
||||
impl std::fmt::Display for EnvVars {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
match self {
|
||||
EnvVars::NoxisNoHagent => write!(f, "NOXIS_NO_HAGENT"),
|
||||
EnvVars::NoxisNoLogs => write!(f, "NOXIS_NO_LOGS"),
|
||||
EnvVars::NoxisRefreshLogs => write!(f, "NOXIS_REFRESH_LOGS"),
|
||||
EnvVars::NoxisNoRemoteConfig => write!(f, "NOXIS_NO_REMOTE_CONFIG"),
|
||||
EnvVars::NoxisNoConfigSub => write!(f, "NOXIS_NO_CONFIG_SUB"),
|
||||
EnvVars::NoxisSocketPath => write!(f, "NOXIS_SOCKET_PATH"),
|
||||
EnvVars::NoxisLogTo => write!(f, "NOXIS_LOG_TO"),
|
||||
EnvVars::NoxisRemoteServerUrl => write!(f, "NOXIS_REMOTE_SERVER_URL"),
|
||||
EnvVars::NoxisConfig => write!(f, "NOXIS_CONFIG"),
|
||||
EnvVars::NoxisMetrics => write!(f, "NOXIS_METRICS"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
impl<'a> EnvVars {
|
||||
// Default trait func is not satisfying this issue
|
||||
fn default(self) -> &'a str {
|
||||
match self {
|
||||
EnvVars::NoxisNoHagent => "false",
|
||||
EnvVars::NoxisNoLogs => "false",
|
||||
EnvVars::NoxisRefreshLogs => "false",
|
||||
EnvVars::NoxisNoRemoteConfig => "false",
|
||||
EnvVars::NoxisNoConfigSub => "false",
|
||||
EnvVars::NoxisSocketPath => "/var/run/enode/hostagent.sock",
|
||||
EnvVars::NoxisLogTo => "./",
|
||||
EnvVars::NoxisRemoteServerUrl => "localhost",
|
||||
EnvVars::NoxisConfig => "./settings.json",
|
||||
EnvVars::NoxisMetrics => "full",
|
||||
}
|
||||
}
|
||||
fn process_env_var(self, preboot_value: &str) {
|
||||
// let default = self.default();
|
||||
match var(self.to_string()) {
|
||||
std::result::Result::Ok(val) => {
|
||||
if val != preboot_value {
|
||||
std::env::set_var(self.to_string(), self.default());
|
||||
}
|
||||
},
|
||||
Err(_) => {
|
||||
std::env::set_var(self.to_string(), preboot_value);
|
||||
},
|
||||
}
|
||||
}
|
||||
pub fn setup(preboot: &PrebootParams) {
|
||||
// setup default if not exists
|
||||
// check values and save preboot states in env vars if not equal
|
||||
|
||||
Self::NoxisNoHagent.process_env_var(&preboot.no_hostagent.to_string());
|
||||
Self::NoxisNoLogs.process_env_var(&preboot.no_logs.to_string());
|
||||
Self::NoxisRefreshLogs.process_env_var(&preboot.refresh_logs.to_string());
|
||||
Self::NoxisNoRemoteConfig.process_env_var(&preboot.no_remote_config.to_string());
|
||||
Self::NoxisNoConfigSub.process_env_var(&preboot.no_sub.to_string());
|
||||
Self::NoxisSocketPath.process_env_var(preboot.socket_path.to_str().unwrap());
|
||||
Self::NoxisLogTo.process_env_var(preboot.log_to.to_str().unwrap());
|
||||
Self::NoxisRemoteServerUrl.process_env_var(&preboot.remote_server_url);
|
||||
Self::NoxisConfig.process_env_var(preboot.config.to_str().unwrap());
|
||||
Self::NoxisMetrics.process_env_var(&preboot.metrics.to_string());
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
/// # Enum `MetricsPrebootParams`
|
||||
/// ## for setting up metrics mode as preboot param from command prompt
|
||||
///
|
||||
/// examples:
|
||||
/// ``` bash
|
||||
/// noxis-rs ... --metrics full
|
||||
/// noxis-rs ... --metrics system
|
||||
/// noxis-rs ... --metrics processes
|
||||
/// noxis-rs ... --metrics net
|
||||
/// noxis-rs ... --metrics none
|
||||
/// ```
|
||||
///
|
||||
#[derive(clap::ValueEnum, Debug, Clone)]
|
||||
pub enum MetricsPrebootParams {
|
||||
enum MetricsPrebootParams {
|
||||
Full,
|
||||
System,
|
||||
Processes,
|
||||
|
|
@ -109,8 +12,6 @@ pub enum MetricsPrebootParams {
|
|||
None,
|
||||
}
|
||||
|
||||
/// # `std::fmt::Display` implementation for `MetricsPrebootParams`
|
||||
/// ## to enable parsing object to String
|
||||
impl std::fmt::Display for MetricsPrebootParams {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
match self {
|
||||
|
|
@ -123,71 +24,6 @@ impl std::fmt::Display for MetricsPrebootParams {
|
|||
}
|
||||
}
|
||||
|
||||
/// # struct `PrebootParams`
|
||||
/// ## to parse and set up all modes as preboot params from command prompt
|
||||
///
|
||||
/// ### args :
|
||||
///
|
||||
/// `--no-hagent` - to disable hagent work module and set up work mode as autonomous
|
||||
/// ### usage :
|
||||
/// ``` bash
|
||||
/// noxis-rs ... --no-hagent ...
|
||||
/// ```
|
||||
///
|
||||
///
|
||||
/// `--no-logs` - to disable logging at all
|
||||
/// ### usage :
|
||||
/// ``` bash
|
||||
/// noxis-rs ... --no-logs ...
|
||||
/// ```
|
||||
///
|
||||
/// `--refresh-logs` - to truncate logs directory
|
||||
/// ### usage :
|
||||
/// ``` bash
|
||||
/// noxis-rs ... --refresh-logs ...
|
||||
/// ```
|
||||
///
|
||||
/// `--no-remote-config` - to disable work with Redis as config producer
|
||||
/// ### usage :
|
||||
/// ``` bash
|
||||
/// noxis-rs ... --no-remote-config ...
|
||||
/// ```
|
||||
///
|
||||
/// `--no-sub` - to disable Redis subscribtion mechanism
|
||||
/// ### usage :
|
||||
/// ``` bash
|
||||
/// noxis-rs ... --no-sub ...
|
||||
/// ```
|
||||
///
|
||||
/// `--socket-path` - to set Unix Domain Socket file's directory
|
||||
/// ### usage :
|
||||
/// ``` bash
|
||||
/// noxis-rs ... --socket-path /var/run/enode/hostagent.sock ...
|
||||
/// ```
|
||||
///
|
||||
/// `--log-to` - to set directory for logs
|
||||
/// ### usage :
|
||||
/// ``` bash
|
||||
/// noxis-rs ... --log-to /dir/to/logs/ ...
|
||||
/// ```
|
||||
///
|
||||
/// `--remote-server-url` - to set Redis Server
|
||||
/// ### usage :
|
||||
/// ``` bash
|
||||
/// noxis-rs ... --remote-server-url 192.168.28.12 ...
|
||||
/// ```
|
||||
///
|
||||
/// `--config` - to set Noxis' config full path
|
||||
/// ### usage :
|
||||
/// ``` bash
|
||||
/// noxis-rs ... --config /etc/enode/settings.json ...
|
||||
/// ```
|
||||
///
|
||||
/// `--metrics` - to set metrics mode
|
||||
/// ### usage :
|
||||
/// ``` bash
|
||||
/// noxis-rs ... --metrics full ...
|
||||
/// ```
|
||||
#[derive(Debug, Parser)]
|
||||
pub struct PrebootParams {
|
||||
// actions
|
||||
|
|
@ -232,28 +68,28 @@ pub struct PrebootParams {
|
|||
conflicts_with="no_hostagent",
|
||||
help="To set .sock file's path used in communication with host-agent"
|
||||
)]
|
||||
pub socket_path : PathBuf,
|
||||
socket_path : PathBuf,
|
||||
#[arg(
|
||||
long = "log-to",
|
||||
default_value="./",
|
||||
conflicts_with="no_logs",
|
||||
help="To set a path to logs directory"
|
||||
)]
|
||||
pub log_to : PathBuf,
|
||||
log_to : PathBuf,
|
||||
#[arg(
|
||||
long = "remote-server-url",
|
||||
default_value="localhost",
|
||||
default_value="redis://localhost",
|
||||
conflicts_with="no_remote_config",
|
||||
help = "To set url of remote config server using in remote config pulling mechanism"
|
||||
)]
|
||||
pub remote_server_url : String,
|
||||
remote_server_url : String,
|
||||
#[arg(
|
||||
long = "config",
|
||||
short,
|
||||
default_value="settings.json",
|
||||
help="To set local config file path"
|
||||
)]
|
||||
pub config : PathBuf,
|
||||
config : PathBuf,
|
||||
|
||||
// value enum params (metrics)
|
||||
#[arg(
|
||||
|
|
@ -262,47 +98,26 @@ pub struct PrebootParams {
|
|||
default_value_t=MetricsPrebootParams::Full,
|
||||
help="To set metrics grubbing mode"
|
||||
)]
|
||||
pub metrics: MetricsPrebootParams,
|
||||
metrics: MetricsPrebootParams,
|
||||
}
|
||||
|
||||
/// # implementation for `MetricsPrebootParams`
|
||||
/// ## to enable validation mechanism
|
||||
impl PrebootParams {
|
||||
pub fn validate(mut self) -> Result<Self> {
|
||||
dotenv().ok();
|
||||
if !self.socket_path.exists() && !self.no_hostagent {
|
||||
if self.socket_path.to_string_lossy() == SOCKET_PATH {
|
||||
self.no_hostagent = true;
|
||||
eprintln!("Warning: Socket-file wasn't found. Working without hostagent module...");
|
||||
} else {
|
||||
eprintln!("Warning: Socket-file wasn't found or Noxis can't read it. Socket-file was set to default");
|
||||
if !PathBuf::from(SOCKET_PATH).exists() {
|
||||
self.no_hostagent = true;
|
||||
eprintln!("Warning: Socket-file wasn't found. Working without hostagent module...");
|
||||
} else {
|
||||
self.socket_path = PathBuf::from(SOCKET_PATH);
|
||||
}
|
||||
}
|
||||
// return Err(Error::msg("Socket-file not found or Noxis can't read it. Cannot start"));
|
||||
pub fn validate(self) -> Result<Self> {
|
||||
if !self.socket_path.exists() {
|
||||
eprintln!("Socket-file {} doesn't exist. Cannot start", &self.socket_path.display());
|
||||
return Err(Error::msg("Socket-file Not Found"));
|
||||
}
|
||||
// existing log dir
|
||||
if !self.log_to.exists() && !self.no_logs {
|
||||
eprintln!("Error: Log-Dir not found or Noxis can't read it. LogDir was set to default");
|
||||
self.log_to = PathBuf::from("./");
|
||||
// return Err(Error::msg("Log Directory Not Found or Noxis can't read it. Cannot start"));
|
||||
if !self.log_to.exists() {
|
||||
eprintln!("Log directory {} doesn't exist", &self.log_to.display());
|
||||
return Err(Error::msg("Log Directory Not Found. Cannot start"));
|
||||
}
|
||||
// existing sock file
|
||||
if !self.config.exists() {
|
||||
eprintln!("Error: Invalid character in config file. Config path was set to default");
|
||||
let config = PathBuf::from("/etc/settings.json");
|
||||
if !config.exists() && self.no_remote_config {
|
||||
return Err(Error::msg("Noxis cannot run without config. Create local config or enable remote-config mechanism"));
|
||||
}
|
||||
self.config = PathBuf::from("settings.json");
|
||||
// return Err(Error::msg("Local Config Not Found or Noxis can't read it. Cannot start"));
|
||||
eprintln!("Local config file {} doesn't exist", &self.config.display());
|
||||
return Err(Error::msg("Local Config Not Found. Cannot start"));
|
||||
}
|
||||
// redis server check
|
||||
EnvVars::setup(&self);
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
use super::structs::CustomError;
|
||||
use crate::options::structs::CustomError;
|
||||
use std::sync::Arc;
|
||||
use tokio::io;
|
||||
use tokio::sync::mpsc;
|
||||
|
|
|
|||
|
|
@ -156,7 +156,7 @@ async fn process_protocol_symbol(proc: Arc<TrackingProcess>, val: u8) -> Result<
|
|||
// },
|
||||
// 101 - Impermissible trigger values in JSON
|
||||
101 => {
|
||||
error!("Impermissible trigger values in JSON in {}'s block. Killing thread...", &proc.name);
|
||||
error!("Impermissible trigger values in JSON in {}'s block. Killing thread...", proc.name);
|
||||
if is_active(&proc.name).await {
|
||||
terminate_process(&proc.name).await;
|
||||
}
|
||||
|
|
@ -164,10 +164,9 @@ async fn process_protocol_symbol(proc: Arc<TrackingProcess>, val: u8) -> Result<
|
|||
},
|
||||
//
|
||||
// 121 - Cannot create valid watcher for file dependency
|
||||
// todo : think about valid situation
|
||||
121 => {
|
||||
error!("Cannot create valid watcher for file dependency. Terminating {} process...", &proc.name);
|
||||
let _ = terminate_process(&proc.name).await;
|
||||
error!("Cannot create valid watcher for {}'s file dependency. Terminating thread...", proc.name);
|
||||
let _ = terminate_process("runner-rs").await;
|
||||
return Err(CustomError::Fatal)
|
||||
},
|
||||
// 111 - global thread termination with killing current child in a face
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
use crate::options::structs::{CustomError, Files};
|
||||
use super::prcs::{is_active, is_frozen};
|
||||
use crate::utils::prcs::{is_active, is_frozen};
|
||||
use inotify::{EventMask, Inotify, WatchMask};
|
||||
use std::borrow::BorrowMut;
|
||||
use std::path::Path;
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ use crate::options::structs::TrackingProcess;
|
|||
use sysinfo::{Process, System};
|
||||
use tokio::join;
|
||||
use crate::options::structs::{ProcessMetrics, ContainerMetrics};
|
||||
use super::get_container_id;
|
||||
use crate::utils::get_container_id;
|
||||
// use pcap::{Device, Capture, Active};
|
||||
// use std::net::Ipv4Addr;
|
||||
// use anyhow::{Result, Ok};
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
use crate::options::structs::{CustomError, Services};
|
||||
use super::prcs::{is_active, is_frozen};
|
||||
use crate::utils::prcs::{is_active, is_frozen};
|
||||
use log::{error, warn};
|
||||
use std::net::{TcpStream, ToSocketAddrs};
|
||||
use std::sync::Arc;
|
||||
|
|
|
|||
Loading…
Reference in New Issue