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.hdfs.server.blockmanagement;
019
020 import java.io.DataInput;
021 import java.io.IOException;
022 import java.util.ArrayList;
023 import java.util.Collection;
024 import java.util.Iterator;
025 import java.util.LinkedList;
026 import java.util.List;
027 import java.util.Queue;
028 import java.util.Set;
029 import java.util.TreeSet;
030
031 import org.apache.hadoop.classification.InterfaceAudience;
032 import org.apache.hadoop.classification.InterfaceStability;
033 import org.apache.hadoop.hdfs.DeprecatedUTF8;
034 import org.apache.hadoop.hdfs.protocol.Block;
035 import org.apache.hadoop.hdfs.protocol.DatanodeID;
036 import org.apache.hadoop.hdfs.protocol.DatanodeInfo;
037 import org.apache.hadoop.io.Text;
038 import org.apache.hadoop.io.WritableUtils;
039
040 /**************************************************
041 * DatanodeDescriptor tracks stats on a given DataNode, such as
042 * available storage capacity, last update time, etc., and maintains a
043 * set of blocks stored on the datanode.
044 *
045 * This data structure is internal to the namenode. It is *not* sent
046 * over-the-wire to the Client or the Datanodes. Neither is it stored
047 * persistently in the fsImage.
048 **************************************************/
049 @InterfaceAudience.Private
050 public class DatanodeDescriptor extends DatanodeInfo {
051
052 // Stores status of decommissioning.
053 // If node is not decommissioning, do not use this object for anything.
054 public DecommissioningStatus decommissioningStatus = new DecommissioningStatus();
055
056 /** Block and targets pair */
057 @InterfaceAudience.Private
058 @InterfaceStability.Evolving
059 public static class BlockTargetPair {
060 public final Block block;
061 public final DatanodeDescriptor[] targets;
062
063 BlockTargetPair(Block block, DatanodeDescriptor[] targets) {
064 this.block = block;
065 this.targets = targets;
066 }
067 }
068
069 /** A BlockTargetPair queue. */
070 private static class BlockQueue<E> {
071 private final Queue<E> blockq = new LinkedList<E>();
072
073 /** Size of the queue */
074 synchronized int size() {return blockq.size();}
075
076 /** Enqueue */
077 synchronized boolean offer(E e) {
078 return blockq.offer(e);
079 }
080
081 /** Dequeue */
082 synchronized List<E> poll(int numBlocks) {
083 if (numBlocks <= 0 || blockq.isEmpty()) {
084 return null;
085 }
086
087 List<E> results = new ArrayList<E>();
088 for(; !blockq.isEmpty() && numBlocks > 0; numBlocks--) {
089 results.add(blockq.poll());
090 }
091 return results;
092 }
093
094 /**
095 * Returns <tt>true</tt> if the queue contains the specified element.
096 */
097 boolean contains(E e) {
098 return blockq.contains(e);
099 }
100 }
101
102 private volatile BlockInfo blockList = null;
103 private int numBlocks = 0;
104 // isAlive == heartbeats.contains(this)
105 // This is an optimization, because contains takes O(n) time on Arraylist
106 public boolean isAlive = false;
107 public boolean needKeyUpdate = false;
108
109 // A system administrator can tune the balancer bandwidth parameter
110 // (dfs.balance.bandwidthPerSec) dynamically by calling
111 // "dfsadmin -setBalanacerBandwidth <newbandwidth>", at which point the
112 // following 'bandwidth' variable gets updated with the new value for each
113 // node. Once the heartbeat command is issued to update the value on the
114 // specified datanode, this value will be set back to 0.
115 private long bandwidth;
116
117 /** A queue of blocks to be replicated by this datanode */
118 private BlockQueue<BlockTargetPair> replicateBlocks = new BlockQueue<BlockTargetPair>();
119 /** A queue of blocks to be recovered by this datanode */
120 private BlockQueue<BlockInfoUnderConstruction> recoverBlocks =
121 new BlockQueue<BlockInfoUnderConstruction>();
122 /** A set of blocks to be invalidated by this datanode */
123 private Set<Block> invalidateBlocks = new TreeSet<Block>();
124
125 /* Variables for maintaining number of blocks scheduled to be written to
126 * this datanode. This count is approximate and might be slightly bigger
127 * in case of errors (e.g. datanode does not report if an error occurs
128 * while writing the block).
129 */
130 private int currApproxBlocksScheduled = 0;
131 private int prevApproxBlocksScheduled = 0;
132 private long lastBlocksScheduledRollTime = 0;
133 private static final int BLOCKS_SCHEDULED_ROLL_INTERVAL = 600*1000; //10min
134 private int volumeFailures = 0;
135 /**
136 * When set to true, the node is not in include list and is not allowed
137 * to communicate with the namenode
138 */
139 private boolean disallowed = false;
140
141 /** Default constructor */
142 public DatanodeDescriptor() {}
143
144 /** DatanodeDescriptor constructor
145 * @param nodeID id of the data node
146 */
147 public DatanodeDescriptor(DatanodeID nodeID) {
148 this(nodeID, 0L, 0L, 0L, 0L, 0, 0);
149 }
150
151 /** DatanodeDescriptor constructor
152 *
153 * @param nodeID id of the data node
154 * @param networkLocation location of the data node in network
155 */
156 public DatanodeDescriptor(DatanodeID nodeID,
157 String networkLocation) {
158 this(nodeID, networkLocation, null);
159 }
160
161 /** DatanodeDescriptor constructor
162 *
163 * @param nodeID id of the data node
164 * @param networkLocation location of the data node in network
165 * @param hostName it could be different from host specified for DatanodeID
166 */
167 public DatanodeDescriptor(DatanodeID nodeID,
168 String networkLocation,
169 String hostName) {
170 this(nodeID, networkLocation, hostName, 0L, 0L, 0L, 0L, 0, 0);
171 }
172
173 /** DatanodeDescriptor constructor
174 *
175 * @param nodeID id of the data node
176 * @param capacity capacity of the data node
177 * @param dfsUsed space used by the data node
178 * @param remaining remaining capacity of the data node
179 * @param bpused space used by the block pool corresponding to this namenode
180 * @param xceiverCount # of data transfers at the data node
181 */
182 public DatanodeDescriptor(DatanodeID nodeID,
183 long capacity,
184 long dfsUsed,
185 long remaining,
186 long bpused,
187 int xceiverCount,
188 int failedVolumes) {
189 super(nodeID);
190 updateHeartbeat(capacity, dfsUsed, remaining, bpused, xceiverCount,
191 failedVolumes);
192 }
193
194 /** DatanodeDescriptor constructor
195 *
196 * @param nodeID id of the data node
197 * @param networkLocation location of the data node in network
198 * @param capacity capacity of the data node, including space used by non-dfs
199 * @param dfsUsed the used space by dfs datanode
200 * @param remaining remaining capacity of the data node
201 * @param bpused space used by the block pool corresponding to this namenode
202 * @param xceiverCount # of data transfers at the data node
203 */
204 public DatanodeDescriptor(DatanodeID nodeID,
205 String networkLocation,
206 String hostName,
207 long capacity,
208 long dfsUsed,
209 long remaining,
210 long bpused,
211 int xceiverCount,
212 int failedVolumes) {
213 super(nodeID, networkLocation, hostName);
214 updateHeartbeat(capacity, dfsUsed, remaining, bpused, xceiverCount,
215 failedVolumes);
216 }
217
218 /**
219 * Add datanode to the block.
220 * Add block to the head of the list of blocks belonging to the data-node.
221 */
222 public boolean addBlock(BlockInfo b) {
223 if(!b.addNode(this))
224 return false;
225 // add to the head of the data-node list
226 blockList = b.listInsert(blockList, this);
227 numBlocks++;
228 return true;
229 }
230
231 /**
232 * Remove block from the list of blocks belonging to the data-node.
233 * Remove datanode from the block.
234 */
235 public boolean removeBlock(BlockInfo b) {
236 blockList = b.listRemove(blockList, this);
237 if ( b.removeNode(this) ) {
238 numBlocks--;
239 return true;
240 } else {
241 return false;
242 }
243 }
244
245 /**
246 * Move block to the head of the list of blocks belonging to the data-node.
247 */
248 void moveBlockToHead(BlockInfo b) {
249 blockList = b.listRemove(blockList, this);
250 blockList = b.listInsert(blockList, this);
251 }
252
253 /**
254 * Replace specified old block with a new one in the DataNodeDescriptor.
255 *
256 * @param oldBlock - block to be replaced
257 * @param newBlock - a replacement block
258 * @return the new block
259 */
260 public BlockInfo replaceBlock(BlockInfo oldBlock, BlockInfo newBlock) {
261 boolean done = removeBlock(oldBlock);
262 assert done : "Old block should belong to the data-node when replacing";
263 done = addBlock(newBlock);
264 assert done : "New block should not belong to the data-node when replacing";
265 return newBlock;
266 }
267
268 public void resetBlocks() {
269 this.capacity = 0;
270 this.remaining = 0;
271 this.blockPoolUsed = 0;
272 this.dfsUsed = 0;
273 this.xceiverCount = 0;
274 this.blockList = null;
275 this.invalidateBlocks.clear();
276 this.volumeFailures = 0;
277 }
278
279 public int numBlocks() {
280 return numBlocks;
281 }
282
283 /**
284 * Updates stats from datanode heartbeat.
285 */
286 public void updateHeartbeat(long capacity, long dfsUsed, long remaining,
287 long blockPoolUsed, int xceiverCount, int volFailures) {
288 this.capacity = capacity;
289 this.dfsUsed = dfsUsed;
290 this.remaining = remaining;
291 this.blockPoolUsed = blockPoolUsed;
292 this.lastUpdate = System.currentTimeMillis();
293 this.xceiverCount = xceiverCount;
294 this.volumeFailures = volFailures;
295 rollBlocksScheduled(lastUpdate);
296 }
297
298 /**
299 * Iterates over the list of blocks belonging to the datanode.
300 */
301 public static class BlockIterator implements Iterator<BlockInfo> {
302 private BlockInfo current;
303 private DatanodeDescriptor node;
304
305 BlockIterator(BlockInfo head, DatanodeDescriptor dn) {
306 this.current = head;
307 this.node = dn;
308 }
309
310 public boolean hasNext() {
311 return current != null;
312 }
313
314 public BlockInfo next() {
315 BlockInfo res = current;
316 current = current.getNext(current.findDatanode(node));
317 return res;
318 }
319
320 public void remove() {
321 throw new UnsupportedOperationException("Sorry. can't remove.");
322 }
323 }
324
325 public Iterator<BlockInfo> getBlockIterator() {
326 return new BlockIterator(this.blockList, this);
327 }
328
329 /**
330 * Store block replication work.
331 */
332 void addBlockToBeReplicated(Block block, DatanodeDescriptor[] targets) {
333 assert(block != null && targets != null && targets.length > 0);
334 replicateBlocks.offer(new BlockTargetPair(block, targets));
335 }
336
337 /**
338 * Store block recovery work.
339 */
340 void addBlockToBeRecovered(BlockInfoUnderConstruction block) {
341 if(recoverBlocks.contains(block)) {
342 // this prevents adding the same block twice to the recovery queue
343 BlockManager.LOG.info("Block " + block +
344 " is already in the recovery queue.");
345 return;
346 }
347 recoverBlocks.offer(block);
348 }
349
350 /**
351 * Store block invalidation work.
352 */
353 void addBlocksToBeInvalidated(List<Block> blocklist) {
354 assert(blocklist != null && blocklist.size() > 0);
355 synchronized (invalidateBlocks) {
356 for(Block blk : blocklist) {
357 invalidateBlocks.add(blk);
358 }
359 }
360 }
361
362 /**
363 * The number of work items that are pending to be replicated
364 */
365 int getNumberOfBlocksToBeReplicated() {
366 return replicateBlocks.size();
367 }
368
369 /**
370 * The number of block invalidation items that are pending to
371 * be sent to the datanode
372 */
373 int getNumberOfBlocksToBeInvalidated() {
374 synchronized (invalidateBlocks) {
375 return invalidateBlocks.size();
376 }
377 }
378
379 public List<BlockTargetPair> getReplicationCommand(int maxTransfers) {
380 return replicateBlocks.poll(maxTransfers);
381 }
382
383 public BlockInfoUnderConstruction[] getLeaseRecoveryCommand(int maxTransfers) {
384 List<BlockInfoUnderConstruction> blocks = recoverBlocks.poll(maxTransfers);
385 if(blocks == null)
386 return null;
387 return blocks.toArray(new BlockInfoUnderConstruction[blocks.size()]);
388 }
389
390 /**
391 * Remove the specified number of blocks to be invalidated
392 */
393 public Block[] getInvalidateBlocks(int maxblocks) {
394 return getBlockArray(invalidateBlocks, maxblocks);
395 }
396
397 static private Block[] getBlockArray(Collection<Block> blocks, int max) {
398 Block[] blockarray = null;
399 synchronized(blocks) {
400 int available = blocks.size();
401 int n = available;
402 if (max > 0 && n > 0) {
403 if (max < n) {
404 n = max;
405 }
406 // allocate the properly sized block array ...
407 blockarray = new Block[n];
408
409 // iterate tree collecting n blocks...
410 Iterator<Block> e = blocks.iterator();
411 int blockCount = 0;
412
413 while (blockCount < n && e.hasNext()) {
414 // insert into array ...
415 blockarray[blockCount++] = e.next();
416
417 // remove from tree via iterator, if we are removing
418 // less than total available blocks
419 if (n < available){
420 e.remove();
421 }
422 }
423 assert(blockarray.length == n);
424
425 // now if the number of blocks removed equals available blocks,
426 // them remove all blocks in one fell swoop via clear
427 if (n == available) {
428 blocks.clear();
429 }
430 }
431 }
432 return blockarray;
433 }
434
435 /** Serialization for FSEditLog */
436 public void readFieldsFromFSEditLog(DataInput in) throws IOException {
437 this.name = DeprecatedUTF8.readString(in);
438 this.storageID = DeprecatedUTF8.readString(in);
439 this.infoPort = in.readShort() & 0x0000ffff;
440
441 this.capacity = in.readLong();
442 this.dfsUsed = in.readLong();
443 this.remaining = in.readLong();
444 this.blockPoolUsed = in.readLong();
445 this.lastUpdate = in.readLong();
446 this.xceiverCount = in.readInt();
447 this.location = Text.readString(in);
448 this.hostName = Text.readString(in);
449 setAdminState(WritableUtils.readEnum(in, AdminStates.class));
450 }
451
452 /**
453 * @return Approximate number of blocks currently scheduled to be written
454 * to this datanode.
455 */
456 public int getBlocksScheduled() {
457 return currApproxBlocksScheduled + prevApproxBlocksScheduled;
458 }
459
460 /**
461 * Increments counter for number of blocks scheduled.
462 */
463 public void incBlocksScheduled() {
464 currApproxBlocksScheduled++;
465 }
466
467 /**
468 * Decrements counter for number of blocks scheduled.
469 */
470 void decBlocksScheduled() {
471 if (prevApproxBlocksScheduled > 0) {
472 prevApproxBlocksScheduled--;
473 } else if (currApproxBlocksScheduled > 0) {
474 currApproxBlocksScheduled--;
475 }
476 // its ok if both counters are zero.
477 }
478
479 /**
480 * Adjusts curr and prev number of blocks scheduled every few minutes.
481 */
482 private void rollBlocksScheduled(long now) {
483 if ((now - lastBlocksScheduledRollTime) >
484 BLOCKS_SCHEDULED_ROLL_INTERVAL) {
485 prevApproxBlocksScheduled = currApproxBlocksScheduled;
486 currApproxBlocksScheduled = 0;
487 lastBlocksScheduledRollTime = now;
488 }
489 }
490
491 @Override
492 public int hashCode() {
493 // Super implementation is sufficient
494 return super.hashCode();
495 }
496
497 @Override
498 public boolean equals(Object obj) {
499 // Sufficient to use super equality as datanodes are uniquely identified
500 // by DatanodeID
501 return (this == obj) || super.equals(obj);
502 }
503
504 /** Decommissioning status */
505 public class DecommissioningStatus {
506 private int underReplicatedBlocks;
507 private int decommissionOnlyReplicas;
508 private int underReplicatedInOpenFiles;
509 private long startTime;
510
511 synchronized void set(int underRep,
512 int onlyRep, int underConstruction) {
513 if (isDecommissionInProgress() == false) {
514 return;
515 }
516 underReplicatedBlocks = underRep;
517 decommissionOnlyReplicas = onlyRep;
518 underReplicatedInOpenFiles = underConstruction;
519 }
520
521 /** @return the number of under-replicated blocks */
522 public synchronized int getUnderReplicatedBlocks() {
523 if (isDecommissionInProgress() == false) {
524 return 0;
525 }
526 return underReplicatedBlocks;
527 }
528 /** @return the number of decommission-only replicas */
529 public synchronized int getDecommissionOnlyReplicas() {
530 if (isDecommissionInProgress() == false) {
531 return 0;
532 }
533 return decommissionOnlyReplicas;
534 }
535 /** @return the number of under-replicated blocks in open files */
536 public synchronized int getUnderReplicatedInOpenFiles() {
537 if (isDecommissionInProgress() == false) {
538 return 0;
539 }
540 return underReplicatedInOpenFiles;
541 }
542 /** Set start time */
543 public synchronized void setStartTime(long time) {
544 startTime = time;
545 }
546 /** @return start time */
547 public synchronized long getStartTime() {
548 if (isDecommissionInProgress() == false) {
549 return 0;
550 }
551 return startTime;
552 }
553 } // End of class DecommissioningStatus
554
555 /**
556 * Set the flag to indicate if this datanode is disallowed from communicating
557 * with the namenode.
558 */
559 public void setDisallowed(boolean flag) {
560 disallowed = flag;
561 }
562 /** Is the datanode disallowed from communicating with the namenode? */
563 public boolean isDisallowed() {
564 return disallowed;
565 }
566
567 /**
568 * @return number of failed volumes in the datanode.
569 */
570 public int getVolumeFailures() {
571 return volumeFailures;
572 }
573
574 /**
575 * @param nodeReg DatanodeID to update registration for.
576 */
577 public void updateRegInfo(DatanodeID nodeReg) {
578 super.updateRegInfo(nodeReg);
579 }
580
581 /**
582 * @return Blanacer bandwidth in bytes per second for this datanode.
583 */
584 public long getBalancerBandwidth() {
585 return this.bandwidth;
586 }
587
588 /**
589 * @param bandwidth Blanacer bandwidth in bytes per second for this datanode.
590 */
591 public void setBalancerBandwidth(long bandwidth) {
592 this.bandwidth = bandwidth;
593 }
594
595
596 }