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 package org.apache.hadoop.fs;
019
020 import java.io.Closeable;
021 import java.io.FileNotFoundException;
022 import java.io.IOException;
023 import java.net.URI;
024 import java.security.PrivilegedExceptionAction;
025 import java.util.ArrayList;
026 import java.util.Arrays;
027 import java.util.EnumSet;
028 import java.util.HashMap;
029 import java.util.HashSet;
030 import java.util.IdentityHashMap;
031 import java.util.Iterator;
032 import java.util.List;
033 import java.util.Map;
034 import java.util.NoSuchElementException;
035 import java.util.ServiceLoader;
036 import java.util.Set;
037 import java.util.Stack;
038 import java.util.TreeSet;
039 import java.util.concurrent.atomic.AtomicInteger;
040 import java.util.concurrent.atomic.AtomicLong;
041
042 import org.apache.commons.logging.Log;
043 import org.apache.commons.logging.LogFactory;
044 import org.apache.hadoop.classification.InterfaceAudience;
045 import org.apache.hadoop.classification.InterfaceStability;
046 import org.apache.hadoop.conf.Configuration;
047 import org.apache.hadoop.conf.Configured;
048 import org.apache.hadoop.fs.Options.Rename;
049 import org.apache.hadoop.fs.permission.FsPermission;
050 import org.apache.hadoop.io.MultipleIOException;
051 import org.apache.hadoop.net.NetUtils;
052 import org.apache.hadoop.security.Credentials;
053 import org.apache.hadoop.security.SecurityUtil;
054 import org.apache.hadoop.security.UserGroupInformation;
055 import org.apache.hadoop.security.token.Token;
056 import org.apache.hadoop.util.Progressable;
057 import org.apache.hadoop.util.ReflectionUtils;
058 import org.apache.hadoop.util.ShutdownHookManager;
059
060 /****************************************************************
061 * An abstract base class for a fairly generic filesystem. It
062 * may be implemented as a distributed filesystem, or as a "local"
063 * one that reflects the locally-connected disk. The local version
064 * exists for small Hadoop instances and for testing.
065 *
066 * <p>
067 *
068 * All user code that may potentially use the Hadoop Distributed
069 * File System should be written to use a FileSystem object. The
070 * Hadoop DFS is a multi-machine system that appears as a single
071 * disk. It's useful because of its fault tolerance and potentially
072 * very large capacity.
073 *
074 * <p>
075 * The local implementation is {@link LocalFileSystem} and distributed
076 * implementation is DistributedFileSystem.
077 *****************************************************************/
078 @InterfaceAudience.Public
079 @InterfaceStability.Stable
080 public abstract class FileSystem extends Configured implements Closeable {
081 public static final String FS_DEFAULT_NAME_KEY =
082 CommonConfigurationKeys.FS_DEFAULT_NAME_KEY;
083 public static final String DEFAULT_FS =
084 CommonConfigurationKeys.FS_DEFAULT_NAME_DEFAULT;
085
086 public static final Log LOG = LogFactory.getLog(FileSystem.class);
087
088 /**
089 * Priority of the FileSystem shutdown hook.
090 */
091 public static final int SHUTDOWN_HOOK_PRIORITY = 10;
092
093 /** FileSystem cache */
094 static final Cache CACHE = new Cache();
095
096 /** The key this instance is stored under in the cache. */
097 private Cache.Key key;
098
099 /** Recording statistics per a FileSystem class */
100 private static final Map<Class<? extends FileSystem>, Statistics>
101 statisticsTable =
102 new IdentityHashMap<Class<? extends FileSystem>, Statistics>();
103
104 /**
105 * The statistics for this file system.
106 */
107 protected Statistics statistics;
108
109 /**
110 * A cache of files that should be deleted when filsystem is closed
111 * or the JVM is exited.
112 */
113 private Set<Path> deleteOnExit = new TreeSet<Path>();
114
115 /**
116 * This method adds a file system for testing so that we can find it later. It
117 * is only for testing.
118 * @param uri the uri to store it under
119 * @param conf the configuration to store it under
120 * @param fs the file system to store
121 * @throws IOException
122 */
123 static void addFileSystemForTesting(URI uri, Configuration conf,
124 FileSystem fs) throws IOException {
125 CACHE.map.put(new Cache.Key(uri, conf), fs);
126 }
127
128 /**
129 * Get a filesystem instance based on the uri, the passed
130 * configuration and the user
131 * @param uri of the filesystem
132 * @param conf the configuration to use
133 * @param user to perform the get as
134 * @return the filesystem instance
135 * @throws IOException
136 * @throws InterruptedException
137 */
138 public static FileSystem get(final URI uri, final Configuration conf,
139 final String user) throws IOException, InterruptedException {
140 UserGroupInformation ugi;
141 if (user == null) {
142 ugi = UserGroupInformation.getCurrentUser();
143 } else {
144 ugi = UserGroupInformation.createRemoteUser(user);
145 }
146 return ugi.doAs(new PrivilegedExceptionAction<FileSystem>() {
147 public FileSystem run() throws IOException {
148 return get(uri, conf);
149 }
150 });
151 }
152
153 /**
154 * Returns the configured filesystem implementation.
155 * @param conf the configuration to use
156 */
157 public static FileSystem get(Configuration conf) throws IOException {
158 return get(getDefaultUri(conf), conf);
159 }
160
161 /** Get the default filesystem URI from a configuration.
162 * @param conf the configuration to use
163 * @return the uri of the default filesystem
164 */
165 public static URI getDefaultUri(Configuration conf) {
166 return URI.create(fixName(conf.get(FS_DEFAULT_NAME_KEY, DEFAULT_FS)));
167 }
168
169 /** Set the default filesystem URI in a configuration.
170 * @param conf the configuration to alter
171 * @param uri the new default filesystem uri
172 */
173 public static void setDefaultUri(Configuration conf, URI uri) {
174 conf.set(FS_DEFAULT_NAME_KEY, uri.toString());
175 }
176
177 /** Set the default filesystem URI in a configuration.
178 * @param conf the configuration to alter
179 * @param uri the new default filesystem uri
180 */
181 public static void setDefaultUri(Configuration conf, String uri) {
182 setDefaultUri(conf, URI.create(fixName(uri)));
183 }
184
185 /** Called after a new FileSystem instance is constructed.
186 * @param name a uri whose authority section names the host, port, etc.
187 * for this FileSystem
188 * @param conf the configuration
189 */
190 public void initialize(URI name, Configuration conf) throws IOException {
191 statistics = getStatistics(name.getScheme(), getClass());
192 }
193
194 /**
195 * Return the protocol scheme for the FileSystem.
196 * <p/>
197 * This implementation throws an <code>UnsupportedOperationException</code>.
198 *
199 * @return the protocol scheme for the FileSystem.
200 */
201 public String getScheme() {
202 throw new UnsupportedOperationException("Not implemented by the " + getClass().getSimpleName() + " FileSystem implementation");
203 }
204
205 /** Returns a URI whose scheme and authority identify this FileSystem.*/
206 public abstract URI getUri();
207
208 /**
209 * Resolve the uri's hostname and add the default port if not in the uri
210 * @return URI
211 * @see NetUtils#getCanonicalUri(URI, int)
212 */
213 protected URI getCanonicalUri() {
214 return NetUtils.getCanonicalUri(getUri(), getDefaultPort());
215 }
216
217 /**
218 * Get the default port for this file system.
219 * @return the default port or 0 if there isn't one
220 */
221 protected int getDefaultPort() {
222 return 0;
223 }
224
225 /**
226 * Get a canonical service name for this file system. The token cache is
227 * the only user of this value, and uses it to lookup this filesystem's
228 * service tokens. The token cache will not attempt to acquire tokens if the
229 * service is null.
230 * @return a service string that uniquely identifies this file system, null
231 * if the filesystem does not implement tokens
232 * @see SecurityUtil#buildDTServiceName(URI, int)
233 */
234 public String getCanonicalServiceName() {
235 return SecurityUtil.buildDTServiceName(getUri(), getDefaultPort());
236 }
237
238 /** @deprecated call #getUri() instead.*/
239 @Deprecated
240 public String getName() { return getUri().toString(); }
241
242 /** @deprecated call #get(URI,Configuration) instead. */
243 @Deprecated
244 public static FileSystem getNamed(String name, Configuration conf)
245 throws IOException {
246 return get(URI.create(fixName(name)), conf);
247 }
248
249 /** Update old-format filesystem names, for back-compatibility. This should
250 * eventually be replaced with a checkName() method that throws an exception
251 * for old-format names. */
252 private static String fixName(String name) {
253 // convert old-format name to new-format name
254 if (name.equals("local")) { // "local" is now "file:///".
255 LOG.warn("\"local\" is a deprecated filesystem name."
256 +" Use \"file:///\" instead.");
257 name = "file:///";
258 } else if (name.indexOf('/')==-1) { // unqualified is "hdfs://"
259 LOG.warn("\""+name+"\" is a deprecated filesystem name."
260 +" Use \"hdfs://"+name+"/\" instead.");
261 name = "hdfs://"+name;
262 }
263 return name;
264 }
265
266 /**
267 * Get the local file system.
268 * @param conf the configuration to configure the file system with
269 * @return a LocalFileSystem
270 */
271 public static LocalFileSystem getLocal(Configuration conf)
272 throws IOException {
273 return (LocalFileSystem)get(LocalFileSystem.NAME, conf);
274 }
275
276 /** Returns the FileSystem for this URI's scheme and authority. The scheme
277 * of the URI determines a configuration property name,
278 * <tt>fs.<i>scheme</i>.class</tt> whose value names the FileSystem class.
279 * The entire URI is passed to the FileSystem instance's initialize method.
280 */
281 public static FileSystem get(URI uri, Configuration conf) throws IOException {
282 String scheme = uri.getScheme();
283 String authority = uri.getAuthority();
284
285 if (scheme == null) { // no scheme: use default FS
286 return get(conf);
287 }
288
289 if (authority == null) { // no authority
290 URI defaultUri = getDefaultUri(conf);
291 if (scheme.equals(defaultUri.getScheme()) // if scheme matches default
292 && defaultUri.getAuthority() != null) { // & default has authority
293 return get(defaultUri, conf); // return default
294 }
295 }
296
297 String disableCacheName = String.format("fs.%s.impl.disable.cache", scheme);
298 if (conf.getBoolean(disableCacheName, false)) {
299 return createFileSystem(uri, conf);
300 }
301
302 return CACHE.get(uri, conf);
303 }
304
305 /**
306 * Returns the FileSystem for this URI's scheme and authority and the
307 * passed user. Internally invokes {@link #newInstance(URI, Configuration)}
308 * @param uri of the filesystem
309 * @param conf the configuration to use
310 * @param user to perform the get as
311 * @return filesystem instance
312 * @throws IOException
313 * @throws InterruptedException
314 */
315 public static FileSystem newInstance(final URI uri, final Configuration conf,
316 final String user) throws IOException, InterruptedException {
317 UserGroupInformation ugi;
318 if (user == null) {
319 ugi = UserGroupInformation.getCurrentUser();
320 } else {
321 ugi = UserGroupInformation.createRemoteUser(user);
322 }
323 return ugi.doAs(new PrivilegedExceptionAction<FileSystem>() {
324 public FileSystem run() throws IOException {
325 return newInstance(uri,conf);
326 }
327 });
328 }
329 /** Returns the FileSystem for this URI's scheme and authority. The scheme
330 * of the URI determines a configuration property name,
331 * <tt>fs.<i>scheme</i>.class</tt> whose value names the FileSystem class.
332 * The entire URI is passed to the FileSystem instance's initialize method.
333 * This always returns a new FileSystem object.
334 */
335 public static FileSystem newInstance(URI uri, Configuration conf) throws IOException {
336 String scheme = uri.getScheme();
337 String authority = uri.getAuthority();
338
339 if (scheme == null) { // no scheme: use default FS
340 return newInstance(conf);
341 }
342
343 if (authority == null) { // no authority
344 URI defaultUri = getDefaultUri(conf);
345 if (scheme.equals(defaultUri.getScheme()) // if scheme matches default
346 && defaultUri.getAuthority() != null) { // & default has authority
347 return newInstance(defaultUri, conf); // return default
348 }
349 }
350 return CACHE.getUnique(uri, conf);
351 }
352
353 /** Returns a unique configured filesystem implementation.
354 * This always returns a new FileSystem object.
355 * @param conf the configuration to use
356 */
357 public static FileSystem newInstance(Configuration conf) throws IOException {
358 return newInstance(getDefaultUri(conf), conf);
359 }
360
361 /**
362 * Get a unique local file system object
363 * @param conf the configuration to configure the file system with
364 * @return a LocalFileSystem
365 * This always returns a new FileSystem object.
366 */
367 public static LocalFileSystem newInstanceLocal(Configuration conf)
368 throws IOException {
369 return (LocalFileSystem)newInstance(LocalFileSystem.NAME, conf);
370 }
371
372 /**
373 * Close all cached filesystems. Be sure those filesystems are not
374 * used anymore.
375 *
376 * @throws IOException
377 */
378 public static void closeAll() throws IOException {
379 CACHE.closeAll();
380 }
381
382 /**
383 * Close all cached filesystems for a given UGI. Be sure those filesystems
384 * are not used anymore.
385 * @param ugi user group info to close
386 * @throws IOException
387 */
388 public static void closeAllForUGI(UserGroupInformation ugi)
389 throws IOException {
390 CACHE.closeAll(ugi);
391 }
392
393 /**
394 * Make sure that a path specifies a FileSystem.
395 * @param path to use
396 */
397 public Path makeQualified(Path path) {
398 checkPath(path);
399 return path.makeQualified(this.getUri(), this.getWorkingDirectory());
400 }
401
402 /**
403 * Deprecated - use @link {@link #getDelegationTokens(String)}
404 * Get a new delegation token for this file system.
405 * @param renewer the account name that is allowed to renew the token.
406 * @return a new delegation token
407 * @throws IOException
408 */
409 @InterfaceAudience.LimitedPrivate({"HDFS", "MapReduce"})
410 @Deprecated
411 public Token<?> getDelegationToken(String renewer) throws IOException {
412 return null;
413 }
414
415 /**
416 * Get one or more delegation tokens associated with the filesystem. Normally
417 * a file system returns a single delegation token. A file system that manages
418 * multiple file systems underneath, could return set of delegation tokens for
419 * all the file systems it manages.
420 *
421 * @param renewer the account name that is allowed to renew the token.
422 * @return list of new delegation tokens
423 * If delegation tokens not supported then return a list of size zero.
424 * @throws IOException
425 */
426 @InterfaceAudience.LimitedPrivate( { "HDFS", "MapReduce" })
427 public List<Token<?>> getDelegationTokens(String renewer) throws IOException {
428 return new ArrayList<Token<?>>(0);
429 }
430
431 /**
432 * @see #getDelegationTokens(String)
433 * This is similar to getDelegationTokens, with the added restriction that if
434 * a token is already present in the passed Credentials object - that token
435 * is returned instead of a new delegation token.
436 *
437 * If the token is found to be cached in the Credentials object, this API does
438 * not verify the token validity or the passed in renewer.
439 *
440 *
441 * @param renewer the account name that is allowed to renew the token.
442 * @param credentials a Credentials object containing already knowing
443 * delegationTokens.
444 * @return a list of delegation tokens.
445 * @throws IOException
446 */
447 @InterfaceAudience.LimitedPrivate({ "HDFS", "MapReduce" })
448 public List<Token<?>> getDelegationTokens(String renewer,
449 Credentials credentials) throws IOException {
450 List<Token<?>> allTokens = getDelegationTokens(renewer);
451 List<Token<?>> newTokens = new ArrayList<Token<?>>();
452 if (allTokens != null) {
453 for (Token<?> token : allTokens) {
454 Token<?> knownToken = credentials.getToken(token.getService());
455 if (knownToken == null) {
456 newTokens.add(token);
457 } else {
458 newTokens.add(knownToken);
459 }
460 }
461 }
462 return newTokens;
463 }
464
465 /** create a file with the provided permission
466 * The permission of the file is set to be the provided permission as in
467 * setPermission, not permission&~umask
468 *
469 * It is implemented using two RPCs. It is understood that it is inefficient,
470 * but the implementation is thread-safe. The other option is to change the
471 * value of umask in configuration to be 0, but it is not thread-safe.
472 *
473 * @param fs file system handle
474 * @param file the name of the file to be created
475 * @param permission the permission of the file
476 * @return an output stream
477 * @throws IOException
478 */
479 public static FSDataOutputStream create(FileSystem fs,
480 Path file, FsPermission permission) throws IOException {
481 // create the file with default permission
482 FSDataOutputStream out = fs.create(file);
483 // set its permission to the supplied one
484 fs.setPermission(file, permission);
485 return out;
486 }
487
488 /** create a directory with the provided permission
489 * The permission of the directory is set to be the provided permission as in
490 * setPermission, not permission&~umask
491 *
492 * @see #create(FileSystem, Path, FsPermission)
493 *
494 * @param fs file system handle
495 * @param dir the name of the directory to be created
496 * @param permission the permission of the directory
497 * @return true if the directory creation succeeds; false otherwise
498 * @throws IOException
499 */
500 public static boolean mkdirs(FileSystem fs, Path dir, FsPermission permission)
501 throws IOException {
502 // create the directory using the default permission
503 boolean result = fs.mkdirs(dir);
504 // set its permission to be the supplied one
505 fs.setPermission(dir, permission);
506 return result;
507 }
508
509 ///////////////////////////////////////////////////////////////
510 // FileSystem
511 ///////////////////////////////////////////////////////////////
512
513 protected FileSystem() {
514 super(null);
515 }
516
517 /**
518 * Check that a Path belongs to this FileSystem.
519 * @param path to check
520 */
521 protected void checkPath(Path path) {
522 URI uri = path.toUri();
523 String thatScheme = uri.getScheme();
524 if (thatScheme == null) // fs is relative
525 return;
526 URI thisUri = getCanonicalUri();
527 String thisScheme = thisUri.getScheme();
528 //authority and scheme are not case sensitive
529 if (thisScheme.equalsIgnoreCase(thatScheme)) {// schemes match
530 String thisAuthority = thisUri.getAuthority();
531 String thatAuthority = uri.getAuthority();
532 if (thatAuthority == null && // path's authority is null
533 thisAuthority != null) { // fs has an authority
534 URI defaultUri = getDefaultUri(getConf());
535 if (thisScheme.equalsIgnoreCase(defaultUri.getScheme())) {
536 uri = defaultUri; // schemes match, so use this uri instead
537 } else {
538 uri = null; // can't determine auth of the path
539 }
540 }
541 if (uri != null) {
542 // canonicalize uri before comparing with this fs
543 uri = NetUtils.getCanonicalUri(uri, getDefaultPort());
544 thatAuthority = uri.getAuthority();
545 if (thisAuthority == thatAuthority || // authorities match
546 (thisAuthority != null &&
547 thisAuthority.equalsIgnoreCase(thatAuthority)))
548 return;
549 }
550 }
551 throw new IllegalArgumentException("Wrong FS: "+path+
552 ", expected: "+this.getUri());
553 }
554
555 /**
556 * Return an array containing hostnames, offset and size of
557 * portions of the given file. For a nonexistent
558 * file or regions, null will be returned.
559 *
560 * This call is most helpful with DFS, where it returns
561 * hostnames of machines that contain the given file.
562 *
563 * The FileSystem will simply return an elt containing 'localhost'.
564 *
565 * @param file FilesStatus to get data from
566 * @param start offset into the given file
567 * @param len length for which to get locations for
568 */
569 public BlockLocation[] getFileBlockLocations(FileStatus file,
570 long start, long len) throws IOException {
571 if (file == null) {
572 return null;
573 }
574
575 if (start < 0 || len < 0) {
576 throw new IllegalArgumentException("Invalid start or len parameter");
577 }
578
579 if (file.getLen() < start) {
580 return new BlockLocation[0];
581
582 }
583 String[] name = { "localhost:50010" };
584 String[] host = { "localhost" };
585 return new BlockLocation[] {
586 new BlockLocation(name, host, 0, file.getLen()) };
587 }
588
589
590 /**
591 * Return an array containing hostnames, offset and size of
592 * portions of the given file. For a nonexistent
593 * file or regions, null will be returned.
594 *
595 * This call is most helpful with DFS, where it returns
596 * hostnames of machines that contain the given file.
597 *
598 * The FileSystem will simply return an elt containing 'localhost'.
599 *
600 * @param p path is used to identify an FS since an FS could have
601 * another FS that it could be delegating the call to
602 * @param start offset into the given file
603 * @param len length for which to get locations for
604 */
605 public BlockLocation[] getFileBlockLocations(Path p,
606 long start, long len) throws IOException {
607 if (p == null) {
608 throw new NullPointerException();
609 }
610 FileStatus file = getFileStatus(p);
611 return getFileBlockLocations(file, start, len);
612 }
613
614 /**
615 * Return a set of server default configuration values
616 * @return server default configuration values
617 * @throws IOException
618 * @deprecated use {@link #getServerDefaults(Path)} instead
619 */
620 @Deprecated
621 public FsServerDefaults getServerDefaults() throws IOException {
622 Configuration conf = getConf();
623 return new FsServerDefaults(getDefaultBlockSize(),
624 conf.getInt("io.bytes.per.checksum", 512),
625 64 * 1024,
626 getDefaultReplication(),
627 conf.getInt("io.file.buffer.size", 4096));
628 }
629
630 /**
631 * Return a set of server default configuration values
632 * @param p path is used to identify an FS since an FS could have
633 * another FS that it could be delegating the call to
634 * @return server default configuration values
635 * @throws IOException
636 */
637 public FsServerDefaults getServerDefaults(Path p) throws IOException {
638 return getServerDefaults();
639 }
640
641 /**
642 * Return the fully-qualified path of path f resolving the path
643 * through any symlinks or mount point
644 * @param p path to be resolved
645 * @return fully qualified path
646 * @throws FileNotFoundException
647 */
648 public Path resolvePath(final Path p) throws IOException {
649 checkPath(p);
650 return getFileStatus(p).getPath();
651 }
652
653 /**
654 * Opens an FSDataInputStream at the indicated Path.
655 * @param f the file name to open
656 * @param bufferSize the size of the buffer to be used.
657 */
658 public abstract FSDataInputStream open(Path f, int bufferSize)
659 throws IOException;
660
661 /**
662 * Opens an FSDataInputStream at the indicated Path.
663 * @param f the file to open
664 */
665 public FSDataInputStream open(Path f) throws IOException {
666 return open(f, getConf().getInt("io.file.buffer.size", 4096));
667 }
668
669 /**
670 * Create an FSDataOutputStream at the indicated Path.
671 * Files are overwritten by default.
672 * @param f the file to create
673 */
674 public FSDataOutputStream create(Path f) throws IOException {
675 return create(f, true);
676 }
677
678 /**
679 * Create an FSDataOutputStream at the indicated Path.
680 * @param f the file to create
681 * @param overwrite if a file with this name already exists, then if true,
682 * the file will be overwritten, and if false an exception will be thrown.
683 */
684 public FSDataOutputStream create(Path f, boolean overwrite)
685 throws IOException {
686 return create(f, overwrite,
687 getConf().getInt("io.file.buffer.size", 4096),
688 getDefaultReplication(f),
689 getDefaultBlockSize(f));
690 }
691
692 /**
693 * Create an FSDataOutputStream at the indicated Path with write-progress
694 * reporting.
695 * Files are overwritten by default.
696 * @param f the file to create
697 * @param progress to report progress
698 */
699 public FSDataOutputStream create(Path f, Progressable progress)
700 throws IOException {
701 return create(f, true,
702 getConf().getInt("io.file.buffer.size", 4096),
703 getDefaultReplication(f),
704 getDefaultBlockSize(f), progress);
705 }
706
707 /**
708 * Create an FSDataOutputStream at the indicated Path.
709 * Files are overwritten by default.
710 * @param f the file to create
711 * @param replication the replication factor
712 */
713 public FSDataOutputStream create(Path f, short replication)
714 throws IOException {
715 return create(f, true,
716 getConf().getInt("io.file.buffer.size", 4096),
717 replication,
718 getDefaultBlockSize(f));
719 }
720
721 /**
722 * Create an FSDataOutputStream at the indicated Path with write-progress
723 * reporting.
724 * Files are overwritten by default.
725 * @param f the file to create
726 * @param replication the replication factor
727 * @param progress to report progress
728 */
729 public FSDataOutputStream create(Path f, short replication,
730 Progressable progress) throws IOException {
731 return create(f, true,
732 getConf().getInt("io.file.buffer.size", 4096),
733 replication,
734 getDefaultBlockSize(f), progress);
735 }
736
737
738 /**
739 * Create an FSDataOutputStream at the indicated Path.
740 * @param f the file name to create
741 * @param overwrite if a file with this name already exists, then if true,
742 * the file will be overwritten, and if false an error will be thrown.
743 * @param bufferSize the size of the buffer to be used.
744 */
745 public FSDataOutputStream create(Path f,
746 boolean overwrite,
747 int bufferSize
748 ) throws IOException {
749 return create(f, overwrite, bufferSize,
750 getDefaultReplication(f),
751 getDefaultBlockSize(f));
752 }
753
754 /**
755 * Create an FSDataOutputStream at the indicated Path with write-progress
756 * reporting.
757 * @param f the path of the file to open
758 * @param overwrite if a file with this name already exists, then if true,
759 * the file will be overwritten, and if false an error will be thrown.
760 * @param bufferSize the size of the buffer to be used.
761 */
762 public FSDataOutputStream create(Path f,
763 boolean overwrite,
764 int bufferSize,
765 Progressable progress
766 ) throws IOException {
767 return create(f, overwrite, bufferSize,
768 getDefaultReplication(f),
769 getDefaultBlockSize(f), progress);
770 }
771
772
773 /**
774 * Create an FSDataOutputStream at the indicated Path.
775 * @param f the file name to open
776 * @param overwrite if a file with this name already exists, then if true,
777 * the file will be overwritten, and if false an error will be thrown.
778 * @param bufferSize the size of the buffer to be used.
779 * @param replication required block replication for the file.
780 */
781 public FSDataOutputStream create(Path f,
782 boolean overwrite,
783 int bufferSize,
784 short replication,
785 long blockSize
786 ) throws IOException {
787 return create(f, overwrite, bufferSize, replication, blockSize, null);
788 }
789
790 /**
791 * Create an FSDataOutputStream at the indicated Path with write-progress
792 * reporting.
793 * @param f the file name to open
794 * @param overwrite if a file with this name already exists, then if true,
795 * the file will be overwritten, and if false an error will be thrown.
796 * @param bufferSize the size of the buffer to be used.
797 * @param replication required block replication for the file.
798 */
799 public FSDataOutputStream create(Path f,
800 boolean overwrite,
801 int bufferSize,
802 short replication,
803 long blockSize,
804 Progressable progress
805 ) throws IOException {
806 return this.create(f, FsPermission.getDefault().applyUMask(
807 FsPermission.getUMask(getConf())), overwrite, bufferSize,
808 replication, blockSize, progress);
809 }
810
811 /**
812 * Create an FSDataOutputStream at the indicated Path with write-progress
813 * reporting.
814 * @param f the file name to open
815 * @param permission
816 * @param overwrite if a file with this name already exists, then if true,
817 * the file will be overwritten, and if false an error will be thrown.
818 * @param bufferSize the size of the buffer to be used.
819 * @param replication required block replication for the file.
820 * @param blockSize
821 * @param progress
822 * @throws IOException
823 * @see #setPermission(Path, FsPermission)
824 */
825 public abstract FSDataOutputStream create(Path f,
826 FsPermission permission,
827 boolean overwrite,
828 int bufferSize,
829 short replication,
830 long blockSize,
831 Progressable progress) throws IOException;
832
833
834 /*.
835 * This create has been added to support the FileContext that processes
836 * the permission
837 * with umask before calling this method.
838 * This a temporary method added to support the transition from FileSystem
839 * to FileContext for user applications.
840 */
841 @Deprecated
842 protected FSDataOutputStream primitiveCreate(Path f,
843 FsPermission absolutePermission, EnumSet<CreateFlag> flag, int bufferSize,
844 short replication, long blockSize, Progressable progress,
845 int bytesPerChecksum) throws IOException {
846
847 boolean pathExists = exists(f);
848 CreateFlag.validate(f, pathExists, flag);
849
850 // Default impl assumes that permissions do not matter and
851 // nor does the bytesPerChecksum hence
852 // calling the regular create is good enough.
853 // FSs that implement permissions should override this.
854
855 if (pathExists && flag.contains(CreateFlag.APPEND)) {
856 return append(f, bufferSize, progress);
857 }
858
859 return this.create(f, absolutePermission,
860 flag.contains(CreateFlag.OVERWRITE), bufferSize, replication,
861 blockSize, progress);
862 }
863
864 /**
865 * This version of the mkdirs method assumes that the permission is absolute.
866 * It has been added to support the FileContext that processes the permission
867 * with umask before calling this method.
868 * This a temporary method added to support the transition from FileSystem
869 * to FileContext for user applications.
870 */
871 @Deprecated
872 protected boolean primitiveMkdir(Path f, FsPermission absolutePermission)
873 throws IOException {
874 // Default impl is to assume that permissions do not matter and hence
875 // calling the regular mkdirs is good enough.
876 // FSs that implement permissions should override this.
877 return this.mkdirs(f, absolutePermission);
878 }
879
880
881 /**
882 * This version of the mkdirs method assumes that the permission is absolute.
883 * It has been added to support the FileContext that processes the permission
884 * with umask before calling this method.
885 * This a temporary method added to support the transition from FileSystem
886 * to FileContext for user applications.
887 */
888 @Deprecated
889 protected void primitiveMkdir(Path f, FsPermission absolutePermission,
890 boolean createParent)
891 throws IOException {
892
893 if (!createParent) { // parent must exist.
894 // since the this.mkdirs makes parent dirs automatically
895 // we must throw exception if parent does not exist.
896 final FileStatus stat = getFileStatus(f.getParent());
897 if (stat == null) {
898 throw new FileNotFoundException("Missing parent:" + f);
899 }
900 if (!stat.isDirectory()) {
901 throw new ParentNotDirectoryException("parent is not a dir");
902 }
903 // parent does exist - go ahead with mkdir of leaf
904 }
905 // Default impl is to assume that permissions do not matter and hence
906 // calling the regular mkdirs is good enough.
907 // FSs that implement permissions should override this.
908 if (!this.mkdirs(f, absolutePermission)) {
909 throw new IOException("mkdir of "+ f + " failed");
910 }
911 }
912
913 /**
914 * Opens an FSDataOutputStream at the indicated Path with write-progress
915 * reporting. Same as create(), except fails if parent directory doesn't
916 * already exist.
917 * @param f the file name to open
918 * @param overwrite if a file with this name already exists, then if true,
919 * the file will be overwritten, and if false an error will be thrown.
920 * @param bufferSize the size of the buffer to be used.
921 * @param replication required block replication for the file.
922 * @param blockSize
923 * @param progress
924 * @throws IOException
925 * @see #setPermission(Path, FsPermission)
926 * @deprecated API only for 0.20-append
927 */
928 @Deprecated
929 public FSDataOutputStream createNonRecursive(Path f,
930 boolean overwrite,
931 int bufferSize, short replication, long blockSize,
932 Progressable progress) throws IOException {
933 return this.createNonRecursive(f, FsPermission.getDefault(),
934 overwrite, bufferSize, replication, blockSize, progress);
935 }
936
937 /**
938 * Opens an FSDataOutputStream at the indicated Path with write-progress
939 * reporting. Same as create(), except fails if parent directory doesn't
940 * already exist.
941 * @param f the file name to open
942 * @param permission
943 * @param overwrite if a file with this name already exists, then if true,
944 * the file will be overwritten, and if false an error will be thrown.
945 * @param bufferSize the size of the buffer to be used.
946 * @param replication required block replication for the file.
947 * @param blockSize
948 * @param progress
949 * @throws IOException
950 * @see #setPermission(Path, FsPermission)
951 * @deprecated API only for 0.20-append
952 */
953 @Deprecated
954 public FSDataOutputStream createNonRecursive(Path f, FsPermission permission,
955 boolean overwrite, int bufferSize, short replication, long blockSize,
956 Progressable progress) throws IOException {
957 throw new IOException("createNonRecursive unsupported for this filesystem "
958 + this.getClass());
959 }
960
961 /**
962 * Creates the given Path as a brand-new zero-length file. If
963 * create fails, or if it already existed, return false.
964 *
965 * @param f path to use for create
966 */
967 public boolean createNewFile(Path f) throws IOException {
968 if (exists(f)) {
969 return false;
970 } else {
971 create(f, false, getConf().getInt("io.file.buffer.size", 4096)).close();
972 return true;
973 }
974 }
975
976 /**
977 * Append to an existing file (optional operation).
978 * Same as append(f, getConf().getInt("io.file.buffer.size", 4096), null)
979 * @param f the existing file to be appended.
980 * @throws IOException
981 */
982 public FSDataOutputStream append(Path f) throws IOException {
983 return append(f, getConf().getInt("io.file.buffer.size", 4096), null);
984 }
985 /**
986 * Append to an existing file (optional operation).
987 * Same as append(f, bufferSize, null).
988 * @param f the existing file to be appended.
989 * @param bufferSize the size of the buffer to be used.
990 * @throws IOException
991 */
992 public FSDataOutputStream append(Path f, int bufferSize) throws IOException {
993 return append(f, bufferSize, null);
994 }
995
996 /**
997 * Append to an existing file (optional operation).
998 * @param f the existing file to be appended.
999 * @param bufferSize the size of the buffer to be used.
1000 * @param progress for reporting progress if it is not null.
1001 * @throws IOException
1002 */
1003 public abstract FSDataOutputStream append(Path f, int bufferSize,
1004 Progressable progress) throws IOException;
1005
1006 /**
1007 * Get replication.
1008 *
1009 * @deprecated Use getFileStatus() instead
1010 * @param src file name
1011 * @return file replication
1012 * @throws IOException
1013 */
1014 @Deprecated
1015 public short getReplication(Path src) throws IOException {
1016 return getFileStatus(src).getReplication();
1017 }
1018
1019 /**
1020 * Set replication for an existing file.
1021 *
1022 * @param src file name
1023 * @param replication new replication
1024 * @throws IOException
1025 * @return true if successful;
1026 * false if file does not exist or is a directory
1027 */
1028 public boolean setReplication(Path src, short replication)
1029 throws IOException {
1030 return true;
1031 }
1032
1033 /**
1034 * Renames Path src to Path dst. Can take place on local fs
1035 * or remote DFS.
1036 * @param src path to be renamed
1037 * @param dst new path after rename
1038 * @throws IOException on failure
1039 * @return true if rename is successful
1040 */
1041 public abstract boolean rename(Path src, Path dst) throws IOException;
1042
1043 /**
1044 * Renames Path src to Path dst
1045 * <ul>
1046 * <li
1047 * <li>Fails if src is a file and dst is a directory.
1048 * <li>Fails if src is a directory and dst is a file.
1049 * <li>Fails if the parent of dst does not exist or is a file.
1050 * </ul>
1051 * <p>
1052 * If OVERWRITE option is not passed as an argument, rename fails
1053 * if the dst already exists.
1054 * <p>
1055 * If OVERWRITE option is passed as an argument, rename overwrites
1056 * the dst if it is a file or an empty directory. Rename fails if dst is
1057 * a non-empty directory.
1058 * <p>
1059 * Note that atomicity of rename is dependent on the file system
1060 * implementation. Please refer to the file system documentation for
1061 * details. This default implementation is non atomic.
1062 * <p>
1063 * This method is deprecated since it is a temporary method added to
1064 * support the transition from FileSystem to FileContext for user
1065 * applications.
1066 *
1067 * @param src path to be renamed
1068 * @param dst new path after rename
1069 * @throws IOException on failure
1070 */
1071 @Deprecated
1072 protected void rename(final Path src, final Path dst,
1073 final Rename... options) throws IOException {
1074 // Default implementation
1075 final FileStatus srcStatus = getFileStatus(src);
1076 if (srcStatus == null) {
1077 throw new FileNotFoundException("rename source " + src + " not found.");
1078 }
1079
1080 boolean overwrite = false;
1081 if (null != options) {
1082 for (Rename option : options) {
1083 if (option == Rename.OVERWRITE) {
1084 overwrite = true;
1085 }
1086 }
1087 }
1088
1089 FileStatus dstStatus;
1090 try {
1091 dstStatus = getFileStatus(dst);
1092 } catch (IOException e) {
1093 dstStatus = null;
1094 }
1095 if (dstStatus != null) {
1096 if (srcStatus.isDirectory() != dstStatus.isDirectory()) {
1097 throw new IOException("Source " + src + " Destination " + dst
1098 + " both should be either file or directory");
1099 }
1100 if (!overwrite) {
1101 throw new FileAlreadyExistsException("rename destination " + dst
1102 + " already exists.");
1103 }
1104 // Delete the destination that is a file or an empty directory
1105 if (dstStatus.isDirectory()) {
1106 FileStatus[] list = listStatus(dst);
1107 if (list != null && list.length != 0) {
1108 throw new IOException(
1109 "rename cannot overwrite non empty destination directory " + dst);
1110 }
1111 }
1112 delete(dst, false);
1113 } else {
1114 final Path parent = dst.getParent();
1115 final FileStatus parentStatus = getFileStatus(parent);
1116 if (parentStatus == null) {
1117 throw new FileNotFoundException("rename destination parent " + parent
1118 + " not found.");
1119 }
1120 if (!parentStatus.isDirectory()) {
1121 throw new ParentNotDirectoryException("rename destination parent " + parent
1122 + " is a file.");
1123 }
1124 }
1125 if (!rename(src, dst)) {
1126 throw new IOException("rename from " + src + " to " + dst + " failed.");
1127 }
1128 }
1129
1130 /**
1131 * Delete a file
1132 * @deprecated Use {@link #delete(Path, boolean)} instead.
1133 */
1134 @Deprecated
1135 public boolean delete(Path f) throws IOException {
1136 return delete(f, true);
1137 }
1138
1139 /** Delete a file.
1140 *
1141 * @param f the path to delete.
1142 * @param recursive if path is a directory and set to
1143 * true, the directory is deleted else throws an exception. In
1144 * case of a file the recursive can be set to either true or false.
1145 * @return true if delete is successful else false.
1146 * @throws IOException
1147 */
1148 public abstract boolean delete(Path f, boolean recursive) throws IOException;
1149
1150 /**
1151 * Mark a path to be deleted when FileSystem is closed.
1152 * When the JVM shuts down,
1153 * all FileSystem objects will be closed automatically.
1154 * Then,
1155 * the marked path will be deleted as a result of closing the FileSystem.
1156 *
1157 * The path has to exist in the file system.
1158 *
1159 * @param f the path to delete.
1160 * @return true if deleteOnExit is successful, otherwise false.
1161 * @throws IOException
1162 */
1163 public boolean deleteOnExit(Path f) throws IOException {
1164 if (!exists(f)) {
1165 return false;
1166 }
1167 synchronized (deleteOnExit) {
1168 deleteOnExit.add(f);
1169 }
1170 return true;
1171 }
1172
1173 /**
1174 * Delete all files that were marked as delete-on-exit. This recursively
1175 * deletes all files in the specified paths.
1176 */
1177 protected void processDeleteOnExit() {
1178 synchronized (deleteOnExit) {
1179 for (Iterator<Path> iter = deleteOnExit.iterator(); iter.hasNext();) {
1180 Path path = iter.next();
1181 try {
1182 delete(path, true);
1183 }
1184 catch (IOException e) {
1185 LOG.info("Ignoring failure to deleteOnExit for path " + path);
1186 }
1187 iter.remove();
1188 }
1189 }
1190 }
1191
1192 /** Check if exists.
1193 * @param f source file
1194 */
1195 public boolean exists(Path f) throws IOException {
1196 try {
1197 return getFileStatus(f) != null;
1198 } catch (FileNotFoundException e) {
1199 return false;
1200 }
1201 }
1202
1203 /** True iff the named path is a directory.
1204 * Note: Avoid using this method. Instead reuse the FileStatus
1205 * returned by getFileStatus() or listStatus() methods.
1206 * @param f path to check
1207 */
1208 public boolean isDirectory(Path f) throws IOException {
1209 try {
1210 return getFileStatus(f).isDirectory();
1211 } catch (FileNotFoundException e) {
1212 return false; // f does not exist
1213 }
1214 }
1215
1216 /** True iff the named path is a regular file.
1217 * Note: Avoid using this method. Instead reuse the FileStatus
1218 * returned by getFileStatus() or listStatus() methods.
1219 * @param f path to check
1220 */
1221 public boolean isFile(Path f) throws IOException {
1222 try {
1223 return getFileStatus(f).isFile();
1224 } catch (FileNotFoundException e) {
1225 return false; // f does not exist
1226 }
1227 }
1228
1229 /** The number of bytes in a file. */
1230 /** @deprecated Use getFileStatus() instead */
1231 @Deprecated
1232 public long getLength(Path f) throws IOException {
1233 return getFileStatus(f).getLen();
1234 }
1235
1236 /** Return the {@link ContentSummary} of a given {@link Path}.
1237 * @param f path to use
1238 */
1239 public ContentSummary getContentSummary(Path f) throws IOException {
1240 FileStatus status = getFileStatus(f);
1241 if (status.isFile()) {
1242 // f is a file
1243 return new ContentSummary(status.getLen(), 1, 0);
1244 }
1245 // f is a directory
1246 long[] summary = {0, 0, 1};
1247 for(FileStatus s : listStatus(f)) {
1248 ContentSummary c = s.isDirectory() ? getContentSummary(s.getPath()) :
1249 new ContentSummary(s.getLen(), 1, 0);
1250 summary[0] += c.getLength();
1251 summary[1] += c.getFileCount();
1252 summary[2] += c.getDirectoryCount();
1253 }
1254 return new ContentSummary(summary[0], summary[1], summary[2]);
1255 }
1256
1257 final private static PathFilter DEFAULT_FILTER = new PathFilter() {
1258 public boolean accept(Path file) {
1259 return true;
1260 }
1261 };
1262
1263 /**
1264 * List the statuses of the files/directories in the given path if the path is
1265 * a directory.
1266 *
1267 * @param f given path
1268 * @return the statuses of the files/directories in the given patch
1269 * @throws FileNotFoundException when the path does not exist;
1270 * IOException see specific implementation
1271 */
1272 public abstract FileStatus[] listStatus(Path f) throws FileNotFoundException,
1273 IOException;
1274
1275 /*
1276 * Filter files/directories in the given path using the user-supplied path
1277 * filter. Results are added to the given array <code>results</code>.
1278 */
1279 private void listStatus(ArrayList<FileStatus> results, Path f,
1280 PathFilter filter) throws FileNotFoundException, IOException {
1281 FileStatus listing[] = listStatus(f);
1282 if (listing == null) {
1283 throw new IOException("Error accessing " + f);
1284 }
1285
1286 for (int i = 0; i < listing.length; i++) {
1287 if (filter.accept(listing[i].getPath())) {
1288 results.add(listing[i]);
1289 }
1290 }
1291 }
1292
1293 /**
1294 * @return an iterator over the corrupt files under the given path
1295 * (may contain duplicates if a file has more than one corrupt block)
1296 * @throws IOException
1297 */
1298 public RemoteIterator<Path> listCorruptFileBlocks(Path path)
1299 throws IOException {
1300 throw new UnsupportedOperationException(getClass().getCanonicalName() +
1301 " does not support" +
1302 " listCorruptFileBlocks");
1303 }
1304
1305 /**
1306 * Filter files/directories in the given path using the user-supplied path
1307 * filter.
1308 *
1309 * @param f
1310 * a path name
1311 * @param filter
1312 * the user-supplied path filter
1313 * @return an array of FileStatus objects for the files under the given path
1314 * after applying the filter
1315 * @throws FileNotFoundException when the path does not exist;
1316 * IOException see specific implementation
1317 */
1318 public FileStatus[] listStatus(Path f, PathFilter filter)
1319 throws FileNotFoundException, IOException {
1320 ArrayList<FileStatus> results = new ArrayList<FileStatus>();
1321 listStatus(results, f, filter);
1322 return results.toArray(new FileStatus[results.size()]);
1323 }
1324
1325 /**
1326 * Filter files/directories in the given list of paths using default
1327 * path filter.
1328 *
1329 * @param files
1330 * a list of paths
1331 * @return a list of statuses for the files under the given paths after
1332 * applying the filter default Path filter
1333 * @throws FileNotFoundException when the path does not exist;
1334 * IOException see specific implementation
1335 */
1336 public FileStatus[] listStatus(Path[] files)
1337 throws FileNotFoundException, IOException {
1338 return listStatus(files, DEFAULT_FILTER);
1339 }
1340
1341 /**
1342 * Filter files/directories in the given list of paths using user-supplied
1343 * path filter.
1344 *
1345 * @param files
1346 * a list of paths
1347 * @param filter
1348 * the user-supplied path filter
1349 * @return a list of statuses for the files under the given paths after
1350 * applying the filter
1351 * @throws FileNotFoundException when the path does not exist;
1352 * IOException see specific implementation
1353 */
1354 public FileStatus[] listStatus(Path[] files, PathFilter filter)
1355 throws FileNotFoundException, IOException {
1356 ArrayList<FileStatus> results = new ArrayList<FileStatus>();
1357 for (int i = 0; i < files.length; i++) {
1358 listStatus(results, files[i], filter);
1359 }
1360 return results.toArray(new FileStatus[results.size()]);
1361 }
1362
1363 /**
1364 * <p>Return all the files that match filePattern and are not checksum
1365 * files. Results are sorted by their names.
1366 *
1367 * <p>
1368 * A filename pattern is composed of <i>regular</i> characters and
1369 * <i>special pattern matching</i> characters, which are:
1370 *
1371 * <dl>
1372 * <dd>
1373 * <dl>
1374 * <p>
1375 * <dt> <tt> ? </tt>
1376 * <dd> Matches any single character.
1377 *
1378 * <p>
1379 * <dt> <tt> * </tt>
1380 * <dd> Matches zero or more characters.
1381 *
1382 * <p>
1383 * <dt> <tt> [<i>abc</i>] </tt>
1384 * <dd> Matches a single character from character set
1385 * <tt>{<i>a,b,c</i>}</tt>.
1386 *
1387 * <p>
1388 * <dt> <tt> [<i>a</i>-<i>b</i>] </tt>
1389 * <dd> Matches a single character from the character range
1390 * <tt>{<i>a...b</i>}</tt>. Note that character <tt><i>a</i></tt> must be
1391 * lexicographically less than or equal to character <tt><i>b</i></tt>.
1392 *
1393 * <p>
1394 * <dt> <tt> [^<i>a</i>] </tt>
1395 * <dd> Matches a single character that is not from character set or range
1396 * <tt>{<i>a</i>}</tt>. Note that the <tt>^</tt> character must occur
1397 * immediately to the right of the opening bracket.
1398 *
1399 * <p>
1400 * <dt> <tt> \<i>c</i> </tt>
1401 * <dd> Removes (escapes) any special meaning of character <i>c</i>.
1402 *
1403 * <p>
1404 * <dt> <tt> {ab,cd} </tt>
1405 * <dd> Matches a string from the string set <tt>{<i>ab, cd</i>} </tt>
1406 *
1407 * <p>
1408 * <dt> <tt> {ab,c{de,fh}} </tt>
1409 * <dd> Matches a string from the string set <tt>{<i>ab, cde, cfh</i>}</tt>
1410 *
1411 * </dl>
1412 * </dd>
1413 * </dl>
1414 *
1415 * @param pathPattern a regular expression specifying a pth pattern
1416
1417 * @return an array of paths that match the path pattern
1418 * @throws IOException
1419 */
1420 public FileStatus[] globStatus(Path pathPattern) throws IOException {
1421 return globStatus(pathPattern, DEFAULT_FILTER);
1422 }
1423
1424 /**
1425 * Return an array of FileStatus objects whose path names match pathPattern
1426 * and is accepted by the user-supplied path filter. Results are sorted by
1427 * their path names.
1428 * Return null if pathPattern has no glob and the path does not exist.
1429 * Return an empty array if pathPattern has a glob and no path matches it.
1430 *
1431 * @param pathPattern
1432 * a regular expression specifying the path pattern
1433 * @param filter
1434 * a user-supplied path filter
1435 * @return an array of FileStatus objects
1436 * @throws IOException if any I/O error occurs when fetching file status
1437 */
1438 public FileStatus[] globStatus(Path pathPattern, PathFilter filter)
1439 throws IOException {
1440 String filename = pathPattern.toUri().getPath();
1441 List<String> filePatterns = GlobExpander.expand(filename);
1442 if (filePatterns.size() == 1) {
1443 return globStatusInternal(pathPattern, filter);
1444 } else {
1445 List<FileStatus> results = new ArrayList<FileStatus>();
1446 for (String filePattern : filePatterns) {
1447 FileStatus[] files = globStatusInternal(new Path(filePattern), filter);
1448 for (FileStatus file : files) {
1449 results.add(file);
1450 }
1451 }
1452 return results.toArray(new FileStatus[results.size()]);
1453 }
1454 }
1455
1456 private FileStatus[] globStatusInternal(Path pathPattern, PathFilter filter)
1457 throws IOException {
1458 Path[] parents = new Path[1];
1459 int level = 0;
1460 String filename = pathPattern.toUri().getPath();
1461
1462 // path has only zero component
1463 if ("".equals(filename) || Path.SEPARATOR.equals(filename)) {
1464 return getFileStatus(new Path[]{pathPattern});
1465 }
1466
1467 // path has at least one component
1468 String[] components = filename.split(Path.SEPARATOR);
1469 // get the first component
1470 if (pathPattern.isAbsolute()) {
1471 parents[0] = new Path(Path.SEPARATOR);
1472 level = 1;
1473 } else {
1474 parents[0] = new Path(Path.CUR_DIR);
1475 }
1476
1477 // glob the paths that match the parent path, i.e., [0, components.length-1]
1478 boolean[] hasGlob = new boolean[]{false};
1479 Path[] parentPaths = globPathsLevel(parents, components, level, hasGlob);
1480 FileStatus[] results;
1481 if (parentPaths == null || parentPaths.length == 0) {
1482 results = null;
1483 } else {
1484 // Now work on the last component of the path
1485 GlobFilter fp = new GlobFilter(components[components.length - 1], filter);
1486 if (fp.hasPattern()) { // last component has a pattern
1487 // list parent directories and then glob the results
1488 results = listStatus(parentPaths, fp);
1489 hasGlob[0] = true;
1490 } else { // last component does not have a pattern
1491 // remove the quoting of metachars in a non-regexp expansion
1492 String name = unquotePathComponent(components[components.length - 1]);
1493 // get all the path names
1494 ArrayList<Path> filteredPaths = new ArrayList<Path>(parentPaths.length);
1495 for (int i = 0; i < parentPaths.length; i++) {
1496 parentPaths[i] = new Path(parentPaths[i], name);
1497 if (fp.accept(parentPaths[i])) {
1498 filteredPaths.add(parentPaths[i]);
1499 }
1500 }
1501 // get all their statuses
1502 results = getFileStatus(
1503 filteredPaths.toArray(new Path[filteredPaths.size()]));
1504 }
1505 }
1506
1507 // Decide if the pathPattern contains a glob or not
1508 if (results == null) {
1509 if (hasGlob[0]) {
1510 results = new FileStatus[0];
1511 }
1512 } else {
1513 if (results.length == 0 ) {
1514 if (!hasGlob[0]) {
1515 results = null;
1516 }
1517 } else {
1518 Arrays.sort(results);
1519 }
1520 }
1521 return results;
1522 }
1523
1524 /*
1525 * For a path of N components, return a list of paths that match the
1526 * components [<code>level</code>, <code>N-1</code>].
1527 */
1528 private Path[] globPathsLevel(Path[] parents, String[] filePattern,
1529 int level, boolean[] hasGlob) throws IOException {
1530 if (level == filePattern.length - 1)
1531 return parents;
1532 if (parents == null || parents.length == 0) {
1533 return null;
1534 }
1535 GlobFilter fp = new GlobFilter(filePattern[level]);
1536 if (fp.hasPattern()) {
1537 parents = FileUtil.stat2Paths(listStatus(parents, fp));
1538 hasGlob[0] = true;
1539 } else { // the component does not have a pattern
1540 // remove the quoting of metachars in a non-regexp expansion
1541 String name = unquotePathComponent(filePattern[level]);
1542 for (int i = 0; i < parents.length; i++) {
1543 parents[i] = new Path(parents[i], name);
1544 }
1545 }
1546 return globPathsLevel(parents, filePattern, level + 1, hasGlob);
1547 }
1548
1549 /**
1550 * The glob filter builds a regexp per path component. If the component
1551 * does not contain a shell metachar, then it falls back to appending the
1552 * raw string to the list of built up paths. This raw path needs to have
1553 * the quoting removed. Ie. convert all occurances of "\X" to "X"
1554 * @param name of the path component
1555 * @return the unquoted path component
1556 */
1557 private String unquotePathComponent(String name) {
1558 return name.replaceAll("\\\\(.)", "$1");
1559 }
1560
1561 /**
1562 * List the statuses of the files/directories in the given path if the path is
1563 * a directory.
1564 * Return the file's status and block locations If the path is a file.
1565 *
1566 * If a returned status is a file, it contains the file's block locations.
1567 *
1568 * @param f is the path
1569 *
1570 * @return an iterator that traverses statuses of the files/directories
1571 * in the given path
1572 *
1573 * @throws FileNotFoundException If <code>f</code> does not exist
1574 * @throws IOException If an I/O error occurred
1575 */
1576 public RemoteIterator<LocatedFileStatus> listLocatedStatus(final Path f)
1577 throws FileNotFoundException, IOException {
1578 return listLocatedStatus(f, DEFAULT_FILTER);
1579 }
1580
1581 /**
1582 * Listing a directory
1583 * The returned results include its block location if it is a file
1584 * The results are filtered by the given path filter
1585 * @param f a path
1586 * @param filter a path filter
1587 * @return an iterator that traverses statuses of the files/directories
1588 * in the given path
1589 * @throws FileNotFoundException if <code>f</code> does not exist
1590 * @throws IOException if any I/O error occurred
1591 */
1592 protected RemoteIterator<LocatedFileStatus> listLocatedStatus(final Path f,
1593 final PathFilter filter)
1594 throws FileNotFoundException, IOException {
1595 return new RemoteIterator<LocatedFileStatus>() {
1596 private final FileStatus[] stats = listStatus(f, filter);
1597 private int i = 0;
1598
1599 @Override
1600 public boolean hasNext() {
1601 return i<stats.length;
1602 }
1603
1604 @Override
1605 public LocatedFileStatus next() throws IOException {
1606 if (!hasNext()) {
1607 throw new NoSuchElementException("No more entry in " + f);
1608 }
1609 FileStatus result = stats[i++];
1610 BlockLocation[] locs = result.isFile() ?
1611 getFileBlockLocations(result.getPath(), 0, result.getLen()) :
1612 null;
1613 return new LocatedFileStatus(result, locs);
1614 }
1615 };
1616 }
1617
1618 /**
1619 * List the statuses and block locations of the files in the given path.
1620 *
1621 * If the path is a directory,
1622 * if recursive is false, returns files in the directory;
1623 * if recursive is true, return files in the subtree rooted at the path.
1624 * If the path is a file, return the file's status and block locations.
1625 *
1626 * @param f is the path
1627 * @param recursive if the subdirectories need to be traversed recursively
1628 *
1629 * @return an iterator that traverses statuses of the files
1630 *
1631 * @throws FileNotFoundException when the path does not exist;
1632 * IOException see specific implementation
1633 */
1634 public RemoteIterator<LocatedFileStatus> listFiles(
1635 final Path f, final boolean recursive)
1636 throws FileNotFoundException, IOException {
1637 return new RemoteIterator<LocatedFileStatus>() {
1638 private Stack<RemoteIterator<LocatedFileStatus>> itors =
1639 new Stack<RemoteIterator<LocatedFileStatus>>();
1640 private RemoteIterator<LocatedFileStatus> curItor =
1641 listLocatedStatus(f);
1642 private LocatedFileStatus curFile;
1643
1644 @Override
1645 public boolean hasNext() throws IOException {
1646 while (curFile == null) {
1647 if (curItor.hasNext()) {
1648 handleFileStat(curItor.next());
1649 } else if (!itors.empty()) {
1650 curItor = itors.pop();
1651 } else {
1652 return false;
1653 }
1654 }
1655 return true;
1656 }
1657
1658 /**
1659 * Process the input stat.
1660 * If it is a file, return the file stat.
1661 * If it is a directory, traverse the directory if recursive is true;
1662 * ignore it if recursive is false.
1663 * @param stat input status
1664 * @throws IOException if any IO error occurs
1665 */
1666 private void handleFileStat(LocatedFileStatus stat) throws IOException {
1667 if (stat.isFile()) { // file
1668 curFile = stat;
1669 } else if (recursive) { // directory
1670 itors.push(curItor);
1671 curItor = listLocatedStatus(stat.getPath());
1672 }
1673 }
1674
1675 @Override
1676 public LocatedFileStatus next() throws IOException {
1677 if (hasNext()) {
1678 LocatedFileStatus result = curFile;
1679 curFile = null;
1680 return result;
1681 }
1682 throw new java.util.NoSuchElementException("No more entry in " + f);
1683 }
1684 };
1685 }
1686
1687 /** Return the current user's home directory in this filesystem.
1688 * The default implementation returns "/user/$USER/".
1689 */
1690 public Path getHomeDirectory() {
1691 return this.makeQualified(
1692 new Path("/user/"+System.getProperty("user.name")));
1693 }
1694
1695
1696 /**
1697 * Set the current working directory for the given file system. All relative
1698 * paths will be resolved relative to it.
1699 *
1700 * @param new_dir
1701 */
1702 public abstract void setWorkingDirectory(Path new_dir);
1703
1704 /**
1705 * Get the current working directory for the given file system
1706 * @return the directory pathname
1707 */
1708 public abstract Path getWorkingDirectory();
1709
1710
1711 /**
1712 * Note: with the new FilesContext class, getWorkingDirectory()
1713 * will be removed.
1714 * The working directory is implemented in FilesContext.
1715 *
1716 * Some file systems like LocalFileSystem have an initial workingDir
1717 * that we use as the starting workingDir. For other file systems
1718 * like HDFS there is no built in notion of an inital workingDir.
1719 *
1720 * @return if there is built in notion of workingDir then it
1721 * is returned; else a null is returned.
1722 */
1723 protected Path getInitialWorkingDirectory() {
1724 return null;
1725 }
1726
1727 /**
1728 * Call {@link #mkdirs(Path, FsPermission)} with default permission.
1729 */
1730 public boolean mkdirs(Path f) throws IOException {
1731 return mkdirs(f, FsPermission.getDefault());
1732 }
1733
1734 /**
1735 * Make the given file and all non-existent parents into
1736 * directories. Has the semantics of Unix 'mkdir -p'.
1737 * Existence of the directory hierarchy is not an error.
1738 * @param f path to create
1739 * @param permission to apply to f
1740 */
1741 public abstract boolean mkdirs(Path f, FsPermission permission
1742 ) throws IOException;
1743
1744 /**
1745 * The src file is on the local disk. Add it to FS at
1746 * the given dst name and the source is kept intact afterwards
1747 * @param src path
1748 * @param dst path
1749 */
1750 public void copyFromLocalFile(Path src, Path dst)
1751 throws IOException {
1752 copyFromLocalFile(false, src, dst);
1753 }
1754
1755 /**
1756 * The src files is on the local disk. Add it to FS at
1757 * the given dst name, removing the source afterwards.
1758 * @param srcs path
1759 * @param dst path
1760 */
1761 public void moveFromLocalFile(Path[] srcs, Path dst)
1762 throws IOException {
1763 copyFromLocalFile(true, true, srcs, dst);
1764 }
1765
1766 /**
1767 * The src file is on the local disk. Add it to FS at
1768 * the given dst name, removing the source afterwards.
1769 * @param src path
1770 * @param dst path
1771 */
1772 public void moveFromLocalFile(Path src, Path dst)
1773 throws IOException {
1774 copyFromLocalFile(true, src, dst);
1775 }
1776
1777 /**
1778 * The src file is on the local disk. Add it to FS at
1779 * the given dst name.
1780 * delSrc indicates if the source should be removed
1781 * @param delSrc whether to delete the src
1782 * @param src path
1783 * @param dst path
1784 */
1785 public void copyFromLocalFile(boolean delSrc, Path src, Path dst)
1786 throws IOException {
1787 copyFromLocalFile(delSrc, true, src, dst);
1788 }
1789
1790 /**
1791 * The src files are on the local disk. Add it to FS at
1792 * the given dst name.
1793 * delSrc indicates if the source should be removed
1794 * @param delSrc whether to delete the src
1795 * @param overwrite whether to overwrite an existing file
1796 * @param srcs array of paths which are source
1797 * @param dst path
1798 */
1799 public void copyFromLocalFile(boolean delSrc, boolean overwrite,
1800 Path[] srcs, Path dst)
1801 throws IOException {
1802 Configuration conf = getConf();
1803 FileUtil.copy(getLocal(conf), srcs, this, dst, delSrc, overwrite, conf);
1804 }
1805
1806 /**
1807 * The src file is on the local disk. Add it to FS at
1808 * the given dst name.
1809 * delSrc indicates if the source should be removed
1810 * @param delSrc whether to delete the src
1811 * @param overwrite whether to overwrite an existing file
1812 * @param src path
1813 * @param dst path
1814 */
1815 public void copyFromLocalFile(boolean delSrc, boolean overwrite,
1816 Path src, Path dst)
1817 throws IOException {
1818 Configuration conf = getConf();
1819 FileUtil.copy(getLocal(conf), src, this, dst, delSrc, overwrite, conf);
1820 }
1821
1822 /**
1823 * The src file is under FS, and the dst is on the local disk.
1824 * Copy it from FS control to the local dst name.
1825 * @param src path
1826 * @param dst path
1827 */
1828 public void copyToLocalFile(Path src, Path dst) throws IOException {
1829 copyToLocalFile(false, src, dst);
1830 }
1831
1832 /**
1833 * The src file is under FS, and the dst is on the local disk.
1834 * Copy it from FS control to the local dst name.
1835 * Remove the source afterwards
1836 * @param src path
1837 * @param dst path
1838 */
1839 public void moveToLocalFile(Path src, Path dst) throws IOException {
1840 copyToLocalFile(true, src, dst);
1841 }
1842
1843 /**
1844 * The src file is under FS, and the dst is on the local disk.
1845 * Copy it from FS control to the local dst name.
1846 * delSrc indicates if the src will be removed or not.
1847 * @param delSrc whether to delete the src
1848 * @param src path
1849 * @param dst path
1850 */
1851 public void copyToLocalFile(boolean delSrc, Path src, Path dst)
1852 throws IOException {
1853 copyToLocalFile(delSrc, src, dst, false);
1854 }
1855
1856 /**
1857 * The src file is under FS, and the dst is on the local disk. Copy it from FS
1858 * control to the local dst name. delSrc indicates if the src will be removed
1859 * or not. useRawLocalFileSystem indicates whether to use RawLocalFileSystem
1860 * as local file system or not. RawLocalFileSystem is non crc file system.So,
1861 * It will not create any crc files at local.
1862 *
1863 * @param delSrc
1864 * whether to delete the src
1865 * @param src
1866 * path
1867 * @param dst
1868 * path
1869 * @param useRawLocalFileSystem
1870 * whether to use RawLocalFileSystem as local file system or not.
1871 *
1872 * @throws IOException
1873 * - if any IO error
1874 */
1875 public void copyToLocalFile(boolean delSrc, Path src, Path dst,
1876 boolean useRawLocalFileSystem) throws IOException {
1877 Configuration conf = getConf();
1878 FileSystem local = null;
1879 if (useRawLocalFileSystem) {
1880 local = getLocal(conf).getRawFileSystem();
1881 } else {
1882 local = getLocal(conf);
1883 }
1884 FileUtil.copy(this, src, local, dst, delSrc, conf);
1885 }
1886
1887 /**
1888 * Returns a local File that the user can write output to. The caller
1889 * provides both the eventual FS target name and the local working
1890 * file. If the FS is local, we write directly into the target. If
1891 * the FS is remote, we write into the tmp local area.
1892 * @param fsOutputFile path of output file
1893 * @param tmpLocalFile path of local tmp file
1894 */
1895 public Path startLocalOutput(Path fsOutputFile, Path tmpLocalFile)
1896 throws IOException {
1897 return tmpLocalFile;
1898 }
1899
1900 /**
1901 * Called when we're all done writing to the target. A local FS will
1902 * do nothing, because we've written to exactly the right place. A remote
1903 * FS will copy the contents of tmpLocalFile to the correct target at
1904 * fsOutputFile.
1905 * @param fsOutputFile path of output file
1906 * @param tmpLocalFile path to local tmp file
1907 */
1908 public void completeLocalOutput(Path fsOutputFile, Path tmpLocalFile)
1909 throws IOException {
1910 moveFromLocalFile(tmpLocalFile, fsOutputFile);
1911 }
1912
1913 /**
1914 * No more filesystem operations are needed. Will
1915 * release any held locks.
1916 */
1917 public void close() throws IOException {
1918 // delete all files that were marked as delete-on-exit.
1919 processDeleteOnExit();
1920 CACHE.remove(this.key, this);
1921 }
1922
1923 /** Return the total size of all files in the filesystem.*/
1924 public long getUsed() throws IOException{
1925 long used = 0;
1926 FileStatus[] files = listStatus(new Path("/"));
1927 for(FileStatus file:files){
1928 used += file.getLen();
1929 }
1930 return used;
1931 }
1932
1933 /**
1934 * Get the block size for a particular file.
1935 * @param f the filename
1936 * @return the number of bytes in a block
1937 */
1938 /** @deprecated Use getFileStatus() instead */
1939 @Deprecated
1940 public long getBlockSize(Path f) throws IOException {
1941 return getFileStatus(f).getBlockSize();
1942 }
1943
1944 /**
1945 * Return the number of bytes that large input files should be optimally
1946 * be split into to minimize i/o time.
1947 * @deprecated use {@link #getDefaultBlockSize(Path)} instead
1948 */
1949 @Deprecated
1950 public long getDefaultBlockSize() {
1951 // default to 32MB: large enough to minimize the impact of seeks
1952 return getConf().getLong("fs.local.block.size", 32 * 1024 * 1024);
1953 }
1954
1955 /** Return the number of bytes that large input files should be optimally
1956 * be split into to minimize i/o time. The given path will be used to
1957 * locate the actual filesystem. The full path does not have to exist.
1958 * @param f path of file
1959 * @return the default block size for the path's filesystem
1960 */
1961 public long getDefaultBlockSize(Path f) {
1962 return getDefaultBlockSize();
1963 }
1964
1965 /**
1966 * Get the default replication.
1967 * @deprecated use {@link #getDefaultReplication(Path)} instead
1968 */
1969 @Deprecated
1970 public short getDefaultReplication() { return 1; }
1971
1972 /**
1973 * Get the default replication for a path. The given path will be used to
1974 * locate the actual filesystem. The full path does not have to exist.
1975 * @param path of the file
1976 * @return default replication for the path's filesystem
1977 */
1978 public short getDefaultReplication(Path path) {
1979 return getDefaultReplication();
1980 }
1981
1982 /**
1983 * Return a file status object that represents the path.
1984 * @param f The path we want information from
1985 * @return a FileStatus object
1986 * @throws FileNotFoundException when the path does not exist;
1987 * IOException see specific implementation
1988 */
1989 public abstract FileStatus getFileStatus(Path f) throws IOException;
1990
1991 /**
1992 * Get the checksum of a file.
1993 *
1994 * @param f The file path
1995 * @return The file checksum. The default return value is null,
1996 * which indicates that no checksum algorithm is implemented
1997 * in the corresponding FileSystem.
1998 */
1999 public FileChecksum getFileChecksum(Path f) throws IOException {
2000 return null;
2001 }
2002
2003 /**
2004 * Set the verify checksum flag. This is only applicable if the
2005 * corresponding FileSystem supports checksum. By default doesn't do anything.
2006 * @param verifyChecksum
2007 */
2008 public void setVerifyChecksum(boolean verifyChecksum) {
2009 //doesn't do anything
2010 }
2011
2012 /**
2013 * Set the write checksum flag. This is only applicable if the
2014 * corresponding FileSystem supports checksum. By default doesn't do anything.
2015 * @param writeChecksum
2016 */
2017 public void setWriteChecksum(boolean writeChecksum) {
2018 //doesn't do anything
2019 }
2020
2021 /**
2022 * Return a list of file status objects that corresponds to the list of paths
2023 * excluding those non-existent paths.
2024 *
2025 * @param paths
2026 * the list of paths we want information from
2027 * @return a list of FileStatus objects
2028 * @throws IOException
2029 * see specific implementation
2030 */
2031 private FileStatus[] getFileStatus(Path[] paths) throws IOException {
2032 if (paths == null) {
2033 return null;
2034 }
2035 ArrayList<FileStatus> results = new ArrayList<FileStatus>(paths.length);
2036 for (int i = 0; i < paths.length; i++) {
2037 try {
2038 results.add(getFileStatus(paths[i]));
2039 } catch (FileNotFoundException e) { // do nothing
2040 }
2041 }
2042 return results.toArray(new FileStatus[results.size()]);
2043 }
2044
2045 /**
2046 * Returns a status object describing the use and capacity of the
2047 * file system. If the file system has multiple partitions, the
2048 * use and capacity of the root partition is reflected.
2049 *
2050 * @return a FsStatus object
2051 * @throws IOException
2052 * see specific implementation
2053 */
2054 public FsStatus getStatus() throws IOException {
2055 return getStatus(null);
2056 }
2057
2058 /**
2059 * Returns a status object describing the use and capacity of the
2060 * file system. If the file system has multiple partitions, the
2061 * use and capacity of the partition pointed to by the specified
2062 * path is reflected.
2063 * @param p Path for which status should be obtained. null means
2064 * the default partition.
2065 * @return a FsStatus object
2066 * @throws IOException
2067 * see specific implementation
2068 */
2069 public FsStatus getStatus(Path p) throws IOException {
2070 return new FsStatus(Long.MAX_VALUE, 0, Long.MAX_VALUE);
2071 }
2072
2073 /**
2074 * Set permission of a path.
2075 * @param p
2076 * @param permission
2077 */
2078 public void setPermission(Path p, FsPermission permission
2079 ) throws IOException {
2080 }
2081
2082 /**
2083 * Set owner of a path (i.e. a file or a directory).
2084 * The parameters username and groupname cannot both be null.
2085 * @param p The path
2086 * @param username If it is null, the original username remains unchanged.
2087 * @param groupname If it is null, the original groupname remains unchanged.
2088 */
2089 public void setOwner(Path p, String username, String groupname
2090 ) throws IOException {
2091 }
2092
2093 /**
2094 * Set access time of a file
2095 * @param p The path
2096 * @param mtime Set the modification time of this file.
2097 * The number of milliseconds since Jan 1, 1970.
2098 * A value of -1 means that this call should not set modification time.
2099 * @param atime Set the access time of this file.
2100 * The number of milliseconds since Jan 1, 1970.
2101 * A value of -1 means that this call should not set access time.
2102 */
2103 public void setTimes(Path p, long mtime, long atime
2104 ) throws IOException {
2105 }
2106
2107 // making it volatile to be able to do a double checked locking
2108 private volatile static boolean FILE_SYSTEMS_LOADED = false;
2109
2110 private static final Map<String, Class<? extends FileSystem>>
2111 SERVICE_FILE_SYSTEMS = new HashMap<String, Class<? extends FileSystem>>();
2112
2113 private static void loadFileSystems() {
2114 synchronized (FileSystem.class) {
2115 if (!FILE_SYSTEMS_LOADED) {
2116 ServiceLoader<FileSystem> serviceLoader = ServiceLoader.load(FileSystem.class);
2117 for (FileSystem fs : serviceLoader) {
2118 SERVICE_FILE_SYSTEMS.put(fs.getScheme(), fs.getClass());
2119 }
2120 FILE_SYSTEMS_LOADED = true;
2121 }
2122 }
2123 }
2124
2125 public static Class<? extends FileSystem> getFileSystemClass(String scheme,
2126 Configuration conf) throws IOException {
2127 if (!FILE_SYSTEMS_LOADED) {
2128 loadFileSystems();
2129 }
2130 Class<? extends FileSystem> clazz = null;
2131 if (conf != null) {
2132 clazz = (Class<? extends FileSystem>) conf.getClass("fs." + scheme + ".impl", null);
2133 }
2134 if (clazz == null) {
2135 clazz = SERVICE_FILE_SYSTEMS.get(scheme);
2136 }
2137 if (clazz == null) {
2138 throw new IOException("No FileSystem for scheme: " + scheme);
2139 }
2140 return clazz;
2141 }
2142
2143 private static FileSystem createFileSystem(URI uri, Configuration conf
2144 ) throws IOException {
2145 Class<?> clazz = getFileSystemClass(uri.getScheme(), conf);
2146 if (clazz == null) {
2147 throw new IOException("No FileSystem for scheme: " + uri.getScheme());
2148 }
2149 FileSystem fs = (FileSystem)ReflectionUtils.newInstance(clazz, conf);
2150 fs.initialize(uri, conf);
2151 return fs;
2152 }
2153
2154 /** Caching FileSystem objects */
2155 static class Cache {
2156 private final ClientFinalizer clientFinalizer = new ClientFinalizer();
2157
2158 private final Map<Key, FileSystem> map = new HashMap<Key, FileSystem>();
2159 private final Set<Key> toAutoClose = new HashSet<Key>();
2160
2161 /** A variable that makes all objects in the cache unique */
2162 private static AtomicLong unique = new AtomicLong(1);
2163
2164 FileSystem get(URI uri, Configuration conf) throws IOException{
2165 Key key = new Key(uri, conf);
2166 return getInternal(uri, conf, key);
2167 }
2168
2169 /** The objects inserted into the cache using this method are all unique */
2170 FileSystem getUnique(URI uri, Configuration conf) throws IOException{
2171 Key key = new Key(uri, conf, unique.getAndIncrement());
2172 return getInternal(uri, conf, key);
2173 }
2174
2175 private FileSystem getInternal(URI uri, Configuration conf, Key key) throws IOException{
2176 FileSystem fs;
2177 synchronized (this) {
2178 fs = map.get(key);
2179 }
2180 if (fs != null) {
2181 return fs;
2182 }
2183
2184 fs = createFileSystem(uri, conf);
2185 synchronized (this) { // refetch the lock again
2186 FileSystem oldfs = map.get(key);
2187 if (oldfs != null) { // a file system is created while lock is releasing
2188 fs.close(); // close the new file system
2189 return oldfs; // return the old file system
2190 }
2191
2192 // now insert the new file system into the map
2193 if (map.isEmpty() ) {
2194 ShutdownHookManager.get().addShutdownHook(clientFinalizer, SHUTDOWN_HOOK_PRIORITY);
2195 }
2196 fs.key = key;
2197 map.put(key, fs);
2198 if (conf.getBoolean("fs.automatic.close", true)) {
2199 toAutoClose.add(key);
2200 }
2201 return fs;
2202 }
2203 }
2204
2205 synchronized void remove(Key key, FileSystem fs) {
2206 if (map.containsKey(key) && fs == map.get(key)) {
2207 map.remove(key);
2208 toAutoClose.remove(key);
2209 }
2210 }
2211
2212 synchronized void closeAll() throws IOException {
2213 closeAll(false);
2214 }
2215
2216 /**
2217 * Close all FileSystem instances in the Cache.
2218 * @param onlyAutomatic only close those that are marked for automatic closing
2219 */
2220 synchronized void closeAll(boolean onlyAutomatic) throws IOException {
2221 List<IOException> exceptions = new ArrayList<IOException>();
2222
2223 // Make a copy of the keys in the map since we'll be modifying
2224 // the map while iterating over it, which isn't safe.
2225 List<Key> keys = new ArrayList<Key>();
2226 keys.addAll(map.keySet());
2227
2228 for (Key key : keys) {
2229 final FileSystem fs = map.get(key);
2230
2231 if (onlyAutomatic && !toAutoClose.contains(key)) {
2232 continue;
2233 }
2234
2235 //remove from cache
2236 remove(key, fs);
2237
2238 if (fs != null) {
2239 try {
2240 fs.close();
2241 }
2242 catch(IOException ioe) {
2243 exceptions.add(ioe);
2244 }
2245 }
2246 }
2247
2248 if (!exceptions.isEmpty()) {
2249 throw MultipleIOException.createIOException(exceptions);
2250 }
2251 }
2252
2253 private class ClientFinalizer implements Runnable {
2254 public synchronized void run() {
2255 try {
2256 closeAll(true);
2257 } catch (IOException e) {
2258 LOG.info("FileSystem.Cache.closeAll() threw an exception:\n" + e);
2259 }
2260 }
2261 }
2262
2263 synchronized void closeAll(UserGroupInformation ugi) throws IOException {
2264 List<FileSystem> targetFSList = new ArrayList<FileSystem>();
2265 //Make a pass over the list and collect the filesystems to close
2266 //we cannot close inline since close() removes the entry from the Map
2267 for (Map.Entry<Key, FileSystem> entry : map.entrySet()) {
2268 final Key key = entry.getKey();
2269 final FileSystem fs = entry.getValue();
2270 if (ugi.equals(key.ugi) && fs != null) {
2271 targetFSList.add(fs);
2272 }
2273 }
2274 List<IOException> exceptions = new ArrayList<IOException>();
2275 //now make a pass over the target list and close each
2276 for (FileSystem fs : targetFSList) {
2277 try {
2278 fs.close();
2279 }
2280 catch(IOException ioe) {
2281 exceptions.add(ioe);
2282 }
2283 }
2284 if (!exceptions.isEmpty()) {
2285 throw MultipleIOException.createIOException(exceptions);
2286 }
2287 }
2288
2289 /** FileSystem.Cache.Key */
2290 static class Key {
2291 final String scheme;
2292 final String authority;
2293 final UserGroupInformation ugi;
2294 final long unique; // an artificial way to make a key unique
2295
2296 Key(URI uri, Configuration conf) throws IOException {
2297 this(uri, conf, 0);
2298 }
2299
2300 Key(URI uri, Configuration conf, long unique) throws IOException {
2301 scheme = uri.getScheme()==null?"":uri.getScheme().toLowerCase();
2302 authority = uri.getAuthority()==null?"":uri.getAuthority().toLowerCase();
2303 this.unique = unique;
2304
2305 this.ugi = UserGroupInformation.getCurrentUser();
2306 }
2307
2308 /** {@inheritDoc} */
2309 public int hashCode() {
2310 return (scheme + authority).hashCode() + ugi.hashCode() + (int)unique;
2311 }
2312
2313 static boolean isEqual(Object a, Object b) {
2314 return a == b || (a != null && a.equals(b));
2315 }
2316
2317 /** {@inheritDoc} */
2318 public boolean equals(Object obj) {
2319 if (obj == this) {
2320 return true;
2321 }
2322 if (obj != null && obj instanceof Key) {
2323 Key that = (Key)obj;
2324 return isEqual(this.scheme, that.scheme)
2325 && isEqual(this.authority, that.authority)
2326 && isEqual(this.ugi, that.ugi)
2327 && (this.unique == that.unique);
2328 }
2329 return false;
2330 }
2331
2332 /** {@inheritDoc} */
2333 public String toString() {
2334 return "("+ugi.toString() + ")@" + scheme + "://" + authority;
2335 }
2336 }
2337 }
2338
2339 public static final class Statistics {
2340 private final String scheme;
2341 private AtomicLong bytesRead = new AtomicLong();
2342 private AtomicLong bytesWritten = new AtomicLong();
2343 private AtomicInteger readOps = new AtomicInteger();
2344 private AtomicInteger largeReadOps = new AtomicInteger();
2345 private AtomicInteger writeOps = new AtomicInteger();
2346
2347 public Statistics(String scheme) {
2348 this.scheme = scheme;
2349 }
2350
2351 /**
2352 * Copy constructor.
2353 *
2354 * @param st
2355 * The input Statistics object which is cloned.
2356 */
2357 public Statistics(Statistics st) {
2358 this.scheme = st.scheme;
2359 this.bytesRead = new AtomicLong(st.bytesRead.longValue());
2360 this.bytesWritten = new AtomicLong(st.bytesWritten.longValue());
2361 }
2362
2363 /**
2364 * Increment the bytes read in the statistics
2365 * @param newBytes the additional bytes read
2366 */
2367 public void incrementBytesRead(long newBytes) {
2368 bytesRead.getAndAdd(newBytes);
2369 }
2370
2371 /**
2372 * Increment the bytes written in the statistics
2373 * @param newBytes the additional bytes written
2374 */
2375 public void incrementBytesWritten(long newBytes) {
2376 bytesWritten.getAndAdd(newBytes);
2377 }
2378
2379 /**
2380 * Increment the number of read operations
2381 * @param count number of read operations
2382 */
2383 public void incrementReadOps(int count) {
2384 readOps.getAndAdd(count);
2385 }
2386
2387 /**
2388 * Increment the number of large read operations
2389 * @param count number of large read operations
2390 */
2391 public void incrementLargeReadOps(int count) {
2392 largeReadOps.getAndAdd(count);
2393 }
2394
2395 /**
2396 * Increment the number of write operations
2397 * @param count number of write operations
2398 */
2399 public void incrementWriteOps(int count) {
2400 writeOps.getAndAdd(count);
2401 }
2402
2403 /**
2404 * Get the total number of bytes read
2405 * @return the number of bytes
2406 */
2407 public long getBytesRead() {
2408 return bytesRead.get();
2409 }
2410
2411 /**
2412 * Get the total number of bytes written
2413 * @return the number of bytes
2414 */
2415 public long getBytesWritten() {
2416 return bytesWritten.get();
2417 }
2418
2419 /**
2420 * Get the number of file system read operations such as list files
2421 * @return number of read operations
2422 */
2423 public int getReadOps() {
2424 return readOps.get() + largeReadOps.get();
2425 }
2426
2427 /**
2428 * Get the number of large file system read operations such as list files
2429 * under a large directory
2430 * @return number of large read operations
2431 */
2432 public int getLargeReadOps() {
2433 return largeReadOps.get();
2434 }
2435
2436 /**
2437 * Get the number of file system write operations such as create, append
2438 * rename etc.
2439 * @return number of write operations
2440 */
2441 public int getWriteOps() {
2442 return writeOps.get();
2443 }
2444
2445 public String toString() {
2446 return bytesRead + " bytes read, " + bytesWritten + " bytes written, "
2447 + readOps + " read ops, " + largeReadOps + " large read ops, "
2448 + writeOps + " write ops";
2449 }
2450
2451 /**
2452 * Reset the counts of bytes to 0.
2453 */
2454 public void reset() {
2455 bytesWritten.set(0);
2456 bytesRead.set(0);
2457 }
2458
2459 /**
2460 * Get the uri scheme associated with this statistics object.
2461 * @return the schema associated with this set of statistics
2462 */
2463 public String getScheme() {
2464 return scheme;
2465 }
2466 }
2467
2468 /**
2469 * Get the Map of Statistics object indexed by URI Scheme.
2470 * @return a Map having a key as URI scheme and value as Statistics object
2471 * @deprecated use {@link #getAllStatistics} instead
2472 */
2473 @Deprecated
2474 public static synchronized Map<String, Statistics> getStatistics() {
2475 Map<String, Statistics> result = new HashMap<String, Statistics>();
2476 for(Statistics stat: statisticsTable.values()) {
2477 result.put(stat.getScheme(), stat);
2478 }
2479 return result;
2480 }
2481
2482 /**
2483 * Return the FileSystem classes that have Statistics
2484 */
2485 public static synchronized List<Statistics> getAllStatistics() {
2486 return new ArrayList<Statistics>(statisticsTable.values());
2487 }
2488
2489 /**
2490 * Get the statistics for a particular file system
2491 * @param cls the class to lookup
2492 * @return a statistics object
2493 */
2494 public static synchronized
2495 Statistics getStatistics(String scheme, Class<? extends FileSystem> cls) {
2496 Statistics result = statisticsTable.get(cls);
2497 if (result == null) {
2498 result = new Statistics(scheme);
2499 statisticsTable.put(cls, result);
2500 }
2501 return result;
2502 }
2503
2504 /**
2505 * Reset all statistics for all file systems
2506 */
2507 public static synchronized void clearStatistics() {
2508 for(Statistics stat: statisticsTable.values()) {
2509 stat.reset();
2510 }
2511 }
2512
2513 /**
2514 * Print all statistics for all file systems
2515 */
2516 public static synchronized
2517 void printStatistics() throws IOException {
2518 for (Map.Entry<Class<? extends FileSystem>, Statistics> pair:
2519 statisticsTable.entrySet()) {
2520 System.out.println(" FileSystem " + pair.getKey().getName() +
2521 ": " + pair.getValue());
2522 }
2523 }
2524 }