Árvore de páginas

Versões comparadas

Chave

  • Esta linha foi adicionada.
  • Esta linha foi removida.
  • A formatação mudou.
Comentário: Atualização dos scripts de inicialização dos serviços.

Índice

Para a inicialização dos serviços por meio de scripts, será é necessário criá-los no diretório /etc/init.d/

Copie o conteúdo pertinente de cada script, e caso não tenha utilizado . Se os caminhos sugeridos neste manual não foram utilizados, altere-os nos scripts para não se deparar com ocorrerem erros do tipo “Programa Programa não instalado”instalado.

Informaçõestip

Os scripts já estão parametrizados para iniciar, parar e reiniciar (start, stop e restart) os serviços necessários para o Protheus.

Nota
titleAtenção - Parametrização do script para distro

Estes scripts estão parametrizados para RedHat, Oracle Linux e SUSE. 

Você pode utilizar Utilize o comando vim para abrir um novo arquivo no diretório:[root@tpsrv01 ~]# vim /etc/init.d/totvsappbalance

Bloco de código
languagebash
[root@tpsrv01 ~]# vim /etc/init.d/

...

totvsappbroker
[root@tpsrv01 ~]# vim /etc/init.d/

...

totvsappsec01
[root@tpsrv01 ~]# vim /etc/init.d/

...

totvsappsec02
[root@tpsrv01 ~]# vim /etc/init.d/totvsdbaccess

...


[root@tpsrv01 ~]# vim /etc/init.d/totvslicensesrv

Para cada execução do comando vim, será aberto o editor de texto do Linux

Aviso

♦ A partir da release 12.1.2210, o LockServer não é mais utilizado.


Conteúdo dos scripts

script_

#ckconfig: 2345 84 10

#description: Starts and stops DBAccess

#########################################

# CONFIGURACAO DO SERVICO #

#########################################

#Inserir o nome do executavel 

prog="dbaccess64"

#Inserir o caminho do diretorio do executavel

pathbin="/totvs/microsiga/dbaccess"

progbin="${pathbin}/${prog}"

pidfile="/var/run/${prog}.pid"

lockfile="/var/lock/subsys/${prog}"

#################################################################

#Configuracao de ULIMIT #

#################################################################

#open files - (-n)

openFiles=65536

#stack size - (kbytes, -s)

stackSize=1024

#core file size - (blocks, -c)

coreFileSize=unlimited

#file size - (blocks, -f)

fileSize=unlimited

#cpu time - (seconds, -t)

cpuTime=unlimited

#virtual memory - (-v)

virtualMemory=unlimited

#################################

# FIM DA CONFIGURACAO #

#################################

#################################

#################################

#Source function library.

functions="/etc/init.d/functions"

if [ -e ${functions} ] ; then

. /etc/init.d/functions

else

echo "$functions not installed"

exit 5

fi

RETVAL=0

#Verifica se o executavel tem permissao correta e se esta acessivel

test -x $progbin || { echo "$progbin not installed";

        if [ "$1" = "stop" ]; then exit 0;

        else exit 5; fi; }

#Prepara as ulimit para o servico do DBAccess

ulimit -n ${openFiles}

ulimit -s ${stackSize}

ulimit -c ${coreFileSize}

ulimit -f ${fileSize}

ulimit -t ${cpuTime}

ulimit -v ${virtualMemory}

#Acessa o diretorio configurado na variavel PATHBIN

cd $pathbin

#Variaveis de Output

red=`tput setaf 1`

green=`tput setaf 2`

reset=`tput sgr0`

#Function Start

start() {

if [ -z `pidof -x $progbin` ] ; then

   echo "Starting $prog... "

   daemon $progbin >/dev/null &

   #exec ./${prog} >/dev/null &

   RETVAL=$?

   if [ ${RETVAL} -eq 0 ]; then

      touch ${lockfile}

      touch ${pidfile}

      pidof -x ${progbin} > ${pidfile}

      sleep 1

      echo "PID : " `cat ${pidfile}`

      echo "${prog} running :   ${green}[ OK ]${reset}"

   else

      echo "Failed to start ${prog} :         ${red}[ Failure ]${reset}"

   fi 

   echo

else

   echo "$prog is ${green}Started${reset} pid `pidof -x $progbin`"

fi

}

#Function Stop

stop() {

if [ ! -z `pidof -x ${progbin}` ] ; then

   killproc $progbin

   #pkill -f ${prog}

   echo

   rm -f $lockfile

   rm -f $pidfile

   echo -n "Stopping ${prog}."

   while [ ! -z `pidof -x ${progbin}` ]

   do

        echo -n "."

        sleep 1

   done

   echo

   echo "${prog} is Stopped     ${red}[ Stopped ]${reset}"

else

   echo "${prog} is not running ${red}[ Stopped ]${reset}"

fi

}

status() {

pid=$(pidof -x ${progbin})

progport=$(lsof -Pp ${pid} | grep '(LISTEN)' | awk '{ print $9}' | cut -d: -f2 | xargs)

list=$(ps -eo pid,start_time,cputime,pcpu,pmem,stat,size,nlwp,comm | grep ${pid})

start_time=$(echo $list | awk '{ print $2 }')

cputime=$(echo $list | awk '{ print $3 }')

pcpu=$(echo $list | awk '{ print $4 }')

pmem=$(echo $list | awk '{ print $5 }')

stat=$(echo $list | awk '{ print $6 }')

size=$(echo $list | awk '{ print $7 }')

nlwp=$(echo $list | awk '{ print $8 }')

comm=$(echo $list | awk '{ print $9 }')

size=$(echo "$(bc <<< "scale=2;$size/1024") MB")

echo "PROCESS           : ${comm}"

echo "PORT              : ${progport}"

echo "PID               : ${pid}"

echo "STARTED           : ${start_time}"

echo "TIME              : ${cputime}"

echo "%CPU              : ${pcpu}"

echo "%MEM              : ${pmem}"

echo "MEMORY            : ${size}"

echo "STATUS            : ${stat} ${green}[ running ]${reset}"

echo "THREADS           : ${nlwp}"

}

#MAIN

case "$1" in

start)

    start

    ;;

stop)

    stop

    ;;

status)

    if [ ! -z `pidof -x $progbin` ] ; then

       echo "Status process     : ${green}[ OK ]${reset}"

       status

    else

        echo "Status process    : ${red}[ Failure ]${reset}"

        echo "Program $prog is not running!"

    fi

    ;;

restart)

    stop

    sleep 10

    start

    sleep 10

    status

    ;;

condrestart)

   if test "x`pidof -x $progbin`" != x; then

        stop

        start

    fi

    ;;

*)

    echo $"Usage: $0 {start|stop|restart|condrestart|status}"

    exit 1

esac

exit 0

Deck of Cardscode
id
idlanguagescripts_services
Card
bash
title
totvsdbaccess
labeltotvsdbaccess
Card
idscript_totvsapplocksrv
labeltotvsapplocksrv

#ckconfig: 2345 84 10

#description: Starts and stops program

#################################

# CONFIGURACAO DO SERVICO #

#################################

#Inserir o nome do executavel 

prog="appsrvlinux"

#Inserir o caminho do diretorio do executavel

pathbin="/totvs/microsiga/protheus12/bin/applocksrv"

#################################

# Configuracao de ULIMIT #

#################################

#open files - (-n)

openFiles=65536

#stack size - (kbytes, -s)

stackSize=1024

#core file size - (blocks, -c)

coreFileSize=unlimited

#file size - (blocks, -f)

fileSize=unlimited

#cpu time - (seconds, -t)

cpuTime=unlimited

#virtual memory - (-v)

virtualMemory=unlimited

#########################

# FIM DA CONFIGURACAO #

#########################

#Caminho absoluto do executavel

progbin="${pathbin}/${prog}"

#Caminho absoluto do arquivo .pid

pidfile="/var/run/${prog}.pid"

#Caminho absoluto do arquilo de lock

lockfile="/var/lock/subsys/${prog}"

#Caminho absoluto do arquivo de log (script)

logfile="${pathbin}/log_${prog}.log"

#Source function library.

functions="/etc/init.d/functions"

if [ -e ${functions} ] ; then

. /etc/init.d/functions

else

echo "$functions not installed"

exit 5

fi

RETVAL=0

#Verifica se o executavel tem permissao correta e se esta acessivel

test -x $progbin || { echo "$progbin not installed";

        if [ "$1" = "stop" ]; then exit 0;

        else exit 5; fi; }

#Prepara as ulimit para o servico

ulimit -n ${openFiles}

ulimit -s ${stackSize}

ulimit -c ${coreFileSize}

ulimit -f ${fileSize}

ulimit -t ${cpuTime}

ulimit -v ${virtualMemory}

#Variaveis de Output

red=`tput setaf 1`

green=`tput setaf 2`

reset=`tput sgr0`

logmsg="$(date) | $(whoami) | $0 | $1 |"

#Acessa o diretorio configurado na variavel PATHBIN

cd ${pathbin}

#Function Start

start() {

if [ -z `pidof -x ${prog}` ] ; then

   echo "Starting ${prog}... "

   exec ./${prog} >/dev/null &

   RETVAL=$?

   if [ ${RETVAL} -eq 0 ]; then

      touch ${lockfile}

      touch ${pidfile}

      pidof -x ${prog} > ${pidfile}

      sleep 1

      echo "PID : `cat ${pidfile}`"

      echo "${prog} running :   ${green}[ OK ]${reset}"

      echo "${logmsg} ${prog} Started" >> ${logfile}

   else

      echo "Failed to start ${prog} :         ${red}[ Failure ]${reset}"

      echo "${logmsg} Failed to start ${prog}" >> ${logfile}

   fi 

   echo

else

   echo "${prog} is ${green}Started${reset} pid `pidof -x ${prog}`"

   echo "${logmsg} ${prog} already started" >> ${logfile}

fi

}

#Function Stop

stop() {

if [ ! -z `pidof -x ${prog}` ] ; then

   killproc ${prog} >/dev/null &

   #pkill -f ${prog}

   echo

   rm -f $lockfile

   rm -f $pidfile

   echo -n "Stopping ${prog}."

   while [ ! -z `pidof -x ${prog}` ] 

   do

        echo -n "."

        sleep 1

   done

   echo

   echo "${prog} is Stopped     ${red}[ Stopped ]${reset}"

   echo "${logmsg} ${prog} stopped" >> ${logfile}

else

   echo "${prog} is not running ${red}[ Stopped ]${reset}"

   echo "${logmsg} ${prog} already stopped" >> ${logfile}

fi

}

#Function Status

status() {

pid=$(pidof -x ${prog})

progport=$(lsof -Pp ${pid} | grep '(LISTEN)' | awk '{ print $9}' | cut -d: -f2 | xargs)

list=$(ps -eo pid,start_time,cputime,pcpu,pmem,stat,size,nlwp,comm | grep ${pid})

start_time=$(echo $list | awk '{ print $2 }')

cputime=$(echo $list | awk '{ print $3 }')

pcpu=$(echo $list | awk '{ print $4 }')

pmem=$(echo $list | awk '{ print $5 }')

stat=$(echo $list | awk '{ print $6 }')

size=$(echo $list | awk '{ print $7 }')

nlwp=$(echo $list | awk '{ print $8 }')

comm=$(echo $list | awk '{ print $9 }')

size=$(echo "$(bc <<< "scale=2;$size/1024") MB")

echo "PROCESS           : ${comm}"

echo "PORT              : ${progport}"

echo "PID               : ${pid}"

echo "STARTED           : ${start_time}"

echo "TIME              : ${cputime}"

echo "%CPU              : ${pcpu}"

echo "%MEM              : ${pmem}"

echo "MEMORY            : ${size}"

echo "STATUS            : ${green}[ running ]${reset}"

echo "THREADS           : ${nlwp}"

}

