# vim: tabstop=4 shiftwidth=4 softtabstop=4
# coding=utf-8

# Copyright 2012 Hewlett-Packard Development Company, L.P.
# Copyright (c) 2012 NTT DOCOMO, INC.
# 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.

"""
Baremetal IPMI power manager.
"""

import os
import stat
import tempfile

from oslo.config import cfg

from nova import exception
from nova.openstack.common import log as logging
from nova.openstack.common import loopingcall
from nova import paths
from nova import utils
from nova.virt.baremetal import baremetal_states
from nova.virt.baremetal import base
from nova.virt.baremetal import utils as bm_utils

opts = [
    cfg.StrOpt('terminal',
               default='shellinaboxd',
               help='path to baremetal terminal program'),
    cfg.StrOpt('terminal_cert_dir',
               default=None,
               help='path to baremetal terminal SSL cert(PEM)'),
    cfg.StrOpt('terminal_pid_dir',
               default=paths.state_path_def('baremetal/console'),
               help='path to directory stores pidfiles of baremetal_terminal'),
    cfg.IntOpt('ipmi_power_retry',
               default=5,
               help='maximal number of retries for IPMI operations'),
    ]

baremetal_group = cfg.OptGroup(name='baremetal',
                               title='Baremetal Options')

CONF = cfg.CONF
CONF.register_group(baremetal_group)
CONF.register_opts(opts, baremetal_group)

LOG = logging.getLogger(__name__)


def _make_password_file(password):
    fd, path = tempfile.mkstemp()
    os.fchmod(fd, stat.S_IRUSR | stat.S_IWUSR)
    with os.fdopen(fd, "w") as f:
        f.write(password)
    return path


def _get_console_pid_path(node_id):
    name = "%s.pid" % node_id
    path = os.path.join(CONF.baremetal.terminal_pid_dir, name)
    return path


def _get_console_pid(node_id):
    pid_path = _get_console_pid_path(node_id)
    if os.path.exists(pid_path):
        with open(pid_path, 'r') as f:
            pid_str = f.read()
        try:
            return int(pid_str)
        except ValueError:
            LOG.warn(_("pid file %s does not contain any pid"), pid_path)
    return None


class IPMI(base.PowerManager):
    """IPMI Power Driver for Baremetal Nova Compute

    This PowerManager class provides mechanism for controlling the power state
    of physical hardware via IPMI calls. It also provides serial console access
    where available.

    """

    def __init__(self, node, **kwargs):
        self.state = None
        self.retries = None
        self.node_id = node['id']
        self.address = node['pm_address']
        self.user = node['pm_user']
        self.password = node['pm_password']
        self.port = node['terminal_port']

        if self.node_id == None:
            raise exception.InvalidParameterValue(_("Node id not supplied "
                "to IPMI"))
        if self.address == None:
            raise exception.InvalidParameterValue(_("Address not supplied "
                "to IPMI"))
        if self.user == None:
            raise exception.InvalidParameterValue(_("User not supplied "
                "to IPMI"))
        if self.password == None:
            raise exception.InvalidParameterValue(_("Password not supplied "
                "to IPMI"))

    def _exec_ipmitool(self, command):
        args = ['ipmitool',
                '-I',
                'lanplus',
                '-H',
                self.address,
                '-U',
                self.user,
                '-f']
        pwfile = _make_password_file(self.password)
        try:
            args.append(pwfile)
            args.extend(command.split(" "))
            out, err = utils.execute(*args, attempts=3)
            LOG.debug(_("ipmitool stdout: '%(out)s', stderr: '%(err)s'"),
                      {'out': out, 'err': err})
            return out, err
        finally:
            bm_utils.unlink_without_raise(pwfile)

    def _power_on(self):
        """Turn the power to this node ON."""

        def _wait_for_power_on():
            """Called at an interval until the node's power is on."""

            if self.is_power_on():
                self.state = baremetal_states.ACTIVE
                raise loopingcall.LoopingCallDone()
            if self.retries > CONF.baremetal.ipmi_power_retry:
                self.state = baremetal_states.ERROR
                raise loopingcall.LoopingCallDone()
            try:
                self.retries += 1
                self._exec_ipmitool("power on")
            except Exception:
                LOG.exception(_("IPMI power on failed"))

        self.retries = 0
        timer = loopingcall.FixedIntervalLoopingCall(_wait_for_power_on)
        timer.start(interval=0.5).wait()

    def _power_off(self):
        """Turn the power to this node OFF."""

        def _wait_for_power_off():
            """Called at an interval until the node's power is off."""

            if self.is_power_on() is False:
                self.state = baremetal_states.DELETED
                raise loopingcall.LoopingCallDone()
            if self.retries > CONF.baremetal.ipmi_power_retry:
                self.state = baremetal_states.ERROR
                raise loopingcall.LoopingCallDone()
            try:
                self.retries += 1
                self._exec_ipmitool("power off")
            except Exception:
                LOG.exception(_("IPMI power off failed"))

        self.retries = 0
        timer = loopingcall.FixedIntervalLoopingCall(_wait_for_power_off)
        timer.start(interval=0.5).wait()

    def _set_pxe_for_next_boot(self):
        try: