检查蚊子的脚本是健康的

时间:2016-09-01 15:33:42

标签: bash docker mosquitto

我正在尝试为mosquitto创建一个健康检查脚本(由docker使用)。

if [ -z "$USERNAME" ]; then
 mosquitto_sub -t '$SYS/#' -C 1 | grep -v Error || exit 1
else 
 mosquitto_sub -t '$SYS/#' -C 1 -u $USERNAME -P $PASSWRD | grep -v Error || exit 1
fi

我遇到的问题是,如果给出了错误的密码,mosquitto_sub会一直反复输出Connection Refused: not authorised.,并且docker中的超时内容会出现错误,所以它永远不会结束。

看起来mosquitto没有任何方法可以更好地失败。我想我可能需要将它作为一个我可以杀死的后台进程来执行,但我的bash并不是那么好,所以有没有人有更好的想法?

[编辑 - 根据BMitch的建议更新]

我已将脚本修改为如下所示:

#!/bin/sh

if [ -z "$USERNAME" ]; then
        (sleep 10; kill $$) & exec mosquitto_sub -t '$SYS/#' -C 1 | grep -v Error || exit 1 "$@"
else
        (sleep 10; kill $$) & exec mosquitto_sub -t '$SYS/#' -u $USERNAME -P $PASSWORD -C 1 | grep -v Error || exit 1  "$@"
fi

但运行它只会提供以下输出:

Connection Refused: not authorised.
Connection Refused: not authorised.
Connection Refused: not authorised.
Connection Refused: not authorised.
Connection Refused: not authorised.
Connection Refused: not authorised.
Connection Refused: not authorised.
Connection Refused: not authorised.
Connection Refused: not authorised.
Connection Refused: not authorised.
Terminated
root@e30e9cadd8fc:/# Connection Refused: not authorised.
Connection Refused: not authorised.
Connection Refused: not authorised.
Connection Refused: not authorised.
Connection Refused: not authorised.
Connection Refused: not authorised.
Connection Refused: not authorised.

2 个答案:

答案 0 :(得分:0)

关于如何超时运行脚本有一个bash FAQ。尝试用包含以下内容的mosquitto_sub_timeout.sh替换mosquitto_sub:

#!/bin/bash
(sleep 10; kill $$) & exec mosquitto_sub "$@"

然后您的健康检查脚本将如下所示:

if [ -z "$USERNAME" ]; then
 mosquitto_sub_timeout.sh -t '$SYS/#' -C 1 | grep -v Error || exit 1
else 
 mosquitto_sub_timeout.sh -t '$SYS/#' -C 1 -u $USERNAME -P $PASSWRD | grep -v Error || exit 1
fi

最后一次更新,如bash常见问题解答中所述,只要它安装在您的容器中,timeout命令可能是它们的最佳解决方案:

if [ -z "$USERNAME" ]; then
 timeout --foreground 10 mosquitto_sub -t '$SYS/#' -C 1 | grep -v Error || exit 1
else 
 timeout --foreground 10 mosquitto_sub -t '$SYS/#' -C 1 -u $USERNAME -P $PASSWRD | grep -v Error || exit 1
fi

答案 1 :(得分:0)

BMitch的概念已更改)

我不得不将超时参数从--foreground更改为-t,并在其前面加上一个$符号来逃避$

在我的docker-compose中,接下来看(请记住,用户名和密码已删除,您仍然可以添加它们-只需再次跳过$符号): version: '3' services: mosquitto: image: 'eclipse-mosquitto:1.6.7' container_name: mosquitto hostname: mosquitto volumes: - ./mosquitto/data:/mosquitto/data - ./mosquitto/log:/mosquitto/log - ./mosquitto/config:/mosquitto/config networks: - cluster restart: on-failure healthcheck: test: ["CMD-SHELL", "timeout -t 5 mosquitto_sub -t '$$SYS/#' -C 1 | grep -v Error || exit 1"] interval: 10s timeout: 10s retries: 6