FilePath.java 40.3 KB
Newer Older
K
kohsuke 已提交
1 2
package hudson;

3 4 5 6
import hudson.Launcher.LocalLauncher;
import hudson.Launcher.RemoteLauncher;
import hudson.model.Hudson;
import hudson.model.TaskListener;
K
kohsuke 已提交
7 8
import hudson.remoting.Callable;
import hudson.remoting.Channel;
9
import hudson.remoting.DelegatingCallable;
10
import hudson.remoting.Future;
K
kohsuke 已提交
11 12 13
import hudson.remoting.Pipe;
import hudson.remoting.RemoteOutputStream;
import hudson.remoting.VirtualChannel;
K
kohsuke 已提交
14
import hudson.util.FormFieldValidator;
15
import hudson.util.IOException2;
16
import hudson.util.StreamResource;
K
kohsuke 已提交
17 18
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
19
import org.apache.tools.ant.Project;
K
kohsuke 已提交
20
import org.apache.tools.ant.taskdefs.Copy;
21
import org.apache.tools.ant.taskdefs.Untar;
K
kohsuke 已提交
22
import org.apache.tools.ant.types.FileSet;
23 24
import org.apache.tools.tar.TarEntry;
import org.apache.tools.tar.TarOutputStream;
25 26
import org.apache.tools.zip.ZipOutputStream;
import org.apache.tools.zip.ZipEntry;
K
kohsuke 已提交
27

28 29
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
K
kohsuke 已提交
30
import java.io.File;
K
kohsuke 已提交
31 32 33 34
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
K
kohsuke 已提交
35
import java.io.IOException;
K
kohsuke 已提交
36 37 38 39 40 41
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.Writer;
42 43
import java.io.StringWriter;
import java.io.PrintWriter;
K
kohsuke 已提交
44
import java.io.OutputStreamWriter;
45
import java.net.URI;
K
kohsuke 已提交
46 47
import java.util.ArrayList;
import java.util.List;
K
kohsuke 已提交
48
import java.util.StringTokenizer;
49 50
import java.util.Arrays;
import java.util.Comparator;
K
kohsuke 已提交
51
import java.util.regex.Pattern;
52
import java.util.concurrent.ExecutionException;
53 54
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
55 56
import java.util.zip.GZIPOutputStream;
import java.util.zip.GZIPInputStream;
K
kohsuke 已提交
57 58

/**
K
kohsuke 已提交
59
 * {@link File} like object with remoting support.
K
kohsuke 已提交
60 61
 *
 * <p>
K
kohsuke 已提交
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
 * Unlike {@link File}, which always implies a file path on the current computer,
 * {@link FilePath} represents a file path on a specific slave or the master.
 *
 * Despite that, {@link FilePath} can be used much like {@link File}. It exposes
 * a bunch of operations (and we should add more operations as long as they are
 * generally useful), and when invoked against a file on a remote node, {@link FilePath}
 * executes the necessary code remotely, thereby providing semi-transparent file
 * operations.
 *
 * <h2>Using {@link FilePath} smartly</h2>
 * <p>
 * The transparency makes it easy to write plugins without worrying too much about
 * remoting, by making it works like NFS, where remoting happens at the file-system
 * later.
 *
 * <p>
 * But one should note that such use of remoting may not be optional. Sometimes,
 * it makes more sense to move some computation closer to the data, as opposed to
 * move the data to the computation. For example, if you are just computing a MD5
 * digest of a file, then it would make sense to do the digest on the host where
 * the file is located, as opposed to send the whole data to the master and do MD5
 * digesting there.
 *
 * <p>
 * {@link FilePath} supports this "code migration" by in the
 * {@link #act(FileCallable)} method. One can pass in a custom implementation
 * of {@link FileCallable}, to be executed on the node where the data is located.
 * The following code shows the example:
 *
 * <pre>
 * FilePath file = ...;
 *
 * // make 'file' a fresh empty directory.
 * file.act(new FileCallable&lt;Void>() {
 *   // if 'file' is on a different node, this FileCallable will
 *   // be transfered to that node and executed there.
 *   public Void invoke(File f,VirtualChannel channel) {
 *     // f and file represents the same thing
 *     f.deleteContents();
 *     f.mkdirs();
 *   }
 * });
 * </pre>
K
kohsuke 已提交
105 106
 *
 * <p>
K
kohsuke 已提交
107
 * When {@link FileCallable} is transfered to a remote node, it will be done so
E
elefevre 已提交
108
 * by using the same Java serialization scheme that the remoting module uses.
K
kohsuke 已提交
109 110 111 112 113 114 115
 * See {@link Channel} for more about this. 
 *
 * <p>
 * {@link FilePath} itself can be sent over to a remote node as a part of {@link Callable}
 * serialization. For example, sending a {@link FilePath} of a remote node to that
 * node causes {@link FilePath} to become "local". Similarly, sending a
 * {@link FilePath} that represents the local computer causes it to become "remote."
K
kohsuke 已提交
116 117 118
 *
 * @author Kohsuke Kawaguchi
 */
