首页 > 其他分享 >从 aws 读取一个文件

从 aws 读取一个文件

时间:2023-04-21 16:15:10浏览次数:55  
标签:文件 use 读取 aws let expect file mountpoint target

use clap::{Arg, ArgAction, Command};
use fuser::{BackgroundSession, MountOption, Session};
use mountpoint_s3::fuse::S3FuseFilesystem;
use mountpoint_s3::S3FilesystemConfig;
use mountpoint_s3_client::{S3ClientConfig, S3CrtClient};
use mountpoint_s3_crt::common::rust_log_adapter::RustLogAdapter;
use std::{
    fs::File,
    fs::OpenOptions,
    io::{self, BufRead, BufReader},
    time::Instant,
};
use tempfile::tempdir;
use tracing_subscriber::fmt::Subscriber;
use tracing_subscriber::util::SubscriberInitExt;
use tracing_subscriber::EnvFilter;

#[cfg(target_os = "linux")]
use std::os::unix::fs::OpenOptionsExt;

fn init_tracing_subscriber() {
    RustLogAdapter::try_init().expect("unable to install CRT log adapter");

    let subscriber = Subscriber::builder()
        .with_env_filter(EnvFilter::from_default_env())
        .with_writer(std::io::stderr)
        .finish();

    subscriber.try_init().expect("unable to install global subscriber");
}

fn main() -> io::Result<()> {
    init_tracing_subscriber();

    const KB: usize = 1 << 10;
    const MB: usize = 1 << 20;
    const DEFAULT_BUF_CAP: usize = 128;

    let matches = Command::new("benchmark")
        .about("Read a single file from a path and ignore its contents")
        .arg(Arg::new("bucket").required(true))
        .arg(
            Arg::new("file_path")
                .required(true)
                .help("relative path to the mountpoint"),
        )
        .arg(
            Arg::new("buffer-capacity-kb")
                .long("buffer-capacity-kb")
                .help("Buffer reader capacity in KB"),
        )
        .arg(
            Arg::new("direct")
                .long("direct")
                .help("Open file with O_DIRECT option")
                .action(ArgAction::SetTrue),
        )
        .arg(
            Arg::new("throughput-target-gbps")
                .long("throughput-target-gbps")
                .help("Desired throughput in Gbps"),
        )
        .arg(
            Arg::new("iterations")
                .long("iterations")
                .help("Number of times to download"),
        )
        .arg(Arg::new("region").long("region").default_value("us-east-1"))
        .get_matches();

    let bucket_name = matches.get_one::<String>("bucket").unwrap();
    let file_path = matches.get_one::<String>("file_path").unwrap();
    let buffer_capacity = matches
        .get_one::<String>("buffer-capacity-kb")
        .map(|s| s.parse::<usize>().expect("buffer capacity must be a number"));
    let direct = matches.get_flag("direct");
    let throughput_target_gbps = matches
        .get_one::<String>("throughput-target-gbps")
        .map(|s| s.parse::<f64>().expect("throughput target must be an f64"));
    let iterations = matches
        .get_one::<String>("iterations")
        .map(|s| s.parse::<usize>().expect("iterations must be a number"));
    let region = matches.get_one::<String>("region").unwrap();

    let session = mount_file_system(bucket_name, region, throughput_target_gbps);
    let mountpoint = &session.mountpoint;

    #[cfg(not(target_os = "linux"))]
    if direct {
        panic!("O_DIRECT only supported on Linux");
    }

    for i in 0..iterations.unwrap_or(1) {
        let file_path = mountpoint.join(file_path);
        let file = if direct {
            let mut open = OpenOptions::new();
            open.read(true);
            #[cfg(target_os = "linux")]
            open.custom_flags(libc::O_DIRECT);
            open.open(file_path)?
        } else {
            File::open(file_path)?
        };
        let mut received_size: u64 = 0;
        let mut op_counter: u64 = 0;

        let start = Instant::now();
        let mut reader = BufReader::with_capacity(buffer_capacity.unwrap_or(DEFAULT_BUF_CAP) * KB, file);
        loop {
            let length = {
                let buffer = reader.fill_buf()?;
                op_counter += 1;
                received_size += buffer.len() as u64;
                buffer.len()
            };
            if length == 0 {
                break;
            }
            reader.consume(length);
        }

        let elapsed = start.elapsed();

        println!(
            "{}: requested {} ops in {:.2}s: {:.2} IOPS",
            i,
            op_counter,
            elapsed.as_secs_f64(),
            (op_counter as f64) / elapsed.as_secs_f64()
        );

        println!(
            "{}: received {} bytes in {:.2}s: {:.2} MiB/s",
            i,
            received_size,
            elapsed.as_secs_f64(),
            (received_size as f64) / elapsed.as_secs_f64() / MB as f64
        );
    }

    drop(session);
    Ok(())
}

