-
-
Notifications
You must be signed in to change notification settings - Fork 639
Data model duplication #3477
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
ayushgupta704
wants to merge
4
commits into
intelowlproject:develop
Choose a base branch
from
ayushgupta704:feature/data-model-deduplication
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Data model duplication #3477
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
eaca64d
feat: implement CAS for Data Model deduplication
ayushgupta704 b7bf9eb
feat: hardened migration and CAS deduplication
ayushgupta704 3961c1f
feat: hardened migration and CAS deduplication
ayushgupta704 1ae2ab8
cleanup and formatting of migration tests
ayushgupta704 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
25 changes: 25 additions & 0 deletions
25
api_app/data_model_manager/migrations/0012_domaindatamodel_fingerprint_and_more.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,25 @@ | ||
| from django.db import migrations, models | ||
|
|
||
| class Migration(migrations.Migration): | ||
|
|
||
| dependencies = [ | ||
| ('data_model_manager', '0011_data_model_date_index'), | ||
| ] | ||
|
|
||
| operations = [ | ||
| migrations.AddField( | ||
| model_name='domaindatamodel', | ||
| name='fingerprint', | ||
| field=models.CharField(blank=True, db_index=True, max_length=64, default=''), | ||
| ), | ||
| migrations.AddField( | ||
| model_name='filedatamodel', | ||
| name='fingerprint', | ||
| field=models.CharField(blank=True, db_index=True, max_length=64, default=''), | ||
| ), | ||
| migrations.AddField( | ||
| model_name='ipdatamodel', | ||
| name='fingerprint', | ||
| field=models.CharField(blank=True, db_index=True, max_length=64, default=''), | ||
| ), | ||
| ] |
87 changes: 87 additions & 0 deletions
87
api_app/data_model_manager/migrations/0013_populate_fingerprints.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,87 @@ | ||
| import hashlib | ||
| import json | ||
| import logging | ||
|
|
||
| from django.db import migrations | ||
|
|
||
| logger = logging.getLogger(__name__) | ||
|
|
||
| def normalize_dict(obj): | ||
| if isinstance(obj, dict): | ||
| return {k: normalize_dict(v) for k, v in sorted(obj.items())} | ||
| if isinstance(obj, list): | ||
| return [normalize_dict(i) for i in obj] | ||
| return obj | ||
|
|
||
| def generate_fingerprint_from_instance(instance): | ||
| data = {} | ||
| for field in instance._meta.fields: | ||
| name = field.name | ||
| if name in ["id", "date", "fingerprint"]: | ||
| continue | ||
| value = getattr(instance, name) | ||
| if hasattr(value, "isoformat"): | ||
| value = value.isoformat() | ||
| data[name] = value | ||
| normalized_data = normalize_dict(data) | ||
| encoded_data = json.dumps(normalized_data, sort_keys=True).encode("utf-8") | ||
| return hashlib.sha256(encoded_data).hexdigest() | ||
|
|
||
| def populate_fingerprints(apps, schema_editor): | ||
| batch_size = 500 | ||
| for model_name in ["IPDataModel", "DomainDataModel", "FileDataModel"]: | ||
| Model = apps.get_model("data_model_manager", model_name) | ||
| queryset = Model.objects.filter(fingerprint="").iterator(chunk_size=batch_size) | ||
| batch = [] | ||
| for instance in queryset: | ||
| try: | ||
| instance.fingerprint = generate_fingerprint_from_instance(instance) | ||
| batch.append(instance) | ||
| except Exception as e: | ||
| logger.error(f"Failed to generate fingerprint for {model_name} {instance.pk}: {e}") | ||
| if len(batch) >= batch_size: | ||
| Model.objects.bulk_update(batch, ["fingerprint"]) | ||
| batch = [] | ||
| if batch: | ||
| Model.objects.bulk_update(batch, ["fingerprint"]) | ||
| from django.contrib.contenttypes.models import ContentType | ||
| ct, _ = ContentType.objects.get_or_create(app_label="data_model_manager", model=model_name.lower()) | ||
| from django.db.models import Count | ||
| duplicates = Model.objects.values("fingerprint").annotate(c=Count("id")).filter(c__gt=1) | ||
| for entry in duplicates: | ||
| fp = entry["fingerprint"] | ||
| if not fp: | ||
| continue | ||
| instances = list(Model.objects.filter(fingerprint=fp).order_by("date")) | ||
| canonical = instances[0] | ||
| redundant_ids = [r.id for r in instances[1:]] | ||
| AnalyzerReport = apps.get_model("analyzers_manager", "AnalyzerReport") | ||
| AnalyzerReport.objects.filter( | ||
| data_model_content_type_id=ct.id, | ||
| data_model_object_id__in=redundant_ids | ||
| ).update(data_model_object_id=canonical.id) | ||
| Job = apps.get_model("api_app", "Job") | ||
| Job.objects.filter( | ||
| data_model_content_type_id=ct.id, | ||
| data_model_object_id__in=redundant_ids | ||
| ).update(data_model_object_id=canonical.id) | ||
| try: | ||
| UserAnalyzableEvent = apps.get_model("user_events_manager", "UserAnalyzableEvent") | ||
| UserAnalyzableEvent.objects.filter( | ||
| data_model_content_type_id=ct.id, | ||
| data_model_object_id__in=redundant_ids | ||
| ).update(data_model_object_id=canonical.id) | ||
| except LookupError: | ||
| pass | ||
| Model.objects.filter(id__in=redundant_ids).delete() | ||
|
|
||
| def reverse_populate_fingerprints(apps, schema_editor): | ||
| pass | ||
|
|
||
| class Migration(migrations.Migration): | ||
| dependencies = [ | ||
| ('data_model_manager', '0012_domaindatamodel_fingerprint_and_more'), | ||
| ] | ||
| operations = [ | ||
| migrations.RunPython(populate_fingerprints, reverse_populate_fingerprints), | ||
| ] | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
71 changes: 71 additions & 0 deletions
71
tests/api_app/data_model_manager/test_cas_deduplication.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| from kombu import uuid | ||
|
|
||
| from api_app.analyzables_manager.models import Analyzable | ||
| from api_app.analyzers_manager.models import AnalyzerConfig, AnalyzerReport | ||
| from api_app.choices import Classification | ||
| from api_app.data_model_manager.models import IPDataModel | ||
| from api_app.models import Job | ||
| from tests import CustomTestCase | ||
|
|
||
|
|
||
| class CASDeduplicationTestCase(CustomTestCase): | ||
| def setUp(self): | ||
| super().setUp() | ||
| self.analyzable = Analyzable.objects.get_or_create( | ||
| name="1.1.1.1", defaults={"classification": Classification.IP.value} | ||
| )[0] | ||
| self.job1 = Job.objects.create( | ||
| analyzable=self.analyzable, | ||
| status=Job.STATUSES.ANALYZERS_RUNNING.value, | ||
| ) | ||
| self.job2 = Job.objects.create( | ||
| analyzable=self.analyzable, | ||
| status=Job.STATUSES.ANALYZERS_RUNNING.value, | ||
| ) | ||
| self.config = AnalyzerConfig.objects.first() | ||
|
|
||
| def test_smart_deduplication_via_fingerprint(self): | ||
| report1 = AnalyzerReport.objects.create( | ||
| job=self.job1, | ||
| config=self.config, | ||
| status=AnalyzerReport.STATUSES.SUCCESS.value, | ||
| task_id=str(uuid()), | ||
| parameters={}, | ||
| ) | ||
| report1._create_data_model_dictionary = lambda: {"isp": "Google", "asn": 15169} | ||
| dm1 = report1.create_data_model() | ||
| initial_count = IPDataModel.objects.count() | ||
|
|
||
| report2 = AnalyzerReport.objects.create( | ||
| job=self.job2, | ||
| config=self.config, | ||
| status=AnalyzerReport.STATUSES.SUCCESS.value, | ||
| task_id=str(uuid()), | ||
| parameters={}, | ||
| ) | ||
| report2._create_data_model_dictionary = lambda: {"isp": "Google", "asn": 15169} | ||
| dm2 = report2.create_data_model() | ||
| self.assertEqual(dm1.pk, dm2.pk) | ||
| self.assertEqual(IPDataModel.objects.count(), initial_count) | ||
|
|
||
| def test_normalization_stability(self): | ||
| report1 = AnalyzerReport.objects.create( | ||
| job=self.job1, | ||
| config=self.config, | ||
| status=AnalyzerReport.STATUSES.SUCCESS.value, | ||
| task_id=str(uuid()), | ||
| parameters={}, | ||
| ) | ||
| report1._create_data_model_dictionary = lambda: {"asn": 15169, "isp": "Google"} | ||
| dm1 = report1.create_data_model() | ||
| report2 = AnalyzerReport.objects.create( | ||
| job=self.job2, | ||
| config=self.config, | ||
| status=AnalyzerReport.STATUSES.SUCCESS.value, | ||
| task_id=str(uuid()), | ||
| parameters={}, | ||
| ) | ||
| report2._create_data_model_dictionary = lambda: {"isp": "Google", "asn": 15169} | ||
| dm2 = report2.create_data_model() | ||
| self.assertEqual(dm1.fingerprint, dm2.fingerprint) | ||
| self.assertEqual(dm1.pk, dm2.pk) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| from django.db import connection | ||
| from django.db.migrations.executor import MigrationExecutor | ||
|
|
||
| from api_app.helpers import calculate_md5, calculate_sha1, calculate_sha256 | ||
| from tests import CustomTestCase | ||
|
|
||
|
|
||
| class MigrationIntegrityTestCase(CustomTestCase): | ||
| @property | ||
| def app_name(self): | ||
| return "data_model_manager" | ||
|
|
||
| @property | ||
| def migration_from(self): | ||
| return "0012_domaindatamodel_fingerprint_and_more" | ||
|
|
||
| @property | ||
| def migration_to(self): | ||
| return "0013_populate_fingerprints" | ||
|
|
||
| def setUp(self): | ||
| super().setUp() | ||
| self.executor = MigrationExecutor(connection) | ||
| self.old_state = self.executor.migrate([(self.app_name, self.migration_from)]) | ||
|
|
||
| def test_migration_0013_deduplication_integrity(self): | ||
| old_apps = self.old_state.apps | ||
| IPDataModel = old_apps.get_model(self.app_name, "IPDataModel") | ||
| UserAnalyzableEvent = old_apps.get_model("user_events_manager", "UserAnalyzableEvent") | ||
| Analyzable = old_apps.get_model("analyzables_manager", "Analyzable") | ||
| ContentType = old_apps.get_model("contenttypes", "ContentType") | ||
| User = old_apps.get_model("certego_saas_user", "User") | ||
| user = User.objects.create(username="test_migrator", email="test@intelowl.org") | ||
| name1, name2 = "1.1.1.1", "8.8.8.8" | ||
| az1 = Analyzable.objects.create( | ||
| name=name1, | ||
| classification="ip", | ||
| md5=calculate_md5(name1.encode()), | ||
| sha1=calculate_sha1(name1.encode()), | ||
| sha256=calculate_sha256(name1.encode()), | ||
| ) | ||
| az2 = Analyzable.objects.create( | ||
| name=name2, | ||
| classification="ip", | ||
| md5=calculate_md5(name2.encode()), | ||
| sha1=calculate_sha1(name2.encode()), | ||
| sha256=calculate_sha256(name2.encode()), | ||
| ) | ||
| dm1 = IPDataModel.objects.create(evaluation="benign", reliability=5) | ||
| dm2 = IPDataModel.objects.create(evaluation="benign", reliability=5) | ||
| ct = ContentType.objects.get_for_model(IPDataModel) | ||
| UserAnalyzableEvent.objects.create( | ||
| user=user, analyzable=az1, data_model_content_type=ct, data_model_object_id=dm1.id | ||
| ) | ||
| UserAnalyzableEvent.objects.create( | ||
| user=user, analyzable=az2, data_model_content_type=ct, data_model_object_id=dm2.id | ||
| ) | ||
| self.executor.loader.build_graph() | ||
| new_state = self.executor.migrate([(self.app_name, self.migration_to)]) | ||
| new_apps = new_state.apps | ||
| IPDataModelNew = new_apps.get_model(self.app_name, "IPDataModel") | ||
| UserAnalyzableEventNew = new_apps.get_model("user_events_manager", "UserAnalyzableEvent") | ||
| self.assertEqual(IPDataModelNew.objects.count(), 1) | ||
| canonical = IPDataModelNew.objects.first() | ||
| events = UserAnalyzableEventNew.objects.filter(data_model_object_id=canonical.id) | ||
| self.assertEqual(events.count(), 2) | ||
| self.assertFalse(IPDataModelNew.objects.filter(id=dm2.id).exists()) | ||
|
|
||
| def tearDown(self): | ||
| self.executor.migrate(self.executor.loader.graph.leaf_nodes()) | ||
| super().tearDown() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
the problem about adding data migrations is that no failing tests show up by running classic CI because the CI would work on a fresh environment.
This is a very risky change if not tested with already existing environments. The benefit of this could be easily destroyed by introducing an unwanted breaking change. Additional more comprehensive tests should be required. We can't merge this in the next release, we would need to wait a major like we will do for other critical PRs