Github user trixpan commented on a diff in the pull request: https://github.com/apache/nifi/pull/483#discussion_r70612563 --- Diff: nifi-nar-bundles/nifi-email-bundle/nifi-email-processors/src/main/java/org/apache/nifi/processors/email/smtp/handler/SMTPMessageHandlerFactory.java --- @@ -0,0 +1,147 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one or more + * contributor license agreements. See the NOTICE file distributed with + * this work for additional information regarding copyright ownership. + * The ASF licenses this file to You 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 + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * 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 org.apache.nifi.processors.email.smtp.handler; + +import java.io.IOException; +import java.io.InputStream; +import java.security.cert.X509Certificate; +import java.util.concurrent.LinkedBlockingQueue; +import java.util.concurrent.TimeUnit; + +import org.apache.nifi.logging.ComponentLog; +import org.apache.nifi.stream.io.ByteArrayOutputStream; +import org.apache.nifi.util.StopWatch; +import org.subethamail.smtp.DropConnectionException; +import org.subethamail.smtp.MessageContext; +import org.subethamail.smtp.MessageHandler; +import org.subethamail.smtp.MessageHandlerFactory; +import org.subethamail.smtp.RejectException; +import org.subethamail.smtp.TooMuchDataException; +import org.subethamail.smtp.server.SMTPServer; + +import org.apache.nifi.processors.email.smtp.event.SmtpEvent; + + +public class SMTPMessageHandlerFactory implements MessageHandlerFactory { + final LinkedBlockingQueue<SmtpEvent> incomingMessages; + final ComponentLog logger; + + public SMTPMessageHandlerFactory(LinkedBlockingQueue<SmtpEvent> incomingMessages, ComponentLog logger) { + this.incomingMessages = incomingMessages; + this.logger = logger; + } + + @Override + public MessageHandler create(MessageContext messageContext) { + return new Handler(messageContext, incomingMessages, logger); + } + + class Handler implements MessageHandler { + final MessageContext messageContext; + String from; + String recipient; + byte [] messageBody; + + + public Handler(MessageContext messageContext, LinkedBlockingQueue<SmtpEvent> incomingMessages, ComponentLog logger){ + this.messageContext = messageContext; + } + + @Override + public void from(String from) throws RejectException { + // TODO: possibly whitelist senders? + this.from = from; + } + + @Override + public void recipient(String recipient) throws RejectException { + // TODO: possibly whitelist receivers? + this.recipient = recipient; + } + + @Override + public void data(InputStream inputStream) throws RejectException, TooMuchDataException, IOException { + // Start counting the timer... + + StopWatch watch = new StopWatch(false); + + SMTPServer server = messageContext.getSMTPServer(); + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + + byte [] buffer = new byte[1024]; + int rd; + + while ((rd = inputStream.read(buffer, 0, buffer.length)) != -1) { + baos.write(buffer, 0, rd); + } + if (baos.getBufferLength() > server.getMaxMessageSize()) { + throw new TooMuchDataException("Data exceeds the amount allowed."); + } + + baos.flush(); + this.messageBody = baos.toByteArray(); + + + X509Certificate[] certificates = new X509Certificate[]{}; + + String remoteIP = messageContext.getRemoteAddress().toString(); + String helo = messageContext.getHelo(); + if (messageContext.getTlsPeerCertificates() != null ){ + certificates = (X509Certificate[]) messageContext.getTlsPeerCertificates().clone(); + } + + SmtpEvent message = new SmtpEvent(remoteIP, helo, from, recipient, certificates, messageBody); + try { + // Try to queue the message back to the NiFi session + incomingMessages.put(message); + } catch (InterruptedException e) { + // Throws an error to the incoming server alerting about issues queuing the message in NiFi + logger.error("Hit an error sending message back to NiFi main thread {}. Sending and error back to SMTP client and discarding message", new Object [] {e}); + throw new DropConnectionException(451, "NiFi something went wrong while processing you message, please retry again later"); + } + + // Once message has been sent to the queue, it should be processed by NiFi onTrigger, + // a flowfile created and its processed status updated before an acknowledgment is + // given back to the SMTP client + try { + synchronized(message) { + while(! message.getProcessed()) { + // Check to see if it is too late... + final long serverTimeout = TimeUnit.NANOSECONDS.convert(messageContext.getSMTPServer().getConnectionTimeout(), TimeUnit.MILLISECONDS); + if ( watch.getElapsed(TimeUnit.MILLISECONDS) <= serverTimeout) { + // Will should allow for a couple of retries; + message.wait(messageContext.getSMTPServer().getConnectionTimeout() / 20); + } else { + logger.error("Did not receive the onTrigger reponse within the acceptable timeframes"); + throw new DropConnectionException(451, "The processing of your message timed-out, we may have received it but you better off sending it again"); --- End diff -- @JPercivall also worth noting that currently processed means "added to a NiFi Flowfile (not SmtpEvent message reaching its complete state (e.g., with all private values sets)). The way I read (PLEASE, correct me if I'm wrong) the code the following happens: Handler is created, a new latch created and then its methods are called so that MAIL FROM, RCPT TO commands are processed. The processing follows with DATA, creating and populating and SmtpEvent, including the previously created latch. offering the message with a timeout back to onTrigger. If the offer fails a exception informs the sender message wasn't queued and requires resending it. So unless I am missing other scenarios, the only race conditions I see are: Race 1 onTriggers takes to long: In this case, if the latch isn't opened within the timeframe, the await will just timeout. The first action the data() will do after the timeout is to remove the message from the queue, Race 2 What if onTrigger is just doing poll of that very same message when this (`data()` timout) occurs. My understanding was that the LinkedBlockingQueue is capable of handling this implicitly and the object will either explicitly removed by a faster Handler or poll'ed (i.e. removed) from the queue by a faster onTrigger. So in both cases the object would be removed from the queue and the client informed of the timeout with a "please retry". Data is not lost, although it may duplicated. (Isn't that what people call at least once delivery guarantee?) Also, my understanding is that subethasmtp will not arbitrarily terminate the thread, instead it will honor it until done() is completed. At least this is what I understood from the following debugging screenshots (again, feel free to correct as I am learning lots in this whole PR): ![image](https://cloud.githubusercontent.com/assets/3108527/16801919/dedb4ae8-4940-11e6-8f97-ca9f308b1732.png) Note how x = 0 still going to be executed despite the server having been disconnected me already. If the above race conditions cover pretty much what concerns you may I ask what do you think about: 1. Change processed to an AtomicInteger; 2. add another step to the latch: _Remaining count = 2_ latch is created and sent to onTrigger (as currently exists) Once message makes to onTrigger and flowfile dissection is complete, the onTrigger completes its Flowfile work and triggers the latch _(remaining count = 1). onTriger then `await(serverTimeout + 5ms ) ` at the latch _(still remaining count = 1)._ The + 5ms should mean (perhaps an incorrect assumption?) the latch opening would always occur after the disconnect is completed). Back in `done()`, done identifies which way was used to exit the Handler (i.e. reply code 421, 423, 451 or 250) and based on the response, sets `AtomicInteger processed` to the code and releases the last step of the latch (remaining count = 0) as soon it times out or is released, onTrigger queries the processed flag. If set back to false (or , the flowfile now an error was returned is rolled back. The only caveat I would mention is that if I understand correctly we making the processor synchronous and perhaps performance will suffer a bit?
--- If your project is set up for it, you can reply to this email and have your reply appear on GitHub as well. If your project does not have this feature enabled and wishes so, or if the feature is enabled but not working, please contact infrastructure at infrastruct...@apache.org or file a JIRA ticket with INFRA. ---