def get_facility_info(request): json_obj = [] try: client = VoyageMonitor() facilitys = api.nova.get_hypervisors_list(request) facilitys.extend(api.cinder.get_all_hosts_resources(request)) node_type_dict = {node.name: node.type for node in get_nodes(request)} nagios_host_dict = client.get_host_dict( tenant_id=request.user.tenant_id, token=request.user.token.id) nagios_host_state = client.get_host_status( tenant_id=request.user.tenant_id, token=request.user.token.id) show_set = set() i = 0 for facility in facilitys: if i < 5: instance_name = facility.hypervisor_hostname if instance_name not in show_set: show_set.add(instance_name) else: continue if instance_name not in nagios_host_dict \ or instance_name not in node_type_dict: continue memory_mb = facility.memory_mb * 1.5 memory_mb_used = facility.memory_mb_used memory_mb_per = int((memory_mb_used * 100) / memory_mb) instance_online = getattr(facility, 'num_vm_active', 0) num_instances = getattr(facility, 'num_instances', 0) cpu_use = facility.cpu_usage if nagios_host_dict and nagios_host_state: host_state = nagios_host_state[ nagios_host_dict[instance_name]] else: host_state = "offline" facility_obj = {"instance_name": instance_name, "memory_mb_per": memory_mb_per, "instance_online": instance_online, "instance_offline": num_instances - instance_online, "host_type": get_text( node_type_dict[instance_name]), "host_state": get_text(host_state), "cpu_use": cpu_use} json_obj.append(facility_obj) i += 1 return HttpResponse(jsonutils.dumps(json_obj)) except Unauthorized: raise except Exception, e: LOG.error('Can not get hypervisors list , error is %s' % e) return HttpResponse('Not Found')
def associate_ip_action(request, ip_id): """ :param request:request object,ip_id :return:view<'virtual_address_manage/index_ip.html'> """ form = AssociateIPForm(request, ip_id, request.POST) if form.is_valid(): data = form.cleaned_data instance_old = api.server_get(request, data['instance_id']) try: q_instance_id = data['instance_id'] if q_instance_id: target_id = api.network.floating_ip_target_get_by_instance( request, q_instance_id) api.network.floating_ip_associate(request, ip_id, target_id) msg = get_text('Successfully associated Floating IP %(ip)s with Instance: %(inst)s') \ % {"ip": data['floating_ip'], "inst": data['instance_id']} except Unauthorized: raise except Exception, exe: if exe.message.find( 'fixed IP already has a floating IP on external network' ) != -1: msg = get_text('Error associated Floating IP %(ip)s with Instance %(inst)s, as that the instance already has a floating IP.')\ % {"ip": data['floating_ip'], "inst": getattr(instance_old , 'name' , 'unknown')} else: msg = get_text('Error associated Floating IP %(ip)s with Instance %(inst)s, please create a router with external interfaces for the subnet that the instance was in.') \ % {"ip": data['floating_ip'], "inst": getattr(instance_old , 'name' , 'unknown')} LOG.error( 'Error associated Floating IP %(ip)s with Instance %(inst)s .The error is %(e)s' % { "ip": data['floating_ip'], "inst": getattr(instance_old, 'name', 'unknown'), "e": exe.message }) return HttpResponse( { "message": msg, "statusCode": UI_RESPONSE_DWZ_ERROR }, status=UI_RESPONSE_ERROR) return HttpResponse( { "message": msg, "statusCode": UI_RESPONSE_DWZ_SUCCESS, "object_name": (' Floating IP %(ip)s Instance %(inst)s') % { "ip": data['floating_ip'], "inst": getattr(instance_old, 'name', 'unknown') } }, status=UI_RESPONSE_DWZ_SUCCESS)
def ui_response(form=None, message="Unknown", status_code="300", object_name=""): if form: if form.errors: return run_json(message=form.errors.as_text()) else: return run_json(status_code="200", message=get_text(message), object_name=object_name) return run_json(status_code=status_code, message=get_text(message), object_name=object_name)
def update_threshold_strategy(request): """ Modify an existing threshold. :param request: :param thresholds_id: :return: """ if request.is_ajax(): post = request.POST.copy() new_strategy = post.get('new_strategy', None) if not new_strategy: LOG.error('Invalid request data.') return HttpResponse(content=get_text('Invalid request data.'), status=UI_RESPONSE_BADREQUEST) else: client = VoyageClient() try: strategies = client.get_all_os_strategy(request.user.tenant_id, request.user.token.id)[ 'strategies'] except Exception, e: LOG.error('Failed to get os-strategy, reason: %s' % (e)) msg = get_text('Failed to get strategy, ' 'please make sure the voyage server is running.') return HttpResponse(content=msg, status=UI_RESPONSE_ERROR) else: old_id = None available_ids = [] for data in strategies: if not old_id and data['enable'] == 1: old_id = data['strategy_id'] if str(data['strategy_id']) not in available_ids: available_ids.append(str(data['strategy_id'])) if new_strategy not in available_ids: LOG.error('Invalid request data.') return HttpResponse(content=get_text('Invalid request data.'), status=UI_RESPONSE_BADREQUEST) data = { "old_id": old_id, "set_strategy": { "newid": int(new_strategy) } } try: client.update_os_strategy(request.user.tenant_id, request.user.token.id, data) except Exception, e: LOG.error("Fail to update stragety, reason: %s" % (e)) return HttpResponse(content=get_text("Fail to update stragety."), status=UI_RESPONSE_ERROR)
def create_volume_snapshot(request): snapshot_form = CreateVolumeSnapshot(request.POST.copy()) msg = "Create Volume Snapshot Failed!" _status_code = UI_RESPONSE_DWZ_ERROR snapshot_name = '' if snapshot_form.is_valid(): data = snapshot_form.cleaned_data snapshot_name = data['name'] try: tenant_id = data['tenant_id'] if switch_tenants(request, tenant_id) is not None: api.volume_snapshot_create(request, data['volume_id'], snapshot_name, data['description']) _status_code = UI_RESPONSE_DWZ_SUCCESS msg = "Create Volume Snapshot Successfully!" except Unauthorized: raise except LicenseForbidden: raise except Exception, ex: LOG.error("create volume snapshot %s" % ex) if ex.message.count( "'NoneType' object has no attribute 'iteritems'") > 0: msg = get_text( "Not enough server resources,Volume Snapshot %s has been created failed!" ) % snapshot_name
def create_port_action(request, network_id): """ :param request:request object, network_id :return:view<'virtual_network_manage/networkprojectindex.html'>::action for create a port """ form = CreatePort(request.POST) if form.is_valid(): data = form.cleaned_data try: network = api.quantum.network_get(request, network_id) data['tenant_id'] = network.tenant_id data['admin_state_up'] = data['admin_state'] del data['admin_state'] api.quantum.port_create(request, **data) except Unauthorized: raise except Exception as exe: msg = get_text('Failed to create a port for network %s')\ % data['network_name'] LOG.error('Failed to create port,the error is %s' % exe.message) return HttpResponse(jsonutils.dumps(ui_response(message = msg))) return HttpResponse({"message" : "Create port successfully!", "statusCode" : UI_RESPONSE_DWZ_SUCCESS , "object_name" : data['name']}, status = UI_RESPONSE_DWZ_SUCCESS) else: return HttpResponse({"form":form, "message":"", "statusCode":UI_RESPONSE_DWZ_ERROR }, status = UI_RESPONSE_ERROR)
def edit_network_action(request, tenant_id, network_id): """ :param request:request object, tenant_id, network_id :return:view<'virtual_network_manage/networkprojectindex.html'>::edit actin for a network info """ form = UpdateNetwork(request, tenant_id,network_id,request.POST) if form.is_valid(): data = form.cleaned_data switch_tenants(request, tenant_id) try: params = {'name': data['name'], 'admin_state_up': data['admin_state'], 'shared': data['shared'], 'router:external': data['external']} api.quantum.network_modify(request, network_id, **params) except Unauthorized: raise except Exception , exe: msg = 'Failed to Update network' LOG.error("Failed to Update network,the error is %s" % exe.message) return HttpResponse({"message":msg, "statusCode":UI_RESPONSE_DWZ_ERROR}, status = UI_RESPONSE_ERROR) msg = get_text('Update network successfully!') return HttpResponse({"message":msg, "statusCode":UI_RESPONSE_DWZ_SUCCESS , "object_name":data['name']}, status = UI_RESPONSE_DWZ_SUCCESS)
def delete_network_action(request, tenant_id, network_id): """ :param request:request object, tenant_id, network_id :return:view<'virtual_network_manage/networkprojectindex.html'>::delete action of network """ try: switch_tenants(request, tenant_id) network = api.quantum.network_get(request, network_id) api.quantum.network_delete(request, network_id) except Unauthorized: raise except Exception, exe: if exe.message.find( 'There are one or more ports still in use on the network' ) != -1: msg = get_text( 'Error! There are one or more ports still in use on the network.' ) else: msg = 'Unable to delete network.' LOG.error('Unable to delete network,the error is %s' % exe.message) return HttpResponse( { "message": msg, "statusCode": UI_RESPONSE_DWZ_ERROR }, status=UI_RESPONSE_ERROR)
def get_floating_ips_odd(request, tenant_id, floating_ip): """ :param request:request object,tenant_id, floating_ip :return:view<'virtual_address_manage/floatingIpsIndex_ip.html'>::list of floatingip """ float_ip = [] floating_pool = {} floating_ips = None try: if None != switch_tenants(request, tenant_id): float_ip = api.tenant_floating_ip_list(request) floating_pools = api.network.floating_ip_pools_list(request) floating_pool = SortedDict([(pool.id, pool.name) for pool in floating_pools]) for floating in float_ip: if floating.ip == floating_ip: floating_ips = floating break if floating_pool: floating_ips._apidict['pool'] = floating_pool.get( floating_ips.pool, get_text("invalid ip pool")) except Unauthorized: raise except Exception, exe: LOG.exception("ClientException in floating ip index,the error is %s" % exe.message)
def export_logs_count(request): log_lists = logs_list_same(request) log_list_len = len(log_lists) if log_list_len < 1: return HttpResponse(jsonutils.dumps( {"message": get_text('Can not export logs'), "statusCode": 300})) return HttpResponse(jsonutils.dumps({"message": '', "statusCode": 200}))
def get_floating_ips_odd(request, tenant_id, floating_ip): """ :param request:request object,tenant_id, floating_ip :return:view<'virtual_address_manage/floatingIpsIndex_ip.html'>::list of floatingip """ float_ip = [] floating_pool = {} floating_ips = None try: if None != switch_tenants(request , tenant_id): float_ip = api.tenant_floating_ip_list(request) floating_pools = api.network.floating_ip_pools_list(request) floating_pool = SortedDict([(pool.id , pool.name) for pool in floating_pools]) for floating in float_ip: if floating.ip == floating_ip: floating_ips = floating break if floating_pool: floating_ips._apidict['pool'] = floating_pool.get(floating_ips.pool, get_text("invalid ip pool")) except Unauthorized: raise except Exception , exe: LOG.exception("ClientException in floating ip index,the error is %s" % exe.message)
def export_logs_count(request): log_lists = logs_list_same(request) log_list_len = len(log_lists) if log_list_len < 1: return HttpResponse( jsonutils.dumps({ "message": get_text('Can not export logs'), "statusCode": 300 })) return HttpResponse(jsonutils.dumps({"message": '', "statusCode": 200}))
def create_image_goto_instance(request): """ :param request: request object :return view<'get_image_list OR image_template_manage/create.html'>: the corresponding view """ kwargs = {'flavor_list': Instance_Manage.views.flavor_list(request), 'keypair_list': Instance_Manage.views.keypair_list(request), 'security_group_list': security_group_list( request), 'networks': Instance_Manage.views.network_list(request), 'volume_list': Instance_Manage.views.volume_list(request)} time_zone_ins = datetime.now().utcnow() form = CreateImageAndLaunchForm(request, request.POST.copy(), **kwargs) try: ##check_can_custom_image license_custom = cache.get('CreeperQuotas').get('Is_CustomImage') ##check_image_max_num license_image_num = cache.get('CreeperQuotas').get('ImageMaxNum') ##check_can_custom_image license_instance_max_num = cache.get('CreeperQuotas').get('InstanceMaxNum') instances = api.nova.server_list(request, all_tenants=True) if len(instances) >= license_instance_max_num: raise glance_LicenseForbidden if license_custom == 0: raise glance_LicenseForbidden all_images, _more_images = api.image_list_detailed(request) image_list = [] for im in all_images: if im.properties.has_key('image_type'): if im.properties['image_type'] != 'snapshot': image_list.append(im) else: image_list.append(im) all_images = image_list if len(all_images) >= license_image_num: raise glance_LicenseForbidden except glance_LicenseForbidden: raise glance_LicenseForbidden except Exception, exc: LOG.error(exc) return HttpResponse( {"message": get_text('Found no license.'), "statusCode": UI_RESPONSE_DWZ_ERROR}, status=UI_RESPONSE_ERROR)
def toDict(self): fields = [] for field in self._meta.fields: fields.append(field.name) d = {} for attr in fields: if attr == 'action_name': try: d[attr] = reverse(getattr(self,attr)) except: d[attr] = getattr(self,attr) else: d[attr] = get_text(getattr(self,attr)) return d
def associate_ip_action(request , ip_id): """ :param request:request object,ip_id :return:view<'virtual_address_manage/index_ip.html'> """ form = AssociateIPForm(request , ip_id , request.POST) if form.is_valid(): data = form.cleaned_data instance_old = api.server_get(request , data['instance_id']) try: q_instance_id = data['instance_id'] if q_instance_id: target_id = api.network.floating_ip_target_get_by_instance( request, q_instance_id) api.network.floating_ip_associate(request , ip_id , target_id) msg = get_text('Successfully associated Floating IP %(ip)s with Instance: %(inst)s') \ % {"ip": data['floating_ip'], "inst": data['instance_id']} except Unauthorized: raise except Exception , exe: if exe.message.find('fixed IP already has a floating IP on external network') != -1: msg = get_text('Error associated Floating IP %(ip)s with Instance %(inst)s, as that the instance already has a floating IP.')\ % {"ip": data['floating_ip'], "inst": getattr(instance_old , 'name' , 'unknown')} else: msg = get_text('Error associated Floating IP %(ip)s with Instance %(inst)s, please create a router with external interfaces for the subnet that the instance was in.') \ % {"ip": data['floating_ip'], "inst": getattr(instance_old , 'name' , 'unknown')} LOG.error('Error associated Floating IP %(ip)s with Instance %(inst)s .The error is %(e)s' % {"ip": data['floating_ip'], "inst": getattr(instance_old , 'name' , 'unknown') , "e":exe.message}) return HttpResponse({"message":msg , "statusCode":UI_RESPONSE_DWZ_ERROR} , status = UI_RESPONSE_ERROR) return HttpResponse({"message":msg , "statusCode":UI_RESPONSE_DWZ_SUCCESS , "object_name":(' Floating IP %(ip)s Instance %(inst)s') % {"ip": data['floating_ip'], "inst": getattr(instance_old,'name', 'unknown')}} , status = UI_RESPONSE_DWZ_SUCCESS)
def toDict(self): fields = [] for field in self._meta.fields: fields.append(field.name) d = {} for attr in fields: if attr == 'action_name': try: d[attr] = reverse(getattr(self, attr)) except: d[attr] = getattr(self, attr) else: d[attr] = get_text(getattr(self, attr)) return d
def delete_network_action(request, tenant_id, network_id): """ :param request:request object, tenant_id, network_id :return:view<'virtual_network_manage/networkprojectindex.html'>::delete action of network """ try: switch_tenants(request, tenant_id) network = api.quantum.network_get(request, network_id) api.quantum.network_delete(request, network_id) except Unauthorized: raise except Exception , exe: if exe.message.find('There are one or more ports still in use on the network') != -1: msg = get_text('Error! There are one or more ports still in use on the network.') else: msg = 'Unable to delete network.' LOG.error('Unable to delete network,the error is %s' % exe.message) return HttpResponse({ "message":msg, "statusCode":UI_RESPONSE_DWZ_ERROR }, status = UI_RESPONSE_ERROR)
def get_floating_ips_list(request , tenant_id): """ :param request:request object,tenant_id :return:view<'virtual_address_manage/floatingIpsIndex.html'>::list of floatingIp """ args = {} floating_ips = [] floating_pool = {} floatingips = [] try: if None != switch_tenants(request , tenant_id): floating_ips = api.network.tenant_floating_ip_list(request) floating_pools = api.network.floating_ip_pools_list(request) floating_pool = SortedDict([(pool.id , pool.name) for pool in floating_pools]) for floating_ip in floating_ips: if tenant_id == floating_ip.tenant_id : floating_ip._apidict['pool'] = floating_pool.get(floating_ip.pool, get_text("invalid ip pool")) floatingips.append(floating_ip) instances = [] tenant_quota = api.nova.nova_tenant_quota_get(request , tenant_id) for item in tenant_quota: if item.name == "floating_ips": ip_num = item.limit servers = api.server_list(request) for server in servers: # to be removed when nova can support unique names server_name = server.name if any(s.id != server.id and s.name == server.name for s in servers): # duplicate instance name server_name = "%s [%s]" % (server.name, server.id) instances.append((server.id , server_name)) except Unauthorized: raise except Exception , exe: LOG.exception("ClientException in floating ip index,the error is %s " % exe.message)
def get_floating_ips_list(request, tenant_id): """ :param request:request object,tenant_id :return:view<'virtual_address_manage/floatingIpsIndex.html'>::list of floatingIp """ args = {} floating_ips = [] floating_pool = {} floatingips = [] try: if None != switch_tenants(request, tenant_id): floating_ips = api.network.tenant_floating_ip_list(request) floating_pools = api.network.floating_ip_pools_list(request) floating_pool = SortedDict([(pool.id, pool.name) for pool in floating_pools]) for floating_ip in floating_ips: if tenant_id == floating_ip.tenant_id: floating_ip._apidict['pool'] = floating_pool.get( floating_ip.pool, get_text("invalid ip pool")) floatingips.append(floating_ip) instances = [] tenant_quota = api.nova.nova_tenant_quota_get(request, tenant_id) for item in tenant_quota: if item.name == "floating_ips": ip_num = item.limit servers = api.server_list(request) for server in servers: # to be removed when nova can support unique names server_name = server.name if any(s.id != server.id and s.name == server.name for s in servers): # duplicate instance name server_name = "%s [%s]" % (server.name, server.id) instances.append((server.id, server_name)) except Unauthorized: raise except Exception, exe: LOG.exception("ClientException in floating ip index,the error is %s " % exe.message)
def delete_subnet_action(request, subnet_id): """ :param request:request object, subnet_id :return:view<'virtual_network_manage/networkprojectindex.html'>::action for delete subnet """ try: subnet = api.quantum.subnet_get(request, subnet_id) api.quantum.subnet_delete(request, subnet_id) except Unauthorized: raise except Exception as exe: if exe.message.find('One or more ports have an IP allocation from this subnet.') != -1: msg = get_text('Error! One or more ports have an IP allocation from this subnet.') else: msg = 'Unable to delete subnet.' LOG.error('Unable to delete subnet,the error is %s' % exe.message) return HttpResponse({ "message":msg, "statusCode":UI_RESPONSE_DWZ_ERROR }, status = UI_RESPONSE_ERROR) LOG.info('delete subnet successfully!') return HttpResponse({"message":"delete subnet successfully!", "statusCode":UI_RESPONSE_DWZ_SUCCESS , "object_name":getattr(subnet, 'name', 'unknown')}, status = UI_RESPONSE_DWZ_SUCCESS)
def create_port_action(request, network_id): """ :param request:request object, network_id :return:view<'virtual_network_manage/networkprojectindex.html'>::action for create a port """ form = CreatePort(request.POST) if form.is_valid(): data = form.cleaned_data try: network = api.quantum.network_get(request, network_id) data['tenant_id'] = network.tenant_id data['admin_state_up'] = data['admin_state'] del data['admin_state'] api.quantum.port_create(request, **data) except Unauthorized: raise except Exception as exe: msg = get_text('Failed to create a port for network %s')\ % data['network_name'] LOG.error('Failed to create port,the error is %s' % exe.message) return HttpResponse(jsonutils.dumps(ui_response(message=msg))) return HttpResponse( { "message": "Create port successfully!", "statusCode": UI_RESPONSE_DWZ_SUCCESS, "object_name": data['name'] }, status=UI_RESPONSE_DWZ_SUCCESS) else: return HttpResponse( { "form": form, "message": "", "statusCode": UI_RESPONSE_DWZ_ERROR }, status=UI_RESPONSE_ERROR)
def edit_network_action(request, tenant_id, network_id): """ :param request:request object, tenant_id, network_id :return:view<'virtual_network_manage/networkprojectindex.html'>::edit actin for a network info """ form = UpdateNetwork(request, tenant_id, network_id, request.POST) if form.is_valid(): data = form.cleaned_data switch_tenants(request, tenant_id) try: params = { 'name': data['name'], 'admin_state_up': data['admin_state'], 'shared': data['shared'], 'router:external': data['external'] } api.quantum.network_modify(request, network_id, **params) except Unauthorized: raise except Exception, exe: msg = 'Failed to Update network' LOG.error("Failed to Update network,the error is %s" % exe.message) return HttpResponse( { "message": msg, "statusCode": UI_RESPONSE_DWZ_ERROR }, status=UI_RESPONSE_ERROR) msg = get_text('Update network successfully!') return HttpResponse( { "message": msg, "statusCode": UI_RESPONSE_DWZ_SUCCESS, "object_name": data['name'] }, status=UI_RESPONSE_DWZ_SUCCESS)
def create_image(request): """ :param request: request object :return view<'get_image_list OR image_template_manage/create.html'>: the corresponding view """ form = CreateImageForm(request, request.POST.copy()) time_zone = datetime.now().utcnow() try: ##check_can_custom_image license_custom = cache.get('CreeperQuotas').get('Is_CustomImage') ##check_image_max_num license_image_num = cache.get('CreeperQuotas').get('ImageMaxNum') if license_custom == 0: raise glance_LicenseForbidden all_images, _more_images = api.image_list_detailed(request) image_list = [] for im in all_images: if im.properties.has_key('image_type'): if im.properties['image_type'] != 'snapshot': image_list.append(im) else: image_list.append(im) all_images = image_list if len(all_images) >= license_image_num: raise glance_LicenseForbidden except glance_LicenseForbidden: raise glance_LicenseForbidden except Exception, exc: LOG.error(exc) return HttpResponse( {"message": get_text('Found no license.'), "statusCode": UI_RESPONSE_DWZ_ERROR}, status=UI_RESPONSE_ERROR)
def delete_subnet_action(request, subnet_id): """ :param request:request object, subnet_id :return:view<'virtual_network_manage/networkprojectindex.html'>::action for delete subnet """ try: subnet = api.quantum.subnet_get(request, subnet_id) api.quantum.subnet_delete(request, subnet_id) except Unauthorized: raise except Exception as exe: if exe.message.find( 'One or more ports have an IP allocation from this subnet.' ) != -1: msg = get_text( 'Error! One or more ports have an IP allocation from this subnet.' ) else: msg = 'Unable to delete subnet.' LOG.error('Unable to delete subnet,the error is %s' % exe.message) return HttpResponse( { "message": msg, "statusCode": UI_RESPONSE_DWZ_ERROR }, status=UI_RESPONSE_ERROR) LOG.info('delete subnet successfully!') return HttpResponse( { "message": "delete subnet successfully!", "statusCode": UI_RESPONSE_DWZ_SUCCESS, "object_name": getattr(subnet, 'name', 'unknown') }, status=UI_RESPONSE_DWZ_SUCCESS)
def log_query_index(request): """ :param request: request object :return: view <'log_manage/query_index.html'> of the log list """ module_choices = [] role_name = ROLE_ADMIN log_lists = None event_choices = [('add', get_text('add')), ('edit', get_text('edit')), ('del', get_text('del')), ('login', get_text('login')), ('logout', get_text('logout'))] try: role_name = get_user_role_name(request) log_conf_info = LOG_MODULE_LIST for log_index in range(len(log_conf_info)): module_choice = (log_conf_info[log_index], get_text(log_conf_info[log_index])) if module_choices.count(module_choice) < 1: module_choices.append(module_choice) log_lists = get_log_list(request) except Unauthorized: raise except Exception, exc: LOG.error("error is %s." % exc)
def save_log(request, response, user): try: method_name = getattr(request, 'callback', None) status = response.status_code if settings.LOG_INFORMATIONS.has_key(method_name): method_info = settings.LOG_INFORMATIONS.get(method_name) module = method_info[1] type = method_info[2] desc = get_text(method_info[3]) is_primary = method_info[4] user_id = user.id if user.id else '' username = user.username if user.username else '' tenant_id = '' if hasattr(user, 'tenant_id'): if username != 'admin': tenant_id = user.tenant_id tenant_name = '' if hasattr(user, 'tenant_name'): if 'admin' == username: tenant_name = 'admin' else: tenant_name = user.tenant_name if not username and not tenant_name: # for AnonymousUser return try: content = getattr(response, 'content', None) if "" != content and content: _content = jsonutils.loads(content) object_name = None statuscode = None # _content = eval(content) if isinstance(_content, dict): object_name = _content.get('object_name', None) statuscode = _content.get('statusCode', None) if object_name: desc = '%(desc)s:%(object_name)s' % { 'desc': desc, 'object_name': object_name } if statuscode: status = statuscode if type == 'edit' and 'change_user_password_action' ==\ method_name: username = object_name except Exception, e: LOG.error("get object_name error.") create_at = datetime.now(tz=utc).strftime('%Y-%m-%d %H:%M:%S') content_time = dateutil.parser.parse(create_at) + abs( datetime.now() - datetime.utcnow()) desc = desc % { 'create_at': content_time.strftime('%Y-%m-%d %H:%M:%S'), 'user': username } log = LoggingAction(uuid=md5.new(str(datetime.now())).hexdigest(), module=module, event=type, create_at=create_at, content=desc, username=username, userid=user_id, tenant=tenant_name, tenantid=tenant_id, is_primary=is_primary, status=status) CreateLogsThread.logsq.put(log, block=False) except Exception, e: LOG.error("save logs error. %s" % e)
def export_logs_list(request): """ Export Logs for system.s :param request: :return: """ resp = HttpResponse() resp['Content-Disposition'] = 'attachment; filename=log.zip' resp['Content-Type'] = 'application/zip;' out_os = 1 try: user_agent = request.META['HTTP_USER_AGENT'] if user_agent.count("Windows") > 0: out_os = 2 elif user_agent.count("MacOs") > 0: out_os = 3 except: pass log_lists = logs_list_same(request) log_list_len = len(log_lists) log_length = divmod(log_list_len, LOG_LIST_FILE_LINES) if log_length[1] != 0: log_count = log_length[0] + 1 else: log_count = log_length[0] head_array = [ get_text('module'), get_text('event'), get_text('content'), get_text('create_at'), get_text('user_name'), get_text('tenant_name'), get_text('is_primary') ] #Windows system if out_os == 2: head_array = [ head_w.encode('GBK') + " " for head_w in head_array ] #MacOs system elif out_os == 3: head_array = [head_w + ': ' for head_w in head_array] a_file = [] st_path = "" try: if os.path.exists(settings.EXPORTS_ROOT): c_time = datetime.now().utcnow() st_path = c_time.strftime('%Y-%m-%d %X') for log_wr in range(log_count): first_wr = log_wr * LOG_LIST_FILE_LINES second_wr = (log_wr + 1) * LOG_LIST_FILE_LINES log_resource = log_lists[first_wr:second_wr] if log_count == 1: log_resource = log_lists[first_wr:log_list_len] elif log_wr == log_count - 1: log_resource = log_lists[first_wr:] created_at = datetime.now().utcnow() file_path = os.path.join(settings.EXPORTS_ROOT, str(created_at) + '.csv') a_file.append(str(created_at)) cfl = open(file_path, 'wb') wr = csv.writer(cfl, dialect='excel', quoting=csv.QUOTE_MINIMAL) wr.writerow(head_array) #by liu h for log in log_resource: content_array = [ get_text(log.module), log.event, log.content, str( dateutil.parser.parse(log.create_at) + abs(datetime.now() - datetime.utcnow()))[:16], log.username, log.tenant, log.is_primary ] #Windows system if out_os == 2: content_array = [ c_arr.encode('GBK') + " " for c_arr in content_array ] #MacOs system elif out_os == 3: content_array = [c_arr + ": " for c_arr in content_array] try: wr.writerow(content_array) except Exception, exc: LOG.error('Unable to generate csv file,%s.' % exc) cfl.close() except Exception, exc: LOG.error('Unable to open csv file path,%s.' % exc)
:return: """ client = VoyageClient() try: strategies = client.get_all_os_strategy(request.user.tenant_id, request.user.token.id) except Exception, e: LOG.error('Failed to get os-strategy, reason: %s' % (e)) raise Exception(_('Failed to get strategy, ' 'please make sure the voyage server is running.')) else: data = {} for strategy in strategies['strategies']: if strategy['strategy_name'] in data: data[strategy['strategy_name']]['title'] += \ get_text(strategy['type_name']) + ": " + \ get_text('Warning Value') + " " + \ strategy['warning'] + " " + \ get_text('Critical Value') + " " + \ strategy['critical'] + " | " else: title = get_text(strategy['type_name']) + ": " +\ get_text('Warning Value') + " " +\ strategy['warning'] + " " +\ get_text('Critical Value') + " " +\ strategy['critical'] + " | " data[strategy['strategy_name']] = {"id": strategy['strategy_id'], "enable": bool( strategy['enable']), "title": title}
def decorator(func): def _del_attributes(source, attributes): if attributes: for k in attributes: if k in source: del source[k] return source def _set_ui_element(source, args=None, url_rewrite=None): source['navTabId'] = ugettext(navTabId) if not url_rewrite: source['forwardUrl'] = reverse(forwardURL, args=args) else: source['forwardUrl'] = reverse(url_rewrite, args=args) @wraps(func) def _deco(*args, **kwargs): try: _response = func(*args, **kwargs) except Exception, e: LOG.error('invoke function error: %s' % (e)) raise e if isinstance(_response, HttpResponseRedirectBase): LOG.debug('Proxy HTTP redirect response') return _response else: # parameter ref _args = None _url_rewrite = None _content = getattr(_response, '_container', None) if isinstance(_content, dict): LOG.debug('Proxy UI response content.') # forms.Form if 'form' in _content: _form = _content['form'] _new_content = ui_response(form=_form, message=get_text( _content.get('message', 'Unknown')), status_code=_content.get( 'statusCode', '300')) _del_attributes(_content, ['form']) else: _new_content = run_json() _new_content['message'] = get_text( _content.get('message', 'Unknown')) _new_content['statusCode'] = _content.get('statusCode', '300') _args = _content.get('args', None) _url_rewrite = _content.pop('url_rewrite', None) # copy other elements to new dict _del_attributes(_content, ['message', 'statusCode', 'args']) for k, v in _content.items(): _new_content[k] = v elif isinstance(_content, BaseForm): LOG.debug('Proxy form response content.') _new_content = ui_response(form=_content) elif isinstance(_content, basestring): try: _new_content = jsonutils.load(_content) except Exception, e: return _response LOG.debug('Proxy from application/json content') else:
if volume: volume_status = getattr(volume, 'status', 'None') if volume_status == 'error_deleting': vu.volume_id = None else: if vu.volume_id == volume_id: vu.volume_id = None if other_error: volume_status = 'Failed to get state' else: volume_status = 'None' return HttpResponse( jsonutils.dumps({ "status": get_text(volume_status), "instance_id": instance_id, "volume_id": volume_id })) raise NotFound @require_GET def volume_detail(request, volume_id): """ :param request: request object :param volume_id: the volume's id :return view<'volume_manage/detail.html'>: view get_volume_detail """ try: volume = api.volume_get(request, volume_id)
raise except Exception,e: LOG.debug(e) try: api.flavor_delete(request, flavor_id) except Unauthorized: raise except Exception, e: #Fix bug 88 if e.code == UI_RESPONSE_NOTFOUND: msg = "The resource could not be found." else: msg = "Can not delete flavor!" LOG.error('Can not delete flavor,%s' % e) return HttpResponse({ "message":get_text(msg), "statusCode":UI_RESPONSE_DWZ_ERROR}, status=UI_RESPONSE_DWZ_ERROR) return HttpResponse({"message":"delete flavor success", "statusCode":UI_RESPONSE_DWZ_SUCCESS, "object_name":oldflavor.name}, status=UI_RESPONSE_DWZ_SUCCESS) def search_flavor_status(request): """ :param request: request object :return flavors list {flavor.id, flavor.disk} """
def decorator(func): def _del_attributes(source, attributes): if attributes: for k in attributes: if k in source: del source[k] return source def _set_ui_element(source, args=None, url_rewrite=None): source['navTabId'] = ugettext(navTabId) if not url_rewrite: source['forwardUrl'] = reverse(forwardURL, args=args) else: source['forwardUrl'] = reverse(url_rewrite, args=args) @wraps(func) def _deco(*args, **kwargs): try: _response = func(*args, **kwargs) except Exception, e: LOG.error('invoke function error: %s' % (e)) raise e if isinstance(_response, HttpResponseRedirectBase): LOG.debug('Proxy HTTP redirect response') return _response else: # parameter ref _args = None _url_rewrite = None _content = getattr(_response, '_container', None) if isinstance(_content, dict): LOG.debug('Proxy UI response content.') # forms.Form if 'form' in _content: _form = _content['form'] _new_content = ui_response( form=_form, message=get_text(_content.get( 'message', 'Unknown')), status_code=_content.get('statusCode', '300')) _del_attributes(_content, ['form']) else: _new_content = run_json() _new_content['message'] = get_text( _content.get('message', 'Unknown')) _new_content['statusCode'] = _content.get( 'statusCode', '300') _args = _content.get('args', None) _url_rewrite = _content.pop('url_rewrite', None) # copy other elements to new dict _del_attributes(_content, ['message', 'statusCode', 'args']) for k, v in _content.items(): _new_content[k] = v elif isinstance(_content, BaseForm): LOG.debug('Proxy form response content.') _new_content = ui_response(form=_content) elif isinstance(_content, basestring): try: _new_content = jsonutils.load(_content) except Exception, e: return _response LOG.debug('Proxy from application/json content') else:
def index_right(request, role_id): """ :param request: :param type: :return: The menu list """ role = get_user_role_name(request) if not role: return HttpResponse('Not Found') try: right_list = {} rights = Right.objects.all().order_by('key') list_key = [] b_parent = {} if role_id is not None and role_id != '' and 'None' != role_id: role_right = Role_right.objects.filter(role_id=role_id) for ro in role_right: right_list[ro.right_key] = ro.role_id for right in rights: if not right_list.has_key(right.key): if list_key.count(right.parent_id) == 0: list_key.append(right.parent_id) b_parent['parent'] = list_key right_str = '' a_parent = {} b_body = {} back_color = '#F0F3F5' num = 0 for right in rights: if right_list.has_key(right.key): check_str = "checked='checked'" else: check_str = "" check_box_all = "" if right.parent_id == -1: num += 1 if num % 2 == 0: back_color = '#e5eaee' else: back_color = '#FFFFFF' if b_parent.has_key('parent'): if b_parent['parent'].count(right.id) == 0: check_box_all = "checked='checked'" else: check_box_all = "" name = right.name if right_menus.has_key(name): name = get_text(right_menus[name]) else: name = get_text(name) a_parent[ right.id] = "<div><div id='" + right.key + "_div2' class='list_right_div_2' style='background-color:" + back_color + "'><div id='" + right.key + "_div1' class='list_right_div_1' ><div class='all_div_title' title='" + name + "'>" + name + "</div>" a_parent[ right.id] += "<input type='checkbox' style='float:left;' id='" + right.key + "_title' " + check_box_all + " value='" + right.key + "' /></div><ul id='"\ + right.key + "_ul'><li title='" + get_text( right.name) + "'><input type='checkbox' name='rights_list' id='" + right.key + "_input' value='" + right.key + "' " + check_str + " />" + get_text( right.name) + "</li>" else: if right.key in ['2002','2006']: continue name = get_text(right.name) if b_body.has_key(right.parent_id): b_body[ right.parent_id] += "<li title='" + name + "'><input type='checkbox' name='rights_list' id='" + right.key + "_input' value='" + right.key + "' " + check_str + " />" + name + "</li>" else: b_body[ right.parent_id] = "<li title='" + name + "'><input type='checkbox' name='rights_list' id='" + right.key + "_input' value='" + right.key + "' " + check_str + " />" + name + "</li>" keys_list = a_parent.keys() keys_list.sort() for c in keys_list: right_str += a_parent[c] if b_body.has_key(c): right_str += b_body[c] right_str += "</ul></div></div>" if request.is_ajax(): return HttpResponse(jsonutils.dumps(right_str)) except Exception, e: LOG.error('Can not get list of right,error is %s' % e)
def save_log(request, response, user): try: method_name = getattr(request, 'callback', None) status = response.status_code if settings.LOG_INFORMATIONS.has_key(method_name): method_info = settings.LOG_INFORMATIONS.get(method_name) module = method_info[1] type = method_info[2] desc = get_text(method_info[3]) is_primary = method_info[4] user_id = user.id if user.id else '' username = user.username if user.username else '' tenant_id = '' if hasattr(user, 'tenant_id'): if username != 'admin': tenant_id = user.tenant_id tenant_name = '' if hasattr(user, 'tenant_name'): if 'admin' == username: tenant_name = 'admin' else: tenant_name = user.tenant_name if not username and not tenant_name: # for AnonymousUser return try: content = getattr(response, 'content', None) if "" != content and content: _content = jsonutils.loads(content) object_name = None statuscode = None # _content = eval(content) if isinstance(_content, dict): object_name = _content.get('object_name', None) statuscode = _content.get('statusCode', None) if object_name: desc = '%(desc)s:%(object_name)s' % {'desc': desc, 'object_name': object_name} if statuscode: status = statuscode if type == 'edit' and 'change_user_password_action' ==\ method_name: username = object_name except Exception, e: LOG.error("get object_name error.") create_at = datetime.now(tz=utc).strftime('%Y-%m-%d %H:%M:%S') content_time = dateutil.parser.parse(create_at) + abs( datetime.now() - datetime.utcnow()) desc = desc % { 'create_at': content_time.strftime('%Y-%m-%d %H:%M:%S'), 'user': username} log = LoggingAction(uuid=md5.new(str(datetime.now())).hexdigest(), module=module, event=type, create_at=create_at, content=desc, username=username, userid=user_id, tenant=tenant_name, tenantid=tenant_id, is_primary=is_primary, status=status) CreateLogsThread.logsq.put(log, block=False) except Exception, e: LOG.error("save logs error. %s" % e)
status = UI_RESPONSE_ERROR statusCode = UI_RESPONSE_DWZ_ERROR try: if IMAGE_UTILS_INS.timeLen < time_zone_ins - IMAGE_UTILS_INS.timezone: create_instance_thread_cls = CreateInstanceThread(request, form.cleaned_data) IMAGE_UTILS_INS.threadObj = create_instance_thread_cls create_instance_thread_cls.start() except Exception, exc: LOG.error('error is %s.' % exc) status = UI_RESPONSE_ERROR statusCode = UI_RESPONSE_DWZ_ERROR if IMAGE_UTILS_INS.threadObj: IMAGE_UTILS_INS.threadObj = None object_name = form.cleaned_data['name'] + " " + get_text( "Create_at Instance Name") + form.cleaned_data['name_launch'] return HttpResponse({"message": msg, 'object_name': object_name, "statusCode": statusCode}, status=status) else: return HttpResponse( {"form": form, "message": "", "statusCode": UI_RESPONSE_DWZ_ERROR}, status=UI_RESPONSE_ERROR) class CreateImageThread(threading.Thread): objs = {} objs_locker = threading.Lock() def __init__(self, request, data): threading.Thread.__init__(self)
def export_logs_list(request): """ Export Logs for system.s :param request: :return: """ resp = HttpResponse() resp['Content-Disposition'] = 'attachment; filename=log.zip' resp['Content-Type'] = 'application/zip;' out_os = 1 try: user_agent = request.META['HTTP_USER_AGENT'] if user_agent.count("Windows") > 0: out_os = 2 elif user_agent.count("MacOs") > 0: out_os = 3 except: pass log_lists = logs_list_same(request) log_list_len = len(log_lists) log_length = divmod(log_list_len, LOG_LIST_FILE_LINES) if log_length[1] != 0: log_count = log_length[0] + 1 else: log_count = log_length[0] head_array = [get_text('module'), get_text('event'), get_text('content'), get_text('create_at'), get_text('user_name'), get_text('tenant_name'), get_text('is_primary')] #Windows system if out_os == 2: head_array = [head_w.encode('GBK') + " " for head_w in head_array] #MacOs system elif out_os == 3: head_array = [head_w + ': ' for head_w in head_array] a_file = [] st_path = "" try: if os.path.exists(settings.EXPORTS_ROOT): c_time = datetime.now().utcnow() st_path = c_time.strftime('%Y-%m-%d %X') for log_wr in range(log_count): first_wr = log_wr * LOG_LIST_FILE_LINES second_wr = (log_wr + 1) * LOG_LIST_FILE_LINES log_resource = log_lists[first_wr:second_wr] if log_count == 1: log_resource = log_lists[first_wr:log_list_len] elif log_wr == log_count - 1: log_resource = log_lists[first_wr:] created_at = datetime.now().utcnow() file_path = os.path.join(settings.EXPORTS_ROOT, str(created_at) + '.csv') a_file.append(str(created_at)) cfl = open(file_path, 'wb') wr = csv.writer(cfl, dialect='excel', quoting=csv.QUOTE_MINIMAL) wr.writerow(head_array) #by liu h for log in log_resource: content_array = [ get_text(log.module), log.event, log.content, str(dateutil.parser.parse(log.create_at) + abs( datetime.now() - datetime.utcnow()))[:16], log.username, log.tenant, log.is_primary] #Windows system if out_os == 2: content_array = [c_arr.encode('GBK') + " " for c_arr in content_array] #MacOs system elif out_os == 3: content_array = [c_arr + ": " for c_arr in content_array] try: wr.writerow(content_array) except Exception, exc: LOG.error('Unable to generate csv file,%s.' % exc) cfl.close() except Exception, exc: LOG.error('Unable to open csv file path,%s.' % exc)
def index_right(request, role_id): """ :param request: :param type: :return: The menu list """ role = get_user_role_name(request) if not role: return HttpResponse('Not Found') try: right_list = {} rights = Right.objects.all().order_by('key') list_key = [] b_parent = {} if role_id is not None and role_id != '' and 'None' != role_id: role_right = Role_right.objects.filter(role_id=role_id) for ro in role_right: right_list[ro.right_key] = ro.role_id for right in rights: if not right_list.has_key(right.key): if list_key.count(right.parent_id) == 0: list_key.append(right.parent_id) b_parent['parent'] = list_key right_str = '' a_parent = {} b_body = {} back_color = '#F0F3F5' num = 0 for right in rights: if right_list.has_key(right.key): check_str = "checked='checked'" else: check_str = "" check_box_all = "" if right.parent_id == -1: num += 1 if num % 2 == 0: back_color = '#e5eaee' else: back_color = '#FFFFFF' if b_parent.has_key('parent'): if b_parent['parent'].count(right.id) == 0: check_box_all = "checked='checked'" else: check_box_all = "" name = right.name if right_menus.has_key(name): name = get_text(right_menus[name]) else: name = get_text(name) a_parent[ right. id] = "<div><div id='" + right.key + "_div2' class='list_right_div_2' style='background-color:" + back_color + "'><div id='" + right.key + "_div1' class='list_right_div_1' ><div class='all_div_title' title='" + name + "'>" + name + "</div>" a_parent[ right.id] += "<input type='checkbox' style='float:left;' id='" + right.key + "_title' " + check_box_all + " value='" + right.key + "' /></div><ul id='"\ + right.key + "_ul'><li title='" + get_text( right.name) + "'><input type='checkbox' name='rights_list' id='" + right.key + "_input' value='" + right.key + "' " + check_str + " />" + get_text( right.name) + "</li>" else: if right.key in ['2002', '2006']: continue name = get_text(right.name) if b_body.has_key(right.parent_id): b_body[ right. parent_id] += "<li title='" + name + "'><input type='checkbox' name='rights_list' id='" + right.key + "_input' value='" + right.key + "' " + check_str + " />" + name + "</li>" else: b_body[ right. parent_id] = "<li title='" + name + "'><input type='checkbox' name='rights_list' id='" + right.key + "_input' value='" + right.key + "' " + check_str + " />" + name + "</li>" keys_list = a_parent.keys() keys_list.sort() for c in keys_list: right_str += a_parent[c] if b_body.has_key(c): right_str += b_body[c] right_str += "</ul></div></div>" if request.is_ajax(): return HttpResponse(jsonutils.dumps(right_str)) except Exception, e: LOG.error('Can not get list of right,error is %s' % e)
'set_snapshot_public', 'Instance Manage', 'edit', 'user %(user)s %(create_at)s set snapshot public', 'false' ], #instance user [ 'distribution_instance_to_user', 'Instance Manage', 'add', 'user %(user)s%(create_at)s add user to instance', 'false' ], [ 'delete_distribution', 'Instance Manage', 'del', 'user %(user)s %(create_at)s deleted user from instance', 'false' ], # instance classify [ 'select_instance_classify', 'Instance Manage', 'add', get_text('user %(user)s %(create_at)s create instance classify'), 'false' ], [ 'instance_flavor_update', 'Instance Manage', 'edit', get_text('user %(user)s %(create_at)s updated instance flavor'), 'false' ], [ 'instance_classify_update_action', 'Instance Manage', 'edit', get_text('user %(user)sr %(create_at)s update instance classify'), 'false' ], [ 'instance_classify_delete_action', 'Instance Manage', 'del', get_text('user %(user)s %(create_at)s deleted instance classify'),