Mailer.java 18.5 KB
Newer Older
K
kohsuke 已提交
1 2 3 4
package hudson.tasks;

import hudson.Launcher;
import hudson.Util;
K
kohsuke 已提交
5
import hudson.FilePath;
K
kohsuke 已提交
6 7 8 9 10 11
import hudson.model.Build;
import hudson.model.BuildListener;
import hudson.model.Descriptor;
import hudson.model.Result;
import hudson.model.User;
import hudson.model.UserPropertyDescriptor;
12
import hudson.scm.ChangeLogSet;
K
kohsuke 已提交
13 14 15 16
import hudson.scm.ChangeLogSet.Entry;
import org.apache.tools.ant.types.selectors.SelectorUtils;
import org.kohsuke.stapler.StaplerRequest;

17
import javax.mail.Address;
K
kohsuke 已提交
18 19 20 21 22 23 24 25 26 27 28 29 30
import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
31
import java.util.Date;
K
kohsuke 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Sends the build result in e-mail.
 *
 * @author Kohsuke Kawaguchi
 */
public class Mailer extends Publisher {
K
kohsuke 已提交
49

K
kohsuke 已提交
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
    private static final Logger LOGGER = Logger.getLogger(Mailer.class.getName());

    private static final int MAX_LOG_LINES = 250;

    /**
     * Whitespace-separated list of e-mail addresses that represent recipients.
     */
    public String recipients;

    /**
     * If true, only the first unstable build will be reported.
     */
    public boolean dontNotifyEveryUnstableBuild;

    /**
     * If true, individuals will receive e-mails regarding who broke the build.
     */
    public boolean sendToIndividuals;

    // TODO: left so that XStream won't get angry. figure out how to set the error handling behavior
    // in XStream.
    private transient String from;
    private transient String subject;
    private transient boolean failureOnly;

K
kohsuke 已提交
75
    public boolean perform(Build build, Launcher launcher, BuildListener listener) throws InterruptedException {
K
kohsuke 已提交
76
        try {
77
            MimeMessage mail = getMail(build, listener);
K
kohsuke 已提交
78
            if(mail!=null) {
79 80
                Address[] allRecipients = mail.getAllRecipients();
                if(allRecipients!=null) {
81
                StringBuffer buf = new StringBuffer("Sending e-mails to:");
82
                    for (Address a : allRecipients)
83 84 85
                    buf.append(' ').append(a);
                listener.getLogger().println(buf);
                Transport.send(mail);
86 87 88 89
                } else {
                    listener.getLogger().println("An attempt to send an e-mail"
                            + " to empty list of recipients, ignored.");
                }
K
kohsuke 已提交
90 91 92 93 94 95 96 97
            }
        } catch (MessagingException e) {
            e.printStackTrace( listener.error(e.getMessage()) );
        }

        return true;
    }

K
kohsuke 已提交
98
    private MimeMessage getMail(Build build, BuildListener listener) throws MessagingException, InterruptedException {
K
kohsuke 已提交
99
        if(build.getResult()==Result.FAILURE) {
100
            return createFailureMail(build, listener);
K
kohsuke 已提交
101 102 103 104 105
        }

        if(build.getResult()==Result.UNSTABLE) {
            Build prev = build.getPreviousBuild();
            if(!dontNotifyEveryUnstableBuild)
106
                return createUnstableMail(build, listener);
K
kohsuke 已提交
107 108
            if(prev!=null) {
                if(prev.getResult()==Result.SUCCESS)
109
                    return createUnstableMail(build, listener);
K
kohsuke 已提交
110 111 112 113 114 115 116
            }
        }

        if(build.getResult()==Result.SUCCESS) {
            Build prev = build.getPreviousBuild();
            if(prev!=null) {
                if(prev.getResult()==Result.FAILURE)
117
                    return createBackToNormalMail(build, "normal", listener);
K
kohsuke 已提交
118
                if(prev.getResult()==Result.UNSTABLE)
119
                    return createBackToNormalMail(build, "stable", listener);
K
kohsuke 已提交
120 121 122 123 124 125
            }
        }

        return null;
    }

126 127
    private MimeMessage createBackToNormalMail(Build build, String subject, BuildListener listener) throws MessagingException {
        MimeMessage msg = createEmptyMail(build, listener);
K
kohsuke 已提交
128 129 130 131 132 133 134 135 136

        msg.setSubject(getSubject(build,"Hudson build is back to "+subject +": "));
        StringBuffer buf = new StringBuffer();
        appendBuildUrl(build,buf);
        msg.setText(buf.toString());

        return msg;
    }

137 138
    private MimeMessage createUnstableMail(Build build, BuildListener listener) throws MessagingException {
        MimeMessage msg = createEmptyMail(build, listener);
K
kohsuke 已提交
139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154

        msg.setSubject(getSubject(build,"Hudson build became unstable: "));
        StringBuffer buf = new StringBuffer();
        appendBuildUrl(build,buf);
        msg.setText(buf.toString());

        return msg;
    }