K
kohsuke 已提交
119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
public final class FilePath implements Serializable {
    /**
     * When this {@link FilePath} represents the remote path,
     * this field is always non-null on master (the field represents
     * the channel to the remote slave.) When transferred to a slave via remoting,
     * this field reverts back to null, since it's transient.
     *
     * When this {@link FilePath} represents a path on the master,
     * this field is null on master. When transferred to a slave via remoting,
     * this field becomes non-null, representing the {@link Channel}
     * back to the master.
     *
     * This is used to determine whether we are running on the master or the slave.
     */
    private transient VirtualChannel channel;

    // since the platform of the slave might be different, can't use java.io.File
K
kohsuke 已提交
136 137
    private final String remote;

K
kohsuke 已提交
138 139 140 141 142 143 144
    /**
     * Creates a {@link FilePath} that represents a path on the given node.
     *
     * @param channel
     *      To create a path that represents a remote path, pass in a {@link Channel}
     *      that's connected to that machine. If null, that means the local file path.
     */
K
kohsuke 已提交
145 146
    public FilePath(VirtualChannel channel, String remote) {
        this.channel = channel;
K
kohsuke 已提交
147 148 149 150
        this.remote = remote;
    }

    /**
K
kohsuke 已提交
151 152 153 154 155
     * To create {@link FilePath} that represents a "local" path.
     *
     * <p>
     * A "local" path means a file path on the computer where the
     * constructor invocation happened.
K
kohsuke 已提交
156
     */
K
kohsuke 已提交
157 158 159
    public FilePath(File localPath) {
        this.channel = null;
        this.remote = localPath.getPath();
K
kohsuke 已提交
160 161 162
    }

    public FilePath(FilePath base, String rel) {
K
kohsuke 已提交
163
        this.channel = base.channel;
K
kohsuke 已提交
164 165 166 167
        if(rel.startsWith("/") || DRIVE_PATTERN.matcher(rel).matches()) {
            // absolute
            this.remote = rel;
        } else 
K
kohsuke 已提交
168 169 170 171 172 173 174
        if(base.isUnix()) {
            this.remote = base.remote+'/'+rel;
        } else {
            this.remote = base.remote+'\\'+rel;
        }
    }

K
kohsuke 已提交
175 176
    private static final Pattern DRIVE_PATTERN = Pattern.compile("[A-Za-z]:\\\\.+");

K
kohsuke 已提交
177 178 179 180
    /**
     * Checks if the remote path is Unix.
     */
    private boolean isUnix() {
181 182 183 184
        // if the path represents a local path, there' no need to guess.
        if(!isRemote())
            return File.pathSeparatorChar!=';';
            
185 186 187 188 189 190
        // note that we can't use the usual File.pathSeparator and etc., as the OS of
        // the machine where this code runs and the OS that this FilePath refers to may be different.

        // Windows absolute path is 'X:\...', so this is usually a good indication of Windows path
        if(remote.length()>3 && remote.charAt(1)==':' && remote.charAt(2)=='\\')
            return false;
K
kohsuke 已提交
191 192 193 194 195 196 197 198 199
        // Windows can handle '/' as a path separator but Unix can't,
        // so err on Unix side
        return remote.indexOf("\\")==-1;
    }

    public String getRemote() {
        return remote;
    }

200 201 202 203 204 205 206 207 208 209 210
    /**
     * Creates a zip file from this directory or a file and sends that to the given output stream.
     */
    public void createZipArchive(OutputStream os) throws IOException, InterruptedException {
        final OutputStream out = (channel!=null)?new RemoteOutputStream(os):os;
        act(new FileCallable<Void>() {
            private transient byte[] buf;
            public Void invoke(File f, VirtualChannel channel) throws IOException {
                buf = new byte[8192];

                ZipOutputStream zip = new ZipOutputStream(out);
211
                zip.setEncoding(System.getProperty("file.encoding"));
212 213 214 215 216 217 218
                scan(f,zip,"");
                zip.close();
                return null;
            }

            private void scan(File f, ZipOutputStream zip, String path) throws IOException {
                if(f.isDirectory()) {
K
kohsuke 已提交
219 220
                    zip.putNextEntry(new ZipEntry(path+f.getName()+'/'));
                    zip.closeEntry();
221 222 223 224 225 226 227 228 229 230 231 232
                    for( File child : f.listFiles() )
                        scan(child,zip,path+f.getName()+'/');
                } else {
                    zip.putNextEntry(new ZipEntry(path+f.getName()));
                    FileInputStream in = new FileInputStream(f);
                    int len;
                    while((len=in.read(buf))>0)
                        zip.write(buf,0,len);
                    in.close();
                    zip.closeEntry();
                }
            }
K
kohsuke 已提交
233 234
            
            private static final long serialVersionUID = 1L;
235 236 237
        });
    }

K
kohsuke 已提交
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258
    /**
     * Creates a zip file from this directory by only including the files that match the given glob.
     *
     * @param glob
     *      Ant style glob, like "**&#x2F;*.xml". If empty or null, this method
     *      works like {@link #createZipArchive(OutputStream)}
     *
     * @since 1.129
     */
    public void createZipArchive(OutputStream os, final String glob) throws IOException, InterruptedException {
        if(glob==null || glob.length()==0) {
            createZipArchive(os);
            return;
        }
        
        final OutputStream out = (channel!=null)?new RemoteOutputStream(os):os;
        act(new FileCallable<Void>() {
            public Void invoke(File dir, VirtualChannel channel) throws IOException {
                byte[] buf = new byte[8192];

                ZipOutputStream zip = new ZipOutputStream(out);
259
                zip.setEncoding(System.getProperty("file.encoding"));
K
kohsuke 已提交
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277
                for( String entry : glob(dir,glob) ) {
                    zip.putNextEntry(new ZipEntry(dir.getName()+'/'+entry));
                    FileInputStream in = new FileInputStream(new File(dir,entry));
                    int len;
                    while((len=in.read(buf))>0)
                        zip.write(buf,0,len);
                    in.close();
                    zip.closeEntry();
                }

                zip.close();
                return null;
            }

            private static final long serialVersionUID = 1L;
        });
    }

K
kohsuke 已提交
278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304
    /**
     * Code that gets executed on the machine where the {@link FilePath} is local.
     * Used to act on {@link FilePath}.
     *
     * @see FilePath#act(FileCallable)
     */
    public static interface FileCallable<T> extends Serializable {
        /**
         * Performs the computational task on the node where the data is located.
         *
         * @param f
         *      {@link File} that represents the local file that {@link FilePath} has represented.
         * @param channel
         *      The "back pointer" of the {@link Channel} that represents the communication
         *      with the node from where the code was sent.
         */
        T invoke(File f, VirtualChannel channel) throws IOException;
    }

