def post(self, request, *args, **kwargs): crate_user = request.user.username data = {'success': True, 'msg': u'新增成功'} username = request.data.get("username", '') email = request.data.get("email", '') is_superuser = request.data.get("is_superuser", 0) is_staff = request.data.get("is_staff", 0) group_list = request.data.getlist('group_list[]') # 获取用户关联的组信息 if not username: raise APIValidateException(u'username 不能为空') if not str(is_superuser).isdigit() or int(is_superuser) not in (0, 1): raise APIValidateException(u'is_superuser 只能为0或1') if not str(is_staff).isdigit() or int(is_staff) not in (0, 1): raise APIValidateException(u'is_staff 只能为0或1') if len(User.objects.filter(username=username)) > 0: raise APIValidateException(u'用户' + username + u'已存在') user = add_user_default_password(crate_user, username, email, is_superuser, is_staff, group_list) u = model_to_dict(user) u.pop('password') u.pop('groups') u.pop('user_permissions') u['date_joined'] = str(u['date_joined']) if u['last_login']: u['last_login'] = str(u['last_login']) self.changeLog(user.id, user.username, json.dumps(u)) return Response(data)
def get_queryset(self): queryset = Change.objects.all().order_by('-change_time') id = self.request.query_params.get('id', None) end_time = self.request.query_params.get('end_time', None) start_time = self.request.query_params.get('start_time', None) if id: id_arr = id.split(",") queryset = queryset.filter(id__in=id_arr) if end_time: try: etime_struct = time.strptime(end_time, '%Y-%m-%d %H:%M:%S') end_time = int(time.mktime(etime_struct)) queryset = queryset.filter(change_time__lt=end_time) except: raise APIValidateException(u'时间格式必须为:Y-m-d H:M:S') if start_time: try: stime_struct = time.strptime(start_time, '%Y-%m-%d %H:%M:%S') start_time = int(time.mktime(stime_struct)) queryset = queryset.filter(change_time__gte=start_time) except: raise APIValidateException(u'时间格式必须为:Y-m-d H:M:S') return queryset
def perform_create(self, serializer): network = self.request.data.get('network', '') maskint = self.request.data.get('maskint', '') gateway = self.request.data.get('gateway', '') if not check_ip(network): raise APIValidateException(u'network不是合法的ip地址') if not check_ip(gateway): raise APIValidateException(u'gateway不是合法的ip地址') if not str(network).endswith(".0"): raise APIValidateException(u'network必须以.0结尾') if not str(maskint).isdigit() or int(maskint) < 8 or int(maskint) > 32: raise APIValidateException(u'maskint必须为8到32之间的整数') current_time = int(time.time()) obj = serializer.save(ctime=current_time) json_obj = json.dumps(model_to_dict(obj)) ip_segment = obj.network + "/" + str(obj.maskint) iplist = IP(ip_segment) i = 0 for ip in iplist: i += 1 state = 'free' if str(ip).endswith(".0") or i == len(iplist) or str(ip) == str(gateway): state = 'reserve' IpAddress.objects.create(network_id=obj.id, ip=ip, ctime=current_time, state=state) self.changeLog(obj.id, obj.network, json_obj)
def post(self, request, *args, **kwargs): domain = request.data.get("domain", '') path = request.data.get("path", '') if not domain: raise APIValidateException(u'domain不能为空') if not path: raise APIValidateException(u'path不能为空') ip_list = ['1.1.1.1', '2.2.2.2'] return Response({'domain': domain, 'path': path, 'ip_list': ip_list})
def perform_destroy(self, instance): id = instance.id if id == configs.RESOURCE_POOL_ID: raise APIValidateException(u'应用 ' + instance.name + u' 为资源池,不能删除') if len(AppService.objects.filter(app_id=id)): raise APIValidateException(u'应用 ' + instance.name + u' 下还有服务,不能删除') instance.delete() AppSegment.objects.filter(app_id=id).delete() self.changeLog(id, instance.name, 'delete application: ' + instance.name)
def perform_destroy(self, instance): id = instance.id if id in (configs.FREE_VM_ID, configs.FREE_SERVER_ID): raise APIValidateException(u'服务 ' + instance.name + u' 属于资源池,不能删除') if len(ServiceHost.objects.filter(service_id=id)) > 0: raise APIValidateException(u'服务 ' + instance.name + u' 下还有设备,不能删除') instance.delete() # 删除auth_service_principals表中的数据 service_principals = ServicePrincipals.objects.filter(service_id=id) service_principals.delete() self.changeLog(instance.id, instance.name, 'delete business line: ' + instance.name)
def patch(self, request, *args, **kwargs): data = {'success': True, 'msg': u'新增成功'} username = request.user.username password = request.data.get('password') old_password = request.data.get('old_password') if not password: raise APIValidateException(u'password 不能为空') user = auth.authenticate(username=username, password=old_password) if not user: raise APIValidateException(u'旧密码不正确') user.set_password(password) user.save() self.changeLog(user.id, user.username, 'change password') return Response(data)
def delete(self, request, *args, **kwargs): id_list = request.data.getlist('id[]', []) id = request.data.get('id', '') if id: id_list = id_list + id.split(",") if len(id_list) <= 0: raise APIValidateException(u'参数id[]和id不能都为空') if len(Hosts.objects.filter(room_id__in=id_list)) > 0 or len(Rack.objects.filter(room_id__in=id_list)) > 0: raise APIValidateException('room already in use can not delete') rooms = Room.objects.filter(id__in=id_list) uid = str(uuid.uuid1()) for a in rooms: self.changeLog(a.id, a.name, 'delete room: ' + a.name, uid=uid) rooms.delete() return Response({"success": True, "msg": "succ!", "errors": []})
def delete(self, request, *args, **kwargs): # args 相当是一个集合,kwargs 相当是一个字典 id_list = request.data.getlist('id[]', []) # 获取 id 列表 id = request.data.get('id', '') # 获取 id if id: id_list = id_list + id.split(",") if len(id_list) <= 0: raise APIValidateException(u'参数id[]和id不能都为空') groups = Group.objects.filter( id__in=id_list) # 过滤出 id 在 id_list 的 menu group_name_list = [] for group in groups: # 删除相应组对应的菜单 group_name_list.append(group.name) menus = GroupMenu.objects.filter(group_id=group.id) menus.delete() groups.delete() # 删除相应的 groups # 删除 DefaultGroup 表中相应的组名 default_groups = DefaultGroup.objects.filter( group_name__in=group_name_list) if len(default_groups) > 0: default_groups.delete() uid = str(uuid.uuid1()) # 生成唯一的 id return Response({ "success": True, "msg": "succ!", "errors": [] }) # 该函数返回 Response 对象
def delete(self, request, *args, **kwargs): id_list = request.data.getlist('id[]', []) id = request.data.get('id', '') if id: id_list = id_list + id.split(",") if len(id_list) <= 0: raise APIValidateException(u'参数id[]和id不能都为空') if len(IpAddress.objects.filter(network_id__in=id_list, state='used')) > 0: raise APIValidateException(u'网段正在使用,不能删除') networks = Network.objects.filter(id__in=id_list) uid = str(uuid.uuid1()) for a in networks: self.changeLog(a.id, a.network, 'delete network: ' + a.network, uid=uid) networks.delete() IpAddress.objects.filter(network_id__in=id_list).delete() return Response({"success": True, "msg": "succ!", "errors": []})
def perform_destroy(self, instance): id = instance.id if len(IpAddress.objects.filter(network_id=id, state='used')): raise APIValidateException(u'该网段正在使用,不能删除') instance.delete() IpAddress.objects.filter(network_id=id).delete() self.changeLog(instance.id, instance.network, 'delete network: ' + instance.network)
def delete(self, request, *args, **kwargs): cuser = request.user.username id_list = request.data.getlist('id[]', []) id = request.data.get('id', '') if id: id_list = id_list + id.split(",") if len(id_list) <= 0: raise APIValidateException(u'参数id[]和id不能都为空') records = AuthRecord.objects.filter(id__in=id_list) uid = str(uuid.uuid1()) hostids = [] for a in records: hostids.append(a.host_id) host_dict = {} for h in Hosts.objects.filter(id__in=hostids): host_dict[h.id] = h for a in records: ip = '' if host_dict.has_key(a.host_id): ip = host_dict[a.host_id].ip self.changeLog(a.id, str(a.username) , 'delete auth record: ' + a.username + " " + ip + " " + a.role, uid=uid) if host_dict.has_key(a.host_id): ######################################## 删除用户在机器上的ssh key ######################################## try: DelUserKeyTask().addTask(cuser, ip=ip, role=a.role, username=a.username) except: pass ######################################## 删除用户在机器上的ssh key ######################################## records.delete() return Response({"success": True, "msg": "succ!", "errors": []})
def perform_update(self, serializer): id = self.kwargs.get('pk', '') app = App.objects.filter(id=id) oldname = '' if len(app) > 0: oldname = app[0].name obj = serializer.save() # 配置网段 AppSegment.objects.filter(app_id=obj.id).delete() # 先删除网段 segment = self.request.data.get('segment', '') if segment: for s in segment.split("\n"): maskint = get_maskint_by_segment(s) if not maskint: raise APIValidateException(u'网段不合法') AppSegment.objects.create(app_id=obj.id, segment=s) # user 相应更新 old_users = AppPrincipals.objects.filter(app_id=id) old_users.delete() # 先删除旧数据 new_principals = self.request.data.getlist('user_name[]') # 创建新负责人的数据 for principal in new_principals: AppPrincipals.objects.create(app_id=id,user_name=principal,type=2) new_sas = self.request.data.getlist('sa_name[]') # 创建新负责人的数据 for new_sa in new_sas: AppPrincipals.objects.create(app_id=id, user_name=new_sa, type=1) obj_dict = model_to_dict(obj) obj_dict['segment'] = segment.split("\n") json_obj = json.dumps(obj_dict) self.changeLog(obj.id, obj.name, json_obj)
def perform_create(self, serializer): obj = serializer.save() # 配置网段 segment = self.request.data.get('segment', '') auto = self.request.data.get('auto', '') if segment: for s in segment.split("\n"): maskint = get_maskint_by_segment(s) if not maskint: raise APIValidateException(u'网段不合法') AppSegment.objects.create(app_id=obj.id, segment=s) obj_dict = model_to_dict(obj) obj_dict['segment'] = segment.split("\n") json_obj = json.dumps(obj_dict) self.changeLog(obj.id, obj.name, json_obj) # 增添负责人信息 users = self.request.data.getlist("user_name[]", []) for user in users: AppPrincipals.objects.create(app_id=obj.id, user_name=user, type=2) # 增添负责人信息 sas = self.request.data.getlist("sa_name[]", []) for sa in sas: AppPrincipals.objects.create(app_id=obj.id, user_name=sa, type=1)
def get_queryset(self): queryset = AuthRecord.objects.filter(expiration_time__gt=int(time.time())) username = self.request.query_params.get('username', None) if not username: raise APIValidateException(u'username不能为空') queryset = queryset.filter(username=username) return queryset
def perform_update(self, serializer): id = self.kwargs.get('pk', '') # 获取id ,默认值为 '' group_menu = GroupMenu.objects.filter(id=id) # 过滤出相应 id 的菜单名 if len(group_menu) <= 0: # 没有相应菜单名 raise APIValidateException(u'没有相应的信息') # 抛异常 obj = serializer.save()
def delete(self, request, *args, **kwargs): data = {'success': True, 'msg': u'服务缩容成功'} ip = request.data.get("ip", '') service_id = request.data.get("service_id", 0) reip = re.compile(r'(?<![\.\d])(?:\d{1,3}\.){3}\d{1,3}(?![\.\d])') ip_list = [] for _ip in reip.findall(ip): ip_list.append(_ip) if len(ip_list) <= 0: raise APIValidateException(u'请传入合法ip') service = AppService.objects.filter(id=service_id) if len(service) <= 0: raise APIValidateException(u'id为' + str(service_id) + u"的服务不存在") # if len(Hosts.objects.filter(ip__in=ip_list).exclude(state='free')) > 0: # raise APIValidateException(u'只能扩容free状态的主机') resource_pool_list = (configs.FREE_VM_ID, configs.FREE_SERVER_ID) if service_id in resource_pool_list: raise APIValidateException(u'资源池不能缩容') uid = str(uuid.uuid1()) hosts = Hosts.objects.filter(ip__in=ip_list).exclude(state='deleted') hostids = [] for h in hosts: hostids.append(h.id) self.changeLog(h.id, h.ip, 'reduce from service_id ' + str(h.service_id), uid=uid, action='update') if len(ServiceHost.objects.filter(service_id=service_id, host_id__in=hostids, state='Up')) > 0: raise APIValidateException(u'存在upstream状态为Up的主机') for h in hosts: ServiceHost.objects.filter(service_id=service_id, host_id=h.id).delete() # 如果机器不属于任何服务则放入资源池中 if len(ServiceHost.objects.filter(host_id=h.id)) <= 0: sid = configs.FREE_SERVER_ID if h.type == 'server': sid = configs.FREE_SERVER_ID elif h.type == 'vm': sid = configs.FREE_VM_ID ServiceHost.objects.create(service_id=sid, host_id=h.id) Hosts.objects.filter(id=h.id).update(state='free') ############################### 更改主机名 ############################### try: autoHostName(request.user.username, h.id) except Exception, ex: pass
def delete(self, request, *args, **kwargs): id_list = request.data.getlist('id[]', []) id = request.data.get('id', '') if id: id_list = id_list + id.split(",") if len(id_list) <= 0: raise APIValidateException(u'参数id[]和id不能都为空') if len(User.objects.filter(id__in=id_list, is_superuser=1)) > 0: raise APIValidateException(u'不能删除超级管理员') userlist = User.objects.filter(id__in=id_list) uid = str(uuid.uuid1()) for a in userlist: self.changeLog(a.id, a.username, 'delete user: ' + a.username, uid=uid) userlist.delete() return Response({"success": True, "msg": "succ!", "errors": []})
def perform_update(self, serializer): id = self.kwargs.get('pk', '') # 获取主键 id name = self.request.data.get('name', '') # 获取 name groups = Group.objects.filter(id=id) # 过滤出相应 id 的组 if len(groups) <= 0: # 没有相应的业务线 raise APIValidateException(u'业务线不存在') if not name: # name 不能为空 raise APIValidateException(u'name不能为空') group = groups[0] if name != group.name: # 如果 App 中业务线的名称与传进来的名称不相符则更新 App 中的业务线的名称 App.objects.filter(group=group.name).update(group=name) # 更新 App 中业务线的名称 obj = serializer.save() obj_dict = model_to_dict(obj) # 将 model 转化为 dict(字典) json_obj = json.dumps(obj_dict) # 将 dict 对象转换为 str 形式 self.changeLog(obj.id, obj.name, json_obj)
def get_queryset(self): network_id = self.request.query_params.get('network_id', None) if not network_id: raise APIValidateException(u'network_id不能为空') queryset = IpAddress.objects.filter(network_id=network_id) id = self.request.query_params.get('id', None) if id: id_arr = id.split(",") queryset = queryset.filter(id__in=id_arr) return queryset
def delete(self, request, *args, **kwargs): # args 相当是一个集合,kwargs 相当是一个字典 id_list = request.data.getlist('id[]', []) # 获取 id 列表 id = request.data.get('id', '') # 获取 id if id: id_list = id_list + id.split(",") if len(id_list) <= 0: raise APIValidateException(u'参数id[]和id不能都为空') groups = Group.objects.filter(id__in=id_list) # 过滤出 id 在 id_list 的 groups uid = str(uuid.uuid1()) # 生成唯一的 id group_names = [] for a in groups: group_names.append(a.name) self.changeLog(a.id, a.name, 'delete group: ' + a.name, uid=uid) if len(App.objects.filter(group__in=group_names)) > 0: # 判断该组下面还有没有 App raise APIValidateException(u'业务线下还有应用,不能删除') # 抛出异常 groups.delete() # 删除相应的 groups return Response({"success": True, "msg": "succ!", "errors": []}) # 该函数返回 Response 对象
def post(self, request, *args, **kwargs): username = request.data.get('username', '') password = request.data.get('password', '') username_list = username.split('@') if len(username_list) == 1: username += '@puscene.com' status, userinfo = login_sso(username, password) username = username.split('@')[0] if not status: user = auth.authenticate(username=username, password=password) if not user or not user.is_active: raise APIValidateException(u'用户名或密码错误') else: users = User.objects.filter(username=username) if len(users) <= 0: raise APIValidateException(u'用户不存在') user = users[0] token, created = Token.objects.get_or_create(user=user) return Response({'token': token.key})
def post(self, request, *args, **kwargs): data = {'success': True, 'msg': u'服务扩容成功'} ip = request.data.get("ip", '') service_id = request.data.get("service_id", 0) reip = re.compile(r'(?<![\.\d])(?:\d{1,3}\.){3}\d{1,3}(?![\.\d])') ip_list = [] for _ip in reip.findall(ip): ip_list.append(_ip) if len(ip_list) <= 0: raise APIValidateException(u'请传入合法ip') app = AppService.objects.filter(id=service_id) if len(app) <= 0: raise APIValidateException(u'id为' + str(service_id) + u"的服务不存在") # if len(Hosts.objects.filter(ip__in=ip_list).exclude(state='free')) > 0: # raise APIValidateException(u'只能扩容free状态的主机') resource_pool_list = (configs.FREE_VM_ID, configs.FREE_SERVER_ID) if service_id in resource_pool_list: raise APIValidateException(u'资源池不能扩容') uid = str(uuid.uuid1()) hosts = Hosts.objects.filter(ip__in=ip_list).exclude(state='deleted') hostids = [] for h in hosts: hostids.append(h.id) self.changeLog(h.id, h.ip, 'change service_id from ' + str(h.service_id) + ' to ' + str(service_id), uid=uid, action='update') # 将free状态的机器改为offline(从资源池拿出来的机器) hosts.filter(state='free').update(state='offline') hosts.update(service_id=service_id) # 分配出去的机器从资源池删除 ServiceHost.objects.filter(host_id__in=hostids, service_id__in=resource_pool_list).delete() for h in hosts: if len(ServiceHost.objects.filter(service_id=service_id, host_id=h.id)) > 0: continue ServiceHost.objects.create(service_id=service_id, host_id=h.id) ############################### 更改主机名 ############################### try: autoHostName(request.user.username, h.id) except Exception, ex: pass
def post(self, request, *args, **kwargs): user = request.user email = user.email user_id = user.id data = {'success': True, 'msg': u'新增成功'} status, result = create_ssh_key(email, user_id, user.username) if not status: raise APIValidateException(result) u = model_to_dict(result) self.changeLog(user.id, user.username, json.dumps(u)) data['ssh_key'] = result.ssh_key return Response(data)
def get(self, request, *args, **kwargs): search = request.GET.get('search', None) if not search: raise APIValidateException(u'字段search不能为空') result = [] lb_ids = [] for lb in LB.objects.filter(server_name__icontains=search): lb_ids.append(lb.id) serviceids = [] for u in ServiceLB.objects.filter(lb_id__in=lb_ids): serviceids.append(u.service_id) for s in AppService.objects.filter(id__in=serviceids): result.append({ 'service_id': s.id, 'name': s.name, 'ip': '', 'host_id': 0 }) for s in AppService.objects.filter(name__icontains=search): if s.id in serviceids: continue result.append({ 'service_id': s.id, 'name': s.name, 'ip': '', 'host_id': 0 }) host_ids = [] hostid_dict = {} for h in Hosts.objects.filter( models.Q(ip__startswith=search) | models.Q(hostname__startswith=search)): host_ids.append(h.id) hostid_dict[h.id] = h if len(host_ids) > 0: service_dict = {} for s in AppService.objects.all(): service_dict[s.id] = s for sh in ServiceHost.objects.filter(host_id__in=host_ids): if not service_dict.has_key(sh.service_id): continue service_name = service_dict[sh.service_id].name result.append({ 'service_id': sh.service_id, 'name': service_name + " => " + hostid_dict[sh.host_id].ip, 'ip': hostid_dict[sh.host_id].ip, 'host_id': sh.host_id }) return Response(result)
def perform_update(self, serializer): id = self.kwargs.get('pk', '') # 获取id ,默认值为 '' menu = AppPrincipals.objects.filter(id=id) # 过滤出相应 id 的菜单名 if len(menu) <= 0: # 没有相应菜单名 raise APIValidateException(u'没有相应的信息') # 抛异常 obj = serializer.save() # 更新数据 obj_dict = model_to_dict(obj) # 写日志 json_obj = json.dumps(obj_dict) self.changeLog(obj.app_id, obj.user_name, json_obj)
def perform_create(self, serializer): app_id = self.request.data.get('app_id', 0) name = self.request.data.get('name', '') vcsRep = self.request.data.get('vcs_rep', '') auto = self.request.data.get('auto', '') type = self.request.data.get('type', '') if len(App.objects.filter(id=app_id)) <= 0: raise APIValidateException(u'应用不存在') if not name: raise APIValidateException(u'服务名称不能为空') if len(AppService.objects.filter(app_id=app_id, name=name)) > 0: raise APIValidateException(u'该应用下存在相同名称的服务') if auto == 'on' and not vcsRep: raise APIValidateException(u'vcsRep(Git仓库)不能为空') obj = serializer.save() json_obj = json.dumps(model_to_dict(obj)) self.changeLog(obj.id, obj.name, json_obj) # 添加负责人信息 principals_list = self.request.data.getlist('user_name[]',[]) for principal in principals_list: ServicePrincipals.objects.create(service_id=obj.id,user_name=principal)
def delete(self, request, *args, **kwargs): id_list = request.data.getlist('id[]', []) id = request.data.get('id', '') if id: id_list = id_list + id.split(",") if len(id_list) <= 0: raise APIValidateException(u'参数id[]和id不能都为空') if len(ServiceHost.objects.filter(service_id__in=id_list)) > 0: raise APIValidateException(u'服务下还有设备,不能删除') for id in id_list: if id in (configs.FREE_VM_ID, configs.FREE_SERVER_ID): raise APIValidateException(u'服务属于资源池,不能删除') services = AppService.objects.filter(id__in=id_list) uid = str(uuid.uuid1()) for a in services: self.changeLog(a.id, a.name, 'delete service: ' + a.name, uid=uid) services.delete() #批量删除 auth_service_principal 表中的数据 service_principals = ServicePrincipals.objects.filter(service_id__in=id_list) service_principals.delete() return Response({"success": True, "msg": "succ!", "errors": []})
def get(self, request, *args, **kwargs): page = 1 limit = 100 data = [] while True: state, res = GitLabApi().getProjects(page, limit) if not state: raise APIValidateException(res) data += res page += 1 if len(res) < limit: break return Response(data)
def patch(self, request, *args, **kwargs): user = request.user user_id = user.id data = {'success': True, 'msg': u'新增成功'} ssh_key = request.data.get("ssh_key", '') SSHKey.objects.filter(user_id=user_id).delete() u = SSHKey.objects.create(user_id=user_id, ssh_key=ssh_key, private_key='') u = model_to_dict(u) if ssh_key: status, output = FortressOps().addSSHKey(user.username, ssh_key) if not status: raise APIValidateException(output) self.changeLog(user.id, user.username, json.dumps(u)) return Response(data)