From 4cba70039f60fd86224d2b40134b89685190dfe5 Mon Sep 17 00:00:00 2001 From: Ben Francis Date: Thu, 5 Sep 2024 17:51:56 +0100 Subject: [PATCH] Detect if running inside a snap or on Ubuntu Core --- snap/snapcraft.yaml | 1 + src/platform.ts | 48 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/snap/snapcraft.yaml b/snap/snapcraft.yaml index ffaa37e05..de35d6309 100644 --- a/snap/snapcraft.yaml +++ b/snap/snapcraft.yaml @@ -16,6 +16,7 @@ apps: plugs: - network - network-bind + - system-observe parts: python-deps: diff --git a/src/platform.ts b/src/platform.ts index 9986c927e..8c1594858 100644 --- a/src/platform.ts +++ b/src/platform.ts @@ -62,6 +62,41 @@ export function getOS(): string { } } + // If not running inside a snap, give up at this point. + if (!isSnap()) { + console.log('Unknown Linux distribution'); + return 'linux-unknown'; + } + + // Otherwise try to detect if running on Ubuntu Core. + try { + const osReleaseLines = fs + .readFileSync('/var/lib/snapd/hostfs/etc/os-release', { + encoding: 'utf8', + }) + .split('\n'); + // Iterate through the file + for (let line of osReleaseLines) { + // Trim whitespace + line = line.trim(); + // Find the line containing ID + if (line.startsWith('ID=')) { + // Get the value of the ID + let id = line.substring(3, line.length); + // Remove any quotation marks + id = id.replace(/"/g, ''); + if (id == 'ubuntu-core') { + return 'linux-ubuntu-core'; + } else { + console.log('Unknown host Linux distribution'); + } + } + } + } catch (error) { + console.log(`Error trying to read os-release file: ${error}`); + console.log('Check that the system-observe interface is connected'); + } + return 'linux-unknown'; } @@ -85,6 +120,19 @@ export function isContainer(): boolean { ); } +/** + * Determine whether or not we're running inside a snap package. + * + * @returns boolean True if running inside snap, false if not. + */ +export function isSnap(): boolean { + if (process.env.SNAP_NAME == 'webthings-gateway') { + return true; + } else { + return false; + } +} + /** * Get the current node version. */