# Copyright (c) 2011 OpenStack Foundation
# All Rights Reserved.
#
#    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.

import testtools
import webob.exc

from nova.api.openstack.compute import hosts as os_hosts_v21
from nova.compute import power_state
from nova.compute import vm_states
from nova import context as context_maker
from nova import db
from nova import exception
from nova import test
from nova.tests.unit.api.openstack import fakes
from nova.tests.unit import fake_hosts
from nova.tests import uuidsentinel


def stub_service_get_all(context, disabled=None):
    return fake_hosts.SERVICES_LIST


def stub_service_get_by_host_and_binary(context, host_name, binary):
    for service in stub_service_get_all(context):
        if service['host'] == host_name and service['binary'] == binary:
            return service


def stub_set_host_enabled(context, host_name, enabled):
    """Simulates three possible behaviours for VM drivers or compute
    drivers when enabling or disabling a host.

    'enabled' means new instances can go to this host
    'disabled' means they can't
    """
    results = {True: "enabled", False: "disabled"}
    if host_name == "notimplemented":
        # The vm driver for this host doesn't support this feature
        raise NotImplementedError()
    elif host_name == "dummydest":
        # The host does not exist
        raise exception.ComputeHostNotFound(host=host_name)
    elif host_name == "service_not_available":
        # The service is not available
        raise exception.ComputeServiceUnavailable(host=host_name)
    elif host_name == "host_c2":
        # Simulate a failure
        return results[not enabled]
    else:
        # Do the right thing
        return results[enabled]


def stub_set_host_maintenance(context, host_name, mode):
    # We'll simulate success and failure by assuming
    # that 'host_c1' always succeeds, and 'host_c2'
    # always fails
    results = {True: "on_maintenance", False: "off_maintenance"}
    if host_name == "notimplemented":
        # The vm driver for this host doesn't support this feature
        raise NotImplementedError()
    elif host_name == "dummydest":
        # The host does not exist
        raise exception.ComputeHostNotFound(host=host_name)
    elif host_name == "service_not_available":
        # The service is not available
        raise exception.ComputeServiceUnavailable(host=host_name)
    elif host_name == "host_c2":
        # Simulate a failure
        return results[not mode]
    else:
        # Do the right thing
        return results[mode]


def stub_host_power_action(context, host_name, action):
    if host_name == "notimplemented":
        raise NotImplementedError()
    elif host_name == "dummydest":
        # The host does not exist
        raise exception.ComputeHostNotFound(host=host_name)
    elif host_name == "service_not_available":
        # The service is not available
        raise exception.ComputeServiceUnavailable(host=host_name)
    return action


def _create_instance(**kwargs):
    """Create a test instance."""
    ctxt = context_maker.get_admin_context()
    return db.instance_create(ctxt, _create_instance_dict(**kwargs))


def _create_instance_dict(**kwargs):
    """Create a dictionary for a test instance."""
    inst = {}
    inst['image_ref'] = 'cedef40a-ed67-4d10-800e-17455edce175'
    inst['reservation_id'] = 'r-fakeres'
    inst['user_id'] = kwargs.get('user_id', 'admin')
    inst['project_id'] = kwargs.get('project_id', 'fake')
    inst['instance_type_id'] = '1'
    if 'host' in kwargs:
        inst['host'] = kwargs.get('host')
    inst['vcpus'] = kwargs.get('vcpus', 1)
    inst['memory_mb'] = kwargs.get('memory_mb', 20)
    inst['root_gb'] = kwargs.get('root_gb', 30)
    inst['ephemeral_gb'] = kwargs.get('ephemeral_gb', 30)
    inst['vm_state'] = kwargs.get('vm_state', vm_states.ACTIVE)
    inst['power_state'] = kwargs.get('power_state', power_state.RUNNING)
    inst['task_state'] = kwargs.get('task_state', None)
    inst['availability_zone'] = kwargs.get('availability_zone', None)
    inst['ami_launch_index'] = 0
    inst['launched_on'] = kwargs.get('launched_on', 'dummy')
    return inst


class FakeRequestWithNovaZone(object):
    environ = {"nova.context": context_maker.get_admin_context()}
    GET = {"zone": "nova"}


class HostTestCaseV21(test.TestCase):
    """Test Case for hosts."""
    validation_ex = exception.ValidationError
    Controller = os_hosts_v21.HostController
    policy_ex = exception.PolicyNotAuthorized

    def _setup_stubs(self):
        # Pretend we have fake_hosts.HOST_LIST in the DB
        self.stub_out('nova.db.service_get_all',
                      stub_service_get_all)
        # Only hosts in our fake DB exist
        self.stub_out('nova.db.service_get_by_host_and_binary',
                      stub_service_get_by_host_and_binary)
        # 'host_c1' always succeeds, and 'host_c2'
        self.stubs.Set(self.hosts_api, 'set_host_enabled',
                       stub_set_host_enabled)
        # 'host_c1' always succeeds, and 'host_c2'
        self.stubs.Set(self.hosts_api, 'set_host_maintenance',
                       stub_set_host_maintenance)
        self.stubs.Set(self.hosts_api, 'host_power_action',
                       stub_host_power_action)

    def setUp(self):
        super(HostTestCaseV21, self).setUp()
        self.controller = self.Controller()
        self.hosts_api = self.controller.api
        self.req = fakes.HTTPRequest.blank('', use_admin_context=True)

        self._setup_stubs()

    def _test_host_update(self, host, key, val, expected_value):
        body = {key: val}
        result = self.controller.update(self.req, host, body=body)
        self.assertEqual(result[key], expected_value)

    def test_list_hosts(self):
        """Verify that the compute hosts are returned."""
        result = self.controller.index(self.req)
        self.assertIn('hosts', result)
        hosts = result['hosts']
        self.assertEqual(fake_hosts.HOST_LIST, hosts)

    def test_disable_host(self):
        self._test_host_update('host_c1', 'status', 'disable', 'disabled')
        self._test_host_update('host_c2', 'status', 'disable', 'enabled')

    def test_enable_host(self):
        self._test_host_update('host_c1', 'status', 'enable', 'enabled')
        self._test_host_update('host_c2', 'status', 'enable', 'disabled')

    def test_enable_maintenance(self):
        self._test_host_update('host_c1', 'maintenance_mode',
                               'enable', 'on_maintenance')

    def test_disable_maintenance(self):
        self._test_host_update('host_c1', 'maintenance_mode',
                               'disable', 'off_maintenance')