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

Add field for changing target port if app gateway fails to start #50982

Open
wants to merge 3 commits into
base: master
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
3 changes: 3 additions & 0 deletions web/.storybook/preview.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { Theme } from '../packages/design/src/theme/themes/types';
import { ConfiguredThemeProvider } from '../packages/design/src/ThemeProvider';
import history from '../packages/teleport/src/services/history/history';
import { UserContextProvider } from '../packages/teleport/src/User';
import Logger, { ConsoleService } from '../packages/teleterm/src/logger';
import { StaticThemeProvider as TeletermThemeProvider } from '../packages/teleterm/src/ui/ThemeProvider';
import {
darkTheme as teletermDarkTheme,
Expand All @@ -36,6 +37,8 @@ initialize();

history.init();

Logger.init(new ConsoleService());

interface ThemeDecoratorProps {
theme: string;
title: string;
Expand Down
16 changes: 16 additions & 0 deletions web/packages/teleterm/src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,3 +69,19 @@ export class NullService implements LoggerService {
}
/* eslint-enable @typescript-eslint/no-unused-vars */
}

export class ConsoleService implements LoggerService {
createLogger(loggerName: string): types.Logger {
return {
warn(...args: any[]) {
console.warn(loggerName, ...args);
},
info(...args: any[]) {
console.info(loggerName, ...args);
},
error(...args: any[]) {
console.error(loggerName, ...args);
},
};
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ import {
import { makeDatabaseGateway } from 'teleterm/services/tshd/testHelpers';

import { OfflineGateway } from '../components/OfflineGateway';
import {
formSchema,
makeRenderFormControlsFromDefaultPort,
} from './DocumentGateway';
import { OnlineDocumentGateway } from './OnlineDocumentGateway';

type StoryProps = {
Expand Down Expand Up @@ -99,9 +103,10 @@ export function Story(props: StoryProps) {
const offlineGatewayProps: ComponentProps<typeof OfflineGateway> = {
connectAttempt: makeEmptyAttempt(),
reconnect: () => {},
gatewayPort: { isSupported: true, defaultPort: '1337' },
targetName: gateway.targetName,
gatewayKind: 'database',
formSchema,
renderFormControls: makeRenderFormControlsFromDefaultPort('1337'),
};

if (props.connectAttempt === 'error') {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/**
* Teleport
* Copyright (C) 2025 Gravitational, Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

import userEvent from '@testing-library/user-event';

import { render, screen } from 'design/utils/testing';

import { MockedUnaryCall } from 'teleterm/services/tshd/cloneableClient';
import {
makeDatabaseGateway,
makeRootCluster,
} from 'teleterm/services/tshd/testHelpers';
import { MockAppContextProvider } from 'teleterm/ui/fixtures/MockAppContextProvider';
import { MockAppContext } from 'teleterm/ui/fixtures/mocks';
import type * as docs from 'teleterm/ui/services/workspacesService';
import { DatabaseUri } from 'teleterm/ui/uri';

import { MockWorkspaceContextProvider } from '../fixtures/MockWorkspaceContextProvider';
import { DocumentGateway } from './DocumentGateway';

test('it allows reconnecting when the gateway fails to be created', async () => {
const user = userEvent.setup();

const appContext = new MockAppContext();
const cluster = makeRootCluster();
const gateway = makeDatabaseGateway();
const doc: docs.DocumentGateway = {
uri: '/docs/1',
kind: 'doc.gateway',
targetName: gateway.targetName,
targetUri: gateway.targetUri as DatabaseUri,
targetUser: gateway.targetUser,
targetSubresourceName: gateway.targetSubresourceName,
gatewayUri: gateway.uri,
origin: 'resource_table',
title: '',
status: '',
};
appContext.addRootClusterWithDoc(cluster, doc);

jest
.spyOn(appContext.tshd, 'createGateway')
.mockReturnValueOnce(
new MockedUnaryCall(undefined, new Error('Something went wrong'))
)
.mockReturnValueOnce(new MockedUnaryCall(gateway));

render(
<MockAppContextProvider appContext={appContext}>
<MockWorkspaceContextProvider>
<DocumentGateway visible doc={doc} />
</MockWorkspaceContextProvider>
</MockAppContextProvider>
);

expect(
await screen.findByText('Could not establish the connection')
).toBeInTheDocument();

await user.click(screen.getByText('Reconnect'));

expect(await screen.findByText('Close Connection')).toBeInTheDocument();
});
27 changes: 25 additions & 2 deletions web/packages/teleterm/src/ui/DocumentGateway/DocumentGateway.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,15 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

import { useMemo } from 'react';
import { z } from 'zod';

import { getCliCommandArgv0 } from 'teleterm/services/tshd/gateway';
import Document from 'teleterm/ui/Document';
import * as types from 'teleterm/ui/services/workspacesService';

import { OfflineGateway } from '../components/OfflineGateway';
import { PortFieldInput } from '../components/FieldInputs';
import { FormFields, OfflineGateway } from '../components/OfflineGateway';
import { useWorkspaceContext } from '../Documents';
import { OnlineDocumentGateway } from './OnlineDocumentGateway';
import { useGateway } from './useGateway';
Expand Down Expand Up @@ -63,15 +67,21 @@ export function DocumentGateway(props: {
documentsService.setLocation(cliDoc.uri);
};

const renderFormControls = useMemo(
() => makeRenderFormControlsFromDefaultPort(defaultPort),
[defaultPort]
);

if (!connected) {
return (
<Document visible={visible}>
<OfflineGateway
connectAttempt={connectAttempt}
reconnect={reconnect}
gatewayPort={{ isSupported: true, defaultPort }}
targetName={doc.targetName}
gatewayKind="database"
formSchema={formSchema}
renderFormControls={renderFormControls}
/>
</Document>
);
Expand All @@ -92,3 +102,16 @@ export function DocumentGateway(props: {
</Document>
);
}

export const formSchema = z.object({ [FormFields.LocalPort]: z.string() });

export const makeRenderFormControlsFromDefaultPort =
(defaultPort: string) => (isProcessing: boolean) => (
<PortFieldInput
name={FormFields.LocalPort}
label="Port (optional)"
defaultValue={defaultPort}
mb={0}
readonly={isProcessing}
/>
);
104 changes: 58 additions & 46 deletions web/packages/teleterm/src/ui/DocumentGateway/useGateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ import { retryWithRelogin } from 'teleterm/ui/utils';

export function useGateway(doc: DocumentGateway) {
const ctx = useAppContext();
const { clustersService } = ctx;
const { clustersService, usageService } = ctx;
const { documentsService } = useWorkspaceContext();
// The port to show as default in the input field in case creating a gateway fails.
// This is typically the case if someone reopens the app and the port of the gateway is already
Expand All @@ -46,51 +46,63 @@ export function useGateway(doc: DocumentGateway) {
);
const connected = !!gateway;

const [connectAttempt, createGateway] = useAsync(async (port: string) => {
documentsService.update(doc.uri, { status: 'connecting' });
let gw: Gateway;
const [connectAttempt, createGateway] = useAsync(
useCallback(
async (args: { localPort?: string; targetSubresourceName?: string }) => {
documentsService.update(doc.uri, { status: 'connecting' });
let gw: Gateway;

try {
gw = await retryWithRelogin(ctx, doc.targetUri, () =>
clustersService.createGateway({
targetUri: doc.targetUri,
localPort: port,
targetUser: doc.targetUser,
targetSubresourceName: doc.targetSubresourceName,
})
);
} catch (error) {
documentsService.update(doc.uri, { status: 'error' });
throw error;
}
documentsService.update(doc.uri, {
gatewayUri: gw.uri,
// Set the port on doc to match the one returned from the daemon. Teleterm doesn't let the
// user provide a port for the gateway, so instead we have to let the daemon use a random
// one.
//
// Setting it here makes it so that on app restart, Teleterm will restart the proxy with the
// same port number.
port: gw.localPort,
status: 'connected',
});
if (isDatabaseUri(doc.targetUri)) {
ctx.usageService.captureProtocolUse({
uri: doc.targetUri,
protocol: 'db',
origin: doc.origin,
accessThrough: 'local_proxy',
});
}
if (isAppUri(doc.targetUri)) {
ctx.usageService.captureProtocolUse({
uri: doc.targetUri,
protocol: 'app',
origin: doc.origin,
accessThrough: 'local_proxy',
});
}
});
try {
gw = await retryWithRelogin(ctx, doc.targetUri, () =>
clustersService.createGateway({
targetUri: doc.targetUri,
localPort: args.localPort,
targetUser: doc.targetUser,
targetSubresourceName:
args.targetSubresourceName || doc.targetSubresourceName,
})
);
} catch (error) {
documentsService.update(doc.uri, { status: 'error' });
throw error;
}
documentsService.update(doc.uri, {
gatewayUri: gw.uri,
// Set the port on doc to match the one returned from the daemon. By default,
// createGateway is called with an empty localPort, so the daemon creates a listener on a
// random port.
//
// Setting it here makes it so that on app restart, Teleterm will restart the proxy with the
// same port number.
//
// Alternatively, if createGateway was called from OfflineGateway, this will persist in
// the doc the local port chosen by the user.
port: gw.localPort,
// targetSubresourceName needs to be updated here in case the createGateway function was
// called from OfflineGateway.
targetSubresourceName: gw.targetSubresourceName,
status: 'connected',
});
if (isDatabaseUri(doc.targetUri)) {
usageService.captureProtocolUse({
uri: doc.targetUri,
protocol: 'db',
origin: doc.origin,
accessThrough: 'local_proxy',
});
}
if (isAppUri(doc.targetUri)) {
usageService.captureProtocolUse({
uri: doc.targetUri,
protocol: 'app',
origin: doc.origin,
accessThrough: 'local_proxy',
});
}
},
[clustersService, ctx, doc, documentsService, usageService]
)
);

const [disconnectAttempt, disconnect] = useAsync(async () => {
await clustersService.removeGateway(doc.gatewayUri);
Expand Down Expand Up @@ -146,7 +158,7 @@ export function useGateway(doc: DocumentGateway) {
// to open DocumentGateway while the gateway is already running. In that scenario, we must
// not attempt to create a gateway.
if (!gateway && connectAttempt.status === '') {
createGateway(doc.port);
createGateway({ localPort: doc.port });
}
},
// eslint-disable-next-line react-hooks/exhaustive-deps
Expand Down
Loading
Loading