Skip to content

rs_dpr_service/main.md

<< Back to index

rs dpr service main module.

DatabaseJobFormatError

Bases: Exception

Exception raised when an error occurred during the init of a provider.

Source code in docs/rs-dpr-service/rs_dpr_service/main.py
92
93
class DatabaseJobFormatError(Exception):
    """Exception raised when an error occurred during the init of a provider."""

JobsFormatError

Bases: Exception

Exception raised when an error occurred during the init of a provider.

Source code in docs/rs-dpr-service/rs_dpr_service/main.py
96
97
class JobsFormatError(Exception):
    """Exception raised when an error occurred during the init of a provider."""

app_lifespan(fastapi_app) async

Lifespann app to be implemented with start up / stop logic

Source code in docs/rs-dpr-service/rs_dpr_service/main.py
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
@asynccontextmanager
async def app_lifespan(fastapi_app: FastAPI):
    """Lifespann app to be implemented with start up / stop logic"""
    logger.info("Starting up the application...")
    # Create jobs table
    process_manager = init_db()

    fastapi_app.extra["process_manager"] = process_manager
    # fastapi_app.extra["db_table"] = db.table("jobs")
    # fastapi_app.extra["dask_cluster"] = cluster

    # Yield control back to the application (this is where the app will run)
    yield

    # Shutdown logic (cleanup)
    logger.info("Shutting down the application...")
    logger.info("Application gracefully stopped...")

execute_process(request, resource) async

Used to execute processing jobs.

Source code in docs/rs-dpr-service/rs_dpr_service/main.py
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
@router.post("/dpr/processes/{resource}/execution")
async def execute_process(request: Request, resource: str):  # pylint: disable=unused-argument
    """Used to execute processing jobs."""

    with init_opentelemetry.start_span(__name__, "processor"):

        # Check that the input resource exists
        if resource not in api.config["resources"]:
            return ogc_error_response(HTTP_404_NOT_FOUND, f"Process {resource!r} not found")

        # Validate request payload
        try:
            valid_body = await validate_request(request)
        except Exception as e:  # pylint: disable=W0718
            # Handle exceptions and return an appropriate error message
            return ogc_error_response(HTTP_500_INTERNAL_SERVER_ERROR, str(e))

        # Read cluster information
        cluster_info = ClusterInfo(
            jupyter_token=valid_body.pop("jupyter_token"),
            cluster_label=valid_body.pop("cluster_label"),
            cluster_instance=valid_body.pop("cluster_instance"),
        )

        processor_name = api.config["resources"][resource]["processor"]["name"]
        if processor_name in processor_types:
            processor_type = processor_types[processor_name]
            _, dpr_status = await processor_type(app.extra["process_manager"], cluster_info).execute(  # type: ignore
                valid_body,
            )

            # Get identifier of the current job
            status_dict = {
                "accepted": HTTP_201_CREATED,
                "running": HTTP_201_CREATED,
                "successful": HTTP_201_CREATED,
                "failed": HTTP_500_INTERNAL_SERVER_ERROR,
                "dismissed": HTTP_500_INTERNAL_SERVER_ERROR,
            }
            id_key = [status for status in status_dict if status in dpr_status][0]
            formatted_job_data = format_job_data(app.extra["process_manager"].get_job(dpr_status[id_key]))
            validate_response(request, formatted_job_data, HTTP_201_CREATED)
            return JSONResponse(status_code=HTTP_201_CREATED, content=formatted_job_data)
        return ogc_error_response(HTTP_404_NOT_FOUND, f"Processor '{processor_name}' not found")

format_job_data(job)

Method to apply reformatting on job data to make it compliant with OGC (process) standards Args: job: information on a specific job to fromat: the job must have the same attributes than the columns from the PostgreSql database Result: reformatted and validated job_data variable to put in the response

Source code in docs/rs-dpr-service/rs_dpr_service/main.py
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
def format_job_data(job: dict):
    """
    Method to apply reformatting on job data to make it compliant with OGC (process) standards
    Args:
        job: information on a specific job to fromat: the job must have the same attributes
        than the columns from the PostgreSql database
    Result:
        reformatted and validated job_data variable to put in the response
    """
    # Check that the input job have the same struture as the jobs contained in the PostgreSQL database
    if "identifier" not in job:
        raise DatabaseJobFormatError(
            """Input job must have the same structure than the jobs stored in the """
            """PostgreSql database: attribute 'identifier' is missing""",
        )
    job_data = copy.deepcopy(job)
    # Rename attribute "identifier" to be compliant with OGC standards
    job_data[JOB_ATTRS_MAPPING["identifier"]] = job_data.pop("identifier")
    # Remove attributes which should not be part of the response
    for attr in OGC_UNCOMPLIANT_JOB_ATTRS:
        if attr in job_data:
            job_data.pop(attr)
    for key, value in job_data.items():
        # Reformat datetime object to string
        if isinstance(value, datetime):
            job_data[key] = value.strftime("%Y-%m-%dT%H:%M:%SZ")
    # Remove "finished" attribute if its value is None
    if "finished" in job_data and job_data.get("finished") is None:
        job_data.pop("finished")
    return job_data

