Search in sources :

Example 1 with SendResult

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

the class ActiveMqMessagingWorker method sendMessage.

@Override
public SendResult sendMessage(Run<?, ?> build, TaskListener listener, ProviderData pdata) {
    ActiveMQPublisherProviderData pd = (ActiveMQPublisherProviderData) pdata;
    Connection connection = null;
    Session session = null;
    MessageProducer publisher = null;
    TextMessage message;
    String mesgId = "0";
    String mesgContent = "";
    try {
        String ltopic = PluginUtils.getSubstitutedValue(getTopic(provider), build.getEnvironment(listener));
        if (provider.getAuthenticationMethod() != null && ltopic != null && provider.getBroker() != null) {
            ActiveMQConnectionFactory connectionFactory = provider.getConnectionFactory();
            connection = connectionFactory.createConnection();
            connection.start();
            session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
            Destination destination = session.createTopic(ltopic);
            publisher = session.createProducer(destination);
            message = session.createTextMessage("");
            message.setJMSType(JSON_TYPE);
            TreeMap<String, String> envVarParts = new TreeMap<>();
            message.setStringProperty("CI_NAME", build.getParent().getName());
            envVarParts.put("CI_NAME", build.getParent().getName());
            if (pd.getMessageType() != null) {
                message.setStringProperty("CI_TYPE", pd.getMessageType().getMessage());
                envVarParts.put("CI_TYPE", pd.getMessageType().getMessage());
            }
            if (!build.isBuilding()) {
                String ciStatus = (build.getResult() == Result.SUCCESS ? "passed" : "failed");
                message.setStringProperty("CI_STATUS", ciStatus);
                envVarParts.put("CI_STATUS", ciStatus);
                envVarParts.put("BUILD_STATUS", build.getResult().toString());
            }
            EnvVars baseEnvVars = build.getEnvironment(listener);
            EnvVars envVars = new EnvVars();
            envVars.putAll(baseEnvVars);
            envVars.putAll(envVarParts);
            if (!StringUtils.isEmpty(pd.getMessageProperties())) {
                OrderedProperties p = new OrderedProperties();
                p.load(new StringReader(PluginUtils.getSubstitutedValue(pd.getMessageProperties(), envVars)));
                @SuppressWarnings("unchecked") Enumeration<String> e = p.propertyNames();
                while (e.hasMoreElements()) {
                    String key = e.nextElement();
                    if (!key.toLowerCase().startsWith("jms") || !setMessageHeader(message, key, p.getProperty(key), session)) {
                        EnvVars envVars2 = new EnvVars();
                        envVars2.putAll(baseEnvVars);
                        envVars2.putAll(envVarParts);
                        // This allows us to use recently added key/vals
                        // to be substituted
                        String val = PluginUtils.getSubstitutedValue(p.getProperty(key), envVars2);
                        message.setStringProperty(key, val);
                        envVarParts.put(key, val);
                    }
                }
            }
            EnvVars envVars2 = new EnvVars();
            envVars2.putAll(baseEnvVars);
            envVars2.putAll(envVarParts);
            message.setText(PluginUtils.getSubstitutedValue(pd.getMessageContent(), envVars2));
            publisher.send(message);
            mesgId = message.getJMSMessageID();
            mesgContent = message.getText();
            String messageType = "unknown type";
            if (pd.getMessageType() != null) {
                messageType = pd.getMessageType().toString();
            }
            log.info("Sent " + messageType + " message for job '" + build.getParent().getName() + "' to topic '" + ltopic + "':\n" + formatMessage(message));
        } else {
            log.severe("One or more of the following is invalid (null): user, password, topic, broker.");
            return new SendResult(false, mesgId, mesgContent);
        }
    } catch (Exception e) {
        if (pd.isFailOnError()) {
            log.severe("Unhandled exception in perform: ");
            log.severe(ExceptionUtils.getStackTrace(e));
            listener.fatalError("Unhandled exception in perform: ");
            listener.fatalError(ExceptionUtils.getStackTrace(e));
            return new SendResult(false, mesgId, mesgContent);
        } else {
            log.warning("Unhandled exception in perform: ");
            log.warning(ExceptionUtils.getStackTrace(e));
            listener.error("Unhandled exception in perform: ");
            listener.error(ExceptionUtils.getStackTrace(e));
            return new SendResult(true, mesgId, mesgContent);
        }
    } finally {
        if (publisher != null) {
            try {
                publisher.close();
            } catch (JMSException e) {
            }
        }
        if (session != null) {
            try {
                session.close();
            } catch (JMSException e) {
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (JMSException e) {
            }
        }
    }
    return new SendResult(true, mesgId, mesgContent);
}
Also used : Destination(javax.jms.Destination) Connection(javax.jms.Connection) JMSException(javax.jms.JMSException) TreeMap(java.util.TreeMap) 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) EnvVars(hudson.EnvVars) ActiveMQPublisherProviderData(com.redhat.jenkins.plugins.ci.provider.data.ActiveMQPublisherProviderData) SendResult(com.redhat.jenkins.plugins.ci.messaging.data.SendResult) StringReader(java.io.StringReader) OrderedProperties(com.redhat.utils.OrderedProperties) MessageProducer(javax.jms.MessageProducer) TextMessage(javax.jms.TextMessage) Session(javax.jms.Session)