    /**
     * Executes some program on the machine that this {@link FilePath} exists,
     * so that one can perform local file operations.
     */
    public <T> T act(final FileCallable<T> callable) throws IOException, InterruptedException {
        if(channel!=null) {
            // run this on a remote system
            try {
305
                return channel.call(new FileCallableWrapper<T>(callable));
K
kohsuke 已提交
306 307 308 309 310 311 312 313 314 315
            } catch (IOException e) {
                // wrap it into a new IOException so that we get the caller's stack trace as well.
                throw new IOException2("remote file operation failed",e);
            }
        } else {
            // the file is on the local machine.
            return callable.invoke(new File(remote), Hudson.MasterComputer.localChannel);
        }
    }

316 317 318 319 320 321 322 323 324 325 326 327 328 329
    /**
     * Executes some program on the machine that this {@link FilePath} exists,
     * so that one can perform local file operations.
     */
    public <T> Future<T> actAsync(final FileCallable<T> callable) throws IOException, InterruptedException {
        try {
            return (channel!=null ? channel : Hudson.MasterComputer.localChannel)
                .callAsync(new FileCallableWrapper<T>(callable));
        } catch (IOException e) {
            // wrap it into a new IOException so that we get the caller's stack trace as well.
            throw new IOException2("remote file operation failed",e);
        }
    }

K
kohsuke 已提交
330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
    /**
     * Executes some program on the machine that this {@link FilePath} exists,
     * so that one can perform local file operations.
     */
    public <V,E extends Throwable> V act(Callable<V,E> callable) throws IOException, InterruptedException, E {
        if(channel!=null) {
            // run this on a remote system
            return channel.call(callable);
        } else {
            // the file is on the local machine
            return callable.call();
        }
    }

    /**
     * Converts this file to the URI, relative to the machine
     * on which this file is available.
     */
    public URI toURI() throws IOException, InterruptedException {
        return act(new FileCallable<URI>() {
            public URI invoke(File f, VirtualChannel channel) {
                return f.toURI();
            }
        });
    }

K
kohsuke 已提交
356 357 358
    /**
     * Creates this directory.
     */
K
kohsuke 已提交
359
    public void mkdirs() throws IOException, InterruptedException {
360
        if(!act(new FileCallable<Boolean>() {
K
kohsuke 已提交
361
            public Boolean invoke(File f, VirtualChannel channel) throws IOException {
362 363 364 365 366 367 368 369 370 371 372
                if(f.mkdirs() || f.exists())
                    return true;    // OK

                // following Ant <mkdir> task to avoid possible race condition.
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    // ignore
                }

                return f.mkdirs() || f.exists();
K
kohsuke 已提交
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
            }
        }))
            throw new IOException("Failed to mkdirs: "+remote);
    }

    /**
     * Deletes this directory, including all its contents recursively.
     */
    public void deleteRecursive() throws IOException, InterruptedException {
        act(new FileCallable<Void>() {
            public Void invoke(File f, VirtualChannel channel) throws IOException {
                Util.deleteRecursive(f);
                return null;
            }
        });
K
kohsuke 已提交
388 389 390 391 392
    }

    /**
     * Deletes all the contents of this directory, but not the directory itself
     */
