Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion geonode/upload/celery_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
from dynamic_models.models import FieldSchema, ModelSchema
from geonode.base.models import ResourceBase
from geonode.resource.enumerator import ExecutionRequestAction as exa
from geonode.resource.models import ExecutionRequest
from geonode.upload.api.exceptions import (
CopyResourceException,
InvalidInputFileException,
Expand Down Expand Up @@ -1002,8 +1003,16 @@ def rollback(self, *args, **kwargs):

@importer_app.task(name="dynamic_model_error_callback")
def dynamic_model_error_callback(*args, **kwargs):
# revert eventually the import in ogr2ogr or the creation of the model in case of failing
"""
Revert eventually the import in ogr2ogr or the creation of the model in case of failing.
In case of replace the table belongs to the existing dataset, so it must not be dropped
"""
alternate = args[0].args[-1]
execution_id = get_uuid(args[0].args)
exec_obj = ExecutionRequest.objects.filter(exec_id=execution_id).first()
if exec_obj and exec_obj.action == ira.REPLACE.value:
return "error"

schema_model = ModelSchema.objects.filter(name=alternate).first()
if schema_model:
drop_dynamic_model_schema(schema_model)
Expand Down
160 changes: 160 additions & 0 deletions geonode/upload/handlers/common/tests_vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
from mock import MagicMock, patch
from geonode.upload.api.exceptions import ImportException, UpsertException
from geonode.upload.handlers.common.vector import BaseVectorFileHandler, import_with_ogr2ogr
from geonode.upload.handlers.utils import create_alternate
from django.contrib.auth import get_user_model
from geonode.upload import project_dir
from geonode.upload.handlers.geojson.handler import GeoJsonFileHandler
Expand All @@ -48,6 +49,7 @@
from geonode.security.registry import permissions_registry
from geonode.groups.models import GroupProfile
from geonode.base.models import ResourceBase, Region, Thesaurus, ThesaurusKeyword
from geonode.layers.models import Dataset


class TestBaseVectorFileHandler(TestCase):
Expand Down Expand Up @@ -328,6 +330,122 @@ def test_setup_dynamic_model_with_dataset_with_modelschema_overwrite_false(self)
ModelSchema.objects.create(name="stazioni_metropolitana", db_name="datastore", managed=True)
self._assert_test_result(overwrite=False)

def _setup_dynamic_model_for_existing_dataset(
self, dataset_table_name, should_be_overwritten, subtype=None, dataset_name=None, extra_input_params=None
):
"""
Create a dataset with the given table name, then call setup_dynamic_model with resource_pk
pointing to it and the valid gpkg (layer 'stazioni_metropolitana') as the uploaded file
"""
exec_id = orchestrator.create_execution_request(
user=self.user,
func_name="funct1",
step="step",
input_params={"files": self.valid_files, "skip_existing_layer": False},
)
self.addCleanup(lambda: ExecutionRequest.objects.filter(exec_id=exec_id).delete())
resource = self.handler.create_geonode_resource(dataset_table_name, dataset_table_name, str(exec_id))
if subtype:
ResourceBase.objects.filter(pk=resource.pk).update(subtype=subtype)
if dataset_name:
Dataset.objects.filter(pk=resource.pk).update(name=dataset_name)
ExecutionRequest.objects.filter(exec_id=exec_id).update(
input_params={
"files": self.valid_files,
"skip_existing_layer": False,
"resource_pk": resource.pk,
**(extra_input_params or {}),
}
)
layers = ogr.Open(self.valid_gpkg)
dynamic_model, layer_name, _ = self.handler.setup_dynamic_model(
layer=[x for x in layers][0],
execution_id=str(exec_id),
should_be_overwritten=should_be_overwritten,
username=self.user,
)
return exec_id, dynamic_model, layer_name

def test_setup_dynamic_model_replace_dataset_without_modelschema_targets_existing_table(self):
"""
Replacing a dataset that has no ModelSchema (e.g. legacy dataset, restored backup, updatelayers)
must target the existing table and create the missing ModelSchema for it,
instead of publishing a new layer under a generated alternate
"""
self.assertFalse(ModelSchema.objects.filter(name__iexact="legacy_dataset").exists())

_, dynamic_model, layer_name = self._setup_dynamic_model_for_existing_dataset(
"legacy_dataset", should_be_overwritten=True
)

self.assertEqual("legacy_dataset", layer_name)
self.assertEqual("legacy_dataset", dynamic_model.name)
self.assertEqual("legacy_dataset", dynamic_model.db_table_name)
self.assertEqual("datastore", dynamic_model.db_name)
self.assertFalse(ModelSchema.objects.filter(name__startswith="stazioni_metropolitana_").exists())

def test_setup_dynamic_model_replace_dataset_without_modelschema_creates_unmanaged_schema(self):
"""
The table of the dataset already exists, so the ModelSchema created for the replace
must never be managed, even if the execution asks for a managed dynamic model
"""
_, dynamic_model, _ = self._setup_dynamic_model_for_existing_dataset(
"legacy_dataset", should_be_overwritten=True, extra_input_params={"is_dynamic_model_managed": True}
)

self.assertFalse(dynamic_model.managed)

def test_setup_dynamic_model_replace_dataset_name_different_from_alternate(self):
"""
The ModelSchema is looked up by the table name (alternate) of the dataset, not by its name.
A ModelSchema matching the dataset name belongs to another table and must not be used
"""
decoy_schema = ModelSchema.objects.create(name="decoy_name", db_name="datastore", db_table_name="decoy_name")

_, dynamic_model, layer_name = self._setup_dynamic_model_for_existing_dataset(
"legacy_dataset", should_be_overwritten=True, dataset_name="decoy_name"
)

self.assertEqual("legacy_dataset", layer_name)
self.assertEqual("legacy_dataset", dynamic_model.name)
self.assertNotEqual(decoy_schema.pk, dynamic_model.pk)
decoy_schema.refresh_from_db()
self.assertEqual("decoy_name", decoy_schema.db_table_name)

def test_setup_dynamic_model_replace_dataset_with_modelschema_reuses_it(self):
schema = ModelSchema.objects.create(name="legacy_dataset", db_name="datastore", db_table_name="legacy_dataset")

_, dynamic_model, layer_name = self._setup_dynamic_model_for_existing_dataset(
"legacy_dataset", should_be_overwritten=True
)

self.assertEqual("legacy_dataset", layer_name)
self.assertEqual(schema.pk, dynamic_model.pk)
self.assertEqual(1, ModelSchema.objects.filter(name__iexact="legacy_dataset").count())

def test_setup_dynamic_model_replace_raster_dataset_with_vector_is_rejected(self):
"""
A vector file cannot replace a raster dataset: the replace must fail before
any ModelSchema is created or the raster layer is touched
"""
with self.assertRaises(ImportException):
self._setup_dynamic_model_for_existing_dataset(
"raster_dataset", should_be_overwritten=True, subtype="raster"
)

self.assertFalse(ModelSchema.objects.filter(name__iexact="raster_dataset").exists())
self.assertFalse(ModelSchema.objects.filter(name__startswith="stazioni_metropolitana_").exists())

def test_setup_dynamic_model_existing_dataset_without_modelschema_no_replace_uses_new_alternate(self):
exec_id, dynamic_model, layer_name = self._setup_dynamic_model_for_existing_dataset(
"legacy_dataset", should_be_overwritten=False
)

expected_alternate = create_alternate("stazioni_metropolitana", str(exec_id))
self.assertEqual(expected_alternate, layer_name)
self.assertEqual(expected_alternate, dynamic_model.name)
self.assertFalse(ModelSchema.objects.filter(name__iexact="legacy_dataset").exists())

def _assert_test_result(self, overwrite=False):
try:
# Prepare the test
Expand Down Expand Up @@ -370,6 +488,48 @@ def _assert_test_result(self, overwrite=False):
if exec_id:
ExecutionRequest.objects.filter(exec_id=exec_id).delete()

def _run_failing_import_resource(self, action):
"""
Run import_resource with a failure happening after setup_dynamic_model
has selected the dynamic model, and return the mocked drop_dynamic_model_schema
"""
exec_id = orchestrator.create_execution_request(
user=self.user,
func_name="funct1",
step="step",
action=action,
input_params={"files": self.valid_files, "skip_existing_layer": False},
)
self.addCleanup(lambda: ExecutionRequest.objects.filter(exec_id=exec_id).delete())
dynamic_model = MagicMock()
dynamic_model.name = "existing_table"
with (
patch.object(self.handler, "get_ogr2ogr_driver", return_value=ogr.GetDriverByName("GPKG")),
patch("geonode.upload.handlers.common.vector.should_be_imported", return_value=True),
patch.object(
self.handler, "setup_dynamic_model", return_value=(dynamic_model, "existing_table", MagicMock())
),
patch.object(self.handler, "get_ogr2ogr_task_group", side_effect=Exception("celery broker unreachable")),
patch("geonode.upload.handlers.common.vector.drop_dynamic_model_schema") as drop_schema,
):
with self.assertRaises(Exception):
self.handler.import_resource(files=self.valid_files, execution_id=str(exec_id))
return drop_schema, dynamic_model

def test_import_resource_failed_replace_keeps_existing_table(self):
"""
In case of replace the dynamic model points to the table of the existing dataset,
so a failure must not drop it
"""
drop_schema, _ = self._run_failing_import_resource(action=ira.REPLACE.value)

drop_schema.assert_not_called()

def test_import_resource_failed_upload_drops_new_table(self):
drop_schema, dynamic_model = self._run_failing_import_resource(action=exa.IMPORT.value)

drop_schema.assert_called_once_with(dynamic_model)

@patch("geonode.upload.handlers.common.vector.BaseVectorFileHandler.get_ogr2ogr_driver")
@patch("geonode.upload.handlers.common.vector.chord")
def test_import_resource_should_not_be_imported(self, celery_chord, ogr2ogr_driver):
Expand Down
51 changes: 34 additions & 17 deletions geonode/upload/handlers/common/vector.py
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,7 @@ def import_resource(self, files: dict, execution_id: str, **kwargs) -> str:
layer_names = []
alternates = []
task_name = "geonode.upload.import_resource"
should_be_overwritten = _exec.action == ira.REPLACE.value

try:
if len(layers) == 0:
Expand All @@ -481,7 +482,6 @@ def import_resource(self, files: dict, execution_id: str, **kwargs) -> str:
layer = self._extract_layer(gdal_layer)
layer_name = self.fixup_name(layer.GetName())

should_be_overwritten = _exec.action == ira.REPLACE.value
# should_be_imported check if the user+layername already exists or not
if (
should_be_imported(
Expand Down Expand Up @@ -550,10 +550,11 @@ def import_resource(self, files: dict, execution_id: str, **kwargs) -> str:

except Exception as e:
logger.error(e)
if dynamic_model:
if dynamic_model and not should_be_overwritten:
"""
In case of fail, we want to delete the dynamic_model schema and his field
to keep the DB in a consistent state
to keep the DB in a consistent state. In case of replace the dynamic_model
points to the table of the existing dataset, so it must not be dropped
"""
drop_dynamic_model_schema(dynamic_model)
raise e
Expand Down Expand Up @@ -667,7 +668,7 @@ def setup_dynamic_model(
available_dataset = Dataset.objects.filter(pk=resource_pk)
user_dataset = available_dataset.first()
if user_dataset:
dynamic_schema = ModelSchema.objects.filter(name__iexact=user_dataset.name)
dynamic_schema = ModelSchema.objects.filter(name__iexact=user_dataset.alternate.split(":")[-1])
else:
dynamic_schema = ModelSchema.objects.none()
else:
Expand All @@ -677,6 +678,9 @@ def setup_dynamic_model(
dynamic_schema_exists = dynamic_schema.exists()
dataset_exists = available_dataset.exists()

if should_be_overwritten and not dataset_exists:
raise ImportException("The dataset selected for the replace does not exist")

# evaluate if the user has the correct permissions for the resource.
# if can "edit" / manage the resource, it should be able to replace it
if should_be_overwritten and dataset_exists:
Expand All @@ -692,13 +696,32 @@ def setup_dynamic_model(
f"'edit' or 'manage' permission is required."
)

if dataset_exists and dynamic_schema_exists and should_be_overwritten:
if dataset_exists and should_be_overwritten:
"""
If the user has a dataset, the dynamic model has already been created and is in overwrite mode,
we just take the dynamic_model to overwrite the existing one
If the user has a dataset and is in overwrite mode, we take the dynamic_model
to overwrite the existing one. If the dynamic model has not been created before,
we create it for the existing dataset table
"""
dynamic_schema = dynamic_schema.get()
if not self.can_overwrite(_exec_obj, available_dataset.first()):
raise ImportException("Cannot override a raster dataset with a vector one")

layer_name = available_dataset.first().alternate.split(":")[-1]
if dynamic_schema_exists:
dynamic_schema = dynamic_schema.get()
else:
logger.warning(
f"No ModelSchema found for dataset '{layer_name}'. Creating it so that the replace "
f"targets the existing table for execution {execution_id}."
)
# the table already exists, so the dynamic model must never manage it
dynamic_schema, _ = ModelSchema.objects.get_or_create(
name=layer_name,
defaults={
"db_name": "datastore",
"managed": False,
"db_table_name": layer_name,
},
)

elif not dataset_exists and not dynamic_schema_exists:
"""
Expand All @@ -720,14 +743,10 @@ def setup_dynamic_model(
f"(e.g. .shp vs .zip). Reusing the existing schema for execution {execution_id}."
)

elif (
(not dataset_exists and dynamic_schema_exists)
or (dataset_exists and dynamic_schema_exists and not should_be_overwritten)
or (dataset_exists and not dynamic_schema_exists)
):
else:
"""
The layer should not be overwritten so we append the UUID
to the layer name to let it proceed to the next steps
The layer should not be overwritten (or a dynamic model with the same name already exists)
so we append the UUID to the layer name to let it proceed to the next steps
"""
layer_name = create_alternate(layer_name, execution_id)
dynamic_schema, _ = ModelSchema.objects.get_or_create(
Expand All @@ -736,8 +755,6 @@ def setup_dynamic_model(
managed=is_dynamic_model_managed,
db_table_name=layer_name,
)
else:
raise ImportException("Error during the upload of the gpkg file. The dataset does not exists")

# define standard field mapping from ogr to django
dynamic_model, celery_group = self.create_dynamic_model_fields(
Expand Down
39 changes: 39 additions & 0 deletions geonode/upload/tests/unit/test_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
copy_geonode_resource,
create_dynamic_structure,
create_geonode_resource,
dynamic_model_error_callback,
import_orchestrator,
import_resource,
orchestrator,
Expand All @@ -41,6 +42,7 @@
from geonode.resource.models import ExecutionRequest
from geonode.layers.models import Dataset
from geonode.resource.enumerator import ExecutionRequestAction
from geonode.upload.utils import ImporterRequestAction
from geonode.base.models import ResourceBase
from geonode.base.populate_test_data import create_single_dataset
from geonode.assets.handlers import asset_handler_registry
Expand Down Expand Up @@ -614,6 +616,43 @@ def setUp(self):
},
)

def _call_dynamic_model_error_callback(self, action):
"""
Simulate the link_error of a failed import_with_ogr2ogr task:
its first argument is the execution_id and the last one the alternate
"""
ExecutionRequest.objects.filter(exec_id=self.exec_id).update(action=action)
schema = ModelSchema.objects.create(name="callback_table", db_name="datastore", db_table_name="callback_table")
failed_task_request = MagicMock()
failed_task_request.args = [str(self.exec_id), {}, "callback_table", "handler", True, "callback_table"]
with patch("geonode.upload.celery_tasks.drop_dynamic_model_schema") as drop_schema:
result = dynamic_model_error_callback(failed_task_request)
self.assertEqual("error", result)
return drop_schema, schema

def test_dynamic_model_error_callback_failed_replace_keeps_existing_table(self):
drop_schema, _ = self._call_dynamic_model_error_callback(ImporterRequestAction.REPLACE.value)

drop_schema.assert_not_called()

def test_dynamic_model_error_callback_failed_upload_drops_new_table(self):
drop_schema, schema = self._call_dynamic_model_error_callback(ExecutionRequestAction.IMPORT.value)

drop_schema.assert_called_once_with(schema)

def test_dynamic_model_error_callback_works_with_a_single_task_argument(self):
"""
Handlers can override the tasks linked to the callback, so it must not
rely on the failed task having more than one positional argument
"""
failed_task_request = MagicMock()
failed_task_request.args = [str(self.exec_id)]
with patch("geonode.upload.celery_tasks.drop_dynamic_model_schema") as drop_schema:
result = dynamic_model_error_callback(failed_task_request)

self.assertEqual("error", result)
drop_schema.assert_not_called()

def test_create_dynamic_structure_should_raise_error_if_schema_is_not_available(
self,
):
Expand Down
Loading