Example #1
0
 def init_for_main_tcp(self, *args, **keys):
     try:
         queue = config.MAIN_TCP_SERVER_QUEUE_NAME + '_' + str(
             config.MAIN_TCP_SERVER_NAME)
         client = yield self.connect()
         channel = yield self.open_channel(client)
         yield self._init_worker(channel)
         yield channel.queue_declare(queue=queue, *args, **keys)
         yield channel.exchange_declare(
             exchange=config.MAIN_TCP_SERVER_EXCHANGE_NAME,
             type="direct",
             durable=True)
         yield channel.exchange_declare(
             exchange=config.EXCHANGE_NAME_WORKER,
             type="direct",
             durable=True)
         yield channel.queue_bind(0, queue,
                                  config.MAIN_TCP_SERVER_EXCHANGE_NAME,
                                  queue)
         reply = yield channel.basic_consume(queue=queue, no_ack=True)
         queue = yield client.queue(reply.consumer_tag)
         logging.info('init for hub mq finish')
         while True:
             data = yield queue.get()
             msg = json_helper.loads(data.content.body)
             print msg
             #处理消息
             # SessionManager.handler_data_from_mq(msg)
     except:
         logging.error(traceback.format_exc())
Example #2
0
def flush_host_perform_data_to_db():
    """
        提交数据并写入数据库,返回插入数据状态
        :return
        {
          "code": 0,
          "data": {
            "operate_return": "success",
            "record_num": 11,
            "record_success_insert_num": 11
          },
          "msg": "success"
        }
    """

    datadict = request.data
    datadict = json_helper.loads(datadict)  #数据可能有多条
    datadict = datadict['params']

    datadict = datadict['params']
    print datadict
    ndatalist = []  # 存放多条数据的列表
    ndatadict = {}  # 临时存储每一条数据【字典】
    for metric_key, info in datadict.items():
        ndatadict['metric_key'] = metric_key
        for key, value in info.items():
            ndatadict[key] = value
        ndatalist.append(ndatadict)
        ndatadict = {}
    result = hms.HostMetricService().push_data_to_db(metricinfo_list=ndatalist)

    print "result=", result
    r = host_metric_list.host_metric_apiresp(result)
    return r
Example #3
0
    def dispatch_request(self):
        start_time = time.time()
        resp = super(My_Flask, self).dispatch_request()
        cost = time.time() - start_time
        req = _request_ctx_stack.top.request
        ret_data = {}
        try:
            if resp:
                resp_data = resp.data
                if resp.data.startswith("jQuery") or resp.data.startswith(
                        'jsonp'):
                    first = resp_data.find('(')
                    resp_data = resp_data[first + 1:-2]
                ret_data = json_helper.loads(resp_data)
        except:
            errinfo = traceback.format_exc()
            errinfo = 'resp:%s exc:%s' % (resp, errinfo)
            log_helper.log_error(errinfo)
        ret_code = ret_data.get('code')
        if ret_code is not None:
            ret_code = int(ret_code)

        #log 不要打印password
        get_args = dict(req.args.items())
        get_args.pop('password', None)
        post_args = dict(req.form.items())
        post_args.pop('password', None)

        logging.debug("ip:%s path:%s cost:%.3fs  get args:%s post args:%s ret:%s ret_msg:%s",\
                      ip_helper.get_real_ip(req),req.full_path, cost, get_args.items(), post_args.items(), \
                      ret_code, const_define.ErrorMsg.MSG_DICT.get(ret_code))
        return resp
Example #4
0
    def dispatch_request(self):
        start_time = time.time()
        resp = super(My_Flask,self).dispatch_request()
        cost = time.time() - start_time
        req = _request_ctx_stack.top.request
        ret_data = {}
        try:
            if resp:
                resp_data = resp.data
                if resp.data.startswith("jQuery") or resp.data.startswith('jsonp'):
                    first = resp_data.find('(')
                    resp_data = resp_data[first+1:-2]
                ret_data = json_helper.loads(resp_data)
        except:
            errinfo = traceback.format_exc()
            errinfo = 'resp:%s exc:%s'%(resp,errinfo)
            log_helper.log_error( errinfo )
        ret_code = ret_data.get('code')
        if ret_code is not None:
            ret_code = int(ret_code)

        #log 不要打印password
        get_args = dict(req.args.items())
        get_args.pop('password',None)
        post_args = dict(req.form.items())
        post_args.pop('password',None)

        logging.debug("ip:%s path:%s cost:%.3fs  get args:%s post args:%s ret:%s ret_msg:%s",\
                      ip_helper.get_real_ip(req),req.full_path, cost, get_args.items(), post_args.items(), \
                      ret_code, const_define.ErrorMsg.MSG_DICT.get(ret_code))
        return resp
