コード例 #1
0
def ip_id_validator(value):
    if isinstance(value, list):
        for v in value:
            if not IpsModel.ip_exists_by_id(v):
                raise serializers.ValidationError(_(u"%s 不存在" % v))
    if not IpsModel.ip_exists_by_id(value):
        raise serializers.ValidationError(_(u"%s 不存在" % value))
コード例 #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)
コード例 #3
0
def sync_quota(resource, _payload):
    ret_set = []
    extra_infos = RESOURCE_TO_DESC_EXTRA_PARA.get(resource)
    func = RESOURCE_TO_DESC_FUN.get(resource)
    for extra_info in extra_infos:
        resp = func(dict(_payload, **extra_info))
        if resp.get("ret_code") != 0:
            logger.error("cannot get the resource list of %s" %
                         unicode(resource))
            return
        ret_set += resp.get("ret_set")

    if resource != "net":
        value = len(ret_set)
        # add logic for pre-pay
        resource_ids = []
        records = []
        pre_pay_num = 0
        if resource == 'disk':
            for disk_info in ret_set:
                resource_ids.append(disk_info.get('disk_id'))
            records = DisksModel.get_exact_disks_by_ids(resource_ids)
        elif resource == 'instance':
            for inst_info in ret_set:
                resource_ids.append(inst_info.get('instance_id'))
            records = InstancesModel.get_exact_instances_by_ids(resource_ids)
        elif resource == 'backup':
            for backup_info in ret_set:
                resource_ids.append(backup_info.get('backup_id'))
            records_fir = InstanceBackupModel.\
                get_exact_backups_by_ids(resource_ids)
            records_sec = DiskBackupModel.get_exact_backups_by_ids(
                resource_ids)
            for record in records_fir:
                records.append(record)
            for record in records_sec:
                records.append(record)
        elif resource == 'pub_ip':
            for ip_info in ret_set:
                resource_ids.append(ip_info.get('ip_id'))
            records = IpsModel.get_exact_ips_by_ids(resource_ids)
        if len(records) > 0:
            for record in records:
                if getattr(record, 'charge_mode') != "pay_on_time":
                    pre_pay_num += 1
        value -= pre_pay_num

        payload = deepcopy(_payload)
        q_type = RESOURCE_TO_GENERAL_QTYPE.get(resource, None)
        if q_type:
            payload.update({"quota_type": q_type})
            synchronize_visible_to_db(payload, value)
    # special quota sync
    if resource in SYNC_QUOTA_FUNC.keys():
        func = SYNC_QUOTA_FUNC.get(resource)
        func(ret_set, _payload["owner"], _payload["zone"])
コード例 #4
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)
コード例 #5
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()
コード例 #6
0
ファイル: qos.py プロジェクト: wang-shun/console
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
コード例 #7
0
def filter_subnet_pubips(ip_set):
    ip_list = list()
    for item in ip_set:
        ip_addr = item.get("floating_ip_address")
        ip_status = item.get("status")
        ip_uuid = item.get("id")
        binding_resource = item.get("binding_resource")
        ip_id = 'Unkonw'
        ip_name = 'Unknow'
        bandwidth = -1
        create_datetime = 0

        # 根据 ip 地址的 uuid 查询数据库表 ips ,可以获得 ID、名称、计费模式、带宽、分配时间
        ip_obj = IpsModel.get_ip_by_uuid(ip_uuid)
        if ip_obj:
            ip_id = ip_obj.ip_id
            ip_name = ip_obj.name
            bandwidth = ip_obj.bandwidth
            create_datetime = datetime_to_timestamp(ip_obj.create_datetime)

        instance_uuid = binding_resource.get("instance_id")
        if instance_uuid:
            instance_inst = InstancesModel.get_instance_by_uuid(instance_uuid)
            if instance_inst:
                instance_id = instance_inst.instance_id
                instance_name = instance_inst.name
                binding_resource["instance_id"] = instance_id
                binding_resource["instance_name"] = instance_name

        router_uuid = binding_resource.get("router_id")
        if router_uuid:
            router_inst = RoutersModel.get_router_by_uuid(router_uuid)
            if router_inst:
                router_id = router_inst.router_id
                router_name = router_inst.name
                binding_resource["router_id"] = router_id
                binding_resource["router_name"] = router_name

        ip_list.append({
            "ip_id": ip_id,
            "ip_name": ip_name,
            "ip_addr": ip_addr,
            "ip_status": ip_status,
            "bandwidth": bandwidth,
            "binding_resource": json.dumps(binding_resource),
            "create_datetime": create_datetime
        })
    return ip_list
