Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove read_file_to_str helper #245

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 4 additions & 4 deletions crates/runc-shim/src/runc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,15 +40,15 @@ use containerd_shim::{
cgroups::metrics::Metrics,
protobuf::{CodedInputStream, Message},
},
util::{asyncify, mkdir, mount_rootfs, read_file_to_str, write_options, write_runtime},
util::{asyncify, mkdir, mount_rootfs, write_options, write_runtime},
Console, Error, ExitSignal, Result,
};
use log::{debug, error};
use nix::{sys::signal::kill, unistd::Pid};
use oci_spec::runtime::{LinuxResources, Process};
use runc::{Command, Runc, Spawner};
use tokio::{
fs::{remove_file, File, OpenOptions},
fs::{self, remove_file, File, OpenOptions},
io::{AsyncBufReadExt, AsyncRead, AsyncReadExt, AsyncWrite, BufReader},
};

Expand Down Expand Up @@ -179,7 +179,7 @@ impl RuncFactory {
return Err(runtime_error(bundle, e, "OCI runtime create failed").await);
}
copy_io_or_console(init, socket, pio, init.lifecycle.exit_signal.clone()).await?;
let pid = read_file_to_str(pid_path).await?.parse::<i32>()?;
let pid = fs::read_to_string(pid_path).await?.parse::<i32>()?;
init.pid = pid;
Ok(())
}
Expand Down Expand Up @@ -427,7 +427,7 @@ impl ProcessLifecycle<ExecProcess> for RuncExecLifecycle {
}

copy_io_or_console(p, socket, pio, p.lifecycle.exit_signal.clone()).await?;
let pid = read_file_to_str(pid_path).await?.parse::<i32>()?;
let pid = fs::read_to_string(pid_path).await?.parse::<i32>()?;
p.pid = pid;
p.state = Status::RUNNING;
Ok(())
Expand Down
6 changes: 3 additions & 3 deletions crates/shim/src/asynchronous/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,14 +47,14 @@ use nix::{
unistd::Pid,
};
use signal_hook_tokio::Signals;
use tokio::{io::AsyncWriteExt, sync::Notify};
use tokio::{fs, io::AsyncWriteExt, sync::Notify};

use crate::{
args,
asynchronous::{monitor::monitor_notify_by_pid, publisher::RemotePublisher},
error::{Error, Result},
logger, parse_sockaddr, reap, socket_address,
util::{asyncify, read_file_to_str, write_str_to_file},
util::{asyncify, write_str_to_file},
Config, Flags, StartOpts, SOCKET_FD, TTRPC_ADDRESS,
};

Expand Down Expand Up @@ -188,7 +188,7 @@ where

// NOTE: If the shim server is down(like oom killer), the address
// socket might be leaking.
if let Ok(address) = read_file_to_str("address").await {
if let Ok(address) = fs::read_to_string("address").await {
remove_socket_silently(&address).await;
}
Ok(())
Expand Down
34 changes: 11 additions & 23 deletions crates/shim/src/asynchronous/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ use libc::mode_t;
use nix::sys::stat::Mode;
use oci_spec::runtime::Spec;
use tokio::{
fs::OpenOptions,
io::{AsyncReadExt, AsyncWriteExt},
fs::{self, OpenOptions},
io::AsyncWriteExt,
task::spawn_blocking,
};

Expand All @@ -41,22 +41,6 @@ where
.map_err(other_error!(e, "failed to spawn blocking task"))?
}

pub async fn read_file_to_str(path: impl AsRef<Path>) -> Result<String> {
let mut file = tokio::fs::File::open(&path).await.map_err(io_error!(
e,
"failed to open file {}",
path.as_ref().display()
))?;

let mut content = String::new();
file.read_to_string(&mut content).await.map_err(io_error!(
e,
"failed to read {}",
path.as_ref().display()
))?;
Ok(content)
}

