use of com.redhat.jenkins.plugins.ci.CIEnvironmentContributingAction in project jms-messaging-plugin by jenkinsci.
the class RabbitMQMessagingWorker method waitForMessage.
@Override
public String waitForMessage(Run<?, ?> build, TaskListener listener, ProviderData pdata) {
RabbitMQSubscriberProviderData pd = (RabbitMQSubscriberProviderData) pdata;
try {
if (connection == null || !connection.isOpen()) {
connect();
}
if (channel == null || !channel.isOpen()) {
this.channel = connection.createChannel();
}
channel.exchangeDeclarePassive(exchangeName);
channel.queueBind(getQueue(provider), exchangeName, this.topic);
} catch (Exception ex) {
log.severe("Connection to broker can't be established!");
log.severe(ExceptionUtils.getStackTrace(ex));
listener.error("Connection to broker can't be established!");
listener.error(ExceptionUtils.getStackTrace(ex));
return null;
}
log.info("Waiting for message.");
listener.getLogger().println("Waiting for message.");
for (MsgCheck msgCheck : pd.getChecks()) {
log.info(" with check: " + msgCheck.toString());
listener.getLogger().println(" with check: " + msgCheck);
}
Integer timeout = (pd.getTimeout() != null ? pd.getTimeout() : RabbitMQSubscriberProviderData.DEFAULT_TIMEOUT_IN_MINUTES);
log.info(" with timeout: " + timeout + " minutes");
listener.getLogger().println(" with timeout: " + timeout + " minutes");
// Create deliver callback to listen for messages
DeliverCallback deliverCallback = (consumerTag, delivery) -> {
String json = new String(delivery.getBody(), StandardCharsets.UTF_8);
listener.getLogger().println("Received '" + delivery.getEnvelope().getRoutingKey() + "':\n" + "Message id: '" + delivery.getProperties().getMessageId() + "'\n'" + json + "'");
log.info("Received '" + delivery.getEnvelope().getRoutingKey() + "':\n" + "Message id: '" + delivery.getProperties().getMessageId() + "'\n'" + json + "'");
RabbitMQMessage message = new RabbitMQMessage(delivery.getEnvelope().getRoutingKey(), json, delivery.getProperties().getMessageId());
message.setTimestamp(new Date().getTime());
message.setDeliveryTag(delivery.getEnvelope().getDeliveryTag());
messageQueue.add(message);
};
String consumerTag = null;
long startTime = new Date().getTime();
int timeoutInMs = timeout * 60 * 1000;
try {
consumerTag = channel.basicConsume(getQueue(provider), deliverCallback, (CancelCallback) null);
while ((new Date().getTime() - startTime) < timeoutInMs) {
if (!messageQueue.isEmpty()) {
RabbitMQMessage message = messageQueue.poll();
log.info("Obtained message from queue: " + message.toJson());
if (!provider.verify(message.getBodyJson(), pd.getChecks(), jobname)) {
channel.basicAck(message.getDeliveryTag(), false);
continue;
}
listener.getLogger().println("Message: '" + message.getMsgId() + "' was succesfully checked.");
if (build != null) {
if (StringUtils.isNotEmpty(pd.getVariable())) {
EnvVars vars = new EnvVars();
vars.put(pd.getVariable(), message.getBodyJson());
build.addAction(new CIEnvironmentContributingAction(vars));
}
}
channel.basicAck(message.getDeliveryTag(), false);
return message.getBodyJson();
}
if (interrupt) {
return null;
}
TimeUnit.MILLISECONDS.sleep(500);
}
log.severe("Timed out waiting for message!");
listener.getLogger().println("Timed out waiting for message!");
} catch (Exception e) {
// for more info
if (e.getClass() == InterruptedException.class) {
Thread.currentThread().interrupt();
}
log.log(Level.SEVERE, "Unhandled exception waiting for message.", e);
} finally {
try {
if (consumerTag != null) {
channel.basicCancel(consumerTag);
}
channel.close();
} catch (Exception e) {
listener.getLogger().println("exception in finally");
}
}
return null;
}
use of com.redhat.jenkins.plugins.ci.CIEnvironmentContributingAction in project jms-messaging-plugin by jenkinsci.
the class ActiveMqMessagingWorker method waitForMessage.
@Override
public String waitForMessage(Run<?, ?> build, TaskListener listener, ProviderData pdata) {
ActiveMQSubscriberProviderData pd = (ActiveMQSubscriberProviderData) pdata;
String ip = null;
try {
ip = Inet4Address.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
log.severe("Unable to get localhost IP address.");
}
String ltopic = getTopic(provider);
try {
ltopic = PluginUtils.getSubstitutedValue(getTopic(provider), build.getEnvironment(listener));
} catch (IOException | InterruptedException e) {
log.warning(e.getMessage());
}
if (ip != null && provider.getAuthenticationMethod() != null && ltopic != null && provider.getBroker() != null) {
log.info("Waiting for message with selector: " + pd.getSelector());
listener.getLogger().println("Waiting for message with selector: " + pd.getSelector());
Connection connection = null;
MessageConsumer consumer = null;
try {
ActiveMQConnectionFactory connectionFactory = provider.getConnectionFactory();
connection = connectionFactory.createConnection();
connection.setClientID(ip + "_" + UUID.randomUUID());
connection.start();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
if (provider.getUseQueues()) {
Queue destination = session.createQueue(ltopic);
consumer = session.createConsumer(destination, pd.getSelector(), false);
} else {
Topic destination = session.createTopic(ltopic);
consumer = session.createDurableSubscriber(destination, jobname, pd.getSelector(), false);
}
long startTime = new Date().getTime();
int timeout = (pd.getTimeout() != null ? pd.getTimeout() : ActiveMQSubscriberProviderData.DEFAULT_TIMEOUT_IN_MINUTES) * 60 * 1000;
Message message;
do {
message = consumer.receive(timeout);
if (message != null) {
String value = getMessageBody(message);
if (provider.verify(value, pd.getChecks(), jobname)) {
if (StringUtils.isNotEmpty(pd.getVariable())) {
EnvVars vars = new EnvVars();
vars.put(pd.getVariable(), value);
build.addAction(new CIEnvironmentContributingAction(vars));
}
log.info("Received message with selector: " + pd.getSelector() + "\n" + formatMessage(message));
listener.getLogger().println("Received message with selector: " + pd.getSelector() + "\n" + formatMessage(message));
return value;
}
}
} while ((new Date().getTime() - startTime) < timeout && message != null);
log.info("Timed out waiting for message!");
listener.getLogger().println("Timed out waiting for message!");
} catch (Exception e) {
log.log(Level.SEVERE, "Unhandled exception waiting for message.", e);
} finally {
if (consumer != null) {
try {
consumer.close();
} catch (Exception e) {
}
}
if (connection != null) {
try {
connection.close();
} catch (Exception e) {
}
}
}
} else {
log.severe("One or more of the following is invalid (null): ip, user, password, topic, broker.");
}
return null;
}
use of com.redhat.jenkins.plugins.ci.CIEnvironmentContributingAction in project jms-messaging-plugin by jenkinsci.
the class FedMsgMessagingWorker method waitForMessage.
@Override
public String waitForMessage(Run<?, ?> build, TaskListener listener, ProviderData pdata) {
FedMsgSubscriberProviderData pd = (FedMsgSubscriberProviderData) pdata;
log.info("Waiting for message.");
listener.getLogger().println("Waiting for message.");
for (MsgCheck msgCheck : pd.getChecks()) {
log.info(" with check: " + msgCheck.toString());
listener.getLogger().println(" with check: " + msgCheck);
}
Integer timeout = (pd.getTimeout() != null ? pd.getTimeout() : FedMsgSubscriberProviderData.DEFAULT_TIMEOUT_IN_MINUTES);
log.info(" with timeout: " + timeout);
listener.getLogger().println(" with timeout: " + timeout);
ZMQ.Context lcontext = ZMQ.context(1);
ZMQ.Poller lpoller = lcontext.poller(1);
ZMQ.Socket lsocket = lcontext.socket(ZMQ.SUB);
String ltopic = getTopic(provider);
try {
ltopic = PluginUtils.getSubstitutedValue(getTopic(provider), build.getEnvironment(listener));
} catch (IOException | InterruptedException e) {
log.warning(e.getMessage());
}
lsocket.subscribe(ltopic.getBytes(StandardCharsets.UTF_8));
lsocket.setLinger(0);
lsocket.connect(provider.getHubAddr());
lpoller.register(lsocket, ZMQ.Poller.POLLIN);
ObjectMapper mapper = new ObjectMapper();
long startTime = new Date().getTime();
int timeoutInMs = timeout * 60 * 1000;
try {
while ((new Date().getTime() - startTime) < timeoutInMs) {
if (lpoller.poll(1000) > 0) {
if (lpoller.pollin(0)) {
ZMsg z = ZMsg.recvMsg(lpoller.getSocket(0));
listener.getLogger().println("Received a message");
String json = z.getLast().toString();
FedmsgMessage data = mapper.readValue(json, FedmsgMessage.class);
String body = data.getBodyJson();
if (!provider.verify(body, pd.getChecks(), jobname)) {
continue;
}
if (StringUtils.isNotEmpty(pd.getVariable())) {
EnvVars vars = new EnvVars();
vars.put(pd.getVariable(), body);
build.addAction(new CIEnvironmentContributingAction(vars));
}
return body;
}
}
}
log.severe("Timed out waiting for message!");
listener.getLogger().println("Timed out waiting for message!");
} catch (Exception e) {
log.log(Level.SEVERE, "Unhandled exception waiting for message.", e);
} finally {
try {
ZMQ.Socket s = lpoller.getSocket(0);
lpoller.unregister(s);
s.disconnect(provider.getHubAddr());
lsocket.unsubscribe(ltopic.getBytes(StandardCharsets.UTF_8));
lsocket.close();
lcontext.term();
} catch (Exception e) {
listener.getLogger().println("exception in finally");
}
}
return null;
}
Aggregations