def do_verify(request): # # getting if the uuid is assigned to a server.. if not create it # s = Server.objects(uuid=request.POST['server']).first() if s is None: s = Server(host=request.POST['host'], uuid=request.POST['server']) s.save() return s
def init_servers(self): s = self._get_assets_servers() _ = lambda x: x.decode("utf8") for _server in s.servers: try: server = Server(hostname=_(_server['hostname']), sn=_(_server['sn'])) server.save() except IntegrityError: print "hostname:%s duplicated" % _server['hostname'] continue
def post(self, request): ret = {'status': 0, 'errmsg': 'ok'} data = QueryDict(request.body) data = dict(data.items()) try: server = Server(**data) server.save() except Exception as e: msg = "user {} add server error:{}".format(request.user.username, e.args) logger.error(msg) ret['status'] = 1 ret['errmsg'] = msg return JsonResponse(ret, safe=True)
def add_server(form_data): """ 添加服务器 :param form_data: :return: """ server_name = form_data['server_name'] server_ip = form_data['server_ip'] server_description = form_data['server_description'] if form_data['server_description'] else '' # 描述 try: s = Server.objects.get(server_ip=server_ip) return False, '机器已经存在,请核实!' except Server.DoesNotExist: s = Server(server_name=server_name, server_ip=server_ip, server_description=server_description) s.save() return True, '机器添加成功!'
class TestRPCHandler(TestCase): """ """ def setUp(self): self.s = Server(ip="127.0.0.1", username="******", name="localhost_test") self.s.save() self.s.connect() def tearDown(self): self.s.close() def test_call_method(self): """ Test remote call to a Server method. """ self.rh = RPCHandler([self.s, ]) r = self.rh.call_method(self.s.id, "show_processlist") self.assertTrue(len(r))
def set_server_info(form_data): """ 添加服务器 :param form_data: :return: """ server_name = form_data['server_name'] server_ip = form_data['server_ip'] server_description = '自动' # 描述 try: s = Server.objects.get(server_ip=server_ip) s.server_name = server_name s.server_ip = server_ip s.save() msg = 'server information update success!' except Server.DoesNotExist: s = Server(server_name=server_name, server_ip=server_ip, server_description=server_description) s.save() msg = 'server auto reg success!!' return True, msg
class ServerTest(TestCase): """ Testing for Server model. """ def setUp(self): self.s = Server(ip="127.0.0.1", username="******", name="localhost_test") self.s.save() def teatDown(self): """ """ self.s.close() def test_connect(self): """ Testing 'connection' method for Server class. """ self.s.close() self.assertIn(self.s.connect(), [True, False]) def test_doquery(self): """ Testing query request and result format. """ self.s.restart() sql = "SELECT NOW();" r = self.s.doquery(sql) self.assertTrue(r) def test_show_status(self): """ Testing status query for server. """ self.s.restart() r = self.s.show_status(pattern='Threads_running') self.assertTrue(r)
def add_server_fast(form_data, user_id): """ 批量增加主机 :param form_data: :param user_id: :return: """ server_list = form_data['server_list'] msg = '新增结果:' flag = True for s in server_list.split('\n'): server_name = s.split(',')[0].strip() # 主机名 server_ip = s.split(',')[1].strip() # 主机名 try: s = Server.objects.get(server_ip=server_ip) flag = False msg = msg + '失败:' + server_name.strip() + '|' + server_ip.strip() + '' except Server.DoesNotExist: s = Server(server_name=server_name, server_ip=server_ip) s.save() if flag: return True, '机器添加成功!' else: return False, msg
def add(request): if request.POST: nocid = request.POST.get('org.nocid', None) nocname = request.POST.get('org.nocname', None) elementid = request.POST.get('org.elementid', None) in_ip = request.POST.get('org.in_ip', None) out_ip = request.POST.get('org.out_ip', None) manage_account = request.POST.get('org.manage_account', None) manage_password = request.POST.get('org.manage_password', None) manage_port = request.POST.get('org.manage_port', None) virtual_flag = request.POST.get('org.virtual_flag', None) saltid = request.POST.get('saltid', None) service_name = request.POST.get('service_name', None) ids = request.POST.get('org.softid', None) agent_flag = request.POST.get('agent_flag', None) agent_saltid = request.POST.get('org.agent_saltid', None) '''验证机房编号,内网IP,saltid是否为空''' if not nocid or not in_ip or not saltid: return HttpResponse(simplejson.dumps({"statusCode":302, "navTabId":request.POST.get('navTabId','serverindex'), "callbackType":request.POST.get('callbackType',None), "message":u'机房编号或内网IP为空不能添加'}), mimetype='application/json') # '''验证重复资产编号''' # servers = Server.objects.filter(elementid__iexact=elementid) # if servers: # return HttpResponse(simplejson.dumps({"statusCode":302, "navTabId":request.POST.get('navTabId','serverindex'), "callbackType":request.POST.get('callbackType',None), "message":u'资产编号已经存在不能添加'}), mimetype='application/json') '''验证机房编号+内网IP是否唯一''' servers = Server.objects.filter(nocid__iexact=nocid, in_ip__iexact=in_ip) if servers: return HttpResponse(simplejson.dumps({"statusCode":302, "navTabId":request.POST.get('navTabId','serverindex'), "callbackType":request.POST.get('callbackType',None), "message":u'当前服务器已经存在不能添加'}), mimetype='application/json') '''验证saltid是否唯一''' servers = Server.objects.filter(saltid__iexact=saltid) if servers: return HttpResponse(simplejson.dumps({"statusCode":302, "navTabId":request.POST.get('navTabId','serverindex'), "callbackType":request.POST.get('callbackType',None), "message":u'saltid已经存在不能添加'}), mimetype='application/json') server = Server(nocid=nocid, nocname=nocname, elementid=elementid, in_ip=in_ip, out_ip=out_ip, manage_account=manage_account, manage_password=manage_password, saltid=saltid, service_name=service_name, salt_status=1) if agent_flag != None and agent_flag != '': server.agent_flag = agent_flag if agent_flag == '1': try: agent_server = Server.objects.get(saltid=agent_saltid) server.agent_server = agent_server server.save() except: return HttpResponse(simplejson.dumps({"statusCode":302, "navTabId":request.POST.get('navTabId','serverindex'), "callbackType":request.POST.get('callbackType',None), "message":u'代理服务器选择错误请重新选择'}), mimetype='application/json') server.save() if manage_port != None and manage_port != '': server.manage_port = manage_port else: server.manage_port = None if virtual_flag != None and virtual_flag != '': server.virtual_flag = virtual_flag else: server.virtual_flag = None server.save() # 添加基础应用 if ids != None and ids != '': id_list = ids.split(',') for softid in id_list: softform = get_object_or_404(SoftForm, pk = int(softid)) server.softforms.add(softform) server.save() Log(username=request.user.username, content=u"添加服务器:" + server.elementid + u" 成功!", level=1).save() return HttpResponse(simplejson.dumps({"statusCode":200, "navTabId":request.POST.get('navTabId','serverindex'), "callbackType":request.POST.get('callbackType','closeCurrent'), "message":u'添加成功'}), mimetype='application/json') else: return render_to_response('server/add.html')
def savedata(request, result): if(result['status'] == "timeout"): print result['ip'] + ' ' + result['data'] return "timeout" if 'server_sn' not in result['data']: print result['ip'] + ' ' + "sn error" return "sn error" server = result['data'] sn = server['server_sn'] ip = server['server_ip'] brand = server['server_brand'] model = server['server_model'] cpu = server['server_cpu'] memory = server['server_memory'] network = server['server_default_ipv4'] all_ip = server['server_all_ipv4_address'] system = server['server_system'] hostname = server['server_hostname'] user = '******' status = 'product' # 如果序列号已经存在,只做更新 if Server.objects.filter(sn = sn): olddata = Server.objects.filter(sn = sn) id = olddata[0].id server_update = Server.objects.get(id = id) server_update.ip = ip server_update.brand = brand server_update.model = model server_update.cpu = cpu server_update.memory = memory server_update.network = network server_update.all_ip = all_ip server_update.system = system server_update.hostname = hostname server_update.user = user server_update.status = status server_update.save() print ip+' is update >>>>' return "update" # 插入数据库 server_add = Server( sn = sn, ip = ip, brand = brand, model = model, cpu = cpu, memory = memory, network = network, all_ip = all_ip, system = system, hostname = hostname, user = user, status = status, ) server_add.save() print ip+' is add ****' return "add"
def savedata(request, result): if (result['status'] == "timeout"): print result['ip'] + ' ' + result['data'] return "timeout" if 'server_sn' not in result['data']: print result['ip'] + ' ' + "sn error" return "sn error" server = result['data'] sn = server['server_sn'] ip = server['server_ip'] brand = server['server_brand'] model = server['server_model'] cpu = server['server_cpu'] memory = server['server_memory'] network = server['server_default_ipv4'] all_ip = server['server_all_ipv4_address'] system = server['server_system'] hostname = server['server_hostname'] user = '******' status = 'product' # 如果序列号已经存在,只做更新 if Server.objects.filter(sn=sn): olddata = Server.objects.filter(sn=sn) id = olddata[0].id server_update = Server.objects.get(id=id) server_update.ip = ip server_update.brand = brand server_update.model = model server_update.cpu = cpu server_update.memory = memory server_update.network = network server_update.all_ip = all_ip server_update.system = system server_update.hostname = hostname server_update.user = user server_update.status = status server_update.save() print ip + ' is update >>>>' return "update" # 插入数据库 server_add = Server( sn=sn, ip=ip, brand=brand, model=model, cpu=cpu, memory=memory, network=network, all_ip=all_ip, system=system, hostname=hostname, user=user, status=status, ) server_add.save() print ip + ' is add ****' return "add"
def handle(self, *args, **options): #pr = cProfile.Profile() #pr.enable() transaction.set_autocommit(False) self.Faker = Factory.create() dodemo = False dodemopassword = '' try: dodemo = True if args[0] == '1' else False dodemopassword = args[1] except: pass # Set up a default seed so developers can talk to eachother self.Faker.seed(10000) # First, spirit needs us to create some categories for it to work at all: self.stdout.write("Filling up the standard categories\n") cat = Category(title="Private",slug="private",description="The category for all private discussions", is_closed=0, is_removed=0, is_private=0) cat.save() transaction.commit() if(cat.pk != ST_TOPIC_PRIVATE_CATEGORY_PK): raise CommandError("The id for the private category does not match up with our default in the settings. Check ST_TOPIC_PRIVATE_CATEGORY_PK, should be %d but is %d " % (ST_TOPIC_PRIVATE_CATEGORY_PK, cat.pk)) cat = Category(title="Uncategorized",slug="uncategorized",description="The category for all uncategorized discussions", is_closed=0, is_removed=0, is_private=0) cat.save() transaction.commit() if(cat.pk != ST_UNCATEGORIZED_CATEGORY_PK): raise CommandError("The id for the uncategorized category does not match up with our default in the settings. Check ST_UNCATEGORIZED_CATEGORY_PK, should be %d but is %d " % (ST_UNCATEGORIZED_CATEGORY_PK, cat.pk)) cat = Category(title="Other",slug="other",description="The category for external (server) discussions", is_closed=0, is_removed=0, is_private=0) cat.save() transaction.commit() if(cat.pk != ST_OTHER_CATEGORY_PK): raise CommandError("The id for the other category does not match up with our default in the settings. Check ST_OTHER_CATEGORY_PK, should be %d but is %d " % (ST_OTHER_CATEGORY_PK, cat.pk)) if dodemo: self.stdout.write("Starting the fill of demo data\n") # Here is where we generate some categories cat_list = [] self.stdout.write("Creating some fake categories\n") for str in self.categories: cat = Category(title=str,description="The category for all discussions about " + str, is_closed=0, is_removed=0, is_private=0) cat.save() cat_list.append(cat) transaction.commit() # Here is where we generate a couple of servers self.stdout.write("Creating some fake servers\n") servers = [] for i in range(0, 100): name = random.choice(self.animals) + "'s " + random.choice(self.words) + " " + random.choice(self.games) server = Server(name=name, description=self.Faker.sentence() + " " +self.Faker.sentence(), questions="questions here", image='tuxie.jpg', image_height=0, image_width=0, status=random.randint(1, 3)) server.save() servers.append(server) transaction.commit() # Create three users. One Admin, two unpriviliged users mem = self.create_random_member(True) adminuser = mem["member"] # The admin generated admin_pass = mem["password"] mem = self.create_random_member() unpriv_user1 = mem["member"] # Two unpriviliged users unpriv_pass1 = mem["password"] mem = self.create_random_member() unpriv_user2 = mem["member"] unpriv_pass2 = mem["password"] # Now generate a motherload of them for i in range(0,1000): self.create_random_member() self.stdout.write("Creating some fake members (may take a while)\n") transaction.commit() self.stdout.write("Creating some fake volunteers\n") # Here is where we generate a couple of volunteers statuscodes = ["OK", "WAITING", "DENIED"] for i in range(0, 300): vol = Volunteer(member=random.choice(self.members), server=random.choice(servers), answer=self.Faker.text(), role=self.Faker.word(), status=random.choice(statuscodes), sec_edit=self.Faker.boolean(), sec_accept=self.Faker.boolean() ) vol.save() # Finally some topics transaction.commit() self.stdout.write("Creating some fake threads (may take a while!)\n") for i in range(0, 1000): top = Topic(user=random.choice(self.members), category=random.choice(cat_list), title=self.Faker.sentence(), is_pinned=self.Faker.boolean(5), is_closed=self.Faker.boolean(5), is_removed=self.Faker.boolean(5) ) top.save() # Aaand some comments for z in range(0, random.randint(1, 500)): text = self.Faker.text() comm = Comment(user=random.choice(self.members), topic=top, comment=text, comment_html=text ) comm.save() transaction.commit() self.stdout.write("Done! Below are three sample users of the 1003 we created:") self.stdout.write("Admin username: "******" Admin password: "******"\n") self.stdout.write("Unprivileged username sample 1: "+unpriv_user1.username+" Unprivileged user 1 password: "******"\n") self.stdout.write("Unprivileged username sample 1: "+unpriv_user2.username+" Unprivileged user 2 password: "******"\n") #pr.disable() #s = StringIO.StringIO() #sortby = 'cumulative' #ps = pstats.Stats(pr, stream=s).sort_stats(sortby) #ps.print_stats() #self.stdout.write(s.getvalue()) return