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.datanode.fsdataset;
019
020import java.io.IOException;
021import java.util.List;
022
023import org.apache.commons.logging.Log;
024import org.apache.commons.logging.LogFactory;
025import org.apache.hadoop.util.DiskChecker.DiskOutOfSpaceException;
026
027/**
028 * Choose volumes in round-robin order.
029 */
030public class RoundRobinVolumeChoosingPolicy<V extends FsVolumeSpi>
031    implements VolumeChoosingPolicy<V> {
032  public static final Log LOG = LogFactory.getLog(RoundRobinVolumeChoosingPolicy.class);
033
034  private int curVolume = 0;
035
036  @Override
037  public synchronized V chooseVolume(final List<V> volumes, long blockSize)
038      throws IOException {
039
040    if(volumes.size() < 1) {
041      throw new DiskOutOfSpaceException("No more available volumes");
042    }
043    
044    // since volumes could've been removed because of the failure
045    // make sure we are not out of bounds
046    if(curVolume >= volumes.size()) {
047      curVolume = 0;
048    }
049    
050    int startVolume = curVolume;
051    long maxAvailable = 0;
052    
053    while (true) {
054      final V volume = volumes.get(curVolume);
055      curVolume = (curVolume + 1) % volumes.size();
056      long availableVolumeSize = volume.getAvailable();
057      if (availableVolumeSize > blockSize) {
058        return volume;
059      }
060      
061      if (availableVolumeSize > maxAvailable) {
062        maxAvailable = availableVolumeSize;
063      }
064      
065      if (curVolume == startVolume) {
066        throw new DiskOutOfSpaceException("Out of space: "
067            + "The volume with the most available space (=" + maxAvailable
068            + " B) is less than the block size (=" + blockSize + " B).");
069      }
070    }
071  }
072}