Skip to content

armgit / core

Public Imported from GitHub
0

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

Unified thread creation and configuration

Christian Bauer4f4b3a4b947b
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java b/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java
index 8a43034b6..78ed5942d 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/AbstractProtocol.java
@@ -52,10 +52,12 @@ public abstract class AbstractProtocol implements Protocol {
final protected Map<AttributeRef, AssetAttribute> linkedAttributes = new HashMap<>();
protected MessageBrokerContext messageBrokerContext;
protected ProducerTemplate producerTemplate;
+ protected ProtocolExecutorService executorService;
@Override
public void init(Container container) throws Exception {
LOG.info("Initializing protocol: " + getProtocolName());
+ executorService = container.getService(ProtocolExecutorService.class);
}
@Override
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java b/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java
index 67a6cf83b..e586a13dd 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/Protocol.java
@@ -59,7 +59,7 @@ public interface Protocol extends ContainerService {
// TODO: Some of these options should be configurable depending on expected load etc.
// Message topic for communicating from asset/thing to protocol layer (asset attribute changed, trigger actuator)
- String ACTUATOR_TOPIC = "seda://ActuatorTopic?multipleConsumers=true&concurrentConsumers=10&waitForTaskToComplete=NEVER&purgeWhenStopping=true&discardIfNoConsumers=true&limitConcurrentConsumers=false&size=1000";
+ String ACTUATOR_TOPIC = "seda://ActuatorTopic?multipleConsumers=true&concurrentConsumers=1&waitForTaskToComplete=NEVER&purgeWhenStopping=true&discardIfNoConsumers=true&limitConcurrentConsumers=false&size=1000";
// Message queue for communicating from protocol to asset/thing layer (sensor changed, trigger asset attribute update)
String SENSOR_QUEUE = "seda://SensorQueue?waitForTaskToComplete=NEVER&purgeWhenStopping=true&discardIfNoConsumers=false&size=1000";
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/ProtocolExecutorService.java b/agent/src/main/java/org/openremote/agent3/protocol/ProtocolExecutorService.java
new file mode 100644
index 000000000..6cc8ba211
--- /dev/null
+++ b/agent/src/main/java/org/openremote/agent3/protocol/ProtocolExecutorService.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2017, 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.agent3.protocol;
+
+import org.openremote.container.ContainerService;
+
+import java.util.concurrent.ScheduledFuture;
+
+/**
+ * All protocol implementors should use this service to execute non-blocking background tasks.
+ * <p>
+ * TODO: If we need to run blocking tasks in protocols we can add a regular thread pool/ExecutorService here
+ */
+public interface ProtocolExecutorService extends ContainerService {
+
+ /**
+ * @see java.util.concurrent.ScheduledExecutorService#schedule
+ */
+ ScheduledFuture schedule(Runnable runnable, long delayMillis);
+
+ /**
+ * @see java.util.concurrent.ScheduledExecutorService#scheduleAtFixedRate)
+ */
+ ScheduledFuture scheduleAtFixedRate(Runnable runnable, long initialDelayMillis, long periodMillis);
+
+ /**
+ * @see java.util.concurrent.ScheduledExecutorService#scheduleWithFixedDelay
+ */
+ ScheduledFuture scheduleWithFixedDelay(Runnable runnable, long initialDelayMillis, long periodMillis);
+}
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroProtocol.java b/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroProtocol.java
index d6bb93d62..edf1bb5d3 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroProtocol.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/macro/MacroProtocol.java
@@ -21,7 +21,6 @@ package org.openremote.agent3.protocol.macro;
import elemental.json.JsonValue;
import org.openremote.agent3.protocol.AbstractProtocol;
-import org.openremote.container.Container;
import org.openremote.model.AttributeEvent;
import org.openremote.model.AttributeExecuteStatus;
import org.openremote.model.AttributeRef;
@@ -31,10 +30,7 @@ import org.openremote.model.asset.AssetAttribute;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import java.util.stream.Collectors;
@@ -122,23 +118,17 @@ public class MacroProtocol extends AbstractProtocol {
}
// Get next execution delay
- Integer delay = actions.get(iteration).getDelayMilliseconds();
+ Integer delayMillis = actions.get(iteration).getDelayMilliseconds();
// Schedule the next iteration
- scheduledFuture = executor.schedule(this::run, delay > 0 ? delay : 0, TimeUnit.MILLISECONDS);
+ scheduledFuture = executorService.schedule(this::run, delayMillis > 0 ? delayMillis: 0);
}
}
private static final Logger LOG = Logger.getLogger(MacroProtocol.class.getName());
- protected final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
protected final Map<AttributeRef, List<MacroAction>> actionMap = new HashMap<>();
protected final Map<AttributeRef, MacroExecutionTask> executions = new HashMap<>();
- @Override
- public void start(Container container) throws Exception {
- super.start(container);
- }
-
@Override
public String getProtocolName() {
return PROTOCOL_NAME;
diff --git a/agent/src/main/java/org/openremote/agent3/protocol/simulator/SimulatorProtocol.java b/agent/src/main/java/org/openremote/agent3/protocol/simulator/SimulatorProtocol.java
index 8e5d4004f..4ae9cfe71 100644
--- a/agent/src/main/java/org/openremote/agent3/protocol/simulator/SimulatorProtocol.java
+++ b/agent/src/main/java/org/openremote/agent3/protocol/simulator/SimulatorProtocol.java
@@ -31,9 +31,6 @@ import org.openremote.model.asset.AssetAttribute;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
import static org.openremote.model.Constants.PROTOCOL_NAMESPACE;
@@ -79,8 +76,6 @@ public class SimulatorProtocol extends AbstractProtocol {
protected static final Map<AttributeRef, SimulatorElement> elements = new HashMap<>();
- private static final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
-
private static final Logger LOG = Logger.getLogger(org.openremote.agent3.protocol.simulator.SimulatorProtocol.class.getName());
public static final int DEFAULT_WRITE_DELAY = 1000;
@@ -203,7 +198,7 @@ public class SimulatorProtocol extends AbstractProtocol {
if (updateSensorDelayMilliseconds <= 0) {
onSensorUpdate(state);
} else {
- executorService.schedule(() -> onSensorUpdate(state), updateSensorDelayMilliseconds, TimeUnit.MILLISECONDS);
+ executorService.schedule(() -> onSensorUpdate(state), updateSensorDelayMilliseconds);
}
}
diff --git a/container/src/main/java/org/openremote/container/Container.java b/container/src/main/java/org/openremote/container/Container.java
index 3711e7c7c..618f4b897 100644
--- a/container/src/main/java/org/openremote/container/Container.java
+++ b/container/src/main/java/org/openremote/container/Container.java
@@ -26,12 +26,10 @@ import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.openremote.container.json.ElementalJsonModule;
+import org.openremote.container.concurrent.ContainerThreads;
import org.openremote.container.util.LogUtil;
import java.util.*;
-import java.util.concurrent.CompletableFuture;
-import java.util.concurrent.CountDownLatch;
-import java.util.concurrent.ExecutionException;
import java.util.logging.Logger;
import static org.openremote.container.util.MapAccess.getBoolean;
@@ -75,7 +73,7 @@ public class Container {
protected final Map<String, String> config = new HashMap<>();
protected final boolean devMode;
- protected boolean running;
+ protected Thread waitingThread;
protected final Map<Class<? extends ContainerService>, ContainerService> services = new LinkedHashMap<>();
public Container(ContainerService... services) {
@@ -112,35 +110,36 @@ public class Container {
return devMode;
}
- public CompletableFuture start() {
- return CompletableFuture.runAsync(() -> {
- synchronized (services) {
- if (running)
- return;
- LOG.info(">>> Starting runtime container...");
- try {
- for (ContainerService service : getServices()) {
- LOG.fine("Initializing service: " + service);
- service.init(Container.this);
- }
- for (ContainerService service : getServices()) {
- LOG.fine("Starting service: " + service);
- service.start(Container.this);
- }
- } catch (RuntimeException ex) {
- throw ex;
- } catch (Exception ex) {
- throw new RuntimeException(ex);
+ public boolean isRunning() {
+ return waitingThread != null;
+ }
+
+ public void start() {
+ synchronized (services) {
+ if (isRunning())
+ return;
+ LOG.info(">>> Starting runtime container...");
+ try {
+ for (ContainerService service : getServices()) {
+ LOG.fine("Initializing service: " + service);
+ service.init(Container.this);
}
- running = true;
- LOG.info(">>> Runtime container startup complete");
+ for (ContainerService service : getServices()) {
+ LOG.fine("Starting service: " + service);
+ service.start(Container.this);
+ }
+ } catch (RuntimeException ex) {
+ throw ex;
+ } catch (Exception ex) {
+ throw new RuntimeException(ex);
}
- });
+ LOG.info(">>> Runtime container startup complete");
+ }
}
public void stop() {
synchronized (services) {
- if (!running)
+ if (!isRunning())
return;
LOG.info("<<< Stopping runtime container...");
List<ContainerService> servicesToStop = Arrays.asList(getServices());
@@ -153,7 +152,8 @@ public class Container {
} catch (Exception ex) {
throw new RuntimeException(ex);
} finally {
- running = false;
+ waitingThread.interrupt();
+ waitingThread = null;
}
LOG.info("<<< Runtime container stopped");
}
@@ -163,28 +163,8 @@ public class Container {
* Starts the container and a non-daemon thread that waits forever.
*/
public void startBackground() throws Exception {
- // We block here so we die fast if startup fails
- try {
- start().get();
- } catch (ExecutionException ex) {
- if (ex.getCause() instanceof Exception) {
- throw (Exception) ex.getCause();
- } else {
- throw ex;
- }
- }
- Thread containerThread = new Thread("container") {
- @Override
- public void run() {
- try {
- new CountDownLatch(1).await();
- } catch (InterruptedException ex) {
- // Shutdown
- }
- }
- };
- containerThread.setDaemon(false);
- containerThread.start();
+ start();
+ waitingThread = ContainerThreads.startWaitingThread();
}
public ContainerService[] getServices() {
diff --git a/container/src/main/java/org/openremote/container/concurrent/ContainerExecutor.java b/container/src/main/java/org/openremote/container/concurrent/ContainerExecutor.java
new file mode 100644
index 000000000..d500be994
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/concurrent/ContainerExecutor.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright 2017, 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.container.concurrent;
+
+import java.util.concurrent.*;
+
+import static org.openremote.container.concurrent.ContainerThreads.DEFAULT_REJECTED_EXECUTION_HANDLER;
+import static org.openremote.container.concurrent.ContainerThreads.logExceptionCause;
+
+public class ContainerExecutor extends ThreadPoolExecutor {
+
+ /**
+ * Creates an unbounded thread pool with {@link SynchronousQueue}, this is the same as
+ * {@link Executors#newCachedThreadPool}.
+ */
+ public ContainerExecutor(String name) {
+ this(name, 0, Integer.MAX_VALUE, 60L, -1);
+ }
+
+ /**
+ * @param blockingQueueCapacity Set to <code>-1</code> if a {@link SynchronousQueue} should be used.
+ */
+ public ContainerExecutor(String name,
+ int corePoolSize,
+ int maximumPoolSize,
+ long keepAliveSeconds,
+ int blockingQueueCapacity) {
+ this(
+ new ContainerThreadFactory(name),
+ DEFAULT_REJECTED_EXECUTION_HANDLER,
+ corePoolSize,
+ maximumPoolSize,
+ keepAliveSeconds,
+ blockingQueueCapacity == -1 ? new SynchronousQueue<>() : new ArrayBlockingQueue<>(blockingQueueCapacity)
+ );
+ }
+
+ public ContainerExecutor(ThreadFactory threadFactory,
+ RejectedExecutionHandler rejectedHandler,
+ int corePoolSize,
+ int maximumPoolSize,
+ long keepAliveSeconds,
+ BlockingQueue<Runnable> workQueue) {
+ super(corePoolSize, maximumPoolSize, keepAliveSeconds, TimeUnit.SECONDS, workQueue, threadFactory, rejectedHandler);
+ }
+
+ @Override
+ protected void afterExecute(Runnable runnable, Throwable throwable) {
+ super.afterExecute(runnable, throwable);
+ logExceptionCause(runnable, throwable);
+ }
+}
\ No newline at end of file
diff --git a/container/src/main/java/org/openremote/container/concurrent/ContainerScheduledExecutor.java b/container/src/main/java/org/openremote/container/concurrent/ContainerScheduledExecutor.java
new file mode 100644
index 000000000..1a7e927ea
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/concurrent/ContainerScheduledExecutor.java
@@ -0,0 +1,45 @@
+/*
+ * Copyright 2017, 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.container.concurrent;
+
+import java.util.concurrent.RejectedExecutionHandler;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
+import java.util.concurrent.ThreadFactory;
+
+import static org.openremote.container.concurrent.ContainerThreads.DEFAULT_REJECTED_EXECUTION_HANDLER;
+import static org.openremote.container.concurrent.ContainerThreads.logExceptionCause;
+
+public class ContainerScheduledExecutor extends ScheduledThreadPoolExecutor {
+
+ public ContainerScheduledExecutor(String name, int corePoolSize) {
+ this(new ContainerThreadFactory(name), DEFAULT_REJECTED_EXECUTION_HANDLER, corePoolSize);
+ }
+
+ public ContainerScheduledExecutor(ThreadFactory threadFactory, RejectedExecutionHandler rejectedHandler, int corePoolSize) {
+ super(corePoolSize, threadFactory, rejectedHandler);
+ }
+
+ @Override
+ protected void afterExecute(Runnable runnable, Throwable throwable) {
+ super.afterExecute(runnable, throwable);
+ logExceptionCause(runnable, throwable);
+ }
+
+}
\ No newline at end of file
diff --git a/container/src/main/java/org/openremote/container/concurrent/ContainerThreadFactory.java b/container/src/main/java/org/openremote/container/concurrent/ContainerThreadFactory.java
new file mode 100644
index 000000000..e8d4d8585
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/concurrent/ContainerThreadFactory.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2017, 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.container.concurrent;
+
+import java.util.concurrent.ThreadFactory;
+import java.util.concurrent.atomic.AtomicInteger;
+
+/**
+ * Creates daemon-threads with {@link Thread#NORM_PRIORITY} and a sensible
+ * name (prefix plus incrementing number) in the security manager's thread group
+ * or if there is no security manager, in the calling thread's group.
+ */
+public class ContainerThreadFactory implements ThreadFactory {
+
+ static protected final AtomicInteger threadNumber = new AtomicInteger(1);
+
+ protected final String name;
+ protected final ThreadGroup group;
+
+ public ContainerThreadFactory(String name) {
+ this.name = name;
+ SecurityManager securityManager = System.getSecurityManager();
+ group = (securityManager != null)
+ ? securityManager.getThreadGroup()
+ : Thread.currentThread().getThreadGroup();
+ }
+
+ public Thread newThread(Runnable r) {
+ Thread t = new Thread(group, r, name + "-" + threadNumber.getAndIncrement(), 0);
+ t.setDaemon(true);
+ if (t.getPriority() != Thread.NORM_PRIORITY)
+ t.setPriority(Thread.NORM_PRIORITY);
+ return t;
+ }
+}
\ No newline at end of file
diff --git a/container/src/main/java/org/openremote/container/concurrent/ContainerThreads.java b/container/src/main/java/org/openremote/container/concurrent/ContainerThreads.java
new file mode 100644
index 000000000..f84c9d9e3
--- /dev/null
+++ b/container/src/main/java/org/openremote/container/concurrent/ContainerThreads.java
@@ -0,0 +1,78 @@
+/*
+ * Copyright 2017, 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.container.concurrent;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.RejectedExecutionHandler;
+import java.util.concurrent.ThreadPoolExecutor;
+import java.util.logging.Level;
+import java.util.logging.Logger;
+
+public interface ContainerThreads {
+
+ Logger LOG = Logger.getLogger(ContainerThreads.class.getName());
+
+ RejectedExecutionHandler DEFAULT_REJECTED_EXECUTION_HANDLER = new ThreadPoolExecutor.DiscardPolicy() {
+ @Override
+ public void rejectedExecution(Runnable runnable, ThreadPoolExecutor threadPoolExecutor) {
+ // Log and discard
+ LOG.info("Container thread pool '" + threadPoolExecutor + "' rejected execution of " + runnable.getClass());
+ super.rejectedExecution(runnable, threadPoolExecutor);
+ }
+ };
+
+ static Thread startWaitingThread() {
+ Thread thread = new Thread("Container Waiting") {
+ @Override
+ public void run() {
+ try {
+ new CountDownLatch(1).await();
+ } catch (InterruptedException ex) {
+ // Ignore, thrown on shutdown
+ }
+ }
+ };
+ thread.setDaemon(false);
+ thread.start();
+ return thread;
+ }
+
+ static void logExceptionCause(Runnable runnable, Throwable throwable) {
+ if (throwable != null) {
+ Throwable cause = unwrap(throwable);
+ if (cause instanceof InterruptedException) {
+ // Ignore this, might happen when we shutdownNow() the executor. We can't
+ // log at this point as the logging system might be stopped already.
+ return;
+ }
+ LOG.log(Level.WARNING, "Thread terminated unexpectedly executing: " +runnable.getClass(), throwable);
+ }
+ }
+
+ static Throwable unwrap(Throwable throwable) throws IllegalArgumentException {
+ if (throwable == null) {
+ throw new IllegalArgumentException("Cannot unwrap null throwable");
+ }
+ for (Throwable current = throwable; current != null; current = current.getCause()) {
+ throwable = current;
+ }
+ return throwable;
+ }
+}
diff --git a/container/src/main/java/org/openremote/container/message/MessageBrokerSetupService.java b/container/src/main/java/org/openremote/container/message/MessageBrokerSetupService.java
index 55db6f22a..003ab8ca4 100644
--- a/container/src/main/java/org/openremote/container/message/MessageBrokerSetupService.java
+++ b/container/src/main/java/org/openremote/container/message/MessageBrokerSetupService.java
@@ -22,15 +22,22 @@ package org.openremote.container.message;
import org.apache.camel.Processor;
import org.apache.camel.builder.LoggingErrorHandlerBuilder;
import org.apache.camel.impl.DefaultStreamCachingStrategy;
-import org.apache.camel.spi.RouteContext;
-import org.apache.camel.spi.StreamCachingStrategy;
+import org.apache.camel.spi.*;
+import org.apache.camel.util.ObjectHelper;
+import org.apache.camel.util.concurrent.CamelThreadFactory;
import org.openremote.container.Container;
import org.openremote.container.ContainerService;
import org.openremote.container.security.IdentityService;
+import org.openremote.container.concurrent.ContainerExecutor;
+import org.openremote.container.concurrent.ContainerScheduledExecutor;
import org.openremote.container.web.DefaultWebsocketComponent;
import org.openremote.container.web.WebService;
import org.openremote.container.web.socket.WebsocketComponent;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ThreadFactory;
+
import static org.openremote.container.util.MapAccess.getString;
public class MessageBrokerSetupService implements ContainerService {
@@ -46,6 +53,48 @@ public class MessageBrokerSetupService implements ContainerService {
public void init(Container container) throws Exception {
context = new MessageBrokerContext();
+ // We use our own thread factories for creating thread pools - the only method called
+ // is really newThreadPool() for all of the seda:// topics and queues
+ final ExecutorServiceManager executorServiceManager = context.getExecutorServiceManager();
+ executorServiceManager.setThreadNamePattern("#counter# #name#");
+ executorServiceManager.setThreadPoolFactory(new ThreadPoolFactory() {
+ @Override
+ public ExecutorService newCachedThreadPool(ThreadFactory threadFactory) {
+ // This should only be called by the MulticastProcessor aggregation, which we don't use currently!
+ return new ContainerExecutor(getExecutorName("MessagingMcast", threadFactory), 1, 1, 0, -1);
+ }
+
+ @Override
+ public ExecutorService newThreadPool(ThreadPoolProfile profile, ThreadFactory threadFactory) {
+ return new ContainerExecutor(
+ getExecutorName("Messaging", threadFactory),
+ profile.getPoolSize(),
+ profile.getMaxPoolSize(),
+ profile.getKeepAliveTime(),
+ profile.getMaxQueueSize()
+ );
+ }
+
+ @Override
+ public ScheduledExecutorService newScheduledThreadPool(ThreadPoolProfile profile, ThreadFactory threadFactory) {
+ return new ContainerScheduledExecutor(
+ getExecutorName("MessagingTasks", threadFactory),
+ profile.getPoolSize()
+ );
+ }
+
+ protected String getExecutorName(String name, ThreadFactory threadFactory) {
+ if (threadFactory instanceof CamelThreadFactory) {
+ CamelThreadFactory factory = (CamelThreadFactory) threadFactory;
+ String camelName = factory.getName();
+ camelName = camelName.contains("://") ? ObjectHelper.after(camelName, "://") : camelName;
+ camelName = camelName.contains("?") ? ObjectHelper.before(camelName, "?") : camelName;
+ name = name + "-" + camelName;
+ }
+ return name;
+ }
+ });
+
// TODO make configurable in environment
context.disableJMX();
diff --git a/container/src/main/java/org/openremote/container/persistence/Database.java b/container/src/main/java/org/openremote/container/persistence/Database.java
index db427c654..9326b31d3 100644
--- a/container/src/main/java/org/openremote/container/persistence/Database.java
+++ b/container/src/main/java/org/openremote/container/persistence/Database.java
@@ -23,6 +23,7 @@ import com.zaxxer.hikari.HikariConfig;
import com.zaxxer.hikari.HikariDataSource;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.spatial.dialect.postgis.PostgisDialect;
+import org.openremote.container.concurrent.ContainerThreadFactory;
import java.util.HashMap;
import java.util.Map;
@@ -57,6 +58,7 @@ public interface Database {
@Override
public void open(Map<String, Object> properties, String connectionUrl, String username, String password, int connectionTimeoutSeconds, int minIdle, int maxPoolSize) {
hikariConfig = new HikariConfig();
+ hikariConfig.setThreadFactory(new ContainerThreadFactory("Database Connections"));
hikariConfig.setDataSourceClassName("org.postgresql.ds.PGSimpleDataSource");
hikariConfig.addDataSourceProperty("url", connectionUrl);
hikariConfig.setUsername(username);
diff --git a/container/src/main/java/org/openremote/container/persistence/PersistenceEvent.java b/container/src/main/java/org/openremote/container/persistence/PersistenceEvent.java
index ba22f447c..adfc5ebf0 100644
--- a/container/src/main/java/org/openremote/container/persistence/PersistenceEvent.java
+++ b/container/src/main/java/org/openremote/container/persistence/PersistenceEvent.java
@@ -23,7 +23,7 @@ public class PersistenceEvent<T> {
// TODO: Make configurable
public static final String PERSISTENCE_TOPIC =
- "seda://PersistenceTopic?multipleConsumers=true&discardIfNoConsumers=true";
+ "seda://PersistenceTopic?multipleConsumers=true&concurrentConsumers=1&waitForTaskToComplete=NEVER&purgeWhenStopping=true&discardIfNoConsumers=true&limitConcurrentConsumers=false&size=1000";
public static final String HEADER_ENTITY_TYPE = PersistenceEvent.class.getSimpleName() + ".ENTITY_TYPE";
diff --git a/container/src/main/java/org/openremote/container/util/LogFormatter.java b/container/src/main/java/org/openremote/container/util/LogFormatter.java
index 4916f15f5..c747851f5 100644
--- a/container/src/main/java/org/openremote/container/util/LogFormatter.java
+++ b/container/src/main/java/org/openremote/container/util/LogFormatter.java
@@ -19,6 +19,8 @@
*/
package org.openremote.container.util;
+import org.openremote.model.util.TextUtil;
+
import java.io.PrintWriter;
import java.io.StringWriter;
import java.time.Instant;
@@ -33,14 +35,16 @@ public class LogFormatter extends Formatter {
public String format(LogRecord record) {
OffsetDateTime date = fromMillis(record.getMillis());
- StringBuilder sb = new StringBuilder(180);
+ StringBuilder sb = new StringBuilder(250);
- sb.append(pad(date.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME), 29));
+ sb.append(TextUtil.pad(date.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME), 29));
sb.append(" ");
- sb.append(pad(record.getLevel().toString(), 7));
+ sb.append(TextUtil.pad(record.getLevel().toString(), 7));
sb.append(" ");
- sb.append("[").append(pad(truncate(Thread.currentThread().getName(), 20, true), 20)).append("] ");
- sb.append(pad(truncate(record.getLoggerName(), 40, true), 40));
+ sb.append("[").append(
+ TextUtil.pad(Thread.currentThread().getName().replaceFirst("(.{24}).+(.{4})", "$1..$2"), 30)
+ ).append("] ");
+ sb.append(TextUtil.pad(TextUtil.truncate(record.getLoggerName(), 40, true), 40));
sb.append(" : ");
sb.append(formatMessage(record));
@@ -60,19 +64,5 @@ public class LogFormatter extends Formatter {
return OffsetDateTime.ofInstant(Instant.ofEpochMilli(epochMillis), ZoneId.systemDefault());
}
- protected String pad(String s, int size) {
- while (s.length() < size) {
- s = s + " ";
- }
- return s;
- }
- protected String truncate(String s, int maxLength, boolean alignRight) {
- if (s.length() <= maxLength)
- return s;
-
- return alignRight
- ? s.substring(s.length() - maxLength, s.length())
- : s.substring(s.length() - maxLength);
- }
}
diff --git a/container/src/main/java/org/openremote/container/web/DefaultWebsocketComponent.java b/container/src/main/java/org/openremote/container/web/DefaultWebsocketComponent.java
index 83efe2fd8..7b18fd0c0 100644
--- a/container/src/main/java/org/openremote/container/web/DefaultWebsocketComponent.java
+++ b/container/src/main/java/org/openremote/container/web/DefaultWebsocketComponent.java
@@ -19,12 +19,12 @@
*/
package org.openremote.container.web;
-import io.undertow.connector.ByteBufferPool;
import io.undertow.server.DefaultByteBufferPool;
import io.undertow.server.HttpHandler;
import io.undertow.servlet.api.*;
import io.undertow.servlet.util.ImmediateInstanceHandle;
import io.undertow.websockets.jsr.DefaultContainerConfigurator;
+import io.undertow.websockets.jsr.UndertowContainerProvider;
import io.undertow.websockets.jsr.WebSocketDeploymentInfo;
import org.openremote.container.message.MessageBrokerSetupService;
import org.openremote.container.security.IdentityService;
@@ -32,20 +32,22 @@ import org.openremote.container.web.socket.*;
import org.xnio.OptionMap;
import org.xnio.Options;
import org.xnio.Xnio;
-import org.xnio.XnioWorker;
import javax.servlet.DispatcherType;
import javax.servlet.Filter;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;
-import java.security.Principal;
import java.util.logging.Logger;
public class DefaultWebsocketComponent extends WebsocketComponent {
private static final Logger LOG = Logger.getLogger(DefaultWebsocketComponent.class.getName());
+ static {
+ UndertowContainerProvider.disableDefaultContainer();
+ }
+
final protected IdentityService identityService;
final protected WebService webService;
final protected String allowedOrigin;
@@ -92,12 +94,22 @@ public class DefaultWebsocketComponent extends WebsocketComponent {
);
});
- // TODO https://issues.jboss.org/browse/UNDERTOW-682 remove this code block in 1.3.21.final
+ // We use the I/O thread to handle received websocket frames, as we expect to quickly hand them over to
+ // an internal asynchronous message queue for processing, so we don't need a separate worker thread
+ // pool for websocket frame processing
+ webSocketDeploymentInfo.setDispatchToWorkerThread(false);
+
+ // Make the shit Undertow/Websocket JSR client bootstrap happy - this is the pool that would be used
+ // when Undertow acts as a WebSocket client, which we don't do... and I'm not even sure it can do that...
+ webSocketDeploymentInfo.setWorker(Xnio.getInstance().createWorker(
+ OptionMap.builder()
+ .set(Options.WORKER_TASK_MAX_THREADS, 1)
+ .set(Options.WORKER_NAME, "WebsocketInternalClient")
+ .set(Options.THREAD_DAEMON, true)
+ .getMap()
+ ));
boolean directBuffers = Boolean.getBoolean("io.undertow.websockets.direct-buffers");
- XnioWorker worker = Xnio.getInstance().createWorker(OptionMap.create(Options.THREAD_DAEMON, true));
- ByteBufferPool buffers = new DefaultByteBufferPool(directBuffers, 1024, 100, 12);
- webSocketDeploymentInfo.setWorker(worker);
- webSocketDeploymentInfo.setBuffers(buffers);
+ webSocketDeploymentInfo.setBuffers(new DefaultByteBufferPool(directBuffers, 1024, 100, 12));
deploymentInfo = new DeploymentInfo()
.setDeploymentName("WebSocket Deployment")
diff --git a/container/src/main/java/org/openremote/container/web/WebService.java b/container/src/main/java/org/openremote/container/web/WebService.java
index 539674725..b0ed71788 100644
--- a/container/src/main/java/org/openremote/container/web/WebService.java
+++ b/container/src/main/java/org/openremote/container/web/WebService.java
@@ -42,6 +42,7 @@ import org.openremote.container.security.CORSFilter;
import org.openremote.container.security.IdentityService;
import org.openremote.container.security.SimpleKeycloakServletExtension;
import org.openremote.container.web.jsapi.JSAPIServlet;
+import org.xnio.Options;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.UriBuilder;
@@ -66,6 +67,10 @@ public abstract class WebService implements ContainerService {
public static final int WEBSERVER_LISTEN_PORT_DEFAULT = 8080;
public static final String WEBSERVER_DUMP_REQUESTS = "WEBSERVER_DUMP_REQUESTS";
public static final boolean WEBSERVER_DUMP_REQUESTS_DEFAULT = false;
+ public static final String WEBSERVER_IO_THREADS_MAX = "WEBSERVER_IO_THREADS_MAX";
+ public static final int WEBSERVER_IO_THREADS_MAX_DEFAULT = Math.max(Runtime.getRuntime().availableProcessors(), 2);
+ public static final String WEBSERVER_WORKER_THREADS_MAX = "WEBSERVER_WORKER_THREADS_MAX";
+ public static final int WEBSERVER_WORKER_THREADS_MAX_DEFAULT = Math.max(Runtime.getRuntime().availableProcessors(), 10);
// Authenticating requests requires a realm, either we receive this in a header or
// we extract it (e.g. from request path segment) and set it as a header before
@@ -106,10 +111,15 @@ public abstract class WebService implements ContainerService {
.host(containerHost)
.port(port).build();
+
undertow = build(
container,
Undertow.builder()
.addHttpListener(port, host)
+ .setIoThreads(getInteger(container.getConfig(), WEBSERVER_IO_THREADS_MAX, WEBSERVER_IO_THREADS_MAX_DEFAULT))
+ .setWorkerThreads(getInteger(container.getConfig(), WEBSERVER_WORKER_THREADS_MAX, WEBSERVER_WORKER_THREADS_MAX_DEFAULT))
+ .setWorkerOption(Options.WORKER_NAME, "WebService")
+ .setWorkerOption(Options.THREAD_DAEMON, true)
).build();
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/Main.java b/manager/server/src/main/java/org/openremote/manager/server/Main.java
index 3ec53e3fd..0436b58c3 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/Main.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/Main.java
@@ -38,6 +38,7 @@ import org.openremote.manager.server.rules.RulesService;
import org.openremote.manager.server.rules.RulesetStorageService;
import org.openremote.manager.server.security.ManagerIdentityService;
import org.openremote.manager.server.setup.SetupService;
+import org.openremote.manager.server.concurrent.ManagerExecutorService;
import org.openremote.manager.server.web.ManagerWebService;
import java.util.ArrayList;
@@ -51,6 +52,7 @@ public class Main {
List<ContainerService> services = new ArrayList<ContainerService>() {
{
addAll(Arrays.asList(
+ new ManagerExecutorService(),
new I18NService(),
new PersistenceService(),
new MessageBrokerSetupService(),
diff --git a/manager/server/src/main/java/org/openremote/manager/server/concurrent/ManagerExecutorService.java b/manager/server/src/main/java/org/openremote/manager/server/concurrent/ManagerExecutorService.java
new file mode 100644
index 000000000..ab5e1f4d3
--- /dev/null
+++ b/manager/server/src/main/java/org/openremote/manager/server/concurrent/ManagerExecutorService.java
@@ -0,0 +1,98 @@
+/*
+ * Copyright 2017, 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.server.concurrent;
+
+import org.openremote.agent3.protocol.ProtocolExecutorService;
+import org.openremote.container.Container;
+import org.openremote.container.concurrent.ContainerExecutor;
+import org.openremote.container.concurrent.ContainerScheduledExecutor;
+
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+
+import static org.openremote.container.util.MapAccess.getInteger;
+
+public class ManagerExecutorService implements ProtocolExecutorService {
+
+ /**
+ * Threads used by rules engines, each rule engine runs in a separate thread and blocks it.
+ * The pool size limits the number of rules engines that can exist.
+ */
+ public static final String RULES_THREADS_MAX = "RULES_THREADS_MAX";
+ public static final int RULES_THREADS_MAX_DEFAULT = Integer.MAX_VALUE;
+
+ /**
+ * Threads used by scheduled, usually short-lived and non-blocking tasks, such as protocols
+ * polling a remote service at regular interval, or the internal checks for expired client
+ * subscriptions on the event bus.
+ */
+ public static final String SCHEDULED_TASKS_THREADS_MAX = "SCHEDULED_TASKS_THREADS_MAX";
+ public static final int SCHEDULED_TASKS_THREADS_MAX_DEFAULT = Math.max(Runtime.getRuntime().availableProcessors(), 2);
+
+ protected ExecutorService rulesExecutor;
+ protected ScheduledExecutorService scheduledTasksExecutor;
+
+ @Override
+ public void init(Container container) throws Exception {
+ int rulesThreadsMax =
+ getInteger(container.getConfig(), RULES_THREADS_MAX, RULES_THREADS_MAX_DEFAULT);
+ rulesExecutor = new ContainerExecutor("Rules engine", 0, rulesThreadsMax, 60, -1);
+
+ int scheduledTasksThreadsMax =
+ getInteger(container.getConfig(), SCHEDULED_TASKS_THREADS_MAX, SCHEDULED_TASKS_THREADS_MAX_DEFAULT);
+ scheduledTasksExecutor = new ContainerScheduledExecutor("Scheduled task", scheduledTasksThreadsMax);
+ }
+
+ @Override
+ public void start(Container container) throws Exception {
+ }
+
+ @Override
+ public void stop(Container container) throws Exception {
+ rulesExecutor.shutdownNow();
+ scheduledTasksExecutor.shutdown();
+ }
+
+ public ExecutorService getRulesExecutor() {
+ return rulesExecutor;
+ }
+
+ @Override
+ public ScheduledFuture schedule(Runnable runnable, long delayMillis) {
+ return scheduledTasksExecutor.schedule(runnable, delayMillis, TimeUnit.MILLISECONDS);
+ }
+
+ @Override
+ public ScheduledFuture scheduleAtFixedRate(Runnable runnable, long initialDelayMillis, long periodMillis) {
+ return scheduledTasksExecutor.scheduleAtFixedRate(runnable, initialDelayMillis, periodMillis, TimeUnit.MILLISECONDS);
+ }
+
+ @Override
+ public ScheduledFuture scheduleWithFixedDelay(Runnable runnable, long initialDelayMillis, long periodMillis) {
+ return scheduledTasksExecutor.scheduleWithFixedDelay(runnable, initialDelayMillis, periodMillis, TimeUnit.MILLISECONDS);
+ }
+
+ @Override
+ public String toString() {
+ return getClass().getSimpleName() + "{}";
+ }
+}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/event/EventService.java b/manager/server/src/main/java/org/openremote/manager/server/event/EventService.java
index 3806ba03c..4ce44c7d9 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/event/EventService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/event/EventService.java
@@ -27,6 +27,7 @@ import org.openremote.container.message.MessageBrokerService;
import org.openremote.container.message.MessageBrokerSetupService;
import org.openremote.container.web.socket.WebsocketAuth;
import org.openremote.container.web.socket.WebsocketConstants;
+import org.openremote.manager.server.concurrent.ManagerExecutorService;
import org.openremote.model.event.shared.CancelEventSubscription;
import org.openremote.model.event.shared.EventSubscription;
import org.openremote.model.event.shared.SharedEvent;
@@ -92,19 +93,20 @@ public class EventService implements ContainerService {
public static final String WEBSOCKET_EVENTS = "events";
// TODO: Some of these options should be configurable depending on expected load etc.
- public static final String INCOMING_EVENT_TOPIC = "seda://IncomingEventTopic?multipleConsumers=true&concurrentConsumers=10&waitForTaskToComplete=NEVER&purgeWhenStopping=true&discardIfNoConsumers=true&limitConcurrentConsumers=false&size=1000";
+ public static final String INCOMING_EVENT_TOPIC = "seda://IncomingEventTopic?multipleConsumers=true&concurrentConsumers=1&waitForTaskToComplete=NEVER&purgeWhenStopping=true&discardIfNoConsumers=true&limitConcurrentConsumers=false&size=1000";
public static final String OUTGOING_EVENT_QUEUE = "seda://OutgoingEventQueue?multipleConsumers=false&waitForTaskToComplete=NEVER&purgeWhenStopping=true&discardIfNoConsumers=true&size=1000";
- final protected EventSubscriptions eventSubscriptions = new EventSubscriptions();
final protected Collection<EventSubscriptionAuthorizer> eventSubscriptionAuthorizers = new CopyOnWriteArraySet<>();
-
protected MessageBrokerService messageBrokerService;
+ protected EventSubscriptions eventSubscriptions;
@Override
public void init(Container container) throws Exception {
messageBrokerService = container.getService(MessageBrokerService.class);
+ eventSubscriptions = new EventSubscriptions(container.getService(ManagerExecutorService.class));
+
MessageBrokerSetupService messageBrokerSetupService = container.getService(MessageBrokerSetupService.class);
messageBrokerSetupService.getContext().getTypeConverterRegistry().addTypeConverters(
new EventTypeConverters()
@@ -176,7 +178,6 @@ public class EventService implements ContainerService {
@Override
public void start(Container container) {
-
}
@Override
diff --git a/manager/server/src/main/java/org/openremote/manager/server/event/EventSubscriptions.java b/manager/server/src/main/java/org/openremote/manager/server/event/EventSubscriptions.java
index 023a1bf36..64d8c32db 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/event/EventSubscriptions.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/event/EventSubscriptions.java
@@ -23,14 +23,12 @@ import org.apache.camel.Exchange;
import org.apache.camel.Message;
import org.apache.camel.impl.DefaultMessage;
import org.openremote.container.web.socket.WebsocketConstants;
+import org.openremote.manager.server.concurrent.ManagerExecutorService;
import org.openremote.model.event.shared.CancelEventSubscription;
import org.openremote.model.event.shared.EventSubscription;
import org.openremote.model.event.shared.SharedEvent;
import java.util.*;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
/**
@@ -42,15 +40,6 @@ public class EventSubscriptions {
final protected Map<String, SessionSubscriptions> sessionSubscriptions = new HashMap<>();
- final protected ScheduledExecutorService reaperScheduler = Executors.newScheduledThreadPool(
- 1,
- r -> {
- Thread t = Executors.defaultThreadFactory().newThread(r);
- t.setDaemon(true);
- return t;
- }
- );
-
class SessionSubscriptions extends HashSet<SessionSubscription> {
public void removeExpired() {
removeIf(sessionSubscription -> {
@@ -91,14 +80,15 @@ public class EventSubscriptions {
}
}
- public EventSubscriptions() {
- reaperScheduler.scheduleAtFixedRate(() -> {
+ public EventSubscriptions(ManagerExecutorService executorService) {
+ LOG.info("Starting background task checking for expired event subscriptions from clients");
+ executorService.scheduleAtFixedRate(() -> {
synchronized (this.sessionSubscriptions) {
for (SessionSubscriptions subscriptions : sessionSubscriptions.values()) {
subscriptions.removeExpired();
}
}
- }, 0, 1, TimeUnit.SECONDS);
+ }, 5000, 1000);
}
public void update(String sessionKey, EventSubscription subscription) {
diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.java
index 20301c9b3..e78674153 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesDeployment.java
@@ -50,6 +50,7 @@ import org.openremote.manager.server.asset.AssetProcessingService;
import org.openremote.manager.server.asset.AssetStorageService;
import org.openremote.manager.server.asset.ServerAsset;
import org.openremote.manager.server.notification.NotificationService;
+import org.openremote.manager.server.concurrent.ManagerExecutorService;
import org.openremote.manager.shared.rules.AssetRuleset;
import org.openremote.manager.shared.rules.GlobalRuleset;
import org.openremote.manager.shared.rules.Ruleset;
@@ -64,10 +65,7 @@ import org.openremote.model.rules.Assets;
import org.openremote.model.rules.Users;
import java.util.*;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.logging.Level;
import java.util.logging.Logger;
@@ -76,7 +74,8 @@ public class RulesDeployment<T extends Ruleset> {
public static final Logger LOG = Logger.getLogger(RulesDeployment.class.getName());
- protected final NotificationService notificationService;
+ final protected ManagerExecutorService executorService;
+ final protected NotificationService notificationService;
final protected AssetStorageService assetStorageService;
final protected AssetProcessingService assetProcessingService;
final protected Class<T> rulesetType;
@@ -100,11 +99,14 @@ public class RulesDeployment<T extends Ruleset> {
protected boolean running;
protected long currentFactCount;
final protected Map<AssetState, FactHandle> assetStates = new HashMap<>();
- protected static final ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
protected ScheduledFuture startTimer;
- public RulesDeployment(AssetStorageService assetStorageService, NotificationService notificationService, AssetProcessingService assetProcessingService,
+ public RulesDeployment(ManagerExecutorService executorService,
+ AssetStorageService assetStorageService,
+ NotificationService notificationService,
+ AssetProcessingService assetProcessingService,
Class<T> rulesetType, String id) {
+ this.executorService = executorService;
this.assetStorageService = assetStorageService;
this.notificationService = notificationService; // shouldBeUser service or Identity Service ?
this.assetProcessingService = assetProcessingService;
@@ -250,7 +252,7 @@ public class RulesDeployment<T extends Ruleset> {
}
});
} else {
- startTimer = executorService.schedule(this::start, AUTO_START_DELAY_SECONDS, TimeUnit.SECONDS);
+ startTimer = executorService.schedule(this::start, AUTO_START_DELAY_SECONDS * 1000);
}
// Add new ruleset
@@ -303,7 +305,7 @@ public class RulesDeployment<T extends Ruleset> {
if (!isError() && !isEmpty()) {
// Queue engine start
- startTimer = executorService.schedule(this::start, AUTO_START_DELAY_SECONDS, TimeUnit.SECONDS);
+ startTimer = executorService.schedule(this::start, AUTO_START_DELAY_SECONDS * 1000);
}
}
diff --git a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java
index 72454e8c5..bbac19f74 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/rules/RulesService.java
@@ -32,6 +32,7 @@ import org.openremote.manager.server.asset.AssetStorageService;
import org.openremote.manager.server.asset.ServerAsset;
import org.openremote.manager.server.notification.NotificationService;
import org.openremote.manager.server.security.ManagerIdentityService;
+import org.openremote.manager.server.concurrent.ManagerExecutorService;
import org.openremote.manager.shared.rules.AssetRuleset;
import org.openremote.manager.shared.rules.GlobalRuleset;
import org.openremote.manager.shared.rules.Ruleset;
@@ -74,6 +75,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
public static final String RULE_EVENT_EXPIRES = "RULE_EVENT_EXPIRES";
public static final String RULE_EVENT_EXPIRES_DEFAULT = "1h";
+ protected ManagerExecutorService executorService;
protected PersistenceService persistenceService;
protected RulesetStorageService rulesetStorageService;
protected ManagerIdentityService identityService;
@@ -94,6 +96,7 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
@Override
public void init(Container container) throws Exception {
+ executorService = container.getService(ManagerExecutorService.class);
persistenceService = container.getService(PersistenceService.class);
rulesetStorageService = container.getService(RulesetStorageService.class);
identityService = container.getService(ManagerIdentityService.class);
@@ -408,7 +411,14 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
// Global rules have access to everything in the system
if (globalDeployment == null) {
- globalDeployment = new RulesDeployment<>(assetStorageService, notificationService, assetProcessingService, GlobalRuleset.class, "GLOBAL");
+ globalDeployment = new RulesDeployment<>(
+ executorService,
+ assetStorageService,
+ notificationService,
+ assetProcessingService,
+ GlobalRuleset.class,
+ "GLOBAL"
+ );
}
globalDeployment.addRuleset(ruleset);
@@ -434,7 +444,14 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
RulesDeployment<TenantRuleset> deployment = tenantDeployments
.computeIfAbsent(ruleset.getRealmId(), (realmId) -> {
created[0] = true;
- return new RulesDeployment<>(assetStorageService, notificationService, assetProcessingService, TenantRuleset.class, realmId);
+ return new RulesDeployment<>(
+ executorService,
+ assetStorageService,
+ notificationService,
+ assetProcessingService,
+ TenantRuleset.class,
+ realmId
+ );
});
deployment.addRuleset(ruleset);
@@ -490,7 +507,14 @@ public class RulesService extends RouteBuilder implements ContainerService, Cons
RulesDeployment<AssetRuleset> deployment = assetDeployments
.computeIfAbsent(ruleset.getAssetId(), (assetId) -> {
created[0] = true;
- return new RulesDeployment<>(assetStorageService, notificationService, assetProcessingService, AssetRuleset.class, assetId);
+ return new RulesDeployment<>(
+ executorService,
+ assetStorageService,
+ notificationService,
+ assetProcessingService,
+ AssetRuleset.class,
+ assetId
+ );
});
deployment.addRuleset(ruleset);
diff --git a/manager/server/src/main/java/org/openremote/manager/server/setup/SchemaExporter.java b/manager/server/src/main/java/org/openremote/manager/server/setup/SchemaExporter.java
index 0fb9c6994..594f9c247 100644
--- a/manager/server/src/main/java/org/openremote/manager/server/setup/SchemaExporter.java
+++ b/manager/server/src/main/java/org/openremote/manager/server/setup/SchemaExporter.java
@@ -75,6 +75,6 @@ public class SchemaExporter {
}
);
- container.start().get();
+ container.start();
}
}
diff --git a/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy b/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy
index aba588e43..f467587cf 100644
--- a/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy
+++ b/manager/test/src/main/groovy/org/openremote/test/ManagerContainerTrait.groovy
@@ -23,6 +23,7 @@ import org.openremote.manager.server.rules.RulesService
import org.openremote.manager.server.rules.RulesetStorageService
import org.openremote.manager.server.security.ManagerIdentityService
import org.openremote.manager.server.setup.SetupService
+import org.openremote.manager.server.concurrent.ManagerExecutorService
import org.openremote.manager.server.web.ManagerWebService
import static org.openremote.manager.server.setup.builtin.BuiltinSetupTasks.SETUP_IMPORT_DEMO_RULES
@@ -31,6 +32,7 @@ trait ManagerContainerTrait extends ContainerTrait {
static Iterable<ContainerService> defaultServices(Iterable<ContainerService> additionalServices) {
[
+ new ManagerExecutorService(),
new I18NService(),
new PersistenceService(),
new MessageBrokerSetupService(),
diff --git a/model/src/main/java/org/openremote/model/util/TextUtil.java b/model/src/main/java/org/openremote/model/util/TextUtil.java
index 8daf219c3..146d583d5 100644
--- a/model/src/main/java/org/openremote/model/util/TextUtil.java
+++ b/model/src/main/java/org/openremote/model/util/TextUtil.java
@@ -67,7 +67,7 @@ public class TextUtil {
sb.append(s).append(",");
}
if (sb.length() > 0) {
- sb.deleteCharAt(sb.length()-1);
+ sb.deleteCharAt(sb.length() - 1);
}
return sb.toString();
}
@@ -153,4 +153,19 @@ public class TextUtil {
return text.substring(0, end) + "...";
}
+ public static String pad(String s, int size) {
+ while (s.length() < size) {
+ s = s + " ";
+ }
+ return s;
+ }
+
+ public static String truncate(String s, int maxLength, boolean alignRight) {
+ if (s.length() <= maxLength)
+ return s;
+
+ return alignRight
+ ? s.substring(s.length() - maxLength, s.length())
+ : s.substring(0, maxLength);
+ }
}