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 */ 018package org.apache.hadoop.hdfs.server.namenode.snapshot; 019 020import java.io.DataInput; 021import java.io.DataOutput; 022import java.io.IOException; 023import java.util.ArrayList; 024import java.util.Collections; 025import java.util.HashMap; 026import java.util.List; 027import java.util.Map; 028import java.util.concurrent.atomic.AtomicInteger; 029 030import javax.management.ObjectName; 031 032import org.apache.hadoop.hdfs.DFSUtil; 033import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport; 034import org.apache.hadoop.hdfs.protocol.SnapshotException; 035import org.apache.hadoop.hdfs.protocol.SnapshotInfo; 036import org.apache.hadoop.hdfs.protocol.SnapshottableDirectoryStatus; 037import org.apache.hadoop.hdfs.protocol.SnapshotDiffReport.DiffReportEntry; 038import org.apache.hadoop.hdfs.server.namenode.AuthorizationProvider; 039import org.apache.hadoop.hdfs.server.namenode.FSDirectory; 040import org.apache.hadoop.hdfs.server.namenode.FSImageFormat; 041import org.apache.hadoop.hdfs.server.namenode.FSNamesystem; 042import org.apache.hadoop.hdfs.server.namenode.INode; 043import org.apache.hadoop.hdfs.server.namenode.INode.BlocksMapUpdateInfo; 044import org.apache.hadoop.hdfs.server.namenode.INodeDirectory; 045import org.apache.hadoop.hdfs.server.namenode.INodesInPath; 046import org.apache.hadoop.metrics2.util.MBeans; 047 048import com.google.common.base.Preconditions; 049 050/** 051 * Manage snapshottable directories and their snapshots. 052 * 053 * This class includes operations that create, access, modify snapshots and/or 054 * snapshot-related data. In general, the locking structure of snapshot 055 * operations is: <br> 056 * 057 * 1. Lock the {@link FSNamesystem} lock in {@link FSNamesystem} before calling 058 * into {@link SnapshotManager} methods.<br> 059 * 2. Lock the {@link FSDirectory} lock for the {@link SnapshotManager} methods 060 * if necessary. 061 */ 062public class SnapshotManager implements SnapshotStatsMXBean { 063 private boolean allowNestedSnapshots = false; 064 private final FSDirectory fsdir; 065 private static final int SNAPSHOT_ID_BIT_WIDTH = 24; 066 067 private final AtomicInteger numSnapshots = new AtomicInteger(); 068 069 private int snapshotCounter = 0; 070 071 /** All snapshottable directories in the namesystem. */ 072 private final Map<Long, INodeDirectory> snapshottables = 073 new HashMap<Long, INodeDirectory>(); 074 075 public SnapshotManager(final FSDirectory fsdir) { 076 this.fsdir = fsdir; 077 } 078 079 public void initAuthorizationProvider() { 080 Map<AuthorizationProvider.INodeAuthorizationInfo, Integer> map = 081 new HashMap<AuthorizationProvider.INodeAuthorizationInfo, Integer>(); 082 for (INodeDirectory dir : getSnapshottableDirs()) { 083 int currentSnapshot = Snapshot.CURRENT_STATE_ID; 084 DirectorySnapshottableFeature sf = 085 dir.getDirectorySnapshottableFeature(); 086 if (sf != null) { 087 currentSnapshot = sf.getLastSnapshotId(); 088 } 089 map.put(dir, currentSnapshot); 090 } 091 AuthorizationProvider.get().setSnaphottableDirs(map); 092 } 093 094 /** Used in tests only */ 095 void setAllowNestedSnapshots(boolean allowNestedSnapshots) { 096 this.allowNestedSnapshots = allowNestedSnapshots; 097 } 098 099 private void checkNestedSnapshottable(INodeDirectory dir, String path) 100 throws SnapshotException { 101 if (allowNestedSnapshots) { 102 return; 103 } 104 105 for(INodeDirectory s : snapshottables.values()) { 106 if (s.isAncestorDirectory(dir)) { 107 throw new SnapshotException( 108 "Nested snapshottable directories not allowed: path=" + path 109 + ", the subdirectory " + s.getFullPathName() 110 + " is already a snapshottable directory."); 111 } 112 if (dir.isAncestorDirectory(s)) { 113 throw new SnapshotException( 114 "Nested snapshottable directories not allowed: path=" + path 115 + ", the ancestor " + s.getFullPathName() 116 + " is already a snapshottable directory."); 117 } 118 } 119 } 120 121 /** 122 * Set the given directory as a snapshottable directory. 123 * If the path is already a snapshottable directory, update the quota. 124 */ 125 public void setSnapshottable(final String path, boolean checkNestedSnapshottable) 126 throws IOException { 127 final INodesInPath iip = fsdir.getINodesInPath4Write(path); 128 final INodeDirectory d = INodeDirectory.valueOf(iip.getLastINode(), path); 129 if (checkNestedSnapshottable) { 130 checkNestedSnapshottable(d, path); 131 } 132 133 if (d.isSnapshottable()) { 134 //The directory is already a snapshottable directory. 135 d.setSnapshotQuota(DirectorySnapshottableFeature.SNAPSHOT_LIMIT); 136 } else { 137 d.addSnapshottableFeature(); 138 } 139 addSnapshottable(d); 140 } 141 142 /** Add the given snapshottable directory to {@link #snapshottables}. */ 143 public void addSnapshottable(INodeDirectory dir) { 144 Preconditions.checkArgument(dir.isSnapshottable()); 145 AuthorizationProvider.get().addSnapshottable(dir); 146 snapshottables.put(dir.getId(), dir); 147 } 148 149 /** Remove the given snapshottable directory from {@link #snapshottables}. */ 150 private void removeSnapshottable(INodeDirectory s) { 151 AuthorizationProvider.get().removeSnapshottable(s); 152 snapshottables.remove(s.getId()); 153 } 154 155 /** Remove snapshottable directories from {@link #snapshottables} */ 156 public void removeSnapshottable(List<INodeDirectory> toRemove) { 157 if (toRemove != null) { 158 for (INodeDirectory s : toRemove) { 159 removeSnapshottable(s); 160 } 161 } 162 } 163 164 /** 165 * Set the given snapshottable directory to non-snapshottable. 166 * 167 * @throws SnapshotException if there are snapshots in the directory. 168 */ 169 public void resetSnapshottable(final String path) throws IOException { 170 final INodesInPath iip = fsdir.getINodesInPath4Write(path); 171 final INodeDirectory d = INodeDirectory.valueOf(iip.getLastINode(), path); 172 DirectorySnapshottableFeature sf = d.getDirectorySnapshottableFeature(); 173 if (sf == null) { 174 // the directory is already non-snapshottable 175 return; 176 } 177 if (sf.getNumSnapshots() > 0) { 178 throw new SnapshotException("The directory " + path + " has snapshot(s). " 179 + "Please redo the operation after removing all the snapshots."); 180 } 181 182 if (d == fsdir.getRoot()) { 183 d.setSnapshotQuota(0); 184 } else { 185 d.removeSnapshottableFeature(); 186 } 187 removeSnapshottable(d); 188 } 189 190 /** 191 * Find the source root directory where the snapshot will be taken 192 * for a given path. 193 * 194 * @param path The directory path where the snapshot will be taken. 195 * @return Snapshottable directory. 196 * @throws IOException 197 * Throw IOException when the given path does not lead to an 198 * existing snapshottable directory. 199 */ 200 public INodeDirectory getSnapshottableRoot(final String path) 201 throws IOException { 202 final INodeDirectory dir = INodeDirectory.valueOf(fsdir 203 .getINodesInPath4Write(path).getLastINode(), path); 204 if (!dir.isSnapshottable()) { 205 throw new SnapshotException( 206 "Directory is not a snapshottable directory: " + path); 207 } 208 return dir; 209 } 210 211 /** 212 * Create a snapshot of the given path. 213 * It is assumed that the caller will perform synchronization. 214 * 215 * @param path 216 * The directory path where the snapshot will be taken. 217 * @param snapshotName 218 * The name of the snapshot. 219 * @throws IOException 220 * Throw IOException when 1) the given path does not lead to an 221 * existing snapshottable directory, and/or 2) there exists a 222 * snapshot with the given name for the directory, and/or 3) 223 * snapshot number exceeds quota 224 */ 225 public String createSnapshot(final String path, String snapshotName 226 ) throws IOException { 227 INodeDirectory srcRoot = getSnapshottableRoot(path); 228 229 if (snapshotCounter == getMaxSnapshotID()) { 230 // We have reached the maximum allowable snapshot ID and since we don't 231 // handle rollover we will fail all subsequent snapshot creation 232 // requests. 233 // 234 throw new SnapshotException( 235 "Failed to create the snapshot. The FileSystem has run out of " + 236 "snapshot IDs and ID rollover is not supported."); 237 } 238 239 AuthorizationProvider.get().createSnapshot(srcRoot, snapshotCounter); 240 srcRoot.addSnapshot(snapshotCounter, snapshotName); 241 242 //create success, update id 243 snapshotCounter++; 244 numSnapshots.getAndIncrement(); 245 return Snapshot.getSnapshotPath(path, snapshotName); 246 } 247 248 /** 249 * Delete a snapshot for a snapshottable directory 250 * @param path Path to the directory where the snapshot was taken 251 * @param snapshotName Name of the snapshot to be deleted 252 * @param collectedBlocks Used to collect information to update blocksMap 253 * @throws IOException 254 */ 255 public void deleteSnapshot(final String path, final String snapshotName, 256 BlocksMapUpdateInfo collectedBlocks, final List<INode> removedINodes) 257 throws IOException { 258 // parse the path, and check if the path is a snapshot path 259 // the INodeDirectorySnapshottable#valueOf method will throw Exception 260 // if the path is not for a snapshottable directory 261 INodeDirectory srcRoot = getSnapshottableRoot(path); 262 AuthorizationProvider.get().removeSnapshot(srcRoot, snapshotCounter); 263 srcRoot.removeSnapshot(snapshotName, collectedBlocks, removedINodes); 264 numSnapshots.getAndDecrement(); 265 } 266 267 /** 268 * Rename the given snapshot 269 * @param path 270 * The directory path where the snapshot was taken 271 * @param oldSnapshotName 272 * Old name of the snapshot 273 * @param newSnapshotName 274 * New name of the snapshot 275 * @throws IOException 276 * Throw IOException when 1) the given path does not lead to an 277 * existing snapshottable directory, and/or 2) the snapshot with the 278 * old name does not exist for the directory, and/or 3) there exists 279 * a snapshot with the new name for the directory 280 */ 281 public void renameSnapshot(final String path, final String oldSnapshotName, 282 final String newSnapshotName) throws IOException { 283 // Find the source root directory path where the snapshot was taken. 284 // All the check for path has been included in the valueOf method. 285 final INodeDirectory srcRoot = getSnapshottableRoot(path); 286 // Note that renameSnapshot and createSnapshot are synchronized externally 287 // through FSNamesystem's write lock 288 srcRoot.renameSnapshot(path, oldSnapshotName, newSnapshotName); 289 } 290 291 public int getNumSnapshottableDirs() { 292 return snapshottables.size(); 293 } 294 295 public int getNumSnapshots() { 296 return numSnapshots.get(); 297 } 298 299 void setNumSnapshots(int num) { 300 numSnapshots.set(num); 301 } 302 303 int getSnapshotCounter() { 304 return snapshotCounter; 305 } 306 307 void setSnapshotCounter(int counter) { 308 snapshotCounter = counter; 309 } 310 311 INodeDirectory[] getSnapshottableDirs() { 312 return snapshottables.values().toArray( 313 new INodeDirectory[snapshottables.size()]); 314 } 315 316 /** 317 * Write {@link #snapshotCounter}, {@link #numSnapshots}, 318 * and all snapshots to the DataOutput. 319 */ 320 public void write(DataOutput out) throws IOException { 321 out.writeInt(snapshotCounter); 322 out.writeInt(numSnapshots.get()); 323 324 // write all snapshots. 325 for(INodeDirectory snapshottableDir : snapshottables.values()) { 326 for (Snapshot s : snapshottableDir.getDirectorySnapshottableFeature() 327 .getSnapshotList()) { 328 s.write(out); 329 } 330 } 331 } 332 333 /** 334 * Read values of {@link #snapshotCounter}, {@link #numSnapshots}, and 335 * all snapshots from the DataInput 336 */ 337 public Map<Integer, Snapshot> read(DataInput in, FSImageFormat.Loader loader 338 ) throws IOException { 339 snapshotCounter = in.readInt(); 340 numSnapshots.set(in.readInt()); 341 342 // read snapshots 343 final Map<Integer, Snapshot> snapshotMap = new HashMap<Integer, Snapshot>(); 344 for(int i = 0; i < numSnapshots.get(); i++) { 345 final Snapshot s = Snapshot.read(in, loader); 346 snapshotMap.put(s.getId(), s); 347 } 348 return snapshotMap; 349 } 350 351 /** 352 * List all the snapshottable directories that are owned by the current user. 353 * @param userName Current user name. 354 * @return Snapshottable directories that are owned by the current user, 355 * represented as an array of {@link SnapshottableDirectoryStatus}. If 356 * {@code userName} is null, return all the snapshottable dirs. 357 */ 358 public SnapshottableDirectoryStatus[] getSnapshottableDirListing( 359 String userName) { 360 if (snapshottables.isEmpty()) { 361 return null; 362 } 363 364 List<SnapshottableDirectoryStatus> statusList = 365 new ArrayList<SnapshottableDirectoryStatus>(); 366 for (INodeDirectory dir : snapshottables.values()) { 367 if (userName == null || userName.equals(dir.getUserName())) { 368 SnapshottableDirectoryStatus status = new SnapshottableDirectoryStatus( 369 dir.getModificationTime(), dir.getAccessTime(), 370 dir.getFsPermission(), dir.getUserName(), dir.getGroupName(), 371 dir.getLocalNameBytes(), dir.getId(), 372 dir.getChildrenNum(Snapshot.CURRENT_STATE_ID), 373 dir.getDirectorySnapshottableFeature().getNumSnapshots(), 374 dir.getDirectorySnapshottableFeature().getSnapshotQuota(), 375 dir.getParent() == null ? DFSUtil.EMPTY_BYTES : 376 DFSUtil.string2Bytes(dir.getParent().getFullPathName())); 377 statusList.add(status); 378 } 379 } 380 Collections.sort(statusList, SnapshottableDirectoryStatus.COMPARATOR); 381 return statusList.toArray( 382 new SnapshottableDirectoryStatus[statusList.size()]); 383 } 384 385 /** 386 * Compute the difference between two snapshots of a directory, or between a 387 * snapshot of the directory and its current tree. 388 */ 389 public SnapshotDiffReport diff(final String path, final String from, 390 final String to) throws IOException { 391 // Find the source root directory path where the snapshots were taken. 392 // All the check for path has been included in the valueOf method. 393 final INodeDirectory snapshotRoot = getSnapshottableRoot(path); 394 395 if ((from == null || from.isEmpty()) 396 && (to == null || to.isEmpty())) { 397 // both fromSnapshot and toSnapshot indicate the current tree 398 return new SnapshotDiffReport(path, from, to, 399 Collections.<DiffReportEntry> emptyList()); 400 } 401 final SnapshotDiffInfo diffs = snapshotRoot 402 .getDirectorySnapshottableFeature().computeDiff(snapshotRoot, from, to); 403 return diffs != null ? diffs.generateReport() : new SnapshotDiffReport( 404 path, from, to, Collections.<DiffReportEntry> emptyList()); 405 } 406 407 public void clearSnapshottableDirs() { 408 snapshottables.clear(); 409 } 410 411 /** 412 * Returns the maximum allowable snapshot ID based on the bit width of the 413 * snapshot ID. 414 * 415 * @return maximum allowable snapshot ID. 416 */ 417 public int getMaxSnapshotID() { 418 return ((1 << SNAPSHOT_ID_BIT_WIDTH) - 1); 419 } 420 421 private ObjectName mxBeanName; 422 423 public void registerMXBean() { 424 mxBeanName = MBeans.register("NameNode", "SnapshotInfo", this); 425 } 426 427 public void shutdown() { 428 MBeans.unregister(mxBeanName); 429 mxBeanName = null; 430 } 431 432 @Override // SnapshotStatsMXBean 433 public SnapshottableDirectoryStatus.Bean[] 434 getSnapshottableDirectories() { 435 List<SnapshottableDirectoryStatus.Bean> beans = 436 new ArrayList<SnapshottableDirectoryStatus.Bean>(); 437 for (INodeDirectory d : getSnapshottableDirs()) { 438 beans.add(toBean(d)); 439 } 440 return beans.toArray(new SnapshottableDirectoryStatus.Bean[beans.size()]); 441 } 442 443 @Override // SnapshotStatsMXBean 444 public SnapshotInfo.Bean[] getSnapshots() { 445 List<SnapshotInfo.Bean> beans = new ArrayList<SnapshotInfo.Bean>(); 446 for (INodeDirectory d : getSnapshottableDirs()) { 447 for (Snapshot s : d.getDirectorySnapshottableFeature().getSnapshotList()) { 448 beans.add(toBean(s)); 449 } 450 } 451 return beans.toArray(new SnapshotInfo.Bean[beans.size()]); 452 } 453 454 public static SnapshottableDirectoryStatus.Bean toBean(INodeDirectory d) { 455 return new SnapshottableDirectoryStatus.Bean( 456 d.getFullPathName(), 457 d.getDirectorySnapshottableFeature().getNumSnapshots(), 458 d.getDirectorySnapshottableFeature().getSnapshotQuota(), 459 d.getModificationTime(), 460 Short.valueOf(Integer.toOctalString( 461 d.getFsPermissionShort())), 462 d.getUserName(), 463 d.getGroupName()); 464 } 465 466 public static SnapshotInfo.Bean toBean(Snapshot s) { 467 return new SnapshotInfo.Bean( 468 s.getRoot().getLocalName(), s.getRoot().getFullPathName(), 469 s.getRoot().getModificationTime()); 470 } 471}