コード例 #8
0
def filter_needed_ip_set(ip_set, ip_ids):
    ip_ret = []
    if ip_ids:
        for ip in ip_set:
            ip_ist = IpsModel.get_ip_by_uuid(ip["id"])
            if ip_ist:
                ip_id = ip_ist.ip_id
            else:
                ip_id = None

            if ip_id and ip_id in ip_ids:
                ip_ret.append(ip)
    else:
        ip_ret = ip_set

    return ip_ret
コード例 #9
0
def get_ip_detail_by_uuid(uuid):
    detail = {}
    try:
        info = IpsModel.get_ip_by_uuid(uuid)
        detail["ip_id"] = info.ip_id
        detail["ip_name"] = info.name
        detail["bandwidth"] = info.bandwidth
        detail["is_normal"] = info.is_normal
        detail["billing_mode"] = info.billing_mode
        detail["create_datetime"] = datetime_to_timestamp(info.create_datetime)
        detail["charge_mode"] = getattr(info, "charge_mode")
    except IpsModel.DoesNotExist:
        # TODO: logging
        pass

    return detail
コード例 #10
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()
コード例 #11
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])
コード例 #12
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
コード例 #13
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
コード例 #14
0
def make_ip_id():
    while True:
        ip_id = "%s-%s" % (settings.IP_PREFIX, randomname_maker())
        if not IpsModel.ip_exists_by_id(ip_id):
            return ip_id
コード例 #15
0
        def handle_args(*args, **kwargs):

            _payload = kwargs.get("payload", None)
            if _payload is None:
                _payload = args[0]
            payload = copy.deepcopy(_payload)
            owner = payload.get("owner")
            zone = payload.get("zone")
            capacity = 1

            resp = func(*args, **kwargs)
            value = resp.get("ret_set")
            logger.info("%s, %s, %s" % (str(owner), str(zone), str(quota_type)))
            if value is not None:

                # add logic for pre-pay
                pre_pay_num = 0
                if resp.get("ret_code") == 0:
                    records = []
                    if quota_type == 'disk':
                        resource_ids = payload.get("disk_id")
                        records = DisksModel.get_exact_disks_by_ids(resource_ids)
                    elif quota_type == 'instance':
                        resource_ids = payload.get("instances")
                        records = InstancesModel.get_exact_instances_by_ids(
                            resource_ids)
                    elif quota_type == 'backup':
                        resource_ids = payload.get("backup_id_list")
                        records_fir = InstanceBackupModel. \
                            get_exact_backups_by_ids(resource_ids)
                        records_sec = DiskBackupModel. \
                            get_exact_backups_by_ids(resource_ids)
                        for record in records_fir:
                            records.append(record)
                        for record in records_sec:
                            records.append(record)
                    elif quota_type == 'pub_ip':
                        resource_ids = payload.get("ips")
                        records = IpsModel.get_exact_ips_by_ids(resource_ids)
                    if len(records) > 0:
                        for record in records:
                            if getattr(record, 'charge_mode') != "pay_on_time":
                                pre_pay_num += 1

                if isinstance(value, list):
                    dec_resp = append_quota(
                        zone=zone, owner=owner, q_type=quota_type,
                        value=((len(value) - pre_pay_num) * capacity))
                    if dec_resp.get("ret_code") != 0:
                        logger.error(QUOTAS_MSG.get(QuotaErrorCode.
                                                    QUOTA_MODIFICATION_ERROR))
                    else:
                        logger.info("%s quota increased by: %s" %
                                    (str(quota_type), str(len(value) * capacity)))
                else:
                    dec_resp = append_quota(
                        zone=zone, owner=owner, q_type=quota_type,
                        value=(1 - pre_pay_num) * capacity)
                    if dec_resp.get("ret_code") != 0:
                        logger.error(QUOTAS_MSG.get(QuotaErrorCode.
                                                    QUOTA_MODIFICATION_ERROR))
                    else:
                        logger.info("%s quota increased by: %s" %
                                    (str(quota_type), str(capacity)))
            return resp
