java調用Rsync併發遷移數據並執行校驗

java調用Rsync併發遷移數據並執行校驗

java代碼如下

RsyncFile.java

import lombok.NoArgsConstructor;
import lombok.SneakyThrows;

import java.io.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.*;

/**
 * @ClassName RsyncFile
 * @Descriptiom TODO rsync多線程同步遷移數據
 * @Author KING
 * @Date 2019/11/25 09:17
 * @Version 1.2.2
 * rsync -vzrtopg --progress --delete   //鏡像同步
 **/
@NoArgsConstructor
public class RsyncFile implements  Runnable{
    private static final int availProcessors = Runtime.getRuntime().availableProcessors();
    //構造以cpu核心數爲核心池,cpu線程數爲最大池,超時時間爲1s,線程隊列爲大小爲無界的安全阻塞線程隊列,拒絕策略爲DiscardOldestPolicy()的線程池。(同步數據當然不能丟下拒絕任務)
    private ExecutorService ThreadPool = new ThreadPoolExecutor(availProcessors >> 1,
            availProcessors,
            1L,
            TimeUnit.SECONDS,
            new LinkedBlockingQueue<>(),Executors.defaultThreadFactory(),
            new ThreadPoolExecutor.DiscardOldestPolicy());

    //保存掃描得到的文件列表
    private static ArrayList<String> fileNameList = new ArrayList<String>();
    private String shellname;
    private String filename;
    private String userip;
    private CountDownLatch countDownLatch;
    private static int deep = 0;

    public RsyncFile(String ShellName, String filename, String UserIP, CountDownLatch countDownLatch) {
        this.shellname = ShellName;
        this.filename = filename;
        this.userip = UserIP;
        this.countDownLatch = countDownLatch;
    }

    public static void main(String[] args) {
        try {
            new RsyncFile().Do(args[0],args[1],Integer.parseInt(args[2]));
        }catch (ArrayIndexOutOfBoundsException e){
            System.out.println(e);
            System.out.println("Error , args send fault");
            System.out.println("please send localAddress remote username @ remote IP or hostname and catalogue");
            System.out.println("like this [  /home/test/  root@node1:/test/   1 ]");
        }catch(NumberFormatException e1){
            System.out.println(e1);
            System.out.println("please input Right Directory depth, this number must be int");
            System.out.println("like this [  /home/test/  root@node1:/test/   1 ]");
        }
    }

    @SneakyThrows
    private void Do(String content,String UserIP,int setdeep){
        System.out.println("開始執行");
        System.out.println("開始時間:" + new Date());
        Long a = System.nanoTime();
        File file = new File(content);
        System.out.println("開始掃描本地指定目錄");
        GetAllFile(file,setdeep);//按深度掃描非空文件夾和文件
        System.out.println("掃描本地目錄完成");

        //給腳本賦予權限
        String [] cmd={"/bin/sh","-c","chmod 755 ./do*"};
        Runtime.getRuntime().exec(cmd);
        //創建遠端目錄操作
        System.out.println("開始創建遠端目錄結構");
        //一次計數鎖用於保證目錄創建完成
        CountDownLatch doDirLock = new CountDownLatch(1);
        ThreadPool.execute(new RsyncFile("./doDirc.sh",content,UserIP,doDirLock));
        doDirLock.await();
        System.out.println("創建遠端目錄結構完成");

        //開始同步工作
        System.out.println("開始執行同步工作");
        System.out.println("同步的文件夾或文件總數: " + fileNameList.size());
        System.out.println("正在同步。。。。。");
        //fileNameList.size()次計數鎖用於保證數據同步完成(保證計時準確)
        CountDownLatch rsyncLock = new CountDownLatch(fileNameList.size());
        System.out.println(fileNameList.size());
        for (String fileName:fileNameList) {
            //除去文件名中與UserIP重複的文件路徑
            String RemoteDir = UserIP.concat(fileName.replace(content, ""));
            System.out.println("要同步的本地目錄或文件: " + fileName);
            System.out.println("要同步的遠端目錄或文件: " + RemoteDir);
            ThreadPool.execute(new RsyncFile("./doRync.sh",fileName, RemoteDir,rsyncLock));
        }
        rsyncLock.await();
        System.out.println("執行同步工作完成");

        //開始文件校驗工作
        System.out.println("執行文件校驗及重傳");
        //一次計數鎖用於保證校驗完成
        CountDownLatch chechSumLock = new CountDownLatch(1);
        ThreadPool.execute(new RsyncFile("./doChecksum.sh",content,UserIP,chechSumLock));
        chechSumLock.await();
        System.out.println("文件校驗及重傳完成");
        ThreadPool.shutdown();

        Long b = System.nanoTime();
        Long aLong = (b - a)/1000000L;
        System.out.println("處理時間" + aLong + "ms");
        System.out.println("結束時間:" + new Date());

    }