#MAIN

case "$1" in

start)

    start

    ;;

stop)

    stop

    ;;

status)

    if [ ! -z `pidof -x ${prog}` ] ; then

       echo "Status process     : ${green}[ OK ]${reset}"

       status

    else

        echo "Status process    : ${red}[ Failure ]${reset}"

        echo "Program $prog is not running!"

    fi

    ;;

restart)

    stop

    sleep 2

    start

    sleep 2

    status

    ;;

log)

    cat ${logfile}

    echo "More details at ${logfile}"

    ;;

*)

    echo $"Usage: $0 {start|stop|restart|status|log}"

    exit 1

esac

exit 0

Card
idscript_totvsappslv01
labeltotvsappslv01

#ckconfig: 2345 84 10

#description: Starts and stops program

#################################

# CONFIGURACAO DO SERVICO #

#################################

#Inserir o nome do executavel 

prog="appsrvlinux"

#Inserir o caminho do diretorio do executavel

pathbin="/totvs/microsiga/protheus12/bin/appslv01"

#################################

# Configuracao de ULIMIT #

#################################

#open files - (-n)

openFiles=65536

#stack size - (kbytes, -s)

stackSize=1024

#core file size - (blocks, -c)

coreFileSize=unlimited

#file size - (blocks, -f)

fileSize=unlimited

#cpu time - (seconds, -t)

cpuTime=unlimited

#virtual memory - (-v)

virtualMemory=unlimited

#########################

# FIM DA CONFIGURACAO #

#########################

#Caminho absoluto do executavel

progbin="${pathbin}/${prog}"

#Caminho absoluto do arquivo .pid

pidfile="/var/run/${prog}.pid"

#Caminho absoluto do arquilo de lock

lockfile="/var/lock/subsys/${prog}"

#Caminho absoluto do arquivo de log (script)

logfile="${pathbin}/log_${prog}.log"

#Source function library.

functions="/etc/init.d/functions"

if [ -e ${functions} ] ; then

. /etc/init.d/functions

else

echo "$functions not installed"

exit 5

fi

RETVAL=0

#Verifica se o executavel tem permissao correta e se esta acessivel

test -x $progbin || { echo "$progbin not installed";

        if [ "$1" = "stop" ]; then exit 0;

        else exit 5; fi; }

#Prepara as ulimit para o servico

ulimit -n ${openFiles}

ulimit -s ${stackSize}

ulimit -c ${coreFileSize}

ulimit -f ${fileSize}

ulimit -t ${cpuTime}

ulimit -v ${virtualMemory}

#Variaveis de Output

red=`tput setaf 1`

green=`tput setaf 2`

reset=`tput sgr0`

logmsg="$(date) | $(whoami) | $0 | $1 |"

#Acessa o diretorio configurado na variavel PATHBIN

cd ${pathbin}

#Function Start

start() {

if [ -z `pidof -x ${prog}` ] ; then

   echo "Starting ${prog}... "

   exec ./${prog} >/dev/null &

   RETVAL=$?

   if [ ${RETVAL} -eq 0 ]; then

      touch ${lockfile}

      touch ${pidfile}

      pidof -x ${prog} > ${pidfile}

      sleep 1

      echo "PID : `cat ${pidfile}`"

      echo "${prog} running :   ${green}[ OK ]${reset}"

      echo "${logmsg} ${prog} Started" >> ${logfile}

   else

      echo "Failed to start ${prog} :         ${red}[ Failure ]${reset}"

      echo "${logmsg} Failed to start ${prog}" >> ${logfile}

   fi 

   echo

else

   echo "${prog} is ${green}Started${reset} pid `pidof -x ${prog}`"

   echo "${logmsg} ${prog} already started" >> ${logfile}

fi

}

#Function Stop

stop() {

if [ ! -z `pidof -x ${prog}` ] ; then

   killproc ${prog} >/dev/null &

   #pkill -f ${prog}

   echo

   rm -f $lockfile

   rm -f $pidfile

   echo -n "Stopping ${prog}."

   while [ ! -z `pidof -x ${prog}` ] 

   do

        echo -n "."

        sleep 1

   done

   echo

   echo "${prog} is Stopped     ${red}[ Stopped ]${reset}"

   echo "${logmsg} ${prog} stopped" >> ${logfile}

else

   echo "${prog} is not running ${red}[ Stopped ]${reset}"

   echo "${logmsg} ${prog} already stopped" >> ${logfile}

fi

}

#Function Status

status() {

pid=$(pidof -x ${prog})

progport=$(lsof -Pp ${pid} | grep '(LISTEN)' | awk '{ print $9}' | cut -d: -f2 | xargs)

list=$(ps -eo pid,start_time,cputime,pcpu,pmem,stat,size,nlwp,comm | grep ${pid})

start_time=$(echo $list | awk '{ print $2 }')

cputime=$(echo $list | awk '{ print $3 }')

pcpu=$(echo $list | awk '{ print $4 }')

pmem=$(echo $list | awk '{ print $5 }')

stat=$(echo $list | awk '{ print $6 }')

size=$(echo $list | awk '{ print $7 }')

nlwp=$(echo $list | awk '{ print $8 }')

comm=$(echo $list | awk '{ print $9 }')

size=$(echo "$(bc <<< "scale=2;$size/1024") MB")

echo "PROCESS           : ${comm}"

echo "PORT              : ${progport}"

echo "PID               : ${pid}"

echo "STARTED           : ${start_time}"

echo "TIME              : ${cputime}"

echo "%CPU              : ${pcpu}"

echo "%MEM              : ${pmem}"

echo "MEMORY            : ${size}"

echo "STATUS            : ${green}[ running ]${reset}"

echo "THREADS           : ${nlwp}"

}

#MAIN

case "$1" in

start)

    start

    ;;

stop)

    stop

    ;;

status)

    if [ ! -z `pidof -x ${prog}` ] ; then

       echo "Status process     : ${green}[ OK ]${reset}"

       status

    else

        echo "Status process    : ${red}[ Failure ]${reset}"

        echo "Program $prog is not running!"

    fi

    ;;

restart)

    stop

    sleep 2

    start

    sleep 2

    status

    ;;

log)

    cat ${logfile}

    echo "More details at ${logfile}"

    ;;

*)

    echo $"Usage: $0 {start|stop|restart|status|log}"

    exit 1

esac

exit 0

Card
idscript_totvsappslv02
labeltotvsappslv02

#ckconfig: 2345 84 10

#description: Starts and stops program

#################################

# CONFIGURACAO DO SERVICO #

#################################

#Inserir o nome do executavel 

prog="appsrvlinux"

#Inserir o caminho do diretorio do executavel

pathbin="/totvs/microsiga/protheus12/bin/appslv02"

#################################

# Configuracao de ULIMIT #

#################################

#open files - (-n)

openFiles=65536

#stack size - (kbytes, -s)

stackSize=1024

#core file size - (blocks, -c)

coreFileSize=unlimited

#file size - (blocks, -f)

fileSize=unlimited

#cpu time - (seconds, -t)

cpuTime=unlimited

#virtual memory - (-v)

virtualMemory=unlimited

#########################

# FIM DA CONFIGURACAO #

#########################

#Caminho absoluto do executavel

progbin="${pathbin}/${prog}"

#Caminho absoluto do arquivo .pid

pidfile="/var/run/${prog}.pid"

#Caminho absoluto do arquilo de lock

lockfile="/var/lock/subsys/${prog}"

#Caminho absoluto do arquivo de log (script)

logfile="${pathbin}/log_${prog}.log"

#Source function library.

functions="/etc/init.d/functions"

if [ -e ${functions} ] ; then

. /etc/init.d/functions

else

echo "$functions not installed"

exit 5

fi

RETVAL=0

#Verifica se o executavel tem permissao correta e se esta acessivel

test -x $progbin || { echo "$progbin not installed";

        if [ "$1" = "stop" ]; then exit 0;

        else exit 5; fi; }

#Prepara as ulimit para o servico

ulimit -n ${openFiles}

ulimit -s ${stackSize}

ulimit -c ${coreFileSize}

ulimit -f ${fileSize}

ulimit -t ${cpuTime}

ulimit -v ${virtualMemory}

#Variaveis de Output

red=`tput setaf 1`

green=`tput setaf 2`

reset=`tput sgr0`

logmsg="$(date) | $(whoami) | $0 | $1 |"

#Acessa o diretorio configurado na variavel PATHBIN

cd ${pathbin}

#Function Start

start() {

if [ -z `pidof -x ${prog}` ] ; then

   echo "Starting ${prog}... "

   exec ./${prog} >/dev/null &

   RETVAL=$?

   if [ ${RETVAL} -eq 0 ]; then

      touch ${lockfile}

      touch ${pidfile}

      pidof -x ${prog} > ${pidfile}

      sleep 1

      echo "PID : `cat ${pidfile}`"

      echo "${prog} running :   ${green}[ OK ]${reset}"

      echo "${logmsg} ${prog} Started" >> ${logfile}

   else

      echo "Failed to start ${prog} :         ${red}[ Failure ]${reset}"

      echo "${logmsg} Failed to start ${prog}" >> ${logfile}

   fi 

   echo

else

   echo "${prog} is ${green}Started${reset} pid `pidof -x ${prog}`"

   echo "${logmsg} ${prog} already started" >> ${logfile}

fi

}

#Function Stop

stop() {

if [ ! -z `pidof -x ${prog}` ] ; then

   killproc ${prog} >/dev/null &

   #pkill -f ${prog}

   echo

   rm -f $lockfile

   rm -f $pidfile

   echo -n "Stopping ${prog}."

   while [ ! -z `pidof -x ${prog}` ] 

   do

        echo -n "."

        sleep 1

   done

   echo

   echo "${prog} is Stopped     ${red}[ Stopped ]${reset}"

   echo "${logmsg} ${prog} stopped" >> ${logfile}

else

   echo "${prog} is not running ${red}[ Stopped ]${reset}"

   echo "${logmsg} ${prog} already stopped" >> ${logfile}

fi

}

#Function Status

status() {

pid=$(pidof -x ${prog})

progport=$(lsof -Pp ${pid} | grep '(LISTEN)' | awk '{ print $9}' | cut -d: -f2 | xargs)

list=$(ps -eo pid,start_time,cputime,pcpu,pmem,stat,size,nlwp,comm | grep ${pid})

start_time=$(echo $list | awk '{ print $2 }')

cputime=$(echo $list | awk '{ print $3 }')

pcpu=$(echo $list | awk '{ print $4 }')

pmem=$(echo $list | awk '{ print $5 }')

stat=$(echo $list | awk '{ print $6 }')

size=$(echo $list | awk '{ print $7 }')

nlwp=$(echo $list | awk '{ print $8 }')

comm=$(echo $list | awk '{ print $9 }')

size=$(echo "$(bc <<< "scale=2;$size/1024") MB")

echo "PROCESS           : ${comm}"

echo "PORT              : ${progport}"

echo "PID               : ${pid}"

echo "STARTED           : ${start_time}"

echo "TIME              : ${cputime}"

echo "%CPU              : ${pcpu}"

echo "%MEM              : ${pmem}"

echo "MEMORY            : ${size}"

echo "STATUS            : ${green}[ running ]${reset}"

echo "THREADS           : ${nlwp}"

}