Example #5
0
def simple_post(url, params={}, timeout=5, decode_json_resp=False):
    query = urllib.urlencode(params)
    request = urllib2.Request(url, query)
    data = urllib2.urlopen(request, timeout=timeout).read()
    if decode_json_resp:
        return json_helper.loads(data)
    return data
Example #6
0
    def parse(self, data):
        self.buffer += data
        while True:
            #如果缓冲区数据长度小于包头的长度
            if len(self.buffer) < const_define.TCP_HEADER.HEAD_LEN:
                return (-1, None)
            #继续解析包头
            head_data = tcp_pack_helper.depack_msg(
                self.buffer[:const_define.TCP_HEADER.HEAD_LEN])
            if head_data['magic_num'] != const_define.TCP_HEADER.MAGIC_NUM:
                #没有按照规定的格式传输数据 不是正常的客户端  断开该连接
                self.transport.loseConnection()
                return

            cmd = head_data['cmd']
            #然后解析包体
            body_data = json_helper.loads(
                self.buffer[const_define.TCP_HEADER.
                            HEAD_LEN:const_define.TCP_HEADER.HEAD_LEN +
                            head_data['body_len']])
            #数据已经接收完毕 清空缓冲区
            self.buffer = ''
            return {
                'header': head_data,
                'body': body_data,
            }
Example #7
0
def get_host_perform_data_by_hostip(host_ip=None):
    if request.method == 'POST':
        print 'post=', request
        print request.data
    datadict = json_helper.loads(request.data)
    gethostip = datadict['params']['host_ip']
    needinfo = hms.HostMetricService().get_data_from_db_with_post(gethostip)
    print 'needinfo_byhostip=', needinfo
    r = host_metric_list.host_metric_getapiresp(needinfo)
    return r
Example #8
0
def simple_get(url, params={}, timeout=5, decode_json_resp=False):
    query = urllib.urlencode(params)
    if params:
        request_url = '%s?%s' % (url, query)
    else:
        request_url = url
    request = urllib2.Request(request_url)
    resp_data = urllib2.urlopen(request, timeout=timeout).read()
    if decode_json_resp:
        return json_helper.loads(resp_data)
    return resp_data
Example #9
0
 def init_for_worker(self, worker_queue=config.WORKER_QUEUE_NAME):
     client = yield self.connect()
     channel = yield self.open_channel(client)
     yield self._init_worker(channel)
     reply = yield channel.basic_consume(queue=worker_queue, no_ack=True)
     queue = yield client.queue(reply.consumer_tag)
     while True:
         data = yield queue.get()
         try:
             msg = json_helper.loads(data.content.body)
             print msg
             #这里收到来自mq的消息 后面接着处理
             # session = Session(msg['sid'])
             # green_thread(Worker.dispatch_message)(session, msg)
         except:
             logging.error(traceback.format_exc())
Example #10
0
 def init_for_worker(self, worker_queue=config.WORKER_QUEUE_NAME):
     client = yield self.connect()
     channel = yield self.open_channel(client)
     yield self._init_worker(channel)
     reply = yield channel.basic_consume(queue=worker_queue, no_ack=True)
     queue = yield client.queue(reply.consumer_tag)
     while True:
         data = yield queue.get()
         try:
             msg = json_helper.loads(data.content.body)
             print msg
             #这里收到来自mq的消息 后面接着处理
             # session = Session(msg['sid'])
             # green_thread(Worker.dispatch_message)(session, msg)
         except:
             logging.error(traceback.format_exc())
Example #11
0
def http_post_json(url, req_data=None, header=None):
    code = -1
    error = ''
    data = {}
    req_data = {} if req_data is None else req_data
    header = {} if header is None else header

    request = urllib2.Request(url)
    request.add_header('Content-Type', 'application/json')

    for k, v in header.items():
        request.add_header(k, v)

    try:
        resp = urllib2.urlopen(request, json_helper.dumps(req_data)).read()
        data = json_helper.loads(resp)
    except HTTPError, e:
        code = e.code
        error = e.strerror
