From c2528cfbf0caef5c4decf2c3d8fdbbcb2b9d8e9d Mon Sep 17 00:00:00 2001 From: Percy Baker Date: Mon, 23 Nov 2026 14:00:56 +0000 Subject: [PATCH 1/7] Alarm client status tracking --- .../org/phoebus/pv/alarm/AlarmContext.java | 6 +- .../applications/alarm/AlarmSystem.java | 5 +- .../phoebus/applications/alarm/Messages.java | 15 +- .../alarm/client/AlarmClient.java | 210 ++++++++++++---- .../alarm/client/AlarmClientListener.java | 7 +- .../alarm/client/AlarmClientState.java | 102 ++++++++ .../alarm/client/AlarmConfigMonitor.java | 2 +- .../resources/alarm_preferences.properties | 19 +- .../applications/alarm/messages.properties | 8 + .../alarm/AlarmClientModelDemo.java | 5 +- .../applications/alarm/ui/AlarmUI.java | 33 ++- .../alarm/ui/area/AlarmAreaView.java | 9 +- .../alarm/ui/table/AlarmTableMediator.java | 5 +- .../alarm/ui/table/AlarmTableUI.java | 27 +- .../alarm/ui/tree/AlarmTreeConfigView.java | 203 ++++----------- .../alarm/ui/tree/AlarmTreeView.java | 235 ++++++------------ 16 files changed, 464 insertions(+), 427 deletions(-) create mode 100644 app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClientState.java diff --git a/app/alarm/datasource/src/main/java/org/phoebus/pv/alarm/AlarmContext.java b/app/alarm/datasource/src/main/java/org/phoebus/pv/alarm/AlarmContext.java index da0bcdf41c..b772025c48 100644 --- a/app/alarm/datasource/src/main/java/org/phoebus/pv/alarm/AlarmContext.java +++ b/app/alarm/datasource/src/main/java/org/phoebus/pv/alarm/AlarmContext.java @@ -5,6 +5,7 @@ import org.phoebus.applications.alarm.client.AlarmClientLeaf; import org.phoebus.applications.alarm.client.AlarmClientListener; import org.phoebus.applications.alarm.client.AlarmClientNode; +import org.phoebus.applications.alarm.client.AlarmClientState; import org.phoebus.applications.alarm.model.AlarmTreeItem; import org.phoebus.framework.jobs.JobManager; @@ -200,10 +201,9 @@ private AlarmClientDatasourceListener(String config) { } @Override - public void serverStateChanged(boolean alive) + public void alarmClientStateChanged(AlarmClientState oldState, AlarmClientState state) { - if(!alive) - { + if (state.isServerDisconnectedState()) { // Disconnect AlarmPVs associated with this config only pvs.values().stream() .filter(alarmPV -> { diff --git a/app/alarm/model/src/main/java/org/phoebus/applications/alarm/AlarmSystem.java b/app/alarm/model/src/main/java/org/phoebus/applications/alarm/AlarmSystem.java index 63b0126b17..e22d9b8c60 100644 --- a/app/alarm/model/src/main/java/org/phoebus/applications/alarm/AlarmSystem.java +++ b/app/alarm/model/src/main/java/org/phoebus/applications/alarm/AlarmSystem.java @@ -69,9 +69,6 @@ public class AlarmSystem extends AlarmSystemConstants /** Limit for the number of context menu items */ @Preference public static int alarm_menu_max_items; - /** Initial Alarm Tree UI update delay [ms] */ - @Preference public static int alarm_tree_startup_ms; - /** Alarm table columns */ @Preference public static String[] alarm_table_columns; @@ -126,6 +123,8 @@ public class AlarmSystem extends AlarmSystemConstants @Preference public static int max_block_ms; + @Preference public static int kafka_connection_timeout_seconds; + /** Macros used in UI display/command/web links */ public static MacroValueProvider macros; diff --git a/app/alarm/model/src/main/java/org/phoebus/applications/alarm/Messages.java b/app/alarm/model/src/main/java/org/phoebus/applications/alarm/Messages.java index 6fbdc83ab8..4f49a22380 100644 --- a/app/alarm/model/src/main/java/org/phoebus/applications/alarm/Messages.java +++ b/app/alarm/model/src/main/java/org/phoebus/applications/alarm/Messages.java @@ -5,10 +5,17 @@ /** Externalized strings */ public class Messages { - /** Externalized strings */ - public static String Disabled, - Disconnected, - NoPV; + public static String Disabled; + public static String Disconnected; + public static String NoPV; + public static String connecting; + public static String noInitialKafkaConnection; + public static String loading; + public static String noKafkaConnection; + public static String connected; + public static String noAlarmserverConnection; + public static String clientError; + public static String clientShutDown; static { diff --git a/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClient.java b/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClient.java index 34f5969cd6..117cef4a73 100644 --- a/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClient.java +++ b/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClient.java @@ -12,6 +12,8 @@ import org.apache.kafka.clients.consumer.ConsumerRecords; import org.apache.kafka.clients.producer.Producer; import org.apache.kafka.clients.producer.ProducerRecord; +import org.apache.kafka.common.Metric; +import org.apache.kafka.common.TopicPartition; import org.apache.kafka.common.record.TimestampType; import org.phoebus.applications.alarm.AlarmSystem; import org.phoebus.applications.alarm.model.AlarmTreeItem; @@ -24,7 +26,10 @@ import java.time.Duration; import java.time.Instant; import java.util.List; +import java.util.Map; import java.util.Objects; +import java.util.Optional; +import java.util.OptionalLong; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; @@ -69,6 +74,11 @@ public class AlarmClient { */ private static final int KAFKA_CLIENT_TIMEOUT = 10; + /** + * Time spent in checkUpdates() waiting for, well, updates + */ + private static final Duration POLL_PERIOD = Duration.ofMillis(100); + /** * Alarm tree Paths that have been deleted. * @@ -110,15 +120,20 @@ public class AlarmClient { private final Thread thread; /** - * Time of last state update (ms), - * used to determine timeout + * Time of last state update (ms), used to determine when the alarm + * server has timed out */ private long last_state_update = 0; /** - * Timeout, not seen any messages from server? + * Current state of the alarm client + */ + private volatile AlarmClientState state = AlarmClientState.LOADING; + + /** + * The time (unix milliseconds) at which {@link run} was called */ - private volatile boolean has_timed_out = false; + private long startupTime; /** * @param server Kafka Server host:port @@ -224,49 +239,118 @@ public void setNotify(final boolean disable_notify) throws Exception { final ProducerRecord record = new ProducerRecord<>(command_topic, AlarmSystem.COMMAND_PREFIX + root.getPathName(), json); producer.send(record); } catch (final Exception ex) { - logger.log(Level.WARNING, "Cannot set mode for " + root + " to " + cmd, ex); + logger.log(Level.WARNING, "Cannot set notify for " + root + " to " + cmd, ex); throw ex; } } /** - * Background thread loop that checks for alarm tree updates + * Main loop which polls and processes updates from Kafka */ private void run() { - // Send an initial "no server" notification, - // to be cleared once we receive data from server. - checkServerState(); + startupTime = System.currentTimeMillis(); + setState(AlarmClientState.CONNECTING); // Ensure listeners are notified of initial CONNECTING state try { while (running.get()) { - checkUpdates(); - checkServerState(); + final ConsumerRecords records = consumer.poll(POLL_PERIOD); + for (final ConsumerRecord record : records) { + handleUpdate(record); + } + checkState(); } } catch (final Throwable ex) { - if (running.get()) + if (running.get()) { + setState(AlarmClientState.CLIENT_ERROR); logger.log(Level.SEVERE, "Alarm client model error", ex); - // else: Intended shutdown + } else { + setState(AlarmClientState.CLIENT_SHUT_DOWN); + logger.log(Level.INFO, "Alarm client has shut down"); + } } finally { consumer.close(); producer.close(); } } - /** - * Time spent in checkUpdates() waiting for, well, updates - */ - private static final Duration POLL_PERIOD = Duration.ofMillis(100); - - /** - * Perform one check for updates - */ - private void checkUpdates() { - // Check for messages, with timeout. - // TODO Because of Kafka bug, this will hang if Kafka isn't running. - // Fixed according to https://issues.apache.org/jira/browse/KAFKA-1894 , - // but update to kafka-client 1.1.1 (latest in July 2018) makes no difference. - final ConsumerRecords records = consumer.poll(POLL_PERIOD); - for (final ConsumerRecord record : records) - handleUpdate(record); + private void checkState() { + switch (state) { + case CONNECTING -> { + if (System.currentTimeMillis() - startupTime > AlarmSystem.kafka_connection_timeout_seconds * 1000.0) { + // We use the heartbeat metric to determine whether the Kafka consumer + // is still connected. Unfortunately, until the consumer has connected + // (and for a short time after), this metric always returns -1, + // so we have to use our own logic to determine when the initial + // connection attempt has timed out. + setState(AlarmClientState.NO_INITIAL_KAFKA_CONNECTION); + } else if (!consumer.assignment().isEmpty()) { + // Once the consumer has been assigned partitions, we can be sure it has + // managed to establish contact with the controller and transition to the + // loading state. (Ideally we would use the heartbeat but again this returns + // -1 for a short time after connection has been established, so it's not a + // great metric) + setState(AlarmClientState.LOADING); + } + } + case NO_INITIAL_KAFKA_CONNECTION -> { + // Note: It might take a few moments for the first heartbeat after a new connection, + // so we may end up processing messages while still in NO_INIIAL_KAFKA_CONNECTION + final long secondsSinceLastHeartbeat = getSecondSinceLastConsumerHeartbeat(); + if (secondsSinceLastHeartbeat != -1 && secondsSinceLastHeartbeat <= AlarmSystem.kafka_connection_timeout_seconds) { + setState(AlarmClientState.LOADING); + } + } + case NO_KAFKA_CONNECTION -> { + // Note: It might take a few moments for the first heartbeat after a new + // connection, so we may end up processing messages while still in NO_KAFKA_CONNECTION + final long secondsSinceLastHeartbeat = getSecondSinceLastConsumerHeartbeat(); + if (secondsSinceLastHeartbeat != -1 && secondsSinceLastHeartbeat <= AlarmSystem.kafka_connection_timeout_seconds) { + setState(AlarmClientState.CONNECTED); + } + } + case LOADING -> { + if (getSecondSinceLastConsumerHeartbeat() > AlarmSystem.kafka_connection_timeout_seconds) { + setState(AlarmClientState.NO_INITIAL_KAFKA_CONNECTION); + } else { + // Lag is just how many messages still need to be polled for us to catch up + // We check across all partitions because of course we need to be caught + // up on all partitions. + // + // If no partition has been assigned yet, this means the consumer is still + // waiting for an assignment and will not return any records yet, so we need + // to wait until the consumer has been assigned partitions. + boolean caughtUp = !consumer.assignment().isEmpty(); + for (final TopicPartition partition : consumer.assignment()) { + final OptionalLong lag = consumer.currentLag(partition); + // From Kafka docs - currentLag can be empty if the lag is not known for + // whatever reason - if this happens we likely just need to wait until it + // is known + if (lag.isEmpty() || lag.getAsLong() != 0) { + caughtUp = false; + } + } + if (caughtUp) { + setState(AlarmClientState.CONNECTED); + } + } + } + case CONNECTED -> { + final long now = System.currentTimeMillis(); + if (getSecondSinceLastConsumerHeartbeat() > AlarmSystem.kafka_connection_timeout_seconds) { + setState(AlarmClientState.NO_KAFKA_CONNECTION); + } else if (now - last_state_update > AlarmSystem.idle_timeout_ms * 3) { + setState(AlarmClientState.NO_ALARMSERVER_CONNECTION); + } + } + case NO_ALARMSERVER_CONNECTION -> { + final long now = System.currentTimeMillis(); + if (getSecondSinceLastConsumerHeartbeat() > AlarmSystem.kafka_connection_timeout_seconds) { + setState(AlarmClientState.NO_KAFKA_CONNECTION); + } else if (now - last_state_update <= AlarmSystem.idle_timeout_ms * 3) { + setState(AlarmClientState.CONNECTED); + } + } + case CLIENT_ERROR, CLIENT_SHUT_DOWN -> throw new IllegalStateException("Alarm client is attempting to process updates after it has shut down"); + } } /** @@ -569,31 +653,6 @@ public void acknowledge(final AlarmTreeItem item, final boolean acknowledge) } } - /** - * @return true if connected to server, else updates have timed out - */ - public boolean isServerAlive() { - return !has_timed_out; - } - - /** - * Check if there have been any messages from server - */ - private void checkServerState() { - final long now = System.currentTimeMillis(); - if (now - last_state_update > AlarmSystem.idle_timeout_ms * 3) { - if (!has_timed_out) { - has_timed_out = true; - for (final AlarmClientListener listener : listeners) - listener.serverStateChanged(false); - } - } else if (has_timed_out) { - has_timed_out = false; - for (final AlarmClientListener listener : listeners) - listener.serverStateChanged(true); - } - } - /** * Stop client */ @@ -608,4 +667,47 @@ public void shutdown() { logger.log(Level.INFO, () -> thread.getName() + " shut down"); } + + public AlarmClientState getState() { + return state; + } + + /** + * Updates the current state and notifies all listeners + */ + private void setState(final AlarmClientState newState) { + if (state != newState) { + final AlarmClientState oldState = state; + state = newState; + for (final AlarmClientListener listener : listeners) { + listener.alarmClientStateChanged(oldState, newState); + } + } + } + + /** + * Queries the Kafka consumer to get how many seconds ago the last heartbeat was + * + * See https://chrzaszcz.dev/2019/06/kafka-heartbeat-thread/ and https://docs.confluent.io/platform/current/kafka/consumer-metrics.html#join-total + */ + private long getSecondSinceLastConsumerHeartbeat() { + final Optional secondsSinceLastConsumerHeartbeat = consumer.metrics() + .entrySet() + .stream() + .filter(e -> e.getKey().name().equals("last-heartbeat-seconds-ago")) + .map(Map.Entry::getValue) + .findFirst() + .map(Metric::metricValue); + if (secondsSinceLastConsumerHeartbeat.isPresent() && secondsSinceLastConsumerHeartbeat.get() instanceof final Double value) { + return Math.round(value); + } + // I don't think this should ever not be present, but in the event it is we prefer to + // progress the state rather than leave the client believing there is no Kafka connection. + // Even though there may not actually be a connection, in the event it isn't and + // something else has caused this to return empty, the alarm tree requires us to reach + // the LOADING state for the alarm tree to display its contents. So it's safer to fail + // like this rather than risk breaking the alarm tree completely. + logger.log(Level.WARNING, "Kafka consumer did not have metric last-heartbeat-seconds-ago; ignoring Kafka connectivity check"); + return 0; + } } diff --git a/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClientListener.java b/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClientListener.java index 3b3546e4bc..ae60ee844f 100644 --- a/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClientListener.java +++ b/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClientListener.java @@ -14,8 +14,11 @@ */ public interface AlarmClientListener { - /** @param alive Is server alive, or has it timed out? */ - void serverStateChanged(boolean alive); + /** + * @param oldState State of the alarm client before it was updated + * @param state New (current) state of the alarm client + */ + void alarmClientStateChanged(AlarmClientState oldState, AlarmClientState state); /** @param maintenance_mode Is the server in 'maintenance' mode? Else 'normal' */ void serverModeChanged(boolean maintenance_mode); diff --git a/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClientState.java b/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClientState.java new file mode 100644 index 0000000000..1b07933774 --- /dev/null +++ b/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClientState.java @@ -0,0 +1,102 @@ +package org.phoebus.applications.alarm.client; + +import org.phoebus.applications.alarm.Messages; + +import java.util.Set; + + +public enum AlarmClientState { + + /** + * Start state. There is no way to reach this from other states. + * + * CONNECTING -> NO_INITIAL_KAFKA_CONNECTION + * CONNECTING -> LOADING + */ + CONNECTING, + + /** + * Indicates we were either unable to initially reach Kafka at all, or we were + * disconnected from Kafka while loading the initial flurry of Kafka messages. + * + * This exists alongside NO_KAFKA_CONNECTION so we know to go back to LOADING + * rather than CONNECTED. + * + * NO_INITIAL_KAFKA_CONNECTION -> LOADING + */ + NO_INITIAL_KAFKA_CONNECTION, + + /** + * Indicates we're still loading the initial flurry of Kafka messages + * + * LOADING -> NO_INITIAL_KAFKA_CONNECTION + * LOADING -> CONNECTED + */ + LOADING, + + /** + * Indicates we have been disconnected from Kafka at some point after we + * connected initially and loaded the initial flurry of Kafka messages + * + * NO_KAFKA_CONNECTION -> CONNECTED + */ + NO_KAFKA_CONNECTION, + + /** + * CONNECTED -> NO_KAFKA_CONNECTION + * CONNECTED -> NO_ALARMSERVER_CONNECTION + */ + CONNECTED, + + /** + * NO_ALARMSERVER_CONNECTION -> NO_KAFKA_CONNECTION + * NO_ALARMSERVER_CONNECTION -> CONNECTED + */ + NO_ALARMSERVER_CONNECTION, + + /** + * Indicates an error has occurred while processing messages + * + * When this state is reached, the client will have stopped + * processing messages - it is a final state + */ + CLIENT_ERROR, + + /** + * Indicates the client has shut down + * + * When this state is reached, the client will have stopped + * processing messages - it is a final state + */ + CLIENT_SHUT_DOWN; + + private static final Set INITIAL_STATES = Set.of(CONNECTING, NO_INITIAL_KAFKA_CONNECTION, LOADING); + private static final Set SERVER_DISCONNECTED_STATES = Set.of(NO_INITIAL_KAFKA_CONNECTION, NO_KAFKA_CONNECTION, NO_ALARMSERVER_CONNECTION); + + /** + * @return true if this state occurs prior to the config being loaded + */ + public boolean isInitialState() { + return INITIAL_STATES.contains(this); + } + + /** + * @return true if this state indicates Kafka or the alarm server are not connected + */ + public boolean isServerDisconnectedState() { + return SERVER_DISCONNECTED_STATES.contains(this); + } + + public String getDisplayName() { + return switch (this) { + case CONNECTING -> Messages.connecting; + case NO_INITIAL_KAFKA_CONNECTION -> Messages.noInitialKafkaConnection; + case LOADING -> Messages.loading; + case NO_KAFKA_CONNECTION -> Messages.noKafkaConnection; + case CONNECTED -> Messages.connected; + case NO_ALARMSERVER_CONNECTION -> Messages.noAlarmserverConnection; + case CLIENT_ERROR -> Messages.clientError; + case CLIENT_SHUT_DOWN -> Messages.clientShutDown; + }; + } +} diff --git a/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmConfigMonitor.java b/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmConfigMonitor.java index 45bcadc231..9a81f6fbf3 100644 --- a/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmConfigMonitor.java +++ b/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmConfigMonitor.java @@ -46,7 +46,7 @@ public class AlarmConfigMonitor private final AlarmClientListener config_listener = new AlarmClientListener() { @Override - public void serverStateChanged(final boolean alive) + public void alarmClientStateChanged(final AlarmClientState oldState, final AlarmClientState state) { //NOP } diff --git a/app/alarm/model/src/main/resources/alarm_preferences.properties b/app/alarm/model/src/main/resources/alarm_preferences.properties index e724d9c00e..a7e4d2ca70 100644 --- a/app/alarm/model/src/main/resources/alarm_preferences.properties +++ b/app/alarm/model/src/main/resources/alarm_preferences.properties @@ -58,20 +58,6 @@ alarm_table_font_size=12 # 'display' and 'command' menu entries. alarm_menu_max_items=10 -# Initial Alarm Tree UI update delay, in milliseconds. -# -# The initial flurry of alarm tree updates can be slow -# to render. By allowing the alarm client to accumulate -# alarm tree information for a little time and then -# performing an initial bulk representation, the overall -# alarm tree startup can be faster, especially when -# the UI is viewed via a remote desktop. -# -# Set to `0` for original implementation where -# all alarm tree items are added to the model -# as they are received in initial flurry of updates. -alarm_tree_startup_ms=2000 - # Order of columns in alarm table. # # Allows re-ordering as well as omitting columns @@ -187,3 +173,8 @@ macros=TOP=/home/controls/displays,WEBROOT=http://localhost/controls/displays # Max time in milliseconds a producer call will block. max_block_ms=10000 + +# The maximum time from the last successful communication with Kafka +# before it is considered to have disconnected. The client will +# continually try to re-establish contact regardless of this setting. +kafka_connection_timeout_seconds=10 \ No newline at end of file diff --git a/app/alarm/model/src/main/resources/org/phoebus/applications/alarm/messages.properties b/app/alarm/model/src/main/resources/org/phoebus/applications/alarm/messages.properties index 6e8ebe5480..dd31096a7f 100644 --- a/app/alarm/model/src/main/resources/org/phoebus/applications/alarm/messages.properties +++ b/app/alarm/model/src/main/resources/org/phoebus/applications/alarm/messages.properties @@ -1,3 +1,11 @@ Disabled=Disabled Disconnected=Disconnected NoPV=No PV +connecting=Connecting... +noInitialKafkaConnection=No Kafka connection +loading=Loading... +noKafkaConnection=No Kafka connection +connected=Connected +noAlarmserverConnection=No Alarmserver connection +clientError=Client error (check error log) +clientShutDown=Client shut down \ No newline at end of file diff --git a/app/alarm/model/src/test/java/org/phoebus/applications/alarm/AlarmClientModelDemo.java b/app/alarm/model/src/test/java/org/phoebus/applications/alarm/AlarmClientModelDemo.java index 4730faccec..deb533b242 100644 --- a/app/alarm/model/src/test/java/org/phoebus/applications/alarm/AlarmClientModelDemo.java +++ b/app/alarm/model/src/test/java/org/phoebus/applications/alarm/AlarmClientModelDemo.java @@ -10,6 +10,7 @@ import org.junit.jupiter.api.Test; import org.phoebus.applications.alarm.client.AlarmClient; import org.phoebus.applications.alarm.client.AlarmClientListener; +import org.phoebus.applications.alarm.client.AlarmClientState; import org.phoebus.applications.alarm.model.AlarmTreeItem; import org.phoebus.applications.alarm.model.print.ModelPrinter; @@ -35,9 +36,9 @@ public void testClientModel() throws Exception client.addListener(new AlarmClientListener() { @Override - public void serverStateChanged(final boolean alive) + public void alarmClientStateChanged(final AlarmClientState oldState, final AlarmClientState state) { - System.out.println("Server alive: " + alive); + System.out.println("Server state: " + state); } @Override diff --git a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/AlarmUI.java b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/AlarmUI.java index e62af387bd..18d4e13ed9 100644 --- a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/AlarmUI.java +++ b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/AlarmUI.java @@ -10,6 +10,7 @@ import java.util.Arrays; import org.phoebus.applications.alarm.client.AlarmClient; +import org.phoebus.applications.alarm.client.AlarmClientState; import org.phoebus.applications.alarm.model.SeverityLevel; import org.phoebus.security.authorization.AuthorizationService; import org.phoebus.ui.Preferences; @@ -250,12 +251,32 @@ public static boolean mayDisableNotify(final AlarmClient model) return haveQualifiedAuthorization(model, "alarm_notify"); } - /** @return Label that indicates missing server connection */ - public static Label createNoServerLabel() + public static Background getAlarmClientStateBackground(final AlarmClientState state) { + final Color color = switch (state) { + case CONNECTING -> Color.DARKCYAN; + case LOADING -> Color.DARKBLUE; + case NO_INITIAL_KAFKA_CONNECTION -> Color.DARKRED; + case NO_KAFKA_CONNECTION -> Color.DARKRED; + case CONNECTED -> Color.GREEN; + case NO_ALARMSERVER_CONNECTION -> Color.DARKRED; + case CLIENT_ERROR -> Color.DARKGOLDENROD; + case CLIENT_SHUT_DOWN -> Color.DARKVIOLET; + }; + return new Background(new BackgroundFill(color, CornerRadii.EMPTY, Insets.EMPTY)); + } + + /** @return Label that that indicates the server status, initially showing {@link AlarmClientState.CONNECTING} */ + public static Label createAlarmClientStateLabel() + { + return createAlarmClientStateLabel(AlarmClientState.CONNECTING); + } + + /** @return Label that that indicates the given server state */ + public static Label createAlarmClientStateLabel(final AlarmClientState state) { - final Label no_server = new Label("No Alarm Server Connection"); - no_server.setTextFill(Color.WHITE); - no_server.setBackground(new Background(new BackgroundFill(Color.RED, CornerRadii.EMPTY, Insets.EMPTY))); - return no_server; + final Label noServer = new Label(state.getDisplayName()); + noServer.setTextFill(Color.WHITE); + noServer.setBackground(getAlarmClientStateBackground(state)); + return noServer; } } diff --git a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/area/AlarmAreaView.java b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/area/AlarmAreaView.java index 809ad3d2e1..917e929503 100644 --- a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/area/AlarmAreaView.java +++ b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/area/AlarmAreaView.java @@ -30,6 +30,7 @@ import org.phoebus.applications.alarm.AlarmSystem; import org.phoebus.applications.alarm.client.AlarmClient; import org.phoebus.applications.alarm.client.AlarmClientListener; +import org.phoebus.applications.alarm.client.AlarmClientState; import org.phoebus.applications.alarm.model.AlarmTreeItem; import org.phoebus.applications.alarm.model.SeverityLevel; import org.phoebus.applications.alarm.ui.AlarmUI; @@ -112,14 +113,14 @@ public AlarmAreaView(final AlarmClient model) // AlarmClientModelListener @Override - public void serverStateChanged(final boolean alive) + public void alarmClientStateChanged(final AlarmClientState oldState, final AlarmClientState state) { Platform.runLater(() -> { - if (alive) - getChildren().setAll(grid); + if (state.isServerDisconnectedState()) + getChildren().setAll(AlarmUI.createAlarmClientStateLabel(state)); else - getChildren().setAll(AlarmUI.createNoServerLabel()); + getChildren().setAll(grid); }); } diff --git a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/table/AlarmTableMediator.java b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/table/AlarmTableMediator.java index 0970bee71e..f91b81d09b 100644 --- a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/table/AlarmTableMediator.java +++ b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/table/AlarmTableMediator.java @@ -14,6 +14,7 @@ import org.phoebus.applications.alarm.client.AlarmClient; import org.phoebus.applications.alarm.client.AlarmClientLeaf; import org.phoebus.applications.alarm.client.AlarmClientListener; +import org.phoebus.applications.alarm.client.AlarmClientState; import org.phoebus.applications.alarm.model.AlarmTreeItem; import org.phoebus.ui.javafx.UpdateThrottle; @@ -43,9 +44,9 @@ public AlarmTableMediator(final AlarmClient client, final AlarmTableUI ui) // AlarmClientModelListener @Override - public void serverStateChanged(final boolean alive) + public void alarmClientStateChanged(final AlarmClientState oldState, final AlarmClientState state) { - Platform.runLater(() -> ui.setServerState(alive)); + Platform.runLater(() -> ui.setAlarmClientState(state)); } // AlarmClientModelListener diff --git a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/table/AlarmTableUI.java b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/table/AlarmTableUI.java index 98ae4461bc..54787c8971 100644 --- a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/table/AlarmTableUI.java +++ b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/table/AlarmTableUI.java @@ -18,24 +18,22 @@ import javafx.application.Platform; import javafx.scene.control.TableColumnBase; import javafx.scene.image.Image; -import javafx.scene.layout.Background; import javafx.scene.layout.BorderPane; import javafx.scene.layout.Priority; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import org.phoebus.applications.alarm.AlarmSystem; import org.phoebus.applications.alarm.client.AlarmClient; +import org.phoebus.applications.alarm.client.AlarmClientState; import org.phoebus.applications.alarm.model.AlarmTreeItem; import org.phoebus.applications.alarm.model.SeverityLevel; import org.phoebus.applications.alarm.ui.AlarmContextMenuHelper; import org.phoebus.applications.alarm.ui.AlarmUI; import org.phoebus.applications.alarm.ui.tree.ConfigureComponentAction; -import org.phoebus.framework.jobs.Job; import org.phoebus.framework.jobs.JobManager; import org.phoebus.framework.persistence.Memento; import org.phoebus.framework.selection.Selection; import org.phoebus.framework.selection.SelectionService; -import org.phoebus.ui.application.ContextMenuHelper; import org.phoebus.ui.application.ContextMenuService; import org.phoebus.ui.application.SaveSnapshotAction; import org.phoebus.ui.application.TableHelper; @@ -59,7 +57,6 @@ import javafx.collections.transformation.SortedList; import javafx.geometry.Insets; import javafx.geometry.Orientation; -import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; @@ -80,7 +77,7 @@ import javafx.scene.input.Dragboard; import javafx.scene.input.TransferMode; import javafx.scene.paint.Color; -import javafx.scene.paint.Paint; + /** Alarm Table UI * @@ -122,7 +119,7 @@ public class AlarmTableUI extends BorderPane final TextField search = new ClearingTextField(); - private final Label no_server = AlarmUI.createNoServerLabel(); + private final Label alarm_client_state_label = AlarmUI.createAlarmClientStateLabel(); private final Button server_mode = new Button(); @@ -370,22 +367,16 @@ private ToolBar createToolbar() search.textProperty().addListener(prop -> selectRows()); if (AlarmSystem.disable_notify_visible) - return new ToolBar(active_count,ToolbarHelper.createStrut(), ToolbarHelper.createSpring(), server_mode, server_notify, acknowledge, unacknowledge, search); + return new ToolBar(active_count,ToolbarHelper.createStrut(), alarm_client_state_label, ToolbarHelper.createSpring(), server_mode, server_notify, acknowledge, unacknowledge, search); - return new ToolBar(active_count,ToolbarHelper.createStrut(), ToolbarHelper.createSpring(), server_mode, acknowledge, unacknowledge, search); + return new ToolBar(active_count, ToolbarHelper.createStrut(), alarm_client_state_label, ToolbarHelper.createSpring(), server_mode, acknowledge, unacknowledge, search); } - /** Show if connected to server or not - * @param alive Is server alive? - */ - void setServerState(final boolean alive) + /** Show state of alarm client */ + void setAlarmClientState(final AlarmClientState state) { - final ObservableList items = toolbar.getItems(); - items.remove(no_server); - if (! alive) - // Place to the left of spring, maint, ack, unack, filter, - // i.e. right of "active alarms" and optional AlarmConfigSelector - items.add(items.size() - 5, no_server); + alarm_client_state_label.setBackground(AlarmUI.getAlarmClientStateBackground(state)); + alarm_client_state_label.setText(state.getDisplayName()); } void setMaintenanceMode(final boolean maintenance_mode) diff --git a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/AlarmTreeConfigView.java b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/AlarmTreeConfigView.java index 5d985e4ebb..44b44674a0 100644 --- a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/AlarmTreeConfigView.java +++ b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/AlarmTreeConfigView.java @@ -11,9 +11,6 @@ import javafx.beans.value.ChangeListener; import javafx.collections.FXCollections; import javafx.collections.ObservableList; -import javafx.geometry.Insets; -import javafx.scene.Cursor; -import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.SelectionMode; @@ -21,15 +18,12 @@ import javafx.scene.control.Tooltip; import javafx.scene.control.TreeItem; import javafx.scene.control.TreeView; -import javafx.scene.layout.Background; -import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.BorderPane; -import javafx.scene.layout.CornerRadii; -import javafx.scene.paint.Color; import org.phoebus.applications.alarm.AlarmSystem; import org.phoebus.applications.alarm.client.AlarmClient; import org.phoebus.applications.alarm.client.AlarmClientLeaf; import org.phoebus.applications.alarm.client.AlarmClientListener; +import org.phoebus.applications.alarm.client.AlarmClientState; import org.phoebus.applications.alarm.model.AlarmTreeItem; import org.phoebus.applications.alarm.model.BasicState; import org.phoebus.applications.alarm.ui.AlarmUI; @@ -45,9 +39,7 @@ import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; import static org.phoebus.applications.alarm.AlarmSystem.logger; @@ -63,32 +55,14 @@ @SuppressWarnings("nls") public class AlarmTreeConfigView extends BorderPane implements AlarmClientListener { - private final Label no_server = AlarmUI.createNoServerLabel(); + private final Label alarm_client_state_label = AlarmUI.createAlarmClientStateLabel(); + private final TreeView> tree_config_view = new TreeView<>(); /** Model with current alarm tree, sends updates */ private final AlarmClient model; private final String itemName; - /** Latch for initially pausing model listeners - * - * Imagine a large alarm tree that changes. - * The alarm table can periodically display the current - * alarms, it does not need to display every change right away. - * The tree on the other hand must reflect every added or removed item, - * because updates cannot be applied once the tree structure gets out of sync. - * When the model is first started, there is a flurry of additions and removals, - * which arrive in the order in which the tree was generated, not necessarily - * in the order they're laid out in the hierarchy. - * These can be slow to render, especially if displaying via a remote desktop (ssh-X). - * The alarm tree view thus starts in stages: - * 1) Wait for model to receive the bulk of initial additions and removals - * 2) Add listeners to model changes, but block them via this latch - * 3) Represent the initial model - * 4) Release this latch to handle changes (blocked and those that arrive from now on) - */ - private final CountDownLatch block_item_changes = new CountDownLatch(1); - /** Map from alarm tree path to view's TreeItem */ private final ConcurrentHashMap>> path2view = new ConcurrentHashMap<>(); @@ -101,23 +75,6 @@ public class AlarmTreeConfigView extends BorderPane implements AlarmClientListen /** Throttle [5Hz] used for updates of existing items */ private final UpdateThrottle throttle = new UpdateThrottle(200, TimeUnit.MILLISECONDS, this::performUpdates); - /** Cursor change doesn't work on Mac, so add indicator to toolbar */ - private final Label changing = new Label("Loading..."); - - /** Is change indicator shown, and future been submitted to clear it? */ - private final AtomicReference> ongoing_change = new AtomicReference<>(); - - /** Clear the change indicator */ - private final Runnable clear_change_indicator = () -> - Platform.runLater(() -> - { - logger.log(Level.INFO, "Alarm tree changes end"); - ongoing_change.set(null); - setCursor(null); - final ObservableList items = getToolbar().getItems(); - items.remove(changing); - }); - // Javadoc for TreeItem shows example for overriding isLeaf() and getChildren() // to dynamically create TreeItem as TreeView requests information. // @@ -141,9 +98,6 @@ public AlarmTreeConfigView(final AlarmClient model) { */ public AlarmTreeConfigView(final AlarmClient model, String itemName) { - changing.setTextFill(Color.WHITE); - changing.setBackground(new Background(new BackgroundFill(Color.BLUE, CornerRadii.EMPTY, Insets.EMPTY))); - this.model = model; this.itemName = itemName; @@ -154,57 +108,11 @@ public AlarmTreeConfigView(final AlarmClient model, String itemName) setTop(createToolbar()); setCenter(tree_config_view); - if (AlarmSystem.alarm_tree_startup_ms <= 0) - { - // Original implementation: - // Create initial (empty) representation, - // register listener, then model gets started - block_item_changes.countDown(); - tree_config_view.setRoot(createViewItem(model.getRoot())); - model.addListener(AlarmTreeConfigView.this); - } - else - UpdateThrottle.TIMER.schedule(this::startup, AlarmSystem.alarm_tree_startup_ms, TimeUnit.MILLISECONDS); + model.addListener(AlarmTreeConfigView.this); // Caller will start the model once we return from constructor } - private void startup() - { - // Waited for model to receive the bulk of initial additions and removals... - Platform.runLater(() -> - { - if (! model.isRunning()) - { - logger.log(Level.WARNING, model.getRoot().getName() + " was disposed while waiting for alarm tree startup"); - return; - } - // Listen to model changes, but they're blocked, - // so this blocks model changes from now on - model.addListener(AlarmTreeConfigView.this); - - // Represent model that should by now be fairly complete - tree_config_view.setRoot(createViewItem(model.getRoot())); - - // expand tree item if is matches item name - if (tree_config_view.getRoot() != null && itemName != null) { - for (TreeItem treeItem : tree_config_view.getRoot().getChildren()) { - if (((AlarmTreeItem) treeItem.getValue()).getName().equals(itemName)) { - expandAlarms(treeItem); - break; - } - } - } - - // Set change indicator so that it clears when there are no more changes - indicateChange(); - showServerState(model.isServerAlive()); - - // Un-block to handle changes from now on - block_item_changes.countDown(); - }); - } - private ToolBar createToolbar() { final Button collapse = new Button("", @@ -226,7 +134,7 @@ private ToolBar createToolbar() show_disabled.setTooltip(new Tooltip("Expand alarm tree to show disabled PVs")); show_disabled.setOnAction(event -> expandDisabledPVs(tree_config_view.getRoot())); - return new ToolBar(no_server, changing, ToolbarHelper.createSpring(), collapse, show_alarms, show_disabled); + return new ToolBar(alarm_client_state_label, ToolbarHelper.createSpring(), collapse, show_alarms, show_disabled); } ToolBar getToolbar() @@ -287,43 +195,45 @@ private TreeItem> createViewItem(final AlarmTreeItem model_i return view_item; } - /** Called when an item is added/removed to tell user - * that there are changes to the tree structure, - * may not make sense to interact with the tree right now. - * - *

Resets on its own after 1 second without changes. - */ - private void indicateChange() - { - final ScheduledFuture previous = ongoing_change.getAndSet(UpdateThrottle.TIMER.schedule(clear_change_indicator, 1, TimeUnit.SECONDS)); - if (previous == null) - { - logger.log(Level.INFO, "Alarm tree changes start"); - setCursor(Cursor.WAIT); - final ObservableList items = getToolbar().getItems(); - if (! items.contains(changing)) - items.add(1, changing); - } - else - previous.cancel(false); - } - - /** @param alive Have we seen server messages? */ - private void showServerState(final boolean alive) - { - final ObservableList items = getToolbar().getItems(); - items.remove(no_server); - if (! alive) - // Place left of spring, collapse, expand_alarms, - // i.e. right of potential AlarmConfigSelector - items.add(items.size()-3, no_server); - } - // AlarmClientModelListener @Override - public void serverStateChanged(final boolean alive) + public void alarmClientStateChanged(final AlarmClientState oldState, final AlarmClientState state) { - Platform.runLater(() -> showServerState(alive)); + if (oldState == AlarmClientState.LOADING && state == AlarmClientState.CONNECTED) { + // Finished loading initial flurry of updates + + final CountDownLatch done = new CountDownLatch(1); + Platform.runLater(() -> { + // Represent model that should by now be fairly complete + tree_config_view.setRoot(createViewItem(model.getRoot())); + + // expand tree item if is matches item name + if (tree_config_view.getRoot() != null && itemName != null) { + for (final TreeItem> treeItem : tree_config_view.getRoot().getChildren()) { + if (treeItem.getValue().getName().equals(itemName)) { + expandAlarms(treeItem); + break; + } + } + } + done.countDown(); + }); + + // Wait until initial tree is displayed before we process new messages + try + { + done.await(); + } + catch (final InterruptedException ex) + { + logger.log(Level.WARNING, "Interrupted while waiting for initial tree to be created", ex); + } + } + + Platform.runLater(() -> { + alarm_client_state_label.setBackground(AlarmUI.getAlarmClientStateBackground(state)); + alarm_client_state_label.setText(state.getDisplayName()); + }); } // AlarmClientModelListener @@ -340,25 +250,13 @@ public void serverDisableNotifyChanged(final boolean disable_notify) // NOP } - /** Block until changes to items should be shown */ - private void blockItemChanges() - { - try - { - block_item_changes.await(); - } - catch (InterruptedException ex) - { - logger.log(Level.WARNING, "Blocker for item changes got interrupted", ex); - } - } - // AlarmClientModelListener @Override public void itemAdded(final AlarmTreeItem item) { - blockItemChanges(); - // System.out.println(Thread.currentThread() + " Add " + item.getPathName()); + if (model.getState().isInitialState()) { + return; + } // Parent must already exist final AlarmTreeItem model_parent = item.getParent(); @@ -376,7 +274,6 @@ public void itemAdded(final AlarmTreeItem item) final CountDownLatch done = new CountDownLatch(1); Platform.runLater(() -> { - indicateChange(); // Keep sorted by inserting at appropriate index final List>> items = view_parent.getChildren(); final int index = Collections.binarySearch(items, view_item, @@ -407,8 +304,9 @@ public void itemAdded(final AlarmTreeItem item) @Override public void itemRemoved(final AlarmTreeItem item) { - blockItemChanges(); - // System.out.println(Thread.currentThread() + " Removed " + item.getPathName()); + if (model.getState().isInitialState()) { + return; + } // Remove item and all sub-items from model2ui final TreeItem> view_item = removeViewItems(item); @@ -419,7 +317,6 @@ public void itemRemoved(final AlarmTreeItem item) final CountDownLatch done = new CountDownLatch(1); Platform.runLater(() -> { - indicateChange(); // Can only locate the parent view item on UI thread, // because item might just have been created by itemAdded() event // and won't be on the screen until UI thread runs. @@ -461,8 +358,10 @@ private TreeItem> removeViewItems(final AlarmTreeItem item) @Override public void itemUpdated(final AlarmTreeItem item) { - blockItemChanges(); - // System.out.println(Thread.currentThread() + " Updated " + item.getPathName()); + if (model.getState().isInitialState()) { + return; + } + final TreeItem> view_item = path2view.get(item.getPathName()); if (view_item == null) { diff --git a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/AlarmTreeView.java b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/AlarmTreeView.java index 3671f35bed..5e0170a79e 100644 --- a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/AlarmTreeView.java +++ b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/AlarmTreeView.java @@ -18,18 +18,16 @@ import java.util.Map; import java.util.Set; import java.util.concurrent.CountDownLatch; -import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; -import java.util.concurrent.atomic.AtomicReference; import java.util.logging.Level; import java.util.stream.Collectors; import javafx.collections.FXCollections; -import org.phoebus.applications.alarm.AlarmSystem; import org.phoebus.applications.alarm.client.AlarmClient; import org.phoebus.applications.alarm.client.AlarmClientLeaf; import org.phoebus.applications.alarm.client.AlarmClientListener; import org.phoebus.applications.alarm.client.AlarmClientNode; +import org.phoebus.applications.alarm.client.AlarmClientState; import org.phoebus.applications.alarm.model.AlarmTreeItem; import org.phoebus.applications.alarm.model.BasicState; import org.phoebus.applications.alarm.ui.AlarmContextMenuHelper; @@ -52,9 +50,6 @@ import javafx.application.Platform; import javafx.collections.ObservableList; -import javafx.geometry.Insets; -import javafx.scene.Cursor; -import javafx.scene.Node; import javafx.scene.control.Button; import javafx.scene.control.ContextMenu; import javafx.scene.control.Label; @@ -69,11 +64,8 @@ import javafx.scene.input.ClipboardContent; import javafx.scene.input.Dragboard; import javafx.scene.input.TransferMode; -import javafx.scene.layout.Background; -import javafx.scene.layout.BackgroundFill; import javafx.scene.layout.BorderPane; -import javafx.scene.layout.CornerRadii; -import javafx.scene.paint.Color; + /** Tree-based UI for alarm configuration * @@ -89,36 +81,37 @@ * exception to this is itemUpdated, which adds to a queue of * items to be updated which is then regularly processed. * + * When the tree is loading, we wait until we have caught up to all + * the incoming updates from Kafka before rendering the tree. This + * is primarily to avoid 2 issues: firstly, the tree can be slow to + * render due to how many updates are occuring especially if + * displaying via a remote desktop (ssh-X). Secondly, the way the + * tree loads can be visually confusing due to the order of the + * messages from Kafka not necessarily being a logical order. + * + * The alarm tree view thus starts in stages: + * 1) Register model listener + * 2) Wait for model to receive the bulk of initial additions and + * removals (loading state). Add/remove/update listener methods + * do nothing while the model is in the loading state + * 3) Render the initial model to the UI + * 4) The add/remove/update listeners now handle incoming changes + * and update the UI accordingly + * * @author Kay Kasemir */ @SuppressWarnings("nls") public class AlarmTreeView extends BorderPane implements AlarmClientListener { - private final Label no_server = AlarmUI.createNoServerLabel(); + private final Label alarm_client_state_label = AlarmUI.createAlarmClientStateLabel(); + private final TreeView> tree_view = new TreeView<>(); /** Model with current alarm tree, sends updates */ private final AlarmClient model; - private final String itemName; - /** Latch for initially pausing model listeners - * - * Imagine a large alarm tree that changes. - * The alarm table can periodically display the current - * alarms, it does not need to display every change right away. - * The tree on the other hand must reflect every added or removed item, - * because updates cannot be applied once the tree structure gets out of sync. - * When the model is first started, there is a flurry of additions and removals, - * which arrive in the order in which the tree was generated, not necessarily - * in the order they're laid out in the hierarchy. - * These can be slow to render, especially if displaying via a remote desktop (ssh-X). - * The alarm tree view thus starts in stages: - * 1) Wait for model to receive the bulk of initial additions and removals - * 2) Add listeners to model changes, but block them via this latch - * 3) Represent the initial model - * 4) Release this latch to handle changes (blocked and those that arrive from now on) - */ - private final CountDownLatch block_item_changes = new CountDownLatch(1); + /** Item name that should be expanded and focused */ + private final String itemName; /** Map from alarm tree path to view's TreeItem */ private final Map>> path2view = new HashMap<>(); @@ -132,23 +125,6 @@ public class AlarmTreeView extends BorderPane implements AlarmClientListener /** Throttle [5Hz] used for updates of existing items */ private final UpdateThrottle throttle = new UpdateThrottle(200, TimeUnit.MILLISECONDS, this::performUpdates); - /** Cursor change doesn't work on Mac, so add indicator to toolbar */ - private final Label changing = new Label("Loading..."); - - /** Is change indicator shown, and future been submitted to clear it? */ - private final AtomicReference> ongoing_change = new AtomicReference<>(); - - /** Clear the change indicator */ - private final Runnable clear_change_indicator = () -> - Platform.runLater(() -> - { - logger.log(Level.INFO, "Alarm tree changes end"); - ongoing_change.set(null); - setCursor(null); - final ObservableList items = getToolbar().getItems(); - items.remove(changing); - }); - // Javadoc for TreeItem shows example for overriding isLeaf() and getChildren() // to dynamically create TreeItem as TreeView requests information. // @@ -168,16 +144,13 @@ public AlarmTreeView(final AlarmClient model) { /** * @param model Model to represent. Must not be running, yet - * @param itemName item name that may be expanded or given focus + * @param itemName item name that should be expanded and focused */ public AlarmTreeView(final AlarmClient model, final String itemName) { if (model.isRunning()) throw new IllegalStateException(); - changing.setTextFill(Color.WHITE); - changing.setBackground(new Background(new BackgroundFill(Color.BLUE, CornerRadii.EMPTY, Insets.EMPTY))); - this.model = model; this.itemName = itemName; @@ -192,57 +165,11 @@ public AlarmTreeView(final AlarmClient model, final String itemName) addClickSupport(); addDragSupport(); - if (AlarmSystem.alarm_tree_startup_ms <= 0) - { - // Original implementation: - // Create initial (empty) representation, - // register listener, then model gets started - block_item_changes.countDown(); - tree_view.setRoot(createViewItem(model.getRoot())); - model.addListener(AlarmTreeView.this); - } - else - UpdateThrottle.TIMER.schedule(this::startup, AlarmSystem.alarm_tree_startup_ms, TimeUnit.MILLISECONDS); + model.addListener(AlarmTreeView.this); // Caller will start the model once we return from constructor } - private void startup() - { - // Waited for model to receive the bulk of initial additions and removals... - Platform.runLater(() -> - { - if (! model.isRunning()) - { - logger.log(Level.WARNING, model.getRoot().getName() + " was disposed while waiting for alarm tree startup"); - return; - } - // Listen to model changes, but they're blocked, - // so this blocks model changes from now on - model.addListener(AlarmTreeView.this); - - // Represent model that should by now be fairly complete - tree_view.setRoot(createViewItem(model.getRoot())); - - // expand tree item if is matches item name - if (tree_view.getRoot() != null && itemName != null) { - for (TreeItem treeItem : tree_view.getRoot().getChildren()) { - if (((AlarmTreeItem) treeItem.getValue()).getName().equals(itemName)) { - expandAlarms(treeItem); - break; - } - } - } - - // Set change indicator so that it clears when there are no more changes - indicateChange(); - showServerState(model.isServerAlive()); - - // Un-block to handle changes from now on - block_item_changes.countDown(); - }); - } - private ToolBar createToolbar() { final Button collapse = new Button("", @@ -264,7 +191,7 @@ private ToolBar createToolbar() show_disabled.setTooltip(new Tooltip("Expand alarm tree to show disabled PVs")); show_disabled.setOnAction(event -> expandDisabledPVs(tree_view.getRoot())); - return new ToolBar(no_server, changing, ToolbarHelper.createSpring(), collapse, show_alarms, show_disabled); + return new ToolBar(alarm_client_state_label, ToolbarHelper.createSpring(), collapse, show_alarms, show_disabled); } ToolBar getToolbar() @@ -325,43 +252,45 @@ private TreeItem> createViewItem(final AlarmTreeItem model_i return view_item; } - /** Called when an item is added/removed to tell user - * that there are changes to the tree structure, - * may not make sense to interact with the tree right now. - * - *

Resets on its own after 1 second without changes. - */ - private void indicateChange() - { - final ScheduledFuture previous = ongoing_change.getAndSet(UpdateThrottle.TIMER.schedule(clear_change_indicator, 1, TimeUnit.SECONDS)); - if (previous == null) - { - logger.log(Level.INFO, "Alarm tree changes start"); - setCursor(Cursor.WAIT); - final ObservableList items = getToolbar().getItems(); - if (! items.contains(changing)) - items.add(1, changing); - } - else - previous.cancel(false); - } - - /** @param alive Have we seen server messages? */ - private void showServerState(final boolean alive) - { - final ObservableList items = getToolbar().getItems(); - items.remove(no_server); - if (! alive) - // Place left of spring, collapse, expand_alarms, - // i.e. right of potential AlarmConfigSelector - items.add(items.size()-3, no_server); - } - // AlarmClientModelListener @Override - public void serverStateChanged(final boolean alive) + public void alarmClientStateChanged(final AlarmClientState oldState, final AlarmClientState state) { - Platform.runLater(() -> showServerState(alive)); + if (oldState == AlarmClientState.LOADING && state == AlarmClientState.CONNECTED) { + // Finished loading initial flurry of updates + + final CountDownLatch done = new CountDownLatch(1); + Platform.runLater(() -> { + // Represent model that should by now be fairly complete + tree_view.setRoot(createViewItem(model.getRoot())); + + // expand tree item if is matches item name + if (tree_view.getRoot() != null && itemName != null) { + for (final TreeItem> treeItem : tree_view.getRoot().getChildren()) { + if (treeItem.getValue().getName().equals(itemName)) { + expandAlarms(treeItem); + break; + } + } + } + done.countDown(); + }); + + // Wait until initial tree is displayed before we process new messages + try + { + done.await(); + } + catch (final InterruptedException ex) + { + logger.log(Level.WARNING, "Interrupted while waiting for initial tree to be created", ex); + } + } + + Platform.runLater(() -> { + alarm_client_state_label.setBackground(AlarmUI.getAlarmClientStateBackground(state)); + alarm_client_state_label.setText(state.getDisplayName()); + }); } // AlarmClientModelListener @@ -378,31 +307,16 @@ public void serverDisableNotifyChanged(final boolean disable_notify) // NOP } - /** Block until changes to items should be shown */ - private void blockItemChanges() - { - try - { - block_item_changes.await(); - } - catch (InterruptedException ex) - { - logger.log(Level.WARNING, "Blocker for item changes got interrupted", ex); - } - } - // AlarmClientModelListener @Override public void itemAdded(final AlarmTreeItem item) { - blockItemChanges(); + if (model.getState().isInitialState()) + return; final CountDownLatch done = new CountDownLatch(1); - Platform.runLater(() -> { - indicateChange(); - // Parent must already exist final AlarmTreeItem model_parent = item.getParent(); final TreeItem> view_parent = path2view.get(model_parent.getPathName()); @@ -425,10 +339,8 @@ public void itemAdded(final AlarmTreeItem item) done.countDown(); }); - // Waiting on the UI thread throttles the model's updates - // to a rate that the UI can handle. - // The result is a slower startup when loading the model, - // but keeping the UI responsive + // Processing UI add/remove updates one-at-a-time prevents a whole host of potential + // race conditions and throttles large batches of updates to a rate that the UI can handle try { done.await(); @@ -443,13 +355,12 @@ public void itemAdded(final AlarmTreeItem item) @Override public void itemRemoved(final AlarmTreeItem item) { - blockItemChanges(); + if (model.getState().isInitialState()) + return; final CountDownLatch done = new CountDownLatch(1); Platform.runLater(() -> { - indicateChange(); - // Remove item and all sub-items from model2ui final TreeItem> view_item = removeViewItems(item); if (view_item == null) @@ -467,10 +378,8 @@ public void itemRemoved(final AlarmTreeItem item) done.countDown(); }); - // Waiting on the UI thread throttles the model's updates - // to a rate that the UI can handle. - // The result is a slower startup when loading the model, - // but keeping the UI responsive + // Processing UI add/remove updates one-at-a-time prevents a whole host of potential + // race conditions and throttles large batches of updates to a rate that the UI can handle try { done.await(); @@ -498,7 +407,9 @@ private TreeItem> removeViewItems(final AlarmTreeItem item) @Override public void itemUpdated(final AlarmTreeItem item) { - blockItemChanges(); + if (model.getState().isInitialState()) { + return; + } // UI update of existing item, i.e. // Platform.runLater(() -> TreeHelper.triggerTreeItemRefresh(view_item)); From 8aaea2ddd464afb70e0977cc0b17e920166761c4 Mon Sep 17 00:00:00 2001 From: Percy Baker Date: Tue, 24 Nov 2026 10:12:34 +0000 Subject: [PATCH 2/7] fix javadoc formatting maybe --- .../alarm/ui/tree/AlarmTreeView.java | 30 +++++++++---------- 1 file changed, 15 insertions(+), 15 deletions(-) diff --git a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/AlarmTreeView.java b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/AlarmTreeView.java index ec378c1908..d051549ebe 100644 --- a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/AlarmTreeView.java +++ b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/tree/AlarmTreeView.java @@ -85,22 +85,22 @@ * exception to this is itemUpdated, which adds to a queue of * items to be updated which is then regularly processed. * - * When the tree is loading, we wait until we have caught up to all - * the incoming updates from Kafka before rendering the tree. This - * is primarily to avoid 2 issues: firstly, the tree can be slow to - * render due to how many updates are occuring especially if - * displaying via a remote desktop (ssh-X). Secondly, the way the - * tree loads can be visually confusing due to the order of the - * messages from Kafka not necessarily being a logical order. + *

When the tree is loading, we wait until we have caught up to all + * the incoming updates from Kafka before rendering the tree. This + * is primarily to avoid 2 issues: firstly, the tree can be slow to + * render due to how many updates are occuring especially if + * displaying via a remote desktop (ssh-X). Secondly, the way the + * tree loads can be visually confusing due to the order of the + * messages from Kafka not necessarily being a logical order. * - * The alarm tree view thus starts in stages: - * 1) Register model listener - * 2) Wait for model to receive the bulk of initial additions and - * removals (loading state). Add/remove/update listener methods - * do nothing while the model is in the loading state - * 3) Render the initial model to the UI - * 4) The add/remove/update listeners now handle incoming changes - * and update the UI accordingly + *

The alarm tree view thus starts in stages: + * 1) Register model listener + * 2) Wait for model to receive the bulk of initial additions and + * removals (loading state) - add/remove/update listener methods + * do nothing while the model is in the loading state + * 3) Render the initial model to the UI + * 4) The add/remove/update listeners now handle incoming changes + * and update the UI accordingly * * @author Kay Kasemir */ From 70e7f0ddc57ad53c0ff13f77f7b6ab16a1cc747d Mon Sep 17 00:00:00 2001 From: Percy Baker Date: Tue, 24 Nov 2026 11:00:35 +0000 Subject: [PATCH 3/7] Small cleanup of checkState logic and fix rare edge case where disconnect before first heartbeat hangs in loading --- .../alarm/client/AlarmClient.java | 56 ++++++++++--------- 1 file changed, 31 insertions(+), 25 deletions(-) diff --git a/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClient.java b/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClient.java index 117cef4a73..8aa61d236a 100644 --- a/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClient.java +++ b/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClient.java @@ -272,43 +272,49 @@ private void run() { } } + /** + * Updates the state field to reflect the current state of the model based largely + * on the Kafka consumer and various timeouts. + */ private void checkState() { + // Until the first heartbeat arrives, getSecondSinceLastConsumerHeartbeat will return -1. + // The first heartbeat can sometimes only arrive after the first message. Therefore, + // until the first heartbeat arrives (i.e. while secondsSinceLastHeartbeat == -1), we + // simply check how long it's been since the model started and use that to determine + // whether the connection to Kafka has timed out. + final long secondsSinceLastHeartbeat = getSecondSinceLastConsumerHeartbeat(); + final boolean isKafkaTimedOut = secondsSinceLastHeartbeat == -1 + ? System.currentTimeMillis() - startupTime > AlarmSystem.kafka_connection_timeout_seconds * 1000.0 + : secondsSinceLastHeartbeat > AlarmSystem.kafka_connection_timeout_seconds; + + // Note: It might take a few moments for the first heartbeat after a new connection, + // so we may end up processing messages while still in a 'no connection' state + final boolean isKafkaConnected = secondsSinceLastHeartbeat != -1 + && secondsSinceLastHeartbeat <= AlarmSystem.kafka_connection_timeout_seconds; + switch (state) { case CONNECTING -> { - if (System.currentTimeMillis() - startupTime > AlarmSystem.kafka_connection_timeout_seconds * 1000.0) { - // We use the heartbeat metric to determine whether the Kafka consumer - // is still connected. Unfortunately, until the consumer has connected - // (and for a short time after), this metric always returns -1, - // so we have to use our own logic to determine when the initial - // connection attempt has timed out. + if (isKafkaTimedOut) { setState(AlarmClientState.NO_INITIAL_KAFKA_CONNECTION); } else if (!consumer.assignment().isEmpty()) { // Once the consumer has been assigned partitions, we can be sure it has // managed to establish contact with the controller and transition to the - // loading state. (Ideally we would use the heartbeat but again this returns - // -1 for a short time after connection has been established, so it's not a - // great metric) + // loading state. setState(AlarmClientState.LOADING); } } case NO_INITIAL_KAFKA_CONNECTION -> { - // Note: It might take a few moments for the first heartbeat after a new connection, - // so we may end up processing messages while still in NO_INIIAL_KAFKA_CONNECTION - final long secondsSinceLastHeartbeat = getSecondSinceLastConsumerHeartbeat(); - if (secondsSinceLastHeartbeat != -1 && secondsSinceLastHeartbeat <= AlarmSystem.kafka_connection_timeout_seconds) { + if (isKafkaConnected) { setState(AlarmClientState.LOADING); } } case NO_KAFKA_CONNECTION -> { - // Note: It might take a few moments for the first heartbeat after a new - // connection, so we may end up processing messages while still in NO_KAFKA_CONNECTION - final long secondsSinceLastHeartbeat = getSecondSinceLastConsumerHeartbeat(); - if (secondsSinceLastHeartbeat != -1 && secondsSinceLastHeartbeat <= AlarmSystem.kafka_connection_timeout_seconds) { + if (isKafkaConnected) { setState(AlarmClientState.CONNECTED); } } case LOADING -> { - if (getSecondSinceLastConsumerHeartbeat() > AlarmSystem.kafka_connection_timeout_seconds) { + if (isKafkaTimedOut) { setState(AlarmClientState.NO_INITIAL_KAFKA_CONNECTION); } else { // Lag is just how many messages still need to be polled for us to catch up @@ -317,7 +323,9 @@ private void checkState() { // // If no partition has been assigned yet, this means the consumer is still // waiting for an assignment and will not return any records yet, so we need - // to wait until the consumer has been assigned partitions. + // to wait until the consumer has been assigned partitions. (This should not + // happen in practice due to the state machine design but is here just in + // case) boolean caughtUp = !consumer.assignment().isEmpty(); for (final TopicPartition partition : consumer.assignment()) { final OptionalLong lag = consumer.currentLag(partition); @@ -334,18 +342,16 @@ private void checkState() { } } case CONNECTED -> { - final long now = System.currentTimeMillis(); - if (getSecondSinceLastConsumerHeartbeat() > AlarmSystem.kafka_connection_timeout_seconds) { + if (isKafkaTimedOut) { setState(AlarmClientState.NO_KAFKA_CONNECTION); - } else if (now - last_state_update > AlarmSystem.idle_timeout_ms * 3) { + } else if (System.currentTimeMillis() - last_state_update > AlarmSystem.idle_timeout_ms * 3) { setState(AlarmClientState.NO_ALARMSERVER_CONNECTION); } } case NO_ALARMSERVER_CONNECTION -> { - final long now = System.currentTimeMillis(); - if (getSecondSinceLastConsumerHeartbeat() > AlarmSystem.kafka_connection_timeout_seconds) { + if (isKafkaTimedOut) { setState(AlarmClientState.NO_KAFKA_CONNECTION); - } else if (now - last_state_update <= AlarmSystem.idle_timeout_ms * 3) { + } else if (System.currentTimeMillis() - last_state_update <= AlarmSystem.idle_timeout_ms * 3) { setState(AlarmClientState.CONNECTED); } } From 8b19858f54d17fbb1fe5608ae0f00cf982088d24 Mon Sep 17 00:00:00 2001 From: Percy Baker Date: Tue, 24 Nov 2026 11:32:04 +0000 Subject: [PATCH 4/7] Short circuit lag check + improve comment --- .../phoebus/applications/alarm/client/AlarmClient.java | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClient.java b/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClient.java index 8aa61d236a..57f14f40ee 100644 --- a/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClient.java +++ b/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClient.java @@ -329,11 +329,13 @@ private void checkState() { boolean caughtUp = !consumer.assignment().isEmpty(); for (final TopicPartition partition : consumer.assignment()) { final OptionalLong lag = consumer.currentLag(partition); - // From Kafka docs - currentLag can be empty if the lag is not known for - // whatever reason - if this happens we likely just need to wait until it - // is known + // From Kafka docs - currentLag can be empty if the lag is not known due + // to the client not having the required data yet. If this happens, the + // client will start a request to obtain said data from Kafka in the + // background. if (lag.isEmpty() || lag.getAsLong() != 0) { caughtUp = false; + break; } } if (caughtUp) { From 14d5a637d04bc3e3d2039f16ce23f3fc2c14099a Mon Sep 17 00:00:00 2001 From: Percy Baker Date: Tue, 24 Nov 2026 12:28:34 +0000 Subject: [PATCH 5/7] satisfy pedantic linter --- .../org/phoebus/applications/alarm/messages.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/alarm/model/src/main/resources/org/phoebus/applications/alarm/messages.properties b/app/alarm/model/src/main/resources/org/phoebus/applications/alarm/messages.properties index dd31096a7f..9835d58767 100644 --- a/app/alarm/model/src/main/resources/org/phoebus/applications/alarm/messages.properties +++ b/app/alarm/model/src/main/resources/org/phoebus/applications/alarm/messages.properties @@ -8,4 +8,4 @@ noKafkaConnection=No Kafka connection connected=Connected noAlarmserverConnection=No Alarmserver connection clientError=Client error (check error log) -clientShutDown=Client shut down \ No newline at end of file +clientShutDown=Client shut down From 722a2ce1b45d977f27cfffdff3242cafbebeef41 Mon Sep 17 00:00:00 2001 From: Percy Baker Date: Tue, 24 Nov 2026 12:28:52 +0000 Subject: [PATCH 6/7] satisfy pedantic linter --- app/alarm/model/src/main/resources/alarm_preferences.properties | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/app/alarm/model/src/main/resources/alarm_preferences.properties b/app/alarm/model/src/main/resources/alarm_preferences.properties index a7e4d2ca70..7334c1f09d 100644 --- a/app/alarm/model/src/main/resources/alarm_preferences.properties +++ b/app/alarm/model/src/main/resources/alarm_preferences.properties @@ -177,4 +177,4 @@ max_block_ms=10000 # The maximum time from the last successful communication with Kafka # before it is considered to have disconnected. The client will # continually try to re-establish contact regardless of this setting. -kafka_connection_timeout_seconds=10 \ No newline at end of file +kafka_connection_timeout_seconds=10 From a22ea599b1b153eec6fa945c084390451aebe1a4 Mon Sep 17 00:00:00 2001 From: Percy Baker Date: Wed, 2 Dec 2026 11:43:20 +0000 Subject: [PATCH 7/7] Javadoc typo, improve misleading log message, and display client error status if failed to construct client --- .../phoebus/applications/alarm/client/AlarmClient.java | 9 +++++++-- .../java/org/phoebus/applications/alarm/ui/AlarmUI.java | 2 +- .../applications/alarm/ui/table/AlarmTableInstance.java | 4 ++++ 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClient.java b/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClient.java index 57f14f40ee..db67a7ef8f 100644 --- a/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClient.java +++ b/app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClient.java @@ -270,6 +270,11 @@ private void run() { consumer.close(); producer.close(); } + + if (state != AlarmClientState.CLIENT_ERROR && state != AlarmClientState.CLIENT_SHUT_DOWN) { + // Normal shutdown without an error + setState(AlarmClientState.CLIENT_SHUT_DOWN); + } } /** @@ -669,10 +674,10 @@ public void shutdown() { consumer.wakeup(); try { thread.join(2000); + logger.log(Level.INFO, () -> thread.getName() + " shut down"); } catch (final InterruptedException ex) { - logger.log(Level.WARNING, thread.getName() + " thread doesn't shut down", ex); + logger.log(Level.WARNING, thread.getName() + " thread didn't shut down within 2 seconds", ex); } - logger.log(Level.INFO, () -> thread.getName() + " shut down"); } diff --git a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/AlarmUI.java b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/AlarmUI.java index 18d4e13ed9..1410fffdf5 100644 --- a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/AlarmUI.java +++ b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/AlarmUI.java @@ -271,7 +271,7 @@ public static Label createAlarmClientStateLabel() return createAlarmClientStateLabel(AlarmClientState.CONNECTING); } - /** @return Label that that indicates the given server state */ + /** @return Label that indicates the given server state */ public static Label createAlarmClientStateLabel(final AlarmClientState state) { final Label noServer = new Label(state.getDisplayName()); diff --git a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/table/AlarmTableInstance.java b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/table/AlarmTableInstance.java index cfb6cea7d4..931775c2c5 100644 --- a/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/table/AlarmTableInstance.java +++ b/app/alarm/ui/src/main/java/org/phoebus/applications/alarm/ui/table/AlarmTableInstance.java @@ -17,6 +17,7 @@ import org.apache.kafka.common.KafkaException; import org.phoebus.applications.alarm.AlarmSystem; import org.phoebus.applications.alarm.client.AlarmClient; +import org.phoebus.applications.alarm.client.AlarmClientState; import org.phoebus.applications.alarm.ui.AlarmConfigSelector; import org.phoebus.applications.alarm.ui.AlarmURI; import org.phoebus.framework.persistence.Memento; @@ -99,6 +100,9 @@ private Node create(final URI input) throws Exception mediator = new AlarmTableMediator(client, table); client.addListener(mediator); client.start(); + } else { + // Failed to construct the client; notify the user there's an error + table.setAlarmClientState(AlarmClientState.CLIENT_ERROR); } return table;