1
0
mirror of https://github.com/lensapp/lens.git synced 2025-05-20 05:10:56 +00:00

Support port forwarding https protocol (#4119)

* added support for port-forwarding https

Signed-off-by: Jim Ehrismann <jehrismann@mirantis.com>

* added protocol to the port-forward list and details page. Added the port-forward address to the details page title

Signed-off-by: Jim Ehrismann <jehrismann@mirantis.com>

* predict the protocol based on the port name, some cleanup

Signed-off-by: Jim Ehrismann <jehrismann@mirantis.com>

* address review comments

Signed-off-by: Jim Ehrismann <jehrismann@mirantis.com>

* code reorg

Signed-off-by: Jim Ehrismann <jehrismann@mirantis.com>

* fix lint

Signed-off-by: Jim Ehrismann <jehrismann@mirantis.com>
This commit is contained in:
Jim Ehrismann 2021-10-25 11:25:37 -04:00 committed by GitHub
parent bd7ba9ff43
commit 353b79ab76
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
11 changed files with 120 additions and 39 deletions

View File

@ -34,6 +34,7 @@ interface PortForwardArgs {
name: string;
port: number;
forwardPort: number;
protocol?: string;
}
const internalPortRegex = /^forwarding from (?<address>.+) ->/i;
@ -47,7 +48,8 @@ class PortForward {
pf.kind == forward.kind &&
pf.name == forward.name &&
pf.namespace == forward.namespace &&
pf.port == forward.port
pf.port == forward.port &&
(!forward.protocol || pf.protocol == forward.protocol)
));
}
@ -58,6 +60,7 @@ class PortForward {
public name: string;
public port: number;
public forwardPort: number;
public protocol: string;
constructor(public kubeConfig: string, args: PortForwardArgs) {
this.clusterId = args.clusterId;
@ -66,6 +69,7 @@ class PortForward {
this.name = args.name;
this.port = args.port;
this.forwardPort = args.forwardPort;
this.protocol = args.protocol ?? "http";
}
public async start() {
@ -119,21 +123,21 @@ export class PortForwardRoute {
const { namespace, resourceType, resourceName } = params;
const port = Number(query.get("port"));
const forwardPort = Number(query.get("forwardPort"));
const protocol = query.get("protocol");
try {
let portForward = PortForward.getPortforward({
clusterId: cluster.id, kind: resourceType, name: resourceName,
namespace, port, forwardPort,
namespace, port, forwardPort, protocol,
});
let thePort = 0;
if (forwardPort > 0 && forwardPort < 65536) {
thePort = forwardPort;
}
if (!portForward) {
logger.info(`Creating a new port-forward ${namespace}/${resourceType}/${resourceName}:${port}`);
const thePort = 0 < forwardPort && forwardPort < 65536
? forwardPort
: 0;
portForward = new PortForward(await cluster.getProxyKubeconfigPath(), {
clusterId: cluster.id,
kind: resourceType,
@ -141,6 +145,7 @@ export class PortForwardRoute {
name: resourceName,
port,
forwardPort: thePort,
protocol,
});
const started = await portForward.start();
@ -169,10 +174,11 @@ export class PortForwardRoute {
const { namespace, resourceType, resourceName } = params;
const port = Number(query.get("port"));
const forwardPort = Number(query.get("forwardPort"));
const protocol = query.get("protocol");
const portForward = PortForward.getPortforward({
clusterId: cluster.id, kind: resourceType, name: resourceName,
namespace, port, forwardPort
namespace, port, forwardPort, protocol,
});
respondJson(response, { port: portForward?.forwardPort ?? null });
@ -189,6 +195,7 @@ export class PortForwardRoute {
name: f.name,
port: f.port,
forwardPort: f.forwardPort,
protocol: f.protocol,
})
);

View File

@ -23,7 +23,7 @@ import "./port-forward-details.scss";
import React from "react";
import { Link } from "react-router-dom";
import type { PortForwardItem } from "../../port-forward";
import { portForwardAddress, PortForwardItem } from "../../port-forward";
import { Drawer, DrawerItem } from "../drawer";
import { cssNames } from "../../utils";
import { podsApi, serviceApi } from "../../../common/k8s-api/endpoints";
@ -80,6 +80,9 @@ export class PortForwardDetails extends React.Component<Props> {
<DrawerItem name="Local Port">
{portForward.getForwardPort()}
</DrawerItem>
<DrawerItem name="Protocol">
{portForward.getProtocol()}
</DrawerItem>
<DrawerItem name="Status">
<span className={cssNames("status", portForward.getStatus().toLowerCase())}>{portForward.getStatus()}</span>
</DrawerItem>
@ -96,7 +99,7 @@ export class PortForwardDetails extends React.Component<Props> {
className="PortForwardDetails"
usePortal={true}
open={!!portForward}
title="Port Forward"
title={`Port Forward: ${portForwardAddress(portForward)}`}
onClose={hideDetails}
toolbar={toolbar}
>

View File

@ -57,7 +57,7 @@ export class PortForwardMenu extends React.Component<Props> {
<span className="title">Open</span>
</MenuItem>
<MenuItem onClick={() => PortForwardDialog.open(portForward)}>
<Icon material="edit" tooltip="Change port" interactive={toolbar} />
<Icon material="edit" tooltip="Change port or protocol" interactive={toolbar} />
<span className="title">Edit</span>
</MenuItem>
</>

View File

@ -37,6 +37,7 @@ enum columnId {
kind = "kind",
port = "port",
forwardPort = "forwardPort",
protocol = "protocol",
status = "status",
}
@ -102,6 +103,7 @@ export class PortForwards extends React.Component<Props> {
[columnId.kind]: item => item.getKind(),
[columnId.port]: item => item.getPort(),
[columnId.forwardPort]: item => item.getForwardPort(),
[columnId.protocol]: item => item.getProtocol(),
[columnId.status]: item => item.getStatus(),
}}
searchFilters={[
@ -114,6 +116,7 @@ export class PortForwards extends React.Component<Props> {
{ title: "Kind", className: "kind", sortBy: columnId.kind, id: columnId.kind },
{ title: "Pod Port", className: "port", sortBy: columnId.port, id: columnId.port },
{ title: "Local Port", className: "forwardPort", sortBy: columnId.forwardPort, id: columnId.forwardPort },
{ title: "Protocol", className: "protocol", sortBy: columnId.protocol, id: columnId.protocol },
{ title: "Status", className: "status", sortBy: columnId.status, id: columnId.status },
]}
renderTableContents={item => [
@ -122,6 +125,7 @@ export class PortForwards extends React.Component<Props> {
item.getKind(),
item.getPort(),
item.getForwardPort(),
item.getProtocol(),
{ title: item.getStatus(), className: item.getStatus().toLowerCase() },
]}
renderItemMenu={pf => (

View File

@ -28,7 +28,7 @@ import { observable, makeObservable, reaction } from "mobx";
import { cssNames } from "../../utils";
import { Notifications } from "../notifications";
import { Button } from "../button";
import { addPortForward, getPortForward, openPortForward, PortForwardDialog, portForwardStore, removePortForward } from "../../port-forward";
import { addPortForward, getPortForward, openPortForward, PortForwardDialog, portForwardStore, predictProtocol, removePortForward } from "../../port-forward";
import type { ForwardedPort } from "../../port-forward";
import { Spinner } from "../spinner";
@ -87,6 +87,7 @@ export class ServicePortComponent extends React.Component<Props> {
namespace: service.getNs(),
port: port.port,
forwardPort: this.forwardPort,
protocol: predictProtocol(port.name),
};
this.waiting = true;
@ -143,6 +144,7 @@ export class ServicePortComponent extends React.Component<Props> {
namespace: service.getNs(),
port: port.port,
forwardPort: this.forwardPort,
protocol: predictProtocol(port.name),
};
PortForwardDialog.open(portForward, { openInBrowser: true });

View File

@ -28,7 +28,7 @@ import { observable, makeObservable, reaction } from "mobx";
import { cssNames } from "../../utils";
import { Notifications } from "../notifications";
import { Button } from "../button";
import { addPortForward, getPortForward, openPortForward, PortForwardDialog, portForwardStore, removePortForward } from "../../port-forward";
import { addPortForward, getPortForward, openPortForward, PortForwardDialog, portForwardStore, predictProtocol, removePortForward } from "../../port-forward";
import type { ForwardedPort } from "../../port-forward";
import { Spinner } from "../spinner";
@ -91,6 +91,7 @@ export class PodContainerPort extends React.Component<Props> {
namespace: pod.getNs(),
port: port.containerPort,
forwardPort: this.forwardPort,
protocol: predictProtocol(port.name),
};
this.waiting = true;
@ -149,6 +150,7 @@ export class PodContainerPort extends React.Component<Props> {
namespace: pod.getNs(),
port: port.containerPort,
forwardPort: this.forwardPort,
protocol: predictProtocol(port.name),
};
PortForwardDialog.open(portForward, { openInBrowser: true });

View File

@ -22,3 +22,4 @@
export * from "./port-forward.store";
export * from "./port-forward-item";
export * from "./port-forward-dialog";
export * from "./port-forward-utils";

View File

@ -44,7 +44,8 @@ interface PortForwardDialogOpenOptions {
const dialogState = observable.object({
isOpen: false,
data: null as ForwardedPort,
openInBrowser: false
useHttps: false,
openInBrowser: false,
});
@observer
@ -60,6 +61,7 @@ export class PortForwardDialog extends Component<Props> {
static open(portForward: ForwardedPort, options: PortForwardDialogOpenOptions = { openInBrowser: false }) {
dialogState.isOpen = true;
dialogState.data = portForward;
dialogState.useHttps = portForward.protocol === "https";
dialogState.openInBrowser = options.openInBrowser;
}
@ -96,6 +98,8 @@ export class PortForwardDialog extends Component<Props> {
try {
let port: number;
portForward.protocol = dialogState.useHttps ? "https" : "http";
if (currentPort) {
port = await modifyPortForward(portForward, desiredPort);
} else {
@ -131,6 +135,13 @@ export class PortForwardDialog extends Component<Props> {
onChange={this.changePort}
/>
</div>
<Checkbox
data-testid="port-forward-https"
theme="light"
label="https"
value={dialogState.useHttps}
onChange={value => dialogState.useHttps = value}
/>
<Checkbox
data-testid="port-forward-open"
theme="light"

View File

@ -30,6 +30,7 @@ export interface ForwardedPort {
name: string;
port: number;
forwardPort: number;
protocol?: string;
}
export class PortForwardItem implements ItemObject {
@ -39,6 +40,7 @@ export class PortForwardItem implements ItemObject {
name: string;
port: number;
forwardPort: number;
protocol: string;
constructor(pf: ForwardedPort) {
this.clusterId = pf.clusterId;
@ -47,6 +49,7 @@ export class PortForwardItem implements ItemObject {
this.name = pf.name;
this.port = pf.port;
this.forwardPort = pf.forwardPort;
this.protocol = pf.protocol ?? "http";
autoBind(this);
}
@ -79,6 +82,10 @@ export class PortForwardItem implements ItemObject {
return this.forwardPort;
}
getProtocol() {
return this.protocol;
}
getStatus() {
return "Active"; // to-do allow port-forward-items to be stopped (without removing them)
}

View File

@ -0,0 +1,53 @@
/**
* Copyright (c) 2021 OpenLens Authors
*
* 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.
*/
import { openExternal } from "../utils";
import { Notifications } from "../components/notifications";
import type { ForwardedPort } from "./port-forward-item";
import logger from "../../common/logger";
export function portForwardAddress(portForward: ForwardedPort) {
return `${portForward.protocol ?? "http"}://localhost:${portForward.forwardPort}`;
}
export function openPortForward(portForward: ForwardedPort) {
const browseTo = portForwardAddress(portForward);
openExternal(browseTo)
.catch(error => {
logger.error(`failed to open in browser: ${error}`, {
clusterId: portForward.clusterId,
port: portForward.port,
kind: portForward.kind,
namespace: portForward.namespace,
name: portForward.name,
});
Notifications.error(`Failed to open ${browseTo} in browser`);
}
);
}
export function predictProtocol(name: string) {
return name === "https" ? "https" : "http";
}

View File

@ -22,11 +22,10 @@
import { makeObservable, observable, reaction } from "mobx";
import { ItemStore } from "../../common/item.store";
import { autoBind, createStorage, disposer, getHostedClusterId, openExternal } from "../utils";
import { autoBind, createStorage, disposer, getHostedClusterId } from "../utils";
import { ForwardedPort, PortForwardItem } from "./port-forward-item";
import { apiBase } from "../api";
import { waitUntilFree } from "tcp-port-used";
import { Notifications } from "../components/notifications";
import logger from "../../common/logger";
export class PortForwardStore extends ItemStore<PortForwardItem> {
@ -88,7 +87,7 @@ export class PortForwardStore extends ItemStore<PortForwardItem> {
if (index === -1) {
return null;
}
return this.getItems()[index];
}
}
@ -105,8 +104,10 @@ export async function addPortForward(portForward: ForwardedPort): Promise<number
let response: PortForwardResult;
try {
response = await apiBase.post<PortForwardResult>(`/pods/port-forward/${portForward.namespace}/${portForward.kind}/${portForward.name}?port=${portForward.port}&forwardPort=${portForward.forwardPort}`);
const protocol = portForward.protocol ?? "http";
response = await apiBase.post<PortForwardResult>(`/pods/port-forward/${portForward.namespace}/${portForward.kind}/${portForward.name}?port=${portForward.port}&forwardPort=${portForward.forwardPort}&protocol=${protocol}`);
if (response?.port && response.port != +portForward.forwardPort) {
logger.warn(`specified ${portForward.forwardPort} got ${response.port}`);
}
@ -119,11 +120,19 @@ export async function addPortForward(portForward: ForwardedPort): Promise<number
return response?.port;
}
function getProtocolQuery(protocol: string) {
if (protocol) {
return `&protocol=${protocol}`;
}
return "";
}
export async function getPortForward(portForward: ForwardedPort): Promise<number> {
let response: PortForwardResult;
try {
response = await apiBase.get<PortForwardResult>(`/pods/port-forward/${portForward.namespace}/${portForward.kind}/${portForward.name}?port=${portForward.port}&forwardPort=${portForward.forwardPort}`);
response = await apiBase.get<PortForwardResult>(`/pods/port-forward/${portForward.namespace}/${portForward.kind}/${portForward.name}?port=${portForward.port}&forwardPort=${portForward.forwardPort}${getProtocolQuery(portForward.protocol)}`);
} catch (error) {
logger.warn("Error getting port-forward:", error, portForward);
throw(error);
@ -168,22 +177,4 @@ export async function getPortForwards(): Promise<ForwardedPort[]> {
}
}
export function openPortForward(portForward: ForwardedPort) {
const browseTo = `http://localhost:${portForward.forwardPort}`;
openExternal(browseTo)
.catch(error => {
logger.error(`failed to open in browser: ${error}`, {
clusterId: portForward.clusterId,
port: portForward.port,
kind: portForward.kind,
namespace: portForward.namespace,
name: portForward.name,
});
Notifications.error(`Failed to open ${browseTo} in browser`);
}
);
}
export const portForwardStore = new PortForwardStore();