下面列出了java.nio.file.AccessMode#java.nio.file.FileStore 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Get the location of the DVD, or null if no DVD can be found.
* <p>
* @return the DVD location.
*/
private String getLocation() {
FileSystem fs = FileSystems.getDefault();
for(Path rootPath : fs.getRootDirectories()) {
try {
FileStore store = Files.getFileStore(rootPath);
if(store.type().toLowerCase().contains("udf")) {
if(store.getTotalSpace()>10000000000L) { //Blu-ray
return "bluray:///" + rootPath.toString();
}
else {
return "dvdsimple:///" + rootPath.toString(); //DVD
}
}
}
catch(IOException ex) {
//Never mind
}
}
return null;
}
@Test
public void testFileStore() throws URISyntaxException, IOException {
URI uri = clusterUri.resolve("/tmp/testFileStore");
Path path = Paths.get(uri);
if (Files.exists(path))
Files.delete(path);
assertFalse(Files.exists(path));
Files.createFile(path);
assertTrue(Files.exists(path));
FileStore st = Files.getFileStore(path);
assertNotNull(st);
Assert.assertNotNull(st.name());
Assert.assertNotNull(st.type());
Assert.assertFalse(st.isReadOnly());
Assert.assertNotEquals(0, st.getTotalSpace());
Assert.assertNotEquals(0, st.getUnallocatedSpace());
Assert.assertNotEquals(0, st.getUsableSpace());
Assert
.assertTrue(st.supportsFileAttributeView(BasicFileAttributeView.class));
Assert.assertTrue(st.supportsFileAttributeView("basic"));
st.getAttribute("test");
}
@Override
public boolean isStorageAvailable() {
try {
FileStore fileStore = Files.getFileStore(contentDir);
long usableSpace = fileStore.getUsableSpace();
boolean readOnly = fileStore.isReadOnly();
boolean result = !readOnly && usableSpace > 0;
if (!result) {
log.warn("File blob store '{}' is not writable. Read only: {}. Usable space: {}",
getBlobStoreConfiguration().getName(), readOnly, usableSpace);
}
return result;
}
catch (IOException e) {
log.warn("File blob store '{}' is not writable.", getBlobStoreConfiguration().getName(), e);
return false;
}
}
private void fillFromStorage ( final Map<String, Object> model )
{
if ( this.manager != null )
{
final Path base = this.manager.getContext ().getBasePath ();
try
{
final FileStore store = Files.getFileStore ( base );
model.put ( "storageTotal", store.getTotalSpace () );
model.put ( "storageFree", store.getUsableSpace () );
model.put ( "storageUsed", store.getTotalSpace () - store.getUsableSpace () );
model.put ( "storageName", store.name () );
}
catch ( final Exception e )
{
logger.warn ( "Failed to check storage space", e );
// ignore
}
}
}
@Override
public Iterable<FileStore> getFileStores() {
return MCRStoreCenter.instance().getCurrentStores(org.mycore.datamodel.ifs2.MCRFileStore.class)
.filter(s -> s.getID().startsWith(MCRFileSystemUtils.STORE_ID_PREFIX))
.sorted(Comparator.comparing(MCRStore::getID))
.map(MCRStore::getID)
.distinct()
.map(storeId -> {
try {
return MCRFileStore.getInstance(storeId);
} catch (IOException e) {
LogManager.getLogger().error("Error while iterating FileStores.", e);
return null;
}
})
.filter(Objects::nonNull)
.map(FileStore.class::cast)::iterator;
}
@Override
public Iterable<FileStore> getFileStores() {
final Iterable<FileStore> fileStores = delegate.getFileStores();
return () -> {
final Iterator<FileStore> iterator = fileStores.iterator();
return new Iterator<FileStore>() {
@Override
public boolean hasNext() {
return iterator.hasNext();
}
@Override
public FileStore next() {
return new FilterFileStore(iterator.next(), parent.getScheme()) {};
}
@Override
public void remove() {
iterator.remove();
}
};
};
}
public MockLinuxFileSystemProvider(FileSystem delegateInstance, final Map<String,FileStore> filesToStore, Path root) {
super("mocklinux://", delegateInstance);
if (mockedPath(root)) {
throw new AssumptionViolatedException("can't mock /sys and /dev inside of /sys or /dev!");
}
final Collection<FileStore> allStores = new HashSet<>(filesToStore.values());
this.fileSystem = new FilterFileSystem(this, delegateInstance) {
@Override
public Iterable<FileStore> getFileStores() {
return allStores;
}
@Override
public Path getPath(String first, String... more) {
return new MockLinuxPath(delegateInstance.getPath(first, more), this);
}
};
this.filesToStore = filesToStore;
this.root = new MockLinuxPath(root, this.fileSystem);
}
public void testSSD() throws Exception {
assumeFalse("windows is not supported", Constants.WINDOWS);
Path dir = createTempDir();
dir = FilterPath.unwrap(dir).toRealPath();
// fake ssd
FileStore root = new MockFileStore(dir.toString() + " (/dev/zzz1)", "btrfs", "/dev/zzz1");
// make a fake /dev/zzz1 for it
Path devdir = dir.resolve("dev");
Files.createDirectories(devdir);
Files.createFile(devdir.resolve("zzz1"));
// make a fake /sys/block/zzz/queue/rotational file for it
Path sysdir = dir.resolve("sys").resolve("block").resolve("zzz").resolve("queue");
Files.createDirectories(sysdir);
try (OutputStream o = Files.newOutputStream(sysdir.resolve("rotational"))) {
o.write("0\n".getBytes(StandardCharsets.US_ASCII));
}
Map<String,FileStore> mappings = Collections.singletonMap(dir.toString(), root);
FileSystem mockLinux = new MockLinuxFileSystemProvider(dir.getFileSystem(), mappings, dir).getFileSystem(null);
Path mockPath = mockLinux.getPath(dir.toString());
assertFalse(IOUtils.spinsLinux(mockPath));
}
public void testManyPartitions() throws Exception {
assumeFalse("windows is not supported", Constants.WINDOWS);
Path dir = createTempDir();
dir = FilterPath.unwrap(dir).toRealPath();
// fake ssd
FileStore root = new MockFileStore(dir.toString() + " (/dev/zzz12)", "zfs", "/dev/zzz12");
// make a fake /dev/zzz11 for it
Path devdir = dir.resolve("dev");
Files.createDirectories(devdir);
Files.createFile(devdir.resolve("zzz12"));
// make a fake /sys/block/zzz/queue/rotational file for it
Path sysdir = dir.resolve("sys").resolve("block").resolve("zzz").resolve("queue");
Files.createDirectories(sysdir);
try (OutputStream o = Files.newOutputStream(sysdir.resolve("rotational"))) {
o.write("0\n".getBytes(StandardCharsets.US_ASCII));
}
Map<String,FileStore> mappings = Collections.singletonMap(dir.toString(), root);
FileSystem mockLinux = new MockLinuxFileSystemProvider(dir.getFileSystem(), mappings, dir).getFileSystem(null);
Path mockPath = mockLinux.getPath(dir.toString());
assertFalse(IOUtils.spinsLinux(mockPath));
}
private boolean hasEnoughDiskSpace(Path path)
{
try {
FileStore fileStore = getFileStore(path);
return fileStore.getUsableSpace() > fileStore.getTotalSpace() * (1.0 - maxUsedSpaceThreshold);
}
catch (IOException e) {
throw new PrestoException(OUT_OF_SPILL_SPACE, "Cannot determine free space for spill", e);
}
}
public void diagnose() {
Objects.requireNonNull(fileName(), "the filename should not be null, " +
"you have misconfigured this service, fatal error");
final Path path =
IO.path(fileName());
puts("in diagnose");
puts("Filename :", path.toAbsolutePath());
puts("File exists? :", Files.exists(path));
puts("File writeable? :", Files.isWritable(path));
puts("Output dir :", outputDir.toAbsolutePath());
puts("Output dir exists? :", Files.exists(outputDir));
puts("Output dir writeable? :", Files.isWritable(outputDir));
if (!Files.isWritable(outputDir) || !Files.exists(outputDir)) {
error.set(true);
}
try {
FileStore fileStore = Files.getFileStore(path.getParent());
puts("Total space :", str(fileStore.getTotalSpace()));
puts("Use-able space :", str(fileStore.getUsableSpace()));
puts("Free Space :", str(fileStore.getUnallocatedSpace()));
puts("type :", fileStore.type());
puts("name :", fileStore.name());
puts("read-only :", fileStore.isReadOnly());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public Iterable<FileStore> getFileStores() {
FileStore store;
try {
store = Files.getFileStore(root);
} catch (IOException ioe) {
store = null;
}
return SoleIterable(store);
}
@Override
public Iterable<FileStore> getFileStores() {
FileStore store;
try {
store = Files.getFileStore(root);
} catch (IOException ioe) {
store = null;
}
return SoleIterable(store);
}
@Override
public Iterable<FileStore> getFileStores() {
FileStore store;
try {
store = Files.getFileStore(root);
} catch (IOException ioe) {
store = null;
}
return SoleIterable(store);
}
private static long getUsableSpace() {
// Ensure that the directory exists.
rootDirectory.mkdirs();
// Get the usable space.
long freeSpace = 0L;
Path path = Paths.get(rootDirectory.getAbsolutePath());
try {
FileStore store = Files.getFileStore(path);
freeSpace = store.getUsableSpace();
} catch (Exception ignored) { }
return freeSpace;
}
private String sizeOfDir(String directory) {
try {
Path path = Paths.get(directory);
FileStore store = Files.getFileStore(path.getRoot());
return Utils.format("(total {}, unallocated {}, root {})", FileUtils.byteCountToDisplaySize(store.getTotalSpace()), FileUtils.byteCountToDisplaySize(store.getUnallocatedSpace()), path.getRoot());
} catch (Exception e) {
return "";
}
}
@Test
public void getFileStores_shouldContainTheOnlyFileStore() {
Collection<FileStore> stores = new ArrayList<>();
for(FileStore root : gfs.getFileStores())
stores.add(root);
assertTrue(stores.contains(gfs.getFileStore()));
}
@SuppressForbidden(reason = "tries to determine if disk is spinning")
// TODO: move PathUtils to be package-private here instead of
// public+forbidden api!
ESFileStore(final FileStore in) {
this.in = in;
if (Constants.LINUX) {
try {
final List<String> lines = Files.readAllLines(PathUtils.get("/proc/self/mountinfo"));
for (final String line : lines) {
final String[] fields = line.trim().split("\\s+");
final String mountPoint = fields[4];
if (mountPoint.equals(getMountPointLinux(in))) {
final String[] deviceNumbers = fields[2].split(":");
majorDeviceNumber = Integer.parseInt(deviceNumbers[0]);
minorDeviceNumber = Integer.parseInt(deviceNumbers[1]);
break;
}
}
} catch (final Exception e) {
majorDeviceNumber = -1;
minorDeviceNumber = -1;
}
} else {
majorDeviceNumber = -1;
minorDeviceNumber = -1;
}
}
@Override
public void sense(final MetricContext metricContext) throws SenseException
{
try {
// Determine the file store for the directory the JVM was started in
FileStore fileStore = Files.getFileStore(Paths.get(System.getProperty("user.dir")));
long total = fileStore.getTotalSpace();
long free = fileStore.getUsableSpace();
double percent_free = 100.0 * ((double)(total-free)/(double)total);
metricContext.record(DISK_USED, percent_free, Unit.PERCENT);
} catch (IOException e) {
throw new SenseException("Problem reading disk space", e);
}
}
protected BundleFileStore(BundleFileSystem fs, FileStore origFileStore) {
if (fs == null || origFileStore == null) {
throw new NullPointerException();
}
// this.fs = fs;
this.origFileStore = origFileStore;
}
public long getFreeSpace() {
long freeSpace = 0;
try {
FileStore fileStore = Files.getFileStore(Paths.get("."));
freeSpace = fileStore.getUsableSpace();
} catch (IOException ioEx) {
logger.log(Level.WARNING, "Cannot calculate free/total disk space", ioEx);
}
return freeSpace;
}
static void checkFileStores(FileSystem fs) throws IOException {
// sanity check method
if (FileUtils.areFileSystemsAccessible()) {
System.out.println("\n--- Begin FileStores ---");
for (FileStore store: fs.getFileStores()) {
System.out.println(store);
}
System.out.println("--- EndFileStores ---\n");
} else {
System.err.println
("Skipping FileStore check due to file system access failure");
}
}
public long getTotalSpace() {
long totalSpace = 0;
try {
FileStore fileStore = Files.getFileStore(Paths.get("."));
totalSpace = fileStore.getTotalSpace();
} catch (IOException ioEx) {
logger.log(Level.WARNING, "Cannot calculate free disk space", ioEx);
}
return totalSpace;
}
@Override
protected AccumulatingBlobStoreMetrics getAccumulatingBlobStoreMetrics() throws BlobStoreMetricsNotAvailableException {
try {
FileStore fileStore = Files.getFileStore(storageDirectory);
ImmutableMap<String, Long> availableSpace = ImmutableMap
.of("fileStore:" + fileStore.name(), fileStore.getUsableSpace());
return new AccumulatingBlobStoreMetrics(0, 0, availableSpace, false);
}
catch (IOException e) {
throw new BlobStoreMetricsNotAvailableException(e);
}
}
static void checkFileStores(FileSystem fs) throws IOException {
// sanity check method
if (FileUtils.areFileSystemsAccessible()) {
System.out.println("\n--- Begin FileStores ---");
for (FileStore store: fs.getFileStores()) {
System.out.println(store);
}
System.out.println("--- EndFileStores ---\n");
} else {
System.err.println
("Skipping FileStore check due to file system access failure");
}
}
public long freeDiskBytes() throws IOException {
Iterable<FileStore> fileStores = localFileSystem.getFileStores();
long totalUsableSpace = 0l;
for(FileStore fs:fileStores){
totalUsableSpace+=fs.getUsableSpace();
}
return totalUsableSpace;
}
@Override
public FsStat getFsStat() throws IOException {
FileStore store = Files.getFileStore(_root);
long total = store.getTotalSpace();
long free = store.getUsableSpace();
return new FsStat(total, Long.MAX_VALUE, total-free, pathToInode.size());
}
@Override
public void bindTo(MeterRegistry registry) {
for (FileStore fileStore : FileSystems.getDefault().getFileStores()) {
LOG.debug(
"Add gauge metric for {}, isReadOnly {}, type {}",
fileStore.name(),
fileStore.isReadOnly(),
fileStore.type());
Iterable<Tag> tagsWithPath = Tags.concat(Tags.empty(), "path", fileStore.toString());
Gauge.builder("disk.free", fileStore, exceptionToNonWrapper(FileStore::getUnallocatedSpace))
.tags(tagsWithPath)
.description("Unallocated space for file storage")
.baseUnit("bytes")
.strongReference(true)
.register(registry);
Gauge.builder("disk.total", fileStore, exceptionToNonWrapper(FileStore::getTotalSpace))
.tags(tagsWithPath)
.description("Total space for file storage")
.baseUnit("bytes")
.strongReference(true)
.register(registry);
Gauge.builder("disk.usable", fileStore, exceptionToNonWrapper(FileStore::getUsableSpace))
.tags(tagsWithPath)
.description("Usable space for file storage")
.baseUnit("bytes")
.strongReference(true)
.register(registry);
}
}
public static boolean isReadOnlyExecutable(Path path) throws IOException {
FileStore fileStore = Files.getFileStore(path);
if (fileStore.supportsFileAttributeView("posix")) {
Set<PosixFilePermission> perms = Files.getPosixFilePermissions(path);
if (perms.contains(PosixFilePermission.OWNER_EXECUTE)
&& !perms.contains(PosixFilePermission.GROUP_EXECUTE)
&& !perms.contains(PosixFilePermission.OTHERS_EXECUTE)) {
setReadOnlyPerms(path, true);
}
return perms.contains(PosixFilePermission.OWNER_EXECUTE);
} else {
return Files.isExecutable(path);
}
}
@Test
public void testFileStore() throws URISyntaxException, IOException {
URI uri = clusterUri.resolve("/tmp/testFileStore");
Path path = Paths.get(uri);
if (Files.exists(path))
Files.delete(path);
assertFalse(Files.exists(path));
Files.createFile(path);
assertTrue(Files.exists(path));
FileStore st = Files.getFileStore(path);
assertNotNull(st);
}