Пример #1
0
def get_keypair_instances(zone, owner, keypair_id):
    """
    Get keypair related instances
    """

    payload = {
        "zone": zone,
        "owner": owner,
        "action": "DescribeKeyPairsResource",
        "name": keypair_id
    }

    instances = []
    resp = api.get(payload)
    if resp["code"] != 0 and resp["data"].get("total_count", 0) <= 0:
        return instances

    infos = resp["data"]["ret_set"]
    for info in infos:
        instance_uuid = info["instance_id"]
        instance_inst = InstancesModel.get_instance_by_uuid(instance_uuid)
        if instance_inst:
            info.update({"instance_id": instance_inst.instance_id})
            info.update({"instance_name": instance_inst.name})
            instances.append(info)
    return instances
Пример #2
0
def get_apply_instance_info(payload):
    payload.update({"action": "DescribeSecurityGroupResource"})
    # resp = api.get(payload=payload, timeout=10)
    resp = api.get(payload=payload)

    new_result = []
    ret_code = resp.get("code")
    if ret_code == 0:
        result = resp.get("data").get("ret_set")

        ins_uuid_set = set()
        for i in range(0, len(result)):
            applied_ins_info = result[i]
            ins_uuid = applied_ins_info.get("instance_id")
            if ins_uuid in ins_uuid_set:
                continue
            else:
                ins_uuid_set.add(ins_uuid)
            try:
                ins_model = InstancesModel.get_instance_by_uuid(uuid=ins_uuid)
                ins_id = ins_model.instance_id
                name = ins_model.name
                applied_ins_info["instance_id"] = ins_id
                applied_ins_info["name"] = name
                new_result.append(result[i])
            except Exception as exp:
                logger.error(str(exp))

    return new_result
Пример #3
0
 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
Пример #4
0
def restore_instance_backup(payload):
    resource_id = payload.pop("resource_id", None)
    backup_id = payload.pop("backup_id")
    action = payload.pop("action")
    version = payload.pop("version")
    backup_info = InstanceBackupModel.get_backup_by_id(backup_id=backup_id)
    backup_uuid = backup_info.uuid
    if resource_id is not None:
        try:
            resource_uuid = InstancesModel.get_instance_by_id(
                instance_id=resource_id).uuid
        except Exception:
            error_info = "cannot find instance with instance_id " \
                         + resource_id
            return console_response(BackupErrorCode.RESTORE_RESOURCE_NOT_FOUND,
                                    error_info)
    else:
        payload.update({"action": "DescribeImage", "image_id": backup_uuid})
        # resp = api.get(payload=payload, timeout=10)
        resp = api.get(payload=payload)
        if resp.get("code") != 0:
            return console_response(CommonErrorCode.REQUEST_API_ERROR,
                                    resp.get("msg"))
        elif resp["data"]["total_count"] <= 0:
            return console_response(
                BackupErrorCode.ASSOCIATE_INSTANCE_NOT_FOUND,
                "the instance related to the backup "
                "cannot be found, may be it has already"
                " been deleted")
        resource_uuid = resp["data"]["ret_set"][0]["instance_uuid"]
        resource_record = InstancesModel.get_instance_by_uuid(resource_uuid)
        if resource_record:
            resource_id = resource_record.instance_id
    payload.update({
        "action": action,
        "version": version,
        "instance_id": resource_uuid,
        "image_id": backup_uuid
    })
    # resp = api.get(payload=payload, timeout=10)
    resp = api.get(payload=payload)
    msg = resp.get("msg")
    if msg is None:
        msg = "Success"
    code = 0
    if resp.get("code") != 0:
        code = CommonErrorCode.REQUEST_API_ERROR
    return console_response(code, msg, 1, [{
        "instance_id": resource_id,
        "backup_id": backup_id
    }], {"source_backup_id": resource_id})
Пример #5
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
Пример #6
0
def get_resource_inst_by_uuid(backup_type, uuid, zone, deleted=False):
    if backup_type == "disk":
        try:
            inst = DisksModel.get_disk_by_uuid(uuid=uuid,
                                               zone=zone,
                                               deleted=deleted)
            return inst
        except Exception as exp:
            return None
    else:
        try:
            inst = InstancesModel.get_instance_by_uuid(uuid=uuid,
                                                       deleted=deleted)
            return inst
        except Exception as exp:
            return None
