Linux Shell脚本之远程自动化部署java maven项目

简介:

脚本功能:

检查运行环境(包括运行权限、网络、DNS解析等),自动从git上获取java maven项目工程源码,在机器A上build,build完成后,备份机器B上原有的配置文件(如果存在),将Class、Lib文件和备份的配置文件等上传到机器B,重新启动机器B上的服务以便变更生效。

脚本特点:

1.(与之前的自动部署脚本相比)全新优化了脚本代码,更friendly,结构更紧凑、逻辑更加严谨

2.Public header删除了无用或者不好用的有色彩显示函数,并修正了WORKDIR不是绝对路径可能导致的bug

3.修正了域名解析判断是否正常的一个bug,该bug可能导致遇到无法解析后不断尝试解析

4.全新的通用main函数,自带文件锁和自动接受处理INT、TERM、EXIT进程信号,整个脚本更加的模块化和标准化

5.针对项目方面,增加了对java项目配置文件的备份和还原功能,增加了对docker容器的支持

使用办法:

将脚本上传到Linux任意目录,至少修改三个变量(分别是项目源码的git地址、部署对象的IP、部署对象的目标目录):

1
2
3
project_clone= "ssh://git@xxx/xxx.git"
deploy_target_host_ip= "xxx.xxx.xxx.xxx"
project_top_directory_to_target_host= "/path/to/deploy/project"

如果此项目依赖于其他项目,则修改“project_clone_depends_1”变量,如果要想使部署后自动生效,则,可以将启动脚本放在项目git源码下的bin目录下,默认名称为“startup.sh”

如果此项目部署在目标主机的docker容器内,则修改“docker_container_name”变量,以便重启容器生效。

多个容器启动的依赖关系的处理已经在TODO计划中。

首次执行需要将配置文件准确的写入项目文件中,一次写入后期无须修改,如需修改,直接修改部署对象主机上的配置文件即可。

在任意位置使用下方命令运行即可,脚本一旦运行一次,自动添加可执行权限,无须手动添加。

1
bash  /path/to/this .sh

可以从GitHub上获取最新脚本内容:https://github.com/DingGuodong/AutomaticDeployJavaMavenProject

脚本内容:

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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
#!/bin/bash
 
# Name: doDeploy.sh
#Execute this shell script to deploy Java projects built by Maven automatically on remote hosts.
 
# debug option
#_XTRACE_FUNCTIONS=$(set +o | grep xtrace)
#set -o xtrace
 
# define user friendly messages
header="
Function: Execute this shell script to deploy Java projects built by Maven automatically on remote hosts.
License: Open  source  software
"
 
# define variables
# Where to get source code
project_clone_depends_1= ""
project_clone= "ssh://git@xxx/xxx.git"
deploy_target_host_ip= "xxx.xxx.xxx.xxx"
project_top_directory_to_target_host= "/path/to/deploy/project"
docker_container_name= ""
# Setting how many days do you want save old releases, default is 10 days
save_old_releases_for_days=10
# end define variables
 
# pretreatment
test  -z ${project_clone_depends_1} || project_clone_target_depends_1= "`echo ${project_clone_depends_1} | awk -F '[/.]+' '{ print $(NF-1)}'`"
project_clone_target= "`echo ${project_clone} | awk -F '[/.]+' '{ print $(NF-1)}'`"
project_clone_repository_name=${project_clone_target}
 
# end pretreatment
 
# Public header
# =============================================================================================================================
# resolve links - $0 may be a symbolic link
# learn from apache-tomcat-6.x.xx/bin/catalina.sh
PRG= "$0"
 
while  [ -h  "$PRG"  ];  do
   ls =` ls  -ld  "$PRG" `
   link=` expr  "$ls"  '.*-> \(.*\)$' `
   if  expr  "$link"  '/.*'  /dev/null then
     PRG= "$link"
   else
     PRG=` dirname  "$PRG" `/ "$link"
   fi
done
 
# Get standard environment variables
PRGDIR=` dirname  "$PRG" `
 
