Files
open-im-server/scripts/mongo-init.sh
T

67 lines
2.1 KiB
Bash
Raw Normal View History

2023-07-04 11:15:20 +08:00
# Copyright © 2023 OpenIM. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# 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.
2024-01-04 20:50:29 +08:00
mongosh <<EOF
2024-06-03 20:27:43 +08:00
var maxRetries = 300;
var connected = false;
2024-04-19 22:23:08 +08:00
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';
2024-04-22 15:30:14 +08:00
2024-06-03 20:27:43 +08:00
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
}
}
if (connected) {
db = db.getSiblingDB(dbName);
var createUserResult = db.createUser({
user: openimUsername,
pwd: openimPassword,
roles: [{
role: 'readWrite',
db: dbName
}]
});
if (createUserResult.ok == 1) {
print('User creation successful. User: ' + openimUsername + ', Database: ' + dbName);
} else {
print('User creation failed for user: ' + openimUsername + ' in database: ' + dbName);
quit(1);
}
2024-04-19 22:23:08 +08:00
} else {
2024-06-03 20:27:43 +08:00
print('Failed to connect to MongoDB after 300 retries.');
quit(1);
2024-04-19 22:23:08 +08:00
}
2023-06-30 23:22:58 +08:00
EOF
2024-04-22 16:03:06 +08:00
2024-04-22 16:24:37 +08:00
2024-04-24 12:11:24 +08:00
2024-06-03 20:27:43 +08:00