/** * @file packages/core/src/cli.ts * @description This file contains the CLI entry point of Matterbridge. * @author Luca Liguori * @created 2023-12-29 * @version 3.1.0 * @license Apache-2.0 * * Copyright 2023, 2024, 2025, 2026 Luca Liguori. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* oxlint-disable no-console */ /* oxlint-disable n/no-process-exit */ // Node.js modules import os from 'node:os'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; // @matterbridge import { ThreadsManager } from '@matterbridge/thread/manager'; import { BroadcastServer } from '@matterbridge/thread/server'; import type { ApiSystemUpdate } from '@matterbridge/types'; import { constrainedMemory, memoryFootprint } from '@matterbridge/utils/bun'; import { hasAnyParameter, hasParameter } from '@matterbridge/utils/cli'; import { inspectError } from '@matterbridge/utils/error'; import { formatBytes, formatUptime } from '@matterbridge/utils/format'; import { Inspector } from '@matterbridge/utils/inspector'; import { logModuleLoaded } from '@matterbridge/utils/loader'; import { Tracker, type TrackerSnapshot } from '@matterbridge/utils/tracker'; // AnsiLogger module import { AnsiLogger, LogLevel, TimestampFormat } from 'node-ansi-logger'; // Cli import { cliEmitter } from './cliEmitter.js'; // matterbridge import type { Matterbridge } from './matterbridge.js'; logModuleLoaded('Cli'); export let instance: Matterbridge | undefined; export const tracker = new Tracker('Cli', false, false); export const inspector = new Inspector('Cli', false, false); const log = new AnsiLogger({ logName: 'Cli', logTimestampFormat: TimestampFormat.TIME_MILLIS, logLevel: hasAnyParameter('debug', 'verbose') ? LogLevel.DEBUG : LogLevel.INFO }); const manager = new ThreadsManager(path.dirname(fileURLToPath(import.meta.url))); const server = new BroadcastServer('cli', log); /** * Starts the CPU and memory tracker. */ function startCpuMemoryCheck(): void { const memoryUsage = process.memoryUsage(); const systemUpdate: ApiSystemUpdate = { systemUptime: formatUptime(Math.floor(os.uptime())), processUptime: formatUptime(Math.floor(process.uptime())), totalMemory: formatBytes(os.totalmem()), freeMemory: formatBytes(os.freemem()), constrainedMemory: formatBytes(constrainedMemory()), rss: formatBytes(memoryFootprint()), heapTotal: formatBytes(memoryUsage.heapTotal), heapUsed: formatBytes(memoryUsage.heapUsed), external: formatBytes(memoryUsage.external), arrayBuffers: formatBytes(memoryUsage.arrayBuffers), cpuUsage: 0, processCpuUsage: 0, }; log.debug(`Cpu memory check starting...`); tracker.start(); tracker.on('uptime', (systemUptime: number, processUptime: number) => { systemUpdate.systemUptime = formatUptime(Math.floor(systemUptime)); systemUpdate.processUptime = formatUptime(Math.floor(processUptime)); }); tracker.on('snapshot', (snapshot: TrackerSnapshot) => { systemUpdate.totalMemory = formatBytes(snapshot.totalMemory); systemUpdate.freeMemory = formatBytes(snapshot.freeMemory); systemUpdate.constrainedMemory = formatBytes(snapshot.constrainedMemory); systemUpdate.rss = formatBytes(snapshot.rss); systemUpdate.heapTotal = formatBytes(snapshot.heapTotal); systemUpdate.heapUsed = formatBytes(snapshot.heapUsed); systemUpdate.external = formatBytes(snapshot.external); systemUpdate.arrayBuffers = formatBytes(snapshot.arrayBuffers); systemUpdate.cpuUsage = Math.round(snapshot.osCpu * 100) / 100; systemUpdate.processCpuUsage = Math.round(snapshot.processCpu * 100) / 100; server.request({ type: 'frontend_broadcast_message', src: 'cli', dst: 'frontend', params: { msg: { id: 0, src: 'Matterbridge', dst: 'Frontend', method: 'system_update', success: true, response: systemUpdate } }, }); }); log.debug(`Cpu memory check started`); } /** * Stops the CPU and memory tracker. */ function stopCpuMemoryCheck(): void { log.debug(`Cpu memory check stopping...`); tracker.stop(); tracker.removeAllListeners(); log.debug(`Cpu memory check stopped`); } /** * Starts the inspector for heap sampling. * This function is called when the -inspect parameter is passed. */ async function startInspector(): Promise { await inspector.start(); } /** * Stops the heap sampling and saves the profile. * This function is called when the -inspect parameter is passed. */ async function stopInspector(): Promise { await inspector.stop(); } /** * Takes a heap snapshot */ async function takeHeapSnapshot(): Promise { await inspector.takeHeapSnapshot(); } /** * Triggers a manual garbage collection. * This function is working only if the node process is started with --expose_gc. * * @remarks To check the effect of the garbage collection, add also --trace_gc or --trace_gc_verbose. */ function triggerGarbageCollection(): void { inspector.runGarbageCollector(); } /** * Registers event handlers for the Matterbridge instance. */ function registerHandlers(): void { log.debug('Registering event handlers...'); /* v8 ignore next cause registerHandlers is called only if instance is defined */ if (!instance) return; instance.on('shutdown', () => void shutdown().catch(/* v8 ignore next -- @preserve */ (error: unknown) => inspectError(log, 'Failed to shutdown', error))); instance.on('restart', () => void restart().catch(/* v8 ignore next -- @preserve */ (error: unknown) => inspectError(log, 'Failed to restart', error))); instance.on('update', () => void update().catch(/* v8 ignore next -- @preserve */ (error: unknown) => inspectError(log, 'Failed to update', error))); instance.on('startmemorycheck', () => startCpuMemoryCheck()); instance.on('stopmemorycheck', () => stopCpuMemoryCheck()); instance.on('startinspector', () => void startInspector().catch(/* v8 ignore next -- @preserve */ (error: unknown) => inspectError(log, 'Failed to start inspector', error))); instance.on('stopinspector', () => void stopInspector().catch(/* v8 ignore next -- @preserve */ (error: unknown) => inspectError(log, 'Failed to stop inspector', error))); instance.on( 'takeheapsnapshot', () => void takeHeapSnapshot().catch(/* v8 ignore next -- @preserve */ (error: unknown) => inspectError(log, 'Failed to take heap snapshot', error)), ); instance.on('triggergarbagecollection', () => triggerGarbageCollection()); log.debug('Registered event handlers'); } /** * Shuts down the Matterbridge instance and exits the process. */ async function shutdown(): Promise { log.debug('Received shutdown event, exiting...'); if (hasParameter('inspect')) await stopInspector(); stopCpuMemoryCheck(); server.close(); manager.destroy(); cliEmitter.emit('shutdown'); log.debug('Received shutdown event, exit with code 0'); process.exit(0); } /** * Restarts the Matterbridge instance. */ async function restart(): Promise { log.debug('Received restart event, loading...'); const { Matterbridge } = await import('./matterbridge.js'); instance = await Matterbridge.loadInstance(true); registerHandlers(); } /** * Updates the Matterbridge instance. */ async function update(): Promise { log.debug('Received update event, updating...'); // TODO: Implement update logic outside of matterbridge const { Matterbridge } = await import('./matterbridge.js'); instance = await Matterbridge.loadInstance(true); registerHandlers(); } /** * Main function that initializes the Matterbridge instance and starts the CLI. * * @remarks * * Debug parameters: * * --debug enables debug logging. * * --verbose enables verbose logging. * * --loader enables loader logging. * * --inspect enables the inspector for heap sampling. * * --snapshotinterval can be used to set the heap snapshot interval. Default is undefined. Minimum is 30000 ms. */ export async function main(): Promise { log.debug(`Cli main() started`); /** Minimal ANSI styling */ if (!(!process.env.NO_COLOR && process.env.TERM !== 'dumb' && process.env.FORCE_COLOR !== '0' && !hasParameter('no-ansi'))) process.env.NO_COLOR = '1'; startCpuMemoryCheck(); if (hasParameter('inspect')) await startInspector(); log.debug(`***Matterbridge.loadInstance(true) called`); const { Matterbridge } = await import('./matterbridge.js'); // Freeze the prototypes of the core classes before loading the Matterbridge instance const { protectCorePrototypes } = await import('./protectPrototypes.js'); await protectCorePrototypes(); instance = await Matterbridge.loadInstance(true); log.debug(`***Matterbridge.loadInstance(true) exited`); // v8 ignore next -- just experimental if (hasParameter('experimental-backend')) { log.notice(`***Starting experimental Backend thread...`); manager.runThread('Backend'); log.notice(`***Started experimental Backend thread`); } // Check if the instance needs to shut down from parseCommandLine() if (!instance || instance.shutdown) { await shutdown(); } else { registerHandlers(); cliEmitter.emit('ready'); log.debug(`Cli main() ready`); } } if (hasAnyParameter('help', 'h')) help(); if (hasAnyParameter('version', 'v')) await version(); main().catch((error: unknown) => { inspectError(log, 'Matterbridge.loadInstance() failed with error', error); /* v8 ignore next cause process.exit is not relevant for coverage */ // oxlint-disable-next-line promise/no-nesting shutdown().catch(/* v8 ignore next -- @preserve */ () => process.exit(1)); }); /** * Displays the version and exits. */ async function version(): Promise { // Dynamic JSON import with import attributes const { default: pkg } = await import('../package.json', { with: { type: 'json' } }); console.log(`Matterbridge version ${pkg.version}`); process.exit(0); } /** * Displays the help and exits. */ function help(): void { console.log(` Usage: matterbridge [options] [command] Commands: --help: show the help --version: show the version --add [plugin path]: register the plugin from the given absolute or relative path --add [plugin name]: register the globally installed plugin with the given name --remove [plugin path]: remove the plugin from the given absolute or relative path --remove [plugin name]: remove the globally installed plugin with the given name --enable [plugin path]: enable the plugin from the given absolute or relative path --enable [plugin name]: enable the globally installed plugin with the given name --disable [plugin path]: disable the plugin from the given absolute or relative path --disable [plugin name]: disable the globally installed plugin with the given name --list: list the registered plugins --loginterfaces: log the network interfaces (usefull for finding the name of the interface to use with -mdnsinterface option) --logstorage: log the node storage --systemcheck: perform a system check (check Node.js version and network interfaces) --demo-devices: create demo devices (only in bridge mode) Reset Commands: --reset: remove the commissioning for Matterbridge (bridge mode and childbridge mode). Shutdown Matterbridge before using it! --reset [plugin path]: remove the commissioning for the plugin from the given absolute or relative path (childbridge mode). Shutdown Matterbridge before using it! --reset [plugin name]: remove the commissioning for the globally installed plugin (childbridge mode). Shutdown Matterbridge before using it! --factoryreset: remove all commissioning information and reset all internal storages. Shutdown Matterbridge before using it! Options: --bridge: start Matterbridge in bridge mode --childbridge: start Matterbridge in childbridge mode --port [port]: start the matter commissioning server on the given port (default 5540) --mdnsinterface [name]: set the interface to use for the matter server mdnsInterface (default all interfaces) --ipv4address [address]: set the ipv4 interface address to use for the matter server listener (default all addresses) --ipv6address [address]: set the ipv6 interface address to use for the matter server listener (default all addresses) --frontend [port]: start the frontend on the given port (default 8283) --bind [address]: bind the frontend to the given address (default all addresses) --logger: set the matterbridge logger level: debug | info | notice | warn | error | fatal (default info) --filelogger: enable the matterbridge file logger (matterbridge.log) --matterlogger: set the matter.js logger level: debug | info | notice | warn | error | fatal (default info) --matterfilelogger: enable the matter.js file logger (matter.log) --sudo: force the use of sudo to install or update packages if the internal logic fails --nosudo: force not to use sudo to install or update packages if the internal logic fails --norestore: force not to automatically restore the matterbridge node storage and the matter storage from backup if it is corrupted --novirtual: disable the creation of the virtual devices Restart, Update and Reboot Matterbridge --root-camera: add the Power Source, Time Synchronization, TLS Certificate Management and TLS Client Management clusters on the Root endpoint, required by the camera device types --ssl: enable SSL for the frontend and the WebSocketServer (the server will use the certificates and switch to https) --tls: enable SSL for the frontend and the WebSocketServer (the server will use the certificates and switch to https) --mtls: enable mTLS for the frontend and the WebSocketServer (both server and client will use and require the certificates and switch to https); it also enables https, so --ssl --tls is not needed --vendorId: override the default vendorId 0xfff1 --vendorName: override the default vendorName "Matterbridge" --productId: override the default productId 0x8000 --productName: override the default productName "Matterbridge aggregator" --service: enable the service mode (used in the linux systemctl configuration file and macOS launchctl plist) --docker: enable the docker mode (used in the docker image) --homedir: override the home directory (default the os homedir) --delay [seconds]: set a delay in seconds before starting Matterbridge in the first 5 minutes from a reboot (default 120) --fixed_delay [seconds]: set a fixed delay in seconds before starting Matterbridge (default 120) --no-ansi: disable ANSI color output in the logs --reset-sessions: reset sessions and resumption records on shutdown (use only if your controller has issue reconnecting on restart) --configuration-version: increment by one the configuration version of all the server nodes when they go online (add a value to set it instead, i.e. --configuration-version 5) `); process.exit(0); }