コード例 #16
0
ファイル: services.py プロジェクト: wang-shun/console
    def filter(zone, owner):
        payload = {
            'owner': owner,
            'zone': zone,
            'action': 'DescribeLoadbalancers',
        }
        lb_details = LoadbalancerTrash.objects.filter(
            lb__zone__name=zone,
            lb__user__username=owner,
            delete_datetime=None,
            restore_datetime=None).values('lb__lb_id', 'create_datetime')
        lb_delete_datetimes = {
            lb_detail['lb__lb_id']: lb_detail['create_datetime']
            for lb_detail in lb_details
        }
        resp = describe_loadbalancers_api(payload)
        lb_set = resp.get("data", {}).get("ret_set", [])

        lb_list = []
        for single in lb_set:
            lb_id = single.get("name", None)
            if lb_id not in lb_delete_datetimes:
                continue

            raw_status = single.get("provisioning_status", None)
            if lb_id and LoadbalancerModel.lb_exists_by_id(lb_id,
                                                           deleted=True):
                lb = LoadbalancerModel.get_lb_by_id(lb_id, deleted=True)
            else:
                continue

            info = {
                "lb_id": lb_id,
                "lb_name": lb.name,
                "create_datetime": datetime_to_timestamp(lb.create_datetime),
                "status": transfer_lb_status(raw_status),
            }

            net_info = {"is_basenet": lb.is_basenet}
            if not lb.is_basenet:
                net_payload = {
                    "zone": zone,
                    "owner": owner,
                    "action": "DescribeNets",
                    "subnet_id": lb.net_id
                }
                resp = api.get(net_payload)
                net_data = resp['data']['ret_set'][0]
                net_type = 'private' if net_data.get(
                    'gateway_ip') is None else 'public'
                net_info.update({"net_type": net_type})
                net_info.update({"net_id": lb.net_id})
                net_info.update({"net_name": net_data['name']})
            info.update({"net": net_info})

            ip_info = {"vip_addr": single.get("vip_address", None)}
            fip_info = single.get("fip_info")
            if fip_info:
                fip_uuid = fip_info["ip_uuid"]
                fip_address = fip_info["ip_address"]
                ip = IpsModel.get_ip_by_uuid(fip_uuid)
                ip_info.update({"ip_id": ip.ip_id})
                ip_info.update({"fip_addr": fip_address})
                ip_info.update({"bandwidth": ip.bandwidth})
            info.update({"ip": ip_info})
            info['delete_datetime'] = datetime_to_timestamp(
                lb_delete_datetimes[lb_id])

            lb_list.append(info)

        return lb_list
