Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proof of concept for new config option: ckanext.xloader.site_url #234

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 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
23 changes: 12 additions & 11 deletions ckanext/xloader/action.py
Original file line number Diff line number Diff line change
Expand Up @@ -140,17 +140,18 @@ def xloader_submit(context, data_dict):
qualified=True
)
data = {
'api_key': utils.get_xloader_user_apitoken(),
'job_type': 'xloader_to_datastore',
'result_url': callback_url,
'metadata': {
'ignore_hash': data_dict.get('ignore_hash', False),
'ckan_url': config['ckan.site_url'],
'resource_id': res_id,
'set_url_type': data_dict.get('set_url_type', False),
'task_created': task['last_updated'],
'original_url': resource_dict.get('url'),
}
"api_key": utils.get_xloader_user_apitoken(),
"job_type": "xloader_to_datastore",
"result_url": callback_url,
"metadata": {
"ignore_hash": data_dict.get("ignore_hash", False),
"ckan_url": config.get("ckanext.xloader.site_url")
or config["ckan.site_url"],
kowh-ai marked this conversation as resolved.
Show resolved Hide resolved
"resource_id": res_id,
"set_url_type": data_dict.get("set_url_type", False),
"task_created": task["last_updated"],
"original_url": resource_dict.get("url"),
},
}
if custom_queue != rq_jobs.DEFAULT_QUEUE_NAME:
# Don't automatically retry if it's a custom run
Expand Down
11 changes: 5 additions & 6 deletions ckanext/xloader/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,12 +114,11 @@ def _submit_resource(self, resource, user, indent=0, sync=False, queue=None):
'ignore_hash': True,
}
if sync:
data_dict['ckan_url'] = tk.config.get('ckan.site_url')
input_dict = {
'metadata': data_dict,
'api_key': 'TODO'
}
logger = logging.getLogger('ckanext.xloader.cli')
data_dict["ckan_url"] = tk.config.get(
"ckanext.xloader.site_url"
) or tk.config.get("ckan.site_url")
input_dict = {"metadata": data_dict, "api_key": "TODO"}
logger = logging.getLogger("ckanext.xloader.cli")
xloader_data_into_datastore_(input_dict, None, logger)
else:
if queue:
Expand Down
10 changes: 8 additions & 2 deletions ckanext/xloader/config_declaration.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,14 @@ version: 1
groups:
- annotation: ckanext-xloader settings
options:
- key: ckanext.xloader.site_url
example: http://ckan-dev:5000
default:
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we don't need an empty string default, it's normal for optional settings to be not present if not provided

Suggested change
default:

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

instead of the toolkit.config.get("ckanext.xloader.site_url") or toolkit.config.get("ckan.site_url") logic below we should be able to use just toolkit.config.get("ckanext.xloader.site_url") along with:

       validators: configured_default("ckan.site_url",None)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@wardi ok I see. so that default is just set in the config yaml, and then, any code can assume that fallback default for the ckanext.xloader.site_url setting?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

yeah, this validator will set ckanext.xloader.site_url to the same as ckan.site_url when it's not given. Another one of @smotornyuk 's clever ideas.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do we need to bother with that when jobs.py already has the fallback config.get('ckanext.xloader.site_url') or config.get('ckan.site_url')?

IMO we should keep the fallback in jobs.py in case someone manually sets ckanext.xloader.site_url to a blank value (which could happen if eg the config is being automatically generated/populated from somewhere, perhaps using ckanext-ssm-config), so the validator approach is redundant.

description: |
Provide an alternate site URL for the xloader_submit action.
This is useful, for example, when the site is running within a docker network.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
This is useful, for example, when the site is running within a docker network.
This is useful, for example, when the site is running within a docker network
or where the job runner can't access ckan using its normal public site URL.

validators: configured_default("ckan.site_url",None)
required: false
- key: ckanext.xloader.jobs_db.uri
default: sqlite:////tmp/xloader_jobs.db
description: |
Expand Down Expand Up @@ -152,5 +160,3 @@ groups:
they will also display "complete", "active", "inactive", and "unknown".
type: bool
required: false


26 changes: 23 additions & 3 deletions ckanext/xloader/jobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@
from rq import get_current_job
import sqlalchemy as sa

from urllib.parse import urljoin, urlunsplit

from ckan import model
from ckan.plugins.toolkit import get_action, asbool, enqueue_job, ObjectNotFound, config

Expand Down Expand Up @@ -79,9 +81,15 @@ def xloader_data_into_datastore(input):
# First flag that this task is running, to indicate the job is not
# stillborn, for when xloader_submit is deciding whether another job would
# be a duplicate or not

callback_url = config.get('ckanext.xloader.site_url') or config.get('ckan.site_url')
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

since this snippet is everywhere, can we make a function and place it in a util/helper function so all places can reference the same code.

i.e. instead of just getting the callback_url, it should take a 'url' and replace the 'site_url' with 'xloader.site_url' when set. or append if domain is not available (which is very rare).

In the jobs table . result_url is always a fqdn i.e. https://www.data.qld.gov.au/api/3/action/xloader_hook


