Home > Enterprise >  How to resolve mongodump error code 0 with server connection error?
How to resolve mongodump error code 0 with server connection error?

Time:11-17

I'm writing a bash script that backs up a mongodb instance using mongodump. There are multiple steps to the script, that only run if the dump is successful, so I need an error code that tells me if the backup ran successfully. I've been using the following:

for i in $(seq 1 30); do
  mongodump --host mongodb -u user -p password --archive | gzip > backup.gz
  check=$?
  echo "$check"
  if [ "$check" -eq "0" ]; then
    break
  fi
done

if [ "$check" -eq "0" ]; then
  echo "do something with the file"
fi

This works fine, when mongodump is actually successful, but the issue is, even when mongodump fails, it returns 0. Which seems counter to what I understand from their documentation here.

For example, if I disconnect this server from the database by unplugging a network cable, it fails with the error Failed: can't create session: could not connect to server: server selection error: server selection timeout. But the return code for that is also 0, just like a success.

Maybe it's supposed to be, but how do I error check for network errors if the error code for network errors is the same as success?

Or is that success coming from the gzip? Which would make my question, why does mongodump create the backup file even on network failure?

CodePudding user response:

Replace $? with "${PIPESTATUS[0]}" to get exit status of first command (mongodump ...) in your pipe.

From man bash:

PIPESTATUS: An array variable containing a list of exit status values from the processes in the most-recently-executed foreground pipeline (which may contain only a single command).


Or avoid a pipe. Replace

mongodump --host mongodb -u user -p password --archive | gzip > backup.gz

with

mongodump --host mongodb -u user -p password --archive > >(gzip > backup.gz)
  • Related