From 09c44e3e4877a283bdb9bfca6ac1036513f2f2c1 Mon Sep 17 00:00:00 2001
From: licunlong <licunlong1@huawei.com>
Date: Wed, 5 Jul 2023 16:29:35 +0800
Subject: [PATCH] fix: log message out when we create/delete a file or
 directory

---
 coms/service/src/mng.rs            |  9 ++-------
 core/libsysmaster/rel/api.rs       | 17 ++++++++++-------
 core/libsysmaster/rel/history.rs   | 23 ++++++++++-------------
 core/sysmaster/manager/commands.rs |  9 ++++++---
 core/sysmaster/unit/sigchld.rs     |  5 ++++-
 init/src/runtime/comm.rs           | 12 ++++++++----
 libs/cgroup/src/cgroup.rs          |  9 +++++++--
 9 files changed, 53 insertions(+), 46 deletions(-)

diff --git a/coms/service/src/mng.rs b/coms/service/src/mng.rs
index 4bf20bd..b44a0dd 100644
--- a/coms/service/src/mng.rs
+++ b/coms/service/src/mng.rs
@@ -20,7 +20,7 @@ use super::rentry::{
 };
 use super::spawn::ServiceSpawn;
 use crate::rentry::{ExitStatus, PreserveMode};
-use basic::{fd_util, IN_SET};
+use basic::{do_entry_log, fd_util, IN_SET};
 use basic::{file_util, process_util};
 use event::{EventState, EventType, Events, Source};
 use log::Level;
@@ -623,12 +623,7 @@ impl ServiceMng {
         }
 
         if let Some(p) = self.config.pid_file() {
-            if let Err(e) = nix::unistd::unlink(&p) {
-                log::warn!(
-                    "{}",
-                    format!("failed to unlink pid file: {:?}, error: {}", p, e)
-                );
-            }
+            do_entry_log!(nix::unistd::unlink, p, "unlink");
         }
     }
 
diff --git a/core/libsysmaster/rel/api.rs b/core/libsysmaster/rel/api.rs
index ad14796..fb482b8 100644
--- a/core/libsysmaster/rel/api.rs
+++ b/core/libsysmaster/rel/api.rs
@@ -19,6 +19,7 @@ use super::{
     ReDbTable, ReStation, ReStationKind,
 };
 use crate::{error::*, rel::base};
