def test_mass_delete(self): from app.models import Group g1 = Group(name="g1", project_id=self.project1._id) g1.save() h1 = Host(fqdn="host1", group_id=g1._id) h1.save() h2 = Host(fqdn="host2", group_id=g1._id) h2.save() h3 = Host(fqdn="host3", group_id=g1._id) h3.save() h4 = Host(fqdn="host4", group_id=g1._id) h4.save() r = self.post_json("/api/v1/hosts/mass_delete", {"host_ids": [str(h2._id), str(h3._id)]}) self.assertEqual(200, r.status_code) data = json.loads(r.data) self.assertIn("data", data) hosts_data = data["data"] self.assertIn("hosts", hosts_data) hosts_data = hosts_data["hosts"] self.assertIs(list, type(hosts_data)) self.assertEqual(2, len(hosts_data)) deleted_hosts = Host.find({"_id": {"$in": [h2._id, h3._id]}}) self.assertEqual(0, deleted_hosts.count()) g1 = Group.find_one({"_id": g1._id}) self.assertItemsEqual([h1._id, h4._id], g1.host_ids)
def test_show_host(self): h = Host(**TEST_HOST_1) h.save() r = self.get("/api/v1/hosts/%s" % h._id) self.assertEqual(200, r.status_code) data = json.loads(r.data) self.assertIn("data", data) data = data["data"] self.assertIs(list, type(data)) self.assertEqual(1, len(data)) host_attrs = data[0] self.assertEqual(h.fqdn, host_attrs["fqdn"]) self.assertItemsEqual(h.tags, host_attrs["tags"]) self.assertEqual(h.description, host_attrs["description"])
def insert_one(self, host): """Insert a New Host""" token = self.__crypto.get_token() host = Host( name=host["name"], slug=host["slug"], type=host["type"], server=self.__crypto.encrypt(host["server"], token), auth_data=self.__crypto.encrypt(host["auth_data"], token), user=User.objects.get(pk=host["user_id"]), token=token ) host.save() return False if host.pk is None else host
def create(): from app.models import Host hosts_attrs = dict( [x for x in request.json.items() if x[0] in Host.FIELDS]) if "fqdn_pattern" in request.json: if "fqdn" in hosts_attrs: return json_response({ "errors": [ "fqdn field is not allowed due to fqdn_pattern param presence" ] }) try: hostnames = list(expand_pattern(request.json["fqdn_pattern"])) except Exception as e: return json_exception(e) else: hostnames = [hosts_attrs["fqdn"]] del (hosts_attrs["fqdn"]) try: hosts_attrs["group_id"] = ObjectId(hosts_attrs["group_id"]) except (KeyError, InvalidId): hosts_attrs["group_id"] = None try: hosts_attrs["datacenter_id"] = ObjectId(hosts_attrs["datacenter_id"]) except (KeyError, InvalidId): hosts_attrs["datacenter_id"] = None for fqdn in hostnames: attrs = hosts_attrs attrs["fqdn"] = fqdn host = Host(**attrs) try: host.save() except Exception as e: return json_exception(e, 500) hosts = Host.find({"fqdn": {"$in": list(hostnames)}}) try: data = paginated_data(hosts.sort("fqdn")) except AttributeError as e: return json_exception(e, 500) return json_response(data, 201)
def platform_info(name='liudong-ubuntu', force_update=False): host = Host.objects.filter(name=name).first() if not host or force_update: if not host: host = Host(name=name) host.core_num = psutil.cpu_count() host.cpu = platform.machine() uname_result = platform.uname() host.system = uname_result[0] host.system_version = uname_result[2] host.system_arch = uname_result[4] sdiskusage = psutil.disk_usage('/') host.hard_disk = sdiskusage.total * 1.0 / (1024**3) mem = psutil.virtual_memory() host.memory = mem.total * 1.0 / (1024**3) host.save()
def add_host(request): request_dict = request.GET name = request_dict.get('name') force_update = request_dict.get('force_update') print request_dict data = {k: v for k, v in request_dict.items()} host = Host.objects.filter(name=name).first() if not host or force_update: if not host: host = Host(**data) host.save(force_insert=True) data = { 'msg': 'ok', 'status': 'ok' } return JsonResponse(data)
def test_mass_detach(self): from app.models import Group g1 = Group(name="g1", project_id=self.project1._id) g1.save() g2 = Group(name="g2", project_id=self.project1._id) g2.save() h1 = Host(fqdn="host1", group_id=g1._id) h1.save() h2 = Host(fqdn="host2", group_id=g1._id) h2.save() h3 = Host(fqdn="host3", group_id=g2._id) h3.save() h4 = Host(fqdn="host4", group_id=g2._id) h4.save() r = self.post_json( "/api/v1/hosts/mass_detach", {"host_ids": [str(h1._id), str(h2._id), str(h3._id), str(h4._id)]}) self.assertEqual(200, r.status_code) data = json.loads(r.data) self.assertIn("data", data) hosts_data = data["data"] self.assertIn("hosts", hosts_data) hosts_data = hosts_data["hosts"] self.assertIs(list, type(hosts_data)) self.assertEqual(4, len(hosts_data)) g1 = Group.get(g1._id) g2 = Group.get(g2._id) self.assertItemsEqual([], g1.host_ids) self.assertItemsEqual([], g2.host_ids) hosts = Host.find( {"fqdn": { "$in": ["host1", "host2", "host3", "host4"] }}) for host in hosts: self.assertEqual(host.group_id, None)
def init(): # Role.objects(name__not__iexact="admin").delete() # Role(name="admin", description="Allow anything") # Role(name="addHost", description="Add a host to the inventory").save() # Role(name="addGroup", description="Add a group to the inventory").save() # Role(name="readOnly", description="Read access on inventory").save() # Role(name="query", description="Read access on inventory").save() User.objects(name__not__iexact=current_app.config.get('BARN_CONFIG').get( "barn_init_admin_user")).delete() user_1 = User(name="Sander Descamps", username="******", password="******", admin=True, roles=["test"]) user_1.save() Host.objects().delete() h_srvplex01 = Host(name="srvplex01.myhomecloud.be") h_srvplex01.save() h_srvdns01 = Host(name="srvdns01.myhomecloud.be", vars=dict(deploytime="today", env_environment="staging")) h_srvdns01.save() h_srvdns02 = Host(name="srvdns02.myhomecloud.be").save() h_srvdns02.save() Group.objects().delete() g_dns_servers = Group(name="dns_servers") g_dns_servers.hosts.append(h_srvdns01) g_dns_servers.hosts.append(h_srvdns02) g_dns_servers.save() g_all_servers = Group(name="all_servers") g_all_servers.child_groups.append(g_dns_servers) g_all_servers.hosts.append(h_srvplex01) g_all_servers.save() return jsonify({'message': 'Database has been reseted'})
idc.groups.add(1) # many idc.save() HOST_NUM = 10 for i in range(HOST_NUM): h = Host() h.idc = IDC.objects.get(id=i + 1) h.name = 'Host名称-%s' % i h.user = random.choice(names) h.password = '******' h.memory = random.choice([4, 8, 16]) h.service_type = SERVICE_TYPES[random.randint(0, 8)][0] h.description = '描述 --' + ''.join( [str(random.randint(0, 9)) for _i in range(8)]) h.administrator = User.objects.get(id=i + 1) h.save() HOST_NUM = 10 for i in range(HOST_NUM): h = HostGroup() h.name = 'Host名称-%s' % i h.description = '描述 --' + ''.join( [str(random.randint(0, 9)) for _i in range(8)]) h.save() # many 多对多 这样赋值 h = HostGroup.objects.get(id=i + 1) h.hosts.add(2, 4, 6, 8) if i % 2 else h.hosts.add(1, 3, 5, 7, 9) # many h.save()
def put_hosts(action=None, resp=None): if resp is None: resp = ResponseFormater() args = merge_args_data(request.args, request.get_json(silent=True)) name = args.get("name", None) if name is None: resp.failed(msg='name not defined') return resp.get_response() # Create Host o_host = Host.objects(name=name).first() if o_host is not None and action == "add": resp.failed(msg='%s already exist' % (args.get("name"))) return resp.get_response() elif o_host is None: if action == "update": resp.failed(msg='Host not found: %s Does not exist' % (args.get("name"))) return resp.get_response() else: try: o_host = Host(name=name) resp.succeed(changed=True, msg="Create host {}".format(name), status=HTTPStatus.CREATED) except NotUniqueError: resp.failed(msg='%s already exist' % (args.get("name"))) return resp.get_response() # Set variables barn_vars = args.get("vars", {}) if action == "set" and barn_vars != o_host.vars: o_host.vars = {} resp.changed() resp.add_message("Reset host variables") for k, v in barn_vars.items(): if o_host.vars.get(k, None) != v: o_host.vars[k] = v resp.changed() resp.add_message("Change variable: {}".format(k)) # Delete variables if action != "add": vars_to_remove = args.get("vars_absent", []) for var_to_remove in vars_to_remove: if var_to_remove in o_host.vars: del o_host.vars[var_to_remove] resp.add_message("Remove variable: {}".format(var_to_remove)) resp.changed() # Save Host if resp.get_changed(): o_host.save() # Add host to group o_groups_remove_list = [] o_groups_add_list = [] if args.get("groups", False): groups = list_parser(args.get("groups")) for group in groups: o_group = Group.objects(name=group).first() if not o_group and args.get('create_groups', True): o_group = Group(name=group) resp.changed() resp.add_message("Create {} group".format(group)) if o_group: o_groups_add_list.append(o_group) if args.get("groups_present", False): groups = list_parser(args.get("groups_present")) for group in groups: o_group = Group.objects(name=group).first() if not o_group and args.get('create_groups', True): o_group = Group(name=group) if o_group: o_groups_add_list.append(o_group) if args.get("groups_set", False) and not any( k in args for k in ("groups", "groups_present", "groups_absent")): groups = list_parser(args.get("groups_set")) o_groups_remove = Group.objects(name__not__in=groups, hosts__in=[o_host]) for g in o_groups_remove: o_groups_remove_list.append(g) for group in groups: o_group = Group.objects(name=group).first() if not o_group and args.get('create_groups', True): o_group = Group(name=group) if o_group: o_groups_add_list.append(o_group) if args.get("groups_absent", False): groups = list_parser(args.get("groups_absent")) o_groups_remove = Group.objects(name__in=groups) for g in o_groups_remove: o_groups_remove_list.append(g) for g in list(set(o_groups_remove_list)): if o_host in g.hosts: g.hosts.remove(o_host) resp.add_message("Remove {} from {} group".format(name, g.name)) g.save() resp.changed() for g in list(set(o_groups_add_list)): if o_host not in g.hosts: g.hosts.append(o_host) resp.add_message("Add {} into {} group".format(name, g.name)) g.save() resp.changed() return resp.get_response()
def post(self, jwt): if request.is_json and request.get_json(silent=True) is not None: try: post_data = request.get_json() host_name = post_data.get('host_name') alias = post_data.get('alias') address = post_data.get('address') contact_groups = post_data.get('contact_groups') contacts = post_data.get('contacts') sms = post_data.get('sms') street_address = post_data.get('street_address', '') notes = post_data.get('notes') notes_url = post_data.get('notes_url') hosttemplates = post_data.get('use') host_templates_str = "" if hosttemplates is not None: host_templates_str = ','.join(hosttemplates) notification_period = post_data.get('notification_period', "24x7") notification_options = "d,u,r" if post_data.get('notification_options') is not None: notification_options = ','.join( post_data.get('notification_options')) notifications_enabled = 1 if post_data.get( 'notifications_enabled') == True else 0 check_interval = post_data.get('check_interval', 5) retry_interval = post_data.get('retry_interval', 1) max_check_attempts = post_data.get('max_check_attempts', 5) notification_interval = post_data.get('notification_interval', 120) check_command = post_data.get('check_command', "check-host-alive") _SNMPVERSION = post_data.get('_SNMPVERSION', "2c") _SNMPCOMMUNITY = post_data.get('_SNMPCOMMUNITY', '') # Confirm this hostname doesn't already exist first. if Host.get_by_hostname(host_name): return jsonify(error=True, msg="Hostname already exists.") if host_name is None: return jsonify(error=True, msg="Missing host_name required field.") if alias is None: return jsonify(error=True, msg="Missing alias required field.") if address is None: return jsonify(error=True, msg="Missing address required field.") contacts_str = '' if contacts is not None and len(contacts) > 0: contacts_str = ','.join(contacts) newhost = Host(host_name=host_name.strip(), alias=alias.strip(), display_name=None, address=address.strip(), importance=None, check_command=check_command.strip(), max_check_attempts=max_check_attempts, check_interval=check_interval, retry_interval=retry_interval, active_checks_enabled=True, passive_checks_enabled=True, check_period="24x7", obsess_over_host=False, check_freshness=True, freshness_threshold=None, event_handler=None, event_handler_enabled=None, low_flap_threshold=None, high_flap_threshold=None, flap_detection_enabled=None, flap_detection_options=None, process_perf_data=True, retain_status_information=True, retain_nonstatus_information=True, contacts=contacts_str, contact_groups="", notification_interval=notification_interval, first_notification_delay=None, notification_period=notification_period.strip(), notification_options=notification_options, notifications_enabled=notifications_enabled, use=host_templates_str, hostgroups="null", street_address=street_address.strip(), sms=sms.strip(), notes=notes.strip(), notes_url=notes_url.strip(), icon_image='', icon_image_alt='', _SNMPVERSION=_SNMPVERSION, _SNMPCOMMUNITY=_SNMPCOMMUNITY) host_id = newhost.save() newservice = Service( host_name=host_name.strip(), hostgroup_name=None, service_description="PING", display_name="PING", importance=None, servicegroups="", is_volatile=None, check_command="PING", check_command_pre=None, check_command_param=None, snmp_type=None, snmp_option=None, snmp_check=None, max_check_attempts=5, check_interval=str(1), retry_interval=1, active_checks_enabled=True, passive_checks_enabled=False, check_period="24x7", obsess_over_host=None, check_freshness=None, freshness_threshold=None, event_handler=None, event_handler_enabled=None, low_flap_threshold=None, high_flap_threshold=None, flap_detection_enabled=None, flap_detection_options=None, process_perf_data=True, retain_status_information=True, retain_nonstatus_information=True, contacts=contacts_str, contact_groups="", notification_interval=60, first_notification_delay=5, notification_period="24x7", notification_options="w,c,r", notifications_enabled=True, use="", command=None, retry_check_interval=None, normal_check_interval=None, name=None, warning=None, critical=None, ) service_id = newservice.save() # create relations if contacts: Host.create_contacts_relations(host_id, contacts) Service.create_contacts_relations(service_id, contacts) if contact_groups: Host.create_contactgroups_relations( host_id, contact_groups) Service.create_contactgroups_relations( service_id, contact_groups) if hosttemplates: Host.create_hosttemplate_relations(host_id, hosttemplates) Service.create_hosts_relations(service_id, [host_name.strip()]) writeNagiosConfigFile(newhost) writeNagiosServicesConfigFile(newservice) if not restartNagios(): syncNagiosAllConfigWithDb() return jsonify(error=True, msg="Invalid process") return jsonify(data=newhost.serialize()) except Exception as e: syncNagiosAllConfigWithDb() return jsonify(error=True, msg=str(e)) return jsonify(error=True)