def typeahead_slugs(request, slug='Node'): response = HttpResponse(content_type='application/json') to_find = request.GET.get('query', None) result = [] if to_find: # split for search match_q = regex_escape(to_find.split()) labels = [ helpers.slug_to_node_type(slug).get_label() for s in slug.split('+') ] try: q = """ MATCH (n:Node) WHERE any(label in labels(n) where label in $labels) OPTIONAL MATCH (n)<-[:Has]-(e:Node) WITH n.handle_id as handle_id, coalesce(e.name, "") + " "+ n.name as name WHERE name =~ $name_re RETURN handle_id, trim(name) as name """ name_re = '(?i).*{}.*'.format('.*'.join(match_q)) result = nc.query_to_list(nc.graphdb.manager, q, labels=labels, name_re=name_re) except Exception as e: raise e json.dump(result, response) return response
def create_node(self, name, _type, meta='Physical'): nt = helpers.slug_to_node_type(_type, True) return NodeHandle.objects.create( node_name=name, node_type=nt, node_meta_type=meta, creator=self.user, modifier=self.user, )
def get_node_type(request, slug): """ Compiles a list of alla nodes of that node type and returns a list of node name, node id tuples. """ node_type = helpers.slug_to_node_type(slug) label = node_type.type.replace(' ', '_') result_list = [] for node in nc.get_node_by_type(nc.graphdb.manager, label): result_list.append([node['handle_id'], node['name']]) result_list = sorted(result_list, key=lambda n: n[1].lower()) return JsonResponse(result_list, safe=False)
def validate_unique(self, item): error = None if item['name']: slug = slugify(item['node_type']) node_type = helpers.slug_to_node_type(slug, create=True) try: NodeHandle.objects.get(node_name=item['name'], node_type=node_type) error = "Must be unique." except NodeHandle.MultipleObjectsReturned: error = "Must be unique." except NodeHandle.DoesNotExist: pass return error
def convert_host(request, handle_id, slug): """ Convert a Host to Firewall or Switch. """ allowed_types = ['firewall', 'switch', 'pdu', 'router'] # Types that can be added as Hosts by nmap nh = get_object_or_404(NodeHandle, pk=handle_id) if slug in allowed_types and nh.node_type.type == 'Host': node_type = helpers.slug_to_node_type(slug, create=True) nh, node = helpers.logical_to_physical(request.user, handle_id) node.switch_type(nh.node_type.get_label(), node_type.get_label()) nh.node_type = node_type nh.save() node_properties = { 'backup': '' } helpers.dict_update_node(request.user, node.handle_id, node_properties, node_properties.keys()) return redirect(nh.get_absolute_url())
def get_unlocated_node_type(request, slug): """ Compiles a list of alla nodes of that node type that does not have a Located_in relationship and returns a list of node name, node id tuples. """ node_type = helpers.slug_to_node_type(slug) q = ''' MATCH (node:{node_type}) WHERE NOT (node)-[:Located_in]->() RETURN node.handle_id, node.name ORDER BY node.name '''.format(node_type=node_type.type.replace(' ', '_')) result_list = [] with nc.graphdb.manager.session as s: result = s.run(q) result_list = [r for r in result] return JsonResponse(result_list, safe=False)
def get_port(self, bundle, device_name, device_type, port_name): node_type = helpers.slug_to_node_type(slugify(device_type), create=True) parent_node = nc.get_unique_node_by_name(nc.graphdb.manager, device_name, node_type.get_label()) if not parent_node: raise_not_acceptable_error("End point {0} {1} not found.".format( device_type, device_name)) result = parent_node.get_port(port_name).get('Has', []) if len(result) > 1: raise_not_acceptable_error( 'Multiple port objects returned for a unique port name.') if result: port_node = result[0]['node'] else: port_node = helpers.create_port(parent_node, port_name, bundle.request.user) return port_node
def obj_create(self, bundle, **kwargs): try: node_type = helpers.slug_to_node_type(self.Meta.resource_name, create=True) NodeHandle.objects.get(node_name=bundle.data['node_name'], node_type=node_type) raise_conflict_error('Cable ID (%s) is already in use.' % bundle.data['node_name']) except NodeHandle.DoesNotExist: bundle.data.update(self._initial_form_data(bundle)) bundle.data['name'] = bundle.data['node_name'] form = common_forms.NewCableForm(bundle.data) if form.is_valid(): bundle.data.update({ 'node_name': form.cleaned_data['name'], 'creator': '/api/%s/user/%d/' % (self._meta.api_name, bundle.request.user.pk), 'modifier': '/api/%s/user/%d/' % (self._meta.api_name, bundle.request.user.pk), }) node_data = bundle.data.get('node', {}) node_data.update( {'cable_type': form.cleaned_data['cable_type']}) bundle.data['node'] = node_data del bundle.data['name'] # Create the new cable bundle = super(NodeHandleResource, self).obj_create(bundle, **kwargs) # Depend the created service on provided end points end_point_nodes = self.get_end_point_nodes(bundle) node = bundle.obj.get_node() for end_point in end_point_nodes: helpers.set_connected_to(bundle.request.user, node, end_point.handle_id) return self.hydrate_node(bundle) else: raise_not_acceptable_error([ "%s is missing or incorrect." % key for key in form.errors.keys() ])
def get_child_form_data(request, handle_id, slug=None): """ Compiles a list of the nodes children and returns a list of node name, node id tuples. If node_type is set the function will only return nodes of that type. """ nh = get_object_or_404(NodeHandle, handle_id=handle_id) node_type = slug if slug: node_type = helpers.slug_to_node_type(slug).type.replace(' ', '_') child_list = [] for child in nh.get_node().get_child_form_data(node_type): if not slug: node_type = helpers.labels_to_node_type(child['labels']) name = u'{} {}'.format(node_type.replace('_', ' '), child['name']) if child.get('description', None): name = u'{} ({})'.format(name, child['description']) child_list.append((child['handle_id'], name)) child_list = sorted(child_list, key=itemgetter(1)) return JsonResponse(child_list, safe=False)
def get_subtype_form_data(request, slug, key, value): """ Compiles a list of the nodes children and returns a list of node name, node id tuples. If node_type is set the function will only return nodes of that type. """ node_type = helpers.slug_to_node_type(slug).type.replace(' ', '_') q = """ MATCH (n:{node_type}) WHERE n.{key} = '{value}' RETURN n.handle_id as handle_id, n.name as name, n.description as description ORDER BY n.name """.format(node_type=node_type, key=key, value=value) subtype_list = [] for subtype in nc.query_to_list(nc.graphdb.manager, q): name = subtype['name'] if subtype.get('description', None): name = u'{} ({})'.format(name, subtype['description']) subtype_list.append((subtype['handle_id'], name)) subtype_list = sorted(subtype_list, key=itemgetter(1)) return JsonResponse(subtype_list, safe=False)