# HG changeset patch # User Branko Majic # Date 2013-11-09 13:50:30 # Node ID 353630bdfef62e5617d5bf0550294001fb0ad5ed # Parent 5edc670d4252600ddb2973ba7e054f4aae4d3553 CONNT-17: Added helper method for the Project model for obtaining a summary of communcations that can be then easily output in a table. diff --git a/conntrackt/models.py b/conntrackt/models.py --- a/conntrackt/models.py +++ b/conntrackt/models.py @@ -27,7 +27,7 @@ from django.db import models from django.db.models.query_utils import Q # Application imports. -from .utils import list_formatter_callback +from .utils import list_formatter_callback, get_distinct_colors class SearchManager(models.Manager): @@ -145,6 +145,50 @@ class Project(RelatedCollectorMixin, mod return reverse("project", kwargs={'pk': self.pk}) + def get_project_communications_summary(self): + """ + Creates a list of dictionaries where each dictionary provides summary of + a communication. Each dictionary will contain the following keys: + + - source - Source of the communication. + - source_color - Color that is associated with the source of + communication. The color will match with color used in the project + communications diagram. + - destination - Destination of the communication. + - destination_color - Color that is associated with the destination of + communication. The color will match with color used in the project + communications diagram. + - protocol - Protocol used for communication. + - port - Port used for communication. + + Returns: + List of dictionaries, where each dictionary describes a single communication. + """ + + # Obtain the list of colors. + colors = get_distinct_colors(self.entity_set.count()) + + # Fetch ID's of each end entity. + entity_ids = self.entity_set.values_list("pk", flat=True).order_by("pk") + + # Map the entity ID's to generated colors. + entity_colors = dict(zip(entity_ids, colors)) + + # Set-up an empty list where the resulting data will be stored. + communications = [] + + # Process each communication, and add the information to result. + for communication in Communication.objects.filter(source__entity__project=self).select_related().order_by("source__entity__pk"): + communications.append({"source": communication.source.entity.name, + "source_color": entity_colors[communication.source.entity.pk], + "destination": communication.destination.entity.name, + "destination_color": entity_colors[communication.destination.entity.pk], + "protocol": communication.protocol, + "port": communication.port,}) + + # Finally return the result. + return communications + class Location(RelatedCollectorMixin, models.Model): """