Esempio n. 1
0
def modify_ip_name(payload):
    """
    Modify ip name
    """

    ip_id = payload.pop("ip_id")
    ip_inst = IpsModel.get_ip_by_id(ip_id)
    ip_inst.name = payload.pop("ip_name")
    ip_inst.save()
    ret_set = [ip_id]

    return console_response(code=0, msg="succ", total_count=1, ret_set=ret_set)
Esempio n. 2
0
def release_ip(payload):
    """
    Release ip from db and backend
    """
    ips = payload.pop("ips")
    owner = payload["owner"]
    zone = payload["zone"]

    from console.console.alarms.helper import unbind_alarm_resource_before_delete
    unbind_alarm_resource_before_delete(payload, ips)

    ret_status = []
    succ_num = 0
    for ip_id in ips:
        _payload = deepcopy(payload)

        ip = IpsModel.get_ip_by_id(ip_id)

        _payload["floatingip_id"] = ip.uuid

        # bandwidth = ip.bandwidth

        # 超时操作

        # call backend api
        # resp = api.get(payload=_payload, timeout=10)
        resp = api.get(payload=_payload)

        if resp["code"] != 0:
            # ret_status.append({'ip_id': ip_id, 'msg': resp["msg"]})
            continue

        # delete qos
        qos_id = ip.qos
        delete_qos_rule(zone, owner, qos_id)

        # delete from db if succeed
        IpsModel.delete_ip(ip_id)

        # remove 'action'
        resp["data"].pop("action", None)

        ret_status.append(ip_id)
        succ_num += 1

    code, msg = 0, "succ"
    if succ_num != len(ips):
        code, msg = 1, "failed"

    return console_response(code=code,
                            msg=msg,
                            total_count=len(ret_status),
                            ret_set=ret_status)
Esempio n. 3
0
def update_qos_rule(ip_id, rate, unit="MBIT", direction="BOTH"):
    """
    Update Qos Rule
    """
    def call_qos_api(payload_pre, qos_rule_id):
        payload = deepcopy(payload_pre)
        payload.update({"qos_rule_id": qos_rule_id})

        # resp = api.get(payload=payload, timeout=10)
        resp = api.get(payload=payload)
        ret_code = resp["code"]
        if ret_code != 0:
            # todo: logging
            pass

        return ret_code, None

    if not (direction_valid(direction) and unit_valid(unit)):
        return 1, None  # TODO: return defined error code

    # get info by ip_id
    ip_inst = IpsModel.get_ip_by_id(ip_id)
    zone = ip_inst.zone.name
    owner = ip_inst.user.username
    qos_inst = ip_inst.qos
    ingress_uuid = qos_inst.ingress_uuid
    egress_uuid = qos_inst.egress_uuid

    payload_pre = {
        "action": "UpdateQosRule",
        "zone": zone,
        "owner": owner,
        "unit": QOS_UNIT[unit],
        "rate": rate,
    }

    # get direction
    ingress, egress = get_direction(direction)

    if ingress:
        ret_code, msg = call_qos_api(payload_pre, ingress_uuid)
        if ret_code != 0:
            return ret_code

    if egress:
        ret_code, msg = call_qos_api(payload_pre, egress_uuid)
        if ret_code != 0:
            return ret_code

    return 0
Esempio n. 4
0
def unbind_loadbalancer_ip(payload):
    ip_id = payload.pop("ip_id")

    ip = IpsModel.get_ip_by_id(ip_id)

    resp = unbind_ip_api(payload, ip.uuid)
    api_code = resp.get("data", {}).get("ret_code")
    code = resp.get("code", -1)
    msg = resp.get("msg", "failed")
    if code != Code.OK:
        code = convert_api_code(api_code)
        return console_response(code=code, msg=msg)

    return console_response()