Пример #7
0
def get_instances_info(owner, zone, is_basenet, net_id=None, instance_uuid=None):
    payload = {
        "zone": zone,
        "owner": owner
    }
    if instance_uuid:
        payload.update({"instance_id": instance_uuid})
    # get instance info from backend
    resp = describe_instance_api(payload)
    err = resp.get("msg", "failed")
    code = resp.get("code", -1)
    if code != Code.OK:
        logger.error("DescribeInstance Error: %s" % str(err))
        return []

    ret_set = resp.get("data", {}).get("ret_set", [])

    instances_info = []
    subnet_uuid_info = get_subnet_uuid_info(zone, owner)
    for instance in ret_set:
        uuid = instance["id"]
        addresses = instance.get("addresses", {})
        ins = InstancesModel.get_instance_by_uuid(uuid)
        if not ins:
            continue
        instance_id = ins.instance_id
        instance_name = ins.name
        if not ins.seen_flag or ins.vhost_type != "KVM":
            continue
        if is_basenet:
            if "base-net" not in addresses:
                continue
            logger.debug("get one")
            instances_info.append(
                generate_resource_info("instance", instance_id, instance_name, addresses["base-net"][0].get("addr"))
            )
            logger.debug(instances_info)
        else:
            nets, net_count = get_nets_info(addresses, uuid, subnet_uuid_info, None)
            net_info = get_net_by_net_id(nets, net_id)
            if net_info:
                instances_info.append(generate_resource_info("instance", instance_id, instance_name, net_info["ip_address"]))

    return instances_info
Пример #8
0
def format_instance_monitor_info(resp, name_dict, point_num, data_fmt, item,
                                 sort_method):
    logger.debug("the osapi resp for multi monitor is " + str(resp))
    # resp_timestamp = resp["data"].get("timestamp")
    # logger.info("the timestamp of the first point is: " + str(resp_timestamp))
    ret_set = resp.get("data").get("ret_set")
    ret_set = dict(ret_set)
    new_ret_set = []
    unit = item_to_unit.get(item)
    display_name = item_to_display.get(item)
    timestamp = resp.get("data").get("timestamp")

    for ins_uuid, ins_info in ret_set.items():
        instance_record = InstancesModel.get_instance_by_uuid(uuid=ins_uuid)
        if not instance_record:
            logger.error("cannot find instance with uuid " + str(ins_uuid))
            continue
        ins_id = instance_record.instance_id
        ins_info = list(ins_info)
        for item in ins_info:
            item = dict(item)
            item_name, result_data = dict(item).popitem()

            result_data = process_point_data(result_data, point_num, data_fmt)
        instance_name = get_resource_name(ins_id)
        new_ret_set.append({
            "resource_id": ins_id,
            "resource_name": instance_name,
            "data": result_data,
            "unit": unit,
            "display_name": display_name,
            "timestamp": timestamp
        })
    new_ret_set = sort_monitor_info_version2(new_ret_set, sort_method)
    resp["data"]["ret_set"] = new_ret_set
    return resp
Пример #9
0
def format_multi_response(resp,
                          name_dict,
                          point_num,
                          data_fmt,
                          item,
                          sort_method,
                          instance_info_dict,
                          call_source='console'):
    logger.debug("the osapi resp for multi monitor is " + str(resp))
    # resp_timestamp = resp["data"].get("timestamp")
    # logger.info("the timestamp of the first point is: " + str(resp_timestamp))
    ret_set = resp.get("data").get("ret_set")

    ret_set = dict(ret_set)
    new_ret_set = []
    unit = item_to_unit.get(item)
    display_name = item_to_display.get(item)
    timestamp = resp.get("data").get("timestamp")
    id_str = 'instance_id'
    name_str = 'instance_name'

    for ins_uuid, ins_info in ret_set.items():
        if call_source == 'console':
            instance_record = InstancesModel.get_instance_by_uuid(
                uuid=ins_uuid)
            if not instance_record:
                logger.error("cannot find instance with uuid " + str(ins_uuid))
                continue
            ins_id = instance_record.instance_id
        elif call_source == 'finance':
            ins_id = instance_info_dict[ins_uuid]['name']

        ins_info = list(ins_info)
        new_ins_info = {}
        for item in ins_info:
            item = dict(item)
            if call_source == 'finance':
                item.pop('unit')

            device_name = name_dict.get(item.pop("device_name", "NOVALUE"),
                                        "default")
            item_name, result_data = dict(item).popitem()

            result_data = process_point_data(result_data, point_num, data_fmt)
            resource_name = get_resource_name(device_name)
            result_data = {"resource_name": resource_name, "data": result_data}
            if new_ins_info is None:
                new_ins_info = {device_name: result_data}
            else:
                new_ins_info.update({device_name: result_data})
        instance_name = get_resource_name(ins_id) or None

        if call_source == 'finance':
            if not instance_name:
                instance_name = instance_info_dict[ins_uuid][
                    'OS-EXT-SRV-ATTR:instance_name']
            id_str = 'id'
            name_str = 'name'
        if new_ins_info:
            new_ret_set.append({
                id_str: ins_id,
                name_str: instance_name,
                "monitor_info": new_ins_info,
                "unit": unit,
                "display_name": display_name,
                "timestamp": timestamp
            })
    if sort_method:
        if sort_method == "increase":
            new_ret_set = sort_monitor_info(new_ret_set, id_str, False)
        elif sort_method == "decrease":
            new_ret_set = sort_monitor_info(new_ret_set, id_str, True)
        else:
            new_ret_set = sort_by_name(new_ret_set, "instance_name")
    resp["data"]["ret_set"] = new_ret_set
    return resp
