From 5db74329559f54effacb2699c42130ba9ca707b6 Mon Sep 17 00:00:00 2001 From: Jones Magloire Date: Tue, 11 Jun 2019 13:38:22 +0200 Subject: [PATCH] feat(docker): Handle SIGTERM event and add test/oa in .dockerignore (#46) * feat(docker): Handle SIGTERM event and add test/oa in .dockerignore * feat(docker): Avoid use of process.exit --- .dockerignore | 5 ++++- server/http.js | 30 +++++++++++++++++++++++++----- 2 files changed, 29 insertions(+), 6 deletions(-) diff --git a/.dockerignore b/.dockerignore index 6109fa5f..47a5ebfe 100644 --- a/.dockerignore +++ b/.dockerignore @@ -13,4 +13,7 @@ resources/whosonfirst/dictionaries/*/*.txt !resources/whosonfirst/dictionaries/region/wof:shortcode.txt !resources/whosonfirst/dictionaries/region/name:eng_x_preferred.txt !resources/whosonfirst/dictionaries/region/abrv:eng_x_preferred.txt -!resources/whosonfirst/dictionaries/locality/name:eng_x_preferred.txt \ No newline at end of file +!resources/whosonfirst/dictionaries/locality/name:eng_x_preferred.txt + +# ignore any openaddresses test cases +test/oa \ No newline at end of file diff --git a/server/http.js b/server/http.js index f784ff94..8b7687a3 100644 --- a/server/http.js +++ b/server/http.js @@ -26,9 +26,9 @@ const envCpus = parseInt(process.env.CPUS, 10) const cpus = Math.min(Math.max(envCpus || Infinity, 1), os.cpus().length) // optionally override port/host using env var -var PORT = process.env.PORT || 3000 -var HOST = process.env.HOST || undefined -var app = express() +const PORT = process.env.PORT || 3000 +const HOST = process.env.HOST || undefined +const app = express() // init placeholder and store it on $app console.error('parser loading') @@ -61,21 +61,41 @@ if (cpus > 1) { console.error('[master] worker forked', worker.process.pid) }) + // handle SIGTERM (required for fast docker restarts) + process.on('SIGTERM', () => { + console.error('[master] closing app') + Object.keys(cluster.workers) + .map(id => cluster.workers[id]) + .forEach(worker => worker.send('graceful-shutdown')) + }) + // fork workers for (var c = 0; c < cpus; c++) { cluster.fork() } } else { - app.listen(PORT, HOST, () => { + const server = app.listen(PORT, HOST, () => { console.error('[worker %d] listening on %s:%s', process.pid, HOST || '0.0.0.0', PORT) }) + process.on('message', (msg) => { + // handle SIGTERM (required for fast docker restarts) + if (msg === 'graceful-shutdown') { + console.error('[worker %d] closing server', process.pid) + server.close(() => cluster.worker.disconnect()) + } + }) } // start single-threaded server } else { console.error('[master] using %d cpus', cpus) - app.listen(PORT, HOST, () => { + const server = app.listen(PORT, HOST, () => { console.log('[master] listening on %s:%s', HOST || '0.0.0.0', PORT) + // handle SIGTERM (required for fast docker restarts) + process.on('SIGTERM', () => { + console.error('[master] closing app') + server.close() + }) }) }