Example #12
0
 def init_for_main_tcp(self, *args, **keys):
     try:
         queue = config.MAIN_TCP_SERVER_QUEUE_NAME + '_' + str(config.MAIN_TCP_SERVER_NAME)
         client = yield self.connect()
         channel = yield self.open_channel(client)
         yield self._init_worker(channel)
         yield channel.queue_declare(queue=queue, *args, **keys)
         yield channel.exchange_declare(exchange=config.MAIN_TCP_SERVER_EXCHANGE_NAME, type="direct", durable=True)
         yield channel.exchange_declare(exchange=config.EXCHANGE_NAME_WORKER, type="direct", durable=True)
         yield channel.queue_bind(0, queue, config.MAIN_TCP_SERVER_EXCHANGE_NAME, queue)
         reply = yield channel.basic_consume(queue=queue, no_ack=True)
         queue = yield client.queue(reply.consumer_tag)
         logging.info('init for hub mq finish')
         while True:
             data = yield queue.get()
             msg = json_helper.loads(data.content.body)
             print msg
             #处理消息
             # SessionManager.handler_data_from_mq(msg)
     except:
         logging.error(traceback.format_exc())
Example #13
0
    def parse(self, data):
        self.buffer += data
        while True:
            #如果缓冲区数据长度小于包头的长度
            if len(self.buffer) < const_define.TCP_HEADER.HEAD_LEN:
                return (-1,None)
            #继续解析包头
            head_data = tcp_pack_helper.depack_msg(self.buffer[:const_define.TCP_HEADER.HEAD_LEN])
            if head_data['magic_num'] != const_define.TCP_HEADER.MAGIC_NUM:
                #没有按照规定的格式传输数据 不是正常的客户端  断开该连接
                self.transport.loseConnection()
                return

            cmd = head_data['cmd']
            #然后解析包体
            body_data = json_helper.loads(self.buffer[const_define.TCP_HEADER.HEAD_LEN:const_define.TCP_HEADER.HEAD_LEN+head_data['body_len']])
            #数据已经接收完毕 清空缓冲区
            self.buffer = ''
            return {
                'header':head_data,
                'body' : body_data,
            }
Example #14
0
    def my_after_request(response):
        response.direct_passthrough = False

        log_type = None
        field_data = {}
        # 登录日志
        if request.path.startswith('/login') \
                or request.path.startswith('/logout'):
            log_type = AuditType.LOGIN
            field_data.update({
                'Oper_name':
                'login' if request.path.startswith('/login') else 'logout'
            })

        # 角色/权限管理日志
        elif request.path.startswith(
                '/user_group') and request.method == 'DELETE':
            log_type = AuditType.PERMMGR
            # 被操作的账号
            oper_user_id = request.values.get('user_id')
            oper_user_info = user_s.UserService().get_user_info_by_user_id(
                oper_user_id)
            if oper_user_info:
                oper_user_name = oper_user_info['username']
            else:
                oper_user_name = None

            group_id = request.values.get('group_id')
            field_data.update({
                'User_name':
                oper_user_name,
                'Oper_type':
                'delete',
                'Oper_content_old':
                'user in group id ' + group_id,
                'Oper_content_new':
                'delete user from group id ' + group_id
            })
        elif request.path.startswith('/user_group/insideuser/'):
            log_type = AuditType.PERMMGR

            # 被操作的账号
            oper_user_id = request.values.get('user_id')
            oper_user_info = user_s.UserService().get_user_info_by_user_id(
                oper_user_id)
            if oper_user_info:
                oper_user_name = oper_user_info['username']
            else:
                oper_user_name = None

            group_name = request.values.get('group_name')
            field_data.update({
                'User_name':
                oper_user_name,
                'Oper_type':
                'authorize',
                'Oper_content_old':
                'user not in group ' + group_name,
                'Oper_content_new':
                'add user to group ' + group_name
            })
        elif request.path.startswith('/user_group/otheruser/'):
            log_type = AuditType.PERMMGR
            group_name = request.values.get('group_name')
            field_data.update({
                'User_name':
                request.values.get('user_name'),
                'Oper_type':
                'authorize',
                'Oper_content_old':
                'user not in group ' + group_name,
                'Oper_content_new':
                'add user to group ' + group_name
            })

        try:
            resp_result = json_helper.loads(response.data)
            # 判断请求是否成功
            if resp_result.get('code') == ErrorCode.SUCCESS:
                field_data.update({'Oper_result': '1 Success'})
            else:
                field_data.update({
                    'Oper_result': '0 Fail',
                    'fail_reason': resp_result.get('msg')
                })
        except Exception, e:
            pass
