# -*- coding: utf-8 -*-
import requests

from odoo import models, fields, api, exceptions


class DeployNode(models.Model):
    _name = 'ex.dev.tool.deploy.node'
    _description = u'部署节点'

    ip = fields.Char(u'ip地址', required=True)
    port = fields.Integer(u'端口', required=True)
    log_file = fields.Char(u'日志文件', required=True)

    @api.multi
    def restart(self):
        # odoo.service.server.restart()
        msg = []
        for item in self:
            url = 'http://%s:%d/ex/tool/hotfix/restart' % (item.ip, item.port)
            resp = requests.post(url)
            if (resp.status_code == 200 and resp.content == 'ok') or resp.status_code == 204:
                pass
            else:
                err = '%(ip)s:%(port)d, resp code:%(code)d,resp msg:%(msg)s' % {
                    'ip': item.ip,
                    'port': item.port,
                    'code': resp.status_code,
                    'msg': resp.content
                }
                msg.append(err)

        if msg:
            raise exceptions.ValidationError(msg)

    def ping(self):
        for item in self:
            url = 'http://%s:%d/ex/tool/hotfix/ping' % (item.ip, item.port)
            requests.post(url)