K
kohsuke 已提交
393 394 395 396 397 398 399
    public void deleteContents() throws IOException, InterruptedException {
        act(new FileCallable<Void>() {
            public Void invoke(File f, VirtualChannel channel) throws IOException {
                Util.deleteContentsRecursive(f);
                return null;
            }
        });
K
kohsuke 已提交
400 401 402 403 404 405 406 407
    }

    /**
     * Gets just the file name portion.
     *
     * This method assumes that the file name is the same between local and remote.
     */
    public String getName() {
408 409 410 411 412
        String r = remote;
        if(r.endsWith("\\") || r.endsWith("/"))
            r = r.substring(0,r.length()-1);

        int len = r.length()-1;
K
kohsuke 已提交
413
        while(len>=0) {
414
            char ch = r.charAt(len);
K
kohsuke 已提交
415 416 417 418 419
            if(ch=='\\' || ch=='/')
                break;
            len--;
        }

420
        return r.substring(len+1);
K
kohsuke 已提交
421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
    }

    /**
     * The same as {@code new FilePath(this,rel)} but more OO.
     */
    public FilePath child(String rel) {
        return new FilePath(this,rel);
    }

    /**
     * Gets the parent file.
     */
    public FilePath getParent() {
        int len = remote.length()-1;
        while(len>=0) {
            char ch = remote.charAt(len);
            if(ch=='\\' || ch=='/')
                break;
            len--;
        }

K
kohsuke 已提交
442
        return new FilePath( channel, remote.substring(0,len) );
K
kohsuke 已提交
443 444 445 446 447
    }

    /**
     * Creates a temporary file.
     */
K
kohsuke 已提交
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465
    public FilePath createTempFile(final String prefix, final String suffix) throws IOException, InterruptedException {
        try {
            return new FilePath(this,act(new FileCallable<String>() {
                public String invoke(File dir, VirtualChannel channel) throws IOException {
                    File f = File.createTempFile(prefix, suffix, dir);
                    return f.getName();
                }
            }));
        } catch (IOException e) {
            throw new IOException2("Failed to create a temp file on "+remote,e);
        }
    }

    /**
     * Creates a temporary file in this directory and set the contents by the
     * given text (encoded in the platform default encoding)
     */
    public FilePath createTextTempFile(final String prefix, final String suffix, final String contents) throws IOException, InterruptedException {
466 467 468 469 470 471 472 473
        return createTextTempFile(prefix,suffix,contents,true);
    }

    /**
     * Creates a temporary file in this directory and set the contents by the
     * given text (encoded in the platform default encoding)
     */
    public FilePath createTextTempFile(final String prefix, final String suffix, final String contents, final boolean inThisDirectory) throws IOException, InterruptedException {
K
kohsuke 已提交
474
        try {
K
kohsuke 已提交
475
            return new FilePath(channel,act(new FileCallable<String>() {
K
kohsuke 已提交
476
                public String invoke(File dir, VirtualChannel channel) throws IOException {
477 478
                    if(!inThisDirectory)
                        dir = null;
479 480
                    else
                        dir.mkdirs();
481 482 483 484 485 486 487

                    File f;
                    try {
                        f = File.createTempFile(prefix, suffix, dir);
                    } catch (IOException e) {
                        throw new IOException2("Failed to create a temporary directory in "+dir,e);
                    }
K
kohsuke 已提交
488 489 490 491 492

                    Writer w = new FileWriter(f);
                    w.write(contents);
                    w.close();

K
kohsuke 已提交
493
                    return f.getAbsolutePath();
K
kohsuke 已提交
494 495
                }
            }));
K
kohsuke 已提交
496
        } catch (IOException e) {
K
kohsuke 已提交
497
            throw new IOException2("Failed to create a temp file on "+remote,e);
K
kohsuke 已提交
498
        }
K
kohsuke 已提交
499 500 501 502 503
    }

    /**
     * Deletes this file.
     */
K
kohsuke 已提交
504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520
    public boolean delete() throws IOException, InterruptedException {
        return act(new FileCallable<Boolean>() {
            public Boolean invoke(File f, VirtualChannel channel) throws IOException {
                return f.delete();
            }
        });
    }

    /**
     * Checks if the file exists.
     */
    public boolean exists() throws IOException, InterruptedException {
        return act(new FileCallable<Boolean>() {
            public Boolean invoke(File f, VirtualChannel channel) throws IOException {
                return f.exists();
            }
        });
K
kohsuke 已提交
521 522
    }

K
kohsuke 已提交
523 524 525 526 527 528 529 530 531 532 533 534
    /**
     * Gets the last modified time stamp of this file, by using the clock
     * of the machine where this file actually resides.
     *
     * @see File#lastModified()
     */
    public long lastModified() throws IOException, InterruptedException {
        return act(new FileCallable<Long>() {
            public Long invoke(File f, VirtualChannel channel) throws IOException {
                return f.lastModified();
            }
        });
K
kohsuke 已提交
535 536
    }

K
kohsuke 已提交
537 538 539 540 541 542 543 544 545
    /**
     * Checks if the file is a directory.
     */
    public boolean isDirectory() throws IOException, InterruptedException {
        return act(new FileCallable<Boolean>() {
            public Boolean invoke(File f, VirtualChannel channel) throws IOException {
                return f.isDirectory();
            }
        });
K
kohsuke 已提交
546
    }
K
kohsuke 已提交
547 548 549
    
    /**
     * Returns the file size in bytes.
K
kohsuke 已提交
550 551
     *
     * @since 1.129
K
kohsuke 已提交
552 553 554 555 556 557 558 559
     */
    public long length() throws IOException, InterruptedException {
        return act(new FileCallable<Long>() {
            public Long invoke(File f, VirtualChannel channel) throws IOException {
                return f.length();
            }
        });
    }
K
kohsuke 已提交
560

K
kohsuke 已提交
561
    /**
K
kohsuke 已提交
562 563 564 565 566 567 568
     * List up files in this directory.
     *
     * @param filter
     *      The optional filter used to narrow down the result.
     *      If non-null, must be {@link Serializable}.
     *      If this {@link FilePath} represents a remote path,
     *      the filter object will be executed on the remote machine.
K
kohsuke 已提交
569
     */
K
kohsuke 已提交
570 571 572 573 574 575 576 577 578 579 580 581 582 583 584
    public List<FilePath> list(final FileFilter filter) throws IOException, InterruptedException {
        return act(new FileCallable<List<FilePath>>() {
            public List<FilePath> invoke(File f, VirtualChannel channel) throws IOException {
                File[] children = f.listFiles(filter);
                if(children ==null)     return null;

                ArrayList<FilePath> r = new ArrayList<FilePath>(children.length);
                for (File child : children)
                    r.add(new FilePath(child));

                return r;
            }
        });
    }

K
kohsuke 已提交
585 586 587 588 589
    /**
     * List up files in this directory that matches the given Ant-style filter.
     *
     * @param includes
     *      See {@link FileSet} for the syntax. String like "foo/*.zip".
K
kohsuke 已提交
590 591
     * @return
     *      can be empty but always non-null.
K
kohsuke 已提交
592 593 594 595
     */
    public FilePath[] list(final String includes) throws IOException, InterruptedException {
        return act(new FileCallable<FilePath[]>() {
            public FilePath[] invoke(File f, VirtualChannel channel) throws IOException {
K
kohsuke 已提交
596
                String[] files = glob(f,includes);
K
kohsuke 已提交
597 598 599 600 601 602 603 604 605 606

                FilePath[] r = new FilePath[files.length];
                for( int i=0; i<r.length; i++ )
                    r[i] = new FilePath(new File(f,files[i]));

                return r;
            }
        });
    }

K
kohsuke 已提交
607 608 609 610
    /**
     * Runs Ant glob expansion.
     */
    private static String[] glob(File dir, String includes) {
611
        FileSet fs = Util.createFileSet(dir,includes);
K
kohsuke 已提交
612 613 614 615 616
        DirectoryScanner ds = fs.getDirectoryScanner(new Project());
        String[] files = ds.getIncludedFiles();
        return files;
    }

K
kohsuke 已提交
617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640
    /**
     * Reads this file.
     */
    public InputStream read() throws IOException {
        if(channel==null)
            return new FileInputStream(new File(remote));

        final Pipe p = Pipe.createRemoteToLocal();
        channel.callAsync(new Callable<Void,IOException>() {
            public Void call() throws IOException {
                FileInputStream fis = new FileInputStream(new File(remote));
                Util.copyStream(fis,p.getOut());
                fis.close();
                p.getOut().close();
                return null;
            }
        });

        return p.getIn();
    }

    /**
     * Writes to this file.
     * If this file already exists, it will be overwritten.
K
kohsuke 已提交
641
     * If the directory doesn't exist, it will be created.
K
kohsuke 已提交
642
     */
643
    public OutputStream write() throws IOException, InterruptedException {
644 645 646 647 648
        if(channel==null) {
            File f = new File(remote);
            f.getParentFile().mkdirs();
            return new FileOutputStream(f);
        }
K
kohsuke 已提交
649

650 651
        return channel.call(new Callable<OutputStream,IOException>() {
            public OutputStream call() throws IOException {
K
kohsuke 已提交
652 653 654
                File f = new File(remote);
                f.getParentFile().mkdirs();
                FileOutputStream fos = new FileOutputStream(f);
655
                return new RemoteOutputStream(fos);
K
kohsuke 已提交
656 657 658 659
            }
        });
    }

K
kohsuke 已提交
660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687
    /**
     * Overwrites this file by placing the given String as the content.
     *
     * @param encoding
     *      Null to use the platform default encoding.
     * @since 1.105
     */
    public void write(final String content, final String encoding) throws IOException, InterruptedException {
        channel.call(new Callable<Void,IOException>() {
            public Void call() throws IOException {
                File f = new File(remote);
                f.getParentFile().mkdirs();
                FileOutputStream fos = new FileOutputStream(f);
                try {
                    Writer w;
                    if(encoding!=null)
                    w = new OutputStreamWriter(fos, encoding);
                    else
                        w = new OutputStreamWriter(fos);
                    w.write(content);
                } finally {
                    fos.close();
                }
                return null;
            }
        });
    }