    private void appendBuildUrl(Build build, StringBuffer buf) {
        String baseUrl = DESCRIPTOR.getUrl();
        if(baseUrl!=null) {
            buf.append("See ").append(baseUrl).append(Util.encode(build.getUrl())).append("\n\n");
        }
    }

K
kohsuke 已提交
155
    private MimeMessage createFailureMail(Build build, BuildListener listener) throws MessagingException, InterruptedException {
156
        MimeMessage msg = createEmptyMail(build, listener);
K
kohsuke 已提交
157 158 159 160 161 162

        msg.setSubject(getSubject(build, "Build failed in Hudson: "));

        StringBuffer buf = new StringBuffer();
        appendBuildUrl(build,buf);

163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
        boolean firstChange = true;
        for (ChangeLogSet.Entry entry : build.getChangeSet()) {
            if (firstChange) {
                firstChange = false;
                buf.append("Changes:\n\n");
            }
            buf.append('[');
            buf.append(entry.getAuthor().getFullName());
            buf.append("] ");
            String m = entry.getMsg();
            buf.append(m);
            if (!m.endsWith("\n")) {
                buf.append('\n');
            }
            buf.append('\n');
        }

        buf.append("------------------------------------------\n");
K
kohsuke 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200

        try {
            String log = build.getLog();
            String[] lines = log.split("\n");
            int start = 0;
            if (lines.length > MAX_LOG_LINES) {
                // Avoid sending enormous logs over email.
                // Interested users can always look at the log on the web server.
                buf.append("[...truncated " + (lines.length - MAX_LOG_LINES) + " lines...]\n");
                start = lines.length - MAX_LOG_LINES;
            }
            String workspaceUrl = null, artifactUrl = null;
            Pattern wsPattern = null;
            String baseUrl = DESCRIPTOR.getUrl();
            if (baseUrl != null) {
                // Hyperlink local file paths to the repository workspace or build artifacts.
                // Note that it is possible for a failure mail to refer to a file using a workspace
                // URL which has already been corrected in a subsequent build. To fix, archive.
                workspaceUrl = baseUrl + Util.encode(build.getProject().getUrl()) + "ws/";
                artifactUrl = baseUrl + Util.encode(build.getUrl()) + "artifact/";
K
kohsuke 已提交
201
                FilePath ws = build.getProject().getWorkspace();
K
kohsuke 已提交
202 203 204 205 206 207 208 209 210
                // Match either file or URL patterns, i.e. either
                // c:\hudson\workdir\jobs\foo\workspace\src\Foo.java
                // file:/c:/hudson/workdir/jobs/foo/workspace/src/Foo.java
                // will be mapped to one of:
                // http://host/hudson/job/foo/ws/src/Foo.java
                // http://host/hudson/job/foo/123/artifact/src/Foo.java
                // Careful with path separator between $1 and $2:
                // workspaceDir will not normally end with one;
                // workspaceDir.toURI() will end with '/' if and only if workspaceDir.exists() at time of call
K
kohsuke 已提交
211
                wsPattern = Pattern.compile("(" +
K
kohsuke 已提交
212
                    quoteRegexp(ws.getRemote()) + "|" + quoteRegexp(ws.toURI().toString()) + ")[/\\\\]?([^:#\\s]*)");
K
kohsuke 已提交
213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
            }
            for (int i = start; i < lines.length; i++) {
                String line = lines[i];
                if (wsPattern != null) {
                    // Perl: $line =~ s{$rx}{$path = $2; $path =~ s!\\\\!/!g; $workspaceUrl . $path}eg;
                    Matcher m = wsPattern.matcher(line);
                    int pos = 0;
                    while (m.find(pos)) {
                        String path = m.group(2).replace(File.separatorChar, '/');
                        String linkUrl = DESCRIPTOR.artifactMatches(path, build) ? artifactUrl : workspaceUrl;
                        // Append ' ' to make sure mail readers do not interpret following ':' as part of URL:
                        String prefix = line.substring(0, m.start()) + linkUrl + Util.encode(path) + ' ';
                        pos = prefix.length();
                        line = prefix + line.substring(m.end());
                        // XXX better style to reuse Matcher and fix offsets, but more work
                        m = wsPattern.matcher(line);
                    }
                }
                buf.append(line);
                buf.append('\n');
            }
        } catch (IOException e) {
            // somehow failed to read the contents of the log
            StringWriter sw = new StringWriter();
            e.printStackTrace(new PrintWriter(sw));
            buf.append("Failed to access build log\n\n").append(sw);
        }

        msg.setText(buf.toString());

        return msg;
    }

K
kohsuke 已提交
246
    private MimeMessage createEmptyMail(Build build, BuildListener listener) throws MessagingException {
K
kohsuke 已提交
247 248 249 250 251
        MimeMessage msg = new MimeMessage(DESCRIPTOR.createSession());
        // TODO: I'd like to put the URL to the page in here,
        // but how do I obtain that?
        msg.setContent("","text/plain");
        msg.setFrom(new InternetAddress(DESCRIPTOR.getAdminAddress()));
K
kohsuke 已提交
252
        msg.setSentDate(new Date());
K
kohsuke 已提交
253 254 255 256 257 258 259 260 261

        List<InternetAddress> rcp = new ArrayList<InternetAddress>();
        StringTokenizer tokens = new StringTokenizer(recipients);
        while(tokens.hasMoreTokens())
            rcp.add(new InternetAddress(tokens.nextToken()));
        if(sendToIndividuals) {
            Set<User> users = new HashSet<User>();
            for (Entry change : build.getChangeSet()) {
                User a = change.getAuthor();
K
kohsuke 已提交
262 263 264 265
                if(users.add(a)) {
                    String adrs = a.getProperty(UserProperty.class).getAddress();
                    if(adrs!=null)
                        rcp.add(new InternetAddress(adrs));
K
kohsuke 已提交
266 267 268
                    else {
                        listener.getLogger().println("Failed to send e-mail to "+a.getFullName()+" because no e-mail address is known, and no default e-mail domain is configured");
                    }
K
kohsuke 已提交
269
                }
K
kohsuke 已提交
270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
            }
        }
        msg.setRecipients(Message.RecipientType.TO, rcp.toArray(new InternetAddress[rcp.size()]));
        return msg;
    }

