# -*- coding:utf-8 -*-
import os
import stat
from utils.common.fic_base import StepBaseInterface
from utils.common.message import Message
import utils.common.log as logger
from utils.common.exception import FCUException
from plugins.eBackup.common.eBackupUpgrade import EbackupUpgrader
from plugins.eBackup.common.util import Utils


class DatamoverUpgrade(StepBaseInterface):
    def __init__(self, project_id, pod_id, regionid_list=None):
        super(DatamoverUpgrade, self).__init__(project_id, pod_id,
                                               regionid_list)
        self.project_id = project_id
        self.pod_id = pod_id
        self.regionid_list = regionid_list
        self.__db_param_dict = Utils.init_system_params(project_id,
                                                        regionid_list[0])
        self.result_file = os.path.realpath(
            __file__ + '/../%s_datamover_upgrade_result.txt' %
            str(regionid_list[0]))

    def execute(self, project_id, pod_id, regionid_list=None):
        try:
            host_info = self.__db_param_dict["eBackup_Datamover_nodes"]
            host_info = host_info.replace(" ", "").split("|")

            all_result = []
            flags = os.O_WRONLY | os.O_CREAT
            modes = stat.S_IWUSR | stat.S_IRUSR
            with os.fdopen(os.open(self.result_file, flags, modes), 'w') as fp:
                fp.truncate()

            logger.info("Begin to upgrade all datamover nodes(%s)" %
                        str(host_info))
            for group in host_info:
                host_ips = group.split(";")
                logger.info("Begin to upgrade datamover nodes(%s)" %
                            str(host_ips))
                ebackup_upgrade = EbackupUpgrader(host_ips,
                                                  self.__db_param_dict,
                                                  "datamover")
                is_true = ebackup_upgrade.upgrade()
                if is_true:
                    logger.info("Upgrade eBackup datamover(%s) successfully." %
                                str(host_ips))
                else:
                    logger.error("Fail to upgrade eBackup datamover(%s)." %
                                 str(host_ips))
                    with open(self.result_file, mode='a') as fp:
                        fp.write(','.join(host_ips) + '\n')
                all_result.append(is_true)

            if False in all_result:
                logger.error("Fail to upgrade all eBackup datamover nodes.")
                return Message(500, error_msg_cn="升级Datamover失败，"
                                                 "请登录DMK查看失败原因，并重试",
                               error_msg_en="Upgrade Datamover failed, please "
                                            "log in DMK to see the details, "
                                            "and try again.")

            logger.info("Upgrade all eBackup datamover successfully.")
            if os.path.exists(self.result_file):
                os.remove(self.result_file)
            return Message(200)

        except Exception as ex:
            logger.error(str(ex))
            return Message(500,
                           error_msg_cn="升级Datamover出现异常,"
                                        "请查看升级日志并重试，"
                                        "异常信息：%s" % str(ex),
                           error_msg_en="Exception occurs when upgrade "
                                        "Datamover,please see log and try "
                                        "again, error info:%s" % str(ex))

    def rollback(self, project_id, pod_id, regionid_list=None):
        return Message(200)

    def retry(self, project_id, pod_id, regionid_list=None):
        try:
            if not os.path.exists(self.result_file):
                logger.error("There is no result file:" + self.result_file)
                raise FCUException(
                    650032, self.result_file + " does not exist",
                    self.result_file)

            with open(self.result_file, mode='r') as fp:
                host_group_list = fp.readlines()

            if 0 == len(host_group_list):
                logger.error(
                    "Get ips from %s failed." % self.result_file)
                raise FCUException(
                    650032,
                    "There is no IP address of the node which need to"
                    " be retried in " + self.result_file,
                    self.result_file)

            for group in host_group_list:
                if 0 == len(group.replace('\n', '')):
                    logger.info("There is no host.")
                    continue
                host_ips = group.replace('\n', '').split(",")

                ebackup_upgrade = EbackupUpgrader(host_ips,
                                                  self.__db_param_dict,
                                                  "datamover")
                is_true = ebackup_upgrade.rollback_force()
                if not is_true:
                    logger.error("Rollback %s failed." % str(group))
                    return Message(500, error_msg_cn="回退Datamover[%s]失败，"
                                                     "请联系技术支持" %
                                                     str(group),
                                   error_msg_en="Rollback eBackup Datamover"
                                                "[%s]failed,please contact "
                                                "support engineers." %
                                                str(group))

            return self.execute(project_id, pod_id,
                                regionid_list)
        except FCUException as ex:
            logger.error("Exception occurs when retry to "
                         "upgrade eBackup: " + str(ex))
            return Message(500, ex)
        except Exception as e:
            logger.error(
                "Exception occurs when retry to upgrade eBackup: " + str(e))
            return Message(500,
                           error_msg_cn="重试出现异常，请联系技术支持，异常信息:"
                                        "%s" % str(e),
                           error_msg_en="Exception occurs when retry to "
                                        "upgrade eBackup,please contact  "
                                        "support engineers, error info：%s" %
                                        str(e))