#MAIN

case "$1" in

start)

    start

    ;;

stop)

    stop

    ;;

status)

    if [ ! -z `pidof -x ${prog}` ] ; then

       echo "Status process     : ${green}[ OK ]${reset}"

       status

    else

        echo "Status process    : ${red}[ Failure ]${reset}"

        echo "Program $prog is not running!"

    fi

    ;;

restart)

    stop

    sleep 2

    start

    sleep 2

    status

    ;;

log)

    cat ${logfile}

    echo "More details at ${logfile}"

    ;;

*)

    echo $"Usage: $0 {start|stop|restart|status|log}"

    exit 1

esac

exit 0

Card
idscript_totvsappbalance
labeltotvsappbalance

#ckconfig: 2345 84 10

#description: Starts and stops program

#################################

# CONFIGURACAO DO SERVICO #

#################################

#Inserir o nome do executavel 

prog="appsrvlinux"

#Inserir o caminho do diretorio do executavel

pathbin="/totvs/microsiga/protheus12/bin/appbalance"

#################################

# Configuracao de ULIMIT #

#################################

#open files - (-n)

openFiles=65536

#stack size - (kbytes, -s)

stackSize=1024

#core file size - (blocks, -c)

coreFileSize=unlimited

#file size - (blocks, -f)

fileSize=unlimited

#cpu time - (seconds, -t)

cpuTime=unlimited

#virtual memory - (-v)

virtualMemory=unlimited

#########################

# FIM DA CONFIGURACAO #

#########################

#Caminho absoluto do executavel

progbin="${pathbin}/${prog}"

#Caminho absoluto do arquivo .pid

pidfile="/var/run/${prog}.pid"

#Caminho absoluto do arquilo de lock

lockfile="/var/lock/subsys/${prog}"

#Caminho absoluto do arquivo de log (script)

logfile="${pathbin}/log_${prog}.log"

#Source function library.

functions="/etc/init.d/functions"

if [ -e ${functions} ] ; then

. /etc/init.d/functions

else

echo "$functions not installed"

exit 5

fi

RETVAL=0

#Verifica se o executavel tem permissao correta e se esta acessivel

test -x $progbin || { echo "$progbin not installed";

        if [ "$1" = "stop" ]; then exit 0;

        else exit 5; fi; }

#Prepara as ulimit para o servico

ulimit -n ${openFiles}

ulimit -s ${stackSize}

ulimit -c ${coreFileSize}

ulimit -f ${fileSize}

ulimit -t ${cpuTime}

ulimit -v ${virtualMemory}

#Variaveis de Output

red=`tput setaf 1`

green=`tput setaf 2`

reset=`tput sgr0`

logmsg="$(date) | $(whoami) | $0 | $1 |"

#Acessa o diretorio configurado na variavel PATHBIN

cd ${pathbin}

#Function Start

start() {

if [ -z `pidof -x ${prog}` ] ; then

   echo "Starting ${prog}... "

   exec ./${prog} >/dev/null &

   RETVAL=$?

   if [ ${RETVAL} -eq 0 ]; then

      touch ${lockfile}

      touch ${pidfile}

      pidof -x ${prog} > ${pidfile}

      sleep 1

      echo "PID : `cat ${pidfile}`"

      echo "${prog} running :   ${green}[ OK ]${reset}"

      echo "${logmsg} ${prog} Started" >> ${logfile}

   else

      echo "Failed to start ${prog} :         ${red}[ Failure ]${reset}"

      echo "${logmsg} Failed to start ${prog}" >> ${logfile}

   fi 

   echo

else

   echo "${prog} is ${green}Started${reset} pid `pidof -x ${prog}`"

   echo "${logmsg} ${prog} already started" >> ${logfile}

fi

}

#Function Stop

stop() {

if [ ! -z `pidof -x ${prog}` ] ; then

   killproc ${prog} >/dev/null &

   #pkill -f ${prog}

   echo

   rm -f $lockfile

   rm -f $pidfile

   echo -n "Stopping ${prog}."

   while [ ! -z `pidof -x ${prog}` ] 

   do

        echo -n "."

        sleep 1

   done

   echo

   echo "${prog} is Stopped     ${red}[ Stopped ]${reset}"

   echo "${logmsg} ${prog} stopped" >> ${logfile}

else

   echo "${prog} is not running ${red}[ Stopped ]${reset}"

   echo "${logmsg} ${prog} already stopped" >> ${logfile}

fi

}

#Function Status

status() {

pid=$(pidof -x ${prog})

progport=$(lsof -Pp ${pid} | grep '(LISTEN)' | awk '{ print $9}' | cut -d: -f2 | xargs)

list=$(ps -eo pid,start_time,cputime,pcpu,pmem,stat,size,nlwp,comm | grep ${pid})

start_time=$(echo $list | awk '{ print $2 }')

cputime=$(echo $list | awk '{ print $3 }')

pcpu=$(echo $list | awk '{ print $4 }')

pmem=$(echo $list | awk '{ print $5 }')

stat=$(echo $list | awk '{ print $6 }')

size=$(echo $list | awk '{ print $7 }')

nlwp=$(echo $list | awk '{ print $8 }')

comm=$(echo $list | awk '{ print $9 }')

size=$(echo "$(bc <<< "scale=2;$size/1024") MB")

echo "PROCESS           : ${comm}"

echo "PORT              : ${progport}"

echo "PID               : ${pid}"

echo "STARTED           : ${start_time}"

echo "TIME              : ${cputime}"

echo "%CPU              : ${pcpu}"

echo "%MEM              : ${pmem}"

echo "MEMORY            : ${size}"

echo "STATUS            : ${green}[ running ]${reset}"

echo "THREADS           : ${nlwp}"

}

#MAIN

case "$1" in

start)

    start

    ;;

stop)

    stop

    ;;

status)

    if [ ! -z `pidof -x ${prog}` ] ; then

       echo "Status process     : ${green}[ OK ]${reset}"

       status

    else

        echo "Status process    : ${red}[ Failure ]${reset}"

        echo "Program $prog is not running!"

    fi

    ;;

restart)

    stop

    sleep 2

    start

    sleep 2

    status

    ;;

log)

    cat ${logfile}

    echo "More details at ${logfile}"

    ;;

*)

    echo $"Usage: $0 {start|stop|restart|status|log}"

    exit 1

esac

exit 0

...

collapsetrue
#!/bin/bash
# description: Este script é usado para gerenciar serviços do Protheus, permitindo 
# iniciar, parar, reiniciar, matar, verificar o status, exibir informações detalhadas, 
# exportar logs e configurações, e monitorar logs em tempo real. 
# Use as opções start, stop, kill, restart, status, describe, export, ou log para realizar 
# operações comuns de serviço de maneira fácil e eficiente.

#########################################
#	CONFIGURACAO DO SERVICO		#
#########################################
#Inserir o nome do executavel 
prog="dbaccess64"

#Inserir o caminho do diretorio do executavel
pathbin="/totvs/protheus/bin/dbaccess/multi"

alias=$(basename $(dirname ${pathbin}))

progbin="${pathbin}/${prog}"
pidfile="/var/run/${alias}.pid"
lockfile="/var/lock/subsys/${alias}"

config_filename=dbaccess.ini
log_filename=dbconsole.log
#################################################################
#AMBIENTE COM DB ORACLE
#################################################################
#Variavel EnvOracle define se deve exportar as variaveis do ORACLE
#       1 - Habilitado | 0 - Desabilitado
#################################################################
envOracle=0
#################################################################
oracle_sid="orcl"
oracle_home="/usr/lib/oracle/19.10/client64"
tns_admin="/usr/lib/oracle/19.10/client64/lib/network/admin/"
#################################################################
#################################################################
#Configuracao de ULIMIT
#################################################################
#open files - (-n)
openFiles=65536
#stack size - (kbytes, -s)
stackSize=1024
#core file size - (blocks, -c)
coreFileSize=unlimited
#file size - (blocks, -f)
fileSize=unlimited
#cpu time - (seconds, -t)
cpuTime=unlimited
#virtual memory - (-v)
virtualMemory=unlimited

#################################
#	FIM DA CONFIGURACAO	#
#################################

###################################################################
#Exporta as variaveis de ambiente do Oracle
###################################################################
exportOracle() {
	if [ ${envOracle} -eq 1 ]
	then
		export ORACLE_SID=${oracle_sid}
		export ORACLE_HOME=${oracle_home}
		export TNS_ADMIN=${tns_admin}
		export CLASSPATH=$ORACLE_HOME/JRE:$ORACLE_HOME/jlib:$ORACLE_HOME/rdbms/jlib:$ORACLE_HOME/network/jlib
		export LD_LIBRARY_PATH=$ORACLE_HOME:/lib:/usr/lib:/usr/local/lib:${pathbin}
		export PATH=$ORACLE_HOME:$PATH
		echo -e "Exported ORACLE environment variables..."
	fi
}
##################################################################
##################################################################
RETVAL=0

## Verifica se o executavel tem permissao correta e se esta acessivel
test -x $progbin || { echo "$progbin not installed";
        if [ "$1" = "stop" ]; then exit 0;
        else exit 5; fi; }

#Prepara as ulimit para o servico do DBAccess
ulimit -n ${openFiles}
ulimit -s ${stackSize}
ulimit -c ${coreFileSize}
ulimit -f ${fileSize}
ulimit -t ${cpuTime}
ulimit -v ${virtualMemory}

#Acessa o diretorio configurado na variavel PATHBIN
cd $pathbin

#Variaveis de Output
red="\033[31m"
green='\033[32m'
reset='\033[m'

export LD_LIBRARY_PATH=${pathbin}

## Start_service: função que inicia o serviço.
start_service() {
exportOracle
if [ -z `pidof -x $progbin` ] ; then
   echo "Starting $prog... "
    ${progbin} -daemon >/dev/null &
   RETVAL=$?
   if [ ${RETVAL} -eq 0 ]; then
      touch ${lockfile}
      touch ${pidfile}
      pidof -x ${progbin} > ${pidfile}
      sleep 1
      echo "PID : " `cat ${pidfile}`
      echo -e "${prog} running :   ${green}[ OK ]${reset}"
   else
      echo -e "Failed to start ${prog} :         ${red}[ Failure ]${reset}"
   fi 
   echo
else
   echo -e "$prog is ${green}Started${reset} pid `pidof -x $progbin`"
fi
}

## Stop_service: função que encerra o serviço.
stop_service() {
if [ ! -z `pidof -x ${progbin}` ] ; then

   kill -s SIGTERM $(pidof -x ${progbin})

   echo
   rm -f $lockfile
   rm -f $pidfile
   echo -n "Stopping ${prog}."
   while [ ! -z `pidof -x ${progbin}` ]
   do
        echo -n "."
        sleep 1
   done
   echo
   echo -e "${prog} is Stopped     ${red}[ Stopped ]${reset}"
else
   echo -e "${prog} is not running ${red}[ Stopped ]${reset}"
fi
}

## Kill_service: função que interrompe o serviço.
kill_service() {
if [ ! -z `pidof -x ${progbin}` ] ; then

   kill -s SIGKILL $(pidof -x ${progbin})

   echo
   rm -f $lockfile
   rm -f $pidfile
   echo -n "Stopping ${prog}."
   while [ ! -z `pidof -x ${progbin}` ]
   do
        echo -n "."
        sleep 1
   done
   echo
   echo -e "${prog} is Killed     ${red}[ Killed ]${reset}"
else
   echo -e "${prog} is not running ${red}[ Stopped ]${reset}"
fi
}

