Search in sources :

Example 1 with RabbitMQSubscriberProviderData

use of com.redhat.jenkins.plugins.ci.provider.data.RabbitMQSubscriberProviderData in project jms-messaging-plugin by jenkinsci.

the class RabbitMQMessagingWorker method receive.

@Override
public void receive(String jobname, ProviderData pdata) {
    RabbitMQSubscriberProviderData pd = (RabbitMQSubscriberProviderData) pdata;
    int timeout = (pd.getTimeout() != null ? pd.getTimeout() : RabbitMQSubscriberProviderData.DEFAULT_TIMEOUT_IN_MINUTES) * 60 * 1000;
    if (interrupt) {
        log.info("we have been interrupted at start of receive");
        return;
    }
    // subscribe job
    while (!subscribe(jobname)) {
        if (!Thread.currentThread().isInterrupted()) {
            try {
                int WAIT_SECONDS = 2;
                Thread.sleep(WAIT_SECONDS * 1000);
            } catch (InterruptedException e) {
                // We were interrupted while waiting to retry. We will
                // jump ship on the next iteration.
                // NB: The interrupt flag was cleared when
                // InterruptedException was thrown. We have to
                // re-install it to make sure we eventually leave this
                // thread.
                Thread.currentThread().interrupt();
            }
        }
    }
    long lastSeenMessage = new Date().getTime();
    try {
        while ((new Date().getTime() - lastSeenMessage) < timeout) {
            if (!messageQueue.isEmpty()) {
                RabbitMQMessage data = messageQueue.poll();
                // Reset timer
                lastSeenMessage = data.getTimestamp().getTime();
                // 
                if (provider.verify(data.getBodyJson(), pd.getChecks(), jobname)) {
                    Map<String, String> params = new HashMap<>();
                    params.put("CI_MESSAGE", data.getBodyJson());
                    trigger(jobname, data.getBodyJson(), params);
                }
                channel.basicAck(data.getDeliveryTag(), false);
            } else {
                if (interrupt) {
                    log.info("We have been interrupted...");
                    break;
                }
            }
            TimeUnit.MILLISECONDS.sleep(500);
        }
    } catch (Exception e) {
        // for more info
        if (e.getClass() == InterruptedException.class) {
            Thread.currentThread().interrupt();
        }
        if (!Thread.currentThread().isInterrupted()) {
            // Something other than an interrupt causes this.
            // Unsubscribe, but stay in our loop and try to reconnect..
            log.log(Level.WARNING, "JMS exception raised, going to re-subscribe for job '" + jobname + "'.", e);
            // Try again next time.
            unsubscribe(jobname);
        }
    }
}
Also used : HashMap(java.util.HashMap) RabbitMQSubscriberProviderData(com.redhat.jenkins.plugins.ci.provider.data.RabbitMQSubscriberProviderData) Date(java.util.Date) RabbitMQMessage(com.redhat.jenkins.plugins.ci.messaging.data.RabbitMQMessage) IOException(java.io.IOException)

Example 2 with RabbitMQSubscriberProviderData

use of com.redhat.jenkins.plugins.ci.provider.data.RabbitMQSubscriberProviderData 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;
}
Also used : DeliverCallback(com.rabbitmq.client.DeliverCallback) Date(java.util.Date) SendResult(com.redhat.jenkins.plugins.ci.messaging.data.SendResult) ZonedDateTime(java.time.ZonedDateTime) RabbitMQSubscriberProviderData(com.redhat.jenkins.plugins.ci.provider.data.RabbitMQSubscriberProviderData) HashMap(java.util.HashMap) Connection(com.rabbitmq.client.Connection) StringUtils(org.apache.commons.lang3.StringUtils) Level(java.util.logging.Level) CancelCallback(com.rabbitmq.client.CancelCallback) Map(java.util.Map) EnvVars(hudson.EnvVars) TaskListener(hudson.model.TaskListener) ConnectionFactory(com.rabbitmq.client.ConnectionFactory) RabbitMQPublisherProviderData(com.redhat.jenkins.plugins.ci.provider.data.RabbitMQPublisherProviderData) Jenkins(jenkins.model.Jenkins) ExceptionUtils(org.apache.commons.lang.exception.ExceptionUtils) RabbitMQMessage(com.redhat.jenkins.plugins.ci.messaging.data.RabbitMQMessage) MsgCheck(com.redhat.jenkins.plugins.ci.messaging.checks.MsgCheck) PluginUtils(com.redhat.utils.PluginUtils) IOException(java.io.IOException) UUID(java.util.UUID) Logger(java.util.logging.Logger) StandardCharsets(java.nio.charset.StandardCharsets) Run(hudson.model.Run) TimeUnit(java.util.concurrent.TimeUnit) Result(hudson.model.Result) Channel(com.rabbitmq.client.Channel) CIEnvironmentContributingAction(com.redhat.jenkins.plugins.ci.CIEnvironmentContributingAction) ProviderData(com.redhat.jenkins.plugins.ci.provider.data.ProviderData) AMQP(com.rabbitmq.client.AMQP) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) DeliverCallback(com.rabbitmq.client.DeliverCallback) MsgCheck(com.redhat.jenkins.plugins.ci.messaging.checks.MsgCheck) IOException(java.io.IOException) RabbitMQMessage(com.redhat.jenkins.plugins.ci.messaging.data.RabbitMQMessage) Date(java.util.Date) EnvVars(hudson.EnvVars) RabbitMQSubscriberProviderData(com.redhat.jenkins.plugins.ci.provider.data.RabbitMQSubscriberProviderData) CancelCallback(com.rabbitmq.client.CancelCallback) CIEnvironmentContributingAction(com.redhat.jenkins.plugins.ci.CIEnvironmentContributingAction)