fn mount_file_system(bucket_name: &str, region: &str, throughput_target_gbps: Option<f64>) -> BackgroundSession {
    let temp_dir = tempdir().expect("Should be able to create temp directory");
    let mountpoint = temp_dir.path();

    let config = S3ClientConfig {
        throughput_target_gbps,
        ..Default::default()
    };
    let client = S3CrtClient::new(region, config).expect("Failed to create S3 client");
    let runtime = client.event_loop_group();

    let mut options = vec![MountOption::RO, MountOption::FSName("mountpoint-s3".to_string())];
    options.push(MountOption::AutoUnmount);

    let filesystem_config = S3FilesystemConfig::default();

    println!(
        "Mounting bucket {} to path {}",
        bucket_name,
        mountpoint.to_str().unwrap()
    );
    let session = Session::new(
        S3FuseFilesystem::new(client, runtime, bucket_name, &Default::default(), filesystem_config),
        mountpoint,
        &options,
    )
    .expect("Should have created FUSE session successfully");

    BackgroundSession::new(session).expect("Should have started FUSE session successfully")
}


来源:

https://github.com/awslabs/mountpoint-s3/blob/main/mountpoint-s3/examples/fs_benchmark.rs

标签:文件,use,读取,aws,let,expect,file,mountpoint,target
From: https://www.cnblogs.com/itfanr/p/17340761.html

相关文章

  • nginx配置文件生成完成批量配置
    1.创建模板worker_processes1;events{worker_connections1024;}stream{ server{listenlisten-port;proxy_passip:port; proxy_connect_timeout2s;}#foreach($portin[9000..9009])server{listen$port;p......
  • 流文件
    mpegts.js是在HTML5上直接播放MPEG2-TS流的播放器,针对低延迟直播优化,可用于DVB/ISDB数字电视流或监控摄像头等的低延迟回放。mpegts.js基于flv.js改造而来。 npminstall--savempegts.jsimportmpegtsfrom'mpegts.js';constrefDom=document.getElementById......
  • linux 命令使用11--lozone(文件)
    1.IOzone简介  IOzone是一个开源文件系统基准工具,用来测试文件系统的读写性能,也可以进行测试磁盘读写性能。Iozone能够运行于许多平台。这份文档涵盖Iozone所执行的许多不同类型的操作和它的所有命令行参数。2. 安装  ubuntu直接安装:    apt-getinstalliozone33.......
  • node实现文件上传和文件下载
    node实现文件上传和下载安装multer和fs模块npminstallmulterfs--save//multer文件上传,fs文件处理上传文件并存放相应路径下multer({dest:"upload"}).single('file')//dest后是文件存放的地址,single中的为filename//.single(fieldname)-单个文件上传......
  • ssh-keygen 生成.ssh文件
    ssh-keygen-trsa-C"[email protected]":生成最新OPENSSH格式的密钥对。openssh格式 ssh-keygen-mPEM-trsa-b4096-C"[email protected]"生成老版本的rsa格式的密钥对。rsa格式 参数说明-m:参数指定密钥的格式,PEM(也就是RSA格式)是之前使用的旧格式-b:指定密钥长度;-e:......
  • C#一个界面类下面有多个CS文件
    一.当我们用VS创建一个Form窗体时,会生成一个窗体类和设计类 二.当界面复杂,并且每个界面有多少关联的类时,我们需要按一定规则放,可以放在该窗体下面打开.csproj文件,增加一个修改FormSub1和Form2Sub2的Compile节点(如果没有,直接增加)修改后,保存,重新用VS打开项目(VS2010和VS201......
  • spring boot项目上传文件
    严重:Servlet.service()forservlet[dispatcherServlet]incontextwithpath[]threwexception[Requestprocessingfailed;nestedexceptionisorg.springframework.web.multipart.MaxUploadSizeExceededException:Maximumuploadsizeexceeded;nestedexception......
  • tomcat提示静态文件缓存超限,造成日志爆满的问题
    日志片段:21-Apr-202311:20:47.215警告[http-nio-80-exec-5308]org.apache.catalina.webresources.Cache.getResourceUnabletoaddtheresourceat[/FileUploads/www/site/2022/11/30/ZZVRQAHD08ZX4GOW47.jpg]tothecacheforwebapplication[]becausetherewasin......
  • Ubuntu 搭建一个局域网文件存储服务器
    在Ubuntu上搭建一个局域网文件存储服务器可以使用Samba服务,Samba是一个能够与Windows兼容的文件和打印机共享服务。下面是搭建过程:安装Samba服务打开终端,运行以下命令安装Samba:sqlCopycodesudoapt-getupdatesudoapt-getinstallsamba创建共享文件夹......
  • Aras学习笔记 (53) - 根据ID快速找到文件Vault路径
    Step1:首先在对象类File中根据名称找到ID;Step2:右键文件-->Share-->CopyID;Step3:在Console中输入下命令:top.aras.IomInnovator.getFileUrl("[文件ID]",top.aras.Enums.UrlType.SecurityToken)结果如下: ......