I also see that you dropped input['result_url'] which containers a lookup of the api endpoint. I'm unsure why we should be 'hacking' the callback_url instead of using a 'generic' replacement function to swap the domain like you are doing to the 'resource' url.


The metadata on the 'input' is below

callback_url = p.toolkit.url_for(
        "api.action",
        ver=3,
        logic_function="xloader_hook",
        qualified=True
    )
data = {
        'api_key': utils.get_xloader_user_apitoken(),
        'job_type': 'xloader_to_datastore',
        'result_url': callback_url,
        'metadata': {
            'ignore_hash': data_dict.get('ignore_hash', False),
            'ckan_url': config['ckan.site_url'],
            'resource_id': res_id,
            'set_url_type': data_dict.get('set_url_type', False),
            'task_created': task['last_updated'],
            'original_url': resource_dict.get('url'),
        }
    }

callback_url = urljoin(
callback_url.rstrip('/'), '/api/3/action/xloader_hook')
result_url = callback_url

job_dict = dict(metadata=input['metadata'],
status='running')
callback_xloader_hook(result_url=input['result_url'],
callback_xloader_hook(result_url=result_url,
api_key=input['api_key'],
job_dict=job_dict)

Expand Down Expand Up @@ -143,7 +151,7 @@ def xloader_data_into_datastore(input):
errored = True
finally:
# job_dict is defined in xloader_hook's docstring
is_saved_ok = callback_xloader_hook(result_url=input['result_url'],
is_saved_ok = callback_xloader_hook(result_url=result_url,
api_key=input['api_key'],
job_dict=job_dict)
errored = errored or not is_saved_ok
Expand Down Expand Up @@ -204,7 +212,11 @@ def direct_load():
set_datastore_active(data, resource, logger)
if 'result_url' in input:
job_dict['status'] = 'running_but_viewable'
callback_xloader_hook(result_url=input['result_url'],
callback_url = config.get('ckanext.xloader.site_url') or config.get('ckan.site_url')
callback_url = urljoin(
callback_url.rstrip('/'), '/api/3/action/xloader_hook')
result_url = callback_url
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why create result_url at all?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You mean assign callback_url back to result_url ? I'm try to minimise changes to the rest of the XLoader code. If you think I should just use callback_url then I can do that

Copy link
Collaborator

@ThrawnCA ThrawnCA Jan 16, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're already changing from result_url=input['result_url'] to result_url=result_url. Why not just change it to result_url=callback_url? Or just call it result_url instead of callback_url on line 215 in the first place.

callback_xloader_hook(result_url=result_url,
api_key=api_key,
job_dict=job_dict)
logger.info('Data now available to users: %s', resource_ckan_url)
Expand Down Expand Up @@ -285,6 +297,14 @@ def _download_resource_data(resource, data, api_key, logger):
'Only http, https, and ftp resources may be fetched.'
)

resource_uri = urlunsplit(('', '', url_parts.path, url_parts.query, url_parts.fragment))
callback_url = config.get('ckanext.xloader.site_url') or config.get('ckan.site_url')
callback_url = urljoin(
callback_url.rstrip('/'), resource_uri)

url = callback_url
url_parts = urlsplit(url) # reparse the url after the callback_url is set
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will break all 'external' url's which are not internally referenced. We should be using a 'generic' function that takes a url and does the swap if the original url.

Details below on my reasoning:

I see in my jobs stats table items is

{"metadata": {"ignore_hash": false, "ckan_url": "https://www.data.qld.gov.au", "resource_id": "5d1e8368-7ec3-435a-92d0-280ad1e3db0d", "set_url_type": false, "task_created": "2025-01-11 00:15:03.218182", "original_url": "https://apps.des.qld.gov.au/data-sets/water/gregory-environmental.csv?timestamp=2025-01-10T10:15:02+10:00", "datastore_contains_all_records_of_source_file": true, "datastore_active": true}, "status": "complete"}

using this as an example. The input of the _download_resource_data function is
res_dict = get_action('resource_show')(context, {'id': resource_id})

looking at : https://www.data.qld.gov.au/api/action/resource_show?id=5d1e8368-7ec3-435a-92d0-280ad1e3db0d

on line 292, it gets the url which would be:

"url": "https://apps.des.qld.gov.au/data-sets/water/gregory-environmental.csv?timestamp=2025-01-16T10:15:01+10:00",

Which since you are 'force' changing the url, instead of checking its pointing to the CKAN site url first. it would then end up with

http://localhost:5000/data-sets/water/gregory-environmental.csv?timestamp=2025-01-16T10:15:01+10:00
if the ckanext.xloader.site_url is http://localhost:5000

which would then be a 404 or hanging situation.

Copy link
Collaborator

@kowh-ai kowh-ai Jan 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @duttonw for taking the time to help me with this. It is much appreaciated.

Yes, I agree that a util/helper function is needed to swap out the CKAN URL

With regards to your scenario, why would you set ckanext.xloader.site_url to something if it broke communication? The ckanext.xloader.site_url config option does not exist at the moment in master. If ckanext.xloader.site_url is not set then the callback_url would just fall back to ckan.site_url which would exist as it is mandatory. So in your case it would be set to http://www.data.qld.gov.au/data-sets/water/gregory-environmental.csv?timestamp=2025-01-16T10:15:01+10:00 as I think your ckan.site_url is set to http://www.data.qld.gov.au

Update: actually if ckanext.xloader.site_url is not set, then that config option (ckanext.xloader.site_url) would be set to the value for ckan.site_url through the validator for ckanext.xloader.site_url in the config_declaration.yaml file. Maybe that's not a great idea if we ever want to keep those 2 parameters distinct

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hi @kowh-ai ,

http://www.data.qld.gov.au/data-sets/water/gregory-environmental.csv?timestamp=2025-01-16T10:15:01+10:00 is a 404, since its not on www.data.qld.gov.au, but on apps.des.qld.gov.au (non ckan endpoint)

With the new function def get_ckan_url():
just update it to take a url. And it would alter it if incoming url 'matches' ckan.site_url at the start of the string and replace it with ckanext.xloader.site_url if not empty/blank string. (or if no domain is set, inject).

This will still need at least another 5 unit tests for this new function to 'verify' that it does what we expect it to do. i.e. not break external data assets.


somethings i've been thinking for a while is that if you have the 'archiver' plugin installed, like how there is a use case to 'wait' for the validation plugin to complete successfully. If the archiver has 'saved' the resource locally, then we could/should use that ingest into the datastore. The only negative is like these external csv files which are updated adhoc and the 'manual datastore upload' won't collect the latest like it does now. (harvester normally is set up to run on initial upload and then can be setup to run adhoc { for our instance monthly } , this is too slow and will cause frustration for authors who wish to have the latest from an external csv )

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This whole section should probably be moved down ten lines or so, to the block where url_type is upload. When the URL type is link the site URL is not involved in downloading it.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@duttonw - What about the other callbacks to CKAN ie: when these 2 functions call callback_xloader_hook(result_url, api_key, job_dict)

  1. xloader_data_into_datastore()
  2. xloader_data_into_datastore_()

The result_url parameter will need to change in a docker network to access the internal CKAN container ie: http://ckan-dev:5000/

In your case could the ckan.site_url be different to where you want to access the CKAN URL from within the XLoader code? like when you are downloading the resource file? In my case I need to set the CKAN URL to ckanext.xloader.site_url

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@duttonw - please let me know if the (new) modify_resource_url() function will work in this case where the original_url is different than the ckan_url


# fetch the resource data
logger.info('Fetching from: {0}'.format(url))
tmp_file = get_tmp_file(url)
Expand Down
12 changes: 5 additions & 7 deletions ckanext/xloader/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,13 +61,11 @@ def configure(self, config_):
else:
self.ignore_hash = False

for config_option in ("ckan.site_url",):
if not config_.get(config_option):
raise Exception(
"Config option `{0}` must be set to use ckanext-xloader.".format(
config_option
)
)
site_url_configs = ("ckan.site_url", "ckanext.xloader.site_url")
if not any(site_url_configs):
raise Exception(
f"One of config options {site_url_configs} must be set to use ckanext-xloader."
)
Comment on lines +64 to +68
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ckan will refuse to start if a site_url isn't provided, so this code would never get executed

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@wardi here, I'm just extending the existing check for that. I prefer not to remove existing behavior, but just to provide the minimal new behavior required for the PR

https://github.com/ckan/ckanext-xloader/blob/master/ckanext/xloader/plugin.py#L64

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you did not cleanup the error message, this would not have been commented upon ;)

I'm fine leaving this in as its a belts and braces approach, better to fail early (if it does occur which is very very remote)


# IDomainObjectModification

Expand Down
23 changes: 12 additions & 11 deletions ckanext/xloader/tests/test_jobs.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,17 +59,18 @@ def data(create_with_upload, apikey):
"api.action", ver=3, logic_function="xloader_hook", qualified=True
)
return {
'api_key': apikey,
'job_type': 'xloader_to_datastore',
'result_url': callback_url,
'metadata': {
'ignore_hash': True,
'ckan_url': toolkit.config.get('ckan.site_url'),
'resource_id': resource["id"],
'set_url_type': False,
'task_created': datetime.utcnow().isoformat(),
'original_url': resource["url"],
}
"api_key": apikey,
kowh-ai marked this conversation as resolved.
Show resolved Hide resolved
"job_type": "xloader_to_datastore",
"result_url": callback_url,
"metadata": {
"ignore_hash": True,
"ckan_url": toolkit.config.get("ckanext.xloader.site_url")
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

going to need more tests created to set these two values for proper validation.
one for default site url, another for the xloader override value. updating the fixture is so/so.

or toolkit.config.get("ckan.site_url"),
"resource_id": resource["id"],
"set_url_type": False,
"task_created": datetime.utcnow().isoformat(),
"original_url": resource["url"],
},
}


Expand Down
Loading