001/**
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *      http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing, software
013 * distributed under the License is distributed on an "AS IS" BASIS,
014 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
015 * See the License for the specific language governing permissions and
016 * limitations under the License.
017 */
018
019package org.apache.oozie.action.email;
020
021import java.io.File;
022import java.io.IOException;
023import java.io.InputStream;
024import java.io.OutputStream;
025import java.net.URI;
026import java.net.URISyntaxException;
027import java.util.ArrayList;
028import java.util.List;
029import java.util.Properties;
030
031import javax.activation.DataHandler;
032import javax.activation.DataSource;
033import javax.mail.Authenticator;
034import javax.mail.Message;
035import javax.mail.Message.RecipientType;
036import javax.mail.MessagingException;
037import javax.mail.Multipart;
038import javax.mail.NoSuchProviderException;
039import javax.mail.PasswordAuthentication;
040import javax.mail.Session;
041import javax.mail.Transport;
042import javax.mail.internet.AddressException;
043import javax.mail.internet.InternetAddress;
044import javax.mail.internet.MimeBodyPart;
045import javax.mail.internet.MimeMessage;
046import javax.mail.internet.MimeMultipart;
047
048import org.apache.hadoop.conf.Configuration;
049import org.apache.hadoop.fs.FileSystem;
050import org.apache.hadoop.fs.Path;
051import org.apache.oozie.action.ActionExecutor;
052import org.apache.oozie.action.ActionExecutorException;
053import org.apache.oozie.action.ActionExecutorException.ErrorType;
054import org.apache.oozie.client.WorkflowAction;
055import org.apache.oozie.service.ConfigurationService;
056import org.apache.oozie.service.HadoopAccessorException;
057import org.apache.oozie.service.Services;
058import org.apache.oozie.service.HadoopAccessorService;
059import org.apache.oozie.util.XLog;
060import org.apache.oozie.util.XmlUtils;
061import org.jdom.Element;
062import org.jdom.Namespace;
063
064/**
065 * Email action executor. It takes to, cc, bcc addresses along with a subject and body and sends
066 * out an email.
067 */
068public class EmailActionExecutor extends ActionExecutor {
069
070    public static final String CONF_PREFIX = "oozie.email.";
071    public static final String EMAIL_SMTP_HOST = CONF_PREFIX + "smtp.host";
072    public static final String EMAIL_SMTP_PORT = CONF_PREFIX + "smtp.port";
073    public static final String EMAIL_SMTP_AUTH = CONF_PREFIX + "smtp.auth";
074    public static final String EMAIL_SMTP_USER = CONF_PREFIX + "smtp.username";
075    public static final String EMAIL_SMTP_PASS = CONF_PREFIX + "smtp.password";
076    public static final String EMAIL_SMTP_FROM = CONF_PREFIX + "from.address";
077    public static final String EMAIL_ATTACHMENT_ENABLED = CONF_PREFIX + "attachment.enabled";
078
079    private final static String TO = "to";
080    private final static String CC = "cc";
081    private final static String BCC = "bcc";
082    private final static String SUB = "subject";
083    private final static String BOD = "body";
084    private final static String ATTACHMENT = "attachment";
085    private final static String COMMA = ",";
086    private final static String CONTENT_TYPE = "content_type";
087
088    private final static String DEFAULT_CONTENT_TYPE = "text/plain";
089    private XLog LOG = XLog.getLog(getClass());
090    public static final String EMAIL_ATTACHMENT_ERROR_MSG =
091            "\n Note: This email is missing configured email attachments "
092            + "as sending attachments in email action is disabled in the Oozie server. "
093            + "It could be for security compliance with data protection or other reasons";
094
095    public EmailActionExecutor() {
096        super("email");
097    }
098
099    @Override
100    public void initActionType() {
101        super.initActionType();
102    }
103
104    @Override
105    public void start(Context context, WorkflowAction action) throws ActionExecutorException {
106        try {
107            context.setStartData("-", "-", "-");
108            Element actionXml = XmlUtils.parseXml(action.getConf());
109            validateAndMail(context, actionXml);
110            context.setExecutionData("OK", null);
111        }
112        catch (Exception ex) {
113            throw convertException(ex);
114        }
115    }
116
117    @SuppressWarnings("unchecked")
118    protected void validateAndMail(Context context, Element element) throws ActionExecutorException {
119        // The XSD does the min/max occurrence validation for us.
120        Namespace ns = element.getNamespace();
121        String tos[] = new String[0];
122        String ccs[] = new String[0];
123        String bccs[] ;
124        String subject = "";
125        String body = "";
126        String attachments[] = new String[0];
127        String contentType;
128        Element child = null;
129
130        // <to> - One ought to exist.
131        String text = element.getChildTextTrim(TO, ns);
132        if (text.isEmpty()) {
133            throw new ActionExecutorException(ErrorType.ERROR, "EM001", "No receipents were specified in the to-address field.");
134        }
135        tos = text.split(COMMA);
136
137        // <cc> - Optional, but only one ought to exist.
138        try {
139            ccs = element.getChildTextTrim(CC, ns).split(COMMA);
140        } catch (Exception e) {
141            // It is alright for cc to be given empty or not be present.
142            ccs = new String[0];
143        }
144
145        // <bcc> - Optional, but only one ought to exist.
146        try {
147            bccs = element.getChildTextTrim(BCC, ns).split(COMMA);
148        } catch (Exception e) {
149            // It is alright for bcc to be given empty or not be present.
150            bccs = new String[0];
151        }
152        // <subject> - One ought to exist.
153        subject = element.getChildTextTrim(SUB, ns);
154
155        // <body> - One ought to exist.
156        body = element.getChildTextTrim(BOD, ns);
157
158        // <attachment> - Optional
159        String attachment = element.getChildTextTrim(ATTACHMENT, ns);
160        if(attachment != null) {
161            attachments = attachment.split(COMMA);
162        }
163
164        contentType = element.getChildTextTrim(CONTENT_TYPE, ns);
165        if (contentType == null || contentType.isEmpty()) {
166            contentType = DEFAULT_CONTENT_TYPE;
167        }
168
169        // All good - lets try to mail!
170        email(tos, ccs, bccs, subject, body, attachments, contentType, context.getWorkflow().getUser());
171    }
172
173    public void email(String[] to, String[] cc, String subject, String body, String[] attachments,
174                      String contentType, String user) throws ActionExecutorException {
175        email(to, cc, new String[0], subject, body, attachments, contentType, user);
176    }
177
178    public void email(String[] to, String[] cc, String[] bcc, String subject, String body, String[] attachments,
179                      String contentType, String user) throws ActionExecutorException {
180        // Get mailing server details.
181        String smtpHost = getOozieConf().get(EMAIL_SMTP_HOST, "localhost");
182        String smtpPort = getOozieConf().get(EMAIL_SMTP_PORT, "25");
183        Boolean smtpAuth = getOozieConf().getBoolean(EMAIL_SMTP_AUTH, false);
184        String smtpUser = getOozieConf().get(EMAIL_SMTP_USER, "");
185        String smtpPassword = ConfigurationService.getPassword(EMAIL_SMTP_PASS, "");
186        String fromAddr = getOozieConf().get(EMAIL_SMTP_FROM, "oozie@localhost");
187
188        Properties properties = new Properties();
189        properties.setProperty("mail.smtp.host", smtpHost);
190        properties.setProperty("mail.smtp.port", smtpPort);
191        properties.setProperty("mail.smtp.auth", smtpAuth.toString());
192
193        Session session;
194        // Do not use default instance (i.e. Session.getDefaultInstance)
195        // (cause it may lead to issues when used second time).
196        if (!smtpAuth) {
197            session = Session.getInstance(properties);
198        } else {
199            session = Session.getInstance(properties, new JavaMailAuthenticator(smtpUser, smtpPassword));
200        }
201
202        Message message = new MimeMessage(session);
203        InternetAddress from;
204        List<InternetAddress> toAddrs = new ArrayList<InternetAddress>(to.length);
205        List<InternetAddress> ccAddrs = new ArrayList<InternetAddress>(cc.length);
206        List<InternetAddress> bccAddrs = new ArrayList<InternetAddress>(bcc.length);
207
208        try {
209            from = new InternetAddress(fromAddr);
210            message.setFrom(from);
211        } catch (AddressException e) {
212            throw new ActionExecutorException(ErrorType.ERROR, "EM002", "Bad from address specified in ${oozie.email.from.address}.", e);
213        } catch (MessagingException e) {
214            throw new ActionExecutorException(ErrorType.ERROR, "EM003", "Error setting a from address in the message.", e);
215        }
216
217        try {
218            // Add all <to>
219            for (String toStr : to) {
220                toAddrs.add(new InternetAddress(toStr.trim()));
221            }
222            message.addRecipients(RecipientType.TO, toAddrs.toArray(new InternetAddress[0]));
223
224            // Add all <cc>
225            for (String ccStr : cc) {
226                ccAddrs.add(new InternetAddress(ccStr.trim()));
227            }
228            message.addRecipients(RecipientType.CC, ccAddrs.toArray(new InternetAddress[0]));
229
230            // Add all <bcc>
231            for (String bccStr : bcc) {
232                bccAddrs.add(new InternetAddress(bccStr.trim()));
233            }
234            message.addRecipients(RecipientType.BCC, bccAddrs.toArray(new InternetAddress[0]));
235
236            // Set subject
237            message.setSubject(subject);
238
239            // when there is attachment
240            if (attachments != null && attachments.length > 0 && ConfigurationService.getBoolean(EMAIL_ATTACHMENT_ENABLED)) {
241                Multipart multipart = new MimeMultipart();
242
243                // Set body text
244                MimeBodyPart bodyTextPart = new MimeBodyPart();
245                bodyTextPart.setText(body);
246                multipart.addBodyPart(bodyTextPart);
247
248                for (String attachment : attachments) {
249                    URI attachUri = new URI(attachment);
250                    if (attachUri.getScheme() != null && attachUri.getScheme().equals("file")) {
251                        throw new ActionExecutorException(ErrorType.ERROR, "EM008",
252                                "Encountered an error when attaching a file. A local file cannot be attached:"
253                                        + attachment);
254                    }
255                    MimeBodyPart messageBodyPart = new MimeBodyPart();
256                    DataSource source = new URIDataSource(attachUri, user);
257                    messageBodyPart.setDataHandler(new DataHandler(source));
258                    messageBodyPart.setFileName(new File(attachment).getName());
259                    multipart.addBodyPart(messageBodyPart);
260                }
261                message.setContent(multipart);
262            }
263            else {
264                if (attachments != null && attachments.length > 0 && !ConfigurationService.getBoolean(EMAIL_ATTACHMENT_ENABLED)) {
265                    body = body + EMAIL_ATTACHMENT_ERROR_MSG;
266                }
267                message.setContent(body, contentType);
268            }
269        }
270        catch (AddressException e) {
271            throw new ActionExecutorException(ErrorType.ERROR, "EM004", "Bad address format in <to> or <cc> or <bcc>.", e);
272        }
273        catch (MessagingException e) {
274            throw new ActionExecutorException(ErrorType.ERROR, "EM005", "An error occured while adding recipients.", e);
275        }
276        catch (URISyntaxException e) {
277            throw new ActionExecutorException(ErrorType.ERROR, "EM008", "Encountered an error when attaching a file", e);
278        }
279        catch (HadoopAccessorException e) {
280            throw new ActionExecutorException(ErrorType.ERROR, "EM008", "Encountered an error when attaching a file", e);
281        }
282
283        try {
284            // Send over SMTP Transport
285            // (Session+Message has adequate details.)
286            Transport.send(message);
287        } catch (NoSuchProviderException e) {
288            throw new ActionExecutorException(ErrorType.ERROR, "EM006", "Could not find an SMTP transport provider to email.", e);
289        } catch (MessagingException e) {
290            throw new ActionExecutorException(ErrorType.ERROR, "EM007", "Encountered an error while sending the email message over SMTP.", e);
291        }
292    }
293
294    @Override
295    public void end(Context context, WorkflowAction action) throws ActionExecutorException {
296        String externalStatus = action.getExternalStatus();
297        WorkflowAction.Status status = externalStatus.equals("OK") ? WorkflowAction.Status.OK :
298                                       WorkflowAction.Status.ERROR;
299        context.setEndData(status, getActionSignal(status));
300    }
301
302    @Override
303    public void check(Context context, WorkflowAction action)
304            throws ActionExecutorException {
305
306    }
307
308    @Override
309    public void kill(Context context, WorkflowAction action)
310            throws ActionExecutorException {
311
312    }
313
314    @Override
315    public boolean isCompleted(String externalStatus) {
316        return true;
317    }
318
319    public static class JavaMailAuthenticator extends Authenticator {
320
321        String user;
322        String password;
323
324        public JavaMailAuthenticator(String user, String password) {
325            this.user = user;
326            this.password = password;
327        }
328
329        @Override
330        protected PasswordAuthentication getPasswordAuthentication() {
331           return new PasswordAuthentication(user, password);
332        }
333    }
334
335    class URIDataSource implements DataSource{
336
337        HadoopAccessorService has = Services.get().get(HadoopAccessorService.class);
338        FileSystem fs;
339        URI uri;
340        public URIDataSource(URI uri, String user) throws HadoopAccessorException {
341            this.uri = uri;
342            Configuration fsConf = has.createJobConf(uri.getAuthority());
343            fs = has.createFileSystem(user, uri, fsConf);
344        }
345
346        @Override
347        public InputStream getInputStream() throws IOException {
348            return fs.open(new Path(uri));
349        }
350
351        @Override
352        public OutputStream getOutputStream() throws IOException {
353            return fs.create(new Path(uri));
354        }
355
356        @Override
357        public String getContentType() {
358            return "application/octet-stream";
359        }
360
361        @Override
362        public String getName() {
363            return uri.getPath();
364        }
365    }
366}