K
kohsuke 已提交
688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733
    /**
     * Computes the MD5 digest of the file in hex string.
     */
    public String digest() throws IOException, InterruptedException {
        return act(new FileCallable<String>() {
            public String invoke(File f, VirtualChannel channel) throws IOException {
                return Util.getDigestOf(new FileInputStream(f));
            }
        });
    }

    /**
     * Copies this file to the specified target.
     */
    public void copyTo(FilePath target) throws IOException, InterruptedException {
        OutputStream out = target.write();
        try {
            copyTo(out);
        } finally {
            out.close();
        }
    }

    /**
     * Sends the contents of this file into the given {@link OutputStream}.
     */
    public void copyTo(OutputStream os) throws IOException, InterruptedException {
        final OutputStream out = new RemoteOutputStream(os);

        act(new FileCallable<Void>() {
            public Void invoke(File f, VirtualChannel channel) throws IOException {
                FileInputStream fis = new FileInputStream(f);
                Util.copyStream(fis,out);
                fis.close();
                out.close();
                return null;
            }
        });
    }

    /**
     * Remoting interface used for {@link FilePath#copyRecursiveTo(String, FilePath)}.
     *
     * TODO: this might not be the most efficient way to do the copy.
     */
    interface RemoteCopier {
K
kohsuke 已提交
734 735 736 737
        /**
         * @param fileName
         *      relative path name to the output file. Path separator must be '/'.
         */
K
kohsuke 已提交
738 739 740 741 742
        void open(String fileName) throws IOException;
        void write(byte[] buf, int len) throws IOException;
        void close() throws IOException;
    }

K
kohsuke 已提交
743 744 745 746
    public int copyRecursiveTo(String fileMask, FilePath target) throws IOException, InterruptedException {
        return copyRecursiveTo(fileMask,null,target);
    }

K
kohsuke 已提交
747 748 749
    /**
     * Copies the files that match the given file mask to the specified target node.
     *
K
kohsuke 已提交
750 751
     * @param excludes
     *      Files to be excluded. Can be null.
K
kohsuke 已提交
752 753 754
     * @return
     *      the number of files copied.
     */
K
kohsuke 已提交
755
    public int copyRecursiveTo(final String fileMask, final String excludes, final FilePath target) throws IOException, InterruptedException {
K
kohsuke 已提交
756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
        if(this.channel==target.channel) {
            // local to local copy.
            return act(new FileCallable<Integer>() {
                public Integer invoke(File base, VirtualChannel channel) throws IOException {
                    assert target.channel==null;

                    try {
                        class CopyImpl extends Copy {
                            private int copySize;

                            public CopyImpl() {
                                setProject(new org.apache.tools.ant.Project());
                            }

                            protected void doFileOperations() {
                                copySize = super.fileCopyMap.size();
                                super.doFileOperations();
                            }

                            public int getNumCopied() {
                                return copySize;
                            }
                        }

                        CopyImpl copyTask = new CopyImpl();
                        copyTask.setTodir(new File(target.remote));
782
                        copyTask.addFileset(Util.createFileSet(base,fileMask,excludes));
K
kohsuke 已提交
783 784 785 786 787 788 789 790

                        copyTask.execute();
                        return copyTask.getNumCopied();
                    } catch (BuildException e) {
                        throw new IOException2("Failed to copy "+base+"/"+fileMask+" to "+target,e);
                    }
                }
            });
791 792 793 794 795 796 797
        } else
        if(this.channel==null) {
            // local -> remote copy
            final Pipe pipe = Pipe.createLocalToRemote();

            Future<Void> future = target.actAsync(new FileCallable<Void>() {
                public Void invoke(File f, VirtualChannel channel) throws IOException {
798 799 800 801 802 803
                    try {
                        readFromTar(remote+'/'+fileMask, f,pipe.getIn());
                        return null;
                    } finally {
                        pipe.getIn().close();
                    }
804 805 806 807 808 809 810 811 812
                }
            });
            int r = writeToTar(new File(remote),fileMask,excludes,pipe);
            try {
                future.get();
            } catch (ExecutionException e) {
                throw new IOException2(e);
            }
            return r;
K
kohsuke 已提交
813
        } else {
814 815
            // remote -> local copy
            final Pipe pipe = Pipe.createRemoteToLocal();
K
kohsuke 已提交
816

817 818
            Future<Integer> future = actAsync(new FileCallable<Integer>() {
                public Integer invoke(File f, VirtualChannel channel) throws IOException {
819 820 821 822 823
                    try {
                        return writeToTar(f,fileMask,excludes,pipe);
                    } finally {
                        pipe.getOut().close();
                    }
K
kohsuke 已提交
824 825
                }
            });
826 827 828 829 830 831 832 833 834 835 836
            try {
                readFromTar(remote+'/'+fileMask,new File(target.remote),pipe.getIn());
            } catch (IOException e) {// BuildException or IOException
                try {
                    future.get(3,TimeUnit.SECONDS);
                    throw e;    // the remote side completed successfully, so the error must be local
                } catch (ExecutionException x) {
                    // report both errors
                    StringWriter sw = new StringWriter();
                    e.printStackTrace(new PrintWriter(sw));
                    throw new IOException2(sw.toString(),x);
837
                } catch (TimeoutException _) {
838 839 840 841
                    // remote is hanging
                    throw e;
                }
            }
842 843 844 845 846 847 848 849 850 851 852 853 854 855 856
            try {
                return future.get();
            } catch (ExecutionException e) {
                throw new IOException2(e);
            }
        }
    }

    /**
     * Writes to a tar stream and stores obtained files to the base dir.
     *
     * @return
     *      number of files/directories that are written.
     */
    private Integer writeToTar(File baseDir, String fileMask, String excludes, Pipe pipe) throws IOException {
857
        FileSet fs = Util.createFileSet(baseDir,fileMask,excludes);
858 859 860 861

        byte[] buf = new byte[8192];

        TarOutputStream tar = new TarOutputStream(new GZIPOutputStream(new BufferedOutputStream(pipe.getOut())));
862
        tar.setLongFileMode(TarOutputStream.LONGFILE_GNU);
863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886
        DirectoryScanner ds = fs.getDirectoryScanner(new org.apache.tools.ant.Project());
        String[] files = ds.getIncludedFiles();
        for( String f : files) {
            if(Functions.isWindows())
                f = f.replace('\\','/');

            File file = new File(baseDir, f);

            TarEntry te = new TarEntry(f);
            te.setModTime(file.lastModified());
            if(!file.isDirectory())
                te.setSize(file.length());

            tar.putNextEntry(te);

            if (!file.isDirectory()) {
                FileInputStream in = new FileInputStream(file);
                int len;
                while((len=in.read(buf))>=0)
                    tar.write(buf,0,len);
                in.close();
            }

            tar.closeEntry();
K
kohsuke 已提交
887
        }
888 889 890 891 892 893 894 895 896

        tar.close();

        return files.length;
    }

    /**
     * Reads from a tar stream and stores obtained files to the base dir.
     */
