Skip to content

armgit / core

Public Imported from GitHub
0

100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps

Feature/Added services page and resource API (#1979)

Dominique Kleeven0a050dcab8a7
diff --git a/container/src/main/java/org/openremote/container/security/AuthContext.java b/container/src/main/java/org/openremote/container/security/AuthContext.java
index 99ffe83ef..1e4ec881d 100644
--- a/container/src/main/java/org/openremote/container/security/AuthContext.java
+++ b/container/src/main/java/org/openremote/container/security/AuthContext.java
@@ -20,6 +20,7 @@
package org.openremote.container.security;
import org.openremote.model.Constants;
+import org.openremote.model.security.User;
/**
* Services should use this interface to access a user's identity and perform authorization checks.
@@ -42,6 +43,11 @@ public interface AuthContext {
return Constants.MASTER_REALM.equals(getAuthenticatedRealmName()) && hasRealmRole(Constants.SUPER_USER_REALM_ROLE);
}
+ default boolean isServiceAccount() {
+ String username = getUsername();
+ return username != null && username.startsWith(User.SERVICE_ACCOUNT_PREFIX);
+ }
+
boolean hasRealmRole(String role);
boolean hasResourceRole(String role, String resource);
diff --git a/manager/src/main/java/org/openremote/manager/services/ExternalServiceRegistryService.java b/manager/src/main/java/org/openremote/manager/services/ExternalServiceRegistryService.java
new file mode 100644
index 000000000..553c8c36b
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/services/ExternalServiceRegistryService.java
@@ -0,0 +1,381 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * 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/>.
+ */
+package org.openremote.manager.services;
+
+import static org.openremote.model.Constants.MASTER_REALM;
+
+import java.util.HashMap;
+import java.util.Map;
+import java.util.NoSuchElementException;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.concurrent.ConcurrentHashMap;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.logging.Logger;
+
+import org.openremote.container.timer.TimerService;
+import org.openremote.manager.event.ClientEventService;
+import org.openremote.manager.security.ManagerIdentityService;
+import org.openremote.manager.web.ManagerWebService;
+import org.openremote.model.Constants;
+import org.openremote.model.Container;
+import org.openremote.model.ContainerService;
+import org.openremote.model.event.shared.EventSubscription;
+import org.openremote.model.services.ExternalService;
+import org.openremote.model.services.ExternalServiceEvent;
+import org.openremote.model.services.ExternalServiceStatus;
+
+
+import org.openremote.model.security.ClientRole;
+import org.openremote.model.services.ExternalServiceLeaseInfo;
+
+/**
+ * Manages {@link org.openremote.model.services.ExternalService} discovery and
+ * registration with lease-based lifecycle management; supports both
+ * global (multi-tenant) and realm-bound services, allowing multiple instances
+ * per service ID for
+ * horizontal scaling and high availability.
+ * <p>
+ * The service automatically manages external service health through scheduled tasks
+ * that mark expired
+ * instances as unavailable and eventually deregister long-expired instances. It
+ * registers a REST resource
+ * ({@link ExternalServiceResourceImpl}) for external access to the registry and
+ * adds event subscription
+ * authorization to the {@link ClientEventService} to filter external service events
+ * based on realm and user
+ * roles, publishing external service lifecycle events for external consumption.
+ */
+public class ExternalServiceRegistryService implements ContainerService {
+
+ private static final Logger LOG = Logger.getLogger(ExternalServiceRegistryService.class.getName());
+
+ // Lease duration is 60 seconds until expiration
+ protected static final long DEFAULT_LEASE_DURATION_MS = 60000;
+ // Mark expired service instances every 30 seconds
+ protected static final long MARK_EXPIRED_INSTANCES_INTERVAL_MS = 30000;
+
+ // Deregister threshold is 24 hours since a service has gone unavailable
+ protected static final long DEFAULT_DEREGISTER_UNAVAILABLE_MS = 86400000;
+ // Check for deregister-able services every hour
+ protected static final long DEREGISTER_UNAVAILABLE_INTERVAL_MS = 3600000;
+
+ protected TimerService timerService;
+ protected ScheduledExecutorService scheduledExecutorService;
+ protected ManagerIdentityService identityService;
+ protected ClientEventService clientEventService;
+
+ // serviceId: <instanceId: ExternalService>
+ protected ConcurrentHashMap<String, HashMap<Integer, ExternalService>> registry;
+
+ // Track next available instanceId for each serviceId
+ protected ConcurrentHashMap<String, AtomicInteger> serviceIdCounters;
+
+ // Scheduled future for the lease check task
+ protected ScheduledFuture<?> markExpiredInstancesAsUnavailableFuture;
+
+ // Scheduled future for the deregister task
+ protected ScheduledFuture<?> deregisterExpiredUnavailableInstancesFuture;
+
+ @Override
+ public void init(Container container) throws Exception {
+ this.timerService = container.getService(TimerService.class);
+ this.scheduledExecutorService = container.getScheduledExecutor();
+ this.identityService = container.getService(ManagerIdentityService.class);
+ this.clientEventService = container.getService(ClientEventService.class);
+
+ this.registry = new ConcurrentHashMap<>();
+ this.serviceIdCounters = new ConcurrentHashMap<>();
+
+ // Register the external service REST resource
+ container.getService(ManagerWebService.class).addApiSingleton(
+ new ExternalServiceResourceImpl(timerService, identityService, this));
+
+ addExternalServiceEventSubscriptionAuthorizer();
+ }
+
+ protected void addExternalServiceEventSubscriptionAuthorizer() {
+ clientEventService.addSubscriptionAuthorizer((realm, authContext, eventSubscription) -> {
+ if (!eventSubscription.isEventType(ExternalServiceEvent.class) || authContext == null) {
+ return false;
+ }
+
+ if (authContext.isSuperUser()) {
+ return true;
+ }
+
+ @SuppressWarnings("unchecked")
+ EventSubscription<ExternalServiceEvent> subscription = (EventSubscription<ExternalServiceEvent>) eventSubscription;
+ subscription.setFilter(event -> {
+ ExternalService eventExternalService = event.getService();
+ boolean isGlobalService = eventExternalService.getIsGlobal();
+ boolean realmMatches = Objects.equals(eventExternalService.getRealm(),
+ authContext.getAuthenticatedRealmName());
+
+ return isGlobalService || realmMatches ? event : null;
+ });
+
+ return authContext.hasResourceRole(ClientRole.READ_SERVICES.getValue(),
+ Constants.KEYCLOAK_CLIENT_ID);
+ });
+ }
+
+ @Override
+ public void start(Container container) throws Exception {
+ markExpiredInstancesAsUnavailableFuture = scheduledExecutorService.scheduleAtFixedRate(
+ this::markExpiredInstancesAsUnavailable, MARK_EXPIRED_INSTANCES_INTERVAL_MS,
+ MARK_EXPIRED_INSTANCES_INTERVAL_MS, TimeUnit.MILLISECONDS);
+
+ deregisterExpiredUnavailableInstancesFuture = scheduledExecutorService.scheduleAtFixedRate(
+ this::deregisterLongExpiredInstances, DEREGISTER_UNAVAILABLE_INTERVAL_MS,
+ DEREGISTER_UNAVAILABLE_INTERVAL_MS, TimeUnit.MILLISECONDS);
+ }
+
+ @Override
+ public void stop(Container container) throws Exception {
+ // cancel any scheduled tasks
+ if (markExpiredInstancesAsUnavailableFuture != null) {
+ markExpiredInstancesAsUnavailableFuture.cancel(true);
+ }
+ if (deregisterExpiredUnavailableInstancesFuture != null) {
+ deregisterExpiredUnavailableInstancesFuture.cancel(true);
+ }
+
+ // clear the registry and counters
+ registry.clear();
+ serviceIdCounters.clear();
+ }
+
+
+ /**
+ * Register an external service instance
+ *
+ * @param registrarUserId The userId of the user who registered the service
+ * @param externalService The external service to register
+ */
+ public void registerService(String registrarUserId, ExternalService externalService) {
+
+ // Set the instanceId based on the incremental counter for this serviceId
+ int nextInstanceId = serviceIdCounters.computeIfAbsent(externalService.getServiceId(),
+ k -> new AtomicInteger(0)).incrementAndGet();
+ externalService.setInstanceId(nextInstanceId);
+
+ LOG.info("Registering external service: " + externalService.getServiceId() + ", instanceId: "
+ + externalService.getInstanceId() + ", isGlobal: " + externalService.getIsGlobal() + ", registrarUserId: " + registrarUserId);
+
+ long now = timerService.getCurrentTimeMillis();
+ externalService.setLeaseInfo(new ExternalServiceLeaseInfo(registrarUserId, now + DEFAULT_LEASE_DURATION_MS, now, now));
+
+ // merge the external service into the registry if it doesn't already exist
+ registry.merge(
+ externalService.getServiceId(),
+ new HashMap<>(Map.of(externalService.getInstanceId(), externalService)),
+ (existingMap, newMap) -> {
+ ExternalService existing = existingMap.putIfAbsent(externalService.getInstanceId(), externalService);
+ if (existing != null) {
+ throw new IllegalStateException("ExternalService already registered: "
+ + externalService.getServiceId() + ", instanceId: " + externalService.getInstanceId());
+ }
+ return existingMap;
+ });
+
+ // publish the register event as a new external service has been added to the
+ // registry
+ clientEventService.publishEvent(new ExternalServiceEvent(externalService, ExternalServiceEvent.Cause.REGISTER));
+
+ LOG.info("Successfully registered external service: " + externalService.getServiceId() + ", instanceId: "
+ + externalService.getInstanceId() + ", isGlobal: " + externalService.getIsGlobal() + ", registrarUserId: " + registrarUserId);
+ }
+
+ /**
+ * Update the active registration lease info for the specified external service.
+ * This is used to indicate that the external service is still running and
+ * available.
+ * If the external service is not found, a {@link NoSuchElementException} is
+ * thrown.
+ *
+ * @param serviceId The serviceId of the external service to send the heartbeat to
+ * @param instanceId The instanceId of the external service to send the heartbeat to
+ */
+ public void heartbeat(String serviceId, int instanceId) {
+ Map<Integer, ExternalService> instanceMap = registry.get(serviceId);
+ if (instanceMap == null) {
+ throw new NoSuchElementException("Service not found: " + serviceId);
+ }
+
+ instanceMap.compute(instanceId, (id, entry) -> {
+ if (entry == null) {
+ throw new NoSuchElementException("Instance not found: " + serviceId + ", instanceId: " + instanceId);
+ }
+ // update the lease info and set the instance status to available
+ long now = timerService.getCurrentTimeMillis();
+ entry.getLeaseInfo().setRenewalTimestamp(now);
+ entry.getLeaseInfo().setExpirationTimestamp(now + DEFAULT_LEASE_DURATION_MS);
+ entry.setStatus(ExternalServiceStatus.AVAILABLE);
+
+ // publish the update event as the lease has been refreshed
+ clientEventService.publishEvent(new ExternalServiceEvent(entry, ExternalServiceEvent.Cause.UPDATE));
+
+ LOG.fine(
+ "Successfully refreshed lease info for external service: " + serviceId + ", instanceId: " + instanceId);
+ return entry;
+ });
+ }
+
+ /**
+ * Deregister an external service instance.
+ * <p>
+ * If the external service is not found, a {@link NoSuchElementException} is
+ * thrown.
+ *
+ * @param serviceId The serviceId of the external service to deregister
+ * @param instanceId The instanceId of the external service to deregister
+ */
+ public void deregisterService(String serviceId, int instanceId) {
+ registry.compute(serviceId, (unused, instanceMap) -> {
+ if (instanceMap == null) {
+ throw new NoSuchElementException(
+ "The given serviceId does not exist in the registry");
+ }
+
+ ExternalService removed = instanceMap.remove(instanceId);
+ if (removed == null) {
+ throw new NoSuchElementException(
+ "The given serviceId and instanceId combination does not exist in the registry");
+ }
+
+ // Publish deregister event
+ clientEventService.publishEvent(
+ new ExternalServiceEvent(removed, ExternalServiceEvent.Cause.DEREGISTER));
+
+ LOG.info("Successfully de-registered external service: " + serviceId + ", instanceId: " + instanceId);
+
+ // If the map is empty after removal, we can just return null to remove the
+ // serviceId entry
+ if (instanceMap.isEmpty()) {
+ LOG.info("No instances left for service: " + serviceId + ", removed from registry");
+ serviceIdCounters.remove(serviceId);
+ return null;
+ }
+
+ return instanceMap;
+ });
+ }
+
+ /**
+ * Get all registered services and external services and their instances for the
+ * given
+ * realm.
+ *
+ * @param realm The realm to filter services by
+ * @return An array of all registered external services and their instances
+ */
+ public ExternalService[] getServices(String realm) {
+ return registry.entrySet().stream()
+ .flatMap(serviceEntry -> serviceEntry.getValue().values().stream())
+ .filter(entry -> entry.getRealm().equals(realm))
+ .toArray(ExternalService[]::new);
+ }
+
+ /**
+ * Get all globally registered services and external services and their instances.
+ * A service is considered global if it is registered with the master realm and,
+ * it has the isGlobal flag set to true.
+ *
+ * @return An array of all globally registered external services and their instances
+ */
+ public ExternalService[] getGlobalServices() {
+ return registry.entrySet().stream()
+ .flatMap(serviceEntry -> serviceEntry.getValue().values().stream())
+ .filter(entry -> entry.getRealm().equals(MASTER_REALM) && entry.getIsGlobal())
+ .toArray(ExternalService[]::new);
+ }
+
+ /**
+ * Get a specific external service registration.
+ *
+ * @param serviceId The serviceId of the external service to get
+ * @param instanceId The instanceId of the external service to get
+ * @return The external service
+ */
+ public ExternalService getService(String serviceId, int instanceId) {
+ return Optional.ofNullable(registry.get(serviceId))
+ .map(instanceMap -> instanceMap.get(instanceId))
+ .orElse(null);
+ }
+
+ /**
+ * Check for expired registrations and mark them as unavailable if the
+ * instance lease has not been renewed within the configured
+ * {@link #DEFAULT_LEASE_DURATION_MS} lease duration.
+ */
+ protected void markExpiredInstancesAsUnavailable() {
+ long now = timerService.getCurrentTimeMillis();
+ LOG.fine("Marking expired external service instances as unavailable");
+
+ registry.entrySet().stream()
+ .flatMap(serviceEntry -> serviceEntry.getValue().entrySet().stream())
+ .map(Map.Entry::getValue)
+ // filter by lease expired and current status is still available
+ .filter(ms -> ms.getLeaseInfo().isExpired(now)
+ && ms.getStatus() == ExternalServiceStatus.AVAILABLE)
+ .forEach(ms -> {
+ ms.setStatus(ExternalServiceStatus.UNAVAILABLE);
+ clientEventService.publishEvent(new ExternalServiceEvent(ms, ExternalServiceEvent.Cause.UPDATE));
+ LOG.fine("Marked external service as unavailable: "
+ + ms.getServiceId() + ", instanceId: " + ms.getInstanceId());
+ });
+ }
+
+ /**
+ * Deregister long expired external services. This is used to remove external service
+ * instances that have been unavailable for longer than the configured
+ * {@link #DEFAULT_DEREGISTER_UNAVAILABLE_MS} threshold.
+ */
+ protected void deregisterLongExpiredInstances() {
+ LOG.info("De-registering long expired external service registrations");
+
+ long now = timerService.getCurrentTimeMillis();
+ long deregisterThreshold = now - DEFAULT_DEREGISTER_UNAVAILABLE_MS;
+
+ // Collect services to deregister first
+ var servicesToDeregister = registry.entrySet().stream()
+ .flatMap(serviceEntry -> serviceEntry.getValue().entrySet().stream())
+ .map(Map.Entry::getValue)
+ // filter by unavailable + meets threshold
+ .filter(ms -> ms.getStatus() == ExternalServiceStatus.UNAVAILABLE
+ && ms.getLeaseInfo().isExpired(deregisterThreshold))
+ .toList();
+
+ // Deregister the collected services
+ servicesToDeregister.forEach(ms -> {
+ try {
+ deregisterService(ms.getServiceId(), ms.getInstanceId());
+ } catch (NoSuchElementException e) {
+ LOG.warning("Service was already deregistered: " + ms.getServiceId()
+ + ", instanceId: " + ms.getInstanceId() + " - " + e.getMessage());
+ }
+ });
+ }
+
+}
diff --git a/manager/src/main/java/org/openremote/manager/services/ExternalServiceResourceImpl.java b/manager/src/main/java/org/openremote/manager/services/ExternalServiceResourceImpl.java
new file mode 100644
index 000000000..4ebf3dd3e
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/services/ExternalServiceResourceImpl.java
@@ -0,0 +1,229 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * 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/>.
+ */
+package org.openremote.manager.services;
+
+import java.util.logging.Logger;
+
+import org.openremote.container.timer.TimerService;
+import org.openremote.manager.security.ManagerIdentityService;
+import org.openremote.manager.web.ManagerWebResource;
+import org.openremote.model.http.RequestParams;
+import org.openremote.model.services.ExternalService;
+import org.openremote.model.services.ExternalServiceResource;
+
+import static org.openremote.model.Constants.MASTER_REALM;
+
+import jakarta.ws.rs.WebApplicationException;
+import jakarta.ws.rs.core.Response;
+
+public class ExternalServiceResourceImpl extends ManagerWebResource implements ExternalServiceResource {
+
+ protected ExternalServiceRegistryService externalServiceRegistry;
+ private static final Logger LOG = Logger.getLogger(ExternalServiceResourceImpl.class.getName());
+
+ public ExternalServiceResourceImpl(TimerService timerService, ManagerIdentityService identityService,
+ ExternalServiceRegistryService serviceRegistry) {
+ super(timerService, identityService);
+ this.externalServiceRegistry = serviceRegistry;
+ }
+
+ @Override
+ public ExternalService registerService(RequestParams requestParams, ExternalService externalService) {
+ if (!isServiceAccount()) {
+ LOG.warning("Service registration not allowed for non-service users");
+ throw new WebApplicationException("Service registration not allowed for non-service users",
+ Response.Status.UNAUTHORIZED);
+ }
+
+ if (getRequestRealm() == null) {
+ throw new WebApplicationException("Invalid realm", Response.Status.BAD_REQUEST);
+ }
+
+ // Set the realm for the service based on the request realm
+ externalService.setRealm(getRequestRealmName());
+
+ try {
+ externalServiceRegistry.registerService(getUserId(), externalService);
+ return externalService;
+ } catch (IllegalStateException e) {
+ LOG.warning("Failed to register service: " + externalService.getServiceId() + " with instanceId: "
+ + externalService.getInstanceId() + " due to conflict: " + e.getMessage());
+ throw new WebApplicationException(e.getMessage(), Response.Status.CONFLICT);
+ }
+
+ }
+
+ @Override
+ public ExternalService registerGlobalService(RequestParams requestParams, ExternalService externalService) {
+ if (!isServiceAccount()) {
+ LOG.warning("Service registration is only available for service users");
+ throw new WebApplicationException("Service registration is only available for service users",
+ Response.Status.UNAUTHORIZED);
+ }
+
+ if (!isSuperUser()) {
+ throw new WebApplicationException("Global services can only be registered by super users",
+ Response.Status.FORBIDDEN);
+ }
+
+ if (getRequestRealm() == null) {
+ throw new WebApplicationException("Invalid realm", Response.Status.BAD_REQUEST);
+ }
+
+ // Restrict global services to the master realm
+ if (!getRequestRealmName().equals(MASTER_REALM)) {
+ throw new WebApplicationException("Global services must have the realm set to the master realm, got: "
+ + getRequestRealmName(),
+ Response.Status.BAD_REQUEST);
+ }
+
+ // Set the realm for the service based on the request realm
+ externalService.setRealm(getRequestRealmName());
+
+ // Set the global flag for the service since it is a global service
+ externalService.setIsGlobal(true);
+
+
+ try {
+ externalServiceRegistry.registerService(getUserId(), externalService);
+ return externalService;
+ } catch (IllegalStateException e) {
+ LOG.warning("Failed to register global service: " + externalService.getServiceId() + " with instanceId: "
+ + externalService.getInstanceId() + " due to conflict: " + e.getMessage());
+ throw new WebApplicationException(e.getMessage(), Response.Status.CONFLICT);
+ }
+ }
+
+ @Override
+ public ExternalService[] getServices(RequestParams requestParams, String realm) {
+ if (!isRealmActiveAndAccessible(realm)) {
+ throw new WebApplicationException("Realm '" + realm + "' is nonexistent, inactive or inaccessible",
+ Response.Status.FORBIDDEN);
+ }
+
+ return externalServiceRegistry.getServices(realm);
+ }
+
+ @Override
+ public ExternalService getService(RequestParams requestParams, String serviceId, int instanceId) {
+ ExternalService service = externalServiceRegistry.getService(serviceId, instanceId);
+
+ if (service == null) {
+ throw new WebApplicationException("Service " + serviceId + " instance " + instanceId + " not found",
+ Response.Status.NOT_FOUND);
+ }
+
+ if (!isRealmActiveAndAccessible(service.getRealm())) {
+ throw new WebApplicationException(
+ "Realm '" + service.getRealm() + "' is nonexistent, inactive or inaccessible",
+ Response.Status.FORBIDDEN);
+ }
+
+ return service;
+ }
+
+ @Override
+ public ExternalService[] getGlobalServices(RequestParams requestParams) {
+ return externalServiceRegistry.getGlobalServices();
+ }
+
+ @Override
+ public void heartbeat(RequestParams requestParams, String serviceId, int instanceId) {
+ if (!isServiceAccount()) {
+ LOG.warning("Service heartbeat is only available for service users");
+ throw new WebApplicationException("Service heartbeat is only available for service users",
+ Response.Status.UNAUTHORIZED);
+ }
+
+ ExternalService service = externalServiceRegistry.getService(serviceId, instanceId);
+
+ if (service == null) {
+ throw new WebApplicationException("Service " + serviceId + " instance " + instanceId + " not found",
+ Response.Status.NOT_FOUND);
+ }
+
+ if (!isRealmActiveAndAccessible(service.getRealm())) {
+ throw new WebApplicationException(
+ "Realm '" + service.getRealm() + "' is nonexistent, inactive or inaccessible",
+ Response.Status.FORBIDDEN);
+ }
+
+ // Restrict heartbeats to the user who registered the service
+ if (!isServiceRegistrarCurrentUser(service)) {
+ LOG.warning("User " + getUserId() + " tried to heartbeat service " + serviceId + " instance " + instanceId + " expected to be performed by user " + service.getLeaseInfo().getRegistrarUserId());
+ throw new WebApplicationException("Heartbeats for services can only be performed by the user who registered the service",
+ Response.Status.FORBIDDEN);
+ }
+
+ // Restrict global service mutations to superusers
+ if (isServiceGlobalAndUserIsNotSuperUser(service)) {
+ throw new WebApplicationException("Heartbeats for global services can only be performed by super users",
+ Response.Status.FORBIDDEN);
+ }
+
+ externalServiceRegistry.heartbeat(serviceId, instanceId);
+ }
+
+ @Override
+ public void deregisterService(RequestParams requestParams, String serviceId, int instanceId) {
+ if (!isServiceAccount()) {
+ LOG.warning("De-registering a service is only available for service users");
+ throw new WebApplicationException("De-registering a service is only available for service users",
+ Response.Status.UNAUTHORIZED);
+ }
+
+ ExternalService service = externalServiceRegistry.getService(serviceId, instanceId);
+
+ if (service == null) {
+ throw new WebApplicationException("Service " + serviceId + " instance " + instanceId + " not found",
+ Response.Status.NOT_FOUND);
+ }
+
+ if (!isRealmActiveAndAccessible(service.getRealm())) {
+ throw new WebApplicationException(
+ "Realm '" + service.getRealm() + "' is nonexistent, inactive or inaccessible",
+ Response.Status.FORBIDDEN);
+ }
+
+ // Restrict de-registering a service to the user who registered the service
+ if (!isServiceRegistrarCurrentUser(service)) {
+ LOG.warning("User " + getUserId() + " tried to de-register service " + serviceId + " instance " + instanceId + " expected to be performed by user " + service.getLeaseInfo().getRegistrarUserId());
+ throw new WebApplicationException("De-registering a service can only be performed by the user who registered the service",
+ Response.Status.FORBIDDEN);
+ }
+
+ // Restrict global service mutations to superusers
+ if (isServiceGlobalAndUserIsNotSuperUser(service)) {
+ throw new WebApplicationException("Global services can only be de-registered by super users",
+ Response.Status.FORBIDDEN);
+ }
+
+ externalServiceRegistry.deregisterService(serviceId, instanceId);
+ }
+
+ protected boolean isServiceGlobalAndUserIsNotSuperUser(ExternalService service) {
+ return service.getIsGlobal() && !isSuperUser();
+ }
+
+ protected boolean isServiceRegistrarCurrentUser(ExternalService service) {
+ return service.getLeaseInfo().getRegistrarUserId().equals(getUserId());
+ }
+
+}
diff --git a/manager/src/main/java/org/openremote/manager/setup/AbstractKeycloakSetup.java b/manager/src/main/java/org/openremote/manager/setup/AbstractKeycloakSetup.java
index 99cd8db08..e4cb40a9a 100644
--- a/manager/src/main/java/org/openremote/manager/setup/AbstractKeycloakSetup.java
+++ b/manager/src/main/java/org/openremote/manager/setup/AbstractKeycloakSetup.java
@@ -52,11 +52,13 @@ public abstract class AbstractKeycloakSetup implements Setup {
ClientRole.READ_RULES,
ClientRole.READ_INSIGHTS,
ClientRole.READ_ALARMS,
+ ClientRole.READ_SERVICES,
ClientRole.WRITE_ASSETS,
ClientRole.WRITE_ATTRIBUTES,
ClientRole.WRITE_RULES,
ClientRole.WRITE_INSIGHTS,
- ClientRole.WRITE_ALARMS
+ ClientRole.WRITE_ALARMS,
+ ClientRole.WRITE_SERVICES
};
final protected Container container;
diff --git a/manager/src/main/java/org/openremote/manager/setup/database/V20250916_01__AddServiceRoles.java b/manager/src/main/java/org/openremote/manager/setup/database/V20250916_01__AddServiceRoles.java
new file mode 100644
index 000000000..14ef3a15b
--- /dev/null
+++ b/manager/src/main/java/org/openremote/manager/setup/database/V20250916_01__AddServiceRoles.java
@@ -0,0 +1,120 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * 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/>.
+ */
+package org.openremote.manager.setup.database;
+
+import org.flywaydb.core.api.migration.BaseJavaMigration;
+import org.flywaydb.core.api.migration.Context;
+import org.keycloak.admin.client.Keycloak;
+import org.keycloak.admin.client.resource.RealmResource;
+import org.keycloak.admin.client.resource.RolesResource;
+import org.keycloak.admin.client.resource.ClientResource;
+import org.keycloak.representations.idm.RealmRepresentation;
+import org.keycloak.representations.idm.RoleRepresentation;
+import org.keycloak.representations.idm.ClientRepresentation;
+import org.openremote.container.security.keycloak.KeycloakIdentityProvider;
+import org.openremote.container.security.IdentityProvider;
+import org.openremote.model.Constants;
+
+import jakarta.ws.rs.NotFoundException;
+import jakarta.ws.rs.core.UriBuilder;
+
+import java.util.List;
+import java.util.logging.Logger;
+
+/**
+ * Flyway migration script to add write:services and read:services roles using
+ * Keycloak
+ * admin API.
+ */
+public class V20250916_01__AddServiceRoles extends BaseJavaMigration {
+
+ private static final Logger LOG = Logger.getLogger(V20250916_01__AddServiceRoles.class.getName());
+
+ @Override
+ public void migrate(Context context) throws Exception {
+
+ // Build the keycloak URL
+ UriBuilder uriBuilder = UriBuilder.fromPath("/")
+ .scheme("http")
+ .host(System.getenv().getOrDefault(KeycloakIdentityProvider.OR_KEYCLOAK_HOST,
+ KeycloakIdentityProvider.OR_KEYCLOAK_HOST_DEFAULT))
+ .port(Integer.parseInt(System.getenv().getOrDefault(KeycloakIdentityProvider.OR_KEYCLOAK_PORT,
+ String.valueOf(KeycloakIdentityProvider.OR_KEYCLOAK_PORT_DEFAULT))));
+
+ String path = System.getenv().getOrDefault(KeycloakIdentityProvider.OR_KEYCLOAK_PATH,
+ KeycloakIdentityProvider.OR_KEYCLOAK_PATH_DEFAULT);
+
+ if (path != null && !path.isBlank()) {
+ uriBuilder.path(path);
+ }
+
+ String keycloakUrl = uriBuilder.build().toString();
+ String adminUser = Constants.MASTER_REALM_ADMIN_USER;
+ String adminPassword = System.getenv().getOrDefault(IdentityProvider.OR_ADMIN_PASSWORD,
+ IdentityProvider.OR_ADMIN_PASSWORD_DEFAULT);
+
+ // Get the keycloak instance
+ try (Keycloak keycloak = Keycloak.getInstance(
+ keycloakUrl,
+ Constants.MASTER_REALM,
+ adminUser,
+ adminPassword,
+ KeycloakIdentityProvider.ADMIN_CLI_CLIENT_ID)) {
+
+ // Get all available realms
+ List<String> realmNames = keycloak.realms().findAll().stream()
+ .map(RealmRepresentation::getRealm)
+ .toList();
+
+ // For every realm, check if the openremote client has the write:services and
+ // read:services roles added
+ for (String realmName : realmNames) {
+ RealmResource realm = keycloak.realm(realmName);
+
+ List<ClientRepresentation> clients = realm.clients().findByClientId(Constants.KEYCLOAK_CLIENT_ID);
+
+ if (clients.isEmpty()) {
+ LOG.warning("Client '" + Constants.KEYCLOAK_CLIENT_ID + "' not found in realm " + realmName
+ + ", skipping role creation.");
+ continue; // Skip realms without the openremote client
+ }
+ ClientResource clientResource = realm.clients().get(clients.get(0).getId());
+ RolesResource clientRoles = clientResource.roles();
+ createRoleIfNotExists(clientRoles, "write:services", "Write service data");
+ createRoleIfNotExists(clientRoles, "read:services", "View services");
+ }
+ }
+ }
+
+ // Create the role if it doesn't exist by handling the NotFoundException
+ private void createRoleIfNotExists(RolesResource roles, String roleName, String description) {
+ try {
+ roles.get(roleName).toRepresentation();
+ } catch (NotFoundException e) {
+ roles.create(new RoleRepresentation(roleName, description, false));
+ }
+ }
+
+ // Since its a code migration, no DB transaction is needed
+ @Override
+ public boolean canExecuteInTransaction() {
+ return false;
+ }
+}
diff --git a/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerService b/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerService
index b877ede2e..4765b5517 100644
--- a/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerService
+++ b/manager/src/main/resources/META-INF/services/org.openremote.model.ContainerService
@@ -37,3 +37,4 @@ org.openremote.manager.asset.ForecastService
org.openremote.manager.setup.KeycloakInitService
org.openremote.manager.alarm.AlarmService
org.openremote.manager.security.KeyStoreServiceImpl
+org.openremote.manager.services.ExternalServiceRegistryService
diff --git a/model/src/main/java/org/openremote/model/Constants.java b/model/src/main/java/org/openremote/model/Constants.java
index 152ffb1c2..458e63709 100644
--- a/model/src/main/java/org/openremote/model/Constants.java
+++ b/model/src/main/java/org/openremote/model/Constants.java
@@ -37,6 +37,8 @@ public interface Constants {
String READ_RULES_ROLE = "read:rules";
String READ_INSIGHTS_ROLE = "read:insights";
String READ_ALARMS_ROLE = "read:alarms";
+ String READ_SERVICES_ROLE = "read:services";
+ String WRITE_SERVICES_ROLE = "write:services";
String WRITE_USER_ROLE = "write:user";
String WRITE_ADMIN_ROLE = "write:admin";
String WRITE_LOGS_ROLE = "write:logs";
diff --git a/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java b/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java
index c988c69b7..345dc8a00 100644
--- a/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java
+++ b/model/src/main/java/org/openremote/model/event/shared/SharedEvent.java
@@ -25,6 +25,7 @@ import org.openremote.model.asset.*;
import org.openremote.model.attribute.AttributeEvent;
import org.openremote.model.event.Event;
import org.openremote.model.gateway.*;
+import org.openremote.model.services.ExternalServiceEvent;
import org.openremote.model.rules.RulesEngineStatusEvent;
import org.openremote.model.rules.RulesetChangedEvent;
import org.openremote.model.simulator.RequestSimulatorState;
@@ -38,6 +39,7 @@ import org.openremote.model.alarm.AlarmEvent;
@JsonSubTypes({
// Events used on client and server (serializable)
@JsonSubTypes.Type(value = AlarmEvent.class, name = "alarm"),
+ @JsonSubTypes.Type(value = ExternalServiceEvent.class, name = "external-service"),
@JsonSubTypes.Type(value = SyslogEvent.class, name = "syslog"),
@JsonSubTypes.Type(value = AttributeEvent.class, name = "attribute"),
@JsonSubTypes.Type(value = AssetEvent.class, name = "asset"),
diff --git a/model/src/main/java/org/openremote/model/security/ClientRole.java b/model/src/main/java/org/openremote/model/security/ClientRole.java
index 26b06a819..b03aecfa2 100644
--- a/model/src/main/java/org/openremote/model/security/ClientRole.java
+++ b/model/src/main/java/org/openremote/model/security/ClientRole.java
@@ -39,6 +39,8 @@ public enum ClientRole {
READ_RULES(Constants.READ_RULES_ROLE, "Read rulesets"),
READ_INSIGHTS(Constants.READ_INSIGHTS_ROLE, "Read dashboards"),
READ_ALARMS(Constants.READ_ALARMS_ROLE, "Read alarms"),
+ READ_SERVICES(Constants.READ_SERVICES_ROLE, "View services"),
+ WRITE_SERVICES(Constants.WRITE_SERVICES_ROLE, "Write service data"),
WRITE_USER(Constants.WRITE_USER_ROLE, "Write data of the authenticated user"),
WRITE_ADMIN(Constants.WRITE_ADMIN_ROLE, "Write system settings, realms, and users"),
@@ -57,7 +59,8 @@ public enum ClientRole {
READ_ASSETS,
READ_RULES,
READ_INSIGHTS,
- READ_ALARMS
+ READ_ALARMS,
+ READ_SERVICES
}),
WRITE("write", "Write all data", new ClientRole[]{
@@ -69,6 +72,7 @@ public enum ClientRole {
READ_RULES,
READ_INSIGHTS,
READ_ALARMS,
+ READ_SERVICES,
WRITE_USER,
WRITE_ADMIN,
WRITE_LOGS,
@@ -76,7 +80,8 @@ public enum ClientRole {
WRITE_ATTRIBUTES,
WRITE_RULES,
WRITE_INSIGHTS,
- WRITE_ALARMS
+ WRITE_ALARMS,
+ WRITE_SERVICES
});
// Only individual roles, not composites
diff --git a/model/src/main/java/org/openremote/model/services/ExternalService.java b/model/src/main/java/org/openremote/model/services/ExternalService.java
new file mode 100644
index 000000000..cb6c55b88
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/services/ExternalService.java
@@ -0,0 +1,261 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * 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/>.
+ */
+package org.openremote.model.services;
+
+import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
+import jakarta.validation.constraints.NotEmpty;
+import jakarta.validation.constraints.NotNull;
+import jakarta.validation.constraints.Size;
+
+/**
+ * Represents an external service managed by the OpenRemote
+ * external service registry.
+ * <p>
+ * This class encapsulates service metadata and the required information needed
+ * to register, manage,
+ * and track the lifecycle of external services within the OpenRemote system.
+ */
+public class ExternalService {
+
+ /**
+ * The unique identifier of the service (e.g., "energy-service").
+ * <p>
+ * This ID is used to group related service instances and must be consistent
+ * across all instances of the same service type.
+ */
+ @Size(min = 3, max = 255, message = "{ExternalService.serviceId.Size}")
+ @NotEmpty(message = "{ExternalService.serviceId.NotEmpty}")
+ @JsonProperty("serviceId")
+ protected String serviceId;
+
+ /**
+ * Identifier for this specific instance within the scope of the
+ * serviceId.
+ * <p>
+ * This instanceId is an incremental integer assigned by the external service
+ * registry when the service is registered.
+ */
+ @JsonProperty(value = "instanceId")
+ protected int instanceId;
+
+ /**
+ * The version of the service.
+ * <p>
+ * Can be optionally set, to determine the version of the service, and interpret
+ * which version of the service is running and registered.
+ */
+ @Size(min = 3, max = 255, message = "{ExternalService.version.Size}")
+ @JsonProperty("version")
+ protected String version;
+
+ /**
+ * The realm identifier where this service is registered.
+ * <p>
+ * Services are typically scoped to a specific realm. When
+ * registered by a super admin service user, the realm must be MASTER, the service then becomes available
+ * across all realms if the isGlobal flag is also set to true.
+ */
+ @JsonProperty(access = JsonProperty.Access.READ_ONLY)
+ protected String realm;
+
+ /**
+ * The icon to display for the service.
+ * <p>
+ * This icon is used in user interfaces to provide a visual representation
+ * of the service. The default icon is "puzzle" which is a generic service icon.
+ * <p>
+ * Should be a valid icon name from the Material Design Icons library.
+ */
+ @JsonProperty("icon")
+ protected String icon = "puzzle";
+
+ /**
+ * Human-readable display name for the service (e.g., "Energy Service").
+ * <p>
+ * This label is used in user interfaces to provide a friendly name
+ * for the service.
+ */
+ @NotEmpty(message = "{ExternalService.label.NotEmpty}")
+ @Size(min = 1, max = 255, message = "{ExternalService.label.Size}")
+ @JsonProperty("label")
+ protected String label;
+
+ /**
+ * URL to the service's configuration page or user interface.
+ * <p>
+ * This URL provides access to the service's web interface for configuration
+ * and management purposes (e.g.,
+ * "https://openremote.app/services/energy-service/ui").
+ *
+ */
+ @Size(min = 3, max = 512, message = "{ExternalService.homepageUrl.Size}")
+ @NotEmpty(message = "{ExternalService.homepageUrl.NotEmpty}")
+ @JsonProperty("homepageUrl")
+ protected String homepageUrl;
+
+ /**
+ * Current operational status of the service instance.
+ * <p>
+ * Indicates whether the service is available, unavailable, or in another state.
+ * The status is managed by the external service registry based on lease expiration.
+ */
+ @NotNull(message = "{ExternalService.status.NotNull}")
+ @JsonProperty("status")
+ protected ExternalServiceStatus status;
+
+ /**
+ * Internal lease management information for the service registration.
+ * <p>
+ * Contains timestamps for lease expiration, registration, and renewal.
+ * This information is used internally by the external service registry to manage
+ * service lifecycle and availability.
+ */
+ @JsonIgnore
+ protected ExternalServiceLeaseInfo leaseInfo;
+
+ /**
+ * Indicates whether this service is globally accessible across all realms.
+ * <p>
+ * Global services are available to all realms and typically use super admin
+ * service users with system-wide access permissions.
+ * <p>
+ * This is set automatically by the external service registry when the service is
+ * registered by a super admin service user and set to MASTER_REALM.
+ */
+ @JsonProperty(access = JsonProperty.Access.READ_ONLY)
+ protected boolean isGlobal = false;
+
+ public ExternalService() {
+ }
+
+ // Minimal constructor
+ public ExternalService(String serviceId, String realm, String label, String homepageUrl, ExternalServiceStatus status) {
+ this.serviceId = serviceId;
+ this.realm = realm;
+ this.label = label;
+ this.homepageUrl = homepageUrl;
+ this.status = status;
+ }
+
+ public ExternalService(String serviceId, String label, String homepageUrl, ExternalServiceStatus status) {
+ this.serviceId = serviceId;
+ this.label = label;
+ this.homepageUrl = homepageUrl;
+ this.status = status;
+ }
+
+ // Getters and setters in property order
+ public String getServiceId() {
+ return serviceId;
+ }
+
+ public void setServiceId(String serviceId) {
+ this.serviceId = serviceId;
+ }
+
+ public int getInstanceId() {
+ return instanceId;
+ }
+
+ public void setInstanceId(int instanceId) {
+ this.instanceId = instanceId;
+ }
+
+ public String getVersion() {
+ return version;
+ }
+
+ public void setVersion(String version) {
+ this.version = version;
+ }
+
+ public String getRealm() {
+ return realm;
+ }
+
+ public void setRealm(String realm) {
+ this.realm = realm;
+ }
+
+ public String getIcon() {
+ return icon;
+ }
+
+ public void setIcon(String icon) {
+ this.icon = icon;
+ }
+
+ public String getLabel() {
+ return label;
+ }
+
+ public void setLabel(String label) {
+ this.label = label;
+ }
+
+ public String getHomepageUrl() {
+ return homepageUrl;
+ }
+
+ public void setHomepageUrl(String homepageUrl) {
+ this.homepageUrl = homepageUrl;
+ }
+
+ public ExternalServiceStatus getStatus() {
+ return status;
+ }
+
+ public void setStatus(ExternalServiceStatus status) {
+ this.status = status;
+ }
+
+ public ExternalServiceLeaseInfo getLeaseInfo() {
+ return leaseInfo;
+ }
+
+ public void setLeaseInfo(ExternalServiceLeaseInfo leaseInfo) {
+ this.leaseInfo = leaseInfo;
+ }
+
+ public boolean getIsGlobal() {
+ return isGlobal;
+ }
+
+ public void setIsGlobal(boolean isGlobal) {
+ this.isGlobal = isGlobal;
+ }
+
+ @Override
+ public String toString() {
+ return "ExternalService{" +
+ "serviceId='" + serviceId + '\'' +
+ ", instanceId='" + instanceId + '\'' +
+ ", version='" + version + '\'' +
+ ", realm='" + realm + '\'' +
+ ", icon='" + icon + '\'' +
+ ", label='" + label + '\'' +
+ ", homepageUrl='" + homepageUrl + '\'' +
+ ", status='" + status + '\'' +
+ ", isGlobal='" + isGlobal + '\'' +
+ '}';
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/services/ExternalServiceEvent.java b/model/src/main/java/org/openremote/model/services/ExternalServiceEvent.java
new file mode 100644
index 000000000..c285c3657
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/services/ExternalServiceEvent.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * 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/>.
+ */
+package org.openremote.model.services;
+
+import org.openremote.model.event.shared.RealmScopedEvent;
+
+public class ExternalServiceEvent extends RealmScopedEvent {
+
+ public enum Cause {
+ REGISTER, UPDATE, DEREGISTER
+ }
+
+ protected ExternalService service;
+
+ protected ExternalServiceEvent.Cause cause;
+
+ public ExternalServiceEvent(ExternalService service, ExternalServiceEvent.Cause cause) {
+ this.realm = service.getRealm();
+ this.cause = cause;
+ this.service = service;
+ }
+
+ public ExternalService getService() {
+ return service;
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{" +
+ "realm=" + realm +
+ ", service=" + service +
+ ", cause=" + cause +
+ '}';
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/services/ExternalServiceLeaseInfo.java b/model/src/main/java/org/openremote/model/services/ExternalServiceLeaseInfo.java
new file mode 100644
index 000000000..23760bc96
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/services/ExternalServiceLeaseInfo.java
@@ -0,0 +1,103 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * 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/>.
+ */
+package org.openremote.model.services;
+
+/**
+ * Lease info for an external service instance, contains timestamps for lease
+ * expiration, registration and renewal.
+ */
+public class ExternalServiceLeaseInfo {
+
+
+ /**
+ * The user's userId that registered the service
+ */
+ private String registrarUserId;
+
+
+ /**
+ * The timestamp when the lease expires.
+ */
+ private long expirationTimestamp;
+
+ /**
+ * The timestamp when the lease was registered.
+ */
+ private long registrationTimestamp;
+
+ /**
+ * The timestamp when the lease was renewed.
+ */
+ private long renewalTimestamp;
+
+ public ExternalServiceLeaseInfo(String registrarUserId, long expirationTimestamp, long registrationTimestamp,
+ long renewalTimestamp) {
+ this.registrarUserId = registrarUserId;
+ this.expirationTimestamp = expirationTimestamp;
+ this.registrationTimestamp = registrationTimestamp;
+ this.renewalTimestamp = renewalTimestamp;
+ }
+
+ public void setExpirationTimestamp(long expirationTimestamp) {
+ this.expirationTimestamp = expirationTimestamp;
+ }
+
+ public long getExpirationTimestamp() {
+ return expirationTimestamp;
+ }
+
+ public long getRegistrationTimestamp() {
+ return registrationTimestamp;
+ }
+
+ public void setRegistrationTimestamp(long registrationTimestamp) {
+ this.registrationTimestamp = registrationTimestamp;
+ }
+
+ public long getRenewalTimestamp() {
+ return renewalTimestamp;
+ }
+
+ public void setRenewalTimestamp(long renewalTimestamp) {
+ this.renewalTimestamp = renewalTimestamp;
+ }
+
+ public boolean isExpired(long currentTime) {
+ return expirationTimestamp < currentTime;
+ }
+
+ public String getRegistrarUserId() {
+ return registrarUserId;
+ }
+
+ public void setRegistrarUserId(String registrarUserId) {
+ this.registrarUserId = registrarUserId;
+ }
+
+ @Override
+ public String toString() {
+ return "ExternalServiceLeaseInfo{" +
+ ", registrarUserId=" + registrarUserId +
+ ", expirationTimestamp=" + expirationTimestamp +
+ ", registrationTimestamp=" + registrationTimestamp +
+ ", renewalTimestamp=" + renewalTimestamp +
+ '}';
+ }
+}
diff --git a/model/src/main/java/org/openremote/model/services/ExternalServiceResource.java b/model/src/main/java/org/openremote/model/services/ExternalServiceResource.java
new file mode 100644
index 000000000..aa91b05ed
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/services/ExternalServiceResource.java
@@ -0,0 +1,188 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * 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/>.
+ */
+package org.openremote.model.services;
+
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.media.Content;
+import io.swagger.v3.oas.annotations.media.Schema;
+import io.swagger.v3.oas.annotations.responses.ApiResponse;
+import io.swagger.v3.oas.annotations.tags.Tag;
+
+import org.openremote.model.Constants;
+import org.openremote.model.http.RequestParams;
+
+import jakarta.annotation.security.RolesAllowed;
+import jakarta.validation.Valid;
+import jakarta.validation.constraints.NotNull;
+import jakarta.validation.constraints.Size;
+import jakarta.ws.rs.*;
+
+import static jakarta.ws.rs.core.MediaType.APPLICATION_JSON;
+
+/**
+ * REST resource for managing external services.
+ * <p>
+ * This resource provides endpoints for service discovery, registration, and
+ * management of external services through the manager.
+ * <p>
+ * Registered services are made available via the OpenRemote manager's Web UI
+ * and API, enabling centralized service management and monitoring.
+ */
+@Tag(name = "Services", description = "Registration and management of external services")
+@Path("service")
+public interface ExternalServiceResource {
+
+ /**
+ * Register a new external service with the OpenRemote manager.
+ * <p>
+ * Creates a new registration entry and returns the registered external service
+ * with its generated instanceId and initial status.
+ * <p>
+ * This service will be made available only to the realm it is registered for.
+ *
+ * @param service The external service to register
+ * @return The registered external service with its instanceId and status
+ */
+ @POST
+ @Consumes(APPLICATION_JSON)
+ @Produces(APPLICATION_JSON)
+ @RolesAllowed({ Constants.WRITE_SERVICES_ROLE })
+ @Operation(operationId = "registerService", summary = "Register an external service with the OpenRemote manager", responses = {
+ @ApiResponse(responseCode = "200", description = "Service registered successfully", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ExternalService.class))),
+ @ApiResponse(responseCode = "400", description = "Invalid external service object"),
+ @ApiResponse(responseCode = "409", description = "ExternalService instance already registered"),
+ })
+ ExternalService registerService(@BeanParam RequestParams requestParams,
+ @NotNull @Valid ExternalService service);
+
+ /**
+ * Register a new global external service with the OpenRemote
+ * manager. This service will be made available to all realms.
+ * <p>
+ * Creates a new registration entry and returns the registered external service
+ * with its generated instanceId and initial status.
+ *
+ * @param service The external service to register
+ * @return The registered external service with its instanceId and status
+ */
+ @POST
+ @Path("global")
+ @Consumes(APPLICATION_JSON)
+ @Produces(APPLICATION_JSON)
+ @RolesAllowed({ Constants.WRITE_SERVICES_ROLE })
+ @Operation(operationId = "registerGlobalService", summary = "Register a global external service with the OpenRemote manager", responses = {
+ @ApiResponse(responseCode = "200", description = "Service registered successfully", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ExternalService.class))),
+ @ApiResponse(responseCode = "400", description = "Invalid external service object"),
+ @ApiResponse(responseCode = "409", description = "ExternalService instance already registered"),
+ })
+ ExternalService registerGlobalService(@BeanParam RequestParams requestParams,
+ @NotNull @Valid ExternalService service);
+
+ /**
+ * Retrieve all registered external services for a specific
+ * realm.
+ *
+ * @param realm The realm to filter services by
+ * @return Array of registered external services for the specified realm
+ */
+ @GET
+ @Produces(APPLICATION_JSON)
+ @RolesAllowed({ Constants.READ_SERVICES_ROLE })
+ @Operation(operationId = "getServices", summary = "List all registered external services for the given realm within the OpenRemote manager", responses = {
+ @ApiResponse(responseCode = "200", description = "List of registered external services", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ExternalService[].class))),
+ })
+ ExternalService[] getServices(@BeanParam RequestParams requestParams, @QueryParam("realm") @NotNull String realm);
+
+ /**
+ * Retrieve a specific external service by its serviceId and
+ * instanceId.
+ *
+ * @param serviceId The serviceId of the external service to retrieve
+ * @param instanceId The instanceId of the external service to retrieve
+ * @return The external service with the specified serviceId and instanceId
+ */
+ @GET
+ @Path("{serviceId}/{instanceId}")
+ @Produces(APPLICATION_JSON)
+ @RolesAllowed({ Constants.READ_SERVICES_ROLE })
+ @Operation(operationId = "getService", summary = "Retrieve a specific external service by its serviceId and instanceId", responses = {
+ @ApiResponse(responseCode = "200", description = "ExternalService retrieved successfully", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ExternalService.class))),
+ @ApiResponse(responseCode = "404", description = "ExternalService not found"),
+ })
+ ExternalService getService(@BeanParam RequestParams requestParams,
+ @PathParam("serviceId") @NotNull @Size(min = 1) String serviceId,
+ @PathParam("instanceId") int instanceId);
+
+ /**
+ * Retrieve all external services that are globally registered
+ *
+ * @return Array of globally accessible external services
+ */
+ @GET
+ @Path("global")
+ @Produces(APPLICATION_JSON)
+ @RolesAllowed({ Constants.READ_SERVICES_ROLE })
+ @Operation(operationId = "getGlobalServices", summary = "List all registered external services that are globally accessible within the OpenRemote manager", responses = {
+ @ApiResponse(responseCode = "200", description = "List of registered external services", content = @Content(mediaType = "application/json", schema = @Schema(implementation = ExternalService[].class))),
+ })
+ ExternalService[] getGlobalServices(@BeanParam RequestParams requestParams);
+
+ /**
+ * Send a heartbeat to refresh the active registration lease for an external service.
+ * <p>
+ * This endpoint is used by external services to indicate they are still running
+ * and available. It extends the service's lease duration and maintains its
+ * active status in the registry.
+ *
+ * @param serviceId The serviceId of the external service to send the heartbeat to
+ * @param instanceId The instanceId of the external service to send the heartbeat to
+ */
+ @PUT
+ @Path("{serviceId}/{instanceId}")
+ @RolesAllowed({ Constants.WRITE_SERVICES_ROLE })
+ @Operation(operationId = "heartbeat", summary = "Update the active registration lease for the specified external service", responses = {
+ @ApiResponse(responseCode = "204", description = "Heartbeat sent successfully"),
+ @ApiResponse(responseCode = "404", description = "Service instance not found"),
+ })
+ void heartbeat(@BeanParam RequestParams requestParams,
+ @PathParam("serviceId") @NotNull @Size(min = 1) String serviceId,
+ @PathParam("instanceId") int instanceId);
+
+ /**
+ * Deregister an external service from the registry.
+ * <p>
+ * Removes the active registration for the specified service, causing it to
+ * no longer be available through the external service registry. This is typically
+ * called when a service shuts down or needs to be removed from the system.
+ *
+ * @param serviceId The serviceId of the external service to deregister
+ * @param instanceId The instanceId of the external service to deregister
+ */
+ @DELETE
+ @Path("{serviceId}/{instanceId}")
+ @RolesAllowed({ Constants.WRITE_SERVICES_ROLE })
+ @Operation(operationId = "deregisterService", summary = "Deregister an external service", responses = {
+ @ApiResponse(responseCode = "204", description = "Service deregistered successfully"),
+ @ApiResponse(responseCode = "404", description = "Service instance not found"),
+ })
+ void deregisterService(@BeanParam RequestParams requestParams, @PathParam("serviceId") String serviceId,
+ @PathParam("instanceId") int instanceId);
+
+}
diff --git a/model/src/main/java/org/openremote/model/services/ExternalServiceStatus.java b/model/src/main/java/org/openremote/model/services/ExternalServiceStatus.java
new file mode 100644
index 000000000..9cb5db91a
--- /dev/null
+++ b/model/src/main/java/org/openremote/model/services/ExternalServiceStatus.java
@@ -0,0 +1,33 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * 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/>.
+ */
+package org.openremote.model.services;
+
+/**
+ * Status of a registered external service.
+ *
+ * <ul>
+ * <li>AVAILABLE: The external service is available and can be accessed</li>
+ * <li>UNAVAILABLE: The external service is unavailable</li>
+ * </ul>
+ */
+public enum ExternalServiceStatus {
+ AVAILABLE,
+ UNAVAILABLE,
+}
diff --git a/model/src/main/resources/ValidationMessages.properties b/model/src/main/resources/ValidationMessages.properties
index 5af4ea4a0..2c7d3be01 100644
--- a/model/src/main/resources/ValidationMessages.properties
+++ b/model/src/main/resources/ValidationMessages.properties
@@ -52,7 +52,16 @@ GatewayConnection.clientId.NotNull = Gateway connection client ID can not be emp
GatewayConnection.clientId.Size = Gateway connection client ID must be at least {min} and not more than {max} characters long
GatewayConnection.clientSecret.NotNull = Gateway connection client secret can not be empty
GatewayConnection.clientSecret.Size = Gateway connection client secret must be at least {min} and not more than {max} characters long
-
+ExternalService.serviceId.Size = External serviceId must be at least {min} and not more than {max} characters long
+ExternalService.serviceId.NotEmpty = External serviceId can not be empty
+ExternalService.realm.Size = External service realm must be at least {min} and not more than {max} characters long
+ExternalService.realm.NotEmpty = External service realm can not be empty
+ExternalService.label.Size = External service label must be at least {min} and not more than {max} characters long
+ExternalService.label.NotEmpty = External service label can not be empty
+ExternalService.homepageUrl.Size = External service homepageUrl must be at least {min} and not more than {max} characters long
+ExternalService.homepageUrl.NotEmpty = External service homepageUrl can not be empty
+ExternalService.status.NotNull = External service status can not be null
+ExternalService.version.Size = External service version must be at least {min} and not more than {max} characters long
Asset.invalid.message = Asset is not valid
ValueConstraint.Future.message = must be a future date
ValueConstraint.FutureOrPresent.message = must be a date in the present or in the future
diff --git a/setup/src/integration/java/org/openremote/setup/integration/KeycloakTestSetup.java b/setup/src/integration/java/org/openremote/setup/integration/KeycloakTestSetup.java
index cefe15f54..dc38b4501 100644
--- a/setup/src/integration/java/org/openremote/setup/integration/KeycloakTestSetup.java
+++ b/setup/src/integration/java/org/openremote/setup/integration/KeycloakTestSetup.java
@@ -38,6 +38,7 @@ import java.util.stream.Stream;
import static org.openremote.model.Constants.MASTER_REALM;
import static org.openremote.model.Constants.RESTRICTED_USER_REALM_ROLE;
+import static org.openremote.model.Constants.SUPER_USER_REALM_ROLE;
/**
* We have the following demo users:
@@ -72,6 +73,7 @@ public class KeycloakTestSetup extends AbstractKeycloakSetup {
public User testuser4;
public User buildingUser;
public User smartCityUser;
+ public User superServiceUser;
public User serviceUser;
public User serviceUser2;
@@ -83,8 +85,10 @@ public class KeycloakTestSetup extends AbstractKeycloakSetup {
public void onStart() throws Exception {
super.onStart();
+ ManagerIdentityProvider identityProvider = identityService.getIdentityProvider();
+
// Realms
- realmMaster = identityService.getIdentityProvider().getRealm(Constants.MASTER_REALM);
+ realmMaster = identityProvider.getRealm(Constants.MASTER_REALM);
realmBuilding = createRealm("building", "Building", true);
realmCity = createRealm("smartcity", "Smart City", true);
realmEnergy = createRealm("energy", "Energy Test", true);
@@ -133,6 +137,23 @@ public class KeycloakTestSetup extends AbstractKeycloakSetup {
this.smartCityUserId = smartCityUser.getId();
keycloakProvider.updateUserClientRoles(realmCity.getName(), smartCityUserId, "account"); // Remove all roles for account client
+
+
+ // Service user for master realm with SUPER_USER realm role
+ superServiceUser = new User()
+ .setServiceAccount(true)
+ .setEnabled(true)
+ .setUsername("superserviceuser");
+ superServiceUser = keycloakProvider.createUpdateUser(MASTER_REALM, superServiceUser, UniqueIdentifierGenerator.generateId("superserviceusertest"), true);
+ keycloakProvider.updateUserClientRoles(
+ MASTER_REALM,
+ superServiceUser.getId(),
+ Constants.KEYCLOAK_CLIENT_ID,
+ Stream.of(ClientRole.WRITE_SERVICES, ClientRole.READ_SERVICES).map(ClientRole::getValue).toArray(String[]::new)
+ );
+ // Add SUPER_USER_REALM_ROLE to superServiceUser
+ identityProvider.updateUserRealmRoles(MASTER_REALM, superServiceUser.getId(), identityProvider.addUserRealmRoles(MASTER_REALM, superServiceUser.getId(), SUPER_USER_REALM_ROLE));
+
/*
* Service user clients
*/
@@ -145,7 +166,7 @@ public class KeycloakTestSetup extends AbstractKeycloakSetup {
realmBuilding.getName(),
serviceUser.getId(),
Constants.KEYCLOAK_CLIENT_ID,
- Stream.of(ClientRole.READ_ASSETS, ClientRole.WRITE_ASSETS, ClientRole.WRITE_ATTRIBUTES).map(ClientRole::getValue).toArray(String[]::new)
+ Stream.of(ClientRole.READ_ASSETS, ClientRole.WRITE_ASSETS, ClientRole.WRITE_ATTRIBUTES, ClientRole.WRITE_SERVICES, ClientRole.READ_SERVICES).map(ClientRole::getValue).toArray(String[]::new)
);
serviceUser2 = new User()
.setServiceAccount(true)
@@ -156,11 +177,10 @@ public class KeycloakTestSetup extends AbstractKeycloakSetup {
realmBuilding.getName(),
serviceUser2.getId(),
Constants.KEYCLOAK_CLIENT_ID,
- Stream.of(ClientRole.READ_ASSETS, ClientRole.WRITE_ASSETS, ClientRole.WRITE_ATTRIBUTES).map(ClientRole::getValue).toArray(String[]::new)
+ Stream.of(ClientRole.READ_ASSETS, ClientRole.WRITE_ASSETS, ClientRole.WRITE_ATTRIBUTES, ClientRole.WRITE_SERVICES, ClientRole.READ_SERVICES).map(ClientRole::getValue).toArray(String[]::new)
);
// ################################ Make users restricted ###################################
- ManagerIdentityProvider identityProvider = identityService.getIdentityProvider();
identityProvider.updateUserRealmRoles(realmBuilding.getName(), testuser3Id, identityProvider.addUserRealmRoles(realmBuilding.getName(), testuser3Id, RESTRICTED_USER_REALM_ROLE));
identityProvider.updateUserRealmRoles(realmBuilding.getName(), buildingUserId, identityProvider.addUserRealmRoles(realmBuilding.getName(), buildingUserId, RESTRICTED_USER_REALM_ROLE));
identityProvider.updateUserRealmRoles(realmBuilding.getName(), serviceUser2.getId(), identityProvider.addUserRealmRoles(realmBuilding.getName(), serviceUser2.getId(), RESTRICTED_USER_REALM_ROLE));
diff --git a/test/src/test/groovy/org/openremote/test/services/ExternalServiceTest.groovy b/test/src/test/groovy/org/openremote/test/services/ExternalServiceTest.groovy
new file mode 100644
index 000000000..48b476cc3
--- /dev/null
+++ b/test/src/test/groovy/org/openremote/test/services/ExternalServiceTest.groovy
@@ -0,0 +1,335 @@
+package org.openremote.test.services
+
+import jakarta.ws.rs.WebApplicationException
+import org.openremote.manager.services.ExternalServiceRegistryService
+import org.openremote.manager.setup.SetupService
+import org.openremote.model.services.ExternalService
+import org.openremote.model.services.ExternalServiceResource
+import org.openremote.model.services.ExternalServiceStatus
+import org.openremote.setup.integration.KeycloakTestSetup
+import org.openremote.test.ManagerContainerTrait
+import spock.lang.Specification
+import spock.util.concurrent.PollingConditions
+
+import jakarta.ws.rs.core.Response
+
+import java.util.concurrent.TimeUnit
+
+import static org.openremote.model.Constants.*
+
+class ExternalServiceTest extends Specification implements ManagerContainerTrait {
+
+ def "Test external service resource and local manager external service registry logic"() {
+
+ given: "the server container is started"
+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)
+ def container = startContainer(defaultConfig(), defaultServices())
+ def externalServiceRegistryService = container.getService(ExternalServiceRegistryService.class)
+ def keycloakTestSetup = container.getService(SetupService.class).getTaskOfType(KeycloakTestSetup.class)
+ WebApplicationException ex
+
+
+ when: "the users are authenticated"
+ // regular user for non-service-user testing but with read:services scope
+ def regularUserAccessToken = authenticate(
+ container,
+ MASTER_REALM,
+ KEYCLOAK_CLIENT_ID,
+ "testuser1",
+ "testuser1"
+ ).token
+
+ // building service user for single tenant logic
+ def buildingServiceUserAccessToken = authenticate(
+ container,
+ keycloakTestSetup.realmBuilding.getName(),
+ keycloakTestSetup.serviceUser.username,
+ keycloakTestSetup.serviceUser.secret
+ ).token
+
+ def buildingServiceUser2AccessToken = authenticate(
+ container,
+ keycloakTestSetup.realmBuilding.getName(),
+ keycloakTestSetup.serviceUser2.username,
+ keycloakTestSetup.serviceUser2.secret
+ ).token
+
+ // master service user for multi-tenant logic
+ def superServiceUserAccessToken = authenticate(
+ container,
+ MASTER_REALM,
+ keycloakTestSetup.superServiceUser.username,
+ keycloakTestSetup.superServiceUser.secret
+ ).token
+
+ then: "the users have been authenticated and the tokens are retrieved"
+ conditions.eventually {
+ assert buildingServiceUserAccessToken != null
+ assert regularUserAccessToken != null
+ assert superServiceUserAccessToken != null
+ }
+
+ when: "the external service resource is set up"
+ def serverUri = serverUri(serverPort)
+ def buildingExternalServiceResource = getClientApiTarget(serverUri, keycloakTestSetup.realmBuilding.getName(), buildingServiceUserAccessToken).proxy(ExternalServiceResource)
+ def buildingExternalServiceResource2 = getClientApiTarget(serverUri, keycloakTestSetup.realmBuilding.getName(), buildingServiceUser2AccessToken).proxy(ExternalServiceResource)
+ def regularUserExternalServiceResource = getClientApiTarget(serverUri, MASTER_REALM, regularUserAccessToken).proxy(ExternalServiceResource)
+ def superServiceUserExternalServiceResource = getClientApiTarget(serverUri, MASTER_REALM, superServiceUserAccessToken).proxy(ExternalServiceResource)
+
+ then: "the external service resources should be accessible"
+ assert buildingExternalServiceResource != null
+ assert regularUserExternalServiceResource != null
+ assert superServiceUserExternalServiceResource != null
+
+
+ // === Tests related to interacting with the external services resource as a service user for a specific realm ===
+
+ when: "the building service user registers an external service"
+ def buildingExternalService = new ExternalService(
+ serviceId: "building-energy-management",
+ label: "Building Energy Management Service",
+ homepageUrl: "https://local.test/services/building-energy-management/ui",
+ status: ExternalServiceStatus.AVAILABLE,
+ )
+ def registeredBuildingExternalService = buildingExternalServiceResource.registerService(null, buildingExternalService)
+
+ then: "the building external service should be registered and the registered external service should have an instanceId assigned"
+ assert registeredBuildingExternalService.instanceId != 0
+
+ and: "the building external service should be included in the list of external services for the building realm"
+ def buildingServices = buildingExternalServiceResource.getServices(null, keycloakTestSetup.realmBuilding.getName())
+ assert buildingServices != null
+ assert buildingServices.size() == 1
+ assert buildingServices[0].serviceId == buildingExternalService.serviceId
+ assert buildingServices[0].label == buildingExternalService.label
+ assert buildingServices[0].realm == buildingExternalService.realm
+ assert buildingServices[0].homepageUrl == buildingExternalService.homepageUrl
+ assert buildingServices[0].status == buildingExternalService.status
+
+ when: "time advanced by 70 seconds, longer than the default registration lease duration"
+ advancePseudoClock(70, TimeUnit.SECONDS)
+
+ then: "the building external service should now be marked as unavailable"
+ externalServiceRegistryService.markExpiredInstancesAsUnavailable()
+ def buildingServiceAfterInstanceExpiry = buildingExternalServiceResource.getService(null, registeredBuildingExternalService.serviceId, registeredBuildingExternalService.instanceId)
+ assert buildingServiceAfterInstanceExpiry.status == ExternalServiceStatus.UNAVAILABLE
+
+ when: "the building service user sends a heartbeat"
+ buildingExternalServiceResource.heartbeat(null, registeredBuildingExternalService.serviceId, registeredBuildingExternalService.instanceId)
+
+ then: "the building external service should now be marked as available"
+ def buildingServiceAfterHeartbeat = buildingExternalServiceResource.getService(null, registeredBuildingExternalService.serviceId, registeredBuildingExternalService.instanceId)
+ assert buildingServiceAfterHeartbeat.status == ExternalServiceStatus.AVAILABLE
+ when: "another service user tries to send a heartbeat for the same external service"
+ buildingExternalServiceResource2.heartbeat(null, registeredBuildingExternalService.serviceId, registeredBuildingExternalService.instanceId)
+
+ then: "the heartbeat should be rejected, and a forbidden response received"
+ ex = thrown(WebApplicationException)
+ assert ex.response.status == Response.Status.FORBIDDEN.getStatusCode()
+
+ when: "another service user tries to de-register the same external service"
+ buildingExternalServiceResource2.deregisterService(null, registeredBuildingExternalService.serviceId, registeredBuildingExternalService.instanceId)
+
+ then: "the de-registration should be rejected, and a forbidden response received"
+ ex = thrown(WebApplicationException)
+ assert ex.response.status == Response.Status.FORBIDDEN.getStatusCode()
+
+ when: "the building service user de-registers the external service"
+ buildingExternalServiceResource.deregisterService(null, registeredBuildingExternalService.serviceId, registeredBuildingExternalService.instanceId)
+
+ then: "the building external service should no longer be included in the list of external services for the building realm"
+ def buildingServicesAfterDeregister = buildingExternalServiceResource.getServices(null, keycloakTestSetup.realmBuilding.getName())
+ assert buildingServicesAfterDeregister != null
+ assert buildingServicesAfterDeregister.size() == 0
+
+ when: "the building service user tries to retrieve the now deregistered external service"
+ buildingExternalServiceResource.getService(null, registeredBuildingExternalService.serviceId, registeredBuildingExternalService.instanceId)
+
+ then: "the building service user should receive a 404 not found response"
+ ex = thrown(WebApplicationException)
+ assert ex.response.status == Response.Status.NOT_FOUND.getStatusCode()
+
+ when: "the building service user tries to retrieve the external services from an inaccessible realm"
+ buildingExternalServiceResource.getServices(null, MASTER_REALM)
+
+ then: "the building service user should receive a 403 forbidden response"
+ ex = thrown(WebApplicationException)
+ assert ex.response.status == Response.Status.FORBIDDEN.getStatusCode()
+
+ // === Tests related to global service registration and management ===
+
+ when: "the super user registers a global service (master realm + user is super user)"
+ def globalExternalService = new ExternalService(
+ serviceId: "forecasting-service",
+ label: "Forecasting Service",
+ homepageUrl: "https://local.test/services/forecasting-service/ui",
+ status: ExternalServiceStatus.AVAILABLE,
+ )
+ def registeredGlobalExternalService = superServiceUserExternalServiceResource.registerGlobalService(null, globalExternalService)
+
+ then: "the global external service should be registered and the registered external service should have an instanceId assigned"
+ assert registeredGlobalExternalService.instanceId != null
+
+ and: "the global external service should be included in the list of global services"
+ def globalServices = superServiceUserExternalServiceResource.getGlobalServices()
+ assert globalServices != null
+ assert globalServices.size() == 1
+ assert globalServices[0].serviceId == globalExternalService.serviceId
+
+ when: "time advanced by 70 seconds, longer than the default registration lease duration"
+ advancePseudoClock(70, TimeUnit.SECONDS)
+
+ then: "the global external service should now be marked as unavailable"
+ externalServiceRegistryService.markExpiredInstancesAsUnavailable()
+ def globalServiceAfterInstanceExpiry = superServiceUserExternalServiceResource.getService(null, registeredGlobalExternalService.serviceId, registeredGlobalExternalService.instanceId)
+ assert globalServiceAfterInstanceExpiry.status == ExternalServiceStatus.UNAVAILABLE
+
+ when: "the super user sends a heartbeat for the global external service"
+ superServiceUserExternalServiceResource.heartbeat(null, registeredGlobalExternalService.serviceId, registeredGlobalExternalService.instanceId)
+
+ then: "the global external service should now be marked as available"
+ def globalServiceAfterHeartbeat = superServiceUserExternalServiceResource.getService(null, registeredGlobalExternalService.serviceId, registeredGlobalExternalService.instanceId)
+ assert globalServiceAfterHeartbeat.status == ExternalServiceStatus.AVAILABLE
+
+
+ // === Tests related to interacting with global services as a service user from a realm different from the master realm ===
+
+ when: "the building service user tries to retrieve the global services"
+ def globalServicesForBuildingRealm = buildingExternalServiceResource.getGlobalServices()
+
+ then: "the building service user should receive the global services which includes the newly registered global forecasting service"
+ assert globalServicesForBuildingRealm != null
+ assert globalServicesForBuildingRealm.size() == 1
+ assert globalServicesForBuildingRealm[0].serviceId == registeredGlobalExternalService.serviceId
+
+ when: "the building service user registers a new realm-bound external service"
+ def buildingExternalService2 = new ExternalService(
+ serviceId: "building-energy-management-2",
+ label: "Building Energy Management Service 2",
+ homepageUrl: "https://local.test/services/building-energy-management-2/ui",
+ status: ExternalServiceStatus.AVAILABLE,
+ )
+ def registeredBuildingExternalService2 = buildingExternalServiceResource.registerService(null, buildingExternalService2)
+
+ then: "the building service user should receive the new realm-bound external service"
+ assert registeredBuildingExternalService2.instanceId != null
+
+ when: "the building service user retrieves the global external services"
+ def globalServicesForBuildingRealm2 = buildingExternalServiceResource.getGlobalServices()
+
+ then: "the returned global external services should only include the global forecasting service"
+ assert globalServicesForBuildingRealm2 != null
+ assert globalServicesForBuildingRealm2.size() == 1
+ assert globalServicesForBuildingRealm2[0].serviceId == registeredGlobalExternalService.serviceId
+
+ when: "the building service user retrieves external services from its realm"
+ def buildingServicesForBuildingRealm2 = buildingExternalServiceResource.getServices(null, keycloakTestSetup.realmBuilding.getName())
+
+ then: "the returned external services should only include the new realm-bound external service"
+ assert buildingServicesForBuildingRealm2 != null
+ assert buildingServicesForBuildingRealm2.size() == 1
+ assert buildingServicesForBuildingRealm2[0].serviceId == buildingExternalService2.serviceId
+
+ when: "the building service user tries to send a heartbeat for the global external service"
+ buildingExternalServiceResource.heartbeat(null, registeredGlobalExternalService.serviceId, registeredGlobalExternalService.instanceId)
+
+ then: "the building service user should receive a 403 forbidden response"
+ ex = thrown(WebApplicationException)
+ assert ex.response.status == Response.Status.FORBIDDEN.getStatusCode()
+
+ when: "the building service user tries to deregister the global external service"
+ buildingExternalServiceResource.deregisterService(null, registeredGlobalExternalService.serviceId, registeredGlobalExternalService.instanceId)
+
+ then: "the building service user should receive a 403 forbidden response"
+ ex = thrown(WebApplicationException)
+ assert ex.response.status == Response.Status.FORBIDDEN.getStatusCode()
+
+
+ // == Tests related to a regular user trying to interact with external services ===
+
+ when: "the regular user tries to retrieve the global external services"
+
+ def regularUserGlobalServices = regularUserExternalServiceResource.getGlobalServices()
+
+ then: "the regular user should receive a list of all global external services, since they are available to all realms"
+ assert regularUserGlobalServices != null
+ assert regularUserGlobalServices.size() == 1
+ assert regularUserGlobalServices[0].serviceId == registeredGlobalExternalService.serviceId
+
+ when: "the regular user tries to retrieve the external services from its realm"
+ def regularUserRealmServices = regularUserExternalServiceResource.getServices(null, MASTER_REALM)
+
+ then: "the regular user should receive a list of all external services from its realm"
+ assert regularUserRealmServices != null
+ assert regularUserRealmServices.size() == 1
+
+ when: "the regular user tries to retrieve the external services from a realm other than its own"
+ regularUserExternalServiceResource.getServices(null, keycloakTestSetup.realmBuilding.getName())
+
+ then: "the regular user should receive a 403 forbidden response"
+ ex = thrown(WebApplicationException)
+ assert ex.response.status == Response.Status.FORBIDDEN.getStatusCode()
+
+ when: "the regular user tries to send a heartbeat for an external service"
+ regularUserExternalServiceResource.heartbeat(null, registeredBuildingExternalService2.serviceId, registeredBuildingExternalService2.instanceId)
+
+ then: "the regular user should receive a 401 unauthorized response"
+ ex = thrown(WebApplicationException)
+ assert ex.response.status == Response.Status.UNAUTHORIZED.getStatusCode()
+
+ when: "the regular user tries to deregister an external service"
+ regularUserExternalServiceResource.deregisterService(null, registeredBuildingExternalService2.serviceId, registeredBuildingExternalService2.instanceId)
+
+ then: "the regular user should receive a 401 unauthorized response"
+ ex = thrown(WebApplicationException)
+ assert ex.response.status == Response.Status.UNAUTHORIZED.getStatusCode()
+
+ when: "the regular user tries to register an external service"
+ def regularUserNewService = new ExternalService(
+ serviceId: "regular-user-new-service",
+ label: "Regular User New Service",
+ homepageUrl: "https://local.test/services/regular-user-new-service/ui",
+ status: ExternalServiceStatus.AVAILABLE,
+ )
+ regularUserExternalServiceResource.registerService(null, regularUserNewService)
+
+ then: "the regular user should receive a 401 unauthorized response"
+ ex = thrown(WebApplicationException)
+ assert ex.response.status == Response.Status.UNAUTHORIZED.getStatusCode()
+
+ when: "the regular user tries to register a global external service"
+ regularUserExternalServiceResource.registerGlobalService(null, regularUserNewService)
+
+ then: "the regular user should receive a 401 unauthorized response"
+ ex = thrown(WebApplicationException)
+ assert ex.response.status == Response.Status.UNAUTHORIZED.getStatusCode()
+
+
+ // == Additional miscellaneous tests ==
+
+ when: "time advances by 70 seconds, longer than the default registration lease duration"
+ advancePseudoClock(70, TimeUnit.SECONDS)
+
+ then: "the global external service should now be marked as unavailable"
+ externalServiceRegistryService.markExpiredInstancesAsUnavailable()
+ def globalServiceAfterInstanceExpiryMisc = superServiceUserExternalServiceResource.getService(null, registeredGlobalExternalService.serviceId, registeredGlobalExternalService.instanceId)
+ assert globalServiceAfterInstanceExpiryMisc.status == ExternalServiceStatus.UNAVAILABLE
+
+ and: "the building external service should now be marked as unavailable"
+ def buildingServiceAfterInstanceExpiryMisc = buildingExternalServiceResource.getService(null, registeredBuildingExternalService2.serviceId, registeredBuildingExternalService2.instanceId)
+ assert buildingServiceAfterInstanceExpiryMisc.status == ExternalServiceStatus.UNAVAILABLE
+
+ when: "time advances by 24 hours, longer than the default automatic deregistration threshold"
+ advancePseudoClock(24, TimeUnit.HOURS)
+ externalServiceRegistryService.deregisterLongExpiredInstances()
+
+ then: "the building external service should now be deregistered, thus the list of external services for the building realm should be empty"
+ def buildingRealmServices = buildingExternalServiceResource.getServices(null, keycloakTestSetup.realmBuilding.getName())
+ assert buildingRealmServices.size() == 0
+
+ and: "the global external service should now be deregistered, thus the list of global external services should be empty"
+ def globalRealmServices = buildingExternalServiceResource.getGlobalServices()
+ assert globalRealmServices.size() == 0
+
+ }
+}
diff --git a/test/src/test/groovy/org/openremote/test/users/UserResourceTest.groovy b/test/src/test/groovy/org/openremote/test/users/UserResourceTest.groovy
index 075e738b2..0f1d3773d 100644
--- a/test/src/test/groovy/org/openremote/test/users/UserResourceTest.groovy
+++ b/test/src/test/groovy/org/openremote/test/users/UserResourceTest.groovy
@@ -117,7 +117,7 @@ class UserResourceTest extends Specification implements ManagerContainerTrait {
def users = adminUserResource.query(null, new UserQuery().realm(new RealmPredicate(keycloakTestSetup.realmMaster.name)))
then: "all users should be returned including system users"
- users.size() == 3
+ users.size() == 4
users.find {it.isSystemAccount() && it.username == Constants.MANAGER_CLIENT_ID} != null
users.find {it.username == MASTER_REALM_ADMIN_USER} != null
users.find {it.id == keycloakTestSetup.testuser1Id} != null
@@ -126,7 +126,7 @@ class UserResourceTest extends Specification implements ManagerContainerTrait {
users = regularUserMasterResource.query(null, new UserQuery().realm(new RealmPredicate(keycloakTestSetup.realmMaster.name)))
then: "only non system users of the users realm should be returned"
- users.size() == 2
+ users.size() == 3
users.find {it.username == MASTER_REALM_ADMIN_USER} != null
users.find {it.id == keycloakTestSetup.testuser1Id} != null
@@ -424,7 +424,7 @@ class UserResourceTest extends Specification implements ManagerContainerTrait {
then: "user1 is fetched correctly"
User[] users = adminUserResource.query(null, new UserQuery().realm(new RealmPredicate(keycloakTestSetup.realmMaster.name)))
- assert users.size() == (3 + 1)
+ assert users.size() == (4 + 1)
assert users.any { it.username == username1 }
/* ---------- */
@@ -464,7 +464,7 @@ class UserResourceTest extends Specification implements ManagerContainerTrait {
then: "user4 is created correctly"
User[] users4 = adminUserResource.query(null, new UserQuery().realm(new RealmPredicate(keycloakTestSetup.realmMaster.name)))
- assert users4.size() == (3 + 2)
+ assert users4.size() == (4 + 2)
assert users4.any { it.username == username4 }
/* ---------- */
@@ -476,7 +476,7 @@ class UserResourceTest extends Specification implements ManagerContainerTrait {
then: "user5 is created correctly"
User[] users5 = adminUserResource.query(null, new UserQuery().realm(new RealmPredicate(keycloakTestSetup.realmMaster.name)))
- assert users5.size() == (3 + 3)
+ assert users5.size() == (4 + 3)
assert users5.any { it.username == username5 }
}
}
diff --git a/ui/.prettierrc.json b/ui/.prettierrc.json
index 3e919d3df..ae879dc2b 100644
--- a/ui/.prettierrc.json
+++ b/ui/.prettierrc.json
@@ -1,5 +1,7 @@
{
"trailingComma": "es5",
"printWidth": 120,
- "singleQuote": false
+ "singleQuote": false,
+ "tabWidth": 4,
+ "useTabs": false
}
diff --git a/ui/app/manager/src/headers.ts b/ui/app/manager/src/headers.ts
index 01fafa946..eef1fc328 100644
--- a/ui/app/manager/src/headers.ts
+++ b/ui/app/manager/src/headers.ts
@@ -19,6 +19,15 @@ export function headerItemAssets<S extends AppStateKeyed, A extends AnyAction>(o
};
}
+export function headerItemServices<S extends AppStateKeyed, A extends AnyAction>(orApp: OrApp<S>): HeaderItem {
+ return {
+ icon: "puzzle",
+ href: "services",
+ text: "services.title",
+ roles: ["read:services"]
+ };
+}
+
export function headerItemRules<S extends AppStateKeyed, A extends AnyAction>(orApp: OrApp<S>): HeaderItem {
return {
icon: "state-machine",
diff --git a/ui/app/manager/src/index.ts b/ui/app/manager/src/index.ts
index ca3cb7c48..dec6771d3 100644
--- a/ui/app/manager/src/index.ts
+++ b/ui/app/manager/src/index.ts
@@ -11,6 +11,7 @@ import {
headerItemGatewayConnection,
headerItemGatewayTunnel,
headerItemInsights,
+ headerItemServices,
headerItemLanguage,
headerItemLogout,
headerItemLogs,
@@ -29,6 +30,8 @@ import "./pages/page-gateway";
import {pageGatewayProvider} from "./pages/page-gateway";
import "./pages/page-insights";
import {PageInsightsConfig, pageInsightsProvider} from "./pages/page-insights";
+import "./pages/page-services";
+import {pageServicesProvider} from "./pages/page-services";
import "./pages/page-rules";
import {PageRulesConfig, pageRulesProvider} from "./pages/page-rules";
import "./pages/page-logs";
@@ -70,6 +73,7 @@ export const DefaultPagesConfig: PageProvider<any>[] = [
pageGatewayTunnelProvider(store),
pageLogsProvider(store),
pageInsightsProvider(store),
+ pageServicesProvider(store),
pageRulesProvider(store),
pageAccountProvider(store),
pageRolesProvider(store),
@@ -85,7 +89,8 @@ export const DefaultHeaderMainMenu: {[name: string]: HeaderItem} = {
map: headerItemMap(orApp),
assets: headerItemAssets(orApp),
rules: headerItemRules(orApp),
- insights: headerItemInsights(orApp)
+ services: headerItemServices(orApp),
+ insights: headerItemInsights(orApp),
};
export const DefaultHeaderSecondaryMenu: {[name: string]: HeaderItem} = {
diff --git a/ui/app/manager/src/pages/page-services.ts b/ui/app/manager/src/pages/page-services.ts
new file mode 100644
index 000000000..43eea8977
--- /dev/null
+++ b/ui/app/manager/src/pages/page-services.ts
@@ -0,0 +1,374 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * 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 { css, html, PropertyValues, TemplateResult } from "lit";
+import { customElement, state } from "lit/decorators.js";
+import { AppStateKeyed, Page, PageProvider, router } from "@openremote/or-app";
+import { createSelector, Store } from "@reduxjs/toolkit";
+import { manager } from "@openremote/core";
+import "@openremote/or-services";
+import { ExternalService, ExternalServiceEvent, ExternalServiceEventCause, ExternalServiceStatus } from "@openremote/model";
+import { getServicesRoute } from "../routes";
+
+import { showSnackbar } from "@openremote/or-mwc-components/or-mwc-snackbar";
+import { i18next } from "@openremote/or-translate";
+
+export function pageServicesProvider(store: Store<AppStateKeyed>): PageProvider<AppStateKeyed> {
+ return {
+ name: "services",
+ routes: ["services", "services/:serviceName"],
+ pageCreator: () => {
+ const page = new PageServices(store);
+ return page;
+ },
+ };
+}
+
+const serviceStyles = css`
+ :host {
+ overflow: hidden;
+ }
+
+ #services {
+ z-index: 0;
+ background: transparent;
+ }
+`;
+
+/**
+ * Consolidate services by serviceId, preferring AVAILABLE over UNAVAILABLE
+ * @param services - Array of services to consolidate
+ * @returns Consolidated array with unique serviceIds
+ */
+function consolidateServices(services: ExternalService[]): ExternalService[] {
+ return Object.values(
+ services.reduce((acc, service) => {
+ const serviceId = service.serviceId || "";
+ const existing = acc[serviceId];
+ if (
+ !existing ||
+ (service.status === ExternalServiceStatus.AVAILABLE && existing.status !== ExternalServiceStatus.AVAILABLE)
+ ) {
+ acc[serviceId] = service;
+ }
+ return acc;
+ }, {} as Record<string, ExternalService>)
+ );
+}
+
+@customElement("page-services")
+export class PageServices extends Page<AppStateKeyed> {
+ static get styles() {
+ return [serviceStyles];
+ }
+
+ get name(): string {
+ return "services.title";
+ }
+
+ @state()
+ protected serviceId: string | null = null;
+
+ @state()
+ protected realmName = "";
+
+ @state()
+ protected services: ExternalService[] = [];
+
+ @state()
+ protected selectedService: ExternalService | null = null;
+
+ @state()
+ protected _loading = false;
+
+ protected _eventSubscriptionId?: string;
+
+ constructor(store: Store<AppStateKeyed>) {
+ super(store);
+ this.realmName = manager.displayRealm;
+ }
+
+ connectedCallback(): void {
+ super.connectedCallback();
+ this._subscribeEvents();
+ }
+
+ disconnectedCallback(): void {
+ super.disconnectedCallback();
+ this._unsubscribeEvents();
+ }
+
+ protected async _subscribeEvents() {
+ if (manager.events) {
+ this._eventSubscriptionId = await manager.events.subscribe<ExternalServiceEvent>(
+ {
+ eventType: "external-service",
+ },
+ (ev) => this._onEvent(ev)
+ );
+ }
+ }
+
+ protected _unsubscribeEvents() {
+ if (this._eventSubscriptionId) {
+ manager.events?.unsubscribe(this._eventSubscriptionId);
+ }
+ }
+
+ protected _onEvent(event: ExternalServiceEvent) {
+ if (!event.service || !event.cause) {
+ return;
+ }
+
+ // Super users receive all events, so we need to filter them out if they are not for the display realm or global
+ if (manager.isSuperUser && event.service.realm !== this.realmName && !event.service.isGlobal) {
+ return;
+ }
+
+ // Handle the event based on the cause
+ switch (event.cause) {
+ case ExternalServiceEventCause.REGISTER: {
+ this._onServiceRegistered(event);
+ break;
+ }
+ case ExternalServiceEventCause.UPDATE: {
+ this._onServiceUpdated(event);
+ break;
+ }
+ case ExternalServiceEventCause.DEREGISTER: {
+ this._onServiceDeregistered(event);
+ break;
+ }
+ default:
+ break;
+ }
+
+ this.services = consolidateServices(this.services);
+ }
+
+ protected _onServiceRegistered(event: ExternalServiceEvent): void {
+ this.services.push(event.service);
+
+ // If the pushed service is the same as the selected service.serviceId and the current selected service is unvailable, refresh the iframe
+ if (
+ this._eventIsForSelectedServiceId(event) &&
+ this.selectedService?.status === ExternalServiceStatus.UNAVAILABLE
+ ) {
+ this.selectedService = event.service;
+ this._refreshIframe();
+ }
+ }
+
+ protected _onServiceUpdated(event: ExternalServiceEvent): void {
+ const existingServiceInstance = this.services.find(
+ (service) =>
+ service.serviceId === event.service?.serviceId &&
+ service.instanceId === event.service?.instanceId
+ );
+
+ // Overwrite the existing service with the updated service object
+ if (existingServiceInstance) {
+ Object.assign(existingServiceInstance, event.service);
+ }
+
+ // If the selected service instance is the one that was updated, and the status has changed, refresh the iframe
+ if (
+ this._eventIsForSelectedServiceInstance(event) &&
+ this.selectedService?.status !== event.service?.status
+ ) {
+ this.selectedService = event.service;
+ this._refreshIframe();
+ return;
+ }
+
+ // If the selected serviceId is the same as the event serviceId and the current selected status is unavailable, refresh the iframe
+ if (
+ this._eventIsForSelectedServiceId(event) &&
+ this.selectedService?.status === ExternalServiceStatus.UNAVAILABLE
+ ) {
+ this.selectedService = event.service;
+ this._refreshIframe();
+ }
+ }
+
+ protected _onServiceDeregistered(event: ExternalServiceEvent): void {
+ // Filter out the service instance that was deregistered
+ this.services = this.services.filter(
+ (service) =>
+ service.serviceId !== event.service?.serviceId &&
+ service.instanceId !== event.service?.instanceId
+ );
+
+ // If the selected service instance is the one that was deregistered, set the selected service to null
+ if (this._eventIsForSelectedServiceInstance(event)) {
+ this.selectedService = null;
+ }
+ }
+
+ protected _eventIsForSelectedServiceInstance(event: ExternalServiceEvent): boolean {
+ return (
+ this.selectedService?.serviceId === event.service?.serviceId &&
+ this.selectedService?.instanceId === event.service?.instanceId
+ );
+ }
+
+ protected _eventIsForSelectedServiceId(event: ExternalServiceEvent): boolean {
+ return this.selectedService?.serviceId === event.service?.serviceId;
+ }
+
+ protected async _loadData(silent = false): Promise<void> {
+ if (!silent) {
+ this._loading = true;
+ }
+
+ try {
+ // Use promise.allSettled to run both requests in parallel and wait for both to complete
+ // If we use Promise.all, we would not be able to handle the case where one request fails and the other succeeds
+ const [realmServicesResult, globalServicesResult] = await Promise.allSettled([
+ manager.rest.api.ExternalServiceResource.getServices({
+ realm: this.realmName,
+ }),
+ manager.rest.api.ExternalServiceResource.getGlobalServices(),
+ ]);
+
+ // Temporary array to store all retrieved services
+ const retrievedServices: ExternalService[] = [];
+
+ const realmServicesRequestHasSucceeded =
+ realmServicesResult.status === "fulfilled" && realmServicesResult.value.status === 200;
+
+ // Handle realm services result
+ if (realmServicesRequestHasSucceeded) {
+ retrievedServices.push(...realmServicesResult.value.data);
+ } else {
+ console.error("Failed to load realm services:", realmServicesResult.status);
+ showSnackbar(undefined, i18next.t("services.realmServicesLoadError"));
+ }
+
+ // Handle global services result
+ const globalServicesRequestHasSucceeded =
+ globalServicesResult.status === "fulfilled" && globalServicesResult.value.status === 200;
+ if (globalServicesRequestHasSucceeded) {
+ retrievedServices.push(...globalServicesResult.value.data);
+ } else {
+ console.error("Failed to load global services:", globalServicesResult.status);
+ showSnackbar(undefined, i18next.t("services.globalServicesLoadError"));
+ }
+
+ // Update the services state if we able to retrieve any
+ if (retrievedServices.length > 0) {
+ this.services = consolidateServices(retrievedServices);
+ this.requestUpdate();
+
+ // Re-select the service if serviceId is set and no service is selected
+ if (this.serviceId && !this.selectedService) {
+ const service = this.services.find((service) => service.serviceId === this.serviceId);
+ if (service) {
+ this.selectedService = service;
+ }
+ }
+ }
+ } catch (error) {
+ console.error("Unexpected error loading services:", error);
+ showSnackbar(undefined, i18next.t("services.servicesLoadError"));
+ } finally {
+ this._loading = false;
+ }
+ }
+
+ // Reload the current service iframe
+ protected _refreshIframe(): void {
+ const servicesComponent = this.shadowRoot?.querySelector("or-services") as any;
+ if (servicesComponent && typeof servicesComponent.refreshIframe === "function") {
+ servicesComponent.refreshIframe();
+ } else {
+ console.warn("Unable to reload iframe: services component not found or refreshIframe method not available");
+ }
+ }
+
+ public stateChanged(state: AppStateKeyed): void {
+ this.getRealmState(state);
+
+ // Update serviceId from URL params - this will trigger updated() which handles the selection
+ const newServiceId = state.app.params?.serviceName;
+ if (newServiceId !== this.serviceId) {
+ this.serviceId = newServiceId;
+ }
+ }
+
+ protected realmSelector = (state: AppStateKeyed) => state.app.realm || manager.config.realm;
+
+ protected getRealmState = createSelector([this.realmSelector], (realm: string) => {
+ this.realmName = realm;
+ });
+
+ protected _onServiceSelected(e: CustomEvent): void {
+ const service = e.detail as ExternalService;
+
+ if (service && service.serviceId !== this.serviceId) {
+ this.serviceId = service.serviceId;
+ this.selectedService = service;
+ this._updateRoute();
+ }
+ }
+
+ protected willUpdate(changedProperties: PropertyValues) {
+ super.willUpdate(changedProperties);
+
+ if (changedProperties.has("serviceId")) {
+ if (this.serviceId) {
+ this._updateServiceSelection();
+ }
+ }
+
+ if (changedProperties.has("realmName")) {
+ this._loadData();
+ }
+ }
+
+ protected _updateRoute() {
+ router.navigate(getServicesRoute(this.serviceId));
+ }
+
+ protected _updateServiceSelection() {
+ if (this.serviceId) {
+ const service = this.services.find((service) => service.serviceId === this.serviceId);
+ if (service) {
+ this.selectedService = service;
+ }
+ } else {
+ this.selectedService = null;
+ }
+ }
+
+ protected render(): TemplateResult {
+ return html`
+ <div style="width: 100%;">
+ <or-services
+ id="services"
+ .realmName="${this.realmName}"
+ .services="${this.services}"
+ .selectedService="${this.selectedService}"
+ .loading="${this._loading}"
+ @or-service-selected="${this._onServiceSelected}"
+ ></or-services>
+ </div>
+ `;
+ }
+}
diff --git a/ui/app/manager/src/routes.ts b/ui/app/manager/src/routes.ts
index a6e3b91f2..63d018d4e 100644
--- a/ui/app/manager/src/routes.ts
+++ b/ui/app/manager/src/routes.ts
@@ -48,3 +48,10 @@ export function getAlarmsRoute(alarmId?: string) {
}
return route;
}
+export function getServicesRoute(serviceId?: string) {
+ let route = "services";
+ if(serviceId) {
+ route += "/" + serviceId;
+ }
+ return route;
+}
diff --git a/ui/app/shared/locales/en/or.json b/ui/app/shared/locales/en/or.json
index 416073cf6..ab5f1c180 100644
--- a/ui/app/shared/locales/en/or.json
+++ b/ui/app/shared/locales/en/or.json
@@ -964,5 +964,17 @@
"source": "Source"
},
"expandAll": "Expand all",
- "collapseAll": "Collapse all"
+ "collapseAll": "Collapse all",
+ "services": {
+ "noServiceSelected": "Please select a service on the left",
+ "refresh": "Refresh",
+ "title": "Services",
+ "servicesLoadError": "Something went wrong while retrieving services",
+ "realmServicesLoadError": "Something went wrong while retrieving realm services",
+ "globalServicesLoadError": "Something went wrong while retrieving global services",
+ "noServices": "No services found, check the documentation on how to add services",
+ "iframeLoadError": "The selected service could not be loaded",
+ "serviceUnavailable": "Service is unavailable",
+ "servicesReloaded": "{{count}} service(s) retrieved"
+ }
}
diff --git a/ui/app/shared/locales/nl/or.json b/ui/app/shared/locales/nl/or.json
index 24a529303..39e26b5dc 100644
--- a/ui/app/shared/locales/nl/or.json
+++ b/ui/app/shared/locales/nl/or.json
@@ -963,5 +963,17 @@
"source": "Bron"
},
"expandAll": "Alles uitklappen",
- "collapseAll": "Alles inklappen"
+ "collapseAll": "Alles inklappen",
+ "services": {
+ "noServiceSelected": "Selecteer een service aan de linkerkant",
+ "title": "Services",
+ "refresh": "Verversen",
+ "servicesLoadError": "Er is iets misgegaan bij het ophalen van de services",
+ "realmServicesLoadError": "Er is iets misgegaan bij het ophalen van de realm services",
+ "globalServicesLoadError": "Er is iets misgegaan bij het ophalen van de globale services",
+ "noServices": "Geen services gevonden, controleer de documentatie op hoe je services kunt toevoegen",
+ "iframeLoadError": "De geselecteerde service kon niet worden geladen",
+ "serviceUnavailable": "Service is niet beschikbaar",
+ "servicesReloaded": "{{count}} service(s) opgehaald"
+ }
}
diff --git a/ui/component/or-app/package.json b/ui/component/or-app/package.json
index ed6df3d55..4c9b46867 100644
--- a/ui/component/or-app/package.json
+++ b/ui/component/or-app/package.json
@@ -33,6 +33,7 @@
"@openremote/or-map": "workspace:*",
"@openremote/or-mwc-components": "workspace:*",
"@openremote/or-rules": "workspace:*",
+ "@openremote/or-services": "workspace:*",
"@openremote/or-smart-notify": "workspace:*",
"@openremote/or-timeline": "workspace:*",
"@openremote/rest": "workspace:*",
diff --git a/ui/component/or-app/tsconfig.json b/ui/component/or-app/tsconfig.json
index b18281966..a054a3d7a 100644
--- a/ui/component/or-app/tsconfig.json
+++ b/ui/component/or-app/tsconfig.json
@@ -22,6 +22,7 @@
{ "path": "../../component/or-log-viewer" },
{ "path": "../../component/or-chart" },
{ "path": "../../component/or-rules" },
+ { "path": "../../component/or-services" },
{ "path": "../../component/or-dashboard-builder" },
{ "path": "../../component/or-gauge" }
]
diff --git a/ui/component/or-components/src/or-iframe.ts b/ui/component/or-components/src/or-iframe.ts
new file mode 100644
index 000000000..b09cc582e
--- /dev/null
+++ b/ui/component/or-components/src/or-iframe.ts
@@ -0,0 +1,250 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * 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 { css, html, LitElement, PropertyValues } from "lit";
+import { customElement, property, state } from "lit/decorators.js";
+import "./or-loading-indicator";
+import "@openremote/or-icon";
+
+export enum OrIFrameEventType {
+ LOADED = "or-iframe-loaded",
+ ERROR = "or-iframe-error",
+ TIMEOUT = "or-iframe-timeout",
+}
+
+/**
+ * Event detail for or-iframe-event
+ */
+export interface OrIFrameEventDetail {
+ type: OrIFrameEventType;
+ src?: string;
+ error?: string; // Error message if the event type is ERROR or TIMEOUT
+}
+
+/**
+ * Model for the IFRAME-EVENT that {@link OrIframe} can dispatch.
+ * Fired when the iframe loading state changes.
+ */
+export class OrIFrameEvent extends CustomEvent<OrIFrameEventDetail> {
+ public static readonly NAME = "or-iframe-event";
+
+ constructor(detail: OrIFrameEventDetail) {
+ super(OrIFrameEvent.NAME, {
+ bubbles: true,
+ composed: true,
+ detail: detail,
+ });
+ }
+}
+
+const style = css`
+ :host {
+ display: block;
+ width: 100%;
+ height: 100%;
+ }
+
+ .wrapper {
+ position: relative;
+ width: 100%;
+ height: 100%;
+ }
+
+ iframe {
+ width: 100%;
+ height: 100%;
+ border: none;
+ display: block;
+ opacity: 0;
+ transition: opacity 0.3s ease;
+ overflow-y: auto;
+ overflow-x: hidden;
+ }
+
+ iframe.loaded {
+ opacity: 1;
+ }
+
+ .error {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ height: 100%;
+ font-weight: 500;
+ gap: 0.5rem;
+ }
+`;
+
+/**
+ * @event {OrIFrameEvent} or-iframe-event - Fired when the iframe loading state changes, and dispatches the event detail containing type, src, and optional error.
+ */
+@customElement("or-iframe")
+export class OrIframe extends LitElement {
+ static get styles() {
+ return [style];
+ }
+
+ @property({ type: String })
+ public src?: string;
+
+ @property({ type: Number })
+ public timeout = 10000; // 10 seconds default timeout
+
+ @state()
+ protected loading = true;
+
+ @state()
+ protected error = false;
+
+ @property({ type: Boolean })
+ public preventCache = true;
+
+ protected timeoutId?: number;
+
+ protected _clearTimeout(): void {
+ if (this.timeoutId) {
+ window.clearTimeout(this.timeoutId);
+ this.timeoutId = undefined;
+ }
+ }
+
+ protected _startTimeout(): void {
+ this._clearTimeout();
+
+ this.timeoutId = window.setTimeout(() => {
+ console.warn(`Iframe load timeout after ${this.timeout}ms for src: ${this.src}`);
+ this._handleIframeEvent(OrIFrameEventType.TIMEOUT, new Event("timeout"));
+ }, this.timeout);
+ }
+
+ protected _resetState(): void {
+ this.loading = true;
+ this.error = false;
+ this._startTimeout();
+ }
+
+ connectedCallback(): void {
+ super.connectedCallback();
+ this._resetState();
+ }
+
+ willUpdate(changedProperties: PropertyValues): void {
+ if (changedProperties.has("src")) {
+ this._resetState();
+ }
+ }
+
+ protected readonly _handleLoadEvent = (event: Event): void => {
+ this._handleIframeEvent(OrIFrameEventType.LOADED, event);
+ };
+
+ protected readonly _handleErrorEvent = (event: Event): void => {
+ this._handleIframeEvent(OrIFrameEventType.ERROR, event);
+ };
+
+ protected readonly _handleIframeEvent = (type: OrIFrameEventType, event: Event): void => {
+ this._clearTimeout();
+
+ const detail: OrIFrameEventDetail = {
+ type,
+ src: this.src,
+ error:
+ type === OrIFrameEventType.ERROR || type === OrIFrameEventType.TIMEOUT
+ ? type === OrIFrameEventType.TIMEOUT
+ ? "Timeout loading iframe"
+ : "Error loading iframe"
+ : undefined,
+ };
+
+ this.dispatchEvent(new OrIFrameEvent(detail));
+
+ switch (type) {
+ case OrIFrameEventType.LOADED:
+ this.error = false;
+ this.loading = false;
+ break;
+ case OrIFrameEventType.ERROR:
+ this.error = true;
+ this.loading = false;
+ console.error(`Error event loading iframe for src: ${this.src}`, event);
+ break;
+ case OrIFrameEventType.TIMEOUT:
+ this.error = true;
+ this.loading = false;
+ console.error(`Timeout event loading iframe for src: ${this.src}`, event);
+ break;
+ }
+ };
+
+ disconnectedCallback(): void {
+ this._clearTimeout();
+ }
+
+ public getSrc(): string {
+ if (this.preventCache && this.src) {
+ const url = new URL(this.src);
+ url.searchParams.set("t", Date.now().toString());
+ return url.toString();
+ }
+ return this.src || "";
+ }
+
+ /**
+ * Reload the iframe content by clearing and resetting the src
+ */
+ public reload(): void {
+ if (!this.src) {
+ console.warn("Cannot reload iframe: no src specified");
+ return;
+ }
+ this._resetState();
+
+ // Force iframe reload by temporarily clearing and resetting src
+ const iframe = this.shadowRoot?.querySelector("iframe");
+ if (iframe) {
+ const currentSrc = this.getSrc();
+ iframe.src = "";
+ // We can't use iframe.contentWindow.location.reload() because it doesn't work in all cases due to browser security restrictions
+ requestAnimationFrame(() => {
+ iframe.src = currentSrc;
+ });
+ }
+ }
+
+ render() {
+ return html`
+ <div class="wrapper">
+ ${this.loading ? html`<or-loading-indicator></or-loading-indicator>` : html``}
+ ${this.error
+ ? html`<div class="error">
+ <or-icon icon="alert-octagon"></or-icon>
+ <slot name="onerror">Failed to load iframe</slot>
+ </div>`
+ : html``}
+ <iframe
+ @load=${this._handleLoadEvent}
+ @error=${this._handleErrorEvent}
+ id="or-iframe"
+ src="${this.getSrc()}"
+ class="${!this.loading ? "loaded" : ""}"
+ ></iframe>
+ </div>
+ `;
+ }
+}
diff --git a/ui/component/or-services/.npmignore b/ui/component/or-services/.npmignore
new file mode 100644
index 000000000..b2544e0f1
--- /dev/null
+++ b/ui/component/or-services/.npmignore
@@ -0,0 +1,9 @@
+build/
+build.gradle
+test/
+src/
+webpack.config.js
+rspack.config.js
+tsconfig.json
+dist/*.map
+*.tsbuildinfo
diff --git a/ui/component/or-services/README.md b/ui/component/or-services/README.md
new file mode 100644
index 000000000..50de12bd2
--- /dev/null
+++ b/ui/component/or-services/README.md
@@ -0,0 +1,31 @@
+# @openremote/or-services \<or-services\>
+[![NPM Version][npm-image]][npm-url]
+[![Linux Build][travis-image]][travis-url]
+[![Test Coverage][coveralls-image]][coveralls-url]
+
+Web component for displaying registered services from the OpenRemote Manager. The listed services are displayed in a sidebar menu and can be selected to display the service in an iframe.
+
+## Install
+```bash
+npm i @openremote/or-services
+yarn add @openremote/or-services
+```
+
+## Usage
+For a full list of properties, methods and options refer to the TypeDoc generated [documentation]().
+
+
+## Supported Browsers
+The last 2 versions of all modern browsers are supported, including Chrome, Safari, Opera, Firefox, Edge. In addition,
+Internet Explorer 11 is also supported.
+
+
+## License
+[GNU AGPL](https://www.gnu.org/licenses/agpl-3.0.en.html)
+
+[npm-image]: https://img.shields.io/npm/v/live-xxx.svg
+[npm-url]: https://npmjs.org/package/@openremote/or-timeline
+[travis-image]: https://img.shields.io/travis/live-js/live-xxx/master.svg
+[travis-url]: https://travis-ci.org/live-js/live-xxx
+[coveralls-image]: https://img.shields.io/coveralls/live-js/live-xxx/master.svg
+[coveralls-url]: https://coveralls.io/r/live-js/live-xxx?branch=master
diff --git a/ui/component/or-services/build.gradle b/ui/component/or-services/build.gradle
new file mode 100644
index 000000000..05e00b4bf
--- /dev/null
+++ b/ui/component/or-services/build.gradle
@@ -0,0 +1,20 @@
+buildDir = "dist"
+
+task clean() {
+ doLast {
+ delete "dist"
+ delete "lib"
+ }
+}
+
+task installDist() {
+ dependsOn npmAnalyze
+}
+
+task prepareUi() {
+ dependsOn clean, npmAnalyze, npmPrepare
+}
+
+task publishUi() {
+ dependsOn clean, npmPublish
+}
diff --git a/ui/component/or-services/package.json b/ui/component/or-services/package.json
new file mode 100644
index 000000000..fa996bee9
--- /dev/null
+++ b/ui/component/or-services/package.json
@@ -0,0 +1,36 @@
+{
+ "name": "@openremote/or-services",
+ "version": "1.8.0-snapshot",
+ "description": "OpenRemote services related UI components",
+ "customElements": "custom-elements.json",
+ "main": "dist/umd/index.bundle.js",
+ "module": "lib/index.js",
+ "exports": {
+ ".": "./lib/index.js",
+ "./*": "./lib/*.js"
+ },
+ "types": "lib/index.d.ts",
+ "scripts": {
+ "analyze": "npx cem analyze --config ../custom-elements-manifest.config.mjs",
+ "test": "echo \"No tests\" && exit 0",
+ "prepack": "npx rspack"
+ },
+ "author": "OpenRemote",
+ "license": "AGPL-3.0-or-later",
+ "dependencies": {
+ "@openremote/core": "workspace:*",
+ "@openremote/model": "workspace:*",
+ "@openremote/or-components": "workspace:*",
+ "@openremote/or-icon": "workspace:*",
+ "@openremote/or-mwc-components": "workspace:*",
+ "@openremote/or-translate": "workspace:*",
+ "@openremote/or-tree-menu": "workspace:*",
+ "@openremote/rest": "workspace:*"
+ },
+ "devDependencies": {
+ "@openremote/util": "workspace:*"
+ },
+ "publishConfig": {
+ "access": "public"
+ }
+}
diff --git a/ui/component/or-services/rspack.config.js b/ui/component/or-services/rspack.config.js
new file mode 100644
index 000000000..06448283a
--- /dev/null
+++ b/ui/component/or-services/rspack.config.js
@@ -0,0 +1,7 @@
+const util = require("@openremote/util");
+
+bundles = {
+ "index.bundle": undefined
+};
+
+module.exports = util.generateExports(__dirname);
diff --git a/ui/component/or-services/src/index.ts b/ui/component/or-services/src/index.ts
new file mode 100644
index 000000000..2a67e55c7
--- /dev/null
+++ b/ui/component/or-services/src/index.ts
@@ -0,0 +1,299 @@
+/* eslint-disable import/no-duplicates */
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * 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 { css, html, LitElement, TemplateResult } from "lit";
+import { customElement, property, state } from "lit/decorators.js";
+import { manager } from "@openremote/core";
+import { ExternalService } from "@openremote/model";
+import { i18next } from "@openremote/or-translate";
+import { OrIframe } from "@openremote/or-components/or-iframe";
+import "@openremote/or-components/or-iframe";
+import "@openremote/or-icon";
+import "./or-service-tree";
+import { getServiceUrlPath } from "./utils";
+import { OrServiceSelectedEvent } from "./types";
+
+const serviceStyles = css`
+ :host {
+ flex: 1;
+ width: 100%;
+ }
+
+ .wrapper {
+ display: flex;
+ flex-direction: row;
+ height: 100%;
+ }
+
+ or-iframe {
+ margin: 0 10px;
+ width: calc(100% - 20px);
+ transition: opacity 0.3s ease-in-out;
+ }
+
+ .sidebar {
+ background: #fff;
+ width: 300px;
+ min-width: 300px;
+ box-shadow: rgba(0, 0, 0, 0.21) 0px 1px 3px 0px;
+ z-index: 2;
+ display: flex;
+ flex-direction: column;
+ }
+
+ .msg {
+ display: flex;
+ justify-content: center;
+ align-items: center;
+ height: 100%;
+ width: 100%;
+ background-color: #f9f9f9;
+ transition: opacity 0.3s ease-in-out;
+ }
+
+ #fullscreen-header-wrapper {
+ min-height: 36px;
+ padding: 20px 30px 15px;
+ display: flex;
+ flex-direction: row;
+ align-items: center;
+ }
+
+ #fullscreen-header-title {
+ font-size: 18px;
+ font-weight: bold;
+ color: var(--or-app-color3, #424242);
+ display: flex;
+ align-items: center;
+ }
+
+ #fullscreen-header-title > or-icon {
+ margin-right: 10px;
+ cursor: pointer;
+ }
+
+ /* Mobile responsive styles */
+ @media only screen and (max-width: 640px) {
+ .hideMobile {
+ display: none !important;
+ }
+
+ .sidebar {
+ width: 100%;
+ min-width: 100%;
+ flex: 1;
+ }
+
+ .sidebar.hidden {
+ display: none !important;
+ }
+
+ .wrapper {
+ flex-direction: column;
+ }
+
+ or-iframe {
+ flex: 1;
+ min-height: 400px;
+ }
+
+ #fullscreen-header-wrapper {
+ padding: 11px !important;
+ }
+ }
+
+ @media only screen and (min-width: 641px) {
+ .showMobile {
+ display: none !important;
+ }
+
+ .sidebar {
+ width: 300px;
+ min-width: 300px;
+ }
+
+ .wrapper {
+ flex-direction: row;
+ }
+ }
+
+ /* Desktop layout */
+ @media only screen and (min-width: 768px) {
+ .sidebar {
+ width: 300px;
+ min-width: 300px;
+ box-shadow: rgba(0, 0, 0, 0.21) 0px 1px 3px 0px;
+ }
+
+ or-iframe {
+ flex: 1;
+ max-width: calc(100vw - 300px);
+ }
+ }
+`;
+
+@customElement("or-services")
+export class OrServices extends LitElement {
+ static get styles() {
+ return [serviceStyles];
+ }
+
+ @property({ type: String })
+ public realmName: string = manager.displayRealm;
+
+ @property({ type: Array })
+ public services: ExternalService[] = [];
+
+ @property({ type: Object })
+ public selectedService: ExternalService | null = null;
+
+ @property({ type: Boolean })
+ public loading = false;
+
+ @state()
+ protected showServiceTree = true;
+
+ connectedCallback(): void {
+ super.connectedCallback();
+ }
+
+ disconnectedCallback(): void {
+ super.disconnectedCallback();
+ }
+
+ // Method to refresh iframe - called by parent component
+ public refreshIframe(): void {
+ const iframe = this.shadowRoot?.querySelector("#service-iframe") as OrIframe;
+ if (iframe && typeof iframe.reload === "function") {
+ console.log("Reloading iframe");
+ iframe.reload();
+ } else {
+ console.warn("Unable to reload iframe: iframe not found or reload method not available");
+ }
+ }
+
+ protected _selectService(service: ExternalService): void {
+ this.selectedService = service;
+
+ // Dispatch event for parent components to handle navigation
+ const event = new OrServiceSelectedEvent(service);
+ this.dispatchEvent(event);
+
+ // On mobile, hide the tree when a service is selected
+ if (window.matchMedia("(max-width: 600px)").matches) {
+ this.showServiceTree = false;
+ }
+ }
+
+ protected _toggleServiceTree(): void {
+ this.showServiceTree = !this.showServiceTree;
+ }
+
+ protected _getSidebarClass(): string {
+ return this.selectedService ? "hideMobile" : "";
+ }
+
+ protected _onServiceSelected(e: OrServiceSelectedEvent): void {
+ const service = e.detail;
+ if (service) {
+ this._selectService(service);
+ }
+ }
+
+ protected _getServiceUrlPath(service: ExternalService): string {
+ const isSuperUser = manager.isSuperUser();
+ return getServiceUrlPath(service, this.realmName, isSuperUser);
+ }
+
+ protected _getServiceContentTemplate(): TemplateResult {
+ if (this.loading) {
+ return html``; // ignore
+ }
+
+ // If no services available, show a single consistent message
+ if (this.services.length === 0) {
+ return html`<div class="msg">
+ <or-translate value="services.noServices"></or-translate>
+ </div>`;
+ }
+
+ // If services exist but none selected, show selection prompt
+ if (!this.selectedService) {
+ return html`<div class="msg">
+ <or-translate value="services.noServiceSelected"></or-translate>
+ </div>`;
+ }
+
+ // Service selected - render iframe
+ return html`<or-iframe id="service-iframe" .src="${this._getServiceUrlPath(this.selectedService)}">
+ <span slot="onerror">${i18next.t("services.iframeLoadError")}</span>
+ </or-iframe>`;
+ }
+
+ protected render(): TemplateResult {
+
+
+ return html`
+ <div class="wrapper">
+ ${this.showServiceTree
+ ? html`
+ <div class="sidebar ${this._getSidebarClass()}">
+ <or-service-tree
+ .services="${this.services}"
+ .selectedService="${this.selectedService}"
+ @or-service-selected="${this._onServiceSelected}"
+ ></or-service-tree>
+ </div>
+ `
+ : undefined}
+ <div
+ class="${this.selectedService == null ? "hideMobile" : undefined}"
+ style="flex: 1; display: flex; flex-direction: column;"
+ >
+ ${this.selectedService
+ ? html`
+ <div id="fullscreen-header">
+ <div id="fullscreen-header-wrapper">
+ <div id="fullscreen-header-title">
+ <or-icon
+ class="showMobile"
+ icon="chevron-left"
+ @click="${() => {
+ this.selectedService = null;
+ this.showServiceTree = true;
+ }}"
+ ></or-icon>
+ <or-icon
+ class="hideMobile"
+ icon="${this.selectedService.icon ?? "puzzle"}"
+ title="${i18next.t("services.services")}"
+ ></or-icon>
+ <span>${this.selectedService.label || this.selectedService.serviceId}</span>
+ </div>
+ </div>
+ </div>
+ `
+ : undefined}
+ <div style="flex: 1;">${this._getServiceContentTemplate()}</div>
+ </div>
+ </div>
+ `;
+ }
+}
diff --git a/ui/component/or-services/src/or-service-tree.ts b/ui/component/or-services/src/or-service-tree.ts
new file mode 100644
index 000000000..c80db5409
--- /dev/null
+++ b/ui/component/or-services/src/or-service-tree.ts
@@ -0,0 +1,178 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * 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 { css, html, unsafeCSS, TemplateResult, PropertyValues } from "lit";
+import { customElement, property } from "lit/decorators.js";
+import { DefaultColor3, DefaultColor5, DefaultColor6 , Util } from "@openremote/core";
+import { OrTreeMenu, TreeMenuSelection, OrTreeNode, TreeMenuSorting } from "@openremote/or-tree-menu";
+import { ExternalService, ExternalServiceStatus } from "@openremote/model";
+import {
+ ServiceTreeNode,
+ ExternalServiceStatusIcon,
+ ExternalServiceStatusColor,
+ OrServiceSelectedEvent,
+} from "./types";
+
+
+export enum ServiceTreeSorting {
+ NAME = "name", STATUS = "status"
+}
+
+const treeStyles = css`
+ .iconfill-gray {
+ --or-icon-fill: var(--or-app-color5, ${unsafeCSS(DefaultColor5)});
+ }
+
+ .iconfill-red {
+ --or-icon-fill: var(--or-app-color6, ${unsafeCSS(DefaultColor6)});
+ }
+
+ .service-icon {
+ --or-icon-fill: var(--or-app-color3, ${unsafeCSS(DefaultColor3)});
+ }
+
+ or-tree-node {
+ padding-left: 10px;
+ }
+`;
+
+
+
+/**
+ * @event {OrServiceSelectedEvent} or-service-selected - Triggers upon selecting a service, and dispatches the selected service.
+ */
+@customElement("or-service-tree")
+export class OrServiceTree extends OrTreeMenu {
+ static get styles(): any[] {
+ return [...super.styles, treeStyles];
+ }
+
+ @property({ type: Array })
+ public services?: ExternalService[];
+
+ @property({ type: Object })
+ public selectedService?: ExternalService;
+
+ @property({ type: Boolean })
+ public readonly = false;
+
+ nodes: ServiceTreeNode[] = [];
+ selection = TreeMenuSelection.SINGLE;
+ menuTitle = "services";
+ sortBy: any = ServiceTreeSorting.NAME;
+ sortOptions: any[] = [ServiceTreeSorting.NAME, ServiceTreeSorting.STATUS];
+
+ protected willUpdate(changedProps: PropertyValues): void {
+ if (changedProps.has("services")) {
+ if (this.services) {
+ this.nodes = this._getServiceNodes(this.services);
+
+ // Select any existing selected service
+ if (this.selectedService) {
+ const nodeToSelect = this.nodes.find((node) => node.id === this.selectedService?.serviceId);
+ if (nodeToSelect) {
+ this._selectNode(nodeToSelect as unknown as OrTreeNode);
+ }
+ }
+ }
+ }
+
+ // Handle select change from parent
+ if (changedProps.has("selectedService")) {
+ if (this.selectedService) {
+ const nodeToSelect = this.nodes.find((node) => node.id === this.selectedService?.serviceId);
+ if (nodeToSelect) {
+ this._selectNode(nodeToSelect as unknown as OrTreeNode);
+ }
+ } else {
+ this.deselectAllNodes();
+ }
+ }
+
+ super.willUpdate(changedProps);
+ }
+
+ protected _dispatchSelectEvent(nodes?: ServiceTreeNode[]): boolean {
+ // Only select if ONE is selected
+ const newSelected = !nodes || nodes.length > 1 ? undefined : nodes[0];
+
+ if (newSelected?.service) {
+ // Dispatch a custom event that the page can listen to
+ const event = new OrServiceSelectedEvent(newSelected.service);
+ this.dispatchEvent(event);
+ }
+
+ return super._dispatchSelectEvent(nodes);
+ }
+
+ protected _getServiceNodes(services: ExternalService[]): ServiceTreeNode[] {
+ return services.map((service) => ({
+ id: service.serviceId || "",
+ label: service.label || "",
+ service,
+ disabled: service.status === ExternalServiceStatus.UNAVAILABLE,
+ }));
+ }
+
+ protected _getSingleNodeSlotTemplate(node: ServiceTreeNode): TemplateResult {
+ const service = node.service!;
+ const statusIcon =
+ service.status && ExternalServiceStatusIcon[service.status]
+ ? ExternalServiceStatusIcon[service.status]
+ : ExternalServiceStatusIcon.UNAVAILABLE;
+ const statusColor =
+ service.status && ExternalServiceStatusColor[service.status]
+ ? ExternalServiceStatusColor[service.status]
+ : ExternalServiceStatusColor.UNAVAILABLE;
+
+
+
+ return html`
+ <or-icon class="service-icon" slot="prefix" icon="${node.service?.icon ?? "puzzle"}"></or-icon>
+ <span>${node.label}</span>
+ <or-icon slot="suffix" icon="${statusIcon}" class="${statusColor}"> </or-icon>
+ `;
+ }
+
+ protected _getHeaderTemplate(): TemplateResult {
+ return html`
+ <div id="tree-header">
+ <h3 id="tree-header-title">
+ <or-translate value="services.title"></or-translate>
+ </h3>
+ <div id="tree-header-actions">
+ ${this._getSortActionTemplate(this.sortBy, this.sortOptions)}
+ </div>
+ </div>
+ `;
+ }
+
+ protected _getSortFunction(sortBy?: TreeMenuSorting): (a: ServiceTreeNode, b: ServiceTreeNode) => number {
+ const sorting = sortBy as unknown as ServiceTreeSorting | undefined;
+ switch (sorting) {
+ case ServiceTreeSorting.STATUS: {
+ return Util.sortByString(node => node.service?.status || "");
+ }
+ case ServiceTreeSorting.NAME:
+ default: {
+ return super._getSortFunction(sortBy);
+ }
+ }
+ }
+}
diff --git a/ui/component/or-services/src/types.ts b/ui/component/or-services/src/types.ts
new file mode 100644
index 000000000..419dfae0c
--- /dev/null
+++ b/ui/component/or-services/src/types.ts
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * 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 { TreeNode } from "@openremote/or-tree-menu";
+import { ExternalService } from "@openremote/model";
+
+export enum ExternalServiceStatusIcon {
+ AVAILABLE = "play",
+ UNAVAILABLE = "alert-octagon",
+}
+
+export enum ExternalServiceStatusColor {
+ AVAILABLE = "iconfill-gray",
+ UNAVAILABLE = "iconfill-red",
+}
+
+export interface ServiceTreeNode extends TreeNode {
+ service?: ExternalService;
+}
+
+/**
+ * Model for the SERVICE-SELECTED event that {@link OrServiceTree} can dispatch.
+ * Once a service is selected, the selected service will be shared with the consumer elements.
+ */
+export class OrServiceSelectedEvent extends CustomEvent<ExternalService> {
+ public static readonly NAME = "or-service-selected";
+
+ constructor(service: ExternalService) {
+ super(OrServiceSelectedEvent.NAME, {
+ bubbles: true,
+ composed: true,
+ detail: service,
+ });
+ }
+}
diff --git a/ui/component/or-services/src/utils.ts b/ui/component/or-services/src/utils.ts
new file mode 100644
index 000000000..c243d7017
--- /dev/null
+++ b/ui/component/or-services/src/utils.ts
@@ -0,0 +1,35 @@
+/*
+ * Copyright 2025, OpenRemote Inc.
+ *
+ * See the CONTRIBUTORS.txt file in the distribution for a
+ * full listing of individual contributors.
+ *
+ * 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 { ExternalService } from "@openremote/model";
+
+
+
+/**
+ * Get the iframe src path for a given service
+ * @param service - The service to get the iframe src path for
+ * @param realmName - The realm name
+ * @param isSuperUser - Whether the user is a super user
+ * @returns The iframe src path
+ */
+export function getServiceUrlPath(service: ExternalService, realmName: string, isSuperUser: boolean): string {
+ // Replace {realm} param if provided, uses query param if not super user
+ const homepageUrl = service.homepageUrl || "";
+ return homepageUrl.replace("{realm}", isSuperUser ? realmName : `?realm=${realmName}`);
+}
diff --git a/ui/component/or-services/tsconfig.json b/ui/component/or-services/tsconfig.json
new file mode 100644
index 000000000..43175577c
--- /dev/null
+++ b/ui/component/or-services/tsconfig.json
@@ -0,0 +1,21 @@
+{
+ "extends": "../../tsconfig",
+ "compilerOptions": {
+ "outDir": "./lib",
+ "rootDir": "src"
+ },
+ "include": [
+ "./src"
+ ],
+ "references": [
+ { "path": "../core" },
+ { "path": "../or-translate" },
+ { "path": "../or-icon" },
+ { "path": "../or-components" },
+ { "path": "../or-mwc-components" },
+ { "path": "../or-attribute-input" },
+ { "path": "../or-attribute-picker" },
+ { "path": "../or-asset-tree" },
+ { "path": "../or-tree-menu" }
+ ]
+}
diff --git a/ui/component/or-tree-menu/src/index.ts b/ui/component/or-tree-menu/src/index.ts
index 42d1c7470..06bc10097 100644
--- a/ui/component/or-tree-menu/src/index.ts
+++ b/ui/component/or-tree-menu/src/index.ts
@@ -73,7 +73,7 @@ const styles = css`
display: flex;
justify-content: space-between;
align-items: center;
- padding: 0 15px;
+ padding: 0px 5px 0px 15px;
min-height: 48px;
background: var(--or-app-color4, #4d9d2a);
color: var(--or-app-color7, white);
diff --git a/yarn.lock b/yarn.lock
index bc6795868..21548e711 100644
--- a/yarn.lock
+++ b/yarn.lock
@@ -1473,6 +1473,7 @@ __metadata:
"@openremote/or-map": "workspace:*"
"@openremote/or-mwc-components": "workspace:*"
"@openremote/or-rules": "workspace:*"
+ "@openremote/or-services": "workspace:*"
"@openremote/or-smart-notify": "workspace:*"
"@openremote/or-timeline": "workspace:*"
"@openremote/rest": "workspace:*"
@@ -1820,6 +1821,22 @@ __metadata:
languageName: unknown
linkType: soft
+"@openremote/or-services@workspace:*, @openremote/or-services@workspace:ui/component/or-services":
+ version: 0.0.0-use.local
+ resolution: "@openremote/or-services@workspace:ui/component/or-services"
+ dependencies:
+ "@openremote/core": "workspace:*"
+ "@openremote/model": "workspace:*"
+ "@openremote/or-components": "workspace:*"
+ "@openremote/or-icon": "workspace:*"
+ "@openremote/or-mwc-components": "workspace:*"
+ "@openremote/or-translate": "workspace:*"
+ "@openremote/or-tree-menu": "workspace:*"
+ "@openremote/rest": "workspace:*"
+ "@openremote/util": "workspace:*"
+ languageName: unknown
+ linkType: soft
+
"@openremote/or-smart-notify@workspace:*, @openremote/or-smart-notify@workspace:ui/component/or-smart-notify":
version: 0.0.0-use.local
resolution: "@openremote/or-smart-notify@workspace:ui/component/or-smart-notify"