init-repl.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. (function () {
  2. const replSetName = 'rs0';
  3. const replSetHost = 'box-mongodb:27017';
  4. const config = {
  5. _id: replSetName,
  6. members: [
  7. {
  8. _id: 0,
  9. host: replSetHost,
  10. },
  11. ],
  12. };
  13. function replicaSetIsReady() {
  14. try {
  15. const status = rs.status();
  16. return status && status.ok === 1;
  17. } catch (error) {
  18. print('Replica set status unavailable:', error.message);
  19. return false;
  20. }
  21. }
  22. if (!replicaSetIsReady()) {
  23. print('Initializing replica set', JSON.stringify(config));
  24. rs.initiate(config);
  25. let attempts = 0;
  26. while (attempts < 20) {
  27. let status;
  28. try {
  29. status = rs.status();
  30. } catch (error) {
  31. print('Replica set not ready yet:', error.message);
  32. sleep(1000);
  33. attempts += 1;
  34. continue;
  35. }
  36. if (status && status.ok === 1 && status.myState === 1) {
  37. print('Replica set is PRIMARY');
  38. break;
  39. }
  40. print('Waiting for PRIMARY (attempt', attempts + 1, ')');
  41. sleep(1000);
  42. attempts += 1;
  43. }
  44. } else {
  45. print('Replica set already initialized');
  46. }
  47. ['box_admin', 'box_stats'].forEach((dbName) => {
  48. const targetDb = db.getSiblingDB(dbName);
  49. const result = targetDb.runCommand({ ping: 1 });
  50. print('Ensured database ' + dbName + ':', tojson(result));
  51. });
  52. })();