897
    private static void readFromTar(String name, File baseDir, InputStream in) throws IOException {
898 899
        Untar untar = new Untar();
        untar.setProject(new Project());
900
        untar.add(new StreamResource(name,new BufferedInputStream(new GZIPInputStream(in))));
901
        untar.setDest(baseDir);
902 903 904 905 906
        try {
            untar.execute();
        } catch (BuildException e) {
            throw new IOException2("Failed to read the remote stream "+name,e);
        }
K
kohsuke 已提交
907 908
    }

909 910
    /**
     * Creates a {@link Launcher} for starting processes on the node
K
typo.  
kohsuke 已提交
911
     * that has this file.
912
     * @since 1.89
913 914 915 916 917 918 919 920
     */
    public Launcher createLauncher(TaskListener listener) {
        if(channel==null)
            return new LocalLauncher(listener);
        else
            return new RemoteLauncher(listener,channel,isUnix());
    }

921
    /**
K
kohsuke 已提交
922
     * Validates the ant file mask (like "foo/bar/*.txt, zot/*.jar")
923 924
     * against this directory, and try to point out the problem.
     *
K
kohsuke 已提交
925 926 927
     * <p>
     * This is useful in conjunction with {@link FormFieldValidator}.
     *
928 929 930
     * @return
     *      null if no error was found.
     * @since 1.90
K
kohsuke 已提交
931
     * @see FormFieldValidator.WorkspaceFileMask
932
     */
