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