## get_stats: função que coleta os dados do serviço e exporta no contexto atual.
get_stats() {
date 
echo
if [ ! -z `pidof -x ${progbin}` ] ; then
    export pid=$(pidof -x ${progbin})

    export progport=$(lsof -Pp ${pid} | grep '(LISTEN)' | awk '{ print $9}' | cut -d: -f2 | xargs | tr ' ' ',')

    export list=$(ps -eo pid,start_time,cputime,pcpu,pmem,stat,size,nlwp,comm | grep ${pid})

    export start_time=$(echo -e $list | awk '{ print $2 }')
    export cputime=$(echo -e $list | awk '{ print $3 }')
    export pcpu=$(echo -e $list | awk '{ print $4 }')
    export pmem=$(echo -e $list | awk '{ print $5 }')
    export stat=$(echo -e $list | awk '{ print $6 }')
    export size=$(echo -e $list | awk '{ print $7 }')
    export nlwp=$(echo -e $list | awk '{ print $8 }')
    export comm=$(echo -e $list | awk '{ print $9 }')

    export size=$(echo -e "$(bc <<< "scale=2;$size/1024")MB")
else
    echo -e "Status process: ${red} [ Stopped ] ${reset} "
    echo -e "${red}- Program $prog is not running! ${reset}"
fi
}

## Status: função que exibe o estado atual do serviço em formato de tabela.
status() {
get_stats

output=$(cat << EOF
ALIAS PROCESS PORT PID CPU_TIME %CPU %MEM MEMORY THREADS STATUS PATH
${alias} ${comm} ${progport} ${pid} ${cputime} ${pcpu} ${pmem} ${size} ${nlwp} ${green}[running]${reset} ${progbin} 
EOF
)

echo -e "$output" | column -t
}

get_log() {
    consolelog=$(grep -i '^\s*consolefile\s*=' "${pathbin}/${config_filename}" | awk -F= '{print $2}' | tr -d ' ')
    if [ ! -n "$consolelog" ]; then
        if [ -n "${pathbin}/${log_filename}" ]; then
            consolelog="${pathbin}/${log_filename}"
        else
            echo '${red}Logfile not found!${reset} : "${pathbin}/${log_filename}"'
            echo 'Config File: ${pathbin}/${config_filename}'
            echo 'Add parameter: consolefile=${pathbin}/${log_filename}'
        fi
    fi
    echo ${consolelog}
}


## Describe: função que exibe as configurações do ambiente onde o servico está rodando.
describe() {
get_stats

## Exibe o status atual do serviço caso ele esteja em execução.
if [ ! -z `pidof -x ${progbin}` ] ; then
    output=$(cat << EOF
AlIAS ${alias}
PROCESS ${comm}
PATH ${progbin}
PORT ${progport}
PID ${pid}
STARTED ${start_time}
TIME ${cputime}
%CPU ${pcpu}
%MEM ${pmem}
MEMORY ${size}
STATUS [Running]
THREADS ${nlwp}
EOF
)
echo -e "$output" | column -t
echo
fi

## Exibe as bibliotecas utilizadas pelo serviço.
echo "### LIBRARY ####"
ldd ${progbin}
echo ""

## Exibe o appserver.ini completo quando localizado.
echo "### INI ###"
if [ -n "${pathbin}/${config_filename}" ]; then
    echo ""
    echo -e "${config_filename} : ${green} ${pathbin}/${config_filename} ${reset}"
    echo ""
    cat ${pathbin}/${config_filename}
else
    echo "O appserver não foi localizado."
fi
echo ""

## Exibe as 15 primeiras linhas e as 15 ultimas linhas do logfile.
echo "### LOGFILE ###"

consolelog=$(get_log)

if [ -n "${consolelog}" ]; then
    echo ""
    echo -e "${log_filename} : ${green} ${consolelog} ${reset}"
    echo ""
    head -n 15 "${consolelog}"
    echo ...
    tail -n 15 "${consolelog}"
else

    echo "Chave 'consolefile' não encontrada no arquivo ${pathbin}/${config_filename}."
fi

}

## Tail_log: Executa o comando tail -f no arquivo de log do serviço.
tail_log() {

consolelog=$(get_log)

if [ -n "${consolelog}" ]; then
    echo ""
    echo -e "${log_filename} : ${green}${consolelog}${reset}"
    echo ""
    head -n 15 "${consolelog}"
    echo ...
    tail -f -n 15 "${consolelog}"
else
    echo "Chave 'consolefile' não encontrada no arquivo ${pathbin}/${config_filename}."
fi
}

## Export_service: Exporta as configurações do ambiente onde o serviço sendo executado junto com o logfile.
export_service() {

describe > /tmp/${SCRIPT_NAME}_describe.txt

ldd -v ${progbin} > /tmp/${SCRIPT_NAME}_library.txt

consolelog=$(get_log)
if [ -n "$consolelog" ]; then
    cp -p $consolelog /tmp/${SCRIPT_NAME}_console.log
else
    echo "Chave 'consolefile' não encontrada no arquivo ${pathbin}/${config_filename}."
fi

if [ -n "${pathbin}/${config_filename}" ]; then
    cp -p ${pathbin}/${config_filename} /tmp/${SCRIPT_NAME}_${config_filename}
else
    echo "O appserver não foi localizado."
fi

zip_file="/tmp/${SCRIPT_NAME}_export.zip"
cd /tmp
zip -r "$zip_file" "${SCRIPT_NAME}_describe.txt" "${SCRIPT_NAME}_console.log" "${SCRIPT_NAME}_${config_filename}" "${SCRIPT_NAME}_library.txt"

if [ -f "$zip_file" ]; then
    echo -e "Pacote criado com sucesso: ${green} ${zip_file} ${reset}"
else
    echo -e "${red}$ Erro ao criar o pacote .zip ${reset}"
fi
rm -f /tmp/${SCRIPT_NAME}_describe.txt /tmp/${SCRIPT_NAME}_console.log /tmp/${SCRIPT_NAME}_${config_filename} /tmp/${SCRIPT_NAME}_library.txt

}

SCRIPT_NAME=$(basename "$0")

## Show_help: Mensagem de ajuda para usar este script.
show_help() {
    cat << EOF
Usage: ${SCRIPT_NAME} {start|stop|kill|restart|status|describe|export|log}

Gerenciamento de serviços permite iniciar, parar, reiniciar, matar, verificar o status, exibir informações. 
Use as opções start|stop|kill|restart|status|describe|export|log para realizar operações comuns de serviço com facilidade.

  start     : Inicia o serviço.
  stop      : Encerra o serviço.
  kill      : Encerra o serviço de forma abrupta.
  restart   : Reinicia o serviço.
  status    : Exibe os detalhes do serviço em formato de tabela.
  describe  : Exibe os detalhes do serviço e configurações.
  export    : Exporta as informações do describe junto com o appserver.ini e console.log para 
              o arquivo ${SCRIPT_NAME}.zip em /tmp.
  log       : Exibe o log com o comando tail -f.

EOF
}

#MAIN
case "$1" in
start)
    start_service 2>/dev/null
    ;;
stop)
    stop_service
    ;;
kill)
    kill_service
    ;;
restart)
    stop_service
    sleep 1
    start_service 2>/dev/null
    sleep 1
    status
    exit $?
    ;;
status)
    if [ ! -z `pidof -x $progbin` ] ; then
       status
    else
        echo -e "Status process: ${red} [ Stoppe ] ${reset} "
        echo -e "${red}- Program $prog is not running! ${reset}"
    fi
    ;;
describe)
    describe
    ;;
log)
    tail_log
    ;;
export)
    export_service
    ;;
*)
    show_help
    exit 1
esac

exit 0
Bloco de código
languagebash
titletotvsappsec01
collapsetrue
#!/bin/bash
# description: Este script é usado para gerenciar serviços do Protheus, permitindo 
# iniciar, parar, reiniciar, matar, verificar o status, exibir informações detalhadas, 
# exportar logs e configurações, e monitorar logs em tempo real. 
# Use as opções start, stop, kill, restart, status, describe, export, ou log para realizar 
# operações comuns de serviço de maneira fácil e eficiente.

#########################################
#	CONFIGURACAO DO SERVICO		#
#########################################
#Inserir o nome do executavel 
prog="appsrvlinux"

#Inserir o caminho do diretorio do executavel
pathbin="/totvs/protheus/bin/protheus_sec01"

alias=$(basename "${pathbin}")

progbin="${pathbin}/${prog}"
pidfile="/var/run/${alias}.pid"
lockfile="/var/lock/subsys/${alias}"

config_filename=appserver.ini
log_filename=console.log
#################################################################
#Configuracao de ULIMIT
#################################################################
#open files - (-n)
openFiles=65536
#stack size - (kbytes, -s)
stackSize=1024
#core file size - (blocks, -c)
coreFileSize=unlimited
#file size - (blocks, -f)
fileSize=unlimited
#cpu time - (seconds, -t)
cpuTime=unlimited
#virtual memory - (-v)
virtualMemory=unlimited

#################################
#	FIM DA CONFIGURACAO	#
#################################

RETVAL=0

## Verifica se o executavel tem permissao correta e se esta acessivel
test -x $progbin || { echo "$progbin not installed";
        if [ "$1" = "stop" ]; then exit 0;
        else exit 5; fi; }

#Prepara as ulimit para o servico do DBAccess
ulimit -n ${openFiles}
ulimit -s ${stackSize}
ulimit -c ${coreFileSize}
ulimit -f ${fileSize}
ulimit -t ${cpuTime}
ulimit -v ${virtualMemory}

#Acessa o diretorio configurado na variavel PATHBIN
cd $pathbin

#Variaveis de Output
red="\033[31m"
green='\033[32m'
reset='\033[m'

export LD_LIBRARY_PATH=${pathbin}

## Start_service: função que inicia o serviço.
start_service() {

if [ -z `pidof -x $progbin` ] ; then
   echo "Starting $prog... "
    ${progbin} -daemon >/dev/null &
   RETVAL=$?
   if [ ${RETVAL} -eq 0 ]; then
      touch ${lockfile}
      touch ${pidfile}
      pidof -x ${progbin} > ${pidfile}
      sleep 1
      echo "PID : " `cat ${pidfile}`
      echo -e "${prog} running :   ${green}[ OK ]${reset}"
   else
      echo -e "Failed to start ${prog} :         ${red}[ Failure ]${reset}"
   fi 
   echo
else
   echo -e "$prog is ${green}Started${reset} pid `pidof -x $progbin`"
fi
}

## Stop_service: função que encerra o serviço.
stop_service() {
if [ ! -z `pidof -x ${progbin}` ] ; then

   kill -s SIGTERM $(pidof -x ${progbin})

   echo
   rm -f $lockfile
   rm -f $pidfile
   echo -n "Stopping ${prog}."
   while [ ! -z `pidof -x ${progbin}` ]
   do
        echo -n "."
        sleep 1
   done
   echo
   echo -e "${prog} is Stopped     ${red}[ Stopped ]${reset}"
else
   echo -e "${prog} is not running ${red}[ Stopped ]${reset}"
fi
}

