config.py 10.9 KB
Newer Older
1
#!/usr/bin/python
2
# -*- coding: utf-8 -*-
3
4
5
6
#
# This file is part of CERN Search.
# Copyright (C) 2018-2019 CERN.
#
7
# Citadel Search is free software; you can redistribute it and/or modify it
8
# under the terms of the MIT License; see LICENSE file for more details.
9
"""Configuration for Citadel Search."""
10
11

from __future__ import absolute_import, print_function
Pablo Panero's avatar
Pablo Panero committed
12

13
import ast
Pablo Panero's avatar
Pablo Panero committed
14
import copy
15
import os
Carina Antunes's avatar
Carina Antunes committed
16

17
from cern_search_rest_api.modules.cernsearch.api import CernSearchRecord
18
from cern_search_rest_api.modules.cernsearch.facets import regex_aggregation, simple_query_string
19
from cern_search_rest_api.modules.cernsearch.indexer import CernSearchRecordIndexer
20
21
22
23
24
from cern_search_rest_api.modules.cernsearch.permissions import (record_create_permission_factory,
                                                                 record_delete_permission_factory,
                                                                 record_list_permission_factory,
                                                                 record_read_permission_factory,
                                                                 record_update_permission_factory)
25
from elasticsearch_dsl import A
26
from flask import request
Pablo Panero's avatar
Pablo Panero committed
27
from invenio_oauthclient.contrib import cern
28
from invenio_records_rest import config as irr_config
29
from invenio_records_rest.facets import terms_filter
30
from kombu import Exchange, Queue
31
32
33
34
35
36


def _(x):
    """Identity function used to trigger string extraction."""
    return x

37

Pablo Panero's avatar
Theme    
Pablo Panero committed
38
39
40
41
# Theme
# =====
THEME_SEARCHBAR = False

Pablo Panero's avatar
Pablo Panero committed
42
43
44
45
46
# OAuth Client
# ============

CERN_REMOTE_APP = copy.deepcopy(cern.REMOTE_APP)
CERN_REMOTE_APP["params"].update(dict(request_token_params={
47
    "resource": os.getenv('CERN_SEARCH_REMOTE_APP_RESOURCE', 'test-cern-search.cern.ch'),
Pablo Panero's avatar
Pablo Panero committed
48
49
50
    "scope": "Name Email Bio Groups",
}))

51
52
CERN_REMOTE_APP["authorized_handler"] = \
    'cern_search_rest_api.modules.cernsearch.handlers:cern_authorized_signup_handler'
Pablo Panero's avatar
Pablo Panero committed
53

Pablo Panero's avatar
Pablo Panero committed
54
55
56
OAUTHCLIENT_REMOTE_APPS = dict(
    cern=CERN_REMOTE_APP,
)
57

Carina Antunes's avatar
Carina Antunes committed
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# OAuth REST Client
# ============

OAUTH_REMOTE_APP = copy.deepcopy(cern.REMOTE_REST_APP)
OAUTH_REMOTE_APP["params"].update(dict(request_token_params={
    "resource": os.getenv('CERN_SEARCH_REMOTE_APP_RESOURCE', 'test-cern-search.cern.ch'),
    "scope": "Name Email Bio Groups Group",
}))
OAUTH_REMOTE_APP["authorized_handler"] = \
    'cern_search_rest_api.modules.cernsearch.handlers:cern_authorized_signup_handler'
OAUTHCLIENT_REST_REMOTE_APPS = dict(
    cern=OAUTH_REMOTE_APP,
)

Pablo Panero's avatar
Pablo Panero committed
72
73
74
75
76
# Accounts
# ========
# FIXME: Needs to be disable for role base auth in SSO. If not invenio_account/sessions:login_listener will crash

ACCOUNTS_SESSION_ACTIVITY_ENABLED = False
77
SERVER_NAME = os.getenv("CERN_SEARCH_SERVER_NAME")
Pablo Panero's avatar
Pablo Panero committed
78
79
80
81