+use basic::do_entry_or_return_io_error;
 use heed::Database;
 use std::{
     fs::{self, File},
@@ -267,6 +268,7 @@ impl Reliability {
             } else {
                 log::info!("reliability debug_clear: first time, try clear.");
                 File::create(&cfirst).unwrap();
+                log::debug!("Successfully created {cfirst:?}");
                 log::info!("reliability debug_clear: first time, clear ...");
 
                 // clear data excluding enable
@@ -289,6 +291,7 @@ impl Reliability {
             } else {
                 log::info!("reliability debug_panic: first time, try panic.");
                 File::create(&pfirst).unwrap();
+                log::debug!("Successfully created {pfirst:?}");
                 log::info!("reliability debug_panic: first time, panic ...");
                 panic!("first debug_panic.");
             }
@@ -366,15 +369,15 @@ impl Reliability {
 pub fn reli_debug_enable_switch(enable: bool) -> Result<()> {
     log::info!("reliability debug: enable[{}] switch.", enable);
 
-    // [enable]touch switch.debug or [disable]rm -rf switch.debug
     let dir_string = base::reli_dir_get().unwrap();
     let switch = Path::new(&dir_string).join(RELI_DEBUG_SWITCH_FILE);
-    if enable {
-        if !switch.exists() {
-            File::create(&switch).context(IoSnafu)?;
-        }
-    } else if switch.exists() {
-        fs::remove_file(&switch).context(IoSnafu)?;
+    // touch switch.debug if enable
+    if enable && !switch.exists() {
+        do_entry_or_return_io_error!(File::create, switch, "create");
+    }
+    // remove switch.debug if disable
+    if !enable && switch.exists() {
+        do_entry_or_return_io_error!(fs::remove_file, switch, "remove");
     }
 
     Ok(())
diff --git a/core/libsysmaster/rel/history.rs b/core/libsysmaster/rel/history.rs
index 9381c10..fc31623 100644
--- a/core/libsysmaster/rel/history.rs
+++ b/core/libsysmaster/rel/history.rs
@@ -12,6 +12,7 @@
 
 use super::base::{ReDbRoTxn, ReDbRwTxn, ReDbTable};
 use crate::error::*;
+use basic::{do_entry_log, do_entry_or_return_io_error};
 use heed::{CompactionOption, Env, EnvOpenOptions};
 use std::cell::RefCell;
 use std::collections::HashMap;
@@ -126,8 +127,8 @@ impl ReliHistory {
         let next_file = next_path.join(RELI_HISTORY_DATA_FILE);
 
         // clear next: delete and re-create the whole directory
-        fs::remove_dir_all(next_path.clone()).context(IoSnafu)?;
-        fs::create_dir_all(next_path).context(IoSnafu)?;
+        do_entry_or_return_io_error!(fs::remove_dir_all, next_path, "remove");
+        do_entry_or_return_io_error!(fs::create_dir_all, next_path, "create");
 
         // copy to next
         self.env
@@ -138,21 +139,17 @@ impl ReliHistory {
         // remark the next flag at last: the another one
         let bflag = bflag_path_get(history.clone());
         if self.b_exist {
-            fs::remove_file(bflag).context(IoSnafu)?;
+            do_entry_or_return_io_error!(fs::remove_file, bflag, "remove");
         } else {
-            File::create(bflag).context(IoSnafu)?;
+            do_entry_or_return_io_error!(File::create, bflag, "create");
         }
 
         // try to clear previous: it would be done in the next re-exec, but we try to delete it as soon as possible.
         let cur_path = history.join(subdir_cur_get(self.b_exist));
         let cur_data = cur_path.join(RELI_HISTORY_DATA_FILE);
         let cur_lock = cur_path.join(RELI_HISTORY_LOCK_FILE);
-        if let Err(e) = fs::remove_file(cur_data.clone()) {
-            log::error!("remove data file {:?} failed, err = {:?}", cur_data, e);
-        }
-        if let Err(e) = fs::remove_file(cur_lock.clone()) {
-            log::error!("remove lock file {:?} failed, err = {:?}", cur_lock, e);
-        }
+        do_entry_log!(fs::remove_file, cur_data, "remove");
+        do_entry_log!(fs::remove_file, cur_lock, "remove");
 
         Ok(())
     }
@@ -181,18 +178,18 @@ pub fn prepare(dir_str: &str) -> Result<()> {
     // directory
     let history = history_path_get(dir_str);
     if !history.exists() {
-        fs::create_dir_all(&history).context(IoSnafu)?;
+        do_entry_or_return_io_error!(fs::create_dir_all, history, "create");
     }
 
     // sub-directory
     let a = history.join(RELI_HISTORY_A_DIR);
     if !a.exists() {
-        fs::create_dir_all(&a).context(IoSnafu)?;
+        do_entry_or_return_io_error!(fs::create_dir_all, a, "create");
     }
 
     let b = history.join(RELI_HISTORY_B_DIR);
     if !b.exists() {
-        fs::create_dir_all(&b).context(IoSnafu)?;
+        do_entry_or_return_io_error!(fs::create_dir_all, a, "create");
     }
 
     Ok(())
diff --git a/core/sysmaster/manager/commands.rs b/core/sysmaster/manager/commands.rs
index 57f9d5d..6e1da40 100644
--- a/core/sysmaster/manager/commands.rs
+++ b/core/sysmaster/manager/commands.rs
@@ -10,7 +10,7 @@
 // NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 // See the Mulan PSL v2 for more details.
 
-use basic::socket_util;
+use basic::{do_entry_log, socket_util};
 use cmdproto::proto::execute::ExecuterAction;
 use cmdproto::proto::ProstServerStream;
 use event::{EventType, Events, Source};
@@ -37,7 +37,7 @@ impl<T> Commands<T> {
         let sctl_socket_path = Path::new(SCTL_SOCKET);
         /* remove the old socket if it exists */
         if sctl_socket_path.exists() && !sctl_socket_path.is_symlink() {
-            let _ = std::fs::remove_file(sctl_socket_path);
+            do_entry_log!(std::fs::remove_file, sctl_socket_path, "remove");
         }
         let sctl_socket_addr = socket::UnixAddr::new(Path::new(SCTL_SOCKET)).unwrap();
         let socket_fd = socket::socket(
@@ -51,7 +51,10 @@ impl<T> Commands<T> {
         socket_util::set_pass_cred(socket_fd, true).unwrap();
         /* create the socket with mode 666 */
         let old_mask = stat::umask(stat::Mode::from_bits_truncate(!0o666));
-        let _ = socket::bind(socket_fd, &sctl_socket_addr);
+        match socket::bind(socket_fd, &sctl_socket_addr) {
+            Err(e) => log::error!("Failed to bind {sctl_socket_addr:?}: {e}"),
+            Ok(_) => log::debug!("Successfully bind {sctl_socket_addr:?}"),
+        }
         /* restore our umask */
         let _ = stat::umask(old_mask);
         /* Allow at most 4096 incoming connections can queue */
diff --git a/core/sysmaster/unit/sigchld.rs b/core/sysmaster/unit/sigchld.rs
index 423b9b9..eead6f7 100644
--- a/core/sysmaster/unit/sigchld.rs
+++ b/core/sysmaster/unit/sigchld.rs
@@ -198,7 +198,10 @@ impl SigchldData {
 
         // check
         let (pid, code, signal) = si.unwrap();
-        log::debug!("Process {} exited witch code: {code}, signal: {signal:?}", pid.as_raw());
+        log::debug!(
+            "Process {} exited witch code: {code}, signal: {signal:?}",
+            pid.as_raw()
+        );
 
         if pid.as_raw() <= 0 {
             log::debug!("invalid pid in signal: {:?}", pid);
diff --git a/init/src/runtime/comm.rs b/init/src/runtime/comm.rs
index 8f71511..92d52bc 100644
--- a/init/src/runtime/comm.rs
+++ b/init/src/runtime/comm.rs
@@ -282,11 +282,15 @@ fn create_listen_fd(epoll: &Rc<Epoll>) -> Result<(i32, Inotify, WatchDescriptor)
     )?;
 
     let sock_path = PathBuf::from(INIT_SOCKET);
-    let parent_path = sock_path.as_path().parent();
-    match parent_path {
-        Some(path) => fs::create_dir_all(path)
-            .map_err(|e| Errno::from_i32(e.raw_os_error().unwrap_or(Errno::EINVAL as i32)))?,
+    let path = match sock_path.as_path().parent() {
         None => return Err(Errno::EINVAL),
+        Some(v) => v,
+    };
+    if let Err(e) = fs::create_dir_all(path) {
+        eprintln!("Failed to create directory {path:?}: {e}");
+        return Err(Errno::from_i32(
+            e.raw_os_error().unwrap_or(Errno::EINVAL as i32),
+        ));
     }
 
     if let Err(e) = unistd::unlink(&sock_path) {
diff --git a/libs/cgroup/src/cgroup.rs b/libs/cgroup/src/cgroup.rs
index 13efee2..02b266c 100644
--- a/libs/cgroup/src/cgroup.rs
+++ b/libs/cgroup/src/cgroup.rs
@@ -13,6 +13,7 @@
 use super::CgFlags;
 use crate::error::*;
 use crate::CgType;
+use basic::do_entry_or_return_io_error;
 use basic::special::CGROUP_SYSMASTER;
 use basic::special::INIT_SCOPE;
 use basic::special::SYSMASTER_SLICE;
@@ -146,7 +147,7 @@ pub fn cg_attach(pid: Pid, cg_path: &PathBuf) -> Result<()> {
 pub fn cg_create(cg_path: &PathBuf) -> Result<()> {
     log::debug!("cgroup create path {:?}", cg_path);
     let abs_cg_path: PathBuf = cg_abs_path(cg_path, &PathBuf::from(""))?;
-    fs::create_dir_all(abs_cg_path).context(IoSnafu)?;
+    do_entry_or_return_io_error!(fs::create_dir_all, abs_cg_path, "create");
 
     Ok(())
 }
@@ -232,7 +233,10 @@ fn remove_dir(cg_path: &PathBuf) -> Result<()> {
     let mut try_times = 0;
     loop {
         let e = match fs::remove_dir(cg_path) {
-            Ok(()) => return Ok(()),
+            Ok(()) => {
+                log::debug!("Successfully removed {cg_path:?}");
+                return Ok(());
+            }
             Err(e) => e,
         };
         let os_errno = match e.raw_os_error() {
@@ -244,6 +248,7 @@ fn remove_dir(cg_path: &PathBuf) -> Result<()> {
             try_times += 1;
             continue;
         }
+        log::error!("Failed to remove {cg_path:?}: {e}");
         return Err(Error::Io { source: e });
     }
 }
-- 
2.33.0

