Add a retry mechanism to mongo init (#2328)

pull/2347/head
skiffer-git 5 months ago committed by GitHub
parent 973442e3d3
commit e32d30f287
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

@ -11,29 +11,42 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
mongosh <<EOF
use admin
var maxRetries = 300;
var connected = false;
var rootUsername = '$MONGO_INITDB_ROOT_USERNAME';
var rootPassword = '$MONGO_INITDB_ROOT_PASSWORD';
var dbName = '$MONGO_INITDB_DATABASE';
var openimUsername = '$MONGO_OPENIM_USERNAME';
var openimPassword = '$MONGO_OPENIM_PASSWORD';
while (!connected && maxRetries > 0) {
try {
db = connect('mongodb://127.0.0.1:27017/admin');
var authResult = db.auth(rootUsername, rootPassword);
if (authResult) {
print('Authentication successful for root user: ' + rootUsername);
connected = true;
} else {
print('Authentication failed for root user: ' + rootUsername + ' with password: ' + rootPassword);
quit(1);
}
} catch (e) {
maxRetries--;
print('Connection failed, retrying... Remaining attempts: ' + maxRetries);
sleep(1000); // Sleep for 1 second
}
}
var dbName = '$MONGO_INITDB_DATABASE';
if (connected) {
db = db.getSiblingDB(dbName);
var openimUsername = '$MONGO_OPENIM_USERNAME';
var openimPassword = '$MONGO_OPENIM_PASSWORD';
var createUserResult = db.createUser({
user: openimUsername,
pwd: openimPassword,
roles: [
{ role: 'readWrite', db: dbName }
]
roles: [{
role: 'readWrite',
db: dbName
}]
});
if (createUserResult.ok == 1) {
@ -42,7 +55,12 @@ if (createUserResult.ok == 1) {
print('User creation failed for user: ' + openimUsername + ' in database: ' + dbName);
quit(1);
}
} else {
print('Failed to connect to MongoDB after 300 retries.');
quit(1);
}
EOF

Loading…
Cancel
Save