def kvm_common_info():
    def _filter_least_host_num(hostpool_id, least_host_num):
        '''
            过滤掉不满足最少host数的集群
        :param hostpool_id:
        :param least_host_num:
        :return:
        '''
        # 获取主机列表
        all_hosts_nums, all_hosts_data = host_s.HostService(
        ).get_hosts_of_hostpool(hostpool_id)
        if all_hosts_nums < least_host_num or all_hosts_nums < 1:
            logging.info(
                'filter hostpool %s that has no least host nums %s when get create init info',
                hostpool_id, least_host_num)
            return False
        return True

    def _filter_no_segment_info(hostpool_id):
        '''
            过滤掉没有网段信息的集群
        :param hostpool_id:
        :return:
        '''
        segments_list = hostpool_service.get_segment_info(hostpool_id)
        if not segments_list:
            logging.error(
                'filter hostpool %s that has no segment info when get create init info',
                hostpool_id)
            return False
        return True

    data_from_api = request.data
    data_requset = json_helper.loads(data_from_api)
    user_id = data_requset['userId']

    resp = KvmInfoResp()
    user_all_area_ids = user_s.user_all_area_ids_by_userid(user_id)

    # area层级信息 - 总部
    area_zb_data = hostpool_service.get_level_info_hostpool_zb()
    for i in area_zb_data:
        # 不显示不满足最少host数的集群
        if not _filter_least_host_num(i['hostpool_id'], i['least_host_num']):
            continue

        # 不显示没有负载均衡网络的区域
        if "LoadBalance" not in i['net_area_name']:
            continue

        # 不显示没有网段信息的集群
        if not _filter_no_segment_info(i['hostpool_id']):
            continue

        # 只显示当前用户所属的区域
        if user_all_area_ids and i['area_id'] not in user_all_area_ids:
            continue
        resp.area_ZB.append(i)

    # area层级信息 - 地区
    area_dq_data = hostpool_service.get_level_info_hostpool_dq()
    for i in area_dq_data:
        # 不显示不满足最少host数的集群
        if not _filter_least_host_num(i['hostpool_id'], i['least_host_num']):
            continue

        # 不显示没有负载均衡网络的区域
        if "LoadBalance" not in i['net_area_name']:
            continue

        # 不显示没有网段信息的集群
        if not _filter_no_segment_info(i['hostpool_id']):
            continue

        # 只显示当前用户所属的区域
        if user_all_area_ids and i['area_id'] not in user_all_area_ids:
            continue

        _area_dq_info = area_dq_init_info.AreaDQInitInfo().init_from_db(i)
        # 表示有父区域
        if i['parent_id']:
            _parent_info = area_service.AreaService().get_area_info(
                i['parent_id'])
            if _parent_info:
                _area_dq_info.area_name = _parent_info['displayname']
                _area_dq_info.child_area_name = i['area_name']
            else:
                # 有父区域ID但没有相应信息,则当做没有父区域
                _area_dq_info.area_name = i['area_name']
        else:
            _area_dq_info.area_name = i['area_name']
        resp.area_DQ.append(_area_dq_info)

    # group信息
    user_groups = user_s.current_user_groups_by_userid(user_id)
    user_group_ids_list = []
    is_middleware_admin_group = False
    for _groups in user_groups:
        user_group_ids_list.append(_groups['id'])
        # 中间件管理员组,这里后期要注意,如果中间件管理员组id不为2,则识别不出用户是否是中间件管理员组
        if _groups['id'] == 2:
            is_middleware_admin_group = True

    groups_params = {
        'WHERE_AND': {
            '=': {
                'isdeleted': '0'
            }
        },
    }
    groups_nums, groups_data = group_service.GroupService().query_data(
        **groups_params)
    for i in groups_data:
        # 中间件管理员组可以显示所有组,而非管理员组的只显示当前用户所在应用组
        if not is_middleware_admin_group and i['id'] not in user_group_ids_list:
            continue

        _group_info = group_info.GroupInitInfo().init_from_db_1(i)
        resp.groups.append(_group_info)

    return json_helper.format_api_resp(code=ErrorCode.SUCCESS,
                                       data=resp.to_json())
