From 906b94061f8cfd2bbbef892ad31cbe4a2c37ffb1 Mon Sep 17 00:00:00 2001 From: xcps Date: Thu, 27 Sep 2018 15:40:46 +0500 Subject: [PATCH] Acquire lock before running syncBlockchain --- .gitignore | 1 + bin/syncBlockchain.js | 31 ++++++++++++++++++++++++++----- package.json | 3 ++- 3 files changed, 29 insertions(+), 6 deletions(-) diff --git a/.gitignore b/.gitignore index bfb6c24..b77eab7 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ node_modules package-lock.json config/config.json todo +sync.lock \ No newline at end of file diff --git a/bin/syncBlockchain.js b/bin/syncBlockchain.js index c644618..2847f23 100644 --- a/bin/syncBlockchain.js +++ b/bin/syncBlockchain.js @@ -1,4 +1,6 @@ var http = require('http'); +const fs = require('fs-ext'); + var models = require('../models'); var rpcConfig = require('../config/config')['rpc']; @@ -150,19 +152,38 @@ async function getSyncedHeight() { return height; } +async function acquireLock() { + let fd = fs.openSync('sync.lock', 'w'); + try { + fs.flockSync(fd, 'exnb'); + } catch(ex) { + if (ex.code === 'EAGAIN') { + console.log('Synchronization is already running'); + } else { + console.log('Could\'nt lock file', ex); + } + throw ex; + } +} + async function syncBlockchain() { - let syncedHeight = await getSyncedHeight(); - console.log('\x1b[36m%s\x1b[0m', 'syncedHeight is', syncedHeight); - let currentHeight = await getCurrentHeight(); - console.log('\x1b[36m%s\x1b[0m', 'currentHeight is', currentHeight); try { + + await acquireLock(); + + let syncedHeight = await getSyncedHeight(); + console.log('\x1b[36m%s\x1b[0m', 'syncedHeight is', syncedHeight); + + let currentHeight = await getCurrentHeight(); + console.log('\x1b[36m%s\x1b[0m', 'currentHeight is', currentHeight); + while (syncedHeight < currentHeight) { syncedHeight = await syncNextBlock(syncedHeight); console.log('\x1b[36m%s\x1b[0m', 'syncedHeight: ', syncedHeight) } } catch (e) { - console.log('=====', e); + console.log(e); } finally { models.sequelize.close().then(() => process.exit(0)); } diff --git a/package.json b/package.json index ebbcdba..204ab98 100644 --- a/package.json +++ b/package.json @@ -21,8 +21,9 @@ "body-parser": "~1.18.2", "cookie-parser": "~1.4.3", "debug": "~2.6.9", - "express": "~4.15.5", + "express": "^4.16.3", "forever": "^0.15.3", + "fs-ext": "^1.2.1", "morgan": "~1.9.0", "mysql": "^2.15.0", "mysql2": "^1.5.1",