# Copyright (C) 2012-2013 Red Hat, Inc.
#
#    Licensed under the Apache License, Version 2.0 (the "License"); you may
#    not use this file except in compliance with the License. You may obtain
#    a copy of the License at
#
#         http://www.apache.org/licenses/LICENSE-2.0
#
#    Unless required by applicable law or agreed to in writing, software
#    distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
#    WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
#    License for the specific language governing permissions and limitations
#    under the License.

"""
Handling of block device information and mapping.

This module contains helper methods for interpreting the block
device information and determining the suitable mapping to
guest devices and libvirt XML.

Throughout these methods there are a number of standard
variables / types used

 * 'mapping': a dict contains the storage device mapping.

   For the default disk types it will contain the following
   keys & values:

      'disk' -> disk_info
      'disk.rescue' -> disk_info
      'disk.local' -> disk_info
      'disk.swap' -> disk_info
      'disk.config' -> disk_info

   If any of the default disks are overridden by the block
   device info mappings, the hash value will be None

   For any ephemeral device there will also be a dict entry

      'disk.eph$NUM' -> disk_info

   For any volume device there will also be a dict entry:

       $path -> disk_info

   Finally a special key will refer to the root device:

      'root' -> disk_info


 * 'disk_info': a tuple specifying disk configuration

   It contains the following 3 fields

      (disk bus, disk dev, device type)

   and possibly these optional fields: ('format',)

 * 'disk_bus': the guest bus type ('ide', 'virtio', 'scsi', etc)

 * 'disk_dev': the device name 'vda', 'hdc', 'sdf', 'xvde' etc

 * 'device_type': type of device eg 'disk', 'cdrom', 'floppy'

 * 'format': Which format to apply to the device if applicable

 * 'boot_index': Number designating the boot order of the device

"""

import itertools
import operator

from oslo.config import cfg

from nova import block_device
from nova.compute import arch
from nova import exception
from nova.i18n import _
from nova.objects import base as obj_base
from nova.virt import block_device as driver_block_device
from nova.virt import configdrive
from nova.virt import driver
from nova.virt.libvirt import utils as libvirt_utils

CONF = cfg.CONF


SUPPORTED_DEVICE_TYPES = ('disk', 'cdrom', 'floppy', 'lun')
BOOT_DEV_FOR_TYPE = {'disk': 'hd', 'cdrom': 'cdrom', 'floppy': 'fd'}


def has_disk_dev(mapping, disk_dev):
    """Determine if a disk device name has already been used.

       Looks at all the keys in mapping to see if any
       corresponding disk_info tuple has a device name
       matching disk_dev

       Returns True if the disk_dev is in use.
    """

    for disk in mapping:
        info = mapping[disk]
        if info['dev'] == disk_dev:
            return True
    return False


def get_dev_prefix_for_disk_bus(disk_bus):
    """Determine the dev prefix for a disk bus.

       Determine the dev prefix to be combined
       with a disk number to fix a disk_dev.
       eg 'hd' for 'ide' bus can be used to
       form a disk dev 'hda'

       Returns the dev prefix or raises an
       exception if the disk bus is unknown.
    """

    if CONF.libvirt.disk_prefix:
        return CONF.libvirt.disk_prefix
    if disk_bus == "ide":
        return "hd"
    elif disk_bus == "virtio":
        return "vd"
    elif disk_bus == "xen":
        # Two possible mappings for Xen, xvda or sda
        # which are interchangeable, so we pick sda
        return "sd"
    elif disk_bus == "scsi":
        return "sd"
    elif disk_bus == "usb":
        return "sd"
    elif disk_bus == "fdc":
        return "fd"
    elif disk_bus == "uml":
        return "ubd"
    elif disk_bus == "lxc":
        return None
    else:
        raise exception.NovaException(
            _("Unable to determine disk prefix for %s") %
            disk_bus)


def get_dev_count_for_disk_bus(disk_bus):
    """Determine the number disks supported.

       Determine how many disks can be supported in
       a single VM for a particular disk bus.

       Returns the number of disks supported.
    """

    if disk_bus == "ide":
        return 4
    else:
        return 26


def find_disk_dev_for_disk_bus(mapping, bus, last_device=False):
    """Identify a free disk dev name for a bus.

       Determines the possible disk dev names for
       the bus, and then checks them in order until
       it identifies one that is not yet used in the
       disk mapping. If 'last_device' is set, it will
       only consider the last available disk dev name.

       Returns the chosen disk_dev name, or raises an
       exception if none is available.
    """

    dev_prefix = get_dev_prefix_for_disk_bus(bus)
    if dev_prefix is None:
        return None

    max_dev = get_dev_count_for_disk_bus(bus)
    if last_device:
        devs = [max_dev - 1]
    else:
        devs = range(max_dev)

    for idx in devs:
        disk_dev = dev_prefix + chr(ord('a') + idx)
        if not has_disk_dev(mapping, disk_dev):
            return disk_dev

    raise exception.NovaException(
        _("No free disk device names for prefix '%s'"),
        dev_prefix)


def is_disk_bus_valid_for_virt(virt_type, disk_bus):
    valid_bus = {
        'qemu': ['virtio', 'scsi', 'ide', 'usb', 'fdc'],
        'kvm': ['virtio', 'scsi', 'ide', 'usb', 'fdc'],
        'xen': ['xen', 'ide'],
        'uml': ['uml'],
        'lxc': ['lxc'],
        }

    if virt_type not in valid_bus:
        raise exception.UnsupportedVirtType(virt=virt_type)

    return disk_bus in valid_bus[virt_type]


def get_disk_bus_for_device_type(virt_type,
                                 image_meta=None,
                                 device_type="disk"):
    """Determine the best disk bus to use for a device type.

       Considering the currently configured virtualization