From 97be0919b769c550993a564dd47345dc71001c4c Mon Sep 17 00:00:00 2001 From: cha0s Date: Sun, 24 Jan 2021 10:41:04 -0600 Subject: [PATCH] refactor: persist docker --- packages/db/src/docker.js | 29 +++++++++++++++++------------ packages/redis/src/docker.js | 17 +++++++++++++---- 2 files changed, 30 insertions(+), 16 deletions(-) diff --git a/packages/db/src/docker.js b/packages/db/src/docker.js index 13cb0de..a377963 100644 --- a/packages/db/src/docker.js +++ b/packages/db/src/docker.js @@ -1,21 +1,24 @@ -import {spawn} from 'child_process'; +import {spawn, spawnSync} from 'child_process'; import mkdirp from 'mkdirp'; export default function createDockerContainer(latus) { + const {id} = latus.get('@latus/core'); const { - config: { - '@latus/db/server': { - database, - docker, - password, - port, - }, - }, - } = latus; + database, + docker, + password, + port, + } = latus.get('@latus/db/server'); + const name = `${id}_sequelize`; + const {output} = spawnSync(`docker container inspect -f '{{.State.Running}}' ${name}`); + if ('true' === output) { + return; + } const args = [ 'run', '--rm', + '--name', name, '-p', `${port}:3306`, '-e', `MYSQL_DATABASE=${database}`, '-e', `MYSQL_ROOT_PASSWORD=${password}`, @@ -32,6 +35,8 @@ export default function createDockerContainer(latus) { 'mysql', '--default-authentication-plugin=mysql_native_password', ); - const {pid} = spawn('docker', args, {stdio: 'ignore'}); - process.on('exit', () => process.kill(pid)); + spawn('docker', args, { + detached: true, + stdio: 'ignore', + }).unref(); } diff --git a/packages/redis/src/docker.js b/packages/redis/src/docker.js index b75cee9..a2e0d8c 100644 --- a/packages/redis/src/docker.js +++ b/packages/redis/src/docker.js @@ -1,6 +1,6 @@ import D from 'debug'; -import {spawn} from 'child_process'; +import {spawn, spawnSync} from 'child_process'; import mkdirp from 'mkdirp'; @@ -9,10 +9,17 @@ import createClient from './create-client'; const debug = D('@latus/redis/docker'); export default async function createDockerContainer(latus) { - const {config: {'@latus/redis/server': {docker, port}}} = latus; + const {id} = latus.get('@latus/core'); + const {docker, port} = latus.get('@latus/redis/server'); + const name = `${id}_redis`; + const {output} = spawnSync(`docker container inspect -f '{{.State.Running}}' ${name}`); + if ('true' === output) { + return; + } const args = [ 'run', '--rm', + '--name', name, '-p', `${port}:6379`, ]; if ('cached' === docker) { @@ -26,8 +33,10 @@ export default async function createDockerContainer(latus) { args.push( 'redis', ); - const {pid} = spawn('docker', args, {stdio: 'ignore'}); - process.on('exit', () => process.kill(pid)); + spawn('docker', args, { + detached: true, + stdio: 'ignore', + }).unref(); // eslint-disable-next-line no-constant-condition while (true) { const client = createClient(latus);