Example 2 with SendResult

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

the class RabbitMQMessagingWorker method sendMessage.

@Override
public SendResult sendMessage(Run<?, ?> build, TaskListener listener, ProviderData pdata) {
    RabbitMQPublisherProviderData pd = (RabbitMQPublisherProviderData) pdata;
    try {
        if (connection == null || !connection.isOpen()) {
            connect();
        }
        if (channel == null || !channel.isOpen()) {
            this.channel = connection.createChannel();
            log.info("Channel created.");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    }
    String body = "";
    String msgId = "";
    // Fedora messaging wire format support
    Map<String, Object> headers = new HashMap<>();
    if (pd.isFedoraMessaging()) {
        headers.put("fedora_messaging_severity", pd.getSeverity());
        headers.put("fedora_messaging_schema", pd.getSchema());
        headers.put("sent_at", ZonedDateTime.now().toString());
    }
    System.out.println(headers);
    try {
        EnvVars env = new EnvVars();
        env.putAll(build.getEnvironment(listener));
        env.put("CI_NAME", build.getParent().getName());
        if (!build.isBuilding()) {
            env.put("CI_STATUS", (build.getResult() == Result.SUCCESS ? "passed" : "failed"));
            env.put("BUILD_STATUS", build.getResult().toString());
        }
        RabbitMQMessage msg = new RabbitMQMessage(PluginUtils.getSubstitutedValue(getTopic(provider), build.getEnvironment(listener)), PluginUtils.getSubstitutedValue(pd.getMessageContent(), env));
        msg.setTimestamp(System.currentTimeMillis() / 1000L);
        body = msg.getBodyJson();
        msgId = msg.getMsgId();
        try {
            channel.exchangeDeclarePassive(exchangeName);
            channel.basicPublish(exchangeName, msg.getTopic(), new AMQP.BasicProperties.Builder().headers(headers).messageId(msgId).build(), body.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            if (pd.isFailOnError()) {
                log.severe("Unhandled exception in perform: Failed to send message!");
                return new SendResult(false, msgId, body);
            }
        }
        log.fine("Message headers:\n" + headers);
        log.fine("JSON message:\n" + msg.toJson());
        listener.getLogger().println("Message id: " + msg.getMsgId());
        listener.getLogger().println("Message topic: " + msg.getTopic());
        listener.getLogger().println("Message headers:\n" + headers);
        listener.getLogger().println("JSON message body:\n" + body);
    } catch (Exception e) {
        if (pd.isFailOnError()) {
            log.severe("Unhandled exception in perform: ");
            log.severe(ExceptionUtils.getStackTrace(e));
            listener.fatalError("Unhandled exception in perform: ");
            listener.fatalError(ExceptionUtils.getStackTrace(e));
            return new SendResult(false, msgId, body);
        } else {
            log.warning("Unhandled exception in perform: ");
            log.warning(ExceptionUtils.getStackTrace(e));
            listener.error("Unhandled exception in perform: ");
            listener.error(ExceptionUtils.getStackTrace(e));
            return new SendResult(true, msgId, body);
        }
    } finally {
        try {
            channel.close();
        } catch (Exception e) {
            log.warning("Unhandled exception when closing channel: ");
            log.warning(ExceptionUtils.getStackTrace(e));
            listener.getLogger().println("exception in finally");
        }
    }
    return new SendResult(true, msgId, body);
}
Also used : EnvVars(hudson.EnvVars) HashMap(java.util.HashMap) AMQP(com.rabbitmq.client.AMQP) SendResult(com.redhat.jenkins.plugins.ci.messaging.data.SendResult) IOException(java.io.IOException) RabbitMQPublisherProviderData(com.redhat.jenkins.plugins.ci.provider.data.RabbitMQPublisherProviderData) IOException(java.io.IOException) RabbitMQMessage(com.redhat.jenkins.plugins.ci.messaging.data.RabbitMQMessage)

Example 3 with SendResult

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

the class FedMsgMessagingWorker method sendMessage.

@Override
public SendResult sendMessage(Run<?, ?> build, TaskListener listener, ProviderData pdata) {
    FedMsgPublisherProviderData pd = (FedMsgPublisherProviderData) pdata;
    ZMQ.Context context = ZMQ.context(1);
    ZMQ.Socket sock = context.socket(ZMQ.PUB);
    sock.setLinger(0);
    log.fine("pub address: " + provider.getPubAddr());
    sock.connect(provider.getPubAddr());
    try {
        Thread.sleep(5000);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    String body = "";
    String msgId = "";
    try {
        EnvVars env = new EnvVars();
        env.putAll(build.getEnvironment(listener));
        env.put("CI_NAME", build.getParent().getName());
        if (!build.isBuilding()) {
            env.put("CI_STATUS", (build.getResult() == Result.SUCCESS ? "passed" : "failed"));
            env.put("BUILD_STATUS", Objects.requireNonNull(build.getResult()).toString());
        }
        FedmsgMessage fm = new FedmsgMessage(PluginUtils.getSubstitutedValue(getTopic(provider), build.getEnvironment(listener)), PluginUtils.getSubstitutedValue(pd.getMessageContent(), env));
        fm.setTimestamp(System.currentTimeMillis());
        // Use toString() instead of getBodyJson so that message ID is included and sent.
        body = fm.toJson();
        msgId = fm.getMsgId();
        if (!sock.sendMore(fm.getTopic()) && pd.isFailOnError()) {
            log.severe("Unhandled exception in perform: Failed to send message (topic)!");
            return new SendResult(false, msgId, body);
        }
        if (!sock.send(body) && pd.isFailOnError()) {
            log.severe("Unhandled exception in perform: Failed to send message (body)!");
            return new SendResult(false, msgId, body);
        }
        log.fine("JSON message body:\n" + body);
        listener.getLogger().println("JSON message body:\n" + body);
    } catch (Exception e) {
        if (pd.isFailOnError()) {
            log.severe("Unhandled exception in perform: ");
            log.severe(ExceptionUtils.getStackTrace(e));
            listener.fatalError("Unhandled exception in perform: ");
            listener.fatalError(ExceptionUtils.getStackTrace(e));
            return new SendResult(false, msgId, body);
        } else {
            log.warning("Unhandled exception in perform: ");
            log.warning(ExceptionUtils.getStackTrace(e));
            listener.error("Unhandled exception in perform: ");
            listener.error(ExceptionUtils.getStackTrace(e));
            return new SendResult(true, msgId, body);
        }
    } finally {
        sock.close();
        context.term();
    }
    return new SendResult(true, msgId, body);
}
Also used : EnvVars(hudson.EnvVars) FedmsgMessage(com.redhat.jenkins.plugins.ci.messaging.data.FedmsgMessage) SendResult(com.redhat.jenkins.plugins.ci.messaging.data.SendResult) FedMsgPublisherProviderData(com.redhat.jenkins.plugins.ci.provider.data.FedMsgPublisherProviderData) IOException(java.io.IOException) ZMQ(org.zeromq.ZMQ)

Example 4 with SendResult

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

the class MessageUtils method sendMessage.

public static SendResult sendMessage(Run<?, ?> build, TaskListener listener, ProviderData pdata) {
    String startMessage = "Sending message for job '" + build.getParent().getName() + "'.";
    log.info(startMessage);
    listener.getLogger().println(startMessage);
    GlobalCIConfiguration config = GlobalCIConfiguration.get();
    JMSMessagingWorker worker = config.getProvider(pdata.getName()).createWorker(pdata, build.getParent().getName());
    SendResult sendResult = worker.sendMessage(build, listener, pdata);
    String completedMessage = "Sent successfully with messageId: " + sendResult.getMessageId();
    log.info(completedMessage);
    listener.getLogger().println(completedMessage);
    return sendResult;
}
Also used : JMSMessagingWorker(com.redhat.jenkins.plugins.ci.messaging.JMSMessagingWorker) SendResult(com.redhat.jenkins.plugins.ci.messaging.data.SendResult) GlobalCIConfiguration(com.redhat.jenkins.plugins.ci.GlobalCIConfiguration)

Aggregations

SendResult (com.redhat.jenkins.plugins.ci.messaging.data.SendResult)4 EnvVars (hudson.EnvVars)3 IOException (java.io.IOException)3 AMQP (com.rabbitmq.client.AMQP)1 GlobalCIConfiguration (com.redhat.jenkins.plugins.ci.GlobalCIConfiguration)1 JMSMessagingWorker (com.redhat.jenkins.plugins.ci.messaging.JMSMessagingWorker)1 FedmsgMessage (com.redhat.jenkins.plugins.ci.messaging.data.FedmsgMessage)1 RabbitMQMessage (com.redhat.jenkins.plugins.ci.messaging.data.RabbitMQMessage)1 ActiveMQPublisherProviderData (com.redhat.jenkins.plugins.ci.provider.data.ActiveMQPublisherProviderData)1 FedMsgPublisherProviderData (com.redhat.jenkins.plugins.ci.provider.data.FedMsgPublisherProviderData)1 RabbitMQPublisherProviderData (com.redhat.jenkins.plugins.ci.provider.data.RabbitMQPublisherProviderData)1 OrderedProperties (com.redhat.utils.OrderedProperties)1 StringReader (java.io.StringReader)1 UnknownHostException (java.net.UnknownHostException)1 HashMap (java.util.HashMap)1 TreeMap (java.util.TreeMap)1 Connection (javax.jms.Connection)1 Destination (javax.jms.Destination)1 InvalidSelectorException (javax.jms.InvalidSelectorException)1 JMSException (javax.jms.JMSException)1