# Admin
# =====

82
ADMIN_PERMISSION_FACTORY = 'cern_search_rest_api.modules.cernsearch.permissions:admin_permission_factory'
Pablo Panero's avatar
Pablo Panero committed
83

84
85
86
87
88
89
# JSON Schemas configuration
# ==========================

JSONSCHEMAS_ENDPOINT = '/schemas'
JSONSCHEMAS_HOST = '0.0.0.0'
# Do not register the endpoints on the UI app."""
90
JSONSCHEMAS_REGISTER_ENDPOINTS_UI = True
91
92
93
94

# Search configuration
# =====================

95
SEARCH_MAPPINGS = [os.getenv('CERN_SEARCH_INSTANCE', 'test')]
96
SEARCH_USE_EGROUPS = ast.literal_eval(os.getenv('CERN_SEARCH_USE_EGROUPS', 'True'))
97
SEARCH_DOC_PIPELINES = ast.literal_eval(os.getenv('CERN_SEARCH_DOC_PIPELINES', '{}'))
98

99
100
101
# Alias instance - don't allow updates, allow only search
SEARCH_INSTANCE_IMMUTABLE = ast.literal_eval(os.getenv('CERN_SEARCH_INSTANCE_IMMUTABLE', 'False'))

102
# Records REST configuration
Pablo Panero's avatar
Pablo Panero committed
103
# ===========================
104
105
106

#: Records REST API configuration

107
_Record_PID = 'pid(recid, record_class="cern_search_rest_api.modules.cernsearch.api:CernSearchRecord")'  # TODO
108

109
110
111
112
113
114
115
116
RECORDS_FILES_REST_ENDPOINTS = {
    'RECORDS_REST_ENDPOINTS': {
        'docid': '/files',
    }
}

FILES_REST_PERMISSION_FACTORY = 'cern_search_rest_api.modules.cernsearch.permissions:files_permission_factory'

117
118
119
120
121
122
123
124
125
126
RECORDS_REST_ENDPOINTS = dict(
    docid=dict(
        pid_type='recid',
        pid_fetcher='recid',
        pid_minter='recid',
        default_endpoint_prefix=True,
        default_media_type='application/json',
        item_route='/record/<{0}:pid_value>'.format(_Record_PID),
        list_route='/records/',
        links_factory_imp='invenio_records_rest.links:default_links_factory',
127
128
        record_class=CernSearchRecord,
        indexer_class=CernSearchRecordIndexer,
129
        record_serializers={
130
            'application/json': ('cern_search_rest_api.modules.cernsearch.serializers'
131
132
                                 ':json_v1_response'),
        },
133
134
        record_loaders={
            'application/json': ('cern_search_rest_api.modules.cernsearch.loaders:'
135
136
                                 'csas_loader'),
            'application/json-patch+json': lambda: request.get_json(force=True)
137
        },
138
        search_class='cern_search_rest_api.modules.cernsearch.search.RecordCERNSearch',
139
        search_index=os.getenv('CERN_SEARCH_INSTANCE', 'test'),
140
        search_serializers={
141
            'application/json': ('cern_search_rest_api.modules.cernsearch.serializers'
142
143
                                 ':json_v1_search'),
        },
144
        search_factory_imp='cern_search_rest_api.modules.cernsearch.search.csas_search_factory',
145
        max_result_window=10000,
146
        read_permission_factory_imp=record_read_permission_factory,
147
        list_permission_factory_imp=record_list_permission_factory,
148
149
150
        create_permission_factory_imp=record_create_permission_factory,
        update_permission_factory_imp=record_update_permission_factory,
        delete_permission_factory_imp=record_delete_permission_factory,
151
152
153
154
155
156
157
        suggesters={
            'phrase': {
                'completion': {
                    'field': 'suggest_keywords',
                }
            },
        },
158
    )
Pablo Panero's avatar
Pablo Panero committed
159
)
Pablo Panero's avatar
Oauth    
Pablo Panero committed
160

