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 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 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 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 create_instance_backup(payload): _backup_name = payload.pop("backup_name") # 用于前端展示的备份的名称 _resource_id = payload.pop("resource_id") _version = payload.get("version") _owner = payload.get("owner") _zone = payload.get("zone") _action = payload.get("action") charge_mode = payload.get("charge_mode") backup_id = payload["name"] instance_to_image = payload.get("instance_to_image") resource_uuid = InstancesModel.get_instance_by_id( instance_id=_resource_id).uuid cr = get_backup_instance_info(payload, resource_uuid, logger) if cr.get("ret_code") != 0: return cr image_uuid = cr["ret_set"][0]["image"].get("id", None) image_info = get_backup_instance_image_info(image_uuid, _zone, logger) platform = image_info.get("platform", 'linux') system = image_info.get("system", 'unknown system') image_name = image_info.get("image_name", system) payload.update({ "action": _action, "server": resource_uuid, "version": _version, "name": backup_id, "backup_type": "instance", "rotation": 100 }) if instance_to_image: payload.update({"image_base_type": "private_image"}) _resp = api.get(payload=payload) if _resp.get("code") == 0: uuid = _resp["data"]["ret_set"][0]["snapshot_uuid"] _inst, err = InstanceBackupModel.objects.create( zone=_zone, owner=_owner, backup_id=backup_id, system=system, backup_name=_backup_name, uuid=uuid, backup_type="instance", platform=platform, image_name=image_name, charge_mode=charge_mode) if err is not None: return console_response(BackupErrorCode.SAVE_BACKUP_FAILED, str(err)) # source_backup_id is added for record action return console_response(0, "Success", 1, [backup_id], {"source_backup_id": _resource_id}) else: return console_response(CommonErrorCode.REQUEST_API_ERROR, _resp.get("msg"))
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 get_resource_name(device_name): resource_name = device_name if device_name.startswith("d-"): resource_name = DisksModel.get_disk_by_id(device_name) elif device_name.startswith("i-"): resource_name = InstancesModel.get_instance_by_id(device_name) elif device_name.startswith("lb-"): resource_name = LoadbalancerModel.get_lb_by_id(device_name) elif device_name.startswith("lbl-"): resource_name = ListenersModel.get_lbl_by_id(device_name) elif device_name.startswith("rds-"): resource_name = RdsModel.get_rds_by_id(device_name) if isinstance(resource_name, BaseModel): resource_name = resource_name.name return resource_name
def apply_or_remove_security_group(payload): """ apply the security group to a instance, need to get ins_uuid """ ins_ids = payload.pop("resource_id") sg_ids = payload.pop("sg_id") action = payload.get("action") version = payload.get("version") result_data = {} code = 0 msg = 'Success' for ins_id in ins_ids: sg_results_succ = [] for sg_id in sg_ids: sg = SecurityGroupModel.get_security_by_id(sg_id=sg_id) sg_uuid = sg.uuid instance = InstancesModel.get_instance_by_id(instance_id=ins_id) ins_uuid = instance.uuid payload.update({"server": ins_uuid}) payload.update({"security_group": sg_uuid}) payload.update({"version": version}) payload.update({"action": action}) # resp = api.get(payload=payload, timeout=10) resp = api.get(payload=payload) if resp.get("code") != 0: code = CommonErrorCode.REQUEST_API_ERROR msg = resp.get("msg") # sg_results.update({sg_id: "failed"}) if action == "GrantSecurityGroup": logger.error("security_group with sg_id " + sg_id + " cannot apply to instance with ins_id %s" + ins_id) else: logger.error( "security_group with sg_id " + sg_id + " cannot remove from instance with ins_id %s" + ins_id) else: sg_results_succ.append(sg_id) result_data.update({ins_id: sg_results_succ}) resp = console_response(code, msg, len(result_data.keys()), [result_data]) return resp
def resize_instance_confirm(payload, try_times=0): """ Check instance resize state and confrim :param payload: :param try_times: :return: """ instance_id = payload["instance_id"] instance_inst = InstancesModel.get_instance_by_id(instance_id) charge_mode = instance_inst.charge_mode # check try times if try_times >= RESIZE_MAX_TRIES: logger.error("resize comfirm failed after %s tries" % RESIZE_MAX_TRIES) return # state task_state, vm_state = get_instance_state(payload) logger.debug("instance %s resize task_state: %s, vm_state: %s" % (instance_id, str(task_state), str(vm_state))) if vm_state != "resized": # failed if task_state is None: logger.error("[%d] instance %s resize failed" % (try_times, instance_id)) return # not finished logger.info("[%d] instance %s resized task_state %s, vm_state %s" % (try_times, instance_id, str(task_state), str(vm_state))) resize_instance_confirm.apply_async((payload, try_times + 1), countdown=RETRY_INTELVAL) return return resize_instance_confirm_impl(payload)
def start_instances(payload): instance_ids = payload.pop("instances") vm_types = payload.pop('vm_types') ret_set = [] ret_code, ret_msg = 0, "succ" for instance_id, vm_type in zip(instance_ids, vm_types): instance = InstancesModel.get_instance_by_id(instance_id, deleted=True) _payload = deepcopy(payload) if vm_type == 'POWERVM' and settings.USE_POWERVM_HMC: _payload.update({'vm_type': 'POWERVM_HMC'}) _payload["instance_id"] = instance.uuid resp = api.get(payload=_payload) if resp["code"] != 0: ret_code = CommonErrorCode.REQUEST_API_ERROR ret_msg = resp["msg"] break resp["data"].pop("action", None) ret_set.append(instance_id) return console_response(ret_code, ret_msg, len(ret_set), ret_set)
def create_loadbalancer_member(payload): zone = payload.get("zone") owner = payload.get("owner") lb_id = payload.pop("lb_id") lbl_id = payload.pop("lbl_id") instance_id = payload.pop("instance_id") # ip_address = payload.pop("ip_address") protocol_port = payload.pop("protocol_port") weight = payload.pop("weight") lb = LoadbalancerModel.get_lb_by_id(lb_id) lbl = ListenersModel.get_lbl_by_id(lbl_id) pool = lbl.pool instance = InstancesModel.get_instance_by_id(instance_id) subnet_id = lb.net_id if not lb.is_basenet else None # get member address from backend is_basenet = lb.is_basenet net_id = None if not is_basenet: net_id = lb.net_id instance_info = get_instances_info(owner, zone, is_basenet, net_id, instance_uuid=instance.uuid) if instance_info: ip_address = instance_info[0]["resource_addr"] else: msg = "%s IP addr NOT found" % instance_id logger.error(msg) return console_response( code=LoadBalancerErrorCode.INSTANCE_IP_ADDR_NOT_FOUND, msg=msg) # check address and port is legal or not if MembersModel.lbm_exists_by_address_and_port(lbl, ip_address, protocol_port): msg = "%s:%d already EXISTED" % (ip_address, protocol_port) logger.error(msg) return console_response(code=LoadBalancerErrorCode.LB_MEMBER_EXISTED, msg=msg) # wait for listener status is ACTIVE flag, err = wait_for_lb_status(payload, lb.uuid, LB_STATUS.ACTIVE) if not flag: msg = "Wait Loadbalancer Status Error" logger.error(msg) return console_response( code=LoadBalancerErrorCode.WAIT_LB_STATUS_ERROR, msg=msg) # call backend resp_create_member = create_pool_member_api(payload, pool.uuid, lb.is_basenet, ip_address, protocol_port, weight, subnet_id=subnet_id) api_code = resp_create_member.get("data", {}).get("ret_code") code = resp_create_member.get("code", -1) msg = resp_create_member.get("msg", "failed") if code != Code.OK: code = convert_api_code(api_code) return console_response(code=code, msg=msg) ret_member = resp_create_member.get("data", {}).get("ret_set", [{}])[0] if not ret_member: msg = "Create Member Error from Backend" logger.error(msg) return console_response(code=LoadBalancerErrorCode.CREATE_MEMBER_ERROR, msg=msg) member_uuid = ret_member.get("id") # save member lbm_id = make_lbm_id() lbl, err = save_lb_member(zone, owner, lbm_id, member_uuid, lbl_id, instance_id, ip_address, protocol_port, weight) if err: logger.error("Save LB Member %s from database error: %s" % (lbm_id, err)) return console_response( code=LoadBalancerErrorCode.SAVE_LB_MEMBER_ERROR, msg=str(err)) code, msg = Code.OK, "succ" return console_response(code=code, msg=msg, total_count=1, ret_set=[lbm_id])
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
def post(self, request, *args, **kwargs): form = SingleMonitorValidator(data=request.data) if not form.is_valid(): return Response(console_response(code=90001, msg=form.errors)) _data = form.validated_data ins_id = _data.get("instance_id") instance_record = InstancesModel.get_instance_by_id(instance_id=ins_id) uuid = instance_record.uuid _payload = Payload( request=request, action=None, ) _payload = _payload.dumps() resp = get_resources_info(_payload, 'Instance') ret_code = resp.get("ret_code") if ret_code is None or ret_code != 0: return Response(resp) instances = resp.get("ret_set") instance = None for ins in instances: if ins.get("id").strip() == uuid.strip(): instance = ins break if instance is None: msg = "instance with uuid " + uuid + " not found" return Response( console_response(InstanceErrorCode.INSTANCE_NOT_FOUND, msg)) data_fmt = _data.get("data_fmt") item_set = request.data.get("item_set") timestamp = _data.get("timestamp") point_num = _data.get("point_num") standard_point_num = _data.get("standard_point_num") standard_point_num = False if standard_point_num else True timestamp = get_current_timestamp() if item_set is None: item_set = get_all_item_for_single_mintor(instance) item_set = dict(item_set) post_data_list = [] post_data_item = {} name_dict = {} items = [] for k, v in item_set.items(): item_name = item_mapper.get(k) data_list = list(v) data_list, partial_name_dict = format_data_list( k, data_list, instance, _payload) name_dict.update(partial_name_dict) for item_data in data_list: item = {} item[item_name] = item_data items.append(item) post_data_item["uuid"] = uuid # 主机uuid post_data_item["item"] = items post_data_list.append(post_data_item) data_fmt_para = data_fmt if data_fmt_para == "addition_time_data": data_fmt_para = "real_time_data" _payload = Payload(request=request, action='ceilometer', timestamp=timestamp, data_fmt=data_fmt_para, data_set=post_data_list) urlparams = ["timestamp", "data_fmt"] resp = api.post(payload=_payload.dumps(), urlparams=urlparams) code = resp.get('code', 1) msg = "Success" if resp.get("code") == 0 and resp.get("data").get("ret_code") == 0: resp = format_single_response(resp, name_dict, point_num, data_fmt) code = resp.get('code') msg = resp.get('msg') else: code = CommonErrorCode.REQUEST_API_ERROR msg = resp.get('msg') ret_set = resp.get('data', {}).get('ret_set', []) resp = console_response(code=code, msg=msg, total_count=len(ret_set), ret_set=ret_set) return Response(resp)
def join_nets(payload): """ one instance join nets """ NetsModel.update_nets_model() instance_id = payload.pop("instance_id", None) 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", None) # status, error_net_id = check_join_nets_legal( # instance_id, # net_id_list, # {"owner": payload.get("owner"), "zone": payload.get("zone")} # ) # if not status: # logger.error("JoinNets error: some instance has joined the net") # return console_response(code=ErrorCode.net.JOIN_NET_DUPLICATE, # msg="%s has joined %s" % (instance_id, error_net_id)) join_status = [] succ_num = 0 for net_id in net_id_list: _payload = deepcopy(payload) inst = NetsModel.objects.get(uuid=net_id) uuid = inst.uuid net_type = inst.net_type _payload.update({"subnet_id": uuid}) network_uuid = NetworksModel.get_network_by_id( network_id=inst.network_id).uuid _payload.update({"network_id": network_uuid}) # flag indicate can do action or not flag = False if net_type == 'public': # flag indicate the instance has not join public net # judge from instance helper flag = has_joined_ext_network(instance_id) if flag: logger.error("JoinNet %s has joined public net or base-net" % instance_id) # join_status[net_id] = "failed, %s has joined public net or base-net" % instance_id join_status.append({ 'net_id': net_id, "msg": "failed, %s has joined public net or base-net" % instance_id }) continue # call api # resp = api.get(payload=_payload, timeout=10) resp = api.get(payload=_payload) msg = resp["msg"] api_code = resp.get("data", {}).get("ret_code", -1) api_status = resp.get('api_status', -1) if resp["code"] != Code.OK: # join_status[net_id] = msg logger.error( "%s join %s error: api_ret_code (%d), api_status (%d), msg (%s)" % (instance_id, net_id, api_code, api_status, msg)) join_status.append({'net_id': net_id, "msg": msg}) continue join_status.append({'net_id': net_id, "msg": "Success"}) succ_num += 1 # judge whether instance join all nets success if succ_num != len(net_id_list): code, msg = Code.ERROR, "error" response = console_response(code=ErrorCode.net.JOIN_NETS_FAILED, msg=msg, total_count=len(join_status), ret_set=join_status) else: code, msg = Code.OK, "succ" response = console_response(code=code, msg=msg, total_count=len(join_status), ret_set=join_status) return response
def modify_security_group(payload): """ apply the security group to a instance, if the instance already has a security group replace the old with the new """ version = payload.get("version") ins_ids = payload.pop("resource_id") sg_ids = payload.pop("sg_id") apply_action = "GrantSecurityGroup" remove_action = "RemoveSecurityGroup" check_instance_security_action = "DescribeSecurityGroupByInstance" version = payload.get("version") result_data = {} if len(sg_ids) > 1: return console_response( SecurityErrorCode.ONE_SECURITY_PER_INSTANCE_ERROR, "modify failed") sg_id = sg_ids[0] code = 0 msg = 'Success' for ins_id in ins_ids: sg_results_succ = [] sg = SecurityGroupModel.get_security_by_id(sg_id=sg_id) sg_uuid = sg.uuid instance = InstancesModel.get_instance_by_id(instance_id=ins_id) ins_uuid = instance.uuid payload.update({ "action": check_instance_security_action, "version": version, "server": ins_uuid }) # check_resp = api.get(payload=payload, timeout=10) check_resp = api.get(payload=payload) if check_resp.get("code") != 0: code = CommonErrorCode.REQUEST_API_ERROR msg = check_resp.get("msg") continue # if the instance already has a security group, remove it if check_resp["data"]["total_count"] > 0: old_sg_uuid = check_resp["data"]["ret_set"][0]["id"] payload.update({ "action": remove_action, "version": version, "server": ins_uuid, "security_group": old_sg_uuid }) # remove_resp = api.get(payload=payload, timeout=10) remove_resp = api.get(payload=payload) if remove_resp.get("code") != 0: logger.debug("the resp of removing the old securty group is:" + str(remove_resp)) code = CommonErrorCode.REQUEST_API_ERROR msg = remove_resp.get("msg") continue # grant the new security group to the instance payload.update({ "action": apply_action, "version": version, "server": ins_uuid, "security_group": sg_uuid }) # grant_resp = api.get(payload=payload, timeout=10) grant_resp = api.get(payload=payload) if grant_resp.get("code") != 0: logger.debug("the resp of granting the new securty group is:" + str(grant_resp)) code = CommonErrorCode.REQUEST_API_ERROR msg = grant_resp.get("msg") logger.error("security_group with sg_id " + sg_id + " cannot apply to instance with ins_id " + ins_id) else: sg_results_succ.append(sg_id) result_data.update({ins_id: sg_results_succ}) resp = console_response(code, msg, len(result_data.keys()), [result_data]) return resp
def describe_instance_backups(payload): backup_id = payload.get("backup_id", None) resource_id = payload.pop("resource_id", None) backup_status = payload.pop("status", None) owner = payload.get("owner") zone = payload.get("zone") zone_record = ZoneModel.get_zone_by_name(zone) availability_zone = payload.get('availability_zone') search_key = payload.get('search_key') instance_to_image = payload.get("instance_to_image") if backup_id is not None: try: backup_uuid = InstanceBackupModel.get_backup_by_id( backup_id=backup_id).uuid payload.update({"image_id": backup_uuid}) except Exception: err_msg = "cannot find backup whose backup id is " + backup_id return console_response(BackupErrorCode.BACKUP_NOT_FOUND, err_msg) elif resource_id is not None: try: instance_uuid = InstancesModel.get_instance_by_id( instance_id=resource_id).uuid payload.update({"instance_uuid": instance_uuid}) except Exception: err_msg = "cannot find instance uuid whose instance id is " \ + resource_id return console_response( BackupErrorCode.ASSOCIATE_INSTANCE_NOT_FOUND, err_msg) if instance_to_image: payload.pop("instance_to_image") payload.update({"private_image": "True"}) resp = api.get(payload=payload) if resp["code"] == 0: # 对镜像列表进行过滤 # 接口传入backup_id时,不对镜像进行过滤 resp_data = filter_instance_backup_info( resp["data"].get("ret_set", []), backup_status, owner, zone_record, hypervisor_type=availability_zone, filter_img=not bool(backup_id), ) if resp_data is None: return console_response( 1, "The uuid do not found, maybe the " "disk has been deleted") result_list = [] if search_key: for resp_item in resp_data: for item in resp_item.values(): if search_key in str(item): if resp_item not in result_list: result_list.append(resp_item) else: result_list = resp_data result = console_response(0, "Success", len(result_list), result_list) else: result = console_response(CommonErrorCode.REQUEST_API_ERROR, resp.get("msg")) return result