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.hadoop.fs;
020
021import java.io.*;
022import java.net.InetAddress;
023import java.net.URI;
024import java.net.UnknownHostException;
025import java.util.ArrayList;
026import java.util.Arrays;
027import java.util.Enumeration;
028import java.util.List;
029import java.util.Map;
030import java.util.jar.Attributes;
031import java.util.jar.JarOutputStream;
032import java.util.jar.Manifest;
033import java.util.zip.GZIPInputStream;
034import java.util.zip.ZipEntry;
035import java.util.zip.ZipFile;
036
037import org.apache.commons.collections.map.CaseInsensitiveMap;
038import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
039import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
040import org.apache.hadoop.classification.InterfaceAudience;
041import org.apache.hadoop.classification.InterfaceStability;
042import org.apache.hadoop.conf.Configuration;
043import org.apache.hadoop.fs.permission.FsAction;
044import org.apache.hadoop.fs.permission.FsPermission;
045import org.apache.hadoop.io.IOUtils;
046import org.apache.hadoop.io.nativeio.NativeIO;
047import org.apache.hadoop.util.StringUtils;
048import org.apache.hadoop.util.Shell;
049import org.apache.hadoop.util.Shell.ShellCommandExecutor;
050import org.apache.commons.logging.Log;
051import org.apache.commons.logging.LogFactory;
052
053/**
054 * A collection of file-processing util methods
055 */
056@InterfaceAudience.Public
057@InterfaceStability.Evolving
058public class FileUtil {
059
060  private static final Log LOG = LogFactory.getLog(FileUtil.class);
061
062  /* The error code is defined in winutils to indicate insufficient
063   * privilege to create symbolic links. This value need to keep in
064   * sync with the constant of the same name in:
065   * "src\winutils\common.h"
066   * */
067  public static final int SYMLINK_NO_PRIVILEGE = 2;
068
069  /**
070   * convert an array of FileStatus to an array of Path
071   * 
072   * @param stats
073   *          an array of FileStatus objects
074   * @return an array of paths corresponding to the input
075   */
076  public static Path[] stat2Paths(FileStatus[] stats) {
077    if (stats == null)
078      return null;
079    Path[] ret = new Path[stats.length];
080    for (int i = 0; i < stats.length; ++i) {
081      ret[i] = stats[i].getPath();
082    }
083    return ret;
084  }
085
086  /**
087   * convert an array of FileStatus to an array of Path.
088   * If stats if null, return path
089   * @param stats
090   *          an array of FileStatus objects
091   * @param path
092   *          default path to return in stats is null
093   * @return an array of paths corresponding to the input
094   */
095  public static Path[] stat2Paths(FileStatus[] stats, Path path) {
096    if (stats == null)
097      return new Path[]{path};
098    else
099      return stat2Paths(stats);
100  }
101  
102  /**
103   * Delete a directory and all its contents.  If
104   * we return false, the directory may be partially-deleted.
105   * (1) If dir is symlink to a file, the symlink is deleted. The file pointed
106   *     to by the symlink is not deleted.
107   * (2) If dir is symlink to a directory, symlink is deleted. The directory
108   *     pointed to by symlink is not deleted.
109   * (3) If dir is a normal file, it is deleted.
110   * (4) If dir is a normal directory, then dir and all its contents recursively
111   *     are deleted.
112   */
113  public static boolean fullyDelete(final File dir) {
114    return fullyDelete(dir, false);
115  }
116  
117  /**
118   * Delete a directory and all its contents.  If
119   * we return false, the directory may be partially-deleted.
120   * (1) If dir is symlink to a file, the symlink is deleted. The file pointed
121   *     to by the symlink is not deleted.
122   * (2) If dir is symlink to a directory, symlink is deleted. The directory
123   *     pointed to by symlink is not deleted.
124   * (3) If dir is a normal file, it is deleted.
125   * (4) If dir is a normal directory, then dir and all its contents recursively
126   *     are deleted.
127   * @param dir the file or directory to be deleted
128   * @param tryGrantPermissions true if permissions should be modified to delete a file.
129   * @return true on success false on failure.
130   */
131  public static boolean fullyDelete(final File dir, boolean tryGrantPermissions) {
132    if (tryGrantPermissions) {
133      // try to chmod +rwx the parent folder of the 'dir': 
134      File parent = dir.getParentFile();
135      grantPermissions(parent);
136    }
137    if (deleteImpl(dir, false)) {
138      // dir is (a) normal file, (b) symlink to a file, (c) empty directory or
139      // (d) symlink to a directory
140      return true;
141    }
142    // handle nonempty directory deletion
143    if (!fullyDeleteContents(dir, tryGrantPermissions)) {
144      return false;
145    }
146    return deleteImpl(dir, true);
147  }
148
149  /**
150   * Returns the target of the given symlink. Returns the empty string if
151   * the given path does not refer to a symlink or there is an error
152   * accessing the symlink.
153   * @param f File representing the symbolic link.
154   * @return The target of the symbolic link, empty string on error or if not
155   *         a symlink.
156   */
157  public static String readLink(File f) {
158    /* NB: Use readSymbolicLink in java.nio.file.Path once available. Could
159     * use getCanonicalPath in File to get the target of the symlink but that
160     * does not indicate if the given path refers to a symlink.
161     */
162    try {
163      return Shell.execCommand(
164          Shell.getReadlinkCommand(f.toString())).trim();
165    } catch (IOException x) {
166      return "";
167    }
168  }
169
170  /*
171   * Pure-Java implementation of "chmod +rwx f".
172   */
173  private static void grantPermissions(final File f) {
174      FileUtil.setExecutable(f, true);
175      FileUtil.setReadable(f, true);
176      FileUtil.setWritable(f, true);
177  }
178
179  private static boolean deleteImpl(final File f, final boolean doLog) {
180    if (f == null) {
181      LOG.warn("null file argument.");
182      return false;
183    }
184    final boolean wasDeleted = f.delete();
185    if (wasDeleted) {
186      return true;
187    }
188    final boolean ex = f.exists();
189    if (doLog && ex) {
190      LOG.warn("Failed to delete file or dir ["
191          + f.getAbsolutePath() + "]: it still exists.");
192    }
193    return !ex;
194  }
195  
196  /**
197   * Delete the contents of a directory, not the directory itself.  If
198   * we return false, the directory may be partially-deleted.
199   * If dir is a symlink to a directory, all the contents of the actual
200   * directory pointed to by dir will be deleted.
201   */
202  public static boolean fullyDeleteContents(final File dir) {
203    return fullyDeleteContents(dir, false);
204  }
205  
206  /**
207   * Delete the contents of a directory, not the directory itself.  If
208   * we return false, the directory may be partially-deleted.
209   * If dir is a symlink to a directory, all the contents of the actual
210   * directory pointed to by dir will be deleted.
211   * @param tryGrantPermissions if 'true', try grant +rwx permissions to this 
212   * and all the underlying directories before trying to delete their contents.
213   */
214  public static boolean fullyDeleteContents(final File dir, final boolean tryGrantPermissions) {
215    if (tryGrantPermissions) {
216      // to be able to list the dir and delete files from it
217      // we must grant the dir rwx permissions: 
218      grantPermissions(dir);
219    }
220    boolean deletionSucceeded = true;
221    final File[] contents = dir.listFiles();
222    if (contents != null) {
223      for (int i = 0; i < contents.length; i++) {
224        if (contents[i].isFile()) {
225          if (!deleteImpl(contents[i], true)) {// normal file or symlink to another file
226            deletionSucceeded = false;
227            continue; // continue deletion of other files/dirs under dir
228          }
229        } else {
230          // Either directory or symlink to another directory.
231          // Try deleting the directory as this might be a symlink
232          boolean b = false;
233          b = deleteImpl(contents[i], false);
234          if (b){
235            //this was indeed a symlink or an empty directory
236            continue;
237          }
238          // if not an empty directory or symlink let
239          // fullydelete handle it.
240          if (!fullyDelete(contents[i], tryGrantPermissions)) {
241            deletionSucceeded = false;
242            // continue deletion of other files/dirs under dir
243          }
244        }
245      }
246    }
247    return deletionSucceeded;
248  }
249
250  /**
251   * Recursively delete a directory.
252   * 
253   * @param fs {@link FileSystem} on which the path is present
254   * @param dir directory to recursively delete 
255   * @throws IOException
256   * @deprecated Use {@link FileSystem#delete(Path, boolean)}
257   */
258  @Deprecated
259  public static void fullyDelete(FileSystem fs, Path dir) 
260  throws IOException {
261    fs.delete(dir, true);
262  }
263
264  //
265  // If the destination is a subdirectory of the source, then
266  // generate exception
267  //
268  private static void checkDependencies(FileSystem srcFS, 
269                                        Path src, 
270                                        FileSystem dstFS, 
271                                        Path dst)
272                                        throws IOException {
273    if (srcFS == dstFS) {
274      String srcq = src.makeQualified(srcFS).toString() + Path.SEPARATOR;
275      String dstq = dst.makeQualified(dstFS).toString() + Path.SEPARATOR;
276      if (dstq.startsWith(srcq)) {
277        if (srcq.length() == dstq.length()) {
278          throw new IOException("Cannot copy " + src + " to itself.");
279        } else {
280          throw new IOException("Cannot copy " + src + " to its subdirectory " +
281                                dst);
282        }
283      }
284    }
285  }
286
287  /** Copy files between FileSystems. */
288  public static boolean copy(FileSystem srcFS, Path src, 
289                             FileSystem dstFS, Path dst, 
290                             boolean deleteSource,
291                             Configuration conf) throws IOException {
292    return copy(srcFS, src, dstFS, dst, deleteSource, true, conf);
293  }
294
295  public static boolean copy(FileSystem srcFS, Path[] srcs, 
296                             FileSystem dstFS, Path dst,
297                             boolean deleteSource, 
298                             boolean overwrite, Configuration conf)
299                             throws IOException {
300    boolean gotException = false;
301    boolean returnVal = true;
302    StringBuilder exceptions = new StringBuilder();
303
304    if (srcs.length == 1)
305      return copy(srcFS, srcs[0], dstFS, dst, deleteSource, overwrite, conf);
306
307    // Check if dest is directory
308    if (!dstFS.exists(dst)) {
309      throw new IOException("`" + dst +"': specified destination directory " +
310                            "does not exist");
311    } else {
312      FileStatus sdst = dstFS.getFileStatus(dst);
313      if (!sdst.isDirectory()) 
314        throw new IOException("copying multiple files, but last argument `" +
315                              dst + "' is not a directory");
316    }
317
318    for (Path src : srcs) {
319      try {
320        if (!copy(srcFS, src, dstFS, dst, deleteSource, overwrite, conf))
321          returnVal = false;
322      } catch (IOException e) {
323        gotException = true;
324        exceptions.append(e.getMessage());
325        exceptions.append("\n");
326      }
327    }
328    if (gotException) {
329      throw new IOException(exceptions.toString());
330    }
331    return returnVal;
332  }
333
334  /** Copy files between FileSystems. */
335  public static boolean copy(FileSystem srcFS, Path src, 
336                             FileSystem dstFS, Path dst, 
337                             boolean deleteSource,
338                             boolean overwrite,
339                             Configuration conf) throws IOException {
340    FileStatus fileStatus = srcFS.getFileStatus(src);
341    return copy(srcFS, fileStatus, dstFS, dst, deleteSource, overwrite, conf);
342  }
343
344  /** Copy files between FileSystems. */
345  public static boolean copy(FileSystem srcFS, FileStatus srcStatus,
346                             FileSystem dstFS, Path dst,
347                             boolean deleteSource,
348                             boolean overwrite,
349                             Configuration conf) throws IOException {
350    Path src = srcStatus.getPath();
351    dst = checkDest(src.getName(), dstFS, dst, overwrite);
352    if (srcStatus.isDirectory()) {
353      checkDependencies(srcFS, src, dstFS, dst);
354      if (!dstFS.mkdirs(dst)) {
355        return false;
356      }
357      FileStatus contents[] = srcFS.listStatus(src);
358      for (int i = 0; i < contents.length; i++) {
359        copy(srcFS, contents[i], dstFS,
360             new Path(dst, contents[i].getPath().getName()),
361             deleteSource, overwrite, conf);
362      }
363    } else {
364      InputStream in=null;
365      OutputStream out = null;
366      try {
367        in = srcFS.open(src);
368        out = dstFS.create(dst, overwrite);
369        IOUtils.copyBytes(in, out, conf, true);
370      } catch (IOException e) {
371        IOUtils.closeStream(out);
372        IOUtils.closeStream(in);
373        throw e;
374      }
375    }
376    if (deleteSource) {
377      return srcFS.delete(src, true);
378    } else {
379      return true;
380    }
381  
382  }
383
384  @Deprecated
385  /** Copy all files in a directory to one output file (merge). */
386  public static boolean copyMerge(FileSystem srcFS, Path srcDir, 
387                                  FileSystem dstFS, Path dstFile, 
388                                  boolean deleteSource,
389                                  Configuration conf, String addString) throws IOException {
390    dstFile = checkDest(srcDir.getName(), dstFS, dstFile, false);
391
392    if (!srcFS.getFileStatus(srcDir).isDirectory())
393      return false;
394   
395    OutputStream out = dstFS.create(dstFile);
396    
397    try {
398      FileStatus contents[] = srcFS.listStatus(srcDir);
399      Arrays.sort(contents);
400      for (int i = 0; i < contents.length; i++) {
401        if (contents[i].isFile()) {
402          InputStream in = srcFS.open(contents[i].getPath());
403          try {
404            IOUtils.copyBytes(in, out, conf, false);
405            if (addString!=null)
406              out.write(addString.getBytes("UTF-8"));
407                
408          } finally {
409            in.close();
410          } 
411        }
412      }
413    } finally {
414      out.close();
415    }
416    
417
418    if (deleteSource) {
419      return srcFS.delete(srcDir, true);
420    } else {
421      return true;
422    }
423  }  
424  
425  /** Copy local files to a FileSystem. */
426  public static boolean copy(File src,
427                             FileSystem dstFS, Path dst,
428                             boolean deleteSource,
429                             Configuration conf) throws IOException {
430    dst = checkDest(src.getName(), dstFS, dst, false);
431
432    if (src.isDirectory()) {
433      if (!dstFS.mkdirs(dst)) {
434        return false;
435      }
436      File contents[] = listFiles(src);
437      for (int i = 0; i < contents.length; i++) {
438        copy(contents[i], dstFS, new Path(dst, contents[i].getName()),
439             deleteSource, conf);
440      }
441    } else if (src.isFile()) {
442      InputStream in = null;
443      OutputStream out =null;
444      try {
445        in = new FileInputStream(src);
446        out = dstFS.create(dst);
447        IOUtils.copyBytes(in, out, conf);
448      } catch (IOException e) {
449        IOUtils.closeStream( out );
450        IOUtils.closeStream( in );
451        throw e;
452      }
453    } else {
454      throw new IOException(src.toString() + 
455                            ": No such file or directory");
456    }
457    if (deleteSource) {
458      return FileUtil.fullyDelete(src);
459    } else {
460      return true;
461    }
462  }
463
464  /** Copy FileSystem files to local files. */
465  public static boolean copy(FileSystem srcFS, Path src, 
466                             File dst, boolean deleteSource,
467                             Configuration conf) throws IOException {
468    FileStatus filestatus = srcFS.getFileStatus(src);
469    return copy(srcFS, filestatus, dst, deleteSource, conf);
470  }
471
472  /** Copy FileSystem files to local files. */
473  private static boolean copy(FileSystem srcFS, FileStatus srcStatus,
474                              File dst, boolean deleteSource,
475                              Configuration conf) throws IOException {
476    Path src = srcStatus.getPath();
477    if (srcStatus.isDirectory()) {
478      if (!dst.mkdirs()) {
479        return false;
480      }
481      FileStatus contents[] = srcFS.listStatus(src);
482      for (int i = 0; i < contents.length; i++) {
483        copy(srcFS, contents[i],
484             new File(dst, contents[i].getPath().getName()),
485             deleteSource, conf);
486      }
487    } else {
488      InputStream in = srcFS.open(src);
489      IOUtils.copyBytes(in, new FileOutputStream(dst), conf);
490    }
491    if (deleteSource) {
492      return srcFS.delete(src, true);
493    } else {
494      return true;
495    }
496  }
497
498  private static Path checkDest(String srcName, FileSystem dstFS, Path dst,
499      boolean overwrite) throws IOException {
500    if (dstFS.exists(dst)) {
501      FileStatus sdst = dstFS.getFileStatus(dst);
502      if (sdst.isDirectory()) {
503        if (null == srcName) {
504          throw new IOException("Target " + dst + " is a directory");
505        }
506        return checkDest(null, dstFS, new Path(dst, srcName), overwrite);
507      } else if (!overwrite) {
508        throw new IOException("Target " + dst + " already exists");
509      }
510    }
511    return dst;
512  }
513
514  /**
515   * Convert a os-native filename to a path that works for the shell.
516   * @param filename The filename to convert
517   * @return The unix pathname
518   * @throws IOException on windows, there can be problems with the subprocess
519   */
520  public static String makeShellPath(String filename) throws IOException {
521    return filename;
522  }
523  
524  /**
525   * Convert a os-native filename to a path that works for the shell.
526   * @param file The filename to convert
527   * @return The unix pathname
528   * @throws IOException on windows, there can be problems with the subprocess
529   */
530  public static String makeShellPath(File file) throws IOException {
531    return makeShellPath(file, false);
532  }
533
534  /**
535   * Convert a os-native filename to a path that works for the shell.
536   * @param file The filename to convert
537   * @param makeCanonicalPath 
538   *          Whether to make canonical path for the file passed
539   * @return The unix pathname
540   * @throws IOException on windows, there can be problems with the subprocess
541   */
542  public static String makeShellPath(File file, boolean makeCanonicalPath) 
543  throws IOException {
544    if (makeCanonicalPath) {
545      return makeShellPath(file.getCanonicalPath());
546    } else {
547      return makeShellPath(file.toString());
548    }
549  }
550
551  /**
552   * Takes an input dir and returns the du on that local directory. Very basic
553   * implementation.
554   * 
555   * @param dir
556   *          The input dir to get the disk space of this local dir
557   * @return The total disk space of the input local directory
558   */
559  public static long getDU(File dir) {
560    long size = 0;
561    if (!dir.exists())
562      return 0;
563    if (!dir.isDirectory()) {
564      return dir.length();
565    } else {
566      File[] allFiles = dir.listFiles();
567      if(allFiles != null) {
568         for (int i = 0; i < allFiles.length; i++) {
569           boolean isSymLink;
570           try {
571             isSymLink = org.apache.commons.io.FileUtils.isSymlink(allFiles[i]);
572           } catch(IOException ioe) {
573             isSymLink = true;
574           }
575           if(!isSymLink) {
576             size += getDU(allFiles[i]);
577           }
578         }
579      }
580      return size;
581    }
582  }
583    
584  /**
585   * Given a File input it will unzip the file in a the unzip directory
586   * passed as the second parameter
587   * @param inFile The zip file as input
588   * @param unzipDir The unzip directory where to unzip the zip file.
589   * @throws IOException
590   */
591  public static void unZip(File inFile, File unzipDir) throws IOException {
592    Enumeration<? extends ZipEntry> entries;
593    ZipFile zipFile = new ZipFile(inFile);
594
595    try {
596      entries = zipFile.entries();
597      while (entries.hasMoreElements()) {
598        ZipEntry entry = entries.nextElement();
599        if (!entry.isDirectory()) {
600          InputStream in = zipFile.getInputStream(entry);
601          try {
602            File file = new File(unzipDir, entry.getName());
603            if (!file.getParentFile().mkdirs()) {           
604              if (!file.getParentFile().isDirectory()) {
605                throw new IOException("Mkdirs failed to create " + 
606                                      file.getParentFile().toString());
607              }
608            }
609            OutputStream out = new FileOutputStream(file);
610            try {
611              byte[] buffer = new byte[8192];
612              int i;
613              while ((i = in.read(buffer)) != -1) {
614                out.write(buffer, 0, i);
615              }
616            } finally {
617              out.close();
618            }
619          } finally {
620            in.close();
621          }
622        }
623      }
624    } finally {
625      zipFile.close();
626    }
627  }
628
629  /**
630   * Given a Tar File as input it will untar the file in a the untar directory
631   * passed as the second parameter
632   * 
633   * This utility will untar ".tar" files and ".tar.gz","tgz" files.
634   *  
635   * @param inFile The tar file as input. 
636   * @param untarDir The untar directory where to untar the tar file.
637   * @throws IOException
638   */
639  public static void unTar(File inFile, File untarDir) throws IOException {
640    if (!untarDir.mkdirs()) {
641      if (!untarDir.isDirectory()) {
642        throw new IOException("Mkdirs failed to create " + untarDir);
643      }
644    }
645
646    boolean gzipped = inFile.toString().endsWith("gz");
647    if(Shell.WINDOWS) {
648      // Tar is not native to Windows. Use simple Java based implementation for 
649      // tests and simple tar archives
650      unTarUsingJava(inFile, untarDir, gzipped);
651    }
652    else {
653      // spawn tar utility to untar archive for full fledged unix behavior such 
654      // as resolving symlinks in tar archives
655      unTarUsingTar(inFile, untarDir, gzipped);
656    }
657  }
658  
659  private static void unTarUsingTar(File inFile, File untarDir,
660      boolean gzipped) throws IOException {
661    StringBuffer untarCommand = new StringBuffer();
662    if (gzipped) {
663      untarCommand.append(" gzip -dc '");
664      untarCommand.append(FileUtil.makeShellPath(inFile));
665      untarCommand.append("' | (");
666    } 
667    untarCommand.append("cd '");
668    untarCommand.append(FileUtil.makeShellPath(untarDir)); 
669    untarCommand.append("' ; ");
670    untarCommand.append("tar -xf ");
671
672    if (gzipped) {
673      untarCommand.append(" -)");
674    } else {
675      untarCommand.append(FileUtil.makeShellPath(inFile));
676    }
677    String[] shellCmd = { "bash", "-c", untarCommand.toString() };
678    ShellCommandExecutor shexec = new ShellCommandExecutor(shellCmd);
679    shexec.execute();
680    int exitcode = shexec.getExitCode();
681    if (exitcode != 0) {
682      throw new IOException("Error untarring file " + inFile + 
683                  ". Tar process exited with exit code " + exitcode);
684    }
685  }
686  
687  private static void unTarUsingJava(File inFile, File untarDir,
688      boolean gzipped) throws IOException {
689    InputStream inputStream = null;
690    TarArchiveInputStream tis = null;
691    try {
692      if (gzipped) {
693        inputStream = new BufferedInputStream(new GZIPInputStream(
694            new FileInputStream(inFile)));
695      } else {
696        inputStream = new BufferedInputStream(new FileInputStream(inFile));
697      }
698
699      tis = new TarArchiveInputStream(inputStream);
700
701      for (TarArchiveEntry entry = tis.getNextTarEntry(); entry != null;) {
702        unpackEntries(tis, entry, untarDir);
703        entry = tis.getNextTarEntry();
704      }
705    } finally {
706      IOUtils.cleanup(LOG, tis, inputStream);
707    }
708  }
709  
710  private static void unpackEntries(TarArchiveInputStream tis,
711      TarArchiveEntry entry, File outputDir) throws IOException {
712    if (entry.isDirectory()) {
713      File subDir = new File(outputDir, entry.getName());
714      if (!subDir.mkdirs() && !subDir.isDirectory()) {
715        throw new IOException("Mkdirs failed to create tar internal dir "
716            + outputDir);
717      }
718
719      for (TarArchiveEntry e : entry.getDirectoryEntries()) {
720        unpackEntries(tis, e, subDir);
721      }
722
723      return;
724    }
725
726    File outputFile = new File(outputDir, entry.getName());
727    if (!outputFile.getParentFile().exists()) {
728      if (!outputFile.getParentFile().mkdirs()) {
729        throw new IOException("Mkdirs failed to create tar internal dir "
730            + outputDir);
731      }
732    }
733
734    if (entry.isLink()) {
735      File src = new File(outputDir, entry.getLinkName());
736      HardLink.createHardLink(src, outputFile);
737      return;
738    }
739
740    int count;
741    byte data[] = new byte[2048];
742    try (BufferedOutputStream outputStream = new BufferedOutputStream(
743        new FileOutputStream(outputFile));) {
744
745      while ((count = tis.read(data)) != -1) {
746        outputStream.write(data, 0, count);
747      }
748
749      outputStream.flush();
750    }
751  }
752  
753  /**
754   * Class for creating hardlinks.
755   * Supports Unix, WindXP.
756   * @deprecated Use {@link org.apache.hadoop.fs.HardLink}
757   */
758  @Deprecated
759  public static class HardLink extends org.apache.hadoop.fs.HardLink { 
760    // This is a stub to assist with coordinated change between
761    // COMMON and HDFS projects.  It will be removed after the
762    // corresponding change is committed to HDFS.
763  }
764
765  /**
766   * Create a soft link between a src and destination
767   * only on a local disk. HDFS does not support this.
768   * On Windows, when symlink creation fails due to security
769   * setting, we will log a warning. The return code in this
770   * case is 2.
771   *
772   * @param target the target for symlink 
773   * @param linkname the symlink
774   * @return 0 on success
775   */
776  public static int symLink(String target, String linkname) throws IOException{
777    // Run the input paths through Java's File so that they are converted to the
778    // native OS form
779    File targetFile = new File(
780        Path.getPathWithoutSchemeAndAuthority(new Path(target)).toString());
781    File linkFile = new File(
782        Path.getPathWithoutSchemeAndAuthority(new Path(linkname)).toString());
783
784    String[] cmd = Shell.getSymlinkCommand(
785        targetFile.toString(),
786        linkFile.toString());
787
788    ShellCommandExecutor shExec;
789    try {
790      if (Shell.WINDOWS &&
791          linkFile.getParentFile() != null &&
792          !new Path(target).isAbsolute()) {
793        // Relative links on Windows must be resolvable at the time of
794        // creation. To ensure this we run the shell command in the directory
795        // of the link.
796        //
797        shExec = new ShellCommandExecutor(cmd, linkFile.getParentFile());
798      } else {
799        shExec = new ShellCommandExecutor(cmd);
800      }
801      shExec.execute();
802    } catch (Shell.ExitCodeException ec) {
803      int returnVal = ec.getExitCode();
804      if (Shell.WINDOWS && returnVal == SYMLINK_NO_PRIVILEGE) {
805        LOG.warn("Fail to create symbolic links on Windows. "
806            + "The default security settings in Windows disallow non-elevated "
807            + "administrators and all non-administrators from creating symbolic links. "
808            + "This behavior can be changed in the Local Security Policy management console");
809      } else if (returnVal != 0) {
810        LOG.warn("Command '" + StringUtils.join(" ", cmd) + "' failed "
811            + returnVal + " with: " + ec.getMessage());
812      }
813      return returnVal;
814    } catch (IOException e) {
815      if (LOG.isDebugEnabled()) {
816        LOG.debug("Error while create symlink " + linkname + " to " + target
817            + "." + " Exception: " + StringUtils.stringifyException(e));
818      }
819      throw e;
820    }
821    return shExec.getExitCode();
822  }
823
824  /**
825   * Change the permissions on a filename.
826   * @param filename the name of the file to change
827   * @param perm the permission string
828   * @return the exit code from the command
829   * @throws IOException
830   * @throws InterruptedException
831   */
832  public static int chmod(String filename, String perm
833                          ) throws IOException, InterruptedException {
834    return chmod(filename, perm, false);
835  }
836
837  /**
838   * Change the permissions on a file / directory, recursively, if
839   * needed.
840   * @param filename name of the file whose permissions are to change
841   * @param perm permission string
842   * @param recursive true, if permissions should be changed recursively
843   * @return the exit code from the command.
844   * @throws IOException
845   */
846  public static int chmod(String filename, String perm, boolean recursive)
847                            throws IOException {
848    String [] cmd = Shell.getSetPermissionCommand(perm, recursive);
849    String[] args = new String[cmd.length + 1];
850    System.arraycopy(cmd, 0, args, 0, cmd.length);
851    args[cmd.length] = new File(filename).getPath();
852    ShellCommandExecutor shExec = new ShellCommandExecutor(args);
853    try {
854      shExec.execute();
855    }catch(IOException e) {
856      if(LOG.isDebugEnabled()) {
857        LOG.debug("Error while changing permission : " + filename 
858                  +" Exception: " + StringUtils.stringifyException(e));
859      }
860    }
861    return shExec.getExitCode();
862  }
863
864  /**
865   * Set the ownership on a file / directory. User name and group name
866   * cannot both be null.
867   * @param file the file to change
868   * @param username the new user owner name
869   * @param groupname the new group owner name
870   * @throws IOException
871   */
872  public static void setOwner(File file, String username,
873      String groupname) throws IOException {
874    if (username == null && groupname == null) {
875      throw new IOException("username == null && groupname == null");
876    }
877    String arg = (username == null ? "" : username)
878        + (groupname == null ? "" : ":" + groupname);
879    String [] cmd = Shell.getSetOwnerCommand(arg);
880    execCommand(file, cmd);
881  }
882
883  /**
884   * Platform independent implementation for {@link File#setReadable(boolean)}
885   * File#setReadable does not work as expected on Windows.
886   * @param f input file
887   * @param readable
888   * @return true on success, false otherwise
889   */
890  public static boolean setReadable(File f, boolean readable) {
891    if (Shell.WINDOWS) {
892      try {
893        String permission = readable ? "u+r" : "u-r";
894        FileUtil.chmod(f.getCanonicalPath(), permission, false);
895        return true;
896      } catch (IOException ex) {
897        return false;
898      }
899    } else {
900      return f.setReadable(readable);
901    }
902  }
903
904  /**
905   * Platform independent implementation for {@link File#setWritable(boolean)}
906   * File#setWritable does not work as expected on Windows.
907   * @param f input file
908   * @param writable
909   * @return true on success, false otherwise
910   */
911  public static boolean setWritable(File f, boolean writable) {
912    if (Shell.WINDOWS) {
913      try {
914        String permission = writable ? "u+w" : "u-w";
915        FileUtil.chmod(f.getCanonicalPath(), permission, false);
916        return true;
917      } catch (IOException ex) {
918        return false;
919      }
920    } else {
921      return f.setWritable(writable);
922    }
923  }
924
925  /**
926   * Platform independent implementation for {@link File#setExecutable(boolean)}
927   * File#setExecutable does not work as expected on Windows.
928   * Note: revoking execute permission on folders does not have the same
929   * behavior on Windows as on Unix platforms. Creating, deleting or renaming
930   * a file within that folder will still succeed on Windows.
931   * @param f input file
932   * @param executable
933   * @return true on success, false otherwise
934   */
935  public static boolean setExecutable(File f, boolean executable) {
936    if (Shell.WINDOWS) {
937      try {
938        String permission = executable ? "u+x" : "u-x";
939        FileUtil.chmod(f.getCanonicalPath(), permission, false);
940        return true;
941      } catch (IOException ex) {
942        return false;
943      }
944    } else {
945      return f.setExecutable(executable);
946    }
947  }
948
949  /**
950   * Platform independent implementation for {@link File#canRead()}
951   * @param f input file
952   * @return On Unix, same as {@link File#canRead()}
953   *         On Windows, true if process has read access on the path
954   */
955  public static boolean canRead(File f) {
956    if (Shell.WINDOWS) {
957      try {
958        return NativeIO.Windows.access(f.getCanonicalPath(),
959            NativeIO.Windows.AccessRight.ACCESS_READ);
960      } catch (IOException e) {
961        return false;
962      }
963    } else {
964      return f.canRead();
965    }
966  }
967
968  /**
969   * Platform independent implementation for {@link File#canWrite()}
970   * @param f input file
971   * @return On Unix, same as {@link File#canWrite()}
972   *         On Windows, true if process has write access on the path
973   */
974  public static boolean canWrite(File f) {
975    if (Shell.WINDOWS) {
976      try {
977        return NativeIO.Windows.access(f.getCanonicalPath(),
978            NativeIO.Windows.AccessRight.ACCESS_WRITE);
979      } catch (IOException e) {
980        return false;
981      }
982    } else {
983      return f.canWrite();
984    }
985  }
986
987  /**
988   * Platform independent implementation for {@link File#canExecute()}
989   * @param f input file
990   * @return On Unix, same as {@link File#canExecute()}
991   *         On Windows, true if process has execute access on the path
992   */
993  public static boolean canExecute(File f) {
994    if (Shell.WINDOWS) {
995      try {
996        return NativeIO.Windows.access(f.getCanonicalPath(),
997            NativeIO.Windows.AccessRight.ACCESS_EXECUTE);
998      } catch (IOException e) {
999        return false;
1000      }
1001    } else {
1002      return f.canExecute();
1003    }
1004  }
1005
1006  /**
1007   * Set permissions to the required value. Uses the java primitives instead
1008   * of forking if group == other.
1009   * @param f the file to change
1010   * @param permission the new permissions
1011   * @throws IOException
1012   */
1013  public static void setPermission(File f, FsPermission permission
1014                                   ) throws IOException {
1015    FsAction user = permission.getUserAction();
1016    FsAction group = permission.getGroupAction();
1017    FsAction other = permission.getOtherAction();
1018
1019    // use the native/fork if the group/other permissions are different
1020    // or if the native is available or on Windows
1021    if (group != other || NativeIO.isAvailable() || Shell.WINDOWS) {
1022      execSetPermission(f, permission);
1023      return;
1024    }
1025    
1026    boolean rv = true;
1027    
1028    // read perms
1029    rv = f.setReadable(group.implies(FsAction.READ), false);
1030    checkReturnValue(rv, f, permission);
1031    if (group.implies(FsAction.READ) != user.implies(FsAction.READ)) {
1032      rv = f.setReadable(user.implies(FsAction.READ), true);
1033      checkReturnValue(rv, f, permission);
1034    }
1035
1036    // write perms
1037    rv = f.setWritable(group.implies(FsAction.WRITE), false);
1038    checkReturnValue(rv, f, permission);
1039    if (group.implies(FsAction.WRITE) != user.implies(FsAction.WRITE)) {
1040      rv = f.setWritable(user.implies(FsAction.WRITE), true);
1041      checkReturnValue(rv, f, permission);
1042    }
1043
1044    // exec perms
1045    rv = f.setExecutable(group.implies(FsAction.EXECUTE), false);
1046    checkReturnValue(rv, f, permission);
1047    if (group.implies(FsAction.EXECUTE) != user.implies(FsAction.EXECUTE)) {
1048      rv = f.setExecutable(user.implies(FsAction.EXECUTE), true);
1049      checkReturnValue(rv, f, permission);
1050    }
1051  }
1052
1053  private static void checkReturnValue(boolean rv, File p, 
1054                                       FsPermission permission
1055                                       ) throws IOException {
1056    if (!rv) {
1057      throw new IOException("Failed to set permissions of path: " + p + 
1058                            " to " + 
1059                            String.format("%04o", permission.toShort()));
1060    }
1061  }
1062  
1063  private static void execSetPermission(File f, 
1064                                        FsPermission permission
1065                                       )  throws IOException {
1066    if (NativeIO.isAvailable()) {
1067      NativeIO.POSIX.chmod(f.getCanonicalPath(), permission.toShort());
1068    } else {
1069      execCommand(f, Shell.getSetPermissionCommand(
1070                  String.format("%04o", permission.toShort()), false));
1071    }
1072  }
1073  
1074  static String execCommand(File f, String... cmd) throws IOException {
1075    String[] args = new String[cmd.length + 1];
1076    System.arraycopy(cmd, 0, args, 0, cmd.length);
1077    args[cmd.length] = f.getCanonicalPath();
1078    String output = Shell.execCommand(args);
1079    return output;
1080  }
1081
1082  /**
1083   * Create a tmp file for a base file.
1084   * @param basefile the base file of the tmp
1085   * @param prefix file name prefix of tmp
1086   * @param isDeleteOnExit if true, the tmp will be deleted when the VM exits
1087   * @return a newly created tmp file
1088   * @exception IOException If a tmp file cannot created
1089   * @see java.io.File#createTempFile(String, String, File)
1090   * @see java.io.File#deleteOnExit()
1091   */
1092  public static final File createLocalTempFile(final File basefile,
1093                                               final String prefix,
1094                                               final boolean isDeleteOnExit)
1095    throws IOException {
1096    File tmp = File.createTempFile(prefix + basefile.getName(),
1097                                   "", basefile.getParentFile());
1098    if (isDeleteOnExit) {
1099      tmp.deleteOnExit();
1100    }
1101    return tmp;
1102  }
1103
1104  /**
1105   * Move the src file to the name specified by target.
1106   * @param src the source file
1107   * @param target the target file
1108   * @exception IOException If this operation fails
1109   */
1110  public static void replaceFile(File src, File target) throws IOException {
1111    /* renameTo() has two limitations on Windows platform.
1112     * src.renameTo(target) fails if
1113     * 1) If target already exists OR
1114     * 2) If target is already open for reading/writing.
1115     */
1116    if (!src.renameTo(target)) {
1117      int retries = 5;
1118      while (target.exists() && !target.delete() && retries-- >= 0) {
1119        try {
1120          Thread.sleep(1000);
1121        } catch (InterruptedException e) {
1122          throw new IOException("replaceFile interrupted.");
1123        }
1124      }
1125      if (!src.renameTo(target)) {
1126        throw new IOException("Unable to rename " + src +
1127                              " to " + target);
1128      }
1129    }
1130  }
1131  
1132  /**
1133   * A wrapper for {@link File#listFiles()}. This java.io API returns null 
1134   * when a dir is not a directory or for any I/O error. Instead of having
1135   * null check everywhere File#listFiles() is used, we will add utility API
1136   * to get around this problem. For the majority of cases where we prefer 
1137   * an IOException to be thrown.
1138   * @param dir directory for which listing should be performed
1139   * @return list of files or empty list
1140   * @exception IOException for invalid directory or for a bad disk.
1141   */
1142  public static File[] listFiles(File dir) throws IOException {
1143    File[] files = dir.listFiles();
1144    if(files == null) {
1145      throw new IOException("Invalid directory or I/O error occurred for dir: "
1146                + dir.toString());
1147    }
1148    return files;
1149  }  
1150  
1151  /**
1152   * A wrapper for {@link File#list()}. This java.io API returns null 
1153   * when a dir is not a directory or for any I/O error. Instead of having
1154   * null check everywhere File#list() is used, we will add utility API
1155   * to get around this problem. For the majority of cases where we prefer 
1156   * an IOException to be thrown.
1157   * @param dir directory for which listing should be performed
1158   * @return list of file names or empty string list
1159   * @exception IOException for invalid directory or for a bad disk.
1160   */
1161  public static String[] list(File dir) throws IOException {
1162    String[] fileNames = dir.list();
1163    if(fileNames == null) {
1164      throw new IOException("Invalid directory or I/O error occurred for dir: "
1165                + dir.toString());
1166    }
1167    return fileNames;
1168  }  
1169  
1170  public static String[] createJarWithClassPath(String inputClassPath, Path pwd,
1171      Map<String, String> callerEnv) throws IOException {
1172    return createJarWithClassPath(inputClassPath, pwd, pwd, callerEnv);
1173  }
1174  
1175  /**
1176   * Create a jar file at the given path, containing a manifest with a classpath
1177   * that references all specified entries.
1178   * 
1179   * Some platforms may have an upper limit on command line length.  For example,
1180   * the maximum command line length on Windows is 8191 characters, but the
1181   * length of the classpath may exceed this.  To work around this limitation,
1182   * use this method to create a small intermediate jar with a manifest that
1183   * contains the full classpath.  It returns the absolute path to the new jar,
1184   * which the caller may set as the classpath for a new process.
1185   * 
1186   * Environment variable evaluation is not supported within a jar manifest, so
1187   * this method expands environment variables before inserting classpath entries
1188   * to the manifest.  The method parses environment variables according to
1189   * platform-specific syntax (%VAR% on Windows, or $VAR otherwise).  On Windows,
1190   * environment variables are case-insensitive.  For example, %VAR% and %var%
1191   * evaluate to the same value.
1192   * 
1193   * Specifying the classpath in a jar manifest does not support wildcards, so
1194   * this method expands wildcards internally.  Any classpath entry that ends
1195   * with * is translated to all files at that path with extension .jar or .JAR.
1196   * 
1197   * @param inputClassPath String input classpath to bundle into the jar manifest
1198   * @param pwd Path to working directory to save jar
1199   * @param targetDir path to where the jar execution will have its working dir
1200   * @param callerEnv Map<String, String> caller's environment variables to use
1201   *   for expansion
1202   * @return String[] with absolute path to new jar in position 0 and
1203   *   unexpanded wild card entry path in position 1
1204   * @throws IOException if there is an I/O error while writing the jar file
1205   */
1206  public static String[] createJarWithClassPath(String inputClassPath, Path pwd,
1207      Path targetDir,
1208      Map<String, String> callerEnv) throws IOException {
1209    // Replace environment variables, case-insensitive on Windows
1210    @SuppressWarnings("unchecked")
1211    Map<String, String> env = Shell.WINDOWS ? new CaseInsensitiveMap(callerEnv) :
1212      callerEnv;
1213    String[] classPathEntries = inputClassPath.split(File.pathSeparator);
1214    for (int i = 0; i < classPathEntries.length; ++i) {
1215      classPathEntries[i] = StringUtils.replaceTokens(classPathEntries[i],
1216        StringUtils.ENV_VAR_PATTERN, env);
1217    }
1218    File workingDir = new File(pwd.toString());
1219    if (!workingDir.mkdirs()) {
1220      // If mkdirs returns false because the working directory already exists,
1221      // then this is acceptable.  If it returns false due to some other I/O
1222      // error, then this method will fail later with an IOException while saving
1223      // the jar.
1224      LOG.debug("mkdirs false for " + workingDir + ", execution will continue");
1225    }
1226
1227    StringBuilder unexpandedWildcardClasspath = new StringBuilder();
1228    // Append all entries
1229    List<String> classPathEntryList = new ArrayList<String>(
1230      classPathEntries.length);
1231    for (String classPathEntry: classPathEntries) {
1232      if (classPathEntry.length() == 0) {
1233        continue;
1234      }
1235      if (classPathEntry.endsWith("*")) {
1236        boolean foundWildCardJar = false;
1237        // Append all jars that match the wildcard
1238        Path globPath = new Path(classPathEntry).suffix("{.jar,.JAR}");
1239        FileStatus[] wildcardJars = FileContext.getLocalFSFileContext().util()
1240          .globStatus(globPath);
1241        if (wildcardJars != null) {
1242          for (FileStatus wildcardJar: wildcardJars) {
1243            foundWildCardJar = true;
1244            classPathEntryList.add(wildcardJar.getPath().toUri().toURL()
1245              .toExternalForm());
1246          }
1247        }
1248        if (!foundWildCardJar) {
1249          unexpandedWildcardClasspath.append(File.pathSeparator);
1250          unexpandedWildcardClasspath.append(classPathEntry);
1251        }
1252      } else {
1253        // Append just this entry
1254        File fileCpEntry = null;
1255        if(!new Path(classPathEntry).isAbsolute()) {
1256          fileCpEntry = new File(targetDir.toString(), classPathEntry);
1257        }
1258        else {
1259          fileCpEntry = new File(classPathEntry);
1260        }
1261        String classPathEntryUrl = fileCpEntry.toURI().toURL()
1262          .toExternalForm();
1263
1264        // File.toURI only appends trailing '/' if it can determine that it is a
1265        // directory that already exists.  (See JavaDocs.)  If this entry had a
1266        // trailing '/' specified by the caller, then guarantee that the
1267        // classpath entry in the manifest has a trailing '/', and thus refers to
1268        // a directory instead of a file.  This can happen if the caller is
1269        // creating a classpath jar referencing a directory that hasn't been
1270        // created yet, but will definitely be created before running.
1271        if (classPathEntry.endsWith(Path.SEPARATOR) &&
1272            !classPathEntryUrl.endsWith(Path.SEPARATOR)) {
1273          classPathEntryUrl = classPathEntryUrl + Path.SEPARATOR;
1274        }
1275        classPathEntryList.add(classPathEntryUrl);
1276      }
1277    }
1278    String jarClassPath = StringUtils.join(" ", classPathEntryList);
1279
1280    // Create the manifest
1281    Manifest jarManifest = new Manifest();
1282    jarManifest.getMainAttributes().putValue(
1283        Attributes.Name.MANIFEST_VERSION.toString(), "1.0");
1284    jarManifest.getMainAttributes().putValue(
1285        Attributes.Name.CLASS_PATH.toString(), jarClassPath);
1286
1287    // Write the manifest to output JAR file
1288    File classPathJar = File.createTempFile("classpath-", ".jar", workingDir);
1289    FileOutputStream fos = null;
1290    BufferedOutputStream bos = null;
1291    JarOutputStream jos = null;
1292    try {
1293      fos = new FileOutputStream(classPathJar);
1294      bos = new BufferedOutputStream(fos);
1295      jos = new JarOutputStream(bos, jarManifest);
1296    } finally {
1297      IOUtils.cleanup(LOG, jos, bos, fos);
1298    }
1299    String[] jarCp = {classPathJar.getCanonicalPath(),
1300                        unexpandedWildcardClasspath.toString()};
1301    return jarCp;
1302  }
1303
1304  public static boolean compareFs(FileSystem srcFs, FileSystem destFs) {
1305    if (srcFs==null || destFs==null) {
1306      return false;
1307    }
1308    URI srcUri = srcFs.getUri();
1309    URI dstUri = destFs.getUri();
1310    if (srcUri.getScheme()==null) {
1311      return false;
1312    }
1313    if (!srcUri.getScheme().equals(dstUri.getScheme())) {
1314      return false;
1315    }
1316    String srcHost = srcUri.getHost();
1317    String dstHost = dstUri.getHost();
1318    if ((srcHost!=null) && (dstHost!=null)) {
1319      if (srcHost.equals(dstHost)) {
1320        return srcUri.getPort()==dstUri.getPort();
1321      }
1322      try {
1323        srcHost = InetAddress.getByName(srcHost).getCanonicalHostName();
1324        dstHost = InetAddress.getByName(dstHost).getCanonicalHostName();
1325      } catch (UnknownHostException ue) {
1326        if (LOG.isDebugEnabled()) {
1327          LOG.debug("Could not compare file-systems. Unknown host: ", ue);
1328        }
1329        return false;
1330      }
1331      if (!srcHost.equals(dstHost)) {
1332        return false;
1333      }
1334    } else if (srcHost==null && dstHost!=null) {
1335      return false;
1336    } else if (srcHost!=null) {
1337      return false;
1338    }
1339    // check for ports
1340    return srcUri.getPort()==dstUri.getPort();
1341  }
1342}