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

[#6320] feat (gvfs-fuse): Support mount and umount command for gvfs-fuse command line tools #6321

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions clients/filesystem-fuse/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,9 @@ name = "gvfs_fuse"
[dependencies]
async-trait = "0.1"
bytes = "1.6.0"
clap = { version = "4.5.24", features = ["derive"] }
config = "0.13"
daemonize = "0.5.0"
dashmap = "6.1.0"
fuse3 = { version = "0.8.1", "features" = ["tokio-runtime", "unprivileged"] }
futures-util = "0.3.30"
Expand Down
57 changes: 57 additions & 0 deletions clients/filesystem-fuse/src/command_args.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
use clap::{Parser, Subcommand};

#[derive(Parser, Debug)]
#[command(
name = "gvfs-fuse",
version = "1.0",
about = "A FUSE-based file system client"
)]
pub(crate) struct Arguments {
#[command(subcommand)]
pub(crate) command: Commands,
}

#[derive(Subcommand, Debug)]
pub(crate) enum Commands {
Mount {
#[arg(help = "Mount point for the filesystem")]
mount_point: String,

#[arg(help = "Location of GVFS fileset URI")]
diqiu50 marked this conversation as resolved.
Show resolved Hide resolved
location: String,

#[arg(short, long)]
config: Option<String>,

#[arg(short, long, help = "Debug level", default_value_t = 0)]
debug: u8,
Copy link
Contributor

Choose a reason for hiding this comment

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

Looks like this is an overdesign?
Are we really using this argument?

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Yes, we will need to use this argument in PR #5905.


#[arg(short, long, default_value_t = false, help = "Run in foreground")]
foreground: bool,
},
Umount {
#[arg(help = "Mount point to umount")]
mount_point: String,

#[arg(short, long, help = "Force umount")]
force: bool,
},
}
12 changes: 6 additions & 6 deletions clients/filesystem-fuse/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -205,19 +205,19 @@ impl AppConfig {
.unwrap_or_else(|e| panic!("Failed to set default for {}: {}", entity.name, e))
}