Example 3 with RabbitMQSubscriberProviderData

use of com.redhat.jenkins.plugins.ci.provider.data.RabbitMQSubscriberProviderData in project jms-messaging-plugin by jenkinsci.

the class MessageProviderMigrator method updateCIMessageSubscriberBuilder.

private static boolean updateCIMessageSubscriberBuilder(AbstractProject<?, ?> p, CIMessageSubscriberBuilder builder) {
    if (builder.getProviderData() == null) {
        if (builder.getProviderName() == null) {
            builder.setProviderName(GlobalCIConfiguration.get().getConfigs().get(0).getName());
        }
        JMSMessagingProvider prov = GlobalCIConfiguration.get().getProvider(builder.getProviderName());
        if (prov instanceof ActiveMqMessagingProvider) {
            ActiveMQSubscriberProviderData apd = new ActiveMQSubscriberProviderData(builder.getProviderName());
            apd.setOverrides(builder.getOverrides());
            apd.setSelector(builder.getSelector());
            apd.setChecks(builder.getChecks());
            apd.setVariable(builder.getVariable());
            apd.setTimeout(builder.getTimeout());
            builder.setProviderData(apd);
        } else if (prov instanceof FedMsgMessagingProvider) {
            FedMsgSubscriberProviderData fpd = new FedMsgSubscriberProviderData(builder.getProviderName());
            fpd.setOverrides(builder.getOverrides());
            fpd.setVariable(builder.getVariable());
            fpd.setTimeout(builder.getTimeout());
            builder.setProviderData(fpd);
        } else {
            RabbitMQSubscriberProviderData rpd = new RabbitMQSubscriberProviderData(builder.getProviderName());
            rpd.setOverrides(builder.getOverrides());
            rpd.setVariable(builder.getVariable());
            rpd.setTimeout(builder.getTimeout());
            builder.setProviderData(rpd);
        }
        try {
            p.save();
            return true;
        } catch (IOException e) {
            log.log(Level.WARNING, "Failed to save project", e);
        }
    }
    return false;
}
Also used : FedMsgSubscriberProviderData(com.redhat.jenkins.plugins.ci.provider.data.FedMsgSubscriberProviderData) ActiveMQSubscriberProviderData(com.redhat.jenkins.plugins.ci.provider.data.ActiveMQSubscriberProviderData) RabbitMQSubscriberProviderData(com.redhat.jenkins.plugins.ci.provider.data.RabbitMQSubscriberProviderData) IOException(java.io.IOException)

Aggregations

RabbitMQSubscriberProviderData (com.redhat.jenkins.plugins.ci.provider.data.RabbitMQSubscriberProviderData)3 IOException (java.io.IOException)3 RabbitMQMessage (com.redhat.jenkins.plugins.ci.messaging.data.RabbitMQMessage)2 Date (java.util.Date)2 HashMap (java.util.HashMap)2 AMQP (com.rabbitmq.client.AMQP)1 CancelCallback (com.rabbitmq.client.CancelCallback)1 Channel (com.rabbitmq.client.Channel)1 Connection (com.rabbitmq.client.Connection)1 ConnectionFactory (com.rabbitmq.client.ConnectionFactory)1 DeliverCallback (com.rabbitmq.client.DeliverCallback)1 CIEnvironmentContributingAction (com.redhat.jenkins.plugins.ci.CIEnvironmentContributingAction)1 MsgCheck (com.redhat.jenkins.plugins.ci.messaging.checks.MsgCheck)1 SendResult (com.redhat.jenkins.plugins.ci.messaging.data.SendResult)1 ActiveMQSubscriberProviderData (com.redhat.jenkins.plugins.ci.provider.data.ActiveMQSubscriberProviderData)1 FedMsgSubscriberProviderData (com.redhat.jenkins.plugins.ci.provider.data.FedMsgSubscriberProviderData)1 ProviderData (com.redhat.jenkins.plugins.ci.provider.data.ProviderData)1 RabbitMQPublisherProviderData (com.redhat.jenkins.plugins.ci.provider.data.RabbitMQPublisherProviderData)1 PluginUtils (com.redhat.utils.PluginUtils)1 EnvVars (hudson.EnvVars)1