コード例 #17
0
def describe_loadbalancers(payload):
    zone = payload.get("zone")
    owner = payload.get("owner")
    lb_id = payload.pop("lb_id", None)
    features = payload.pop("features", [])

    if lb_id:
        lb = LoadbalancerModel.get_lb_by_id(lb_id)
        lb_uuid = lb.uuid
    else:
        lb_uuid = None

    # call backend
    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", [])
    lb_list = []
    for single in lb_set:
        lb_id = single.get("name", None)
        raw_status = single.get("provisioning_status", None)
        if lb_id and LoadbalancerModel.lb_exists_by_id(lb_id):
            lb = LoadbalancerModel.get_lb_by_id(lb_id)
        else:
            continue

        info = {
            "lb_id": lb_id,
            "lb_name": lb.name,
            "create_datetime": datetime_to_timestamp(lb.create_datetime),
            "status": transfer_lb_status(raw_status),
        }

        net_info = {"is_basenet": lb.is_basenet}
        if not lb.is_basenet:

            net_payload = {
                "zone": zone,
                "owner": owner,
                "action": "DescribeNets",
                "subnet_id": lb.net_id
            }
            resp = api.get(net_payload)
            net_data = resp['data']['ret_set'][0]
            net_type = 'private' if net_data.get(
                'gateway_ip') is None else 'public'
            net_info.update({"net_type": net_type})
            net_info.update({"net_id": lb.net_id})
            net_info.update({"net_name": net_data['name']})
        info.update({"net": net_info})

        ip_info = {"vip_addr": single.get("vip_address", None)}
        logger.debug('single: ')
        logger.debug(single)
        fip_info = single.get("fip_info")
        if fip_info:
            fip_uuid = fip_info["ip_uuid"]
            fip_address = fip_info["ip_address"]
            ip = IpsModel.get_ip_by_uuid(fip_uuid)
            ip_info.update({"ip_id": ip.ip_id})
            ip_info.update({"fip_addr": fip_address})
            ip_info.update({"bandwidth": ip.bandwidth})
        info.update({"ip": ip_info})

        for feature in features:
            if 'elastic' == feature:
                elastic = ElasticGroupService.get_by_loadbalance_id(lb_id)
                if elastic:
                    serializer = DescribeLoadbalancerSerializer(elastic)
                    info.update({'elastic': serializer.data})

        lb_list.append(info)
    lb_list = sorted(lb_list,
                     key=lambda x: x.get("create_datetime"),
                     reverse=True)

    return console_response(code=Code.OK,
                            msg=msg,
                            total_count=len(lb_list),
                            ret_set=lb_list)
コード例 #18
0
ファイル: helper.py プロジェクト: wang-shun/console
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
コード例 #19
0
def allocate_ips(payload):
    """
    Allocate ip Synchronously
    """
    count = payload.pop("count")  # 创建IP的个数
    name_base = payload.pop("ip_name")  # IP的名称

    zone = payload["zone"]
    owner = payload["owner"]
    bandwidth = payload.pop("bandwidth")
    billing_mode = payload.pop("billing_mode")
    charge_mode = payload.get("charge_mode")
    # package_size = payload.get("package_size")
    is_normal = payload.get("is_normal", True)

    create_status = []  # IP创建的状态map
    succ_num = 0  # IP创建的成功数量

    for n in xrange(count):
        _payload = deepcopy(payload)
        ip_name = get_ip_name(name_base, n)
        ip_id = make_ip_id()

        # for the pre-pay, count can only be 1, if create_billing failed,
        # return the corresponding error code directly
        # if charge_mode.strip() != 'pay_on_time':
        #     is_succ = billing_allocate_ip(ip_id, uuid, billing_mode, bandwidth,
        #                                   owner, zone, charge_mode, package_size)
        #     if not is_succ:
        #         return console_response(BillingErrorCode.BALANCE_NOT_ENOUGH,
        #                                 "pre-pay failed")

        _payload.update({"name": ip_id})

        # call backend api
        # resp = api.get(payload=_payload, timeout=10)
        resp = api.get(payload=_payload)
        if resp["code"] != 0:
            # create_status.append({'ip_id':ip_id, 'msg': resp["msg"]})
            continue

        ip_info = resp["data"]["ret_set"][0]
        uuid = ip_info["id"]  # ip uuid

        # save ip info to db
        ip, err = IpsModel.save_ip(uuid=uuid,
                                   ip_name=ip_name,
                                   ip_id=ip_id,
                                   zone=zone,
                                   owner=owner,
                                   bandwidth=bandwidth,
                                   billing_mode=billing_mode,
                                   charge_mode=charge_mode,
                                   is_normal=is_normal)
        if err is not None:
            logger.error("Save ip error, %s" % str(err))
            # create_status.append({'ip_id':ip_id, 'msg': str(err)})
            continue

        # create qos
        floatingip_address = ip_info.get("floating_ip_address", None)
        _set_qos_rule(zone, owner, ip_id, floatingip_address, bandwidth)

        # filter response infos
        ip_info = filter_needed_ip_info(ip_info)[0]
        ip_info["bandwidth"] = ip.bandwidth
        ip_info["billing_mode"] = ip.billing_mode
        ip_info["create_datetime"] = ip.create_datetime
        ip_info["name"] = ip.name
        ip_info.pop("instance", None)
        ip_info.pop("router", None)

        create_status.append(ip_id)
        succ_num += 1
    if succ_num != count:
        code, msg = 1, "error"
    else:
        code, msg = 0, "succ"

    return console_response(code=code,
                            msg=msg,
                            total_count=len(create_status),
                            ret_set=create_status)
