def move_user(self, data): group = db_api.get_group_with_first({"uuid": data['group_uuid']}) if not group: logger.error("group: %s not exist" % data['group_uuid']) return get_error_result("GroupNotExists", name='') for user in data['users']: user = db_api.get_group_user_with_first({'uuid': user['uuid']}) if not user: logger.error("user %s not exist", user['user_name']) return get_error_result("GroupUserNotExists", name=user['user_name']) if user.group_uuid == group.uuid: logger.info("user %s already in group %s, skip", user.user_name, group.name) continue try: user.group_uuid = data['group_uuid'] # 移动后,原先的跟桌面绑定关系要删除 binds = db_api.get_instance_with_all({"user_uuid": user.uuid}) for bind in binds: bind.user_uuid = '' bind.soft_update() user.soft_update() except Exception as e: logger.error("move user %s to group %s failed:%s", user.user_name, group.name, e) return get_error_result("GroupUserMoveError", user_name=user.user_name, group=group.name) logger.info("move user %s to group %s success", user.user_name, group.name) return get_error_result("Success")
def user_password_change(self, data): """ 终端用户密码修改 """ user_name = data.get("user_name", "") passwd = data.get("password", "") user = db_api.get_group_user_with_first({"user_name": user_name}) if not user: logger.error("terminal user login error: %s not exist" % user_name) return build_result("TerminalUserNotExistError") if not user.validate_password(passwd): logger.error("terminal user login error: %s password error" % user_name) return build_result("TerminalAccountError") if not user.enabled: logger.error("terminal user login error: %s is unenabled" % user_name) return build_result("TerminalUserUnenabledError") new_password = data.get("new_password", "") if not new_password: return build_result("ParamError") user.change_password(new_password) user.online = 0 user.mac = "" user.soft_update() # session.soft_delete() logger.info("terminal user %s change password success!" % user.user_name) return build_result("Success")
def person_instance_close(self, data): """ 关闭个人终端的所有桌面 """ session_id = data.get("session_id", "") session = db_api.get_group_user_session_first( {"session_id": session_id}) if not session: logger.error( "terminal user query desktop group error: %s not exist" % session_id) return build_result("TerminalUserLogout") user = db_api.get_group_user_with_first({"uuid": session.user_uuid}) if not user: logger.error( "terminal user query desktop group error: %s not exist" % session.user_uuid) return build_result("TerminalUserNotExistError") if not user.enabled: logger.error( "terminal user query desktop group error: %s is unenabled" % user.user_name) return build_result("TerminalUserUnenabledError") contraller = BaseController() random_instances = db_api.get_user_random_instance_with_all( {"user_uuid": user.uuid}) static_instances = db_api.get_instance_with_all({ "classify": constants.PERSONAL_DEKSTOP, "user_uuid": user.uuid }) for i in random_instances: desktop = i.desktop instance = i.instance # sys_restore = desktop.sys_restore if not contraller.stop_instance(instance, desktop): logger.error("terminal close personal instance fail: %s" % instance.uuid) instance.allocated = 0 desktop_uuids = list() for instance in static_instances: desktop_uuid = instance.desktop_uuid if desktop_uuid not in desktop_uuids: desktop_uuids.append(desktop_uuid) desktop_dict = dict() desktops = db_api.get_personal_desktop_all_by_uuids(desktop_uuids) for desktop in desktops: desktop_dict[desktop.uuid] = desktop for instance in static_instances: desktop = desktop_dict[instance.desktop_uuid] if not contraller.stop_instance(instance, desktop): logger.error("terminal close personal instance fail: %s" % instance.uuid) logger.info("terminal close personal instance success !!!") return build_result("Success")
def person_desktop_groups(self, data): """ 个人桌面组列表 """ session_id = data.get("session_id", "") session = db_api.get_group_user_session_first( {"session_id": session_id}) if not session: logger.error( "terminal user query desktop group error: %s not exist" % session_id) return build_result("TerminalUserLogout") user = db_api.get_group_user_with_first({"uuid": session.user_uuid}) if not user: logger.error( "terminal user query desktop group error: %s not exist" % session.user_uuid) return build_result("TerminalUserNotExistError") if not user.enabled: logger.error( "terminal user query desktop group error: %s is unenabled" % user.user_name) return build_result("TerminalUserUnenabledError") # 个人桌面组分为随机桌面组和静态桌面组 desktop_uuids = list() # 随机桌面 random_desktop_groups = db_api.get_random_desktop_with_all( {"group_uuid": user.group_uuid}) for group in random_desktop_groups: desktop_uuids.append(group.desktop_uuid) # instance_uuids = list() static_instances = db_api.get_instance_with_all( {"user_uuid": user.uuid}) for instance in static_instances: desktop_uuids.append(instance.desktop_uuid) # instances = db_api.get_instance_all_by_uuids(instance_uuids) # for instance in instances: # desktop_uuids.append(instance.desktop_uuid) desktop_groups = db_api.get_personal_desktop_all_by_uuids( desktop_uuids) _groups = list() for desktop in desktop_groups: _d = { "uuid": desktop.uuid, "name": desktop.name, "desc": desktop.template.desc, "maintenance": desktop.maintenance, "order_num": desktop.order_num, "os_type": desktop.os_type } _groups.append(_d) _groups = sorted(_groups, key=lambda _groups: _groups['order_num']) logger.info("person terminal desktop group list: %s" % _groups) return build_result("Success", _groups)
def delete_user(self, user_uuid): user = db_api.get_group_user_with_first({'uuid': user_uuid}) if not user: logger.error("user: %s not exist" % user_uuid) return get_error_result("GroupUserNotExists", name='') binds = db_api.get_instance_with_all({"user_uuid": user.uuid}) for bind in binds: bind.user_uuid = '' bind.soft_update() user.soft_delete() logger.info("delete group user %s success", user_uuid) return get_error_result("Success")
def multi_create_user(self, data): """ 如果用户名冲突,则失败计数加1 """ group = db_api.get_group_with_first({'uuid': data['group_uuid']}) if not group: logger.error("group: %s not exist", data['group_uuid']) return get_error_result("GroupNotExists", name='') success_num = 0 failed_num = 0 postfix = data['postfix'] postfix_start = data['postfix_start'] for i in range(data['user_num']): # 桌面名称是前缀加几位数字 if len(str(postfix_start)) < postfix: post = '0' * (postfix - len(str(postfix_start))) + str(postfix_start) else: post = str(postfix_start) user_name = data['prefix'] + post if db_api.get_group_user_with_first({'user_name': user_name}): logger.info( "multi create user failed, the user %s already exists", user_name) failed_num += 1 postfix_start += 1 continue user_uuid = create_uuid() user_value = { "uuid": user_uuid, "group_uuid": data['group_uuid'], "user_name": user_name, "passwd": create_md5(data['passwd']), "name": data.get('name', ''), "phone": data.get('phone', ''), "email": data.get('email', ''), "enabled": data.get('enabled', True) } postfix_start += 1 try: db_api.create_group_user(user_value) logger.info("create user:%s success", user_name) except Exception as e: logging.info("insert group user info to db failed:%s", e) failed_num += 1 postfix_start += 1 continue success_num += 1 logger.info("multi create group user success") return get_error_result("Success", { "failed_num": failed_num, "success_num": success_num })
def reset_passwd(self, user_uuid): user = db_api.get_group_user_with_first({'uuid': user_uuid}) if not user: logger.error("user %s not exist", user_uuid) return get_error_result("GroupUserNotExists", name='') try: user.passwd = create_md5("123456") user.soft_update() except Exception as e: logger.error("reset user %s passwd failed:%s", user.user_name, e) return get_error_result("GroupUserUpdateError", user_name=user.user_name) logger.info("reset user %s passwd success", user.user_name) return get_error_result("Success")
def disable_user(self, user_uuid): user = db_api.get_group_user_with_first({'uuid': user_uuid}) if not user: logger.error("user %s not exist", user_uuid) return get_error_result("GroupUserNotExists", name='') try: user.enabled = False user.soft_update() except Exception as e: logger.error("disable user %s failed:%s", user.user_name, e) return get_error_result("GroupUserDisableError", user_name=user.user_name) logger.info("disable user %s success", user.user_name) return get_error_result("Success")
def user_logout(self, data): """ 终端用户注销 """ session_id = data.get("session_id", "") session = db_api.get_group_user_session_first( {"session_id": session_id}) if not session: logger.error("terminal user logout error: %s not exist" % session_id) return build_result("Success") user = db_api.get_group_user_with_first({"uuid": session.user_uuid}) if user: logger.info("terminal user logout: %s" % user.user_name) user.online = 0 user.mac = "" user.soft_update() session.soft_delete() logger.info("terminal user logout success: %s" % session.user_uuid) return build_result("Success")
def update_user(self, data): user_uuid = data.get('uuid', '') user = db_api.get_group_user_with_first({"uuid": user_uuid}) if not user: logger.error("user: %s not exist" % user_uuid) return get_error_result("GroupUserNotExists", name='') if data['value'].get('passwd'): data['value']['passwd'] = create_md5(data['value']['passwd']) # if not data['value'].get('name'): # data['value'].pop('name') # if not data['value'].get('email'): # data['value'].pop('email') # if not data['value'].get('phone'): # data['value'].pop('phone') try: user.update(data['value']) user.soft_update() except Exception as e: logger.error("update group user:%s failed:%s", user_uuid, e) return get_error_result("GroupUserUpdateError", user_name=user.user_name) logger.info("update group user:%s success", user_uuid) return get_error_result("Success")
def wrapped_func(self, data, *args, **kwargs): session_id = data.get("session_id", "") session = db_api.get_group_user_session_first( {"session_id": session_id}) if not session: logger.error( "terminal user query desktop group error: %s not exist" % session_id) return build_result("TerminalUserLogout") user = db_api.get_group_user_with_first( {"uuid": session.user_uuid}) if not user: logger.error( "terminal user query desktop group error: %s not exist" % session.user_uuid) return build_result("TerminalUserNotExistError") if not user.enabled: logger.error( "terminal user query desktop group error: %s is unenabled" % user.user_name) return build_result("TerminalUserUnenabledError") return func(self, data)
def import_user(self, data): file = data['filepath'] enabled = data['enabled'] logger.info("begin to import user, file:%s", file) success_num = 0 failed_num = 0 book = openpyxl.load_workbook(file) ws = book.active for row in ws.iter_rows(min_row=2, max_col=6): flag = True values = dict() for cell in row: if 1 == cell.column: user_name = cell.value if not user_name: failed_num += 1 flag = False logger.error("the user_name can not be blank, skip", user_name) break user = db_api.get_group_user_with_first( {"user_name": user_name}) if user: failed_num += 1 flag = False logger.error("the user %s already exist in db, skip", user_name) break values['user_name'] = user_name elif 2 == cell.column: passwd = cell.value if not passwd: failed_num += 1 flag = False logger.error("the password can not be blank") break if len(str(passwd)) < 6 or len(str(passwd)) > 16: failed_num += 1 flag = False logger.error("the password len must between 6~16") break values['passwd'] = create_md5(cell.value) elif 3 == cell.column: group_name = cell.value group = db_api.get_group_with_first({"name": group_name}) if not group: failed_num += 1 flag = False logger.error("the group %s not exist, skip", group_name) break else: values['group_uuid'] = group.uuid elif 4 == cell.column: name = cell.value if name: values['name'] = str(name) elif 5 == cell.column: email = cell.value if email: values['email'] = str(email) elif 6 == cell.column: phone = cell.value if phone: values['phone'] = str(phone) else: break if flag: values['enabled'] = int(enabled) values['uuid'] = create_uuid() db_api.create_group_user(values) success_num += 1 return get_error_result("Success", { "failed_num": failed_num, "success_num": success_num })
def export_user(self, data): """ :param data: { "filename": "file1", "users": [ { "uuid": "", "user_name": "" } ] } :return: """ logger.info("begin to export user:%s", data) # 添加任务信息数据记录 uuid = create_uuid() task_data = { "uuid": uuid, "task_uuid": uuid, "name": constants.NAME_TYPE_MAP[6], "status": constants.TASK_RUNNING, "type": 6 } db_api.create_task_info(task_data) task_obj = db_api.get_task_info_first({"uuid": uuid}) users = data.get('users', []) filename = '%s.xlsx' % data['filename'] filepath = '/root/%s' % filename book = openpyxl.Workbook() ws = book.active ws.title = 'users' lines = list() info = ["用户名", "状态", "所属分组", "姓名", "邮箱", "电话"] lines.append(info) for user in users: user = db_api.get_group_user_with_first({'uuid': user['uuid']}) if not user: continue # return build_result("GroupUserNotExists", name=user['user_name']) if user.enabled: status = "启用" else: status = "禁用" user_info = [ user.user_name, status, user.group.name, user.email, user.phone ] lines.append(user_info) try: for line in lines: ws.append(line) book.save(filepath) except Exception as e: logger.error("write xlsx file failed:%s", e) task_obj.update({"status": constants.TASK_ERROR}) task_obj.soft_update() return get_error_result("GroupUserExportError", file=filename) node = db_api.get_controller_node() bind = SERVER_CONF.addresses.get_by_default('server_bind', '') if bind: port = bind.split(':')[-1] else: port = constants.SERVER_DEFAULT_PORT endpoint = 'http://%s:%s' % (node.ip, port) url = '%s/api/v1/group/user/download?path=%s' % (endpoint, filepath) logger.info("export user to file %s success", filename) task_obj.update({"status": constants.TASK_COMPLETE}) task_obj.soft_update() return get_error_result("Success", {"url": url})
def person_instance(self, data): """ 个人桌面的详情 """ session_id = data.get("session_id", "") desktop_uuid = data.get("desktop_uuid", "") desktop_name = data.get("desktop_name", "") auth_info = LicenseManager().get_auth_info() # 0-过期 1-宽限期 2-试用期 3-正式版 # if 0 == auth_info.get('auth_type') or (1 == auth_info.get('auth_type') and auth_info.get('delay_days', 0) == 0)\ # or (2 == auth_info.get('auth_type') and auth_info.get('expire_time', 0) == 0): if auth_info.get("auth_type", 0) == 0: return build_result("AuthExpired") if self.get_links_num() >= auth_info.get('vdi_size', 0): return build_result("AuthSizeExpired") # 判断用户的登录状态 session = db_api.get_group_user_session_first( {"session_id": session_id}) if not session: logger.error( "terminal user query desktop group error: %s not exist" % session_id) return build_result("TerminalUserLogout") user = db_api.get_group_user_with_first({"uuid": session.user_uuid}) if not user: logger.error( "terminal user query desktop group error: %s not exist" % session.user_uuid) return build_result("TerminalUserNotExistError") if not user.enabled: logger.error( "terminal user query desktop group error: %s is unenabled" % user.user_name) return build_result("TerminalUserUnenabledError") desktop_group = db_api.get_personal_desktop_with_first( {"uuid": desktop_uuid}) if not desktop_group: logger.error("person desktop not exist: %s" % desktop_uuid) return build_result("DesktopNotExist", name=desktop_name) # 查找当前用户分配的随机及静态桌面 instances = list() # 静态桌面 static_instances = db_api.get_instance_with_all( {"user_uuid": user.uuid}) for obj in static_instances: instances.append(obj) random_instances = db_api.get_user_random_instance_with_all( {"user_uuid": user.uuid}) for obj in random_instances: instances.append(obj.instance) # 查找桌面的spice链接状态 host_spice_ports = dict() current_instance = None for instance in instances: host_ip = instance.host.ip if host_ip not in host_spice_ports: host_spice_ports[host_ip] = [] if instance.spice_port: host_spice_ports[host_ip].append(str(instance.spice_port)) if instance.desktop_uuid == desktop_uuid: current_instance = instance # 获取所有个人桌面的链接状态 ret = self.get_spice_link(host_spice_ports) if current_instance: host_ip = current_instance.host.ip spice_port = current_instance.spice_port if spice_port and ret.get(host_ip, {}).get(spice_port): logger.info( "terminal user request the same instance: user %s, desktop %s", user.uuid, desktop_uuid) instance_info = current_instance.instance_base_info() instance_info.update({"os_type": desktop_group.os_type}) return build_result("Success", instance_info) else: # 如果是随机桌面,需要释放 if desktop_group.desktop_type == constants.RANDOM_DESKTOP: for _obj in random_instances: if _obj.instance_uuid == current_instance.uuid: _obj.soft_delete() break current_instance.allocated = 0 current_instance.soft_update() # 判断已链接数是否大于等于2 count = 0 for k, v in ret.items(): for i, j in v.items(): if j: count += 1 if count >= 2: logger.error("user %s person desktop instance much 2", user.uuid) return build_result("TerminalPersonalInstanceNumError") # 如果桌面组状态为维护 if desktop_group.maintenance: logger.error("person desktop is maintenance: %s", desktop_uuid) return build_result("TerminalPersonMaintenance") subnet = db_api.get_subnet_by_uuid(desktop_group.subnet_uuid) # if not subnet: # logger.error("person instance start error: not subnet %s" % desktop_group.subnet_uuid) # return build_result("TerminalPersonStartError") # 启动桌面 controller = BaseController() template = db_api.get_instance_template(desktop_group.template_uuid) sys_base, data_base = controller._get_storage_path_with_uuid( template.sys_storage, template.data_storage) if desktop_group.desktop_type == constants.RANDOM_DESKTOP: # 随机桌面 instance = db_api.get_instance_by_desktop_first_alloc(desktop_uuid) if not instance: logger.error("person desktop not instance to alloc") return build_result("TerminalPersonInstanceNotAlloc") ret = controller.create_instance(desktop_group, subnet, instance, sys_base, data_base) if ret.get('code') != 0: logger.error("person instance start error: %s", instance.uuid) return build_result("TerminalPersonStartError") # 记录数据库 instance_binds = db_api.get_user_random_instance_with_all( {"instance_uuid": instance.uuid}) # 清除其他绑定关系 for random_ins in random_instances: if random_ins.desktop_uuid == desktop_uuid: instance = random_ins.instance instance.allocated = 0 instance.terminal_mac = None instance.link_time = None instance.soft_update() random_ins.soft_delete() for random_ins in instance_binds: random_ins.soft_delete() values = { "uuid": create_uuid(), "desktop_uuid": desktop_uuid, "user_uuid": user.uuid, "instance_uuid": instance.uuid } db_api.create_user_random_instance(values) instance.allocated = 1 instance.link_time = datetime.now() instance.spice_link = 1 instance.terminal_mac = user.mac instance.soft_update() logger.info("random person instance start succes: %s", instance.uuid) else: static_instance_bind = db_api.get_instance_with_first({ "desktop_uuid": desktop_uuid, "user_uuid": user.uuid }) if not static_instance_bind: logger.error( "static person desktop not bind: desktop group %s, user %s", desktop_uuid, user.uuid) return build_result("TerminalPersonInstanceNotAlloc") instance = static_instance_bind ret = controller.create_instance(desktop_group, subnet, instance, sys_base, data_base) if ret.get('code') != 0: logger.error("person instance start error: %s", instance.uuid) return build_result("TerminalPersonStartError") logger.info("static person instance start succes: %s", instance.uuid) instance.link_time = datetime.now() instance.terminal_mac = user.mac instance.spice_link = 1 instance.soft_update() data = { "spice_host": instance.host.ip, "spice_token": instance.spice_token, "spice_port": instance.spice_port, "name": instance.name, "uuid": instance.uuid, "os_type": desktop_group.os_type } edu_instance = db_api.get_instance_first({ "terminal_mac": user.mac, "classify": constants.EDUCATION_DESKTOP, "status": constants.STATUS_ACTIVE }) if edu_instance: desktop = db_api.get_desktop_by_uuid(edu_instance.desktop_uuid) controller.stop_instance(edu_instance, desktop) return build_result("Success", data)
def user_login(self, data): """ 终端用户登录 """ user_name = data.get("user_name", "") passwd = data.get("password", "") mac = data.get("mac") if not (user_name and passwd and mac): logger.error("terminal user login error: param error %s" % data) return build_result("ParamError") user = db_api.get_group_user_with_first({"user_name": user_name}) if not user: logger.error("terminal user login error: %s not exist" % user_name) return build_result("TerminalUserNotExistError") if not user.validate_password(passwd): logger.error("terminal user login error: %s password error" % user_name) return build_result("TerminalAccountError") if not user.enabled: logger.error("terminal user login error: %s is unenabled" % user_name) return build_result("TerminalUserUnenabledError") session = db_api.get_group_user_session_first({"user_uuid": user.uuid}) if session: logger.info("terminal user login : %s session is exist" % user_name) session.soft_delete() old_mac = None if not user.mac: # 没有绑定的终端 users = db_api.get_group_user_with_all({"mac": mac}) for _user in users: session = db_api.get_group_user_session_first( {"user_uuid": _user.uuid}) if session: session.soft_delete() else: if user.mac != mac: old_mac = user.mac try: session_id = create_md5(str(time.time())) expire_time = datetime.now() + timedelta(hours=2) values = { "session_id": session_id, "user_uuid": user.uuid, "expire_time": expire_time } db_api.create_group_user_session(values) users = db_api.get_group_user_with_all({"mac": mac}) for old_user in users: old_user.mac = '' user.online = 1 user.mac = mac user.soft_update() except Exception as e: logger.error("terminal user login fail: %s" % user_name, exc_info=True) return build_result("SystemError") user_info = user.to_json() user_info["session_id"] = session_id user_info["expire_time"] = expire_time.strftime("%Y-%m-%d %H:%M:%S") if old_mac: user_info["old_mac"] = old_mac logger.info("terminal user login success: %s" % user.to_json()) return build_result("Success", user_info)