From 1b052ad16be1e8eeaf7434f357668d632cbf2dcd Mon Sep 17 00:00:00 2001 From: Fedor Indutny <79877362+indutny-signal@users.noreply.github.com> Date: Mon, 9 May 2022 18:12:04 -0700 Subject: [PATCH] Report process cpu/memory usage in debug log --- ACKNOWLEDGMENTS.md | 12 ++++++ package.json | 1 + ts/logging/debuglogs.ts | 65 +++++++++++++++++++----------- ts/logging/main_process_logging.ts | 38 ++++++----------- ts/logging/shared.ts | 2 + ts/util/deleteAllLogs.ts | 19 +++------ yarn.lock | 10 ++--- 7 files changed, 80 insertions(+), 67 deletions(-) diff --git a/ACKNOWLEDGMENTS.md b/ACKNOWLEDGMENTS.md index b64e145b2..19b4d8545 100644 --- a/ACKNOWLEDGMENTS.md +++ b/ACKNOWLEDGMENTS.md @@ -2563,6 +2563,18 @@ Signal Desktop makes use of the following open source projects. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +## p-timeout + + MIT License + + Copyright (c) Sindre Sorhus (https://sindresorhus.com) + + Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + ## parchment Copyright (c) 2015, Jason Chen diff --git a/package.json b/package.json index acdcfe148..aa402d792 100644 --- a/package.json +++ b/package.json @@ -134,6 +134,7 @@ "p-map": "2.1.0", "p-props": "4.0.0", "p-queue": "6.6.2", + "p-timeout": "4.1.0", "parchment": "1.1.4", "pify": "3.0.0", "pino": "6.11.1", diff --git a/ts/logging/debuglogs.ts b/ts/logging/debuglogs.ts index d431f60e6..2bab8a59a 100644 --- a/ts/logging/debuglogs.ts +++ b/ts/logging/debuglogs.ts @@ -39,6 +39,7 @@ const getHeader = ( capabilities, remoteConfig, statistics, + appMetrics, user, }: Omit, nodeVersion: string, @@ -56,6 +57,29 @@ const getHeader = ( headerSection('User info', user), headerSection('Capabilities', capabilities), headerSection('Remote config', remoteConfig), + headerSection( + 'Metrics', + appMetrics.reduce((acc, stats, index) => { + const { + type = '?', + serviceName = '?', + name = '?', + cpu, + memory, + } = stats; + + const processId = `${index}:${type}/${serviceName}/${name}`; + + return { + ...acc, + [processId]: + `cpuUsage=${cpu.percentCPUUsage.toFixed(2)} ` + + `wakeups=${cpu.idleWakeupsPerSecond} ` + + `workingMemory=${memory.workingSetSize} ` + + `peakWorkingMemory=${memory.peakWorkingSetSize}`, + }; + }, {}) + ), headerSection('Statistics', statistics), headerSectionTitle('Logs'), ].join('\n'); @@ -79,32 +103,27 @@ function formatLine(mightBeEntry: unknown): string { return `${getLevel(entry.level)} ${entry.time} ${entry.msg}`; } -export function fetch( +export async function fetch( nodeVersion: string, appVersion: string ): Promise { - return new Promise(resolve => { - ipc.send('fetch-log'); + const data: unknown = await ipc.invoke('fetch-log'); - ipc.on('fetched-log', (_event, data: unknown) => { - let header: string; - let body: string; - if (isFetchLogIpcData(data)) { - const { logEntries } = data; - header = getHeader(data, nodeVersion, appVersion); - body = logEntries.map(formatLine).join('\n'); - } else { - header = headerSectionTitle('Partial logs'); - const entry: LogEntryType = { - level: LogLevel.Error, - msg: 'Invalid IPC data when fetching logs; dropping all logs', - time: new Date().toISOString(), - }; - body = formatLine(entry); - } + let header: string; + let body: string; + if (isFetchLogIpcData(data)) { + const { logEntries } = data; + header = getHeader(data, nodeVersion, appVersion); + body = logEntries.map(formatLine).join('\n'); + } else { + header = headerSectionTitle('Partial logs'); + const entry: LogEntryType = { + level: LogLevel.Error, + msg: 'Invalid IPC data when fetching logs; dropping all logs', + time: new Date().toISOString(), + }; + body = formatLine(entry); + } - const result = `${header}\n${body}`; - resolve(result); - }); - }); + return `${header}\n${body}`; } diff --git a/ts/logging/main_process_logging.ts b/ts/logging/main_process_logging.ts index 084198364..d3649a3e7 100644 --- a/ts/logging/main_process_logging.ts +++ b/ts/logging/main_process_logging.ts @@ -20,6 +20,7 @@ import rimraf from 'rimraf'; import { createStream } from 'rotating-file-stream'; import type { LoggerType } from '../types/Logging'; +import * as durations from '../util/durations'; import * as log from './log'; import { Environment, getEnvironment } from '../environment'; @@ -56,6 +57,13 @@ export async function initialize( const logPath = join(basePath, 'logs'); mkdirp.sync(logPath); + let appMetrics = app.getAppMetrics(); + + setInterval(() => { + // CPU stats are computed since the last call to `getAppMetrics`. + appMetrics = app.getAppMetrics(); + }, 30 * durations.SECOND).unref(); + try { await cleanupLogs(logPath); } catch (error) { @@ -103,7 +111,7 @@ export async function initialize( timestamp: pino.stdTimeFunctions.isoTime, }); - ipc.on('fetch-log', async event => { + ipc.handle('fetch-log', async () => { const mainWindow = getMainWindow(); if (!mainWindow) { logger.info('Logs were requested, but the main window is missing'); @@ -118,6 +126,7 @@ export async function initialize( ]); data = { logEntries, + appMetrics, ...rest, }; } catch (error) { @@ -125,25 +134,10 @@ export async function initialize( return; } - try { - event.sender.send('fetched-log', data); - } catch (err: unknown) { - // NOTE(evanhahn): We don't want to send a message to a window that's closed. - // I wanted to use `event.sender.isDestroyed()` but that seems to fail. - // Instead, we attempt the send and catch the failure as best we can. - const hasUserClosedWindow = isProbablyObjectHasBeenDestroyedError(err); - if (hasUserClosedWindow) { - logger.info('Logs were requested, but it seems the window was closed'); - } else { - logger.error( - 'Problem replying with fetched logs', - err instanceof Error && err.stack ? err.stack : err - ); - } - } + return data; }); - ipc.on('delete-all-logs', async event => { + ipc.handle('delete-all-logs', async () => { // Restart logging when the streams will close shouldRestart = true; @@ -152,8 +146,6 @@ export async function initialize( } catch (error) { logger.error(`Problem deleting all logs: ${error.stack}`); } - - event.sender.send('delete-all-logs-complete'); }); globalLogger = logger; @@ -335,7 +327,7 @@ export function fetchLogs(logPath: string): Promise> { export const fetchAdditionalLogData = ( mainWindow: BrowserWindow -): Promise> => +): Promise> => new Promise(resolve => { mainWindow.webContents.send('additional-log-data-request'); ipc.once('additional-log-data-response', (_event, data) => { @@ -352,10 +344,6 @@ function logAtLevel(level: LogLevel, ...args: ReadonlyArray) { } } -function isProbablyObjectHasBeenDestroyedError(err: unknown): boolean { - return err instanceof Error && err.message === 'Object has been destroyed'; -} - // This blows up using mocha --watch, so we ensure it is run just once if (!console._log) { log.setLogAtLevel(logAtLevel); diff --git a/ts/logging/shared.ts b/ts/logging/shared.ts index 00f4b7c26..5912c9f6f 100644 --- a/ts/logging/shared.ts +++ b/ts/logging/shared.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: AGPL-3.0-only import pino from 'pino'; +import type { ProcessMetric } from 'electron'; import { isRecord } from '../util/isRecord'; import { redactAll } from '../util/privacy'; import { missingCaseError } from '../util/missingCaseError'; @@ -15,6 +16,7 @@ export type FetchLogIpcData = { remoteConfig: Record; statistics: Record; user: Record; + appMetrics: ReadonlyArray; // We expect `logEntries` to be `Array`, but we don't validate that // upfront—we only validate it when we go to log each line. This improves the diff --git a/ts/util/deleteAllLogs.ts b/ts/util/deleteAllLogs.ts index c2946834d..83f43dee1 100644 --- a/ts/util/deleteAllLogs.ts +++ b/ts/util/deleteAllLogs.ts @@ -2,23 +2,14 @@ // SPDX-License-Identifier: AGPL-3.0-only import { ipcRenderer } from 'electron'; +import pTimeout from 'p-timeout'; import { beforeRestart } from '../logging/set_up_renderer_logging'; +import * as durations from './durations'; export function deleteAllLogs(): Promise { - return new Promise((resolve, reject) => { - // Restart logging again when the file stream close - beforeRestart(); + // Restart logging again when the file stream close + beforeRestart(); - const timeout = setTimeout(() => { - reject(new Error('Request to delete all logs timed out')); - }, 5000); - - ipcRenderer.once('delete-all-logs-complete', () => { - clearTimeout(timeout); - resolve(); - }); - - ipcRenderer.send('delete-all-logs'); - }); + return pTimeout(ipcRenderer.invoke('delete-all-logs'), 5 * durations.SECOND); } diff --git a/yarn.lock b/yarn.lock index 848d3340c..8ee63c6ef 100644 --- a/yarn.lock +++ b/yarn.lock @@ -11411,6 +11411,11 @@ p-retry@^4.5.0: "@types/retry" "^0.12.0" retry "^0.13.1" +p-timeout@4.1.0, p-timeout@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/p-timeout/-/p-timeout-4.1.0.tgz#788253c0452ab0ffecf18a62dff94ff1bd09ca0a" + integrity sha512-+/wmHtzJuWii1sXn3HCuH/FTwGhrp4tmJTxSKJbfS+vkipci6osxXM5mY0jUiRzWKMTgUT8l7HFbeSwZAynqHw== + p-timeout@^3.2.0: version "3.2.0" resolved "https://registry.yarnpkg.com/p-timeout/-/p-timeout-3.2.0.tgz#c7e17abc971d2a7962ef83626b35d635acf23dfe" @@ -11418,11 +11423,6 @@ p-timeout@^3.2.0: dependencies: p-finally "^1.0.0" -p-timeout@^4.1.0: - version "4.1.0" - resolved "https://registry.yarnpkg.com/p-timeout/-/p-timeout-4.1.0.tgz#788253c0452ab0ffecf18a62dff94ff1bd09ca0a" - integrity sha512-+/wmHtzJuWii1sXn3HCuH/FTwGhrp4tmJTxSKJbfS+vkipci6osxXM5mY0jUiRzWKMTgUT8l7HFbeSwZAynqHw== - p-try@^2.0.0: version "2.0.0" resolved "https://registry.yarnpkg.com/p-try/-/p-try-2.0.0.tgz#85080bb87c64688fa47996fe8f7dfbe8211760b1"