161
162
163
164
165
166
167
168
169
170
171
172

def aggs_filter(field):
    """Create a term filter.

    :param field: Field name.
    :returns: Function that returns the Terms query.
    """
    def inner(values):
        return A('terms', field=field, include=f'.*{values[0]}.*')
    return inner


173
RECORDS_REST_FACETS = {
Carina Antunes's avatar
Carina Antunes committed
174
    'webservices': {
175
176
177
        'aggs': {
            'collection': {
                'terms': {'field': 'collection'}
178
179
180
181
            },
            'type_format': {
                'terms': {'field': 'type_format'}
            },
182
183
184
            'author': regex_aggregation('_data.authors.exact_match', 'authors_suggest'),
            'site': regex_aggregation('_data.site.exact_match', 'sites_suggest'),
            'keyword': regex_aggregation('_data.keywords.exact_match', 'keywords_suggest')
185
        },
Carina Antunes's avatar
Carina Antunes committed
186
        'filters': {
187
188
            'collection': terms_filter("collection"),
            'type_format': terms_filter("type_format"),
189
190
191
192
193
            'author': terms_filter("_data.authors.exact_match"),
            'site': terms_filter("_data.site.exact_match"),
            'keyword': terms_filter("_data.keywords.exact_match"),
        },
        'matches': {
194
195
196
197
198
            'author_match': simple_query_string("_data.authors"),
            'keyword_match': simple_query_string("_data.keywords"),
            'site_match': simple_query_string("_data.site"),
            'name_match': simple_query_string("_data.name"),
            'url_match': simple_query_string("url"),
199
        }
200
201
202
203
204
205
206
207
208
209
210
211
212
    },
    'indico': {
        'aggs': {
            'event_type': {
                'terms': {'field': '_data.event_type'}
            },
            'speakers_chairs': {
                'terms': {'field': '_data.speakers_chairs.exact_match'}
            },
            'list_of_persons': {
                'terms': {'field': '_data.list_of_persons.exact_match'}
            }
        }
213
214
215
    }
}

216
RECORDS_REST_SORT_OPTIONS = {
Carina Antunes's avatar
Carina Antunes committed
217
    'webservices': {
218
219
220
221
222
223
224
225
226
227
        'bestmatch': {
            'fields': ['-_score'],
            'title': 'Best match',
            'default_order': 'asc',
        },
        'mostrecent': {
            'fields': ['_updated'],
            'title': 'Newest',
            'default_order': 'asc',
        }
228
    },
Carina Antunes's avatar
Carina Antunes committed
229
    'edms': {
230
231
232
233
234
235
236
237
238
239
        'bestmatch': {
            'fields': ['-_score'],
            'title': 'Best match',
            'default_order': 'asc',
        },
        'mostrecent': {
            'fields': ['_updated'],
            'title': 'Newest',
            'default_order': 'asc',
        }
240
241
242
    }
}

243
244
245
246
247
RECORDS_REST_ELASTICSEARCH_ERROR_HANDLERS = copy.deepcopy(
    irr_config.RECORDS_REST_ELASTICSEARCH_ERROR_HANDLERS)
RECORDS_REST_ELASTICSEARCH_ERROR_HANDLERS['mapper_parsing_exception'] = \
    'cern_search_rest_api.modules.cernsearch.views:elasticsearch_mapper_parsing_exception_handler'

Pablo Panero's avatar
Pablo Panero committed
248
249
250
# App
# ===

251
APP_HEALTH_BLUEPRINT_ENABLED = True
Pablo Panero's avatar
Pablo Panero committed
252

Pablo Panero's avatar
Pablo Panero committed
253
254
255
256
257
258
259
# CORS
# ====

