Search in sources :

Example 1 with CIEnvironmentContributingAction

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;
}
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 2 with CIEnvironmentContributingAction

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;
}
Also used : MessageConsumer(javax.jms.MessageConsumer) UnknownHostException(java.net.UnknownHostException) MapMessage(javax.jms.MapMessage) Message(javax.jms.Message) TextMessage(javax.jms.TextMessage) BytesMessage(javax.jms.BytesMessage) Connection(javax.jms.Connection) IOException(java.io.IOException) Date(java.util.Date) JMSException(javax.jms.JMSException) IOException(java.io.IOException) UnknownHostException(java.net.UnknownHostException) InvalidSelectorException(javax.jms.InvalidSelectorException) JMSSecurityException(javax.jms.JMSSecurityException) ActiveMQConnectionFactory(org.apache.activemq.ActiveMQConnectionFactory) ActiveMQSubscriberProviderData(com.redhat.jenkins.plugins.ci.provider.data.ActiveMQSubscriberProviderData) EnvVars(hudson.EnvVars) Topic(javax.jms.Topic) Queue(javax.jms.Queue) Session(javax.jms.Session) CIEnvironmentContributingAction(com.redhat.jenkins.plugins.ci.CIEnvironmentContributingAction)

Example 3 with CIEnvironmentContributingAction

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;
}
Also used : FedMsgSubscriberProviderData(com.redhat.jenkins.plugins.ci.provider.data.FedMsgSubscriberProviderData) IOException(java.io.IOException) MsgCheck(com.redhat.jenkins.plugins.ci.messaging.checks.MsgCheck) ZMsg(org.zeromq.ZMsg) Date(java.util.Date) IOException(java.io.IOException) EnvVars(hudson.EnvVars) FedmsgMessage(com.redhat.jenkins.plugins.ci.messaging.data.FedmsgMessage) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) ZMQ(org.zeromq.ZMQ) CIEnvironmentContributingAction(com.redhat.jenkins.plugins.ci.CIEnvironmentContributingAction)

Aggregations

CIEnvironmentContributingAction (com.redhat.jenkins.plugins.ci.CIEnvironmentContributingAction)3 EnvVars (hudson.EnvVars)3 IOException (java.io.IOException)3 Date (java.util.Date)3 MsgCheck (com.redhat.jenkins.plugins.ci.messaging.checks.MsgCheck)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 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 FedmsgMessage (com.redhat.jenkins.plugins.ci.messaging.data.FedmsgMessage)1 RabbitMQMessage (com.redhat.jenkins.plugins.ci.messaging.data.RabbitMQMessage)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 RabbitMQSubscriberProviderData (com.redhat.jenkins.plugins.ci.provider.data.RabbitMQSubscriberProviderData)1