format_jobs_data(jobs)

Method validate information on all existing jobs

Parameters:

Name Type Description Default
jobs dict

information on all existing jobs

required

Result: reformatted and validated jobs_data variable to provide to the response

Source code in docs/rs-dpr-service/rs_dpr_service/main.py
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
def format_jobs_data(jobs: dict):
    """
    Method validate information on all existing jobs

    Args:
        jobs: information on all existing jobs
    Result:
        reformatted and validated jobs_data variable to provide to the response
    """
    if not isinstance(jobs, dict):
        raise JobsFormatError("Expected a dictionary as input")
    if "jobs" not in jobs:
        raise JobsFormatError("Invalid format for input jobs: missing 'jobs' key")
    jobs_data = copy.deepcopy(jobs)
    # Add "links" mandatory field to the response
    jobs_data.update(
        {
            "links": [
                {
                    "href": "string",
                    "rel": "service",
                    "type": "application/json",
                    "hreflang": "en",
                    "title": "List of jobs",
                },
            ],
        },
    )
    # Remove SQLAlchemy _sa_instance_state objects and convert datetime
    for i, job_data in enumerate(jobs_data["jobs"]):
        jobs_data["jobs"][i] = format_job_data(job_data)
    return jobs_data

get_config_contents()

Return the pygeoapi configuration yaml file contents.

Source code in docs/rs-dpr-service/rs_dpr_service/main.py
107
108
109
110
111
112
113
114
115
116
117
def get_config_contents() -> dict:
    """Return the pygeoapi configuration yaml file contents."""
    # Open the configuration file
    with open(get_config_path(), encoding="utf8") as opened:
        contents = opened.read()

        # Replace env vars by their value
        contents = Template(contents).substitute(os.environ)

        # Parse contents as yaml
        return yaml.safe_load(contents)

get_config_path()

Return the pygeoapi configuration path and set the PYGEOAPI_CONFIG env var accordingly.

Source code in docs/rs-dpr-service/rs_dpr_service/main.py
100
101
102
103
104
def get_config_path() -> pathlib.Path:
    """Return the pygeoapi configuration path and set the PYGEOAPI_CONFIG env var accordingly."""
    path = pathlib.Path(__file__).parent.parent / "config" / "geoapi.yaml"
    os.environ["PYGEOAPI_CONFIG"] = str(path)
    return path

get_job_status_endpoint(request, job_id=Path(..., title='The ID of the job')) async

Used to get status of processing job.

Source code in docs/rs-dpr-service/rs_dpr_service/main.py
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
@router.get("/dpr/jobs/{job_id}")
async def get_job_status_endpoint(request: Request, job_id: str = Path(..., title="The ID of the job")):
    """Used to get status of processing job."""
    try:
        job = app.extra["process_manager"].get_job(job_id)
    except JobNotFoundError:  # pylint: disable=W0718
        # Handle case when job_id is not found
        return ogc_error_response(HTTP_404_NOT_FOUND, f"Job with ID {job_id} not found")

    try:
        formatted_job_data = format_job_data(job)
        validate_response(request, formatted_job_data)
        return JSONResponse(status_code=HTTP_200_OK, content=formatted_job_data)
    except Exception as e:  # pylint: disable=W0718
        return ogc_error_response(HTTP_500_INTERNAL_SERVER_ERROR, str(e))

get_jobs_list(request) async

Returns all jobs from database.

Source code in docs/rs-dpr-service/rs_dpr_service/main.py
372
373
374
375
376
377
378
379
380
@router.get("/dpr/jobs")
async def get_jobs_list(request: Request):
    """Returns all jobs from database."""
    try:
        formatted_jobs_data = format_jobs_data(app.extra["process_manager"].get_jobs())
        validate_response(request, formatted_jobs_data)
        return JSONResponse(status_code=HTTP_200_OK, content=formatted_jobs_data)
    except Exception as e:  # pylint: disable=W0718
        return ogc_error_response(HTTP_404_NOT_FOUND, str(e))

get_processes(request) async

Returns list of all available processes from config.

Source code in docs/rs-dpr-service/rs_dpr_service/main.py
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
@router.get("/dpr/processes")
async def get_processes(request: Request):
    """Returns list of all available processes from config."""

    try:
        processes = {
            "processes": [],
            "links": [
                {"href": str(request.url), "rel": "self", "type": "application/json", "title": "List of processes"},
            ],
        }
        for resource in api.config["resources"]:
            processes["processes"].append(
                {
                    "id": api.config["resources"][resource]["processor"]["name"],
                    "version": "1.0.0",
                },
            )
        validate_response(request, processes)
        return JSONResponse(status_code=HTTP_200_OK, content=processes)

    except Exception as e:  # pylint: disable=W0718
        return ogc_error_response(HTTP_500_INTERNAL_SERVER_ERROR, str(e))

get_resource(request, resource) async

Should return info about a specific resource.

