gitlab多线程备份脚本

本文介绍了一种使用Perl脚本实现GitLab服务器备份的方法,并通过多线程将大型备份文件分割后传输到远程服务器的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

将公司的gitlab服务器进行备份,并且将备份rsync到异地机房,因为备份文件太大,所以这里做了切割成多个文件,进行多线程传输。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
#!/usr/bin/env perl    
################    
#filename: gitback.pl    
#version : 1.0    
#author : zzq    
#date : 20160705    
#function: The transmission of gitlab backup files to the remote host    
#########################    
use strict;    
use threads;    
use Thread::Queue;    
use File::Rsync;    
use threads::shared;    
use File::Find;    
use File::Basename;    
use POSIX qw(strftime);    
use Log::Log4perl qw(:easy);    
use Mail::Sender;    
my ($logger,$Msg,$Subject,$filename,$srcFile,$fileName,$filePath,$fileSize,$backFilename);    
my $fileCount;    
my $filemsg;    
my $message;    
######### remote host rsync config ##################    
my $remotehost 'rsync@10.xx.xx.xx::gitbackup';    
############# back file dir##############    
my $backFiledir '/data/gitbackups/';    
######## max threads count##############    
my $thread_max = 10;    
########## current time #############    
my $currentTime = strftime("%Y%m%d%H%M"localtime(time));    
$Msg "$currentTime\n";    
########## log file ##############    
my $logFile "gitback.log";    
my $splitFileQueue = Thread::Queue->new();    
my $remotefileQueue = Thread::Queue->new();    
############## define smtp ######################    
#Sender    
my $send_user='monitor@.cc.cn';    
#passwd for Sender    
#my $send_user_pw='123';    
#smtp address    
my $smtp_server='10.168.xx.xx';    
#define mail subject    
$Subject "gitback-$currentTime";    
#address    
my @address=qw(xxx.cn);    
#################################################    
################### define log conf #########################    
my $log_logger = get_logger();    
$log_logger->level($INFO);    
my $file_appender = Log::Log4perl::Appender->new(    
                    "Log::Dispatch::File",    
                    filename => "$logFile",    
                    mode     => "append",    
                    );    
$log_logger->add_appender($file_appender);    
my $layout =  Log::Log4perl::Layout::PatternLayout->new(    
"%d %p > %F{1} %M -- %m%n"    
);    
$file_appender->layout($layout);    
###################################################    
main();    
sub main {    
    Usage() unless scalar(@ARGV) == 0);    
    $log_logger->info("Begin:$currentTime");    
    $srcFile = backup();    
    print "srcFile is $srcFile\n";    
    ($fileName,$filePath) = fileparse($srcFileif (-f $srcFile);    
    $fileSize=(stat $srcFile)[7];    
    srcFileMd5($srcFile);    
    splitFile($srcFile);    
    find(\&findSplitFile,$filePath);    
    $fileCount $splitFileQueue->pending();    
    $Msg "$Msg"."FileCount: $fileCount\n"."$filemsg";    
    splitFileMd5Thread();    
    rsyncThread();      
   for my $addr (@address){    
        sendMail($addr);    
    }    
    $currentTime=strftime("%Y%m%d%H%M"localtime(time));    
    $log_logger->info("End:$currentTime");    
}    
###################Access to the backup name for gitlab ################    
sub backup {    
my $result=`gitlab-rake gitlab:backup:create`;    
my $flag=`echo $?`;    
if ($flag == 0){    
    $log_logger->info("gitlab-backup-create : success ");             
    my @result=split(/\n/,$result);    
    for my $cc (@result){    
        if ($cc =~ /(?<filename>\d+_gitlab_backup.tar)/){    
            $backFilename=$+{'filename'};    
            $log_logger->info("gitlab-backup-filename : $backFilename");               
            }    
        }    
    }else{    
    $log_logger->info("gitlab-backup-create : fail ");                
    }    
    return "$backFiledir$backFilename";    
}    
############# Search the file after segmentation ################    
sub findSplitFile {    
        if $_ =~ /$fileName\.\d{3}$/) {    
            $log_logger->info("splitFileQueue enqueue : $_");    
            $filemsg "$filemsg"."$_\n";    
            $splitFileQueue->enqueue($_);    
            $log_logger->info("remotefileQueue enqueue : $_");                
            $remotefileQueue->enqueue($_);    
#           $log_logger->info("print to logfile : $_");    
    }    
}    
############## Search the MD5 file after segmentation ############    
sub splitFileMd5Thread {    
    while($splitFileQueue->pending()) {    
        my $Queue $splitFileQueue->dequeue();    
        $log_logger->info("splitfileQueueMD5 dequeue : $Queue ");    
        threads->create(\&splitFileMd5,$Queue);    
        }    
foreach my $thread (threads->list(threads::all)){    
if ($thread->is_joinable()){    
$thread->join();    
}    
}    
foreach my $thread ( threads->list(threads::all) ) {    
$thread->join();    
}    
    }    