コード例 #20
0
def filter_needed_ip_info(ip_info):
    """
    获取js端需要的参数信息
    """
    def get_binding_instance(instance_uuid):
        instance_inst = InstancesModel.get_instance_by_uuid(instance_uuid)
        if not instance_inst:
            return {}
        instance = {
            "instance_id": instance_inst.instance_id,
            "instance_name": instance_inst.name
        }
        return instance

    def get_binding_router(router_uuid):
        router_inst = RoutersModel.get_router_by_uuid(router_uuid)
        if not router_inst:
            return {}
        router = {
            "router_id": router_inst.router_id,
            "router_name": router_inst.name
        }
        return router

    def get_binding_lb(lb_uuid):
        lb_inst = LoadbalancerModel.get_lb_by_uuid(lb_uuid)
        if not lb_inst:
            return {}
        lb = {"lb_id": lb_inst.lb_id, "lb_name": lb_inst.name}
        return lb

    def get_binding_resource(binding_resource):
        if not binding_resource:
            return None, None, None
        instance_uuid = binding_resource.get("instance_id", "")
        instance = get_binding_instance(instance_uuid)

        router_uuid = binding_resource.get("router_id", "")
        router = get_binding_router(router_uuid)

        lb_uuid = binding_resource.get("lb_id", "")
        lb = get_binding_lb(lb_uuid)
        return instance, router, lb

    def map_status(status, binding_resource=None):
        status = str(status)
        if status != "ERROR":
            if binding_resource:
                status = "ACTIVE"
            else:
                status = "DOWN"
        if str.upper(status) in STATUS_MAP:
            return STATUS_MAP.get(str.upper(status))
        else:
            return status

    if isinstance(ip_info, list):
        ip_info = filter(lambda x: IpsModel.ip_exists_by_uuid(x["id"]),
                         ip_info)
    else:
        ip_info = [ip_info]

    # needed_info = IP_FILTER_MAP.values()
    info_list = []
    for ip in ip_info:
        info = get_ip_detail_by_uuid(ip["id"])

        # router_info
        router_uuid = ip["router_id"]
        if router_uuid is not None:
            router_inst = RoutersModel.get_router_by_uuid(router_uuid)
            if router_inst:
                info["router_id"] = router_inst.router_id
                info["router_name"] = router_inst.name

        # ip_address
        info["ip_address"] = ip["floating_ip_address"]

        # binding resource
        binding_resource = ip.get("binding_resource", None)
        info["instance"], info["router"], info["loadbalancer"] \
            = get_binding_resource(binding_resource)
        # status
        info["status"] = map_status(ip.get("status", "UNKNOWN"),
                                    binding_resource=binding_resource)
        info_list.append(info)

    return info_list