K
kohsuke 已提交
933
    public String validateAntFileMask(final String fileMasks) throws IOException, InterruptedException {
934 935
        return act(new FileCallable<String>() {
            public String invoke(File dir, VirtualChannel channel) throws IOException {
K
kohsuke 已提交
936
                StringTokenizer tokens = new StringTokenizer(fileMasks,",");
K
kohsuke 已提交
937 938 939

                while(tokens.hasMoreTokens()) {
                    final String fileMask = tokens.nextToken().trim();
940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965
                    if(hasMatch(dir,fileMask))
                        continue;   // no error on this portion

                    // in 1.172 we introduced an incompatible change to stop using ' ' as the separator
                    // so see if we can match by using ' ' as the separator
                    if(fileMask.contains(" ")) {
                        boolean matched = true;
                        for (String token : Util.tokenize(fileMask))
                            matched &= hasMatch(dir,token);
                        if(matched)
                            return Messages.FilePath_validateAntFileMask_whitespaceSeprator();
                    }

                    // a common mistake is to assume the wrong base dir, and there are two variations
                    // to this: (1) the user gave us aa/bb/cc/dd where cc/dd was correct
                    // and (2) the user gave us cc/dd where aa/bb/cc/dd was correct.

                    {// check the (1) above first
                        String f=fileMask;
                        while(true) {
                            int idx = findSeparator(f);
                            if(idx==-1)     break;
                            f=f.substring(idx+1);

                            if(hasMatch(dir,f))
                                return Messages.FilePath_validateAntFileMask_doesntMatchAndSuggest(fileMask,f);
K
kohsuke 已提交
966
                        }
967
                    }
968

969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994
                    {// check the (1) above next as this is more expensive.
                        // Try prepending "**/" to see if that results in a match
                        FileSet fs = Util.createFileSet(dir,"**/"+fileMask);
                        DirectoryScanner ds = fs.getDirectoryScanner(new Project());
                        if(ds.getIncludedFilesCount()!=0) {
                            // try shorter name first so that the suggestion results in least amount of changes
                            String[] names = ds.getIncludedFiles();
                            Arrays.sort(names,SHORTER_STRING_FIRST);
                            for( String f : names) {
                                // now we want to decompose f to the leading portion that matched "**"
                                // and the trailing portion that matched the file mask, so that
                                // we can suggest the user error.
                                //
                                // this is not a very efficient/clever way to do it, but it's relatively simple

                                String prefix="";
                                while(true) {
                                    int idx = findSeparator(f);
                                    if(idx==-1)     break;

                                    prefix+=f.substring(0,idx)+'/';
                                    f=f.substring(idx+1);
                                    if(hasMatch(dir,prefix+fileMask))
                                        return Messages.FilePath_validateAntFileMask_doesntMatchAndSuggest(fileMask, prefix+fileMask);
                                }
                            }
K
kohsuke 已提交
995
                        }
996
                    }
997

998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
                    {// finally, see if we can identify any sub portion that's valid. Otherwise bail out
                        String previous = null;
                        String pattern = fileMask;

                        while(true) {
                            if(hasMatch(dir,pattern)) {
                                // found a match
                                if(previous==null)
                                    return String.format("'%s' doesn't match anything, although '%s' exists",
                                        fileMask, pattern );
                                else
                                    return String.format("'%s' doesn't match anything: '%s' exists but not '%s'",
                                        fileMask, pattern, previous );
                            }

                            int idx = findSeparator(pattern);
                            if(idx<0) {// no more path component left to go back
                                if(pattern.equals(fileMask))
                                    return String.format("'%s' doesn't match anything", fileMask );
                                else
                                    return String.format("'%s' doesn't match anything: even '%s' doesn't exist",
                                        fileMask, pattern );
                            }

                            // cut off the trailing component and try again
                            previous = pattern;
                            pattern = pattern.substring(0,idx);
                        }
K
kohsuke 已提交
1026
                    }
1027
                }
K
kohsuke 已提交
1028 1029

                return null; // no error
1030
            }
1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048

            private boolean hasMatch(File dir, String pattern) {
                FileSet fs = Util.createFileSet(dir,pattern);
                DirectoryScanner ds = fs.getDirectoryScanner(new Project());

                return ds.getIncludedFilesCount()!=0 || ds.getIncludedDirsCount()!=0;
            }

            /**
             * Finds the position of the first path separator.
             */
            private int findSeparator(String pattern) {
                int idx1 = pattern.indexOf('\\');
                int idx2 = pattern.indexOf('/');
                if(idx1==-1)    return idx2;
                if(idx2==-1)    return idx1;
                return Math.min(idx1,idx2);
            }
1049 1050 1051
        });
    }

K
kohsuke 已提交
1052 1053 1054
    @Deprecated
    public String toString() {
        // to make writing JSPs easily, return local
K
kohsuke 已提交
1055
        return remote;
K
kohsuke 已提交
1056 1057
    }

K
kohsuke 已提交
1058 1059 1060 1061 1062
    public VirtualChannel getChannel() {
        if(channel!=null)   return channel;
        else                return Hudson.MasterComputer.localChannel;
    }

K
kohsuke 已提交
1063 1064 1065 1066
    /**
     * Returns true if this {@link FilePath} represents a remote file. 
     */
    public boolean isRemote() {
K
typo.  
kohsuke 已提交
1067
        return channel!=null;
K
kohsuke 已提交
1068 1069
    }

K
kohsuke 已提交
1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092
    private void writeObject(ObjectOutputStream oos) throws IOException {
        Channel target = Channel.current();

        if(channel!=null && channel!=target)
            throw new IllegalStateException("Can't send a remote FilePath to a different remote channel");

        oos.defaultWriteObject();
        oos.writeBoolean(channel==null);
    }

    private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
        Channel channel = Channel.current();
        assert channel!=null;

        ois.defaultReadObject();
        if(ois.readBoolean()) {
            this.channel = channel;
        } else {
            this.channel = null;
        }
    }

    private static final long serialVersionUID = 1L;
1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113

    /**
     * Adapts {@link FileCallable} to {@link Callable}.
     */
    private class FileCallableWrapper<T> implements DelegatingCallable<T,IOException> {
        private final FileCallable<T> callable;

        public FileCallableWrapper(FileCallable<T> callable) {
            this.callable = callable;
        }

        public T call() throws IOException {
            return callable.invoke(new File(remote), Channel.current());
        }

        public ClassLoader getClassLoader() {
            return callable.getClass().getClassLoader();
        }

        private static final long serialVersionUID = 1L;
    }
1114 1115 1116 1117 1118 1119

    private static final Comparator<String> SHORTER_STRING_FIRST = new Comparator<String>() {
        public int compare(String o1, String o2) {
            return o1.length()-o2.length();
        }
    };
K
kohsuke 已提交
1120
}