    public Descriptor<Publisher> getDescriptor() {
        return DESCRIPTOR;
    }

    private String getSubject(Build build, String caption) {
        return caption +build.getProject().getName()+" #"+build.getNumber();
    }


    public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();

    public static final class DescriptorImpl extends Descriptor<Publisher> {
288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305
        /**
         * The default e-mail address suffix appended to the user name found from changelog,
         * to send e-mails. Null if not configured.
         */
        private String defaultSuffix;

        /**
         * Hudson's own URL, to put into the e-mail.
         */
        private String hudsonUrl;

        /**
         * If non-null, use SMTP-AUTH with these information.
         */
        private String smtpAuthPassword,smtpAuthUsername;

        /**
         * The e-mail address that Hudson puts to "From:" field in outgoing e-mails.
K
kohsuke 已提交
306
         * Null if not configured.
307 308 309 310 311 312 313 314
         */
        private String adminAddress;

        /**
         * The SMTP server to use for sending e-mail. Null for default to the environment,
         * which is usually <tt>localhost</tt>.
         */
        private String smtpHost;
K
kohsuke 已提交
315 316 317

        public DescriptorImpl() {
            super(Mailer.class);
318
            load();
K
kohsuke 已提交
319 320
        }

321 322 323 324 325 326 327 328 329 330 331 332
        /**
         * For backward compatibility.
         */
        protected void convert(Map<String, Object> oldPropertyBag) {
            defaultSuffix = (String)oldPropertyBag.get("mail.default.suffix");
            hudsonUrl = (String)oldPropertyBag.get("mail.hudson.url");
            smtpAuthUsername = (String)oldPropertyBag.get("mail.hudson.smtpauth.username");
            smtpAuthPassword = (String)oldPropertyBag.get("mail.hudson.smtpauth.password");
            adminAddress = (String)oldPropertyBag.get("mail.admin.address");
            smtpHost = (String)oldPropertyBag.get("mail.smtp.host");
        }

K
kohsuke 已提交
333 334 335 336 337 338 339 340 341
        public String getDisplayName() {
            return "E-mail Notification";
        }

        public String getHelpFile() {
            return "/help/project-config/mailer.html";
        }

        public String getDefaultSuffix() {
342
            return defaultSuffix;
K
kohsuke 已提交
343 344 345 346 347
        }

        /** JavaMail session. */
        public Session createSession() {
            Properties props = new Properties(System.getProperties());
348 349
            if(smtpHost!=null)
                props.put("mail.smtp.host",smtpHost);
K
kohsuke 已提交
350 351 352 353 354 355 356 357 358 359 360 361 362 363

            return Session.getInstance(props,getAuthenticator());
        }

        private Authenticator getAuthenticator() {
            final String un = getSmtpAuthUserName();
            if(un==null)    return null;
            return new Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(getSmtpAuthUserName(),getSmtpAuthPassword());
                }
            };
        }

