diff --git a/db/docker.js b/db/docker.js index 849cf182c..e3f105971 100644 --- a/db/docker.js +++ b/db/docker.js @@ -39,7 +39,8 @@ module.exports = class Docker { let runChown = process.platform != 'linux'; - let container = await this.execP(`docker run --env RUN_CHOWN=${runChown} -d ${dockerArgs} salix-db`); + const healthCheck = `--health-cmd='mysqladmin ping --silent'`; + const container = await this.execP(`docker run ${healthCheck} --env RUN_CHOWN=${runChown} -d ${dockerArgs} salix-db`); this.id = container.stdout; try { @@ -53,7 +54,7 @@ module.exports = class Docker { this.dbConf.port = netSettings.Ports['3306/tcp'][0]['HostPort']; } - if (runChown) await this.wait(); + await this.waitForHealthy(); } catch (err) { if (this.isRandom) await this.rm(); @@ -88,6 +89,43 @@ module.exports = class Docker { } } + waitForHealthy() { + return new Promise((resolve, reject) => { + let interval = 100; + let elapsedTime = 0; + let maxInterval = 4 * 60 * 1000; + + log('Waiting for MySQL init process...'); + + async function checker() { + elapsedTime += interval; + let status; + + try { + let result = await this.execP(`docker inspect -f "{{.State.Health.Status}}" ${this.id}`); + status = result.stdout.trimEnd(); + } catch (err) { + return reject(new Error(err.message)); + } + + if (status == 'unhealthy') + return reject(new Error('Docker exited, please see the docker logs for more info')); + + if (status == 'healthy') { + log('MySQL process ready.'); + return resolve(); + } + + if (elapsedTime >= maxInterval) + reject(new Error(`MySQL not initialized whithin ${elapsedTime / 1000} secs`)); + else + setTimeout(bindedChecker, interval); + } + let bindedChecker = checker.bind(this); + bindedChecker(); + }); + } + wait() { return new Promise((resolve, reject) => { const mysql = require('mysql2');