Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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 -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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;
Expand Down Expand Up @@ -69,6 +74,11 @@
*/
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.
*
Expand Down Expand Up @@ -110,15 +120,20 @@
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
Expand Down Expand Up @@ -224,49 +239,131 @@
final ProducerRecord<String, String> 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);

Check warning on line 242 in app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClient.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Lambda should be used to defer string concatenation.

See more on https://sonarcloud.io/project/issues?id=ControlSystemStudio_phoebus&issues=AaINiKkReHnEbLXK0xCg&open=AaINiKkReHnEbLXK0xCg&pullRequest=4036
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<String, String> records = consumer.poll(POLL_PERIOD);
for (final ConsumerRecord<String, String> record : records) {

Check warning on line 256 in app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClient.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Rename this variable to not match a restricted identifier.

See more on https://sonarcloud.io/project/issues?id=ControlSystemStudio_phoebus&issues=AaINiKkReHnEbLXK0xCh&open=AaINiKkReHnEbLXK0xCh&pullRequest=4036
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);
if (state != AlarmClientState.CLIENT_ERROR && state != AlarmClientState.CLIENT_SHUT_DOWN) {
// Normal shutdown without an error
setState(AlarmClientState.CLIENT_SHUT_DOWN);
}
}

/**
* 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<String, String> records = consumer.poll(POLL_PERIOD);
for (final ConsumerRecord<String, String> record : records)
handleUpdate(record);
* Updates the state field to reflect the current state of the model based largely
* on the Kafka consumer and various timeouts.
*/
private void checkState() {

Check failure on line 284 in app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClient.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this method to reduce its Cognitive Complexity from 30 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=ControlSystemStudio_phoebus&issues=AaINiKkReHnEbLXK0xCi&open=AaINiKkReHnEbLXK0xCi&pullRequest=4036
// 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 (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.
setState(AlarmClientState.LOADING);
}
}
case NO_INITIAL_KAFKA_CONNECTION -> {
if (isKafkaConnected) {
setState(AlarmClientState.LOADING);
}

Check warning on line 314 in app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClient.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Replace this "if" statement with a pattern match guard.

See more on https://sonarcloud.io/project/issues?id=ControlSystemStudio_phoebus&issues=AaINiKkReHnEbLXK0xCk&open=AaINiKkReHnEbLXK0xCk&pullRequest=4036
}
case NO_KAFKA_CONNECTION -> {
if (isKafkaConnected) {
setState(AlarmClientState.CONNECTED);
}

Check warning on line 319 in app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClient.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Replace this "if" statement with a pattern match guard.

See more on https://sonarcloud.io/project/issues?id=ControlSystemStudio_phoebus&issues=AaINiKkReHnEbLXK0xCj&open=AaINiKkReHnEbLXK0xCj&pullRequest=4036
}
case LOADING -> {
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
// 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. (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);
// 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) {
setState(AlarmClientState.CONNECTED);
}
}
}
case CONNECTED -> {
if (isKafkaTimedOut) {
setState(AlarmClientState.NO_KAFKA_CONNECTION);
} else if (System.currentTimeMillis() - last_state_update > AlarmSystem.idle_timeout_ms * 3) {
setState(AlarmClientState.NO_ALARMSERVER_CONNECTION);
}
}
case NO_ALARMSERVER_CONNECTION -> {
if (isKafkaTimedOut) {
setState(AlarmClientState.NO_KAFKA_CONNECTION);
} else if (System.currentTimeMillis() - 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");
}
}

/**
Expand Down Expand Up @@ -570,42 +667,60 @@
}

/**
* @return <code>true</code> if connected to server, else updates have timed out
* Stop client
*/
public boolean isServerAlive() {
return !has_timed_out;
public void shutdown() {
running.set(false);
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 didn't shut down within 2 seconds", ex);

Check warning on line 679 in app/alarm/model/src/main/java/org/phoebus/applications/alarm/client/AlarmClient.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Lambda should be used to defer string concatenation.

See more on https://sonarcloud.io/project/issues?id=ControlSystemStudio_phoebus&issues=AaI2lL2SvFTT2OaW48n6&open=AaI2lL2SvFTT2OaW48n6&pullRequest=4036
}

}

public AlarmClientState getState() {
return state;
}

/**
* Check if there have been any messages from server
* Updates the current state and notifies all listeners
*/
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);
private void setState(final AlarmClientState newState) {
if (state != newState) {
final AlarmClientState oldState = state;
state = newState;
for (final AlarmClientListener listener : listeners) {
listener.alarmClientStateChanged(oldState, newState);
}
} else if (has_timed_out) {
has_timed_out = false;
for (final AlarmClientListener listener : listeners)
listener.serverStateChanged(true);
}
}

/**
* Stop client
*/
public void shutdown() {
running.set(false);
consumer.wakeup();
try {
thread.join(2000);
} catch (final InterruptedException ex) {
logger.log(Level.WARNING, thread.getName() + " thread doesn't shut down", ex);
* 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<Object> 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);
}
logger.log(Level.INFO, () -> thread.getName() + " shut down");

// 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;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
Loading
Loading