-
-
Notifications
You must be signed in to change notification settings - Fork 203
Expand file tree
/
Copy pathmodels.py
More file actions
2593 lines (2190 loc) · 84.7 KB
/
Copy pathmodels.py
File metadata and controls
2593 lines (2190 loc) · 84.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-License-Identifier: Apache-2.0
#
# http://nexb.com and https://github.com/nexB/scancode.io
# The ScanCode.io software is licensed under the Apache License version 2.0.
# Data generated with ScanCode.io is provided as-is without warranties.
# ScanCode is a trademark of nexB Inc.
#
# You may not use this software except in compliance with the License.
# You may obtain a copy of the License at: http://apache.org/licenses/LICENSE-2.0
# Unless required by applicable law or agreed to in writing, software distributed
# under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
# CONDITIONS OF ANY KIND, either express or implied. See the License for the
# specific language governing permissions and limitations under the License.
#
# Data Generated with ScanCode.io is provided on an "AS IS" BASIS, WITHOUT WARRANTIES
# OR CONDITIONS OF ANY KIND, either express or implied. No content created from
# ScanCode.io should be considered or used as legal advice. Consult an Attorney
# for any legal advice.
#
# ScanCode.io is a free software code scanning tool from nexB Inc. and others.
# Visit https://github.com/nexB/scancode.io for support and download.
import inspect
import json
import logging
import re
import shutil
import uuid
from collections import Counter
from contextlib import suppress
from itertools import groupby
from operator import itemgetter
from pathlib import Path
from traceback import format_tb
from django.apps import apps
from django.conf import settings
from django.core import checks
from django.core.exceptions import ObjectDoesNotExist
from django.core.serializers.json import DjangoJSONEncoder
from django.core.validators import EMPTY_VALUES
from django.db import models
from django.db import transaction
from django.db.models import Count
from django.db.models import IntegerField
from django.db.models import OuterRef
from django.db.models import Prefetch
from django.db.models import Q
from django.db.models import Subquery
from django.db.models import TextField
from django.db.models.functions import Cast
from django.db.models.functions import Lower
from django.dispatch import receiver
from django.forms import model_to_dict
from django.urls import reverse
from django.utils import timezone
from django.utils.functional import cached_property
from django.utils.text import slugify
from django.utils.translation import gettext_lazy as _
import django_rq
import redis
import requests
from commoncode.fileutils import parent_directory
from commoncode.hash import multi_checksums
from cyclonedx import model as cyclonedx_model
from cyclonedx.model import component as cyclonedx_component
from formattedcode.output_cyclonedx import CycloneDxExternalRef
from licensedcode.cache import build_spdx_license_expression
from packageurl import PackageURL
from packageurl import normalize_qualifiers
from packageurl.contrib.django.models import PackageURLMixin
from packageurl.contrib.django.models import PackageURLQuerySetMixin
from rest_framework.authtoken.models import Token
from rq.command import send_stop_job_command
from rq.exceptions import NoSuchJobError
from rq.job import Job
from rq.job import JobStatus
from scancodeio import __version__ as scancodeio_version
from scanpipe import tasks
logger = logging.getLogger(__name__)
scanpipe_app = apps.get_app_config("scanpipe")
class RunInProgressError(Exception):
"""Run are in progress or queued on this project."""
# PackageURL._fields
PURL_FIELDS = ("type", "namespace", "name", "version", "qualifiers", "subpath")
class UUIDPKModel(models.Model):
uuid = models.UUIDField(
verbose_name=_("UUID"),
primary_key=True,
default=uuid.uuid4,
editable=False,
db_index=True,
)
class Meta:
abstract = True
def __str__(self):
return str(self.uuid)
@property
def short_uuid(self):
return str(self.uuid)[0:8]
class HashFieldsMixin(models.Model):
"""
The hash fields are not indexed by default, use the `indexes` in Meta as needed:
class Meta:
indexes = [
models.Index(fields=['md5']),
models.Index(fields=['sha1']),
models.Index(fields=['sha256']),
models.Index(fields=['sha512']),
]
"""
md5 = models.CharField(
_("MD5"),
max_length=32,
blank=True,
help_text=_("MD5 checksum hex-encoded, as in md5sum."),
)
sha1 = models.CharField(
_("SHA1"),
max_length=40,
blank=True,
help_text=_("SHA1 checksum hex-encoded, as in sha1sum."),
)
sha256 = models.CharField(
_("SHA256"),
max_length=64,
blank=True,
help_text=_("SHA256 checksum hex-encoded, as in sha256sum."),
)
sha512 = models.CharField(
_("SHA512"),
max_length=128,
blank=True,
help_text=_("SHA512 checksum hex-encoded, as in sha512sum."),
)
class Meta:
abstract = True
class AbstractTaskFieldsModel(models.Model):
task_id = models.UUIDField(
blank=True,
null=True,
editable=False,
)
task_start_date = models.DateTimeField(
blank=True,
null=True,
editable=False,
)
task_end_date = models.DateTimeField(
blank=True,
null=True,
editable=False,
)
task_exitcode = models.IntegerField(
null=True,
blank=True,
editable=False,
)
task_output = models.TextField(
blank=True,
editable=False,
)
class Meta:
abstract = True
def delete(self, *args, **kwargs):
"""
Before deletion of the Run instance, try to stop the task if currently running
or to remove it from the queue if currently queued.
Note that projects with queued or running pipeline runs cannot be deleted.
See the `_raise_if_run_in_progress` method.
The following if statements should not be triggered unless the `.delete()`
method is directly call from a instance of this class.
"""
with suppress(redis.exceptions.ConnectionError, AttributeError):
if self.status == self.Status.RUNNING:
self.stop_task()
elif self.status == self.Status.QUEUED:
self.delete_task(delete_self=False)
return super().delete(*args, **kwargs)
@staticmethod
def get_job(job_id):
with suppress(NoSuchJobError):
return Job.fetch(job_id, connection=django_rq.get_connection())
@property
def job(self):
"""None if the job could not be found in the queues registries."""
return self.get_job(str(self.task_id))
@property
def job_status(self):
job = self.job
if job:
return self.job.get_status()
@property
def task_succeeded(self):
"""Return True if the task was successfully executed."""
return self.task_exitcode == 0
@property
def task_failed(self):
"""Return True if the task failed."""
return self.task_exitcode and self.task_exitcode > 0
@property
def task_stopped(self):
"""Return True if the task was stopped."""
return self.task_exitcode == 99
@property
def task_staled(self):
"""Return True if the task staled."""
return self.task_exitcode == 88
class Status(models.TextChoices):
"""List of Run status."""
NOT_STARTED = "not_started"
QUEUED = "queued"
RUNNING = "running"
SUCCESS = "success"
FAILURE = "failure"
STOPPED = "stopped"
STALE = "stale"
@property
def status(self):
"""Return the task current status."""
status = self.Status
if self.task_succeeded:
return status.SUCCESS
elif self.task_staled:
return status.STALE
elif self.task_stopped:
return status.STOPPED
elif self.task_failed:
return status.FAILURE
elif self.task_start_date:
return status.RUNNING
elif self.task_id:
return status.QUEUED
return status.NOT_STARTED
@property
def execution_time(self):
if self.task_staled:
return
elif self.task_end_date and self.task_start_date:
total_seconds = (self.task_end_date - self.task_start_date).total_seconds()
return int(total_seconds)
@property
def execution_time_for_display(self):
execution_time = self.execution_time
if execution_time:
message = f"{execution_time} seconds"
if execution_time > 3600:
message += f" ({execution_time / 3600:.1f} hours)"
elif execution_time > 60:
message += f" ({execution_time / 60:.1f} minutes)"
return message
def reset_task_values(self):
"""Reset all task-related fields to their initial null value."""
self.task_id = None
self.task_start_date = None
self.task_end_date = None
self.task_exitcode = None
self.task_output = ""
def set_task_started(self, task_id):
"""Set the `task_id` and `task_start_date` fields before executing the task."""
self.task_id = task_id
self.task_start_date = timezone.now()
self.save()
def set_task_ended(self, exitcode, output="", refresh_first=True):
"""
Set the task-related fields after the task execution.
An optional `refresh_first` —enabled by default— forces refreshing
the instance with the latest data from the database before saving.
This prevents losing values saved on the instance during the task
execution.
"""
if refresh_first:
self.refresh_from_db()
self.task_exitcode = exitcode
self.task_output = output
self.task_end_date = timezone.now()
self.save()
def set_task_queued(self):
"""
Set the task as "queued" by updating the `task_id` from None to this instance
`pk`.
Uses the QuerySet `update` method instead of `save` to prevent overriding
any fields that were set but not saved yet in the DB.
"""
manager = self.__class__.objects
return manager.filter(pk=self.pk, task_id__isnull=True).update(task_id=self.pk)
def set_task_staled(self):
"""Set the task as "stale" using a special 88 exitcode value."""
self.set_task_ended(exitcode=88)
def set_task_stopped(self):
"""Set the task as "stopped" using a special 99 exitcode value."""
self.set_task_ended(exitcode=99)
def stop_task(self):
"""Stop a "running" task."""
if not settings.SCANCODEIO_ASYNC:
self.set_task_stopped()
return
job_status = self.job_status
if not job_status:
self.set_task_staled()
return
if self.job_status == JobStatus.FAILED:
self.set_task_ended(
exitcode=1, output=f"Killed from outside, exc_info={self.job.exc_info}"
)
return
send_stop_job_command(
connection=django_rq.get_connection(), job_id=str(self.task_id)
)
self.set_task_stopped()
def delete_task(self, delete_self=True):
"""Delete a "not started" or "queued" task."""
if settings.SCANCODEIO_ASYNC and self.task_id:
job = self.job
if job:
self.job.delete()
if delete_self:
self.delete()
class ExtraDataFieldMixin(models.Model):
"""Add the `extra_data` field and helper methods."""
extra_data = models.JSONField(
default=dict,
blank=True,
help_text=_("Optional mapping of extra data key/values."),
)
def update_extra_data(self, data):
"""Update the `extra_data` field with the provided `data` dict."""
if type(data) != dict:
raise ValueError("Argument `data` value must be a dict()")
self.extra_data.update(data)
self.save()
class Meta:
abstract = True
def get_project_work_directory(project):
"""
Return the work directory location for a given `project`.
The `project` name is "slugified" to generate a nicer directory path without
any whitespace or special characters.
A short version of the `project` uuid is added as a suffix to ensure
uniqueness of the work directory location.
"""
project_workspace_id = f"{slugify(project.name)}-{project.short_uuid}"
return f"{scanpipe_app.workspace_path}/projects/{project_workspace_id}"
class ProjectQuerySet(models.QuerySet):
def with_counts(self, *fields):
"""
Annotate the QuerySet with counts of provided relational `fields`.
Using `Subquery` in place of the `Count` aggregate function as it results in
poor query performances when combining multiple counts.
Usage:
project_queryset.with_counts("codebaseresources", "discoveredpackages")
"""
annotations = {}
for field_name in fields:
count_label = f"{field_name}_count"
subquery_qs = self.model.objects.annotate(
**{count_label: Count(field_name)}
).filter(pk=OuterRef("pk"))
annotations[count_label] = Subquery(
subquery_qs.values(count_label),
output_field=IntegerField(),
)
return self.annotate(**annotations)
class Project(UUIDPKModel, ExtraDataFieldMixin, models.Model):
"""
The Project encapsulates all analysis processing.
Multiple analysis pipelines can be run on the same project.
"""
created_date = models.DateTimeField(
auto_now_add=True,
db_index=True,
help_text=_("Creation date for this project."),
)
name = models.CharField(
unique=True,
db_index=True,
max_length=100,
help_text=_("Name for this project."),
)
WORK_DIRECTORIES = ["input", "output", "codebase", "tmp"]
work_directory = models.CharField(
max_length=2048,
editable=False,
help_text=_("Project work directory location."),
)
input_sources = models.JSONField(default=dict, blank=True, editable=False)
is_archived = models.BooleanField(
default=False,
editable=False,
help_text=_(
"Archived projects cannot be modified anymore and are not displayed by "
"default in project lists. Multiple levels of data cleanup may have "
"happened during the archive operation."
),
)
objects = ProjectQuerySet.as_manager()
class Meta:
ordering = ["-created_date"]
def __str__(self):
return self.name
def save(self, *args, **kwargs):
"""
Save this project instance.
The workspace directories are set up during project creation.
"""
if not self.work_directory:
self.work_directory = get_project_work_directory(project=self)
self.setup_work_directory()
super().save(*args, **kwargs)
def archive(self, remove_input=False, remove_codebase=False, remove_output=False):
"""
Set the project `is_archived` field to True.
The `remove_input`, `remove_codebase`, and `remove_output` can be provided
during the archive operation to delete the related work directories.
The project cannot be archived if one of its related run is queued or already
running.
"""
self._raise_if_run_in_progress()
if remove_input:
shutil.rmtree(self.input_path, ignore_errors=True)
if remove_codebase:
shutil.rmtree(self.codebase_path, ignore_errors=True)
if remove_output:
shutil.rmtree(self.output_path, ignore_errors=True)
shutil.rmtree(self.tmp_path, ignore_errors=True)
self.setup_work_directory()
self.is_archived = True
self.save()
def delete(self, *args, **kwargs):
"""Delete the `work_directory` along project-related data in the database."""
self._raise_if_run_in_progress()
shutil.rmtree(self.work_directory, ignore_errors=True)
return super().delete(*args, **kwargs)
def reset(self, keep_input=True):
"""
Reset the project by deleting all related database objects and all work
directories except the input directory—when the `keep_input` option is True.
"""
self._raise_if_run_in_progress()
relationships = [
self.projecterrors,
self.runs,
self.discoveredpackages,
self.discovereddependencies,
self.codebaseresources,
]
for relation in relationships:
relation.all().delete()
work_directories = [
self.codebase_path,
self.output_path,
self.tmp_path,
]
if not keep_input:
work_directories.append(self.input_path)
self.input_sources = {}
self.extra_data = {}
self.save()
for path in work_directories:
shutil.rmtree(path, ignore_errors=True)
self.setup_work_directory()
def _raise_if_run_in_progress(self):
"""
Raise a `RunInProgressError` exception if one of the project related run is
queued or running.
"""
if self.runs.queued_or_running().exists():
raise RunInProgressError(
"Cannot execute this action until all associated pipeline runs are "
"completed."
)
def setup_work_directory(self):
"""Create all of the work_directory structure and skips if already existing."""
for subdirectory in self.WORK_DIRECTORIES:
Path(self.work_directory, subdirectory).mkdir(parents=True, exist_ok=True)
@property
def work_path(self):
"""Return the `work_directory` as a Path instance."""
return Path(self.work_directory)
@property
def input_path(self):
"""Return the `input` directory as a Path instance."""
return Path(self.work_path / "input")
@property
def output_path(self):
"""Return the `output` directory as a Path instance."""
return Path(self.work_path / "output")
@property
def codebase_path(self):
"""Return the `codebase` directory as a Path instance."""
return Path(self.work_path / "codebase")
@property
def tmp_path(self):
"""Return the `tmp` directory as a Path instance."""
return Path(self.work_path / "tmp")
def clear_tmp_directory(self):
"""
Delete the whole content of the tmp/ directory.
This is called at the end of each pipeline Run, and it doesn't store
any content that might be needed for further processing in following
pipeline Run.
"""
shutil.rmtree(self.tmp_path, ignore_errors=True)
self.tmp_path.mkdir(parents=True, exist_ok=True)
@property
def input_sources_list(self):
return [
{"filename": filename, "source": source}
for filename, source in self.input_sources.items()
]
def inputs(self, pattern="**/*"):
"""
Return all files and directories path of the input/ directory matching
a given `pattern`.
The default `**/*` pattern means "this directory and all subdirectories,
recursively".
Use the `*` pattern to only list the root content.
"""
return self.input_path.glob(pattern)
@property
def input_files(self):
"""Return list of files' relative paths in the input/ directory recursively."""
return [
str(path.relative_to(self.input_path))
for path in self.inputs()
if path.is_file()
]
@staticmethod
def get_root_content(directory):
"""
Return a list of all files and directories of a given `directory`.
Only the first level children will be listed.
"""
return [str(path.relative_to(directory)) for path in directory.glob("*")]
@property
def input_root(self):
"""
Return a list of all files and directories of the input/ directory.
Only the first level children will be listed.
"""
return self.get_root_content(self.input_path)
@property
def inputs_with_source(self):
"""
Return a list of inputs including the source, type, sha256, and size data.
Return the `missing_inputs` defined in the `input_sources` field but not
available in the input/ directory.
Only first level children will be listed.
"""
input_path = self.input_path
input_sources = dict(self.input_sources)
inputs = []
for path in input_path.glob("*"):
inputs.append(
{
"name": path.name,
"is_file": path.is_file(),
"size": path.stat().st_size,
**multi_checksums(path, ["sha256"]),
"source": input_sources.pop(path.name, "not_found"),
}
)
missing_inputs = input_sources
return inputs, missing_inputs
@property
def output_root(self):
"""
Return a list of all files and directories of the output/ directory.
Only first level children will be listed.
"""
return self.get_root_content(self.output_path)
def get_output_file_path(self, name, extension):
"""
Return a crafted file path in the project output/ directory using
given `name` and `extension`.
The current date and time strings are added to the filename.
This method ensures the proper setup of the work_directory in case of
a manual wipe and re-creates the missing pieces of the directory structure.
"""
from scanpipe.pipes import filename_now
self.setup_work_directory()
filename = f"{name}-{filename_now()}.{extension}"
return self.output_path / filename
def get_latest_output(self, filename):
"""
Return the latest output file with the "filename" prefix, for example
"scancode-<timestamp>.json".
"""
output_files = sorted(self.output_path.glob(f"*{filename}*.json"))
if output_files:
return output_files[-1]
def walk_codebase_path(self):
"""Return files and directories path of the codebase/ directory recursively."""
return self.codebase_path.rglob("*")
@cached_property
def can_add_input(self):
"""Return True until one pipeline run has started to execute on the project."""
return not self.runs.has_start_date().exists()
def add_input_source(self, filename, source, save=False):
"""
Add given `filename` and `source` to the current project's `input_sources`
field.
"""
self.input_sources[filename] = source
if save:
self.save()
def write_input_file(self, file_object):
"""Write the provided `file_object` to the project's input/ directory."""
filename = file_object.name
file_path = Path(self.input_path / filename)
with open(file_path, "wb+") as f:
for chunk in file_object.chunks():
f.write(chunk)
def copy_input_from(self, input_location):
"""
Copy the file at `input_location` to the current project's input/
directory.
"""
from scanpipe.pipes.input import copy_inputs
copy_inputs([input_location], self.input_path)
def move_input_from(self, input_location):
"""
Move the file at `input_location` to the current project's input/
directory.
"""
from scanpipe.pipes.input import move_inputs
move_inputs([input_location], self.input_path)
def add_downloads(self, downloads):
"""
Move the given `downloads` to the current project's input/ directory and
adds the `input_source` for each entry.
"""
for downloaded in downloads:
self.move_input_from(downloaded.path)
self.add_input_source(downloaded.filename, downloaded.uri)
self.save()
def add_uploads(self, uploads):
"""
Write the given `uploads` to the current project's input/ directory and
adds the `input_source` for each entry.
"""
for uploaded in uploads:
self.write_input_file(uploaded)
self.add_input_source(filename=uploaded.name, source="uploaded")
self.save()
def add_pipeline(self, pipeline_name, execute_now=False):
"""
Create a new Run instance with the provided `pipeline` on the current project.
If `execute_now` is True, the pipeline task is created.
on_commit() is used to postpone the task creation after the transaction is
successfully committed.
If there isn’t any active transactions, the callback will be executed
immediately.
"""
pipeline_class = scanpipe_app.pipelines.get(pipeline_name)
if not pipeline_class:
raise ValueError(f"Unknown pipeline: {pipeline_name}")
run = Run.objects.create(
project=self,
pipeline_name=pipeline_name,
description=pipeline_class.get_summary(),
)
if execute_now:
transaction.on_commit(run.execute_task_async)
return run
def add_webhook_subscription(self, target_url):
"""
Create a new WebhookSubscription instance with the provided `target_url` for
the current project.
"""
return WebhookSubscription.objects.create(project=self, target_url=target_url)
def get_next_run(self):
"""Return the next non-executed Run instance assigned to current project."""
with suppress(ObjectDoesNotExist):
return self.runs.not_started().earliest("created_date")
def get_latest_failed_run(self):
"""Return the latest failed Run instance of the current project."""
with suppress(ObjectDoesNotExist):
return self.runs.failed().latest("created_date")
def add_error(self, error, model, details=None):
"""
Create a "ProjectError" record from the provided `error` Exception for this
project.
The `model` attribute can be provided as a string or as a Model class.
"""
if inspect.isclass(model):
model = model.__name__
traceback = ""
if hasattr(error, "__traceback__"):
traceback = "".join(format_tb(error.__traceback__))
return ProjectError.objects.create(
project=self,
model=model,
details=details or {},
message=str(error),
traceback=traceback,
)
def get_absolute_url(self):
"""Return this project's details URL."""
return reverse("project_detail", args=[self.uuid])
@cached_property
def resource_count(self):
"""Return the number of resources related to this project."""
return self.codebaseresources.count()
@cached_property
def file_count(self):
"""Return the number of **file** resources related to this project."""
return self.codebaseresources.files().count()
@cached_property
def file_in_package_count(self):
"""
Return the number of **file** resources **in a package** related to this
project.
"""
return self.codebaseresources.files().in_package().count()
@cached_property
def file_not_in_package_count(self):
"""
Return the number of **file** resources **not in a package** related to this
project.
"""
return self.codebaseresources.files().not_in_package().count()
@cached_property
def package_count(self):
"""Return the number of packages related to this project."""
return self.discoveredpackages.count()
@cached_property
def dependency_count(self):
"""Return the number of dependencies related to this project."""
return self.discovereddependencies.count()
@cached_property
def error_count(self):
"""Return the number of errors related to this project."""
return self.projecterrors.count()
@cached_property
def has_single_resource(self):
"""
Return True if we only have a single CodebaseResource associated to this
project, False otherwise.
"""
return self.codebaseresources.count() == 1
class GroupingQuerySetMixin:
most_common_limit = settings.SCANCODEIO_MOST_COMMON_LIMIT
def group_by(self, field_name):
"""
Return a list of grouped values with their count, DESC ordered by count
for the provided `field_name`.
"""
return (
self.values(field_name).annotate(count=Count(field_name)).order_by("-count")
)
def most_common_values(self, field_name, limit=most_common_limit):
"""
Return a list of the most common values for the `field_name` ending at the
provided `limit`.
"""
return self.group_by(field_name)[:limit].values_list(field_name, flat=True)
def less_common_values(self, field_name, limit=most_common_limit):
"""
Return a list of the less common values for the `field_name` starting at the
provided `limit`.
"""
return self.group_by(field_name)[limit:].values_list(field_name, flat=True)
def less_common(self, field_name, limit=most_common_limit):
"""
Return a QuerySet filtered by the less common values for the provided
`field_name` starting at the `limit`.
"""
json_fields_mapping = {
"license_key": ("licenses", "key"),
"license_category": ("licenses", "category"),
"copyrights": ("copyrights", "copyright"),
"holders": ("holders", "holder"),
}
if field_name in json_fields_mapping:
field_name, data_field = json_fields_mapping.get(field_name)
values_list = self.values_from_json_field(field_name, data_field)
sorted_by_occurrence = list(dict(Counter(values_list).most_common()).keys())
less_common_values = sorted_by_occurrence[limit:]
return self.json_list_contains(field_name, data_field, less_common_values)
less_common_values = self.less_common_values(field_name, limit)
return self.filter(**{f"{field_name}__in": less_common_values})
class JSONFieldQuerySetMixin:
def json_field_contains(self, field_name, value):
"""
Filter the QuerySet looking for the `value` string in the `field_name` JSON
field converted into text.
Empty values are excluded as there's no need to cast those into text.
"""
return (
self.filter(~Q(**{field_name: []}))
.annotate(**{f"{field_name}_as_text": Cast(field_name, TextField())})
.filter(**{f"{field_name}_as_text__contains": value})
)
def json_list_contains(self, field_name, key, values):
"""
Filter on the JSONField `field_name` that stores a list of dictionaries.
json_list_contains("licenses", "name", ["MIT License", "Apache License 2.0"])
"""
lookups = Q()
for value in values:
lookups |= Q(**{f"{field_name}__contains": [{key: value}]})
return self.filter(lookups)
def values_from_json_field(self, field_name, data_field):
"""
Extract and return `data_field` values from each object of a JSONField
`field_name` that stores a list of dictionaries.
Empty value are kept in the return results as empty strings.
"""
values = []
for objects in self.values_list(field_name, flat=True):
if not objects:
values.append("")
else:
values.extend(
object_dict.get(data_field, "") for object_dict in objects
)
return values
class ProjectRelatedQuerySet(
GroupingQuerySetMixin, JSONFieldQuerySetMixin, models.QuerySet
):
def project(self, project):
return self.filter(project=project)
class ProjectRelatedModel(models.Model):
"""A base model for all models that are related to a Project."""
project = models.ForeignKey(
Project, related_name="%(class)ss", on_delete=models.CASCADE, editable=False
)
objects = ProjectRelatedQuerySet.as_manager()