## Kill_service: função que interrompe o serviço.
kill_service() {
if [ ! -z `pidof -x ${progbin}` ] ; then

   kill -s SIGKILL $(pidof -x ${progbin})

   echo
   rm -f $lockfile
   rm -f $pidfile
   echo -n "Stopping ${prog}."
   while [ ! -z `pidof -x ${progbin}` ]
   do
        echo -n "."
        sleep 1
   done
   echo
   echo -e "${prog} is Killed     ${red}[ Killed ]${reset}"
else
   echo -e "${prog} is not running ${red}[ Stopped ]${reset}"
fi
}

## get_stats: função que coleta os dados do serviço e exporta no contexto atual.
get_stats() {
date 
echo
if [ ! -z `pidof -x ${progbin}` ] ; then
    export pid=$(pidof -x ${progbin})

    export progport=$(lsof -Pp ${pid} | grep '(LISTEN)' | awk '{ print $9}' | cut -d: -f2 | xargs | tr ' ' ',')

    export list=$(ps -eo pid,start_time,cputime,pcpu,pmem,stat,size,nlwp,comm | grep ${pid})

    export start_time=$(echo -e $list | awk '{ print $2 }')
    export cputime=$(echo -e $list | awk '{ print $3 }')
    export pcpu=$(echo -e $list | awk '{ print $4 }')
    export pmem=$(echo -e $list | awk '{ print $5 }')
    export stat=$(echo -e $list | awk '{ print $6 }')
    export size=$(echo -e $list | awk '{ print $7 }')
    export nlwp=$(echo -e $list | awk '{ print $8 }')
    export comm=$(echo -e $list | awk '{ print $9 }')

    export size=$(echo -e "$(bc <<< "scale=2;$size/1024")MB")
else
    echo -e "Status process: ${red} [ Stopped ] ${reset} "
    echo -e "${red}- Program $prog is not running! ${reset}"
fi
}

## Status: função que exibe o estado atual do serviço em formato de tabela.
status() {
get_stats

output=$(cat << EOF
ALIAS PROCESS PORT PID CPU_TIME %CPU %MEM MEMORY THREADS STATUS PATH
${alias} ${comm} ${progport} ${pid} ${cputime} ${pcpu} ${pmem} ${size} ${nlwp} ${green}[running]${reset} ${progbin} 
EOF
)

echo -e "$output" | column -t
}

get_log() {
    consolelog=$(grep -i '^\s*consolefile\s*=' "${pathbin}/${config_filename}" | awk -F= '{print $2}' | tr -d ' ')
    if [ ! -n "$consolelog" ]; then
        if [ -n "${pathbin}/${log_filename}" ]; then
            consolelog="${pathbin}/${log_filename}"
        else
            echo '${red}Logfile not found!${reset} : "${pathbin}/${log_filename}"'
            echo 'Config File: ${pathbin}/${config_filename}'
            echo 'Add parameter: consolefile=${pathbin}/${log_filename}'
        fi
    fi
    echo ${consolelog}
}

## Describe: função que exibe as configurações do ambiente onde o servico está rodando.
describe() {
get_stats

## Exibe o status atual do serviço caso ele esteja em execução.
if [ ! -z `pidof -x ${progbin}` ] ; then
    output=$(cat << EOF
AlIAS ${alias}
PROCESS ${comm}
PATH ${progbin}
PORT ${progport}
PID ${pid}
STARTED ${start_time}
TIME ${cputime}
%CPU ${pcpu}
%MEM ${pmem}
MEMORY ${size}
STATUS [Running]
THREADS ${nlwp}
EOF
)
echo -e "$output" | column -t
echo
fi

## Exibe as bibliotecas utilizadas pelo serviço.
echo "### LIBRARY ####"
ldd ${progbin}
echo ""

## Exibe o appserver.ini completo quando localizado.
echo "### INI ###"
if [ -n "${pathbin}/appserver.ini" ]; then
    echo ""
    echo -e "appserver.ini : ${green} ${pathbin}/appserver.ini ${reset}"
    echo ""
    cat ${pathbin}/appserver.ini
else
    echo "O appserver não foi localizado."
fi
echo ""

## Exibe as 15 primeiras linhas e as 15 ultimas linhas do logfile.
echo "### LOGFILE ###"
consolelog=$(get_log)

if [ -n "$consolelog" ]; then
    echo ""
    echo -e "console.log : ${green} ${consolelog} ${reset}"
    echo ""
    head -n 15 "$consolelog"
    echo ...
    tail -n 15 "$consolelog"
else
    echo "Chave 'consolefile' não encontrada no arquivo ${pathbin}/appserver.ini."
fi

}

## Tail_log: Executa o comando tail -f no arquivo de log do serviço.
tail_log() {
consolelog=$(get_log)

if [ -n "$consolelog" ]; then
    echo ""
    echo -e "console.log : ${green}$consolelog${reset}"
    echo ""
    head -n 15 "$consolelog"
    echo ...
    tail -f -n 15 "$consolelog"
else
    echo "Chave 'consolefile' não encontrada no arquivo ${pathbin}/appserver.ini."
fi
}

## Export_service: Exporta as configurações do ambiente onde o serviço sendo executado junto com o logfile.
export_service() {

describe > /tmp/${SCRIPT_NAME}_describe.txt

ldd -v ${progbin} > /tmp/${SCRIPT_NAME}_library.txt

consolelog=$(get_log)
if [ -n "$consolelog" ]; then
    cp -p $consolelog /tmp/${SCRIPT_NAME}_console.log
else
    echo "Chave 'consolefile' não encontrada no arquivo ${pathbin}/appserver.ini."
fi

if [ -n "${pathbin}/appserver.ini" ]; then
    cp -p ${pathbin}/appserver.ini /tmp/${SCRIPT_NAME}_appserver.ini
else
    echo "O appserver não foi localizado."
fi

zip_file="/tmp/${SCRIPT_NAME}_export.zip"
cd /tmp
zip -r "$zip_file" "${SCRIPT_NAME}_describe.txt" "${SCRIPT_NAME}_console.log" "${SCRIPT_NAME}_appserver.ini" "${SCRIPT_NAME}_library.txt"

if [ -f "$zip_file" ]; then
    echo -e "Pacote criado com sucesso: ${green} $zip_file ${reset}"
else
    echo -e "${red}$ Erro ao criar o pacote .zip ${reset}"
fi
rm -f /tmp/${SCRIPT_NAME}_describe.txt /tmp/${SCRIPT_NAME}_console.log /tmp/${SCRIPT_NAME}_appserver.ini /tmp/${SCRIPT_NAME}_library.txt

}

SCRIPT_NAME=$(basename "$0")

## Show_help: Mensagem de ajuda para usar este script.
show_help() {
    cat << EOF
Usage: ${SCRIPT_NAME} {start|stop|kill|restart|status|describe|export|log}

Gerenciamento de serviços permite iniciar, parar, reiniciar, matar, verificar o status, exibir informações. 
Use as opções start|stop|kill|restart|status|describe|export|log para realizar operações comuns de serviço com facilidade.

  start     : Inicia o serviço.
  stop      : Encerra o serviço.
  kill      : Encerra o serviço de forma abrupta.
  restart   : Reinicia o serviço.
  status    : Exibe os detalhes do serviço em formato de tabela.
  describe  : Exibe os detalhes do serviço e configurações.
  export    : Exporta as informações do describe junto com o appserver.ini e console.log para 
              o arquivo ${SCRIPT_NAME}.zip em /tmp.
  log       : Exibe o log com o comando tail -f.

EOF
}

#MAIN
case "$1" in
start)
    start_service 2>/dev/null
    ;;
stop)
    stop_service
    ;;
kill)
    kill_service
    ;;
restart)
    stop_service
    sleep 1
    start_service 2>/dev/null
    sleep 1
    status
    exit $?
    ;;
status)
    if [ ! -z `pidof -x $progbin` ] ; then
       status
    else
        echo -e "Status process: ${red} [ Stoppe ] ${reset} "
        echo -e "${red}- Program $prog is not running! ${reset}"
    fi
    ;;
describe)
    describe
    ;;
log)
    tail_log
    ;;
export)
    export_service
    ;;
*)
    show_help
    exit 1
esac

exit 0
 
Bloco de código
languagebash
titletotvsappsec02
collapsetrue
#!/bin/bash
# description: Este script é usado para gerenciar serviços do Protheus, permitindo 
# iniciar, parar, reiniciar, matar, verificar o status, exibir informações detalhadas, 
# exportar logs e configurações, e monitorar logs em tempo real. 
# Use as opções start, stop, kill, restart, status, describe, export, ou log para realizar 
# operações comuns de serviço de maneira fácil e eficiente.

#########################################
#	CONFIGURACAO DO SERVICO		#
#########################################
#Inserir o nome do executavel 
prog="appsrvlinux"

#Inserir o caminho do diretorio do executavel
pathbin="/totvs/protheus/bin/protheus_sec02"

alias=$(basename "${pathbin}")

progbin="${pathbin}/${prog}"
pidfile="/var/run/${alias}.pid"
lockfile="/var/lock/subsys/${alias}"

config_filename=appserver.ini
log_filename=console.log
#################################################################
#Configuracao de ULIMIT
#################################################################
#open files - (-n)
openFiles=65536
#stack size - (kbytes, -s)
stackSize=1024
#core file size - (blocks, -c)
coreFileSize=unlimited
#file size - (blocks, -f)
fileSize=unlimited
#cpu time - (seconds, -t)
cpuTime=unlimited
#virtual memory - (-v)
virtualMemory=unlimited

#################################
#	FIM DA CONFIGURACAO	#
#################################

RETVAL=0

## Verifica se o executavel tem permissao correta e se esta acessivel
test -x $progbin || { echo "$progbin not installed";
        if [ "$1" = "stop" ]; then exit 0;
        else exit 5; fi; }

#Prepara as ulimit para o servico do DBAccess
ulimit -n ${openFiles}
ulimit -s ${stackSize}
ulimit -c ${coreFileSize}
ulimit -f ${fileSize}
ulimit -t ${cpuTime}
ulimit -v ${virtualMemory}

#Acessa o diretorio configurado na variavel PATHBIN
cd $pathbin

#Variaveis de Output
red="\033[31m"
green='\033[32m'
reset='\033[m'

export LD_LIBRARY_PATH=${pathbin}

## Start_service: função que inicia o serviço.
start_service() {

if [ -z `pidof -x $progbin` ] ; then
   echo "Starting $prog... "
    ${progbin} -daemon >/dev/null &
   RETVAL=$?
   if [ ${RETVAL} -eq 0 ]; then
      touch ${lockfile}
      touch ${pidfile}
      pidof -x ${progbin} > ${pidfile}
      sleep 1
      echo "PID : " `cat ${pidfile}`
      echo -e "${prog} running :   ${green}[ OK ]${reset}"
   else
      echo -e "Failed to start ${prog} :         ${red}[ Failure ]${reset}"
   fi 
   echo
else
   echo -e "$prog is ${green}Started${reset} pid `pidof -x $progbin`"
fi
}

## Stop_service: função que encerra o serviço.
stop_service() {
if [ ! -z `pidof -x ${progbin}` ] ; then

   kill -s SIGTERM $(pidof -x ${progbin})

   echo
   rm -f $lockfile
   rm -f $pidfile
   echo -n "Stopping ${prog}."
   while [ ! -z `pidof -x ${progbin}` ]
   do
        echo -n "."
        sleep 1
   done
   echo
   echo -e "${prog} is Stopped     ${red}[ Stopped ]${reset}"
else
   echo -e "${prog} is not running ${red}[ Stopped ]${reset}"
fi
}