REST_ENABLE_CORS = True
CORS_SEND_WILDCARD = ast.literal_eval(os.getenv('CERN_SEARCH_CORS_SEND_WILDCARD', 'False'))
CORS_SUPPORTS_CREDENTIALS = ast.literal_eval(os.getenv('CERN_SEARCH_CORS_SUPPORTS_CREDENTIALS', 'True'))

Pablo Panero's avatar
Oauth    
Pablo Panero committed
260
261
262
263
264
265
266
# Flask Security
# ==============
# Avoid error upon registration with email sending
# FIXME flask_security/registrable:40 "Too many values to unpack"
SECURITY_SEND_REGISTER_EMAIL = False
SECURITY_CONFIRM_REGISTRATION = False
SECURITY_CONFIRMABLE = False
Pablo Panero's avatar
Pablo Panero committed
267
268
SECURITY_REGISTERABLE = False  # Avoid user registration outside of CERN SSO
SECURITY_RECOVERABLE = False  # Avoid user password recovery
269
SESSION_COOKIE_SECURE = True
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316

# Celery Configuration
# ====================
FILES_PROCESSOR_QUEUE = os.getenv("CERN_SEARCH_FILES_PROCESSOR_QUEUE", 'files_processor')
FILES_PROCESSOR_QUEUE_DLX = os.getenv("CERN_SEARCH_FILES_PROCESSOR_QUEUE_DLX", 'files_processor_dlx')
FILES_PROCESSOR_EXCHANGE = os.getenv("CERN_SEARCH_FILES_PROCESSOR_EXCHANGE", 'default')
FILES_PROCESSOR_EXCHANGE_DLX = os.getenv("CERN_SEARCH_FILES_PROCESSOR_EXCHANGE_DLX", 'dlx')

#: URL of message broker for Celery (default is RabbitMQ).
CELERY_BROKER_URL = os.getenv('INVENIO_CELERY_BROKER_URL', 'amqp://guest:guest@localhost:5672')
#: URL of backend for result storage (default is Redis).
CELERY_RESULT_BACKEND = os.getenv('INVENIO_CELERY_RESULT_BACKEND', 'redis://localhost:6379/2')

CELERY_TASK_QUEUES = {
    Queue(
        name=FILES_PROCESSOR_QUEUE,
        exchange=Exchange(FILES_PROCESSOR_EXCHANGE, type='direct'),
        routing_key=FILES_PROCESSOR_QUEUE,
        queue_arguments={
            'x-dead-letter-exchange': FILES_PROCESSOR_EXCHANGE_DLX,
            'x-dead-letter-routing-key': FILES_PROCESSOR_QUEUE_DLX
        }
    ),
    Queue('celery', Exchange('celery'), routing_key='celery')
}

CELERY_TASK_ROUTES = {
    'cern_search_rest_api.modules.cernsearch.tasks.process_file_async': {
        'queue': FILES_PROCESSOR_QUEUE,
        'routing_key': FILES_PROCESSOR_QUEUE,
    }
}

CELERY_TASK_DEFAULT_QUEUE = 'celery'

CELERY_BROKER_POOL_LIMIT = os.getenv("BROKER_POOL_LIMIT", None)

SQLALCHEMY_ENGINE_OPTIONS = {
    'pool_size': int(os.getenv("SQLALCHEMY_POOL_SIZE", 5)),
    'max_overflow': int(os.getenv("SQLALCHEMY_MAX_OVERFLOW", 10)),
    'pool_recycle': int(os.getenv("SQLALCHEMY_POOL_RECYCLE", 300)),  # in seconds
}

SEARCH_CLIENT_CONFIG = dict(
    # allow up to 25 connections to each node
    maxsize=int(os.getenv("ELASTICSEARCH_MAX_SIZE", 5)),
)
317
318
319

# FILE
PROCESS_FILE_META = ast.literal_eval(os.getenv("CERN_SEARCH_PROCESS_FILE_META", 'False'))