def restore_disk_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 = DiskBackupModel.get_backup_by_id(backup_id=backup_id) backup_uuid = backup_info.uuid if resource_id is not None: try: resource_uuid = DisksModel.get_disk_by_id(disk_id=resource_id).uuid except Exception: error_info = "cannot find disk with disk_id " + resource_id return console_response(BackupErrorCode.RESTORE_RESOURCE_NOT_FOUND, error_info) else: payload.update({ "action": "DescribeDiskBackup", "backup_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_DISK_NOT_FOUND, "the disk related to the backup cannot " "be found, may be it has already " "been deleted") resource_uuid = resp["data"]["ret_set"][0]["volume_id"] zone_record = ZoneModel.get_zone_by_name(payload["zone"]) resource_record = DisksModel.get_disk_by_uuid(resource_uuid, zone_record) if resource_record: resource_id = resource_record.disk_id payload.update({ "action": action, "version": version, "disk_uuid": resource_uuid, "backup_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 # source_backup_id is for record return console_response(code, msg, 1, [{ "disk_id": resource_id, "backup_id": backup_id }], {"source_backup_id": resource_id})
def describe_routers(payload): """ List routers by user 是否开启公网网关字段,通过返回值中是否含有ip_address字段判断 :param payload: :return: """ resp = api.get(payload=payload) # call api # get all subnet to save time payload_net = { "action": "DescribeNets", "owner": payload.get("owner"), "zone": payload.get("zone") } resp_net = api.get(payload=payload_net) if resp.get("code") == 0 and resp_net.get("code") == 0: router_set = resp.get("data", {}).get("ret_set", []) net_set = resp_net.get("data", {}).get("ret_set", []) # router_list = [] # total_count = 0 # for router in router_set: # if router.get("router") is not None: # router = router["router"] # router_id = router["name"] # # try: # rtr = RoutersModel.get_router_by_id(router_id=router_id) # if rtr: # router.update({"router_name": rtr.name}) # router.update({"create_datetime": datetime_to_timestamp(rtr.create_datetime)}) # # router_list.append(router) # total_count += 1 # # except Exception: # pass resp["data"]["ret_set"] = filter_needed_router_info( router_set, net_set) # resp["data"]["ret_set"] = router_set resp["data"]["total_count"] = len(router_set) code = resp.get('code') msg = resp.get('msg', 'failed') ret_set = resp.get("data", {}).get("ret_set", []) return console_response(code=code, msg=msg, total_count=len(ret_set), ret_set=ret_set)
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})
def resize_disk(payload): """ Resize the disk """ new_size = payload["new_size"] disk_id = payload.pop("disk_id") _inst = DisksModel.get_disk_by_id(disk_id=disk_id) uuid = _inst.uuid action = payload.pop("action") version = payload.pop("version") # disk_type = _inst.disk_type # get size and volume type payload.update({ "action": "DescribeDisks", "version": version, "volume_id": uuid }) # des_resp = api.get(payload=payload, timeout=10) des_resp = api.get(payload=payload) if des_resp.get("code") != 0: logger.error("list disk info failed") return console_response(CommonErrorCode.REQUEST_API_ERROR, "get the disk information failed") old_size = 0 # disk_type = "sata" try: old_size = des_resp["data"]["ret_set"][0]["size"] # disk_type = des_resp["data"]["ret_set"][0]["volume_type"] except Exception: exp_cause = "size" if old_size == 0 else "type" logger.error("cannot find old disk" + exp_cause + " with uuid " + uuid) payload.update({"action": action, "version": version}) payload.update({"volume_id": uuid}) resp = api.get(payload=payload) if resp.get("code") == 0: DisksModel.objects.filter(disk_id=disk_id).update(disk_size=new_size) return console_response(0, "Success", 1, [{ "disk_id": disk_id, "new_size": new_size }], {"new_size": new_size}) else: return console_response(CommonErrorCode.REQUEST_API_ERROR, resp.get("msg"))
def resize_instance_confirm_impl(payload): """ Confirm Resize an instance's flavor """ if not payload: return # update instance_id instance_id = payload["instance_id"] instance_uuid = payload.pop("instance_uuid") payload.update({"instance_id": instance_uuid}) instance_type_id = payload["instance_type_id"] instance_ins = InstancesModel.get_instance_by_id(instance_id) charge_mode = instance_ins.charge_mode # call backend api # resp = api.get(payload=payload, timeout=10) resp = api.get(payload=payload) if resp["code"] != 0: logger.error("instance resize confirm failed: %s" % resp["msg"]) return # save the changes try: instance_type_ins \ = InstanceTypeModel.get_instance_type_by_id(instance_type_id) instance_ins.instance_type = instance_type_ins instance_ins.save() except Exception as exp: logger.error("unable to save the flavor changes to db") return
def get_instance_state(payload): """ Get instance vm_state and task_state from backend api :param _payload: :return: """ # Describe instances payload _payload = { "zone": payload["zone"], "owner": payload["owner"], "action": "DescribeInstance", "instance_id": payload["instance_uuid"], } # call backend api # resp = api.get(payload=_payload, timeout=10) resp = api.get(payload=_payload) if resp["code"] != 0: logger.error(resp["msg"]) return None, None task_state = resp["data"]["ret_set"][0]["OS-EXT-STS:task_state"] vm_state = resp["data"]["ret_set"][0]["OS-EXT-STS:vm_state"] return task_state, vm_state
def get_private_images(payload): resp = api.get(payload) if resp.get("code") != 0: logger.error("get_private_images failed") return [] result = [] ret_set = resp["data"].get("ret_set") for image in ret_set: tmpInfo = {} tmpInfo["create_datetime"] = image.get("create_datetime") tmpInfo["image_id"] = image.get("name") tmpInfo["image_name"] = InstanceBackupModel.get_name_by_backup_id( tmpInfo.get("image_id")) tmpInfo["platform"] = image.get("os_type") tmpInfo["size"] = image.get("min_disk") if image.get("status") == "active": tmpInfo["status"] = "available" elif image.get("status") == "queued": tmpInfo["status"] = "queued" else: tmpInfo["status"] = "error" tmpInfo["system"] = tmpInfo["image_name"] result.append(tmpInfo) return result
def delete_rds(payload): rds_id = payload["rds_id"] deleted = payload.get('deleted', False) rds_record = RdsModel.get_rds_by_id(rds_id, deleted=deleted) rds_type = rds_record.rds_type if rds_type == "ha": rds_group = rds_record.rds_group net_payload = { "zone": payload['zone'], "owner": payload['owner'], "action": "DescribeNets", "subnet_id": rds_record.net_id } resp = api.get(net_payload) net_data = resp['data']['ret_set'][0] network_uuid = net_data['network_id'] net_id = rds_record.net_id network_id = network_uuid resp = delete_rds_api(payload, rds_record.uuid, network_id, net_id) if resp.get("code") != 0: logger.error("delete_rds failed, {}".format(resp)) return console_response(RdsErrorCode.DELETE_RDS_FAILED, msg="response of osapi: {}".format(resp)) rds_records = RdsModel.get_rds_records_by_group(rds_group) for rds_record in rds_records: RdsModel.delete_rds_by_id(rds_record.rds_id) else: console_response(1, ret_msg=_(u"rds类型目前不支持")) return console_response(total_count=1, ret_set=[rds_id], action_record={"rds_ids": rds_id})
def get_instance_last_backuptime(zone, owner): """ Get instance related backup time """ payload = { "zone": zone, "owner": owner, "action": "DescribeImage", "is_system": "False" } # backup_resp = api.get(payload=payload, timeout=10) backup_resp = api.get(payload=payload) ins_to_last_backuptime = {} if backup_resp.get("code") == 0: for backup_info in backup_resp["data"]["ret_set"]: ins_uuid = backup_info.get("instance_uuid") if ins_uuid is not None: last_time = ins_to_last_backuptime.get(ins_uuid, 0) new_time = datetime_to_timestamp( backup_info.get("create_datetime")) if new_time > last_time: ins_to_last_backuptime[ins_uuid] = new_time else: logger.error("cannot get the image list") return ins_to_last_backuptime
def leave_base_net(payload): instance_id = payload.pop('instance_id') payload.update({ 'instance_id': InstancesModel.get_instance_by_id(instance_id=instance_id).uuid }) mode = 'base-net' payload.update({'mode': mode}) # call api # resp = api.get(payload=payload, timeout=10) resp = api.get(payload=payload) code = resp["code"] msg = resp["msg"] api_code = resp.get('data', {}).get("ret_code", -1) api_status = resp['api_status'] if resp["code"] != Code.OK: logger.error( "%s leave base-net error: api_ret_code (%d), api_status (%d), msg (%s)" % (instance_id, api_code, api_status, msg)) code, msg = ErrorCode.net.LEAVE_BASE_NET_FAILED, msg response = console_response(code=code, msg=msg) else: code, msg = Code.OK, "succ" response = console_response(code=code, msg=msg) return response
def join_base_net(payload): instance_id = payload.pop('instance_id') payload.update({ 'instance_id': InstancesModel.get_instance_by_id(instance_id=instance_id).uuid }) mode = 'base-net' payload.update({'mode': mode}) # flag indicate the instance has not join public net flag = has_joined_ext_network(instance_id) if flag: return console_response(code=ErrorCode.net.JOIN_PUBLIC_NET_CONFLICT, msg=_(u"%s has joined public net or base-net" % instance_id)) # call api # resp = api.get(payload=payload, timeout=10) resp = api.get(payload=payload) code = resp["code"] msg = resp["msg"] api_code = resp.get('data', {}).get("ret_code", -1) api_status = resp['api_status'] if code != Code.OK: logger.error( "%s join base-net error: api_ret_code (%d), api_status (%d), msg (%s)" % (instance_id, api_code, api_status, msg)) code, msg = ErrorCode.net.JOIN_BASE_NET_FAILED, msg response = console_response(code=code, msg=msg) else: code, msg = Code.OK, "succ" response = console_response(code=code, msg=msg) return response
def describe_net_instances(payload): """ Describe net instances """ NetsModel.update_nets_model() net_id = payload.pop("net_id", None) inst = NetsModel.get_net_by_id(net_id) uuid = inst.uuid payload.update({"subnet_id": uuid}) # call api # resp = api.get(payload=payload, timeout=10) resp = api.get(payload=payload) code = resp["code"] msg = resp["msg"] api_code = resp["data"].get('ret_code', -1) if code != 0: code = convert_api_code(api_code) return console_response(code=code, msg=msg) instance_set = resp["data"].get("ret_set", []) instance_list = [] for n in instance_set: instance_list.append(n) resp["data"]["ret_set"] = instance_list resp["data"]["total_count"] = len(resp["data"]["ret_set"]) return console_response(code=Code.OK, total_count=len(instance_set), ret_set=instance_set)
def describe_net_by_name(subnet_name, owner, zone): """ 根据子网名称查询 :param subnet_name: :return: """ action = "DescribeNets" payload = { "action": action, "subnet_name": subnet_name, "owner": owner, "zone": zone } resp = api.get(payload=payload) data = resp.get("data") code = data.get("ret_code") total = data.get("total_count") net_info = data.get("ret_set") if code: logger.error("describe net by name error, reason is %s", net_info) return None elif not total: logger.debug("has no subnet named %s", subnet_name) return None net_info = net_info[0] subnet_id = net_info.get("id") network_id = net_info.get("network_id") search_for_net = [{"id": subnet_id, "network_id": network_id}] return search_for_net
def delete_disk(payload): """ Delete disk from db and backend """ disk_id_list = payload.pop("disk_id") action = payload.pop("action") version = payload.pop("version") results = dict.fromkeys(disk_id_list) code = 0 msg = "Success" for disk_id in disk_id_list: _inst = DisksModel.objects.get(disk_id=disk_id) attach_instance = _inst.attach_instance if not attach_instance: uuid = _inst.uuid payload.update({"volume_id": uuid}) payload.update({"action": action}) payload.update({"version": version}) resp = api.get(payload=payload) results[disk_id] = "succ" if resp["code"] == 0 else resp["msg"] if resp["code"] == 0: DisksModel.delete_disk(disk_id) else: code = 1 msg = u'{}绑定了主机{}不能删除'.format(disk_id, attach_instance) break success_list = [] for k, v in results.items(): if v == "succ": success_list.append(k) else: code = DiskErrorCode.DELETE_DISK_FAILED msg = v return console_response(code, msg, len(success_list), success_list)
def get_joinable_nets_for_instance(payload, instance_id): payload.update({"action": "DescribeNets"}) # describe_net_resp = api.get(payload=payload, timeout=10) describe_net_resp = api.get(payload=payload) if describe_net_resp.get("code") != 0: return console_response(CommonErrorCode.REQUEST_API_ERROR, describe_net_resp.get("msg")) nets_info = [] if describe_net_resp["data"]["total_count"] > 0: nets_info = describe_net_resp["data"]["ret_set"] # try: # instance = InstancesModel.get_instance_by_id(instance_id) # except Exception as exp: # return Response(console_response(InstanceErrorCode.INSTANCE_NOT_FOUND, str(exp)), # status=status.HTTP_200_OK) payload.update({"action": "DescribeInstance", "instance_id": instance_id}) describe_instance_resp = describe_instances(payload) if describe_net_resp.get("code") != 0: return console_response(CommonErrorCode.REQUEST_API_ERROR, describe_instance_resp.get("msg")) joint_nets = [] if describe_instance_resp.get("total_count") > 0: joint_nets = describe_instance_resp.get("ret_set", {})[0].get("nets", []) joint_nets_ids = [] joint_ext_net = False for joint_net in joint_nets: joint_nets_ids.append(joint_net.get("net_id")) if not joint_ext_net and joint_net.get("net_type") == "public": joint_ext_net = True joinable_nets_cr = get_joinable_nets(nets_info, joint_nets_ids, joint_ext_net) return joinable_nets_cr
def create_security_group(payload): """ Create security group """ name = payload.pop("name") # description = payload.pop("description") sg_id = make_security_group_id() payload.update({"sg_id": sg_id}) payload.update({"name": sg_id}) payload.update({"description": " "}) create_status = {} _code = 0 # resp = api.get(payload, timeout=10) resp = api.get(payload) payload.update({"description": name}) if resp.get("code") != 0: create_status[sg_id] = resp.get("msg") # _code = resp.get("code") _code = SecurityErrorCode.CREATE_SECURITY_GROUP_FAILED return console_response(_code, resp.get("msg")) else: _security_group_info = resp["data"]["ret_set"][0] _security_group_info.update({"name": name}) current_time = get_current_time() _security_group_info.update({"create_time": current_time}) create_status[sg_id] = _security_group_info payload.update({"name": name}) _security_group, err = save_security_group(resp, payload) if err is not None: create_status[sg_id] = str(err) return console_response( SecurityErrorCode.SAVE_SECURITY_GROUP_FAILED, str(err)) return console_response(_code, "Success", 1, [sg_id])
def get_used_subnets(self, request): pub_net = 0 pri_net = 0 payload = Payload( request=request, action='DescribeNets', simple=1, ) resp = api.get(payload=payload.dumps()) code = resp["code"] msg = resp.get("msg", '') api_code = resp.get("ret_code", -1) api_status = resp['api_status'] if code != 0: logger.error( "ResourceInfo DescribeNets error: api_ret_code (%d), api_status (%d), msg (%s)" % (api_code, api_status, msg)) return pub_net, pri_net net_set = resp["data"].get("ret_set", []) logger.debug("ResourceInfo DescribeNets: %s" % net_set) if net_set: net_set = net_set[0].get('subnets', []) for item in net_set: if item.get("gateway_ip"): pub_net += 1 else: pri_net += 1 logger.info("ResourceInfo pub_net:%s pri_net:%s" % (pub_net, pri_net)) return pub_net, pri_net
def refresh_event(owner, zone): remainder_count = 500 alarm_list = RiskVulneraModel.get_all_risk_vulnera(zone) alarm_list = filter(lambda x: check_last_time(x.gen_time), alarm_list) for alarm in alarm_list: alarm.is_deleted = True alarm.save() while remainder_count != 0: payload = { 'action': 'SafedogQueryAlarm', 'owner': owner, 'record_count': 500, 'zone': zone, 'region': 'bj' } resp = api.get(payload) logger.info("SafedogQueryAlarm->"+json.dumps(resp)) data = resp['data']['ret_set'] if data: data = data[0] else: break remainder_count = data['count'] if len(data['list']) == 0: break alarm_list = data['list'] for alarm in alarm_list: process_alarm_info(owner, zone, alarm) return []
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
def describe_router_samples(payload): resp = api.get(payload=payload) # call api if resp.get("code") != 0: return [] backend_routers = resp["data"].get("ret_set", []) routers = [] for router in backend_routers: if 'router' in router: router = router['router'] routers.append(router) for router in routers: status = router.pop('admin_state_up', None) router['status'] = u'运行中' if status else u'关机中' nets = router.pop('subnets', []) router['subnet_count'] = len(nets) router.pop('create_datetime', None) router.pop('ha', None) router.pop('distributed', None) return routers
def clone_disk(payload): disk_id = payload.get('disk_id') disk_obj = DisksModel.get_disk_by_id(disk_id) disk_size = disk_obj.disk_size disk_type = disk_obj.disk_type clone_disk_id = make_disk_id() disk_name = payload.pop('disk_name') availability_zone = disk_obj.availability_zone payload['size'] = disk_size payload['name'] = clone_disk_id payload['source_volid'] = disk_obj.uuid resp = api.get(payload=payload) code = 0 msg = 'succ' if resp["code"] != 0: msg = resp['msg'] return console_response(code, msg) ret_set = resp['data']['ret_set'][0] clone_disk_obj, err = save_disk(uuid=ret_set.get('id'), disk_name=disk_name, disk_id=clone_disk_id, zone=payload.get('zone'), owner=payload.get('owner'), disk_size=disk_size, disk_type=disk_type, availability_zone=availability_zone) if err is not None: logger.error("Save disk error where clone disk, %s" % str(err)) return console_response(code, msg, total_count=1, ret_set=ret_set)
def detach_keypair_impl(payload): """ Detach keypair """ instances = payload.pop("instances") ret_set = [] succ_num = 0 ret_code, ret_msg = 0, "succ" for instance_id in instances: instance_uuid = InstancesModel.get_instance_by_id(instance_id).uuid payload["server"] = instance_uuid _payload = deepcopy(payload) # call backend api # resp = api.get(payload=_payload, timeout=60) resp = api.get(payload=_payload) if resp["code"] != 0: ret_code = CommonErrorCode.REQUEST_API_ERROR ret_msg = resp["msg"] continue ret_set.append(instance_id) succ_num += 1 return console_response(ret_code, ret_msg, succ_num, ret_set)
def create_cluster(name, cluster_type, owner, zone, vm_type, available_zone): cluster_id = '%s-%s' % (CLUSTER_ID_PREFIX, get_random_string(settings.NAME_ID_LENGTH)) if cluster_type == 'lc': size = 3 elif cluster_type == 'mc': size = 5 elif cluster_type == 'hc': size = 10 else: size = 3 cluster, status = ClusterModel.objects.create(owner, zone, cluster_id, name, size) payload = dict(zone=zone, owner=owner, cluster_id=cluster.cluster_id, size=size, vm_type=vm_type, available_zone=available_zone, action='containerCreatecluster') ret = api.get(payload) logger.debug(ret) if 0 != ret['code'] or 0 != ret['data']['ret_code']: return console_response(1, 'backend error') cluster.status = True cluster.cluster_uuid = ret['data']['ret_set'] cluster.save() return console_response(ret_set={'cluster_id': cluster_id})
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
def delete_keypairs(payload): """ Delete keypairs from db and backend """ keypairs = payload.pop("keypairs") owner = payload["owner"] zone = payload["zone"] ret_set = [] succ_num = 0 ret_code, ret_msg = 0, "succ" for keypair_id in keypairs: _payload = deepcopy(payload) _payload["name"] = keypair_id # detach async detach_keypair_from_instances.apply_async((zone, owner, keypair_id), ) ############### # call backend api # resp = api.get(payload=_payload, timeout=10) resp = api.get(payload=_payload) if resp["code"] != 0: ret_code = CommonErrorCode.REQUEST_API_ERROR ret_msg = resp["msg"] continue # delete from db if succeed KeypairsModel.delete_keypair(keypair_id) ret_set.append(keypair_id) succ_num += 1 return console_response(ret_code, ret_msg, succ_num, ret_set)
def create_disk_to_restore(payload, disk_name, backup_id, pool_name): backup_record = DiskBackupModel.get_backup_by_id(backup_id) backup_uuid = backup_record.uuid payload.update({"action": "DescribeDiskBackup", "backup_id": backup_uuid}) # bak_resp = api.get(payload=payload, timeout=10) bak_resp = api.get(payload=payload) if bak_resp.get("code") == 0: if bak_resp["data"]["total_count"] < 1: return console_response(BackupErrorCode.BACKUP_NOT_FOUND, "didn't found backup with id " + backup_id) else: backup_ins = bak_resp["data"]["ret_set"][0] size = backup_ins.get("size") # 以前使用description存储硬盘类型(现在已经改为将该信息存储在数据库中) # disk_type = backup_ins.get("description") disk_type = pool_name payload.update({ "action": "CreateDisk", "disk_name": disk_name, "count": 1, "size": size, "disk_type": disk_type }) disk_resp = create_disks(payload) return disk_resp else: return console_response(CommonErrorCode.REQUEST_API_ERROR, bak_resp.get("msg"))
def construct_rds_resp(raw_rds_info, **kwargs): uuid = raw_rds_info.get("id") zone = kwargs.get("zone") owner = kwargs.get("owner") deleted = kwargs.get('deleted', False) rds_info = {} rds_record = RdsModel.get_rds_by_uuid(uuid, zone, deleted=deleted) logger.info('RDS: %s', rds_record) if not rds_record or not rds_record.visible: return None iops_record = RdsIOPSModel.get_iops_by_flavor_and_volume_type( rds_record.volume_type, rds_record.flavor.flavor_id) volume_size = rds_record.volume_size volume_usage = float(raw_rds_info.get("volume_used") or 0) / volume_size if volume_usage and volume_usage > 0: volume_usage = str(round(volume_usage * 100, 2)) + "%" else: volume_usage = 0 rds_info.update({"rds_id": rds_record.rds_id, "rds_name": rds_record.rds_name, "status": raw_rds_info.get("status"), "db_type": rds_record.db_version.db_type, "db_version": rds_record.db_version.db_version, "volume_size": rds_record.volume_size, "volume_type": rds_record.volume_type, "ip_addr": rds_record.ip_addr, "charge_mode": rds_record.charge_mode, "IOPS": iops_record.iops, "net_id": None, "net_name": None, "config_id": None, "config_name": None, "rdsg_id": None, "rdsg_name": None, "volume_usage": volume_usage, "core": rds_record.flavor.vcpus, "memory": rds_record.flavor.memory, "create_datetime": datetime_to_timestamp(rds_record.create_datetime)}) if rds_record.net_id: net_payload = { "zone": zone, "owner": owner, "action": "DescribeNets", "subnet_id": rds_record.net_id } resp = api.get(net_payload) import simplejson logger.error(simplejson.dumps(resp, indent=2)) net_data = resp['data']['ret_set'][0] subnet_name = net_data['name'] subnet_id = net_data['id'] rds_info.update({"net_id": subnet_id, "net_name": subnet_name}) if rds_record.config: rds_info.update({"config_id": rds_record.config.config_id, "config_name": rds_record.config.config_name}) if rds_record.sg: rds_info.update({"rdsg_id": rds_record.sg.sg_id, "rdsg_name": rds_record.sg.sg_name}) return rds_info
def leave_nets(payload): """ leave net """ NetsModel.update_nets_model() instance_id = payload.pop("instance_id", []) instance_uuid = InstancesModel.get_instance_by_id( instance_id=instance_id).uuid payload.update({"instance_id": instance_uuid}) net_id_list = payload.pop("net_id_list", []) leave_status = [] succ_num = 0 for net_id in net_id_list: _payload = deepcopy(payload) inst = NetsModel.objects.get(uuid=net_id) uuid = inst.uuid _payload.update({"subnet_id": uuid}) _payload.update({ "network_id": NetworksModel.get_network_by_id(network_id=inst.network_id).uuid }) # call api # resp = api.get(payload=_payload, timeout=10) resp = api.get(payload=_payload) code = resp["code"] msg = resp["msg"] api_code = resp.get('data', {}).get("ret_code", -1) api_status = resp['api_status'] if code != Code.OK: leave_status.append({'net_id': net_id, 'msg': msg}) logger.error( "LeaveNets %s error: api_ret_code (%d), api_status (%d), msg (%s)" % (instance_id, api_code, api_status, msg)) continue leave_status.append({'net_id': net_id, 'msg': "Success"}) succ_num += 1 # judge whether instance leave all nets success if succ_num != len(net_id_list): code, msg = Code.ERROR, "error" response = console_response(code=ErrorCode.net.LEAVE_NETS_FAILED, msg=msg, total_count=len(leave_status), ret_set=leave_status) else: code, msg = Code.OK, "succ" response = console_response(code=code, msg=msg, total_count=len(leave_status), ret_set=leave_status) return response
def api_router(payload): resp = api.get(payload) code = resp.get("data").get("ret_code") if code != 0: logger.error("api_router in helper error.action : %s", payload.get("action")) return console_response(code, resp.get("msg")) ret_set = resp.get("data").get("ret_set") return console_response(code, "console_succ", len(ret_set), ret_set)
def describe_policy(cls): payload = {"zone": "policy", "action": "DescribePolicy"} resp = api.get(payload) if resp['code'] != 0: ret_code = AdminErrorCode.DESCRIBE_POLICY_FAILED logger.error("describe_policy failed: %s" % resp["msg"]) return console_response(ret_code, resp["msg"]) return resp["data"]