## Kill_service: função que interrompe o serviço.
kill_service() {
if [ ! -z `pidof -x ${progbin}` ] ; then

   kill -s SIGKILL $(pidof -x ${progbin})

   echo
   rm -f $lockfile
   rm -f $pidfile
   echo -n "Stopping ${prog}."
   while [ ! -z `pidof -x ${progbin}` ]
   do
        echo -n "."
        sleep 1
   done
   echo
   echo -e "${prog} is Killed     ${red}[ Killed ]${reset}"
else
   echo -e "${prog} is not running ${red}[ Stopped ]${reset}"
fi
}

## get_stats: função que coleta os dados do serviço e exporta no contexto atual.
get_stats() {
date 
echo
if [ ! -z `pidof -x ${progbin}` ] ; then
    export pid=$(pidof -x ${progbin})

    export progport=$(lsof -Pp ${pid} | grep '(LISTEN)' | awk '{ print $9}' | cut -d: -f2 | xargs | tr ' ' ',')

    export list=$(ps -eo pid,start_time,cputime,pcpu,pmem,stat,size,nlwp,comm | grep ${pid})

    export start_time=$(echo -e $list | awk '{ print $2 }')
    export cputime=$(echo -e $list | awk '{ print $3 }')
    export pcpu=$(echo -e $list | awk '{ print $4 }')
    export pmem=$(echo -e $list | awk '{ print $5 }')
    export stat=$(echo -e $list | awk '{ print $6 }')
    export size=$(echo -e $list | awk '{ print $7 }')
    export nlwp=$(echo -e $list | awk '{ print $8 }')
    export comm=$(echo -e $list | awk '{ print $9 }')

    export size=$(echo -e "$(bc <<< "scale=2;$size/1024")MB")
else
    echo -e "Status process: ${red} [ Stopped ] ${reset} "
    echo -e "${red}- Program $prog is not running! ${reset}"
fi
}

## Status: função que exibe o estado atual do serviço em formato de tabela.
status() {
get_stats

output=$(cat << EOF
ALIAS PROCESS PORT PID CPU_TIME %CPU %MEM MEMORY THREADS STATUS PATH
${alias} ${comm} ${progport} ${pid} ${cputime} ${pcpu} ${pmem} ${size} ${nlwp} ${green}[running]${reset} ${progbin} 
EOF
)

echo -e "$output" | column -t
}

get_log() {
    consolelog=$(grep -i '^\s*consolefile\s*=' "${pathbin}/${config_filename}" | awk -F= '{print $2}' | tr -d ' ')
    if [ ! -n "$consolelog" ]; then
        if [ -n "${pathbin}/${log_filename}" ]; then
            consolelog="${pathbin}/${log_filename}"
        else
            echo '${red}Logfile not found!${reset} : "${pathbin}/${log_filename}"'
            echo 'Config File: ${pathbin}/${config_filename}'
            echo 'Add parameter: consolefile=${pathbin}/${log_filename}'
        fi
    fi
    echo ${consolelog}
}

## Describe: função que exibe as configurações do ambiente onde o servico está rodando.
describe() {
get_stats

## Exibe o status atual do serviço caso ele esteja em execução.
if [ ! -z `pidof -x ${progbin}` ] ; then
    output=$(cat << EOF
AlIAS ${alias}
PROCESS ${comm}
PATH ${progbin}
PORT ${progport}
PID ${pid}
STARTED ${start_time}
TIME ${cputime}
%CPU ${pcpu}
%MEM ${pmem}
MEMORY ${size}
STATUS [Running]
THREADS ${nlwp}
EOF
)
echo -e "$output" | column -t
echo
fi

## Exibe as bibliotecas utilizadas pelo serviço.
echo "### LIBRARY ####"
ldd ${progbin}
echo ""

## Exibe o appserver.ini completo quando localizado.
echo "### INI ###"
if [ -n "${pathbin}/appserver.ini" ]; then
    echo ""
    echo -e "appserver.ini : ${green} ${pathbin}/appserver.ini ${reset}"
    echo ""
    cat ${pathbin}/appserver.ini
else
    echo "O appserver não foi localizado."
fi
echo ""

## Exibe as 15 primeiras linhas e as 15 ultimas linhas do logfile.
echo "### LOGFILE ###"
consolelog=$(get_log)

if [ -n "$consolelog" ]; then
    echo ""
    echo -e "console.log : ${green} ${consolelog} ${reset}"
    echo ""
    head -n 15 "$consolelog"
    echo ...
    tail -n 15 "$consolelog"
else
    echo "Chave 'consolefile' não encontrada no arquivo ${pathbin}/appserver.ini."
fi

}

## Tail_log: Executa o comando tail -f no arquivo de log do serviço.
tail_log() {
consolelog=$(get_log)

if [ -n "$consolelog" ]; then
    echo ""
    echo -e "console.log : ${green}$consolelog${reset}"
    echo ""
    head -n 15 "$consolelog"
    echo ...
    tail -f -n 15 "$consolelog"
else
    echo "Chave 'consolefile' não encontrada no arquivo ${pathbin}/appserver.ini."
fi
}

## Export_service: Exporta as configurações do ambiente onde o serviço sendo executado junto com o logfile.
export_service() {

describe > /tmp/${SCRIPT_NAME}_describe.txt

ldd -v ${progbin} > /tmp/${SCRIPT_NAME}_library.txt

consolelog=$(get_log)
if [ -n "$consolelog" ]; then
    cp -p $consolelog /tmp/${SCRIPT_NAME}_console.log
else
    echo "Chave 'consolefile' não encontrada no arquivo ${pathbin}/appserver.ini."
fi

if [ -n "${pathbin}/appserver.ini" ]; then
    cp -p ${pathbin}/appserver.ini /tmp/${SCRIPT_NAME}_appserver.ini
else
    echo "O appserver não foi localizado."
fi

zip_file="/tmp/${SCRIPT_NAME}_export.zip"
cd /tmp
zip -r "$zip_file" "${SCRIPT_NAME}_describe.txt" "${SCRIPT_NAME}_console.log" "${SCRIPT_NAME}_appserver.ini" "${SCRIPT_NAME}_library.txt"

if [ -f "$zip_file" ]; then
    echo -e "Pacote criado com sucesso: ${green} $zip_file ${reset}"
else
    echo -e "${red}$ Erro ao criar o pacote .zip ${reset}"
fi
rm -f /tmp/${SCRIPT_NAME}_describe.txt /tmp/${SCRIPT_NAME}_console.log /tmp/${SCRIPT_NAME}_appserver.ini /tmp/${SCRIPT_NAME}_library.txt

}

SCRIPT_NAME=$(basename "$0")

## Show_help: Mensagem de ajuda para usar este script.
show_help() {
    cat << EOF
Usage: ${SCRIPT_NAME} {start|stop|kill|restart|status|describe|export|log}

Gerenciamento de serviços permite iniciar, parar, reiniciar, matar, verificar o status, exibir informações. 
Use as opções start|stop|kill|restart|status|describe|export|log para realizar operações comuns de serviço com facilidade.

  start     : Inicia o serviço.
  stop      : Encerra o serviço.
  kill      : Encerra o serviço de forma abrupta.
  restart   : Reinicia o serviço.
  status    : Exibe os detalhes do serviço em formato de tabela.
  describe  : Exibe os detalhes do serviço e configurações.
  export    : Exporta as informações do describe junto com o appserver.ini e console.log para 
              o arquivo ${SCRIPT_NAME}.zip em /tmp.
  log       : Exibe o log com o comando tail -f.

EOF
}

#MAIN
case "$1" in
start)
    start_service 2>/dev/null
    ;;
stop)
    stop_service
    ;;
kill)
    kill_service
    ;;
restart)
    stop_service
    sleep 1
    start_service 2>/dev/null
    sleep 1
    status
    exit $?
    ;;
status)
    if [ ! -z `pidof -x $progbin` ] ; then
       status
    else
        echo -e "Status process: ${red} [ Stoppe ] ${reset} "
        echo -e "${red}- Program $prog is not running! ${reset}"
    fi
    ;;
describe)
    describe
    ;;
log)
    tail_log
    ;;
export)
    export_service
    ;;
*)
    show_help
    exit 1
esac

exit 0
Bloco de código
languagebash
titletotvsappbroker
collapsetrue
#!/bin/bash
#description: Starts and stops

#########################################
#	CONFIGURACAO DO SERVICO		#
#########################################
#Inserir o nome do executavel 
prog="appsrvlinux_broker"

## Configuração do tipo de balance:
    # broker_type="balance_smart_client_desktop"
    # broker_type="balance_http"
    # broker_type="balance_telnet"
    # broker_type="balance_web_services"

broker_type="balance_smart_client_desktop"

#Inserir o caminho do diretorio do executavel
pathbin="/totvs/protheus/bin/protheus_broker"

alias=$(basename "${pathbin}")

progbin="${pathbin}/${prog}"
pidfile="/var/run/${alias}.pid"
lockfile="/var/lock/subsys/${alias}"

log_filename=console.log
#O appserver.ini do broker dever ter o mesmo nome do executável.
config_filename=${prog}
#################################################################
#Configuracao de ULIMIT
#################################################################
#open files - (-n)
openFiles=65536
#stack size - (kbytes, -s)
stackSize=1024
#core file size - (blocks, -c)
coreFileSize=unlimited
#file size - (blocks, -f)
fileSize=unlimited
#cpu time - (seconds, -t)
cpuTime=unlimited
#virtual memory - (-v)
virtualMemory=unlimited

#################################
#	FIM DA CONFIGURACAO	#
#################################

RETVAL=0

## Verifica se o executavel tem permissao correta e se esta acessivel
test -x $progbin || { echo "$progbin not installed";
        if [ "$1" = "stop" ]; then exit 0;
        else exit 5; fi; }

#Prepara as ulimit para o servico do DBAccess
ulimit -n ${openFiles}
ulimit -s ${stackSize}
ulimit -c ${coreFileSize}
ulimit -f ${fileSize}
ulimit -t ${cpuTime}
ulimit -v ${virtualMemory}

#Acessa o diretorio configurado na variavel PATHBIN
cd $pathbin

#Variaveis de Output
red="\033[31m"
green='\033[32m'
reset='\033[m'

export LD_LIBRARY_PATH=${pathbin}

## Start_service: função que inicia o serviço.
start_service() {

if [ -z `pidof -x $progbin` ] ; then
   echo "Starting $prog... "
   ${progbin} -daemon -${broker_type} -a >/dev/null &
   RETVAL=$?
   if [ ${RETVAL} -eq 0 ]; then
      touch ${lockfile}
      touch ${pidfile}
      pidof -x ${progbin} > ${pidfile}
      sleep 1
      echo "PID : " `cat ${pidfile}`
      echo -e "${prog} running :   ${green}[ OK ]${reset}"
   else
      echo -e "Failed to start ${prog} :         ${red}[ Failure ]${reset}"
   fi 
   echo
else
   echo -e "$prog is ${green}Started${reset} pid `pidof -x $progbin`"
fi
}

## Stop_service: função que encerra o serviço.
stop_service() {
if [ ! -z `pidof -x ${progbin}` ] ; then

   ./${progbin} -${broker_type} -o

   echo
   rm -f $lockfile
   rm -f $pidfile
   echo -n "Stopping ${prog}."
   while [ ! -z `pidof -x ${progbin}` ]
   do
        echo -n "."
        sleep 1
   done
   echo
   echo -e "${prog} is Stopped     ${red}[ Stopped ]${reset}"
else
   echo -e "${prog} is not running ${red}[ Stopped ]${reset}"
fi
}

## Kill_service: função que interrompe o serviço.
kill_service() {
if [ ! -z `pidof -x ${progbin}` ] ; then

   kill -s SIGKILL $(pidof -x ${progbin})

   echo
   rm -f $lockfile
   rm -f $pidfile
   echo -n "Stopping ${prog}."
   while [ ! -z `pidof -x ${progbin}` ]
   do
        echo -n "."
        sleep 1
   done
   echo
   echo -e "${prog} is Killed     ${red}[ Killed ]${reset}"
else
   echo -e "${prog} is not running ${red}[ Stopped ]${reset}"
fi
}

## get_stats: função que coleta os dados do serviço e exporta no contexto atual.
get_stats() {
date 
echo
if [ ! -z `pidof -x ${progbin}` ] ; then
    export pid=$(pidof -x ${progbin})

    export progport=$(lsof -Pp ${pid} | grep '(LISTEN)' | awk '{ print $9}' | cut -d: -f2 | xargs | tr ' ' ',')

    export list=$(ps -eo pid,start_time,cputime,pcpu,pmem,stat,size,nlwp,comm | grep ${pid})

    export start_time=$(echo -e $list | awk '{ print $2 }')
    export cputime=$(echo -e $list | awk '{ print $3 }')
    export pcpu=$(echo -e $list | awk '{ print $4 }')
    export pmem=$(echo -e $list | awk '{ print $5 }')
    export stat=$(echo -e $list | awk '{ print $6 }')
    export size=$(echo -e $list | awk '{ print $7 }')
    export nlwp=$(echo -e $list | awk '{ print $8 }')
    export comm=$(echo -e $list | awk '{ print $9 }')

    export size=$(echo -e "$(bc <<< "scale=2;$size/1024")MB")
else
    echo -e "Status process: ${red} [ Stopped ] ${reset} "
    echo -e "${red}- Program $prog is not running! ${reset}"
fi
}

## Status: função que exibe o estado atual do serviço em formato de tabela.
status() {
get_stats

output=$(cat << EOF
ALIAS PROCESS PORT PID CPU_TIME %CPU %MEM MEMORY THREADS STATUS PATH
${alias} ${comm} ${progport} ${pid} ${cputime} ${pcpu} ${pmem} ${size} ${nlwp} ${green}[running]${reset} ${progbin} 
EOF
)

echo -e "$output" | column -t
}

get_log() {
    consolelog=$(grep -i '^\s*consolefile\s*=' "${pathbin}/${config_filename}" | awk -F= '{print $2}' | tr -d ' ')
    if [ ! -n "$consolelog" ]; then
        if [ -n "${pathbin}/${log_filename}" ]; then
            consolelog="${pathbin}/${log_filename}"
        else
            echo '${red}Logfile not found!${reset} : "${pathbin}/${log_filename}"'
            echo 'Config File: ${pathbin}/${config_filename}'
            echo 'Add parameter: consolefile=${pathbin}/${log_filename}'
        fi
    fi
    echo ${consolelog}
}

## Describe: função que exibe as configurações do ambiente onde o servico está rodando.
describe() {
get_stats

## Exibe o status atual do serviço caso ele esteja em execução.
if [ ! -z `pidof -x ${progbin}` ] ; then
    output=$(cat << EOF
AlIAS ${alias}
PROCESS ${comm}
PATH ${progbin}
PORT ${progport}
PID ${pid}
STARTED ${start_time}
TIME ${cputime}
%CPU ${pcpu}
%MEM ${pmem}
MEMORY ${size}
STATUS [Running]
THREADS ${nlwp}
EOF
)
echo -e "$output" | column -t
echo
fi

## Exibe as bibliotecas utilizadas pelo serviço.
echo "### LIBRARY ####"
ldd ${progbin}
echo ""

## Exibe o appserver.ini completo quando localizado.
echo "### INI ###"
if [ -n "${pathbin}/${config_filename}" ]; then
    echo ""
    echo -e "${config_filename} : ${green} ${pathbin}/${config_filename} ${reset}"
    echo ""
    cat ${pathbin}/${config_filename}
else
    echo "O appserver não foi localizado."
fi
echo ""

## Exibe as 15 primeiras linhas e as 15 ultimas linhas do logfile.
echo "### LOGFILE ###"
consolelog=$(get_log)

if [ -n "$consolelog" ]; then
    echo ""
    echo -e "console.log : ${green} ${consolelog} ${reset}"
    echo ""
    head -n 15 "$consolelog"
    echo ...
    tail -n 15 "$consolelog"
else
    echo "Chave 'consolefile' não encontrada no arquivo ${pathbin}/${config_filename}."
fi

}

## Tail_log: Executa o comando tail -f no arquivo de log do serviço.
tail_log() {
consolelog=$(get_log)

if [ -n "$consolelog" ]; then
    echo ""
    echo -e "console.log : ${green}$consolelog${reset}"
    echo ""
    head -n 15 "$consolelog"
    echo ...
    tail -f -n 15 "$consolelog"
else
    echo "Chave 'consolefile' não encontrada no arquivo ${pathbin}/${config_filename}."
fi
}

## Export_service: Exporta as configurações do ambiente onde o serviço sendo executado junto com o logfile.
export_service() {

describe > /tmp/${SCRIPT_NAME}_describe.txt

ldd -v ${progbin} > /tmp/${SCRIPT_NAME}_library.txt

consolelog=$(get_log)
if [ -n "$consolelog" ]; then
    cp -p $consolelog /tmp/${SCRIPT_NAME}_console.log
else
    echo "Chave 'consolefile' não encontrada no arquivo ${pathbin}/${config_filename}."
fi

if [ -n "${pathbin}/${config_filename}" ]; then
    cp -p ${pathbin}/${config_filename} /tmp/${SCRIPT_NAME}_${config_filename}
else
    echo "O appserver não foi localizado."
fi

zip_file="/tmp/${SCRIPT_NAME}_export.zip"
cd /tmp
zip -r "$zip_file" "${SCRIPT_NAME}_describe.txt" "${SCRIPT_NAME}_console.log" "${SCRIPT_NAME}_${config_filename}" "${SCRIPT_NAME}_library.txt"

if [ -f "$zip_file" ]; then
    echo -e "Pacote criado com sucesso: ${green} $zip_file ${reset}"
else
    echo -e "${red}$ Erro ao criar o pacote .zip ${reset}"
fi
rm -f /tmp/${SCRIPT_NAME}_describe.txt /tmp/${SCRIPT_NAME}_console.log /tmp/${SCRIPT_NAME}_${config_filename} /tmp/${SCRIPT_NAME}_library.txt

}

SCRIPT_NAME=$(basename "$0")

## Link: cria o link simbolico com o nome do serviço configurado neste script e 
## renomeia o appserver.ini para o mesmo nome do programa configurado. Configuração necessária apenas para o serviço do broker.
link() {
if [ -e $progbin ] ; then
   echo "Appserver symbolic link "
   echo
else
   ln -s ${pathbin}/appsrvlinux $progbin
   echo "$progbin created symbolic link"
   cp -p ${pathbin}/appserver.ini $progbin.ini
   echo "Copy ${pathbin}/appserver.ini to ${progbin}.ini"
fi
}

## Show_help: Mensagem de ajuda para usar este script.
show_help() {
    cat << EOF
Usage: ${SCRIPT_NAME} {start|stop|kill|restart|status|describe|export|log}

Gerenciamento de serviços permite iniciar, parar, reiniciar, matar, verificar o status, exibir informações. 
Use as opções start|stop|kill|restart|status|describe|export|log para realizar operações comuns de serviço com facilidade.

  start     : Inicia o serviço.
  stop      : Encerra o serviço.
  kill      : Encerra o serviço de forma abrupta.
  restart   : Reinicia o serviço.
  status    : Exibe os detalhes do serviço em formato de tabela.
  describe  : Exibe os detalhes do serviço e configurações.
  export    : Exporta as informações do describe junto com o ${config_filename} e console.log para 
              o arquivo ${SCRIPT_NAME}.zip em /tmp.
  log       : Exibe o log com o comando tail -f.

EOF
}

#MAIN
case "$1" in
start)
    start_service 2>/dev/null
    ;;
stop)
    stop_service
    ;;
kill)
    kill_service
    ;;
restart)
    stop_service
    sleep 1
    start_service 2>/dev/null
    sleep 1
    status
    exit $?
    ;;
status)
    if [ ! -z `pidof -x $progbin` ] ; then
       status
    else
        echo -e "Status process: ${red} [ Stoppe ] ${reset} "
        echo -e "${red}- Program $prog is not running! ${reset}"
    fi
    ;;
describe)
    describe
    ;;
log)
    tail_log
    ;;
link)
    link
    ;;
export)
    export_service
    ;;
*)
    show_help
    exit 1
esac

exit 0
Bloco de código
languagebash
titletotvslicensesrv
collapsetrue
#!/bin/bash
# description: Este script é usado para gerenciar serviços do Protheus, permitindo 
# iniciar, parar, reiniciar, matar, verificar o status, exibir informações detalhadas, 
# exportar logs e configurações, e monitorar logs em tempo real. 
# Use as opções start, stop, kill, restart, status, describe, export, ou log para realizar 
# operações comuns de serviço de maneira fácil e eficiente.

#########################################
#	CONFIGURACAO DO SERVICO		#
#########################################
#Inserir o nome do executavel 
prog="appsrvlinux"

#Inserir o caminho do diretorio do executavel
pathbin="/totvs/licenseserver/bin/appserver"

alias=$(basename $(dirname $(dirname ${pathbin})))

progbin="${pathbin}/${prog}"
pidfile="/var/run/${alias}.pid"
lockfile="/var/lock/subsys/${alias}"

config_filename=appserver.ini
log_filename=console.log
#################################################################
#Configuracao de ULIMIT
#################################################################
#open files - (-n)
openFiles=65536
#stack size - (kbytes, -s)
stackSize=1024
#core file size - (blocks, -c)
coreFileSize=unlimited
#file size - (blocks, -f)
fileSize=unlimited
#cpu time - (seconds, -t)
cpuTime=unlimited
#virtual memory - (-v)
virtualMemory=unlimited

#################################
#	FIM DA CONFIGURACAO	#
#################################

RETVAL=0

## Verifica se o executavel tem permissao correta e se esta acessivel
test -x $progbin || { echo "$progbin not installed";
        if [ "$1" = "stop" ]; then exit 0;
        else exit 5; fi; }

#Prepara as ulimit para o servico do DBAccess
ulimit -n ${openFiles}
ulimit -s ${stackSize}
ulimit -c ${coreFileSize}
ulimit -f ${fileSize}
ulimit -t ${cpuTime}
ulimit -v ${virtualMemory}

#Acessa o diretorio configurado na variavel PATHBIN
cd $pathbin

#Variaveis de Output
red="\033[31m"
green='\033[32m'
reset='\033[m'

export LD_LIBRARY_PATH=${pathbin}

## Start_service: função que inicia o serviço.
start_service() {

if [ -z `pidof -x $progbin` ] ; then
   echo "Starting $prog... "
    ${progbin} -daemon >/dev/null &
   RETVAL=$?
   if [ ${RETVAL} -eq 0 ]; then
      touch ${lockfile}
      touch ${pidfile}
      pidof -x ${progbin} > ${pidfile}
      sleep 1
      echo "PID : " `cat ${pidfile}`
      echo -e "${prog} running :   ${green}[ OK ]${reset}"
   else
      echo -e "Failed to start ${prog} :         ${red}[ Failure ]${reset}"
   fi 
   echo
else
   echo -e "$prog is ${green}Started${reset} pid `pidof -x $progbin`"
fi
}

## Stop_service: função que encerra o serviço.
stop_service() {
if [ ! -z `pidof -x ${progbin}` ] ; then

   kill -s SIGTERM $(pidof -x ${progbin})

   echo
   rm -f $lockfile
   rm -f $pidfile
   echo -n "Stopping ${prog}."
   while [ ! -z `pidof -x ${progbin}` ]
   do
        echo -n "."
        sleep 1
   done
   echo
   echo -e "${prog} is Stopped     ${red}[ Stopped ]${reset}"
else
   echo -e "${prog} is not running ${red}[ Stopped ]${reset}"
fi
}

## Kill_service: função que interrompe o serviço.
kill_service() {
if [ ! -z `pidof -x ${progbin}` ] ; then

   kill -s SIGKILL $(pidof -x ${progbin})

   echo
   rm -f $lockfile
   rm -f $pidfile
   echo -n "Stopping ${prog}."
   while [ ! -z `pidof -x ${progbin}` ]
   do
        echo -n "."
        sleep 1
   done
   echo
   echo -e "${prog} is Killed     ${red}[ Killed ]${reset}"
else
   echo -e "${prog} is not running ${red}[ Stopped ]${reset}"
fi
}

## get_stats: função que coleta os dados do serviço e exporta no contexto atual.
get_stats() {
date 
echo
if [ ! -z `pidof -x ${progbin}` ] ; then
    export pid=$(pidof -x ${progbin})

    export progport=$(lsof -Pp ${pid} | grep '(LISTEN)' | awk '{ print $9}' | cut -d: -f2 | xargs | tr ' ' ',')

    export list=$(ps -eo pid,start_time,cputime,pcpu,pmem,stat,size,nlwp,comm | grep ${pid})

    export start_time=$(echo -e $list | awk '{ print $2 }')
    export cputime=$(echo -e $list | awk '{ print $3 }')
    export pcpu=$(echo -e $list | awk '{ print $4 }')
    export pmem=$(echo -e $list | awk '{ print $5 }')
    export stat=$(echo -e $list | awk '{ print $6 }')
    export size=$(echo -e $list | awk '{ print $7 }')
    export nlwp=$(echo -e $list | awk '{ print $8 }')
    export comm=$(echo -e $list | awk '{ print $9 }')

    export size=$(echo -e "$(bc <<< "scale=2;$size/1024")MB")
else
    echo -e "Status process: ${red} [ Stopped ] ${reset} "
    echo -e "${red}- Program $prog is not running! ${reset}"
fi
}

## Status: função que exibe o estado atual do serviço em formato de tabela.
status() {
get_stats

output=$(cat << EOF
ALIAS PROCESS PORT PID CPU_TIME %CPU %MEM MEMORY THREADS STATUS PATH
${alias} ${comm} ${progport} ${pid} ${cputime} ${pcpu} ${pmem} ${size} ${nlwp} ${green}[running]${reset} ${progbin} 
EOF
)

echo -e "$output" | column -t
}

get_log() {
    consolelog=$(grep -i '^\s*consolefile\s*=' "${pathbin}/${config_filename}" | awk -F= '{print $2}' | tr -d ' ')
    if [ ! -n "$consolelog" ]; then
        if [ -n "${pathbin}/${log_filename}" ]; then
            consolelog="${pathbin}/${log_filename}"
        else
            echo '${red}Logfile not found!${reset} : "${pathbin}/${log_filename}"'
            echo 'Config File: ${pathbin}/${config_filename}'
            echo 'Add parameter: consolefile=${pathbin}/${log_filename}'
        fi
    fi
    echo ${consolelog}
}

## Describe: função que exibe as configurações do ambiente onde o servico está rodando.
describe() {
get_stats

## Exibe o status atual do serviço caso ele esteja em execução.
if [ ! -z `pidof -x ${progbin}` ] ; then
    output=$(cat << EOF
AlIAS ${alias}
PROCESS ${comm}
PATH ${progbin}
PORT ${progport}
PID ${pid}
STARTED ${start_time}
TIME ${cputime}
%CPU ${pcpu}
%MEM ${pmem}
MEMORY ${size}
STATUS [Running]
THREADS ${nlwp}
EOF
)
echo -e "$output" | column -t
echo
fi

## Exibe as bibliotecas utilizadas pelo serviço.
echo "### LIBRARY ####"
ldd ${progbin}
echo ""

## Exibe o appserver.ini completo quando localizado.
echo "### INI ###"
if [ -n "${pathbin}/${config_filename}" ]; then
    echo ""
    echo -e "${config_filename} : ${green} ${pathbin}/${config_filename} ${reset}"
    echo ""
    cat ${pathbin}/${config_filename}
else
    echo "O appserver não foi localizado."
fi
echo ""

## Exibe as 15 primeiras linhas e as 15 ultimas linhas do logfile.
echo "### LOGFILE ###"
consolelog=$(get_log)

if [ -n "$consolelog" ]; then
    echo ""
    echo -e "console.log : ${green} ${consolelog} ${reset}"
    echo ""
    head -n 15 "$consolelog"
    echo ...
    tail -n 15 "$consolelog"
else
    echo "Chave 'consolefile' não encontrada no arquivo ${pathbin}/${config_filename}."
fi

}

## Tail_log: Executa o comando tail -f no arquivo de log do serviço.
tail_log() {
consolelog=$(get_log)

if [ -n "$consolelog" ]; then
    echo ""
    echo -e "console.log : ${green}$consolelog${reset}"
    echo ""
    head -n 15 "$consolelog"
    echo ...
    tail -f -n 15 "$consolelog"
else
    echo "Chave 'consolefile' não encontrada no arquivo ${pathbin}/${config_filename}."
fi
}

## Export_service: Exporta as configurações do ambiente onde o serviço sendo executado junto com o logfile.
export_service() {

describe > /tmp/${SCRIPT_NAME}_describe.txt

ldd -v ${progbin} > /tmp/${SCRIPT_NAME}_library.txt

consolelog=$(get_log)
if [ -n "$consolelog" ]; then
    cp -p $consolelog /tmp/${SCRIPT_NAME}_console.log
else
    echo "Chave 'consolefile' não encontrada no arquivo ${pathbin}/${config_filename}."
fi

if [ -n "${pathbin}/${config_filename}" ]; then
    cp -p ${pathbin}/${config_filename} /tmp/${SCRIPT_NAME}_${config_filename}
else
    echo "O appserver não foi localizado."
fi

zip_file="/tmp/${SCRIPT_NAME}_export.zip"
cd /tmp
zip -r "$zip_file" "${SCRIPT_NAME}_describe.txt" "${SCRIPT_NAME}_console.log" "${SCRIPT_NAME}_${config_filename}" "${SCRIPT_NAME}_library.txt"

if [ -f "$zip_file" ]; then
    echo -e "Pacote criado com sucesso: ${green} $zip_file ${reset}"
else
    echo -e "${red}$ Erro ao criar o pacote .zip ${reset}"
fi
rm -f /tmp/${SCRIPT_NAME}_describe.txt /tmp/${SCRIPT_NAME}_console.log /tmp/${SCRIPT_NAME}_${config_filename} /tmp/${SCRIPT_NAME}_library.txt

}

SCRIPT_NAME=$(basename "$0")

## Show_help: Mensagem de ajuda para usar este script.
show_help() {
    cat << EOF
Usage: ${SCRIPT_NAME} {start|stop|kill|restart|status|describe|export|log}

Gerenciamento de serviços permite iniciar, parar, reiniciar, matar, verificar o status, exibir informações. 
Use as opções start|stop|kill|restart|status|describe|export|log para realizar operações comuns de serviço com facilidade.

  start     : Inicia o serviço.
  stop      : Encerra o serviço.
  kill      : Encerra o serviço de forma abrupta.
  restart   : Reinicia o serviço.
  status    : Exibe os detalhes do serviço em formato de tabela.
  describe  : Exibe os detalhes do serviço e configurações.
  export    : Exporta as informações do describe junto com o appserver.ini e console.log para 
              o arquivo ${SCRIPT_NAME}.zip em /tmp.
  log       : Exibe o log com o comando tail -f.

EOF
}

#MAIN
case "$1" in
start)
    start_service 2>/dev/null
    ;;
stop)
    stop_service
    ;;
kill)
    kill_service
    ;;
restart)
    stop_service
    sleep 1
    start_service 2>/dev/null
    sleep 1
    status
    exit $?
    ;;
status)
    if [ ! -z `pidof -x $progbin` ] ; then
       status
    else
        echo -e "Status process: ${red} [ Stoppe ] ${reset} "
        echo -e "${red}- Program $prog is not running! ${reset}"
    fi
    ;;
describe)
    describe
    ;;
log)
    tail_log
    ;;
export)
    export_service
    ;;
*)
    show_help
    exit 1
esac

exit 0
Nota

Os scripts precisam ter permissão para executar os serviços. Para iniciá-los, demos as seguintes permissões:

[root@tpsrv01 init.d]# chmod

...

+x totvs*

Informações
titleObservação

Os scripts de iniciar os serviços foram criados pela engenharia Engenharia e homologados no cenário do teste sistêmico, onde os testes foram realizados no Linux

Utilizando os scripts

Os serviços tem a seguinte ordem de inicialização:

01 - LockServer (totvsapplocksrv)02 - License Server (totvsapplicensesrv)

03 02 - Dbaccess (totvsdbaccess)

04 03 - Slaves Secundários (totvsappslv01 totvsappsec01 e totvsappslv02totvsappsec02)

05 04 - Balance Broker (totvsappbalancetotvsappbroker)


Informações
title

Start

...

Observação
Para executar os scripts, acesse o diretório /etc/init.d.


Abaixo, está a relação dos comandos para iniciar, parar e consultar a situação dos serviços:

Comandos para iniciar serviços (start)

./totvsapplocksrv  start

...

./totvsapplicensesrv start

...

./totvsdbaccess start

...

./

...

totvsappbroker start

[root@tpsrv01 init.d]# ./totvsappslv01 start

[root@tpsrv01 init.d]# ./totvsappslv02 start

Stop

...

./totvsappsec01 start

./totvsappsec02 start

Comandos para parar serviços (stop)

./totvsapplocksrv  stop

...

./totvsapplicensesrv stop

...

./totvsdbaccess stop

...

./

...

totvsappbroker stop

...

./

...

totvsappsec01 stop

...

./

...

totvsappsec02 stop

Status

[root@tpsrv01 init.d]# ./totvsapplocksrv  status

[root@tpsrv01 init.d]# ./totvsapplicensesrv status

[root@tpsrv01 init.d]# ./totvsdbaccess status

[root@tpsrv01 init.d]# ./totvsappbalance status

[root@tpsrv01 init.d]# ./totvsappslv01 status

...

Comandos para verificar o status dos serviços (status)

./totvsappsec02 status

./totvsappsec01 status

./totvsappbroker status

./totvsdbaccess status

./totvsapplicensesrv status

./totvsapplocksrv  status