pub fn from_file(config_file_path: Option<&str>) -> GvfsResult<AppConfig> {
pub fn from_file(config_file_path: Option<String>) -> GvfsResult<AppConfig> {
let builder = Self::crete_default_config_builder();

let config_path = {
if config_file_path.is_some() {
let path = config_file_path.unwrap();
//check config file exists
if fs::metadata(path).is_err() {
if fs::metadata(&path).is_err() {
return Err(
ConfigNotFound.to_error("The configuration file not found".to_string())
);
}
info!("Use configuration file: {}", path);
info!("Use configuration file: {}", &path);
path
} else {
//use default config
Expand All @@ -232,11 +232,11 @@ impl AppConfig {
CONF_FUSE_CONFIG_PATH.default
);
}
CONF_FUSE_CONFIG_PATH.default
CONF_FUSE_CONFIG_PATH.default.to_string()
}
};
let config = builder
.add_source(config::File::with_name(config_path).required(true))
.add_source(config::File::with_name(&config_path).required(true))
.build();
if let Err(e) = config {
let msg = format!("Failed to build configuration: {}", e);
Expand Down Expand Up @@ -302,7 +302,7 @@ mod test {

#[test]
fn test_config_from_file() {
let config = AppConfig::from_file(Some("tests/conf/config_test.toml")).unwrap();
let config = AppConfig::from_file(Some("tests/conf/config_test.toml".to_string())).unwrap();
assert_eq!(config.fuse.file_mask, 0o644);
assert_eq!(config.fuse.dir_mask, 0o755);
assert_eq!(config.filesystem.block_size, 8192);
Expand Down
3 changes: 2 additions & 1 deletion clients/filesystem-fuse/src/fuse_server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ use crate::utils::GvfsResult;
use fuse3::raw::{Filesystem, Session};
use fuse3::MountOptions;
use log::{error, info};
use std::path::Path;
use std::process::exit;
use std::sync::Arc;
use tokio::select;
Expand All @@ -46,7 +47,7 @@ impl FuseServer {
/// Starts the FUSE filesystem and blocks until it is stopped.
pub async fn start(&self, fuse_fs: impl Filesystem + Sync + 'static) -> GvfsResult<()> {
//check if the mount point exists
if !std::path::Path::new(&self.mount_point).exists() {
if !Path::new(&self.mount_point).exists() {
error!("Mount point {} does not exist", self.mount_point);
exit(libc::ENOENT);
}
Expand Down
183 changes: 152 additions & 31 deletions clients/filesystem-fuse/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,49 +16,170 @@
* specific language governing permissions and limitations
* under the License.
*/
use fuse3::Errno;
mod command_args;

use crate::command_args::Commands;
use clap::Parser;
use daemonize::Daemonize;
use gvfs_fuse::config::AppConfig;
use gvfs_fuse::{gvfs_mount, gvfs_unmount};
use log::{error, info};
use std::fs::OpenOptions;
use std::path::Path;
use std::process::{exit, Command};
use std::{env, io};
use tokio::runtime::Runtime;
use tokio::signal;
use tokio::signal::unix::{signal, SignalKind};

#[tokio::main]
async fn main() -> fuse3::Result<()> {
tracing_subscriber::fmt().init();
fn make_daemon() {
let log_file_name = "/tmp/gvfs-fuse.log";
let log_file = OpenOptions::new()
.create(true)
.append(true)
.open(log_file_name)
.unwrap();
let log_err_file = OpenOptions::new().write(true).open(log_file_name).unwrap();

// todo need inmprove the args parsing
let args: Vec<String> = std::env::args().collect();
let (mount_point, mount_from, config_path) = match args.len() {
4 => (args[1].clone(), args[2].clone(), args[3].clone()),
_ => {
error!("Usage: {} <mount_point> <mount_from> <config>", args[0]);
return Err(Errno::from(libc::EINVAL));
}
};
let cwd = env::current_dir();
if let Err(e) = cwd {
error!("Error getting current directory: {}", e);
return;
}
let cwd = cwd.unwrap();

let daemonize = Daemonize::new()
.pid_file("/tmp/gvfs-fuse.pid")
.chown_pid_file(true)
.working_directory(&cwd)
.stdout(log_file)
.stderr(log_err_file);

//todo(read config file from args)
let config = AppConfig::from_file(Some(&config_path));
if let Err(e) = &config {
error!("Failed to load config: {:?}", e);
return Err(Errno::from(libc::EINVAL));
match daemonize.start() {
Ok(_) => info!("Gvfs-fuse Daemon started successfully"),
Err(e) => {
error!("Gvfs-fuse Daemon failed to start: {:?}", e);
exit(-1)
}
}
let config = config.unwrap();
let handle = tokio::spawn(async move {
let result = gvfs_mount(&mount_point, &mount_from, &config).await;
if let Err(e) = result {
error!("Failed to mount gvfs: {:?}", e);
return Err(Errno::from(libc::EINVAL));
}

fn mount_fuse(config: AppConfig, mount_point: String, target: String) -> io::Result<()> {
let rt = Runtime::new().unwrap();
rt.block_on(async {
let handle = tokio::spawn(async move {
let result = gvfs_mount(&mount_point, &target, &config).await;
if let Err(e) = result {
error!("Failed to mount gvfs: {:?}", e);
return Err(io::Error::from(io::ErrorKind::InvalidInput));
}
Ok(())
});

let mut term_signal = signal(SignalKind::terminate())?;
tokio::select! {
_ = handle => {}
_ = signal::ctrl_c() => {
info!("Received Ctrl+C, unmounting gvfs...")
}
_ = term_signal.recv()=> {
info!("Received SIGTERM, unmounting gvfs...")
}
}

let _ = gvfs_unmount().await;
Ok(())
});
})
}

#[cfg(target_os = "macos")]
fn do_umount(mp: &str, force: bool) -> std::io::Result<()> {
let cmd_result = if force {
Command::new("umount").arg("-f").arg(mp).output()
} else {
Command::new("umount").arg(mp).output()
};

tokio::select! {
_ = handle => {}
_ = signal::ctrl_c() => {
info!("Received Ctrl+C, unmounting gvfs...");
handle_command_result(cmd_result)
}

#[cfg(target_os = "linux")]
fn do_umount(mp: &str, force: bool) -> std::io::Result<()> {
let cmd_result =
if Path::new("/bin/fusermount").exists() || Path::new("/usr/bin/fusermount").exists() {
if force {
Command::new("fusermount").arg("-uz").arg(mp).output()
} else {
Command::new("fusermount").arg("-u").arg(mp).output()
}
} else if force {
Command::new("umount").arg("-l").arg(mp).output()
} else {
Command::new("umount").arg(mp).output()
};

handle_command_result(cmd_result)
}

fn handle_command_result(cmd_result: io::Result<std::process::Output>) -> io::Result<()> {
match cmd_result {
Ok(output) => {
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
Err(io::Error::new(io::ErrorKind::Other, stderr.to_string()))
} else {
Ok(())
}
}
Err(e) => Err(e),
}
}

let _ = gvfs_unmount().await;
Ok(())
#[cfg(not(any(target_os = "macos", target_os = "linux")))]
fn do_umount(_mp: &str, _force: bool) -> std::io::Result<()> {
Err(std::io::Error::new(
std::io::ErrorKind::Other,
format!("OS {} is not supported", env::consts::OS),
))
}

fn main() -> Result<(), i32> {
tracing_subscriber::fmt().init();
let args = command_args::Arguments::parse();
match args.command {
Commands::Mount {
mount_point,
location,
config,
debug: _,
foreground,
} => {
let app_config = AppConfig::from_file(config);
if let Err(e) = &app_config {
error!("Failed to load config: {:?}", e);
return Err(-1);
};
let app_config = app_config.unwrap();
let result = if foreground {
mount_fuse(app_config, mount_point, location)
} else {
make_daemon();
mount_fuse(app_config, mount_point, location)
};

if let Err(e) = result {
error!("Failed to mount gvfs: {:?}", e.to_string());
return Err(-1);
};
Ok(())
}
Commands::Umount { mount_point, force } => {
let result = do_umount(&mount_point, force);
if let Err(e) = result {
error!("Failed to unmount gvfs: {:?}", e.to_string());
return Err(-1);
};
Ok(())
}
}
}
2 changes: 1 addition & 1 deletion clients/filesystem-fuse/src/s3_filesystem.rs
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ pub(crate) mod tests {
config_file_name = source_file_name;
}

AppConfig::from_file(Some(config_file_name)).unwrap()
AppConfig::from_file(Some(config_file_name.to_string())).unwrap()
}

#[tokio::test]
Expand Down
6 changes: 3 additions & 3 deletions clients/filesystem-fuse/tests/bin/gvfs_fuse.sh
Original file line number Diff line number Diff line change
Expand Up @@ -52,14 +52,14 @@ start_gvfs_fuse() {
make build

echo "Starting gvfs-fuse-daemon"
$CLIENT_FUSE_DIR/target/debug/gvfs-fuse $MOUNT_DIR $MOUNT_FROM_LOCATION $TEST_CONFIG_FILE > \
$CLIENT_FUSE_DIR/target/debug/gvfs-fuse mount $MOUNT_DIR $MOUNT_FROM_LOCATION -c $TEST_CONFIG_FILE -f > \
$CLIENT_FUSE_DIR/target/debug/fuse.log 2>&1 &
check_gvfs_fuse_ready
cd -
}

stop_gvfs_fuse() {
# Stop the gvfs-fuse process if it's running
pkill -INT gvfs-fuse || true
# Unmount the gvfs-fuse
$CLIENT_FUSE_DIR/target/debug/gvfs-fuse umount $MOUNT_DIR
echo "Stopping gvfs-fuse-daemon"
}
2 changes: 1 addition & 1 deletion clients/filesystem-fuse/tests/fuse_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ impl FuseTest {
info!("Start gvfs fuse server");
let mount_point = self.mount_point.clone();

let config = AppConfig::from_file(Some("tests/conf/gvfs_fuse_memory.toml"))
let config = AppConfig::from_file(Some("tests/conf/gvfs_fuse_memory.toml".to_string()))
.expect("Failed to load config");
self.runtime.spawn(async move {
let result = gvfs_mount(&mount_point, "", &config).await;
Expand Down
Loading