Esempio n. 5
0
def bind_loadbalancer_ip(payload):
    ip_id = payload.pop("ip_id")
    lb_id = payload.pop("lb_id")

    lb = LoadbalancerModel.get_lb_by_id(lb_id)
    ip = IpsModel.get_ip_by_id(ip_id)

    # call describe_loadbalancer api
    resp = describe_loadbalancers_api(payload, loadbalancer_id=lb.uuid)

    api_code = resp.get("data", {}).get("ret_code")
    code = resp.get("code", -1)
    msg = resp.get("msg", "failed")
    if code != Code.OK:
        code = convert_api_code(api_code)
        return console_response(code=code, msg=msg)

    lb_set = resp.get("data", {}).get("ret_set", [])
    port_id = None
    fip_info = None
    if lb_set:
        port_id = lb_set[0].get("vip_port_id")
        fip_info = lb_set[0]["fip_info"]

    if not port_id:
        msg = "Lb(%s) get port_id error" % lb_id
        logger.error(msg)
        return console_response(code=LoadBalancerErrorCode, msg=msg)

    if fip_info:
        msg = "Lb(%s) had bind fip(%s)" % (lb_id, fip_info["ip_address"])
        logger.error(msg)
        return console_response(code=LoadBalancerErrorCode.BIND_IP_REPEATED,
                                msg=msg)

    resp = bind_ip_api(payload, port_id, ip.uuid)
    api_code = resp.get("data", {}).get("ret_code")
    code = resp.get("code", -1)
    msg = resp.get("msg", "failed")
    if code != Code.OK:
        code = convert_api_code(api_code)
        return console_response(code=code, msg=msg)

    return console_response()
Esempio n. 6
0
    def create(self, owner, zone, rds_id, uuid, rds_name,
               volume_size, volume_type, ip_addr, rds_type, visible,
               cluster_relation, db_version_id, flavor_id, charge_mode,
               sg_id=None,config_id=None, group_id=None, net_id=None, ip_id=None):
        try:
            user_record = User.objects.get(username=owner)
            zone_record = ZoneModel.get_zone_by_name(zone)
            db_version = RdsDBVersionModel.get_db_version_by_id(db_version_id)
            sg = RdsSecurityGroupModel.get_security_by_id(sg_id)
            config = RdsConfigModel.get_config_by_id(config_id)
            rds_group = RdsGroupModel.get_rds_group_by_id(group_id)
            # net = NetsModel.get_net_by_id(net_id)
            public_ip = IpsModel.get_ip_by_id(ip_id)
            flavor = RdsFlavorModel.get_flavor_by_flavor_id(flavor_id)
            _rds_record = RdsModel(
                rds_id=rds_id,
                uuid=uuid,
                rds_name=rds_name,
                volume_size=volume_size,
                volume_type=volume_type,
                ip_addr=ip_addr,
                rds_type=rds_type,
                visible=visible,
                cluster_relation=cluster_relation,

                sg=sg,
                config=config,
                rds_group=rds_group,
                net_id=net_id,
                public_ip=public_ip,
                db_version=db_version,
                flavor=flavor,

                charge_mode=charge_mode,
                user=user_record,
                zone=zone_record)
            _rds_record.save()
            return _rds_record, None
        except Exception as exp:
            logger.error("cannot save rds, {}".format(exp))
            return None, exp
Esempio n. 7
0
def modify_ip_bandwidth(payload):
    """
    Resize the ip bandwith
    """
    # zone = payload.get("zone")
    # owner = payload.get("owner")
    ip_id = payload.get("ip_id")

    # ip_inst = IpsModel.get_ip_by_id(ip_id)
    # charge_mode = ip_inst.charge_mode

    # old_bandwidth = ip_inst.bandwidth
    # new_bandwidth = payload["bandwidth"]

    # _payload = deepcopy(payload)
    # _payload.update({"action": "DescribeIP"})
    # _payload.update({"ip_id": [ip_id]})

    # Get ip status
    # resp = describe_ips(_payload, internal=True)
    # code = resp.get("ret_code")
    # msg = resp["msg"]
    # status = resp.get("ret_set", [{}])[0].get("status", "")
    # if code != 0:
    #    return console_response(code=code,
    #                            msg=msg)

    # Check qos status: if ip is in-active, just update db
    # if status == "in-use":  # TODO: deal with more status
    update_qos_rule(ip_id=ip_id, rate=payload.get("bandwidth"))

    # update db
    try:
        ip = IpsModel.get_ip_by_id(ip_id)
        # change billing mode
        ip.bandwidth = payload.get("bandwidth")
        ip.save()
    except IpsModel.DoesNotExist as exp:
        return console_response(code=90001, msg=str(exp))

    return console_response(code=0, msg="succ", total_count=1, ret_set=[ip_id])