Пример #10
0
def describe_disk(payload, need_sim=False):
    disks = payload.pop("disks", [])
    disk_id = payload.pop("disk_id", None)
    status = payload.pop("status", None)
    version = payload.get("version", settings.API_VERSION)
    search_key = payload.get('search_key')
    if not search_key:
        search_key = None
    limit = payload.get('limit', 10)
    offset = payload.get('offset', 1)
    start = limit * (offset - 1)
    end = start + limit
    availability_zone = payload.get('availability_zone')
    if disk_id:
        disk = DisksModel.get_disk_by_id(disk_id=disk_id)
        availability_zone = disk.availability_zone
        disk_type = disk.disk_type
        payload.update({"volume_id": disk.uuid})
        if disk_type == DiskTypeMetadata.POWERVM_HMC:
            from .hmc_helper import HMCDiskHelper
            return HMCDiskHelper.list(payload)
    else:
        payload.update({"sort_key": payload.get("sort_key")})

    resp = api.get(payload=payload)
    if need_sim:
        return resp

    if resp.get("code") != 0:
        return console_response(CommonErrorCode.REQUEST_API_ERROR,
                                resp.get("msg"))

    disk_set = resp["data"].get("ret_set", [])
    disk_list = []

    for disk in disk_set:
        disk_id = disk["name"]
        inst = DisksModel.objects.filter(disk_id=disk_id,
                                         deleted=False,
                                         availability_zone=availability_zone)
        if inst.count() == 1:
            inst = inst[0]
        else:
            continue

        inst.disk_size = disk.get('size')
        if inst.disk_size:
            inst.save()

        disk.update({
            'disk_name': inst.name,
            'charge_mode': inst.charge_mode,
            'is_normal': inst.is_normal
        })
        attach_info = disk.get("attachments")
        if attach_info and len(attach_info) > 0:
            instance_uuid = attach_info[0].get("server_id")
            device = attach_info[0].get("device")
            try:
                instance = InstancesModel.get_instance_by_uuid(
                    uuid=instance_uuid)
                instance_info_dict = {
                    'instance_id': instance.instance_id,
                    'instance_name': instance.name,
                }
                disk.update({"attach_instance": instance_info_dict})
                if not device:
                    logger.error("the device parameter is None")
                    continue
                disk.update({"device": device})
            except Exception:
                logger.error(
                    "the instance with instance_uuid %s cannot be found" %
                    instance_uuid)
        if not status or disk.get("status") == REVERSE_STATUS_MAP.get(status):
            if search_key is not None:
                for item in disk.values():
                    if search_key in str(item):
                        if disk not in disk_list:
                            disk_list.append(disk)
            else:
                disk_list.append(disk)
    payload.update({"action": "DescribeDiskBackup", "version": version})
    payload.pop("volume_id", None)
    desp_backup_resp = api.get(payload=payload)
    if desp_backup_resp.get("code") != 0:
        return console_response(CommonErrorCode.REQUEST_API_ERROR,
                                desp_backup_resp.get("msg"))
    backup_list = desp_backup_resp["data"]["ret_set"]
    disk_uuid_list = []
    for backup in backup_list:
        disk_uuid_list.append(backup.get("volume_id"))

    total_data = filter_needed_disk_info(disk_list, disk_uuid_list, disks)
    ret_set = total_data[start:end]
    total_count = len(total_data)
    total_page = (total_count + limit - 1) / limit
    return console_response(0,
                            "Success",
                            total_count,
                            ret_set,
                            total_page=total_page)