    /**
     * 執行rsync腳本的線程方法,使用PrintWriter來與linux Terminal交互
     */
    @Override
    public void run() {
        try {
            String command=shellname.concat(" ").concat(filename).concat(" ").concat(userip);
            File wd = new File("/bin");
            Process process = null;
            process = Runtime.getRuntime().exec("/bin/bash", null, wd);
            if (process != null) {
                InputStream is = process.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(is));
                PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(process.getOutputStream())),
                        true);
                //切換到當前class文件所在目錄
                out.println("cd " + System.getProperty("user.dir"));
                out.println(command);
                out.println("exit");
                StringBuilder sb = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    sb.append(line + System.lineSeparator());
                }
                process.waitFor();
                reader.close();
                out.close();
                process.destroy();
                System.out.println("result:" + sb.toString());
            }else {
                System.out.println("找不到系統bash工具,請檢查系統是否異常,併爲系統創建/bin/sh的bash工具軟連接");
            }
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }finally {
            //倒記數鎖釋放一次
            countDownLatch.countDown();
        }
    }


    /**遍歷指定的目錄並能指定深度
     * @param file 指定要遍歷的目錄
     * @param setDeep 設定遍歷深度
     */
    @SneakyThrows
    private static void  GetAllFile(File file, int setDeep) {
        if(file != null){
            if(file.isDirectory() && deep<setDeep){
                deep++;
                File f[] = file.listFiles();
                if(f != null) {
                    int length = f.length;
                    for(int i = 0; i < length; i++)
                        GetAllFile(f[i],setDeep);
                    deep--;
                }
            } else {
                if(file.isDirectory()){
                    //如果爲目錄末尾添加 / 保證rsync正常處理
                    fileNameList.add(file.getAbsolutePath().concat("/"));
                }else {
                    fileNameList.add(file.getAbsolutePath());
                }
            }
        }
    }

}

doDir.sh

rsync -av --include='*/' --exclude='*' $1 $2 |tee -a /tmp/rsync.log 2>&1
echo "創建目錄結構操作"

doRsync.sh

rsync -avzi --stats --progress $1 $2 |tee -a /tmp/rsync.log 2>&1

doChecksum.sh

rsync -acvzi --stats --progress $1 $2 |tee -a /tmp/checksum.log 2>&1

附錄

rsync輸出日誌說明如下

YXcstpoguax  path/to/file
|||||||||||
||||||||||╰- x: The extended attribute information changed
|||||||||╰-- a: The ACL information changed
||||||||╰--- u: The u slot is reserved for future use
|||||||╰---- g: Group is different
||||||╰----- o: Owner is different
|||||╰------ p: Permission are different
||||╰------- t: Modification time is different
|||╰-------- s: Size is different
||╰--------- c: Different checksum (for regular files), or
||              changed value (for symlinks, devices, and special files)
|╰---------- the file type:
|            f: for a file,
|            d: for a directory,
|            L: for a symlink,
|            D: for a device,
|            S: for a special file (e.g. named sockets and fifos)
╰----------- the type of update being done::
             <: file is being transferred to the remote host (sent)
             >: file is being transferred to the local host (received)
             c: local change/creation for the item, such as:
                - the creation of a directory
                - the changing of a symlink,
                - etc.
             h: the item is a hard link to another item (requires 
                --hard-links).
             .: the item is not being updated (though it might have
                attributes that are being modified)
             *: means that the rest of the itemized-output area contains
                a message (e.g. "deleting")
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章