Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: handle error so that it is shown in both page and task manager #247

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/crc-setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,12 @@ export async function needSetup(): Promise<boolean> {
await execPromise(getCrcCli(), ['setup', '--check-only']);
return false;
} catch (e) {
console.log(e);
return true;
}
}

// eslint-disable-next-line @typescript-eslint/no-unused-vars
export async function setUpCrc(logger: extensionApi.Logger, askForPreset = false): Promise<boolean> {
export async function setUpCrc(askForPreset = false): Promise<boolean> {
if (askForPreset) {
const preset = await extensionApi.window.showInformationMessage(
'Which preset bundle would you like to use with OpenShift Local. MicroShift, provides a lightweight and optimized environment with a limited set of services. OpenShift, provides a single node OpenShift cluster with a fuller set of services, including a web console (requires more resources).',
Expand Down
5 changes: 3 additions & 2 deletions src/crc-start.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { startCrc } from './crc-start.js';
import * as logProvider from './log-provider.js';
import * as daemon from './daemon-commander.js';
import type { StartInfo } from './types.js';
import { getLoggerCallback } from './util.js';

vi.mock('@podman-desktop/api', async () => {
return {
Expand All @@ -44,7 +45,7 @@ test('setUpCRC is skipped if already setup, it just perform the daemon start com
{
updateStatus: vi.fn(),
} as unknown as extensionApi.Provider,
{} as extensionApi.Logger,
getLoggerCallback(),
{ logUsage: vi.fn() } as unknown as extensionApi.TelemetryLogger,
);
expect(setUpMock).not.toBeCalled();
Expand All @@ -65,7 +66,7 @@ test('set up CRC and then start the daemon', async () => {
{
updateStatus: vi.fn(),
} as unknown as extensionApi.Provider,
{} as extensionApi.Logger,
getLoggerCallback(),
{ logUsage: vi.fn() } as unknown as extensionApi.TelemetryLogger,
);
expect(setUpMock).toBeCalled();
Expand Down
20 changes: 9 additions & 11 deletions src/crc-start.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ const missingPullSecret = 'Failed to ask for pull secret';

export async function startCrc(
provider: extensionApi.Provider,
logger: extensionApi.Logger,
loggerCallback: (data: string) => void,
telemetryLogger: extensionApi.TelemetryLogger,
): Promise<boolean> {
telemetryLogger.logUsage('crc.start', {
Expand All @@ -49,16 +49,15 @@ export async function startCrc(
if (isNeedSetup) {
try {
crcStatus.setSetupRunning(true);
await setUpCrc(logger);
await setUpCrc();
} catch (error) {
logger.error(error);
provider.updateStatus('stopped');
return;
throw error;
} finally {
crcStatus.setSetupRunning(false);
}
}
await crcLogProvider.startSendingLogs(logger);
await crcLogProvider.startSendingLogs(loggerCallback);
const result = await commander.start();
if (result.Status === 'Running') {
provider.updateStatus('started');
Expand All @@ -72,26 +71,26 @@ export async function startCrc(
// check that crc missing pull secret
if (err.message.startsWith(missingPullSecret)) {
// ask user to provide pull secret
if (await askAndStorePullSecret(logger)) {
if (await askAndStorePullSecret()) {
// if pull secret provided try to start again
return startCrc(provider, logger, telemetryLogger);
return startCrc(provider, loggerCallback, telemetryLogger);
} else {
throw new Error('Could not start without pullsecret!');
throw new Error(`${productName} start error: VM cannot be started without the pullsecret`);
}
} else if (err.name === 'RequestError' && err.code === 'ECONNRESET') {
// look like crc start normally, but we receive empty response from socket, so 'got' generate an error
provider.updateStatus('started');
return true;
}
}
await extensionApi.window.showErrorMessage(`${productName} start error: ${err}`);
console.error(err);
provider.updateStatus('stopped');
throw new Error(`${productName} start error: ${err}`);
}
return false;
}

async function askAndStorePullSecret(logger: extensionApi.Logger): Promise<boolean> {
async function askAndStorePullSecret(): Promise<boolean> {
let pullSecret: string;
const authSession: extensionApi.AuthenticationSession | undefined = await extensionApi.authentication.getSession(
'redhat.authentication-provider',
Expand Down Expand Up @@ -147,7 +146,6 @@ async function askAndStorePullSecret(logger: extensionApi.Logger): Promise<boole
return true;
} catch (error) {
console.error(error);
logger.error(error);
}
return false;
}
4 changes: 2 additions & 2 deletions src/crc-status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export class CrcStatus {
try {
// we don't need to update status while setup is going
if (this.isSetupGoing) {
this._status = createStatus('Starting', this._status.Preset);
this._status = createStatus('Stopped', this._status.Preset);
return;
}
const oldStatus = this._status;
Expand Down Expand Up @@ -93,7 +93,7 @@ export class CrcStatus {
setSetupRunning(setup: boolean): void {
if (setup) {
this.isSetupGoing = true;
this._status = createStatus('Starting', this._status.Preset);
this._status = createStatus('Stopped', this._status.Preset);
} else {
this.isSetupGoing = false;
}
Expand Down
1 change: 1 addition & 0 deletions src/daemon-commander.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ export class DaemonCommander {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const response = await (got as any).post(url, {
body: value,
enableUnixSockets: true,
throwHttpErrors: false,
retry: {
limit: 0,
Expand Down
88 changes: 51 additions & 37 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ import * as path from 'node:path';
import * as os from 'node:os';
import * as fs from 'node:fs';
import { commander, isDaemonRunning } from './daemon-commander.js';
import { defaultPreset, getPresetLabel, isWindows, productName, providerId } from './util.js';
import { defaultPreset, getLoggerCallback, getPresetLabel, isWindows, productName, providerId } from './util.js';
import type { CrcVersion } from './crc-cli.js';
import { getPreset } from './crc-cli.js';
import { getCrcVersion } from './crc-cli.js';
Expand All @@ -30,17 +30,16 @@ import { CrcInstall } from './install/crc-install.js';

import { crcStatus } from './crc-status.js';
import { startCrc } from './crc-start.js';
import { needSetup, setUpCrc } from './crc-setup.js';
import { deleteCrc, registerDeleteCommand } from './crc-delete.js';
import { presetChangedEvent, saveConfig, syncPreferences } from './preferences.js';
import { stopCrc } from './crc-stop.js';
import { registerOpenTerminalCommand } from './dev-terminal.js';
import { commandManager } from './command.js';
import { registerOpenConsoleCommand } from './crc-console.js';
import { registerLogInCommands } from './login-commands.js';
import { defaultLogger } from './logger.js';
import { pushImageToCrcCluster } from './image-handler.js';
import type { Preset } from './types.js';
import { needSetup, setUpCrc } from './crc-setup.js';

const CRC_PUSH_IMAGE_TO_CLUSTER = 'crc.image.push.to.cluster';
const CRC_PRESET_KEY = 'crc.crcPreset';
Expand Down Expand Up @@ -219,15 +218,19 @@ function registerProviderConnectionFactory(
extensionContext: extensionApi.ExtensionContext,
telemetryLogger: extensionApi.TelemetryLogger,
): void {
let justInitialized = false;
connectionFactoryDisposable = provider.setKubernetesProviderConnectionFactory(
{
initialize: async () => {
await createCrcVm(provider, extensionContext, telemetryLogger, defaultLogger);
await initializeCrc(provider, extensionContext, telemetryLogger);
justInitialized = true;
},
create: async (params, logger) => {
await presetChanged(provider, extensionContext, telemetryLogger);
await saveConfig(params);
if (params['crc.factory.start.now']) {
if (params['crc.factory.start.now'] || justInitialized) {
justInitialized = false;
await connectToCrc();
await createCrcVm(provider, extensionContext, telemetryLogger, logger);
}
},
Expand All @@ -248,18 +251,11 @@ async function createCrcVm(
logger: extensionApi.Logger,
): Promise<void> {
// we already have an instance
if (crcStatus.status.CrcStatus !== 'No Cluster' && !isNeedSetup()) {
if (crcStatus.status.CrcStatus !== 'No Cluster') {
return;
}

if (isNeedSetup()) {
const initResult = await initializeCrc(provider, extensionContext, telemetryLogger, logger);
if (!initResult) {
throw new Error(`${productName} not initialized.`);
}
}

const hasStarted = await startCrc(provider, logger, telemetryLogger);
const hasStarted = await startCrc(provider, getLoggerCallback(undefined, logger), telemetryLogger);
if (!connectionDisposable && hasStarted) {
addCommands(telemetryLogger);
await presetChanged(provider, extensionContext, telemetryLogger);
Expand All @@ -270,29 +266,43 @@ async function initializeCrc(
provider: extensionApi.Provider,
extensionContext: extensionApi.ExtensionContext,
telemetryLogger: extensionApi.TelemetryLogger,
logger: extensionApi.Logger,
): Promise<boolean> {
const hasSetupFinished = await setUpCrc(logger, true);
if (hasSetupFinished) {
await needSetup();
await connectToCrc();
await presetChanged(provider, extensionContext, telemetryLogger);
addCommands(telemetryLogger);
await syncPreferences(provider, extensionContext, telemetryLogger);
): Promise<void> {
const hasToBeSetup = await needSetup();
if (hasToBeSetup) {
crcStatus.setSetupRunning(true);
let hasSetupFinished = false;
try {
hasSetupFinished = await setUpCrc(true);
} catch (e) {
console.log(String(e));
} finally {
crcStatus.setSetupRunning(false);
}
if (!hasSetupFinished) {
throw new Error(`Failed at initializing ${productName}`);
}
}
return hasSetupFinished;

addCommands(telemetryLogger);
await syncPreferences(provider, extensionContext, telemetryLogger);
await presetChanged(provider, extensionContext, telemetryLogger);
provider.updateStatus('configured');
}

function addCommands(telemetryLogger: extensionApi.TelemetryLogger): void {
registerOpenTerminalCommand();
registerOpenConsoleCommand();
registerLogInCommands();
registerDeleteCommand();

commandManager.addCommand(CRC_PUSH_IMAGE_TO_CLUSTER, image => {
telemetryLogger.logUsage('pushImage');
return pushImageToCrcCluster(image);
});
try {
registerOpenTerminalCommand();
registerOpenConsoleCommand();
registerLogInCommands();
registerDeleteCommand();

commandManager.addCommand(CRC_PUSH_IMAGE_TO_CLUSTER, image => {
telemetryLogger.logUsage('pushImage');
pushImageToCrcCluster(image).catch((e: unknown) => console.error(String(e)));
});
} catch (e) {
// do nothing
}
}

function deleteCommands(): void {
Expand Down Expand Up @@ -338,24 +348,28 @@ function registerOpenShiftLocalCluster(
extensionContext: extensionApi.ExtensionContext,
telemetryLogger: extensionApi.TelemetryLogger,
): void {
const status = () => crcStatus.getConnectionStatus();
const apiURL = 'https://api.crc.testing:6443';
const kubernetesProviderConnection: extensionApi.KubernetesProviderConnection = {
name,
endpoint: {
apiURL,
},
status,
status: () => crcStatus.getConnectionStatus(),
};

connectionDisposable = provider.registerKubernetesProviderConnection(kubernetesProviderConnection);
kubernetesProviderConnection.lifecycle = {
delete: () => {
return handleDelete(provider, extensionContext, telemetryLogger);
},
start: async ctx => {
start: async (ctx, logger) => {
provider.updateStatus('starting');
await startCrc(provider, ctx.log, telemetryLogger);
try {
await startCrc(provider, getLoggerCallback(ctx, logger), telemetryLogger);
} catch (e) {
logger.error(e);
throw e;
}
},
stop: () => {
provider.updateStatus('stopping');
Expand Down
2 changes: 1 addition & 1 deletion src/install/crc-install.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,7 @@ export class CrcInstall {
provider.updateVersion(newInstalledCrc.version);
let setupResult = false;
if (await needSetup()) {
setupResult = await setUpCrc(logger, true);
setupResult = await setUpCrc(true);
}
installFinishedFn(setupResult, newInstalledCrc);
}
Expand Down
5 changes: 2 additions & 3 deletions src/log-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,22 +16,21 @@
* SPDX-License-Identifier: Apache-2.0
***********************************************************************/

import type { Logger } from '@podman-desktop/api';
import type { DaemonCommander } from './daemon-commander.js';
import { commander } from './daemon-commander.js';

export class LogProvider {
private timeout: NodeJS.Timeout;
constructor(private readonly commander: DaemonCommander) {}

async startSendingLogs(logger: Logger): Promise<void> {
async startSendingLogs(loggerCallback: (data: string) => void): Promise<void> {
let lastLogLine = 0;
this.timeout = setInterval(async () => {
try {
const logs = await this.commander.logs();
const logsDiff: string[] = logs.Messages.slice(lastLogLine, logs.Messages.length - 1);
lastLogLine = logs.Messages.length;
logger.log(logsDiff.join('\n'));
loggerCallback(logsDiff.join('\n'));
} catch (e) {
console.log('Logs tick: ' + e);
}
Expand Down
4 changes: 2 additions & 2 deletions src/preferences.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import * as extensionApi from '@podman-desktop/api';
import type { Configuration, Preset } from './types.js';
import { commander } from './daemon-commander.js';
import { isEmpty, productName } from './util.js';
import { getLoggerCallback, isEmpty, productName } from './util.js';
import { crcStatus } from './crc-status.js';
import { stopCrc } from './crc-stop.js';
import { deleteCrc } from './crc-delete.js';
Expand Down Expand Up @@ -337,7 +337,7 @@ async function handleRecreate(
} else if (result === 'Delete and Restart') {
await stopCrc(telemetryLogger);
await deleteCrc();
await startCrc(provider, defaultLogger, telemetryLogger);
await startCrc(provider, getLoggerCallback(undefined, defaultLogger), telemetryLogger);
return true;
} else if (result === 'Delete') {
await deleteCrc();
Expand Down
43 changes: 43 additions & 0 deletions src/util.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/**********************************************************************
* Copyright (C) 2024 Red Hat, Inc.
*
* 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.
*
* SPDX-License-Identifier: Apache-2.0
***********************************************************************/

import type * as extensionApi from '@podman-desktop/api';
import { expect, test, vi } from 'vitest';
import { getLoggerCallback } from './util';

test('check logger passed to getLoggerCallback is actually called with data', async () => {
const logMock = vi.fn();
const logger = {
log: logMock,
} as unknown as extensionApi.Logger;
const callback = getLoggerCallback(undefined, logger);
callback('data');
expect(logMock).toBeCalledWith('data');
});

test('check logger passed to getLoggerCallback is actually called with data', async () => {
const logMock = vi.fn();
const context = {
log: {
log: logMock,
},
} as unknown as extensionApi.LifecycleContext;
const callback = getLoggerCallback(context);
callback('data2');
expect(logMock).toBeCalledWith('data2');
});
Loading