################## Search for the source file md5 #################    
sub srcFileMd5 {    
    my $file=shift;    
    my $md5_command=`md5sum $file`;    
    my $flag=`echo $?`;    
    if ($flag == 0) {    
        my ($file_md5,$filename) = split(/\s+/,$md5_command);    
        my $log "srcfile:$file filesize:$fileSize file_md5sum:$file_md5";    
        $Msg "$Msg"."srcfile:$file filesize:$fileSize file_md5sum:$file_md5\n";    
        $log_logger->info($log);    
    }else {    
        my $file_md5 "system command maybe exec fail, command result code is $md5_command";    
        my $log "srcfile:$file filesize:$fileSize file_md5sum:$file_md5";    
        $Msg "$Msg"."srcfile:$file filesize:$fileSize file_md5sum:$file_md5\n";    
        $log_logger->warn($log);                     
    }    
}    
####### split File MD5 ###############    
sub splitFileMd5 {    
    my $file=shift;    
    my $md5_command=`md5sum $filePath$file`;    
    my $flag=`echo $?`;    
    if ($flag == 0) {    
        my ($file_md5,$filename) = split(/\s+/,$md5_command);    
        my $log "file:$file  file_md5sum:$file_md5";    
    $log_logger->info($log);    
    }    
}    
################# Will be cut by the source file ################    
sub splitFile {    
        my $srcFile shift;    
        my $split_command =`split -b 50M $srcFile -d -a 3 $srcFile.`;    
        $split_command = `echo $? `;    
        if ($split_command == 0 ){    
                my $splitFileCode 'success';    
                $log_logger->info(" srcFile:$srcFile  desc:$splitFileCode splitFileResult:$split_command");    
        }else{    
                my $splitFileCode 'fail';    
                $log_logger->warn(" srcFile:$srcFile  desc:$splitFileCode splitFileResult:$split_command");    
            }    
}    
sub rsyncThread {    
    while $remotefileQueue->pending() ){        
        if (scalar threads->list() < $thread_max) {          
            my $readQueue $remotefileQueue->dequeue();    
            $log_logger->info("remotefileQueue dequeue : $readQueue ");    
            threads->create(\&rsync,$readQueue);    
    }    
    foreach my $thread (threads->list(threads::all)){             
                if ($thread->is_joinable()){    
                    $thread->join();             
            }       
        }    
    }    
    foreach my $thread ( threads->list(threads::all) ) {    
        $thread->join();    
    }        
}    
sub rsync {    
        my $file shift;    
        my $obj = File::Rsync->new(    
        {    
        archive    => 1,    
        compress => 1,    
        checksum => 1,    
        recursive => 1,    
        owner => 1,    
        devices => 1,    
        group => 1,    
        perms => 1,    
        times => 1,    
   verbose => 1,    
        progress => 1,    
        stats => 1,    
        links => 1,    
       'hard-links' => 1,    
          'ignore-times' => 1,    
          'password-file' => './rsync.pass',    
        }    
);    
$obj->exec( { src => "$filePath$file", dest => $remotehost } );    
#or warn ($log_logger->warn("rsync: $file to $remotehost fail!" ));    
my $rval $obj->realstatus;    
        if ($rval == 0 ) {    
        $log_logger->info("rsync: $file to $remotehost Success!\n");    
        }else{    
        my $rsyncError sprintf ("%s"$obj->err);    
        $message "$message"."Transfer Failed:\nfile:$file         reason:$rsyncError";    
        $log_logger->info("rsync: $file to $remotehost fail reason:$rsyncError");    
        }    
}    
sub sendMail {    
    my $CONTACTEMAIL shift;    
   my $sender = new Mail::Sender{    
    ctype => 'text/plain; charset=utf-8',    
    encoding => 'utf-8',    
   } ;    
    die "Error in mailing : $Mail::Sender::Error\n" unless ref $sender;    
    if ($sender->MailMsg({    
        smtp => $smtp_server,    
        from => $send_user,    
        to => $CONTACTEMAIL,    
        subject => $Subject,    
        msg => $Msg,    
#       file => "$file",    
#       auth => 'LOGIN',     
#       authid => $send_user,    
#       authpwd => $send_user_pw,    
        charset=>'utf-8'    
        }) < 0) {    
            die $log_logger->error("senermail fail -- $Mail::Sender::Error\n");      
        }    
        $sender->Close();    
    }    
sub Usage {    
print <<"END";    
    perl gitback.pl     
END    
exit 2;    
}



本文转自 西索oO 51CTO博客,原文链接:http://blog.51cto.com/lansgg/1864156
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值