服务管理CLI 通用shell模板

123 阅读1分钟

一个通用的shell自动化部署shell模板, 用于批量启动/停止服务。

功能如下:

  • 日志开关
  • 子命令框架
  • 服务目录扫描

Convention

  • 所有微服务放在一个目录下,每个目录一个微服务
  • 每个目录有启动/停止脚本 start.sh/stop.sh
  • 微服务目录,以固定前缀命名

Code

#!/bin/bash

# debug switch
DEBUG_MODE=false

# service list
declare -a SERVICE_LIST=()

# service directory
SERVICE_DIR=/var/lib/install_example

# subcommand selection
SUBCOMMAND=$1

# service dir prefix
SERVICE_PREFIX=svc

# print a full line which occupy the whole terminal size
function printline(){
  printf '%*s\n' "${COLUMNS:-$(tput cols)}" '' | tr ' ' -
}

function debug(){
  if [ $DEBUG_MODE = true ]
  then
     echo $@
  fi
}


# service module discovery
for dir in $(ls $SERVICE_DIR)
do
    if [ $(echo $dir | grep $SERVICE_PREFIX |wc -l) -ne 0 ] && [ -d $dir ]
    then
       SERVICE_LIST+=($dir)
    fi
done

# cd path and exec command,then return to current dir
function cmd::cdexec(){
   local current_dir=$(pwd)
   printline
   cd $1
   shift
   $@
   cd $current_dir
}

# by convention, all microservice must have start.sh as an entrypoint
function service::batch::start(){
    for item in ${SERVICE_LIST[*]}
    do
       debug starting service: $item
       cmd::cdexec ${SERVICE_DIR}/$item bash start.sh
    done
}

# by convention, all microservice must have stop.sh as an destroy
function service::batch::stop(){
    for item in ${SERVICE_LIST[*]}
    do
       debug starting service: $item
       cmd::cdexec ${SERVICE_DIR}/$item bash stop.sh
    done
}


# print usage if user wrong parameter
function usage(){

    echo "
service-ctl [batch-start|version] ...

service-ctl is utility tools for services which obey the convention.

subcommand description:


   batch-start: start all services under the installation directory
   batch-stop : stop all services under the installation directory
   version    : print the version and exit

"

}

case $SUBCOMMAND in
    batch-start)
      echo "batch start services..."
      service::batch::start
      ;;
    batch-stop)
      echo "batch stop services..."
      service::batch::stop
      ;;
    version)
      echo v1.0.0;;
    *)
      echo [ERROR] at least one subcommand should be specified.
      usage
      exit 1
      ;;
esac