Last active
February 15, 2024 16:53
-
-
Save edufolly/113c3ad24d033a07692e84da388eddb0 to your computer and use it in GitHub Desktop.
Configurar Host Flashman Docker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
#Configura host para execução do Flashman via Docker | |
VERSAO=2024021501 | |
#2024021501 - Atualizado o portainer agent para 2.19.4 | |
#2023112601 - Adicionando parametro de use-vc para uso de TCP em resolucoes de DNS no host | |
#2023082401 - Adicionando trecho para silenciamento dos logs de erro do docker | |
#2023072105 - Movendo o trecho que habilita o ufw para antes de bloquear as portas [5]7547. o comando de deny retorna erro quando ufw está disabled | |
#2023072104 - Consertando if que checa se rede ingress já existe | |
#2023072103 - Na hora de instalar o plugin loki, verifica antes se já foi instalado | |
#2023072102 - Na hora de criar cada uma das redes docker necessárias, verifica se a mesma já existe | |
#2023072101 - Na hora de checar se docker existe, checa também se o comando "docker" existe, além de só testar se o arquivo DOCKER_SOURCELIST existe | |
#2023062601 - Adicionando "--yes" no comando gpg quando instalando chaves para repositório do docker (evita pergunta de confirmação) | |
#2023030601 - Inserindo variavel para pular a verificacao de IP local com IP resolvido pelo DNS | |
#2023030302 - Liberando porta 9001 apenas para IP do portainer | |
#2023030301 - Removendo diretiva root no crontab. Estava errado | |
#2023030201 - Atualizado o portainer agent para 2.17.1 | |
#2023030101 - Inserido pacote "host" no apt | |
#2023020701 - Inserindo verificação de IP e dominio informados | |
#2023012701 - Melhorando comando para coletar IP de interface default atraves de comando route. Ajuste na espera de input por expect. | |
#2023011801 - Incluindo entrada no crontab para limpeza de imagem e conteineres | |
#2023011201 - Acertando setup docker de swarm init | |
#2023010201 - incluindo ubuntu 22.04 | |
#202212802 - inclusao de logica para pular etapas que a estao configuradas | |
#202212801 - inclusao de opcao para liberar portas do CWMP. Portas do CWMP ficam | |
# bloqueadas por padrao na primeira configuracao | |
#2022122201 - primeira VERSAO | |
aTRUE=0 | |
aFALSE=1 | |
LOG=$HOME/$(basename $0).log | |
ARQ_RESP="/tmp/$(basename "$0").resp" | |
LOCK_FILE="/tmp/$(basename "$0").pid" | |
#Arquivos que devem ser apagados ao usar aErrorExit ou aExit | |
DELETE_FILES="$ARQ_RESP $LOCK_FILE" | |
RE_NUM='^[0-9]+$' | |
RE_CLOUD='.anlix.io' | |
DOCKER_SOURCELIST="/etc/apt/sources.list.d/docker.list" | |
DO_IP_VERIFICATION="true" | |
#Funcoes | |
aInitLog(){ | |
if [ "$LOG" = '' ]; then | |
aErrorExit -t "[$0 ERRO] Variavel LOG vazia." | |
else | |
mkdir -p "$(dirname "$LOG")" || aErrorExit -t "[$0 ERRO] Nao foi possivel criar diretorio de log $(dirname "$LOG")" | |
if [ "$1" = "--new" ]; then | |
echo > $LOG | |
else | |
touch $LOG | |
fi | |
[ $? != $aTRUE ] && aErrorExit -t "[$0 ERRO] Nao foi possivel criar arquivo de log $LOG" | |
fi | |
} | |
aPrint(){ | |
if [ $# != 2 ]; then | |
cat <<EOF | |
aPrint <-t|-l|-b|-tn|-ln|-bn> "<msg>" | |
onde | |
-t : imprime <msg> na tela | |
-l : imprime <msg> no log (arquivo indicado na variavel LOG) | |
-b : imprime <msg> na tela e no log | |
-tn : imprime <msg> na tela sem incluir quebra de linha | |
-ln :imprime <msg> no log sem incluir quebra de linha | |
-bn: imprime <msg> na tela e no log sem incluir quebra de linha | |
EOF | |
else | |
case "$1" in | |
-t) echo -e "$2" ;; | |
-tn) echo -e -n "$2" ;; | |
-l) [ -w $LOG ] && echo -e "$2" >> $LOG || echo "$LOG nao existe, executou aInitLog antes?";; | |
-ln) [ -w $LOG ] && echo -e -n "$2" >> $LOG || echo "$LOG nao existe, executou aInitLog antes?";; | |
-b) [ -w $LOG ] && echo -e "$2" | tee -a $LOG || echo "$LOG nao existe, executou aInitLog antes?";; | |
-bn) [ -w $LOG ] && echo -e -n "$2" | tee -a $LOG || echo "$LOG nao existe, executou aInitLog antes?";; | |
esac | |
fi | |
} | |
aExit(){ | |
STATUS=0 | |
for file in $DELETE_FILES; do | |
[ -f $file ] && rm -f $file | |
done | |
if [ $# = 1 ]; then | |
STATUS=$1 | |
fi | |
exit $STATUS | |
} | |
aErrorExit(){ | |
if [ $# != 2 ]; then | |
cat <<EOF | |
aErrorExit <-t|-l|-b> "<msg>" | |
onde | |
-t : imprime <msg> na tela | |
-l : imprime <msg> no log (arquivo indicado na variavel LOG) | |
-b : imprime <msg> na tela e no log | |
EOF | |
else | |
aPrint "$1" "$2" | |
aPrint -l "FIM|$(date "+%Y%m%dT%H:%M%S")" | |
fi | |
for file in $DELETE_FILES; do | |
[ -f $file ] && rm -f $file | |
done | |
exit $aFALSE | |
} | |
showHelp() { | |
cat << EOF | |
Como usar: | |
$0 | |
Modo interativo, vai pedir os parametros um a um, ou | |
$0 -a uninstall | |
$0 -a unblock-cwmp-ports | |
Para desinstalar o ambiente flashman para docker, ou | |
$0 <-a|--acao> <acao>" | |
Onde: | |
<acao>: por enquanto apenas | |
full - prepara o host para o flashman atraves do Docker | |
Exemplo: | |
$0 -a full | |
EOF | |
} | |
aptupdate(){ | |
aPrint -bn "Atualizando lista de pacotes disponiveis ... " | |
if sudo apt-get update >> $LOG 2>&1; then | |
aPrint -b "OK" | |
else | |
aErrorExit -b "[$0 ERRO] ao tentar atualizar lista de pacotes, ver $LOG" | |
fi | |
} | |
aptinstall(){ | |
export DEBIAN_FRONTEND=noninteractive | |
echo -n "Instalando $@ ... " | tee -a $LOG | |
#FIXME: porque isso não funciona? da erro como se nao tivesse passado parametro para o aPrint: aPrint -b "Instalando $@ ... " | |
if sudo apt-get install -y $@ >> $LOG 2>&1; then | |
aPrint -b "OK" | |
else | |
echo -n "[$0 ERRO] ao tentar instalar $@, ver $LOG" | tee -a $LOG | |
aExit 1 | |
fi | |
} | |
aptpurge(){ | |
echo -n "Removendo completamente $@ ... " | tee -a $LOG | |
if sudo apt-get purge -y $@ >> $LOG 2>&1; then | |
aPrint -b "OK" | |
else | |
echo -n "[$0 ERRO] ao tentar remover completamente $@, ver $LOG" | tee -a $LOG | |
fi | |
} | |
sctlenable(){ | |
aPrint -bn "Habilitando $1 ... " | |
if sudo systemctl enable $1 >> $LOG 2>&1; then | |
aPrint -b "OK" | |
else | |
aErrorExit -b "[$0 ERRO] ao tentar habilitar $1, ver o log em $LOG" | |
fi | |
} | |
sctlstart(){ | |
aPrint -bn "Iniciando $1 ... " | |
if sudo systemctl start $1 >> $LOG 2>&1; then | |
if sudo systemctl -q is-active $1; then | |
aPrint -b "OK" | |
else | |
aErrorExit -b "[$0 ERRO] ao tentar iniciar $1, para mais detalhes execute:\njournalctl -u $1" | |
fi | |
else | |
aErrorExit -b "[$0 ERRO] ao tentar iniciar $1, para mais detalhes execute:\njournalctl -u $1" | |
fi | |
} | |
sctlstop(){ | |
aPrint -bn "Parando $1 ... " | |
if sudo systemctl stop $1 >> $LOG 2>&1; then | |
if sudo systemctl -q is-active $1; then | |
aErrorExit -b "[$0 ERRO] ao tentar parar $1, verificar manualmente" | |
else | |
aPrint -b "OK" | |
fi | |
else | |
aErrorExit -b "[$0 ERRO] ao tentar parar $1, verificar manualmente" | |
fi | |
} | |
sctlreload(){ | |
aPrint -bn "Iniciando $1 ... " | |
if sudo systemctl reload $1 >> $LOG 2>&1; then | |
if sudo systemctl -q is-active $1; then | |
aPrint -b "OK" | |
else | |
aErrorExit -b "[$0 ERRO] ao tentar recarregar configuracao de $1, para mais detalhes execute:\njournalctl -u $1" | |
fi | |
else | |
aErrorExit -b "[$0 ERRO] ao tentar recarregar configuracao de $1, para mais detalhes execute:\njournalctl -u $1" | |
fi | |
} | |
sctlrestart(){ | |
aPrint -bn "Reiniciando $1 ... " | |
if sudo systemctl restart $1 >> $LOG 2>&1; then | |
if sudo systemctl -q is-active $1; then | |
aPrint -b "OK" | |
else | |
aErrorExit -b "[$0 ERRO] ao tentar recarregar $1, para mais detalhes execute:\njournalctl -u $1" | |
fi | |
else | |
aErrorExit -b "[$0 ERRO] ao tentar recarregar $1, para mais detalhes execute:\njournalctl -u $1" | |
fi | |
} | |
getParams(){ | |
options=$(getopt -l "help,acao:,cfqdn:,lfqdn:,porta:,mqtts:,senha:,pularip:" -- "ha:c:l:p:m:s:u:" "$@") | |
# set --: | |
# If no arguments follow this option, then the positional parameters are unset. Otherwise, the positional parameters | |
# are set to the arguments, even if some of them begin with a ‘-’. | |
eval set -- "$options" | |
while true; do | |
case $1 in | |
-h|--help) | |
showHelp | |
exit 0 | |
;; | |
-a|--acao) | |
shift | |
ACAO="$1" | |
;; | |
-c|--dominio_nuvem) | |
shift | |
DOMINIO_NUVEM="$1" | |
;; | |
-l|--dominio_empresa) | |
shift | |
DOMINIO_EMPRESA="$1" | |
;; | |
-p|--porta_ssh) | |
shift | |
PORTA_SSH="$1" | |
;; | |
-m|--porta_mqtts) | |
shift | |
MQTTS_PORT="$1" | |
;; | |
-s|--senha_sudo) | |
shift | |
SENHA_SUDO="$1" | |
;; | |
-u|--pular_verificacao_ip) | |
shift | |
DO_IP_VERIFICATION="$1" | |
;; | |
--) | |
shift | |
break | |
;; | |
esac | |
shift | |
done | |
} | |
checkParams(){ | |
if [ -z $ACAO ]; then | |
aErrorExit -b "\n[$0 ERRO] parametro nao informado: acao\n\n$(showHelp)" | |
else | |
ACAO_OK=$aFALSE | |
for ac in full; do | |
if [ $ACAO = $ac ]; then | |
ACAO_OK=$aTRUE | |
break | |
fi | |
done | |
if [ $ACAO_OK = $aFALSE ]; then | |
aErrorExit -b "\n[$0 ERRO] valores invalido ou ainda nao implementado para acao: $ACAO\n\n$(showHelp)" | |
fi | |
fi | |
if [ "$ACAO" = "full" ]; then | |
if [ -z $DOMINIO_NUVEM ]; then | |
aErrorExit -b "\n[$0 ERRO] parametro nao informado: dominio_nuvem\n\n$(showHelp)" | |
else | |
if ! getent ahostsv4 $DOMINIO_NUVEM >/dev/null 2>&1; then | |
aErrorExit -b "\n[$0 ERRO] Nao consegui resolver o dominio: $DOMINIO_NUVEM\nVerifique se o dominio foi cadastrado corretamente e se este servidor esta resolvendo nome\n" | |
fi | |
fi | |
if [ -z $DOMINIO_EMPRESA ]; then | |
aErrorExit -b "\n[$0 ERRO] parametro nao informado: dominio_empresa\n\n$(showHelp)" | |
else | |
if ! getent ahostsv4 $DOMINIO_EMPRESA >/dev/null 2>&1; then | |
aErrorExit -b "\n[$0 ERRO] Nao consegui resolver o dominio: $DOMINIO_EMPRESA\nVerifique se o dominio foi cadastrado corretamente e se este servidor esta resolvendo nome\n" | |
fi | |
fi | |
fi | |
if [ -z $PORTA_SSH ]; then | |
aErrorExit -b "\n[$0 ERRO] parametro nao informado: porta_ssh\n\n$(showHelp)" | |
else | |
re='^[0-9]+$' | |
if ! [[ $PORTA_SSH =~ $re ]]; then | |
aErrorExit -b "\n[$0 ERRO] A porta informada nao e um numero\n" | |
fi | |
fi | |
if [ -z $MQTTS_PORT ]; then | |
aErrorExit -b "\n[$0 ERRO] parametro nao informado: porta_mqtts\n\n$(showHelp)" | |
else | |
re='^[0-9]+$' | |
if ! [[ $MQTTS_PORT =~ $re ]]; then | |
aErrorExit -b "\n[$0 ERRO] A porta informada nao e um numero\n" | |
fi | |
fi | |
} | |
uninstall(){ | |
if [ -f /etc/security/limits.conf-antesFLASHMAN ]; then | |
aPrint -b "Restaurando /etc/security/limits.conf ... " | |
sudo mv /etc/security/limits.conf-antesFLASHMAN /etc/security/limits.conf && aPrint -b "OK" || aPrint -b "FALHOU" | |
fi | |
if [ -f $DOCKER_SOURCELIST ]; then | |
sctlstop docker | |
aptpurge docker-ce docker-ce-cli containerd.io | |
sudo rm -f $DOCKER_SOURCELIST | |
fi | |
aPrint -b "Removendo pacotes desnecessarios ... " | |
sudo apt-get autoremove -y && aPrint -b "OK" || aPrint -b "FALHOU" | |
aPrint -b "Removendo bash history" | |
history -c | |
rm -f ~/.bash_history | |
aPrint -b "OK" | |
aPrint -b "Removendo firewall local (ufw)" | |
sudo aptpurge ufw | |
aPrint -b "Nao esqueca de verificar se alguma porta ficou aberta no firewall.\nPressione ENTER para continuar." | |
read -e R | |
} | |
unblockCwmpPorts(){ | |
aPrint -b "Liberar as portas 7547 57547 no ufw" | |
for porta in 7547 57547; do | |
if sudo ufw allow $porta >> $LOG 2>&1; then | |
aPrint -b "$porta OK" | |
else | |
aErrorExit -b "[$0 ERRO] ao tentar liberar a porta $porta via ufw allow, ver $LOG" | |
fi | |
done | |
} | |
#Inicio script | |
aInitLog | |
FLASHMAN_USER=$(whoami) | |
if ! which sudo > /dev/null; then | |
aErrorExit -b "[$0 ERRO] sudo nao instalado. Por favor instale e configure para que o usuario $FLASHMAN_USER possa usar sudo para executar comandos como root" | |
fi | |
getParams $@ | |
# Teste se sudo necessita de senha | |
SUDO_NECESSITA_SENHA="false" | |
sudo -n true >> /dev/null 2>&1 | |
if [ $? = $aTRUE ]; then | |
aPrint -b "Sudo nao necessita de senha. Continuando..." | |
else | |
aPrint -b "Sudo necessita de senha. Inserindo senha..." | |
SUDO_NECESSITA_SENHA="true" | |
echo "$SENHA_SUDO" | sudo -S date | |
if [ $? = $aTRUE ]; then | |
aPrint -b "Sudo autorizado com sucesso." | |
else | |
aErrorExit -b "[$0 ERRO] Senha para sudo incorreta. Por favor verifique a senha antes de continuar." | |
fi | |
fi | |
if [ "$1" = "-a" ] && [ "$2" = "uninstall" ]; then | |
while | |
echo "A acao de desinstalacao considera que esse servidor tem somente o Flashman instalado." | |
echo "Deseja continuar?[s|n]" | |
read -e R | |
[ "$R" != "s" ] && [ "$R" != "n" ] | |
do | |
continue | |
done | |
if [ "$R" = "s" ]; then | |
uninstall | |
aPrint -b "Ambiente Flashman desinstalado com sucesso." | |
fi | |
aExit $aTRUE | |
fi | |
if [ "$1" = "-a" ] && [ "$2" = "unblock-cwmp-ports" ]; then | |
unblockCwmpPorts | |
aPrint -b "Portas CWMP 7547 e 57547 liberadas com sucesso." | |
aExit $aTRUE | |
fi | |
if [ $# -ne 14 ] && [ "$1" != '-h' ] && [ "$1" != "--help" ]; then | |
aPrint -b "parametros insuficientes" | |
showHelp | |
aErrorExit -l "[ERRO] saindo" | |
fi | |
checkParams | |
aPrint -bn "ACAO: $ACAO " | |
if [ "$ACAO" = "full" ]; then | |
aPrint -b "DOMINIO_NUVEM: $DOMINIO_NUVEM DOMINIO_EMPRESA: $DOMINIO_EMPRESA USUARIO_FLASHMAN: $FLASHMAN_USER HOME_USUARIO: $HOME" | |
fi | |
aPrint -bn "Configurando timezone ..." | |
if sudo timedatectl set-timezone America/Sao_Paulo 2>&1 | tee -a $LOG; then | |
aPrint -b "OK" | |
else | |
aErrorExit -b "[$0 ERRO] ao executar 'timedatectl set-timezone America/Sao_Paulo', ver $LOG" | |
fi | |
aptupdate | |
if ! which lsb_release > /dev/null; then | |
aPrint -b "lsb-release nao instalado, tentando instalar" | |
aptinstall lsb-release | |
fi | |
DISTRO_ID=$(lsb_release -si) | |
DISTRO_RELEASE=$(lsb_release -sr) | |
DISTRO_CODENAME=$(lsb_release -sc) | |
DISTRO_SUPPORTED="Debian 10 Buster, Debian 11 Bullseye, Debian 12 Bookworm, Ubuntu 18.04 Bionic, Ubuntu 20.04 Focal, Ubuntu 22.04 Jammy" | |
case "$DISTRO_ID" in | |
"Debian") | |
case "$DISTRO_CODENAME" in | |
"buster"|"bullseye"|"bookworm") | |
DISTRO_OK=$aTRUE | |
;; | |
*) | |
DISTRO_OK=$aFALSE | |
;; | |
esac | |
;; | |
"Ubuntu") | |
case "$DISTRO_CODENAME" in | |
"bionic"|"focal"|"jammy") | |
DISTRO_OK=$aTRUE | |
;; | |
*) | |
DISTRO_OK=$aFALSE | |
;; | |
esac | |
;; | |
*) | |
DISTRO_OK=$aFALSE | |
;; | |
esac | |
aPrint -b "Distribuicao Linux: ID $DISTRO_ID RELEASE $DISTRO_RELEASE CODENAME $DISTRO_CODENAME" | |
if [ $DISTRO_OK = $aFALSE ]; then | |
aErrorExit -b "[$0 ERRO] Distribuicao Linux nao suportada.\nAs distribuicoes suportadas sao: $DISTRO_SUPPORTED" | |
fi | |
CORES=$(nproc) | |
aPrint -b "Quantidade de nucleos: $CORES" | |
aPrint -b "Aumentando limite de criacao de arquivos e sockets" | |
aPrint -bn " Criando backup do arquivo /etc/security/limits.conf ... " | |
sudo cp /etc/security/limits.conf /etc/security/limits.conf-antesFLASHMAN && aPrint -b "OK" || aErrorExit -b "[$0 ERRO] falhou" | |
aPrint -bn " Sobrescrevendo conteudo do arquivo /etc/security/limits.conf ... " | |
LIMITS_CONF="* soft nofile 1048576 | |
* hard nofile 1048576 | |
root soft nofile 1048576 | |
root hard nofile 1048576 | |
* soft nproc 1048576 | |
* hard nproc 1048576 | |
root soft nproc 1048576 | |
root hard nproc 1048576" | |
echo "$LIMITS_CONF" | sudo tee /etc/security/limits.conf > /dev/null && aPrint -b "OK" || aErrorExit -b "[$0 ERRO] falhou" | |
aPrint -b "Configurando consultas de DNS por TCP no resolv.conf ... " | |
sudo grep -q "options" /etc/resolv.conf | |
if [ $? -eq 0 ] | |
then | |
# Use sed to remove line that contains "options" in /etc/resolv.conf | |
sudo sed -i '/options/d' /etc/resolv.conf | |
# Add use-vc option to /etc/resolv.conf | |
echo "options use-vc" | sudo tee -a /etc/resolv.conf | |
else | |
# Add use-vc option to /etc/resolv.conf | |
echo "options use-vc" | sudo tee -a /etc/resolv.conf | |
fi | |
PORTA_HTTP=80 | |
PORTA_HTTPS=443 | |
aPrint -bn "Verificando se existe algum servico rodando nas portas $PORTA_HTTP e $PORTA_HTTPS utilizadas pelo servico HAProxy ... " | |
INFO_PORTA=$(sudo ss -tlnpH "( sport = $PORTA_HTTP or sport = $PORTA_HTTPS )" | awk '{print $4" | "$6}') | |
# Ignorar se estiver em uso pelo Docker | |
echo "$INFO_PORTA" | grep -q "docker-proxy" | |
USO_DOCKER_PORTA=$? | |
if [ "$INFO_PORTA" = "" ] || [ $USO_DOCKER_PORTA = $aTRUE ]; then | |
aPrint -b "OK" | |
else | |
aErrorExit -b "[$0 ERRO] Ja existe um servico ouvindo na porta $PORTA_HTTP ou $PORTA_HTTPS, as mesmas portas utilizadas pelo o servico HAProxy\nEndereco | usuario e pid\n$INFO_PORTA" | |
fi | |
PKGS="docker docker-engine docker.io containerd runc" | |
aptpurge $PKGS | |
PKGS="apt-transport-https ca-certificates curl gnupg jq software-properties-common unzip vim wget zip expect net-tools gawk cron host coreutils" | |
aptinstall $PKGS | |
aPrint -bn "Criando ~/.vimrc ... " | |
cat <<EOF > ~/.vimrc && aPrint -b "OK" || aPrint -b "[AVISO] erro ao criar ~/.vimrc" | |
set nocompatible | |
set bg=dark | |
EOF | |
if [ "$DO_IP_VERIFICATION" != "false" ] | |
then | |
aPrint -bn "Verificando se IP de saida para a Internet confere com o apontamento em nuvem registrado ..." | |
IP_HOST="$(ip route get 1 | awk '{ for (x=1;x<=NF;x++) if ($x~"src") print $(x+1);exit }')" | |
IP_RESOLVED_DNS="$(host $DOMINIO_NUVEM | awk 'END{ print $NF }')" | |
if [ "$IP_HOST" != "$IP_RESOLVED_DNS" ]; then | |
aErrorExit -b "[$0 ERRO] falhou ao conferir IP de saida com IP de apontamento em nuvem." | |
else | |
aPrint -b "OK" | |
fi | |
fi | |
aPrint -bn "Habilitando ntp ..." | |
if [ "$DISTRO_ID" = "Debian" ] && [ "$DISTRO_CODENAME" = "bullseye" ]; then | |
aptpurge ntp | |
else | |
if sudo timedatectl set-ntp on 2>&1 | tee -a $LOG; then | |
aPrint -b "OK" | |
else | |
aErrorExit -b "[$0 ERRO] ao executar 'timedatectl set-ntp on', ver $LOG" | |
fi | |
fi | |
aPrint -b "Instalar repositório para o Docker" | |
if [ -f $DOCKER_SOURCELIST ] && command -v docker &> /dev/null ; then | |
aPrint -b "$DOCKER_SOURCELIST existe, Docker ja foi instalado" | |
if ! systemctl -q is-active docker; then | |
aErrorExit -b "Servico docker nao esta ativo, verificar manualmente" | |
else | |
aPrint -b "Servico docker ativo, continuando" | |
fi | |
else | |
aPrint -bn "Fazendo o download da chave do repositorio do Docker ... " | |
case "$DISTRO_ID" in | |
"Debian") | |
case "$DISTRO_CODENAME" in | |
"buster"|"bullseye"|"bookworm") | |
if curl -fsSL https://download.docker.com/linux/debian/gpg 2>>$LOG | sudo gpg --yes --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg >> $LOG 2>&1; then | |
aPrint -b "OK" | |
else | |
aErrorExit -b "[$0 ERRO] ao fazer download da chave do repositorio do docker, ver $LOG" | |
fi | |
aPrint -bn "Criando arquivo de configuracao do repositorio em $DOCKER_SOURCELIST ... " | |
if echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/debian $(lsb_release -cs) stable" | sudo tee $DOCKER_SOURCELIST >> $LOG; then | |
aPrint -b "OK" | |
else | |
aErrorExit -b "[$0 ERRO] falhou ao tentar criar a configuracao do repositorio docker, ver $LOG" | |
fi | |
;; | |
*) | |
aErrorExit -b "[$0 ERRO] Distribuicao nao suportada: $DISTRO_ID $DISTRO_CODENAME" | |
;; | |
esac | |
;; | |
"Ubuntu") | |
case "$DISTRO_CODENAME" in | |
"bionic"|"focal"|"jammy") | |
sudo mkdir -p /etc/apt/keyrings && aPrint -b "OK" || aErrorExit -b "[$0 ERRO] falhou" | |
if curl -fsSL https://download.docker.com/linux/ubuntu/gpg 2>>$LOG | sudo gpg --yes --dearmor -o /etc/apt/keyrings/docker.gpg >> $LOG 2>&1; then | |
aPrint -b "OK" | |
else | |
aErrorExit -b "[$0 ERRO] ao fazer download da chave do repositorio do docker, ver $LOG" | |
fi | |
sudo chmod a+r /etc/apt/keyrings/docker.gpg && aPrint -b "OK" || aErrorExit -b "[$0 ERRO] falhou" | |
aPrint -bn "Criando arquivo de configuracao do repositorio em $DOCKER_SOURCELIST ... " | |
if echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu $(lsb_release -cs) stable" | sudo tee $DOCKER_SOURCELIST >> $LOG; then | |
aPrint -b "OK" | |
else | |
aErrorExit -b "[$0 ERRO] falhou ao tentar criar a configuracao do repositorio docker, ver $LOG" | |
fi | |
;; | |
*) | |
aErrorExit -b "[$0 ERRO] Distribuicao nao suportada: $DISTRO_ID $DISTRO_CODENAME" | |
;; | |
esac | |
;; | |
esac | |
aptupdate | |
aptinstall docker-ce docker-ce-cli containerd.io | |
sctlenable docker | |
sctlstart docker | |
fi | |
aPrint -b "Adicionar configuração de log level ao daemon Docker" | |
DOCKER_CONFIG="" | |
if [ -f "/etc/docker/daemon.json" ] ; then | |
DOCKER_CONFIG="$(sudo cat '/etc/docker/daemon.json')" | |
else | |
DOCKER_CONFIG="{}" | |
fi | |
echo "$DOCKER_CONFIG" | sudo jq '."log-level" = "fatal"' > tmp.json | |
sudo mv tmp.json /etc/docker/daemon.json | |
sctlrestart docker | |
aPrint -b "Configurando Docker" | |
cd ~ | |
HOST_ON_SWARM="false" | |
case "$(sudo docker info --format '{{.Swarm.LocalNodeState}}')" in | |
active) | |
aPrint -b "Host a configurado como parte do swarm docker. Continuando..." | |
HOST_ON_SWARM="true" | |
;; | |
*) | |
aPrint -b "Host nao esta ativo em um swarm. Iniciando configuracao swarm..." | |
HOST_ON_SWARM="false" | |
;; | |
esac | |
if [ "$HOST_ON_SWARM" == "false" ]; then | |
IP_HOST="$(ip route get 1 | awk '{ for (x=1;x<=NF;x++) if ($x~"src") print $(x+1);exit }')" | |
if sudo docker swarm init --advertise-addr "$IP_HOST" >> $LOG 2>&1; then | |
aPrint -b "OK" | |
else | |
aErrorExit -b "[$0 ERRO] executando swarm init, veja $LOG" | |
fi | |
if [ "$( sudo docker plugin ls | grep -w 'loki:latest' )" = "" ] ; then | |
aPrint -b "Instalando plugin Docker Loki" | |
if sudo docker plugin install grafana/loki-docker-driver:2.7.1 --alias loki --grant-all-permissions >> $LOG 2>&1; then | |
aPrint -b "OK" | |
else | |
aErrorExit -b "[$0 ERRO] instalando plugin Loki, veja $LOG" | |
fi | |
else | |
aPrint -b "Plugin loki já está instalado" | |
fi | |
aPrint -b "Configurando rede ingress" | |
if [ "$SUDO_NECESSITA_SENHA" == "false" ]; then | |
/usr/bin/expect <(cat << EOF | |
spawn sudo docker network rm ingress | |
expect "Are you sure you want to continue?" | |
send "y\r" | |
interact | |
expect "\\$" | |
EOF | |
) | |
else | |
/usr/bin/expect <(cat << EOF | |
set timeout 10 | |
spawn sudo docker network rm ingress | |
expect ":" | |
send -- "$SENHA_SUDO\r" | |
expect "Are you sure you want to continue?" | |
send "y\r" | |
expect eof | |
EOF | |
) | |
fi | |
if [ $? = $aTRUE ]; then | |
aPrint -b "OK" | |
sleep 3 # Wait network removal that can have a small delay | |
else | |
aErrorExit -b "[$0 ERRO] ao remover rede ingress" | |
fi | |
aPrint -b "Criando rede ingress" | |
if [ "$( sudo docker network ls | grep -w ingress )" = "" ] ; then | |
if sudo docker network create -d overlay --ingress --subnet=172.23.0.0/16 ingress >> $LOG 2>&1; then | |
aPrint -b "OK" | |
else | |
aErrorExit -b "[$0 ERRO] configurando rede de ingress, veja $LOG" | |
fi | |
else | |
aPrint -b "Rede ingress já existe" | |
fi | |
aPrint -b "Criando rede docker swarm_overlay_network" | |
if [ "$( sudo docker network ls | grep -w swarm_overlay_network )" = "" ] ; then | |
if sudo docker network create -d overlay --subnet=172.22.32.0/24 swarm_overlay_network >> $LOG 2>&1; then | |
aPrint -b "OK" | |
else | |
aErrorExit -b "[$0 ERRO] configurando rede de swarm overlay, veja $LOG" | |
fi | |
else | |
aPrint -b "Rede swarm_overlay_network já existe" | |
fi | |
aPrint -b "Criando rede docker portainer_agent_network" | |
if [ "$( sudo docker network ls | grep -w portainer_agent_network )" = "" ] ; then | |
aPrint -b "Configurando rede do agente portainer" | |
if sudo docker network create --driver overlay portainer_agent_network >> $LOG 2>&1; then | |
aPrint -b "OK" | |
else | |
aErrorExit -b "[$0 ERRO] configurando rede portainer agent, veja $LOG" | |
fi | |
else | |
aPrint -b "Rede portainer_agent_network já existe" | |
fi | |
fi | |
RUNNING_AGENT="false" | |
sudo docker service ps portainer_agent >> $LOG 2>&1 | |
if [ $? = $aTRUE ]; then | |
aPrint -b "Agente Portainer em execucao. Continuando..." | |
RUNNING_AGENT="true" | |
else | |
aPrint -b "Nenhum agente Portainer em execucao." | |
RUNNING_AGENT="false" | |
fi | |
if [ "$RUNNING_AGENT" == "false" ]; then | |
aPrint -b "Criando servico do agente portainer" | |
sudo docker service create \ | |
--name portainer_agent \ | |
--network portainer_agent_network \ | |
-p 9001:9001/tcp \ | |
--mode global \ | |
--constraint 'node.platform.os == linux' \ | |
--mount type=bind,src=//var/run/docker.sock,dst=/var/run/docker.sock \ | |
--mount type=bind,src=//var/lib/docker/volumes,dst=/var/lib/docker/volumes \ | |
portainer/agent:2.19.4 >> $LOG 2>&1 | |
if [ $? = $aTRUE ]; then | |
aPrint -b "OK" | |
else | |
aErrorExit -b "[$0 ERRO] ao criar servico do agente portainer" | |
fi | |
fi | |
aPrint -bn "Agendando rotina de limpeza de docker no crontab ..." | |
cat <<EOF | sudo crontab && aPrint -b "OK" || aErrorExit -b "[$0 ERRO] ao tentar agendar rotina de limpeza de docker no crontab" | |
SHELL=/bin/bash | |
PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin | |
00 02 * * * docker container prune -f | |
05 02 * * * docker image prune -f | |
EOF | |
aPrint -bn "Instalando ufw (firewall local) ... " | |
if sudo apt install ufw >> $LOG 2>&1; then | |
aPrint -b "OK" | |
else | |
aErrorExit -b "[$0 ERRO] ao tentar instalar ufw, ver $LOG" | |
fi | |
aPrint -b "Habilitando ufw... " | |
if sudo ufw --force enable >> $LOG 2>&1; then | |
aPrint -b "OK" | |
else | |
aErrorExit -b "[$0 ERRO] ao tentar habilitar o ufw, ver $LOG" | |
fi | |
aPrint -b "Liberar as portas no ufw" | |
for porta in $PORTA_SSH 80 443 7567 3478 $MQTTS_PORT; do | |
if sudo ufw allow $porta >> $LOG 2>&1; then | |
aPrint -b "$porta OK" | |
else | |
aErrorExit -b "[$0 ERRO] ao tentar liberar a porta $porta via ufw allow, ver $LOG" | |
fi | |
done | |
if sudo ufw allow from 45.77.115.7 to any port 9001 >> $LOG 2>&1; then | |
aPrint -b "9001 OK" | |
else | |
aErrorExit -b "[$0 ERRO] ao tentar liberar a porta 9001 via ufw allow, ver $LOG" | |
fi | |
aPrint -b "Bloquear as portas 7547 57547 no ufw" | |
for porta in 7547 57547; do | |
if sudo ufw deny $porta >> $LOG 2>&1; then | |
aPrint -b "$porta OK" | |
else | |
aErrorExit -b "[$0 ERRO] ao tentar bloquear a porta $porta via ufw deny, ver $LOG" | |
fi | |
done | |
aPrint -bn "Limpando historico de comandos do bash ... " | |
history -c >> $LOG 2>&1 && aPrint -b "OK" | |
cat <<EOF | |
ATENCAO: | |
Foi ativado atraves desse script o firewall local (ufw), com a liberacao das portas dos nossos servicos | |
e a porta $PORTA_SSH do ssh. Qualquer porta diferente da padrao devera ser liberada, antes de desconectar da maquina, para nao perder o acesso via SSH. | |
NAO ESQUEÇER DE LIBERAR A PORTA ATRAVES DO COMANDO <sudo ufw allow numero-da-porta>. | |
Para o correto funcionamento dos servicos, verifique se as portas estao liberadas no servidor. | |
E possivel usar o seguinte comando a partir de outra maquina para descobrir se uma porta esta liberada: | |
telnet *IP DO FLASHMAN* <porta> | |
As portas a verificar sao: | |
80 443 3478 9001 | |
Verificar tambem a porta MQTTS: $MQTTS_PORT | |
AS PORTAS 7547 57547 FICAM BLOQUEADAS POR PADRAO. EXECUTAR OPCAO NESTE SCRIPT PARA LIBERA-LAS | |
E possivel usar o comando | |
sudo ufw status | |
para saber se ha firewall utilizando o ufw | |
EOF | |
aPrint -b "Procedimento completo de instalacao e configuraçao do host para conexao ao gerenciador de conteineres da Anlix" | |
aExit $aTRUE |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment