From e32d30f2870c9bdd742012eb9fd44b1962d48c76 Mon Sep 17 00:00:00 2001 From: skiffer-git <72860476+skiffer-git@users.noreply.github.com> Date: Mon, 3 Jun 2024 20:27:43 +0800 Subject: [PATCH] Add a retry mechanism to mongo init (#2328) --- scripts/mongo-init.sh | 62 ++++++++++++++++++++++++++++--------------- 1 file changed, 40 insertions(+), 22 deletions(-) diff --git a/scripts/mongo-init.sh b/scripts/mongo-init.sh index 01199c4806..25bb2d654c 100755 --- a/scripts/mongo-init.sh +++ b/scripts/mongo-init.sh @@ -11,38 +11,56 @@ # 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 < 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); + } } else { - print('User creation failed for user: ' + openimUsername + ' in database: ' + dbName); - quit(1); + print('Failed to connect to MongoDB after 300 retries.'); + quit(1); } EOF +