364
        public boolean configure(StaplerRequest req) throws FormException {
K
kohsuke 已提交
365
            // this code is brain dead
366 367 368
            smtpHost = nullify(req.getParameter("mailer_smtp_server"));
            adminAddress = req.getParameter("mailer_admin_address");
            defaultSuffix = nullify(req.getParameter("mailer_default_suffix"));
K
kohsuke 已提交
369 370 371
            String url = nullify(req.getParameter("mailer_hudson_url"));
            if(url!=null && !url.endsWith("/"))
                url += '/';
372
            hudsonUrl = url;
K
kohsuke 已提交
373

374 375 376 377 378 379
            if(req.getParameter("mailer.useSMTPAuth")!=null) {
                smtpAuthUsername = nullify(req.getParameter("mailer.SMTPAuth.userName"));
                smtpAuthPassword = nullify(req.getParameter("mailer.SMTPAuth.password"));
            } else {
                smtpAuthUsername = smtpAuthPassword = null;
            }
K
kohsuke 已提交
380 381 382 383 384 385 386 387 388 389 390

            save();
            return super.configure(req);
        }

        private String nullify(String v) {
            if(v!=null && v.length()==0)    v=null;
            return v;
        }

        public String getSmtpServer() {
391
            return smtpHost;
K
kohsuke 已提交
392 393 394
        }

        public String getAdminAddress() {
395
            String v = adminAddress;
K
kohsuke 已提交
396 397 398 399 400
            if(v==null)     v = "address not configured yet <nobody>";
            return v;
        }

        public String getUrl() {
401
            return hudsonUrl;
K
kohsuke 已提交
402 403 404
        }

        public String getSmtpAuthUserName() {
405
            return smtpAuthUsername;
K
kohsuke 已提交
406 407 408
        }

        public String getSmtpAuthPassword() {
409
            return smtpAuthPassword;
K
kohsuke 已提交
410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
        }

        /** Check whether a path (/-separated) will be archived. */
        public boolean artifactMatches(String path, Build build) {
            ArtifactArchiver aa = (ArtifactArchiver) build.getProject().getPublishers().get(ArtifactArchiver.DESCRIPTOR);
            if (aa == null) {
                LOGGER.finer("No ArtifactArchiver found");
                return false;
            }
            String artifacts = aa.getArtifacts();
            for (String include : artifacts.split("[, ]+")) {
                String pattern = include.replace(File.separatorChar, '/');
                if (pattern.endsWith("/")) {
                    pattern += "**";
                }
                if (SelectorUtils.matchPath(pattern, path)) {
                    LOGGER.log(Level.FINER, "DescriptorImpl.artifactMatches true for {0} against {1}", new Object[] {path, pattern});
                    return true;
                }
            }
            LOGGER.log(Level.FINER, "DescriptorImpl.artifactMatches for {0} matched none of {1}", new Object[] {path, artifacts});
            return false;
        }

        public Publisher newInstance(StaplerRequest req) {
            Mailer m = new Mailer();
            req.bindParameters(m,"mailer_");
            return m;
        }
    }

    /**
     * Per user property that is e-mail address.
     */
    public static class UserProperty extends hudson.model.UserProperty {
        public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();

        /**
         * The user's e-mail address.
         * Null to leave it to default.
         */
        private final String emailAddress;

        public UserProperty(String emailAddress) {
            this.emailAddress = emailAddress;
        }

        public String getAddress() {
            if(emailAddress!=null)
                return emailAddress;

            String ds = Mailer.DESCRIPTOR.getDefaultSuffix();
            if(ds!=null)
                return user.getId()+ds;
            else
                return null;
        }

        public DescriptorImpl getDescriptor() {
            return DESCRIPTOR;
        }

        public static final class DescriptorImpl extends UserPropertyDescriptor {
            public DescriptorImpl() {
                super(UserProperty.class);
            }

            public String getDisplayName() {
                return "E-mail";
            }

            public UserProperty newInstance(User user) {
                return new UserProperty(null);
            }

            public UserProperty newInstance(StaplerRequest req) throws FormException {
                return new UserProperty(req.getParameter("email.address"));
            }
        }
    }
K
kohsuke 已提交
490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510

    /**
     * Copied from JDK5, to avoid 5.0 dependency.
     */
    private static String quoteRegexp(String s) {
        int slashEIndex = s.indexOf("\\E");
        if (slashEIndex == -1)
            return "\\Q" + s + "\\E";

        StringBuilder sb = new StringBuilder(s.length() * 2);
        sb.append("\\Q");
        int current = 0;
        while ((slashEIndex = s.indexOf("\\E", current)) != -1) {
            sb.append(s.substring(current, slashEIndex));
            current = slashEIndex + 2;
            sb.append("\\E\\\\E\\Q");
        }
        sb.append(s.substring(current, s.length()));
        sb.append("\\E");
        return sb.toString();
    }
K
kohsuke 已提交
511
}