pub async fn write_str_to_file(filename: impl AsRef<Path>, s: impl AsRef<str>) -> Result<()> {
let file = filename.as_ref().file_name().ok_or_else(|| {
Error::InvalidArgument(format!("pid path illegal {}", filename.as_ref().display()))
Expand Down Expand Up @@ -89,20 +73,21 @@ pub async fn write_str_to_file(filename: impl AsRef<Path>, s: impl AsRef<str>) -

pub async fn read_spec(bundle: impl AsRef<Path>) -> Result<Spec> {
let path = bundle.as_ref().join(CONFIG_FILE_NAME);
let content = read_file_to_str(&path).await?;
let content = fs::read_to_string(path).await?;
serde_json::from_str::<Spec>(content.as_str()).map_err(other_error!(e, "read spec"))
}

pub async fn read_options(bundle: impl AsRef<Path>) -> Result<Options> {
let path = bundle.as_ref().join(OPTIONS_FILE_NAME);
let opts_str = read_file_to_str(path).await?;
let opts_str = fs::read_to_string(path).await?;
let opts =
serde_json::from_str::<JsonOptions>(&opts_str).map_err(other_error!(e, "read options"))?;
Ok(opts.into())
}

pub async fn read_runtime(bundle: impl AsRef<Path>) -> Result<String> {
read_file_to_str(bundle.as_ref().join(RUNTIME_FILE_NAME)).await
let content = fs::read_to_string(bundle.as_ref().join(RUNTIME_FILE_NAME)).await?;
Ok(content)
}

pub async fn write_options(bundle: impl AsRef<Path>, opt: &Options) -> Result<()> {
Expand Down Expand Up @@ -143,15 +128,18 @@ pub async fn mkdir(path: impl AsRef<Path>, mode: mode_t) -> Result<()> {

#[cfg(test)]
mod tests {
use crate::util::{read_file_to_str, write_str_to_file};
use tokio::fs;

use crate::util::write_str_to_file;

#[tokio::test]
async fn test_read_write_str() {
let tmpdir = tempfile::tempdir().unwrap();
let tmp_file = tmpdir.path().join("test");
let test_str = "this is a test";
write_str_to_file(&tmp_file, test_str).await.unwrap();
let read_str = read_file_to_str(&tmp_file).await.unwrap();

let read_str = fs::read_to_string(&tmp_file).await.unwrap();
assert_eq!(read_str, test_str);
}
}
3 changes: 3 additions & 0 deletions crates/shim/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,9 @@ pub enum Error {
#[error("Failed to send exit event: {0}")]
Send(#[from] std::sync::mpsc::SendError<ExitEvent>),

#[error("Failed to read file: {0}")]
Io(#[from] std::io::Error),
Comment on lines +87 to +88
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will this type of error always be failed to read a file?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@mxpv IoError is defined in L40, I think you can use macro io_error! to map errors.
The error message in std::io::Error is not contains any info of filename, for exampe, if the file is not exist, the error would be No such file or directory without any info to indicate which file or directory is not exist, that is diffcult to debug. Thus, the macro io_error! is used for load the filename or other details, here is an example:

    let finame = "config.json";
    File::open(finame)
        .await
        .map_err(io_error!(e, "failed to open {}: ", finame))?;

and the error would be failed to open config.json error: No such file or directory

Copy link
Member Author

@mxpv mxpv Feb 23, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't really like the requirement to map errors and use macros everywhere, like
map_err(io_error!. I feel like anyhow.Context would be a better fit here. Will investigate this more.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

However, anyhow error is not easy to downcast if you need check the exact type of error

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where exactly we need to downcast?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Where exactly we need to downcast?

When you want to ignore some specific error.


#[error("Other: {0}")]
Other(String),

Expand Down
35 changes: 9 additions & 26 deletions crates/shim/src/synchronous/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,7 @@
limitations under the License.
*/

use std::{
fs::{rename, File, OpenOptions},
io::{Read, Write},
path::Path,
};
use std::{fs, io::Write, path::Path};

use containerd_shim_protos::shim::oci::Options;
#[cfg(unix)]
Expand All @@ -33,40 +29,27 @@ use crate::{
Error,
};

pub fn read_file_to_str<P: AsRef<Path>>(filename: P) -> crate::Result<String> {
let mut file = File::open(&filename).map_err(io_error!(
e,
"open {}",
filename.as_ref().to_string_lossy()
))?;
let mut content: String = String::new();
file.read_to_string(&mut content).map_err(io_error!(
e,
"read {}",
filename.as_ref().to_string_lossy()
))?;
Ok(content)
}

pub fn read_options(bundle: impl AsRef<Path>) -> crate::Result<Options> {
let path = bundle.as_ref().join(OPTIONS_FILE_NAME);
let opts_str = read_file_to_str(path)?;
let opts_str = fs::read_to_string(path)?;
let json_opt: JsonOptions = serde_json::from_str(&opts_str)?;
Ok(json_opt.into())
}

pub fn read_runtime(bundle: impl AsRef<Path>) -> crate::Result<String> {
let path = bundle.as_ref().join(RUNTIME_FILE_NAME);
read_file_to_str(path)
let data = fs::read_to_string(path)?;
Ok(data)
}

pub fn read_address() -> crate::Result<String> {
let path = Path::new("address");
read_file_to_str(path)
let data = fs::read_to_string(path)?;
Ok(data)
}

pub fn read_pid_from_file(pid_path: &Path) -> crate::Result<i32> {
let pid_str = read_file_to_str(pid_path)?;
let pid_str = fs::read_to_string(pid_path)?;
let pid = pid_str.parse::<i32>()?;
Ok(pid)
}
Expand All @@ -82,14 +65,14 @@ pub fn write_str_to_path(filename: &Path, s: &str) -> crate::Result<()> {
let tmp_path = tmp_path
.to_str()
.ok_or_else(|| Error::InvalidArgument(String::from("failed to get path")))?;
let mut f = OpenOptions::new()
let mut f = fs::OpenOptions::new()
.write(true)
.create_new(true)
.open(tmp_path)
.map_err(io_error!(e, "open {}", filename.to_str().unwrap()))?;
f.write_all(s.as_bytes())
.map_err(io_error!(e, "write tmp file"))?;
rename(tmp_path, filename).map_err(io_error!(
fs::rename(tmp_path, filename).map_err(io_error!(
e,
"rename tmp file to {}",
filename.to_str().unwrap()
Expand Down