2756 dangling snapshots

This commit is contained in:
Cezary Statkiewicz committed 2024-09-24 09:43:47 +00:00
1 parent 04a7fa5caa
commit e0a07588ab
42 files changed
+1644 -251

No files matched your search

+6
View File
@@ -10,3 +10,9 @@ ERROR_MAX_JOB_COUNT_EXCEEDED = (
HTTP_400_BAD_REQUEST,
"Max running job count for this type is exceeded.",
)
ERROR_JOB_NOT_CANCELLABLE = (
"ERROR_JOB_NOT_CANCELLABLE",
HTTP_400_BAD_REQUEST,
"The job cannot be cancelled",
)
+12 -2
View File
@@ -4,11 +4,21 @@ from drf_spectacular.types import OpenApiTypes
from drf_spectacular.utils import extend_schema_field
from rest_framework import serializers
from baserow.core.jobs.constants import JOB_FAILED, JOB_FINISHED, JOB_PENDING
from baserow.core.jobs.constants import (
JOB_CANCELLED,
JOB_FAILED,
JOB_FINISHED,
JOB_PENDING,
)
from baserow.core.jobs.models import Job
from baserow.core.jobs.registries import job_type_registry
VALID_JOB_STATES = [JOB_PENDING, JOB_FINISHED, JOB_FAILED]
VALID_JOB_STATES = [
JOB_PENDING,
JOB_FINISHED,
JOB_FAILED,
JOB_CANCELLED,
]
class JobSerializer(serializers.ModelSerializer):
+2 -1
View File
@@ -1,10 +1,11 @@
from django.urls import re_path
from .views import JobsView, JobView
from .views import CancelJobView, JobsView, JobView
app_name = "baserow.api.jobs"
urlpatterns = [
re_path(r"^$", JobsView.as_view(), name="list"),
re_path(r"(?P<job_id>[0-9]+)/$", JobView.as_view(), name="item"),
re_path(r"(?P<job_id>[0-9]+)/cancel/$", CancelJobView.as_view(), name="cancel"),
]
+71 -7
View File
@@ -13,11 +13,19 @@ from baserow.api.decorators import (
)
from baserow.api.schemas import get_error_schema
from baserow.api.utils import DiscriminatorCustomFieldsMappingSerializer
from baserow.core.jobs.exceptions import JobDoesNotExist, MaxJobCountExceeded
from baserow.core.jobs.exceptions import (
JobDoesNotExist,
JobNotCancellable,
MaxJobCountExceeded,
)
from baserow.core.jobs.handler import JobHandler
from baserow.core.jobs.registries import job_type_registry
from .errors import ERROR_JOB_DOES_NOT_EXIST, ERROR_MAX_JOB_COUNT_EXCEEDED
from .errors import (
ERROR_JOB_DOES_NOT_EXIST,
ERROR_JOB_NOT_CANCELLABLE,
ERROR_MAX_JOB_COUNT_EXCEEDED,
)
from .serializers import CreateJobSerializer, JobSerializer, ListJobQuerySerializer
@@ -31,7 +39,7 @@ class JobsView(APIView):
location=OpenApiParameter.QUERY,
type=OpenApiTypes.STR,
description="A comma separated list of jobs state to look for. "
"The only possible values are: `pending`, `finished` and `failed`. "
"The only possible values are: `pending`, `finished`, `failed` and `cancelled`. "
"It's possible to exclude a state by prefixing it with a `!`. ",
),
OpenApiParameter(
@@ -61,13 +69,17 @@ class JobsView(APIView):
states = query_params.get("states", None)
job_ids = query_params.get("job_ids", None)
jobs = JobHandler().get_jobs_for_user(
jobs = JobHandler.get_jobs_for_user(
request.user, filter_states=states, filter_ids=job_ids
)
# FIXME: job.specific makes a query for each job to get the specific instance.
# As long as we have max_count=1 for each job type, there's not much we can do,
# but this should be optimized in the future if we allow multiple jobs of the
# same type.
serialized_jobs = [
job_type_registry.get_serializer(
job,
job.specific,
JobSerializer,
context={"request": request},
).data
@@ -166,9 +178,61 @@ class JobView(APIView):
def get(self, request, job_id):
"""Returns the job related to the provided id."""
job = JobHandler().get_job(request.user, job_id)
job = JobHandler.get_job(request.user, job_id)
serializer = job_type_registry.get_serializer(
job,
job.specific,
JobSerializer,
context={"request": request},
)
return Response(serializer.data)
class CancelJobView(APIView):
permission_classes = (IsAuthenticated,)
@extend_schema(
parameters=[
OpenApiParameter(
name="job_id",
location=OpenApiParameter.PATH,
type=OpenApiTypes.INT,
description="The job id to cancel.",
)
],
tags=["Jobs"],
operation_id="cancel_job",
description=(
"Cancels a job. Note: you can cancel only "
"a scheduled or a job that is already running. The user "
"requesting must be the owner of the job to cancel."
),
responses={
200: DiscriminatorCustomFieldsMappingSerializer(
job_type_registry, JobSerializer
),
400: get_error_schema(["ERROR_JOB_NOT_CANCELLABLE"]),
404: get_error_schema(["ERROR_JOB_DOES_NOT_EXIST"]),
},
)
@map_exceptions(
{
JobDoesNotExist: ERROR_JOB_DOES_NOT_EXIST,
JobNotCancellable: ERROR_JOB_NOT_CANCELLABLE,
}
)
def post(self, request, job_id):
"""Cancels a job.
This endpoint can be used to cancel a job that is currently running or
scheduled to run. The user requesting must be the owner of the job to
cancel.
"""
job = JobHandler.get_job(request.user, job_id)
JobHandler.cancel_job(job)
serializer = job_type_registry.get_serializer(
job.specific,
JobSerializer,
context={"request": request},
)
@@ -14,10 +14,16 @@ class SnapshotSerializer(serializers.ModelSerializer):
class Meta:
model = Snapshot
fields = ["id", "name", "snapshot_from_application", "created_by", "created_at"]
fields = [
"id",
"name",
"snapshot_from_application",
"created_at",
"created_by",
]
read_only_fields = [
"id",
"snapshot_from_application",
"created_by",
"created_at",
"created_by",
]
@@ -1,4 +1,5 @@
import json
from typing import Any
from django.core.files.base import ContentFile
from django.db import transaction
@@ -127,6 +128,25 @@ class FileImportJobType(JobType):
return read_committed_single_table_transaction(job.table_id)
def cleanup_job(self, job: FileImportJob, error_report: dict[str, Any]):
"""
Removes the data file to save space and save the error report.
This will be executed when a job finished successfully.
:param job: The job instance.
:param error_report: The error report that should be saved.
"""
job.data_file.delete(save=False)
job.report = {"failing_rows": error_report}
job.save(
update_fields=(
"report",
"data_file",
"updated_on",
)
)
def run(self, job, progress):
"""
Fills the provided table with the normalized data that needs to be created upon
@@ -136,36 +156,46 @@ class FileImportJobType(JobType):
with job.data_file.open("r") as fin:
data = json.load(fin)
if job.table is None:
new_table, error_report = action_type_registry.get_by_type(
CreateTableActionType
).do(
job.user,
job.database,
name=job.name,
data=data,
first_row_header=job.first_row_header,
progress=progress,
)
try:
if job.table is None:
new_table, error_report = action_type_registry.get_by_type(
CreateTableActionType
).do(
job.user,
job.database,
name=job.name,
data=data,
first_row_header=job.first_row_header,
progress=progress,
)
job.table = new_table
job.save(update_fields=("table",))
else:
_, error_report = action_type_registry.get_by_type(ImportRowsActionType).do(
job.user,
table=job.table,
data=data,
progress=progress,
)
job.table = new_table
job.save(update_fields=("table",))
else:
_, error_report = action_type_registry.get_by_type(
ImportRowsActionType
).do(
job.user,
table=job.table,
data=data,
progress=progress,
)
# when a job handler fails, celery worker will not commit and `after_commit`
# won't be called. That's why we need to catch this specific error and
# perform a bit of cleanup on the job.
except ReportMaxErrorCountExceeded as err:
self.cleanup_job(job, err.report)
raise
except Exception:
raise
def after_commit():
"""
Removes the data file to save space and save the error report.
This will be executed when a job finished successfully.
"""
job.refresh_from_db()
job.data_file.delete(save=False)
job.report = {"failing_rows": error_report}
job.save(update_fields=("report", "data_file"))
self.cleanup_job(job, error_report)
transaction.on_commit(after_commit)
+1 -1
View File
@@ -1,2 +1,2 @@
def job_progress_key(job_id: int):
def job_progress_key(job_id: int) -> str:
return f"core_job_progress_{job_id}"
@@ -1,4 +1,5 @@
JOB_PENDING = "pending"
JOB_STARTED = "started"
JOB_CANCELLED = "cancelled"
JOB_FAILED = "failed"
JOB_FINISHED = "finished"
@@ -23,3 +23,15 @@ class JobTypeAlreadyRegistered(InstanceTypeAlreadyRegistered):
Raised when trying to register a job type that exists
already.
"""
class JobCancelled(Exception):
"""
Raised when a job has been canceled while running.
"""
class JobNotCancellable(Exception):
"""
Raised when a job cannot be cancelled.
"""
+98 -55
View File
@@ -3,15 +3,17 @@ from typing import List, Optional, Type
from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.core.cache import cache
from django.db import transaction
from django.db.models import Q, QuerySet
from baserow.core.utils import Progress
from .cache import job_progress_key
from .constants import JOB_FAILED, JOB_PENDING
from .exceptions import JobDoesNotExist, MaxJobCountExceeded
from .exceptions import (
JobCancelled,
JobDoesNotExist,
JobNotCancellable,
MaxJobCountExceeded,
)
from .models import Job
from .registries import job_type_registry
from .tasks import run_async_job
@@ -19,7 +21,30 @@ from .types import AnyJob
class JobHandler:
def run(self, job: AnyJob):
@classmethod
def cancel_job(cls, job: AnyJob) -> Job | None:
"""
Marks a job for cancellation. It will mark the job as cancelled, but won't
cancel a Celery task directly. The task's responsible to drop job's processing
as soon as it detects the marker.
:param job: The job to cancel.
:return: The job that was marked for cancellation.
:raises JobNotCancellable: If the job is already finished and cannot be
cancelled.
"""
if job.cancelled:
return
if job.finished:
raise JobNotCancellable()
job.set_state_cancelled()
job.save()
return job
@classmethod
def run(cls, job: AnyJob):
def progress_updated(percentage, state):
"""
Every time the progress of the job changes, this callback function is
@@ -27,39 +52,36 @@ class JobHandler:
"""
nonlocal job
changed = False
if job.progress_percentage != percentage:
job.progress_percentage = percentage
changed = True
# Periodically check for a job cancellation marker. Users can cancel jobs
# via the UI, but this won't stop tasks already running in Celery. To handle
# cancellations within a worker, the JobType.run method should periodically
# check for a cancellation marker, either manually or whenever Progress
# methods are called.
if job.cancelled:
raise JobCancelled()
job.progress_percentage = percentage
if state is not None and job.state != state:
job.state = state
changed = True
if changed:
# The progress must also be stored in the Redis cache. Because we're
# currently in a transaction, other database connections don't know
# about the progress and this way, we can still communicate it to
# the user.
cache.set(
job_progress_key(job.id),
{
"progress_percentage": job.progress_percentage,
"state": job.state,
},
timeout=None,
)
job.save()
if state:
job.set_state(state)
job.set_cached_state()
progress = Progress(100)
progress.register_updated_event(progress_updated)
job_type = job_type_registry.get_by_model(job)
return job_type.run(job, progress)
out = job_type.run(job, progress)
@staticmethod
# Final check if the job was cancelled because we don't want to overwrite the
# state if the `job_type.run` didn't notice the cancellation.
if job.cancelled:
raise JobCancelled()
return out
@classmethod
def get_job(
cls,
user: AbstractUser,
job_id: int,
job_model: Optional[Type[AnyJob]] = None,
@@ -86,8 +108,9 @@ class JobHandler:
except Job.DoesNotExist:
raise JobDoesNotExist(f"The job with id {job_id} does not exist.")
@classmethod
def get_jobs_for_user(
self,
cls,
user: AbstractUser,
filter_states: Optional[List[str]],
filter_ids: Optional[List[int]],
@@ -121,8 +144,9 @@ class JobHandler:
return queryset.select_related("content_type")
@classmethod
def get_pending_or_running_jobs(
self,
cls,
job_type_name: str,
) -> QuerySet:
"""
@@ -165,7 +189,7 @@ class JobHandler:
)
job_values = job_type.prepare_values(kwargs, user)
job = model_class.objects.create(user=user, **job_values)
job: AnyJob = model_class.objects.create(user=user, **job_values)
job_type.after_job_creation(job, kwargs)
if sync:
@@ -180,11 +204,10 @@ class JobHandler:
run_async_job.delay(job.id)
except BaseException as e:
job.refresh_from_db()
if job.state == JOB_PENDING:
job.state = JOB_FAILED
job.error = str(e)
job.human_readable_error = (
f"Something went wrong during the job({job.id}) execution."
if job.pending:
job.set_state_failed(
str(e),
f"Something went wrong during the job({job.id}) execution.",
)
job.save()
raise
@@ -199,30 +222,50 @@ class JobHandler:
"""
# Delete old job
limit_date = datetime.now(tz=timezone.utc) - timedelta(
now = datetime.now(tz=timezone.utc)
limit_date = now - timedelta(
minutes=(settings.BASEROW_JOB_EXPIRATION_TIME_LIMIT)
)
for job_to_delete in Job.objects.filter(
created_on__lte=limit_date
).is_finished():
job_type = job_type_registry.get_by_model(job_to_delete.specific)
job_type.before_delete(job_to_delete.specific)
job_to_delete.delete()
self.delete_job(job_to_delete.specific)
# Expire non expired jobs
limit_date = datetime.now(tz=timezone.utc) - timedelta(
seconds=(settings.BASEROW_JOB_SOFT_TIME_LIMIT + 1)
)
limit_date = now - timedelta(seconds=(settings.BASEROW_JOB_SOFT_TIME_LIMIT + 1))
(
Job.objects.filter(created_on__lte=limit_date)
.is_pending_or_running()
.update(
state=JOB_FAILED,
human_readable_error=(
"Something went wrong during the file_import job execution."
),
error="Unknown error",
updated_on=datetime.now(tz=timezone.utc),
# Use updated_on instead of created_on to verify the last update date
# but use the cache since the DB is not updated until the end of the transaction
jobs_to_update = []
for job in Job.objects.filter(
created_on__lte=limit_date
).is_pending_or_running():
if (
last_updated_on := job.last_updated_on
) and last_updated_on < limit_date:
job.set_state_failed(
"Timeout error",
"Something went wrong during the job execution.",
)
# Set the updated_on manually because it won't be set by bulk_update
job.updated_on = now
jobs_to_update.append(job)
if jobs_to_update:
Job.objects.bulk_update(
jobs_to_update,
fields=["updated_on", "state", "error", "human_readable_error"],
)
)
@classmethod
def delete_job(cls, job: Type[Job]):
"""
Deletes a job, calls the job type's before_delete method and clears the job
cache.
:param job: The specific job to delete.
"""
job_type = job_type_registry.get_by_model(job)
job_type.before_delete(job)
job.clear_job_cache()
job.delete()
+118 -7
View File
@@ -1,3 +1,4 @@
from datetime import datetime
from typing import Any
from django.contrib.auth import get_user_model
@@ -8,10 +9,19 @@ from django.db import models
from baserow.core.mixins import CreatedAndUpdatedOnMixin, PolymorphicContentTypeMixin
from .cache import job_progress_key
from .constants import JOB_FAILED, JOB_FINISHED, JOB_PENDING
from .constants import JOB_CANCELLED, JOB_FAILED, JOB_FINISHED, JOB_PENDING, JOB_STARTED
User = get_user_model()
JOB_STATES_FAILED = (
JOB_CANCELLED,
JOB_FAILED,
)
JOB_STATES_FINISHED = JOB_STATES_FAILED + (JOB_FINISHED,)
JOB_STATES_NOT_RUNNING = JOB_STATES_FINISHED + (JOB_PENDING,)
JOB_STATES_RUNNING = (JOB_STARTED,)
JOB_STATES_PENDING = (JOB_PENDING,)
def get_default_job_content_type():
return ContentType.objects.get_for_model(Job)
@@ -19,13 +29,13 @@ def get_default_job_content_type():
class JobQuerySet(models.QuerySet):
def is_running(self):
return self.exclude(state__in=[JOB_PENDING, JOB_FINISHED, JOB_FAILED])
return self.exclude(state__in=JOB_STATES_NOT_RUNNING)
def is_finished(self):
return self.filter(state__in=[JOB_FINISHED, JOB_FAILED])
return self.filter(state__in=JOB_STATES_FINISHED)
def is_pending_or_running(self):
return self.exclude(state__in=[JOB_FINISHED, JOB_FAILED])
return self.exclude(state__in=JOB_STATES_FINISHED)
class Job(CreatedAndUpdatedOnMixin, PolymorphicContentTypeMixin, models.Model):
@@ -60,6 +70,17 @@ class Job(CreatedAndUpdatedOnMixin, PolymorphicContentTypeMixin, models.Model):
objects = JobQuerySet.as_manager()
def get_from_cache(self) -> dict | None:
"""
Returns cached state for the job. Cached state is set with
Job.set_cached_state().
If no state is present in cache, returns None.
:return:
"""
return cache.get(job_progress_key(self.id))
def get_from_cached_value_or_from_self(self, name: str) -> Any:
"""
Because the `progress_percentage` and `state` are updated via a transaction,
@@ -75,9 +96,7 @@ class Job(CreatedAndUpdatedOnMixin, PolymorphicContentTypeMixin, models.Model):
:return: The correct value.
"""
return cache.get(job_progress_key(self.id), default={}).get(
name, getattr(self, name)
)
return (self.get_from_cache() or {}).get(name, getattr(self, name))
def get_cached_progress_percentage(self) -> int:
return self.get_from_cached_value_or_from_self("progress_percentage")
@@ -88,3 +107,95 @@ class Job(CreatedAndUpdatedOnMixin, PolymorphicContentTypeMixin, models.Model):
class Meta:
ordering = ("id",)
indexes = [models.Index(fields=["-updated_on"])]
def set_cached_state(self):
"""
Updates job progress cache key.
"""
progress = {
"progress_percentage": self.progress_percentage,
"state": self.state,
"updated_on": datetime.now(),
}
cache.set(job_progress_key(self.id), progress, timeout=None)
def set_state(
self, state: str, error: str | None = None, message: str | None = None
):
"""
Helper method to set a state on a job.
:param state: One of JOB_* states
:param error: Short error message
:param message: Longer, human readable error description
"""
self.state = state
if error is not None:
self.error = error
if message is not None:
self.human_readable_error = message
self.set_cached_state()
def set_state_cancelled(self):
"""
Mark job as pending cancellatttion
"""
self.set_state(JOB_CANCELLED)
def set_state_failed(self, error: str, message: str):
"""
Mark job as failed with an error.
:param error: Short error message.
:param message: Longer, human readable error description.
"""
self.set_state(JOB_FAILED, error, message)
def set_state_started(self):
"""
Mark job as started
"""
self.set_state(JOB_STARTED)
def set_state_finished(self):
"""
Mark job as started
"""
self.set_state(JOB_FINISHED)
@property
def last_updated_on(self) -> datetime | None:
return self.get_from_cached_value_or_from_self("updated_on")
@property
def pending(self) -> bool:
return self.get_cached_state() == JOB_PENDING
@property
def failed(self) -> bool:
return self.get_cached_state() == JOB_FAILED
@property
def cancelled(self) -> bool:
return self.get_cached_state() == JOB_CANCELLED
@property
def started(self) -> bool:
return self.get_cached_state() == JOB_STARTED
@property
def finished(self) -> bool:
return self.get_cached_state() == JOB_FINISHED
def clear_job_cache(self):
"""
Clears job's cache entries.
"""
cache.delete(job_progress_key(self.id))
@@ -45,6 +45,12 @@ class JobType(
messages.
"""
max_count: int = 1
"""
A number of max jobs count for the same type for a given user.
"""
def transaction_atomic_context(self, job: Job):
"""
This method gives the possibility to change the transaction context per request.
+20 -30
View File
@@ -3,6 +3,7 @@ from datetime import timedelta
from django.conf import settings
from baserow.config.celery import app
from baserow.core.jobs.exceptions import JobCancelled
from baserow.core.jobs.registries import job_type_registry
@@ -14,30 +15,33 @@ from baserow.core.jobs.registries import job_type_registry
def run_async_job(self, job_id: int):
"""Run the job task asynchronously"""
from django.core.cache import cache
from celery.exceptions import SoftTimeLimitExceeded
from baserow.core.jobs.constants import JOB_FAILED, JOB_FINISHED, JOB_STARTED
from baserow.core.jobs.handler import JobHandler
from baserow.core.jobs.models import Job
from .cache import job_progress_key
job = Job.objects.get(id=job_id).specific
if job.cancelled:
return # Job cancelled before it started. No need to run it.
job_type = job_type_registry.get_by_model(job)
job.state = JOB_STARTED
job.save(update_fields=("state",))
job.set_state_started()
job.save()
try:
with job_type.transaction_atomic_context(job):
JobHandler().run(job)
JobHandler.run(job)
job.state = JOB_FINISHED
# Don't override the other properties that have been set during the
# progress update.
job.save(update_fields=("state",))
except BaseException as e: # We also want to catch SystemExit exception here.
job.set_state_finished()
job.save()
except JobCancelled:
# It shouldn't be necessary because the JobHandler shouldn't call job.save(),
# but this guarantees that the job is in the cancelled state at the end.
job.set_state_cancelled()
job.save()
except BaseException as e:
# We also want to catch SystemExit exception here and all other possible
# exceptions to set the job state in a failed state.
error = f"Something went wrong during the {job_type.type} job execution."
exception_mapping = {
@@ -51,28 +55,14 @@ def run_async_job(self, job_id: int):
error = error_message.format(e=e)
break
job.state = JOB_FAILED
job.error = str(e)
job.human_readable_error = error
# Don't override the other properties that have been set during the
# progress update.
job.save(
update_fields=(
"state",
"error",
"human_readable_error",
)
)
# Allow a job_type to modify job after an error
job_type.on_error(job.specific, e)
job.set_state_failed(str(e), error)
job.save()
raise
finally:
# Delete the import job cached entry because the transaction has been committed
# and the Job entry now contains the latest data.
cache.delete(job_progress_key(job.id))
job.clear_job_cache()
# noinspection PyUnusedLocal
+1 -1
View File
@@ -2,4 +2,4 @@ from typing import TypeVar
from .models import Job
AnyJob = TypeVar("AnyJob", bound=Job)
AnyJob = TypeVar("AnyJob", bound=Job, covariant=True)
@@ -0,0 +1,16 @@
# Generated by Django 4.2.13 on 2024-09-05 06:24
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
("core", "0088_remove_blacklistedtoken_user"),
]
operations = [
migrations.AlterUniqueTogether(
name="snapshot",
unique_together=set(),
),
]
+29 -5
View File
@@ -7,7 +7,8 @@ from django.contrib.auth import get_user_model
from django.contrib.contenttypes.models import ContentType
from django.contrib.postgres.fields import ArrayField
from django.db import models
from django.db.models import Q, UniqueConstraint
from django.db.models import Q, QuerySet, UniqueConstraint
from django.db.models.manager import BaseManager
from baserow.core.jobs.mixins import (
JobWithUndoRedoIds,
@@ -52,7 +53,6 @@ __all__ = [
"BlacklistedToken",
]
User = get_user_model()
@@ -583,6 +583,31 @@ class DuplicateApplicationJob(
)
class SnapshotManager(BaseManager.from_queryset(QuerySet)):
def restorable(self) -> QuerySet:
"""
Returns a queryset with Snapshots that can be restored.
:return: A queryset with Snapshots that can be restored.
"""
return self.get_queryset().filter(
snapshot_to_application__isnull=False, mark_for_deletion=False
)
def unusable(self) -> QuerySet:
"""
Returns a queryset with Snapshots that cannot be restored.
:returns: A queryset with Snapshots that cannot be restored because they are
either not associated with an application or are marked for deletion.
"""
return self.get_queryset().filter(
Q(snapshot_to_application__isnull=True) | Q(mark_for_deletion=True)
)
class Snapshot(HierarchicalModelMixin, models.Model):
name = models.CharField(max_length=160)
snapshot_from_application = models.ForeignKey(
@@ -595,12 +620,11 @@ class Snapshot(HierarchicalModelMixin, models.Model):
created_by = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
unique_together = ("name", "snapshot_from_application")
def get_parent(self):
return self.snapshot_from_application
objects = SnapshotManager()
class InstallTemplateJob(
JobWithUserIpAddress,
+23 -18
View File
@@ -3,8 +3,8 @@ from datetime import datetime, timedelta, timezone
from django.conf import settings
from django.contrib.auth.models import AbstractUser
from django.core.files.storage import default_storage
from django.db import IntegrityError, OperationalError
from django.db.models.query import QuerySet
from django.db import OperationalError
from django.db.models import QuerySet
from baserow.contrib.database.exceptions import (
DatabaseSnapshotMaxLocksExceededException,
@@ -49,9 +49,11 @@ class SnapshotHandler:
:param workspace: The workspace for which to count the snapshots.
"""
return Snapshot.objects.filter(
snapshot_from_application__workspace=workspace, mark_for_deletion=False
).count()
return (
Snapshot.objects.restorable()
.filter(snapshot_from_application__workspace=workspace)
.count()
)
def _check_is_in_use(self, snapshot: Snapshot) -> None:
"""
@@ -65,8 +67,7 @@ class SnapshotHandler:
"""
restoring_jobs_count = (
JobHandler()
.get_pending_or_running_jobs(RestoreSnapshotJobType.type)
JobHandler.get_pending_or_running_jobs(RestoreSnapshotJobType.type)
.filter(snapshot=snapshot)
.count()
)
@@ -113,11 +114,8 @@ class SnapshotHandler:
)
return (
Snapshot.objects.filter(
snapshot_from_application__id=application_id,
snapshot_to_application__isnull=False,
mark_for_deletion=False,
)
Snapshot.objects.restorable()
.filter(snapshot_from_application__id=application_id)
.select_related("created_by")
.order_by("-created_at", "-id")
)
@@ -197,16 +195,23 @@ class SnapshotHandler:
if creating_jobs_count > 0:
raise SnapshotIsBeingCreated()
try:
snapshot = Snapshot.objects.create(
if (
Snapshot.objects.restorable()
.filter(
snapshot_from_application=application,
created_by=performed_by,
name=name,
)
except IntegrityError as e:
if "unique constraint" in e.args[0]:
raise SnapshotNameNotUnique()
raise e
.exists()
):
raise SnapshotNameNotUnique()
snapshot = Snapshot.objects.create(
snapshot_from_application=application,
created_by=performed_by,
name=name,
)
return snapshot
def start_restore_job(
@@ -31,6 +31,16 @@ class CreateSnapshotJobType(JobType):
DatabaseSnapshotMaxLocksExceededException: DatabaseSnapshotMaxLocksExceededException.message
}
serializer_field_names = ["snapshot"]
@property
def serializer_field_overrides(self):
from baserow.api.snapshots.serializers import SnapshotSerializer
return {
"snapshot": SnapshotSerializer(),
}
def transaction_atomic_context(self, job: CreateSnapshotJob):
application = (
CoreHandler()
@@ -47,9 +57,10 @@ class CreateSnapshotJobType(JobType):
job.user, job.snapshot, progress
)
def on_error(self, job: CreateSnapshotJob, error: Exception):
if job.snapshot:
# avoid dangling snapshot entries
def before_delete(self, job):
# Delete the dangling snapshot if it didn't finish correctly but the snapshot is
# still there.
if not job.finished and job.snapshot_id is not None:
job.snapshot.delete()
@@ -63,6 +74,16 @@ class RestoreSnapshotJobType(JobType):
SnapshotDoesNotExist: ERROR_SNAPSHOT_DOES_NOT_EXIST,
}
serializer_field_names = ["snapshot"]
@property
def serializer_field_overrides(self):
from baserow.api.snapshots.serializers import SnapshotSerializer
return {
"snapshot": SnapshotSerializer(),
}
def run(self, job: RestoreSnapshotJob, progress):
from .actions import RestoreSnapshotActionType
@@ -13,6 +13,8 @@ from baserow.core.models import Application
def delete_application_snapshot(self, application_id: int):
"""
A job that will delete an application.
:param application_id: The id of the application that must be deleted.
"""
from baserow.core.trash.handler import TrashHandler
@@ -1,11 +1,16 @@
import asyncio
import contextlib
import os
import sys
import threading
from contextlib import contextmanager
from functools import partial
from pathlib import Path
from typing import Any, Dict, Optional
from unittest.mock import patch
from django.conf import settings as django_settings
from django.core import cache
from django.core.files.storage import Storage
from django.core.management import call_command
from django.db import DEFAULT_DB_ALIAS, OperationalError, connection
@@ -14,6 +19,7 @@ from django.test.utils import CaptureQueriesContext
import pytest
from faker import Faker
from loguru import logger
from pygments import highlight
from pygments.formatters import TerminalFormatter
from pygments.lexers import PostgresLexer
@@ -24,6 +30,7 @@ from sqlparse import format
from baserow.contrib.database.application_types import DatabaseApplicationType
from baserow.core.context import clear_current_workspace_id
from baserow.core.exceptions import PermissionDenied
from baserow.core.jobs.registries import job_type_registry
from baserow.core.permission_manager import CorePermissionManagerType
from baserow.core.services.dispatch_context import DispatchContext
from baserow.core.trash.trash_types import WorkspaceTrashableItemType
@@ -204,6 +211,14 @@ def mutable_builder_workflow_action_registry():
builder_workflow_action_type_registry.registry = before
@pytest.fixture()
def mutable_job_type_registry():
with patch.object(job_type_registry, "registry", {}):
job_type_registry.get_for_class.cache_clear()
yield job_type_registry
job_type_registry.get_for_class.cache_clear()
@pytest.fixture()
def stub_user_source_registry(data_fixture, mutable_user_source_registry, fake):
from baserow.core.user_sources.registries import UserSourceType
@@ -675,6 +690,35 @@ def enable_singleton_testing(settings):
yield
@pytest.fixture
def enable_locmem_testing(settings):
"""
Enables in-memory cache and redis for a test
:param settings:
:return:
"""
# celery-singleton uses redis to store the lock state
# so we need to mock redis to make sure the tests don't fail
settings.CACHES = {
**django_settings.CACHES,
"default": {
"BACKEND": "django.core.cache.backends.locmem.LocMemCache",
"LOCATION": "testloc",
},
}
from fakeredis import FakeRedis, FakeServer
fake_redis_server = FakeServer()
with patch(
"baserow.celery_singleton_backend.get_redis_connection",
lambda *a, **kw: FakeRedis(server=fake_redis_server),
):
yield
cache.cache.clear()
@pytest.fixture
def stubbed_storage(monkeypatch):
class StubbedStorage(Storage):
@@ -740,3 +784,75 @@ class FakeDispatchContext(DispatchContext):
return "999"
return get_value_at_path(self.context, key)
@pytest.fixture()
def test_thread():
"""
Run a side thread with an arbitrary function.
This fixture allows to run a helper thread with an arbitrary function
to test concurrent flows, i.e. in-Celery-task state changes.
This fixture will increase min thread switching granularity for the test to
to 0.00001s.
It's advised to use threading primitives to communicate with the helper thread.
A callable will be wrapped to log any error ocurred during the execution.
A Thread object yielded from this fixture has .thread_stopped Event attached to
simplify synchronization with the test code. This event is set when a
callable finished it's work.
>>> def test_x(test_thread):
evt_start = threading.Event()
evt_end = threading.Event()
evt_can_end = threading.Event()
def callable(*args, **kwargs):
evt_start.set()
assert evt_can_end(timeout=0.01)
evt_end.set()
with test_thread(callable, foo='bar') as t:
# pick a moment to start
t.start()
evt_can_end.set()
# wait for the callable to finish
assert t.thread_stopped.wait(0.1)
assert evt_start.is_set()
assert evt_end.is_set()
:return:
"""
thread_stopped = threading.Event()
def wrapper(c, *args, **kwargs):
try:
logger.info(f"running callable {c} with args {args} {kwargs}")
return c(*args, **kwargs)
except Exception as err:
logger.error(f"error when running {c}: {err}", exc_info=True)
raise
finally:
thread_stopped.set()
@contextmanager
def run_callable(callable, *args, **kwargs):
t = threading.Thread(target=partial(wrapper, callable, *args, **kwargs))
t.thread_stopped = thread_stopped
switch_interval = 0.00001
orig_switch_interval = sys.getswitchinterval()
try:
sys.setswitchinterval(switch_interval)
yield t
finally:
while t.is_alive():
t.join(0.01)
sys.setswitchinterval(orig_switch_interval)
yield run_callable
@@ -554,7 +554,7 @@ def test_duplicate_application_schedule_job(
assert job["state"] == "pending"
assert job["type"] == "duplicate_application"
job = JobHandler().get_job(user_2, job["id"])
job = JobHandler.get_job(user_2, job["id"])
assert job.user_id == user_2.id
assert job.progress_percentage == 0
assert job.state == "pending"
@@ -1,3 +1,4 @@
import threading
from unittest.mock import patch
from django.urls import reverse
@@ -5,7 +6,11 @@ from django.urls import reverse
import pytest
from rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND
from baserow.core.jobs.constants import JOB_CANCELLED
from baserow.core.jobs.models import Job
from baserow.core.jobs.registries import JobType
from baserow.core.jobs.tasks import run_async_job
from baserow.test_utils.helpers import is_dict_subset
@pytest.mark.django_db(transaction=True)
@@ -171,7 +176,8 @@ def test_list_jobs(data_fixture, api_client):
"states": [
{
"error": "State importing is not a valid state. "
"Valid states are: pending, finished, failed.",
"Valid states are: pending, finished, failed, "
"cancelled.",
"code": "invalid",
}
],
@@ -263,3 +269,238 @@ def test_get_job(data_fixture, api_client):
"human_readable_error": "Wrong",
"test_field": 42,
}
@pytest.mark.django_db(transaction=True)
def test_cancel_job_running(
data_fixture,
api_client,
test_thread,
mutable_job_type_registry,
enable_locmem_testing,
):
# marker that the job started
m_start = threading.Event()
# marker for job to stop
m_set_stop = threading.Event()
# confirmation of m_set_stop
m_stop_wait = threading.Event()
# marker that job finished
m_end = threading.Event()
class IdlingJobType(JobType):
type = "idling_job_b"
model_class = Job
max_count = 1
def run(self, job, progress):
m_start.set()
progress.set_progress(1)
assert m_set_stop.wait(2)
progress.set_progress(2)
m_end.set()
progress.set_progress(3)
mutable_job_type_registry.register(IdlingJobType())
user, token = data_fixture.create_user_and_token()
with patch("baserow.core.jobs.tasks.run_async_job.delay"):
response = api_client.post(
reverse("api:jobs:list"),
{
"type": IdlingJobType.type,
},
HTTP_AUTHORIZATION=f"JWT {token}",
)
assert response.status_code == HTTP_200_OK
resp = response.json()
job = Job.objects.get(id=resp["id"]).specific
assert job
assert job.id
assert job.specific
assert resp == {
"id": job.id,
"type": IdlingJobType.type,
"state": "pending",
"progress_percentage": 0,
"human_readable_error": "",
}
with test_thread(run_async_job.apply, args=(job.id,)) as t:
assert job.pending, job.get_cached_state()
t.start()
assert m_start.wait(0.5)
assert job.started, job.get_cached_state()
response = api_client.post(
reverse("api:jobs:cancel", args=(job.id,)),
HTTP_AUTHORIZATION=f"JWT {token}",
)
assert response.status_code == HTTP_200_OK
resp = response.json()
assert is_dict_subset(
{"state": "cancelled", "id": job.id, "type": IdlingJobType.type}, resp
)
m_set_stop.set()
assert t.thread_stopped.wait(2)
job.refresh_from_db()
assert job.cancelled, job.get_cached_state()
assert not m_end.is_set()
assert response.status_code == HTTP_200_OK
job_data = response.json()
assert job_data["state"] == JOB_CANCELLED
@pytest.mark.django_db(transaction=True)
def test_cancel_job_pending(
data_fixture,
api_client,
test_thread,
mutable_job_type_registry,
enable_locmem_testing,
):
# marker that the job started
m_start = threading.Event()
# marker for job to stop
m_set_stop = threading.Event()
# marker that job finished
m_end = threading.Event()
class IdlingJobType(JobType):
type = "idling_job_b"
model_class = Job
max_count = 1
def run(self, job, progress):
m_start.set()
progress.set_progress(1)
assert m_set_stop.wait(1)
progress.set_progress(2)
m_end.set()
mutable_job_type_registry.register(IdlingJobType())
user, token = data_fixture.create_user_and_token()
with patch("baserow.core.jobs.tasks.run_async_job.delay"):
response = api_client.post(
reverse("api:jobs:list"),
{
"type": IdlingJobType.type,
},
HTTP_AUTHORIZATION=f"JWT {token}",
)
assert response.status_code == HTTP_200_OK
resp = response.json()
job = Job.objects.get(id=resp["id"]).specific
assert job
assert job.id
assert job.specific
assert resp == {
"id": job.id,
"type": IdlingJobType.type,
"state": "pending",
"progress_percentage": 0,
"human_readable_error": "",
}
with test_thread(run_async_job.apply, args=(job.id,)) as t:
assert job.pending, job.get_cached_state()
response = api_client.post(
reverse("api:jobs:cancel", args=(job.id,)),
HTTP_AUTHORIZATION=f"JWT {token}",
)
assert response.status_code == HTTP_200_OK
t.start()
assert job.cancelled, job.get_cached_state()
assert not m_start.is_set()
assert not m_end.is_set()
job_data = response.json()
assert job_data["state"] == JOB_CANCELLED
@pytest.mark.django_db(transaction=True)
def test_cancel_job_finished(
data_fixture,
api_client,
test_thread,
mutable_job_type_registry,
enable_locmem_testing,
):
# marker that the job started
m_start = threading.Event()
# marker for job to stop
m_set_stop = threading.Event()
# marker that job finished
m_end = threading.Event()
class IdlingJobType(JobType):
type = "idling_job_b"
model_class = Job
max_count = 1
def run(self, job, progress):
m_start.set()
progress.set_progress(1)
assert m_set_stop.wait(1)
progress.set_progress(2)
m_end.set()
mutable_job_type_registry.register(IdlingJobType())
user, token = data_fixture.create_user_and_token()
with patch("baserow.core.jobs.tasks.run_async_job.delay"):
response = api_client.post(
reverse("api:jobs:list"),
{
"type": IdlingJobType.type,
},
HTTP_AUTHORIZATION=f"JWT {token}",
)
assert response.status_code == HTTP_200_OK
resp = response.json()
job = Job.objects.get(id=resp["id"]).specific
assert job
assert job.id
assert job.specific
assert resp == {
"id": job.id,
"type": IdlingJobType.type,
"state": "pending",
"progress_percentage": 0,
"human_readable_error": "",
}
with test_thread(run_async_job.apply, args=(job.id,)) as t:
assert job.pending, job.get_cached_state()
t.start()
assert m_start.wait(0.1)
m_set_stop.set()
assert m_end.wait(0.1)
response = api_client.post(
reverse("api:jobs:cancel", args=(job.id,)),
HTTP_AUTHORIZATION=f"JWT {token}",
)
assert response.status_code == HTTP_400_BAD_REQUEST
resp = response.json()
assert resp.get("error") == "ERROR_JOB_NOT_CANCELLABLE"
@@ -1,3 +1,5 @@
from unittest.mock import patch
from django.shortcuts import reverse
import pytest
@@ -11,6 +13,8 @@ from rest_framework.status import (
HTTP_404_NOT_FOUND,
)
from baserow.core.jobs.constants import JOB_STARTED
from baserow.core.jobs.models import JOB_STATES_RUNNING
from baserow.test_utils.helpers import is_dict_subset
# Create
@@ -491,3 +495,133 @@ def test_delete_snapshot(api_client, data_fixture):
)
assert response.status_code == HTTP_204_NO_CONTENT
@pytest.mark.django_db(transaction=True)
def test_get_current_snapshot_job(api_client, data_fixture):
user, token = data_fixture.create_user_and_token()
workspace_1 = data_fixture.create_workspace(user=user)
application_1 = data_fixture.create_database_application(
workspace=workspace_1, order=1
)
url = reverse("api:snapshots:list", kwargs={"application_id": application_1.id})
snapshot_name = "Test snapshot name"
with patch("baserow.core.jobs.tasks.run_async_job.delay"):
response = api_client.post(
url,
{"name": snapshot_name},
format="json",
HTTP_AUTHORIZATION=f"JWT {token}",
)
assert response.status_code == HTTP_202_ACCEPTED
assert is_dict_subset(
{
"human_readable_error": "",
"progress_percentage": 0,
"state": "pending",
"type": "create_snapshot",
},
response.json(),
)
url = reverse("api:jobs:list")
response = api_client.get(
url,
{"state": JOB_STARTED},
format="json",
HTTP_AUTHORIZATION=f"JWT {token}",
)
assert response.status_code == HTTP_200_OK
resp = response.json()
assert isinstance(resp, dict)
assert "jobs" in resp
resp = resp["jobs"]
assert isinstance(resp, list)
assert len(resp) == 1
assert isinstance(resp[0], dict)
assert is_dict_subset(
{
"snapshot": {
"name": "Test snapshot name",
}
},
resp[0],
)
@pytest.mark.django_db(transaction=True)
def test_get_current_snapshot_job_cancelled(api_client, data_fixture):
user, token = data_fixture.create_user_and_token()
workspace_1 = data_fixture.create_workspace(user=user)
application_1 = data_fixture.create_database_application(
workspace=workspace_1, order=1
)
url = reverse("api:snapshots:list", kwargs={"application_id": application_1.id})
snapshot_name = "Test snapshot name"
with patch("baserow.core.jobs.tasks.run_async_job.delay"):
response = api_client.post(
url,
{"name": snapshot_name},
format="json",
HTTP_AUTHORIZATION=f"JWT {token}",
)
assert response.status_code == HTTP_202_ACCEPTED
assert is_dict_subset(
{
"human_readable_error": "",
"progress_percentage": 0,
"state": "pending",
"type": "create_snapshot",
},
response.json(),
)
# list jobs to match with a snapshot
url = reverse("api:jobs:list")
response = api_client.get(
url,
{"state": JOB_STATES_RUNNING},
format="json",
HTTP_AUTHORIZATION=f"JWT {token}",
)
assert response.status_code == HTTP_200_OK
resp = response.json()
assert isinstance(resp, dict)
assert "jobs" in resp
resp = resp["jobs"]
assert len(resp) == 1
assert isinstance(resp[0], dict)
assert isinstance(resp[0].get("snapshot"), dict)
assert is_dict_subset({"name": snapshot_name}, resp[0].get("snapshot"))
job_id = resp[0]["id"]
url = reverse("api:jobs:cancel", kwargs={"job_id": job_id})
response = api_client.post(
url,
format="json",
HTTP_AUTHORIZATION=f"JWT {token}",
)
assert response.status_code == HTTP_200_OK
url = reverse("api:snapshots:list", kwargs={"application_id": application_1.id})
response = api_client.get(
url,
format="json",
HTTP_AUTHORIZATION=f"JWT {token}",
)
assert response.status_code == HTTP_200_OK
resp = response.json()
assert resp == []
@@ -218,7 +218,7 @@ def test_async_install_template_schedule_job(
assert response_json["state"] == "pending"
assert response_json["type"] == "install_template"
job = JobHandler().get_job(user, response_json["id"])
job = JobHandler.get_job(user, response_json["id"])
assert job.user_id == user.id
assert job.progress_percentage == 0
assert job.state == "pending"
@@ -656,8 +656,8 @@ def test_get_airtable_import_job(data_fixture):
job_2 = data_fixture.create_airtable_import_job()
with pytest.raises(JobDoesNotExist):
JobHandler().get_job(user, job_2.id)
JobHandler.get_job(user, job_2.id)
job = JobHandler().get_job(user, job_1.id, job_model=AirtableImportJob)
job = JobHandler.get_job(user, job_1.id, job_model=AirtableImportJob)
assert isinstance(job, AirtableImportJob)
assert job.id == job_1.id
@@ -44,10 +44,11 @@ def test_run_task(mock_get_by_model, data_fixture):
def run(job, progress):
progress.increment(50, "test")
# Check if the job has updated in the transaction
job.refresh_from_db()
assert job.progress_percentage == 50
assert job.state == "test"
# use job's cached state to determine current state/progress_percentage
# as this can be updated from another process. A task will not write
# a job state to db until it's finished correctly.
assert job.get_cached_state() == "test"
assert job.get_cached_progress_percentage() == 50
# We're using the second connection to check if we can get the most recent
# progress value while the transaction is still active.
@@ -1,12 +1,20 @@
import sys
import threading
from time import sleep
from unittest.mock import patch
import pytest
from baserow.core.jobs.exceptions import JobDoesNotExist, MaxJobCountExceeded
from baserow.core.jobs.constants import JOB_CANCELLED
from baserow.core.jobs.exceptions import (
JobDoesNotExist,
JobNotCancellable,
MaxJobCountExceeded,
)
from baserow.core.jobs.handler import JobHandler
from baserow.core.jobs.models import Job
from baserow.core.jobs.registries import JobType, job_type_registry
from baserow.core.jobs.registries import JobType
from baserow.core.jobs.tasks import run_async_job
@pytest.mark.django_db(transaction=True)
@@ -70,15 +78,15 @@ def test_get_job(data_fixture):
job_2 = data_fixture.create_fake_job(type="tmp_job_type_1")
with pytest.raises(JobDoesNotExist):
JobHandler().get_job(user, job_2.id)
JobHandler.get_job(user, job_2.id)
job = JobHandler().get_job(user, job_1.id)
job = JobHandler.get_job(user, job_1.id)
assert isinstance(job, Job)
assert job.id == job_1.id
@pytest.mark.django_db
def test_job_progress_changed_bug_regression(data_fixture):
def test_job_progress_changed_bug_regression(data_fixture, mutable_job_type_registry):
"""
Small regression test for an undefined variable in JobHandler.run
"""
@@ -93,22 +101,266 @@ def test_job_progress_changed_bug_regression(data_fixture):
progress,
)
with patch.object(job_type_registry, "registry", {}):
job_type_registry.get_for_class.cache_clear()
job_type_registry.register(IdlingJobType())
mutable_job_type_registry.register(IdlingJobType())
user = data_fixture.create_user()
user = data_fixture.create_user()
job_1 = data_fixture.create_fake_job(user=user, type=IdlingJobType.type)
job_1 = data_fixture.create_fake_job(user=user, type=IdlingJobType.type)
_job, _progress = JobHandler().run(job_1)
job, progress = JobHandler().run(job_1)
assert _job
assert _progress
assert job
assert progress
_job.progress = 1
_job.save()
_progress.set_progress(1, None)
assert _job.progress == 1
# in old code this will fail with UnboundLocalError
_progress.set_progress(1, None)
job.progress = 1
job.save()
progress.set_progress(1, None)
assert job.progress == 1
# in old code this will fail with UnboundLocalError
progress.set_progress(1, None)
@pytest.mark.django_db(transaction=True)
def test_job_cancel_before_run(
data_fixture, test_thread, mutable_job_type_registry, enable_locmem_testing
):
# marker that the job started
m_start = threading.Event()
# marker for job to stop
m_set_stop = threading.Event()
# marker that job finished
m_end = threading.Event()
class IdlingJobType(JobType):
type = "idling_job_b"
model_class = Job
max_count = 1
def run(self, job, progress):
m_start.set()
m_set_stop.wait(0.003)
progress.set_progress(10)
m_end.set()
jh = JobHandler()
mutable_job_type_registry.register(IdlingJobType())
user = data_fixture.create_user()
with patch("baserow.core.jobs.tasks.run_async_job.delay"):
job = jh.create_and_start_job(user, IdlingJobType.type, sync=False)
assert job.user_id == user.id
assert job.get_cached_progress_percentage() == 0
assert job.pending
assert job.error == ""
with test_thread(run_async_job.apply, args=(job.id,)) as t:
assert job.pending
assert job.progress_percentage == 0
jh.cancel_job(job)
t.start()
sleep(0.005)
# Job.run should not be called so markers are not set
assert not m_start.is_set()
assert not m_end.is_set()
job.refresh_from_db()
assert job.cancelled, (
job.get_cached_state(),
job.state,
)
@pytest.mark.django_db(transaction=True)
def test_job_cancel_when_running(
data_fixture, test_thread, mutable_job_type_registry, enable_locmem_testing
):
# marker that the job started
m_start = threading.Event()
# marker for job to stop
m_set_stop = threading.Event()
# marker that job finished
m_end = threading.Event()
class IdlingJobType(JobType):
type = "idling_job_b"
model_class = Job
max_count = 1
def run(self, job, progress):
progress.set_progress(11)
m_start.set()
progress.set_progress(11)
assert m_set_stop.wait(0.05)
progress.set_progress(12)
m_end.set()
jh = JobHandler()
mutable_job_type_registry.register(IdlingJobType())
user = data_fixture.create_user()
with patch("baserow.core.jobs.tasks.run_async_job.delay"):
job = jh.create_and_start_job(user, IdlingJobType.type, sync=False)
assert job.user_id == user.id
assert job.get_cached_progress_percentage() == 0
assert job.pending
assert job.error == ""
with test_thread(run_async_job.apply, args=(job.id,)) as t:
assert job.pending
assert job.get_cached_progress_percentage() == 0
t.start()
assert m_start.wait(0.02)
assert job.started, job.get_cached_state()
assert (
job.get_cached_progress_percentage() == 11
), job.get_cached_progress_percentage()
jh.cancel_job(job)
m_set_stop.set()
assert not m_end.wait(0.05)
job.refresh_from_db()
# progress percentage is set from model's state, not from cache,
# so this is a different value than one set from .run method
assert job.cancelled
assert job.state == JOB_CANCELLED
@pytest.mark.django_db(transaction=True)
def test_job_cancel_failed(
data_fixture, test_thread, mutable_job_type_registry, enable_locmem_testing
):
# marker that the job started
m_start = threading.Event()
class IdlingJobType(JobType):
type = "idling_job_b"
model_class = Job
max_count = 1
def run(self, job, progress):
m_start.set()
raise ValueError()
jh = JobHandler()
mutable_job_type_registry.register(IdlingJobType())
user = data_fixture.create_user()
with patch("baserow.core.jobs.tasks.run_async_job.delay"):
job = jh.create_and_start_job(user, IdlingJobType.type, sync=False)
assert job.user_id == user.id
assert job.get_cached_progress_percentage() == 0
assert job.pending
assert job.error == ""
with test_thread(run_async_job.apply, args=(job.id,)) as t:
assert job.pending
assert job.get_cached_progress_percentage() == 0
t.start()
assert t.is_alive()
assert m_start.wait(0.05)
# a job failed, so we can't cancel it
job.refresh_from_db()
assert job.failed
out = jh.cancel_job(job)
assert isinstance(out, Job)
assert job.cancelled
@pytest.mark.django_db(transaction=True)
def test_job_cancel_finished(
data_fixture, test_thread, mutable_job_type_registry, enable_locmem_testing
):
m_start = threading.Event()
m_set_stop = threading.Event()
m_end = threading.Event()
class IdlingJobType(JobType):
type = "idling_job_b"
model_class = Job
max_count = 1
def run(self, job, progress):
m_start.set()
assert m_set_stop.wait(0.05)
m_end.set()
jh = JobHandler()
mutable_job_type_registry.register(IdlingJobType())
user = data_fixture.create_user()
with patch("baserow.core.jobs.tasks.run_async_job.delay"):
job = jh.create_and_start_job(user, IdlingJobType.type, sync=False)
assert job.user_id == user.id
assert job.get_cached_progress_percentage() == 0
assert job.pending
assert job.error == ""
with test_thread(run_async_job, job.id) as t:
assert job.pending
assert job.get_cached_progress_percentage() == 0
t.start()
assert t.is_alive()
assert m_start.wait(0.05)
m_set_stop.set()
assert m_end.wait(0.05)
job.refresh_from_db()
with pytest.raises(JobNotCancellable):
assert job.finished, job.get_cached_state()
jh.cancel_job(job)
@pytest.mark.django_db(transaction=True)
def test_job_cancel_cancelled(
data_fixture, test_thread, mutable_job_type_registry, enable_locmem_testing
):
m_start = threading.Event()
m_set_stop = threading.Event()
m_end = threading.Event()
class IdlingJobType(JobType):
type = "idling_job_b"
model_class = Job
max_count = 1
def run(self, job, progress):
m_start.set()
progress.set_progress(10)
assert m_set_stop.wait(0.05)
progress.set_progress(20)
m_end.set()
progress.set_progress(30)
jh = JobHandler()
mutable_job_type_registry.register(IdlingJobType())
user = data_fixture.create_user()
with patch("baserow.core.jobs.tasks.run_async_job.delay"):
job = jh.create_and_start_job(user, IdlingJobType.type, sync=False)
assert job.user_id == user.id
assert job.get_cached_progress_percentage() == 0
assert job.pending
assert job.error == ""
with test_thread(run_async_job, job.id) as t:
assert job.pending
assert job.get_cached_progress_percentage() == 0
t.start()
assert t.is_alive()
assert m_start.wait(0.05)
out = JobHandler.cancel_job(job)
assert isinstance(out, Job)
m_set_stop.set()
job.refresh_from_db()
assert job.cancelled, job.state
out = JobHandler.cancel_job(job)
# won't cancel already cancelled
assert out is None
@@ -1,4 +1,10 @@
from datetime import timedelta
from django.conf import settings
from django.utils import timezone
import pytest
from freezegun import freeze_time
from baserow.core.exceptions import UserNotInWorkspace
from baserow.core.jobs.constants import JOB_FAILED
@@ -8,7 +14,7 @@ from baserow.core.snapshots.models import Snapshot
@pytest.mark.django_db(transaction=True)
def test_no_dangling_snapshots_on_error(data_fixture):
def test_dangling_snapshots_are_removed(data_fixture):
user = data_fixture.create_user()
workspace = data_fixture.create_workspace()
database = data_fixture.create_database_application(workspace=workspace)
@@ -25,4 +31,16 @@ def test_no_dangling_snapshots_on_error(data_fixture):
)
assert job.state == JOB_FAILED
# we still keep that snapshot
assert Snapshot.objects.count() == 1
assert Snapshot.objects.restorable().count() == 0
assert Snapshot.objects.unusable().count() == 1
# cleanup should remove stale snapshots along with a job
with freeze_time(
timezone.now()
+ timedelta(minutes=settings.BASEROW_JOB_EXPIRATION_TIME_LIMIT + 10)
):
JobHandler().clean_up_jobs()
assert Snapshot.objects.count() == 0
@@ -0,0 +1,7 @@
{
"type": "feature",
"message": "Allow to cancel a job (i.e. a database snapshot).",
"issue_number": 2756,
"bullet_points": [],
"created_at": "2024-07-28"
}
@@ -12,6 +12,12 @@
}
}
.snapshots-modal__cancel-button {
position: static;
margin-top: 10px;
color: $color-error-500 !important;
}
.snapshots-modal__info {
min-height: 36px;
flex-grow: 1;
@@ -25,6 +31,10 @@
margin-top: 30px;
}
.snapshots-modal__list--loading {
margin: auto;
}
.snapshots-modal__name {
font-weight: 600;
padding-bottom: 5px;
@@ -107,6 +107,14 @@
margin-left: 16px !important;
}
.margin-left-3 {
margin-left: 30px !important;
}
.margin-left-4 {
margin-left: 40px !important;
}
.margin-right-auto {
margin-right: auto !important;
}
@@ -123,6 +131,14 @@
margin-right: 16px !important;
}
.margin-right-3 {
margin-right: 30px !important;
}
.margin-right-4 {
margin-right: 40px !important;
}
.resizing-horizontal {
cursor: col-resize;
}
@@ -21,6 +21,7 @@
<slot></slot>
</template>
</FormGroup>
<slot name="cancel-action"></slot>
</form>
</template>
@@ -33,6 +34,10 @@ export default {
name: 'CreateSnapshotForm',
mixins: [form],
props: {
applicationName: {
type: String,
required: true,
},
snapshots: {
type: Array,
required: true,
@@ -47,8 +52,8 @@ export default {
},
methods: {
getDefaultName() {
const datetime = moment().utc().format('YYYY-MM-DD HH:mm')
return `${this.$t('snapshotsModal.snapshot')} ${datetime} UTC`
const datetime = moment().format('YYYY-MM-DD HH:mm:ss')
return `${this.applicationName} - ${datetime}`
},
resetName() {
this.values.name = this.getDefaultName()
@@ -18,11 +18,18 @@
</div>
<div class="snapshots-modal__actions">
<a
:class="{ 'snapshots-modal__restore--loading': restoreLoading }"
:class="{ 'snapshots-modal__restore--loading': jobIsRunning }"
@click="restore"
>{{ $t('snapshotListItem.restore') }}</a
>
<a class="snapshots-modal__delete" @click="showDelete">{{
<a
v-if="jobIsRunning || cancelLoading"
class="snapshots-modal__delete"
@click="cancelJob(job.id)"
>
{{ $t('snapshotsModal.cancel') | lowercase }}
</a>
<a v-else class="snapshots-modal__delete" @click="showDelete">{{
$t('snapshotListItem.delete')
}}</a>
<DeleteSnapshotModal
@@ -39,68 +46,74 @@ import SnapshotsService from '@baserow/modules/core/services/snapshots'
import DeleteSnapshotModal from '@baserow/modules/core/components/snapshots/DeleteSnapshotModal'
import { getHumanPeriodAgoCount } from '@baserow/modules/core/utils/date'
import { notifyIf } from '@baserow/modules/core/utils/error'
import jobProgress from '@baserow/modules/core/mixins/jobProgress'
import job from '@baserow/modules/core/mixins/job'
import { RestoreSnapshotJobType } from '@baserow/modules/core/jobTypes'
export default {
components: {
DeleteSnapshotModal,
},
mixins: [jobProgress],
mixins: [job],
props: {
snapshot: {
type: Object,
required: true,
},
},
data() {
return {
restoreLoading: false,
restoreFinished: false,
}
},
computed: {
humanCreatedAt() {
const { period, count } = getHumanPeriodAgoCount(this.snapshot.created_at)
return this.$tc(`datetime.${period}Ago`, count)
},
},
beforeDestroy() {
this.stopPollIfRunning()
mounted() {
if (!this.job) {
this.restoreRunningState()
}
},
methods: {
restoreRunningState() {
const runningJob = this.$store.getters['job/getUnfinishedJobs'].find(
(job) => {
return (
job.type === RestoreSnapshotJobType.getType() &&
job.snapshot.id === this.snapshot.id
)
}
)
if (runningJob) {
this.job = runningJob
}
},
showError(error, message) {
if (error.message && !message) {
message = error.message
}
if (message) {
this.$store.dispatch('toast/error', error, message)
} else {
notifyIf(error)
}
},
async restore() {
this.restoreLoading = true
try {
const { data } = await SnapshotsService(this.$client).restore(
const { data: job } = await SnapshotsService(this.$client).restore(
this.snapshot.id
)
this.startJobPoller(data)
await this.createAndMonitorJob(job)
} catch (error) {
this.restoreLoading = false
notifyIf(error)
}
},
showDelete() {
this.$refs.deleteSnapshotModal.show()
},
// eslint-disable-next-line require-await
async onJobDone() {
this.restoreLoading = false
this.restoreFinished = true
},
// eslint-disable-next-line require-await
async onJobFailed() {
this.restoreLoading = false
onJobFailed() {
this.showError(
this.$t('clientHandler.notCompletedTitle'),
this.$t('clientHandler.notCompletedDescription')
)
},
// eslint-disable-next-line require-await
async onJobPollingError(error) {
this.restoreLoading = false
notifyIf(error)
},
getCustomHumanReadableJobState(jobState) {
if (jobState.startsWith('importing')) {
return this.$t('snapshotsModal.importingState')
@@ -23,40 +23,64 @@
<CreateSnapshotForm
v-if="!limitReached"
ref="form"
:application-name="application.name"
:snapshots="snapshots"
@submitted="submitted"
>
<template v-if="jobIsRunning || jobHasSucceeded" #input>
<ProgressBar
:value="job.progress_percentage"
:status="jobHumanReadableState"
/>
<div class="margin-right-2">
<ProgressBar
:value="job.progress_percentage"
:status="jobHumanReadableState"
/>
</div>
</template>
<template #default>
<Button
v-if="!createFinished"
size="large"
:loading="createLoading"
:disabled="createLoading"
:disabled="createLoading || snapshotsLoading"
>
{{ $t('snapshotsModal.create') }}
</Button>
<Button v-else type="secondary" tag="a" size="large" @click="reset()">
{{ $t('snapshotsModal.reset') }}</Button
{{ $t('snapshotsModal.reset') }}
</Button>
</template>
<template #cancel-action>
<ButtonText
v-if="jobIsRunning || cancelLoading"
tag="a"
type="secondary"
class="snapshots-modal__cancel-button"
:loading="cancelLoading"
@click="cancelJob(job.id)"
>
{{ $t('snapshotsModal.cancel') }}
</ButtonText>
</template>
</CreateSnapshotForm>
<div v-else>
{{ $t('snapshotsModal.limitReached') }}
</div>
<div v-if="snapshotsLoading" class="loading"></div>
<div v-if="snapshots.length > 0" class="snapshots-modal__list">
<SnapshotListItem
v-for="snapshot in snapshots"
:key="snapshot.id"
:snapshot="snapshot"
@snapshot-deleted="snapshotDeleted"
></SnapshotListItem>
<div class="snapshots-modal__list">
<div
v-if="snapshotsLoading"
class="loading snapshots-modal__list--loading"
></div>
<div v-else-if="snapshots.length > 0">
<SnapshotListItem
v-for="snapshot in snapshots"
ref="snapshotsList"
:key="snapshot.id"
:snapshot="snapshot"
@snapshot-deleted="snapshotDeleted"
></SnapshotListItem>
</div>
<div v-else>
{{ $t('snapshotsModal.noSnapshots') }}
</div>
</div>
</div>
</Modal>
@@ -68,8 +92,8 @@ import error from '@baserow/modules/core/mixins/error'
import CreateSnapshotForm from '@baserow/modules/core/components/snapshots/CreateSnapshotForm'
import SnapshotListItem from '@baserow/modules/core/components/snapshots/SnapshotListItem'
import SnapshotsService from '@baserow/modules/core/services/snapshots'
import jobProgress from '@baserow/modules/core/mixins/jobProgress'
import { notifyIf } from '@baserow/modules/core/utils/error'
import job from '@baserow/modules/core/mixins/job'
import { CreateSnapshotJobType } from '@baserow/modules/core/jobTypes'
export default {
name: 'SnapshotsModal',
@@ -77,7 +101,7 @@ export default {
CreateSnapshotForm,
SnapshotListItem,
},
mixins: [modal, error, jobProgress],
mixins: [modal, error, job],
props: {
application: {
type: Object,
@@ -112,9 +136,6 @@ export default {
.filter((component) => component !== null)
},
},
beforeDestroy() {
this.stopPollIfRunning()
},
methods: {
show(...args) {
this.hideError()
@@ -125,55 +146,84 @@ export default {
this.createLoading = true
this.hideError()
try {
const { data } = await SnapshotsService(this.$client).create(
const { data: job } = await SnapshotsService(this.$client).create(
this.application.id,
values
)
this.startJobPoller(data)
this.job = job
await this.createAndMonitorJob(job)
} catch (error) {
this.createLoading = false
this.handleError(error)
}
},
async onJobDone() {
onJobDone() {
this.createLoading = false
this.createFinished = true
await this.loadSnapshots()
if (
this.job.snapshot &&
this.job.type === CreateSnapshotJobType.getType()
) {
this.snapshots.unshift(this.job.snapshot)
this.refreshSnapshots()
}
},
// eslint-disable-next-line require-await
async onJobFailed() {
onJobFailed() {
this.createLoading = false
this.showError(
this.$t('clientHandler.notCompletedTitle'),
this.job.human_readable_error
)
},
// eslint-disable-next-line require-await
async onJobPollingError(error) {
onJobCancelled() {
this.createLoading = false
notifyIf(error)
},
/**
* This should be called if .snapshots list was changed without an API call issued.
*
* Each SnapshotListItem displays time elapsed from snapshot's creation. When an
* item is added to snapshots list, only that element will be freshly rendered.
* Other items won't recalculate time elapsed, so we need to do a force refresh
* from the parent component.
*/
refreshSnapshots() {
this.$forceUpdate()
},
async loadSnapshots() {
this.snapshotsLoading = true
this.snapshots = []
try {
const { data } = await SnapshotsService(this.$client).list(
const { data: snapshots } = await SnapshotsService(this.$client).list(
this.application.id
)
this.snapshots = data
this.snapshots = snapshots
} catch (error) {
this.handleError(error)
} finally {
this.snapshotsLoading = false
}
this.loadRunningJob()
},
snapshotDeleted(deletedSnapshot) {
this.snapshots = this.snapshots.filter(
(snapshot) => snapshot.id !== deletedSnapshot.id
)
},
loadRunningJob() {
const runningJob = this.$store.getters['job/getUnfinishedJobs'].find(
(job) => {
return (
job.type === CreateSnapshotJobType.getType() &&
job.snapshot.snapshot_from_application === this.application.id
)
}
)
if (runningJob) {
this.job = runningJob
this.createLoading = true
}
},
reset() {
this.stopPollIfRunning()
this.job = null
this.createFinished = false
this.createLoading = false
+20
View File
@@ -234,3 +234,23 @@ export class InstallTemplateJobType extends JobType {
await this.app.store.dispatch('job/forceDelete', job)
}
}
export class CreateSnapshotJobType extends JobType {
static getType() {
return 'create_snapshot'
}
getName() {
return 'createSnapshot'
}
}
export class RestoreSnapshotJobType extends JobType {
static getType() {
return 'restore_snapshot'
}
getName() {
return 'restoreSnapshot'
}
}
@@ -522,6 +522,8 @@
"stateStarted": "Started...",
"stateFinished": "Finished",
"stateFailed": "Failed",
"errorJobCannotBeCancelledTitle": "Could not cancel",
"errorJobCannotBeCancelledDescription": "It’s not possible to cancel the job as it has already been completed.\nPlease delete the first snapshot in the list below to remove it.",
"errorJobAlreadyRunningTitle": "Already running",
"errorJobAlreadyRunningDescription": "Another import job is already running. You need to wait for that one to finish before starting another."
},
+138
View File
@@ -0,0 +1,138 @@
/**
* This mixin provides basic job control capabilities using job store.
*
* The purpose is to centralize job state management using job store. Components that
* use this mixin are responsible for job object creation and adding it to the store.
* This is because specific jobs are created using domain-specific API endpoints and not
* using generic jobs API. A job that has been created should be added to the store
* with createAndMonitorJob method during component's initialization.
*
* Job state changes are handled with callbacks. A component that want to use this
* mixin should provide following methods:
* - onJobDone() (optional) is called if the job successfully finishes.
* - onJobFailed() (optional) is called if the job fails.
* - onJobCancelled() (optional) is called if a job has been cancelled.
* - onJobCancelFailed() (optional) is called when a job cancellation request failed.
* - showError({error,message}) handles an error. This can be provided by `error` mixin,
* but a class can provide own implementation here.
* - `getCustomHumanReadableJobState(state)` returns the human readable message your
* custom state values. This mixin provides a default implementation.
*
*/
export default {
data() {
return {
job: null,
cancelLoading: false,
}
},
computed: {
jobHasSucceeded() {
return this.job?.state === 'finished'
},
jobHasFailed() {
return this.job?.state === 'failed' || this.job?.state === 'cancelled'
},
jobIsFinished() {
return this.jobHasSucceeded || this.jobHasFailed
},
jobIsRunning() {
return this.job !== null && !this.jobIsFinished
},
jobHumanReadableState() {
if (this.job === null) {
return ''
}
const translations = {
pending: this.$t('job.statePending'),
started: this.$t('job.stateStarted'),
failed: this.$t('job.stateFailed'),
finished: this.$t('job.stateFinished'),
cancelled: this.$t('Cancelled'),
}
if (translations[this.job.state]) {
return translations[this.job.state]
}
return this.getCustomHumanReadableJobState(this.job.state)
},
},
watch: {
'job.state'(newState) {
switch (newState) {
case 'finished':
if (typeof this.onJobDone === 'function') {
this.onJobDone()
}
break
case 'failed':
if (typeof this.onJobFailed === 'function') {
this.onJobFailed()
}
break
case 'cancelled':
if (typeof this.onJobCancelled === 'function') {
this.onJobCancelled()
}
break
}
},
},
methods: {
/**
* This method adds a job object created externally to job store.
*
* A job object is created by a call to an endpoint that creates a task of a
* specific type in the background because there's no generic job creation endpoint.
* It's up to a component to call appropriate service/endpoint to trigger/schedule
* a job.
*
* @param job a Job object
* @returns {Promise<void>}
*/
async createAndMonitorJob(job) {
await this.$store.dispatch('job/create', job)
this.job = job
},
/**
* Called from a component to cancel any job currently running.
*
* This method can receive error from the dispatch call. The error will be handled
* by showError implementation. By default, if cancellation operation was performed
* successfully, no status/error should be returned here.
*
* @returns {Promise<void>}
*/
async cancelJob() {
if (!this.jobIsRunning) {
return
}
this.cancelLoading = true
try {
await this.$store.dispatch('job/cancel', {
id: this.job.id,
})
} catch (error) {
const errMsg = error.response?.data
if (errMsg?.error === 'ERROR_JOB_NOT_CANCELLABLE') {
this.showError(
this.$t('job.errorJobCannotBeCancelledTitle'),
this.$t('job.errorJobCannotBeCancelledDescription')
)
} else {
this.showError({
title: this.$t('clientHandler.notCompletedTitle'),
message:
(error ? error?.detail || error?.message : null) ||
this.$t('unknown error'),
})
}
if (typeof this.onJobCancelFailed === 'function') {
this.onJobCancelFailed()
}
} finally {
this.cancelLoading = false
}
},
},
}
@@ -1,6 +1,7 @@
import JobService from '@baserow/modules/core/services/job'
/**
* DEPRECATED in favor of job.js.
* To use this mixin you need to create the following methods on your component:
* - `getCustomHumanReadableJobState(state)` returns the human readable message your
* custom state values.
+4
View File
@@ -3,8 +3,10 @@ import Vue from 'vue'
import { Registry } from '@baserow/modules/core/registry'
import { PasswordAuthProviderType } from '@baserow/modules/core/authProviderTypes'
import {
CreateSnapshotJobType,
DuplicateApplicationJobType,
InstallTemplateJobType,
RestoreSnapshotJobType,
} from '@baserow/modules/core/jobTypes'
import {
@@ -187,6 +189,8 @@ export default (context, inject) => {
registry.register('authProvider', new PasswordAuthProviderType(context))
registry.register('job', new DuplicateApplicationJobType(context))
registry.register('job', new InstallTemplateJobType(context))
registry.register('job', new CreateSnapshotJobType(context))
registry.register('job', new RestoreSnapshotJobType(context))
registry.register(
'workspaceSettingsPage',
@@ -9,6 +9,9 @@ export default (client) => {
get(jobId) {
return client.get(`/jobs/${jobId}/`)
},
async cancel(jobId) {
return await client.post(`/jobs/${jobId}/cancel/`)
},
fetchAll(filters = {}) {
const { states, jobIds } = filters
const params = new URLSearchParams()
+13 -1
View File
@@ -1,7 +1,7 @@
import JobService from '@baserow/modules/core/services/job'
import _ from 'lodash'
const FINISHED_STATES = ['finished', 'failed']
const FINISHED_STATES = ['finished', 'failed', 'cancelled']
const STARTING_TIMEOUT_MS = 200
const MAX_POLLING_ATTEMPTS = 100
@@ -181,6 +181,18 @@ export const actions = {
dispatch('forceCreate', job)
dispatch('tryScheduleNextUpdate')
},
/**
* Cancels a scheduled or running job.
*/
async cancel({ dispatch, commit }, job) {
try {
const { data } = await JobService(this.$client).cancel(job.id)
commit('UPDATE_ITEM', { id: data.id, values: data })
} finally {
await dispatch('tryScheduleNextUpdate')
}
},
/**
* Forcefully create an item in the store without making a call to the server.
*/
@@ -772,6 +772,7 @@
"descriptionLimits": "You can have a maximum of {n} snapshots per workspace. | You can have a maximum of {n} snapshot per workspace. | You can have a maximum of {n} snapshots per workspace.",
"createLabel": "Create a new snapshot",
"create": "Create snapshot",
"cancel": "Cancel",
"snapshotRestoredErrorTitle": "Error occurred",
"snapshotRestoredErrorMessage": "The snapshot couldn't be restored. please try again later.",
"snapshotDeletedErrorTitle": "Error occurred",
@@ -779,7 +780,8 @@
"limitReached": "The limit of maximum snapshots has been reached.",
"snapshot": "Snapshot",
"importingState": "Creating",
"reset": "Create another"
"reset": "Create another",
"noSnapshots": "No snapshots for this application yet."
},
"deleteSnapshotModal": {
"title": "Delete snapshot",