100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
Gateways: Add option to close tunnels automatically after X minutes (#1492)
Wouter Born7fbc29f54a8a
diff --git a/manager/src/main/java/org/openremote/manager/gateway/GatewayService.java b/manager/src/main/java/org/openremote/manager/gateway/GatewayService.javaindex c0d8e73cc..26816bfe6 100644--- a/manager/src/main/java/org/openremote/manager/gateway/GatewayService.java+++ b/manager/src/main/java/org/openremote/manager/gateway/GatewayService.java@@ -56,6 +56,7 @@ import org.openremote.model.syslog.SyslogCategory;import org.openremote.model.util.TextUtil;import org.openremote.model.value.MetaItemType;+import java.time.Duration;import java.util.*;import java.util.concurrent.*;import java.util.concurrent.atomic.AtomicBoolean;@@ -94,6 +95,7 @@ public class GatewayService extends RouteBuilder implements ContainerService {public static final String OR_GATEWAY_TUNNEL_SSH_PORT = "OR_GATEWAY_TUNNEL_SSH_PORT";public static final String OR_GATEWAY_TUNNEL_TCP_START = "OR_GATEWAY_TUNNEL_TCP_START";public static final String OR_GATEWAY_TUNNEL_HOSTNAME = "OR_GATEWAY_TUNNEL_HOSTNAME";+ public static final String OR_GATEWAY_TUNNEL_AUTO_CLOSE_MINUTES = "OR_GATEWAY_TUNNEL_AUTO_CLOSE_MINUTES";public static final int OR_GATEWAY_TUNNEL_TCP_START_DEFAULT = 9000;protected AssetStorageService assetStorageService;protected AssetProcessingService assetProcessingService;@@ -109,6 +111,7 @@ public class GatewayService extends RouteBuilder implements ContainerService {protected String tunnelHostname;protected int tunnelSSHPort;protected int tunnelTCPStart;+ protected int tunnelAutoCloseMinutes;/*** Maps gateway asset IDs to connections; note that gateway asset IDs are stored lower case so that they can be@@ -232,6 +235,7 @@ public class GatewayService extends RouteBuilder implements ContainerService {tunnelSSHPort = getInteger(container.getConfig(), OR_GATEWAY_TUNNEL_SSH_PORT, 0);tunnelTCPStart = getInteger(container.getConfig(), OR_GATEWAY_TUNNEL_TCP_START, OR_GATEWAY_TUNNEL_TCP_START_DEFAULT);tunnelHostname = getString(container.getConfig(), OR_GATEWAY_TUNNEL_HOSTNAME, null);+ tunnelAutoCloseMinutes = getInteger(container.getConfig(), OR_GATEWAY_TUNNEL_AUTO_CLOSE_MINUTES, 0);}@Override@@ -538,11 +542,20 @@ public class GatewayService extends RouteBuilder implements ContainerService {if (!TextUtil.isNullOrEmpty(tunnelHostname)) {tunnelInfo.setHostname(tunnelHostname);}+ if (tunnelAutoCloseMinutes > 0) {+ tunnelInfo.setAutoCloseTime(timerService.getNow().plus(Duration.ofMinutes(tunnelAutoCloseMinutes)));+ }+CompletableFuture<Void> startFuture = connector.startTunnel(tunnelInfo);try {pendingTunnelCounter.incrementAndGet();startFuture.get();tunnelInfos.put(tunnelInfo.getId(), tunnelInfo);+ if (tunnelInfo.getAutoCloseTime() != null) {+ Duration delay = Duration.between(timerService.getNow(), tunnelInfo.getAutoCloseTime());+ scheduledExecutorService.schedule(() -> autoCloseTunnel(tunnelInfo.getId()), delay.toMillis(), TimeUnit.MILLISECONDS);+ LOG.fine("Scheduled job to automatically close tunnel '" + tunnelInfo.getId() + "' at " + tunnelInfo.getAutoCloseTime());+ }return tunnelInfo;} catch (ExecutionException e) {if (e.getCause() instanceof TimeoutException) {@@ -600,11 +613,11 @@ public class GatewayService extends RouteBuilder implements ContainerService {try {stopFuture.get(20, TimeUnit.SECONDS);} catch (ExecutionException e) {- String msg = "Failed to start tunnel: An error occurred whilst waiting for the tunnel to be started: id=" + gatewayId;+ String msg = "Failed to stop tunnel: An error occurred whilst waiting for the tunnel to be stopped: id=" + gatewayId;LOG.log(Level.WARNING, msg, e.getCause());throw new RuntimeException(msg, e.getCause());} catch (InterruptedException | TimeoutException e) {- String msg = "Failed to start tunnel: An error occurred whilst waiting for the tunnel to be started: id=" + gatewayId;+ String msg = "Failed to stop tunnel: An error occurred whilst waiting for the tunnel to be stopped: id=" + gatewayId;LOG.warning(msg);throw new RuntimeException(msg);} finally {@@ -819,7 +832,7 @@ public class GatewayService extends RouteBuilder implements ContainerService {LOG.log(Level.SEVERE, "Failed to merge registered gateway: " + gateway.getId(), e);}} catch (Exception e) {- LOG.warning("Failed to create client for gateway '" + gateway.getId());+ LOG.warning("Failed to create client for gateway: " + gateway.getId());}}@@ -848,6 +861,21 @@ public class GatewayService extends RouteBuilder implements ContainerService {return tunnelTCPStart;}+ protected void autoCloseTunnel(String tunnelId) {+ GatewayTunnelInfo tunnelInfo = tunnelInfos.get(tunnelId);+ if (tunnelInfo == null) {+ LOG.fine("Tunnel '" + tunnelId + "' not found so it cannot be automatically closed");+ return;+ }++ try {+ LOG.info("Automatically closing tunnel: " + tunnelId);+ stopTunnel(tunnelInfo);+ } catch (IllegalArgumentException | IllegalStateException e) {+ LOG.log(Level.WARNING, "Failed to automatically close tunnel: " + tunnelId, e);+ }+ }+@Overridepublic String toString() {return getClass().getSimpleName() + "{" +diff --git a/manager/src/web/shared/locales/en/or.json b/manager/src/web/shared/locales/en/or.jsonindex 5e48126cf..45694a37a 100644--- a/manager/src/web/shared/locales/en/or.json+++ b/manager/src/web/shared/locales/en/or.json@@ -353,7 +353,8 @@"protocol": "Protocol","createNew": "Add new Gateway tunnel","selectAsset": "Select gateway asset",- "closeSuccessful": "Closed tunnel successfully"+ "closeSuccessful": "Closed tunnel successfully",+ "closesAt": "Closes at"},"tunnels": "tunnels","tunnel": "tunnel",diff --git a/manager/src/web/shared/locales/nl/or.json b/manager/src/web/shared/locales/nl/or.jsonindex d1275256e..d585a09eb 100644--- a/manager/src/web/shared/locales/nl/or.json+++ b/manager/src/web/shared/locales/nl/or.json@@ -352,7 +352,8 @@"protocol": "Protocol","createNew": "Maak een nieuwe Gateway tunnel","selectAsset": "Selecteer gateway asset",- "closeSuccessful": "Tunnel gesloten"+ "closeSuccessful": "Tunnel gesloten",+ "closesAt": "Sluit op"},"tunnels": "tunnels","tunnel": "tunnel",diff --git a/model/src/main/java/org/openremote/model/gateway/GatewayTunnelInfo.java b/model/src/main/java/org/openremote/model/gateway/GatewayTunnelInfo.javaindex a5b1c2746..7e1f97f47 100644--- a/model/src/main/java/org/openremote/model/gateway/GatewayTunnelInfo.java+++ b/model/src/main/java/org/openremote/model/gateway/GatewayTunnelInfo.java@@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonCreator;import com.fasterxml.jackson.annotation.JsonProperty;import org.openremote.model.util.UniqueIdentifierGenerator;+import java.time.Instant;import java.util.Locale;import java.util.Objects;@@ -22,6 +23,7 @@ public class GatewayTunnelInfo {protected Integer assignedPort = null;protected String hostname;protected Type type = Type.HTTPS;+ protected Instant autoCloseTime;@JsonCreatorpublic GatewayTunnelInfo(String realm, String gatewayId) {@@ -100,6 +102,15 @@ public class GatewayTunnelInfo {return this;}+ public Instant getAutoCloseTime() {+ return autoCloseTime;+ }++ public GatewayTunnelInfo setAutoCloseTime(Instant autoCloseTime) {+ this.autoCloseTime = autoCloseTime;+ return this;+ }+@JsonPropertypublic String getId() {String seed = gatewayId + target + targetPort;diff --git a/ui/app/manager/src/pages/page-gateway-tunnel.ts b/ui/app/manager/src/pages/page-gateway-tunnel.tsindex 013ef63a6..6c134436f 100644--- a/ui/app/manager/src/pages/page-gateway-tunnel.ts+++ b/ui/app/manager/src/pages/page-gateway-tunnel.ts@@ -13,6 +13,7 @@ import {TableColumn, TableRow} from "@openremote/or-mwc-components/or-mwc-table"import {getAssetsRoute} from "../routes";import {OrMwcDialog, showDialog, showOkCancelDialog} from "@openremote/or-mwc-components/or-mwc-dialog";import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";+import moment from "moment";export function pageGatewayTunnelProvider(store: Store<AppStateKeyed>): PageProvider<AppStateKeyed> {return {@@ -97,10 +98,19 @@ export class PageGatewayTunnel extends Page<AppStateKeyed> {@state()protected _loading = false;+ protected _refreshTimer?: number = undefined;+static get styles() {return [styling];}+ disconnectedCallback() {+ if (this._refreshTimer) {+ clearTimeout(this._refreshTimer);+ }+ super.disconnectedCallback();+ }+get name(): string {return "gateway-tunnel";}@@ -147,6 +157,7 @@ export class PageGatewayTunnel extends Page<AppStateKeyed> {{title: i18next.t("gatewayTunnels.target"), isSortable: true, hideMobile: true},{title: i18next.t("gatewayTunnels.targetPort"), isSortable: true, hideMobile: true},{title: i18next.t("gatewayTunnels.assignedPort"), isSortable: true, hideMobile: true},+ {title: i18next.t("gatewayTunnels.closesAt"), isSortable: true, hideMobile: true},{title: ""}];const rows: TableRow[] = tunnels?.map(tunnel => ({@@ -157,6 +168,7 @@ export class PageGatewayTunnel extends Page<AppStateKeyed> {tunnel.target,tunnel.targetPort + "",!tunnel.assignedPort ? "" : tunnel.assignedPort + "",+ tunnel.autoCloseTime ? moment(tunnel.autoCloseTime).format('lll') : "",until(this._getTunnelActionsTemplate(tunnel), html`${i18next.t("loading")}`)],clickable: false,@@ -407,12 +419,31 @@ export class PageGatewayTunnel extends Page<AppStateKeyed> {}if (response.data.length > 0) {+ this._updateRefreshTimer(response.data);return response.data;} else {console.warn("No tunnels were received from the manager.")}}+ /**+ * Sets a timeout to refresh the tunnels whenever the next tunnel is automatically closed.+ */+ protected _updateRefreshTimer(tunnels?: GatewayTunnelInfo[]) {+ if (this._refreshTimer) {+ clearTimeout(this._refreshTimer);+ }++ if (tunnels && tunnels.length > 0) {+ const nextCloseTime = tunnels.map(t => t.autoCloseTime).filter(t => t).sort()[0];+ if (nextCloseTime) {+ const timeout = nextCloseTime - Date.now();+ if (timeout > 0) {+ this._refreshTimer = window.setTimeout(() => this._fetchTunnelsTask.run(), timeout);+ }+ }+ }+ }/* ------------------------------ */diff --git a/ui/component/or-dashboard-builder/src/widgets/gateway-widget.ts b/ui/component/or-dashboard-builder/src/widgets/gateway-widget.tsindex 5627df528..b788c9bef 100644--- a/ui/component/or-dashboard-builder/src/widgets/gateway-widget.ts+++ b/ui/component/or-dashboard-builder/src/widgets/gateway-widget.ts@@ -10,6 +10,7 @@ import manager from "@openremote/core";import {when} from "lit/directives/when.js";import {i18next} from "@openremote/or-translate";import {showSnackbar} from "@openremote/or-mwc-components/or-mwc-snackbar";+import moment from "moment";const styling = css`#gateway-widget-wrapper {@@ -59,6 +60,8 @@ export class GatewayWidget extends OrWidget {protected _startedByUser = false;+ protected _refreshTimer?: number = undefined;+static getManifest(): WidgetManifest {return {displayName: "Gateway",@@ -95,6 +98,11 @@ export class GatewayWidget extends OrWidget {console.warn("Keeping the active tunnel open, as it is not started through the widget.")}}++ if (this._refreshTimer) {+ clearTimeout(this._refreshTimer);+ }+super.disconnectedCallback();}@@ -132,7 +140,7 @@ export class GatewayWidget extends OrWidget {`, () => {if (this._activeTunnel) {return html`-+ <div><or-mwc-input .type="${InputType.BUTTON}" icon="stop" label="${i18next.t('gatewayTunnels.stop')}" .disabled="${disabled}"@or-mwc-input-changed="${(ev: OrInputChangedEvent) => this._onStopTunnelClick(ev)}"></or-mwc-input>@@ -146,7 +154,10 @@ export class GatewayWidget extends OrWidget {@or-mwc-input-changed="${(ev: OrInputChangedEvent) => this._onTunnelNavigateClick(ev)}"></or-mwc-input>`)}-+ </div>+ ${when(this._activeTunnel?.autoCloseTime, () => html`+ <div><or-translate value="gatewayTunnels.closesAt"></or-translate>: ${moment(this._activeTunnel?.autoCloseTime).format("lll")}</div>+ `)}`;} else {return html`@@ -213,6 +224,26 @@ export class GatewayWidget extends OrWidget {*/protected _setActiveTunnel(tunnelInfo?: GatewayTunnelInfo, silent = false) {this._activeTunnel = tunnelInfo;++ if (this._refreshTimer) {+ clearTimeout(this._refreshTimer);+ }++ if (tunnelInfo?.autoCloseTime) {+ const timeout = tunnelInfo?.autoCloseTime - Date.now();+ if (timeout > 0) {+ this._refreshTimer = window.setTimeout(() => {+ this._getActiveTunnel(this._getTunnelInfoByConfig(this.widgetConfig)).then(info => {+ if (info) {+ this._setActiveTunnel(info, true)+ } else {+ this._setActiveTunnel(undefined);+ }+ });+ }, timeout);+ }+ }+if(tunnelInfo && !silent) {this._navigateToTunnel(tunnelInfo);}