Source code in docs/rs-dpr-service/rs_dpr_service/main.py
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
@router.get("/dpr/processes/{resource}")
async def get_resource(request: Request, resource: str):
    """Should return info about a specific resource."""
    with init_opentelemetry.start_span(__name__, "tasktable"):

        # Check that the input resource exists
        if resource not in api.config["resources"]:
            return ogc_error_response(HTTP_404_NOT_FOUND, f"Process {resource!r} not found")

        # Read cluster information
        cluster_info = ClusterInfo(
            jupyter_token=request.query_params["jupyter_token"],
            cluster_label=request.query_params["cluster_label"],
            cluster_instance=request.query_params["cluster_instance"],
        )

        processor_name = api.config["resources"][resource]["processor"]["name"]
        if processor_name in processor_types:
            processor_type = processor_types[processor_name]
            task_table = await processor_type(app.extra["process_manager"], cluster_info).get_tasktable()
            return JSONResponse(status_code=HTTP_200_OK, content=task_table)

init_db(pause=3, timeout=None)

Initialize the PostgreSQL database connection and sets up required table and ENUM type.

This function constructs the database URL using environment variables for PostgreSQL credentials, host, port, and database name. It then creates an SQLAlchemy engine and registers the ENUM type JobStatus and the 'job' tables if they don't already exist.

Environment Variables
  • POSTGRES_USER: Username for database authentication.
  • POSTGRES_PASSWORD: Password for the database.
  • POSTGRES_HOST: Hostname of the PostgreSQL server.
  • POSTGRES_PORT: Port number of the PostgreSQL server.
  • POSTGRES_DB: Database name.

Parameters:

Name Type Description Default
pause int

pause in seconds to wait for the database connection.

3
timeout int | None

timeout in seconds to wait for the database connection.

None

Returns:

Type Description
PostgreSQLManager

PostgreSQLManager instance

Source code in docs/rs-dpr-service/rs_dpr_service/main.py
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
def init_db(pause: int = 3, timeout: int | None = None) -> PostgreSQLManager:
    """Initialize the PostgreSQL database connection and sets up required table and ENUM type.

    This function constructs the database URL using environment variables for PostgreSQL
    credentials, host, port, and database name. It then creates an SQLAlchemy engine and
    registers the ENUM type JobStatus and the 'job' tables if they don't already exist.

    Environment Variables:
        - POSTGRES_USER: Username for database authentication.
        - POSTGRES_PASSWORD: Password for the database.
        - POSTGRES_HOST: Hostname of the PostgreSQL server.
        - POSTGRES_PORT: Port number of the PostgreSQL server.
        - POSTGRES_DB: Database name.

    Args:
        pause: pause in seconds to wait for the database connection.
        timeout: timeout in seconds to wait for the database connection.

    Returns:
        PostgreSQLManager instance
    """
    manager_def = api.config["manager"]
    if not manager_def or not isinstance(manager_def, dict) or not isinstance(manager_def["connection"], dict):
        message = "Error reading the manager definition for pygeoapi PostgreSQL Manager"
        logger.error(message)
        raise RuntimeError(message)
    connection = manager_def["connection"]

    # Create SQL Alchemy engine
    engine = get_engine(driver_name="postgresql+psycopg2", **connection)

    while True:
        try:
            # This registers the ENUM type and creates the jobs table if they do not exist
            Base.metadata.create_all(bind=engine)
            logger.info(f"Reached {engine.url!r}")
            logger.info("Database table and ENUM type created successfully.")
            break

        # It fails if the database is unreachable. Wait a few seconds and try again.
        except SQLAlchemyError:
            logger.warning(f"Trying to reach {engine.url!r}")

            # Sleep for n seconds and raise exception if timeout is reached.
            if timeout is not None:
                timeout -= pause
                if timeout < 0:
                    raise
            sleep(pause)

    # Initialize PostgreSQLManager with the manager configuration
    return PostgreSQLManager(manager_def)

init_pygeoapi()

Init pygeoapi

Source code in docs/rs-dpr-service/rs_dpr_service/main.py
120
121
122
def init_pygeoapi() -> API:
    """Init pygeoapi"""
    return API(get_config_contents(), "")

ogc_error_response(status_code, detail)

Generate an OGC-compliant error response

Source code in docs/rs-dpr-service/rs_dpr_service/main.py
82
83
84
85
86
87
88
89
def ogc_error_response(status_code: int, detail: str):
    """Generate an OGC-compliant error response"""
    error_response = {
        "type": f"https://developer.mozilla.org/en/docs/Web/HTTP/Reference/Status/{status_code}",
        "status": status_code,
        "detail": detail,
    }
    return JSONResponse(status_code=status_code, content=error_response)

ping() async

Liveliness probe.

Source code in docs/rs-dpr-service/rs_dpr_service/main.py
203
204
205
206
@router.get("/_mgmt/ping", include_in_schema=False)
async def ping():
    """Liveliness probe."""
    return JSONResponse(status_code=HTTP_200_OK, content="Healthy")