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; 019 020import java.io.FileNotFoundException; 021import java.io.PrintWriter; 022import java.util.ArrayList; 023import java.util.Collections; 024import java.util.Iterator; 025import java.util.List; 026import java.util.Map; 027 028import org.apache.hadoop.fs.PathIsNotDirectoryException; 029import org.apache.hadoop.fs.XAttr; 030import org.apache.hadoop.fs.permission.PermissionStatus; 031import org.apache.hadoop.hdfs.DFSUtil; 032import org.apache.hadoop.hdfs.protocol.QuotaExceededException; 033import org.apache.hadoop.hdfs.protocol.SnapshotException; 034import org.apache.hadoop.hdfs.server.blockmanagement.BlockStoragePolicySuite; 035import org.apache.hadoop.hdfs.server.namenode.INodeReference.WithCount; 036import org.apache.hadoop.hdfs.server.namenode.snapshot.DirectorySnapshottableFeature; 037import org.apache.hadoop.hdfs.server.namenode.snapshot.DirectoryWithSnapshotFeature; 038import org.apache.hadoop.hdfs.server.namenode.snapshot.DirectoryWithSnapshotFeature.DirectoryDiffList; 039import org.apache.hadoop.hdfs.server.namenode.snapshot.Snapshot; 040import org.apache.hadoop.hdfs.util.Diff.ListType; 041import org.apache.hadoop.hdfs.util.ReadOnlyList; 042 043import com.google.common.annotations.VisibleForTesting; 044import com.google.common.base.Preconditions; 045import com.google.common.collect.ImmutableList; 046 047/** 048 * Directory INode class. 049 */ 050public class INodeDirectory extends INodeWithAdditionalFields 051 implements INodeDirectoryAttributes { 052 053 /** Cast INode to INodeDirectory. */ 054 public static INodeDirectory valueOf(INode inode, Object path 055 ) throws FileNotFoundException, PathIsNotDirectoryException { 056 if (inode == null) { 057 throw new FileNotFoundException("Directory does not exist: " 058 + DFSUtil.path2String(path)); 059 } 060 if (!inode.isDirectory()) { 061 throw new PathIsNotDirectoryException(DFSUtil.path2String(path)); 062 } 063 return inode.asDirectory(); 064 } 065 066 protected static final int DEFAULT_FILES_PER_DIRECTORY = 5; 067 final static byte[] ROOT_NAME = DFSUtil.string2Bytes(""); 068 069 private List<INode> children = null; 070 071 /** constructor */ 072 public INodeDirectory(long id, byte[] name, PermissionStatus permissions, 073 long mtime) { 074 super(id, name, permissions, mtime, 0L); 075 } 076 077 /** 078 * Copy constructor 079 * @param other The INodeDirectory to be copied 080 * @param adopt Indicate whether or not need to set the parent field of child 081 * INodes to the new node 082 * @param featuresToCopy any number of features to copy to the new node. 083 * The method will do a reference copy, not a deep copy. 084 */ 085 public INodeDirectory(INodeDirectory other, boolean adopt, 086 Feature... featuresToCopy) { 087 super(other); 088 this.children = other.children; 089 if (adopt && this.children != null) { 090 for (INode child : children) { 091 child.setParent(this); 092 } 093 } 094 this.features = featuresToCopy; 095 } 096 097 /** @return true unconditionally. */ 098 @Override 099 public final boolean isDirectory() { 100 return true; 101 } 102 103 /** @return this object. */ 104 @Override 105 public final INodeDirectory asDirectory() { 106 return this; 107 } 108 109 @Override 110 public byte getLocalStoragePolicyID() { 111 XAttrFeature f = getXAttrFeature(); 112 ImmutableList<XAttr> xattrs = f == null ? ImmutableList.<XAttr> of() : f 113 .getXAttrs(); 114 for (XAttr xattr : xattrs) { 115 if (BlockStoragePolicySuite.isStoragePolicyXAttr(xattr)) { 116 return (xattr.getValue())[0]; 117 } 118 } 119 return BlockStoragePolicySuite.ID_UNSPECIFIED; 120 } 121 122 @Override 123 public byte getStoragePolicyID() { 124 byte id = getLocalStoragePolicyID(); 125 if (id != BlockStoragePolicySuite.ID_UNSPECIFIED) { 126 return id; 127 } 128 // if it is unspecified, check its parent 129 return getParent() != null ? getParent().getStoragePolicyID() : 130 BlockStoragePolicySuite.ID_UNSPECIFIED; 131 } 132 133 void setQuota(long nsQuota, long dsQuota) { 134 DirectoryWithQuotaFeature quota = getDirectoryWithQuotaFeature(); 135 if (quota != null) { 136 // already has quota; so set the quota to the new values 137 quota.setQuota(nsQuota, dsQuota); 138 if (!isQuotaSet() && !isRoot()) { 139 removeFeature(quota); 140 } 141 } else { 142 final Quota.Counts c = computeQuotaUsage(); 143 quota = addDirectoryWithQuotaFeature(nsQuota, dsQuota); 144 quota.setSpaceConsumed(c.get(Quota.NAMESPACE), c.get(Quota.DISKSPACE)); 145 } 146 } 147 148 @Override 149 public Quota.Counts getQuotaCounts() { 150 final DirectoryWithQuotaFeature q = getDirectoryWithQuotaFeature(); 151 return q != null? q.getQuota(): super.getQuotaCounts(); 152 } 153 154 @Override 155 public void addSpaceConsumed(long nsDelta, long dsDelta, boolean verify) 156 throws QuotaExceededException { 157 final DirectoryWithQuotaFeature q = getDirectoryWithQuotaFeature(); 158 if (q != null) { 159 q.addSpaceConsumed(this, nsDelta, dsDelta, verify); 160 } else { 161 addSpaceConsumed2Parent(nsDelta, dsDelta, verify); 162 } 163 } 164 165 /** 166 * If the directory contains a {@link DirectoryWithQuotaFeature}, return it; 167 * otherwise, return null. 168 */ 169 public final DirectoryWithQuotaFeature getDirectoryWithQuotaFeature() { 170 return getFeature(DirectoryWithQuotaFeature.class); 171 } 172 173 /** Is this directory with quota? */ 174 final boolean isWithQuota() { 175 return getDirectoryWithQuotaFeature() != null; 176 } 177 178 DirectoryWithQuotaFeature addDirectoryWithQuotaFeature( 179 long nsQuota, long dsQuota) { 180 Preconditions.checkState(!isWithQuota(), "Directory is already with quota"); 181 final DirectoryWithQuotaFeature quota = new DirectoryWithQuotaFeature( 182 nsQuota, dsQuota); 183 addFeature(quota); 184 return quota; 185 } 186 187 int searchChildren(byte[] name) { 188 return children == null? -1: Collections.binarySearch(children, name); 189 } 190 191 public DirectoryWithSnapshotFeature addSnapshotFeature( 192 DirectoryDiffList diffs) { 193 Preconditions.checkState(!isWithSnapshot(), 194 "Directory is already with snapshot"); 195 DirectoryWithSnapshotFeature sf = new DirectoryWithSnapshotFeature(diffs); 196 addFeature(sf); 197 return sf; 198 } 199 200 /** 201 * If feature list contains a {@link DirectoryWithSnapshotFeature}, return it; 202 * otherwise, return null. 203 */ 204 public final DirectoryWithSnapshotFeature getDirectoryWithSnapshotFeature() { 205 return getFeature(DirectoryWithSnapshotFeature.class); 206 } 207 208 /** Is this file has the snapshot feature? */ 209 public final boolean isWithSnapshot() { 210 return getDirectoryWithSnapshotFeature() != null; 211 } 212 213 public DirectoryDiffList getDiffs() { 214 DirectoryWithSnapshotFeature sf = getDirectoryWithSnapshotFeature(); 215 return sf != null ? sf.getDiffs() : null; 216 } 217 218 @Override 219 public INodeDirectoryAttributes getSnapshotINode(int snapshotId) { 220 DirectoryWithSnapshotFeature sf = getDirectoryWithSnapshotFeature(); 221 return sf == null ? this : sf.getDiffs().getSnapshotINode(snapshotId, this); 222 } 223 224 @Override 225 public String toDetailString() { 226 DirectoryWithSnapshotFeature sf = this.getDirectoryWithSnapshotFeature(); 227 return super.toDetailString() + (sf == null ? "" : ", " + sf.getDiffs()); 228 } 229 230 public DirectorySnapshottableFeature getDirectorySnapshottableFeature() { 231 return getFeature(DirectorySnapshottableFeature.class); 232 } 233 234 public boolean isSnapshottable() { 235 return getDirectorySnapshottableFeature() != null; 236 } 237 238 public Snapshot getSnapshot(byte[] snapshotName) { 239 return getDirectorySnapshottableFeature().getSnapshot(snapshotName); 240 } 241 242 public void setSnapshotQuota(int snapshotQuota) { 243 getDirectorySnapshottableFeature().setSnapshotQuota(snapshotQuota); 244 } 245 246 public Snapshot addSnapshot(int id, String name) throws SnapshotException, 247 QuotaExceededException { 248 return getDirectorySnapshottableFeature().addSnapshot(this, id, name); 249 } 250 251 public Snapshot removeSnapshot(String snapshotName, 252 BlocksMapUpdateInfo collectedBlocks, final List<INode> removedINodes) 253 throws SnapshotException { 254 return getDirectorySnapshottableFeature().removeSnapshot(this, 255 snapshotName, collectedBlocks, removedINodes); 256 } 257 258 public void renameSnapshot(String path, String oldName, String newName) 259 throws SnapshotException { 260 getDirectorySnapshottableFeature().renameSnapshot(path, oldName, newName); 261 } 262 263 /** add DirectorySnapshottableFeature */ 264 public void addSnapshottableFeature() { 265 Preconditions.checkState(!isSnapshottable(), 266 "this is already snapshottable, this=%s", this); 267 DirectoryWithSnapshotFeature s = this.getDirectoryWithSnapshotFeature(); 268 final DirectorySnapshottableFeature snapshottable = 269 new DirectorySnapshottableFeature(s); 270 if (s != null) { 271 this.removeFeature(s); 272 } 273 this.addFeature(snapshottable); 274 } 275 276 /** remove DirectorySnapshottableFeature */ 277 public void removeSnapshottableFeature() { 278 DirectorySnapshottableFeature s = getDirectorySnapshottableFeature(); 279 Preconditions.checkState(s != null, 280 "The dir does not have snapshottable feature: this=%s", this); 281 this.removeFeature(s); 282 if (s.getDiffs().asList().size() > 0) { 283 // add a DirectoryWithSnapshotFeature back 284 DirectoryWithSnapshotFeature sf = new DirectoryWithSnapshotFeature( 285 s.getDiffs()); 286 addFeature(sf); 287 } 288 } 289 290 /** 291 * Replace the given child with a new child. Note that we no longer need to 292 * replace an normal INodeDirectory or INodeFile into an 293 * INodeDirectoryWithSnapshot or INodeFileUnderConstruction. The only cases 294 * for child replacement is for reference nodes. 295 */ 296 public void replaceChild(INode oldChild, final INode newChild, 297 final INodeMap inodeMap) { 298 Preconditions.checkNotNull(children); 299 final int i = searchChildren(newChild.getLocalNameBytes()); 300 Preconditions.checkState(i >= 0); 301 Preconditions.checkState(oldChild == children.get(i) 302 || oldChild == children.get(i).asReference().getReferredINode() 303 .asReference().getReferredINode()); 304 oldChild = children.get(i); 305 306 if (oldChild.isReference() && newChild.isReference()) { 307 // both are reference nodes, e.g., DstReference -> WithName 308 final INodeReference.WithCount withCount = 309 (WithCount) oldChild.asReference().getReferredINode(); 310 withCount.removeReference(oldChild.asReference()); 311 } 312 children.set(i, newChild); 313 314 // replace the instance in the created list of the diff list 315 DirectoryWithSnapshotFeature sf = this.getDirectoryWithSnapshotFeature(); 316 if (sf != null) { 317 sf.getDiffs().replaceChild(ListType.CREATED, oldChild, newChild); 318 } 319 320 // update the inodeMap 321 if (inodeMap != null) { 322 inodeMap.put(newChild); 323 } 324 } 325 326 INodeReference.WithName replaceChild4ReferenceWithName(INode oldChild, 327 int latestSnapshotId) { 328 Preconditions.checkArgument(latestSnapshotId != Snapshot.CURRENT_STATE_ID); 329 if (oldChild instanceof INodeReference.WithName) { 330 return (INodeReference.WithName)oldChild; 331 } 332 333 final INodeReference.WithCount withCount; 334 if (oldChild.isReference()) { 335 Preconditions.checkState(oldChild instanceof INodeReference.DstReference); 336 withCount = (INodeReference.WithCount) oldChild.asReference() 337 .getReferredINode(); 338 } else { 339 withCount = new INodeReference.WithCount(null, oldChild); 340 } 341 final INodeReference.WithName ref = new INodeReference.WithName(this, 342 withCount, oldChild.getLocalNameBytes(), latestSnapshotId); 343 replaceChild(oldChild, ref, null); 344 return ref; 345 } 346 347 @Override 348 public void recordModification(int latestSnapshotId) { 349 if (isInLatestSnapshot(latestSnapshotId) 350 && !shouldRecordInSrcSnapshot(latestSnapshotId)) { 351 // add snapshot feature if necessary 352 DirectoryWithSnapshotFeature sf = getDirectoryWithSnapshotFeature(); 353 if (sf == null) { 354 sf = addSnapshotFeature(null); 355 } 356 // record self in the diff list if necessary 357 sf.getDiffs().saveSelf2Snapshot(latestSnapshotId, this, null); 358 } 359 } 360 361 /** 362 * Save the child to the latest snapshot. 363 * 364 * @return the child inode, which may be replaced. 365 */ 366 public INode saveChild2Snapshot(final INode child, final int latestSnapshotId, 367 final INode snapshotCopy) { 368 if (latestSnapshotId == Snapshot.CURRENT_STATE_ID) { 369 return child; 370 } 371 372 // add snapshot feature if necessary 373 DirectoryWithSnapshotFeature sf = getDirectoryWithSnapshotFeature(); 374 if (sf == null) { 375 sf = this.addSnapshotFeature(null); 376 } 377 return sf.saveChild2Snapshot(this, child, latestSnapshotId, snapshotCopy); 378 } 379 380 /** 381 * @param name the name of the child 382 * @param snapshotId 383 * if it is not {@link Snapshot#CURRENT_STATE_ID}, get the result 384 * from the corresponding snapshot; otherwise, get the result from 385 * the current directory. 386 * @return the child inode. 387 */ 388 public INode getChild(byte[] name, int snapshotId) { 389 DirectoryWithSnapshotFeature sf; 390 if (snapshotId == Snapshot.CURRENT_STATE_ID || 391 (sf = getDirectoryWithSnapshotFeature()) == null) { 392 ReadOnlyList<INode> c = getCurrentChildrenList(); 393 final int i = ReadOnlyList.Util.binarySearch(c, name); 394 return i < 0 ? null : c.get(i); 395 } 396 397 return sf.getChild(this, name, snapshotId); 398 } 399 400 /** 401 * Search for the given INode in the children list and the deleted lists of 402 * snapshots. 403 * @return {@link Snapshot#CURRENT_STATE_ID} if the inode is in the children 404 * list; {@link Snapshot#NO_SNAPSHOT_ID} if the inode is neither in the 405 * children list nor in any snapshot; otherwise the snapshot id of the 406 * corresponding snapshot diff list. 407 */ 408 public int searchChild(INode inode) { 409 INode child = getChild(inode.getLocalNameBytes(), Snapshot.CURRENT_STATE_ID); 410 if (child != inode) { 411 // inode is not in parent's children list, thus inode must be in 412 // snapshot. identify the snapshot id and later add it into the path 413 DirectoryDiffList diffs = getDiffs(); 414 if (diffs == null) { 415 return Snapshot.NO_SNAPSHOT_ID; 416 } 417 return diffs.findSnapshotDeleted(inode); 418 } else { 419 return Snapshot.CURRENT_STATE_ID; 420 } 421 } 422 423 /** 424 * @param snapshotId 425 * if it is not {@link Snapshot#CURRENT_STATE_ID}, get the result 426 * from the corresponding snapshot; otherwise, get the result from 427 * the current directory. 428 * @return the current children list if the specified snapshot is null; 429 * otherwise, return the children list corresponding to the snapshot. 430 * Note that the returned list is never null. 431 */ 432 public ReadOnlyList<INode> getChildrenList(final int snapshotId) { 433 DirectoryWithSnapshotFeature sf; 434 if (snapshotId == Snapshot.CURRENT_STATE_ID 435 || (sf = this.getDirectoryWithSnapshotFeature()) == null) { 436 return getCurrentChildrenList(); 437 } 438 return sf.getChildrenList(this, snapshotId); 439 } 440 441 private ReadOnlyList<INode> getCurrentChildrenList() { 442 return children == null ? ReadOnlyList.Util.<INode> emptyList() 443 : ReadOnlyList.Util.asReadOnlyList(children); 444 } 445 446 /** 447 * Given a child's name, return the index of the next child 448 * 449 * @param name a child's name 450 * @return the index of the next child 451 */ 452 static int nextChild(ReadOnlyList<INode> children, byte[] name) { 453 if (name.length == 0) { // empty name 454 return 0; 455 } 456 int nextPos = ReadOnlyList.Util.binarySearch(children, name) + 1; 457 if (nextPos >= 0) { 458 return nextPos; 459 } 460 return -nextPos; 461 } 462 463 /** 464 * Remove the specified child from this directory. 465 */ 466 public boolean removeChild(INode child, int latestSnapshotId) { 467 if (isInLatestSnapshot(latestSnapshotId)) { 468 // create snapshot feature if necessary 469 DirectoryWithSnapshotFeature sf = this.getDirectoryWithSnapshotFeature(); 470 if (sf == null) { 471 sf = this.addSnapshotFeature(null); 472 } 473 return sf.removeChild(this, child, latestSnapshotId); 474 } 475 return removeChild(child); 476 } 477 478 /** 479 * Remove the specified child from this directory. 480 * The basic remove method which actually calls children.remove(..). 481 * 482 * @param child the child inode to be removed 483 * 484 * @return true if the child is removed; false if the child is not found. 485 */ 486 public boolean removeChild(final INode child) { 487 final int i = searchChildren(child.getLocalNameBytes()); 488 if (i < 0) { 489 return false; 490 } 491 492 final INode removed = children.remove(i); 493 Preconditions.checkState(removed == child); 494 return true; 495 } 496 497 /** 498 * Add a child inode to the directory. 499 * 500 * @param node INode to insert 501 * @param setModTime set modification time for the parent node 502 * not needed when replaying the addition and 503 * the parent already has the proper mod time 504 * @return false if the child with this name already exists; 505 * otherwise, return true; 506 */ 507 public boolean addChild(INode node, final boolean setModTime, 508 final int latestSnapshotId) throws QuotaExceededException { 509 final int low = searchChildren(node.getLocalNameBytes()); 510 if (low >= 0) { 511 return false; 512 } 513 514 if (isInLatestSnapshot(latestSnapshotId)) { 515 // create snapshot feature if necessary 516 DirectoryWithSnapshotFeature sf = this.getDirectoryWithSnapshotFeature(); 517 if (sf == null) { 518 sf = this.addSnapshotFeature(null); 519 } 520 return sf.addChild(this, node, setModTime, latestSnapshotId); 521 } 522 addChild(node, low); 523 if (setModTime) { 524 // update modification time of the parent directory 525 updateModificationTime(node.getModificationTime(), latestSnapshotId); 526 } 527 return true; 528 } 529 530 public boolean addChild(INode node) { 531 final int low = searchChildren(node.getLocalNameBytes()); 532 if (low >= 0) { 533 return false; 534 } 535 addChild(node, low); 536 return true; 537 } 538 539 /** 540 * Add the node to the children list at the given insertion point. 541 * The basic add method which actually calls children.add(..). 542 */ 543 private void addChild(final INode node, final int insertionPoint) { 544 if (children == null) { 545 children = new ArrayList<INode>(DEFAULT_FILES_PER_DIRECTORY); 546 } 547 node.setParent(this); 548 children.add(-insertionPoint - 1, node); 549 550 if (node.getGroupName() == null) { 551 node.setGroup(getGroupName()); 552 } 553 } 554 555 @Override 556 public Quota.Counts computeQuotaUsage(Quota.Counts counts, boolean useCache, 557 int lastSnapshotId) { 558 final DirectoryWithSnapshotFeature sf = getDirectoryWithSnapshotFeature(); 559 560 // we are computing the quota usage for a specific snapshot here, i.e., the 561 // computation only includes files/directories that exist at the time of the 562 // given snapshot 563 if (sf != null && lastSnapshotId != Snapshot.CURRENT_STATE_ID 564 && !(useCache && isQuotaSet())) { 565 ReadOnlyList<INode> childrenList = getChildrenList(lastSnapshotId); 566 for (INode child : childrenList) { 567 child.computeQuotaUsage(counts, useCache, lastSnapshotId); 568 } 569 counts.add(Quota.NAMESPACE, 1); 570 return counts; 571 } 572 573 // compute the quota usage in the scope of the current directory tree 574 final DirectoryWithQuotaFeature q = getDirectoryWithQuotaFeature(); 575 if (useCache && q != null && q.isQuotaSet()) { // use the cached quota 576 return q.addNamespaceDiskspace(counts); 577 } else { 578 useCache = q != null && !q.isQuotaSet() ? false : useCache; 579 return computeDirectoryQuotaUsage(counts, useCache, lastSnapshotId); 580 } 581 } 582 583 private Quota.Counts computeDirectoryQuotaUsage(Quota.Counts counts, 584 boolean useCache, int lastSnapshotId) { 585 if (children != null) { 586 for (INode child : children) { 587 child.computeQuotaUsage(counts, useCache, lastSnapshotId); 588 } 589 } 590 return computeQuotaUsage4CurrentDirectory(counts); 591 } 592 593 /** Add quota usage for this inode excluding children. */ 594 public Quota.Counts computeQuotaUsage4CurrentDirectory(Quota.Counts counts) { 595 counts.add(Quota.NAMESPACE, 1); 596 // include the diff list 597 DirectoryWithSnapshotFeature sf = getDirectoryWithSnapshotFeature(); 598 if (sf != null) { 599 sf.computeQuotaUsage4CurrentDirectory(counts); 600 } 601 return counts; 602 } 603 604 @Override 605 public ContentSummaryComputationContext computeContentSummary( 606 ContentSummaryComputationContext summary) { 607 final DirectoryWithSnapshotFeature sf = getDirectoryWithSnapshotFeature(); 608 if (sf != null) { 609 sf.computeContentSummary4Snapshot(summary.getCounts()); 610 } 611 final DirectoryWithQuotaFeature q = getDirectoryWithQuotaFeature(); 612 if (q != null) { 613 return q.computeContentSummary(this, summary); 614 } else { 615 return computeDirectoryContentSummary(summary, Snapshot.CURRENT_STATE_ID); 616 } 617 } 618 619 protected ContentSummaryComputationContext computeDirectoryContentSummary( 620 ContentSummaryComputationContext summary, int snapshotId) { 621 ReadOnlyList<INode> childrenList = getChildrenList(snapshotId); 622 // Explicit traversing is done to enable repositioning after relinquishing 623 // and reacquiring locks. 624 for (int i = 0; i < childrenList.size(); i++) { 625 INode child = childrenList.get(i); 626 byte[] childName = child.getLocalNameBytes(); 627 628 long lastYieldCount = summary.getYieldCount(); 629 child.computeContentSummary(summary); 630 631 // Check whether the computation was paused in the subtree. 632 // The counts may be off, but traversing the rest of children 633 // should be made safe. 634 if (lastYieldCount == summary.getYieldCount()) { 635 continue; 636 } 637 // The locks were released and reacquired. Check parent first. 638 if (getParent() == null) { 639 // Stop further counting and return whatever we have so far. 640 break; 641 } 642 // Obtain the children list again since it may have been modified. 643 childrenList = getChildrenList(snapshotId); 644 // Reposition in case the children list is changed. Decrement by 1 645 // since it will be incremented when loops. 646 i = nextChild(childrenList, childName) - 1; 647 } 648 649 // Increment the directory count for this directory. 650 summary.getCounts().add(Content.DIRECTORY, 1); 651 // Relinquish and reacquire locks if necessary. 652 summary.yield(); 653 return summary; 654 } 655 656 /** 657 * This method is usually called by the undo section of rename. 658 * 659 * Before calling this function, in the rename operation, we replace the 660 * original src node (of the rename operation) with a reference node (WithName 661 * instance) in both the children list and a created list, delete the 662 * reference node from the children list, and add it to the corresponding 663 * deleted list. 664 * 665 * To undo the above operations, we have the following steps in particular: 666 * 667 * <pre> 668 * 1) remove the WithName node from the deleted list (if it exists) 669 * 2) replace the WithName node in the created list with srcChild 670 * 3) add srcChild back as a child of srcParent. Note that we already add 671 * the node into the created list of a snapshot diff in step 2, we do not need 672 * to add srcChild to the created list of the latest snapshot. 673 * </pre> 674 * 675 * We do not need to update quota usage because the old child is in the 676 * deleted list before. 677 * 678 * @param oldChild 679 * The reference node to be removed/replaced 680 * @param newChild 681 * The node to be added back 682 * @throws QuotaExceededException should not throw this exception 683 */ 684 public void undoRename4ScrParent(final INodeReference oldChild, 685 final INode newChild) throws QuotaExceededException { 686 DirectoryWithSnapshotFeature sf = getDirectoryWithSnapshotFeature(); 687 Preconditions.checkState(sf != null, 688 "Directory does not have snapshot feature"); 689 sf.getDiffs().removeChild(ListType.DELETED, oldChild); 690 sf.getDiffs().replaceChild(ListType.CREATED, oldChild, newChild); 691 addChild(newChild, true, Snapshot.CURRENT_STATE_ID); 692 } 693 694 /** 695 * Undo the rename operation for the dst tree, i.e., if the rename operation 696 * (with OVERWRITE option) removes a file/dir from the dst tree, add it back 697 * and delete possible record in the deleted list. 698 */ 699 public void undoRename4DstParent(final INode deletedChild, 700 int latestSnapshotId) throws QuotaExceededException { 701 DirectoryWithSnapshotFeature sf = getDirectoryWithSnapshotFeature(); 702 Preconditions.checkState(sf != null, 703 "Directory does not have snapshot feature"); 704 boolean removeDeletedChild = sf.getDiffs().removeChild(ListType.DELETED, 705 deletedChild); 706 int sid = removeDeletedChild ? Snapshot.CURRENT_STATE_ID : latestSnapshotId; 707 final boolean added = addChild(deletedChild, true, sid); 708 // update quota usage if adding is successfully and the old child has not 709 // been stored in deleted list before 710 if (added && !removeDeletedChild) { 711 final Quota.Counts counts = deletedChild.computeQuotaUsage(); 712 addSpaceConsumed(counts.get(Quota.NAMESPACE), 713 counts.get(Quota.DISKSPACE), false); 714 } 715 } 716 717 /** Set the children list to null. */ 718 public void clearChildren() { 719 this.children = null; 720 } 721 722 @Override 723 public void clear() { 724 super.clear(); 725 clearChildren(); 726 } 727 728 /** Call cleanSubtree(..) recursively down the subtree. */ 729 public Quota.Counts cleanSubtreeRecursively(final int snapshot, 730 int prior, final BlocksMapUpdateInfo collectedBlocks, 731 final List<INode> removedINodes, final Map<INode, INode> excludedNodes) { 732 Quota.Counts counts = Quota.Counts.newInstance(); 733 // in case of deletion snapshot, since this call happens after we modify 734 // the diff list, the snapshot to be deleted has been combined or renamed 735 // to its latest previous snapshot. (besides, we also need to consider nodes 736 // created after prior but before snapshot. this will be done in 737 // DirectoryWithSnapshotFeature) 738 int s = snapshot != Snapshot.CURRENT_STATE_ID 739 && prior != Snapshot.NO_SNAPSHOT_ID ? prior : snapshot; 740 for (INode child : getChildrenList(s)) { 741 if (snapshot != Snapshot.CURRENT_STATE_ID && excludedNodes != null 742 && excludedNodes.containsKey(child)) { 743 continue; 744 } else { 745 Quota.Counts childCounts = child.cleanSubtree(snapshot, prior, 746 collectedBlocks, removedINodes); 747 counts.add(childCounts); 748 } 749 } 750 return counts; 751 } 752 753 @Override 754 public void destroyAndCollectBlocks(final BlocksMapUpdateInfo collectedBlocks, 755 final List<INode> removedINodes) { 756 final DirectoryWithSnapshotFeature sf = getDirectoryWithSnapshotFeature(); 757 if (sf != null) { 758 sf.clear(this, collectedBlocks, removedINodes); 759 } 760 for (INode child : getChildrenList(Snapshot.CURRENT_STATE_ID)) { 761 child.destroyAndCollectBlocks(collectedBlocks, removedINodes); 762 } 763 clear(); 764 removedINodes.add(this); 765 } 766 767 @Override 768 public Quota.Counts cleanSubtree(final int snapshotId, int priorSnapshotId, 769 final BlocksMapUpdateInfo collectedBlocks, 770 final List<INode> removedINodes) { 771 DirectoryWithSnapshotFeature sf = getDirectoryWithSnapshotFeature(); 772 // there is snapshot data 773 if (sf != null) { 774 return sf.cleanDirectory(this, snapshotId, priorSnapshotId, 775 collectedBlocks, removedINodes); 776 } 777 // there is no snapshot data 778 if (priorSnapshotId == Snapshot.NO_SNAPSHOT_ID 779 && snapshotId == Snapshot.CURRENT_STATE_ID) { 780 // destroy the whole subtree and collect blocks that should be deleted 781 Quota.Counts counts = Quota.Counts.newInstance(); 782 this.computeQuotaUsage(counts, true); 783 destroyAndCollectBlocks(collectedBlocks, removedINodes); 784 return counts; 785 } else { 786 // process recursively down the subtree 787 Quota.Counts counts = cleanSubtreeRecursively(snapshotId, priorSnapshotId, 788 collectedBlocks, removedINodes, null); 789 if (isQuotaSet()) { 790 getDirectoryWithQuotaFeature().addSpaceConsumed2Cache( 791 -counts.get(Quota.NAMESPACE), -counts.get(Quota.DISKSPACE)); 792 } 793 return counts; 794 } 795 } 796 797 /** 798 * Compare the metadata with another INodeDirectory 799 */ 800 @Override 801 public boolean metadataEquals(INodeDirectoryAttributes other) { 802 return other != null 803 && getQuotaCounts().equals(other.getQuotaCounts()) 804 && getPermissionLong() == other.getPermissionLong() 805 && getAclFeature() == other.getAclFeature() 806 && getXAttrFeature() == other.getXAttrFeature(); 807 } 808 809 /* 810 * The following code is to dump the tree recursively for testing. 811 * 812 * \- foo (INodeDirectory@33dd2717) 813 * \- sub1 (INodeDirectory@442172) 814 * +- file1 (INodeFile@78392d4) 815 * +- file2 (INodeFile@78392d5) 816 * +- sub11 (INodeDirectory@8400cff) 817 * \- file3 (INodeFile@78392d6) 818 * \- z_file4 (INodeFile@45848712) 819 */ 820 static final String DUMPTREE_EXCEPT_LAST_ITEM = "+-"; 821 static final String DUMPTREE_LAST_ITEM = "\\-"; 822 @VisibleForTesting 823 @Override 824 public void dumpTreeRecursively(PrintWriter out, StringBuilder prefix, 825 final int snapshot) { 826 super.dumpTreeRecursively(out, prefix, snapshot); 827 out.print(", childrenSize=" + getChildrenList(snapshot).size()); 828 final DirectoryWithQuotaFeature q = getDirectoryWithQuotaFeature(); 829 if (q != null) { 830 out.print(", " + q); 831 } 832 if (this instanceof Snapshot.Root) { 833 out.print(", snapshotId=" + snapshot); 834 } 835 out.println(); 836 837 if (prefix.length() >= 2) { 838 prefix.setLength(prefix.length() - 2); 839 prefix.append(" "); 840 } 841 dumpTreeRecursively(out, prefix, new Iterable<SnapshotAndINode>() { 842 final Iterator<INode> i = getChildrenList(snapshot).iterator(); 843 844 @Override 845 public Iterator<SnapshotAndINode> iterator() { 846 return new Iterator<SnapshotAndINode>() { 847 @Override 848 public boolean hasNext() { 849 return i.hasNext(); 850 } 851 852 @Override 853 public SnapshotAndINode next() { 854 return new SnapshotAndINode(snapshot, i.next()); 855 } 856 857 @Override 858 public void remove() { 859 throw new UnsupportedOperationException(); 860 } 861 }; 862 } 863 }); 864 865 final DirectorySnapshottableFeature s = getDirectorySnapshottableFeature(); 866 if (s != null) { 867 s.dumpTreeRecursively(this, out, prefix, snapshot); 868 } 869 } 870 871 /** 872 * Dump the given subtrees. 873 * @param prefix The prefix string that each line should print. 874 * @param subs The subtrees. 875 */ 876 @VisibleForTesting 877 public static void dumpTreeRecursively(PrintWriter out, 878 StringBuilder prefix, Iterable<SnapshotAndINode> subs) { 879 if (subs != null) { 880 for(final Iterator<SnapshotAndINode> i = subs.iterator(); i.hasNext();) { 881 final SnapshotAndINode pair = i.next(); 882 prefix.append(i.hasNext()? DUMPTREE_EXCEPT_LAST_ITEM: DUMPTREE_LAST_ITEM); 883 pair.inode.dumpTreeRecursively(out, prefix, pair.snapshotId); 884 prefix.setLength(prefix.length() - 2); 885 } 886 } 887 } 888 889 /** A pair of Snapshot and INode objects. */ 890 public static class SnapshotAndINode { 891 public final int snapshotId; 892 public final INode inode; 893 894 public SnapshotAndINode(int snapshot, INode inode) { 895 this.snapshotId = snapshot; 896 this.inode = inode; 897 } 898 } 899 900 public final int getChildrenNum(final int snapshotId) { 901 return getChildrenList(snapshotId).size(); 902 } 903}