-
Notifications
You must be signed in to change notification settings - Fork 534
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Initial implementation of an experimental queue optimisation using Po…
…stgres LISTEN/NOTIFY
- Loading branch information
Showing
8 changed files
with
522 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
189 changes: 189 additions & 0 deletions
189
...-persistence/src/main/java/com/netflix/conductor/postgres/util/PostgresQueueListener.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,189 @@ | ||
/* | ||
* Copyright 2024 Conductor Authors. | ||
* <p> | ||
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with | ||
* the License. You may obtain a copy of the License at | ||
* <p> | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* <p> | ||
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on | ||
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the | ||
* specific language governing permissions and limitations under the License. | ||
*/ | ||
package com.netflix.conductor.postgres.util; | ||
|
||
import java.sql.Connection; | ||
import java.sql.SQLException; | ||
import java.util.HashMap; | ||
import java.util.Iterator; | ||
|
||
import javax.sql.DataSource; | ||
|
||
import com.fasterxml.jackson.core.JsonProcessingException; | ||
import com.fasterxml.jackson.databind.JsonNode; | ||
import com.fasterxml.jackson.databind.ObjectMapper; | ||
import com.netflix.conductor.postgres.config.PostgresProperties; | ||
import org.postgresql.PGConnection; | ||
import org.postgresql.PGNotification; | ||
import org.slf4j.Logger; | ||
import org.slf4j.LoggerFactory; | ||
|
||
import com.netflix.conductor.core.exception.NonTransientException; | ||
|
||
public class PostgresQueueListener { | ||
|
||
private PGConnection pgconn; | ||
|
||
private Connection conn; | ||
|
||
private DataSource dataSource; | ||
|
||
private HashMap<String, QueueStats> queues; | ||
|
||
private boolean connected = false; | ||
|
||
private long lastNotificationTime = 0; | ||
|
||
private Integer stalePeriod; | ||
|
||
protected final Logger logger = LoggerFactory.getLogger(getClass()); | ||
|
||
public PostgresQueueListener(DataSource dataSource, PostgresProperties properties) { | ||
logger.info("Set up PostgresQueueListener"); | ||
this.dataSource = dataSource; | ||
this.stalePeriod = properties.getExperimentalQueueNotifyStalePeriod(); | ||
connect(); | ||
} | ||
|
||
public boolean hasMessagesReady(String queueName) { | ||
checkUpToDate(); | ||
handleNotifications(); | ||
if (System.currentTimeMillis() - lastNotificationTime > 6000){ | ||
return true; | ||
} | ||
|
||
QueueStats queueStats = queues.get(queueName); | ||
if(queueStats == null){ | ||
return false; | ||
} | ||
|
||
if(queueStats.getNextDelivery() > System.currentTimeMillis()){ | ||
return false; | ||
} | ||
|
||
return true; | ||
} | ||
|
||
public Integer getSize(String queueName) { | ||
checkUpToDate(); | ||
handleNotifications(); | ||
if (System.currentTimeMillis() - lastNotificationTime > 6000){ | ||
return null; | ||
} | ||
|
||
QueueStats queueStats = queues.get(queueName); | ||
if(queueStats == null){ | ||
return 0; | ||
} | ||
|
||
return queueStats.getDepth(); | ||
} | ||
|
||
private void connect(){ | ||
connected = false; | ||
try { | ||
this.conn = dataSource.getConnection(); | ||
this.pgconn = conn.unwrap(PGConnection.class); | ||
|
||
try { | ||
boolean previousAutoCommitMode = conn.getAutoCommit(); | ||
conn.setAutoCommit(true); | ||
try { | ||
conn.prepareStatement("LISTEN conductor_queue_state; SELECT queue_notify();").execute(); | ||
connected = true; | ||
} catch (Throwable th) { | ||
conn.rollback(); | ||
logger.info(th.getMessage()); | ||
} finally { | ||
conn.setAutoCommit(previousAutoCommitMode); | ||
} | ||
} catch (SQLException ex) { | ||
throw new NonTransientException(ex.getMessage(), ex); | ||
} | ||
requestStats(); | ||
|
||
} catch (SQLException e) { | ||
logger.info(e.getSQLState()); | ||
} | ||
} | ||
|
||
private void requestStats(){ | ||
try { | ||
boolean previousAutoCommitMode = conn.getAutoCommit(); | ||
conn.setAutoCommit(true); | ||
try { | ||
conn.prepareStatement("SELECT queue_notify();").execute(); | ||
connected = true; | ||
} catch (Throwable th) { | ||
conn.rollback(); | ||
logger.info(th.getMessage()); | ||
} finally { | ||
conn.setAutoCommit(previousAutoCommitMode); | ||
} | ||
} catch (SQLException ex) { | ||
throw new NonTransientException(ex.getMessage(), ex); | ||
} | ||
} | ||
|
||
private void checkUpToDate(){ | ||
if (System.currentTimeMillis() - lastNotificationTime > this.stalePeriod){ | ||
requestStats(); | ||
} | ||
} | ||
|
||
private void handleNotifications() { | ||
try { | ||
PGNotification[] notifications = pgconn.getNotifications(); | ||
if (notifications == null || notifications.length == 0) { | ||
return; | ||
} | ||
processPayload(notifications[notifications.length-1].getParameter()); | ||
} catch (SQLException e) { | ||
logger.info("Error fetching notifications {}", e.getSQLState()); | ||
if(e.getSQLState() == "08003"){ | ||
logger.info("Reconnecting"); | ||
connect(); | ||
} | ||
} | ||
} | ||
|
||
private void processPayload(String payload){ | ||
logger.info("Payload: {}", payload); | ||
ObjectMapper objectMapper = new ObjectMapper(); | ||
try { | ||
JsonNode notification = objectMapper.readTree(payload); | ||
JsonNode lastNotificationTime = notification.get("__now__"); | ||
if(lastNotificationTime != null){ | ||
this.lastNotificationTime = lastNotificationTime.asLong(); | ||
} | ||
Iterator<String> iterator = notification.fieldNames(); | ||
|
||
HashMap<String, QueueStats> queueStats = new HashMap<>(); | ||
iterator.forEachRemaining(key -> { | ||
if(!key.equals("__now__")){ | ||
QueueStats stats = null; | ||
try { | ||
stats = objectMapper.treeToValue(notification.get(key), QueueStats.class); | ||
} catch (JsonProcessingException e) { | ||
throw new RuntimeException(e); | ||
} | ||
queueStats.put(key, stats); | ||
} | ||
}); | ||
this.queues = queueStats; | ||
logger.info(queues.toString()); | ||
} catch (JsonProcessingException e) { | ||
throw new RuntimeException(e); | ||
} | ||
} | ||
} |
27 changes: 27 additions & 0 deletions
27
postgres-persistence/src/main/java/com/netflix/conductor/postgres/util/QueueStats.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
package com.netflix.conductor.postgres.util; | ||
|
||
public class QueueStats { | ||
private Integer depth; | ||
|
||
private long nextDelivery; | ||
|
||
public void setDepth(Integer depth) { | ||
this.depth = depth; | ||
} | ||
|
||
public Integer getDepth() { | ||
return depth; | ||
} | ||
|
||
public void setNextDelivery(long nextDelivery) { | ||
this.nextDelivery = nextDelivery; | ||
} | ||
|
||
public long getNextDelivery() { | ||
return nextDelivery; | ||
} | ||
|
||
public String toString(){ | ||
return "{nextDelivery: " + nextDelivery + " depth: " + depth + "}"; | ||
} | ||
} |
50 changes: 50 additions & 0 deletions
50
postgres-persistence/src/main/resources/db/migration_postgres/V9__notify.sql
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
CREATE OR REPLACE FUNCTION queue_notify() RETURNS void | ||
LANGUAGE SQL | ||
AS $$ | ||
SELECT pg_notify('conductor_queue_state', ( | ||
SELECT | ||
COALESCE(jsonb_object_agg(KEY, val), '{}'::jsonb) || | ||
jsonb_build_object('__now__', (extract('epoch' from CURRENT_TIMESTAMP)*1000)::bigint) | ||
FROM ( | ||
SELECT | ||
queue_name AS KEY, | ||
jsonb_build_object( | ||
'nextDelivery', | ||
(extract('epoch' from min(deliver_on))*1000)::bigint, | ||
'depth', | ||
count(*) | ||
) AS val | ||
FROM | ||
queue_message | ||
WHERE | ||
popped = FALSE | ||
GROUP BY | ||
queue_name) AS sq)::text); | ||
$$; | ||
|
||
|
||
CREATE FUNCTION queue_notify_trigger() | ||
RETURNS TRIGGER | ||
LANGUAGE PLPGSQL | ||
AS $$ | ||
BEGIN | ||
PERFORM queue_notify(); | ||
RETURN NULL; | ||
END; | ||
$$; | ||
|
||
CREATE TRIGGER queue_update | ||
AFTER UPDATE ON queue_message | ||
FOR EACH ROW | ||
WHEN (OLD.popped IS DISTINCT FROM NEW.popped) | ||
EXECUTE FUNCTION queue_notify_trigger(); | ||
|
||
CREATE TRIGGER queue_insert_delete | ||
AFTER INSERT OR DELETE ON queue_message | ||
FOR EACH ROW | ||
EXECUTE FUNCTION queue_notify_trigger(); | ||
|
||
CREATE TRIGGER queue_delete | ||
AFTER DELETE ON queue_message | ||
FOR EACH ROW | ||
EXECUTE FUNCTION queue_notify_trigger(); |
Oops, something went wrong.