From 2d2ba4521d2112ffdc78e044e6ce185ee114f2eb Mon Sep 17 00:00:00 2001 From: Philipp Muens Date: Mon, 9 Jan 2017 11:15:12 -0800 Subject: [PATCH] Update Docker detection to be cgroup based This ensures a more stable detection strategy since .dockerenv might be not around for the long term. --- lib/classes/Utils.js | 6 +++--- lib/classes/Utils.test.js | 12 +++++++----- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/lib/classes/Utils.js b/lib/classes/Utils.js index 781b3891b..31fad2ae3 100644 --- a/lib/classes/Utils.js +++ b/lib/classes/Utils.js @@ -303,9 +303,9 @@ class Utils { // wrap in try catch to make sure that missing permissions won't break anything let isDockerContainer = false; try { - const dockerenvFile = '.dockerenv'; - const dockerenvFilePath = path.join(this.getRootPath(), dockerenvFile); - isDockerContainer = this.fileExistsSync(dockerenvFilePath) || false; + const cgroupFilePath = path.join(this.getRootPath(), 'proc', '1', 'cgroup'); + const cgroupFileContent = fs.readFileSync(cgroupFilePath).toString(); + isDockerContainer = !!cgroupFileContent.match(/docker/); } catch (exception) { // do nothing } diff --git a/lib/classes/Utils.test.js b/lib/classes/Utils.test.js index cf758dc6e..8a404f61f 100644 --- a/lib/classes/Utils.test.js +++ b/lib/classes/Utils.test.js @@ -374,13 +374,15 @@ describe('Utils', () => { describe('when detecting Docker containers', () => { let rootPathStub; let rootDirPath; - let dockerenvFilePath; + let cgroupFilePath; beforeEach(() => { rootDirPath = testUtils.getTmpDirPath(); - dockerenvFilePath = path.join(rootDirPath, '.dockerenv'); + cgroupFilePath = path.join(rootDirPath, 'proc', '1', 'cgroup'); + const cgroupFileContent = '6:devices:/docker/3601745b3bd54d9780436faa5f0e4f72'; fse.mkdirsSync(rootDirPath); - fse.ensureFileSync(dockerenvFilePath); + fse.ensureFileSync(cgroupFilePath); + fs.writeFileSync(cgroupFilePath, cgroupFileContent); rootPathStub = sinon.stub(utils, 'getRootPath').returns(rootDirPath); }); @@ -404,8 +406,8 @@ describe('Utils', () => { }) ); - it('should not throw error if .dockerenv file is not accessible', () => { - fs.chmodSync(dockerenvFilePath, '000'); + it('should not throw error if cgroup file is not accessible', () => { + fs.chmodSync(cgroupFilePath, '000'); fs.chmodSync(rootDirPath, '400'); utils.logStat(serverless).then(() => {