Esempio n. 8
0
def _set_qos_rule(zone, owner, ip_id, floatingip_address, bandwidth):
    ip_inst = IpsModel.get_ip_by_id(ip_id)
    # limit rate to ip
    ret_code, qos_id = set_qos_rule(zone=zone,
                                    owner=owner,
                                    ip=floatingip_address,
                                    rate=bandwidth)
    if qos_id is None:
        # TODO: logging, qos failed
        logger.error("set_qos_rule function error")
        return False
        pass
    # save qos_id to db
    try:
        ip_inst.qos_id = qos_id
        ip_inst.save()
    except Exception as exp:
        # todo: logging
        logger.error("save qos_id to ip model error %s" % exp)
        return False
        pass

    return True
Esempio n. 9
0
def add_ticket_monitor(owner, content):
    now_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    cur_node = get_monitor_create_node()
    next_node = get_monitor_second_node()
    content_dict = json.loads(content)
    description = content_dict['alarmName'].split(' ')
    host = description[0]
    item = item_reserver_mapper[description[1]]
    threshold_type = '>' if description[2] == '<' else '>'
    last_value = content_dict['Last value'] + item_to_unit.get(item, '')
    threshold = description[3] + item_to_unit.get(item, '')
    if item == 'status':
        last_value = u'关机'
        threshold = ''
        threshold_type = ''
    small_class = item_to_display.get(item)
    host_type = host.split('-')[0]
    system_name = '-'
    if host_type == 'i':
        instance = InstancesModel.get_instance_by_id(instance_id=host)
        host_name = instance.name
        if instance.app_system:
            system_name = instance.app_system.name
        title = '虚拟机' + host_name + '/' + host + ' ' + threshold_type + ' ' + threshold
        big_class = '虚拟机'
    elif host_type == 'ip':
        ip = IpsModel.get_ip_by_id(ip_id=host)
        host_name = ip.name
        payload = {
            'action': 'DescribeIp',
            'ip_id': [host],
            'owner': owner,
            'zone': 'bj'
        }
        resp = describe_ips(payload)
        if resp.get('status', '') == 'in_use':
            instance_id = resp['ret_set']['instance']['instance_id']
            instance = InstancesModel.get_instance_by_id(
                instance_id=instance_id)
            if instance.app_system:
                system_name = instance.app_system.name
        title = '公网IP' + host_name + '/' + host + ' ' + threshold_type + ' ' + threshold
        big_class = '公网IP'
    elif host_type == 'lbl':
        lbl = ListenersModel.get_lbl_by_id(lbl_id=host)
        host_name = lbl.name
        system_name = '-'
        title = '负载均衡' + host_name + '/' + host + ' ' + threshold_type + ' ' + threshold
        big_class = '负载均衡'
    elif host_type == 'lbm':
        lbm = MembersModel.get_lbm_by_id(lbm_id=host)
        host_name = lbm.name
        system_name = '-'
        title = '负载均衡' + host_name + '/' + host + ' ' + threshold_type + ' ' + threshold
        big_class = '负载均衡'
    else:
        rds = RdsModel.get_rds_by_id(rds_id=host)
        host_name = rds.name
        system_name = '-'
        title = '关系型数据库' + host_name + '/' + host + ' ' + threshold_type + ' ' + threshold
        big_class = '负载均衡'

    info = [{
        'unit_name': u'标题',
        'unit_attribute': 'text',
        'unit_choices_list': [],
        'unit_fill_value': title
    }, {
        'unit_name': u'所属应用系统',
        'unit_attribute': 'drop',
        'unit_choices_list': [],
        'unit_fill_value': system_name
    }, {
        'unit_name': u'大类',
        'unit_attribute': 'drop',
        'unit_choices_list': [],
        'unit_fill_value': big_class
    }, {
        'unit_name': u'小类',
        'unit_attribute': 'drop',
        'unit_choices_list': [],
        'unit_fill_value': small_class
    }, {
        'unit_name': u'设备ID/编号',
        'unit_attribute': 'text',
        'unit_choices_list': [],
        'unit_fill_value': host
    }, {
        'unit_name': u'设备名称',
        'unit_attribute': 'text',
        'unit_choices_list': [],
        'unit_fill_value': host_name
    }, {
        'unit_name': u'告警时间',
        'unit_attribute': 'date',
        'unit_choices_list': [],
        'unit_fill_value': now_time
    }, {
        'unit_name': u'采集值',
        'unit_attribute': 'text',
        'unit_choices_list': [],
        'unit_fill_value': last_value
    }]
    fill_data = {
        'cur_node_id': cur_node,
        'next_node_id': next_node,
        'node_data': info
    }
    resp = add_ticket_process(owner=owner,
                              ticket_id=None,
                              ticket_type=1,
                              fill_data=fill_data)
    return resp