设为首页 收藏本站
查看: 1057|回复: 0

[经验分享] 通过Git WebHooks+脚本实现自动更新发布代码之shell脚本

[复制链接]
累计签到:1 天
连续签到:1 天
发表于 2016-1-15 08:30:55 | 显示全部楼层 |阅读模式
前文讲述了《通过Git WebHooks+脚本实现自动更新发布代码》,里面提供了一种自动更新发布代码的脚本编写思路。本文的脚本与前文中的思路不太不同。本脚本以capistrano中的一些思想和理念为依据,用简单好理解的shell脚本实现capistrano原本实现的自动化部署部分。
脚本的一些特点和功能:
  • 解决脚本的符号链接问题,准确获取脚本工作目录(从tomcat脚本中学到);
  • 颜色显示,不同级别的信息用不同的颜色显示(共两种方案,前一种从一位不知名的国外工程师处得到,后一种从lnmp1.2脚本中得到);
  • 生成capistrano目录结构;
  • 清除过期目录和文件;
  • 检查部署要求是否满足,如磁盘空间的需求等,其他的要求检查有待于添加;
  • 部署失败后归滚;
  • 项目废弃后删除项目;
  • 脚本里面尽可能的考虑容错(异常判断)和部分细节;

脚本存在的已知的问题:
(1)脚本中有几个TODO,有待于改善;
(2)repository目录暂时没有用到;
(3)获取git的版本号问题;
(4)部署后生成的日志有待于优化;
(5)脚本基本使用英文(Chinglish)作为注释,部分注释可能不全;
(6)可能存在的其他问题;
为了后期的改进和部分需求变更,也为了便于获取该脚本,此脚本可以从github上获取,欢迎和接受提交任何bug、issue以及任何improvement。
github地址是:
https://github.com/DingGuodong/B ... r/example-deploy.sh
脚本内容如下:
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
#!/bin/bash

# Public header
# =============================================================================================================================
# resolve links - $0 may be a symbolic link
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
function cecho {
    # Usage:
    # cecho -red sometext     #Error, Failed
    # cecho -green sometext   # Success
    # cecho -yellow sometext  # Warnning
    # cecho -blue sometext    # Debug
    # cecho -white sometext   # info
    # cecho -n                # new line
    # end

    while [ "$1" ]; do
        case "$1" in
            -normal)        color="\033[00m" ;;
# -black)         color="\033[30;01m" ;;
-red)           color="\033[31;01m" ;;
-green)         color="\033[32;01m" ;;
-yellow)        color="\033[33;01m" ;;
-blue)          color="\033[34;01m" ;;
# -magenta)       color="\033[35;01m" ;;
# -cyan)          color="\033[36;01m" ;;
-white)         color="\033[37;01m" ;;
-n)             one_line=1;   shift ; continue ;;
*)              echo -n "$1"; shift ; continue ;;
esac

shift
echo -en "$color"
echo -en "$1"
echo -en "\033[00m"
shift

done
if [ ! $one_line ]; then
        echo
fi
}
# end echo color function

# echo color function, smarter
function echo_r () {
    #Error, Failed
    [ $# -ne 1 ] && return 0
    echo -e "\033[31m$1\033[0m"
}
function echo_g () {
    # Success
    [ $# -ne 1 ] && return 0
    echo -e "\033[32m$1\033[0m"
}
function echo_y () {
    # Warnning
    [ $# -ne 1 ] && return 0
    echo -e "\033[33m$1\033[0m"
}
function echo_b () {\
    # Debug
    [ $# -ne 1 ] && return 0
    echo -e "\033[34m$1\033[0m"
}
# end echo color function, smarter

WORKDIR=$PRGDIR
# end public header
# =============================================================================================================================

# Where to get source code
SOURCEURL=https://github.com/DingGuodong/GitOSCAutoDeploy.git

# Setting how many days do you want save old releases, default is 10 days
save_old_releases_for_days=10

function setDirectoryStructure() {
    if [ -f $WORKDIR/.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 branchnames 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/current ] && mkdir $WORKDIR/current
    [ ! -d $WORKDIR/release ] && mkdir $WORKDIR/release
    [ ! -d $WORKDIR/repository ] && mkdir $WORKDIR/repository
    [ ! -d $WORKDIR/share ] && mkdir $WORKDIR/share
    # end directories structure
    touch $WORKDIR/.lock
    echo_g "Set directory structure successfully! "
}

function checkDependencies() {
    echo_b "Checking dependencies for deploy procedure. "
    # 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 $SOURCEURL ]]; then
        echo_r "Error: SOURCEURL is undefined! "
        exit 1
    fi
    DISKSPACE=`df $WORKDIR | tail -n1 | awk '{print $(NF -2)}'`
    if [[ $DISKSPACE -lt 2097152 ]]; then
        echo_y "Warnning: Disk space of $WORKDIR is smaller than 2GB"
        #exit 1
    fi

    echo_g "All required dependencies check pass! "

}

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


}
function deploy() {
    # check a directories lock, Note: this is redundant
    if [[ ! -f $WORKDIR/.lock ]]; then
        setDirectoryStructure
    fi
    cleanOldReleases
    checkDependencies
    # Make directory to release directory
    SOURCEDIR="$WORKDIR/release/$(date +%Y%m%d%H%M%S)"
    [ ! -d $SOURCEDIR ] && mkdir $SOURCEDIR

    # Get files from source code repository
    git clone $SOURCEURL $SOURCEDIR
    # svn co http://$SOURCEURL $WORKDIR/repository

    # TODO
    # get branchnames or revision numbers from VCS data


    # Remove .git or .svn
    [ -d $SOURCEDIR/.git ] && rm -rf $SOURCEDIR/.git
    [ -d $SOURCEDIR/.svn ] && rm -rf $SOURCEDIR/.svn

    # ifdef Complie
    # endif

    # Make source code symbolic link to current
    ( [ -f $WORKDIR/current ] || [ -d $WORKDIR/current ] ) && rm -rf $WORKDIR/current
    ln -s $SOURCEDIR $WORKDIR/current

    # Move conf and logs directies 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
        # external health check
        RETVAL=0
    fi
    RETVAL=$?

    # 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
$SOURCEDIR
eof
    echo_g "Deploy successfully! "
    echo_g "current workable version is $(cat $WORKDIR/share/workable_program.log)"
    ls --color=auto -l $WORKDIR/current
    else
        echo_r "Error: Deploy failed! "
        $0 rollback
    fi
}

# Rollback to last right configuraton
function rollback() {
    # 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 [[ -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
        # external health check
        RETVAL=0
    fi
    RETVAL=$?

    # 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() {
    # echo a warnning message
    echo_y "Warnning: 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 "fielname" |xargs rm -rf
        find -L $WORKDIR -maxdepth 1 ! -name "$(basename $0)" ! -wholename "$WORKDIR"  -exec rm -rf {} \;
        if [ $? -eq 0 ];then
            echo_g "Destory 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

}

# Just a test for call itself, comment it
# if [[ $# -lt 1 ]]; then
#  $0 help
#  exit
# fi
case $1 in
    deploy)
        deploy
        ;;
    rollback)
        rollback
        ;;
    destroy)
        destroy
        ;;
    help|*)
        echo "Usage: $0 {deploy|rollback|destroy} with $0 itself"
        exit 1
        ;;
esac

# This is not essential with 'case .. esac' handled no args excutions
# replace "exit 0" with ":"
#exit 0
:



tag:自动化部署脚本,Shell部署脚本,capistrano的shell脚本实现,脚本实现自动更新和回滚,自动化部署shell脚本实例
--end--


运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-164566-1-1.html 上篇帖子: 通过Git WebHooks+脚本实现自动更新发布代码 下篇帖子: Installing on Linux GIT
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表