2011-01-24

[Shell] 透過版本編號與遠端的 package 同步

有一個的任務是要將一個用 tar 封裝的目錄從 server 端同步到 client 上,然後有機個考量點:
  • 必須確保 client 永遠都讀得到資料
  • 最小的資料中斷
  • 最小的硬碟存取
  • 必要的錯誤處理


建立 server 端的 package
#!/bin/bash
# package_build.sh

PATH=/bin:/sbin:/usr/bin:/usr/sbin
export PATH

PROJECT_NAME=metadata
SOURCE_PATH=/var/projects
PORTING_PATH=/var/www

PACKAGE_NAME=$PROJECT_NAME.$(/bin/date +%s)
OLD_PACKAGE=$(find $PORTING_PATH -name "$PROJECT_NAME.*.tgz")

# Create Package
cd $SOURCE_PATH/$PROJECT_NAME
tar -zcf $PORTING_PATH/$PACKAGE_NAME.tgz ./*

# Update version number to release
echo $PACKAGE_NAME > $PORTING_PATH/$PROJECT_NAME.latest

# remove old version
#rm -f $OLD_PACKAGE

echo -e "<< $PACKAGE_NAME package complete >>"
exit 0


client 端的同步處理
#!/bin/bash
# package_sync.sh

PATH=/bin:/sbin:/usr/bin:/usr/sbin
export PATH

REMOTE_URL=http://remote_site/
TARGET_PATH=/var/www
PROJECT_NAME=metadata
PROJECT_PATH=$TARGET_PATH/$PROJECT_NAME


# get now version
NOW_VERSION=$PROJECT_NAME.0000000000
if [ -h "$PROJECT_PATH" ] && [ -d "$PROJECT_PATH" ]; then
    NOW_VERSION=$(readlink $PROJECT_PATH)
fi
echo -e 'NOW_VERSION' $NOW_VERSION


# get remote version 
REMOTE_VERSION=$(curl -f $REMOTE_URL/$PROJECT_NAME.latest |tr -d '\r')
if [ "j$?" != "j0" ]; then  exit 1; fi
echo -e 'REMOTE_VERSION' $REMOTE_VERSION


# deff version, not deff goto exit.
if [ ! "$NOW_VERSION" \< "$REMOTE_VERSION" ]; then  exit 0; fi



echo -e "Update package"

# create now version folder
mkdir -p $TARGET_PATH/$REMOTE_VERSION
if [ "$?" != "0" ]; then  exit 1; fi

# Download Package
cd $TARGET_PATH/$REMOTE_VERSION
curl -o $PROJECT_NAME.tgz $REMOTE_URL/$REMOTE_VERSION.tgz
if [ "$?" != "0" ]; then  exit 1; fi

# Decompression Package
tar -zxf $PROJECT_NAME.tgz
rm -f $PROJECT_NAME.tgz

# Update version link
cd $TARGET_PATH
ln -sfn $REMOTE_VERSION $PROJECT_NAME

# remove old version
rm -rf $NOW_VERSION

exit 0;

0 回應: