-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathmodels.py
4266 lines (3622 loc) · 142 KB
/
models.py
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/aboutcode-org/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/aboutcode-org/scancode.io for support and download.
import inspect
import json
import logging
import re
import shutil
import uuid
from collections import Counter
from collections import defaultdict
from contextlib import suppress
from itertools import groupby
from operator import itemgetter
from pathlib import Path
from traceback import format_tb
from urllib.parse import urlparse
from django.apps import apps
from django.conf import settings
from django.core import checks
from django.core.exceptions import ObjectDoesNotExist
from django.core.exceptions import ValidationError
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 Case
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 import When
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 NoReverseMatch
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
import saneyaml
from commoncode.fileutils import parent_directory
from cyclonedx import model as cyclonedx_model
from cyclonedx.model import component as cyclonedx_component
from cyclonedx.model import license as cyclonedx_license
from extractcode import EXTRACT_SUFFIX
from licensedcode.cache import build_spdx_license_expression
from licensedcode.cache import get_licensing
from matchcode_toolkit.fingerprinting import IGNORED_DIRECTORY_FINGERPRINTS
from packagedcode.models import build_package_uid
from packagedcode.utils import get_base_purl
from packageurl import PackageURL
from packageurl import normalize_qualifiers
from packageurl.contrib.django.models import PACKAGE_URL_FIELDS
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 taggit.managers import TaggableManager
from taggit.models import GenericUUIDTaggedItemBase
from taggit.models import TaggedItemBase
import scancodeio
from scanpipe import humanize_time
from scanpipe import policies
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."""
class RunNotAllowedToStart(Exception):
"""Previous Runs have not completed yet."""
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):
"""
Base model including all the fields and methods to synchronize tasks in the
database with their related RQ Job.
Specify ``update_fields`` during each ``save()`` to force a SQL UPDATE in order to
avoid any data loss when the model fields are updated during the task execution.
"""
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,
)
log = 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):
"""Return the ``execution_time`` formatted for display."""
execution_time = self.execution_time
if execution_time:
return humanize_time(execution_time)
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 = ""
self.save(
update_fields=[
"task_id",
"task_start_date",
"task_end_date",
"task_exitcode",
"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(update_fields=["task_id", "task_start_date"])
def set_task_ended(self, exitcode, output=""):
"""Set the task-related fields after the task execution."""
self.task_exitcode = exitcode
self.task_output = output
self.task_end_date = timezone.now()
self.save(update_fields=["task_exitcode", "task_output", "task_end_date"])
def set_task_queued(self):
"""
Set the task as "queued" by updating the ``task_id`` from ``None`` to this
instance ``pk``.
"""
if self.task_id:
raise ValueError("task_id is already set")
self.task_id = self.pk
self.save(update_fields=["task_id"])
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."""
self.append_to_log("Stop task requested")
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, latest_result={self.job.latest_result()}",
)
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()
def append_to_log(self, message):
"""Append the ``message`` string to the ``log`` field of this instance."""
message = message.strip()
if any(lf in message for lf in ("\n", "\r")):
raise ValueError("message cannot contain line returns (either CR or LF).")
self.log = self.log + message + "\n"
self.save(update_fields=["log"])
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 not isinstance(data, dict):
raise ValueError("Argument `data` value must be a dict()")
self.extra_data.update(data)
self.save(update_fields=["extra_data"])
class Meta:
abstract = True
class UpdateMixin:
"""
Provide a ``update()`` method to trigger a save() on the object with the
``update_fields`` automatically set to force a SQL UPDATE.
"""
def update(self, **kwargs):
"""
Update this instance with the provided ``kwargs`` values.
The full ``save()`` process will be triggered, including signals, and the
``update_fields`` is automatically set.
"""
for field_name, value in kwargs.items():
setattr(self, field_name, value)
self.save(update_fields=list(kwargs.keys()))
class AdminURLMixin:
"""
A mixin to provide an admin URL for a model instance.
This mixin adds a method to generate the admin URL for a model instance,
which can be useful for linking to the admin interface directly from
the model instances.
"""
def get_admin_url(self):
"""
Return the URL for the admin change view of the instance.
The admin URL is only constructed and returned if the
SCANCODEIO_ENABLE_ADMIN_SITE setting is enabled.
"""
if not settings.SCANCODEIO_ENABLE_ADMIN_SITE:
return
opts = self._meta
viewname = f"admin:{opts.app_label}_{opts.model_name}_change"
try:
url = reverse(viewname, args=[self.pk])
except NoReverseMatch:
return
return url
def get_project_slug(project):
"""
Return a "slug" value for the provided ``project`` based on the slugify name
attribute combined with the ``short_uuid`` to ensure its uniqueness.
"""
return f"{slugify(project.name)}-{project.short_uuid}"
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 = get_project_slug(project)
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)
def get_active_archived_counts(self):
return self.aggregate(
active_count=Count(
Case(When(is_archived=False, then=1), output_field=IntegerField())
),
archived_count=Count(
Case(When(is_archived=True, then=1), output_field=IntegerField())
),
)
class UUIDTaggedItem(GenericUUIDTaggedItemBase, TaggedItemBase):
class Meta:
verbose_name = _("Label")
verbose_name_plural = _("Labels")
class Project(UUIDPKModel, ExtraDataFieldMixin, UpdateMixin, 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,
help_text=_("Creation date for this project."),
)
name = models.CharField(
unique=True,
max_length=100,
help_text=_("Name for this project."),
)
slug = models.SlugField(
unique=True,
max_length=110, # enough for name.max_length + len(short_uuid)
)
WORK_DIRECTORIES = ["input", "output", "codebase", "tmp"]
work_directory = models.CharField(
max_length=2048,
editable=False,
help_text=_("Project work directory location."),
)
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."
),
)
notes = models.TextField(blank=True)
settings = models.JSONField(default=dict, blank=True)
labels = TaggableManager(through=UUIDTaggedItem, ordering=["name"])
purl = models.CharField(
max_length=2048,
blank=True,
help_text=_(
"Package URL (PURL) for the project, required for pushing the project's "
"scan result to FederatedCode. For example, if the input is an input URL "
"like https://registry.npmjs.org/lodash/-/lodash-4.17.21.tgz, the "
"corresponding PURL would be pkg:npm/[email protected]."
),
)
objects = ProjectQuerySet.as_manager()
class Meta:
ordering = ["-created_date"]
indexes = [
models.Index(fields=["-created_date"]),
models.Index(fields=["is_archived"]),
models.Index(fields=["name"]),
]
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.slug:
self.slug = get_project_slug(project=self)
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:
# Delete the file on disk but keep the InputSource entries for reference.
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.update(is_archived=True)
def delete_related_objects(self, keep_input=False, keep_labels=False):
"""
Delete all related object instances using the private `_raw_delete` model API.
This bypass the objects collection, cascade deletions, and signals.
It results in a much faster objects deletion, but it needs to be applied in the
correct models order as the cascading event will not be triggered.
Note that this approach is used in Django's `fast_deletes` but the scanpipe
models cannot be fast-deleted as they have cascades and relations.
"""
# Use default `delete()` on the DiscoveredPackage model, as the
# `codebase_resources (ManyToManyField)` records need to collected and
# properly deleted first.
# Since this `ManyToManyField` has an implicit model table, we cannot directly
# run the `_raw_delete()` on its QuerySet.
_, deleted_counter = self.discoveredpackages.all().delete()
# Removes all tags from this project by deleting the UUIDTaggedItem instances.
if not keep_labels:
self.labels.clear()
relationships = [
self.webhookdeliveries,
self.webhooksubscriptions,
self.projectmessages,
self.codebaserelations,
self.discovereddependencies,
self.codebaseresources,
self.runs,
]
if not keep_input:
relationships.append(self.inputsources)
for qs in relationships:
count = qs.all()._raw_delete(qs.db)
deleted_counter[qs.model._meta.label] = count
return deleted_counter
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)
# Start with the optimized deletion of the related objects before calling the
# full `delete()` process.
self.delete_related_objects()
return super().delete(*args, **kwargs)
def reset(self, keep_input=True, restore_pipelines=False, execute_now=False):
"""
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()
restore_pipeline_kwargs = []
if restore_pipelines:
restore_pipeline_kwargs = [
{
"pipeline_name": run.pipeline_name,
"execute_now": execute_now,
"selected_groups": run.selected_groups,
}
for run in self.runs.all()
]
self.delete_related_objects(keep_input=keep_input, keep_labels=True)
work_directories = [
self.codebase_path,
self.output_path,
self.tmp_path,
]
if not keep_input:
work_directories.append(self.input_path)
self.inputsources.all().delete()
self.extra_data = {}
self.save()
for path in work_directories:
shutil.rmtree(path, ignore_errors=True)
self.setup_work_directory()
for pipeline_kwargs in restore_pipeline_kwargs:
self.add_pipeline(**pipeline_kwargs)
def clone(
self,
clone_name,
copy_inputs=False,
copy_pipelines=False,
copy_settings=False,
copy_subscriptions=False,
execute_now=False,
):
"""Clone this project using the provided ``clone_name`` as new project name."""
new_project = Project.objects.create(
name=clone_name,
purl=self.purl,
settings=self.settings if copy_settings else {},
)
if labels := self.labels.names():
new_project.labels.add(*labels)
if copy_inputs:
# Clone the InputSource instances
for input_source in self.inputsources.all():
input_source.clone(to_project=new_project)
# Copy the files from the input work directory
for input_location in self.inputs():
new_project.copy_input_from(input_location)
if copy_pipelines:
for run in self.runs.all():
new_project.add_pipeline(
run.pipeline_name, execute_now, selected_groups=run.selected_groups
)
if copy_subscriptions:
for subscription in self.webhooksubscriptions.all():
subscription.clone(to_project=new_project)
return new_project
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 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 get_codebase_config_directory(self):
"""
Return the ``.scancode`` config directory if available in the `codebase`
directory.
"""
config_directory = self.codebase_path / settings.SCANCODEIO_CONFIG_DIR
if config_directory.exists():
return config_directory
def get_file_from_work_directory(self, filename):
"""
Return the ``filename`` file from the input/ directory
or from the codebase/ immediate subdirectories.
Priority order:
1. If a ``filename`` file exists directly in the input/ directory, return it.
2. If exactly one ``filename`` file exists in a codebase/ immediate
subdirectory, return it.
3. If multiple ``filename`` files are found in subdirectories, report an error.
"""
# Check for the ``filename`` file in the root of the input/ directory.
root_file = self.input_path / filename
if root_file.exists():
return root_file
# Search for files in immediate codebase/ subdirectories.
subdir_files = list(self.codebase_path.glob(f"*/{filename}"))
# If exactly one file is found in codebase/ subdirectories, return it.
if len(subdir_files) == 1:
return subdir_files[0]
# If multiple files are found, report an error.
if len(subdir_files) > 1:
self.add_warning(
f"More than one {filename} found. "
f"Could not determine which one to use.",
model="Project",
details={
"resources": [
str(path.relative_to(self.work_path)) for path in subdir_files
]
},
)
def get_input_config_file(self):
"""
Return the ``scancode-config.yml`` file from the input/ directory
or from the codebase/ immediate subdirectories.
"""
config_filename = settings.SCANCODEIO_CONFIG_FILE
return self.get_file_from_work_directory(config_filename)
def get_input_policies_file(self):
"""
Return the "policies.yml" file from the input/ directory
or from the codebase/ immediate subdirectories.
"""
return self.get_file_from_work_directory("policies.yml")
def get_settings_as_yml(self):
"""Return the ``settings`` file content as yml, suitable for a config file."""
return saneyaml.dump(self.settings)
def get_enabled_settings(self):
"""Return the enabled settings with non-empty values."""
return {
option: value
for option, value in self.settings.items()
if value not in EMPTY_VALUES
}
def get_env_from_config_file(self):
"""Return ``env`` dict loaded from the ``scancode-config.yml`` config file."""
config_file = self.get_input_config_file()
if not config_file:
return
logger.info(f"Loading env from {config_file.relative_to(self.work_path)}")
try:
return saneyaml.load(config_file.read_text())
except (saneyaml.YAMLError, Exception):
self.add_error(
f'Failed to load configuration from "{config_file}". '
f"The file format is invalid."
)
def get_env(self, field_name=None):
"""
Return the project environment loaded from the ``scancode-config.yml`` config
file, when available, and overridden by the ``settings`` model field.
``field_name`` can be provided to get a single entry from the env.
"""
env = {}
# 1. Load settings from config file when available.
if env_from_config_file := self.get_env_from_config_file():
env = env_from_config_file
# 2. Update with defined values from the Project ``settings`` field.
env.update(self.get_enabled_settings())
if field_name:
return env.get(field_name)
return env
def get_ignored_dependency_scopes_index(self):
"""
Return a dictionary index of the ``ignored_dependency_scopes`` setting values
defined in this Project env.
"""
ignored_dependency_scopes = self.get_env(field_name="ignored_dependency_scopes")
if not ignored_dependency_scopes:
return {}
ignored_scope_index = defaultdict(list)
for entry in ignored_dependency_scopes:
ignored_scope_index[entry.get("package_type")].append(entry.get("scope"))
return dict(ignored_scope_index)
@cached_property
def get_scan_max_file_size(self):
"""
Return a the ``scan_max_file_size`` settings value defined in this
Project env.
"""
scan_max_file_size = self.get_env(field_name="scan_max_file_size")
if scan_max_file_size:
return scan_max_file_size
@cached_property
def ignored_dependency_scopes_index(self):
"""
Return the computed value of get_ignored_dependency_scopes_index.
The value is only generated once and cached for further calls.
"""
return self.get_ignored_dependency_scopes_index()
def get_ignored_vulnerabilities_set(self):
"""
Return a set of ``ignored_vulnerabilities`` setting values defined in this
Project env.
"""
ignored_vulnerabilities = self.get_env(field_name="ignored_vulnerabilities")
if ignored_vulnerabilities:
return set(entry for entry in ignored_vulnerabilities)
return []
@cached_property
def ignored_vulnerabilities_set(self):
"""
Return the computed value of get_ignored_vulnerabilities_set.
The value is only generated once and cached for further calls.
"""
return self.get_ignored_vulnerabilities_set()
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)
def inputs(self, pattern="**/*", extensions=None):
"""
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.
The returned paths can be limited to the provided list of ``extensions``.
"""
if not extensions:
return self.input_path.glob(pattern)
if not isinstance(extensions, list | tuple):
raise TypeError("extensions should be a list or tuple")
return (
path