【问题标题】:Detecting when Mongod's port is open inside a script检测脚本中何时打开 Mongod 的端口
【发布时间】:2018-01-26 19:23:23
【问题描述】:

我正在尝试编写一个启动 mongod 进程的 bash 脚本,等待它启动(即打开默认端口),然后通过 mongo shell 将一些命令输入其中。我想要一些方法来等待 mongod 进程完全启动,这比 sleep 5 更具确定性。

这是目前为止的脚本:

set_up_authorization() {
    echo "Setting up access control"
    /path/to/mongo < configure_access_controls.js
}

wait_for_mongod_to_start() {
    RETRIES=1000
    CONNECTED="false"
    echo "Waiting for mongod to start"
    while [[ $RETRIES -ge 0 && $CONNECTED == "false" ]] ; do
        RESPONSE=$(exec 6<>/dev/tcp/127.0.0.1/27017 || echo "1")
        if [[ $RESPONSE == "" ]] # which should happen if the exec is successful
            CONNECTED="true"
        fi
        RETRIES=$((RETRIES - 1))
    done
    if [[ $RETRIES -eq 0 ]] ; then
        echo "Max retries reached waiting for mongod to start. Exiting."
        exit 1
    fi
    echo "Mongod started"
}

./start_mongod_instance.sh
wait_for_mongod_to_start
set_up_authorization

虽然此脚本有效,但它会在 exec 失败时在终端上产生大量输出:

./initialize_cluster.sh: connect: Connection refused
./initialize_cluster.sh: line xx: /dev/tcp/127.0.0.1/27017: Connection refused

...对所有 ~900 次失败的尝试重复。

以下似乎都没有摆脱终端日志记录:

exec 6<>/dev/tcp/127.0.0.1/27017 >/dev/null
OR
exec 6<>/dev/tcp/127.0.0.1/27017 2>/dev/null

我也尝试过使用以下方法:

ps -aux | grep "mongod" | wc -l 

但是具有 ps 列出的 pid 的进程并不等同于它的端口正在打开或它正在接受连接。

任何一个方面的想法都将不胜感激 - 一种更优雅的等待进程完全启动的方法或一种摆脱对终端的过多日志记录的方法。

注意:我无权访问 nmapnc 来检查端口(这是在客户端计算机上)。

【问题讨论】:

    标签: linux bash mongodb


    【解决方案1】:

    exec 有点特别。它会影响 current shell 的输出。这意味着您需要在运行端口检查之前重定向当前 shell 的 stderr:

    host="localhost"
    port="9000"
    exec 2>/dev/null # redirect error here
    while ! exec 3<>"/dev/tcp/${host}/${port}" ; do
        echo "Waiting ..."
        sleep 1
    done
    

    此外,您可能已经注意到,我检查了exec 的退出状态,而不是一些输出来确定端口是否打开。


    如果你想在之后重置它:

    host="localhost"
    port="9000"
    
    # Copy fd 2 into fd 3 and redirect fd 2 to /dev/null
    exec 3<&2 2>/dev/null
    
    while ! exec 3<>"/dev/tcp/${host}/${port}" ; do
        echo "Waiting ..."
        sleep 1
    done
    
    # Copy back fd 3 into fd 2
    exec 2<&3
    echo "EE oops!" >&2
    

    【讨论】:

    • 工作就像一个魅力!谢谢!
    • 顺便说一句,使用 /dev/tcp 是 imo 实现目标的一种非常优雅的方法!
    猜你喜欢
    • 2018-05-10
    • 2013-05-12
    • 2015-12-07
    • 1970-01-01
    • 2011-06-22
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    相关资源
    最近更新 更多