# echo color function, smarter, learn from lnmp.org lnmp install.sh
function  echo_r (){
     # Color red: Error, Failed
     [ $ # -ne 1 ] && return 1
     echo  -e  "\033[31m$1\033[0m"
}
function  echo_g (){
     # Color green: Success
     [ $ # -ne 1 ] && return 1
     echo  -e  "\033[32m$1\033[0m"
}
function  echo_y (){
     # Color yellow: Warning
     [ $ # -ne 1 ] && return 1
     echo  -e  "\033[33m$1\033[0m"
}
function  echo_b (){
     # Color blue: Debug, friendly prompt
     [ $ # -ne 1 ] && return 1
     echo  -e  "\033[34m$1\033[0m"
}
# end echo color function, smarter
 
#WORKDIR="`realpath ${WORKDIR}`"
WORKDIR= "`readlink -f ${PRGDIR}`"
 
# end public header
# =============================================================================================================================
 
USER= "`id -un`"
LOGNAME= "$USER"
if  [ $UID - ne  0 ];  then
     echo  "WARNING: Running as a non-root user, \"$LOGNAME\". Functionality may be unavailable. Only root can use some commands or options"
fi
 
command_exists() {
     # which "$@" >/dev/null 2>&1
     command  - v  "$@"  > /dev/null  2>&1
}
 
check_command_can_be_execute(){
     [ $ # -ne 1 ] && return 1
     command_exists $1
}
 
check_network_connectivity(){
     echo_b  "checking network connectivity ... "
     network_address_to_check=8.8.4.4
     stable_network_address_to_check=114.114.114.114
     ping_count=2
     ping  -c ${ping_count} ${network_address_to_check} > /dev/null
     retval=$?
     if  [ ${retval} - ne  0 ] ;  then
         if  ping  -c ${ping_count} ${stable_network_address_to_check} > /dev/null ; then
             echo_g  "Network to $stable_network_address_to_check succeed! "
             echo_y  "Note: network to $network_address_to_check failed once! maybe just some packages loss."
         elif  ! ip route |  grep  default > /dev/null then
             echo_r  "Network is unreachable, gateway is not set."
             exit  1
         elif  ping  -c2 $(ip route |  awk  '/default/ {print $3}' ) > /dev/null then
             echo_r  "Network is unreachable, gateway is unreachable."
             exit  1
         else
             echo_r  "Network is blocked! "
             exit  1
         fi
     elif  [ ${retval} - eq  0 ];  then
         echo_g  "Check network connectivity passed! "
     fi
}
 
check_name_resolve(){
     echo_b  "checking DNS name resolve ... "
     target_name_to_resolve= "github.com"
     stable_target_name_to_resolve= "www.aliyun.com"
     ping_count=1
     if  ping   -c${ping_count} ${target_name_to_resolve} > /dev/null then
         echo_y  "Name lookup failed for $target_name_to_resolve with $ping_count times "
         if  ping   -c${ping_count} ${stable_target_name_to_resolve} > /dev/null then
             echo_g  "Name lookup success for $stable_target_name_to_resolve with $ping_count times "
         fi
         eval_md5sum_of_nameserver_config= "`md5sum /etc/resolv.conf | awk '{ print $1 }'`"
         if  test  ${eval_md5sum_of_nameserver_config} =  "674ea91675cdfac353bffbf49dc593c3" then
             echo_y  "Nameserver config file is validated, but name lookup failed for $target_name_to_resolve with $ping_count times"
             return  0
         fi
         [ -f  /etc/resolv .conf ] &&  cp  /etc/resolv .conf  /etc/resolv .conf_$( date  +%Y%m%d%H%M%S)~
         cat  > /etc/resolv .conf<<eof
nameserver 114.114.114.114
nameserver 8.8.4.4
eof
     check_name_resolve
     else
         echo_g  "Check DNS name resolve passed! "
         return  0
     fi
}
 
function  checkOtherDependencies() {
     echo_b  "Checking other dependencies for deploy procedure... "
 
     echo_b  "\tChecking user customized variables..."
     # Refer:
     # if [ -z ${var+x} ]; then
     #     echo "var is unset"; else echo "var is set to '$var'"
     # fi
     # if [ "$var x" = " x" ]; then
     #     echo "var is empty"; else echo "var is set to '$var'"
     # fi
     # if [ -z $var ]; then
     #     echo "var is empty"; else echo "var is set to '$var'"
     # fi
     if  [[ -z ${project_clone} ]];  then
         echo_r  "Error: project_clone is undefined! "
         exit  1
     elif  [[ -z ${deploy_target_host_ip} ]];  then
         echo_r  "Error: deploy_target_host_ip is undefined! "
         exit  1
     elif  [[ -z ${project_top_directory_to_target_host} ]];  then
         echo_r  "Error: project_top_directory_to_target_host is undefined! "
         exit  1
     fi
     echo_g  "\tChecking user customized variables passed! "
 
     echo_b  "\tChecking disk space available..."
     disk_space_available=` df  ${WORKDIR} |  tail  -n1 |  awk  '{print $(NF-2)}' `
     if  [[ ${disk_space_available} -lt 2097152 ]];  then
         echo_y  "Warning: Disk space of $WORKDIR is smaller than 2GB"
         #exit 1
     else
         echo_g  "\tChecking disk space available passed! "
     fi
 
     echo_g  "All required dependencies check passed! "
 
}
 
function  setDirectoryStructureOnLocalHost() {
     if  [ -f ${WORKDIR}/.capistrano_ds_lock ]; then
         echo_g  "Set directory structure has been done, skipping. "
         return
     fi
     echo_b  "Setting directory structure... "
     # learn from capistrano
     # Refer: http://capistranorb.com/documentation/getting-started/structure/
     # Refer: http://capistranorb.com/documentation/getting-started/structure/#
 
     # ├── current -> /var/www/my_app_name/releases/20150120114500/
     # ├── releases
     # │   ├── 20150080072500
     # │   ├── 20150090083000
     # │   ├── 20150100093500
     # │   ├── 20150110104000
     # │   └── 20150120114500
     # ├── repo
     # │   └── <VCS related data>
     # ├── revisions.log
     # └── shared
     #     └── <linked_files and linked_dirs>
 
     # current is a symlink pointing to the latest release. This symlink is updated at the end of a successful deployment. If the deployment fails in any step the current symlink still points to the old release.
     # releases holds all deployments in a timestamped folder. These folders are the target of the current symlink.
     # repo holds the version control system configured. In case of a git repository the content will be a raw git repository (e.g. objects, refs, etc.).
     # revisions.log is used to log every deploy or rollback. Each entry is timestamped and the executing user (username from local machine) is listed. Depending on your VCS data like branch names or revision numbers are listed as well.
     # shared contains the linked_files and linked_dirs which are symlinked into each release. This data persists across deployments and releases. It should be used for things like database configuration files and static and persistent user storage handed over from one release to the next.
     # The application is completely contained within the path of :deploy_to. If you plan on deploying multiple applications to the same server, simply choose a different :deploy_to path.
 
     # Check directories for deploy
     [ ! -d ${WORKDIR} /release  ] &&  mkdir  ${WORKDIR} /release
     [ ! -d ${WORKDIR} /repository  ] &&  mkdir  ${WORKDIR} /repository
     [ ! -d ${WORKDIR} /share  ] &&  mkdir  ${WORKDIR} /share
     # end directories structure
 
     # Additional directories structure for full deploy operation
     # for backup remote host config file
     [ ! -d ${WORKDIR} /backup  ] &&  mkdir  ${WORKDIR} /backup
 
     # set a directories structure lock
     touch  ${WORKDIR}/.capistrano_ds_lock
     echo_g  "Set directory structure successfully! "
}
 
function  cleanOldReleases(){
     save_days=${save_old_releases_for_days:-10}
     if  [ ! -d ${WORKDIR} /release  ];  then
         echo_b  "Can NOT find release directory, skipping . "
         return
     fi
     need_clean=$( find  ${WORKDIR} /release  -mtime +${save_days} - exec  ls  '{}'  \;)
     if  [ ! -z ${need_clean} ];  then
         echo_g  "Expired releases found and will be removed from project! "
         find  ${WORKDIR} /release  -mtime +${save_days} - exec  rm  -rf  '{}'  \;
         if  [ $? - eq  0 ];  then
             echo_g  "Expired releases have removed from project! "
         else
             echo_r  "Can NOT remove expired releases, please alter to Admin users. "
         fi
     else
         echo_g  "All releases are not expired, skipping. "
     fi
 
}
 
# git_project_clone repository branch
function  git_project_clone(){
     set  -o errexit
     [ $ # -ge 1 ] && project_clone_repository="$1"
     project_clone_repository_name= "`echo ${project_clone_repository} | awk -F '[/.]+' '{ print $(NF-1)}'`"
     project_clone_directory=${WORKDIR} /repository/ ${project_clone_repository_name}
     if  test  -n $2;  then
         branch= "$2"
     else
         branch= "develop"
     fi
     if  test  ! -d ${project_clone_directory};  then
         echo_b  "git clone from $project_clone_repository"
         git clone ${project_clone_repository} ${project_clone_directory} >>${WORKDIR} /git_ $( date  +%Y%m%d)_$$.log 2>&1
             # TODO(Guodong Ding) get branch names or revision numbers from VCS data
 
         cd  ${project_clone_directory}
         git checkout ${branch} >>${WORKDIR} /git_ $( date  +%Y%m%d)_$$.log 2>&1
         cd  ..
         echo_g  "git clone from $project_clone_repository successfully! "
     else
         echo_b  "git pull from $project_clone_repository"
         cd  ${project_clone_directory}
         git pull >>${WORKDIR} /git_ $( date  +%Y%m%d)_$$.log 2>&1
         git checkout ${branch} >>${WORKDIR} /git_ $( date  +%Y%m%d)_$$.log 2>&1
         # TODO(Guodong Ding) get branch names or revision numbers from VCS data
         cd  ..
         echo_g  "git pull from $project_clone_repository successfully! "
     fi
     set  +o errexit
}
 
function  maven_build_project_deprecated(){
     set  -o errexit
     echo_b  "Do mvn build java project... "
     check_command_can_be_execute mvn
     [ $ # -ge 1 ] && project_clone_repository="$1"
     project_clone_repository_name= "`echo ${project_clone_repository} | awk -F '[/.]+' '{ print $(NF-1)}'`"
     project_clone_directory=${WORKDIR} /repository/ ${project_clone_repository_name}
     cd  ${project_clone_directory}
     mvn  install  >>${WORKDIR} /mvn_build_ $( date  +%Y%m%d)_$$.log 2>&1
     mvn clean package >>${WORKDIR} /mvn_build_ $( date  +%Y%m%d)_$$.log 2>&1
     cd  ..
     echo_g  "Do mvn build java project finished with exit code 0! "
     set  +o errexit
}
 
function  maven_build_project(){
     echo_b  "Do mvn build java project for `echo $1 | awk -F '[/.]+' '{ print $(NF-1)}'`... "
     check_command_can_be_execute mvn
     [ $ # -ge 1 ] && project_clone_repository="$1"
     project_clone_repository_name= "`echo ${project_clone_repository} | awk -F '[/.]+' '{ print $(NF-1)}'`"
     project_clone_directory=${WORKDIR} /repository/ ${project_clone_repository_name}
 
     cd  ${project_clone_directory}
     mvn  install  >>${WORKDIR} /mvn_build_ $( date  +%Y%m%d)_$$.log 2>&1
     retval=$?
     if  [ ${retval} - ne  0 ] ;  then
         echo_r  "mvn install failed! More details refer to ${WORKDIR}/mvn_build_$(date +%Y%m%d)_$$.log"
         exit  1
     else
         echo_g  "mvn install for ${project_clone_repository_name} successfully! "
     fi
 
     mvn clean package >>${WORKDIR} /mvn_build_ $( date  +%Y%m%d)_$$.log 2>&1
     retval=$?
     if  [ ${retval} - ne  0 ] ;  then
         echo_r  "mvn clean package for ${project_clone_repository_name} failed! More details refer to ${WORKDIR}/mvn_build_$(date +%Y%m%d)_$$.log"
         exit  1
     else
         echo_g  "mvn clean package for ${project_clone_repository_name} successfully! "
     fi
     cd  ..
     echo_g  "Do mvn build java project finished for ${project_clone_repository_name} with exit code 0! "
}
 
function  check_ssh_can_be_connect(){
     [ $ # -ne 1 ] && return 1
     echo_b  "Check if can ssh to remote host $1 ... "
     check_command_can_be_execute  ssh  ||  return  1
     ssh  -i  /etc/ssh/ssh_host_rsa_key  -p 22 -oStrictHostKeyChecking=no root@$1  "uname -a >/dev/null 2>&1"
     retval=$?
     if  [ ${retval} - ne  0 ] ;  then
         echo_r  "Check ssh to remote host $1 failed! "
         exit  1
     else
         echo_g  "Check ssh to remote host $1 successfully! "
     fi
}
 
# ssh_execute_command_on_remote_host hostname command
function  ssh_execute_command_on_remote_host(){
     [ $ # -ne 2 ] && return 1
     ssh  -i  /etc/ssh/ssh_host_rsa_key  -p 22 -oStrictHostKeyChecking=no root@$1  "$2"  >>${WORKDIR} /ssh_command_ $( date  +%Y%m%d)_$$.log
     retval=$?
     if  [ ${retval} - ne  0 ] ;  then
         echo_r  "ssh execute command on remote host $2 failed! More details refer to ${WORKDIR}/ssh_command_$(date +%Y%m%d)_$$.log"
         return  1
     else
         echo_g  "ssh execute command on remote host $2 successfully! "
         return  0
     fi
}
 
function  restart_docker_container(){
     echo_b  "Restarting docker container..."
     [ $ # -ne 1 ] && return 1
     # TODO(Guodong Ding) if we need restart more related docker container
     local  docker_container_name= ""
     test  -n $1 && docker_container_name= "$1"
     ssh_execute_command_on_remote_host  "docker restart $docker_container_name"
     retval=$?
     if  [ ${retval} - ne  0 ] ;  then
         echo_r  "restart docker container for  $docker_container_name failed! "
         exit  1
     else
         echo_g  "restart docker container for $docker_container_name successfully! "
         return  0
     fi
}
 
# scp_local_files_to_remote_host local_path remote_hostname remote_path
function  scp_local_files_to_remote_host(){
     [ $ # -ne 3 ] && return 1
     [ ! -d $1 -a ! -f $1 ] &&  return  1
     check_ssh_can_be_connect $2
     scp  -i  /etc/ssh/ssh_host_rsa_key  -P 22 -oStrictHostKeyChecking=no -rp $1 root@$2:$3 > /dev/null  2>&1
     retval=$?
     if  [ ${retval} - ne  0 ] ;  then
         echo_r  "scp local files to remote host failed! "
         exit  1
     else
         echo_g  "scp local files to remote host successfully! "
     fi
 
}
 
# scp_remote_files_to_local_host remote_hostname remote_path local_path
function  scp_remote_files_to_local_host(){
     [ $ # -ne 3 ] && return 1
     check_ssh_can_be_connect $1
     scp  -i  /etc/ssh/ssh_host_rsa_key  -P 22 -oStrictHostKeyChecking=no -rp root@$1:$2 $3 > /dev/null  2>&1
     retval=$?
     if  [ ${retval} - ne  0 ] ;  then
         echo_r  "scp remote files to local host failed! "
         exit  1
     else
         echo_g  "scp remote files to local host successfully! "
     fi
}
 
function  backup_remote_host_config_files(){
     echo_b  "backup remote host config files..."
     scp_remote_files_to_local_host ${deploy_target_host_ip} ${project_top_directory_to_target_host}/* ${WORKDIR} /backup
     # get config files
     "$(ls -A ${WORKDIR}/backup)"  ] &&  find  ${WORKDIR} /backup/ . - type  f ! -name . -a ! -name  '*.xml*'  -a ! -name  '*.properties*'  - exec  rm  -f --  '{}'  \;
     # remove empty directory
     find  ${WORKDIR} /backup/ . -empty - type  d -delete
     # TODO(Guodong Ding) improvements here
     echo_g  "backup remote host config files finished."
}
 
function  rollback_remote_host_config_files(){
     echo_b  "rollback remote host config files..."
     #scp_local_files_to_remote_host ${WORKDIR}/backup ${deploy_target_host_ip} ${project_top_directory_to_target_host}
     saved_IFS=$IFS
     IFS= ' '
     cd  ${WORKDIR} /current
     for  file  in  ${WORKDIR} /backup/ *; do
         scp_local_files_to_remote_host ${ file } ${deploy_target_host_ip} ${project_top_directory_to_target_host}
     done
     cd  ${WORKDIR}
     IFS=${saved_IFS}
     # TODO(Guodong Ding) if save remote host config files
     # some ops
 
     # TODO(Guodong Ding) improvements here
     echo_g  "rollback remote host config files finished."
}
 
function  deploy() {
     [ -n  "$header"  ] &&  echo  "$header"
     # check a directories lock, Note: this is redundant
     if  [[ ! -f ${WORKDIR}/.lock ]];  then
         setDirectoryStructureOnLocalHost
     fi
     cleanOldReleases
     # do dependencies checking
     check_network_connectivity
     check_name_resolve
     checkOtherDependencies
 
     check_ssh_can_be_connect ${deploy_target_host_ip}
 
     # do core job
     # TODO(Guodong Ding) if we need a git_project_clone "$project_clone_depends_1" here using auto judgment statement
     test  -z ${project_clone_depends_1} || git_project_clone  "$project_clone_depends_1"
     git_project_clone  "$project_clone"
     test  -z ${project_clone_depends_1} || maven_build_project  "$project_clone_depends_1"
     maven_build_project  "$project_clone"
     cd  ${WORKDIR}
 
     # links_target_directory_to_current
     # Make directory to release directory
     if  test  ! -d ${WORKDIR} /release  -o ! -d ${WORKDIR} /share then
         echo_r  "capistrano directory structure is broken, make sure the file .capistrano_ds_lock is deleted before a new deploy! "
         exit  1
#        test -f ${WORKDIR}/.capistrano_ds_lock && \rm -rf  ${WORKDIR}/.capistrano_ds_lock
     fi
     new_release_just_created= "$WORKDIR/release/$(date +%Y%m%d%H%M%S)"
     [ ! -d ${new_release_just_created} ] &&  mkdir  ${new_release_just_created}
     [ -d ${WORKDIR} /repository/ ${project_clone_repository_name} /target/ ${project_clone_repository_name}/ ] && \
         \ cp  -rf ${WORKDIR} /repository/ ${project_clone_repository_name} /target/ ${project_clone_repository_name}/* ${new_release_just_created}
      # Make source code symbolic link to current
     ( [ -f ${WORKDIR} /current  ] || [ -d ${WORKDIR} /current  ] ) &&  rm  -rf ${WORKDIR} /current
     ln  -s ${new_release_just_created} ${WORKDIR} /current
 
     # backup remote host config files
     backup_remote_host_config_files
 
#    scp_local_files_to_remote_host ${WORKDIR}/current/ ${deploy_target_host_ip} ${project_top_directory_to_target_host}
     saved_IFS=$IFS
     IFS= ' '
     cd  ${WORKDIR} /current
     for  file  in  ${WORKDIR} /current/ *; do
         scp_local_files_to_remote_host ${ file } ${deploy_target_host_ip} ${project_top_directory_to_target_host}
     done
     cd  ${WORKDIR}
     IFS=${saved_IFS}
 
     # rollback remote host config files
     rollback_remote_host_config_files
 
     # Move conf and logs directives from release to share
     [ -d ${WORKDIR} /release/conf  ] &&  mv  ${WORKDIR} /release/conf  ${WORKDIR} /share/conf
     [ -d ${WORKDIR} /release/logs  ] &&  mv  ${WORKDIR} /release/logs  ${WORKDIR} /share/logs
 
     # Make conf and logs symbolic link to current
     [ -d ${WORKDIR} /share/conf  ] &&  ln  -s ${WORKDIR} /share/conf  ${WORKDIR} /current/conf
     [ -d ${WORKDIR} /share/logs  ] &&  ln  -s ${WORKDIR} /share/logs  ${WORKDIR} /current/logs
 
     # Start service or validate status
     if  [[ -e ${WORKDIR} /current/bin/startup .sh ]];  then
         ${WORKDIR} /current/bin/startup .sh start
         RETVAL=$?
     else
         # TODO(Guodong Ding) external health check
         test  -z ${docker_container_name} || restart_docker_container ${docker_container_name}
         RETVAL=$?
     fi
 
     # if started ok, then create a workable program to a file
     if  [[ ${RETVAL} - eq  0 ]];  then
     # Note cat with eof must start at row 0, and with eof end only, such as no blank spaces, etc
     cat  >${WORKDIR} /share/workable_program .log <<eof
${new_release_just_created}
eof
     echo_g  "Deploy successfully! "
     echo_g  "current workable version is $(cat ${WORKDIR}/share/workable_program.log)"
#    ls --color=auto -l ${WORKDIR}/current
#    ls --color=auto -l ${WORKDIR}/current/
     else
         echo_r  "Error: Deploy failed! "
         ${WORKDIR}/` basename  $0` rollback
     fi
}
 
# Rollback to last right configuration
function  rollback() {
     [ -n  "$header"  ] &&  echo  "$header"
     echo_b  "Rollback to last right configuration... "
     # The key is find last files which can work
     WORKABLE_PROGRAM=` cat  ${WORKDIR} /share/workable_program .log`
     if  [[ -z ${WORKABLE_PROGRAM} ]];  then
         echo_r  "Error: Can NOT find workable release version! Please check if it is first deployment! "
         exit  1
     fi
     # Stop service if we have
     if  [[ -e ${WORKDIR} /current/bin/startup .sh ]];  then
         ${WORKDIR} /current/bin/startup .sh stop
     fi
 
     # Remove failed deploy
     rm  -rf ${WORKDIR} /current
 
     # Remake source code symbolic link to current
     ln  -s ${WORKABLE_PROGRAM} ${WORKDIR} /current
 
     # Remake conf and logs symbolic link to current
     [ -d ${WORKDIR} /share/conf  ] &&  ln  -s ${WORKDIR} /share/conf  ${WORKDIR} /current
     [ -d ${WORKDIR} /share/logs  ] &&  ln  -s ${WORKDIR} /share/logs  ${WORKDIR} /current
 
     # Start service or validate status
     if  [[ -e ${WORKDIR} /current/bin/startup .sh ]];  then
         ${WORKDIR} /current/bin/startup .sh start
         RETVAL=$?
     else
         # TODO(Guodong Ding) external health check
         test  -z ${docker_container_name} || restart_docker_container ${docker_container_name}
         RETVAL=$?
     fi
 
     # if started ok, then create a workable program to a file
     if  [[ ${RETVAL} - eq  0 ]];  then
         echo_g  "Rollback successfully! "
         echo_g  "current workable version is $WORKABLE_PROGRAM"
#        ls --color=auto -l ${WORKDIR}/current
     fi
}
 
function  destroy() {
     [ -n  "$header"  ] &&  echo  "$header"
     # echo a Warning message
     echo_y  "Warning: This action will destroy all this project, and this is unrecoverable! "
     answer= "n"
     echo_y  "Do you want to destroy this project? "
     read  -p  "(Default no,if you want please input: y ,if not please press the enter button):"  answer
     case  "$answer"  in
         y|Y|Yes|YES| yes |yES|yEs|YeS|yeS )
         # delete all file expect for this script self
         # find: warning: Unix filenames usually don't contain slashes (though pathnames do).  That means that '-name `./deploy.sh'' will probably evaluate to false all the time on this system.  You might find the '-wholename' test more useful, or perhaps '-samefile'.  Alternatively, if you are using GNU grep, you could use 'find ... -print0 | grep -FzZ `./deploy.sh''.
             # echo $WORKDIR/
             #find -L $WORKDIR -type f ! -name "$(basename $0)" -exec ls --color=auto -al {} \;
             # find -L . -type f ! -name "deploy.sh" -exec ls --color=auto -al {} \;
             # find -L . -type d -exec ls --color=auto -al {} \;
             # find -L ./ -maxdepth 1 ! -name "deploy.sh" ! -wholename "./"
         # ls | grep -v "filename" | xargs rm -rf
         find  -L ${WORKDIR} -maxdepth 1 ! -name  "$(basename $0)"  ! -wholename  "$WORKDIR"   - exec  rm  -rf  '{}'  \;
         if  [ $? - eq  0 ]; then
             test  -f ${WORKDIR}/.capistrano_ds_lock && \ rm  -rf  ${WORKDIR}/.capistrano_ds_lock
             echo_g  "Destroy this project successfully! Now will exit with status 0. "
             exit  0
         else
             echo_r  "Error: something go wrong! Please check or alter to Admin user! "
             exit  1
         fi
         ;;
         n|N|No|NO|no|nO)
         echo_g  "destroy action is cancel"
         exit  0
         ;;
         *)
         echo_r  "Are you kidding me? You are a bad kid! "
         exit  1
         ;;
     esac
 
}
 
 
function  main(){
     lock_filename= "lock_$$_$RANDOM"
#    lock_filename_full_path="/var/lock/subsys/$lock_filename"
     lock_filename_full_path= "/var/lock/$lock_filename"
     if  set  -o noclobber;  echo  "$$"  "$lock_filename_full_path" ) 2>  /dev/null ; then
         trap  'rm -f "$lock_filename_full_path"; exit $?'  INT TERM EXIT
         # Just a test for call itself, comment it
          if  [[ $ # -ne 1 ]]; then
#            $0 deploy
             [ ! -x ${WORKDIR}/` basename  $0` ] &&  chmod  +x ${WORKDIR}/` basename  $0`
             ${WORKDIR}/` basename  $0` deploy
             exit  0
          fi
         case  $1  in
             deploy)
                 deploy
                 ;;
             rollback)
                 rollback
                 ;;
             destroy)
                 destroy
                 ;;
             help|*)
                 echo  "Usage: $0 {deploy|rollback|destroy} with $0 itself"
                 exit  1
                 ;;
         esac
 
         rm  -f  "$lock_filename_full_path"
         trap  - INT TERM EXIT
     else
         echo  "Failed to acquire lock: $lock_filename_full_path"
         echo  "held by $(cat ${lock_filename_full_path})"
fi
 
}
 
main $@
 
# debug option
#${_XTRACE_FUNCTIONS}

运行效果:

可以尝试使用Chrome浏览器打开该页面,右键单击,选择“在新标签页中打开图片”查看清晰大图。

推荐Windows用户使用PyCharm(5.0.x)结合Bash Support插件编辑bash shell script文件。

注:由于该脚本的大幅度更新,因此最新的运行效果图可以自行运行观察。

2016-05-09_172111

2016-05-09_172046

--end--





本文转自 urey_pp 51CTO博客,原文链接:http://blog.51cto.com/dgd2010/1771555,如需转载请自行联系原作者


相关文章
|
1月前
|
运维 Java Shell
Linux非常详细的shell运维脚本一键启动停止状态SpringBoot打成可运行jar包
Linux非常详细的shell运维脚本一键启动停止状态SpringBoot打成可运行jar包
36 0
|
1月前
|
Shell Linux
Linux使用Shell脚本SCP批量传输脚本
Linux使用Shell脚本SCP批量传输脚本
34 0
|
5天前
|
Java Apache Maven
Maven 项目文档
在 `C:/MVN` 目录下创建 Maven 项目 `consumerBanking` 使用命令:`mvn archetype:generate -DgroupId=com.companyname.bank -DartifactId=consumerBanking -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false`。为解决 `mvn site` 命令执行时的 `NoClassDefFoundError`
|
14天前
|
Java Maven
idea中maven项目pom文件Could not acquire lock(s)
idea中maven项目pom文件Could not acquire lock(s)
|
1月前
|
Java Maven Spring
【操作宝典】IntelliJ IDEA新建maven项目详细教程
【操作宝典】IntelliJ IDEA新建maven项目详细教程
38 1
|
4天前
|
XML Java 测试技术
Maven 构建 & 项目测试
本文介绍了如何使用Maven构建和测试Java应用。在`C:/MVN/consumerBanking`项目中,`pom.xml`配置了JUnit作为测试框架。执行`mvn clean package`命令进行构建,Maven会清理目标目录,编译源码和测试代码,运行测试用例,最后生成`consumerBanking-1.0-SNAPSHOT.jar`。测试报告位于`surefire-reports`文件夹。添加新Java类`Util.java`到项目后,更新`App.java`以使用`Util`类。
|
7天前
|
Java 项目管理 Maven
【揭秘】Maven聚合与继承:如何轻松实现项目依赖管理?
Maven的聚合和继承是Java开发中重要的概念。聚合允许将多个项目组合成一个构建单元,简化多模块项目的构建过程,提高构建效率。继承则让子项目重用父项目的配置和属性,避免了重复定义,增强了项目的一致性和可维护性。通过聚合和继承,Maven为多模块项目的构建和管理提供了高效且灵活的支持,减少了配置冗余,提升了开发效率。
【揭秘】Maven聚合与继承:如何轻松实现项目依赖管理?
|
7天前
|
Java Maven
Maven 项目文档
学习Maven项目文档创作,借助Doxia引擎将内容转化为通用模型。支持Apt(纯文本)、Xdoc(Maven 1.x格式)、FML(FAQ)和XHTML。
|
7天前
|
Shell Linux 编译器
C语言,Linux,静态库编写方法,makefile与shell脚本的关系。
总结:C语言在Linux上编写静态库时,通常会使用Makefile来管理编译和链接过程,以及Shell脚本来自动化构建任务。Makefile包含了编译规则和链接信息,而Shell脚本可以调用Makefile以及其他构建工具来构建项目。这种组合可以大大简化编译和构建过程,使代码更易于维护和分发。
25 5
|
8天前
|
Java Apache Maven
Maven 项目文档Maven 项目文档
Maven使用Doxia引擎将多种格式(如Apt、Xdoc、FML和XHTML)转换为通用文档模型。在创建Maven项目文档时,例如在C:/MVN下创建consumerBanking项目,需运行指定的mvn archetype:generate命令。接着,更新pom.xml,确保包含maven-site-plugin和maven-project-info-reports-plugin的最新版本(至少3.3和2.7),以避免NoClassDefFoundError。执行`mvn site`命令生成文档。