Example #16
0
import datetime
import simplejson as json

import json_helper

class Entity(object):
    def __init__(self):
        super(Entity, self).__init__()
        self.param = 'val'
        self.dt = datetime.datetime.now()
        self.num = 51

    def __str__(self):
        return 'Entity(param=%s,dt=%s,num=%d)' % (self.param, self.dt, self.num)

Entity = json_helper.setup_from_dict(Entity)

TYPES = json_helper.define_json_classes(Entity)

#s = json.dumps(Entity(), cls=CustomTypeEncoder)
o = Entity()
print o
s = json_helper.dumps(o, TYPES)
#s = json.dumps(o, cls=make_encoder(TYPES))
print s
#print json.loads(s, object_hook=make_decoder(TYPES))
print json_helper.loads(s, TYPES)
Example #17
0
def instance_configure(instance_id):
    '''
        虚机修改配置
        规则:
            热修改(开机状态):cpu disk 加
            冷修改(关机状态):cpu mem 加减  disk 加
    :param instance_id:
    :return:
    '''
    n_flavor_id = request.values.get('flavor_id')
    n_app_info = request.values.get('app_info')
    n_owner = request.values.get('owner')
    n_group_id = request.values.get('group_id')
    n_net_conf_list_req = request.values.get('net_status_list')

    # start
    n_extend_list_req = request.values.get('extend_list')
    n_qemu_ga_update_req = request.values.get('qemu_ga_update')
    c_system = ''
    c_version = None
    # end

    if not instance_id or not n_flavor_id or not n_group_id:
        logging.error('params is invalid when change instance configure')
        return json_helper.format_api_resp(code=ErrorCode.PARAM_ERR)

    ins_data = ins_s.InstanceService().get_instance_info(instance_id)

    ###################################add 2017/09/29#############################3
    uuid = ins_data['uuid']
    user_id = get_user()['user_id']
    request_id = ins_s.generate_req_id()

    if not ins_data:
        logging.error('the instance %s is not exist in db when change instance configure', instance_id)
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)
    # --------------------edit 2017/11/13-----------------------
    if ins_data['create_source'] == '0':
        ins_images_data = ins_s.get_images_of_instance(instance_id)

        if ins_images_data:
            c_system = ins_images_data[0]['system']
    else:
        ins_images_data = v2v_ins_s.V2VInstanceService().get_v2v_instance_info(instance_id)
        if ins_images_data:
            c_system = ins_images_data['os_type']

    ins_status = ins_data['status']

    # 获取虚拟机所在物理机信息
    host_data = ins_s.get_host_of_instance(instance_id)
    ins_datacenter_info = ins_s.get_datacenter_of_instance(instance_id)
    if not host_data or not ins_datacenter_info:
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR, msg="无法获取虚拟机所在物理机信息、机房信息")

    ins_data['dc_type'] = ins_datacenter_info['dc_type']

    # 新flavor信息
    n_flavor_data = fla_s.FlavorService().get_flavor_info(n_flavor_id)
    if not n_flavor_data:
        logging.error('flavor %s is invalid in db when change instance configure', n_flavor_id)
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR, msg='新的配置数据有误,无法修改配置')

    # 虚机现有flavor信息
    c_flavor_data = ins_s.get_flavor_of_instance(instance_id)
    if not c_flavor_data:
        logging.error('instance %s flavor is invalid in db when change instance configure', instance_id)
        return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)

    c_group_data = ins_s.get_group_of_instance(instance_id)
    if c_group_data and int(c_group_data['group_id']) != int(n_group_id):
        # 检查新应用组的配额
        is_group_enough, req_msg = _check_change_group_quota(n_group_id, n_flavor_data, c_flavor_data)
        if not is_group_enough:
            logging.error('new group %s quota is not enough to change new flavor', n_group_id)
            return json_helper.format_api_resp(code=ErrorCode.SYS_ERR, msg=req_msg)

    params = {}

    if json_helper.loads(n_extend_list_req):

        # 检查当前应用组的配额
        is_group_enough, req_msg = _check_change_group_quota(n_group_id, n_flavor_data, c_flavor_data,
                                                             json_helper.loads(n_extend_list_req))
        if not is_group_enough:
            logging.error('new group %s quota is not enough to change new flavor', n_group_id)
            return json_helper.format_api_resp(code=ErrorCode.SYS_ERR, msg=req_msg)

        # 检查物理机当前使用率情况是否满足扩容
        is_host_available, ret_msg = __check_host_capacity(host_data, n_flavor_data, c_flavor_data
                                                           , json_helper.loads(n_extend_list_req))
        if not is_host_available:
            return json_helper.format_api_resp(code=ErrorCode.SYS_ERR, msg=ret_msg)

        vmname = ins_data['name']
        uuid = ''
        host_ip = ''
        n_extend_list_req = json_helper.loads(n_extend_list_req)
        try:
            uuid = ins_data['uuid']
            host_ip = ins_s.get_hostip_of_instance(instance_id)
        except:
            pass

        connect_instance = vmManager.libvirt_get_connect(host_ip, conn_type='instance', vmname=ins_data['name'])
        if not connect_instance:
            pass
        # 添加扩容开始action
        ins_a_s.update_instance_status(VMStatus.CONFIGURE_ING, instance_id)
        ins_a_s.add_disk_extend_action_to_database(uuid, request_id, user_id,
                                                   InstaceActions.INSTANCE_DISK_EXTEND, ActionStatus.START, 'start')
        # 满足扩容条件
        if n_qemu_ga_update_req:
            if c_system.strip() == 'linux':
                flag, msg = connect_instance.exec_qemu_command(
                    "cat /proc/self/mounts | grep -w / | grep -v rootfs | awk '{print $3}'")
                if not flag:
                    c_version = None
                c_version = CentOS_Version.CentOS_6 if msg.strip() == 'ext4' else CentOS_Version.CentOS_7
                flag, result = ins_a_s.extend_mount_size(n_extend_list_req, host_ip, vmname, uuid, c_version, instance_id)
            elif c_system.strip() == 'windows':
                flag, result = ins_a_s.extend_dev_size(n_extend_list_req, host_ip, vmname, uuid, instance_id)
            else:
                flag = False
            if flag:
                msg = "扩容成功"
                ins_a_s.update_disk_action_to_database(request_id, InstaceActions.INSTANCE_DISK_EXTEND,
                                                       ActionStatus.SUCCSESS, msg)
                ins_a_s.update_instance_status(VMStatus.STARTUP, instance_id)
            else:
                msg = "扩容失败,{}".format(result)
                ins_a_s.update_disk_action_to_database(request_id, InstaceActions.INSTANCE_DISK_EXTEND,
                                                       ActionStatus.FAILD, msg)
                ins_a_s.update_instance_status(VMStatus.STARTUP, instance_id)
                return json_helper.format_api_resp(code=ErrorCode.ALL_FAIL, msg=msg)
        else :
            # 非linux系统,关机状态,qemu-guest-agent没有更新成功
            msg = "非linux系统,扩容失败"
            ins_a_s.update_disk_action_to_database(request_id, InstaceActions.INSTANCE_DISK_EXTEND, ActionStatus.FAILD,
                                                   msg)
            ins_a_s.update_instance_status(VMStatus.STARTUP, instance_id)
            return json_helper.format_api_resp(code=ErrorCode.ALL_FAIL, msg=msg)
    else:
        pass

    if c_flavor_data['vcpu'] != n_flavor_data['vcpu'] or c_flavor_data['memory_mb'] != n_flavor_data['memory_mb']:

        # 检查当前应用组的配额
        is_group_enough, req_msg = _check_change_group_quota(n_group_id, n_flavor_data, c_flavor_data)
        if not is_group_enough:
            logging.error('new group %s quota is not enough to change new flavor', n_group_id)
            return json_helper.format_api_resp(code=ErrorCode.SYS_ERR, msg=req_msg)

        # 检查物理机当前使用率情况是否满足扩容
        is_host_available, ret_msg = __check_host_capacity(host_data, n_flavor_data, c_flavor_data)
        if not is_host_available:
            return json_helper.format_api_resp(code=ErrorCode.SYS_ERR, msg=ret_msg)

        # 关机状态
        if ins_status == VMStatus.SHUTDOWN:
            pass
        elif ins_status == VMStatus.STARTUP:
            # 开机状态
            # cpu只能增
            if c_flavor_data['vcpu'] > n_flavor_data['vcpu']:
                logging.error('vcpu only be increase in startup status, now vcpu %s > new vcpu %s',
                              c_flavor_data['vcpu'], n_flavor_data['vcpu'])
                ins_a_s.update_instance_status(VMStatus.STARTUP, instance_id)
                return json_helper.format_api_resp(code=ErrorCode.SYS_ERR, msg='开机状态下,CPU数量只能增加不能减少')

            # 内存不能修改
            if c_flavor_data['memory_mb'] != n_flavor_data['memory_mb']:
                logging.error('memory only no allow be change in startup status, now mem %s, new mem %s',
                              c_flavor_data['memory_mb'], n_flavor_data['memory_mb'])
                ins_a_s.update_instance_status(VMStatus.STARTUP, instance_id)
                return json_helper.format_api_resp(code=ErrorCode.SYS_ERR, msg='开机状态下,不能修改内存容量')
        else:
            logging.error('instance status %s is invalid when change instance configure', ins_status)
            ins_a_s.update_instance_status(VMStatus.STARTUP, instance_id)
            return json_helper.format_api_resp(code=ErrorCode.SYS_ERR, msg='只能在开机或关机状态下修改配置')

    if n_flavor_data['vcpu'] == c_flavor_data['vcpu']:
        pass
    else:
        params['new_vcpu'] = n_flavor_data['vcpu']
        params['old_vcpu'] = c_flavor_data['vcpu']

    new_mem = n_flavor_data['memory_mb']
    old_mem = c_flavor_data['memory_mb']

    if new_mem == old_mem:
        pass
    else:
        # 检查内存是否超分
        if not _check_mem_allocation(instance_id, new_mem, old_mem):
            logging.error('instance %s mem has over allocation, new mem %s, old mem %s', instance_id, new_mem, old_mem)
            ins_a_s.update_instance_status(VMStatus.STARTUP, instance_id)
            return json_helper.format_api_resp(code=ErrorCode.SYS_ERR, msg='物理内存不能超分')
        params['new_mem'] = new_mem
        params['old_mem'] = old_mem

    # 检查网络配置是否需要修改
    n_net_conf_list = json_helper.loads(n_net_conf_list_req)
    if n_net_conf_list:
        params['net_status_list'] = n_net_conf_list

    # 没有一个指标可以修改
    if not params:
        logging.error('vcpu, mem, disk no one can change when change instance configure')
    else:
        host_ip = ins_s.get_hostip_of_instance(ins_data['id'])
        if not host_ip:
            logging.error('instance %s has no host ip when change instance configure', ins_data['id'])
            ins_a_s.update_instance_status(VMStatus.STARTUP, instance_id)
            return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)

        ret_flavor = ins_a_s.change_instance_configure(host_ip, ins_data, c_flavor_data['flavor_id'], n_flavor_id,
                                                       ins_status, **params)
        if not ret_flavor:
            ins_a_s.update_instance_status(VMStatus.STARTUP, instance_id)
            return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)

    update_data_i = {
        'app_info': n_app_info,
        'owner': n_owner,
        'updated_at': get_datetime_str()
    }
    where_data_i = {
        'id': instance_id
    }
    ret_i = ins_s.InstanceService().update_instance_info(update_data_i, where_data_i)
    # if ret_i != 1:
    #     logging.error('update instance info error when configure, update_data:%s, where_data:%s',
    #                   update_data_i, where_data_i)
    #     return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)

    update_data_g = {
        'group_id': n_group_id,
        'updated_at': get_datetime_str()
    }
    where_data_g = {
        'instance_id': instance_id
    }
    ret_g = ins_g_s.InstanceGroupService().update_instance_group_info(update_data_g, where_data_g)
    # if ret_g != 1:
    #     logging.error('update group info error when configure, update_data:%s, where_data:%s',
    #                   update_data_g, where_data_g)
    #     return json_helper.format_api_resp(code=ErrorCode.SYS_ERR)

    # if 'disk_gb_list' in params:
    #    return json_helper.format_api_resp(code=ErrorCode.SUCCESS, msg='硬盘扩容任务发送成功')

    return json_helper.format_api_resp(code=ErrorCode.SUCCESS, msg='修改配置成功')