Skip to content

Commit 7891dde

Browse files
authored
More logs + fix investigation status on job removal (#2653)
* More logs + fix investigation status on job removal * Retry insert if path already exists
1 parent 25022f3 commit 7891dde

File tree

4 files changed

+34
-13
lines changed

4 files changed

+34
-13
lines changed

api_app/investigations_manager/models.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,10 @@
1+
import logging
12
from datetime import datetime
23
from typing import List
34

45
from django.conf import settings
56
from django.db import models
7+
from django.db.models import QuerySet
68

79
from api_app.choices import TLP
810
from api_app.interfaces import OwnershipAbstractModel
@@ -11,8 +13,11 @@
1113
from api_app.models import ListCachable
1214
from certego_saas.apps.user.models import User
1315

16+
logger = logging.getLogger(__name__)
17+
1418

1519
class Investigation(OwnershipAbstractModel, ListCachable):
20+
jobs: QuerySet
1621
name = models.CharField(max_length=100)
1722
description = models.TextField(default="", blank=True)
1823

@@ -60,13 +65,18 @@ def user_can_edit(self, user: User) -> bool:
6065
def set_correct_status(self, save: bool = True):
6166
from api_app.models import Job
6267

68+
logger.info(f"Setting status for investigation {self.pk}")
6369
# if I have some jobs
6470
if self.jobs.exists():
6571
# and at least one is running
6672
for job in self.jobs.all():
6773
job: Job
6874
jobs = job.get_tree(job)
69-
if jobs.exclude(status__in=Job.STATUSES.final_statuses()).count() > 0:
75+
running_jobs = jobs.exclude(status__in=Job.STATUSES.final_statuses())
76+
if running_jobs.count() > 0:
77+
logger.info(
78+
f"Jobs {running_jobs.values_list('pk', flat=True)} are still running for investigation {self.pk}"
79+
)
7080
self.status = self.STATUSES.RUNNING.value
7181
self.end_time = None
7282
break

api_app/investigations_manager/views.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,10 +102,13 @@ def remove_job(self, request, pk):
102102
investigation.refresh_from_db()
103103
# we are possibly changing the status of the investigation
104104
investigation.set_correct_status(save=True)
105-
return Response(
105+
response = Response(
106106
status=status.HTTP_200_OK,
107107
data=InvestigationSerializer(instance=investigation).data,
108108
)
109+
if not investigation.jobs.exists():
110+
investigation.delete()
111+
return response
109112

110113
@action(methods=["GET"], url_name="graph", detail=True)
111114
def tree(self, request, pk):

api_app/models.py

Lines changed: 7 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -562,14 +562,13 @@ def set_final_status(self) -> None:
562562
"finished_analysis_time",
563563
]
564564
)
565-
try:
566-
# we update the status of the analysis
567-
if root_investigation := self.get_root().investigation:
568-
root_investigation.set_correct_status(save=True)
569-
except Exception as e:
570-
logger.exception(
571-
f"investigation status not updated. Job: {self.pk}. Error: {e}"
572-
)
565+
# we update the status of the analysis
566+
if root_investigation := self.get_root().investigation:
567+
from api_app.investigations_manager.models import Investigation
568+
569+
logger.info(f"Updating status of investigation {root_investigation.pk}")
570+
root_investigation: Investigation
571+
root_investigation.set_correct_status(save=True)
573572

574573
def __get_config_reports(self, config: typing.Type["AbstractConfig"]) -> QuerySet:
575574
return getattr(self, f"{config.__name__.split('Config')[0].lower()}reports")

api_app/queryset.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,13 +15,13 @@
1515
from treebeard.mp_tree import MP_NodeQuerySet
1616

1717
if TYPE_CHECKING:
18-
from api_app.models import PythonConfig, AbstractConfig
18+
from api_app.models import PythonConfig
1919
from api_app.serializers import AbstractBIInterface
2020

2121
import logging
2222

2323
from celery.canvas import Signature
24-
from django.db import models
24+
from django.db import IntegrityError, models
2525
from django.db.models import (
2626
BooleanField,
2727
Case,
@@ -280,7 +280,16 @@ def create(self, parent=None, **kwargs):
280280
"""
281281
if parent:
282282
return parent.add_child(**kwargs)
283-
return self.model.add_root(**kwargs)
283+
try:
284+
return self.model.add_root(**kwargs)
285+
except IntegrityError as e:
286+
if "path" in str(e):
287+
logger.warning(
288+
f"Found race condition for {kwargs['name']}. Trying again to calculate path."
289+
)
290+
# we try again a second time, hoping for no race condition
291+
return self.model.add_root(**kwargs)
292+
raise
284293

285294
def delete(self, *args, **kwargs):
286295
"""

0 commit comments

Comments
 (0)